def build_result_item(self, page): """ Builds a result item object """ browser_action = OpenUrlAction(page['url']) hawkeye_action = RunScriptAction('hawkeye --uri="%s"' % page['url'], []) epiphany_action = RunScriptAction( 'epiphany-browser "%s"' % page['url'], []) if self.preferences['primary_action'] == "Hawkeye Quicklook": on_enter = hawkeye_action elif self.preferences['primary_action'] == "Gnome Web": on_enter = epiphany_action else: on_enter = browser_action if self.preferences['secondary_action'] == "None": on_alt_enter = DoNothingAction() elif self.preferences['secondary_action'] == "Hawkeye Quicklook": on_alt_enter = hawkeye_action elif self.preferences['secondary_action'] == "Gnome Web": on_alt_enter = epiphany_action else: on_alt_enter = browser_action return ExtensionResultItem(icon='images/icon.png', name=page['name'], description=page['category'], on_enter=on_enter, on_alt_enter=on_alt_enter)
def on_event(self, event, extension): items = [] pipe = os.popen("if tmux ls > /dev/null 2>&1; then tmux ls; else echo none; fi") terminal_binary = extension.preferences['terminal_binary'] console_parameters_attach = extension.preferences['console_parameters_attach'] console_parameters_new = extension.preferences['console_parameters_new'] output = pipe.read() if output.splitlines()[0] != "none": for line in output.splitlines(): items.append( ExtensionResultItem( icon='images/tmux.png', name='Attach session %s' % line.split(' ')[0], description=line, on_enter=RunScriptAction(terminal_binary + ' ' + console_parameters_attach % line.split(' ')[0], None) ) ) else: items.append( ExtensionResultItem( icon='images/tmux.png', name='Create a new tmux session', description='No active tmux sessions found', on_enter=RunScriptAction(terminal_binary + ' ' + console_parameters_new, None) ) ) return RenderResultListAction(items)
def on_enter(self, query): action_list = ActionList() if query.get_keyword() == self.keyword and query.get_argument(): argument = query.get_argument() elif self.is_default_search: argument = query else: argument = None if self.run_without_argument: if self._is_url(): action = OpenUrlAction(self.cmd.strip()) else: action = RunScriptAction(self.cmd) action_list.append(action) elif argument: if self._is_url(): command = self.cmd.strip().replace('%s', argument) action = OpenUrlAction(command) else: action = RunScriptAction(self.cmd, argument) action_list.append(action) else: action_list.append(SetUserQueryAction('%s ' % self.keyword)) self._query_history.save_query(query, self.get_name()) return action_list
def on_event(self, event, extension): items = [] myList = event.query.split(" ") password_store_path = extension.preferences['password_store_path'] password_store_path = path.expanduser( password_store_path ) if "~" in password_store_path else password_store_path custom_command = extension.preferences['custom_command'] custom_command_delay = extension.preferences['custom_command_delay'] enable_tail = extension.preferences['enable_tail'] pass_list = self.list_gpg(password_store_path) if not myList[1]: for line in pass_list: sleep = "sleep 0" if not custom_command_delay else "sleep " + custom_command_delay command = "pass show -c %s" % line command = command if not custom_command else " && ".join( [custom_command, command, sleep, custom_command]) items.append( ExtensionResultItem( icon='images/key.png', name='%s' % line, description='Copy %s to clipboard' % line, on_enter=RunScriptAction(command, None))) else: myQuery = [item.lower() for item in myList[1:]] for line in pass_list: sleep = "sleep 0" if not custom_command_delay else "sleep " + custom_command_delay command = "pass show -c %s" % line command = command if not custom_command else " && ".join( [custom_command, command, sleep, custom_command]) if all(word in line.lower() for word in myQuery if word != "tail"): try: extra = "\n" + check_output(["pass", "tail", line]).strip() \ if enable_tail and myQuery[-1] == "tail" else '' except CalledProcessError: items.append( ExtensionResultItem( icon='images/key.png', name='Pass tail extension is not installed', description= 'Press Enter to go to the extension\'s website', on_enter=OpenUrlAction( 'https://git.io/vpSgV'))) break items.append( ExtensionResultItem( icon='images/key.png', name='%s' % line, description='Copy %s to clipboard%s' % (line, extra), on_enter=RunScriptAction(command, None))) # `pass tail` command requires time to process. It's best to break it after first result. if extra: break return RenderResultListAction(items[:10])
def generate_results(self, extension, pattern, locate_flags, open_script, terminal_emulator, dirs_only): for (f) in get_file_list(extension, pattern, locate_flags, dirs_only): file_path = '%s' % os.path.abspath(f) file_dir = '%s' % os.path.abspath(os.path.join(file_path, os.pardir)) yield ExtensionSmallResultItem( icon=get_icon(f), name=file_path, on_enter=RunScriptAction(' '.join([open_script, file_path])), on_alt_enter=RunScriptAction(' '.join([terminal_emulator, '--working-directory', file_dir])))
def dnd_item(): if SessionAction.get_dnd_state(): return ExtensionResultItem(icon='images/system-notifications.svg', name='Disable DND', description='Turn off DND mode.', on_enter=RunScriptAction( SessionAction.dnd_off(), None)) else: return ExtensionResultItem(icon='images/system-notifications.svg', name='Enable DND', description='Turn on DND mode.', on_enter=RunScriptAction( SessionAction.dnd_on(), None))
def on_event(self, event, extension): items = [] search = event.get_argument() or "" session_description = extension.preferences['session_description'] or "" pipe = os.popen( "if tmux ls > /dev/null 2>&1; then tmux ls -F '#S%s%s'; else echo none; fi" % (separator, session_description)) terminal_binary = extension.preferences['terminal_binary'] console_parameters_attach = extension.preferences[ 'console_parameters_attach'] console_parameters_new = extension.preferences[ 'console_parameters_new'] default_new_session_name = extension.preferences['new_session_name'] new_session_name = default_new_session_name current_new_session_index = 1 output = pipe.read() lines = output.splitlines() if lines and lines[0] != "none": for line in output.splitlines(): if not search or search.lower() in line.split( separator)[0].lower(): item = ExtensionResultItem( icon='images/tmux.png', name=line.split(separator)[0], description=line.split(separator)[1], on_enter=RunScriptAction( terminal_binary + ' ' + console_parameters_attach % line.split(separator)[0], None)) if search == line.split(separator)[0]: items.insert(0, item) else: items.append(item) if new_session_name == line.split(separator)[0]: current_new_session_index += 1 new_session_name = "%s-%d" % (default_new_session_name, current_new_session_index) if search and (not items or items[0]._name != search): new_session_name = search items.append( ExtensionResultItem( icon='images/tmux.png', name=new_session_name, description='Create %s' % new_session_name, on_enter=RunScriptAction( terminal_binary + ' ' + (console_parameters_new % new_session_name), None))) return RenderResultListAction(items)
def battery_percentage_item(): if SessionAction.get_battery_percentage_state(): return ExtensionResultItem( icon='images/battery.svg', name='Hide battery percentage.', description='Hide battery percentage from wingpanel.', on_enter=RunScriptAction(SessionAction.hide_battery_percentage(), None)) else: return ExtensionResultItem( icon='images/battery.svg', name='Show battery percentage.', description='Show battery percentage in wingpanel.', on_enter=RunScriptAction(SessionAction.show_battery_percentage(), None))
def on_event(self, event, extension): items = [] items.append(ExtensionResultItem(icon='images/icon.png', name='Lock screen', on_enter=RunScriptAction(CMD_LOCKSCREEN, []))) return RenderResultListAction(items)
def on_event(self, event, extension): pattern = str(event.get_argument()) keyword = event.get_keyword() update_keyword = extension.preferences['update_keyword'] locate_file_keyword = extension.preferences['locate_file_keyword'] locate_dir_keyword = extension.preferences['locate_dir_keyword'] locate_flags = extension.preferences['locate_flags'] open_script = extension.preferences['open_script'] terminal_emulator = extension.preferences['terminal_emulator'] permissive_pattern = extension.preferences['permissive_pattern'] if permissive_pattern == 'yes': pattern = '*' + pattern.replace(' ', '*') + '*' if keyword == locate_file_keyword: # locate a file or directory in database return RenderResultListAction(list(self.generate_results(extension, pattern, locate_flags, open_script, terminal_emulator, False))) elif keyword == locate_dir_keyword: # locate a directory in database return RenderResultListAction(list(self.generate_results(extension, pattern, locate_flags, open_script, terminal_emulator, True))) elif keyword == update_keyword: # update files database cmd = ' '.join(['updatedb', '--require-visibility', 'no', '--output', database_filepath]) logger.debug('Database update command: %s ' % cmd) show_notification('Information', 'Updating database...') return RunScriptAction(cmd)
def on_event(self, event, extension): """ Handles the event """ items = [] try: boards = extension.trello_client.get_boards(event.get_argument()) if not boards: return [ ExtensionResultItem(icon='images/icon.png', name='No boards found with name %s' % event.get_argument(), on_enter=HideWindowAction()) ] for board in boards[:25]: items.append( ExtensionSmallResultItem( icon='images/icon.png', name=board['name'], description=board['description'], on_enter=RunScriptAction(board['script']) if bool( board['script']) else OpenUrlAction(board['url']))) except TrelloApiException as e: # pylint: disable=invalid-name LOGGER.error(e) items.append( ExtensionResultItem( icon='images/icon.png', name= 'Error when connecting to Trello API ( status code : %s )' % e.get_status_code(), on_enter=HideWindowAction())) return RenderResultListAction(items)
def execute(self): _LOGGER_.debug("Executing GetAction") items = [] exists = 0 for row in self.db.execute_statement( "SELECT key, value, tags from KV where key like '%{}%' or tags like '%{}%'".format(self.text, self.text)): exists = 1 key = row[0] value = row[1] value_fix = value.strip().replace('$', '\$').replace('"', '\\"').replace('`', '\\`') + '\n' script_action = 'sleep 0.01m && echo -n "' + value_fix + \ '" | xclip -i -selection clipboard && sleep 0.01m && xdotool key --clearmodifiers ctrl+v &' item = ExtensionResultItem( icon=ICON, name="{} = {}".format(key, value.replace('&', '&')), description="Press enter or click to copy '{}' to clipboard or type 'unset' to unset from db".format( value), on_alt_enter=RunScriptAction(script_action, []), on_enter=CopyToClipboardAction(value)) items.append(item) if not exists: item = ExtensionResultItem(icon=ICON, name=NAME) if self.text == "": item._description = "It looks like you have nothing stored" else: item._description = "No VALUE for KEY: '{}'".format(self.text) items.append(item) return items
def render_results(self, path, files, dirs, keyword): """ Prepares the results for the UI """ items = [] limit = int(self.extension.preferences['max-results']) if limit < len(dirs) + len(files): items.append(MORE_ELEMENTS_ITEM) for _dir in dirs: limit -= 1 if limit < 0: break action = SetUserQueryAction("{0} {1}/".format( keyword, os_path.join(path, _dir))) items.append( ExtensionResultItem(icon=FOLDER_ICON, name="{0}".format(_dir), description=FOLDER_DESCRIPTION, on_enter=action)) for _file in files: limit -= 1 if limit < 0: break action = RunScriptAction("pass -c {0}/{1}".format(path, _file), None) items.append( ExtensionResultItem(icon=PASSWORD_ICON, name="{0}".format(_file), description=PASSWORD_DESCRIPTION, on_enter=action)) return items
def show_cheats_list(self, cheats): """ Shows the cheats list """ hawkeye_bin = self.preferences['hawkeye_bin'] use_hawkeye_default = self.preferences['use_hawkeye_as_default_action'] items = [] for cheat in cheats[:8]: open_file_action = OpenAction(cheat['path']) open_in_hawkeye_action = RunScriptAction( '%s --uri="file://%s"' % (hawkeye_bin, cheat['path']), []) if use_hawkeye_default: primary_action = open_in_hawkeye_action secondary_action = open_file_action else: primary_action = open_file_action secondary_action = open_in_hawkeye_action items.append( ExtensionResultItem(icon='images/icon.png', name=cheat['normalized_name'], on_enter=primary_action, on_alt_enter=secondary_action)) return RenderResultListAction(items)
def on_event(self, event, extension): # search term search_term = (event.get_query().get_argument() or "") vbox_exec = extension.preferences.get('vbox_exec') machines = self.get_machine_info_vboxapi() \ if self.have_vboxapi_and_virtualbox() \ else self.get_machine_info_cli() items = [] for machine in machines: # filter machine based on search term if not search_term.lower() in str(machine['name']).lower(): continue # There doesn't seem to be any way at the moment to run custom python code as an action # Also, virtualbox does not yet support wayland, so make sure it starts as X # Even more also, can't use f strings cause I can't assure py 3.6 is available command = 'QT_QPA_PLATFORM=xcb ' + vbox_exec + ' --startvm "' + machine[ 'id'] + '"' items.append( ExtensionResultItem(icon='images/icon.png', name=machine['name'], description=machine['description'], on_enter=RunScriptAction(command))) return RenderResultListAction(items)
def on_event(self, event, extension): items = [] keyword = extension.preferences["project_kw"] type_editor_mapping = { "py": extension.preferences["editor_python"], "js": extension.preferences["editor_js"], "php": extension.preferences["editor_php"], None: extension.preferences["editor_default"], } project_name_query = event.query[len(keyword) + 1:] for project_prefix in extension.preferences["project_dirs"].split(":"): for project_path in Path(project_prefix).expanduser().glob("*"): project_name = project_path.name if project_name_query in project_name: project_type = self._get_project_type(project_path) editor = type_editor_mapping[project_type] items.append( ExtensionResultItem( icon=str(self._get_icon(editor)), name=project_name, description=f"Open {project_name} in {editor}", on_enter=RunScriptAction( f"#!/bin/bash\n{editor} $1", str(project_path)), )) return RenderResultListAction(items)
def searchBoxes(self, search_str): results = [] pattern = re.compile(re.escape("[") + "display") config_lines = [] qemu_path = self.preferences.get("gbox_sessions_path") with open(expanduser(qemu_path)) as boxesFile: config_lines = boxesFile.readlines() config_blocks = [] for i, line in enumerate(config_lines): for match in re.finditer(pattern, line): config_blocks.append(self.get_config_block(config_lines, i)) for block in config_blocks: if search_str == "Start typing..." \ or block["last-seen-name"].__contains__(search_str) \ or block["uuid"].__contains__(search_str): last_access = datetime.fromtimestamp(int(block["access-last-time"]) / 1000000) results.append( ExtensionResultItem( icon='images/icon.png', name=block["last-seen-name"], description="UUID: " + block["uuid"] + "\n" + block["access-ntimes"] + " access, last " + last_access.__str__(), on_enter=RunScriptAction( 'gnome-boxes --open-uuid %s &' % block["uuid"], [] ), on_alt_enter=CopyToClipboardAction(block["uuid"]) ) ) return results
def get_shutdown_item(): return ExtensionResultItem(icon='images/gnome-shutdown.png', name='Shutdown', description='Power off computer', on_enter=RunScriptAction( "gnome-session-quit --power-off --force", None))
def get_logout_item(): return ExtensionResultItem(icon='images/gnome-logout.png', name='Logout', description='Logout from session', on_enter=RunScriptAction( "gnome-session-quit --logout --no-prompt", None))
def get_reboot_item(): return ExtensionResultItem(icon='images/gnome-reboot.png', name='Reboot', description='Reboot computer', on_enter=RunScriptAction( "gnome-session-quit --reboot --force", None))
def test_run(self): test_file = '/tmp/ulauncher_test_%s' % randint(1, 111111) args = 'hello world' RunScriptAction('echo $1 $2 > %s' % test_file, args).run() with open(test_file, 'r') as f: assert f.read() == '%s\n' % args os.remove(test_file)
def on_event(self, event, extension): """ Handles the event """ items = [] keyword = event.get_keyword() query = event.get_argument() or "" file_path = extension.get_recent_projects_file_path(keyword) projects = RecentProjectsParser.parse(file_path, query) if not projects: return RenderResultListAction([ ExtensionResultItem(icon=extension.get_icon(keyword), name='No projects found', on_enter=HideWindowAction()) ]) for project in projects: items.append( ExtensionResultItem( icon=project['icon'] if project['icon'] is not None else extension.get_icon(keyword), name=project['name'], description=project['path'], on_enter=RunScriptAction( '%s "%s" &' % (extension.get_launcher_file(keyword), project['path']), []), on_alt_enter=CopyToClipboardAction(project['path']))) return RenderResultListAction(items)
def open_in_devdocs(self, doc, entry=None): """ Opens a documentation page in DevDocs. :param str doc: The documentation slug :param str entry: The entry slug. Depending of the extension configurations it might open in: - DevDocs website - Devdocs desktop (devdocs protocol) - HawkHeye """ open_result_in = self.preferences['open_doc_in'] doc_path = doc if entry: doc_path = doc_path + "/" + entry doc_url = "https://devdocs.io/%s" % doc_path if open_result_in == "Hawkeye": return RunScriptAction('hawkeye --uri="%s"' % doc_url, []) elif open_result_in == "DevDocs Protocol": return OpenAction("devdocs://%s" % doc_path) return OpenUrlAction(doc_url)
def get_open_in_terminal_script(self, path): """ Returns the script based on the type of terminal """ terminal_emulator = self.preferences['terminal_emulator'] # some terminals might work differently. This is already prepared for that. if terminal_emulator in [ 'deepin-terminal', 'gnome-terminal', 'terminator', 'tilix', 'xfce-terminal' ]: if terminal_emulator == 'deepin-terminal': return RunScriptAction(terminal_emulator, ['--working-directory', path]) else: RunScriptAction(terminal_emulator, ['--working-directory', path]) return DoNothingAction()
def no_config_items(): return [ ExtensionResultItem(icon=ICON_FILE, name='No scripts', description='Add scripts in ' + SCRIPT_PATH, on_enter=RunScriptAction('xdg-open ' + SCRIPT_PATH)) ]
def get_open_in_terminal_script(self, path): """ Returns the script based on the type of terminal """ terminal_emulator = self.preferences['terminal_emulator'] cmd = terminal_emulator + ' ' + ''.join(['--working-directory=', path]) # some terminals might work differently. This is already prepared for that. if terminal_emulator in ['gnome-terminal', 'terminator', 'tilix', 'xfce-terminal']: return RunScriptAction(cmd) return DoNothingAction()
def create_item(name, icon, keyword, description, on_enter): return (keyword, ExtensionResultItem( name=name, description=description, icon=get_icon_path(icon, ExtensionResultItem.ICON_SIZE), on_enter=RunScriptAction( 'xfce4-session-logout --{}'.format(on_enter), None), ))
def create_item(name, image, keyword, description, on_enter): return ( keyword, ExtensionResultItem( name=name, description=description, icon=image, on_enter=RunScriptAction(on_enter, None), ), )
def __init__(self): self.__entries: EntryIndex = EntryIndex() self.__result_items: List[ExtensionResultItem] = [ ExtensionResultItem( icon=entry.icon, name=entry.name, description=entry.description, on_enter=RunScriptAction(entry.command), ) for entry in self.__entries.entries ]
def create_item(name, icon, keyword, description, on_enter): return ( keyword, ExtensionResultItem( name=name, # description=description, icon='images/{}.svg'.format(icon), on_enter=RunScriptAction( '#!/usr/bin/env bash\n{} {}\n'.format(gcpath, on_enter), None)))