#!/bin/bash
# ©2024 J. S. Gilstrap - All Rights Reserved. & GPL ≥2.1  https://www.gnu.org/license
# Menu Generator for TWM 1.0.0 . Sources .desktop files to popluate menus.
# Α<Σ>Ω where <Σ> The Sum of All Things in Between.
# I AM the Αlpha and the Ωmega, the First and
# the Last, the Beginning and the End. Rev. 22:13
[ "$1" = stop ] && exit

# chkconfig: 2345 89 38
# description: TWM Menu Creator.
### BEGIN INIT INFO
# Provides: system.twmrc
# Short-Description: Creates TWM menus.
# Description: Auto generates menus for TWM using .desktop files.
#### END  INIT INFO
#------------------------ Set Defaults -----------------------------------------
#printf "PreProc..."
# TWM Config Home.
TWMhome=/etc/X11/twm

# Set rc name for system or single user install.
SysTWM=system.twmrc ; [ $UID != 0 ] && SysTWM=.twmrc

# Desktop Width & Height
DskTpWd=1280 ; DskTpHt=800

# This calculates the X & Y offset for xclock, oclock, xbiff, tmprtr & xosview
# desktop placement. It is calculated to place them in reference from the right.
# Others can be added which take the geometry argument.
xckofst="$(($DskTpWd-298))+-3" ; ockofst="$(($DskTpWd-155))+40"
xbfofst="$(($DskTpWd-230))+45" ; tmpofst="$(($DskTpWd-406))+-3"
xvwofst="$(($DskTpWd-313))+$(($DskTpHt-343))"

# Define location(s) for .desktop files.
DskTpFls="/usr/share/applications/*.desktop /usr/local/share/applications/*.desktop"

# Define Caregories. If changed you must re-associate each category 
# with its file handle in the case statement starting on line 133.
#                3         4         5         6      7       8  <- File Handles
Categories="Accessories Graphics AudioVideo Network Games Development \
Education Engineering Documentation System Settings Utility Office Other"
#   9         10          11          12      13      14      15    16  <- File Handles

# Set X Term arguments.
Term="xterm -bg rgb:FF/FC/FA -fg rgb:00/00/80 -fn 10x20 -geometry 84x36+150+45 -cr red -sb -sl 5000 -si -sk -rightbar"

# Define Default Programs
 RUN=xfrun4  # Run... Command.
Mail="$Term -T Mutt  -e mutt"   # Mail Client
WebB="$Term -T Links -e links"  # Web Browser
FilB="nautilus --no-desktop --browser"  # File Browser.

#------------------------ End Settings -----------------------------------------
# Cleanup on Ctrl-C exit.
trap "rm -f /tmp/*-twm.$$ ; exit 130" SIGINT

# Get system release info for main menu title.
if [ -f /etc/redhat-release ]
then
	R=$(< /etc/redhat-release) ; R=${R%% (*} ; R=${R/ release}
	R=${R/Red Hat/RedHat} ; Mttl=${R/ Enterprise Linux/EL}
else
	R=$(uname -mrs) ; [ -n "$R" ] && Mttl=${R%%-*} || Mttl=TWM
fi

# Read Line Echo function. A Cat Here File without a system call.
RLE(){ local IFS=$'\n' ; while read line ; do echo "$line" ; done ; }

# Print function.
Print()
	{
	case ${Terminal,,} in
		true|1) printf "\t\"${Name}\"${B}f.exec \"${Term} -T '${Name}' -e ${Exec} &\"\n" ;;
		     *) printf "\t\"$Name\"${B}f.exec \"$Exec &\"\n" ;;
	esac
	}

c=3 # Open file handles.
for cat in $Categories
do
	eval exec ${c}\> /tmp/${cat}-twm.$$
	((c++))
done

