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__()
def __init__(self): self.folders = DictList("folders") super(OutlookControlGrammar,self).__init__( name="Microsoft Outlook control", context=AppContext(executable="outlook"), app_name="Outlook.Application" )
class OutlookControlGrammar(ConnectionGrammar): def __init__(self): self.folders = DictList("folders") super(OutlookControlGrammar,self).__init__( name="Microsoft Outlook control", context=AppContext(executable="outlook"), app_name="Outlook.Application" ) def connection_up(self): self.update_folders() def connection_down(self): self.reset_folders() def update_folders(self): root_folder = self.application.Session.DefaultStore.GetRootFolder() self.folders.set({}) stack = [collection_iter(root_folder.Folders)] while stack: try: folder = stack[-1].next() except StopIteration: stack.pop() continue self.folders[folder.Name] = folder stack.append(collection_iter(folder.Folders)) def reset_folders(self): self.folders.set({}) def get_active_explorer(self): try: explorer = self.application.ActiveExplorer() except com_error, e: self._log.warning('%s: COM error getting active explorer: %s' % (self, e)) return None if not explorer: self._log_warning('%s: no active explorer.' % self) return None return explorer
class StyleRule(CompoundRule): spec = config.lang.set_style styles = DictList("styles") extras = [DictListRef("style", styles)] def _process_recognition(self, node, extras): try: document = self.grammar.application.ActiveDocument document.ActiveWindow.Selection.Style = extras["style"] except com_error, e: if self._log_proc: self._log_proc.warning("Rule %s:" " failed to set style: %s." % (self, e))
def add_builtin_rules(self): # The DictList makes it easy to add new mappings from command context names # which will be recognised by the "enable/disable" command to the contexts themselves self.command_context_dictlist = DictList("manual_contexts") self.add_rule(ContextSwitcher(self.command_context_dictlist)) rebuild_command = os.getenv( "BREATHE_REBUILD_COMMAND") or "rebuild everything" self.add_rule( SimpleRule( name="rebuilder", element=BoundCompound( rebuild_command, value=Function(lambda: self.reload_modules())), ))
config = Config("config manager") config.lang = Section("Language section") config.lang.list_configs = Item("list configs", doc="Command to ...") config.lang.edit_config = Item("edit <config> (config | configuration)", doc="Command to ...") config.lang.show_dragonfly_version = Item("show dragonfly version", doc="Command to ...") config.lang.update_dragonfly = Item("update dragonfly version", doc="Command to ...") config.lang.reload_natlink = Item("reload natlink", doc="Command to ...") config.load() #--------------------------------------------------------------------------- config_map = DictList("config_map") #--------------------------------------------------------------------------- class ConfigManagerGrammar(Grammar): def __init__(self): Grammar.__init__(self, name="config manager", context=None) def _process_begin(self, executable, title, handle): configs = Config.get_instances() # Check for modified config files, and if found cause reload. new_config_map = {} for c in configs: new_config_map[c.name] = c
config.settings.defaults = Item({"fire": ( "firefox", None)}, doc="Default window names. Maps spoken-forms to (executable, title) pairs.") # config.generate_config_file() config.load() # =========================================================================== # Create this module's main grammar object. winControlGrammar = Grammar("window control") # --------------------------------------------------------------------------- # Dictionary list of window and monitor names. win_names = DictList("win_names") win_names_ref = DictListRef("win_names", win_names) mon_names = DictList("mon_names") mon_names_ref = DictListRef("mon_names", mon_names) # Populate monitor names. for i, m in enumerate(monitors): mon_names[str(i+1)] = m # --------------------------------------------------------------------------- # Default window names handling. default_names = config.settings.defaults # Pre-populate the win_names mapping with the given default names.
from dragonfly import MappingRule, Function, Dictation, Grammar, DictList, DictListRef, Text, Clipboard clipboard = Clipboard() vocab_dict = DictList('vocab_dict') vocab_dict['test'] = 'test_vocab' def add_clipboard_contents_to_vocabulary(text): # note that set clipboard=unnamaedplus is needed to work with vim clipboard.copy_from_system() clip_text = clipboard.get_text() if text and clip_text: vocab_dict[str(text)] = clip_text def del_from_vocabulary(text): vocab_dict.pop(str(text), None) def clear_vocabulary(): vocab_dict.clear() def type_out_vocabulary(): action = Text('%(key)s: %(value)s') for k, v in vocab_dict.items(): action.bind({'key': k, 'value': v}).execute() class VocabRule(MappingRule): mapping = {
#"neck": "n", #"ork": "o", "pork": "p", #"quest": "q", #"rug": "r", "sea": "span", "tan": "table", "ush": "ul", #"van": "v", #"wish": "w", #"trex": "x", #"yang": "y", #"zulu": "z", } web_container_map_dict_list = DictList("web_container_map_dict_list", web_container_map) css_words_map = { # "ace": "a", "bed": "border", "chair": "color", "dell": "display", # "egg": "e", "fame": "font", # "golf": "g", "heart": "height", # "ice": "i", # "joy": "j", # "king": "k", # "love": "l", "mars": "margin",
class BringMeBase(MappingRule): """Docstring for BringMeBase. """ type = "base" 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__() entities = property(lambda self: self._entities.copy(), doc='TODO') log = property(lambda self: logging.getLogger("casterplugin.{}" .format(self)), doc='TODO') def __str__(self): return self.__class__.__name__ def subscribe(self, callback): """TODO: callback is called everytime the entities are altered by the user. :returns: TODO """ self._subscribers.append(callback) def bring_me(self, entity): """TODO: Docstring for bring_me. :returns: TODO """ self._bring_me(entity) def bring_me_as(self, entity_type, entity_name): """TODO: Docstring for bring_me_as. :returns: TODO """ assert entity_type == self.type self.log.info('Bringing you %s as "%s"', entity_type, entity_name) self._bring_me_as(entity_name) for subscriber in self._subscribers: subscriber() def bring_me_remove(self, entity_name): self.log.info('Removing "%s" from BringMe', entity_name) self._entities.pop(str(entity_name)) for subscriber in self._subscribers: subscriber() def _bring_me(self, entity): raise NotImplementedError("Please bring me something!") def _bring_me_as(self, entity_name): raise NotImplementedError("Let me bring new stuff!")
def get_mapping(name): if name not in mappings: mappings[name] = DictList(name) return mappings[name]
"k": Text(r" k"), "x": Text(r" x"), "y": Text(r" y"), "z": Text(r" z"), 'squared': Text('^2'), 'plus': Text('+'), 'minus': Text('-'), 'cross': Text(r'\times'), 'times': Text(r'\times'), 'dot product': Text(r'\dot'), 'fraction': Text(r'\frac{}{}') + Key('left:3'), # 'to the <nth>': Text('^%(nth)s'), }) math_commands = DictList('math_commands') def process_math_command(math_command): math_command.execute() def start_inline(): start_math() math_commands['end math'] = Text('$ ') + Function( lambda: math_commands.clear()) math_commands['end inline'] = Text('$ ') + Function( lambda: math_commands.clear()) def start_align():
"zulu": "z", } # Actions for speaking out sequences of characters. character_action_map = { "sign <numerals>": Text("%(numerals)s"), "print <letters>": Text("%(letters)s"), "shout <letters>": Function(lambda letters: Text(letters.upper()).execute()), } char_map = dict( (k, v.strip()) for (k, v) in utils.combine_maps(letters_map).iteritems()) # Simple elements that may be referred to within a rule. numbers_dict_list = DictList("numbers_dict_list", numbers_map) letters_dict_list = DictList("letters_dict_list", letters_map) char_dict_list = DictList("char_dict_list", char_map) letters_map_dict_list = DictList("letters_map_dict_list", letters_map) # A sequence of either short letters or long letters. letters_element = RuleWrap( None, utils.JoinedRepetition("", DictListRef(None, letters_dict_list), min=1, max=10)) # A sequence of numbers. numbers_element = RuleWrap( None,