Exemple #1
0
class ExampleRule(MappingRule):
    mapping = {
        # Recognise 'hello' followed by arbitrary dictation.
        # This mapping cannot be matched using Pocket Sphinx because the
        # engine's support for dictation has been temporarily disabled.
        "hello <dictation>": Function(print_, dict(dictation="x")),

        # You still can use Mimic or engine.mimic() to match dictation.
        "say hello world": Mimic("hello", "WORLD"),

        # Update and recognise from a dragonfly list.
        "update list": Function(update_list),
        "<lst>": Function(print_, dict(lst="x")),

        # Command to type numbers, e.g. 'type one two three'.
        "type <numbers>": Function(type_numbers),

        # Write transcript files used for training models.
        "(make|write) transcripts": Function(write_transcripts),
    }

    extras = [
        Dictation("dictation"),
        ListRef("lst", lst),
        Repetition(IntegerRef("n", 1, 20), min=1, max=16, name="numbers"),
    ]
Exemple #2
0
class EclipseCCR(MergeRule):
    pronunciation = "eclipse jump"

    mapping = {
        #Line Ops
        "configure":
            R(Paste(ec_con.analysis_chars) +
                Key("left:2/5, c-f/20, backslash, rbracket, enter") +
                Function(ec_con.analyze_for_configure)),
        "jump in [<n>]":
            R(Key("c-f, a-o") + Paste(r"[\(\[\{\<]") + Function(ec_con.regex_on) +
                Key("enter:%(n)d/5, escape, right")),
        "jump out [<n>]":
            R(Key("c-f, a-o") + Paste(r"[\)\] \}\>]") + Function(ec_con.regex_on) +
                Key("enter:%(n)d/5, escape, right")),
        "jump back [<n>]":
            R(Key("c-f/5, a-b") + Paste(r"[\)\]\}\>]") + Function(ec_con.regex_on) +
                Key("enter:%(n)d/5, escape, left")),
        "[go to] line <n>":
            R(Key("c-l") + Pause("50") + Text("%(n)d") + Key("enter") + Pause("50")),
        "shackle <n> [<back>]":
            R(Key("c-l") + Key("right, cs-left") + Function(ec_con.lines_relative)),
    }
    extras = [
        Dictation("text"),
        IntegerRefST("n", 1, 1000),
        Boolean("back"),
    ]
    defaults = {"n": 1, "back": False}
Exemple #3
0
class WindowManagementRule(MappingRule):
    mapping = {
        'minimize':
            R(Playback([(["minimize", "window"], 0.0)])),
        'maximize':
            R(Playback([(["maximize", "window"], 0.0)])),
        "remax":
            R(Key("a-space/10,r/10,a-space/10,x")),

        # Workspace management
        "show work [spaces]":
            R(Key("w-tab")),
        "(create | new) work [space]":
            R(Key("wc-d")),
        "close work [space]":
            R(Key("wc-f4")),
        "close all work [spaces]":
            R(Function(windows_virtual_desktops.close_all_workspaces)),
        "next work [space] [<n>]":
            R(Key("wc-right"))*Repeat(extra="n"),
        "(previous | prior) work [space] [<n>]":
            R(Key("wc-left"))*Repeat(extra="n"),

        "go work [space] <n>":
            R(Function(windows_virtual_desktops.go_to_desktop_number)),
        "send work [space] <n>":
            R(Function(windows_virtual_desktops.move_current_window_to_desktop)),
        "move work [space] <n>":
            R(Function(windows_virtual_desktops.move_current_window_to_desktop, follow=True)),
    }

    extras = [
        IntegerRefST("n", 1, 20, default=1),
    ]
Exemple #4
0
class DevelopmentHelp(MappingRule):
    mapping = {
        # caster development tools
        "(show | open) documentation":
        BringApp(settings.SETTINGS["paths"]["DEFAULT_BROWSER_PATH"]) +
        WaitWindow(executable=settings.get_default_browser_executable()) +
        Key('c-t') + WaitWindow(title="New Tab") +
        Text('http://dragonfly.readthedocs.org/en/latest') + Key('enter'),
        "open natlink folder":
        R(BringApp("C:/Windows/explorer.exe",
                   settings.SETTINGS["paths"]["BASE_PATH"].replace("/", "\\")),
          rdescript="Open Natlink Folder"),
        "refresh debug file":
        Function(devgen.refresh),
        "Agrippa <filetype> <path>":
        Function(grep_this),
        "run rule complexity test":
        Function(lambda: run_tests()),
        "run unit tests":
        Function(testrunner.run_tests),
        "run remote debugger":
        Function(run_remote_debugger),
    }
    extras = [
        Dictation("text"),
        Choice("path", {
            "natlink": "c:/natlink/natlink",
            "sea": "C:/",
        }),
        Choice("filetype", {
            "java": "*.java",
            "python": "*.py",
        })
    ]
    defaults = {"text": ""}
