#!/bin/bash
#(c) Barry Kauler 2005/2006 www.puppylinux.com
#(c) rarsa, zigbert, rerwin, rodin.s, ecube, 01micko, etc
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
#keyboard/mouse wizard for Puppy Linux

# Dialogs:
# - X Keyboard Properties (xset) [$HOME/.xset (/root/.xinitrc)]
# - Mouse sensitivity     (xset) [$HOME/.xset (/root/.xinitrc)]
# - Mouse Properties (xorg.conf, xmodmap, unclutter) [requires X restart)
# - * Input-wizard *

export TEXTDOMAIN=input-wizard
export OUTPUT_CHARSET=UTF-8
[ -d /usr/lib64/xorg ] && LIB=lib64 || LIB=lib
export LIB=$LIB

#==============================================================
#    MOUSE PROPERTIES (xmodmap, unclutter, xorg.conf opts)
#==============================================================

touchpad_utils(){
	if type psynclient >/dev/null 2>&1; then
		exec psynclient
	elif type flsynclient >/dev/null 2>&1; then
		exec flsynclient
	fi
}

export -f touchpad_utils

if [ "$1" = "mouse" ] ; then

	CHK_SCROLL_WHEEL="true" #Mouse scroll wheel
	grep -q '#Option\W\+"ZAxisMapping' /etc/X11/xorg.conf && CHK_SCROLL_WHEEL="false"

	CHK_MIDDLE_BUTTON="true"
	grep -q '#Option\W\+"Emulate3Buttons' /etc/X11/xorg.conf && CHK_MIDDLE_BUTTON="false"

	CHK_AUTOHIDE_MOUSE="false"
	IDLETIME="0"
	if [ -f /etc/mousehide ];then
		IDLETIME="`cat /etc/mousehide | cut -f 1 -d ','`"
		[ ! "$IDLETIME" = "0" ] && CHK_AUTOHIDE_MOUSE="true"
	fi

	# if the button 1 is mapped to something different than 1 then I assume
	# it is a lefhanded mouse
	CHK_LEFTHANDED_MOUSE="false"
	LEFT_H_MOUSE=`xmodmap -pp | grep -om1 "[0-9]$"`
	if [ ${LEFT_H_MOUSE} -ne 1 ] ; then
		CHK_LEFTHANDED_MOUSE="true"
	fi

	#v4.11 Control "tapping" function on ALPS/Synaptics touchpads - manipulates MaxTapTime option in xorg.conf.
	TAPCHKBOX=""
	if [ -f /etc/X11/xorg.conf -a "`grep '"MaxTapTime"' /etc/X11/xorg.conf`" != "" ];then #touchpad present
		[ "`grep '"MaxTapTime"' /etc/X11/xorg.conf | grep '"0"'`" = "" ] && CHECKT="true" || CHECKT="false" #taps enabled/disabled
		TAPCHKBOX="    <checkbox>
     <label>$(gettext 'Enable touchpad tapping for mouse button clicks')</label>
     <variable>CHECKBOX013</variable>
     <default>$CHECKT</default>
    </checkbox>
"
	fi
  
	export MouseWizard='
<window title="'$(gettext 'Mouse properties')'" icon-name="gtk-preferences" resizable="false">
<vbox space-expand="true" space-fill="true">
  '"`/usr/lib/gtkdialog/xml_info fixed mouse.svg 60 " " "$(gettext "Configure your mouse")"`"'
  <hbox space-expand="true" space-fill="true">
  <vbox space-expand="true" space-fill="true">
    <frame '$(gettext 'Features')'>
      <text height-request="5"><label>""</label></text>
      <checkbox>
        <label>'$(gettext 'Mouse has a scroll wheel')'</label>
        <variable>CHK_SCROLL_WHEEL</variable>
        <default>'$CHK_SCROLL_WHEEL'</default>
      </checkbox>
      <checkbox>
        <label>'$(gettext 'Middle button emulated on a 2-button mouse')'</label>
        <variable>CHK_MIDDLE_BUTTON</variable>
        <default>'$CHK_MIDDLE_BUTTON'</default>
      </checkbox>
      <checkbox>
        <label>'$(gettext 'Auto-hide mouse cursor when not moving')'</label>
        <variable>CHK_AUTOHIDE_MOUSE</variable>
        <default>'$CHK_AUTOHIDE_MOUSE'</default>
      </checkbox>
      <checkbox>
        <label>'$(gettext 'Left-handed mouse')'</label>
        <variable>CHK_LEFTHANDED_MOUSE</variable>
        <default>'$CHK_LEFTHANDED_MOUSE'</default>
      </checkbox>
      '$TAPCHKBOX'
      <text height-request="5"><label>""</label></text>
    </frame>
  </vbox>
  </hbox>
  <hbox space-expand="false" space-fill="false">
    <button space-expand="false" space-fill="false">
      <label>'$(gettext "Cancel")'</label>
      '"`/usr/lib/gtkdialog/xml_button-icon cancel`"'
      <action>exit:CANCEL</action>
    </button>
    <button space-expand="false" space-fill="false">
      <label>'$(gettext "Ok")'</label>
      '"`/usr/lib/gtkdialog/xml_button-icon ok`"'
      <action>exit:OK</action>
    </button>
  </hbox>
