#!/bin/bash

coproc dialogbox    # Note: bash supports only one co-process
INPUTFD=${COPROC[0]}  # file descriptor the dialogbox process writes to
OUTPUTFD=${COPROC[1]}  # file descriptor the dialogbox process reads from
DBPID=$COPROC_PID    # PID of the dialogbox, if you need it for any purpose... e.g. to kill it

# If your script doesn't use standard input/output you may redirect them to the pipes
# and don't bore with redirection for each input/output command.
# Tools used might output something to the pipe but it is unlikely it will be understood by the
# dialogbox application. So, this is 99.99% safe...
# The following two commands will do the job:
#  exec <&${COPROC[0]}
#  exec >&${COPROC[1]}


cat >&$OUTPUTFD <<EODEMO
add label "<small>This script demonstrates bidirectional communication with the dialogbox application using pipes." note
set note stylesheet "qproperty-textInteractionFlags: NoTextInteraction;"
add separator
add frame horizontal
add checkbox "&Option 1" cb1
add pushbutton "&Disable option 1" dsbl
add frame horizontal
add stretch
add pushbutton O&k okay apply exit
add pushbutton &Cancel cancel exit
end frame
set title "Demo 3"
set okay default
set cb1 focus
EODEMO


flag=0
cbflag=0

while IFS=$'=' read key value
do
  case $key in
    dsbl)
    # Note: if you use echo command don't forget to escape quotes as echo "eats" them
    #    and don't forget to escape ampersand as otherwise shell will interpret it
      if [ "$cbflag" == "0" ]
      then
        echo disable cb1 >&$OUTPUTFD
        echo set dsbl title \"\&Enable option 1\" >&$OUTPUTFD
        cbflag=1
      else
        echo enable cb1 >&$OUTPUTFD
        echo set dsbl title \"\&Disable option 1\" >&$OUTPUTFD
        cbflag=0
      fi
      ;;
    cb1)
    # Note: disabled widgets are not reported
      if [ "$value" == "1" ]
      then
        echo Option 1 is checked
      else
        echo Option 1 is unchecked
      fi
      ;;
    okay)
      flag=1
      echo User clicked Ok pushbutton
      ;;
    cancel)
      flag=1
      echo User clicked Cancel pushbutton
      ;;
  esac
done <&$INPUTFD

# Note: if for a reason you break from the loop you can check whether the dialog
# was closed by the user with command similar to the below one:
# kill -0 $DBPID &>/dev/null || exit

if [ "$flag" == "0" ]
then
  echo User closed the window
fi

exit 0