Exemple #5
0
def refresh(_NEXUS):
    ''' should be able to add new scripts on the fly and then call this '''
    unload()
    global grammar
    grammar = Grammar("si/kuli")

    def refresh_sick_command():
        server_proxy.terminate()
        refresh(_NEXUS)

    mapping = {
        "launch sick IDE": Function(launch_IDE),
        "launch sick server": Function(launch_server),
        "refresh sick you Lee": Function(refresh_sick_command),
        "sick shot": Key("cs-2"),
    }

    rule = MergeRule(name="sik", mapping=mapping)
    gfilter.run_on(rule)
    grammar.add_rule(rule)
    grammar.load()
    # start server
    try:
        # if the server is already running, this should go off without a hitch
        start_server_proxy()
    except Exception:
        launch_server()
        seconds5 = 5
        control.nexus().timer.add_callback(server_proxy_timer_fn, seconds5)
Exemple #6
0
class ChessInputRule(MergeRule):

    pronunciation = "chess input"

    mapping = {
        "calibrate <corner> corner":
            R(Function(calibrate)),
        "<chess_letter> <chess_number> <chess_letter2> <chess_number2>":
            R(Function(move)),
        "flip board":
            R(Function(flip))
    }

    extras = [
        Choice("corner", {
            "left top": True,
            "top left": True,
            "right bottom": False,
            "bottom right": False,
        }),
        Choice("chess_letter", LETTERS),
        Choice("chess_letter2", LETTERS),
        Choice("chess_number", NUMBERS),
        Choice("chess_number2", NUMBERS),
    ]

    defaults = {}
Exemple #7
0
class LegionGridRule(MappingRule):

    mapping = {
        "<n> [<action>]":
            R(Function(send_input)),
        "refresh":
            R(Function(Grid.mouse_alternates, mode="legion")),
        SymbolSpecs.CANCEL + " {weight=2}":
            R(Function(Grid.kill)),
        "<n1> (select | light) <n2>":
            R(Function(drag_highlight)),
    }
    extras = [
        Choice("action", {
            "kick": 0,
            "psychic": 1,
            "select | light": 2,
        }),
        ShortIntegerRef("n", 0, 1000),
        ShortIntegerRef("n1", 0, 1000),
        ShortIntegerRef("n2", 0, 1000),
    ]
    defaults = {
        "action": -1,
    }
class Shortcuts(MergeRule):
    mapping = {
        "<single_shortcut>": Function(single_press),
        "<repeat_shortcut> [<n500>]": Function(repeat_press),
        "work <n12>": Function(workspace_switcher),
        "switch [<n100>]": Key('alt:down,tab:%(n100)s,alt:up'),
        "swap [<n100>]": Key('alt:down,backtick:%(n100)s,alt:up'),
        "swipe [<n100>]": Key('alt:down,ctrl:down,tab:%(n100)s,ctrl:down,alt:up'),
        "window move <n12>": Function(workspace_mover),
        "window <window_direction>": Function(resize_window),
        "launcher": Key("win:down,ctrl:down,l,ctrl:up,win:up"),
        # "swap <n100>": Key('alt:down/25,tab/25:%(n100)s,alt:up')
    }

    extras = [
        IntegerRef("n100", 1, 100),
        IntegerRef("n500", 1, 500),
        IntegerRef("n12", 1, 13),
        Choice("single_shortcut", single_shortcut),
        Choice("repeat_shortcut", repeat_shortcut),
        Choice("window_direction", {
            "left": "left",
            "right": "right",
            "maximize": "maximize",
            "minimize": "minimize",
            })
    ]

    defaults = {
        "n100": 1,
        "n500": 1,
    }
