Пример #1
0
 def __init__(self):
     self.mode = "normal"
     self.frequency = 5
     self.command_titles = ["sublime", "jupyter", "rstudio", "mingw64", "lyx", "scientific notebook"]
     self.command_executables = ["code.exe", "kindle.exe"]
     self.command_contexts = AppContext(title=self.command_titles) | AppContext(self.command_executables)
     self.timer = get_engine().create_timer(self.check_context, self.frequency)
Пример #2
0
def paste_command():
    # Add Command Prompt, putty, ...?
    context = AppContext(executable="console")
    window = Window.get_foreground()
    if context.matches(window.executable, window.title, window.handle):
        return
    release.execute()
    Key("c-v/3").execute()
def paste_command():
    # Add Command Prompt, putty, ...?
    context = AppContext(executable="console")
    window = Window.get_foreground()
    if context.matches(window.executable, window.title, window.handle):
        return
    release.execute()
    Key("c-v/3").execute()
Пример #4
0
 def __init__(self, match=None):
     Context.__init__(self)
     self.chrome_context = AppContext("chrome")
     if isinstance(match, string_types):
         self._matches = [match.lower()]
     elif isinstance(match, (list, tuple)):
         self._matches = [m.lower() for m in match]
     elif match is None:
         self._matches = None
     else:
         raise TypeError("match argument must be a string or None;"
                         " received %r" % match)
Пример #5
0
 def __init__(self):
     self.folders = DictList("folders")
     super(OutlookControlGrammar,self).__init__(
         name="Microsoft Outlook control",
         context=AppContext(executable="outlook"),
         app_name="Outlook.Application"
     )
Пример #6
0
def test_top_level_command():
    Breathe.add_commands(None, {"orange": DoNothing(), "grapefruit": DoNothing()})
    Breathe.add_commands(
        AppContext("notepad"), {"lemon": DoNothing(), "banana": DoNothing()}
    )
    Breathe.add_commands(
        AppContext("notepad"),
        {
            "fruit from <sequence1> and [<sequence2>] [<n>]": DoNothing()
            + Exec("sequence1")
            + DoNothing()
            + Exec("sequence2")* Repeat("n")
        },
        extras=[CommandsRef("sequence1"), CommandsRef("sequence2", 2), IntegerRef("n", 1, 10, 1)],
        top_level=True,
    )
Пример #7
0
 def matches(self, executable, title, handle):
     if AppContext.matches(self, executable, title, handle):
         return True
     # Only check Linux if it is active.
     if title.find("Oracle VM VirtualBox") != -1 or title.find(" - Chrome Remote Desktop") != -1:
         remote_title = linux_helper.GetActiveWindowTitle().lower()
         found = remote_title.find(self._title) != -1
         if self._exclude != found:
             return True
     return False
Пример #8
0
def test_invalid():
    Breathe.add_commands(
        AppContext("code.exe"),
        {
            "test that <nonexistent_extra>": DoNothing(),
            1: DoNothing(),
        },
    )
    assert len(Breathe.contexts) == 1
    assert len(Breathe.context_commands) == 1
Пример #9
0
def test_context_commands():
    Breathe.add_commands(
        AppContext("notepad"),
        {"test [<num>]": lambda num: DoNothing().execute()},
        [Choice("num", {"four": "4", "five": "5", "six": "6"})],
        {"num": ""},
    )
    with pytest.raises(MimicFailure):
        engine.mimic(["test", "three", "test", "four"])
    engine.mimic(["test", "three", "test", "four"], executable="notepad")
Пример #10
0
def test_noccr_commands():
    Breathe.add_commands(
        AppContext("firefox"),
        {"dictation <text>": DoNothing(), "testing static": DoNothing()},
        ccr=False,
    )
    engine.mimic(["testing", "static"], executable="firefox")
    with pytest.raises(MimicFailure):
        engine.mimic(["dictation", "TESTING"])
        engine.mimic(["testing", "static", "testing", "static"], executable="firefox")
    engine.mimic(["dictation", "TESTING"], executable="firefox")
Пример #11
0
def test_negated_context():
    Breathe.add_commands(~(CommandContext("america") | AppContext("england")),
                         {
                             "steak": DoNothing(),
                         })
    engine.mimic(["steak"])
    with pytest.raises(MimicFailure):
        engine.mimic(["steak"], executable="england")
    engine.mimic(["enable", "america"])
    with pytest.raises(MimicFailure):
        engine.mimic(["steak"])
