Debian Codegraph @

src/fenrirscreenreader/core/dynamicKeyboardLayoutMenu.py

raw
1 #!/usr/bin/env python3
2
3 import glob
4 import os
5
6 from fenrirscreenreader.core import debug
7
8
9 class DynamicKeyboardLayoutCommand:
10 """Dynamic command class for keyboard layout selection"""
11
12 def __init__(self, layoutName, layoutPath, env):
13 self.layoutName = layoutName
14 self.layoutPath = layoutPath
15 # Extract just the base name without extension for comparison
16 self.layoutBaseName = layoutName
17 self.env = env
18
19 def initialize(self, environment):
20 self.env = environment
21
22 def shutdown(self):
23 pass
24
25 def get_description(self):
26 return f"Set keyboard layout to {self.layoutName}"
27
28 def run(self):
29 try:
30 settingsManager = self.env["runtime"]["SettingsManager"]
31 currentLayout = settingsManager.get_setting(
32 "keyboard", "keyboard_layout"
33 )
34
35 # Check if already set (compare both full path and base name)
36 currentBaseName = os.path.splitext(os.path.basename(currentLayout))[0] if currentLayout else ""
37 if currentBaseName.lower() == self.layoutBaseName.lower() or currentLayout.lower() == self.layoutPath.lower():
38 self.env["runtime"]["OutputManager"].present_text(
39 f"Keyboard layout already set to {self.layoutName}"
40 )
41 return
42
43 # Set the new layout in the config file using full path
44 try:
45 # Update the setting in memory
46 settingsManager.set_setting(
47 "keyboard", "keyboard_layout", self.layoutPath
48 )
49
50 # Save to the actual config file
51 settingsManager.save_settings()
52
53 self.env["runtime"]["OutputManager"].present_text(
54 f"Keyboard layout set to {self.layoutName}. Please restart Fenrir for this change to take effect."
55 )
56 # Play accept sound
57 self.env["runtime"]["OutputManager"].present_text(
58 "", sound_icon="Accept", interrupt=False
59 )
60 except Exception as e:
61 self.env["runtime"]["OutputManager"].present_text(
62 f"Failed to change keyboard layout to {self.layoutName}"
63 )
64 self.env["runtime"]["DebugManager"].write_debug_out(
65 f"DynamicKeyboardLayout: Error setting layout {self.layoutName}: {e}",
66 debug.DebugLevel.ERROR,
67 )
68 # Play error sound
69 self.env["runtime"]["OutputManager"].present_text(
70 "", sound_icon="ErrorSound", interrupt=False
71 )
72
73 except Exception as e:
74 self.env["runtime"]["OutputManager"].present_text(
75 f"Keyboard layout change error: {str(e)}", interrupt=True
76 )
77 self.env["runtime"]["DebugManager"].write_debug_out(
78 f"DynamicKeyboardLayout: Unexpected error for {self.layoutName}: {e}",
79 debug.DebugLevel.ERROR,
80 )
81
82 def set_callback(self, callback):
83 pass
84
85
86 def add_dynamic_keyboard_layout_menus(VmenuManager):
87 """Add dynamic keyboard layout menus to vmenu system"""
88 try:
89 env = VmenuManager.env
90
91 # Get keyboard layout files
92 layouts = get_keyboard_layouts(env)
93 if not layouts:
94 return
95
96 # Create keyboard layouts submenu
97 layoutMenu = {}
98
99 # Add layout commands
100 for layoutName, layoutPath in layouts:
101 layoutCommand = DynamicKeyboardLayoutCommand(
102 layoutName, layoutPath, env
103 )
104 layoutMenu[f"{layoutName} Action"] = layoutCommand
105
106 # Find keyboard menu in existing vmenu structure
107 # If fenrir menu exists, add layouts under it
108 if "fenrir Menu" in VmenuManager.menuDict:
109 fenrirMenu = VmenuManager.menuDict["fenrir Menu"]
110 if "keyboard Menu" in fenrirMenu:
111 # Add dynamic layouts to existing keyboard menu
112 keyboardMenu = fenrirMenu["keyboard Menu"]
113 keyboardMenu["Keyboard Layouts Menu"] = layoutMenu
114 else:
115 # Create keyboard menu with layouts
116 fenrirMenu["keyboard Menu"] = {
117 "Keyboard Layouts Menu": layoutMenu
118 }
119 else:
120 # Create standalone keyboard layouts menu
121 VmenuManager.menuDict["Keyboard Layouts Menu"] = layoutMenu
122
123 except Exception as e:
124 # Use debug manager for error logging
125 if "DebugManager" in env.get("runtime", {}):
126 env["runtime"]["DebugManager"].write_debug_out(
127 f"Error creating dynamic keyboard layout menus: {e}",
128 debug.DebugLevel.ERROR,
129 )
130 else:
131 print(f"Error creating dynamic keyboard layout menus: {e}")
132
133
134 def get_keyboard_layouts(env):
135 """Get available keyboard layouts from keyboard directory"""
136 layouts = []
137
138 try:
139 # Get keyboard directory paths
140 keyboardDirs = []
141
142 # Check system installation path
143 systemKeyboardPath = "/etc/fenrirscreenreader/keyboard/"
144 if os.path.exists(systemKeyboardPath):
145 keyboardDirs.append(systemKeyboardPath)
146
147 # Check source/development path
148 try:
149 import fenrirscreenreader
150
151 fenrirPath = os.path.dirname(fenrirscreenreader.__file__)
152 devKeyboardPath = os.path.join(
153 fenrirPath, "..", "..", "config", "keyboard"
154 )
155 devKeyboardPath = os.path.abspath(devKeyboardPath)
156 if os.path.exists(devKeyboardPath):
157 keyboardDirs.append(devKeyboardPath)
158 except Exception:
159 pass
160
161 # Get current layout setting path
162 try:
163 currentLayoutSetting = env["runtime"]["SettingsManager"].get_setting(
164 "keyboard", "keyboard_layout"
165 )
166 if currentLayoutSetting and os.path.exists(currentLayoutSetting):
167 currentLayoutDir = os.path.dirname(currentLayoutSetting)
168 if currentLayoutDir not in keyboardDirs:
169 keyboardDirs.append(currentLayoutDir)
170 except Exception:
171 pass
172
173 # Scan for .conf files
174 seenLayouts = set()
175 for keyboardDir in keyboardDirs:
176 try:
177 confFiles = glob.glob(os.path.join(keyboardDir, "*.conf"))
178 for confFile in confFiles:
179 layoutName = os.path.splitext(os.path.basename(confFile))[
180 0
181 ]
182 if layoutName not in seenLayouts:
183 seenLayouts.add(layoutName)
184 layouts.append((layoutName, confFile))
185 except Exception as e:
186 if "DebugManager" in env.get("runtime", {}):
187 env["runtime"]["DebugManager"].write_debug_out(
188 f"Error scanning keyboard directory {keyboardDir}: {e}",
189 debug.DebugLevel.WARNING,
190 )
191
192 # Sort layouts alphabetically
193 layouts.sort(key=lambda x: x[0].lower())
194
195 except Exception as e:
196 if "DebugManager" in env.get("runtime", {}):
197 env["runtime"]["DebugManager"].write_debug_out(
198 f"Error getting keyboard layouts: {e}",
199 debug.DebugLevel.ERROR,
200 )
201
202 return layouts