</vbox>
</window>'

	. /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
	RETPARAMS=`gtkdialog --center -p MouseWizard --styles=/tmp/gtkrc_xml_info.css`
	eval "$RETPARAMS"

	if [ "$EXIT" != "OK" ] ; then
		exit
	fi

	#v4.11 Touchpad tapping control - sets xorg.conf MaxTapTime to 0 to disable tapping and to default or user-specified xorg.conf value to enable.
	if [ "`echo "$RETPARAMS" | grep "CHECKBOX013"`" != "" ];then
		ZEROTAPTIME="`grep '"MaxTapTime"' /etc/X11/xorg.conf | grep '"0"'`"
		if [ "`echo "$RETPARAMS" | grep "CHECKBOX013" | grep "true"`" != "" ];then #enable tapping
			if [ "$ZEROTAPTIME" != "" ];then #currently disabled, else leave as is
				[ -f /root/.maxtaptime ] && MAXTAPTIME="`grep -m 1 '"MaxTapTime"' /root/.maxtaptime`" || MAXTAPTIME='	Option "MaxTapTime" "220"'
				sed -i -e "s/$ZEROTAPTIME/$MAXTAPTIME/" /etc/X11/xorg.conf
			fi
		else #disable tapping
			if [ "$ZEROTAPTIME" = "" ];then #currently enabled, else leave as is
				MAXTAPTIME="`grep '"MaxTapTime"' /etc/X11/xorg.conf`"
				if [ "$MAXTAPTIME" != "" ];then
					echo "$MAXTAPTIME" > /root/.maxtaptime
					ZEROTAPTIME='	Option "MaxTapTime" "0"'
					SEDSCRIPT="s/$MAXTAPTIME/$ZEROTAPTIME/"
					sed -i -e  "$SEDSCRIPT" /etc/X11/xorg.conf
				fi
			fi
		fi
	fi     

	if [ "$CHK_LEFTHANDED_MOUSE" = "true" ];then #v2.01
		XMODMAP_CMD="pointer = 3 2 1 4 5"
	else
		XMODMAP_CMD="pointer = 1 2 3 4 5"
	fi
	xmodmap -e "${XMODMAP_CMD}"
	grep -v "^pointer" /root/.Xmodmap > /tmp/Xmodmap.tmp
	cp /tmp/Xmodmap.tmp /root/.Xmodmap
	echo "${XMODMAP_CMD}" >> /root/.Xmodmap
	#

	if [ "$CHK_AUTOHIDE_MOUSE" = "true" ];then #v2.01
		[ "$IDLETIME" = "0" ] && IDLETIME="3"
		echo -n "${IDLETIME}," > /etc/mousehide
		[ "`pidof unclutter`" = "" ] && unclutter -idle $IDLETIME &
	else
		echo -n '0,' > /etc/mousehide
		[ ! "`pidof unclutter`" = "" ] && killall unclutter
	fi

	# emulate middle button
	if [ "$CHK_MIDDLE_BUTTON" = "true" ];then
		#\W\+ means one or more whitespace chars...
		sed_ptn1='s/.*#Option\W\+"Emulate3Buttons"/	Option      "Emulate3Buttons"/g'
		sed_ptn2='s/.*#Option\W\+"Emulate3Timeout"/	Option      "Emulate3Timeout"/g'
	else
		sed_ptn1='s/.*Option\W\+"Emulate3Buttons"/	#Option     "Emulate3Buttons"/g'
		sed_ptn2='s/.*Option\W\+"Emulate3Timeout"/	#Option     "Emulate3Timeout"/g'
	fi
	if [ -f /etc/X11/xorg.conf ];then
		sed -i -e "$sed_ptn1" -e "$sed_ptn2" /etc/X11/xorg.conf
	fi

	if [ "$CHK_SCROLL_WHEEL" = "true" ];then
		sed_ptn='s/.*#Option\W\+"ZAxisMapping"\W\+"4 5".*/	Option      "ZAxisMapping" "4 5" #scrollwheel/g'
	else
		sed_ptn='s/.*Option\W\+"ZAxisMapping"\W\+"4 5".*/	#Option     "ZAxisMapping" "4 5" #scrollwheel/g'
	fi
	[ -f /etc/X11/xorg.conf ] && sed -i "$sed_ptn" /etc/X11/xorg.conf
	exit
fi


#==============================================================
#                    MOUSE SENSITIVITY
#==============================================================

if [ "$1" = "mousex" ] ; then
	XSETQ="`LANG=C xset q`"
	MOUSEACCEL10=`echo "$XSETQ" | grep '  acceleration:' | grep ' threshold:' | tr -s ' ' | cut -f 3 -d ' ' | cut -f 1 -d '/'`
	MOUSEACCELDIV=`echo "$XSETQ" | grep '  acceleration:' | grep ' threshold:' | tr -s ' ' | cut -f 3 -d ' ' | cut -f 2 -d '/'`
	MOUSEACCEL=`LANG=C dc -e "${MOUSEACCEL10} ${MOUSEACCELDIV} 2 k / p"` #130209
	MOUSETHRESHOLD=`echo "$XSETQ" | grep '  acceleration:' | grep ' threshold:' | tr -s ' ' | cut -f 5 -d ' '`
	#precaution
	[ "$MOUSEACCEL" = "" ] && MOUSEACCEL='2.0'
	[ "$MOUSETHRESHOLD" = "" ] && MOUSETHRESHOLD='4'

	function pupx_mouseaccel() {
		if [ -z "$MOUSEACCEL" ] ; then
			return
		fi
		MOUSEACCX10=`LANG=C dc -e "${MOUSEACCEL} 10 * 1 / p"` #130209
		LANG=C xset m ${MOUSEACCX10}/10 ${MOUSETHRESHOLD} #130209
		XSET_MOUSE="LANG=C xset m ${MOUSEACCX10}/10 ${MOUSETHRESHOLD}"
		[ ! "$1" ] && Xdialog --title "Mouse settings" --msgbox "Mouse acceleration set to ${MOUSEACCX10}/10\nMouse threshold set to ${MOUSETHRESHOLD}\n(for this session only)" 0 0
	}
	export -f pupx_mouseaccel
	combo_items() {
		for i in $@ ; do echo "<item>${i}</item>" ; done
	}

	export MAIN_DIALOG='<window title="'$(gettext 'Mouse sensitivity')'" icon-name="gtk-preferences" resizable="false">