Пример #12
0
def load():
    global git_grammar
    context = aenea.wrappers.AeneaContext(
        ProxyAppContext(
            match='regex',
            app_id='(?i)(?:(?:DOS|CMD).*)|(?:.*(?:TERM|SHELL).*)',
        ),
        AppContext(title='git'),
    )
    git_grammar = Grammar('git', context=context)
    git_grammar.add_rule(GitRule())
    git_grammar.load()
Пример #13
0
 def matches(self, executable, title, handle):
     if AppContext.matches(self, executable, title, handle):
         return True
     # Only check Linux if it is active.
     if title.find("Oracle VM VirtualBox") != -1 or title.find(
             "<remotedesktop.corp.google.com>") != -1:
         remote_title = linux_helper.GetActiveWindowTitle().lower()
         found = any(
             remote_title.find(match) != -1 for match in self._title)
         if self._exclude != found:
             return True
     return False
Пример #14
0
def test_top_level_command_failure():
    Breathe.add_commands(
        AppContext("china"),
        {
            "not marked top level <sequence1> and <sequence2> [<n>]": DoNothing()
            + Exec("sequence1")
            + DoNothing()
            + Exec("sequence2")* Repeat("n")
        },
        extras=[CommandsRef("sequence1"), CommandsRef("sequence2", 2), IntegerRef("n", 1, 10, 1)],
        top_level=False,
    )
    assert len(Breathe.top_level_commands) == 2
Пример #15
0
def test_manual_context_noccr():
    Breathe.add_commands(CommandContext("test") | AppContext("italy"),
                         {"spaghetti": DoNothing()},
                         ccr=False)
    # Loaded rule should be referencing the original
    # "test" context loaded above, which should already be
    # active
    engine.mimic(["spaghetti"])
    engine.mimic(["disable", "test"])
    with pytest.raises(MimicFailure):
        engine.mimic(["spaghetti"])
        engine.mimic(["pizza", "curry"])
    engine.mimic(["spaghetti"], executable="italy")
Пример #16
0
    def __init__(self, manager, config):
        """TODO: to be defined. """

        super().__init__(config.pop("name"), manager)

        executable = config.pop("executable", None)
        title = config.pop("title", None)
        if title is not None or executable is not None:
            self._contexts.append(AppContext(executable=executable,
                                             title=title))

        # Apply plugin specific contexts
        for plugin_id, desired_state in config.items():

            self._contexts.append(
                    PluginContext(manager, plugin_id, desired_state))
Пример #17
0
    def create_non_ccr_grammar(self, managed_rule):
        details = managed_rule.get_details()
        rule_instance = managed_rule.get_rule_class()(name=details.name)

        if not details.transformer_exclusion:
            rule_instance = self._transformers_runner.transform_rule(
                rule_instance)

        self._smr_configurer.configure(rule_instance)

        context = None
        if details.executable is not None or details.title is not None:
            context = AppContext(executable=details.executable,
                                 title=details.title)
        self._name_uniquefier += 1
        counter = "g" + str(self._name_uniquefier)
        grammar_name = counter if details.grammar_name is None else details.grammar_name + counter
        grammar = Grammar(name=grammar_name, context=context)
        grammar.add_rule(rule_instance)
        return grammar
Пример #18
0
class ChromeURLContext(Context):
    def __init__(self, match=None):
        Context.__init__(self)
        self.chrome_context = AppContext("chrome")
        if isinstance(match, string_types):
            self._matches = [match.lower()]
        elif isinstance(match, (list, tuple)):
            self._matches = [m.lower() for m in match]
        elif match is None:
            self._matches = None
        else:
            raise TypeError("match argument must be a string or None;"
                            " received %r" % match)

    def matches(self, executable, title, handle):
        if not self.chrome_context.matches(executable, title, handle):
            return False
        current_url = utilities.chrome_get_url()
        for match in self._matches:
            if match not in current_url:
                return False
        else:
            return True