Exemple #9
0
    def __init__(self, entities):
        """TODO: to be defined. """

        self._entities = DictList('bring_me_base')

        if isinstance(entities, dict):
            self._entities.set(entities)

        self.mapping = {
            "bring me <entity>":
                Function(self.bring_me),
            "<entity_type> to bring me as <entity_name>":
                Function(self.bring_me_as),
            "remove <entity_name> from bring me":
                Function(self.bring_me_remove)
        }

        self.extras = [
            DictListRef("entity", self._entities),
            Literal(self.type, "entity_type"),
            Dictation("entity_name").apply(lambda key:
                                           re.sub(r'[^A-Za-z\'\s]+', '', key)
                                           .lower())
        ]

        self._subscribers = []

        super().__init__()
Exemple #10
0
class SikuliManagementRule(MappingRule):

    mapping = {
        "launch sick IDE": R(Function(_sc.launch_IDE)),
        "launch sick server": R(Function(_sc.bootstrap_start_server_proxy)),
        "terminate sick server": R(Function(_sc.terminate_server_proxy)),
    }
Exemple #11
0
    def _deserialize(self):
        # get active path from config
        config_copy = self._config.get_copy()
        active_path = []
        if TreeRule._PATH in config_copy:
            active_path = list(config_copy[TreeRule._PATH])

        # get speakable nodes along path of tree's branches
        active_nodes = TreeNode.get_nodes_along_path([self._root_node],
                                                     active_path)

        # create mapping/etc. from active nodes
        self._smr_mapping = {}
        self._smr_extras = []
        self._smr_defaults = {}

        for tree_node in active_nodes:
            spec = tree_node.get_spec()
            action = tree_node.get_action()
            action_and_node_change = action + Function(
                TreeRule._create_spec_fn(self._refresh, spec))
            self._smr_mapping[spec] = action_and_node_change
            self._smr_extras.extend(tree_node.get_extras())
            self._smr_defaults.update(tree_node.get_defaults())
        # cancel by TreeRule name: resets tree to root node
        self._smr_mapping["cancel {}".format(
            self._tree_name)] = Function(lambda: self._refresh())

        # run node change hooks, if configured
        if self._hooks_runner is not None:
            event = NodeChangeEvent(self._tree_name, active_path,
                                    [n.get_spec() for n in active_nodes])
            self._hooks_runner.execute(event)
Exemple #12
0
class GridControlRule(MergeRule):

    mapping = {
        "[<pre>] <color> <n> [<action>]":
        R(Function(send_input, nexus=_NEXUS),
          rdescript="Rainbow Grid: Action"),
        "exit | escape | cancel":
        R(Function(kill, nexus=_NEXUS), rdescript="Exit Rainbow Grid"),
    }
    extras = [
        IntegerRefST("pre", 0, 9),
        Choice(
            "color", {
                "red": 0,
                "(orange | tan | brown)": 1,
                "yellow": 2,
                "green": 3,
                "blue": 4,
                "purple": 5
            }),
        Choice("action", {
            "kick": 0,
            "psychic": 1,
        }),
        IntegerRefST("n", 0, 100),
    ]
    defaults = {
        "pre": 0,
        "action": -1,
    }
Exemple #13
0
class SudokuGridRule(MappingRule):
    pronunciation = "sudoku grid"

    mapping = {
        "<n> [grid <s>] [<action>]":
        R(Function(move_mouse)),
        "[<n0>] [grid <s0>] (grab | select | drag) <n> [grid <s>] [<action>]":
        R(Function(drag_mouse)),
        "squat {weight=2}":
        R(Function(store_first_point)),
        "bench {weight=2}":
        R(Function(select_text)),
        SymbolSpecs.CANCEL + "{weight=2}":
        R(Function(Grid.kill)),
    }
    extras = [
        ShortIntegerRef("n", -1, 1500),
        ShortIntegerRef("n0", -1, 1500),
        ShortIntegerRef("s", 0, 10),
        ShortIntegerRef("s0", 0, 10),
        Choice("action", {
            "kick": 0,
            "kick (double | 2)": 1,
            "psychic": 2,
            "move": 3,
        }),
    ]
    defaults = {
        "n": 0,
        "n0": 0,
        "s": 0,
        "s0": 0,
        "action": -1,
    }