<vbox>
   <vbox>
    <frame>
     <hbox>
      <text>
       <label>'$(gettext 'Acceleration:')'</label>
      </text>
      <comboboxtext>
       <variable>MOUSEACCEL</variable>
       '$(combo_items ${MOUSEACCEL} 7.0 6.5 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.8 1.6 1.4 1.2 1.0)'
      </comboboxtext>
     </hbox>
     <text><label>'$(gettext "The mouse will accelerate with this factor when moved more than 'threshold' pixels in a short time")'</label></text>
     <hbox>
      <text>
       <label>'$(gettext 'Threshold:')'</label>
      </text>
      <comboboxtext>
       <variable>MOUSETHRESHOLD</variable>
       '$(combo_items ${MOUSETHRESHOLD} 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1)'
      </comboboxtext>
     </hbox>
     <text><label>'$(gettext 'Acceleration will happen when the mouse is moved this many pixels in a short time')'</label></text>
    </frame>
   </vbox>
  <hbox>
   <button cancel>
    <action type="exit">no save</action>
   </button>
   <button>
    <input file stock="gtk-apply"></input>
    <label>'$(gettext 'Apply')'</label>
    <action>pupx_mouseaccel &</action>
   </button>
   <button ok>
    <action type="exit">save settings</action>
   </button>
  </hbox>
</vbox>
</window>'

	RETPARAMS="`gtkdialog --center --program=MAIN_DIALOG`"
	eval "$RETPARAMS"
	if [ "$EXIT" = "save settings" ] ; then
		pupx_mouseaccel z
		touch $HOME/.xset.sh
		sed -i '/ m /d' $HOME/.xset.sh
		echo "$XSET_MOUSE" >> $HOME/.xset.sh
	fi
	exit
fi


#==============================================================
#                    LIBINPUT MOUSE PROPERTIES
#==============================================================