Пример #19
0
class ModeManager():
    def __init__(self):
        self.mode = "normal"
        self.frequency = 5
        self.command_titles = ["sublime", "jupyter", "rstudio", "mingw64", "lyx", "scientific notebook"]
        self.command_executables = ["code.exe", "kindle.exe"]
        self.command_contexts = AppContext(title=self.command_titles) | AppContext(self.command_executables)
        self.timer = get_engine().create_timer(self.check_context, self.frequency)

    def switch_mode(self, mode="command"):
        Playback([([mode, "mode", "on"], 0.0)]).execute()
        self.mode = mode

    def check_context(self):
        if natlink.getMicState() == "on":
            w = Window.get_foreground()
            should_be_command = self.command_contexts.matches(w.executable, w.title, w.handle)
            if should_be_command and self.mode == "normal":
                self.switch_mode("command")
            elif not should_be_command and self.mode == "command":
                self.switch_mode("normal")
            else:
                pass
Пример #20
0
def build_grammars():
    putty_context = AppContext(title="bash")
    extraterm_context = AppContext(executable="extraterm")
    netbeans_context = AppContext(executable="netbeans64")
    intellij_context = AppContext(executable="idea64")
    vs_context = AppContext(executable="devenv")
    eclipse_context = AppContext(executable="eclipse")

    bash_context = putty_context | extraterm_context

    vim_context = bash_context | netbeans_context | intellij_context | vs_context | eclipse_context

    java_context = vim_context & (build_form_context(L_JAVA)
                                  | netbeans_context
                                  | intellij_context)

    new_grammars = [
        vim.build_grammar(vim_context),
        forms.default.build_grammar(vim_context
                                    & build_form_context(L_DEFAULT)),
        forms.bash.build_grammar(vim_context & build_form_context(L_BASH)),
        forms.rust.build_grammar(vim_context & build_form_context(L_RUST)),
        forms.cpp.build_grammar(vim_context & build_form_context(L_CPP)),
        forms.cs.build_grammar(vim_context & build_form_context(L_CS)),
        #forms.java  .build_grammar(vim_context & build_form_context(L_JAVA)),
        forms.java.build_grammar(java_context),
        forms.python.build_grammar(vim_context & build_form_context(L_PYTHON)),
        forms.unity.build_grammar(vim_context & build_form_context(L_UNITY)),
        #forms.unreal.build_grammar(vim_context & build_form_context(L_UNREAL)),

        # DO NOT REMOVE THIS
        # The last grammar to load doesn't do anything for some reason
        forms.default.build_grammar(FuncContext(lambda: False)),
    ]

    return new_grammars
Пример #21
0
        "interactive search":
        R(Key("a-percent"), rdescript="Emacs: Interactive Search"),
        "go to line <n>":
        R(Key("a-x, %(n)d"), rdescript="Emacs: Go To Line"),
        "prior bracket":
        R(Key("escape:down, c-b, escape:up"),
          rdescript="Emacs: Prior Bracket"),
        "next bracket":
        R(Key("escape:down, c-f, escape:up"), rdescript="Emacs: Next Bracket"),
    }
    extras = [
        Dictation("text"),
        Dictation("mim"),
        IntegerRefST("n", 1, 1000),
    ]
    defaults = {"n": 1, "mim": ""}


#---------------------------------------------------------------------------

context = AppContext(executable="emacs", title="emacs")
grammar = Grammar("emacs", context=context)

if settings.SETTINGS["apps"]["emacs"]:
    if settings.SETTINGS["miscellaneous"]["rdp_mode"]:
        control.nexus().merger.add_global_rule(EmacsRule())
    else:
        rule = EmacsRule(name="emacs")
        gfilter.run_on(rule)
        grammar.add_rule(rule)
        grammar.load()
Пример #22
0
        R(Key("f9"), rdescript="Visual Studio Code:Breakpoint"),
        "step over [<n>]":
        R(Key("f10/50") * Repeat(extra="n"),
          rdescript="Visual Studio Code:Step Over"),
        "step into":
        R(Key("f11"), rdescript="Visual Studio Code:Step Into"),
        "step out [of]":
        R(Key("s-f11"), rdescript="Visual Studio Code:Step Out"),
        "resume":
        R(Key("f5"), rdescript="Visual Studio Code:Resume"),
    }
    extras = [
        Dictation("text"),
        Dictation("mim"),
        IntegerRefST("n", 1, 1000),
    ]
    defaults = {"n": 1, "mim": "", "text": ""}


#---------------------------------------------------------------------------