Exemple #14
0
class Keyboard(MergeRule):

    mapping = {
        "<single_key>": Function(single_press),
        "[<modify_letter>] <alphabet_key>": Function(alphabet_press),
        "<repeat_key> [<n500>]": Function(repeat_press),
        '<modifier_key> <any_key> [<n100>]': Function(any_press),
        "develop testing": Key('colon'),
        "super [<any_key>]": Function(super_press),
        "hold <modifier_full_name>": Key("%(modifier_full_name)s:down"),
        "release": Key("ctrl:up,alt:up,shift:up,win:up")
    }

    extras = [
        IntegerRef("n100", 1, 100),
        IntegerRef("n500", 1, 500),
        Choice("single_key", single_key),
        Choice("repeat_key", repeat_key),
        Choice("any_key", any_key),
        Choice("modifier_key", modifier_key),
        Choice("alphabet_key", alphabet_key),
        Choice("modify_letter", {"cap": "cap"}),
        Choice("modifier_full_name", modifier_full_name)
    ]

    defaults = {
        "n100": 1,
        "n500": 1,
    }
Exemple #15
0
    def __init__(self, spec, action, args={}, **kwargs):
        """
        
        :param string spec: The spec for this command, from which `intros
            <intros>` will be determined.
        :param action: The action to be executed when this
            command is said.
        :type action: a dragonfly action_
        :param dict args: Provides a way to add to or modify the extras
            dictionary. The args dictionary has keys of name strings, items of
            function callbacks. The callbacks are supplied a single parameter
            of a dictionary of extras, and their return value is assigned to
            the extra named by the key. When the ``action`` is executed, it
            will then have these final values available to it.
        :param \*\*kwargs: Passed to `FluidRule`, except ``"name"`` and ``"spec"``
            ignored.
        
        
        """
        if isinstance(action, ActionBase) or not six.callable(action):
            self.action = action
            self._is_call = False
        else:
            self.action = Function(action)
            self._is_call = True

        self.args = args
        kwargs["spec"] = spec
        kwargs["name"] = self._autogenerate_name(spec)
        FluidRule.__init__(self, **kwargs)
Exemple #16
0
class StaticRule(MappingRule):

    mapping = {
        #               config.lang.reload_natlink: FocusWindow("natspeak", "Messages from Python Macros") + Key("a-f, r"),
        config.lang.reload_natlink:
        Function(
            show_natlink_messages_window,
            duration=4,
            msg=
            "reload natlink: COMMENTED OUT, causing an error, requiring restart of Dragon."
        ),
        # Reloading Python subsystem...
        # some error occurred
        # Traceback (most recent call last):
        # File "C:\NatLink\NatLink\MacroSystem\core\natlinkmain.py", line 146, in <module>
        # import natlinkstatus    # for extracting status info (QH)
        # File "C:\NatLink\NatLink\MacroSystem\core\natlinkstatus.py", line 180, in <module>
        # import RegistryDict, natlinkcorefunctions
        # File "C:\NatLink\NatLink\MacroSystem\core\natlinkcorefunctions.py", line 31, in <module>
        # from win32com.shell import shell, shellcon
        # File "C:\Python27\lib\site-packages\win32com\__init__.py", line 82, in <module>
        # SetupEnvironment()
        # File "<string>", line 3, in __init__
        # TypeError: 'NoneType' object is not callable
        config.lang.show_natlink_messages_window:
        Function(show_natlink_messages_window, duration=0),
        config.lang.kick_dragon:
        Function(kick_dragon),
        config.lang.show_natlink_macros_directory:
        Function(show_natlink_macros_directory),
    }
Exemple #17
0
class SudokuGridRule(MappingRule):
    pronunciation = "sudoku grid"

    mapping = {
        "<n> [grid <s>] [<action>]":
        R(Function(move_mouse)),
        "[<n0>] [grid <s0>] drag <n> [grid <s>] [<action>]":
        R(Function(drag_mouse)),
        "escape":
        R(Function(kill)),
        SymbolSpecs.CANCEL:
        R(Function(kill)),
    }
    extras = [
        IntegerRefST("n", -1, 1500),
        IntegerRefST("n0", -1, 1500),
        IntegerRefST("s", 0, 10),
        IntegerRefST("s0", 0, 10),
        Choice("action", {
            "move": 0,
            "kick": 1,
            "kick (double | 2)": 2,
            "psychic": 3,
        }),
    ]
    defaults = {
        "n": 0,
        "n0": 0,
        "s": 0,
        "s0": 0,
        "action": 0,
    }
