| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Fenrir TTY screen reader |
| 5 |
# By Chrys, Storm Dragon, and contributors. |
| 6 |
|
| 7 |
from fenrirscreenreader.core import debug |
| 8 |
from fenrirscreenreader.core.i18n import _ |
| 9 |
from fenrirscreenreader.core.settingsData import settings_data |
| 10 |
|
| 11 |
|
| 12 |
class QuickMenuManager: |
| 13 |
|
| 14 |
def __init__(self): |
| 15 |
self.position = 0 |
| 16 |
self.quickMenu = [] |
| 17 |
self.settings = settings_data |
| 18 |
self._module_request_pending = False |
| 19 |
self._voice_requests_pending = set() |
| 20 |
|
| 21 |
def _select_default_voice(self, voices): |
| 22 |
"""Select a sensible default voice from list, preferring user's |
| 23 |
language. |
| 24 |
|
| 25 |
Args: |
| 26 |
voices (list): List of available voice names |
| 27 |
|
| 28 |
Returns: |
| 29 |
str: Selected default voice (matches user language if possible) |
| 30 |
""" |
| 31 |
if not voices: |
| 32 |
return "" |
| 33 |
|
| 34 |
# Get current voice to preserve language preference |
| 35 |
current_voice = self.env["runtime"]["SettingsManager"].get_setting( |
| 36 |
"speech", "voice" |
| 37 |
) |
| 38 |
|
| 39 |
# Get configured language from settings |
| 40 |
configured_lang = self.env["runtime"]["SettingsManager"].get_setting( |
| 41 |
"speech", "language" |
| 42 |
) |
| 43 |
|
| 44 |
# Extract language code from current voice if available |
| 45 |
current_lang = None |
| 46 |
if current_voice: |
| 47 |
# Extract language code (e.g., 'en-gb' from 'en-gb+male') |
| 48 |
current_lang = current_voice.split('+')[0].lower() |
| 49 |
|
| 50 |
# Build preference list: current language, configured language, English |
| 51 |
preferences = [] |
| 52 |
if current_lang: |
| 53 |
preferences.append(current_lang) |
| 54 |
if configured_lang: |
| 55 |
preferences.append(configured_lang.lower()) |
| 56 |
preferences.extend(['en-gb', 'en-us', 'en']) |
| 57 |
|
| 58 |
# Remove duplicates while preserving order |
| 59 |
seen = set() |
| 60 |
preferences = [x for x in preferences |
| 61 |
if not (x in seen or seen.add(x))] |
| 62 |
|
| 63 |
# Try exact matches for preferred languages |
| 64 |
for pref in preferences: |
| 65 |
for voice in voices: |
| 66 |
# Extract language if voice is in "name|lang" format |
| 67 |
voice_to_check = voice |
| 68 |
if "|" in voice: |
| 69 |
_, voice_lang = voice.split("|", 1) |
| 70 |
voice_to_check = voice_lang |
| 71 |
if voice_to_check.lower() == pref: |
| 72 |
return voice |
| 73 |
|
| 74 |
# Try voices starting with preferred language codes |
| 75 |
for pref in preferences: |
| 76 |
for voice in voices: |
| 77 |
# Extract language if voice is in "name|lang" format |
| 78 |
voice_to_check = voice |
| 79 |
if "|" in voice: |
| 80 |
_, voice_lang = voice.split("|", 1) |
| 81 |
voice_to_check = voice_lang |
| 82 |
if voice_to_check.lower().startswith(pref): |
| 83 |
return voice |
| 84 |
|
| 85 |
# Fall back to first available voice |
| 86 |
return voices[0] |
| 87 |
|
| 88 |
def invalidate_speech_cache(self): |
| 89 |
self.env["runtime"]["SpeechDiscoveryManager"].invalidate_cache() |
| 90 |
|
| 91 |
def initialize(self, environment): |
| 92 |
self.env = environment |
| 93 |
|
| 94 |
# Load base menu from config |
| 95 |
menu_string = self.env["runtime"]["SettingsManager"].get_setting( |
| 96 |
"menu", "quick_menu" |
| 97 |
) |
| 98 |
|
| 99 |
# Dynamically add speech-dispatcher specific items |
| 100 |
if self._is_speechd_driver_active(): |
| 101 |
menu_string = self._add_speechd_menu_items(menu_string) |
| 102 |
|
| 103 |
self.load_menu(menu_string) |
| 104 |
|
| 105 |
def shutdown(self): |
| 106 |
pass |
| 107 |
|
| 108 |
def _is_speechd_driver_active(self): |
| 109 |
"""Check if speechdDriver is currently active. |
| 110 |
|
| 111 |
Returns: |
| 112 |
bool: True if speech driver is speechdDriver |
| 113 |
""" |
| 114 |
try: |
| 115 |
driver = self.env["runtime"]["SettingsManager"].get_setting( |
| 116 |
"speech", "driver" |
| 117 |
) |
| 118 |
return driver == "speechdDriver" |
| 119 |
except Exception as e: |
| 120 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 121 |
(f"QuickMenuManager _is_speechd_driver_active: " |
| 122 |
f"Error checking driver: {e}"), |
| 123 |
debug.DebugLevel.ERROR |
| 124 |
) |
| 125 |
return False |
| 126 |
|
| 127 |
def _add_speechd_menu_items(self, menu_string): |
| 128 |
"""Add speech-dispatcher module and voice to quick menu. |
| 129 |
|
| 130 |
Args: |
| 131 |
menu_string (str): Existing menu string from config |
| 132 |
|
| 133 |
Returns: |
| 134 |
str: Updated menu string with module and voice added |
| 135 |
""" |
| 136 |
if not menu_string: |
| 137 |
return "speech#module;speech#voice" |
| 138 |
|
| 139 |
# Check if already present (user manually added) |
| 140 |
if "speech#module" in menu_string or "speech#voice" in menu_string: |
| 141 |
return menu_string |
| 142 |
|
| 143 |
# Add module and voice after existing items |
| 144 |
return f"{menu_string};speech#module;speech#voice" |
| 145 |
|
| 146 |
def load_menu(self, menuString): |
| 147 |
self.position = 0 |
| 148 |
self.quickMenu = [] |
| 149 |
if menuString == "": |
| 150 |
return |
| 151 |
entrys = menuString.split(";") |
| 152 |
for e in entrys: |
| 153 |
entry = e.split("#") |
| 154 |
if len(entry) != 2: |
| 155 |
continue |
| 156 |
try: |
| 157 |
t = self.settings[entry[0]][entry[1]] |
| 158 |
except Exception as e: |
| 159 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 160 |
"QuickMenuManager load_menu: Setting not found " |
| 161 |
+ str(entry) |
| 162 |
+ ": " |
| 163 |
+ str(e), |
| 164 |
debug.DebugLevel.ERROR, |
| 165 |
) |
| 166 |
print(entry[0], entry[1], "not found") |
| 167 |
continue |
| 168 |
self.quickMenu.append({"section": entry[0], "setting": entry[1]}) |
| 169 |
|
| 170 |
def next_entry(self): |
| 171 |
if len(self.quickMenu) == 0: |
| 172 |
return False |
| 173 |
self.position += 1 |
| 174 |
if self.position >= len(self.quickMenu): |
| 175 |
self.position = 0 |
| 176 |
return True |
| 177 |
|
| 178 |
def prev_entry(self): |
| 179 |
if len(self.quickMenu) == 0: |
| 180 |
return False |
| 181 |
self.position -= 1 |
| 182 |
if self.position < 0: |
| 183 |
self.position = len(self.quickMenu) - 1 |
| 184 |
return True |
| 185 |
|
| 186 |
def next_value(self): |
| 187 |
if len(self.quickMenu) == 0: |
| 188 |
return False |
| 189 |
section = self.quickMenu[self.position]["section"] |
| 190 |
setting = self.quickMenu[self.position]["setting"] |
| 191 |
value_string = "" |
| 192 |
try: |
| 193 |
value_string = self.env["runtime"]["SettingsManager"].get_setting( |
| 194 |
section, setting |
| 195 |
) |
| 196 |
except Exception as e: |
| 197 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 198 |
"QuickMenuManager next_value: Error getting setting value: " |
| 199 |
+ str(e), |
| 200 |
debug.DebugLevel.ERROR, |
| 201 |
) |
| 202 |
return False |
| 203 |
|
| 204 |
try: |
| 205 |
if isinstance(self.settings[section][setting], str): |
| 206 |
# Check for special string cycling cases |
| 207 |
if section == "speech" and setting == "module": |
| 208 |
return self.cycle_speech_module("next") |
| 209 |
elif section == "speech" and setting == "voice": |
| 210 |
return self.cycle_speech_voice("next") |
| 211 |
else: |
| 212 |
# Generic strings not supported for cycling |
| 213 |
value = str(value_string) |
| 214 |
return False |
| 215 |
elif isinstance(self.settings[section][setting], bool): |
| 216 |
if value_string not in ["True", "False"]: |
| 217 |
return False |
| 218 |
value = not value |
| 219 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 220 |
section, setting, str(value) |
| 221 |
) |
| 222 |
elif isinstance(self.settings[section][setting], int): |
| 223 |
value = int(value_string) |
| 224 |
value += 1 |
| 225 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 226 |
section, setting, str(value) |
| 227 |
) |
| 228 |
elif isinstance(self.settings[section][setting], float): |
| 229 |
value = float(value_string) |
| 230 |
value += 0.05 |
| 231 |
if value > 1.0: |
| 232 |
value = 1.0 |
| 233 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 234 |
section, setting, str(value)[:4] |
| 235 |
) |
| 236 |
except Exception as e: |
| 237 |
return False |
| 238 |
return True |
| 239 |
|
| 240 |
def prev_value(self): |
| 241 |
if len(self.quickMenu) == 0: |
| 242 |
return False |
| 243 |
section = self.quickMenu[self.position]["section"] |
| 244 |
setting = self.quickMenu[self.position]["setting"] |
| 245 |
value_string = "" |
| 246 |
try: |
| 247 |
value_string = self.env["runtime"]["SettingsManager"].get_setting( |
| 248 |
section, setting |
| 249 |
) |
| 250 |
except Exception as e: |
| 251 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 252 |
"QuickMenuManager prev_value: Error getting setting value: " |
| 253 |
+ str(e), |
| 254 |
debug.DebugLevel.ERROR, |
| 255 |
) |
| 256 |
return False |
| 257 |
try: |
| 258 |
if isinstance(self.settings[section][setting], str): |
| 259 |
# Check for special string cycling cases |
| 260 |
if section == "speech" and setting == "module": |
| 261 |
return self.cycle_speech_module("prev") |
| 262 |
elif section == "speech" and setting == "voice": |
| 263 |
return self.cycle_speech_voice("prev") |
| 264 |
else: |
| 265 |
# Generic strings not supported for cycling |
| 266 |
value = str(value_string) |
| 267 |
return False |
| 268 |
elif isinstance(self.settings[section][setting], bool): |
| 269 |
if value_string not in ["True", "False"]: |
| 270 |
return False |
| 271 |
value = not value |
| 272 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 273 |
section, setting, str(value) |
| 274 |
) |
| 275 |
elif isinstance(self.settings[section][setting], int): |
| 276 |
value = int(value_string) |
| 277 |
value -= 1 |
| 278 |
if value < 0: |
| 279 |
value = 0 |
| 280 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 281 |
section, setting, str(value) |
| 282 |
) |
| 283 |
elif isinstance(self.settings[section][setting], float): |
| 284 |
value = float(value_string) |
| 285 |
value -= 0.05 |
| 286 |
if value < 0.0: |
| 287 |
value = 0.0 |
| 288 |
self.env["runtime"]["SettingsManager"].set_setting( |
| 289 |
section, setting, str(value)[:4] |
| 290 |
) |
| 291 |
except Exception as e: |
| 292 |
return False |
| 293 |
return True |
| 294 |
|
| 295 |
def cycle_speech_module(self, direction): |
| 296 |
if self._module_request_pending: |
| 297 |
return False |
| 298 |
discovery = self.env["runtime"]["SpeechDiscoveryManager"] |
| 299 |
modules = discovery.get_cached_modules() |
| 300 |
if modules is not None: |
| 301 |
return self._continue_module_cycle(direction, modules, False) |
| 302 |
|
| 303 |
self._module_request_pending = True |
| 304 |
self.env["runtime"]["OutputManager"].present_text( |
| 305 |
"Loading speech modules", interrupt=True |
| 306 |
) |
| 307 |
discovery.request_modules( |
| 308 |
lambda found, error: self._continue_module_cycle( |
| 309 |
direction, found, True, error |
| 310 |
) |
| 311 |
) |
| 312 |
return False |
| 313 |
|
| 314 |
def _continue_module_cycle( |
| 315 |
self, direction, modules, announce_result, error="" |
| 316 |
): |
| 317 |
if error: |
| 318 |
self._module_request_pending = False |
| 319 |
self._report_discovery_error("module", error) |
| 320 |
return False |
| 321 |
if not modules: |
| 322 |
self._module_request_pending = False |
| 323 |
self.env["runtime"]["OutputManager"].present_text( |
| 324 |
"No modules available", interrupt=True |
| 325 |
) |
| 326 |
return False |
| 327 |
|
| 328 |
try: |
| 329 |
current_module = self.env["runtime"]["SettingsManager"].get_setting( |
| 330 |
"speech", "module" |
| 331 |
) |
| 332 |
try: |
| 333 |
current_index = ( |
| 334 |
modules.index(current_module) if current_module else 0 |
| 335 |
) |
| 336 |
except ValueError: |
| 337 |
current_index = 0 |
| 338 |
if direction == "next": |
| 339 |
new_index = (current_index + 1) % len(modules) |
| 340 |
else: |
| 341 |
new_index = (current_index - 1) % len(modules) |
| 342 |
new_module = modules[new_index] |
| 343 |
discovery = self.env["runtime"]["SpeechDiscoveryManager"] |
| 344 |
voices = discovery.get_cached_voices(new_module) |
| 345 |
if voices is not None: |
| 346 |
self._module_request_pending = False |
| 347 |
return self._apply_module( |
| 348 |
new_module, voices, announce_result |
| 349 |
) |
| 350 |
|
| 351 |
self._module_request_pending = True |
| 352 |
discovery.request_voices( |
| 353 |
new_module, |
| 354 |
lambda _module, found, voice_error: self._finish_module_cycle( |
| 355 |
new_module, found, voice_error |
| 356 |
), |
| 357 |
) |
| 358 |
return False |
| 359 |
except Exception as error: |
| 360 |
self._module_request_pending = False |
| 361 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 362 |
f"QuickMenuManager cycle_speech_module: Error: {error}", |
| 363 |
debug.DebugLevel.ERROR, |
| 364 |
) |
| 365 |
return False |
| 366 |
|
| 367 |
def _finish_module_cycle(self, module, voices, error): |
| 368 |
self._module_request_pending = False |
| 369 |
if error: |
| 370 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 371 |
f"QuickMenuManager voice discovery failed: {error}", |
| 372 |
debug.DebugLevel.ERROR, |
| 373 |
) |
| 374 |
self._apply_module(module, voices, False) |
| 375 |
self.env["runtime"]["OutputManager"].present_text( |
| 376 |
f"{module}; voice discovery failed", interrupt=True |
| 377 |
) |
| 378 |
return |
| 379 |
self._apply_module(module, voices, True) |
| 380 |
|
| 381 |
def _apply_module(self, module, voices, announce_result): |
| 382 |
settings_manager = self.env["runtime"]["SettingsManager"] |
| 383 |
settings_manager.set_setting("speech", "module", module) |
| 384 |
speech_driver = self.env["runtime"].get("SpeechDriver") |
| 385 |
if speech_driver: |
| 386 |
speech_driver.set_module(module) |
| 387 |
|
| 388 |
if voices: |
| 389 |
default_voice = self._select_default_voice(voices) |
| 390 |
voice_name, voice_language = self._split_voice(default_voice) |
| 391 |
settings_manager.set_setting("speech", "voice", voice_name) |
| 392 |
if speech_driver: |
| 393 |
if voice_language: |
| 394 |
speech_driver.set_language(voice_language) |
| 395 |
speech_driver.set_voice(voice_name) |
| 396 |
|
| 397 |
if announce_result: |
| 398 |
self.env["runtime"]["OutputManager"].present_text( |
| 399 |
module, interrupt=True |
| 400 |
) |
| 401 |
return True |
| 402 |
|
| 403 |
def cycle_speech_voice(self, direction): |
| 404 |
try: |
| 405 |
current_module = self.env["runtime"]["SettingsManager"].get_setting( |
| 406 |
"speech", "module" |
| 407 |
) |
| 408 |
if not current_module: |
| 409 |
self.env["runtime"]["OutputManager"].present_text( |
| 410 |
"No module selected", interrupt=True |
| 411 |
) |
| 412 |
return False |
| 413 |
discovery = self.env["runtime"]["SpeechDiscoveryManager"] |
| 414 |
voices = discovery.get_cached_voices(current_module) |
| 415 |
if voices is not None: |
| 416 |
return self._apply_voice(direction, voices, False) |
| 417 |
if current_module in self._voice_requests_pending: |
| 418 |
return False |
| 419 |
|
| 420 |
self._voice_requests_pending.add(current_module) |
| 421 |
self.env["runtime"]["OutputManager"].present_text( |
| 422 |
f"Loading voices for {current_module}", interrupt=True |
| 423 |
) |
| 424 |
discovery.request_voices( |
| 425 |
current_module, |
| 426 |
lambda module, found, error: self._finish_voice_cycle( |
| 427 |
direction, module, found, error |
| 428 |
), |
| 429 |
) |
| 430 |
return False |
| 431 |
except Exception as error: |
| 432 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 433 |
f"QuickMenuManager cycle_speech_voice: Error: {error}", |
| 434 |
debug.DebugLevel.ERROR, |
| 435 |
) |
| 436 |
return False |
| 437 |
|
| 438 |
def _finish_voice_cycle(self, direction, module, voices, error): |
| 439 |
self._voice_requests_pending.discard(module) |
| 440 |
if error: |
| 441 |
self._report_discovery_error("voice", error) |
| 442 |
return |
| 443 |
self._apply_voice(direction, voices, True) |
| 444 |
|
| 445 |
def _apply_voice(self, direction, voices, announce_result): |
| 446 |
if not voices: |
| 447 |
self.env["runtime"]["OutputManager"].present_text( |
| 448 |
"No voices available", interrupt=True |
| 449 |
) |
| 450 |
return False |
| 451 |
|
| 452 |
settings_manager = self.env["runtime"]["SettingsManager"] |
| 453 |
current_voice = settings_manager.get_setting("speech", "voice") |
| 454 |
current_index = 0 |
| 455 |
for voice_index, voice in enumerate(voices): |
| 456 |
voice_name, _language = self._split_voice(voice) |
| 457 |
if voice == current_voice or voice_name == current_voice: |
| 458 |
current_index = voice_index |
| 459 |
break |
| 460 |
if direction == "next": |
| 461 |
new_index = (current_index + 1) % len(voices) |
| 462 |
else: |
| 463 |
new_index = (current_index - 1) % len(voices) |
| 464 |
|
| 465 |
voice_name, voice_language = self._split_voice(voices[new_index]) |
| 466 |
settings_manager.set_setting("speech", "voice", voice_name) |
| 467 |
speech_driver = self.env["runtime"].get("SpeechDriver") |
| 468 |
if speech_driver: |
| 469 |
if voice_language: |
| 470 |
speech_driver.set_language(voice_language) |
| 471 |
speech_driver.set_voice(voice_name) |
| 472 |
if announce_result: |
| 473 |
self.env["runtime"]["OutputManager"].present_text( |
| 474 |
voice_name, interrupt=True |
| 475 |
) |
| 476 |
return True |
| 477 |
|
| 478 |
@staticmethod |
| 479 |
def _split_voice(voice): |
| 480 |
if "|" in voice: |
| 481 |
return tuple(voice.split("|", 1)) |
| 482 |
return voice, None |
| 483 |
|
| 484 |
def _report_discovery_error(self, kind, error): |
| 485 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 486 |
f"QuickMenuManager {kind} discovery failed: {error}", |
| 487 |
debug.DebugLevel.ERROR, |
| 488 |
) |
| 489 |
self.env["runtime"]["OutputManager"].present_text( |
| 490 |
f"{kind.capitalize()} discovery failed", interrupt=True |
| 491 |
) |
| 492 |
|
| 493 |
def get_current_entry(self): |
| 494 |
if len(self.quickMenu) == 0: |
| 495 |
return "" |
| 496 |
try: |
| 497 |
return ( |
| 498 |
_(self.quickMenu[self.position]["section"]) |
| 499 |
+ " " |
| 500 |
+ _(self.quickMenu[self.position]["setting"]) |
| 501 |
) |
| 502 |
except Exception as e: |
| 503 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 504 |
"QuickMenuManager get_current_entry: Error formatting entry: " |
| 505 |
+ str(e), |
| 506 |
debug.DebugLevel.ERROR, |
| 507 |
) |
| 508 |
return _("setting invalid") |
| 509 |
|
| 510 |
def get_current_value(self): |
| 511 |
if len(self.quickMenu) == 0: |
| 512 |
return "" |
| 513 |
try: |
| 514 |
return self.env["runtime"]["SettingsManager"].get_setting( |
| 515 |
self.quickMenu[self.position]["section"], |
| 516 |
self.quickMenu[self.position]["setting"], |
| 517 |
) |
| 518 |
except Exception as e: |
| 519 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 520 |
"QuickMenuManager get_current_value: Error getting setting value: " |
| 521 |
+ str(e), |
| 522 |
debug.DebugLevel.ERROR, |
| 523 |
) |
| 524 |
return _("setting value invalid") |