Debian Codegraph @

src/fenrirscreenreader/core/helpManager.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 ast
8 import copy
9
10 from fenrirscreenreader.core import debug
11 from fenrirscreenreader.core.i18n import _
12
13
14 class HelpManager:
15 ACTIVE_SECTION = "active"
16 UNBOUND_SECTION = "unbound"
17 PLUGINS_SECTION = "plugins"
18 HELP_SECTIONS = (
19 ACTIVE_SECTION,
20 UNBOUND_SECTION,
21 PLUGINS_SECTION,
22 )
23
24 def __init__(self):
25 self.env = None
26 self.help_lists = {
27 self.ACTIVE_SECTION: [],
28 self.UNBOUND_SECTION: [],
29 self.PLUGINS_SECTION: [],
30 }
31 self.help_section = self.ACTIVE_SECTION
32 self.tutorial_list_index = None
33 self.bindings_backup = None
34 self.raw_bindings_backup = None
35 self.capture_degraded = False
36
37 def initialize(self, environment):
38 self.env = environment
39
40 def shutdown(self):
41 if self.is_tutorial_mode():
42 self.set_tutorial_mode(False)
43
44 def toggle_tutorial_mode(self):
45 self.set_tutorial_mode(not self.is_tutorial_mode())
46
47 def set_tutorial_mode(self, tutorial_mode):
48 if tutorial_mode == self.is_tutorial_mode():
49 return True
50 if tutorial_mode and self.env["runtime"]["VmenuManager"].get_active():
51 return False
52
53 if tutorial_mode:
54 self.bindings_backup = self.env["bindings"].copy()
55 self.raw_bindings_backup = copy.deepcopy(
56 self.env["rawBindings"]
57 )
58 self.create_help_dict()
59 self.env["general"]["tutorialMode"] = True
60 self._install_help_bindings()
61 self._refresh_input_bindings()
62 self.capture_degraded = not self.env["runtime"][
63 "InputManager"
64 ].set_help_capture(True)
65 return True
66
67 if not self.env["runtime"]["InputManager"].set_help_capture(False):
68 self.env["runtime"]["DebugManager"].write_debug_out(
69 "HelpManager could not release exclusive input capture",
70 debug.DebugLevel.ERROR,
71 )
72 return False
73 self._restore_bindings()
74 self.env["general"]["tutorialMode"] = False
75 self.capture_degraded = False
76 self.env["runtime"]["InputManager"].reset_input_state()
77 self._refresh_input_bindings()
78 return True
79
80 def _install_help_bindings(self):
81 help_bindings = {
82 str([1, ["KEY_ESC"]]): "TOGGLE_TUTORIAL_MODE",
83 str([1, ["KEY_UP"]]): "PREV_HELP",
84 str([1, ["KEY_DOWN"]]): "NEXT_HELP",
85 str([1, ["KEY_LEFT"]]): "PREV_HELP_SECTION",
86 str([1, ["KEY_RIGHT"]]): "NEXT_HELP_SECTION",
87 str([1, ["KEY_SPACE"]]): "CURR_HELP",
88 }
89 self.env["bindings"].update(help_bindings)
90 for shortcut in help_bindings:
91 self.env["rawBindings"][shortcut] = ast.literal_eval(shortcut)
92
93 def _restore_bindings(self):
94 if self.bindings_backup is not None:
95 self.env["bindings"] = self.bindings_backup
96 if self.raw_bindings_backup is not None:
97 self.env["rawBindings"] = self.raw_bindings_backup
98 self.bindings_backup = None
99 self.raw_bindings_backup = None
100
101 def _refresh_input_bindings(self):
102 try:
103 refresh_grabs = getattr(
104 self.env["runtime"]["InputDriver"], "refresh_grabs", None
105 )
106 if refresh_grabs:
107 refresh_grabs(force=True)
108 except Exception as error:
109 self.env["runtime"]["DebugManager"].write_debug_out(
110 "HelpManager could not refresh input bindings: "
111 + str(error),
112 debug.DebugLevel.ERROR,
113 )
114
115 def is_tutorial_mode(self):
116 if self.env is None:
117 return False
118 return self.env["general"]["tutorialMode"]
119
120 def is_capture_degraded(self):
121 return self.capture_degraded
122
123 def _get_shortcuts_by_command(self):
124 bindings = (
125 self.bindings_backup
126 if self.bindings_backup is not None
127 else self.env["bindings"]
128 )
129 raw_bindings = (
130 self.raw_bindings_backup
131 if self.raw_bindings_backup is not None
132 else self.env["rawBindings"]
133 )
134 shortcuts_by_command = {}
135 for shortcut_key, command in bindings.items():
136 raw_shortcut = raw_bindings.get(shortcut_key)
137 if raw_shortcut is None:
138 try:
139 raw_shortcut = ast.literal_eval(shortcut_key)
140 except (SyntaxError, ValueError):
141 continue
142 shortcuts_by_command.setdefault(command, []).append(
143 copy.deepcopy(raw_shortcut)
144 )
145 return shortcuts_by_command
146
147 def _format_shortcut(self, raw_shortcut):
148 shortcut_repeat, raw_keys = raw_shortcut
149 keys = list(raw_keys)
150 formatted_keys = []
151 repeat_prefix = ""
152 if shortcut_repeat in range(2, 9):
153 repeat_prefix = _("{} times ").format(shortcut_repeat)
154 for key_name in [
155 "KEY_FENRIR",
156 "KEY_SCRIPT",
157 "KEY_CTRL",
158 "KEY_SHIFT",
159 "KEY_ALT",
160 "KEY_META",
161 ]:
162 if key_name in keys:
163 formatted_keys.append(self._format_key_name(key_name))
164 keys.remove(key_name)
165 formatted_keys.extend(self._format_key_name(key) for key in keys)
166 return repeat_prefix + ", ".join(formatted_keys)
167
168 def _format_key_name(self, key_name):
169 formatted_key = key_name.lower()
170 formatted_key = formatted_key.replace("key_kp", "keypad ")
171 formatted_key = formatted_key.replace("key_", "")
172 return _(formatted_key.strip())
173
174 def get_formatted_shortcut_for_command(self, command):
175 shortcuts = self._get_shortcuts_by_command().get(command, [])
176 return "; ".join(
177 self._format_shortcut(shortcut) for shortcut in shortcuts
178 )
179
180 def get_command_help_text(self, command, shortcuts=None):
181 command_name = command.lower().split("__-__")[0].replace("_", " ")
182 if command == "TOGGLE_TUTORIAL_MODE":
183 command_description = _("toggles the tutorial mode")
184 else:
185 command_description = self.env["runtime"][
186 "CommandManager"
187 ].get_command_description(command, section="commands")
188 if command_description == "":
189 command_description = _("no description available")
190 if shortcuts is None:
191 shortcuts = self._get_shortcuts_by_command().get(command, [])
192 command_shortcuts = "; ".join(
193 self._format_shortcut(shortcut) for shortcut in shortcuts
194 )
195 if command_shortcuts == "":
196 command_shortcuts = _("unbound")
197 return _(
198 "{command_name}, Shortcuts {command_shortcuts}, Description "
199 "{command_description}"
200 ).format(
201 command_name=command_name,
202 command_shortcuts=command_shortcuts,
203 command_description=command_description,
204 )
205
206 def create_help_dict(self, section="commands"):
207 shortcuts_by_command = self._get_shortcuts_by_command()
208 self.help_lists = {
209 self.ACTIVE_SECTION: [],
210 self.UNBOUND_SECTION: [],
211 self.PLUGINS_SECTION: [],
212 }
213 for command in sorted(self.env["commands"][section]):
214 command_instance = self.env["commands"][section][command]
215 if not getattr(command_instance, "help_visible", True):
216 continue
217 shortcuts = shortcuts_by_command.get(command, [])
218 help_text = self.get_command_help_text(command, shortcuts)
219 if any("KEY_SCRIPT" in shortcut[1] for shortcut in shortcuts):
220 target_section = self.PLUGINS_SECTION
221 elif shortcuts:
222 target_section = self.ACTIVE_SECTION
223 else:
224 target_section = self.UNBOUND_SECTION
225 self.help_lists[target_section].append(help_text)
226 self.help_section = self.ACTIVE_SECTION
227 self.tutorial_list_index = None
228
229 def get_help_section_name(self):
230 if self.help_section == self.PLUGINS_SECTION:
231 return _("Plugins")
232 if self.help_section == self.UNBOUND_SECTION:
233 return _("Unbound actions")
234 return _("Active actions")
235
236 def select_help_section(self, section):
237 if section not in self.help_lists:
238 return self.get_help_section_name()
239 self.help_section = section
240 self.tutorial_list_index = None
241 return self.get_help_section_name()
242
243 def next_help_section(self):
244 section_index = self.HELP_SECTIONS.index(self.help_section)
245 section_index = (section_index + 1) % len(self.HELP_SECTIONS)
246 return self.select_help_section(self.HELP_SECTIONS[section_index])
247
248 def prev_help_section(self):
249 section_index = self.HELP_SECTIONS.index(self.help_section)
250 section_index = (section_index - 1) % len(self.HELP_SECTIONS)
251 return self.select_help_section(self.HELP_SECTIONS[section_index])
252
253 def get_help_for_current_index(self):
254 entries = self.help_lists[self.help_section]
255 if self.tutorial_list_index is None or not entries:
256 return self.get_help_section_name()
257 return entries[self.tutorial_list_index]
258
259 def next_index(self):
260 entries = self.help_lists[self.help_section]
261 if not entries:
262 self.tutorial_list_index = None
263 return
264 if self.tutorial_list_index is None:
265 self.tutorial_list_index = 0
266 return
267 self.tutorial_list_index = (self.tutorial_list_index + 1) % len(
268 entries
269 )
270
271 def prev_index(self):
272 entries = self.help_lists[self.help_section]
273 if not entries:
274 self.tutorial_list_index = None
275 return
276 if self.tutorial_list_index is None:
277 self.tutorial_list_index = len(entries) - 1
278 return
279 self.tutorial_list_index = (self.tutorial_list_index - 1) % len(
280 entries
281 )