Exemple #18
0
class HMCRule(MergeRule):
    mapping = {
        "kill homunculus":
        R(Function(kill, nexus=_NEXUS), rdescript="Kill Helper Window"),
        "complete":
        R(Function(complete, nexus=_NEXUS), rdescript="Complete Input")
    }
    def construct_activation_rule(self):
        """
        Construct new rule and for activation.
        Should be called once only, after initial content loading.
        Rule reloading does not watch for new files, so no need to ever call this again.
        """
        if self._activation_rule_class is not None:
            return None

        _mapping = {}
        for class_name, trigger in self._class_name_to_trigger.items():
            enable_spec = "enable {}".format(trigger)
            disable_spec = "disable {}".format(trigger)
            _mapping[enable_spec] = Function(
                lambda rcn: self._activation_fn(rcn, True), rcn=class_name)
            _mapping[disable_spec] = Function(
                lambda rcn: self._activation_fn(rcn, False), rcn=class_name)

        class GrammarActivatorRule(MappingRule):
            mapping = _mapping

        self._activation_rule_class = GrammarActivatorRule

        # name that should be pretty difficult to say by mistake:
        details = RuleDetails(name="grammar manager grammar activator rule",
                              watch_exclusion=True)

        return self._activation_rule_class, details
Exemple #20
0
class Mousing(MergeRule):
    mapping = {
        # "jump": Function(move_mouse),
        "[<button>] kick":
        Function(click_mouse),
        # "[<button>] click": Function(move_and_click_mouse),
        "[<button>] lick [<n500>]":
        Function(adjust_and_click_mouse, button="left", direction="left"),
        "[<button>] rick [<n500>]":
        Function(adjust_and_click_mouse, button="left", direction="right"),
        "[<button>] sick [<n500>]":
        Function(adjust_and_click_mouse, button="left", direction="up"),
        "[<button>] dick [<n500>]":
        Function(adjust_and_click_mouse, button="left", direction="down"),
    }

    extras = [
        IntegerRef("n500", 1, 500),
        Choice("button", {
            "left": "left",
            "right": "right",
            "middle": "middle",
            "dub": "double"
        }),
    ]

    defaults = {
        "n100": 1,
        "button": 'left',
    }
Exemple #21
0
class Bash(MergeRule):

    mapping = {
        "pseudo-": Text("sudo "),
        "change": Text("cd "),
        "list": Key("l,s,enter"),
        "sublime": Text("subl "),
        "home": Text("~/"),
        "pie": Text("py"),
        "copy": Key("cs-c"),
        "copy <t>": Function(copy),
        "paste": Key("cs-v"),
        "paste <t>": Function(paste),
        "make directory": Text("mkdir "),
        ".Thought": Text(".."),
        "parent": Text("../"),
        "remote <ssh_server>": Text('ssh %(ssh_server)s'),
        "dropbox": Text("cd ~/Dropbox/"),
        "reset": Key("c-c,c-c,up,enter")
    }

    extras = [
        Choice('ssh_server', {}),
        Dictation("t"),
    ]

    defaults = {
        "t": 'default',
    }
Exemple #22
0
class CppSnippetExampleExperimental(MappingRule):
    pronunciation = "sublime snippet"
    mapping = {
        "<snippet>":
            R(Function(insert_snippet)),
        "<snippet_variants> [<n>]":
            R(Function(insert_snippet_with_variants)),
        "variant <n>":
            R(Key("c-z") + Function(insert_variant)),
        "display variants":
            R(Key("c-z") + Function(display_variants)),
        "apply <transformation>":
            R(Key("c-z") + Function(transform_last_snippet)),
        "small test":
            R(Function(send_sublime,c = "insert_snippet",data = {"contents":"${1:${PARAK:y}}=2 + ${PARAK:z}","PARAK":"x"})),
        "small jerry":
            R(Function(send_sublime,c = "prev_field",data = {})),
        "jerry":
            R(Function(store_and_next)),
        "<snippet> over":
            R(Function(insert_snippet_with_defaults)),
        "<snippet_variants> [<n>] over":
            R(Function(insert_snippet_with_variants_and_defaults)),



    }
    extras = [
        IntegerRefST("n",1,10),
        Choice("snippet",{k:v for k,v in snippets.items() if  isinstance(v,str)}),
        Choice("snippet_variants",{k:v for k,v in snippets.items() if  not isinstance(v,str)}),
        Choice("transformation",transformations),
    ]
    defaults = {}
