Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
kendonB committed Dec 8, 2022
1 parent cf30b80 commit f711a15
Show file tree
Hide file tree
Showing 6 changed files with 266 additions and 222 deletions.
39 changes: 27 additions & 12 deletions _caster.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''
"""
main Caster module
Created on Jun 29, 2014
'''
"""
import logging
import importlib
from dragonfly import get_engine, get_current_engine
Expand All @@ -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
16 changes: 10 additions & 6 deletions castervoice/asynch/hmc/h_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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"]
Expand All @@ -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.
Expand Down
65 changes: 36 additions & 29 deletions castervoice/asynch/hud_support.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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():
Expand All @@ -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():
Expand All @@ -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():
"""
Expand All @@ -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
Expand All @@ -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
raise ("") # pylint: disable=raising-bad-type
4 changes: 4 additions & 0 deletions castervoice/lib/ctrl/configure_engine.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
Loading

0 comments on commit f711a15

Please sign in to comment.