context = AppContext(executable="code")
grammar = Grammar("Visual Studio Code", context=context)
if settings.SETTINGS["apps"]["visualstudiocode"]:
    if settings.SETTINGS["miscellaneous"]["rdp_mode"]:
        control.nexus().merger.add_global_rule(VisualStudioCodeRule())
    else:
        rule = VisualStudioCodeRule(name="visualstudiocode")
        gfilter.run_on(rule)
        grammar.add_rule(rule)
        grammar.load()
Пример #23
0
import pyperclip
import re
import copy
from dragonfly import Key, Pause, AppContext, Window
from castervoice.lib import context
from castervoice.lib.ccr.core.punctuation import text_punc_dict
from castervoice.lib.alphanumeric import caster_alphabet

contexts = {
    "texstudio": AppContext(executable="texstudio"),
    "lyx": AppContext(executable="lyx"),
    "winword": AppContext(executable="winword")
}


def get_application():
    window = Window.get_foreground()
    # Check all contexts. Return the name of the first one that matches or
    # "standard" if none matched.
    for name, context in contexts.items():
        if context.matches(window.executable, window.title, window.handle):
            return name
    return "standard"


def get_start_end_position(text, phrase, direction, occurrence_number,
                           dictation_versus_character):
    # def get_start_end_position(text, phrase, direction):
    if dictation_versus_character == "character":
        pattern = re.escape(phrase)
    if dictation_versus_character == "dictation":
Пример #24
0
        Key("ca-w"),
        "[(refactor|re-factor)] (in line|inline)":
        Key("ca-n"),

        # Custom key mappings.
        # "(run SSH session|run SSH console|run remote terminal|run remote console)": Key("a-f11/25, enter"),
    }
    extras = [
        Integer("t", 1, 50),
        Dictation("text"),
        IntegerRef("n", 1, 50000),
        Integer("w", 0, 10),
        Integer("x", 0, 10),
        Integer("y", 0, 10),
        Integer("z", 0, 10),
    ]
    defaults = {
        "t": 1,
    }


context = AppContext(executable="pycharm64")
idea_grammar = Grammar("PyCharm", context=context)
idea_grammar.add_rule(CommandRule())
idea_grammar.load()


def unload():
    global idea_grammar
    idea_grammar = utils.unloadHelper(idea_grammar, __name__)
Пример #25
0
    This module is a simple example of Dragonfly use.

    It shows how to use Dragonfly's Grammar, AppContext, and MappingRule
    classes.  This module can be activated in the same way as other
    Natlink macros by placing it in the "My Documents\Natlink folder" or
    "Program Files\NetLink/MacroSystem".

"""

from dragonfly import (Grammar, AppContext, MappingRule, Choice, Key, Text,
                       Pause)

#---------------------------------------------------------------------------
# Create this module's grammar and the context under which it'll be active.

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"),
Пример #26
0
        R(Function(send_input, nexus=_NEXUS), rdescript="Legion: Action"),
        "refresh":
        R(Function(navigation.mouse_alternates, mode="legion", nexus=_NEXUS),
          rdescript="Legion: Refresh"),
        "exit | escape | cancel":
        R(Function(kill, nexus=_NEXUS), rdescript="Exit Legion"),
    }
    extras = [
        Choice("action", {
            "kick": 0,
            "psychic": 1,
            "light": 2,
        }),
        IntegerRefST("n", 0, 1000),
    ]
    defaults = {
        "action": -1,
    }


#---------------------------------------------------------------------------

context = AppContext(title="legiongrid")
grammar = Grammar("legiongrid", context=context)

if settings.SETTINGS["apps"]["legion"]:
    rule = GridControlRule(name="legion")
    gfilter.run_on(rule)
    grammar.add_rule(rule)
    grammar.load()
Пример #27
0
from aenea import (
    #MappingRule,
    #Grammar,
    Key,
    NoAction,
    Text)

from aenea.proxy_contexts import ProxyAppContext

from dragonfly import (Alternative, AppContext, CompoundRule, Dictation,
                       Grammar, MappingRule, Repetition, RuleRef, Choice,
                       IntegerRef)

general_context = aenea.wrappers.AeneaContext(
    ProxyAppContext(match='regex', title='(?i).*LibreOffice.*'),
    AppContext(title='LibreOffice Writer'))
#vim_context = aenea.wrappers.AeneaContext(
#    ProxyAppContext(match='regex', title='(?i).*eohippus.*'),
#    AppContext(title='mike@eohippus')
#    )
#
#command_t_context = aenea.wrappers.AeneaContext(
#    ProxyAppContext(match='regex', title='^GoToFile.*$'),
#    AppContext(title='GoToFile')
#    ) & vim_context
#
#fugitive_index_context = aenea.wrappers.AeneaContext(
#    ProxyAppContext(match='regex', title='^index.*\.git.*$'),
#    AppContext(title='index') & AppContext('.git')
#    ) & vim_context
Пример #28
0
"""
    This module demonstrates the use of Dragonfly's CompoundRule class.

    It shows how to use Dragonfly's Grammar, AppContext, and CompoundRule
    classes.  This module can be activated in the same way as other
    Natlink macros by placing it in the My Documents\Natlink folder.

