#!/bin/bash
# jgdesktops
#
COLORIZER_CONF="$HOME/.config/colorizer/colorizer.conf"
AREA_CFG="$HOME/.config/areaclick.conf"
GTK3RC="$HOME/.config/gtk-3.0/settings.ini"
source ${COLORIZER_CONF}
. /usr/share/mb-jgtools/jgtools.inc
me="jgdesktops -s"

case $LANG in
    pl*)
        TITLE="Pulpity i Okna"
        REMOVE="Usuń to menu z panelu"
        ACTIVE="bieżący"
        GOTO="Idź do..."
        WINKILL="Zabijacz Okien"
        CLOSEALL_GR="<b>Zamknij wszystkie okna</b> na..."
        CLOSEALL="Zamknij wszystkie okna na..."
        DESKTOP="Pulpicie"
        ALL_DESK="Wszystkich pulpitach"
        MANAGE="Pulpity"
        ADD="<b>Dodaj nowy</b>"
        REMOVE_LAST="<b>Usuń ostatni</b>"
        CONKY_TOGGLE="Włącz/Wyłącz Conky"
        PICOM_TOGGLE="Włącz/Wyłącz Picom"
        DESKMNGR="Menadżer sesji pulpitowych"
        WALLCHANGER="Tapeta oraz <b>stylizacja</b> pulpitu"
        DESKGRID="Desktop Grid"
        SCREEN_RES="Ustawienia ekranu"
        ENABLE="Włącz"
        DISABLE="Wyłącz"
        DESK_SERVICES="Usługi pulpitu"
        TINT2="<b>Tint2 panel</b>"
        CONKY="Sesja <b>Conky</b>"
        PICOM="<b>Picom</b> - kompozytor"
        CORTILE="<b>Cortile</b> - tiling manager"
        MCORNERS="<b>Krawędzie ekranu</b>"
        RUNNING="(uruchomiona)"
        STOPPED="(zatrzymana)"
        MONITORBLANK="<b>Wygaszanie</b> monitora"
        _CURSOR="Kursor"
        _SIZE="rozmiar"
        ON="(włączone)"
        OFF="(wyłączone)"
        WMTWEAKS="Ulepszenia Menadżera Okien"
        SHOW_DESK="Pokaż pulpit - lewy klik"
        SWITCH_DESK="Zmień pulpit - kółko myszy"
        FOCUS="Fokus podąża za myszą"
        WALLPAPER="Tapeta"
        TOOLS="Narzędzia"
        OBTHEME="Motyw Openbox"
        MENUPANELS="Menu i Panele"
        YES="Tak"
        NO="Nie"
        AREACLICK="AreaClick"
        ABOUT_AREACLICK="O AreaClick"
        AREA_WIDTH="rozmiar obszaru"
        EDIT_AREACONF="Edytuj <i>areaclick.conf</i>"
        RESET_AREACONF="Resetuj plik konfiguracyjny"
        RESET_SURE="Na pewno?"
        RESET_YES="Tak, resetuj"
        WM_MARGIN="Marginesy Openbox"
        OBCONF_MARG="ObConf -> Marginesy"
        SET_ALL_MARG="ustaw wszystkie na:"
        ;;
    es*)
        TITLE="Windows &amp; Desktops"
        REMOVE="Eliminar este menú del panel"
        ACTIVE="active"
        GOTO="Go to..."
        WINKILL="Windows Killer"
        CLOSEALL_GR="Gracefully <b>close all windows</b> on..."
        CLOSEALL="Close all windows on..."
        DESKTOP="Desktop"
        ALL_DESK="All Desktops"
        MANAGE="Manage Desktops"
        ADD="<b>Add new</b> desktop"
        REMOVE_LAST="<b>Remove last</b> desktop"
        CONKY_TOGGLE="Conky Toggle"
        PICOM_TOGGLE="Picom Toggle"
        DESKMNGR="Desktop session Manager"
        WALLCHANGER="Wallpaper &amp; Desktop <b>styling</b>"
        DESKGRID="Desktop Grid"
        SCREEN_RES="Screen Settings"
        ENABLE="Enable"
        DISABLE="Disable"
        DESK_SERVICES="Desktop services"
        TINT2="<b>Tint2 panel</b> session"
        CONKY="<b>Conky</b> session"
        PICOM="<b>Picom</b> - compositor"
        CORTILE="<b>Cortile</b> - tiling manager"
        MCORNERS="<b>Screen Edges</b> - hot corners"
        RUNNING="(running)"
        STOPPED="(stopped)"
        MONITORBLANK="Monitor <b>blanking</b>"
        _CURSOR="Cursor"
        _SIZE="size"
        ON="(on)"
        OFF="(off)"
        WMTWEAKS="Window Manager tweaks"
        SHOW_DESK="Show Desktop on left click"
        SWITCH_DESK="Switch Desktop on mousewheel up/down"
        FOCUS="Focus follow Mouse"
        WALLPAPER="Wallpaper"
        TOOLS="Tools"
        OBTHEME="Openbox Theme"
        MENUPANELS="Menus/Panels"
        YES="Yes"
        NO="No"
        AREACLICK="AreaClick"
        ABOUT_AREACLICK="About AreaClick"
        AREA_WIDTH="click area size"
        EDIT_AREACONF="Edit <i>areaclick.conf</i>"
        RESET_AREACONF="Reset config to defaults"
        RESET_SURE="Are you sure?"
        RESET_YES="Yes, reset to defaults"
        WM_MARGIN="Openbox Margin"
        OBCONF_MARG="ObConf -> Margins"
        SET_ALL_MARG="set all margins to:"
        ;;
    *)  
        TITLE="Windows &amp; Desktops"
        REMOVE="Remove this menu from panel"
        ACTIVE="active"
        GOTO="Go to..."
        WINKILL="Windows Killer"
        CLOSEALL_GR="Gracefully <b>close all windows</b> on..."
        CLOSEALL="Close all windows on..."
        DESKTOP="Desktop"
        ALL_DESK="All Desktops"
        MANAGE="Manage Desktops"
        ADD="<b>Add new</b> desktop"
        REMOVE_LAST="<b>Remove last</b> desktop"
        DESKMNGR="Desktop session Manager"
        CONKY_TOGGLE="Conky Toggle"
        PICOM_TOGGLE="Picom Toggle"
        WALLCHANGER="Wallpaper &amp; Desktop <b>styling</b>"
        DESKGRID="Desktop Grid"
        SCREEN_RES="Screen settings"
        ENABLE="Enable"
        DISABLE="Disable"
        DESK_SERVICES="Desktop services"
        TINT2="<b>Tint2 panel</b> session"
        CONKY="<b>Conky</b> session"
        PICOM="<b>Picom</b> - compositor"
        CORTILE="<b>Cortile</b> - tiling manager"
        MCORNERS="<b>Screen Edges</b> - hot corners"
        RUNNING="(running)"
        STOPPED="(stopped)"
        MONITORBLANK="Monitor <b>blanking</b>"
        _CURSOR="Cursor"
        _SIZE="size"
        ON="(on)"
        OFF="(off)"
        WMTWEAKS="Window Manager tweaks"
        SHOW_DESK="Show Desktop on left click"
        SWITCH_DESK="Switch Desktop on mousewheel up/down"
        FOCUS="Focus follow Mouse"
        WALLPAPER="Wallpaper"
        TOOLS="Tools"
        COLORIZER_SETTINGS="Colorizer Settings"
        OBTHEME="Openbox Theme"
        MENUPANELS="Menus/Panels"
        YES="Yes"
        NO="No"
		AREACLICK="AreaClick"
        ABOUT_AREACLICK="About AreaClick"
        AREA_WIDTH="click area size"
        EDIT_AREACONF="Edit <i>areaclick.conf</i>"
        RESET_AREACONF="Reset config to defaults"
        RESET_SURE="Are you sure?"
        RESET_YES="Yes, reset to defaults"
        WM_MARGIN="Openbox Margin"
        OBCONF_MARG="ObConf -> Margins"
        SET_ALL_MARG="set all margins to:"
        ;;