if [ "$1" = "libinputmouse" ] ; then
	#https://github.com/lahwaacz/Scripts/blob/master/toggle-touchpad.sh
	TOUCHPAD="$(xinput list | grep -P '(?<= )[\/\w\s:]*(?i)(touchpad|trackpad|synaptics)(?-i).*?(?=\s*id)' -o | head -n1)"
	if [ "$TOUCHPAD" ]; then
		[ ! "`grep 'LIBINPUT_DEFAULT_TOUCHPAD_ON' $HOME/.libinputrc 2>/dev/null`" ] && echo "LIBINPUT_DEFAULT_TOUCHPAD_ON=1" >> $HOME/.libinputrc
		TOUCHPADSTATE="$(xinput list-props "$TOUCHPAD" | grep -P ".*Device Enabled.*\K.(?=$)" -o)"
		[ "$TOUCHPADSTATE" = "1" ] && TOUCHPADSTATE="true" || TOUCHPADSTATE="false"

		func_toggle_touchpad(){
			#Use xinput list to search for touchpads, then get name of first touchpad
			TOUCHPAD="$(xinput list | grep -P '(?<= )[\/\w\s:]*(?i)(touchpad|trackpad|synaptics)(?-i).*?(?=\s*id)' -o | head -n1)"
			#Toggle touchpad to on/off state opposite of current state
			if [[ "$(xinput list-props "$TOUCHPAD" | grep -P ".*Device Enabled.*\K.(?=$)" -o)" == "1" ]]; then
				sed -i "s%^LIBINPUT_DEFAULT_TOUCHPAD_ON=.*%LIBINPUT_DEFAULT_TOUCHPAD_ON=0%" ~/.libinputrc 
			else
				sed -i "s%^LIBINPUT_DEFAULT_TOUCHPAD_ON=.*%LIBINPUT_DEFAULT_TOUCHPAD_ON=1%" ~/.libinputrc
			fi
}
		export -f func_toggle_touchpad

		TOUCHPAD_TOGGLE='
    <checkbox>
     <label>'$(gettext 'Touchpad ON')'</label>
     <variable>TOUCHPADSTATE</variable>
     <default>'$TOUCHPADSTATE'</default>
     <action>func_toggle_touchpad</action>
    </checkbox>'
	fi

	. ~/.libinputrc

	function libinput_apply() {
		[ -n "$MOUSEACCEL" ] && sed -i "s%^LIBINPUT_DEFAULT_ACCELERATION=.*%LIBINPUT_DEFAULT_ACCELERATION=$MOUSEACCEL%" ~/.libinputrc

		MOUSEACCELPROFILENUM=-1
		case "$MOUSEACCELPROFILE" in
			"$(gettext 'Flat')") MOUSEACCELPROFILENUM=1 ;;
			"$(gettext 'Adaptive')") MOUSEACCELPROFILENUM=2 ;;
		esac
		[ $MOUSEACCELPROFILENUM -ge 0 ] && sed -i "s%^LIBINPUT_DEFAULT_ACCELERATION_PROFILE=.*%LIBINPUT_DEFAULT_ACCELERATION_PROFILE=$MOUSEACCELPROFILENUM%" ~/.libinputrc

		case "$TAPTOCLICK" in
			true) sed -i "s%^LIBINPUT_DEFAULT_TAP=.*%LIBINPUT_DEFAULT_TAP=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_TAP=.*%LIBINPUT_DEFAULT_TAP=0%" ~/.libinputrc ;;
		esac;

		case "$TAPANDDRAG" in
			true) sed -i "s%^LIBINPUT_DEFAULT_DRAG=.*%LIBINPUT_DEFAULT_DRAG=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_DRAG=.*%LIBINPUT_DEFAULT_DRAG=0%" ~/.libinputrc ;;
		esac;

		case "$DISABLEWHILETYPING" in
			true) sed -i "s%^LIBINPUT_DEFAULT_DISABLE_WHILE_TYPING=.*%LIBINPUT_DEFAULT_DISABLE_WHILE_TYPING=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_DISABLE_WHILE_TYPING=.*%LIBINPUT_DEFAULT_DISABLE_WHILE_TYPING=0%" ~/.libinputrc ;;
		esac;

		case "$MIDDLEEMULATION" in
			true) sed -i "s%^LIBINPUT_DEFAULT_MIDDLE_EMULATION=.*%LIBINPUT_DEFAULT_MIDDLE_EMULATION=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_MIDDLE_EMULATION=.*%LIBINPUT_DEFAULT_MIDDLE_EMULATION=0%" ~/.libinputrc ;;
		esac;

		case "$NATURALSCROLLING" in
			true) sed -i "s%^LIBINPUT_DEFAULT_NATURAL_SCROLL=.*%LIBINPUT_DEFAULT_NATURAL_SCROLL=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_NATURAL_SCROLL=.*%LIBINPUT_DEFAULT_NATURAL_SCROLL=0%" ~/.libinputrc ;;
		esac;
	
		CLICKMETHODNUM=-1
		case "$CLICKMETHOD" in
			"$(gettext 'None')") CLICKMETHODNUM=0 ;;
			"$(gettext 'Button areas')") CLICKMETHODNUM=1 ;;
			"$(gettext 'Fingers')") CLICKMETHODNUM=2 ;;
		esac
		[ $CLICKMETHODNUM -ge 0 ] && sed -i "s%^LIBINPUT_DEFAULT_CLICK_METHOD=.*%LIBINPUT_DEFAULT_CLICK_METHOD=$CLICKMETHODNUM%" ~/.libinputrc

		SCROLLMETHODNUM=-1
		case "$SCROLLMETHOD" in
			"$(gettext 'No scrolling')") SCROLLMETHODNUM=0 ;;
			"$(gettext '2 fingers')") SCROLLMETHODNUM=1 ;;
			"$(gettext 'Edge')") SCROLLMETHODNUM=2 ;;
			"$(gettext 'On button down')") SCROLLMETHODNUM=4 ;;
		esac
		[ $SCROLLMETHODNUM -ge 0 ] && sed -i "s%^LIBINPUT_DEFAULT_SCROLL_METHOD=.*%LIBINPUT_DEFAULT_SCROLL_METHOD=$SCROLLMETHODNUM%" ~/.libinputrc

		case "$LEFTHANDED" in
			true) sed -i "s%^LIBINPUT_DEFAULT_LEFT_HANDED=.*%LIBINPUT_DEFAULT_LEFT_HANDED=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_LEFT_HANDED=.*%LIBINPUT_DEFAULT_LEFT_HANDED=0%" ~/.libinputrc ;;
		esac;

		if [ -z "$WAYLAND_DISPLAY" ]; then
			xinput-apply
			return
		fi

		/usr/lib/gtkdialog/box_yesno --yes-first "$(gettext 'Pointer Properties')" "$(gettext 'For the changes to effect you must restart X... Would you like to restart X now?')"
		[ $? -eq 0 ] && restartwm
	}
	export -f libinput_apply
	combo_items() {
		for i in $@ ; do echo "<item>${i}</item>" ; done
	}

	case "$LIBINPUT_DEFAULT_ACCELERATION_PROFILE" in
		1) MOUSEACCELPROFILES="<item>$(gettext 'Flat')</item><item>$(gettext 'Adaptive')</item>" ;;
		*) MOUSEACCELPROFILES="<item>$(gettext 'Adaptive')</item><item>$(gettext 'Flat')</item>" ;;
	esac

	case "$LIBINPUT_DEFAULT_CLICK_METHOD" in
		0) CLICKMETHODS="<item>$(gettext 'None')</item><item>$(gettext 'Button areas')</item><item>$(gettext 'Fingers')</item>" ;;
		1) CLICKMETHODS="<item>$(gettext 'Button areas')</item><item>$(gettext 'None')</item><item>$(gettext 'Fingers')</item>" ;;
		2) CLICKMETHODS="<item>$(gettext 'Fingers')</item><item>$(gettext 'None')</item><item>$(gettext 'Button areas')</item>" ;;
		*) CLICKMETHODS="<item>$(gettext 'None')</item><item>$(gettext 'Button areas')</item><item>$(gettext 'Fingers')</item>" ;;
	esac

	case "$LIBINPUT_DEFAULT_SCROLL_METHOD" in
		0) SCROLLMETHODS="<item>$(gettext 'No scrolling')</item><item>$(gettext '2 fingers')</item><item>$(gettext 'Edge')</item><item>$(gettext 'On button down')</item>" ;;
		1) SCROLLMETHODS="<item>$(gettext '2 fingers')</item><item>$(gettext 'No scrolling')</item><item>$(gettext 'Edge')</item><item>$(gettext 'On button down')</item>" ;;
		2) SCROLLMETHODS="<item>$(gettext 'Edge')</item><item>$(gettext 'No scrolling')</item><item>$(gettext '2 fingers')</item><item>$(gettext 'On button down')</item>" ;;
		4) SCROLLMETHODS="<item>$(gettext 'On button down')</item><item>$(gettext 'No scrolling')</item><item>$(gettext '2 fingers')</item><item>$(gettext 'Edge')</item>" ;;
		*) SCROLLMETHODS="<item>$(gettext 'No scrolling')</item><item>$(gettext '2 fingers')</item><item>$(gettext 'Edge')</item><item>$(gettext 'On button down')</item>" ;;
	esac

	TAPTOCLICK=false
	[ "$LIBINPUT_DEFAULT_TAP" = "1" ] && TAPTOCLICK=true
	
	TAPANDDRAG=false
	[ "$LIBINPUT_DEFAULT_DRAG" = "1" ] && TAPANDDRAG=true

	DISABLEWHILETYPING=false
	[ "$LIBINPUT_DEFAULT_DISABLE_WHILE_TYPING" = "1" ] && DISABLEWHILETYPING=true

	MIDDLEEMULATION=false
	[ "$LIBINPUT_DEFAULT_MIDDLE_EMULATION" = "1" ] && MIDDLEEMULATION=true

	NATURALSCROLLING=false
	[ "$LIBINPUT_DEFAULT_NATURAL_SCROLL" = "1" ] && NATURALSCROLLING=true

	LEFTHANDED=false
	[ "$LIBINPUT_DEFAULT_LEFT_HANDED" = "1" ] && LEFTHANDED=true
	
	export MAIN_DIALOG='<window title="'$(gettext 'Pointer properties')'" icon-name="gtk-preferences" resizable="false">
 <vbox>
  <vbox>
   <frame>
    <hbox>
     <text xalign="0" use-markup="true" space-expand="false" space-fill="false"><label>"'"<b><span size='"'medium'"'>$(gettext 'Touchpad')</span></b>"'"</label></text>
     <text space-expand="true" space-fill="true"><label>" "</label></text>
    </hbox>
    '$TOUCHPAD_TOGGLE'
    <checkbox>
     <label>'$(gettext 'Tap to click')'</label>
     <variable>TAPTOCLICK</variable>
     <default>'$TAPTOCLICK'</default>
    </checkbox>
    <checkbox>
     <label>'$(gettext 'Tap and drag')'</label>
     <variable>TAPANDDRAG</variable>
     <default>'$TAPANDDRAG'</default>
    </checkbox>
    <checkbox>
     <label>'$(gettext 'Disable while typing')'</label>
     <variable>DISABLEWHILETYPING</variable>
     <default>'$DISABLEWHILETYPING'</default>
    </checkbox>
    <hbox>
     <text>
      <label>'$(gettext 'Clickpad method:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Click method for clickpads (no physical buttons)')' ">
      <variable>CLICKMETHOD</variable>
       '$CLICKMETHODS'
     </comboboxtext>
    </hbox>
    <hbox>
     <text>
      <label>'$(gettext 'Scroll method:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Default is two-finger scrolling for multi-touch')' 
 '$(gettext 'touchpads, or edge scrolling for single-touch.')' ">
      <variable>SCROLLMETHOD</variable>
      '$SCROLLMETHODS'
     </comboboxtext>
    </hbox>
    <hseparator space-expand="false" space-fill="false"></hseparator>
    <hbox>
     <text xalign="0" use-markup="true" space-expand="false" space-fill="false"><label>"'"<b><span size='"'medium'"'>$(gettext 'Mouse &amp; Touchpad')</span></b>"'"</label></text>
     <text space-expand="true" space-fill="true"><label>" "</label></text>
    </hbox>
    <hbox>
     <text>
      <label>'$(gettext 'Acceleration:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Maximum acceleration: 1.0')' ">
      <variable>MOUSEACCEL</variable>
       '$(combo_items ${LIBINPUT_DEFAULT_ACCELERATION} 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 -0.1 -0.2 -0.3 -0.4 -0.5 -0.6 -0.7 -0.8 -0.9 -1.0)'
     </comboboxtext>
    </hbox>
    <hbox>
     <text>
      <label>'$(gettext 'Acceleration profile:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Flat (constant) acceleration or Adaptive (varies with current mouse movement)')' ">
      <variable>MOUSEACCELPROFILE</variable>
       '$MOUSEACCELPROFILES'
     </comboboxtext>
    </hbox>
    <checkbox tooltip-text=" '$(gettext 'Scroll indicator moves opposite direction of page contents')' ">
     <label>'$(gettext 'Natural scrolling')'</label>
     <variable>NATURALSCROLLING</variable>
     <default>'$NATURALSCROLLING'</default>
    </checkbox>
    <checkbox tooltip-text=" '$(gettext 'Convert simultaneous left and right button clicks into a middle button')' ">
     <label>'$(gettext 'Middle button emulation')'</label>
     <variable>MIDDLEEMULATION</variable>
     <default>'$MIDDLEEMULATION'</default>
    </checkbox>
    <checkbox tooltip-text=" '$(gettext 'Switch functions of left and right mouse buttons')' ">
     <label>'$(gettext 'Left-handed mode')'</label>
     <variable>LEFTHANDED</variable>
     <default>'$LEFTHANDED'</default>
    </checkbox>
   </frame>
  </vbox>
  <hbox space-expand="true" space-fill="true">
   <button space-expand="true" space-fill="true" tooltip-text=" '$(gettext 'Online libinput documentation')' ">
    <label>'$(gettext 'Help')'</label>
    <input file>/usr/share/pixmaps/puppy/help.svg</input><height>18</height><width>18</width>
    <action>defaulthtmlviewer https:\/\/wayland.freedesktop.org\/libinput/doc\/latest\/features.html &</action>
   </button>
   <button cancel>
    <action type="exit">no save</action>
   </button>
   <button ok>
    <action type="exit">save settings</action>
   </button>
  </hbox>
 </vbox>
