Debian Codegraph @

src/fenrirscreenreader/core/commandManager.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 import glob
8 import inspect
9 import os
10 import time
11
12 from fenrirscreenreader.core import debug
13 from fenrirscreenreader.utils import module_utils
14
15 currentdir = os.path.dirname(
16 os.path.realpath(os.path.abspath(inspect.getfile(inspect.currentframe())))
17 )
18 fenrir_path = os.path.dirname(currentdir)
19
20
21 class CommandManager:
22 def __init__(self):
23 pass
24
25 def initialize(self, environment):
26 self.env = environment
27 # commands
28 self.env["commands"] = {}
29 self.env["commandsIgnore"] = {}
30 for command_folder in self.env["general"]["commandFolderList"]:
31 self.env["runtime"]["CommandManager"].load_commands(command_folder)
32 if (
33 self.env["runtime"]["SettingsManager"].get_setting(
34 "general", "command_path"
35 )
36 != ""
37 ):
38 self.env["runtime"]["CommandManager"].load_commands(
39 command_folder,
40 self.env["runtime"]["SettingsManager"].get_setting(
41 "general", "command_path"
42 ),
43 )
44
45 # scripts for scriptKey
46 self.env["runtime"]["CommandManager"].load_script_commands()
47
48 def shutdown(self):
49 for command_folder in self.env["general"]["commandFolderList"]:
50 self.env["runtime"]["CommandManager"].shutdown_commands(
51 command_folder
52 )
53
54 def load_file(self, filepath=""):
55 if filepath == "":
56 return None
57 if not os.path.exists(filepath):
58 self.env["runtime"]["DebugManager"].write_debug_out(
59 "load_file: filepath not exists:" + filepath,
60 debug.DebugLevel.WARNING,
61 )
62 return None
63 if os.path.isdir(filepath):
64 self.env["runtime"]["DebugManager"].write_debug_out(
65 "load_file: filepath is a directory:" + filepath,
66 debug.DebugLevel.ERROR,
67 )
68 return None
69 if not os.access(filepath, os.R_OK):
70 self.env["runtime"]["DebugManager"].write_debug_out(
71 "load_file: filepath not readable:" + filepath,
72 debug.DebugLevel.ERROR,
73 )
74 return None
75
76 try:
77 file_name, file_extension = os.path.splitext(filepath)
78 file_name = file_name.split("/")[-1]
79 if file_name.startswith("__"):
80 return None
81 if file_extension.lower() == ".py":
82 command_mod = module_utils.import_module(file_name, filepath)
83 command = command_mod.command()
84 command.initialize(self.env)
85 self.env["runtime"]["DebugManager"].write_debug_out(
86 "load_file: Load command:" + filepath,
87 debug.DebugLevel.INFO,
88 on_any_level=True,
89 )
90 return command
91 except Exception as e:
92 self.env["runtime"]["DebugManager"].write_debug_out(
93 "load_file: Loading command:" + filepath,
94 debug.DebugLevel.ERROR,
95 )
96 self.env["runtime"]["DebugManager"].write_debug_out(
97 str(e), debug.DebugLevel.ERROR
98 )
99 return None
100
101 def load_commands(self, section="commands", command_path=""):
102 if command_path == "":
103 command_path = fenrir_path + "/commands/"
104 if not command_path.endswith("/"):
105 command_path += "/"
106 command_folder = command_path + section + "/"
107 if not os.path.exists(command_folder):
108 self.env["runtime"]["DebugManager"].write_debug_out(
109 "load_commands: command_folder not exists:" + command_folder,
110 debug.DebugLevel.WARNING,
111 )
112 return
113 if not os.path.isdir(command_folder):
114 self.env["runtime"]["DebugManager"].write_debug_out(
115 "load_commands: command_folder not a directory:"
116 + command_folder,
117 debug.DebugLevel.ERROR,
118 )
119 return
120 if not os.access(command_folder, os.R_OK):
121 self.env["runtime"]["DebugManager"].write_debug_out(
122 "load_commands: command_folder not readable:" + command_folder,
123 debug.DebugLevel.ERROR,
124 )
125 return
126 self.env["commands"][section] = {}
127 self.env["commandsIgnore"][section] = {}
128 command_list = glob.glob(command_folder + "*")
129 for command in command_list:
130 try:
131 file_name, file_extension = os.path.splitext(command)
132 file_name = file_name.split("/")[-1]
133 if file_name.startswith("__"):
134 continue
135 # Skip base classes that shouldn't be loaded as commands
136 if file_name.endswith("_base"):
137 continue
138 # Check if command already exists to prevent duplicate loading
139 if (
140 file_name.upper() in self.env["commands"][section]
141 and self.env["commands"][section][file_name.upper()]
142 is not None
143 ):
144 continue
145 if file_extension.lower() == ".py":
146 command_mod = module_utils.import_module(
147 file_name, command
148 )
149 self.env["commands"][section][
150 file_name.upper()
151 ] = command_mod.command()
152 self.env["commandsIgnore"][section][
153 file_name.upper()[file_name.upper().find("-") + 1 :]
154 + "_IGNORE"
155 ] = False
156 self.env["commands"][section][
157 file_name.upper()
158 ].initialize(self.env)
159 self.env["runtime"]["DebugManager"].write_debug_out(
160 "load_commands: Load command:"
161 + section
162 + "."
163 + file_name.upper(),
164 debug.DebugLevel.INFO,
165 on_any_level=True,
166 )
167 except Exception as e:
168 self.env["runtime"]["DebugManager"].write_debug_out(
169 "load_commands: Loading command:" + command,
170 debug.DebugLevel.ERROR,
171 )
172 self.env["runtime"]["DebugManager"].write_debug_out(
173 str(e), debug.DebugLevel.ERROR
174 )
175 continue
176
177 def get_script_paths(self, script_path=""):
178 if script_path:
179 candidate_paths = [script_path]
180 else:
181 settings_manager = self.env["runtime"]["SettingsManager"]
182 candidate_paths = [
183 settings_manager.get_user_script_path(),
184 settings_manager.get_setting("general", "script_path"),
185 os.path.join(fenrir_path, "../../config/scripts/"),
186 ]
187
188 script_paths = []
189 seen_paths = set()
190 for path in candidate_paths:
191 if not path:
192 continue
193 normalized_path = os.path.abspath(os.path.expanduser(path))
194 if normalized_path in seen_paths:
195 continue
196 script_paths.append(normalized_path)
197 seen_paths.add(normalized_path)
198 return script_paths
199
200 def load_script_commands(self, section="commands", script_path=""):
201 script_paths = self.get_script_paths(script_path)
202 loaded_any_path = False
203 loaded_script_names = set()
204 for path in script_paths:
205 loaded_any_path = (
206 self.load_script_commands_from_path(
207 section, path, loaded_script_names
208 )
209 or loaded_any_path
210 )
211 if not loaded_any_path:
212 self.env["runtime"]["DebugManager"].write_debug_out(
213 "No script paths available:" + str(script_paths),
214 debug.DebugLevel.WARNING,
215 )
216
217 def load_script_commands_from_path(
218 self, section, script_path, loaded_script_names=None
219 ):
220 if loaded_script_names is None:
221 loaded_script_names = set()
222 if not os.path.exists(script_path):
223 return False
224 if not os.path.isdir(script_path):
225 self.env["runtime"]["DebugManager"].write_debug_out(
226 "scriptpath not a directory:" + script_path,
227 debug.DebugLevel.ERROR,
228 )
229 return False
230 if not os.access(script_path, os.R_OK):
231 self.env["runtime"]["DebugManager"].write_debug_out(
232 "scriptpath not readable:" + script_path,
233 debug.DebugLevel.ERROR,
234 )
235 return False
236 command_list = sorted(glob.glob(os.path.join(script_path, "*")))
237 sub_command = fenrir_path + "/commands/commands/subprocess.py"
238 path_script_names = set()
239 for command in command_list:
240 try:
241 if not os.path.isfile(command):
242 continue
243 file_name, file_extension = os.path.splitext(command)
244 file_name = file_name.split("/")[-1]
245 if file_name.startswith("__"):
246 continue
247 command_name = file_name.upper()
248 script_name = self.get_script_name(file_name)
249 if script_name in loaded_script_names:
250 self.env["runtime"]["DebugManager"].write_debug_out(
251 "Skip script with duplicate script name:"
252 + command_name,
253 debug.DebugLevel.INFO,
254 )
255 continue
256 if command_name in self.env["commands"][section]:
257 self.env["runtime"]["DebugManager"].write_debug_out(
258 "Skip script with duplicate command name:"
259 + command_name,
260 debug.DebugLevel.INFO,
261 )
262 continue
263 shortcut = self.get_script_shortcut(file_name)
264 if not shortcut:
265 continue
266 shortcut_key = str(shortcut)
267 if shortcut_key in self.env["bindings"]:
268 self.env["runtime"]["DebugManager"].write_debug_out(
269 "Skip script with duplicate shortcut:"
270 + command_name
271 + " "
272 + shortcut_key,
273 debug.DebugLevel.INFO,
274 )
275 continue
276 command_mod = module_utils.import_module(
277 file_name, sub_command
278 )
279 self.env["commands"][section][command_name] = (
280 command_mod.command()
281 )
282 self.env["commands"][section][command_name].initialize(
283 self.env, command
284 )
285 self.env["bindings"][shortcut_key] = command_name
286 self.env["rawBindings"][shortcut_key] = shortcut
287 path_script_names.add(script_name)
288 self.env["runtime"]["DebugManager"].write_debug_out(
289 "Load script:" + section + "." + command_name,
290 debug.DebugLevel.INFO,
291 on_any_level=True,
292 )
293 except Exception as e:
294 self.env["runtime"]["DebugManager"].write_debug_out(
295 "Loading script:" + file_name, debug.DebugLevel.ERROR
296 )
297 self.env["runtime"]["DebugManager"].write_debug_out(
298 str(e), debug.DebugLevel.ERROR
299 )
300 continue
301 loaded_script_names.update(path_script_names)
302 return True
303
304 def get_script_name(self, file_name):
305 return file_name.upper().split("__-__", 1)[0]
306
307 def get_script_shortcut(self, file_name):
308 comm_settings = file_name.upper().split("__-__")
309 if len(comm_settings) == 1:
310 keys = comm_settings[0]
311 elif len(comm_settings) == 2:
312 keys = comm_settings[1]
313 else:
314 return None
315
316 shortcut_keys = []
317 for key in keys.split("__+__"):
318 key = key.upper()
319 if not key:
320 return None
321 if not self.env["runtime"]["InputManager"].is_valid_key(key):
322 self.env["runtime"]["DebugManager"].write_debug_out(
323 "invalid key : " + key + " script:" + file_name,
324 debug.DebugLevel.WARNING,
325 )
326 return None
327 shortcut_keys.append(key)
328 if "KEY_SCRIPT" not in shortcut_keys:
329 shortcut_keys.append("KEY_SCRIPT")
330 return [1, sorted(shortcut_keys)]
331
332 def shutdown_commands(self, section):
333 # Check if the section exists in the commands dictionary
334 if section not in self.env["commands"]:
335 self.env["runtime"]["DebugManager"].write_debug_out(
336 "shutdown_commands: section not found:" + section,
337 debug.DebugLevel.WARNING,
338 )
339 return
340
341 for command in sorted(self.env["commands"][section]):
342 try:
343 self.env["commands"][section][command].shutdown()
344 del self.env["commands"][section][command]
345 except Exception as e:
346 self.env["runtime"]["DebugManager"].write_debug_out(
347 "Shutdown command:" + section + "." + command,
348 debug.DebugLevel.ERROR,
349 )
350 self.env["runtime"]["DebugManager"].write_debug_out(
351 str(e), debug.DebugLevel.ERROR
352 )
353 continue
354
355 def execute_switch_trigger(self, trigger, unLoadScript, loadScript):
356 if self.env["runtime"]["ScreenManager"].is_ignored_screen():
357 return
358 # unload
359 old_script = unLoadScript
360 if self.command_exists(old_script, trigger):
361 try:
362 self.env["runtime"]["DebugManager"].write_debug_out(
363 "Executing switchtrigger.unload:"
364 + trigger
365 + "."
366 + old_script,
367 debug.DebugLevel.INFO,
368 )
369 self.env["commands"][trigger][old_script].unload()
370 except Exception as e:
371 self.env["runtime"]["DebugManager"].write_debug_out(
372 "Executing trigger:" + trigger + "." + old_script,
373 debug.DebugLevel.ERROR,
374 )
375 self.env["runtime"]["DebugManager"].write_debug_out(
376 str(e), debug.DebugLevel.ERROR
377 )
378 # load
379 new_script = loadScript
380 if self.command_exists(new_script, trigger):
381 try:
382 self.env["runtime"]["DebugManager"].write_debug_out(
383 "Executing switchtrigger.load:"
384 + trigger
385 + "."
386 + new_script,
387 debug.DebugLevel.INFO,
388 )
389 self.env["commands"][trigger][new_script].load()
390 except Exception as e:
391 self.env["runtime"]["DebugManager"].write_debug_out(
392 "Executing trigger:" + trigger + "." + new_script,
393 debug.DebugLevel.ERROR,
394 )
395 self.env["runtime"]["DebugManager"].write_debug_out(
396 str(e), debug.DebugLevel.ERROR
397 )
398
399 def execute_default_trigger(self, trigger, force=False):
400 if not force:
401 if self.env["runtime"]["ScreenManager"].is_ignored_screen():
402 return
403 for command in sorted(self.env["commands"][trigger]):
404 if self.command_exists(command, trigger):
405 try:
406 if self.env["commandsIgnore"][trigger][
407 command[command.find("-") + 1 :] + "_IGNORE"
408 ]:
409 self.env["commandsIgnore"][trigger][
410 command[command.find("-") + 1 :] + "_IGNORE"
411 ] = False
412 self.env["runtime"]["DebugManager"].write_debug_out(
413 "ignore trigger.command:"
414 + trigger
415 + "."
416 + command,
417 debug.DebugLevel.INFO,
418 )
419 else:
420 self.env["runtime"]["DebugManager"].write_debug_out(
421 "Executing trigger.command:"
422 + trigger
423 + "."
424 + command,
425 debug.DebugLevel.INFO,
426 )
427 self.env["commands"][trigger][command].run()
428 except Exception as e:
429 self.env["runtime"]["DebugManager"].write_debug_out(
430 "Executing trigger:"
431 + trigger
432 + "."
433 + command
434 + str(e),
435 debug.DebugLevel.ERROR,
436 )
437
438 def execute_command(self, command, section="commands"):
439 if (
440 self.env["runtime"]["ScreenManager"].is_ignored_screen()
441 and not self.env["runtime"]["HelpManager"].is_tutorial_mode()
442 ):
443 return
444 if self.command_exists(command, section):
445 try:
446 if (
447 self.env["runtime"]["HelpManager"].is_tutorial_mode()
448 and section != "help"
449 ):
450 self.env["runtime"]["DebugManager"].write_debug_out(
451 "Tutorial for command:" + section + "." + command,
452 debug.DebugLevel.INFO,
453 )
454 description = self.get_command_description(
455 command, section
456 )
457 self.env["runtime"]["OutputManager"].present_text(
458 description, interrupt=False
459 )
460 else:
461 self.env["runtime"]["DebugManager"].write_debug_out(
462 "Executing command:" + section + "." + command,
463 debug.DebugLevel.INFO,
464 )
465 self.run_command(command, section)
466 except Exception as e:
467 self.env["runtime"]["DebugManager"].write_debug_out(
468 "Executing command:"
469 + section
470 + "."
471 + command
472 + " "
473 + str(e),
474 debug.DebugLevel.ERROR,
475 )
476
477 def run_command(self, command, section="commands"):
478 if self.command_exists(command, section):
479 try:
480 command_time = time.time()
481 self.env["commandInfo"]["lastCommand"] = command
482 self.env["commandInfo"]["lastCommandSection"] = section
483 self.env["commandInfo"]["lastCommandRunTime"] = command_time
484 self.env["runtime"]["DebugManager"].write_debug_out(
485 "run_command command:" + section + "." + command,
486 debug.DebugLevel.INFO,
487 )
488 self.env["commands"][section][command].run()
489 except Exception as e:
490 self.env["runtime"]["DebugManager"].write_debug_out(
491 "run_command command:"
492 + section
493 + "."
494 + command
495 + " "
496 + str(e),
497 debug.DebugLevel.ERROR,
498 )
499 self.env["commandInfo"]["lastCommandExecutionTime"] = time.time()
500
501 def get_command_description(self, command, section="commands"):
502 if self.command_exists(command, section):
503 try:
504 return self.env["commands"][section][command].get_description()
505 except Exception as e:
506 self.env["runtime"]["DebugManager"].write_debug_out(
507 "command_manager.get_command_description:" + str(e),
508 debug.DebugLevel.ERROR,
509 )
510 self.env["commandInfo"]["lastCommandExecutionTime"] = time.time()
511
512 def command_exists(self, command, section="commands"):
513 try:
514 return command in self.env["commands"][section]
515 except Exception as e:
516 return False
517
518 def get_shortcut_for_command(self, command, formatKeys=False):
519 shortcut = []
520 try:
521 raw_shortcut = list(self.env["bindings"].keys())[
522 list(self.env["bindings"].values()).index(command)
523 ]
524 # prefer numbers for multitap
525 for k in ["2", "3", "4", "5", "6", "7", "8"]:
526 if k in raw_shortcut:
527 formatted_key = k
528 if formatKeys:
529 formatted_key = formatted_key.lower()
530 formatted_key += " times "
531 shortcut.append(formatted_key)
532 raw_shortcut.remove(k)
533 # prefer metha keys
534 for k in [
535 "KEY_FENRIR",
536 "KEY_SCRIPT",
537 "KEY_CTRL",
538 "KEY_SHIFT",
539 "KEY_ALT",
540 "KEY_META",
541 ]:
542 if k in raw_shortcut:
543 formatted_key = k
544 if formatKeys:
545 formatted_key = formatted_key.lower()
546 formatted_key = formatted_key.replace(
547 "key_kp", " keypad "
548 )
549 formatted_key = formatted_key.replace("key_", " ")
550 shortcut.append(formatted_key)
551 raw_shortcut.remove(k)
552 # handle other keys
553 for k in raw_shortcut:
554 formatted_key = k
555 if formatKeys:
556 formatted_key = formatted_key.lower()
557 formatted_key = formatted_key.replace("key_kp", " keypad ")
558 formatted_key = formatted_key.replace("key_", " ")
559 shortcut.append(formatted_key)
560 except Exception as e:
561 pass
562 return shortcut