#!/usr/bin/env python3 from fenrirscreenreader.core import debug class DynamicVoiceCommand: """Dynamic command class for voice selection""" def __init__(self, module, voice, env): self.module = module self.voice, separator, self.language = voice.partition("|") if not separator: self.language = "" self.env = env self.test_message = ( "This is a voice test. The quick brown fox jumps over the lazy dog." ) self._test_generation = 0 def initialize(self, environment): self.env = environment def shutdown(self): self._test_generation += 1 def get_description(self): return f"Select voice: {self.voice}" def run(self): self._test_generation += 1 generation = self._test_generation try: self.env["runtime"]["OutputManager"].present_text( f"Testing voice {self.voice} from {self.module}. Please wait.", interrupt=True, ) self.env["runtime"]["SpeechDiscoveryManager"].request_voice_test( self.module, self.voice, self.test_message, lambda succeeded, error: self._finish_voice_test( generation, succeeded, error ), ) except Exception as e: self.env["runtime"]["OutputManager"].present_text( f"Voice selection error: {str(e)}", interrupt=False, flush=False, ) def _finish_voice_test(self, generation, succeeded, error): if generation != self._test_generation: return if not succeeded: self.env["runtime"]["OutputManager"].present_text( f"Voice test failed: {error}", interrupt=False, flush=False, ) return self.env["commandBuffer"]["lastTestedModule"] = self.module self.env["commandBuffer"]["lastTestedVoice"] = self.voice self.env["commandBuffer"]["pendingVoiceModule"] = self.module self.env["commandBuffer"]["pendingVoiceVoice"] = self.voice if self.language: self.env["commandBuffer"]["pendingVoiceLanguage"] = self.language else: self.env["commandBuffer"].pop("pendingVoiceLanguage", None) self.env["commandBuffer"]["voiceTestCompleted"] = True self.env["runtime"]["OutputManager"].present_text( "Voice test completed successfully. " "Navigate to Apply Tested Voice to use this voice.", interrupt=False, flush=False, ) def set_callback(self, callback): pass class DynamicApplyVoiceCommand: """Command to apply the tested voice""" def __init__(self, env): self.env = env def initialize(self, environment): self.env = environment def shutdown(self): pass def get_description(self): return "Apply tested voice to Fenrir" def run(self): try: if not self.env["commandBuffer"].get("voiceTestCompleted", False): self.env["runtime"]["OutputManager"].present_text( "No voice has been tested yet", interrupt=True ) return module = self.env["commandBuffer"]["pendingVoiceModule"] voice = self.env["commandBuffer"]["pendingVoiceVoice"] language = self.env["commandBuffer"].get("pendingVoiceLanguage") self.env["runtime"]["OutputManager"].present_text( f"Applying {voice} from {module}", interrupt=True ) # Debug: Show current settings settings_manager = self.env["runtime"]["SettingsManager"] current_module = settings_manager.get_setting("speech", "module") current_voice = settings_manager.get_setting("speech", "voice") self.env["runtime"]["OutputManager"].present_text( f"Current: {current_voice} from {current_module}", interrupt=False, flush=False, ) # Apply to runtime settings with fallback settings_manager = self.env["runtime"]["SettingsManager"] # Store old values for safety old_driver = settings_manager.get_setting("speech", "driver") old_module = settings_manager.get_setting("speech", "module") old_voice = settings_manager.get_setting("speech", "voice") old_language = settings_manager.get_setting("speech", "language") try: # Apply new settings to runtime only (use set_setting to update # settingArgDict) settings_manager.set_setting( "speech", "driver", "speechdDriver" ) settings_manager.set_setting("speech", "module", module) settings_manager.set_setting("speech", "voice", voice) if language: settings_manager.set_setting( "speech", "language", language ) # Apply settings to speech driver directly if "SpeechDriver" in self.env["runtime"]: speech_driver = self.env["runtime"]["SpeechDriver"] # Set module and voice on the driver instance. speech_driver.set_module(module) if language: speech_driver.set_language(language) speech_driver.set_voice(voice) # Debug: verify what was actually set self.env["runtime"]["OutputManager"].present_text( "Speech driver now has module: " f"{speech_driver.module}, voice: " f"{speech_driver.voice}", interrupt=True, ) # Force application by speaking a test message self.env["runtime"]["OutputManager"].present_text( "Voice applied successfully! You should hear this in " "the new voice.", interrupt=True, ) self.env["runtime"]["OutputManager"].present_text( "Use save settings to make permanent", interrupt=True ) # Clear pending state self.env["commandBuffer"]["voiceTestCompleted"] = False # Exit vmenu after successful application self.env["runtime"]["VmenuManager"].set_active(False) except Exception as e: # Revert on failure settings_manager.set_setting("speech", "driver", old_driver) settings_manager.set_setting("speech", "module", old_module) settings_manager.set_setting("speech", "voice", old_voice) settings_manager.set_setting( "speech", "language", old_language ) # Try to reinitialize with old settings if "SpeechDriver" in self.env["runtime"]: try: speech_driver = self.env["runtime"]["SpeechDriver"] speech_driver.shutdown() speech_driver.initialize(self.env) except Exception as e: self.env["runtime"]["DebugManager"].write_debug_out( "dynamicVoiceMenu: Error reinitializing speech driver: " + str(e), debug.DebugLevel.ERROR, ) self.env["runtime"]["OutputManager"].present_text( f"Failed to apply voice, reverted: {str(e)}", interrupt=False, flush=False, ) except Exception as e: self.env["runtime"]["OutputManager"].present_text( f"Apply voice error: {str(e)}", interrupt=False, flush=False ) def set_callback(self, callback): pass def add_dynamic_voice_menus(vmenu_manager): """Populate cached voice menus and start non-blocking discovery if needed.""" try: env = vmenu_manager.env discovery = env["runtime"]["SpeechDiscoveryManager"] generation = getattr(vmenu_manager, "_voice_menu_generation", 0) + 1 vmenu_manager._voice_menu_generation = generation modules = discovery.get_cached_modules() if modules is None: _install_loading_menu(vmenu_manager) discovery.request_modules( lambda found, error: _request_dynamic_voice_lists( vmenu_manager, generation, found, error, False ) ) return _request_dynamic_voice_lists( vmenu_manager, generation, modules, "", True ) except Exception as error: if "DebugManager" in env["runtime"]: env["runtime"]["DebugManager"].write_debug_out( f"Error creating dynamic voice menus: {error}", debug.DebugLevel.ERROR, ) else: print(f"Error creating dynamic voice menus: {error}") def _request_dynamic_voice_lists( vmenu_manager, generation, modules, error, allow_active ): if generation != getattr(vmenu_manager, "_voice_menu_generation", 0): return if error or not modules: if vmenu_manager.get_active() and not allow_active: vmenu_manager._voice_menu_refresh_pending = True return _install_discovery_error_menu(vmenu_manager) return discovery = vmenu_manager.env["runtime"]["SpeechDiscoveryManager"] selected_modules = modules[:8] voices_by_module = {} missing_modules = [] for module in selected_modules: voices = discovery.get_cached_voices(module) if voices is None: missing_modules.append(module) else: voices_by_module[module] = voices if not missing_modules: _install_dynamic_voice_menu( vmenu_manager, generation, selected_modules, voices_by_module, allow_active, ) return _install_loading_menu(vmenu_manager) remaining_modules = set(missing_modules) def voices_ready(module, voices, _voice_error): if generation != getattr(vmenu_manager, "_voice_menu_generation", 0): return voices_by_module[module] = voices remaining_modules.discard(module) if not remaining_modules: _install_dynamic_voice_menu( vmenu_manager, generation, selected_modules, voices_by_module, False, ) for module in missing_modules: discovery.request_voices(module, voices_ready) def _install_dynamic_voice_menu( vmenu_manager, generation, modules, voices_by_module, allow_active, ): if generation != getattr(vmenu_manager, "_voice_menu_generation", 0): return if vmenu_manager.get_active() and not allow_active: vmenu_manager._voice_menu_refresh_pending = True return env = vmenu_manager.env voice_browser_menu = { "Apply Tested Voice Action": DynamicApplyVoiceCommand(env) } for module in modules: module_menu = {} voices = voices_by_module.get(module, []) for voice in voices: voice_name = voice.split("|", 1)[0] module_menu[f"{voice_name} Action"] = DynamicVoiceCommand( module, voice, env ) if not module_menu: module_menu["No voices available Action"] = create_info_command( f"No voices found for {module}", env ) voice_browser_menu[f"{module} Menu"] = module_menu vmenu_manager.menuDict["Voice Browser Menu"] = voice_browser_menu vmenu_manager._voice_menu_refresh_pending = False def _install_loading_menu(vmenu_manager): env = vmenu_manager.env vmenu_manager.menuDict["Voice Browser Menu"] = { "Loading voices Action": create_info_command( "Voice information is still loading", env ) } def _install_discovery_error_menu(vmenu_manager): env = vmenu_manager.env vmenu_manager.menuDict["Voice Browser Menu"] = { "Voice discovery failed Action": create_info_command( "Voice discovery failed", env ) } def create_info_command(message, env): """Create a simple info command""" class InfoCommand: def __init__(self, message, env): self.message = message self.env = env def initialize(self, environment): pass def shutdown(self): pass def get_description(self): return self.message def run(self): self.env["runtime"]["OutputManager"].present_text( self.message, interrupt=True ) def set_callback(self, callback): pass return InfoCommand(message, env)