#!/bin/bash

export V=0.2.5 #sfs
# Initialize gettext for internationalization
export TEXTDOMAIN=xwwall
#export TEXTDOMAINDIR="${XDG_DATA_HOME:-$HOME/.local/share}/locale"
. gettext.sh
gtkdialog=gtkdialog

export GTK3DIALOG
export MAINGUI
[[ -z "$GTK3DIALOG" ]] && GTK3DIALOG=$gtkdialog
if [[ "$(pwd)" == "$HOME" ]]; then 
	export BGDIR="${BGDIR:-$HOME/.local/share/backgrounds}"
else
	export BGDIR="$(pwd)"
fi
export PROG=${0##*\/}
export TEMP=/tmp/$PROG
#export TEMP=$HOME/tmp/$PROG # for testing
rm -rf "$TEMP" # incase of a crash because of "Argument list too long"
mkdir -p "$TEMP"
export CONFDIR="${XDG_CONFIG_HOME:-$HOME/.config}/$PROG"
mkdir -p "$CONFDIR"
export CONF="$CONFDIR/$PROG.conf"
if [[ ! -f "$CONF" ]];then
	echo "BGDIR=$BGDIR" > "$CONF"
fi
. "$CONF"

wlr-randr >/dev/null 2>&1 && export WAYLAND=yes

case "$1" in
	--restore)
	PROFILE="$2"
	echo $PROFILE
	if [[ -n "$PROFILE" && -r "$CONFDIR/$PROFILE/cmd" ]]; then
		. "$CONFDIR/$PROFILE/cmd" && exit 0
	elif [[ -n "$PROFILE" &&  -x "$CONFDIR/$PROFILE/.fehbg" ]]; then
		exec "$CONFDIR/$PROFILE/.fehbg"
	fi
	if [[ -f "$CONFDIR/cmd" && "$WAYLAND" == 'yes' ]]; then
		. "$CONFDIR/cmd" && exit 0
	elif [[ -x "$HOME/.fehbg" ]]; then
		exec "$HOME/.fehbg"
	else
		exit 1
	fi
	;;
	-d|--delconf)
		rm -f "$CONF"
		exit 0
	;;
	-*v|-*version)
	echo -e "\t$PROG $V\n\t\tGPL-2.0+ $(gettext "licence")\n"
	exit 0
	;;
	-*h|-*help)
	echo -e "\t$PROG -h|--help\n\t\t$(gettext "show this help and exit.")\n"
	echo -e "\t$PROG -v|--version\n\t\t$(gettext "print version and exit.")\n"
	echo -e "\t$PROG -d|--delconf\n\t\t$(gettext "delete") \$HOME/.config/$PROG"
	echo -e "\t\t$(gettext "if $PROG doesn't start and exit.")\n"
	echo -e "\t$PROG --restore\n\t\t$(gettext "restore backgrounds at session start.")"
	echo -e "\t$(gettext 'An optional argument "$PROFILE" is supported.')\n"
	echo -e "\t$(gettext 'try "man $PROG" for more information.')"
	exit 0
	;;
esac

# sort out the monitors and positions
if [[ "$WAYLAND" == 'yes' ]]; then
	b=0
	c=1
	MON=''
	pos=''
	while read -r l m n o p q
	do
		case "${l:0:3}" in
			Pos|Mak|Mod|Ser|Phy|Ena|Tra|Sca|Ada)
			if [[ "${l:0:3}" == 'Pos' ]];then
				export pos
				pos=${m%,*};  echo POS=$pos >> "$TEMP/Wmonitor-$((c-1))"
			else
				continue
			fi
			;;
			[a-zA-Z][a-zA-Z]*)MON=$l;;
		esac
		case "$q" in
			current*)res=$l;;
			*)continue;;
		esac
		resX=${res%x*}
		resY=${res#*x}
		echo OUTPUT=$MON >> "$TEMP/Wmonitor-$c"
		echo X=$resX >> "$TEMP/Wmonitor-$c"
		echo Y=$resY >> "$TEMP/Wmonitor-$c"
		c=$((c+1))
		b=$((b+1))
		echo $b > $TEMP/number
	done <<<$(wlr-randr)
	export POPT='edge="top" dist="100"'
	export SOPT='layer="top"'
	export CONFILE="$CONFDIR/Wconf"
else
	k=0
	n=1
	MON=''
	while read -r a b c d z
	do
		echo $a
		[[ "${a}" == 'Monitors:' ]] && continue
		MON=$d
		resX=${c/\/[0-9]*/}
		resY=${c#*x}
		resY=${resY/\/[0-9]*/}
		pos=${c#*+}
		pos=${pos/+/ }
		[[ "${pos%\ *}" == '0' ]] && n=0 # 'xx' position
		pos=${pos%\ *}
		echo  Xmonitor-$n
		echo $MON
		echo $resX
		echo $resY
		echo $pos
		echo OUTPUT=$MON >> "$TEMP/Xmonitor-$n"
		echo X=$resX >> "$TEMP/Xmonitor-$n"
		echo Y=$resY >> "$TEMP/Xmonitor-$n"
		echo POS=$pos >> "$TEMP/Xmonitor-$n"
		n=$((n+1))
		k=$((k+1))
		echo $k > $TEMP/number
	done <<<$(xrandr --listmonitors)
	export POPT='decorated="false"'
	export SOPT=$POPT
	export CONFILE="$CONFDIR/Xconf"
fi

#CSS for splash
[[ -z "$COLOR" ]] && COLOR=666666
echo 'window#splash {
	background: rgba(0,0,0,0.0);
}
#splash {
	background: #5E003E;
	color: #ffffff;
	border-radius: 10px;
	padding: 2px;
}
#sep {
	background: rgba(0,0,0,0.0);
}
#ent {
	background: @theme_selected_bg_color;
}
#noent {
	background: @theme_bg_color;
	color: @theme_fg_color;
	border: none;
}
#cbg {
	background: '#${COLOR}';
}
' > "$TEMP/win.css"
#'
# get the primary output
[[ -z "$TWIDTH" ]] && TWIDTH=9
case $TWIDTH in
	12)THEIGHT=8;;
	11)THEIGHT=9;;
	10)THEIGHT=10;;
	 9)THEIGHT=11;;
	 8)THEIGHT=12;;