</window>'

	RETPARAMS="`gtkdialog --center --program=MAIN_DIALOG`"
	eval "$RETPARAMS"
	if [ "$EXIT" = "save settings" ] ; then
		libinput_apply
	fi
	exit
fi

if [ "$1" = "libinputmouseonly" ] ; then
	. ~/.libinputrc

	function libinput_apply_mouseonly() {
		[ -n "$MOUSEACCEL" ] && sed -i "s%^LIBINPUT_DEFAULT_ACCELERATION=.*%LIBINPUT_DEFAULT_ACCELERATION=$MOUSEACCEL%" ~/.libinputrc

		MOUSEACCELPROFILENUM=-1
		case "$MOUSEACCELPROFILE" in
			"$(gettext 'Flat')") MOUSEACCELPROFILENUM=1 ;;
			"$(gettext 'Adaptive')") MOUSEACCELPROFILENUM=2 ;;
		esac
		[ $MOUSEACCELPROFILENUM -ge 0 ] && sed -i "s%^LIBINPUT_DEFAULT_ACCELERATION_PROFILE=.*%LIBINPUT_DEFAULT_ACCELERATION_PROFILE=$MOUSEACCELPROFILENUM%" ~/.libinputrc

		case "$MIDDLEEMULATION" in
			true) sed -i "s%^LIBINPUT_DEFAULT_MIDDLE_EMULATION=.*%LIBINPUT_DEFAULT_MIDDLE_EMULATION=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_MIDDLE_EMULATION=.*%LIBINPUT_DEFAULT_MIDDLE_EMULATION=0%" ~/.libinputrc ;;
		esac;

		case "$NATURALSCROLLING" in
			true) sed -i "s%^LIBINPUT_DEFAULT_NATURAL_SCROLL=.*%LIBINPUT_DEFAULT_NATURAL_SCROLL=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_NATURAL_SCROLL=.*%LIBINPUT_DEFAULT_NATURAL_SCROLL=0%" ~/.libinputrc ;;
		esac;

		case "$LEFTHANDED" in
			true) sed -i "s%^LIBINPUT_DEFAULT_LEFT_HANDED=.*%LIBINPUT_DEFAULT_LEFT_HANDED=1%" ~/.libinputrc ;;
			false) sed -i "s%^LIBINPUT_DEFAULT_LEFT_HANDED=.*%LIBINPUT_DEFAULT_LEFT_HANDED=0%" ~/.libinputrc ;;
		esac;

		xinput-apply
	}
	export -f libinput_apply_mouseonly
	combo_items() {
		for i in $@ ; do echo "<item>${i}</item>" ; done
	}

	case "$LIBINPUT_DEFAULT_ACCELERATION_PROFILE" in
		1) MOUSEACCELPROFILES="<item>$(gettext 'Flat')</item><item>$(gettext 'Adaptive')</item>" ;;
		*) MOUSEACCELPROFILES="<item>$(gettext 'Adaptive')</item><item>$(gettext 'Flat')</item>" ;;
	esac

	MIDDLEEMULATION=false
	[ "$LIBINPUT_DEFAULT_MIDDLE_EMULATION" = "1" ] && MIDDLEEMULATION=true

	NATURALSCROLLING=false
	[ "$LIBINPUT_DEFAULT_NATURAL_SCROLL" = "1" ] && NATURALSCROLLING=true

	LEFTHANDED=false
	[ "$LIBINPUT_DEFAULT_LEFT_HANDED" = "1" ] && LEFTHANDED=true

	export MAIN_DIALOG='<window title="'$(gettext 'Mouse Properties')'" icon-name="gtk-preferences" resizable="false">
 <vbox>
  <vbox>
   <frame>
    <hbox>
     <text>
      <label>'$(gettext 'Acceleration:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Maximum acceleration: 1.0')' ">
      <variable>MOUSEACCEL</variable>
       '$(combo_items ${LIBINPUT_DEFAULT_ACCELERATION} 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 -0.1 -0.2 -0.3 -0.4 -0.5 -0.6 -0.7 -0.8 -0.9 -1.0)'
     </comboboxtext>
    </hbox>
    <hbox>
     <text>
      <label>'$(gettext 'Acceleration profile:')'</label>
     </text>
     <comboboxtext tooltip-text=" '$(gettext 'Flat (constant) acceleration or Adaptive (varies with current mouse movement)')' ">
      <variable>MOUSEACCELPROFILE</variable>
       '$MOUSEACCELPROFILES'
     </comboboxtext>
    </hbox>
    <checkbox tooltip-text=" '$(gettext 'Scroll indicator moves opposite direction of page contents')' ">
     <label>'$(gettext 'Natural scrolling')'</label>
     <variable>NATURALSCROLLING</variable>
     <default>'$NATURALSCROLLING'</default>
    </checkbox>
    <checkbox tooltip-text=" '$(gettext 'Convert simultaneous left and right button clicks into a middle button')' ">
     <label>'$(gettext 'Middle button emulation')'</label>
     <variable>MIDDLEEMULATION</variable>
     <default>'$MIDDLEEMULATION'</default>
    </checkbox>
    <checkbox tooltip-text=" '$(gettext 'Switch functions of left and right mouse buttons')' ">
     <label>'$(gettext 'Left-handed mode')'</label>
     <variable>LEFTHANDED</variable>
     <default>'$LEFTHANDED'</default>
    </checkbox>
   </frame>
  </vbox>
  <hbox>
   <button cancel>
    <action type="exit">no save</action>
   </button>
   <button ok>
    <action type="exit">save settings</action>
   </button>
  </hbox>
 </vbox>