esac

#CSVFILE="$HOME/.config/mabox/jgdesktops-bottom.csv"
# If config file not exist create one with defaults
#if [ ! -f $CSVFILE ]; then
#cat <<EOF > ${CSVFILE}
#^sep($TOOLS)
#<big>󰸉</big>   $WALLCHANGER,^pipe(jgwallpaperchanger)
#<big>󱇙</big>   $DESKGRID,^pipe(jgdeskgrid)
#<big></big>   $DESKMNGR,^pipe(jgdeskmngr)
#<big>󰹑</big>   $SCREEN_RES - ARandR,arandr
#<big>󰹑</big>   $SCREEN_RES - LXRandr,lxrandr
#EOF
#fi

out+=("^sep(${TITLE})")
currdesk=$(wmctrl -d | grep "*" | awk '{print $1}')
#out+=("^sep(Okna i pulpity)")

i=0

while IFS= read -r linia || [ -n "$linia" ];
do
name=""
read -r ID name< <(echo $linia)
#declare -g "arr$ID"=("$name, wmctrl -s $ID")
dname=$(wmctrl -d | grep ^${ID} | cut -d' ' -f13-)
if [[ "$ID" = "$currdesk" ]]; then
out+=("^sep(<i><small>${dname/&/&amp;} ($ACTIVE)</small></i>)")