#printf "Sort..."
# Process .desktop files and file them under the associated categories.
for app in $DskTpFls
do
	while read line
	do
		case $line in
			      Exec=*) Exec=${line#*=} ; Exec=${Exec%% *} ;;
			      Name=*) Name=${line#*=} ;;
			  Terminal=*) Terminal=${line#*=} ;;
			Categories=*) Category=${line#*=} ;;
			           *) ;;
		esac
	done < $app

	# Libre Office Hack.
	if [ "$Exec" = libreoffice ]
	then
		case "$Name" in
			       'New Document') Name="LibreOffice Writer"  ; Exec="$Exec --writer"  ;;
			 'LibreOffice Writer') Exec="$Exec --writer"  ;;
			    'New Spreadsheet') Name="LibreOffice Calc"    ; Exec="$Exec --calc"    ;; 
			   'LibreOffice Calc') Exec="$Exec --calc"    ;;
			        'New Formula') Name="LibreOffice Math"    ; Exec="$Exec --math"    ;;
			   'LibreOffice Math') Exec="$Exec --matn"    ;;
			   'New Presentation') Name="LibreOffice Impress" ; Exec="$Exec --impress" ;;
			'LibreOffice Impress') Exec="$Exec --impress" ;;
			        'New Drawing') Name="LibreOffice Draw"    ; Exec="$Exec --draw"    ;;
			   'LibreOffice Draw') Exec="$Exec --draw"    ;;
		esac
	fi

	# Various Hacks.
	[ "$Name" = "File Browser" -a "$Exec" = nautilus ] && Exec="$Exec --no-desktop --browser"
	[ "$Name" = "File Manager" -a "$Exec" = nautilus ] && Exec="$Exec --no-desktop"

	case "$Name" in
		Formula|'gThumb Photo Import Tool') Category=skip ;;
		'LibreOffice XSLT based filters') Category=skip ;;
	esac

	case $Exec in 
		gthumb-importer) Name="gThumb Image Importer" ;;
		 gnome-terminal) Name="Gnome Terminal" ;;
		thunar-settings) Name="Thunar Settings" ;;
		nautilus-file-management-properties) Name="Nautilus Settings" ;;
	esac

	# Create buffer character string to pad between Name & Exec in menu for column alignment.
	n=$((21-${#Name})) ; [ $n -lt 1 ] && n=1 ; B="                        " ; B=${B:0:$n}

	# Sort Apps into Categories
	case $Category in
		skip) ;;
		*TextEditor*|*Dictionary*|*Archiving*|*Calculator*|*Accessories*) Print >&3 ;;
		*WordProcessor*|*Spreadsheet*|*Presentation*|*Office*FlowChart*|*Office*Education*)  Print >&15 ;;
		*Graphics*) Print >&4 ;;
		*Audio*|*Video*|*Player*|*AudioVideo*) Print >&5 ;;
		*Email*|*WebBrowser*|*Telephony*|*FileTransfer*|*InstantMessaging*|*Chat*|*RemoteAccess*|*Network*) Print >&6 ;;
		*Game*) Print >&7 ;;
		*Development*) Print >&8 ;;
		*Math*|*Science*|*Physics*|*Education*) Print >&9 ;;
		*Electronics*|*Electrical*|*Mechanical*|*Engineering*) Print >&10 ;;
		*Documentation*) Print >&11 ;;
		*HardwareSettings*|*NetworkSettings*|*SystemSettings*|*Printing*|*PackageManager*|*Monitor*|*Core*|*Security*|*System*) Print >&12 ;;
		*Accessibility*|*DesktopSettings*|*PersonalSettings*|*Settings*) Print >&13 ;;
		*Terminal*|*Emulator*|*TrayIcon*|*Utility*) Print >&14 ;;
		*FlowChart*|*Calendar*|*ContactManagement*|*Office*) Print >&15 ;;
		*) Print >&16 ;;
	esac
done

# Close all file handles.
C=$c ; c=3
while [ $c -lt $C ]
do
	eval exec ${c}\<\&-
	((c++))
done

#printf "Menu Head..."
# Open file handle for [system].twmrc .
exec 3> ${TWMhome}/${SysTWM}
# Generate menu head.
RLE << EoF >&3
# Copyright ©2024  J. S. Gilstrap - All Rights Reserved.
# GPL ≥2.1 https://www.gnu.org/license
# Do not edit this file as it will be overwritten on reboot.
# You may copy it to your home directory as .twmrc and then edit it.

# Add programs that don't need a title bar.
NoTitle
	{
	"tmprtr"
	"xmms"
	"xclock"
	"oclock"
	"xbiff"
	"xconsole"
	"xosview"
	"gnome-panel"
	"xfce4-panel"
	}

NoGrabServer
RestartPreviousState
DecorateTransients
TitleFont "-adobe-helvetica-bold-r-normal--*-120-*-*-*-*-*-*"
ResizeFont "-adobe-helvetica-bold-r-normal--*-120-*-*-*-*-*-*"
MenuFont "-adobe-helvetica-bold-r-normal--*-120-*-*-*-*-*-*"
IconFont "-adobe-helvetica-bold-r-normal--*-120-*-*-*-*-*-*"
IconManagerFont "-adobe-helvetica-bold-r-normal--*-120-*-*-*"
BorderWidth 3