esac
e=0
if [[ "$WAYLAND" == 'yes' ]]; then
	for i in $TEMP/Wmonitor*
	do
		# $i is sourced
		. "$i"
		[[ "$POS" == '0' ]] && echo "$OUTPUT = $(gettext 'primary')" && cp $i $TEMP/ww0
		[[ "$POS" == "$X" ]] && echo "$OUTPUT = $(gettext 'secondary')" && cp $i $TEMP/ww1
		[[ $POS -gt $X ]] && echo "$OUTPUT = $(gettext 'extra')" && cp $i $TEMP/ww2$e && e=$((e+1))
	done
	rm $TEMP/Wmonitor* # finished with these
	read -r NUM < "$TEMP/number"
	export NUM
	echo $NUM $(gettext "outputs")
	. $TEMP/ww0
	export Wdth=$((X / TWIDTH))
	export MWdth=$((X / 2))
	export MHght=$(((Y * 2 / 3) / 11 * THEIGHT))
	echo "GUI: MWdth=$MWdth x MHght=$MHght"
else
	for f in $TEMP/Xmonitor*
	do
		# $f is sourced
		. "$f"
		[[ "$POS" == '0' ]] && echo "$OUTPUT = $(gettext 'primary')" && cp $f $TEMP/xx0
		[[ "$POS" == "$X" ]] && echo "$OUTPUT = $(gettext 'secondary')" && cp $f $TEMP/xx1
		[[ $POS -gt $X ]] && echo "$OUTPUT = $(gettext 'extra')" && cp $f $TEMP/xx2$e && e=$((e+1))
	done
	rm $TEMP/Xmonitor* # finished with these
	export NUM
	read -r NUM < "$TEMP/number"
	echo $NUM $(gettext "outputs")
	. $TEMP/xx0
	export Wdth=$((X / TWIDTH))
	export MWdth=$((X / 2))
	export MHght=$(((Y * 2 / 3) / 11 * THEIGHT))
	echo "GUI: MWdth=$MWdth x MHght=$MHght"
fi

########################    functions     ##############################

# splash window
_splash() {
	[[ -z "$1" ]] && return
	E_VAL=SPLASH
	CR="--geometry=+$((X/2-180))+150"
	case $2 in
		0)[[ "$SPLASH" == 'false' ]] && return
		DIS='
			<button tooltip-text="'$(gettext "Do not show again")'">
				<input file icon="window-close"></input>
				<label>'$(gettext "Dismiss")'</label>
				<action>if grep -q "SPLASH" '$CONF'; then sed -i "s/^SPLASH.*$/SPLASH=false/" '$CONF';else echo SPLASH=false >> '$CONF'; fi</action>
				<action>exit:DISMISS</action>
			</button>'
			E_VAL=Monitors
			;;
		2)E_VAL=Limit;;
		3)ACT='<action>main_gui &</action><action>exit:OK</action>';;
		5)ACT='<action>kill '$PID'</action><action>exit:abort</action>';KILL='<action>kill '$PID'</action>';;
		6)E_VAL=Wait;CR=-c;;
		7)E_VAL=Warning;CR=-c;;
		*)CR=--geometry=+$((X/2-180))+150;ACT='<action>exit:OK</action>';;
	esac
	IVAL=4
	re='^[0-9]'
	[[ $3 =~ $re ]] && IVAL=$3
	if [[ "$WAYLAND" == 'yes' ]]; then
		[[ "$3" == 'b' ]] && POPT='edge="bottom" dist="200"'
	else
		[[ "$3" == 'b' ]] && CR="--geometry=+$((X/2-240))+$((Y-300))"
	fi
	TIMER='<timer interval="'$IVAL'" visible="false">'$KILL'<action>exit:'$E_VAL'</action></timer>'
	echo '<window type-hint="6" icon-name="dialog-info" '$POPT' name="splash" width-request="360" title="'$PROG' ">
	<vbox name="splash">
	   <vbox> 
		<hbox name="splash">
		<hbox space-expand="false" space-fill="false">
		  <pixmap name="splash"><width>42</width><input file icon="dialog-info"></input></pixmap>
		  '$TIMER'
	    </hbox>
	    <hbox space-expand="true" space-fill="true">
	      <text name="splash">
			<label>'"$1"'</label>
		  </text>
		</hbox>
		'$RADIO'
		</hbox>
		<hbox name="splash">
			'$DIS'
			<button>
			  <label>'$(gettext "OK")'</label>
			  <input file icon="gtk-ok"></input>
			  '$ACT'
			</button>
		</hbox>
	   </vbox>
	</vbox>
