Ejemplo n.º 1
0
    def __init__(self,
                 name=None,
                 mapping=None,
                 extras=None,
                 defaults=None,
                 exported=None,
                 ID=None,
                 composite=None,
                 compatible=None,
                 mcontext=None,
                 mwith=None):

        self.ID = ID if ID is not None else MergeRule._get_next_id()
        self.compatible = {} if compatible is None else compatible
        '''composite is the IDs of the rules which this MergeRule is composed of: '''
        self.composite = composite if composite is not None else set([self.ID])
        self._mcontext = self.__class__.mcontext
        if self._mcontext is None: self._mcontext = mcontext
        self._mwith = self.__class__.mwith
        if self._mwith is None: self._mwith = mwith

        if mapping is not None:
            mapping["display available commands"] = Function(
                lambda: self._display_available_commands())

        MappingRule.__init__(self, name, mapping, extras, defaults, exported)
Ejemplo n.º 2
0
 def __init__(self, node, grammar, stat_msg=None, is_reset=False):
     # for self modification
     self.node = node
     first = False
     if self.master_node == None:
         self.master_node = self.node
         first = True
         self.post = ContextSeeker(forward=[L(S(["cancel"], self.reset_node, consume=False))], rspec=self.master_node.spec)
     if self.stat_msg == None:
         self.stat_msg = stat_msg        
     
     mapping = {}
     extras = []
     defaults = {}
     
     # each child node gets turned into a mapping key/value
     for child in self.node.children:
         child.fill_out_rule(mapping, extras, defaults, self)
     
     if len(mapping)==0:
         if self.stat_msg!=None and not first:
             self.stat_msg.text("Node Reset")# status window messaging
         self.reset_node()
         for child in self.node.children:
             child.fill_out_rule(mapping, extras, defaults, self)
     else:
         if self.stat_msg!=None and not first and not is_reset:# status window messaging
             self.stat_msg.hint("\n".join([x.get_spec_and_base_and_node()[0] for x in self.node.children]))
     
     
     MappingRule.__init__(self, "node_" + str(self.master_node.spec), mapping, extras, defaults)
     self.grammar = grammar
Ejemplo n.º 3
0
 def __init__(self, node, grammar, stat_msg=None, is_reset=False):
     # for self modification
     self.node = node
     first = False
     if self.master_node == None:
         self.master_node = self.node
         first = True
         self.post = ContextSeeker(forward=[L(S(["cancel"], self.reset_node, consume=False), 
                                              S([self.master_node.spec], lambda: None, consume=False))], 
                                   rspec=self.master_node.spec)
     if self.stat_msg == None:
         self.stat_msg = stat_msg        
     
     mapping = {}
     extras = []
     defaults = {}
     
     # each child node gets turned into a mapping key/value
     for child in self.node.children:
         child.fill_out_rule(mapping, extras, defaults, self)
     if len(mapping)==0:
         if self.stat_msg!=None and not first:
             self.stat_msg.text("Node Reset")# status window messaging
         self.reset_node()
         for child in self.node.children:
             child.fill_out_rule(mapping, extras, defaults, self)
     else:
         if self.stat_msg!=None and not first and not is_reset:# status window messaging
             self.stat_msg.hint("\n".join([x.get_spec_and_base_and_node()[0] for x in self.node.children]))
     
     
     MappingRule.__init__(self, "node_" + str(self.master_node.spec), mapping, extras, defaults)
     self.grammar = grammar
Ejemplo n.º 4
0
	def __init__(self, name = None, repeatables = None, finishers = None, max = 10, exported = True):
		if repeatables is None: repeatables = self.repeatables
		if finishers is None: finishers = self.finishers

		repeatablesRule = Repetition(Alternative(repeatables), min=1, max=max, name='repeatables')
		finishersRule = Alternative(finishers, name='finishers')

		extras = [repeatablesRule, finishersRule]

		MappingRule.__init__(self, name = name, extras = extras, exported = exported)
