def handleQuery(query): if not query.isTriggered: return None stripped = query.string.strip() if not stripped: return albert.Item( id=__title__, icon=icon_path, text=__title__, subtext="Search NASA ADS", completion=query.rawString, ) query_string = parse_query_string(stripped) return [ albert.Item( id=__title__, icon=icon_path, text="Sorted by date", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string, ) ], ), albert.Item( id=__title__, icon=icon_path, text="Sorted by popularity", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string + "&sort=classic_factor desc", ) ], ), albert.Item( id=__title__, icon=icon_path, text="Sorted by citation count", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string + "&sort=citation_count desc", ) ], ), ]
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string if len(query_str) < 2: keys_monitor.reset() return results keys_monitor.report() if keys_monitor.triggered(): bing_images = list( bing_search_save_to_cache(query=query_str, limit=3)) if not bing_images: results.insert( 0, v0.Item( id=__title__, icon=icon_path, text="No images found", subtext=f"Query: {query_str}", ), ) return results results.extend(get_bing_results_as_items(bing_images)) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def render_noargs( sources_sinks: List[Union[pulsectl.PulseSourceInfo, pulsectl.PulseSinkInfo]], cards: List[pulsectl.PulseCardInfo], ) -> List[v0.Item]: """Display current source, sink and card profiles.""" results = [] # active port for sources, sinks ---------------------------------------------------------- for s in sources_sinks: # discard if it doesn't have any ports if s.port_active is None: continue icon = sink_icon_path if is_sink(s) else src_icon_path # fill actions actions = [ v0.FuncAction(p.description, lambda s=s, p=p: pulse.port_set(s, p)) for p in s.port_list ] results.append( v0.Item( id=__title__, icon=icon, text=s.port_active.description, subtext=s.description, completion=__triggers__, actions=actions, ) ) # active profile for each sound card ------------------------------------------------------ for c in cards: actions = [ v0.FuncAction( prof.description, lambda c=c, prof=prof: pulse.card_profile_set(c, prof) ) for prof in c.profile_list ] results.append( v0.Item( id=__title__, icon=config_icon_path, text=c.profile_active.description, subtext=c.name, completion=__triggers__, actions=actions, ) ) return results
def handleQuery(query): results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string src, dst = extract_src_dst(query_str) if src and dst: actions = [] for m in available_means: actions.append( v0.FuncAction( m.capitalize(), lambda src=src, dst=dst, m=m: spawn_and_launch_route(src, dst, means=m))) results.append( v0.Item( id=__title__, icon=icon_path, text=f"Open route (takes ~5s)", subtext=f"{src} -> {dst}", actions=actions, )) except Exception: # user to report error results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{sys.exc_info()}", ) ], ), ) return results
def get_as_item(item: Union[Countdown, Stopwatch]): """Return an item - ready to be appended to the items list and be rendered by Albert.""" actions = [v0.FuncAction( "Remove", lambda: delete_item(item), )] if item.started(): actions.append(v0.FuncAction( "Pause", lambda: item.pause(), )) else: actions.append(v0.FuncAction( "Resume", lambda: item.start(), )) return v0.Item( id=__title__, icon=countdown_path if isinstance(item, Countdown) else stopwatch_path, text=str(item), subtext="", completion=__triggers__, actions=actions, )
def get_googler_result_as_item(googler_item: dict): actions = [ v0.UrlAction("Open in browser", googler_item["url"]), v0.ClipAction("Copy URL", googler_item["url"]), ] # incognito search if inco_cmd: actions.insert( 1, v0.FuncAction( "Open in browser [incognito mode]", lambda url=googler_item["url"]: inco_cmd(url), ), ) # special url handler if url_handler: # check that the handler is actually there actions.insert( 0, v0.FuncAction( url_handler_desc, lambda url_handler=url_handler: subprocess.Popen( f'{url_handler} {googler_item["url"]}', shell=True), ), ) return v0.Item( id=__title__, icon=icon_path, text=googler_item["title"], subtext=googler_item["abstract"], actions=actions, )
def handleQuery(query): results = [] if query.isTriggered: try: if len(query.string) >= 3: query_dict = format_query(query) search = zoopla.property_listings(query_dict) for s in search["listing"]: results.append(get_as_item(s)) except Exception: # user to report error results.insert( 0, v0.Item( id=__title__, icon=iconPath, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_cmd_items(pair: Tuple[str, Path]): """Return a list of Albert items - one per example.""" with open(pair[-1], "r") as f: lines = [li.strip() for li in f.readlines()] items = [] for i, li in enumerate(lines): if not li.startswith("- "): continue desc = li.lstrip("- ")[:-1] example_cmd = sanitize_string( lines[i + 2].strip("`").replace("{{", "").replace("}}", "") ) items.append( v0.Item( id=__title__, icon=icon_path, text=example_cmd, subtext=desc, actions=[ v0.ClipAction("Copy command", example_cmd), v0.UrlAction( "Do a google search", f'https://www.google.com/search?q="{pair[0]}" command', ), ], ) ) return items
def get_cmd_as_item(pair: Tuple[str, Path]): with open(pair[-1], "r") as f: all_lines = f.readlines() description_lines = [ li.lstrip("> ").rstrip().rstrip(".") for li in all_lines if li.startswith("> ") ] # see if there's a line with more information and a URL more_info_url = None try: more_info = [li for li in all_lines if "more information" in li.lower()][0] more_info_url = re.search("<(.*)>", more_info) if more_info_url is not None and more_info_url.groups(): more_info_url = more_info_url.groups()[0] except IndexError: pass actions = [ v0.ClipAction("Copy command", pair[0]), v0.UrlAction( "Do a google search", f'https://www.google.com/search?q="{pair[0]}" command' ), ] if more_info_url: actions.append(v0.UrlAction("More information", more_info_url)) return v0.Item( id=__title__, icon=icon_path, text=pair[0], completion=" ".join([__triggers__, pair[0]]), subtext=" ".join(description_lines), actions=actions, )
def get_as_item_custom(self, caption1=None, caption2=None): if caption1 or caption2: subtext = f"UP: {caption1} | DOWN: {caption2}" else: subtext = f"USAGE: {self.id} [upper-text] | [lower-text]" return v0.Item( id=__title__, icon=str(self.img), text=self.title(), subtext=subtext, completion=f"{__triggers__} {self.id} ", actions=[ v0.FuncAction( "Copy generated custom meme to clipboard", lambda caption1=caption1, caption2=caption2: self. _create_n_copy_to_clipboard(caption1=caption1, caption2=caption2), ), v0.FuncAction( "Copy generated custom meme path", lambda caption1=caption1, caption2=caption2: str( self._create_n_copy_path_to_clipboard( caption1=caption1, caption2=caption2)), ), v0.FuncAction( "Copy generated custom meme to clipboard", lambda caption1=caption1, caption2=caption2: self. _create_n_copy_to_clipboard(caption1=caption1, caption2=caption2), ), ], )
def get_as_item(result: BingImage): """Return an item. Will return None if the link to the image is not reachable (e.g., on 404) """ try: img = str(result.image.absolute()) except RequestException: return None actions = [ v0.ClipAction("Copy url", result.url), v0.ClipAction("Copy local path to image", img), v0.UrlAction("Open in browser", result.url), ] if result.type != "gif": actions.insert( 0, v0.FuncAction("Copy image", lambda result=result: copy_image(result))) item = v0.Item( id=__title__, icon=str(result.image), text=result.url[-20:], subtext=result.type, completion=f"{__triggers__}", actions=actions, ) return item
def get_as_item(issue: resources.Issue, jira): field = get_as_subtext_field # first action is default action actions = [ v0.UrlAction("Open in jira", f"{issue.permalink()}"), v0.ClipAction("Copy jira URL", f"{issue.permalink()}"), ] # add an action for each one of the available transitions curr_status = issue.fields.status.name for a_transition in jira.transitions(issue): if a_transition["name"] != curr_status: actions.append( v0.FuncAction( f'Mark as "{a_transition["name"]}"', lambda a_transition_id=a_transition["id"]: make_transition( jira, issue, a_transition_id), )) subtext = "{}{}{}{}".format( field(issue.fields.assignee), field(issue.fields.status.name), field(issue.fields.issuetype.name), field(issue.fields.project.key, "proj"), ) subtext += prio_to_text[issue.fields.priority.name] return v0.Item( id=__title__, icon=prio_to_icon[issue.fields.priority.name], text=f"{issue.fields.summary}", subtext=subtext, actions=actions, )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() query_str = query.string.strip() results.append(get_as_item(query_str if query_str else randstr())) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(s): actions = [] if s.details_url: actions.append(v0.UrlAction("Open on Zoopla", s.details_url)) if s.floor_plan: actions.append(v0.UrlAction("Floorplan", s.floor_plan[0])) if s.price: actions.append(v0.ClipAction("Copy price", str(s.price))) if s.price: if s.listing_status == "rent": price_str = f"Weekly: £{s.price} | " else: price_str = f"Total: £{s.price} | " else: price_str = "" return v0.Item( id=__title__, icon=iconPath, text=f"{s.description}", subtext="{}{}{}".format( f"Type: {s.property_type} | " if s.property_type else "", f"Code: {s.outcode} | " if s.outcode else "", price_str, f"# Bedrooms: {s.num_bedrooms} | " if s.num_bedrooms else "", )[:-2], actions=actions, )
def get_as_item(city: str): """Return an item - ready to be appended to the items list and be rendered by Albert.""" code = city_to_code[city] icon = str(get_logo_path_for_code(code)) utc_dt = pytz.utc.localize(datetime.utcnow()) dst_tz = pytz.timezone(city) dst_dt = utc_dt.astimezone(dst_tz) text = f"{str(dst_dt)}" subtext = f"[{code}] | {city}" return v0.Item( id=__title__, icon=icon, text=text, subtext=subtext, completion=city, actions=[ v0.UrlAction( "Open in zeitverschiebung.net", f'https://www.zeitverschiebung.net/en/timezone/{city.replace("/", "--").lower()}', ), ], )
def handleQuery(query) -> list: results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup for path in pass_2fa_dir.iterdir(): results.append(get_as_item(path)) except Exception: # user to report error results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(color): """Return an item - ready to be appended to the items list and be rendered by Albert.""" img_path = str(get_color_thumbnail(color)) rgb = [int(i * 255) for i in color.get_rgb()] hl = color.get_hex_l() if hl in h_to_color_name: name = f"| {h_to_color_name[hl]}" else: name = "" actions = [ v0.ClipAction("Copy Hex (Long)", hl), v0.ClipAction("Copy RGB", f"{rgb}"), v0.ClipAction("Copy RGB [0, 1]", f"{color.get_rgb()}"), ] h = color.get_hex() if h != hl: actions.insert(0, v0.ClipAction("Copy Hex (Short)", h)) return v0.Item( id=__title__, icon=img_path, text=f'<p style="color:{hl}";>{hl}{name}</p>', subtext=f"{rgb}", completion=" ".join([__triggers__, h]), actions=actions, )
def get_as_item(p: Process, *extra_actions): """Return an item - ready to be appended to the items list and be rendered by Albert. if Process is not a valid object (.name or .cmdline raise an exception) then return None """ name_field = cmdline(p) if not name_field: return None try: actions = [ v0.FuncAction("Terminate", lambda: p.terminate()), v0.FuncAction("Kill", lambda: p.kill()), v0.ClipAction("Get PID", f"{p.pid}"), v0.FuncAction( "Terminate matching names", lambda name=p.name(): kill_by_name(name, signal=signal.SIGTERM ), ), v0.FuncAction("Kill matching names", lambda name=p.name(): kill_by_name(name)), ] actions = [*extra_actions, *actions] return v0.Item( id=__title__, icon=icon_path, text=name_field, subtext="", completion=p.name(), actions=actions, ) except psutil.NoSuchProcess: return None
def get_history_item(*, src: str, dst: str, src_txt: str, dst_txt) -> v0.Item: return v0.Item( id=__title__, text=dst_txt, subtext=src_txt, icon=icon_path_hist, completion=f"{__triggers__}{src} {dst} {src_txt}", )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() matched = [ elem[0] for elem in process.extract(query_str, [*cities, *countries], limit=8) ] matched2 = [] # replace country names with its cities for m in matched: if m in countries: matched2.extend(*country_to_cities[m]) else: matched2.append(m) matched2 = get_uniq_elements(matched2) # add own timezone: if local_tz_str in matched2: matched2.remove(local_tz_str) matched2.insert(0, local_tz_str) results.extend([get_as_item(m) for m in matched2]) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(t: Tuple[str, Tuple[str, str]]): return v0.Item( id=__title__, icon=icon_path, text=f"{t[0]} - {t[1][0]}", subtext=f"{t[1][1]}", completion="", actions=[], )
def get_as_item(text, subtext, completion="", actions=[]): return v0.Item( id=__title__, icon=icon_path, text=text, subtext=subtext, completion=completion, actions=actions, )
def get_as_item(t: Tuple[str, tuple]): return v0.Item( id=__title__, icon=icon_path, text=f"{t[0]} - {t[1][0]}", subtext="", completion="", actions=[ v0.UrlAction("More info", f"https://httpstatuses.com/{t[0]}"), ], )
def setup(query) -> list: """Setup is successful if an empty list is returned. Use this function if you need the user to provide you data """ results = [] query_str = query.string # abbreviations file if not abbr_store_fname.is_file(): results.append( v0.Item( id=__title__, icon=icon_path, text=f"Specify file to read/write abbreviations to/from", subtext="Paste the path to the file, then press ENTER", actions=[ v0.FuncAction("Submit path", lambda p=query_str: submit_fname(Path(p))), ], )) return results if not abbr_store_sep.is_file(): results.append( v0.Item( id=__title__, icon=icon_path, text=f"Specify separator *character* for abbreviations", subtext=f"Separator: {query_str}", actions=[ v0.FuncAction("Submit separator", lambda c=query_str: submit_sep(c)), ], )) return results return results
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() if not query_str: return results # see if the name matches a color exactly color = get_as_color(query_str) if color: results.append(get_as_item(color)) return results # no exact match matched = process.extract(query_str, list(color_names_and_hex), limit=10) for m in [elem[0] for elem in matched]: results.append(get_as_item(Color(m))) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(email): """Return an item - ready to be appended to the items list and be rendered by Albert.""" return v0.Item( id=__title__, icon=icon_path, text=f"Temporary email: <u>{email}</u>", subtext="", completion=f"{__triggers__} {email}", actions=[ v0.FuncAction("Open in browser (and copy email address)", lambda email=email: copy_and_go(email)), ], )
def get_as_item(): """Return an item - ready to be appended to the items list and be rendered by Albert.""" return v0.Item( id=__title__, icon=icon_path, text=f"{sys.version}", subtext="Python version", completion="", actions=[ v0.UrlAction("Open in xkcd.com", "https://www.xkcd.com/"), v0.ClipAction("Copy URL", f"https://www.xkcd.com/"), ], )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() # avoid racing conditions when multiple queries are running simultaneously (i.e, # current and previous query due to successive keystrokes) pulse_lock.acquire() sources_sinks: List[Union[pulsectl.PulseSourceInfo, pulsectl.PulseSinkInfo]] = [ *pulse.sink_list(), *pulse.source_list(), ] cards: List[pulsectl.PulseCardInfo] = pulse.card_list() pulse_lock.release() if not query_str: results.extend(render_noargs(sources_sinks, cards)) else: results.extend(render_search(sources_sinks, cards, query_str)) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=None, text="Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def fn(): icon=os.path.join(stickersDir, stickerDir, img) albert.info(icon) item = albert.Item( id=__title__, text=stickerDir + ': ' + img, subtext=stickerDir, icon=icon, actions=[ albert.FuncAction(text="Copy Image", callable=lambda: doCopy(icon)) ] ) results.append(item)
def get_as_item(path: Path): name = path.name return v0.Item( id=__title__, icon=icon_path, text=name, completion="", actions=[ v0.FuncAction( "Copy 2FA code", lambda name=name: totp_show(name=name).strip(), ) ], )