</window>' | $GTK3DIALOG -s "$CR" --styles=$TEMP/win.css
	[[ "$2" == '1' ]] && exit $2
}; export -f _splash

# if < 300 images or on a single monitor there is no welcome splash
# on slow kit a user might want to know if the thing is starting
_greeting() {
	export GREETING='<window type-hint="6" icon-name="xwwall" '$SOPT' name="splash" file-monitor="true" title="'$PROG'" width-request="300">
	<vbox name="splash" space-expand="true" space-fill="true">
	  <hbox space-expand="true" space-fill="true">
	    <pixmap>
	      <input file icon="xwwall"></input><width>64</width>
	    </pixmap>
	  </hbox>
	  <hbox space-expand="true" space-fill="true">
	    <text use-markup="true">
	      <label>"<big><big>'$(gettext "Welcome to")' '$PROG'</big></big>"</label>
	    </text>
	  </hbox>
	</vbox>
	<variable>GREETING</variable>
    <input file>'$TEMP/greeting'</input>
    <action signal="file-changed">exit:GREETING</action>
  </window>'
  $GTK3DIALOG -p GREETING -c --styles=$TEMP/win.css 
}; export -f _greeting

# sort selections
_selections() {
	echo '<hbox>' > $TEMP/ret
	cat $TEMP/selected | while read -r sel
	do
		echo '    <pixmap name="cbg" tooltip-text="'${sel##*\/}'">
		  <width>220</width>
		  <height>120</height>
		  <input file>'$sel'</input>
		</pixmap>' >> $TEMP/ret
	done
	echo '</hbox>' >> $TEMP/ret
}; export -f _selections

# set each background
confirm_gui() {
	_selections
	PIX=$(cat $TEMP/ret)
	export CON='<window icon-name="xwwall" title="'$(gettext "Confirm selection")'">
	<vbox>
    <hbox space-expand="true" space-fill="true">
	    <text><label>'$(gettext "Please confirm that the image below is correct.")'</label></text>
	  </hbox>
	  <hbox space-expand="true" space-fill="true">
		'$PIX'
	  </hbox>
	  <hbox>
	    <button yes>
	      <action signal="button-press-event">echo '$PROG' - sleeping > '$TEMP/wake'</action>
	      <action signal="button-release-event">exit:Yes</action>
	    </button>
	    <button no>
	      <action>rm -f '$TEMP/increment'</action>
          <action>exit:No</action>
	    </button>
	    <button tooltip-text="'$(gettext "If unsatisfied with your choice try again.")'">
	      <input file icon="refresh"></input>
	      <label>'$(gettext "Refresh")'</label>
          <action>exit:REFRESH</action>
	    </button>
	  </hbox>
	</vbox>
</window>'
#'
	eval "$($GTK3DIALOG -p CON -c --styles=$TEMP/win.css)"
	case $EXIT in
		Yes)_build_command; read -r a b c <<<$(ps -ef | grep -m1 'main_gui'); kill -9 $b;;
		REFRESH)rm -f $TEMP/increment $TEMP/selected $TEMP/[XW]set $TEMP/ret;;
		*)rm -f $TEMP/$TEMP/increment $TEMP/selected $TEMP/[XW]set $TEMP/ret; return 1;;
	esac
}; export -f confirm_gui

