diff --git a/_caster.py b/_caster.py index 7aff0eeeb..e6660f9a4 100644 --- a/_caster.py +++ b/_caster.py @@ -1,7 +1,7 @@ -''' +""" main Caster module Created on Jun 29, 2014 -''' +""" import logging import importlib from dragonfly import get_engine, get_current_engine @@ -13,33 +13,48 @@ from castervoice.lib.ctrl.updatecheck import UpdateChecker from castervoice.asynch import hud_support -printer.out("@ - Starting {} with `{}` Engine -\n".format(settings.SOFTWARE_NAME, get_engine().name)) +printer.out( + "@ - Starting {} with `{}` Engine -\n".format( + settings.SOFTWARE_NAME, get_engine().name + ) +) DependencyMan().initialize() # requires nothing settings.initialize() UpdateChecker().initialize() # requires settings/dependencies -EngineConfigEarly() # requires settings/dependencies +EngineConfigEarly() # requires settings/dependencies if control.nexus() is None: from castervoice.lib.ctrl.mgr.loading.load.content_loader import ContentLoader - from castervoice.lib.ctrl.mgr.loading.load.content_request_generator import ContentRequestGenerator - from castervoice.lib.ctrl.mgr.loading.load.reload_fn_provider import ReloadFunctionProvider + from castervoice.lib.ctrl.mgr.loading.load.content_request_generator import ( + ContentRequestGenerator, + ) + from castervoice.lib.ctrl.mgr.loading.load.reload_fn_provider import ( + ReloadFunctionProvider, + ) from castervoice.lib.ctrl.mgr.loading.load.modules_access import SysModulesAccessor + _crg = ContentRequestGenerator() _rp = ReloadFunctionProvider() _sma = SysModulesAccessor() - _content_loader = ContentLoader(_crg, importlib.import_module, _rp.get_reload_fn(), _sma) + _content_loader = ContentLoader( + _crg, importlib.import_module, _rp.get_reload_fn(), _sma + ) control.init_nexus(_content_loader) - EngineConfigLate() # Requires grammars to be loaded and nexus + EngineConfigLate() # Requires grammars to be loaded and nexus if settings.SETTINGS["sikuli"]["enabled"]: from castervoice.asynch.sikuli import sikuli_controller + sikuli_controller.get_instance().bootstrap_start_server_proxy() -if get_current_engine().name != "text": - hud_support.start_hud() +try: + if get_current_engine().name != "text": + hud_support.start_hud() +except ImportError: + pass # HUD is not available dh = printer.get_delegating_handler() -dh.register_handler(hud_support.HudPrintMessageHandler()) # After hud starts -printer.out("\n") # Force update to display text +dh.register_handler(hud_support.HudPrintMessageHandler()) # After hud starts +printer.out("\n") # Force update to display text diff --git a/castervoice/asynch/hmc/h_launch.py b/castervoice/asynch/hmc/h_launch.py index 60fbcf6ec..e25aa4ff9 100644 --- a/castervoice/asynch/hmc/h_launch.py +++ b/castervoice/asynch/hmc/h_launch.py @@ -2,7 +2,7 @@ import subprocess import sys -from xmlrpc.server import SimpleXMLRPCServer +from xmlrpc.server import SimpleXMLRPCServer # pylint: disable=no-name-in-module try: # Style C -- may be imported into Caster, or externally BASE_PATH = os.path.realpath(__file__).rsplit(os.path.sep + "castervoice", 1)[0] @@ -24,7 +24,7 @@ def launch(hmc_type, data=None): def _get_instructions(hmc_type): - if hmc_type == settings.QTTYPE_SETTINGS: + if hmc_type == settings.WXTYPE_SETTINGS: return [ settings.SETTINGS["paths"]["PYTHONW"], settings.SETTINGS["paths"]["SETTINGS_WINDOW_PATH"] @@ -46,15 +46,19 @@ def _get_title(hmc_type): return default + settings.HMC_TITLE_DIRECTORY elif hmc_type == settings.QTYPE_CONFIRM: return default + settings.HMC_TITLE_CONFIRM - elif hmc_type == settings.QTTYPE_SETTINGS: + elif hmc_type == settings.WXTYPE_SETTINGS: return settings.SETTINGS_WINDOW_TITLE + settings.SOFTWARE_VERSION_NUMBER return default def main(): - import PySide2.QtWidgets - from castervoice.asynch.hmc.homunculus import Homunculus - from castervoice.lib.merge.communication import Communicator + # TODO: Remove this try wrapper when CI server supports Qt + try: + import PySide2.QtWidgets + from castervoice.asynch.hmc.homunculus import Homunculus + from castervoice.lib.merge.communication import Communicator + except ImportError: + sys.exit(0) server_address = (Communicator.LOCALHOST, Communicator().com_registry["hmc"]) # Enabled by default logging causes RPC to malfunction when the GUI runs on # pythonw. Explicitly disable logging for the XML server. diff --git a/castervoice/asynch/hud_support.py b/castervoice/asynch/hud_support.py index 8792d18c5..980cad4f1 100644 --- a/castervoice/asynch/hud_support.py +++ b/castervoice/asynch/hud_support.py @@ -1,6 +1,6 @@ import sys, subprocess, json -from dragonfly import CompoundRule, MappingRule, get_current_engine, Function +from dragonfly import CompoundRule, MappingRule, get_current_engine from pathlib import Path @@ -10,17 +10,23 @@ sys.path.append(BASE_PATH) finally: from castervoice.lib import settings - -from castervoice.lib import printer, control, utilities + +from castervoice.lib import printer +from castervoice.lib import control from castervoice.lib.rules_collection import get_instance + def start_hud(): hud = control.nexus().comm.get_com("hud") try: hud.ping() except Exception: - subprocess.Popen([settings.SETTINGS["paths"]["PYTHONW"], - settings.SETTINGS["paths"]["HUD_PATH"]]) + subprocess.Popen( + [ + settings.SETTINGS["paths"]["PYTHONW"], + settings.SETTINGS["paths"]["HUD_PATH"], + ] + ) def show_hud(): @@ -45,8 +51,6 @@ def clear_hud(): hud.clear_hud() except Exception as e: printer.out("Unable to clear hud. Hud not available. \n{}".format(e)) - # clear cmd output if hud unavailable - Function(utilities.clear_log).execute() def show_rules(): @@ -61,25 +65,29 @@ def show_rules(): if any([r.active for r in grammar.rules]): rules = [] for rule in grammar.rules: - if rule.active and not rule.name.startswith('_'): + if rule.active and not rule.name.startswith("_"): if isinstance(rule, CompoundRule): specs = [rule.spec] elif isinstance(rule, MappingRule): - specs = sorted(["{}::{}".format(x, rule._mapping[x]) for x in rule._mapping]) + specs = sorted( + [ + "{}::{}".format(x, rule._mapping[x]) + for x in rule._mapping + ] + ) else: specs = [rule.element.gstring()] - rules.append({ - "name": rule.name, - "exported": rule.exported, - "specs": specs - }) + rules.append( + {"name": rule.name, "exported": rule.exported, "specs": specs} + ) grammars.append({"name": grammar.name, "rules": rules}) grammars.extend(get_instance().serialize()) hud = control.nexus().comm.get_com("hud") try: hud.show_rules(json.dumps(grammars)) except Exception as e: - printer.out("Unable to show hud. Hud not available. \n{}".format(e)) + printer.out("Unable to show hud. Hud not available. \n{}".format(e)) + def hide_rules(): """ @@ -89,14 +97,14 @@ def hide_rules(): try: hud.hide_rules() except Exception as e: - printer.out("Unable to show hud. Hud not available. \n{}".format(e)) - + printer.out("Unable to show hud. Hud not available. \n{}".format(e)) + class HudPrintMessageHandler(printer.BaseMessageHandler): """ - Hud message handler which prints formatted messages to the gui Hud. + Hud message handler which prints formatted messages to the gui Hud. Add symbols as the 1st character in strings utilizing printer.out - + @ Purple arrow - Bold Text - Important Info # Red arrow - Plain text - Caster Info $ Blue arrow - Plain text - Commands/Dictation @@ -105,28 +113,27 @@ class HudPrintMessageHandler(printer.BaseMessageHandler): def __init__(self): super(HudPrintMessageHandler, self).__init__() self.hud = control.nexus().comm.get_com("hud") - self.is_hud_active = False + self.exception = False try: if get_current_engine().name != "text": - self.hud.ping() # HUD running? - self.is_hud_active = True + self.hud.ping() # HUD running? except Exception as e: - self.is_hud_active = False + self.exception = True printer.out("Hud not available. \n{}".format(e)) def handle_message(self, items): - if self.is_hud_active is True: + if self.exception is False: # The timeout with the hud can interfere with the dragonfly speech recognition loop. # This appears as a stutter in recognition. - # This stutter only happens to end user once, while self.hud.ping() is executing. - # is_hud_active is False if the hud is not available/text engine + # Exceptions are tracked so this stutter only happens to end user once. + # Make exception if the hud is not available/python 2/text engine # TODO: handle raising exception gracefully try: self.hud.send("\n".join([str(m) for m in items])) except Exception as e: # If an exception, print is managed by SimplePrintMessageHandler - self.is_hud_active = False + self.exception = True printer.out("Hud not available. \n{}".format(e)) - raise("") # pylint: disable=raising-bad-type + raise ("") # pylint: disable=raising-bad-type else: - raise("") # pylint: disable=raising-bad-type \ No newline at end of file + raise ("") # pylint: disable=raising-bad-type diff --git a/castervoice/lib/ctrl/configure_engine.py b/castervoice/lib/ctrl/configure_engine.py index 6446f342c..a0ec82339 100644 --- a/castervoice/lib/ctrl/configure_engine.py +++ b/castervoice/lib/ctrl/configure_engine.py @@ -1,5 +1,9 @@ import time from dragonfly import get_current_engine, register_recognition_callback, RecognitionObserver +<<<<<<< HEAD +======= +from castervoice.lib.ctrl.mgr.engine_manager import EngineModesManager +>>>>>>> 087ae2a0 (Add HUD (#773)) from castervoice.lib import settings from castervoice.lib import printer diff --git a/castervoice/lib/settings.py b/castervoice/lib/settings.py index 002bf6e97..c8a03d7d3 100644 --- a/castervoice/lib/settings.py +++ b/castervoice/lib/settings.py @@ -49,20 +49,31 @@ def _get_platform_information(): """Return a dictionary containing platform-specific information.""" import sysconfig + system_information = {"platform": sysconfig.get_platform()} system_information.update({"python version": sys.version_info}) if sys.platform == "win32": system_information.update({"binary path": sys.exec_prefix}) system_information.update( - {"main binary": str(Path(sys.exec_prefix).joinpath("python.exe"))}) + {"main binary": str(Path(sys.exec_prefix).joinpath("python.exe"))} + ) system_information.update( - {"hidden console binary": str(Path(sys.exec_prefix).joinpath("pythonw.exe"))}) + { + "hidden console binary": str( + Path(sys.exec_prefix).joinpath("pythonw.exe") + ) + } + ) else: - system_information.update({"binary path": str(Path(sys.exec_prefix).joinpath(sys.exec_prefix).joinpath("bin"))}) - system_information.update( - {"main binary": sys.executable}) system_information.update( - {"hidden console binary": sys.executable}) + { + "binary path": str( + Path(sys.exec_prefix).joinpath(sys.exec_prefix).joinpath("bin") + ) + } + ) + system_information.update({"main binary": sys.executable}) + system_information.update({"hidden console binary": sys.executable}) return system_information @@ -71,15 +82,15 @@ def get_filename(): def _validate_engine_path(): - ''' + """ Validates path 'Engine Path' in settings.toml - ''' - if not sys.platform.startswith('win'): - return '' + """ + if not sys.platform.startswith("win"): + return "" try: from natlink import isNatSpeakRunning # pylint: disable=import-error except ImportError: - return '' + return "" if os.path.isfile(_SETTINGS_PATH): with io.open(_SETTINGS_PATH, "rt", encoding="utf-8") as toml_file: data = tomlkit.loads(toml_file.read()).value @@ -92,20 +103,26 @@ def _validate_engine_path(): data["paths"]["ENGINE_PATH"] = engine_path try: formatted_data = str(tomlkit.dumps(data)) - with io.open(_SETTINGS_PATH, "w", encoding="utf-8") as toml_file: + with io.open( + _SETTINGS_PATH, "w", encoding="utf-8" + ) as toml_file: toml_file.write(formatted_data) printer.out("Setting engine path to {}".format(engine_path)) except Exception as e: - printer.out("Error saving settings file {} {} ".format(e, _SETTINGS_PATH)) + printer.out( + "Error saving settings file {} {} ".format( + e, _SETTINGS_PATH + ) + ) return engine_path else: return _find_natspeak() def _find_natspeak(): - ''' + """ Finds engine 'natspeak.exe' path and verifies supported DNS versions via Windows Registry. - ''' + """ try: import winreg @@ -114,50 +131,62 @@ def _find_natspeak(): return "" printer.out("Searching Windows Registry For DNS...") - proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower() + proc_arch = os.environ["PROCESSOR_ARCHITECTURE"].lower() try: - proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower() + proc_arch64 = os.environ["PROCESSOR_ARCHITEW6432"].lower() except KeyError: proc_arch64 = False - if proc_arch == 'x86' and not proc_arch64: + if proc_arch == "x86" and not proc_arch64: arch_keys = {0} - elif proc_arch == 'x86' or proc_arch == 'amd64': + elif proc_arch == "x86" or proc_arch == "amd64": arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY} else: raise Exception("Unhandled arch: %s" % proc_arch) for arch_key in arch_keys: - key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", - 0, winreg.KEY_READ | arch_key) + key = winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", + 0, + winreg.KEY_READ | arch_key, + ) for i in xrange(0, winreg.QueryInfoKey(key)[0]): skey_name = winreg.EnumKey(key, i) skey = winreg.OpenKey(key, skey_name) - DisplayName, Publisher, DisplayVersion, InstallLocation = 'null' + DisplayName, Publisher, DisplayVersion, InstallLocation = "null" try: - DisplayName = winreg.QueryValueEx(skey, 'DisplayName')[0] - Publisher = winreg.QueryValueEx(skey, 'Publisher')[0] - DisplayVersion = winreg.QueryValueEx(skey, 'DisplayVersion')[0] - InstallLocation = winreg.QueryValueEx(skey, 'InstallLocation')[0] + DisplayName = winreg.QueryValueEx(skey, "DisplayName")[0] + Publisher = winreg.QueryValueEx(skey, "Publisher")[0] + DisplayVersion = winreg.QueryValueEx(skey, "DisplayVersion")[0] + InstallLocation = winreg.QueryValueEx(skey, "InstallLocation")[0] except OSError as error: - if error.errno == 2: # Suppresses '[Error 2] The system cannot find the file specified' + if ( + error.errno == 2 + ): # Suppresses '[Error 2] The system cannot find the file specified' pass else: printer.out(error) finally: skey.Close() - if Publisher == "Nuance Communications Inc." and "Dragon" in DisplayName: + if ( + Publisher == "Nuance Communications Inc." + and "Dragon" in DisplayName + ): DnsVersion = int(str(DisplayVersion)[:2]) if DnsVersion >= 13: - engine_path = str(Path(InstallLocation).joinpath("Program/natspeak.exe")) + engine_path = str( + Path(InstallLocation).joinpath("Program/natspeak.exe") + ) if os.path.isfile(engine_path): printer.out("Search Complete.") return engine_path else: printer.out( - "Dragon Naturally Speaking {} is not supported by Caster. Only versions 13 and above are supported. Purchase Dragon Naturally Speaking 13 or above" - .format(DnsVersion)) + "Dragon Naturally Speaking {} is not supported by Caster. Only versions 13 and above are supported. Purchase Dragon Naturally Speaking 13 or above".format( + DnsVersion + ) + ) printer.out("Cannot find dragon engine path") return "" @@ -185,16 +214,22 @@ def _init(path): with io.open(path, "rt", encoding="utf-8") as f: result = tomlkit.loads(f.read()).value except ValueError as e: - printer.out("\n\n {} while loading settings file: {} \n\n".format(repr(e), path)) + printer.out( + "\n\n {} while loading settings file: {} \n\n".format(repr(e), path) + ) printer.out(sys.exc_info()) except IOError as e: - printer.out("\n\n {} while loading settings file: {} \nAttempting to recover...\n\n".format(repr(e), path)) + printer.out( + "\n\n {} while loading settings file: {} \nAttempting to recover...\n\n".format( + repr(e), path + ) + ) default_settings = _get_defaults() result, num_default_added = _deep_merge_defaults(result, default_settings) if num_default_added > 0: printer.out("Default settings values added: {} ".format(num_default_added)) _save(result, _SETTINGS_PATH) - result['paths'] = {k: os.path.expandvars(v) for k, v in result['paths'].items()} + result["paths"] = {k: os.path.expandvars(v) for k, v in result["paths"].items()} return result @@ -209,7 +244,9 @@ def _deep_merge_defaults(data, defaults): # If the key is in the data, use that, but call recursivly if it's a dict. if key in data: if isinstance(data[key], Mapping): - child_data, child_changes = _deep_merge_defaults(data[key], default_value) + child_data, child_changes = _deep_merge_defaults( + data[key], default_value + ) data[key] = child_data changes += child_changes else: @@ -233,150 +270,119 @@ def _get_defaults(): ahk_path_default = "C:/Program Files/AutoHotkey/AutoHotkey.exe" if not os.path.isfile(ahk_path_default): ahk_path_default = "" - - if sys.platform == "win32": - terminal_loading_time = 5 + + if sys.platform == "win32": + terminal_loading_time = 5 else: terminal_loading_time = 1 return { "paths": { - "BASE_PATH": - _BASE_PATH, - "USER_DIR": - _USER_DIR, + "BASE_PATH": _BASE_PATH, + "USER_DIR": _USER_DIR, # pathlib string conversion can be removed once pathlib is utilized throughout Caster. # DATA - "SM_BRINGME_PATH": - str(Path(_USER_DIR).joinpath("settings/sm_bringme.toml")), - "SM_ALIAS_PATH": - str(Path(_USER_DIR).joinpath("data/sm_aliases.toml")), - "SM_CHAIN_ALIAS_PATH": - str(Path(_USER_DIR).joinpath("data/sm_chain_aliases.toml")), - "SM_HISTORY_PATH": - str(Path(_USER_DIR).joinpath("data/sm_history.toml")), - "RULES_CONFIG_PATH": - str(Path(_USER_DIR).joinpath("settings/rules.toml")), - "TRANSFORMERS_CONFIG_PATH": - str(Path(_USER_DIR).joinpath("settings/transformers.toml")), - "HOOKS_CONFIG_PATH": - str(Path(_USER_DIR).joinpath("settings/hooks.toml")), - "COMPANION_CONFIG_PATH": - str(Path(_USER_DIR).joinpath("settings/companion_config.toml")), - "DLL_PATH": - str(Path(_BASE_PATH).joinpath("lib/dll/")), - "GDEF_FILE": - str(Path(_USER_DIR).joinpath("caster_user_content/transformers/words.txt")), - "LOG_PATH": - str(Path(_USER_DIR).joinpath("log.txt")), - "SAVED_CLIPBOARD_PATH": - str(Path(_USER_DIR).joinpath("data/clipboard.json")), - "SIKULI_SCRIPTS_PATH": - str(Path(_USER_DIR).joinpath("sikuli")), - "GIT_REPO_LOCAL_REMOTE_PATH": - str(Path(_USER_DIR).joinpath("settings/git_repo_local_to_remote_match.toml")), - "GIT_REPO_LOCAL_REMOTE_DEFAULT_PATH": - str(Path(_BASE_PATH).joinpath("bin/share/git_repo_local_to_remote_match.toml.defaults")), - + "SM_BRINGME_PATH": str( + Path(_USER_DIR).joinpath("settings/sm_bringme.toml") + ), + "SM_ALIAS_PATH": str(Path(_USER_DIR).joinpath("data/sm_aliases.toml")), + "SM_CHAIN_ALIAS_PATH": str( + Path(_USER_DIR).joinpath("data/sm_chain_aliases.toml") + ), + "SM_HISTORY_PATH": str(Path(_USER_DIR).joinpath("data/sm_history.toml")), + "RULES_CONFIG_PATH": str(Path(_USER_DIR).joinpath("settings/rules.toml")), + "TRANSFORMERS_CONFIG_PATH": str( + Path(_USER_DIR).joinpath("settings/transformers.toml") + ), + "HOOKS_CONFIG_PATH": str(Path(_USER_DIR).joinpath("settings/hooks.toml")), + "COMPANION_CONFIG_PATH": str( + Path(_USER_DIR).joinpath("settings/companion_config.toml") + ), + "DLL_PATH": str(Path(_BASE_PATH).joinpath("lib/dll/")), + "GDEF_FILE": str( + Path(_USER_DIR).joinpath("caster_user_content/transformers/words.txt") + ), + "LOG_PATH": str(Path(_USER_DIR).joinpath("log.txt")), + "SAVED_CLIPBOARD_PATH": str( + Path(_USER_DIR).joinpath("data/clipboard.json") + ), + "SIKULI_SCRIPTS_PATH": str(Path(_USER_DIR).joinpath("sikuli")), + "GIT_REPO_LOCAL_REMOTE_PATH": str( + Path(_USER_DIR).joinpath("settings/git_repo_local_to_remote_match.toml") + ), + "GIT_REPO_LOCAL_REMOTE_DEFAULT_PATH": str( + Path(_BASE_PATH).joinpath( + "bin/share/git_repo_local_to_remote_match.toml.defaults" + ) + ), # REMOTE_DEBUGGER_PATH is the folder in which pydevd.py can be found - "REMOTE_DEBUGGER_PATH": - str(Path("")), - + "REMOTE_DEBUGGER_PATH": str(Path("")), # SIKULIX EXECUTABLES - "SIKULI_IDE": - str(Path("")), - "SIKULI_RUNNER": - str(Path("")), - + "SIKULI_IDE": str(Path("")), + "SIKULI_RUNNER": str(Path("")), # EXECUTABLES - "AHK_PATH": - str(Path(ahk_path_default)), - "DOUGLAS_PATH": - str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), - "ENGINE_PATH": - _validate_engine_path(), - "HOMUNCULUS_PATH": - str(Path(_BASE_PATH).joinpath("asynch/hmc/h_launch.py")), - "HUD_PATH": - str(Path(_BASE_PATH).joinpath("asynch/hud.py")), - "LEGION_PATH": - str(Path(_BASE_PATH).joinpath("asynch/mouse/legion.py")), - "MEDIA_PATH": - str(Path(_BASE_PATH).joinpath("bin/media")), - "RAINBOW_PATH": - str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), - "REBOOT_PATH": - str(Path(_BASE_PATH).joinpath("bin/reboot.bat")), - "REBOOT_PATH_WSR": - str(Path(_BASE_PATH).joinpath("bin/reboot_wsr.bat")), - "SETTINGS_WINDOW_PATH": - str(Path(_BASE_PATH).joinpath("asynch/settingswindow.py")), - "SIKULI_SERVER_PATH": - str(Path(_BASE_PATH).joinpath("asynch/sikuli/server/xmlrpc_server.sikuli")), - "SUDOKU_PATH": - str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), - "WSR_PATH": - str(Path("C:/Windows/Speech/Common/sapisvr.exe")), - "TERMINAL_PATH": - str(Path(terminal_path_default)), - + "AHK_PATH": str(Path(ahk_path_default)), + "DOUGLAS_PATH": str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), + "ENGINE_PATH": _validate_engine_path(), + "HOMUNCULUS_PATH": str(Path(_BASE_PATH).joinpath("asynch/hmc/h_launch.py")), + "HUD_PATH": str(Path(_BASE_PATH).joinpath("asynch/hud.py")), + "LEGION_PATH": str(Path(_BASE_PATH).joinpath("asynch/mouse/legion.py")), + "MEDIA_PATH": str(Path(_BASE_PATH).joinpath("bin/media")), + "RAINBOW_PATH": str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), + "REBOOT_PATH": str(Path(_BASE_PATH).joinpath("bin/reboot.bat")), + "REBOOT_PATH_WSR": str(Path(_BASE_PATH).joinpath("bin/reboot_wsr.bat")), + "SETTINGS_WINDOW_PATH": str( + Path(_BASE_PATH).joinpath("asynch/settingswindow.py") + ), + "SIKULI_SERVER_PATH": str( + Path(_BASE_PATH).joinpath("asynch/sikuli/server/xmlrpc_server.sikuli") + ), + "SUDOKU_PATH": str(Path(_BASE_PATH).joinpath("asynch/mouse/grids.py")), + "WSR_PATH": str(Path("C:/Windows/Speech/Common/sapisvr.exe")), + "TERMINAL_PATH": str(Path(terminal_path_default)), # CCR - "CONFIGDEBUGTXT_PATH": - str(Path(_USER_DIR).joinpath("data/configdebug.txt")), - + "CONFIGDEBUGTXT_PATH": str( + Path(_USER_DIR).joinpath("data/configdebug.txt") + ), # PYTHON - "PYTHONW": - SYSTEM_INFORMATION["hidden console binary"], + "PYTHONW": SYSTEM_INFORMATION["hidden console binary"], }, - # Speech recognition engine settings "engine": { - "default_engine_mode": False, + "default_engine_mode": False, "engine_mode": "normal", - "default_mic": False, + "default_mic": False, "mic_mode": "on", - "mic_sleep_timer_on": True, - "mic_sleep_timer": 300, # Seconds before microphone goes to sleep after last successful recognition. + "mic_sleep_timer_on": True, + "mic_sleep_timer": 300, # Seconds before microphone goes to sleep after last successful recognition. # Note: No greater than 5 minutes or 300 seconds unless DPI/DPI sleep settings are adjusted }, - # python settings "python": { - "automatic_settings": - True, # Set to false to manually set "version" and "pip" below. - "version": - "python", # Depending Python setup (python, python2, python2.7, py, py -2) - "pip": "pip" # Depending on PIP setup (pip ,pip2, pip2.7) + "automatic_settings": True, # Set to false to manually set "version" and "pip" below. + "version": "python", # Depending Python setup (python, python2, python2.7, py, py -2) + "pip": "pip", # Depending on PIP setup (pip ,pip2, pip2.7) }, - # sikuli settings - "sikuli": { - "enabled": False, - "version": "" - }, - + "sikuli": {"enabled": False, "version": ""}, # gitbash settings # This really should be labelled "terminal" but was named when caster was Windows only. "gitbash": { "loading_time": terminal_loading_time, # the time to initialise the git bash window in seconds - "fetching_time": 3 # the time to fetch a github repository in seconds + "fetching_time": 3, # the time to fetch a github repository in seconds }, - # node rules path "Tree_Node_Path": { "SM_CSS_TREE_PATH": str(Path(_USER_DIR).joinpath("data/sm_css_tree.toml")), }, - "online": { "online_mode": True, # False disables updates "last_update_date": "None", - "update_interval": 7 # Days + "update_interval": 7, # Days }, - # Default enabled hooks: Use hook class name "hooks": { - "default_hooks": ['PrinterHook', 'RulesLoadedHook'], + "default_hooks": ["PrinterHook", "RulesLoadedHook"], }, - # miscellaneous section "miscellaneous": { "dev_commands": True, @@ -390,14 +396,13 @@ def _get_defaults(): "use_aenea": False, "hmc": True, "ccr_on": True, - "dragonfly_pause_default": 0.003, # dragonfly _pause_default 0.02 is too slow! Caster default 0.003 + "dragonfly_pause_default": 0.003, # dragonfly _pause_default 0.02 is too slow! Caster default 0.003 }, # Grammar reloading section "grammar_reloading": { "reload_trigger": "timer", # manual or timer "reload_timer_seconds": 5, # seconds }, - "formats": { "_default": { "text_format": [5, 0], @@ -443,7 +448,7 @@ def _get_defaults(): "text_format": [5, 3], "secondary_format": [1, 3], }, - } + }, } @@ -464,7 +469,7 @@ def settings(key_path, default_value=None): return value -def save_config(paths = False): +def save_config(paths=False): """ Save the current in-memory settings to disk """ @@ -476,20 +481,25 @@ def save_config(paths = False): with io.open(_SETTINGS_PATH, "rt", encoding="utf-8") as f: result = tomlkit.loads(f.read()).value except ValueError as e: - printer.out("\n\n {} while loading settings file: {} \n\n".format(repr(e), _SETTINGS_PATH)) + printer.out( + "\n\n {} while loading settings file: {} \n\n".format( + repr(e), _SETTINGS_PATH + ) + ) printer.out(sys.exc_info()) except IOError as e: - printer.out("\n\n {} while loading settings file: {} \nAttempting to recover...\n\n".format(repr(e), _SETTINGS_PATH)) + printer.out( + "\n\n {} while loading settings file: {} \nAttempting to recover...\n\n".format( + repr(e), _SETTINGS_PATH + ) + ) SETTINGS_tmp = copy.deepcopy(SETTINGS) if "paths" in result: - SETTINGS_tmp['paths'] = result['paths'] + SETTINGS_tmp["paths"] = result["paths"] _save(SETTINGS_tmp, _SETTINGS_PATH) else: _save(SETTINGS, _SETTINGS_PATH) - - - def initialize(): global SETTINGS, SYSTEM_INFORMATION @@ -510,11 +520,14 @@ def initialize(): # Kick everything off. SETTINGS = _init(_SETTINGS_PATH) from castervoice.lib.migration import UserDirUpdater + migrator = UserDirUpdater(_USER_DIR) migrator.create_user_dir_directories() migrator.update_user_dir_packages_to_v1_7_0() migrator.update_bringme_toml_to_v1_7_0() - _debugger_path = SETTINGS["paths"]["REMOTE_DEBUGGER_PATH"] # pylint: disable=invalid-sequence-index + _debugger_path = SETTINGS["paths"][ + "REMOTE_DEBUGGER_PATH" + ] # pylint: disable=invalid-sequence-index if _debugger_path not in sys.path and os.path.isdir(_debugger_path): sys.path.append(_debugger_path) diff --git a/castervoice/rules/core/utility_rules/caster_rule.py b/castervoice/rules/core/utility_rules/caster_rule.py index 10592ec21..15e9a1536 100644 --- a/castervoice/rules/core/utility_rules/caster_rule.py +++ b/castervoice/rules/core/utility_rules/caster_rule.py @@ -1,7 +1,9 @@ from dragonfly import MappingRule, Function, RunCommand from castervoice.lib import control, utilities -from castervoice.lib.ctrl.dependencies import find_pip # pylint: disable=no-name-in-module +from castervoice.lib.ctrl.dependencies import ( + find_pip, +) # pylint: disable=no-name-in-module from castervoice.lib.ctrl.updatecheck import update from castervoice.lib.ctrl.mgr.rule_details import RuleDetails from castervoice.lib.merge.state.short import R @@ -29,31 +31,30 @@ def process_command(self, proc): class CasterRule(MappingRule): mapping = { - "reboot caster": - R(Function(utilities.reboot)), - "update dragonfly": - R(_DependencyUpdate([_PIP, "install", "--upgrade", "dragonfly2"])), + "reboot caster": R(Function(utilities.reboot)), + "update dragonfly": R( + _DependencyUpdate([_PIP, "install", "--upgrade", "dragonfly2"]) + ), # update management ToDo: Fully implement castervoice PIP install - #"update caster": + # "update caster": # R(_DependencyUpdate([_PIP, "install", "--upgrade", "castervoice"])), - # ccr de/activation - "enable (c c r|ccr)": - R(Function(lambda: control.nexus().set_ccr_active(True))), - "disable (c c r|ccr)": - R(Function(lambda: control.nexus().set_ccr_active(False))), - "show caster hud": - R(Function(show_hud), rdescript="Show the HUD window"), - "hide caster hud": - R(Function(hide_hud), rdescript="Hide the HUD window"), - "show caster rules": - R(Function(show_rules), rdescript="Open HUD frame with the list of active rules"), - "hide caster rules": - R(Function(hide_rules), rdescript="Hide the list of active rules"), - "clear caster hud": - R(Function(clear_hud), rdescript="Clear output the HUD window"), + "enable (c c r|ccr)": R(Function(lambda: control.nexus().set_ccr_active(True))), + "disable (c c r|ccr)": R( + Function(lambda: control.nexus().set_ccr_active(False)) + ), + "show hud": R(Function(show_hud), rdescript="Show the HUD window"), + "hide hud": R(Function(hide_hud), rdescript="Hide the HUD window"), + "show rules": R( + Function(show_rules), + rdescript="Open HUD frame with the list of active rules", + ), + "hide rules": R( + Function(hide_rules), rdescript="Hide the list of active rules" + ), + "clear hud": R(Function(clear_hud), rdescript="Clear output the HUD window"), } def get_rule(): - return CasterRule, RuleDetails(name="caster rule") \ No newline at end of file + return CasterRule, RuleDetails(name="caster rule")