# Ultra Violet Color Theme
Color
	{
	BorderColor "rgb:40/FF/40"
	BorderTileForeground "rgb:C0/13/30"
	BorderTileBackground "rgb:C0/13/30"

	DefaultForeground "rgb:FF/FF/00"
	DefaultBackground "rgb:70/00/C0"

	IconBorderColor "rgb:40/FF/40"
	IconForeground "rgb:FF/FF/00"
	IconBackground "rgb:70/00/C0"

	IconManagerBackground "rgb:70/00/C0"
	IconManagerForeground "rgb:40/FF/40"
	IconManagerHighlight "rgb:FF/FF/00"

	TitleForeground "rgb:FF/FF/00"
	TitleBackground "rgb:00/00/FF"

	MenuForeground "rgb:40/FF/40"
	MenuBackground "rgb:70/00/C0"
	MenuTitleForeground "rgb:FF/FF/00"
	MenuTitleBackground "rgb:00/00/FF"
	MenuBorderColor "rgb:FF/FF/00"
	MenuShadowColor "rgb:FF/FF/00"
	}

# Fuctions
MoveDelta 3

Function "move-or-lower"   { f.move f.deltastop f.lower }
Function "move-or-raise"   { f.move f.deltastop f.raise }
Function "move-or-iconify" { f.move f.deltastop f.iconify }
Function "up_iconmgr"      { f.warptoiconmgr "" f.deltastop f.upiconmgr }
Function "down_iconmgr"    { f.warptoiconmgr "" f.deltastop f.downiconmgr }
Function "left_iconmgr"    { f.warptoiconmgr "" f.deltastop f.lefticonmgr }
Function "right_iconmgr"   { f.warptoiconmgr "" f.deltastop f.righticonmgr }

Function "ReStart"
	{
	f.exec "xsetroot -solid rgb:00/00/80"
	f.restart
	}

# Mouse & Key Bindings
Button1 = : root : f.menu "TwmWindows"
Button3 = : root : f.menu "MainMenu"

Button1 = meta : window|icon : f.function "move-or-raise"
Button2 = meta : window|icon : f.iconify
Button3 = meta : window|icon : f.function "move-or-lower"

Button1 = : title : f.function "move-or-raise"
Button3 = : title : f.menu "/WindowOps"

Button1 = : icon : f.function "move-or-iconify"
Button3 = : icon : f.menu "/IconOps"

Button1 = : iconmgr : f.iconify
Button3 = : iconmgr : f.menu "/IconOps"

Button1 = shift : window : f.move
Button3 = shift : window : f.resize

## XTerm menu access. Do NOT use.
#Button1 = control : window
#Button2 = control : window
#Button3 = control : window

Button1 = control meta : window|icon : f.delete
Button3 = control meta : window|icon : f.destroy

"F1" = : root : f.exec "xterm -fg Black -bg White -fn 10x20 -geometry 60x37+240+0 +sb -T 'TWM Help' -e view ${TWMhome}/TWM-Help.txt &"

"F1" = control :  all : f.restart
"F2" = control :  all : f.move
"F3" = control :  all : f.iconify

"Up"    = control meta : all : f.function "up_iconmgr"
"Down"  = control meta : all : f.function "down_iconmgr"
"Left"  = control meta : all : f.function "left_iconmgr"
"Right" = control meta : all : f.function "right_iconmgr"

# Menus
Menu "MainMenu"
	{
#	"        Α < Σ > Ω"    f.nop
	"$Mttl"                f.title
	"X Terminal"           f.exec "$Term -T 'X Term' &"
	"File Browser"         f.exec "$FilB &"
	"Mail Client"          f.exec "$Mail &"
	"Web Browser"          f.exec "$WebB &"
	"━━━━━━━"              f.nop
	"Run Program..."       f.exec "$RUN &"
	"Settings..."          f.menu "/Utilities"
	"Find"                 f.menu "/Find"
	"TWM Menu"             f.menu "/Twm"
	"━━━━━━━"              f.nop
	"Accessories"          f.menu "/Accessories"
	"Documentation"        f.menu "/Documentation"
	"Educational"          f.menu "/Education"
	"Engineering"          f.menu "/Engineering"
	"Development"          f.menu "/Development"
	"Games"                f.menu "/Games"
	"Graphics"             f.menu "/Graphics"
	"Internet"             f.menu "/Network"
	"Office"               f.menu "/Office"
	"Audio & Video"        f.menu "/AudioVideo"
	"Other"                f.menu "/Other"
	"━━━━━━━"              f.nop
	"Log Out..."           f.menu "/LogOut"
	}
 