# build options for output
_output() {
	[[ "$WAYLAND" == 'yes' ]] && fff=ww || fff=xx
	rm -f $TEMP/OP
	for output in $TEMP/${fff}*
	do
		. $output
		export OUTPUT
		export FBG="$1"
		echo "<item>$OUTPUT</item>" >> $TEMP/OP
	done
	[[ -r "$TEMP/increment" ]] || echo -n 1 > "$TEMP/increment"
	INC=$(cat $TEMP/increment)
	case $INC in
		1)DEFAULT=$(sed '1s/item/default/g' < $TEMP/OP | sed -n 1p); echo "$DEFAULT" > $TEMP/default_ent ;;
		2)DEFAULT=$(sed '2s/item/default/g' < $TEMP/OP | sed -n 2p); echo "$DEFAULT" > $TEMP/default_ent ;;
		3)DEFAULT=$(sed '3s/item/default/g' < $TEMP/OP | sed -n 3p); echo "$DEFAULT" > $TEMP/default_ent ;;
		4)DEFAULT=$(sed '4s/item/default/g' < $TEMP/OP | sed -n 4p); echo "$DEFAULT" > $TEMP/default_ent ;;
		5)DEFAULT=$(sed '5s/item/default/g' < $TEMP/OP | sed -n 5p); echo "$DEFAULT" > $TEMP/default_ent ;;
		6)DEFAULT=$(sed '6s/item/default/g' < $TEMP/OP | sed -n 6p); echo "$DEFAULT" > $TEMP/default_ent ;;
	esac
	read -r DEF < $TEMP/default_ent
	. "$CONF"
	sub_gui "$FBG" $INC $DEF
}; export -f _output

# populate buttons for the main GUI
button_gui() {
	local c i j n WALL V buttonsx buttons
	. "$CONF"
	if [[ "$XTRAS" == 'false' || -z "$XTRAS" ]]; then
		echo "$BGDIR"
		c=0
		shopt -s globstar
		for WALL in "$BGDIR"/*{,/**}
		do
			#[[ "$(file --brief --mime-type "$WALL" )" = *image* ]] || continue # test mime
			[[ "$WALL" =~ \.(svg|png|jpg)$ ]] || continue # test mime
			# we take advantage of bash math here
			# for a nicish GUI width *must* be consistent
			i=$((c/4))
			V='  		<button name="cbg" image-position="top" tooltip-text="'"${WALL##*/}"'">
		        <input file>'"\"$WALL\""'</input>
				<width>'$Wdth'</width>
				<action signal="button-press-event">_output '"\"$WALL\""' &</action>
				<action signal="button-release-event" type="disable">MAINGUI</action>
		      </button>'
		      buttonsx[i]+="$V"$'\n'
		      c=$((c+1))
		      export TOT=$((c+1))
		      if [[ $c -ge 300 ]];then
				  export TOT=300
				  _splash "$(gettext "Warning: Limit of 300 images")" 2 2 &
				  break
			  fi
		done
#		echo $buttonsx ;exit
		shopt -u globstar
		for j in "${!buttonsx[@]}"
		do buttons+="		<hbox>
			${buttonsx[j]}
			</hbox>"$'\n'
		done
		echo "$buttons" > "$TEMP/buttons"
	elif [[ "$XTRAS" == 'true' ]]; then
		echo "${EXTRA_BGDIRS[@]}"
		c=0
		n=0
		while [[ n -lt  "${#EXTRA_BGDIRS[@]}" ]]
		do
			shopt -s globstar
			for WALL in "${EXTRA_BGDIRS[n]}"/*{,/**}
			do
				#[[ "$(file --brief --mime-type "$WALL" )" = *image* ]] || continue # test mime
				[[ "$WALL" =~ \.(svg|png|jpg)$ ]] || continue # test mime
				# we take advantage of bash math here
				# for a nicish GUI width *must* be consistent
				i=$((c/4))
				V='  		<button name="cbg" image-position="top" tooltip-text="'"${WALL##*/}"'">
			        <input file>'"\"$WALL\""'</input>
					<width>'$Wdth'</width>
					<action signal="button-press-event">_output '"\"$WALL\""' &</action>
					<action signal="button-release-event" type="disable">MAINGUI</action>
			      </button>'
			      buttonsx[i]+="$V"$'\n'
			      c=$((c+1))
			      export TOT=$((c+1))
			      if [[ $c -ge 300 ]];then
					  export TOT=300
					  _splash "$(gettext "Warning: Limit of 300 images")" 2 2 &
					  break
				  fi
			done
			shopt -u globstar
			n=$((n+1))
		done
		for j in "${!buttonsx[@]}"
		do buttons+="		<hbox>
			${buttonsx[j]}
			</hbox>"$'\n'
		done
		echo "$buttons" > "$TEMP/buttons"	
	fi
}