</window>'

	RETPARAMS="`gtkdialog --center --program=MAIN_DIALOG`"
	eval "$RETPARAMS"
	if [ "$EXIT" = "save settings" ] ; then
		libinput_apply_mouseonly
	fi
	exit
fi

#==============================================================
#                   X KEYBOARD PROPERTIES
#==============================================================

if [ "$1" = "keyboard" ] ; then
	XSETQ="`LANG=C xset q`"
	KEYBOARDVOL="`echo "$XSETQ" | grep 'key click percent: ' | tr -s ' ' | cut -f 8 -d ' '`"
	KEYBOARDAUTO="`echo "$XSETQ" | grep ' auto repeat: ' | tr -s ' ' | cut -f 4 -d ' '`"
	if [ "$KEYBOARDAUTO" = "on" ];then
		KEYBOARDAUTO="yes"
		KBVISIBLE="enabled"
	fi
	if [ "$KEYBOARDAUTO" = "off" ];then
		KEYBOARDAUTO="no"
		KBVISIBLE="disabled"
	fi
	KEYBOARDDELAY="`echo "$XSETQ" | grep ' auto repeat delay: ' | tr -s ' ' | cut -f 5 -d ' '`"
	KEYBOARDRATE="`echo "$XSETQ" | grep ' auto repeat delay: ' | grep 'repeat rate:' | tr -s ' ' | cut -f 8 -d ' '`"
	#precaution
	[ "$KEYBOARDVOL" = "" ] && KEYBOARDVOL='0'
	[ "$KEYBOARDAUTO" = "" ] && KEYBOARDAUTO='yes'
	[ "$KEYBOARDDELAY" = "" ] && KEYBOARDDELAY='500'
	[ "$KEYBOARDRATE" = "" ] && KEYBOARDRATE='6'
	#-
	function pupx_keyboard() {
		if [ -z "$KEYBOARDAUTO" ] ; then
			return
		fi
		KEYBOARDDELAY=`echo -n $KEYBOARDDELAY | cut -f 1 -d '.'`
		KEYBOARDRATE=`echo -n $KEYBOARDRATE | cut -f 1 -d '.'`
		[ $KEYBOARDVOL -eq 0 ] && KEYBOARDVOL=off
		if [ "$KEYBOARDAUTO" = "false" ];then
			KEYBOARDPARAMS="off"
		else
			KEYBOARDPARAMS="rate $KEYBOARDDELAY $KEYBOARDRATE"
		fi
		LANG=C xset c $KEYBOARDVOL r $KEYBOARDPARAMS
		XSET_KEYBOARD="LANG=C xset c $KEYBOARDVOL r $KEYBOARDPARAMS" #130209
		[ ! "$1" ] && Xdialog --title "Keyboard settings" --msgbox "Keyclick volume set to ${KEYBOARDVOL}\nAuto-repeat set to ${KEYBOARDPARAMS}\n(for this session only)" 0 0
	}
	export -f pupx_keyboard
	combo_items() {
		for i in $@ ; do echo "<item>${i}</item>" ; done
	}

	export MAIN_DIALOG='<window title="'$(gettext 'Keyboard settings')'" icon-name="gtk-preferences" resizable="false">
