def handleQuery(query): results = [] if query.isTriggered: if len(query.string) > 2: pattern = re.compile(query.string, re.IGNORECASE) proc = subprocess.Popen(['locate', '-bi', query.string], stdout=subprocess.PIPE) for line in proc.stdout: path = line.decode().strip() basename = os.path.basename(path) results.append( Item(id=path, icon=iconPath, text=pattern.sub(lambda m: "<u>%s</u>" % m.group(0), basename), subtext=path, completion="%s%s" % (__trigger__, basename), actions=[UrlAction("Open", "file://%s" % path)])) else: results.append( Item(id=__prettyname__, icon=iconPath, text="Update locate database", subtext="Type at least three chars for a seach", completion=query.rawString, actions=[ TermAction("Update database", ["sudo", "updatedb"]) ])) return results
def handleQuery(query): if query.isTriggered: return [ Item(id="%s-whole-screen" % __prettyname__, icon=iconPath, text="Screen", subtext="Take a screenshot of the whole screen", actions=[ FuncAction("Take screenshot of whole screen", lambda: doScreenshot([])), FuncAction("Take screenshot of multiple displays", lambda: doScreenshot(["--multidisp"])), ]), Item(id="%s-area-of-screen" % __prettyname__, icon=iconPath, text="Area", subtext="Draw a rectangle with your mouse to capture an area", actions=[ FuncAction("Take screenshot of selected area", lambda: doScreenshot(["--select"])), ]), Item(id="%s-current-window" % __prettyname__, icon=iconPath, text="Window", subtext="Take a screenshot of the current active window", actions=[ FuncAction( "Take screenshot of window with borders", lambda: doScreenshot(["--focused", "--border"])), FuncAction("Take screenshot of window without borders", lambda: doScreenshot(["--focused"])), ]), ]
def handleQuery(query): results = [] if query.isTriggered: # avoid rate limiting sleep(0.2) if not query.isValid: return item = Item(id=__prettyname__, icon=iconPath, completion=query.rawString, text=__prettyname__, actions=[ ProcAction("Open the language configuration file.", commandline=[ "xdg-open", language_configuration_file ]) ]) if len(query.string) >= 2: for lang in languages: try: url = urltmpl % (lang, urllib.parse.quote_plus( query.string)) req = urllib.request.Request(url, headers={'User-Agent': ua}) with urllib.request.urlopen(req) as response: #print(type()) #try: data = json.loads(response.read().decode()) #except TypeError as typerr: # print("Urgh this type.error. %s" % typerr) translText = data[0][0][0] sourceText = data[2] if sourceText == lang: continue else: results.append( Item(id=__prettyname__, icon=iconPath, text="%s" % (translText), subtext="%s" % lang.upper(), actions=[ ClipAction( "Copy translation to clipboard", translText), UrlAction( "Open in your Browser", urlbrowser % (lang, query.string)) ])) except urllib.error.URLError as urlerr: print("Check your internet connection: %s" % urlerr) item.subtext = "Check your internet connection." return item else: item.subtext = "Enter a query: 'mtr <text>'. Languages {%s}" % ", ".join( languages) return item return results
def handleQuery(query): stripped = query.string.strip().lower() if stripped: results = [] for line in subprocess.check_output(['wmctrl', '-l', '-x']).splitlines(): win = Window(*parseWindow(line)) if win.desktop == "-1": continue win_instance, win_class = win.wm_class.replace(' ', '-').split('.') matches = [ win_instance.lower(), win_class.lower(), win.wm_name.lower() ] if any(stripped in match for match in matches): iconPath = iconLookup(win_instance) if iconPath == "": iconPath = iconLookup(win_class.lower()) results.append(Item(id="%s%s" % (__prettyname__, win.wm_class), icon=iconPath, text="%s - <i>Desktop %s</i>" % (win_class.replace('-',' '), win.desktop), subtext=win.wm_name, actions=[ProcAction("Switch Window", ["wmctrl", '-i', '-a', win.wid] ), ProcAction("Move window to this desktop", ["wmctrl", '-i', '-R', win.wid] ), ProcAction("Close the window gracefully.", ["wmctrl", '-c', win.wid])])) return results
def handleQuery(query): if query.isTriggered: stripped = query.string if stripped.startswith(__trigger__): stripped = query.string[len(__trigger__):] stripped = stripped.strip().lower() results = [] for line in subprocess.check_output(["wmctrl", "-l", "-x"]).splitlines(): if not query.isValid: return [] win = Window(*[token.decode() for token in line.split(None, 4)]) wm_class = win.wm_class.split(".") if win.desktop != "-1" and wm_class[0] != "albert": score = fuzzy_match(stripped, " ".join(wm_class).lower()) if score >= 0: results.append(( Item( id="%s%s" % (__prettyname__, win.wm_class), icon=windowIconLookup(win, wm_class), text="%s - <i>Workspace %s</i>" % ( titlecase(wm_class[-1].replace("-", " ")), int(win.desktop) + 1, ), subtext=win.wm_name, actions=[ ProcAction("Focus Window", ["wmctrl", "-ia", win.wid]), ProcAction("Close Window", ["wmctrl", "-ic", win.wid]), ], ), score, )) return [item[0] for item in sorted(results, key=lambda x: x[1])]
def handleQuery(query): if query.isTriggered: results = [] uid = os.getuid() for dir_entry in os.scandir('/proc'): try: if dir_entry.name.isdigit() and dir_entry.stat().st_uid == uid: proc_command = open(os.path.join(dir_entry.path, 'comm'), 'r').read().strip() if query.string in proc_command: proc_cmdline = open( os.path.join(dir_entry.path, 'cmdline'), 'r').read().strip().replace("\0", " ") results.append( Item(id="kill_%s" % proc_cmdline, icon=iconPath, text=proc_command.replace( query.string, "<u>%s</u>" % query.string), subtext=proc_cmdline, completion=query.rawString, actions=[ FuncAction("Terminate", lambda pid=int(dir_entry.name): os.kill(pid, SIGTERM)), FuncAction("Kill", lambda pid=int(dir_entry.name): os.kill(pid, SIGKILL)) ])) except FileNotFoundError: # TOCTOU dirs may disappear continue except IOError: # TOCTOU dirs may disappear continue return results
def buildVmItem(vm): item = Item( id=vm.__uuid__, icon=iconPath, text=vm.name, subtext="{vm.state}".format(vm=vm), completion=vm.name ) if vm.state == MachineState.powered_off: #1 item.addAction(FuncAction(text="Start virtual machine", callable=lambda: startVm(vm))) if vm.state == MachineState.saved: #2 item.addAction(FuncAction(text="Restore virtual machine", callable=lambda: startVm(vm))) item.addAction(FuncAction(text="Discard saved state", callable=lambda: discardSavedVm(vm))) if vm.state == MachineState.aborted: #4 item.addAction(FuncAction(text="Start virtual machine", callable=lambda: startVm(vm))) if vm.state == MachineState.running: #5 item.addAction(FuncAction(text="Save virtual machine", callable=lambda: saveVm(vm))) item.addAction(FuncAction(text="Power off via ACPI event (Power button)", callable=lambda: acpiPowerVm(vm))) item.addAction(FuncAction(text="Turn off virtual machine", callable=lambda: stopVm(vm))) item.addAction(FuncAction(text="Pause virtual machine", callable=lambda: pauseVm(vm))) if vm.state == MachineState.paused: #6 item.addAction(FuncAction(text="Resume virtual machine", callable=lambda: resumeVm(vm))) return item
def handleQuery(query): if query.isTriggered: files = getConfigFiles() all_connections = [getConnectionProperties(f) for f in files] stripped = query.string.strip() results = [] if stripped: # specific query by the user for p in all_connections: # search in names and groups if search(stripped, p[0], IGNORECASE) or search( stripped, p[1], IGNORECASE): results.append(getAsItem(*p)) else: # nothing specified yet, show all possible connections for p in all_connections: results.append(getAsItem(*p)) results.append( Item( id=__prettyname__, icon=ICON_PATH, text=__prettyname__, subtext=__doc__, actions=[FuncAction("Open Remmina", runRemmina)], )) return results
def handleQuery(query): if query.isTriggered: return Item(id=__prettyname__, icon=iconPath, text=__prettyname__, subtext="Look up '%s' using %s" % (query.string, __prettyname__), completion=query.rawString, actions=[ProcAction("Start query in %s" % __prettyname__, ["goldendict", query.string])])
def make_item(engine, query=None): if query is not None: return Item( text=query, subtext=engine["name"], icon=iconLookup(engine["icon"]), actions=[ FuncAction( "Search {}".format(engine["name"]), lambda: webbrowser.open(engine["search"].format(query)), ) ], ) else: return Item( text=engine["shortcut"], subtext=engine["name"], icon=iconLookup(engine["icon"]), )
def _invoke_ag(args, raws): items = list() texts = sp.run(_compose_ag_command(args), shell=True, check=False, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True).stdout.splitlines() if len(texts) == 0: item = Item(id='%s no hit' % __prettyname__, icon=icon, completion=raws, subtext='No Translation Candidate found for "%s"' % args) items.append(item) elif len(texts) == 1: key, values = texts[0].split("\t")[:2] for i, value in enumerate(values.split(',')): text = key + "\t" + value.strip() item = Item(id='%s hit %d' % (__prettyname__, i), icon=icon, completion=raws, text=text, subtext='Translation Candidate for "%s"' % args, actions=[ ClipAction("Copy translated words to Clipboard", value.strip()) ]) items.append(item) else: for i, text in enumerate(texts): if i >= __max_candidate__: break item = Item(id='%s hit %d' % (__prettyname__, i), icon=icon, completion=raws, text=text, subtext='Translation Candidate for "%s"' % args, actions=[ ClipAction("Copy translated words to Clipboard", text.split("\t")[1]) ]) items.append(item) return items
def getAsItem(name, group, server, proto, file): return Item( id=__prettyname__, icon=PROTOCOL_ICONS_PATH % (proto.lower()), text=(name, "%s/ %s" % (group, name))[len(group) > 0], subtext="%s %s" % (proto, server), actions=[ FuncAction("Open connection", lambda cf=file: runRemmina(cf)) ], )
def handleQuery(query): if query.string.strip() and "trash".startswith(query.string.lower()): pattern = re.compile(query.string, re.IGNORECASE) return Item(id="trash-open", icon=iconPath, text=pattern.sub(lambda m: "<u>%s</u>" % m.group(0), "Trash"), subtext="Show trash folder", completion="trash", actions=[UrlAction("Show", "trash:///")])
def handleQuery(query): if not query.string.strip(): defaultResults = [] for line in subprocess.check_output(['wmctrl', '-l', '-x']).splitlines(): win = Window(*[token.decode() for token in line.split(None, 4)]) if "albert" in win.wm_name and "Albert" in win.wm_name: continue if win.desktop != "-1": defaultResults.append(Item(id="%s%s" % (__prettyname__, win.wm_class), icon=iconLookup( win.wm_class.split('.')[1].capitalize()), text="%s" % (win.wm_class.split('.')[1].capitalize()), subtext=win.wm_name, actions=[ProcAction("Switch Window", ["wmctrl", '-i', '-a', win.wid]), ProcAction("Move window to this desktop", ["wmctrl", '-i', '-R', win.wid]), ProcAction("Close the window gracefully.", ["wmctrl", '-c', win.wid])])) return defaultResults stripped = query.string.strip().lower() if stripped: results = [] for line in subprocess.check_output(['wmctrl', '-l', '-x']).splitlines(): win = Window(*[token.decode() for token in line.split(None, 4)]) if "albert" in win.wm_name and "Albert" in win.wm_name: continue if win.desktop != "-1" and stripped in win.wm_name.lower(): results.append(Item(id="%s%s" % (__prettyname__, win.wm_class), icon=iconLookup( win.wm_class.split('.')[1].capitalize()), text="%s" % (win.wm_class.split('.')[1].capitalize()), subtext=win.wm_name, actions=[ProcAction("Switch Window", ["wmctrl", '-i', '-a', win.wid]), ProcAction("Move window to this desktop", ["wmctrl", '-i', '-R', win.wid]), ProcAction("Close the window gracefully.", ["wmctrl", '-c', win.wid])])) return results
def handleQuery(query): if query.isTriggered: args = query.string.strip() raws = query.rawString if len(args) > 0: try: return _invoke_ag(args, raws) except sp.CalledProcessError as e: return Item(id='%s error' % __prettyname__, icon=icon, completion=raws, text=str(e), subtext='Error occurs in Translation for "%s"' % args) else: return Item( id='%s no hit' % __prettyname__, icon=icon, completion=raws, text="Empty input", subtext='Enter an English word to translate into Japanese')
def prepareErrorMessage(message): """ Prepare error messae :param str message: Message :return str """ item = Item(id=__prettyname__, icon=icon_path) item.text = __prettyname__ item.subtext = message return item
def make_vpn_item(vpn): subtext = None actions = [] if vpn.interface == "": subtext = "VPN" actions.append( ProcAction("Connect", ["nmcli", "-t", "c", "up", vpn.id])) else: subtext = "Connected - VPN" actions.append( ProcAction("Disconnect", ["nmcli", "-t", "c", "down", vpn.id])) return Item(text=vpn.name, subtext=subtext, actions=actions, icon=NET_ICON)
def handleQuery(query): if not query.isTriggered: return results = [] results.append( Item(id="card", icon=iconPath, text="Card", subtext="open today card", completion='card', actions=[ FuncAction("Write", open_markdown), ])) return results
def appendItem(items, repo): name = repo["full_name"] description = repo["description"] or "" url = repo["html_url"] item = Item( id=__prettyname__, icon=iconPath, text=name, subtext=description, actions=[UrlAction("Open repository", url)], ) return items + [item]
def prepareResultsItem(query, result): """ Prepare resuls item :param str query : Query :param str result: Result :return Item """ value = result.decode('utf-8').split(' ')[0] item = Item(id=__prettyname__, icon=icon_path, completion=query.rawString) item.text = value item.subtext = result item.addAction(ClipAction("Copy result to clipboard", value)) return item
def handleQuery(query): if query.isTriggered: args = query.string.strip().lower() if len(args) == 0: return list(ss_items.values()) items = list() for cmd, item in ss_items.items(): if cmd.startswith(args): items.append(item) if len(items) > 0: return items return [ Item(id="screen-shot-no-hit", icon=iconPath, text="Not Found", subtext="invoke the collect command") ]
def handleQuery(query): if query.isTriggered: stripped = query.string.strip() items = [] url = stripped if not (url[:7] in ["http://", "https:/"]): url = "https://" + url normal_item = Item( id="website-"+stripped, text=stripped, subtext="open in chromium", completion=stripped, actions=[ ProcAction(text="Open this", commandline=["/usr/bin/chromium", "--app="+url]) ] ) items.append(normal_item) return items
def handleQuery(query): if not query.isTriggered: return item = Item(completion=query.rawString, icon=ICON_PATH) stripped = query.string.strip() if stripped: with NamedTemporaryFile() as f: f.write(bytes(stripped, 'utf-8')) f.flush() output = subprocess.check_output( ['wolframscript', '-print', '-f', f.name]) result = str(output.strip(), 'utf-8') item.text = result item.subtext = 'Result' item.addAction(ClipAction('Copy result to clipboard', result)) else: item.text = '' item.subtext = 'Type a Mathematica expression' return item
def handleQuery(query): if not query.isTriggered: return search = query.string.lower() found_name = [] found_path = [] updateProjects() for project in projects: if search in project["name"].lower(): found_name.append(project) elif search in project["path"].lower(): found_path.append(project) results = [] for project in found_name + found_path: search_regex = re.compile("(%s)" % re.escape(query.string), re.IGNORECASE) results.append( Item(id="godot_%s" % project["path"], icon=project["icon"], text=search_regex.sub("<u>\\1</u>", project["name"]), subtext=search_regex.sub("<u>\\1</u>", project["path"]), completion=query.rawString, actions=[ ProcAction(text="Open Editor", commandline=[ 'godot', '--path', project['path'], '--editor' ]), ProcAction( text="Run Project", commandline=['godot', '--path', project['path']]) ])) return results
def item(self): actions = [ClipAction("Copy password", self.password)] return Item(text=self.name, subtext=self.username, actions=actions, icon=lastpass)
def handleQuery(query): if query.isTriggered: stripped = query.string.strip() accessToken = loadAccessToken() if not accessToken: if stripped: return Item( id=__prettyname__, icon=iconPath, text="Save your GitHub access token", subtext='Require scope is "repo".', actions=[ FuncAction( "Save your GitHub access token", lambda: saveAccessToken(stripped), ) ], ) else: return Item( id=__prettyname__, icon=iconPath, text="Please type your GitHub access token", subtext='Require scope is "repo".', ) if stripped.startswith(">"): items = [] items.append( Item( id=__prettyname__, icon=iconPath, text="Delete cached repositories", subtext= "Please refetch repositories after deleted. It takes a lot of time.", actions=[ FuncAction("Delete cached repositories", lambda: deleteCache()) ], )) items.append( Item( id=__prettyname__, icon=iconPath, text="Delete your saved GitHub access token", subtext="Please reconfigure your GitHub access token.", actions=[ FuncAction( "Delete your saved GitHub access token", lambda: deleteAccessToken(), ) ], )) return items results = [] try: data = loadRepositories(accessToken) except Exception as err: return Item(id=__prettyname__, icon=iconPath, text="Error.", subtext=str(err)) repos = filterByQuery(data, stripped) if stripped else data for repo in repos: results = appendItem(results, repo) if results: return results return noResultItem() if query.string.startswith("g"): return Item( id=__prettyname__, icon=iconPath, text="gh", subtext="Open GitHub repositories in browser", completion="gh ", actions=[ ProcAction("Complete gh trigger", ["albert", "show", "gh "]) ], )
def noResultItem(): return Item(id=__prettyname__, icon=iconPath, text="No results.")
def handleQuery(query): if query.isTriggered and query.string.strip(): # avoid rate limiting time.sleep(0.2) if not query.isValid: return info("Searching YouTube for '{}'".format(query.string)) req = Request(headers=HEADERS, url='https://www.youtube.com/results?{}'.format( urlencode({ 'search_query': query.string.strip() }))) with urlopen(req) as response: responseBytes = response.read() match = re.search(DATA_REGEX, responseBytes.decode()) if match is None: critical("Failed to receive expected data from YouTube. This likely means API changes, but could just be a failed request.") logHtml(responseBytes) return results = json.loads(match.group(3)) results = results['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'] items = [] for result in results: for type, data in result.items(): try: if type == 'videoRenderer': subtext = ['Video'] action = 'Watch on Youtube' link = 'watch?v={}'.format(data['videoId']) if 'lengthText' in data: subtext.append(textFrom(data['lengthText'])) if 'shortViewCountText' in data: subtext.append(textFrom(data['shortViewCountText'])) if 'publishedTimeText' in data: subtext.append(textFrom(data['publishedTimeText'])) elif type == 'channelRenderer': subtext = ['Channel'] action = 'Show on Youtube' link = 'channel/{}'.format(data['channelId']) if 'videoCountText' in data: subtext.append(textFrom(data['videoCountText'])) if 'subscriberCountText' in data: subtext.append(textFrom(data['subscriberCountText'])) else: continue except Exception as e: critical(e) critical(json.dumps(result, indent=4)) item = Item(id=__prettyname__, icon=data['thumbnail']['thumbnails'][0]['url'].split('?', 1)[0] if data['thumbnail']['thumbnails'] else __icon__, text=textFrom(data['title']), subtext=' | '.join(subtext), completion=query.rawString, actions=[ UrlAction(action, 'https://www.youtube.com/' + link) ] ) items.append(item) return items
def handleQuery(query): if query.isTriggered: stripped = query.string if stripped.startswith(__trigger__): stripped = query.string[len(__trigger__) :] return [Item(text=iconLookup(stripped), icon=iconLookup(stripped))]
__author__ = "Tetsutaro Maruyama" __dependencies__ = ["scrot", "xclip"] if which("scrot") is None: raise Exception("'scrot' is not in $PATH.") if which("xclip") is None: raise Exception("'xclip' is not in $PATH.") iconPath = iconLookup("camera-photo") ss_items = { 'screen': Item(id="screen-shot-whole-screen", icon=iconPath, text="Screen", completion=__trigger__ + "Screen", subtext="Take a screenshot of the whole screen", actions=[ FuncAction("Take screenshot of whole screen", lambda: doScreenshot([])) ]), 'screen multi': Item(id="screen-shot-whole-screen-multi", icon=iconPath, text="Screen Multi", completion=__trigger__ + "Screen Multi", subtext="Take a screenshot of multiple displays", actions=[ FuncAction("Take screenshot of multiple displays", lambda: doScreenshot(["--multidisp"])) ]), 'area':