#!/bin/bash
# gxmessage tests and examples

PROG=$(basename $0)

# Default to xmessage if gxmessage isn't available

if command -v gxmessage >/dev/null 2>&1; then
    XMESSAGE=gxmessage
else
    XMESSAGE=xmessage
fi

# Let user override the default

if [ "$1" = '-h' ]
then
  echo "Usage: $PROG [xmessage|gxmessage]"
  exit 0
elif [ "$1" = xmessage ]
then
  XMESSAGE=xmessage
elif [ "$1" = gxmessage ]
then
  XMESSAGE=gxmessage
elif [ $# -ne 0 ]
then
  echo "Try $PROG -h"
  exit 1
fi

$XMESSAGE -center A few $XMESSAGE tests
$XMESSAGE -center -default okay "The default button has focus - just hit <ENTER> to close this window"

$XMESSAGE -center -buttons "one:1,two:2,three:3" \
  "Button labels and return values"
echo $?

$XMESSAGE -center -buttons 'Hello\, world:42,This\, as you see\, is a test:43' \
  "Buttons containing escaped characters"
echo $?

$XMESSAGE -center -print -buttons 'one\: 10:10,two\: 20:20,three\: 30:30,hello\, world\: 40:40' \
  "More buttons with escaped characters"

# GTK stock buttons no longer supported in GTK4, but anyway...
$XMESSAGE -center \
  -buttons "GTK_STOCK_HELP,GTK_STOCK_OK,GTK_STOCK_CANCEL,GTK_STOCK_CLOSE" \
  -default GTK_STOCK_CLOSE "Some GTK stock buttons (not available after GTK3)"
echo $?

$XMESSAGE -center -buttons "" -timeout 3 "The -timeout option..."
echo $?

$XMESSAGE -center -buttons "_Red,_Green,_Blue" -default _Blue \
  "Keyboard accelerators (try pressing ALT to see them)"

$XMESSAGE -center -file "$0" -default okay

# A check for geometry parsing (we only need to extract width and height)
echo "geometry 300x300+100+100"
$XMESSAGE -help | $XMESSAGE -file - -default okay -geom 300x300+100+100

echo "automatic geometry"
$XMESSAGE -help | $XMESSAGE -center -file - -default okay

$XMESSAGE -center -fg white -bg '#10191e' -default okay \
  "The -fg and -bg options"

FONT="monospace bold 12"
[ "$XMESSAGE" = gxmessage ] || FONT="-misc-fixed-*-*-*-*-*-140-*-*-*-*-*-*"
$XMESSAGE -center -default okay -geometry 500x100 ${FONT:+-font "$FONT"} \
  "Using -font without upsetting xmessage"

$XMESSAGE - -- dash - test - -- -center - -default okay -

# These have no effect since GTK4
$XMESSAGE -center -display :0 -default okay "Testing the -display and -name options" \
          -name George

echo "Feeding gxmessage a super long button label should cause it to quit with a warning and an exit code of 1, rather than crash in flames..."
$XMESSAGE "Some text" -buttons $(python3 -c "print('A'*115000)")
echo "The exit code was: $?"

if [ "$XMESSAGE" != gxmessage ]
then

  # skip gxmessage-specific tests if not using gxmessage
  :

else

  NAME=$($XMESSAGE -center -entry -buttons "" "What's your name?")
  echo "Hello, $NAME!"

  ME=${HOSTNAME:-Bart}
  NAME=$($XMESSAGE -center -entrytext "$ME" -buttons "" \
         "What's my name?");
  [ "$NAME" = "$ME" ] || echo "You mean I'm not $ME?!"

fi

echo "finished"

