def pita(textnv): global OLD_ACTIVE_WINDOW_TITLE, ACTIVE_FILE_PATH filename, folders, title = utilities.get_window_title_info() active_has_changed = OLD_ACTIVE_WINDOW_TITLE != title # check to see if the active file has changed; if not, skip this step if active_has_changed: OLD_ACTIVE_WINDOW_TITLE = title ACTIVE_FILE_PATH = scanner.guess_file_based_on_window_title(filename, folders) if filename == None: utilities.report("pita: filename pattern not found in window title") return if ACTIVE_FILE_PATH[0] != None: global CHOICES CHOICES = selector.get_similar_symbol_name(str(textnv), scanner.DATA["directories"][ACTIVE_FILE_PATH[0]][ACTIVE_FILE_PATH[1]]["names"]) try: if settings.SETTINGS["miscellaneous"]["status_window_enabled"]: display = "" counter = 1 for result in CHOICES: if counter>1: display+="\n" display+=str(counter)+" "+result[1] counter+=1 control.nexus().intermediary.hint(display) except Exception: utilities.simple_log()
def execute(fname): try: global server_proxy fn = getattr(server_proxy, fname) fn() except Exception: utilities.simple_log()
def rescan_current_file(): global DATA try: filename, folders, title = utilities.get_window_title_info() current_file_path = guess_file_based_on_window_title(filename, folders) scanned_file = _scan_single_file(current_file_path[1], LanguageFilter("." + filename.split(".")[-1])) # find out exact match in DATA file_was_found=False break_outer = False for d in DATA["directories"]: for f in DATA["directories"][d]: if f == current_file_path[1]: DATA["directories"][d][f] = scanned_file utilities.save_json_file(DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"]) break_outer = True file_was_found=True break if break_outer: break if not file_was_found: if not "uncategorized" in DATA["directories"]: DATA["directories"]["uncategorized"]={} DATA["directories"]["uncategorized"][current_file_path[1]]=scanned_file utilities.save_json_file(DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"]) except Exception: utilities.simple_log()
def fix_dragon_double(): try: lr = control.nexus().history[len(control.nexus().history) - 1] lu = " ".join(lr) Key("left/5:" + str(len(lu)) + ", del").execute() except Exception: utilities.simple_log(False)
def read_selected_without_altering_clipboard(same_is_okay=False): '''Returns a tuple: (0, "text from system") - indicates success (1, None) - indicates no change (2, None) - indicates clipboard error, should not advance cursor before trying again ''' time.sleep(0.05) # time for previous keypress to execute cb = Clipboard(from_system=True) temporary = None prior_content = None try: prior_content = Clipboard.get_system_text() Clipboard.set_system_text("") Key("c-c").execute() time.sleep(0.05) # time for keypress to execute temporary = Clipboard.get_system_text() cb.copy_to_system() except Exception: utilities.simple_log(False) return (2, None) if prior_content == temporary and not same_is_okay: return (1, None) return (0, temporary)
def _scan_directory(data): ''' Adds a scan of the directory to DATA ''' global DATA directory = data["path"] languageFilters = {} scanned_directory = {} try: for base, dirs, files in os.walk( directory ): # traverse base directory, and list directories as dirs and files as files for fname in files: extension = "." + fname.split(".")[-1] if not (extension in languageFilters): languageFilters[extension] = LanguageFilter(extension) if extension in settings.SETTINGS["pita"]["extensions"]: # scanned_file is a list scanned_file = _scan_single_file( base + "/" + fname, languageFilters[extension]) # scanned_directory["absolute path to file"] = that list scanned_directory[base.replace("\\", "/") + "/" + fname] = scanned_file except Exception: utilities.simple_log(True) if "directories" not in DATA: DATA["directories"] = {} DATA["directories"][directory] = scanned_directory utilities.save_json_file(DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"])
def rescan_current_file(): global DATA try: filename, folders, title = utilities.get_window_title_info() current_file_path = guess_file_based_on_window_title(filename, folders) scanned_file = _scan_single_file( current_file_path[1], LanguageFilter("." + filename.split(".")[-1])) # find out exact match in DATA file_was_found = False break_outer = False for d in DATA["directories"]: for f in DATA["directories"][d]: if f == current_file_path[1]: DATA["directories"][d][f] = scanned_file utilities.save_json_file( DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"]) break_outer = True file_was_found = True break if break_outer: break if not file_was_found: if not "uncategorized" in DATA["directories"]: DATA["directories"]["uncategorized"] = {} DATA["directories"]["uncategorized"][ current_file_path[1]] = scanned_file utilities.save_json_file( DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"]) except Exception: utilities.simple_log()
def repeat_that(n): try: if len(control.nexus().history) > 0: for i in range(int(n)): Playback([([str(x) for x in " ".join(control.nexus().history[len(control.nexus().history) - 1]).split()], 0.0)])._execute() except Exception: utilities.simple_log(False)
def add_vocab(): engine = dragonfly.get_engine() if engine.name != "natlink": utilities.report( "feature unavailable in your speech recognition engine", speak=True) return # attempts to get what was highlighted first highlighted = context.read_selected_without_altering_clipboard(True) # change the following regex to accept alphabetical only disallow = "^[A-Za-z]*$" selected = None if highlighted[0] == 0 and highlighted[1] != "": if not re.match(disallow, highlighted[1]): utilities.report("only used for single words", speak=True) return selected = highlighted[1] try: h_launch.launch(settings.QTYPE_SET, process_set, selected) except Exception: utilities.simple_log(False)
def main(argv): help_message = 'legion.py -t <tirg> -d <dimensions> -a <autoquit>' tirg = None dimensions = None auto_quit = False try: opts, args = getopt.getopt(argv, "ht:a:d:", ["tirg=", "dimensions=", "autoquit="]) except getopt.GetoptError: print help_message sys.exit(2) try: for opt, arg in opts: if opt == '-h': print help_message sys.exit() elif opt in ("-t", "--tirg"): tirg = arg elif opt in ("-d", "--dimensions"): # wxh+x+y dimensions = Dimensions(*[int(n) for n in arg.split("_")]) elif opt in ("-a", "--autoquit"): auto_quit = arg in ("1", "t") lg = LegionGrid(grid_size=dimensions, tirg=tirg, auto_quit=auto_quit) except Exception: utilities.simple_log(True)
def stoosh_keep_clipboard(nnavi500, nexus): if nnavi500 == 1: Key("c-c").execute() else: max_tries = 20 cb = Clipboard(from_system=True) Key("c-c").execute() key = str(nnavi500) for i in range(0, max_tries): failure = False try: # time for keypress to execute time.sleep( settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) nexus.clip[key] = Clipboard.get_system_text() utilities.save_toml_file( nexus.clip, settings.SETTINGS["paths"]["SAVED_CLIPBOARD_PATH"]) except Exception: failure = True utilities.simple_log() if not failure: break cb.copy_to_system()
def _scan_directory(data, nexus): ''' Adds a scan of the directory to DATA ''' global DATA directory = data["path"] languageFilters = {} scanned_directory = {} try: for base, dirs, files in os.walk(directory): # traverse base directory, and list directories as dirs and files as files for fname in files: extension = "." + fname.split(".")[-1] if not extension in languageFilters: languageFilters[extension] = LanguageFilter(extension) if extension in settings.SETTINGS["pita"]["extensions"]: # scanned_file is a list scanned_file = _scan_single_file(base + "/" + fname, languageFilters[extension], nexus) # scanned_directory["absolute path to file"] = that list scanned_directory[base.replace("\\", "/") + "/" + fname] = scanned_file except Exception: utilities.simple_log(True) if "directories" not in DATA: DATA["directories"] = {} DATA["directories"][directory] = scanned_directory utilities.save_json_file(DATA, settings.SETTINGS["paths"]["PITA_JSON_PATH"])
def main(argv): help_message = 'legion.py -t <tirg> [-m <monitor>] [-d <dimensions>] [-a <autoquit>]' tirg = None monitor = 1 dimensions = None auto_quit = False try: opts, args = getopt.getopt(argv, "ht:a:d:m:", ["tirg=", "dimensions=", "autoquit="]) except getopt.GetoptError: print(help_message) sys.exit(2) try: for opt, arg in opts: if opt == '-h': print(help_message) sys.exit() elif opt in ("-t", "--tirg"): tirg = arg elif opt == '-m': monitor = arg elif opt in ("-d", "--dimensions"): # wxh+x+y dimensions = Dimensions(*[int(n) for n in arg.split("_")]) elif opt in ("-a", "--autoquit"): auto_quit = arg in ("1", "t") if dimensions is None: r = monitors[int(monitor)-1].rectangle dimensions = Dimensions(int(r.dx), int(r.dy), int(r.x), int(r.y)) lg = LegionGrid(grid_size=dimensions, tirg=tirg, auto_quit=auto_quit) except Exception: utilities.simple_log(True)
def main(argv): help_message = 'legion.py -t <tirg> [-m <monitor>] [-d <dimensions>] [-a <autoquit>]' tirg = None monitor = 1 dimensions = None auto_quit = False try: opts, args = getopt.getopt(argv, "ht:a:d:m:", ["tirg=", "dimensions=", "autoquit="]) except getopt.GetoptError: print(help_message) sys.exit(2) try: for opt, arg in opts: if opt == '-h': print(help_message) sys.exit() elif opt in ("-t", "--tirg"): tirg = arg elif opt == '-m': monitor = arg elif opt in ("-d", "--dimensions"): # wxh+x+y dimensions = Dimensions(*[int(n) for n in arg.split("_")]) elif opt in ("-a", "--autoquit"): auto_quit = arg in ("1", "t") if dimensions is None: r = monitors[int(monitor) - 1].rectangle dimensions = Dimensions(int(r.dx), int(r.dy), int(r.x), int(r.y)) lg = LegionGrid(grid_size=dimensions, tirg=tirg, auto_quit=auto_quit) except Exception: utilities.simple_log(True)
def fix_dragon_double(nexus): try: lr = nexus.history[len(nexus.history) - 1] lu = " ".join(lr) Key("left/5:" + str(len(lu)) + ", del").execute() except Exception: utilities.simple_log(False)
def mouse_alternates(mode): if control.nexus().dep.PIL: try: if mode == "legion": if utilities.window_exists(None, "legiongrid"): pass else: ls = LegionScanner() ls.scan() #[500, 500, 1000, 1000] tscan = ls.get_update() Popen([ "pythonw", settings.SETTINGS["paths"]["LEGION_PATH"], "-t", tscan[0] ]) #, "-d", "500_500_500_500" elif mode == "rainbow": Popen([ "pythonw", settings.SETTINGS["paths"]["RAINBOW_PATH"], "-m", "r" ]) elif mode == "douglas": Popen([ "pythonw", settings.SETTINGS["paths"]["DOUGLAS_PATH"], "-m", "d" ]) except Exception: utilities.simple_log(True) else: utilities.availability_message(mode.title(), "PIL")
def _run_filters(self, merge_pair): for filter_fn in self._filters: try: filter_fn(merge_pair) except Exception: utilities.simple_log() print("Filter function '" + filter_fn.__name__ + "' failed.")
def check_for_response(): global LAST_QUERY, TRIES if LAST_QUERY != None: data = None try: data = control.nexus().comm.get_com("hmc").get_message() except Exception: utilities.simple_log() TRIES+=1 if TRIES>9: # try 10 times max if there's no Homonculus TRIES=0 control.nexus().timer.remove_callback(check_for_response) return if data == None: return try: LAST_QUERY.callback(data) except Exception: utilities.simple_log(False) LAST_QUERY = None if LAST_QUERY == None: control.nexus().timer.remove_callback(check_for_response)
def read_selected_without_altering_clipboard(same_is_okay=False): '''Returns a tuple: (0, "text from system") - indicates success (1, None) - indicates no change (2, None) - indicates clipboard error ''' time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) # time for previous keypress to execute cb = Clipboard(from_system=True) temporary = None prior_content = None try: prior_content = Clipboard.get_system_text() Clipboard.set_system_text("") Key("c-c").execute() time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) # time for keypress to execute temporary = Clipboard.get_system_text() cb.copy_to_system() except Exception: utilities.simple_log(False) return 2, None if prior_content == temporary and not same_is_okay: return 1, None return 0, temporary
def check_for_response(): global LAST_QUERY, TRIES if LAST_QUERY != None: data = None try: data = control.nexus().comm.get_com("hmc").get_message() except Exception: TRIES+=1 if TRIES>9: TRIES=0 control.nexus().timer.remove_callback(check_for_response) return if data == None: return try: LAST_QUERY.callback(data) except Exception: utilities.simple_log(False) LAST_QUERY = None if LAST_QUERY == None: control.nexus().timer.remove_callback(check_for_response)
def read_selected_without_altering_clipboard(same_is_okay=False): '''Returns a tuple: (0, "text from system") - indicates success (1, None) - indicates no change (2, None) - indicates clipboard error ''' time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/1000.) # time for previous keypress to execute cb = Clipboard(from_system=True) temporary = None prior_content = None try: prior_content = Clipboard.get_system_text() Clipboard.set_system_text("") Key("c-c").execute() time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/1000.) # time for keypress to execute temporary = Clipboard.get_system_text() cb.copy_to_system() except Exception: utilities.simple_log(False) return 2, None if prior_content == temporary and not same_is_okay: return 1, None return 0, temporary
def experiment(text): '''this function is for tests''' try: '''''' print str(text) except Exception: utilities.simple_log(False)
def update(name, value): # settings try: control.nexus().node_rule_active(name, value) ccr.set_active() ccr.refresh() except Exception: utilities.simple_log()
def initialize_ccr(): try: for r in settings.SETTINGS["ccr"]["modes"]: if settings.SETTINGS["ccr"]["modes"][r]: set_active(r) refresh() except Exception: utilities.simple_log()
def experiment(text): """this function is for tests""" try: """""" print str(text) except Exception: utilities.simple_log(False)
def navigate_to_character(direction3, target): # to do: possibly speed up the keypresses by figuring out how many lines up or down to go first try: left_or_right = str(direction3) look_left = left_or_right == "left" is_character = False for s in target.split("~"): if s in ".,()[]{}<>": is_character = True break # make sure nothing is highlighted to boot Key("right, left" if look_left else "left, right").execute() if look_left: Key("cs-left").execute() else: Key("cs-right").execute() # max_highlights = 100 index = -1 # last_copy_was_successful = True context = None tries = 0 while context == None: tries += 1 results = read_selected_without_altering_clipboard() error_code = results[0] if error_code == 0: context = results[1] break if tries > 5: return False # if we got to this point, we have a copy result, index = find_index_in_context(target, context, look_left) # highlight only the target if index != -1: Key("left" if look_left else "right").execute() nt = index if look_left else len( context ) - index - 1 # number of times to press left or right before the highlight if nt != 0: Key("right/5:" + str(nt) if look_left else "left/5:" + str(nt)).execute() if is_character: Key("s-right" if look_left else "s-left").execute() else: Key("cs-right" if look_left else "cs-left").execute() return True else: # reset cursor Key("left" if look_left else "right").execute() return False except Exception: utilities.simple_log(False)
def rewrite_alias_module(ccr_, non_): ''' ccr_, non_ are tuples in the form (spec, text), and are nullable ''' global LINE_PATTERN add = ccr_ != None or non_ != None a = ccr_ if ccr_ != None else non_ ccr_open = False non_open = False written = False exists = os.path.isfile(settings.SETTINGS["paths"]["ALIASES_PATH"]) lines = [] if not add or not exists: lines = [x + "\n" for x in ccr.MODULE_SHELL] else: # read in the file try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "r+") as f: lines = f.readlines() except Exception: utilities.simple_log(True) if a != None: for line in lines: # do overwrite if same words are chosen match_object = LINE_PATTERN.findall(line) if len(match_object) > 0: if match_object[0][0] == a[0]: lines.remove(line) break try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "w+") as f: for line in lines: if line.isspace(): continue if ccr.MODULE_MARKERS[0] in line: ccr_open = True elif ccr.MODULE_MARKERS[1] in line: ccr_open = False elif ccr.MODULE_MARKERS[2] in line: non_open = True elif ccr.MODULE_MARKERS[3] in line: non_open = False f.write(line) if add: if not written: if (ccr_open and ccr_ != None) or (non_open and non_ != None): # need to escape for reading back in spec = a[0].replace("'", "\\'").replace("\\", "\\\\") text = a[1].replace("'", "\\'").replace( "\\", "\\\\").replace("\r", "").replace("\n", "\\n") f.write("'" + spec + "': Text('" + text + "'),\n") written = True except Exception: utilities.simple_log(True)
def refresh(): global _grammar _grammar.unload() while len(_grammar.rules)>0: _grammar.remove_rule(_grammar.rules[0]) try: rule = generate_rule(settings.SETTINGS["paths"]["CONFIGDEBUGTXT_PATH"]) _grammar.add_rule(rule) _grammar.load() except Exception: utilities.simple_log()
def navigate_to_character(direction3, target): # to do: possibly speed up the keypresses by figuring out how many lines up or down to go first try: left_or_right = str(direction3) look_left = left_or_right == "left" is_character = False for s in target.split("~"): if s in ".,()[]{}<>": is_character=True break # make sure nothing is highlighted to boot Key("right, left" if look_left else "left, right")._execute() if look_left: Key("cs-left")._execute() else: Key("cs-right")._execute() # max_highlights = 100 index = -1 # last_copy_was_successful = True context = None tries=0 while context==None: tries+=1 results = read_selected_without_altering_clipboard() error_code = results[0] if error_code==0: context = results[1] break if tries>5: return False # if we got to this point, we have a copy result, # print "have copy result: "+context index = find_index_in_context(target, context, look_left) # highlight only the target if index != -1: Key("left" if look_left else "right")._execute() nt = index if look_left else len(context) - index - 1 # number of times to press left or right before the highlight if nt != 0: Key("right/5:" + str(nt) if look_left else "left/5:" + str(nt))._execute() if is_character: Key("s-right" if look_left else "s-left")._execute() else: Key("cs-right" if look_left else "cs-left")._execute() # print "success" return True else: # reset cursor Key("left" if look_left else "right")._execute() return False except Exception: utilities.simple_log(False)
def is_valid(module): ''' This function attempts to import the applications in order to detect errors in their implementation . After they are imported, they are garbage collected when the function returns.''' try: _ = __import__(module, globals(), locals()) return True except Exception as e: print("Ignoring application '{}'. Failed to load with: ".format(module)) utilities.simple_log() return False
def experiment(text): '''this function is for tests''' try: '''''' exes = set([x.executable.split("\\")[-1][:-4] for x in Window.get_all_windows()]) titles = set([x.title for x in Window.get_all_windows()]) # print get_similar_process_name(exes) print titles except Exception: utilities.simple_log(False)
def refresh(): global _grammar _grammar.unload() while len(_grammar.rules) > 0: _grammar.remove_rule(_grammar.rules[0]) try: rule = generate_rule(settings.SETTINGS["paths"]["CONFIGDEBUGTXT_PATH"]) _grammar.add_rule(rule) _grammar.load() except Exception: utilities.simple_log()
def repeat_that(n): try: if len(control.nexus().history) > 0: p = [ str(x) for x in " ".join(control.nexus().history[ len(control.nexus().history) - 1]).split() ] # print p for i in range(int(n)): Playback([(p, 0.0)]).execute() except Exception: utilities.simple_log(False)
def rewrite_alias_module(ccr_, non_): ''' ccr_, non_ are tuples in the form (spec, text), and are nullable ''' global LINE_PATTERN add = ccr_ != None or non_ != None a = ccr_ if ccr_!=None else non_ ccr_open = False non_open = False written = False exists = os.path.isfile(settings.SETTINGS["paths"]["ALIASES_PATH"]) lines = [] if not add or not exists: lines = [x+"\n" for x in ccr.MODULE_SHELL] else: # read in the file try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "r+") as f: lines = f.readlines() except Exception: utilities.simple_log(True) if a != None: for line in lines:# do overwrite if same words are chosen match_object = LINE_PATTERN.findall(line) if len(match_object) > 0: if match_object[0][0]==a[0]: lines.remove(line) break try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "w+") as f: for line in lines: if line.isspace(): continue if ccr.MODULE_MARKERS[0] in line: ccr_open = True elif ccr.MODULE_MARKERS[1] in line: ccr_open = False elif ccr.MODULE_MARKERS[2] in line: non_open = True elif ccr.MODULE_MARKERS[3] in line: non_open = False f.write(line) if add: if not written: if (ccr_open and ccr_ != None) or (non_open and non_ != None): # need to escape for reading back in spec=a[0].replace("'", "\\'").replace("\\", "\\\\") text=a[1].replace("'", "\\'").replace("\\", "\\\\").replace("\r", "").replace("\n", "\\n") f.write("'"+ spec + "': Text('" + text + "'),\n") written = True except Exception: utilities.simple_log(True)
def navigate_to_character(direction3, target, fill=False): try: look_left = str(direction3) == "left" # make sure nothing is highlighted to boot if not fill:# (except when doing "fill" -- if at end of line, there is no space for this ) Key("right, left" if look_left else "left, right").execute() if look_left: Key("cs-left").execute() else: Key("cs-right").execute() context = None tries = 0 while context is None: tries+=1 results = read_selected_without_altering_clipboard() error_code = results[0] if error_code==0: context = results[1] break if tries > 5: return False # if we got to this point, we have a copy result index = _find_index_in_context(target, context, look_left) if index != -1:# target found '''move the cursor to the left of the target if looking left, to the right of the target if looking right:''' Key("left" if look_left else "right").execute() '''number of times to press left or right before the highlight (the target may be a part of a fully highlighted word): ''' nt = index if look_left else len(context) - index - 1 if nt != 0: Key("right/5:" + str(nt) if look_left else "left/5:" + str(nt)).execute() '''highlight only the target''' if _target_is_character(target): Key("s-right" if look_left else "s-left").execute() else: Key("cs-right" if look_left else "cs-left").execute() return True else: # reset cursor Key("left" if look_left else "right").execute() return False except Exception: utilities.simple_log()
def experiment(text): '''this function is for tests''' try: '''''' exes = set([ x.executable.split("\\")[-1][:-4] for x in Window.get_all_windows() ]) titles = set([x.title for x in Window.get_all_windows()]) # print get_similar_process_name(exes) print titles except Exception: utilities.simple_log(False)
def lines_relative(self, back, n): if back: #backward try: num = CONTEXT.read_nmax_tries(10) txt = str(int(num) - int(n) + 1) # +1 to include current line Text(txt).execute() except ValueError: utilities.simple_log() return Key("enter").execute() else: #forward Key("escape, end, home, home").execute( ) # end-home-home to include all of current line # forward or backward Key("s-down:" + str(int(n)) + "/5, s-left").execute()
def check_for_response(): try: _data = self.nexus().comm.get_com("hmc").get_message() except Exception: if log_failure: utilities.simple_log() _["tries"]+=1 if _["tries"]>9: return True # try 10 times max if there's no Homonculus response else: return False if _data is None: return False try: _data.append(_["dragonfly_data"]) # pass dragonfly data into receiver function _["dragonfly_data"] = None receiver(_data) except Exception: if log_failure: utilities.simple_log() return True
def mouse_alternates(mode): if control.nexus().dep.PIL: try: if mode == "legion": if utilities.window_exists(None, "legiongrid"): pass else: ls = LegionScanner() ls.scan()#[500, 500, 1000, 1000] tscan = ls.get_update() Popen(["pythonw", settings.SETTINGS["paths"]["LEGION_PATH"], "-t", tscan[0]])#, "-d", "500_500_500_500" elif mode == "rainbow": Popen(["pythonw", settings.SETTINGS["paths"]["RAINBOW_PATH"], "-m", "r"]) elif mode == "douglas": Popen(["pythonw", settings.SETTINGS["paths"]["DOUGLAS_PATH"], "-m", "d"]) except Exception: utilities.simple_log(True) else: utilities.availability_message(mode.title(), "PIL")
def check_for_response(): try: _data = self.nexus().comm.get_com("hmc").get_message() except Exception: if log_failure: utilities.simple_log() _["tries"] += 1 if _["tries"] > 9: return True # try 10 times max if there's no Homonculus response else: return False if _data is None: return False try: _data.append(_["dragonfly_data"] ) # pass dragonfly data into receiver function _["dragonfly_data"] = None receiver(_data) except Exception: if log_failure: utilities.simple_log() return True
def navigate_to_character(direction3, target, fill=False): try: look_left = str(direction3) == "left" # make sure nothing is highlighted to boot if not fill: # (except when doing "fill" -- if at end of line, there is no space for this ) Key("right, left" if look_left else "left, right").execute() if look_left: Key("cs-left").execute() else: Key("cs-right").execute() context = read_nmax_tries(5, .01) if context is None: return False # if we got to this point, we have a copy result index = _find_index_in_context(target, context, look_left) if index != -1: # target found '''move the cursor to the left of the target if looking left, to the right of the target if looking right:''' Key("left" if look_left else "right").execute() '''number of times to press left or right before the highlight (the target may be a part of a fully highlighted word): ''' nt = index if look_left else len(context) - index - 1 if nt != 0: Key("right/5:" + str(nt) if look_left else "left/5:" + str(nt)).execute() '''highlight only the target''' if _target_is_character(target): Key("s-right" if look_left else "s-left").execute() else: Key("cs-right" if look_left else "cs-left").execute() return True else: # reset cursor Key("left" if look_left else "right").execute() return False except Exception: utilities.simple_log()
def rewrite_alias_module(ccr_, non_): ''' ccr_, non_ are tuples in the form (spec, text), and are nullable ''' add = ccr_ != None or non_ != None ccr_open = False non_open = False written = False exists = os.path.isfile(settings.SETTINGS["paths"]["ALIASES_PATH"]) lines = [] if not add or not exists: lines = ccr.MODULE_SHELL else: # read in the file try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "r+") as f: lines = f.readlines() except Exception: utilities.simple_log(True) try: with open(settings.SETTINGS["paths"]["ALIASES_PATH"], "w+") as f: for line in lines: if line.isspace(): continue if ccr.MODULE_MARKERS[0] in line: ccr_open = True elif ccr.MODULE_MARKERS[1] in line: ccr_open = False elif ccr.MODULE_MARKERS[2] in line: non_open = True elif ccr.MODULE_MARKERS[3] in line: non_open = False # print str(add), str(ccr_open), str(non_open), str(written) f.write(line + "\n") if add: if not written: if (ccr_open and ccr_ != None) or (non_open and non_ != None): a = ccr_ if ccr_open else non_ f.write("'" + a[0] + "': Text('" + a[1] + "'),") written = True except Exception: utilities.simple_log(True)
def clipboard_to_file(nnavi500, nexus, do_copy=False): if do_copy: Key("c-c").execute() max_tries = 20 key = str(nnavi500) for i in range(0, max_tries): failure = False try: time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/1000.) # time for keypress to execute win32clipboard.OpenClipboard() nexus.clip[key] = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() utilities.save_json_file(nexus.clip, settings.SETTINGS["paths"]["SAVED_CLIPBOARD_PATH"]) except Exception: failure = True utilities.simple_log() if not failure: break
def paste_string_without_altering_clipboard(content): ''' True - indicates success False - indicates clipboard error ''' time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/ 1000.) # time for previous keypress to execute cb = Clipboard(from_system=True) try: Clipboard.set_system_text(str(content)) Key("c-v").execute() time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/ 1000.) # time for keypress to execute cb.copy_to_system() except Exception: utilities.simple_log(False) return False return True
def clipboard_to_file(nnavi500, nexus, do_copy=False): if do_copy: Key("c-c").execute() max_tries = 20 key = str(nnavi500) for i in range(0, max_tries): failure = False try: # time for keypress to execute time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) nexus.clip[key] = Clipboard.get_system_text() utilities.save_json_file( nexus.clip, settings.SETTINGS["paths"]["SAVED_CLIPBOARD_PATH"]) except Exception: failure = True utilities.simple_log() if not failure: break
def paste_string_without_altering_clipboard(content): ''' True - indicates success False - indicates clipboard error ''' time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) # time for previous keypress to execute cb = Clipboard(from_system=True) try: Clipboard.set_system_text(str(content)) Key("c-v").execute() time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"] / 1000.) # time for keypress to execute cb.copy_to_system() except Exception: utilities.simple_log(False) return False return True
def main(argv): help_message = 'legion.py -t <tirg> [-m <monitor>] [-d <dimensions>] [-a <autoquit>]' tirg = None monitor = 1 dimensions = None auto_quit = False error_code = windll.shcore.SetProcessDpiAwareness( 2) #enable 1-1 pixel mapping if error_code == -2147024891: raise OSError("Failed to set app awareness") try: opts, args = getopt.getopt(argv, "ht:a:d:m:", ["tirg=", "dimensions=", "autoquit="]) except getopt.GetoptError: print(help_message) sys.exit(2) try: for opt, arg in opts: if opt == '-h': print(help_message) sys.exit() elif opt in ("-t", "--tirg"): tirg = arg elif opt == '-m': monitor = arg elif opt in ("-d", "--dimensions"): # wxh+x+y dimensions = Dimensions(*[int(n) for n in arg.split("_")]) elif opt in ("-a", "--autoquit"): auto_quit = arg in ("1", "t") if dimensions is None: r = monitors[int(monitor) - 1].rectangle dimensions = Dimensions(int(r.dx), int(r.dy), int(r.x), int(r.y)) lg = LegionGrid(grid_size=dimensions, tirg=tirg, auto_quit=auto_quit) except Exception: utilities.simple_log(True)
def main(argv): help_message = 'legion.py -t <tirg> [-m <monitor>] [-d <dimensions>] [-a <autoquit>]' tirg = None monitor = 1 dimensions = None auto_quit = False error_code = windll.shcore.SetProcessDpiAwareness(2) #enable 1-1 pixel mapping if error_code == -2147024891: raise OSError("Failed to set app awareness") try: opts, args = getopt.getopt(argv, "ht:a:d:m:", ["tirg=", "dimensions=", "autoquit="]) except getopt.GetoptError: print(help_message) sys.exit(2) try: for opt, arg in opts: if opt == '-h': print(help_message) sys.exit() elif opt in ("-t", "--tirg"): tirg = arg elif opt == '-m': monitor = arg elif opt in ("-d", "--dimensions"): # wxh+x+y dimensions = Dimensions(*[int(n) for n in arg.split("_")]) elif opt in ("-a", "--autoquit"): auto_quit = arg in ("1", "t") if dimensions is None: r = monitors[int(monitor) - 1].rectangle dimensions = Dimensions(int(r.dx), int(r.dy), int(r.x), int(r.y)) lg = LegionGrid(grid_size=dimensions, tirg=tirg, auto_quit=auto_quit) except Exception: utilities.simple_log(True)
def stoosh_keep_clipboard(nnavi500, nexus): if nnavi500 == 1: Key("c-c").execute() else: max_tries = 20 cb = Clipboard(from_system=True) Key("c-c").execute() key = str(nnavi500) for i in range(0, max_tries): failure = False try: # time for keypress to execute time.sleep(settings.SETTINGS["miscellaneous"]["keypress_wait"]/1000.) nexus.clip[key] = Clipboard.get_system_text() utilities.save_toml_file( nexus.clip, settings.SETTINGS["paths"]["SAVED_CLIPBOARD_PATH"]) except Exception: failure = True utilities.simple_log() if not failure: break cb.copy_to_system()
pass from caster.asynch.hmc import h_launch from caster.asynch.hmc import vocabulary_processing from caster.asynch.sikuli import sikuli from caster.lib import navigation, password from caster.lib.pita import scanner from caster.lib.dfplus.state.short import R ccr.initialize_ccr() recording.load_alias_rules() recording.load_recorded_rules() except: print "\nAttempting to load CCR anyway..." from caster.lib import ccr, utilities utilities.simple_log() ccr.initialize_ccr() from dragonfly import (Key, Function, Grammar, Playback, IntegerRef, Dictation, Choice, Pause, MappingRule) def change_monitor(): if settings.SETTINGS["miscellaneous"]["sikuli_enabled"]: Playback([(["monitor", "select"], 0.0)]).execute() else: utilities.report("This command requires SikuliX to be enabled in the settings file") class MainRule(MappingRule): @staticmethod
def bring_test(): print(settings.SETTINGS["paths"]["BASE_PATH"].replace("/", "\\")) try: BringApp("explorer", settings.SETTINGS["paths"]["BASE_PATH"]).execute() except Exception: utilities.simple_log()
def del_vocab(): try: h_launch.launch(settings.QTYPE_REM, process_delete, None) except Exception: utilities.simple_log(False)