# sub GUI
sub_gui() {
	INC=$2 DEF=$3
	[[ -z "$COLOR" ]] && COLOR=999999
	if [[ "$WAYLAND" == 'yes' ]]; then
		CCOL="-c $COLOR"
		XMODE='<item>tile</item>'
		SS='Wset'
		ACTION='<action signal="button-press-event">echo -e " -o $OUT -m $MODE '$CCOL' -i '\'$1\'' \\" >> '$TEMP/$SS'</action>'
	else
		# feh modes: --bg-scale, --bg-center[ --image-bg=$color], --bg-fill, --bg-max[ --image-bg=$color], --bg-tile
		XCOL=" --image-bg=#${COLOR}"
		[[ $NUM -eq 1 ]] && XMODE='<item>fill</item>'
		SS='Xwset'
		ACTION='<action signal="button-press-event">echo -e " --bg-$MODE '${XCOL}' '\'$1\'' \\" >> '$TEMP/$SS'</action>'
	fi
	if [[ $NUM -eq 1 ]]; then
		DO_ACTION='<action signal="button-press-event">_build_command &</action>'
		ETT=$(gettext "Pressing image will confirm,")
		XTRACTION='<action signal="button-release-event">echo '$PROG' - sleeping > '$TEMP/wake'</action>
	      <action signal="button-release-event">exit:Yes</action>'
	else
		DO_ACTION='<action signal="button-press-event">if [[ '$INC' -ge '$NUM' ]]; then confirm_gui;fi &</action>'
		ETT='Pressing image will save, you can confirm later,'
	fi
	MTEXT=$(gettext 'Choose the Mode.')
    if [[ $INC -eq $NUM && "$WAYLAND" != 'yes' ]]; then # only for X11
    COMBO='<hbox space-expand="false" space-fill="false">
      <entry name="noent" editable="false"><default>'$(gettext "Mode:")'</default><sensitive>false</sensitive></entry>
      <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
      <comboboxtext space-expand="true" space-fill="true">
        <variable>MODE</variable>
        <item>scale</item>
        <item>max</item>
        <item>fill</item>
        <item>center</item>
        <item>tile</item>
      </comboboxtext>
    </hbox>'
    elif [[ "$WAYLAND" == 'yes' ]]; then  
    COMBO='<hbox space-expand="false" space-fill="false">
      <entry name="noent" editable="false"><default>'$(gettext "Mode:")'</default><sensitive>false</sensitive></entry>
      <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
      <comboboxtext space-expand="true" space-fill="true">
        <variable>MODE</variable>
        <item>'$(gettext stretch)'</item>
        <item>'$(gettext fill)'</item>
        <item>'$(gettext fit)'</item>
        <item>'$(gettext center)'</item>
        <item>'$(gettext tile)'</item>
      </comboboxtext>
    </hbox>'
    fi
	export SUBGUI='<window icon-name="xwwall" title="'$(gettext "Selection")'">
	<vbox>
    <hbox space-expand="true" space-fill="true">
	  <text><label>'$MTEXT' '$(gettext "Press the image to set.")'</label></text>
	</hbox>
    '$COMBO'
	<hbox space-expand="false" space-fill="false">
      <entry name="noent" editable="false"><default>'$(gettext "Output:")' '$INC'</default><sensitive>false</sensitive></entry>
      <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
      <entry name="ent" editable="false" width-chars="12">
        <variable>OUT</variable>
        '$DEF'
      </entry>
    </hbox>
	  <hbox space-expand="true" space-fill="true">
		<button name="cbg" tooltip-text="'"${1##*/}"$'\n'''$ETT' '$(gettext "or Press Cancel to reject and confinue.")'">
		  <variable>CBG</variable>
	      <input file>'$1'</input>
	  	  <width>320</width>
		  <action signal="button-press-event">echo -n '$((INC+1))' > $TEMP/increment</action>
		  <action signal="button-press-event">echo '$1' >> '$TEMP'/selected</action>
		  '$ACTION'
		  <action>sed -i -e "s% .$%%g" '$TEMP/$SS'</action>
	      <action signal="button-press-event">echo '$PROG' > '$TEMP/wake'</action>
		  '$DO_ACTION'
		  '$XTRACTION'
	      <action signal="button-release-event">exit:SUB</action>
		</button>
	  </hbox>
	  <hbox>
	    <button ok>
		  <action signal="button-press-event">echo -n '$((INC+1))' > $TEMP/increment</action>
		  <action signal="button-press-event">echo '$1' >> '$TEMP'/selected</action>
		  '$ACTION'
		  <action>sed -i -e "s% .$%%g" '$TEMP/$SS'</action>
	      <action signal="button-press-event">echo '$PROG' > '$TEMP/wake'</action>
		  '$DO_ACTION'
		  '$XTRACTION'
	      <action signal="button-release-event">exit:SUB</action>
	    </button>
	    <button cancel>
	      <action signal="button-press-event">echo '$PROG' > '$TEMP/wake'</action>
	      <action signal="button-release-event">exit:NO</action>
	    </button>
	  </hbox>
	</vbox>
    <variable>SUBGUI</variable>
   </window>'
	eval $($GTK3DIALOG -p SUBGUI -c --styles=$TEMP/win.css)
	case $EXIT in
		Yes)read -r a b c <<<$(ps -ef | grep -m1 'main_gui'); kill -9 $b;;
	esac
}; export -f sub_gui