"""

from dragonfly import (Grammar, AppContext, CompoundRule, Choice, Dictation)


#---------------------------------------------------------------------------
# Create this module's grammar and the context under which it'll be active.

grammar_context = AppContext(executable="notepad")
grammar = Grammar("notepad_example", context=grammar_context)


#---------------------------------------------------------------------------
# Create a compound rule which demonstrates CompoundRule and Choice types.

class FoodGroupRule(CompoundRule):

    spec   = "(I ate <food> <time> | <time> I ate <food>) [and thought it was <opinion>]"
    time   = {
              "(two days ago | day before yesterday)":  2,
              "yesterday":                              1,
              "today":                                  0,
             }
    food   = {
Пример #29
0
        Key("ca-w"),
        "[(refactor|re-factor)] (in line|inline)":
        Key("ca-n"),

        # Custom key mappings.
        # "(run SSH session|run SSH console|run remote terminal|run remote console)": Key("a-f11/25, enter"),
    }
    extras = [
        Integer("t", 1, 50),
        Dictation("text"),
        IntegerRef("n", 1, 50000),
        Integer("w", 0, 10),
        Integer("x", 0, 10),
        Integer("y", 0, 10),
        Integer("z", 0, 10),
    ]
    defaults = {
        "t": 1,
    }


context = AppContext(executable="idea64")
idea_grammar = Grammar("IntelliJ Idea", context=context)
idea_grammar.add_rule(CommandRule())
idea_grammar.load()


def unload():
    global idea_grammar
    idea_grammar = utils.unloadHelper(idea_grammar, __name__)
Пример #30
0
        'open new tab': Key('c-t'),
        'duplicate tab': Key('y/25,t'),  # vimium
        'reopen tab': Key('cs-t'),
        '[go to] next tab': Key('c-pgdown'),
        '[go to] previous tab': Key('c-pgup'),
        'go to tab <tab>': Key('c-%(tab)d'),
        '[go to] first tab': Key('c-1'),
        '[go to] last tab': Key('c-9'),
        'go back': Key('a-left'),
        'go forward': Key('a-right'),
        'go to address': Key('a-d'),
        'reload page': Key('f5'),
        'show labels': Key('f'),  # vimium
        'show labels in new tab': Key('s-f'),  # vimium
        '[go to] label <number>': Text('%(number)d'),  # vimium
        'duplicate tab': Key('y,t'),  # vimium
    }
    extras = [Integer('tab', 1, 8), Integer('number', 1, 9999)]


context = AppContext(executable='chrome')
grammar = Grammar('Google Chrome', context=context)
grammar.add_rule(GlobalChromeMappings())
grammar.load()


def unload():
    global grammar
    if grammar: grammar.unload()
    grammar = None
Пример #31
0
                "(itemize | bullets)": "b",
                "(enumerate | numbering)": "e",
                "description": "d",
                "part": "0",
                "section": "2",
                "subsection": "3",
                "subsubsection": "4",
                "paragraph": "5",
                "subparagraph": "6",
                "title": "t",
                "author": "s-a",
                "date": "s-d",
                "abstract": "a",
                "address": "a-a",
                "(bibliography | biblio)": "s-b",
                "quotation": "a-q",
                # i'm not sure what the differences between quotation and quote
                "quote": "q",
                "verse": "v",
            }),
    ]
    defaults = {
        "n": 1,
    }


context = AppContext(executable="lyx")
grammar = Grammar("lyx", context=context)
rule = LyxRule(name="lyx")
grammar.add_rule(rule)
grammar.load()