else
out+=("^sep(<i><small>${dname/&/&amp;}</small></i>)" "    <i>$GOTO</i>,wmctrl -s $ID")
fi
    while IFS= read -r line
    do
        read -r id DESK host title< <(echo $line)
        if [[ "$DESK" = "$ID" ]]; then
             trimmed=${title:0:60}
            out+=("\"\"\"[ ${trimmed/&/&amp;} ]\"\"\",wmctrl -i -a $id")
        fi
    done < <(wmctrl -l| grep -v " -1")
done < <(wmctrl -d|awk '{print $1" "$10" "$11}')

# Gracefully close windows on any desktop or all windows

if [ $(wmctrl -l | awk $2 '!/-1/ {print $2}' | uniq |wc -l) -gt 0 ];then 
    out+=("^sep($WINKILL)")
    out+=("<big>󰚌</big>  $CLOSEALL_GR,^checkout(killwin)")
    out2+=("^tag(killwin)" "^sep($CLOSEALL)")
    for i in $(wmctrl -l | awk $2 '!/-1/ {print $2}' |sort| uniq)
    do
        dname=$(wmctrl -d | grep ^${i} | cut -d' ' -f13-)
        out2+=("    $DESKTOP ${dname/&/&amp;},killwindows $i")
    done
    out2+=("^sep()" "$ALL_DESK,killwindows all")
fi
out+=("^sep($MANAGE)")
desktops=$(wmctrl -d |wc -l) 
#out+=("    $ADD,wmctrl -n $((desktops+1));$me")
out+=("    $ADD,obxml desktops $((desktops+1));$me")
[[ "$desktops" -gt "1" ]] && out+=("    $REMOVE_LAST,obxml desktops $((desktops-1));$me")



out+=("^sep($DESK_SERVICES)")
if pidof tint2 &>/dev/null;then
out+=("<big>󰄲</big>  $TINT2 <i>$RUNNING</i>,tint2_toggle;$me")

else
out+=("<big>󰄱</big>  $TINT2 <i>$STOPPED</i>,mb-tint2-session &>/dev/null;$me")
fi
if pidof conky &>/dev/null; then
out+=("<big>󰄲</big>  $CONKY <i>$RUNNING</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - c</small> </span>,conky_toggle;$me")
else
out+=("<big>󰄱</big>  $CONKY <i>$STOPPED</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - c</small> </span>,conky_toggle;$me")
fi
if pidof picom &>/dev/null; then
out+=("<big>󰄲</big>  $PICOM <i>$RUNNING</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - p</small> </span>,compton_toggle;$me")
else
out+=("<big>󰄱</big>  $PICOM <i>$STOPPED</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - p</small> </span>,compton_toggle;$me")
fi
#if  command -v mcorners &> /dev/null;then
#    if [[ -f /tmp/mcorners.lck ]]; then
#    out+=("<big>󰄲</big>  $MCORNERS <i>$RUNNING</i>,mcorners --stop;$me")
#    else
#    out+=("<big>󰄱</big>  $MCORNERS <i>$STOPPED</i>,mcorners -tl 'jgdesktops -s' -l 'mb-jgtools places' -tr 'mb-music -s' -bl 'colorizer -s' -br 'skippy-xd-fix' -r 'mb-jgtools right' -iof;$me")
#    fi
#fi
if  command -v cortile &> /dev/null;then
    if pidof cortile &>/dev/null; then
    out+=("<big>󰄲</big>  $CORTILE <i>$RUNNING</i>,cortilectl stop")
    else
    out+=("<big>󰄱</big>  $CORTILE <i>$STOPPED</i>,cortilectl start")
    fi
fi
out+=("^sep()")






# CURSORS
read CURTHEME <<< "$(rg gtk-cursor-theme-name ${GTK3RC} | cut -d'=' -f2)"
read CURSIZE <<< "$(rg gtk-cursor-theme-size ${GTK3RC} | cut -d'=' -f2)"