Exemple #23
0
class HMCConfirmRule(MergeRule):
    mapping = {
        # specific to confirm
        "confirm":                      R(Function(hmc_confirm, value=True, nexus=_NEXUS), rdescript="HMC: Confirm Action"),
        "disconfirm":                   R(Function(hmc_confirm, value=False, nexus=_NEXUS), 
                                          rspec="hmc_cancel",
                                          rdescript="HMC: Cancel Action")
    }
Exemple #24
0
class QuickFluidRule(FluidRule):
    """
    A shortcut to assign an action_ to a spec.
    
    Example::
    
        rule = QuickFluidRule("press home key", Key("home"))
        
    """
    _next_unique_id = 1

    def __init__(self, spec, action, args={}, **kwargs):
        """
        
        :param string spec: The spec for this command, from which `intros
            <intros>` will be determined.
        :param action: The action to be executed when this
            command is said.
        :type action: a dragonfly action_
        :param dict args: Provides a way to add to or modify the extras
            dictionary. The args dictionary has keys of name strings, items of
            function callbacks. The callbacks are supplied a single parameter
            of a dictionary of extras, and their return value is assigned to
            the extra named by the key. When the ``action`` is executed, it
            will then have these final values available to it.
        :param \*\*kwargs: Passed to `FluidRule`, except ``"name"`` and ``"spec"``
            ignored.
        
        
        """
        if isinstance(action, ActionBase) or not six.callable(action):
            self.action = action
            self._is_call = False
        else:
            self.action = Function(action)
            self._is_call = True

        self.args = args
        kwargs["spec"] = spec
        kwargs["name"] = self._autogenerate_name(spec)
        FluidRule.__init__(self, **kwargs)

    def _autogenerate_name(self, spec):
        id_string = str(QuickFluidRule._next_unique_id)
        QuickFluidRule._next_unique_id += 1
        return "quickFluidRule_" + spec + "_id" + id_string

    def _process_recognition(self, node, extras):
        if self._is_call:
            format_candidates = [(name, extra)
                                 for name, extra in extras.items()
                                 if name not in self.args.keys()]
            for name, extra in format_candidates:
                if isinstance(extra, DictationContainerBase):
                    extras[name] = extra.format()
        for name, value_callback in self.args.items():
            extras[name] = value_callback(extras)
        self.action.execute(extras)
class sn_nested(NestedRule):
    mapping = {
        "[<before>] integral from <sequence1> to <sequence2>": [
            Function(lambda: texchar("int")) + Key("c-l"),
            Key("right, c-h"),
            Key("right")
        ],
        "[<before>] definite from <sequence1> to <sequence2>": [
            Key("c-6, right, c-l"),
            Key("right, c-h"),
            Key("right, c-left, left")
        ],
        "[<before>] differential <sequence1> by <sequence2>":
        [Key("c-f, d"), Key("down, d"),
         Key("right")],
        "[<before>] sum from <sequence1> to <sequence2>": [
            Key("f10, i, down:11, enter/25, a, enter, f10, i, down:11, enter/25, b, enter"
                ) + Function(lambda: texchar("sum")) + Key("down"),
            Key("up:2"),
            Key("right")
        ],
        "[<before>] limit from <sequence1> to <sequence2>": [
            Key("f10, i, down:11, enter/25, b, enter") +
            Function(lambda: texchar("lim")) + Key("down"),
            Function(lambda: texchar("rightarrow")),
            Key("right")
        ],
        "[<before>] argument that <minmax> <sequence1>": [
            Key("f10, i, down:11, enter/25, b, enter") +
            Text("arg%(minmax)s") + Key("down"),
            Key("right"), None
        ],
        "[<before>] <minmax> by <sequence1>": [
            Key("f10, i, down:11, enter/25, b, enter") + Text("%(minmax)s") +
            Key("down"),
            Key("right"), None
        ],
        "[<before>] <script1> <singleton1> [<after>]":
        [Key("%(script1)s"), Key("right"), None],
        "[<before>] <script1> <singleton1> <script2> <singleton2> [<after>]":
        [Key("%(script1)s"),
         Key("right, %(script2)s"),
         Key("right")],
    }
    extras = [
        Choice("minmax", {
            "(minimum | minimises)": "min",
            "(maximum | maximises)": "max",
        }),
        Choice("script1", {
            "sub": "c-l",
            "super": "c-h",
        }),
        Choice("script2", {
            "sub": "c-l",
            "super": "c-h",
        }),
    ]