# populate the main GUI
main_gui() {
	echo ''$PROG' - sleeping' > "$TEMP/wake"
	[[ -z "$SWIDTH" ]] && SWIDTH=0
	[[ -r "$TEMP/main_gui.xml" ]] && _splash "$(gettext "Please wait ...")" 6 2 &
	BUTTONS=$(cat $TEMP/buttons)
	export MAINGUI='<window icon-name="xwwall" file-monitor="true" auto-refresh="true" title="'$PROG' - '$(gettext "Background Choice")'">
  <vbox>
    <hbox space-expand="true" space-fill="true">
      <text use-markup="true" tooltip-text="'$TOT' '$(gettext "images")'"><label>"<b>'$(gettext "Select an image for your wallpaper by pressing the image.")'</b>"</label></text>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox>
      <vbox scrollable="true" height="'$MHght'" width="'$((MWdth+SWIDTH))'">
        '$BUTTONS'
      </vbox>
    </hbox>
    <hbox space-expand="true" space-fill="true">
    <hbox space-expand="false" space-fill="false">
      <button tooltip-text="'$(gettext "Preferences")'">
        <label>'$(gettext "Preferences")'</label>
        <width>16</width>
        <input file icon="preferences-desktop-wallpaper"></input>
        <action>exit:PREFS</action>
      </button>
    </hbox>
	<hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
      <text label="'$(gettext "Confirmation is required when finished.")'"></text>
    <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
    <hbox space-expand="false" space-fill="false">
      <button cancel>
        <label>'$(gettext "Cancel")'</label>
        <action>kill '$PID'</action>
        <action>exit:abort</action>
      </button>
    </hbox>
    </hbox>
  </vbox>
  <variable>MAINGUI</variable>
  <input file>'$TEMP/wake'</input>
  <action signal="realize">echo started > '$TEMP/greeting'</action>
  <action signal="file-changed" type="enable">MAINGUI</action>
</window>'
	[[ -r "$TEMP/main_gui.xml" ]] || printf "%s\n" "$MAINGUI" > $TEMP/main_gui.xml
	eval "$($GTK3DIALOG -f $TEMP/main_gui.xml -c --styles=$TEMP/win.css)"
	
	if [[ "$EXIT" == "PREFS" ]]; then
		_pref
	fi
}; export -f main_gui