<vbox>
    <vbox>
     <hbox>
      <text><label>'$(gettext 'Volume:')'</label></text>
      <comboboxtext>
       <variable>KEYBOARDVOL</variable>
       '$(combo_items ${KEYBOARDVOL} 100 90 80 70 60 50 40 30 20 10 0)'
      </comboboxtext>
     </hbox>
     <text><label>'$(gettext 'Keyclick volume in percentage (0-100)')'</label></text>
     <frame '$(gettext 'Auto-repeat')'>
      <checkbox>
       <label>'$(gettext 'Enable auto-repeat')'</label>
       <variable>KEYBOARDAUTO</variable>
       <default>'${KEYBOARDAUTO}'</default>
       <action>if true enable: KEYBOARDDELAY</action>
       <action>if true enable: KEYBOARDRATE</action>
       <action>if false disable: KEYBOARDDELAY</action>
       <action>if false disable: KEYBOARDRATE</action>
      </checkbox>
      <hbox>
       <text><label>"       "</label></text>
       <text><label>'$(gettext 'Delay:')'</label></text>
       
       <spinbutton range-min="1" range-max="9999" range-step="1" range-value="'${KEYBOARDDELAY}'">
         <variable>KEYBOARDDELAY</variable>
         <visible>'${KBVISIBLE}'</visible>   
       </spinbutton>
       
       <text><label>'$(gettext '(milliseconds)       ')'</label></text>
      </hbox>
      <text><label>'$(gettext 'This is the delay before keys start repeating')'</label></text>
      <hbox>
       <text><label>"        "</label></text>
       <text><label>'$(gettext 'Rate:')'</label></text>
       
       <spinbutton range-min="1" range-max="99" range-step="1" range-value="'${KEYBOARDRATE}'">
         <variable>KEYBOARDRATE</variable>
         <visible>'${KBVISIBLE}'</visible>   
       </spinbutton>
  
       <text><label>'$(gettext '(repeats per second)       ')'</label></text>
      </hbox>
      <text><label>'$(gettext 'This is the rate at which keys repeat')'</label></text>
     </frame>
    </vbox>
  <hbox>
   <button cancel>
    <action type="exit">no save</action>
   </button>
   <button>
    <input file stock="gtk-apply"></input>
    <label>'$(gettext 'Apply')'</label>
    <action>pupx_keyboard &</action>
   </button>
   <button ok>
    <action type="exit">save settings</action>
   </button>
  </hbox>
</vbox>
</window>'
	RETPARAMS="`gtkdialog --center --program=MAIN_DIALOG`"
	eval "$RETPARAMS"
	[ "$EXIT" != "save settings" ] && exit
	pupx_keyboard   z
	touch $HOME/.xset.sh
	sed -i '/ c /d' $HOME/.xset.sh
	echo "$XSET_KEYBOARD" >> $HOME/.xset.sh
	chmod +x $HOME/.xset.sh
fi


#==============================================================
#                      MAIN  INPUT WIZARD
#==============================================================

PUPX_MOUSE="$0 mousex"
PUPX_KEYBOARD="$0 keyboard"
MOUSE_CONFIG="$0 mouse"
LIBINPUT_MOUSE_CONFIG="$0 libinputmouse"
LIBINPUT_MOUSEONLY_CONFIG="$0 libinputmouseonly"
SYNCLIENT_BUTTON=""
TOUCHPAD_MANAGER_SWITCHER=""

if [ -z "$WAYLAND_DISPLAY" ] && [ "$(which psynclient)" != "" -o "$(which flsynclient)" != "" ]; then
 SYNCLIENT_BUTTON='<hbox>
        <text><label>'$(gettext 'Touchpad')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon touchpad.svg big`"'
          <action>touchpad_utils &</action>
        </button>
      </hbox>'
fi

