Repository navigation
Expand file tree
/
Copy pathtoshy_tray.py
More file actions
executable file
·910 lines (705 loc) · 37 KB
/
Copy pathtoshy_tray.py
File metadata and controls
executable file
·910 lines (705 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '20261107'
# Indicator tray icon menu app for Toshy, using pygobject/gi
TOSHY_PART = 'tray' # CUSTOMIZE TO SPECIFIC TOSHY COMPONENT! (gui, tray, config)
TOSHY_PART_NAME = 'Toshy Tray Icon App'
APP_VERSION = __version__
# -------- COMMON COMPONENTS --------------------------------------------------
import os
import sys
import time
import shutil
import threading
import subprocess
from subprocess import DEVNULL, PIPE
from toshy_common.overlay_context import (
OverlayFlag,
OVL_METADATA,
OVL_PRESET_FULL,
OVL_PRESET_MINIMAL,
OVL_PRESET_NONE,
get_flag_parent,
)
from toshy_common.proc_launcher import launch_detached
# Check for accessibility support before importing GTK
def is_a11y_available():
try:
# D-Bus query to check whether a11y support is present:
# gdbus introspect --session --dest org.a11y.Bus --object-path /org/a11y/bus
result = subprocess.run([
'gdbus', 'introspect', '--session',
'--dest', 'org.a11y.Bus',
'--object-path', '/org/a11y/bus'
], capture_output=True, timeout=2)
return result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
if not is_a11y_available():
os.environ['GTK_A11Y'] = 'none'
os.environ['NO_AT_BRIDGE'] = '1'
# Initialize Toshy runtime before other imports
from toshy_common.runtime_utils import initialize_toshy_runtime
runtime = initialize_toshy_runtime()
# Local imports
import toshy_common.terminal_utils as term_utils
from toshy_common import logger
from toshy_common.logger import *
from toshy_common.env_context import EnvironmentInfo
from toshy_common.settings_class import Settings
from toshy_common.modifier_modes import CAPSLOCK_MODES, CAPSLOCK_MODE_LABELS
from toshy_common.process_manager import ProcessManager
from toshy_common.service_manager import ServiceManager
from toshy_common import autostart_manager
from toshy_common.monitoring import SettingsMonitor, ServiceMonitor
# Make process manager global
process_mgr = None
logger.FLUSH = True
logger.VERBOSE = False
###############################################################################
# -------- TOSHY TRAY SPECIFIC COMPONENTS -------------------------------------
###############################################################################
# What we need for the indicator tray icon and menu
import gi.repository
gi.require_version('Gtk', '3.0')
try:
gi.require_version('AyatanaAppIndicator3', '0.1')
from gi.repository import AyatanaAppIndicator3 as AppIndicator3
except (ValueError, ImportError) as e:
# debug(f'ImportError: Falling back on AppIndicator3 instead of AyatanaAppIndicator3.')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3
from gi.repository import Gtk, GLib
# Define some globals for the commands run by menu items
# assets_path = os.path.join(current_folder_path, 'assets')
# icon_file_active = os.path.join(assets_path, "toshy_app_icon_rainbow.svg")
# icon_file_grayscale = os.path.join(assets_path, "toshy_app_icon_rainbow_inverse_grayscale.svg")
# icon_file_inverse = os.path.join(assets_path, "toshy_app_icon_rainbow_inverse.svg")
# Fix for Solus Budgie failing to show proper icons when using full path. Use base file name string.
# Icon files will all be copied into the local-share-icons location to make this work.
icon_file_active = "toshy_app_icon_rainbow"
icon_file_grayscale = "toshy_app_icon_rainbow_inverse_grayscale"
icon_file_inverse = "toshy_app_icon_rainbow_inverse"
DISTRO_ID = None
DISTRO_VER = None
VARIANT_ID = None
SESSION_TYPE = None
DESKTOP_ENV = None
DE_MAJ_VER = None
WINDOW_MGR = None
def check_environment():
"""Retrieve the current environment from EnvironmentInfo class"""
global DISTRO_ID, DISTRO_VER, VARIANT_ID, SESSION_TYPE, DESKTOP_ENV, DE_MAJ_VER, WINDOW_MGR
env_ctxt_getter = EnvironmentInfo()
env_info_dct = env_ctxt_getter.get_env_info()
DISTRO_ID = str(env_info_dct.get('DISTRO_ID', 'keymissing')).casefold()
DISTRO_VER = str(env_info_dct.get('DISTRO_VER', 'keymissing')).casefold()
VARIANT_ID = str(env_info_dct.get('VARIANT_ID', 'keymissing')).casefold()
SESSION_TYPE = str(env_info_dct.get('SESSION_TYPE', 'keymissing')).casefold()
DESKTOP_ENV = str(env_info_dct.get('DESKTOP_ENV', 'keymissing')).casefold()
DE_MAJ_VER = str(env_info_dct.get('DE_MAJ_VER', 'keymissing')).casefold()
WINDOW_MGR = str(env_info_dct.get('WINDOW_MGR', 'keymissing')).casefold()
# Populate environment globals at module load time
check_environment()
# =============================================================================
# ENVIRONMENT-SPECIFIC ADJUSTMENTS
# =============================================================================
def show_cinnamon_wayland_warning():
"""Show async warning dialog about Cinnamon Wayland tray menu bugs."""
warning_title = "Cinnamon Wayland: Known Tray Menu Bugs"
warning_text = (
"Cinnamon's Wayland session has bugs affecting tray icon menus:\n\n"
"• Menu appears in wrong location (top-left instead of near icon)\n"
"• Menu stops appearing after first use\n\n"
"This is a Cinnamon compositor bug, not a Toshy issue.\n\n"
"<b>Alternatives:</b>\n"
"• Use the Toshy Preferences app instead (has all the same options)\n"
"• Restart the tray icon via app menu: \"Toshy Tray Icon\"\n"
"• From terminal: <tt>nohup toshy-tray &</tt> (allows closing terminal)"
)
cmd_lst = [
'zenity',
'--warning',
'--title', warning_title,
'--text', warning_text,
'--width', '500',
'--no-wrap',
]
if not launch_detached(cmd_lst, stdout=DEVNULL, stderr=DEVNULL):
error("Cinnamon Wayland has known bugs affecting tray icon menus (zenity not available).")
def cinnamon_version_below(threshold_tup) -> bool:
"""Compare the running Cinnamon version (from 'cinnamon --version',
e.g. 'Cinnamon 6.6.9') against a (major, minor) threshold. Returns
True when the version is known and BELOW the threshold; also returns
True when the version cannot be determined, so version-gated warnings
err toward still showing."""
try:
proc = subprocess.run(['cinnamon', '--version'],
capture_output=True, text=True, timeout=5)
version_str = proc.stdout.strip().split()[-1]
parts_lst = version_str.split('.')
version_tup = (int(parts_lst[0]), int(parts_lst[1]))
except (OSError, subprocess.SubprocessError, ValueError, IndexError):
return True # unknown version: keep showing the warning
return version_tup < threshold_tup
# Cinnamon Wayland: Show warning about known tray menu bugs.
# Cinnamon 6.8 ships the Wayland popup mapping fixes ("Proper mapping
# (sizing and positioning) for new windows, applet popup menus and
# context menus" -- Mint blog, next release scheduled around Christmas
# 2026), so the warning is gated to versions below 6.8. If the fix turns
# out incomplete, lower/adjust the threshold or remove the gate.
if (DESKTOP_ENV == 'cinnamon' and SESSION_TYPE == 'wayland'
and cinnamon_version_below((6, 8))):
show_cinnamon_wayland_warning()
# COSMIC: Desktop environment messes with tray icon, so use 'grayscale' icon for all states
if DESKTOP_ENV == 'cosmic':
icon_file_active = icon_file_grayscale
icon_file_inverse = icon_file_grayscale
loop = None
# Settings class object setup
config_dir_path = runtime.config_dir
cnfg = Settings(config_dir_path)
cnfg.watch_database() # start watching the preferences file for changes
# Notification handler object setup
from toshy_common.notification_manager import NotificationManager
ntfy = NotificationManager(icon_file_active, title='Toshy Alert (Tray)')
# Service manager instance
service_manager = ServiceManager(ntfy, icon_file_active, icon_file_inverse, icon_file_grayscale)
sysctl_cmd = f"{shutil.which('systemctl')}"
user_sysctl = f'{sysctl_cmd} --user'
# -------- CREATE MENU --------------------------------------------------------
main_menu = Gtk.Menu()
# Add menu items here using Gtk.MenuItem and Gtk.ImageMenuItem
tray_indicator = AppIndicator3.Indicator.new(
"Toshy Tray Icon Undefined",
icon_name=icon_file_grayscale,
category=AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
tray_indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
tray_indicator.set_menu(main_menu)
tray_indicator.set_title("Toshy Status Indicator") # try to set what might show in tooltip
# -------- MENU ACTION FUNCTIONS ----------------------------------------------
def fn_open_preferences(widget):
if launch_detached(['toshy-gui']):
return
_ntfy_icon = icon_file_inverse
_ntfy_msg = ("The 'toshy-gui' utility is missing.\r"
"Please check your installation.")
ntfy.send_notification(_ntfy_msg, _ntfy_icon, urgency='critical')
_error_msg = ("The 'toshy-gui' utility is missing.\n"
" Please check your installation.")
error(f"{_error_msg}")
def fn_open_config_folder(widget):
if not shutil.which('xdg-open'):
_ntfy_icon = icon_file_inverse
_ntfy_msg = ("The 'xdg-open' utility is missing.\r"
"Try installing 'xdg-utils' package.")
ntfy.send_notification(_ntfy_msg, _ntfy_icon, urgency='critical')
_error_msg = ("The 'xdg-open' utility is missing.\n"
" Try installing 'xdg-utils' package.")
error(f"{_error_msg}")
return
# Sometimes xdg-open script is unpatched for Plasma 6 (e.g., Leap 16), so use kde-open instead
opener_cmd = 'xdg-open'
if DESKTOP_ENV == 'kde' and DE_MAJ_VER == '6' and shutil.which('kde-open'):
opener_cmd = 'kde-open'
launch_detached([opener_cmd, runtime.config_dir])
def fn_show_services_log(widget):
try:
term_utils.run_cmd_lst_in_terminal(['toshy-services-log'], desktop_env=DESKTOP_ENV)
except term_utils.TerminalNotFoundError as term_err:
# If we reach this, we failed to find a terminal app to use, so show a notification.
_ntfy_icon_file = icon_file_inverse # predefined path to icon file
_ntfy_msg = term_err
ntfy.send_notification(_ntfy_msg, _ntfy_icon_file)
def fn_remove_tray_icon(widget):
global loop
process_mgr.remove_lockfile()
loop.quit()
pkill_cmd = shutil.which('pkill')
os.system(f'{pkill_cmd} -f "toshy_tray.py"')
# Gtk.main_quit()
sys.exit(0)
def set_item_active_thread_safe(menu_item, state=True):
"""Set menu item's active state (thread-safe version)"""
def do_set_active():
menu_item.set_active(state)
return False # Don't repeat
# If we're in the main thread, set directly
if threading.current_thread() is threading.main_thread():
menu_item.set_active(state)
else:
# Schedule for main thread
GLib.idle_add(do_set_active)
# -------- MENU ITEMS --------------------------------------------------
if runtime.is_systemd:
services_label_item = Gtk.MenuItem(label=" ---- Services Status ---- ")
services_label_item.set_sensitive(False)
main_menu.append(services_label_item)
toshy_config_status_item = Gtk.MenuItem( label=" Config: (?)")
toshy_config_status_item.set_sensitive(False)
main_menu.append(toshy_config_status_item)
session_monitor_status_item = Gtk.MenuItem( label=" SessMon: (?)")
session_monitor_status_item.set_sensitive(False)
main_menu.append(session_monitor_status_item)
toshy_svc_config_unit_enabled = autostart_manager.is_service_enabled("toshy-config.service", runtime)
toshy_svc_sessmon_unit_enabled = autostart_manager.is_service_enabled("toshy-session-monitor.service", runtime)
def fn_toggle_toshy_svcs_autostart(widget):
"""Check the status of Toshy services, flip the status, change the menu item label"""
global toshy_svc_config_unit_enabled, toshy_svc_sessmon_unit_enabled
if shutil.which('systemctl') and runtime.is_systemd:
pass
else:
# If either 'systemctl' is missing or init is not 'systemd', immediately return
return
try:
if widget.get_active():
service_manager.enable_services()
else:
service_manager.disable_services()
except subprocess.CalledProcessError as proc_err:
debug(f"Error toggling Toshy systemd user services: {proc_err}")
time.sleep(0.5)
if runtime.is_systemd:
separator_above_svcs_item = Gtk.SeparatorMenuItem()
main_menu.append(separator_above_svcs_item) #-------------------------------------#
restart_toshy_svcs_item = Gtk.MenuItem(label="Re/Start Toshy Services")
# restart_toshy_svcs_item.connect("activate", fn_restart_toshy_services)
restart_toshy_svcs_item.connect("activate", lambda widget: service_manager.restart_services())
main_menu.append(restart_toshy_svcs_item)
quit_toshy_svcs_item = Gtk.MenuItem(label="Stop Toshy Services")
# quit_toshy_svcs_item.connect("activate", fn_stop_toshy_services)
quit_toshy_svcs_item.connect("activate", lambda widget: service_manager.stop_services())
main_menu.append(quit_toshy_svcs_item)
separator_below_svcs_item = Gtk.SeparatorMenuItem()
main_menu.append(separator_below_svcs_item) #-------------------------------------#
restart_toshy_script_item = Gtk.MenuItem(label="Re/Start Config-Only")
# restart_toshy_script_item.connect("activate", fn_restart_toshy_config_only)
restart_toshy_script_item.connect("activate", lambda widget: service_manager.restart_config_only())
main_menu.append(restart_toshy_script_item)
stop_toshy_script_item = Gtk.MenuItem(label="Stop Config-Only")
# stop_toshy_script_item.connect("activate", fn_stop_toshy_config_only)
stop_toshy_script_item.connect("activate", lambda widget: service_manager.stop_config_only())
main_menu.append(stop_toshy_script_item)
separator_below_script_item = Gtk.SeparatorMenuItem()
main_menu.append(separator_below_script_item) #-------------------------------------#
if not runtime.barebones_config:
def load_prefs_submenu_settings():
cnfg.load_settings()
set_item_active_thread_safe(forced_numpad_item, cnfg.forced_numpad)
set_item_active_thread_safe(altgr_on_menu_key_item, cnfg.altgr_on_menu_key)
set_item_active_thread_safe(media_arrows_fix_item, cnfg.media_arrows_fix)
set_item_active_thread_safe(multi_lang_item, cnfg.multi_lang)
set_item_active_thread_safe(ST3_in_VSCode_item, cnfg.ST3_in_VSCode)
set_item_active_thread_safe(Enter2Ent_Cmd_item, cnfg.Enter2Ent_Cmd)
set_item_active_thread_safe(l_cmd_is_sup_and_cmd_item, cnfg.l_cmd_is_sup_and_cmd)
set_item_active_thread_safe(l_opt_is_sup_and_opt_item, cnfg.l_opt_is_sup_and_opt)
set_item_active_thread_safe(swap_spotlight_item, cnfg.swap_spotlight_and_input)
def save_prefs_settings(widget):
new_values_dct = {
'forced_numpad': forced_numpad_item.get_active(),
'altgr_on_menu_key': altgr_on_menu_key_item.get_active(),
'media_arrows_fix': media_arrows_fix_item.get_active(),
'multi_lang': multi_lang_item.get_active(),
'ST3_in_VSCode': ST3_in_VSCode_item.get_active(),
'Enter2Ent_Cmd': Enter2Ent_Cmd_item.get_active(),
'l_cmd_is_sup_and_cmd': l_cmd_is_sup_and_cmd_item.get_active(),
'l_opt_is_sup_and_opt': l_opt_is_sup_and_opt_item.get_active(),
'swap_spotlight_and_input': swap_spotlight_item.get_active(),
}
# No-change guard: programmatic updates (settings monitor echoes)
# re-fire 'toggled' after cnfg already holds the values; saving
# again would rewrite the DB and double the settings emission in
# the config's verbose log.
if all(getattr(cnfg, key) == value for key, value in new_values_dct.items()):
return
for key, value in new_values_dct.items():
setattr(cnfg, key, value)
cnfg.save_settings()
GLib.idle_add(load_prefs_submenu_settings) # Queue the update to run in GTK's main loop
###############################################################
# Preferences submenu
prefs_submenu = Gtk.Menu()
prefs_submenu_item = Gtk.MenuItem(label="Preferences")
prefs_submenu_item.set_submenu(prefs_submenu)
main_menu.append(prefs_submenu_item)
altgr_on_menu_key_item = Gtk.CheckMenuItem(label='Alt_Gr on Menu key')
altgr_on_menu_key_item.set_active(cnfg.altgr_on_menu_key)
altgr_on_menu_key_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(altgr_on_menu_key_item)
multi_lang_item = Gtk.CheckMenuItem(label='Alt_Gr on Right Cmd')
multi_lang_item.set_active(cnfg.multi_lang)
multi_lang_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(multi_lang_item)
Enter2Ent_Cmd_item = Gtk.CheckMenuItem(label='Enter is Enter & Cmd')
Enter2Ent_Cmd_item.set_active(cnfg.Enter2Ent_Cmd)
Enter2Ent_Cmd_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(Enter2Ent_Cmd_item)
forced_numpad_item = Gtk.CheckMenuItem(label='Forced Numpad')
forced_numpad_item.set_active(cnfg.forced_numpad)
forced_numpad_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(forced_numpad_item)
media_arrows_fix_item = Gtk.CheckMenuItem(label='Media Arrows Fix')
media_arrows_fix_item.set_active(cnfg.media_arrows_fix)
media_arrows_fix_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(media_arrows_fix_item)
ST3_in_VSCode_item = Gtk.CheckMenuItem(label='Sublime3 in VSCode')
ST3_in_VSCode_item.set_active(cnfg.ST3_in_VSCode)
ST3_in_VSCode_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(ST3_in_VSCode_item)
swap_spotlight_item = Gtk.CheckMenuItem(label='Swap Spotlight & Input Switch')
swap_spotlight_item.set_active(cnfg.swap_spotlight_and_input)
swap_spotlight_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(swap_spotlight_item)
prefs_submenu.append(Gtk.SeparatorMenuItem())
super_tap_passthru_label_item = Gtk.MenuItem(label='--- Super Tap Passthru ---')
super_tap_passthru_label_item.set_sensitive(False)
prefs_submenu.append(super_tap_passthru_label_item)
l_opt_is_sup_and_opt_item = Gtk.CheckMenuItem(label='L_Opt is Super & Opt')
l_opt_is_sup_and_opt_item.set_active(cnfg.l_opt_is_sup_and_opt)
l_opt_is_sup_and_opt_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(l_opt_is_sup_and_opt_item)
l_cmd_is_sup_and_cmd_item = Gtk.CheckMenuItem(label='L_Cmd is Super & Cmd')
l_cmd_is_sup_and_cmd_item.set_active(cnfg.l_cmd_is_sup_and_cmd)
l_cmd_is_sup_and_cmd_item.connect('toggled', save_prefs_settings)
prefs_submenu.append(l_cmd_is_sup_and_cmd_item)
# End of Preferences submenu
###############################################################
###############################################################
# CapsLock submenu
#
# Radio button items for all the available CapsLock modes
def load_capslock_mode_submenu_settings():
cnfg.load_settings()
active_item = capslock_mode_items_dct.get(cnfg.capslock_mode)
if active_item:
set_item_active_thread_safe(active_item, True)
def save_capslock_mode_setting(menu_item, mode):
if not menu_item.get_active():
return
# Programmatic updates (settings monitor echoes, startup load) re-fire
# 'toggled'; cnfg has already auto-reloaded by then, so a no-change
# save here would just write the DB again and double the settings
# emission in the config's verbose log.
if cnfg.capslock_mode == mode:
return
cnfg.capslock_mode = mode
cnfg.save_settings()
load_capslock_mode_submenu_settings()
# CapsLock Mode radio submenu (replaces legacy Caps2Cmd/Caps2Esc_Cmd toggles).
# Items built from the canonical mode tuple; radio group provides exclusivity.
capslock_mode_submenu = Gtk.Menu()
capslock_mode_submenu_item = Gtk.MenuItem(label='CapsLock Mode')
capslock_mode_submenu_item.set_submenu(capslock_mode_submenu)
main_menu.append(capslock_mode_submenu_item)
capslock_mode_items_dct = {}
group_capslock_mode = None
for caps_mode in CAPSLOCK_MODES:
mode_label = CAPSLOCK_MODE_LABELS.get(caps_mode, caps_mode)
mode_item = Gtk.RadioMenuItem.new_with_label(group_capslock_mode, mode_label)
mode_item.connect('toggled', save_capslock_mode_setting, caps_mode)
capslock_mode_submenu.append(mode_item)
capslock_mode_items_dct[caps_mode] = mode_item
if group_capslock_mode is None:
group_capslock_mode = mode_item.get_group()
# End of CapsLock submenu
###############################################################
###############################################################
# Overlays submenu
#
# Built dynamically from OVL_METADATA so that adding a new overlay
# flag requires only updating overlay_context.py — no changes here.
#
# All flags appear in the menu, including user flags. Users who add
# custom overlay-tagged keymaps to their config can enable the matching
# user flag from this menu without restarting the tray.
overlay_items = {} # {OverlayFlag: Gtk.CheckMenuItem} for state sync
def save_overlay_setting(widget, flag):
"""Toggle a single overlay flag bit and save to settings."""
if widget.get_active():
new_mask = cnfg.overlay_mask | flag
else:
new_mask = cnfg.overlay_mask & ~flag
# No-change guard: see save_prefs_settings.
if new_mask == cnfg.overlay_mask:
return
cnfg.overlay_mask = new_mask
cnfg.save_settings()
GLib.idle_add(load_overlay_submenu_settings)
def apply_overlay_preset(widget, preset_value):
"""Replace the entire overlay mask with a preset value."""
# No-change guard: see save_prefs_settings.
if cnfg.overlay_mask == preset_value:
return
cnfg.overlay_mask = preset_value
cnfg.save_settings()
GLib.idle_add(load_overlay_submenu_settings)
def load_overlay_submenu_settings():
"""Reload overlay checkbox states from settings.
Also updates sensitivity for child flags — a child overlay is
greyed out when its required parent is not enabled, signaling
to the user that the child can't be activated independently.
"""
cnfg.load_settings()
for flag, item in overlay_items.items():
set_item_active_thread_safe(item, bool(cnfg.overlay_mask & flag))
parent = get_flag_parent(flag)
if parent is not None:
item.set_sensitive(bool(cnfg.overlay_mask & parent))
overlays_submenu = Gtk.Menu()
overlays_submenu_item = Gtk.MenuItem(label="Overlays")
overlays_submenu_item.set_submenu(overlays_submenu)
main_menu.append(overlays_submenu_item)
# ─── Preset items at top of submenu ───
# One-click switches that replace the entire mask. Not radio items —
# presets just set the mask; users can then toggle individual flags
# without "leaving" any preset.
preset_full_item = Gtk.MenuItem(label="Preset: Full (all built-ins on)")
preset_full_item.connect('activate', apply_overlay_preset, OVL_PRESET_FULL)
overlays_submenu.append(preset_full_item)
preset_minimal_item = Gtk.MenuItem(label="Preset: Minimal (terminal only)")
preset_minimal_item.connect('activate', apply_overlay_preset, OVL_PRESET_MINIMAL)
overlays_submenu.append(preset_minimal_item)
preset_none_item = Gtk.MenuItem(label="Preset: None (everything off)")
preset_none_item.connect('activate', apply_overlay_preset, OVL_PRESET_NONE)
overlays_submenu.append(preset_none_item)
separator_below_presets_item = Gtk.SeparatorMenuItem()
overlays_submenu.append(separator_below_presets_item) #-------------------------#
# ─── Individual flag toggles ───
# Built from metadata in declaration order. All flags shown — users
# who don't use the user slots can simply ignore them.
for _flag, _display_name, _description in OVL_METADATA:
_item = Gtk.CheckMenuItem(label=_display_name)
_item.connect('toggled', save_overlay_setting, _flag)
overlays_submenu.append(_item)
overlay_items[_flag] = _item
# separator_below_overlays_submenu_item = Gtk.SeparatorMenuItem()
# menu.append(separator_below_overlays_submenu_item) #-------------------------#
# End of Overlays submenu
###############################################################
def load_optspec_layout_submenu_settings():
cnfg.load_settings()
layout = cnfg.optspec_layout
if layout == 'US': set_item_active_thread_safe(optspec_us_item, True)
elif layout == 'ABC': set_item_active_thread_safe(optspec_abc_extended_item, True)
elif layout == 'Disabled': set_item_active_thread_safe(optspec_disabled_item, True)
def save_optspec_layout_setting(menu_item, layout):
if not menu_item.get_active():
return
# No-change guard: programmatic updates (startup load, settings
# monitor echoes) re-fire 'toggled' after cnfg already holds the
# value; saving again would rewrite the DB and double the settings
# emission in the config's verbose log.
if cnfg.optspec_layout == layout:
return
cnfg.optspec_layout = layout
cnfg.save_settings()
load_optspec_layout_submenu_settings()
# OptSpec layout submenu
optspec_layout_submenu = Gtk.Menu()
optspec_layout_item = Gtk.MenuItem(label='OptSpec Layout')
optspec_layout_item.set_submenu(optspec_layout_submenu)
main_menu.append(optspec_layout_item)
# Create submenu items using RadioMenuItem
group_optspec = None
optspec_us_item = Gtk.RadioMenuItem.new_with_label(group_optspec, 'US')
optspec_us_item.connect('toggled', save_optspec_layout_setting, 'US')
optspec_layout_submenu.append(optspec_us_item)
group_optspec = optspec_us_item.get_group()
optspec_abc_extended_item = Gtk.RadioMenuItem.new_with_label(group_optspec, 'ABC Extended')
optspec_abc_extended_item.connect('toggled', save_optspec_layout_setting, 'ABC')
optspec_layout_submenu.append(optspec_abc_extended_item)
optspec_disabled_item = Gtk.RadioMenuItem.new_with_label(group_optspec, 'Disabled*')
optspec_disabled_item.connect('toggled', save_optspec_layout_setting, 'Disabled')
optspec_layout_submenu.append(optspec_disabled_item)
def load_kbtype_submenu_settings():
cnfg.load_settings()
kbtype = cnfg.override_kbtype
if kbtype == 'Auto-Adapt': set_item_active_thread_safe(kbtype_auto_adapt_item, True)
elif kbtype == 'Apple': set_item_active_thread_safe(kbtype_apple_item, True)
elif kbtype == 'Chromebook': set_item_active_thread_safe(kbtype_chromebook_item, True)
elif kbtype == 'IBM': set_item_active_thread_safe(kbtype_ibm_item, True)
elif kbtype == 'Windows': set_item_active_thread_safe(kbtype_windows_item, True)
def save_kbtype_setting(menu_item, kbtype):
if not menu_item.get_active():
return
# No-change guard: also prevents the critical notification below
# from re-firing on startup load or settings monitor echoes.
if cnfg.override_kbtype == kbtype:
return
cnfg.override_kbtype = kbtype
cnfg.save_settings()
GLib.idle_add(load_kbtype_submenu_settings)
valid_kbtypes = ['Apple', 'Chromebook', 'IBM', 'Windows']
if cnfg.override_kbtype in valid_kbtypes:
message = ('Overriding keyboard type disables auto-adaptation.\r'
'This is meant as a temporary fix only! See README.')
ntfy.send_notification(message, icon_file_grayscale, urgency='critical')
###############################################################
# Keyboard Type submenu
kbtype_submenu = Gtk.Menu()
kbtype_item = Gtk.MenuItem(label='Keyboard Type')
kbtype_item.set_submenu(kbtype_submenu)
main_menu.append(kbtype_item)
# create submenu items using RadioMenuItem
group_kbtype = None
kbtype_auto_adapt_item = Gtk.RadioMenuItem.new_with_label(group_kbtype, 'Auto-Adapt*')
kbtype_auto_adapt_item.connect('toggled', save_kbtype_setting, 'Auto-Adapt')
kbtype_submenu.append(kbtype_auto_adapt_item)
group_kbtype = kbtype_auto_adapt_item.get_group()
kbtype_apple_item = Gtk.RadioMenuItem.new_with_label(group_kbtype, 'Apple')
kbtype_apple_item.connect('toggled', save_kbtype_setting, 'Apple')
kbtype_submenu.append(kbtype_apple_item)
kbtype_chromebook_item = Gtk.RadioMenuItem.new_with_label(group_kbtype, 'Chromebook')
kbtype_chromebook_item.connect('toggled', save_kbtype_setting, 'Chromebook')
kbtype_submenu.append(kbtype_chromebook_item)
kbtype_ibm_item = Gtk.RadioMenuItem.new_with_label(group_kbtype, 'IBM')
kbtype_ibm_item.connect('toggled', save_kbtype_setting, 'IBM')
kbtype_submenu.append(kbtype_ibm_item)
kbtype_windows_item = Gtk.RadioMenuItem.new_with_label(group_kbtype, 'Windows')
kbtype_windows_item.connect('toggled', save_kbtype_setting, 'Windows')
kbtype_submenu.append(kbtype_windows_item)
separator_below_kbtype_submenu_item = Gtk.SeparatorMenuItem()
main_menu.append(separator_below_kbtype_submenu_item) #-------------------------------------#
###############################################################
# Tools submenu
tools_submenu = Gtk.Menu()
tools_item = Gtk.MenuItem(label='Tools')
tools_item.set_submenu(tools_submenu)
main_menu.append(tools_item)
if not runtime.barebones_config:
preferences_item = Gtk.MenuItem(label="Open Preferences App")
preferences_item.connect("activate", fn_open_preferences)
tools_submenu.append(preferences_item)
open_config_folder_item = Gtk.MenuItem(label="Open Config Folder")
open_config_folder_item.connect("activate", fn_open_config_folder)
tools_submenu.append(open_config_folder_item)
if runtime.is_systemd:
show_services_log_item = Gtk.MenuItem(label="Show Services Log")
show_services_log_item.connect("activate", fn_show_services_log)
tools_submenu.append(show_services_log_item)
separator_above_remove_icon_item = Gtk.SeparatorMenuItem()
main_menu.append(separator_above_remove_icon_item) #-------------------------------------#
def load_autoload_tray_icon_setting():
cnfg.load_settings()
set_item_active_thread_safe(autoload_tray_icon_item, cnfg.autoload_tray_icon)
def fn_save_autoload_tray_icon_setting(widget):
autoload_tray_icon_bool = widget.get_active()
# debug(f'{autoload_tray_icon_setting = }')
cnfg.autoload_tray_icon = autoload_tray_icon_bool
cnfg.save_settings()
load_autoload_tray_icon_setting()
# create or remove the symlink ~/.config/autostart/Toshy_Tray.desktop
autostart_manager.set_tray_icon_autostart(autoload_tray_icon_bool, runtime)
def load_autostart_config_setting():
"""Non-systemd only: sync the "Autostart Toshy" item with the stored preference"""
cnfg.load_settings()
set_item_active_thread_safe(autostart_toshy_item, cnfg.autostart_config_nonsystemd)
def fn_save_autostart_config_setting(widget):
"""Non-systemd only: store the preference and create or remove the autostart entry"""
autostart_config_bool = widget.get_active()
cnfg.autostart_config_nonsystemd = autostart_config_bool
cnfg.save_settings()
load_autostart_config_setting()
# create or remove the symlink ~/.config/autostart/Toshy_Config_Autostart.desktop
autostart_manager.set_config_autostart(autostart_config_bool, runtime)
autostart_submenu_item = Gtk.MenuItem(label="Autostart Options")
autostart_submenu = Gtk.Menu()
# "Autostart Toshy" means the systemd user services on systemd, and the
# config-only process (via an XDG autostart entry) on any other init system.
autostart_toshy_item = Gtk.CheckMenuItem(label="Autostart Toshy")
if runtime.is_systemd:
autostart_toshy_item.set_active( toshy_svc_sessmon_unit_enabled and
toshy_svc_config_unit_enabled )
autostart_toshy_item.connect("toggled", fn_toggle_toshy_svcs_autostart)
else:
autostart_toshy_item.set_active(cnfg.autostart_config_nonsystemd)
autostart_toshy_item.connect("toggled", fn_save_autostart_config_setting)
autostart_submenu.append(autostart_toshy_item)
autoload_tray_icon_item = Gtk.CheckMenuItem(label="Autoload Tray Icon")
autoload_tray_icon_item.set_active(cnfg.autoload_tray_icon)
autoload_tray_icon_item.connect("toggled", fn_save_autoload_tray_icon_setting)
autostart_submenu.append(autoload_tray_icon_item)
autostart_submenu_item.set_submenu(autostart_submenu)
main_menu.append(autostart_submenu_item)
remove_tray_icon_item = Gtk.MenuItem(label="Remove Icon from Tray")
remove_tray_icon_item.connect("activate", fn_remove_tray_icon)
main_menu.append(remove_tray_icon_item)
main_menu.show_all()
def main():
global process_mgr
process_mgr = ProcessManager(TOSHY_PART, TOSHY_PART_NAME)
process_mgr.initialize()
global loop
# On distros known to not use 'systemd', use 'inverse' icon (except on COSMIC)
if DESKTOP_ENV != 'cosmic' and not runtime.is_systemd:
tray_indicator.set_icon_full(icon_file_inverse, "Toshy Tray Icon Inactive")
def on_settings_changed():
"""Callback for when settings change - update GTK UI."""
if not runtime.barebones_config:
GLib.idle_add(load_prefs_submenu_settings)
GLib.idle_add(load_capslock_mode_submenu_settings)
GLib.idle_add(load_optspec_layout_submenu_settings)
GLib.idle_add(load_kbtype_submenu_settings)
GLib.idle_add(load_autoload_tray_icon_setting)
if not runtime.is_systemd:
GLib.idle_add(load_autostart_config_setting)
GLib.idle_add(load_overlay_submenu_settings)
def on_service_status_changed(config_status, session_monitor_status):
"""Callback for when service status changes - update tray icon and labels."""
# Update tray icon based on status
if config_status == 'Active' and session_monitor_status == 'Active':
GLib.idle_add(tray_indicator.set_icon_full, icon_file_active, "Toshy Tray Icon Active")
elif config_status == 'Inactive' and session_monitor_status == 'Inactive':
GLib.idle_add(tray_indicator.set_icon_full, icon_file_inverse, "Toshy Tray Icon Inactive")
else:
GLib.idle_add(tray_indicator.set_icon_full, icon_file_grayscale, "Toshy Tray Icon Undefined")
# Update menu labels
config_label = f' Config: {config_status}'
sessmon_label = f' SessMon: {session_monitor_status}'
GLib.idle_add(lambda: toshy_config_status_item.set_label(config_label))
GLib.idle_add(lambda: session_monitor_status_item.set_label(sessmon_label))
settings_monitor = SettingsMonitor(cnfg, on_settings_changed)
service_monitor = ServiceMonitor(on_service_status_changed)
if shutil.which('systemctl') and runtime.is_systemd:
# Help out the config file user service - only import existing env vars
env_vars_to_check = [
"KDE_SESSION_VERSION",
# "PATH", # Might be causing problem with venv injection in PATH everywhere
"XDG_SESSION_TYPE",
"XDG_SESSION_DESKTOP",
"XDG_CURRENT_DESKTOP",
"DESKTOP_SESSION",
"DISPLAY",
"WAYLAND_DISPLAY",
]
existing_vars = [var for var in env_vars_to_check if var in os.environ]
if existing_vars:
cmd_lst = ["systemctl", "--user", "import-environment"] + existing_vars
subprocess.run(cmd_lst)
service_monitor.start_monitoring()
settings_monitor.start_monitoring()
if not runtime.barebones_config:
# load the settings for the preferences submenu toggle items
load_prefs_submenu_settings()
# load the setting for the CapsLock mode radio submenu
load_capslock_mode_submenu_settings()
# load the settings for the optspec layout submenu
load_optspec_layout_submenu_settings()
# load the settings for the keyboard type submenu
load_kbtype_submenu_settings()
# load the setting for the autostart tray icon item
load_autoload_tray_icon_setting()
# load the setting for the "Autostart Toshy" item (non-systemd only)
if not runtime.is_systemd:
load_autostart_config_setting()
# load the setting for the overlay bitmask submenu
load_overlay_submenu_settings()
# GUI loop event
loop = GLib.MainLoop()
loop.run()
# Gtk.main()
if __name__ == "__main__":
# debug("")
# debug(cnfg) # prints out the __str__ method of Settings class
main()
# End of File #