# preferences
_pref() {
	. "$CONF"
	if [[ -n "$EXTRA_BGDIRS" ]]; then
		[[ -n "$XTRAS" ]] || XTRAS=true
		DXTRA='	<hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
        <checkbox>
          <label>'$(gettext "enable extra directories.")'</label>
          <variable>CXTRA</variable>
          <default>'$XTRAS'</default>
        </checkbox>
      </hbox>
    </hbox>'
	fi
	export EXTRA_DIRS='<window icon-name="gtk-preferences" title="'$(gettext "Extra Directories")'" width-request="400">
	  <vbox>
	    <hbox space-expand="true" space-fill="true">
          <text use-markup="true"><label>"<b>'$(gettext "Select extra directories.")'</b>"</label></text>
        </hbox>
        <hseparator space-expand="true" space-fill="true"></hseparator>
        <hbox space-expand="true" space-fill="true">
          <text><label>"'$(gettext "Press Save and")' '$PROG' '$(gettext "will restart when you are ready.")'"</label></text>
        </hbox>
        <hseparator name="ent" space-expand="true" space-fill="true"></hseparator>
        <hbox space-expand="true" space-fill="true">
          <text><label>"'$(gettext "Choose the directory to search wallpapers.")'"</label></text>
        </hbox>
        <hbox space-expand="true" space-fill="true">
          <hbox space-expand="true" space-fill="true">
           <entry accept="directory" fs-title="'$PROG'">
            <variable>BACKGROUNDS0</variable>
           </entry>
          </hbox>
          <hbox space-expand="false" space-fill="false">
          <button>
            <input file icon="gtk-directory"></input>
            <variable>FILE_BROWSE_DIRECTORY0</variable>
            <action function="fileselect">BACKGROUNDS0</action>
          </button>
          </hbox>
        </hbox>
        <hseparator space-expand="true" space-fill="true"></hseparator>
        <hbox space-expand="true" space-fill="true">
          <hbox space-expand="true" space-fill="true">
           <entry accept="directory" fs-title="'$PROG'">
            <variable>BACKGROUNDS1</variable>
           </entry>
          </hbox>
          <hbox space-expand="false" space-fill="false">
          <button>
            <input file icon="gtk-directory"></input>
            <variable>FILE_BROWSE_DIRECTORY1</variable>
            <action function="fileselect">BACKGROUNDS1</action>
          </button>
          </hbox>
        </hbox>
        <hseparator space-expand="true" space-fill="true"></hseparator>
        <hbox space-expand="true" space-fill="true">
          <hbox space-expand="true" space-fill="true">
           <entry accept="directory" fs-title="'$PROG'">
            <variable>BACKGROUNDS2</variable>
          </entry>
          </hbox>
          <hbox space-expand="false" space-fill="false">


          <button>
            <input file icon="gtk-directory"></input>
            <variable>FILE_BROWSE_DIRECTORY2</variable>
            <action function="fileselect">BACKGROUNDS2</action>
          </button>
          </hbox>
        </hbox>
       </vbox>
	  <variable>EXTRA_DIRS</variable>
	</window>
	'
	
[[ "$SPLASH" == 'false' ]] && CDEF=false || CDEF=true
[[ -n "$COLOR" ]] && DEFCOL=#${COLOR} ||  DEFCOL=#666666
[[ -n "$SWIDTH" ]] && SW=$SWIDTH || SW=0
[[ -n "$TWIDTH" ]] && TW=$TWIDTH || TW=9
if [[ $NUM -gt 1 ]]; then
    SPLASHPREF='    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
        <checkbox>
          <label>'$(gettext "enable initial splash screen")'</label>
          <variable>SPL</variable>
          <default>'$CDEF'</default>
        </checkbox>
      </hbox>
    </hbox>'
fi
export PGUI='<window icon-name="gtk-preferences" title="'$(gettext "Preferences")'" width-request="400">
  <vbox>
    <hbox space-expand="true" space-fill="true">
      <text use-markup="true"><label>"<b>'$(gettext "Select your preferences.")'</b>"</label></text>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <text><label>"'$(gettext "Press Save and")' '$PROG' '$(gettext "will restart when you are ready.")'"</label></text>
    </hbox>
    <hseparator name="ent" space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <text><label>'$(gettext "Choose the directory to search wallpapers.")'</label></text>
    </hbox>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
      <entry accept="directory" fs-title="'$PROG'">
        <default>'$BGDIR'</default>
        <variable>BACKGROUNDS</variable>
      </entry>
      </hbox>
      <hbox space-expand="false" space-fill="false">
      <button>
        <input file icon="gtk-directory"></input>
        <variable>FILE_BROWSE_DIRECTORY</variable>
        <action function="fileselect">BACKGROUNDS</action>
      </button>
      </hbox>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
'$DXTRA'
'$SPLASHPREF'
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
        <hbox space-expand="false" space-fill="false">
        <text label="'$(gettext "GUI width adjustment")'" tooltip-text="'$(gettext "Adjust the width of the interface to suit. The thumbnail setting below may also need adjustment")'."></text>
        </hbox>
        <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
        <hbox space-expand="false" space-fill="false">
        <spinbutton range-min="-300" range-max="300" range-step="2">
          <variable>SW0</variable>
          <default>'$SW'</default>
        </spinbutton>
        </hbox>
      </hbox>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
        <hbox space-expand="false" space-fill="false">
        <text label="'$(gettext "Thumbnail adjustment")'" tooltip-text="'$(gettext "Adjust the width of thumbnail images. May need to adjust above setting to suit. Larger number is smaller width")'."></text>
        </hbox>
        <hseparator space-expand="true" space-fill="true" name="sep"></hseparator>
        <hbox space-expand="false" space-fill="false">
        <spinbutton range-min="8" range-max="12" range-step="1">
          <variable>TW0</variable>
          <default>'$TW'</default>
        </spinbutton>
        </hbox>
      </hbox>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="true" space-fill="true">
      <hbox space-expand="true" space-fill="true">
      <entry editable="false">
        <default>'$(gettext "Choose a background color")'</default>
      </entry>
      </hbox>
      <hbox space-expand="false" space-fill="false">
      <colorbutton>
        <default>'$DEFCOL'</default>
        <variable>CLB0</variable>
      </colorbutton>
      </hbox>
    </hbox>
    <hseparator space-expand="true" space-fill="true"></hseparator>
    <hbox space-expand="false" space-fill="false">
      <button cancel>
        <action>exit:SAVE</action>
        <action>kill '$PID'</action>
      </button>
      <button>
        <label>'$(gettext "Save")'</label>
        <input file icon="gtk-save"></input>
        <action>exit:SAVE</action>
      </button>
    </hbox>
  </vbox>
</window>'
eval "$($GTK3DIALOG -p PGUI -c --styles=$TEMP/win.css)"
if [[ -d "$BACKGROUNDS" ]]; then
    sed -i "s%^BGDIR.*$%BGDIR=\"$BACKGROUNDS\"%" "$CONF"
    rm -f "$TEMP/buttons"
    rm -f "$TEMP/main_gui.xml"
fi
if ! [[ -z "$BACKGROUNDS0" && -z "$BACKGROUNDS1" && -z "$BACKGROUNDS2" ]]; then # do nothing if all vars are empty
    if [[ -d "$BACKGROUNDS0" || -d "$BACKGROUNDS1" || -d "$BACKGROUNDS2" ]]; then
        if grep -q 'EXTRA_BGDIRS' "$CONF"; then
            sed -i '/EXTRA_BGDIRS/d' "$CONF"
        fi
        printf "%s" "EXTRA_BGDIRS=( " >>  "$CONF"
        [[ -n "$BACKGROUNDS0" ]] && printf "%s" "\"$BACKGROUNDS0\" " >>  "$CONF"
        [[ -n "$BACKGROUNDS1" ]] && printf "%s" "\"$BACKGROUNDS1\" " >>  "$CONF"
        [[ -n "$BACKGROUNDS2" ]] && printf "%s" "\"$BACKGROUNDS2\" " >>  "$CONF"
        printf "%s\n" ")" >>  "$CONF"
        rm -f "$TEMP/buttons"
        rm -f "$TEMP/main_gui.xml"
        # since user just set these, enable them
        echo "XTRAS=true" >> "$CONF"
    fi
fi
if grep -q 'SPLASH' "$CONF"; then
    sed -i "s/^SPLASH.*$/SPLASH=$SPL/" "$CONF"
else
    echo "SPLASH=$SPL" >> "$CONF"
fi
if grep -q 'XTRAS' "$CONF"; then
    [[ -n  "$CXTRA" ]] && \
    sed -i "s/^XTRAS.*$/XTRAS=$CXTRA/" "$CONF"
else
    [[ -n  "$CXTRA" ]] && \
    echo "XTRAS=$CXTRA" >> "$CONF"
fi
if grep -q 'SWIDTH' "$CONF"; then
    sed -i "s/^SWIDTH.*$/SWIDTH=$SW0/" "$CONF"
else
    echo "SWIDTH=$SW0" >> "$CONF"
fi
echo $BACKGROUNDS0 $BACKGROUNDS1 $BACKGROUNDS2
if grep -q 'TWIDTH' "$CONF"; then
    sed -i "s/^TWIDTH.*$/TWIDTH=$TW0/" "$CONF"
else
    echo "TWIDTH=$TW0" >> "$CONF"
fi
if grep -q 'COLOR' "$CONF"; then
    sed -i "s/^COLOR.*$/COLOR=${CLB0:1:6}/" "$CONF"
else
    echo "COLOR=${CLB0:1:6}" >> "$CONF"
fi
if [[ "$EXIT" == 'SAVE' ]]; then
    exec $0
fi
}; export -f _pref