if [ -n "$WAYLAND_DISPLAY" ]; then
 MOUSE_SETTINGS='<hbox>
        <text><label>'$(gettext 'Pointer Properties')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon touchpad.svg big`"'
          <action>'${LIBINPUT_MOUSE_CONFIG}' &</action>
        </button>
      </hbox>'
elif grep -qm 1 "Using input driver 'libinput'" "/var/log/Xorg.${DISPLAY#:}.log"; then #libinput available
 if [ -f /usr/$LIB/xorg/modules/input/synaptics_drv.so ] && [ ! -f $HOME/.config/synaptics/synaptics_drv.so_bak ]; then #if synaptics driver installed, create backup
  mkdir -p $HOME/.config/synaptics
  cp -af /usr/$LIB/xorg/modules/input/synaptics_drv.so $HOME/.config/synaptics/synaptics_drv.so_bak
 fi

 SYNAPTICS="" SYNAPTICS_ACTIVE=""
 if [ -f $HOME/.config/synaptics/synaptics_drv.so_bak ]; then #synaptics driver installed
  SYNAPTICS="true"
  if [ -f /usr/$LIB/xorg/modules/input/synaptics_drv.so ]; then #synaptics driver active
   SYNAPTICS_ACTIVE="true"
  fi
 fi

 if [ "$SYNAPTICS" = "true" ]; then #synaptics driver installed
  if [ "$SYNAPTICS_ACTIVE" = "true" ]; then #synaptics driver active
   TOUCHPAD_MANAGER_SWITCHER='<button height-request="35" width-request="35" tooltip-text=" '$(gettext 'Select touchpad manager (synaptics or libinput)')' ">
     <input file>/usr/share/pixmaps/puppy/preferences.svg</input><height>22</height><width>22</width>
     <action>input-wizard-config &</action>
     <action>exit:quit_now</action>
    </button>'
   MOUSE_SETTINGS='<hbox>
        <text><label>'$(gettext 'Mouse Properties')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon mouse.svg big`"'
          <action>'${LIBINPUT_MOUSEONLY_CONFIG}' &</action>
        </button>
      </hbox>
      '$SYNCLIENT_BUTTON''
  else #synaptics driver inactive
   TOUCHPAD_MANAGER_SWITCHER='<button height-request="35" width-request="35" tooltip-text=" '$(gettext 'Select touchpad manager (synaptics or libinput)')' ">
     <input file>/usr/share/pixmaps/puppy/preferences.svg</input><height>22</height><width>22</width>
     <action>input-wizard-config &</action>
     <action>exit:quit_now</action>
    </button>'
   MOUSE_SETTINGS='<hbox>
        <text><label>'$(gettext 'Pointer Properties')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon mouse.svg big`"'
          <action>'${LIBINPUT_MOUSE_CONFIG}' &</action>
        </button>
      </hbox>'
  fi
 else #synaptics driver not installed
  MOUSE_SETTINGS='<hbox>
        <text><label>'$(gettext 'Pointer Properties')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon mouse.svg big`"'
          <action>'${LIBINPUT_MOUSE_CONFIG}' &</action>
        </button>
      </hbox>'
 fi
else #libinput not available, xset available
 MOUSE_SETTINGS='<hbox>
        <text><label>'$(gettext 'Mouse Properties')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon mouse.svg big`"'
          <action>'${MOUSE_CONFIG}' &</action>
        </button>
      </hbox>
      <hbox>
        <text><label>'$(gettext 'Mouse Sensitivity')'</label></text>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon mouse_sensitivity.svg big`"'
          <action>'${PUPX_MOUSE}' &</action>
        </button>
      </hbox>
      '$SYNCLIENT_BUTTON''
fi

export MouseKeyboardWizard='
<window title="'$(gettext 'Input Wizard')'" icon-name="gtk-preferences" resizable="false">
<vbox space-expand="true" space-fill="true">
  '"`/usr/lib/gtkdialog/xml_info fixed mouse_keyboard.svg 60 " " "$(gettext "Configure your input devices")"`"'
  <hbox space-expand="true" space-fill="true">
    <frame '$(gettext 'Keyboard')'>
      <hbox>
        <button space-expand="false" space-fill="false">
          '"`/usr/lib/gtkdialog/xml_button-icon country_keyboard.svg big`"'
          <action>'chooselayout'</action>
        </button>
        <text space-expand="false" space-fill="false"><label>'$(gettext 'Layout for your country')'</label></text>
        <text space-expand="true" space-fill="true"><label>""</label></text>
      </hbox>
      <hbox>
        <button space-expand="false" space-fill="false">
          '"`/usr/lib/gtkdialog/xml_button-icon keyboard_shortcut.svg big`"'
          <action>'xkbconfigmanager'</action>
        </button>
        <text space-expand="false" space-fill="false"><label>'$(gettext 'Advanced configuration')'</label></text>
        <text space-expand="true" space-fill="true"><label>""</label></text>
      </hbox>
      <hbox>
        <button space-expand="false" space-fill="false">
          '"`/usr/lib/gtkdialog/xml_button-icon keyboard.svg big`"'
          <action>'${PUPX_KEYBOARD}'</action>
        </button>
        <text space-expand="false" space-fill="false"><label>'$(gettext 'X Keyboard properties')'</label></text>
        <text space-expand="true" space-fill="true"><label>""</label></text>
      </hbox>
    </frame>
    <frame '$(gettext 'Pointer')'>
       '$MOUSE_SETTINGS'
     </frame>
  </hbox>
  <hbox space-expand="false" space-fill="false">
    '$TOUCHPAD_MANAGER_SWITCHER'
    <button>
      '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
      <label>'$(gettext 'Quit')'</label>
    </button>
  </hbox>
 </vbox>
</window>'

. /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
gtkdialog --center -p MouseKeyboardWizard --styles=/tmp/gtkrc_xml_info.css

### END ###