Menu "/Utilities"
	{
	"System"               f.menu "/System"
	"User"                 f.menu "/Settings"
	"Utility"              f.menu "/Utility"
	"X Clock"              f.exec "xclock -bg White -digital -update 1 -geometry 295x35+${xckofst} &"
	"O Clock"              f.exec "oclock -geometry 150x150+${ockofst} -fg black -bg white &"
	"X ClipBoard"          f.exec "xclipboard &"
	"X Biff"               f.exec "xbiff -geometry 60x60+${xbfofst} &"
	"VNC Config"           f.exec "vncconfig &"
	"Set BG Color"         f.exec "setbgcolor &"
	"CPU Temp"             f.exec "tmprtr $tmpofst &"
	"XTerm  SU"            f.exec "$Term -T 'Super User' -e su - &"
	"X Console"            f.exec "xconsole -verbose -geometry 640x160+0+0 -fn 9x15 &"
	"X OS View"            f.exec "xosview +disk +net +int -geometry 310x340+${xvwofst} &"
	"X Kill"               f.exec "xkill &"
	"Gnome Panel"          f.exec "gnome-panel &"
	"XFCE Panel"           f.exec "xfce4-panel &"
	}

Menu "/WindowOps"
	{
	"Window"               f.title
	"More"                 f.menu "/More"
	"Move"                 f.move
	"Resize"               f.resize
	"Minimize"             f.iconify
	"Maximize"             f.fullzoom
	"Back"                 f.lower
	"━━━━"                 f.nop
	"Close"                f.delete
	"Quit   (Kill)"        f.destroy
	}                      
                          
Menu "/IconOps"           
	{                      
	"Icon"                 f.title
	"Restore"              f.iconify
	"Move"                 f.move
	"Identify"             f.identify
	"Save State"           f.saveyourself
	"━━━━"                 f.nop
	"Close"                f.delete
	"Quit   (Kill)"        f.destroy
	}                      
                          
Menu "/More"              
	{                      
	"Maximize"             f.title
	"Tall"                 f.zoom
	"Wide"                 f.horizoom
	"Tall & Wide"          f.title
	"Top"                  f.topzoom
	"Bottom"               f.bottomzoom
	"Left"                 f.vlzoom
	"Right"                f.vrzoom
	"Other"                f.title
	"Toggle AutoRaise"     f.autoraise
	"Force Move"           f.forcemove
	"Front"                f.raise
	"Identify"             f.identify
	"Save State"           f.saveyourself
	}                      
                          
Menu "/Find"              
	{                      
	"Files"                f.exec "gnome-search-tool &"
	"Web Search"           f.title
	"Startpage"            f.exec "$Term -e links https://www.startpage.com &"
	"Duck Duck Go"         f.exec "$Term -e links https://www.duckduckgo.com &"
	"Dog Pile"             f.exec "$Term -e links https://www.dogpile.com &"
	"Yahoo"                f.exec "$Term -e links https://www.yahoo.com &"
	"Google"               f.exec "$Term -e links https://www.google.com &"
	}

Menu "/Twm"
	{
	"Functions"            f.title
	"Current Windows"      f.menu "TwmWindows"
	"Window Ops"           f.menu "/WindowOps"
	"Show Icon Manager"    f.showiconmgr
	"Hide Icon Manager"    f.hideiconmgr
	"Focus     Keyboard"   f.focus
	"Unfocus Keyboard"     f.unfocus
	"TWM  Help"            f.exec "xterm -fg Black -bg White -fn 10x20 -geometry 60x37+240+0 +sb -T 'TWM Help' -e view ${TWMhome}/TWM-Help.txt &"
	}

Menu "/LogOut"
	{
	"ReStart"              f.function "ReStart"
	" "                    f.nop
	"Do NOT Use In VNC!"   f.title
	"       Exit     TWM"  f.quit
	}

EoF

#printf "Sub-Menus..."
# Add sub menus from .desktop files to [system].twmrc.
for cat in $Categories
do
	printf "Menu \"/${cat}\"\n\t{\n" >&3
	sort /tmp/${cat}-twm.$$ >&3
	printf "\t}\n\n" >&3
done

# Close file handle and remove /tmp files.
exec 3<&-
rm /tmp/*-twm.$$

#echo "Done."