_build_command() {
    if [[ "$WAYLAND" == 'yes' ]]; then
        echo 'killall swaybg >/dev/null 2>&1' > $TEMP/cmd
        echo 'swaybg \' >> $TEMP/cmd
        cat $TEMP/Wset >> $TEMP/cmd
        echo '>/dev/null 2>&1 &' >> $TEMP/cmd
        # run it
        . "$TEMP/cmd"
        cat $TEMP/cmd > "$CONFDIR/cmd" # you can put this in your startup file
    else
        # this builds ~/.fehbg with the command below.
        echo 'killall feh >/dev/null 2>&1' > $TEMP/cmd
        echo 'feh \' >> $TEMP/cmd
        cat $TEMP/Xwset >> $TEMP/cmd
        echo '>/dev/null 2>&1 &' >> $TEMP/cmd
        # run it
        . "$TEMP/cmd"
    fi
}; export -f _build_command

_dependencies() {     # adapted from bl-includes
    # Usage: _dependencies command [command...]
    local missing_commands=()
    i=
    for i in "$@"
    do
        hash "$i" 2>/dev/null || missing_commands+=(" $i")
    done

    if [[ ${missing_commands[0]} ]];then
        ERR_MSG="$(gettext "This script requires the following commands: \"${missing_commands[*]}\" . Please install the packages containing the missing commands and re-run the script.")"
        _splash "${ERR_MSG}" 3
        exit
    fi
}

trap_exit() {
    trap "rm -rf $TEMP" EXIT
}; export -f trap_exit


########################      main        ##############################

# required programs
declare -a APPS
if [[ "$WAYLAND" == 'yes' ]]; then
    APPS=( "$gtkdialog" "wlr-randr" "swaybg" )
else
    APPS=( "$gtkdialog" "xrandr" "feh" )
fi
_dependencies  "${APPS[@]}" 

trap_exit
export PID=$$

# test for compatibility
KWNINX=$(pidof kwin_x11)
KWNINW=$(pidof kwin_wayland)
GNOME=$(pidof gnome-session) # covers X11 and wayland
XFCE4=$(pidof xfce4-session) # covers X11 and wayland
if [[ -n "$KWNINX" || "$KWNINW" || "$GNOME" || "$XFCE4" ]]; then # more to add
    _splash "$(gettext "WARNING: Your desktop may be unsupported")" 7
fi

if [[ ! -d "$BGDIR" ]]; then
    _splash "$(gettext "Please set a background directory")" 3
    _pref
else
    if  [[ -w "$(pwd)" ]]; then
        [[ -r "$BGDIR/Solid_Color.svg" ]] || cat > "$BGDIR/Solid_Color.svg" <<EOS
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1366 768">
 <path style="fill:rgba(0,0,0,0.0);" d="m 0,0 1366,0 0,768 -1366,0 z"/>
</svg>	
EOS
    fi
fi

touch "$TEMP/greeting"
_greeting &

if [[ "$NUM" != '1' ]]; then
    # this nag can be disabled in prefs
    _splash "$(gettext "You have $NUM monitors connected. Carefully choose an image for each of them.")" 0 b &
fi

echo ================
button_gui
main_gui
[ "$EXIT" = abort ] || $0 &
