Debian Codegraph @

src/fenrirscreenreader/core/outputManager.py

raw
1 #!/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 import re
8 import string
9 import threading
10 import time
11
12 from fenrirscreenreader.core import debug
13 from fenrirscreenreader.core.i18n import _
14 from fenrirscreenreader.utils import line_utils
15
16
17 class OutputManager:
18 def __init__(self):
19 self.last_echo = ""
20 self.interrupt_lock = threading.Lock()
21 self.interrupt_running = False
22 self.interrupt_thread = None
23 self.interrupt_done = None
24 self.interrupt_wait_timeout = 0.1
25 self.speech_driver_lock = threading.Lock()
26 self.speech_driver_lock_timeout = 0.05
27
28 def initialize(self, environment):
29 self.env = environment
30 self.env["runtime"]["SettingsManager"].load_driver(
31 self.env["runtime"]["SettingsManager"].get_setting(
32 "speech", "driver"
33 ),
34 "SpeechDriver",
35 )
36 self.env["runtime"]["SettingsManager"].load_driver(
37 self.env["runtime"]["SettingsManager"].get_setting(
38 "sound", "driver"
39 ),
40 "SoundDriver",
41 )
42
43 def shutdown(self):
44 self.env["runtime"]["SettingsManager"].shutdown_driver("SoundDriver")
45 self.env["runtime"]["SettingsManager"].shutdown_driver("SpeechDriver")
46
47 def present_text(
48 self,
49 text,
50 interrupt=True,
51 sound_icon="",
52 ignore_punctuation=False,
53 announce_capital=False,
54 flush=True,
55 ):
56 if text == "" and sound_icon == "":
57 return
58 if (
59 self.env["runtime"]["SettingsManager"].get_setting_as_bool(
60 "speech", "read_numbers_as_digits"
61 )
62 and len(text.strip()) > 1
63 ):
64 text = re.sub(r"(\d)", r"\1 ", text).rstrip()
65 self.env["runtime"]["DebugManager"].write_debug_out(
66 "present_text:\nsoundIcon:'" + sound_icon + "'\nText:\n" + text,
67 debug.DebugLevel.INFO,
68 )
69 if self.play_sound_icon(sound_icon, interrupt):
70 self.env["runtime"]["DebugManager"].write_debug_out(
71 "sound_icon found", debug.DebugLevel.INFO
72 )
73 return
74 if text == "":
75 return
76 if (len(text) > 1) and (text.strip(string.whitespace) == ""):
77 return
78 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
79 "speech", "enabled"
80 ):
81 speech_history_manager = self.env["runtime"].get(
82 "SpeechHistoryManager"
83 )
84 if speech_history_manager:
85 speech_history_manager.add_text(text)
86 is_capital = self._should_announce_capital(text, announce_capital)
87 use_pitch_for_capital = False
88
89 if is_capital:
90 indicator = self.env["runtime"]["SettingsManager"].get_setting(
91 "speech", "capital_indicator"
92 ).lower()
93
94 if indicator == "none":
95 pass # No indication
96 elif indicator == "beep":
97 # Play beep with interrupt=True to fix stacking
98 self.play_sound_icon("capital", True)
99 elif indicator == "pitch":
100 use_pitch_for_capital = True
101 elif indicator == "both":
102 self.play_sound_icon("capital", True)
103 use_pitch_for_capital = True
104 else:
105 # Default to pitch for unknown values
106 use_pitch_for_capital = True
107
108 self.last_echo = text
109 self.speak_text(
110 text, interrupt, ignore_punctuation, use_pitch_for_capital, flush
111 )
112
113 def _should_announce_capital(self, text, announce_capital):
114 if not announce_capital or not text:
115 return False
116 if len(text) == 1:
117 return text.isupper()
118 if any(char.isspace() for char in text):
119 return False
120 if not any(char.isalpha() for char in text):
121 return False
122 return text.isupper()
123
124 def get_last_echo(self):
125 return self.last_echo
126
127 def process_mid_word_punctuation(self, text):
128 """
129 Process punctuation that appears mid-word to ensure proper pronunciation.
130 Specifically handles dots between word characters (e.g., "settings.conf" -> "settings dot conf")
131 and dots at word beginnings (e.g., ".local" -> "dot local")
132 while preserving sentence-ending periods and other punctuation behavior.
133 """
134 if not text:
135 return text
136
137 # Handle dots at the beginning of words (like .local, .bashrc, .config)
138 # Look for non-word character (or start of string), dot, then word characters
139 text = re.sub(r"(?<!\w)\.(\w+)", r"dot \1", text)
140
141 # Replace dots between word characters in one pass. The old loop
142 # rescanned the full speech string once per remaining dotted word,
143 # which made large directory listings block the event loop for seconds.
144 text = re.sub(r"(?<=\w)\.(?=\w)", " dot ", text)
145
146 return text
147
148 def speak_text(
149 self,
150 text,
151 interrupt=True,
152 ignore_punctuation=False,
153 announce_capital=False,
154 flush=True,
155 ):
156 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
157 "speech", "enabled"
158 ):
159 self.env["runtime"]["DebugManager"].write_debug_out(
160 "Speech disabled in OutputManager.speak_text",
161 debug.DebugLevel.INFO,
162 )
163 return
164 if self.env["runtime"]["SpeechDriver"] is None:
165 self.env["runtime"]["DebugManager"].write_debug_out(
166 "No SpeechDriver in OutputManager.speak_text",
167 debug.DebugLevel.ERROR,
168 )
169 return
170 if interrupt or flush:
171 self.interrupt_output()
172 if not self.speech_driver_lock.acquire(
173 timeout=self.speech_driver_lock_timeout
174 ):
175 self.env["runtime"]["DebugManager"].write_debug_out(
176 "OutputManager.speak_text: Speech driver busy, dropping speech",
177 debug.DebugLevel.WARNING,
178 )
179 return
180 try:
181 try:
182 self.env["runtime"]["SpeechDriver"].set_language(
183 self.env["runtime"]["SettingsManager"].get_setting(
184 "speech", "language"
185 )
186 )
187 except Exception as e:
188 self.env["runtime"]["DebugManager"].write_debug_out(
189 "setting speech language in OutputManager.speak_text",
190 debug.DebugLevel.ERROR,
191 )
192 self.env["runtime"]["DebugManager"].write_debug_out(
193 str(e), debug.DebugLevel.ERROR
194 )
195
196 try:
197 self.env["runtime"]["SpeechDriver"].set_voice(
198 self.env["runtime"]["SettingsManager"].get_setting(
199 "speech", "voice"
200 )
201 )
202 except Exception as e:
203 self.env["runtime"]["DebugManager"].write_debug_out(
204 "Error while setting speech voice in OutputManager.speak_text",
205 debug.DebugLevel.ERROR,
206 )
207 self.env["runtime"]["DebugManager"].write_debug_out(
208 str(e), debug.DebugLevel.ERROR
209 )
210
211 try:
212 if announce_capital:
213 self.env["runtime"]["SpeechDriver"].set_pitch(
214 self.env["runtime"][
215 "SettingsManager"
216 ].get_setting_as_float("speech", "capital_pitch")
217 )
218 else:
219 self.env["runtime"]["SpeechDriver"].set_pitch(
220 self.env["runtime"][
221 "SettingsManager"
222 ].get_setting_as_float("speech", "pitch")
223 )
224 except Exception as e:
225 self.env["runtime"]["DebugManager"].write_debug_out(
226 "setting speech pitch in OutputManager.speak_text",
227 debug.DebugLevel.ERROR,
228 )
229 self.env["runtime"]["DebugManager"].write_debug_out(
230 str(e), debug.DebugLevel.ERROR
231 )
232
233 try:
234 self.env["runtime"]["SpeechDriver"].set_rate(
235 self.env["runtime"][
236 "SettingsManager"
237 ].get_setting_as_float("speech", "rate")
238 )
239 except Exception as e:
240 self.env["runtime"]["DebugManager"].write_debug_out(
241 "setting speech rate in OutputManager.speak_text",
242 debug.DebugLevel.ERROR,
243 )
244 self.env["runtime"]["DebugManager"].write_debug_out(
245 str(e), debug.DebugLevel.ERROR
246 )
247
248 try:
249 self.env["runtime"]["SpeechDriver"].set_module(
250 self.env["runtime"]["SettingsManager"].get_setting(
251 "speech", "module"
252 )
253 )
254 except Exception as e:
255 self.env["runtime"]["DebugManager"].write_debug_out(
256 "setting speech module in OutputManager.speak_text",
257 debug.DebugLevel.ERROR,
258 )
259 self.env["runtime"]["DebugManager"].write_debug_out(
260 str(e), debug.DebugLevel.ERROR
261 )
262
263 try:
264 self.env["runtime"]["SpeechDriver"].set_volume(
265 self.env["runtime"][
266 "SettingsManager"
267 ].get_setting_as_float("speech", "volume")
268 )
269 except Exception as e:
270 self.env["runtime"]["DebugManager"].write_debug_out(
271 "setting speech volume in OutputManager.speak_text ",
272 debug.DebugLevel.ERROR,
273 )
274 self.env["runtime"]["DebugManager"].write_debug_out(
275 str(e), debug.DebugLevel.ERROR
276 )
277
278 try:
279 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
280 "general", "new_line_pause"
281 ):
282 clean_text = text.replace("\n", " , ")
283 else:
284 clean_text = text.replace("\n", " ")
285
286 clean_text = self.env["runtime"][
287 "TextManager"
288 ].replace_head_lines(clean_text)
289 clean_text = self.process_mid_word_punctuation(clean_text)
290 clean_text = self.env["runtime"][
291 "PunctuationManager"
292 ].proceed_punctuation(clean_text, ignore_punctuation)
293 clean_text = re.sub(" +$", " ", clean_text)
294 self.env["runtime"]["SpeechDriver"].speak(
295 clean_text, True, ignore_punctuation
296 )
297 self.env["runtime"]["DebugManager"].write_debug_out(
298 "Speak: " + clean_text, debug.DebugLevel.INFO
299 )
300 except Exception as e:
301 self.env["runtime"]["DebugManager"].write_debug_out(
302 '"speak" in OutputManager.speak_text ',
303 debug.DebugLevel.ERROR,
304 )
305 self.env["runtime"]["DebugManager"].write_debug_out(
306 str(e), debug.DebugLevel.ERROR
307 )
308 finally:
309 self.speech_driver_lock.release()
310
311 def interrupt_output(self, wait=True):
312 interrupt_done, started = self.start_interrupt_output()
313 if wait and started and interrupt_done:
314 interrupt_done.wait(timeout=self.interrupt_wait_timeout)
315
316 def interrupt_output_async(self):
317 self.start_interrupt_output()
318
319 def start_interrupt_output(self):
320 with self.interrupt_lock:
321 if self.interrupt_running:
322 return self.interrupt_done, False
323 self.interrupt_running = True
324 self.interrupt_done = threading.Event()
325 self.interrupt_thread = threading.Thread(
326 target=self.run_interrupt_output,
327 args=(self.interrupt_done,),
328 daemon=True,
329 )
330 interrupt_thread = self.interrupt_thread
331 interrupt_done = self.interrupt_done
332 interrupt_thread.start()
333 return interrupt_done, True
334
335 def run_interrupt_output(self, interrupt_done):
336 try:
337 self.cancel_speech()
338 finally:
339 interrupt_done.set()
340 with self.interrupt_lock:
341 if self.interrupt_done is interrupt_done:
342 self.interrupt_running = False
343
344 def cancel_speech(self):
345 if not self.speech_driver_lock.acquire(
346 timeout=self.speech_driver_lock_timeout
347 ):
348 self.env["runtime"]["DebugManager"].write_debug_out(
349 "OutputManager interrupt_output: Speech driver busy, "
350 "skipping interrupt",
351 debug.DebugLevel.WARNING,
352 )
353 return
354 try:
355 self.env["runtime"]["SpeechDriver"].cancel()
356 self.env["runtime"]["DebugManager"].write_debug_out(
357 "Interrupt speech", debug.DebugLevel.INFO
358 )
359 except Exception as e:
360 self.env["runtime"]["DebugManager"].write_debug_out(
361 "OutputManager interrupt_output: Error canceling speech: "
362 + str(e),
363 debug.DebugLevel.ERROR,
364 )
365 finally:
366 self.speech_driver_lock.release()
367
368 def play_sound_icon(self, sound_icon="", interrupt=True):
369 if sound_icon == "":
370 return False
371 sound_icon = sound_icon.upper()
372 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
373 "sound", "enabled"
374 ):
375 self.env["runtime"]["DebugManager"].write_debug_out(
376 "Sound disabled in OutputManager.play_sound_icon",
377 debug.DebugLevel.INFO,
378 )
379 return False
380
381 try:
382 e = self.env["soundIcons"][sound_icon]
383 except Exception as e:
384 self.env["runtime"]["DebugManager"].write_debug_out(
385 "OutputManager play_sound_icon: SoundIcon does not exist "
386 + sound_icon
387 + ": "
388 + str(e),
389 debug.DebugLevel.WARNING,
390 )
391 return False
392
393 if self.env["runtime"]["SoundDriver"] is None:
394 self.env["runtime"]["DebugManager"].write_debug_out(
395 "No SoundDriver in OutputManager.play_sound_icon: SoundDriver not loaded",
396 debug.DebugLevel.ERROR,
397 )
398 return False
399
400 try:
401 self.env["runtime"]["SoundDriver"].set_volume(
402 self.env["runtime"]["SettingsManager"].get_setting_as_float(
403 "sound", "volume"
404 )
405 )
406 except Exception as e:
407 self.env["runtime"]["DebugManager"].write_debug_out(
408 "OutputManager.play_sound_icon::set_volume: " + str(e),
409 debug.DebugLevel.ERROR,
410 )
411
412 try:
413 self.env["runtime"]["SoundDriver"].play_sound_file(
414 self.env["soundIcons"][sound_icon], interrupt
415 )
416 return True
417 except Exception as e:
418 self.env["runtime"]["DebugManager"].write_debug_out(
419 "OutputManager.play_sound_icon::play_sound_file: " + str(e),
420 debug.DebugLevel.ERROR,
421 )
422 return False
423
424 return False
425
426 def play_sound(self, sound_icon="", interrupt=True):
427 aliases = {
428 "ERROR": "ERRORSCREEN",
429 "ERRORSOUND": "ERRORSCREEN",
430 }
431 normalized_icon = aliases.get(str(sound_icon).upper(), sound_icon)
432 return self.play_sound_icon(normalized_icon, interrupt)
433
434 def play_frequence(self, frequence, duration, interrupt=True):
435 if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
436 "sound", "enabled"
437 ):
438 self.env["runtime"]["DebugManager"].write_debug_out(
439 "Sound disabled in OutputManager.play_frequence",
440 debug.DebugLevel.INFO,
441 )
442 return False
443
444 if frequence < 1 or frequence > 20000:
445 self.env["runtime"]["DebugManager"].write_debug_out(
446 "OutputManager.play_frequence::Filefrequence is out of range:"
447 + str(frequence),
448 debug.DebugLevel.INFO,
449 )
450 return False
451
452 if self.env["runtime"]["SoundDriver"] is None:
453 self.env["runtime"]["DebugManager"].write_debug_out(
454 "No SoundDriver in OutputManager.play_frequence: SoundDriver not loaded",
455 debug.DebugLevel.ERROR,
456 )
457 return False
458
459 try:
460 self.env["runtime"]["SoundDriver"].set_volume(
461 self.env["runtime"]["SettingsManager"].get_setting_as_float(
462 "sound", "volume"
463 )
464 )
465 except Exception as e:
466 self.env["runtime"]["DebugManager"].write_debug_out(
467 "OutputManager.play_sound_icon::set_volume: " + str(e),
468 debug.DebugLevel.ERROR,
469 )
470 adjust_volume = 0.0
471 try:
472 adjust_volume = 1.0 - (frequence / 20000)
473 except Exception as e:
474 self.env["runtime"]["DebugManager"].write_debug_out(
475 "OutputManager play_frequence: Error calculating adjust volume: "
476 + str(e),
477 debug.DebugLevel.ERROR,
478 )
479 if adjust_volume > 9.0:
480 adjust_volume = 9.0
481
482 try:
483 self.env["runtime"]["SoundDriver"].play_frequence(
484 frequence, duration, adjust_volume, interrupt
485 )
486 return True
487 except Exception as e:
488 self.env["runtime"]["DebugManager"].write_debug_out(
489 "OutputManager.play_sound_icon::play_sound_file: " + str(e),
490 debug.DebugLevel.ERROR,
491 )
492 return False
493
494 return False
495
496 def temp_disable_speech(self):
497 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
498 "speech", "enabled"
499 ):
500 self.present_text(
501 _("speech temporary disabled"),
502 sound_icon="SpeechOff",
503 interrupt=True,
504 )
505 self.env["commandBuffer"]["enableSpeechOnKeypress"] = True
506 # Also enable prompt watching for automatic speech restoration
507 if "silenceUntilPrompt" not in self.env["commandBuffer"]:
508 self.env["commandBuffer"]["silenceUntilPrompt"] = False
509 self.env["commandBuffer"]["silenceUntilPrompt"] = True
510 self.env["runtime"]["SettingsManager"].set_setting(
511 "speech",
512 "enabled",
513 str(
514 not self.env["runtime"][
515 "SettingsManager"
516 ].get_setting_as_bool("speech", "enabled")
517 ),
518 )
519 self.interrupt_output()
520
521 def announce_active_cursor(self, interrupt_p=False):
522 if self.env["runtime"]["CursorManager"].is_review_mode():
523 self.present_text(" review cursor ", interrupt=interrupt_p)
524 else:
525 self.present_text(" text cursor ", interrupt=interrupt_p)
526
527 def reset_SpeechDriver(self):
528 """Reset speech driver to clean state - called by settings_manager"""
529 if (
530 "SpeechDriver" in self.env["runtime"]
531 and self.env["runtime"]["SpeechDriver"]
532 ):
533 try:
534 self.env["runtime"]["SpeechDriver"].reset()
535 self.env["runtime"]["DebugManager"].write_debug_out(
536 "Speech driver reset successfully", debug.DebugLevel.INFO
537 )
538 except Exception as e:
539 self.env["runtime"]["DebugManager"].write_debug_out(
540 f"reset_SpeechDriver error: {e}", debug.DebugLevel.ERROR
541 )