out+=("<big> 󰇀</big>   $_CURSOR: <b>$CURTHEME</b> $_SIZE: <b>$CURSIZE</b>,^checkout(mcursor)")
out2+=("^tag(mcursor)")
out2+=("^sep($_CURSOR)")
while read -r line; do

lin=${line::-8}
li=${lin##*/}
[[ "${CURTHEME}" = "${li}" ]] && out2+=("<big>${ron}</big>   <b>${li}</b>") || out2+=("<big>${roff}</big>   ${li},mb-cursor theme ${li}")
#out2+=("${li}")

done < <(find /usr/share/icons ~/.local/share/icons ~/.icons -type d -name "cursors")



out2+=("^sep($_SIZE)")
for c in 16 18 24 32 48 64;do
[[ "${CURSIZE}" == "${c}" ]] && out2+=("<big>${ron}</big>   <b>${c}</b>") || out2+=("<big>${roff}</big>   ${c},mb-cursor size ${c}")
done

out+=("^sep()")
# MONITOR BLANKING
if (xset q|grep --quiet "DPMS is Enabled");then
out+=("<big>󰷛</big>   $MONITORBLANK <i>$ON</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - A - b</small> </span>,noblank;$me")
else
out+=("<big>󰍹</big>   $MONITORBLANK <i>$OFF</i> <span bgcolor='#333333' color='#d3d3d3'> <small> - A - b</small> </span>,noblank;$me")
fi


# DESKTOP MOUSE ACTIONS
mousewheel=$(xml sel -N a=http://openbox.org/3.4/rc -t -v '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Click"][@button="Up"]/a:action/a:to' $HOME/.config/openbox/rc.xml)
focus=$(xml sel -N a=http://openbox.org/3.4/rc -t -v '/a:openbox_config/a:focus/a:followMouse' $HOME/.config/openbox/rc.xml)
areaclick=$(xml sel -N a=http://openbox.org/3.4/rc -t -v '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Press"][@button="Left"]/a:action/a:command' $HOME/.config/openbox/rc.xml)

out+=("^sep($WMTWEAKS)")
if [[ "${areaclick}" != "areaclick" ]]; then
	lclick=$(xml sel -N a=http://openbox.org/3.4/rc -t -v '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Press"][@button="Left"]/a:action/@name' $HOME/.config/openbox/rc.xml)
	if [[ ! -z "$lclick"  ]];then
	[[ "$lclick" = "none" ]] && out+=("<big>󰄱</big>  $SHOW_DESK,obxml show_desk on") || out+=("<big>󰄲</big>  $SHOW_DESK,obxml show_desk off")
	fi
else
	if source ~/.config/areaclick.conf ;then
	[[ "${cmd_center}" == "show_desktop" ]] && out+=("<big>󰄲</big>  $SHOW_DESK,mb-setvar cmd_center=none $AREA_CFG") || out+=("<big>󰄱</big>  $SHOW_DESK,mb-setvar cmd_center=show_desktop $AREA_CFG")
	fi
fi

if [[ ! -z "$mousewheel" ]];then
[[ "$mousewheel" = "none" ]] && out+=("<big>󰄱</big>  $SWITCH_DESK,obxml switch_desk on") || out+=("<big>󰄲</big>  $SWITCH_DESK,obxml switch_desk off")
fi
[[ "$focus" = "no" ]] && out+=("<big>󰄱</big>  $FOCUS,obxml focus_follow_mouse on") || out+=("<big>󰄲</big>  $FOCUS,obxml focus_follow_mouse off")

# AREACLICK
if [[ "${areaclick}" == "areaclick" ]]; then
if source ~/.config/areaclick.conf ;then
	if [[ "${sidearea}" -gt "0" ]];then
	out+=("<big>󰄲</big>   <b>$AREACLICK</b> (<i>$AREA_WIDTH</i>: ${sidearea}px),^checkout(area)")
	else
	out+=("<big>󰄱</big>   <b>$AREACLICK</b> <i>$STOPPED</i>,^checkout(area)")
	fi
	out2+=("^tag(area)")
	out2+=("^sep(AreaClick)")
	#out2+=("$ABOUT_AREACLICK,mb-docs areaclick")
	out2+=("^sep($AREA_WIDTH (px))")
	[[ "${sidearea}" == "0" ]] && out2+=("<big>${ron}</big>   0 (disabled),areaclick area 0") || out2+=("<big>${roff}</big>   0 (disable),areaclick area 0")
	[[ "${sidearea}" == "2" ]] && out2+=("<big>${ron}</big>   2px,areaclick area 2") || out2+=("<big>${roff}</big>   2px,areaclick area 2")
	[[ "${sidearea}" == "10" ]] && out2+=("<big>${ron}</big>   10px,areaclick area 10") || out2+=("<big>${roff}</big>   10px,areaclick area 10")
	[[ "${sidearea}" == "60" ]] && out2+=("<big>${ron}</big>   60px,areaclick area 60") || out2+=("<big>${roff}</big>   60px,areaclick area 60")
	[[ "${sidearea}" == "100" ]] && out2+=("<big>${ron}</big>   100px,areaclick area 80") || out2+=("<big>${roff}</big>   100px,areaclick area 100")
	[[ "${sidearea}" == "200" ]] && out2+=("<big>${ron}</big>   200px (disable),areaclick area 200") || out2+=("<big>${roff}</big>   200px,areaclick area 200")
	out2+=("^sep()")
	out2+=("$EDIT_AREACONF,areaclick editconf")
	out2+=("^sep()")
	out2+=("$RESET_AREACONF,^checkout(reseta)")
	out3+=("^tag(reseta)")
	out3+=("^sep($RESET_SURE)")
	out3+=("\"\"\"$RESET_YES\"\"\", areaclick reset")
	
	out2+=("^sep($WM_MARGIN)")
	m_top=$(obxml sel /a:openbox_config/a:margins/a:top)
	m_bottom=$(obxml sel /a:openbox_config/a:margins/a:bottom)
	m_left=$(obxml sel /a:openbox_config/a:margins/a:top)
	m_right=$(obxml sel /a:openbox_config/a:margins/a:top)
	out2+=("^sep(<big></big> <small>$m_left</small>     <big></big> <small>$m_top</small>     <small>$m_bottom</small> <big></big>     <small>$m_right</small> <big></big>")
	#out2+=("$OBCONF_MARG,obconf")
	out2+=("^sep(<i>$SET_ALL_MARG</i>)")
	out2+=("0,obxml margin all 0")
	out2+=("1px,obxml margin all 1")
	out2+=("2px,obxml margin all 2")
	out2+=("4px,obxml margin all 4")
	out2+=("8px,obxml margin all 8")
	out2+=("16px,obxml margin all 16")
	fi
fi


out+=("^sep($TOOLS)")
out+=("<big>󰸉</big>   $WALLCHANGER,jgwallpaperchanger -s")
out+=("<big>󱇙</big>   SuperClick,jgdeskgrid -s")
out+=("<big></big>   $DESKMNGR,^pipe(jgdeskmngr)")


#out+=(". ~/.config/mabox/jgdesktops-bottom.csv")


### RUN
if [[ "$1" == "-s" || "$1" == "ipc" ]]; then

if [[ $panels_heightpos == "top" ]]; then
MENU_VALIGN="top"
MENU_MARGIN_Y=${panels_topmargin:-0}
elif [[ $panels_heightpos == "bottom" ]]; then
MENU_VALIGN="bottom"
MENU_MARGIN_Y=${panels_topmargin:-0}
else 
    MENU_VALIGN="center"
fi

MENU_PADDING_TOP=${jgtools_padding:-0}
MENU_HALIGN="center"

if [[ "$1" == "ipc" ]]; then 
POSITION_MODE="ipc"
else
POSITION_MODE="pointer"
fi
jgmenu_icon_size=0

[ $(pidof picom) ] && MENU_RADIUS=$jgtools_radius
[ -z $jgmenu_use_borders ] && menu_border=0

mkconfigfile

cat <<EOF > ${MENU_ITEMS}
$(printf '%s\n' "${out[@]}")
$(printf '%s\n' "${out2[@]}")
$(printf '%s\n' "${out3[@]}")
EOF

jgmenu --config-file=${CONFIG_FILE} --csv-file=${MENU_ITEMS} 2>/dev/null

exit 0

fi
printf '%s\n' "${out[@]}"

if [[ $1 == "-r" ]]; then
printf '%s\n' "^sep()"
printf '%s\n' "<i>$REMOVE</i>,mb-setvar places_jgdesktops=false;mb-jgtools places"
fi
printf '%s\n' "${out2[@]}"
printf '%s\n' "${out3[@]}"