Ejemplo n.º 5
0
def refresh():
    ''' 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()

    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"),
    }
    grammar.add_rule(MappingRule(name="sik", mapping=mapping))
    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)
Ejemplo n.º 6
0
def generate_rule(path):
    configuration = ConfigDev("dev")
    configuration.load(path)
    return MappingRule(exported=True,
                       mapping=configuration.cmd.map,
                       extras=configuration.cmd.extras,
                       defaults=configuration.cmd.defaults)
Ejemplo n.º 7
0
    def __init__(
        self,
        name,
        options,
        alias=None,
        base_options=[],
    ):
        alias = alias or name
        self.base_options = base_options

        super(GitCommandRule, self).__init__(
            name=name,
            spec='[help] ({}) <options>'.format(alias),
            exported=False,
            extras=[
                Repetition(
                    name='options',
                    min=0,
                    max=10,
                    child=RuleRef(
                        MappingRule(
                            name=name + '_options',
                            mapping=options,
                            exported=False,
                        )),
                )
            ],
        )
Ejemplo n.º 8
0
    def buildFinalMergedRule(self):
        #log.info("Building final merged rule.")
        if not self.seriesRules and not self.terminatorRule:
            return

        extras = []
        seriesRefNames = []
        for i, r in enumerate(self.seriesRules):
            name = "s" + str(i)
            seriesRefNames.append(name)
            ref = dfly.RuleRef(self.concreteRules[r], name)
            extras.append(ref)
        seriesPart = "[" + " | ".join([("<" + r + ">") for r in seriesRefNames]) + "]"

        terminatorPart = ""
        if self.terminatorRule:
            extras.append(dfly.RuleRef(self.concreteRules[self.terminatorRule], "terminator"))
            terminatorPart = " [<terminator>]"

        masterPhrase = seriesPart + terminatorPart
        mapping = {
            masterPhrase : ReportingAction(masterPhrase, self.client, self.hash)
        }

        log.info("Building master grammar rule with name [%s] mapping [%s] extras [%s] defaults [%s]"
                 % (self.fullName, mapping, extras, {}))
        masterTimeStart = time.time()
        self.finalDflyRule = MappingRule(name=self.hash, mapping=mapping, extras=extras,
                                         defaults={}, exported=True)
        masterTimeEnd = time.time()
        log.info("Master rule construction time: %ss" % (masterTimeEnd - masterTimeStart))
def create_rule(name, action_map, element_map, exported=False, context=None):
    """Creates a rule with the given name, binding the given element map to the
    action map.
    """
    return MappingRule(name,
                       action_map,
                       element_map_to_extras(element_map),
                       element_map_to_defaults(element_map),
                       exported,
                       context=context)
Ejemplo n.º 10
0
    def __init__(self, mapping, extras=None, defaults=None):
        mapping_rule = MappingRule(mapping=mapping, extras=extras,
                                   defaults=defaults, exported=False)
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self, spec=compound_spec,
                              extras=compound_extras, exported=True)
Ejemplo n.º 11
0
class ExclusiveManager:
    """
    Loads and switches exclusivity for caster modes
    :param mode: str
    :param modetype: 'mic_mode' or 'engine_mode' str
    """
    # TODO: Implement set_engine_mode exclusivity with mode rules.
    # TODO: Implement timer for sleep mode.
    # TODO: Implement hotkey for microphone on-off
    sleep_grammar = None
    sleeping = False

    sleep_rule = MappingRule(
        name="sleep_rule",
        mapping={
            "caster <mic_mode>":
            Function(lambda mic_mode: EngineModesManager.set_mic_mode(
                mode=mic_mode)),
            "<text>":
            Function(lambda text: False)
        },
        extras=[
            Choice("mic_mode", {
                "off": "off",
                "on": "on",
                "sleep": "sleeping",
            }),
            Dictation("text")
        ],
        context=FuncContext(lambda: ExclusiveManager.sleeping),
    )

    def __init__(self, mode, modetype):
        if modetype == "mic_mode":
            if not isinstance(ExclusiveManager.sleep_grammar, Grammar):
                grammar = ExclusiveManager.sleep_grammar = Grammar("sleeping")
                grammar.add_rule(self.sleep_rule)
                grammar.load()
            if mode == "sleeping":
                self.set_exclusive(state=True)
                printer.out("Caster: Microphone is sleeping")
            if mode == "on":
                self.set_exclusive(state=False)
                printer.out("Caster: Microphone is on")
            if mode == "off":
                printer.out("Caster: Microphone is off")
        else:
            printer.out("{}, {} not implemented".format(mode, modetype))

    def set_exclusive(self, state):
        grammar = ExclusiveManager.sleep_grammar
        ExclusiveManager.sleeping = state
        grammar.set_exclusive(state)
        get_engine().process_grammars_context()
Ejemplo n.º 12
0
 def value(self, node):
     value = MappingRule.value(self, node)
     if value == 'tcomment':
         # ugly hack to get around tComment's not allowing ranges with gcc.
         value = node.children[0].children[0].children[0].children[1].value()
         if value in (1, '1', None):
             return Text('gcc')
         else:
             return Text('gc%dj' % (int(value) - 1))
     else:
         return value
Ejemplo n.º 13
0
 def value(self, node):
     value = MappingRule.value(self, node)
     if value == 'tcomment':
         # ugly hack to get around tComment's not allowing ranges with gcc.
         value = node.children[0].children[0].children[0].children[1].value()
         if value in (1, '1', None):
             return Text('gcc')
         else:
             return Text('gc%dj' % (int(value) - 1))
     else:
         return value
Ejemplo n.º 14
0
    def _combine_mapping_rules(self, name, base_rule, extension_rule, context):
        mapping = base_rule._mapping.copy()
        mapping.update(extension_rule._mapping)
        extras_dict = base_rule._extras.copy()
        extras_dict.update(extension_rule._extras)
        extras = extras_dict.values()
        defaults = base_rule._defaults.copy()
        defaults.update(extension_rule._defaults)
        exported = base_rule._exported

        return MappingRule(name, mapping, extras, defaults, exported, context)
Ejemplo n.º 15
0
def generate_commands(list_of_functions):
    global server_proxy
    global grammar
    mapping = {}
    for fname in list_of_functions:
        spec = " ".join(fname.split("_"))
        mapping[spec] = Function(execute, fname=fname)
    grammar.unload()
    grammar = Grammar("sikuli")
    grammar.add_rule(MappingRule(mapping=mapping, name="sikuli server"))
    grammar.load()
Ejemplo n.º 16
0
 def value(self, node):
   value = MappingRule.value(self, node)
   if value == "tcomment":
     try:
       # ugly hack to get around tComment's not allowing ranges with gcc.
       value = node.children[0].children[0].children[0].children[1].value()
       if value in (1, "1", None):
         return Text("gcc")
       else:
         return Text("gc%dj" % (int(value) - 1))
     except Exception, ex:
       print ex
Ejemplo n.º 17
0
def create_grammar():
    grammar = Grammar("global state")
    grammar.add_rule(
        MappingRule(
            mapping={
                "mark": Function(__toggle_marking),
                "cursor": Function(__toggle_cursor),
                "done": Function(remove_nesting_level),
                "done all": Function(remove_nesting_levels),
                "dictate": Function(__start_dictating),
                "finish": Function(__stop_dictating)
            }))
    return grammar, True
Ejemplo n.º 18
0
def load_sleep_wake_grammar(initial_awake):
    sleep_grammar = Grammar("sleep")

    def sleep(force=False):
        global sleeping
        if not sleeping or force:
            sleeping = True
            sleep_grammar.set_exclusiveness(True)
        notify('Sleeping...')

    def wake(force=False):
        global sleeping
        if sleeping or force:
            sleeping = False
            sleep_grammar.set_exclusiveness(False)
        notify('Awake...')

    def halt(force=False):
        exit(0)

    class SleepRule(MappingRule):
        mapping = {
            'dragonfly exit':
            Function(halt),
            "start listening":
            Function(wake) +
            Function(lambda: get_engine().start_saving_adaptation_state()),
            "stop listening":
            Function(lambda: get_engine().stop_saving_adaptation_state()) +
            Function(sleep),
            "halt listening":
            Function(lambda: get_engine().stop_saving_adaptation_state()) +
            Function(sleep),
        }

    sleep_grammar.add_rule(SleepRule())

    sleep_noise_rule = MappingRule(
        name="sleep_noise_rule",
        mapping={"<text>": Function(lambda text: False and print(text))},
        extras=[Dictation("text")],
        context=FuncContext(lambda: sleeping),
    )
    sleep_grammar.add_rule(sleep_noise_rule)

    sleep_grammar.load()

    if initial_awake:
        wake(force=True)
    else:
        sleep(force=True)
Ejemplo n.º 19
0
    def __init__(self):
        commands = git_commands.all_commands(GitCommandRuleBuilder)
        spec = '[<cancel>] git [<command_with_options>] [<enter>] [<cancel>]'

        super(GitRule, self).__init__(
            spec=spec,
            extras=[
                RuleRef(name='cancel',
                        rule=MappingRule(
                            name='cancel',
                            mapping={'cancel [last]': Key('c-c')},
                        )),
                Alternative(
                    name='command_with_options',
                    children=commands,
                ),
                RuleRef(name='enter',
                        rule=MappingRule(
                            name='enter',
                            mapping={'enter': Key('enter')},
                        )),
            ],
        )
Ejemplo n.º 20
0
    def test_list_grammars(self):
        """ Verify that the 'list_grammars' RPC method works correctly. """
        # Load a Grammar with three rules and check that the RPC returns the
        # correct data for them.
        g = Grammar("list_grammars_test")
        g.add_rule(CompoundRule(name="compound", spec="testing",
                                exported=True))
        g.add_rule(
            MappingRule(name="mapping",
                        mapping={
                            "command a": ActionBase(),
                            "command b": ActionBase()
                        }))
        g.add_rule(
            Rule(name="base", element=Literal("hello world"), exported=False))
        g.load()

        response = self.send_request("list_grammars", [])
        expected_grammar_data = {
            "name":
            g.name,
            "enabled":
            True,
            "active":
            True,
            "rules": [{
                "name": "compound",
                "specs": ["testing"],
                "exported": True,
                "active": True
            }, {
                "name": "mapping",
                "specs": ["command a", "command b"],
                "exported": True,
                "active": True
            }, {
                "name": "base",
                "specs": ["hello world"],
                "exported": False,
                "active": True
            }]
        }
        # Check that the loaded grammar appears in the result. It might not
        # be the only grammar and that is acceptable because dragonfly's
        # tests can be run while user grammars are loaded.
        try:
            self.assertIn("result", response)
            self.assertIn(expected_grammar_data, response["result"])
        finally:
            g.unload()
Ejemplo n.º 21
0
 def create_grammar(self, g, t):
     rule = MappingRule(
         mapping={
             t("scroll"):
             Function(lambda: self.toggle_scroll()),
             t("right_click"):
             Mouse("right"),
             "\"" + t("left_click") + "|" + t("click") + "|" + t("focus") + "\"":
             Mouse("left"),
             "\"" + t("double_click") + "|" + t("double") + "|" + t("open") + "|" + t("select") + "\"":
             Mouse("left/3, left/3"),
         })
     g.add_rule(rule)
     return True
Ejemplo n.º 22
0
def load_noise_grammar():
    noise_grammar = Grammar("noise")

    noise_grammar.add_rule(
        MappingRule(
            name='noise',
            mapping={
                "<text> {weight=10}":
                Function(lambda text: print('Noise: ', text))
            },
            extras=[Dictation("text")],
        ))

    noise_grammar.load()
Ejemplo n.º 23
0
    def __init__(self,
                 name=None,
                 mapping=None,
                 extras=None,
                 defaults=None,
                 exported=None,
                 ID=None,
                 composite=None,
                 compatible=None,
                 mcontext=None,
                 mwith=None):

        self.ID = ID if ID is not None else MergeRule._get_next_id()
        self.compatible = {} if compatible is None else compatible
        '''composite is the IDs of the rules which this MergeRule is composed of: '''
        self.composite = composite if composite is not None else set([self.ID])
        self._mcontext = self.__class__.mcontext
        if self._mcontext is None: self._mcontext = mcontext
        self._mwith = self.__class__.mwith
        if self._mwith is None: self._mwith = mwith

        self.extras.extend(self.default_extras)
        MappingRule.__init__(self, name, mapping, extras, defaults, exported)
Ejemplo n.º 24
0
def load_sleep_wake_grammar(initial_awake):
    sleep_grammar = Grammar("sleep")

    def sleep(force=False):
        global sleeping
        if not sleeping or force:
            sleeping = True
            sleep_grammar.set_exclusiveness(True)
        notify('sleep')

    def wake(force=False):
        global sleeping
        if sleeping or force:
            sleeping = False
            sleep_grammar.set_exclusiveness(False)
        notify('wake')

    class SleepRule(MappingRule):
        mapping = {
            "listen to me":
            Function(wake) +
            Function(lambda: get_engine().start_saving_adaptation_state()),
            "(go to sleep)|(stop listening)":
            Function(lambda: get_engine().stop_saving_adaptation_state()) +
            Function(sleep),

            # "halt listening":   Function(lambda: get_engine().stop_saving_adaptation_state()) + Function(sleep),
        }

    sleep_grammar.add_rule(SleepRule())

    sleep_noise_rule = MappingRule(
        name="sleep_noise_rule",
        mapping={
            "<text>":
            Function(lambda text: False and print("(asleep) " + text))
        },
        extras=[Dictation("text")],
        context=FuncContext(lambda: sleeping),
    )
    sleep_grammar.add_rule(sleep_noise_rule)

    sleep_grammar.load()

    if initial_awake:
        wake(force=True)
    else:
        sleep(force=True)
Ejemplo n.º 25
0
def load_sleep_wake_grammar(initial_awake):
    sleep_grammar = Grammar("sleep")

    def sleep(force=False):
        global sleeping
        if not sleeping or force:
            sleeping = True
            sleep_grammar.set_exclusiveness(True)
            get_engine().process_grammars_context()
        notify('sleep')

    def wake(force=False):
        global sleeping
        if sleeping or force:
            sleeping = False
            sleep_grammar.set_exclusiveness(False)
            get_engine().process_grammars_context()
        notify('wake')

    class SleepRule(MappingRule):
        mapping = {
            "start listening": Function(wake),
            "stop listening": Function(sleep),
            "halt listening": Function(sleep),
        }

    sleep_grammar.add_rule(SleepRule())

    sleep_noise_rule = MappingRule(
        name="sleep_noise_rule",
        mapping={"<text>": Function(lambda text: False and print(text))},
        extras=[Dictation("text")],
        context=FuncContext(lambda: sleeping),
    )
    sleep_grammar.add_rule(sleep_noise_rule)

    sleep_grammar.load()

    if initial_awake:
        wake(force=True)
    else:
        sleep(force=True)
Ejemplo n.º 26
0
grammar_context = AppContext(executable="outlook")
grammar = Grammar("outlook_example", context=grammar_context)

#---------------------------------------------------------------------------
# Create a rule for static keyboard shortcuts.

static_rule = MappingRule(
    name="static",
    mapping={
        "new folder": Key("cs-e"),
        "new email": Key("cs-m"),
        "new appointment": Key("cs-a"),
        "new meeting request": Key("cs-q"),
        "new contact": Key("cs-c"),
        "new distribution list": Key("cs-l"),
        "new note": Key("cs-n"),
        "new task": Key("cs-k"),
        "accept and edit": Key("a-a, c, e, enter"),
        "accept and send": Key("a-a, c, s, enter"),
        "accept without response": Key("a-a, c, d, enter"),
        "tentative and edit": Key("a-a, a, e, enter"),
        "tentative and send": Key("a-a, a, s, enter"),
        "tentative without response": Key("a-a, a, d, enter"),
        "folder": Key("c-y"),
    },
)

# Add the action rule to the grammar instance.
grammar.add_rule(static_rule)

#---------------------------------------------------------------------------
# Create a rule for our list of folders.
Ejemplo n.º 27
0
 def value(self, node):
     return Text(MappingRule.value(self, node))
Ejemplo n.º 28
0
    DictListRef(
        'dynamic vim.insertions',
        aenea.vocabulary.register_dynamic_vocabulary('vim.insertions')),
    ruleArithmeticInsertion,
    ruleSpellingInsertion,
]

static_code_insertions = aenea.vocabulary.get_static_vocabulary(
    'vim.insertions.code')
static_insertions = aenea.vocabulary.get_static_vocabulary('vim.insertions')

if static_code_insertions:
    primitive_insertions.append(
        RuleRef(
            MappingRule('static vim.insertions,code mapping',
                        mapping=aenea.vocabulary.get_static_vocabulary(
                            'vim.insertions.code')),
            'static vim.insertions.code'))

if static_insertions:
    primitive_insertions.append(
        RuleRef(
            MappingRule('static vim.insertions mapping',
                        mapping=aenea.vocabulary.get_static_vocabulary(
                            'vim.insertions')), 'static vim.insertions'))


class PrimitiveInsertion(CompoundRule):
    spec = '<insertion>'
    extras = [Alternative(primitive_insertions, name='insertion')]
Ejemplo n.º 29
0
rules = MappingRule(
    mapping={
        # Commands and keywords:
        "and": Text(" and "),
        "as": Text("as "),
        "assign": Text(" = "),
        "assert": Text("assert "),
        "break": Text("break"),
        "comment": Text("# "),
        "class": Text("class "),
        "class <text>": Function(define_class),
        "continue": Text("continue"),
        "del": Text("del "),
        "divided by": Text(" / "),
        "(dict|dictionary) key value": Text("\"\": \"\",") + Key("left:6"),
        "enumerate": Text("enumerate()") + Key("left"),
        "(def|define|definition) [function]": Text("def "),
        "(def|define|definition) [function] <text>": Function(define_function),
        "(def|define|definition) method <text>": Function(define_method),
        "(def|define|definition) init": Text("def __init__("),
        "doc string": Text('"""Doc string."""') + Key("left:14, s-right:11"),
        "else": Text("else:") + Key("enter"),
        "except": Text("except "),
        "exec": Text("exec "),
        "(el if|else if)": Text("elif "),
        "(el if|else if) <text>": SCText("elif %(text)s"),
        "equals": Text(" == "),
        "false": Text("False"),
        "finally": Text("finally:") + Key("enter"),
        "for": Text("for "),
        "for <text>": SCText("for %(text)s"),
        "from": Text("from "),
        "from <text>": SCText("from %(text)s"),
        "global ": Text("global "),
        "greater than": Text(" > "),
        "greater [than] equals": Text(" >= "),
        "if": Text("if "),
        "if <text>": SCText("if %(text)s"),
        "in": Text(" in "),
        "in <text>": SCText("in %(text)s"),
        "(int|I N T)": Text("int"),
        "(int|I N T)": Text("int()") + Key("left"),
        "init": Text("init"),
        "import": Text("import "),
        "import <text>": SCText("import %(text)s"),
        "(len|L E N)": Text("len("),
        "lambda": Text("lambda "),
        "less than": Text(" < "),
        "less [than] equals": Text(" <= "),
        "(minus|subtract|subtraction)": Text(" - "),
        "(minus|subtract|subtraction) equals": Text(" -= "),
        "modulo": Key("space") + Key("percent") + Key("space"),
        "not": Text(" not "),
        "not equals": Text(" != "),
        "none": Text("None"),
        "or": Text(" or "),
        "pass": Text("pass"),
        "(plus|add|addition)": Text(" + "),
        "(plus|add|addition) equals": Text(" += "),
        "print": Text("print()") + Key("left"),
        "raise": Text("raise"),
        "raise exception": Text("raise Exception()") + Key("left"),
        "return": Text("return"),
        "return <text>": SCText("return %(text)s"),
        "self": Text("self"),
        "(str|S T R)": Text("str"),
        "(str|S T R) paren": Text("str()") + Key("left"),
        "true": Text("True"),
        "try": Text("try:") + Key("enter"),
        "times": Text(" * "),
        "with": Text("with "),
        "while": Text("while "),
        "yield": Text("yield "),
        # Some common modules.
        "datetime": Text("datetime"),
        "(io|I O)": Text("io"),
        "logging": Text("logging"),
        "(os|O S)": Text("os"),
        "(pdb|P D B)": Text("pdb"),
        "(re|R E)": Text("re"),
        "(sys|S Y S)": Text("sys"),
        "S Q lite 3": Text("sqlite3"),
        "subprocess": Text("subprocess"),
    },
    extras=[
        IntegerRef("n", 1, 100),
        Dictation("text"),
    ],
    defaults={
        "n": 1
    }
)
Ejemplo n.º 30
0
putty_rule = MappingRule(
    name="putty",
    mapping={
        # characters
        "(tab|tabby|Debbie)"            : Key("tab"),
        "Shift (tab|tabby|Debbie)"      : Key("s-tab"),
        "(slap|newline|enter)"          : Key("enter"),
        "(splat|star|asterisk)"         : Key("asterisk"),
        "(hash|hashtag)"                : Key("hash"),
        "(minus|dash|tack|hyphen)"      : Key("hyphen"),
        "(dashdash|tacktack)"           : Key("hyphen,hyphen"),
        "interupt"                      : Key("c-c"), # ctrl-c sends SIGINT
        "end of file"                   : Key("c-d"), # ctrl-d send EOF
        # shell commands
        "(cd|change directory)"         : Text("cd "),
        "(l s|ellis|ls|list files)"     : Text("ls "),
        "(pwd|print working directory)" : Text("pwd ") + Key("enter"),
        "(vi|v i|vim)"                  : Text("vim "),
        "configure"                     : Text("./configure"),
        "make"                          : Text("make "),
        "make install"                  : Text("make install "),
        "get init"                      : Text("git init "),
        "get clone"                     : Text("git clone "),
        "get add"                       : Text("git add "),
        "get commit"                    : Text('git commit -m ""') + Key("left"),
        "get status"                    : Text("git status ") + Key("enter"),
        "get push"                      : Text("git push "),
        "get push origin master"        : Text("git push origin master "),
        "get pull"                      : Text("git pull "),
        "get check out"                 : Text("git checkout ") + Key("tab"),
        "get fetch"                     : Text("git fetch ") + Key("tab"),
        "get merge"                     : Text("git merge ") + Key("tab"),
        "get log"                       : Text("git log ") + Key("enter"),
        "get log pretty"                : Text("git log --pretty=oneline") + Key("enter"),
        "get log author"                : Text('git log --author=""') + Key("left"),
        "get stash save"                : Text("git stash save") + Key("enter"),
        "get stash pop"                 : Text("git stash pop") + Key("enter"),
        "htop"                          : Text("htop") + Key("enter"),
    },
    extras=[
        Dictation("text"),
    ],
)
Ejemplo n.º 31
0
 def value(self, node):
   return Text(MappingRule.value(self, node))
Ejemplo n.º 32
0
 rules = MappingRule(
     mapping={
         # Overall navigation.
         "workspace <direction1> [<direction2>]":
         Function(workspace_direction),  # @IgnorePep8
         "go to launcher":
         Key("a-f1"),
         "go to hud":
         Key("win"),
         "go to run":
         Key("a-f2"),
         "go to spread view":
         Key("w-w"),
         "go to expo view":
         Key("w-s"),
         "show panel menu":
         Key("a-f10"),
         "show window menu":
         Key("a-space"),
         # Window control
         "close window":
         Key("a-f4"),
         "minimize window":
         Key("ca-KP_Insert"),
         "maximize window":
         Key("cw-up"),
         "restore window":
         Key("cw-down"),
         "move window":
         Key("a-f7"),
         "resize window":
         Key("a-f8"),
         "place window <winDirection>":
         Function(window_direction),
         "switch to <text>":
         Function(switch_to_window),
         "toggle desktop":
         Key("cw-d"),
         # Mouse commands.
         "mouse [left] click":
         Mouse("left"),
         "mouse shift [left] click":
         Key("shift:down/3") + Mouse("left") +
         Key("shift:up/3"),  # @IgnorePep8
         "mouse control [left] click":
         Key("ctrl:down/3") + Mouse("left") +
         Key("ctrl:up/3"),  # @IgnorePep8
         "mouse right click":
         Mouse("right"),
         "mouse shift right click":
         Key("shift:down/3") + Mouse("right") +
         Key("shift:up/3"),  # @IgnorePep8
         "mouse control right click":
         Key("ctrl:down/3") + Mouse("right") +
         Key("ctrl:up/3"),  # @IgnorePep8
         "mouse <direction1> <n1> [<direction2> <n2>]":
         Function(mouse_direction),  # @IgnorePep8
         "mouse <direction1> <direction2> <n1>":
         Function(mouse_double_direction),  # @IgnorePep8
         # Starting applications.
         "start terminal":
         Key("ca-t"),
         # Development option only.
         "toggle host server":
         Function(toggle_host_server),
     },
     extras=[
         IntegerRef("n1", 1, 5000),
         IntegerRef("n2", 1, 5000),
         Dictation("text"),
         Choice("direction1", basicDirections),
         Choice("direction2", basicDirections),
         Choice("winDirection", windowDirections),
     ],
     defaults={"n": 1})
Ejemplo n.º 33
0
def load_sleep_wake_grammar(initial_awake):
    sleep_grammar = Grammar("sleep")
    def sleep(force=False):
        get_engine().stop_saving_adaptation_state()
        global sleeping
        if not sleeping or force:
            sleeping = True
            sleep_grammar.set_exclusiveness(True)
            notify('sleep')

    def wake(force=False):
        get_engine().start_saving_adaptation_state()
        global sleeping
        if sleeping or force:
            sleeping = False
            sleep_grammar.set_exclusiveness(False)
            notify('wake')

    class SleepRule(MappingRule):
        mapping = {
            "go to sleep":Function(sleep),
            "bake up": Function(noop),
            "rake up":Function(noop),
            "shake up":Function(noop),
            "lake up":Function(noop),
            "nake up":Function(noop),
            "wake tup":Function(noop),
            "wake sup":Function(noop),
            "whey grub":Function(noop),
            "wake":Function(noop),
            "wake up":Function(wake),
        }
    sleep_grammar.add_rule(SleepRule())

    sleep_noise_rule = MappingRule(
        name = "sleep_noise_rule",
        mapping = { "<text>": Function(lambda text: False and print("(asleep) " + text)) },
        extras = [ Dictation("text") ],
        context = FuncContext(lambda: sleeping),
    )
    sleep_grammar.add_rule(sleep_noise_rule)

    sleep_grammar.load()

    # def checkIniFile():
    #     global sleeping
    #     global sleepOverride
    #     voice = readIni('voice')
    #     new_value = (voice=="off")
    #     if new_value:
    #         sleep()
    #     else:
    #         wake()
            
    # set_interval(checkIniFile,3)
    # watchingIniFile = True
        
    



    if initial_awake:
        wake(force=True)
    else:
        sleep(force=True)
Ejemplo n.º 34
0
from dragonfly import (Grammar, AppContext, MappingRule, Dictation, Key, Text)

firefox_context = AppContext(executable="firefox")
grammar = Grammar("firefox", context=firefox_context)

firefox_rules = MappingRule(name="firefox",
                            mapping={
                                "jump": Key("f12"),
                                "edit": Key("cs-f4"),
                            },
                            extras=[Dictation("text")])

grammar.add_rule(firefox_rules)

grammar.load()


def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None