Exemple #26
0
class DynamicConfigurationUtilities(MappingRule):
    mapping = {
        "set sleep to <sleep_value>": Function(set_sleep),
        "show sleep value": Function(show_sleep),
    }

    extras = [
        IntegerRef("sleep_value", 0, 251),
    ]
Exemple #27
0
class GlobalRules(MappingRule):
    mandimusFlags = []
    isMergedSeries = False
    mapping = {
        "reload client code": Function(reloadClient),
        "snore": Function(snore_and_unload),
    }
    extras = []
    defaults = {}
Exemple #28
0
 class MyBasicRule(BasicRule):
     element = Repetition(
         Alternative((
             Literal("test one", value=Function(lambda: func(1))),
             Literal("test two", value=Function(lambda: func(2))),
             Literal("test three", value=Function(lambda: func(3))),
         )),
         1, 5
     )
class VocabRule(MappingRule):
    mapping = {
        'new vocab <text>': Function(add_clipboard_contents_to_vocabulary),
        '(Dell|delete) vocab <text>': Function(del_from_vocabulary),
        'clear vocab': Function(clear_vocabulary),
        'recall <vocab>': Text('%(vocab)s'),
        'list vocab': Function(type_out_vocabulary)
    }
    extras = [Dictation('text'), DictListRef('vocab', vocab_dict)]
 class SleepRule(MappingRule):
     mapping = {
         "rise from your grave":
         Function(wake) +
         Function(lambda: get_engine().start_saving_adaptation_state()),
         "quiet you":
         Function(lambda: get_engine().stop_saving_adaptation_state()) +
         Function(sleep),
     }
Exemple #31
0
class QuickFluidRule(FluidRule):
    """
    A shortcut to assign an action_ to a spec.
    
    Example::
    
        rule = QuickFluidRule("press home key", Key("home"))
        
    """
    _next_unique_id = 1

    def __init__(self, spec, action, args={}, **kwargs):
        """
        
        :param string spec: The spec for this command, from which `intros
            <intros>` will be determined.
        :param action: The action to be executed when this
            command is said.
        :type action: a dragonfly action_
        :param dict args: Provides a way to add to or modify the extras
            dictionary. The args dictionary has keys of name strings, items of
            function callbacks. The callbacks are supplied a single parameter
            of a dictionary of extras, and their return value is assigned to
            the extra named by the key. When the ``action`` is executed, it
            will then have these final values available to it.
        :param \*\*kwargs: Passed to `FluidRule`, except ``"name"`` and ``"spec"``
            ignored.
        
        
        """
        if isinstance(action, ActionBase) or not six.callable(action):
            self.action = action
            self._is_call = False
        else:
            self.action = Function(action)
            self._is_call = True

        self.args = args
        kwargs["spec"] = spec
        kwargs["name"] = self._autogenerate_name(spec)
        FluidRule.__init__(self, **kwargs)
    
    def _autogenerate_name(self, spec):
        id_string = str(QuickFluidRule._next_unique_id)
        QuickFluidRule._next_unique_id += 1
        return "quickFluidRule_" + spec + "_id" + id_string
            
    def _process_recognition(self, node, extras):
        if self._is_call:
            format_candidates = [(name, extra) for name, extra in extras.items() if name not in self.args.keys()]
            for name, extra in format_candidates:
                if isinstance(extra, DictationContainerBase):
                    extras[name] = extra.format()
        for name, value_callback in self.args.items():
            extras[name] = value_callback(extras)
        self.action.execute(extras)
Exemple #32
0
    def __init__(self, spec, action, args={}, **kwargs):
        """
        
        :param string spec: The spec for this command, from which `intros
            <intros>` will be determined.
        :param action: The action to be executed when this
            command is said.
        :type action: a dragonfly action_
        :param dict args: Provides a way to add to or modify the extras
            dictionary. The args dictionary has keys of name strings, items of
            function callbacks. The callbacks are supplied a single parameter
            of a dictionary of extras, and their return value is assigned to
            the extra named by the key. When the ``action`` is executed, it
            will then have these final values available to it.
        :param \*\*kwargs: Passed to `FluidRule`, except ``"name"`` and ``"spec"``
            ignored.
        
        
        """
        if isinstance(action, ActionBase) or not six.callable(action):
            self.action = action
            self._is_call = False
        else:
            self.action = Function(action)
            self._is_call = True

        self.args = args
        kwargs["spec"] = spec
        kwargs["name"] = self._autogenerate_name(spec)
        FluidRule.__init__(self, **kwargs)