Beispiel #1
0
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_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
Beispiel #3
0
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,
    )
Beispiel #4
0
 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),
             ),
         ],
     )
Beispiel #5
0
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 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
Beispiel #7
0
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,
    )
Beispiel #8
0
    def get_as_albert_item(self):
        item = super().get_as_albert_item()
        item.addAction(
            v0.FuncAction(
                "Move tasks to the day after",
                lambda date=self.date: move_tasks_of_date_to_next_day(date),
            ))

        return item
Beispiel #9
0
 def get_as_albert_items_full(self, query_str):
     item = self.get_as_albert_item()
     item.subtext = query_str
     item.addAction(
         v0.FuncAction(
             "Add task",
             lambda args_list=["add", *query_str.split()]: run_tw_action(
                 args_list),
         ))
     return [item]
Beispiel #10
0
def get_as_item(query_str: str):
    """Return an item - ready to be appended to the items list and be rendered by Albert."""
    query_str = query_str.strip()
    return v0.Item(
        id=__title__,
        icon=icon_path,
        text="Save to scratchpad",
        subtext=query_str,
        completion=f"{__triggers__}{query_str}",
        actions=[
            v0.FuncAction(
                f"Save to scratchpad -> {s_path}",
                lambda line=query_str: save_to_scratchpad(line),
            ),
            v0.FuncAction(
                f"Save to scratchpad - New Section -> {s_path}",
                lambda line=query_str: save_to_scratchpad(line, sep=True),
            ),
        ],
    )
    def get_as_albert_items_full(self, query_str: str):
        item = self.get_as_albert_item()
        item.subtext = ChangeDeck.usage_str if not query_str else f"Deck to use: {query_str}"

        item.addAction(
            v0.FuncAction(
                "Change deck",
                lambda new_deck_name=query_str: ChangeDeck.change_to(
                    new_deck_name),
            ))
        return [item]
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 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)),
        ],
    )
Beispiel #14
0
def render_search(
    sources_sinks: List[Union[pulsectl.PulseSourceInfo, pulsectl.PulseSinkInfo]],
    cards: List[pulsectl.PulseCardInfo],
    query_str: str,
) -> List[v0.Item]:
    results = []

    # sinks, sources
    search_str_to_props: Dict[str, list] = {
        p.description: [
            sink_icon_path if is_sink(s) else src_icon_path,
            s.description,
            lambda s=s, p=p: pulse.port_set(s, p),
        ]
        for s in sources_sinks
        for p in s.port_list
    }

    # profiles
    search_str_to_props.update(
        {
            prof.description: [
                config_icon_path,
                f"Profile | {c.name}",
                lambda c=c, prof=prof: pulse.card_profile_set(c, prof),
            ]
            for c in cards
            for prof in c.profile_list
        }
    )

    # add albert items
    matched = process.extract(query_str, list(search_str_to_props.keys()), limit=10)
    for m in [elem[0] for elem in matched]:
        icon = search_str_to_props[m][0]
        subtext = search_str_to_props[m][1]
        action = v0.FuncAction(m, search_str_to_props[m][2])

        results.append(
            v0.Item(
                id=__title__,
                icon=icon,
                text=m,
                subtext=subtext,
                completion=" ".join([__triggers__, query_str]),
                actions=[action],
            )
        )

    return results
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(),
            )
        ],
    )
Beispiel #16
0
            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)
Beispiel #17
0
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(stream: Stream):
    icon = stream.icon() or icon_path
    actions = [
        v0.FuncAction("Play", lambda stream=stream: start_stream(stream))
    ]
    if stream.homepage:
        actions.append(v0.UrlAction("Go to radio homepage", stream.homepage))

    return v0.Item(
        id=__title__,
        icon=icon,
        text=stream.name,
        subtext=stream.description if stream.description else "",
        completion="",
        actions=actions,
    )
    def get_as_albert_items_full(self, query_str: str):
        item = self.get_as_albert_item()
        query_parts = AddBasicNote.parse_query_str(query_str)
        if query_parts:
            front = query_parts[0]
            back = query_parts[1]
            item.subtext = f'{front} <span style="color: red">|</span> {back}'
        else:
            item.subtext = AddBasicNote.usage_str

        item.addAction(
            v0.FuncAction(
                f"Add {self.name} Note",
                lambda query_str=query_str: self.add_anki_note(query_str),
            ))
        return [item]
    def get_as_albert_items_full(self, query_str: str):
        item = self.get_as_albert_item()

        if self.detect_cloze_note(query_str):
            item.subtext = query_str
        else:
            item.subtext = AddClozeNote.usage_str

        item.addAction(
            v0.FuncAction(
                "Add a new cloze note",
                lambda cloze_text=query_str: self.add_cloze_note(cloze_text=
                                                                 cloze_text),
            ))

        return [item]
Beispiel #21
0
 def get_as_item(self):
     """Return it as item - ready to be appended to the items list and be rendered by
     Albert.
     """
     return v0.Item(
         id=__title__,
         icon=str(self.img),
         text=self.title(),
         subtext="",
         completion=f"{__triggers__} {self.id} ",
         actions=[
             v0.FuncAction("Copy vanilla image",
                           lambda: self.copy_vanilla_img()),
             v0.ClipAction("Copy vanilla image path", str(self.img)),
         ],
     )
Beispiel #22
0
def setup(query):
    """Setup is successful if an empty list is returned."""

    results = []

    query_str = query.string

    # abbreviations file
    if not s_path.is_file():
        results.append(
            v0.Item(
                id=__title__,
                icon=icon_path,
                text=f"Specify the location of the scratchpad file",
                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

    return results
def handleQuery(query):
    results = []
    if query.isTriggered:
        try:
            query.disableSort()

            fields = query.string.split()
            item = v0.Item(
                id=__title__,
                text=__title__,
                subtext='Enter a query in the form of "&lt;srclang&gt; &lt;dstlang&gt; &lt;text&gt;"',
                icon=icon_path,
                completion=query.rawString,
            )

            results.append(item)
            if len(fields) < 3:
                keys_monitor.reset()
                return results

            def completion():
                return f"{__triggers__}{dst} {src} {txt}"

            src = fields[0]
            dst = fields[1]
            txt = " ".join(fields[2:])
            results[-1].completion = completion()

            # determine if we can make the request --------------------------------------------
            keys_monitor.report()
            if keys_monitor.triggered():
                url = url_template % (src, dst, urllib.parse.quote_plus(txt))
                req = urllib.request.Request(url, headers={"User-Agent": ua})
                with urllib.request.urlopen(req) as response:
                    data = json.loads(response.read().decode("utf-8"))
                    result = data[0][0][0]
                    item.text = result
                    item.subtext = "%s -> %s: %s" % (
                        src.upper(),
                        dst.upper(),
                        txt,
                    )
                    item.addAction(
                        v0.FuncAction(
                            "Copy translation to clipboard",
                            lambda lang_config={
                                "src": src,
                                "dst": dst,
                                "src_txt": txt,
                            }, result=result: select_item(
                                lang_config=lang_config, result=result
                            ),
                        )
                    )
                    item.addAction(
                        v0.UrlAction(
                            "Open in browser",
                            f"https://translate.google.com/#view=home&op=translate&sl={src.lower()}&tl={dst.lower()}&text={txt}",
                        )
                    )

            # Show previous results
            iterator = reversed(history_deque)
            try:
                next(iterator)
                for di in iterator:  # last is the most recent
                    results.append(
                        get_history_item(
                            src=di["src"],
                            dst=di["dst"],
                            src_txt=di["src_txt"],
                            dst_txt=di["dst_txt"],
                        )
                    )
            except StopIteration:
                pass

        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
Beispiel #24
0
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_parts = query.string.strip().split()
            name = None
            if query_parts:
                name = query_parts.pop(0)
            subtext = f'Name: {name if name else "Not given"}'

            results.extend([
                v0.Item(
                    id=__title__,
                    icon=countdown_path,
                    text="Create countdown",
                    subtext=
                    f'{subtext}{" - <u>Please provide a duration</u>" if not query_parts else ""}',
                    completion=__triggers__,
                    actions=[
                        v0.FuncAction(
                            "Create countdown",
                            lambda name=name, query_parts=query_parts:
                            create_countdown(
                                name,
                                *query_parts,
                            ),
                        )
                    ],
                ),
                v0.Item(
                    id=__title__,
                    icon=stopwatch_path,
                    text="Create stopwatch",
                    subtext=subtext,
                    completion=__triggers__,
                    actions=[
                        v0.FuncAction(
                            "Create stopwatch",
                            lambda name=name, query_parts=query_parts:
                            create_stopwatch(
                                name,
                                *query_parts,
                            ),
                        )
                    ],
                ),
            ])

            # cleanup watches that are done
            for li in [
                    countdowns,
                    stopwatches,
            ]:
                for watch in li:
                    if watch.to_remove():
                        li.remove(watch)

            results.extend([get_as_item(item) for item in all_watches()])

        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=countdown_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
Beispiel #25
0
def handleQuery(query) -> list:
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_text = query.string.strip()

            if not len(query_text):
                results = [
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text="Update tldr database",
                        actions=[v0.FuncAction("Update", lambda: update_tldr_db())],
                    ),
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text="Reindex tldr pages",
                        actions=[v0.FuncAction("Reindex", lambda: reindex_tldr_pages())],
                    ),
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text="Need at least 1 letter to offer suggestions",
                        actions=[],
                    ),
                ] + results
                return results

            if query_text in page_paths.keys():
                # exact match - show examples
                results.extend(get_cmd_items((query_text, page_paths[query_text])))
            else:
                # fuzzy search based on word
                matched = process.extract(query_text, page_paths.keys(), limit=20)

                for m in [elem[0] for elem in matched]:
                    results.append(get_cmd_as_item((m, page_paths[m])))

        except Exception:  # user to report error
            if in_development:
                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 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.strip().split()) == 0:
                results.append(
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text="[new] Add a new abbreviation",
                        subtext="new <u>abbreviation</u> <u>description</u>",
                        completion=f"{__triggers__}new ",
                    ))
                results.append(
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text="Write more to query the database",
                        subtext="",
                        completion=f"{__triggers__}",
                    ))
                return results

            # new behavior
            tokens = query_str.split()
            if len(tokens) >= 1 and tokens[0] == "new":
                if len(tokens) > 1:
                    name = tokens[1]
                else:
                    name = ""
                if len(tokens) > 2:
                    desc = " ".join(tokens[2:])
                else:
                    desc = ""

                results.append(
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text=f"New abbreviation: {name}",
                        subtext=f"Description: {desc}",
                        actions=[
                            v0.FuncAction(
                                f"Save abbreviation to file",
                                lambda name=name, desc=desc: save_abbr(
                                    name, desc),
                            )
                        ],
                    ))

                return results

            curr_hash = hash_file(abbreviations_path)
            global abbr_latest_hash, abbr_latest_d, abbr_latest_d_bi
            if abbr_latest_hash != curr_hash:
                abbr_latest_hash = curr_hash
                with open(abbreviations_path) as f:
                    conts = f.readlines()
                    abbr_latest_d = make_latest_dict(conts)
                    abbr_latest_d_bi = abbr_latest_d.copy()
                    abbr_latest_d_bi.update(
                        {v: k
                         for k, v in abbr_latest_d.items()})

            if not abbr_latest_d:
                results.append(
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text=
                        f'No lines split by "{split_at}" in the file provided',
                        actions=[
                            v0.ClipAction(
                                f"Copy provided filename",
                                str(abbreviations_path),
                            )
                        ],
                    ))

                return results

            # do fuzzy search on both the abbreviations and their description
            matched = process.extract(query_str,
                                      abbr_latest_d_bi.keys(),
                                      limit=10)
            for m in [elem[0] for elem in matched]:
                if m in abbr_latest_d.keys():
                    results.append(get_abbr_as_item((m, abbr_latest_d[m])))
                else:
                    results.append(get_abbr_as_item((abbr_latest_d_bi[m], 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
Beispiel #27
0
def get_tw_item(task: taskw.task.Task) -> v0.Item:  # type: ignore
    """Get a single TW task as an Albert Item."""
    field = get_as_subtext_field
    task_id = tw_side.get_task_id(task)

    actions = [
        v0.FuncAction(
            "Complete task",
            lambda args_list=["done", task_id]: run_tw_action(args_list),
        ),
        v0.FuncAction(
            "Delete task",
            lambda args_list=["delete", task_id]: run_tw_action(args_list),
        ),
        v0.FuncAction(
            "Start task",
            lambda args_list=["start", task_id]: run_tw_action(args_list),
        ),
        v0.FuncAction(
            "Stop task",
            lambda args_list=["stop", task_id]: run_tw_action(args_list),
        ),
        v0.FuncAction(
            "Edit task interactively",
            lambda args_list=["edit", task_id]: run_tw_action(args_list,
                                                              need_pty=True),
        ),
        v0.FuncAction(
            "Fail task",
            lambda args_list=[task_id, "done", failure_annotation]:
            run_tw_action(args_list),
        ),
        v0.ClipAction("Copy task UUID", f"{task_id}"),
    ]

    found_urls = url_re.findall(task["description"])
    if "annotations" in task.keys():
        found_urls.extend(url_re.findall(" ".join(task["annotations"])))

    for url in found_urls[-1::-1]:
        actions.insert(0, v0.UrlAction(f"Open {url}", url))

    if reminders_tag_path.is_file():
        reminders_tag = load_data(reminders_tag_path)
        actions.append(
            v0.FuncAction(
                f"Add to Reminders (+{reminders_tag})",
                lambda args_list=[
                    "modify",
                    task_id,
                    f"+{reminders_tag}",
                ]: run_tw_action(args_list),
            ))

    urgency_str, icon = urgency_to_visuals(task.get("urgency"))
    text = f'{task["description"]}'
    if "start" in task:
        text = f'<p style="color:orange;">{text}</p>'

    due = None
    if "due" in task:
        due = task["due"].astimezone(dateutil.tz.tzlocal()).strftime(
            "%Y-%m-%d %H:%M:%S")  # type: ignore

    return get_as_item(
        text=text,
        subtext="{}{}{}{}{}".format(
            field(urgency_str),
            "ID: {}... | ".format(tw_side.get_task_id(task)[:8]),
            field(task["status"]),
            field(task.get("tags"), "tags"),
            field(due, "due"),
        )[:-2],
        icon=str(icon),
        completion=f'{__triggers__}{task["description"]}',
        actions=actions,
    )
Beispiel #28
0
def handleQuery(query):
    results = []

    # we're into the new day, create and assign a fresh instance
    last_used = last_used_date.get()
    current_date = datetime.datetime.today().date()

    global tw_side, subcommands
    if last_used < current_date:
        tw_side = TaskWarriorSideWLock()
        subcommands = create_subcommands()
        last_used_date.set(current_date)
    elif last_used > current_date:
        # maybe due to NTP?
        v0.critical(
            f"Current date {current_date} < last_used date {last_used} ?! Overriding current date, please report this if it persists"
        )
        tw_side = TaskWarriorSideWLock()
        subcommands = create_subcommands()
        last_used_date.set(current_date)

    if not query.isTriggered:
        if show_items_wo_trigger and len(query.string) < 2:
            results = [
                ActiveTasks().get_as_albert_item(),
                TodayTasks().get_as_albert_item(),
                *results,
            ]
    else:
        # join any previously launched threads
        for i in range(len(workers)):
            workers.pop(i).join(2)

        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup
            tasks = tw_side.get_all_items(include_completed=False)

            query_str = query.string

            if len(query_str) < 2:
                results.extend([s.get_as_albert_item() for s in subcommands])
                results.append(
                    get_as_item(
                        text="Reload list of tasks",
                        actions=[v0.FuncAction("Reload", async_reload_items)],
                    ))

                tasks.sort(key=lambda t: t["urgency"], reverse=True)
                results.extend([get_tw_item(task) for task in tasks])

            else:
                subcommand_query = get_subcommand_query(query_str)

                if subcommand_query:
                    results.extend(
                        subcommand_query.command.get_as_albert_items_full(
                            subcommand_query.query))

                    if not results:
                        results.append(get_as_item(text="No results"))

                else:
                    # find relevant results
                    desc_to_task = {
                        task["description"]: task
                        for task in tasks
                    }
                    matched = process.extract(query_str,
                                              list(desc_to_task.keys()),
                                              limit=30)
                    for m in [elem[0] for elem in matched]:
                        task = desc_to_task[m]
                        results.append(get_tw_item(task))

        except Exception:  # user to report error
            if dev_mode:
                v0.critical(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 handleQuery(query) -> list:  # noqa
    results = []

    if len(query.rawString.strip()) <= 1 and is_radio_on():
        results.insert(
            0,
            v0.Item(
                id=__title__,
                icon=stop_icon_path,
                text="Stop Radio",
                actions=[v0.FuncAction("Stop Radio", lambda: stop_radio())],
            ),
        )

    reindex_item = v0.Item(
        id=__title__,
        icon=repeat_icon_path,
        text="Reindex stations",
        actions=[v0.FuncAction("Reindex", lambda: init_streams())],
    )

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string.strip().lower()

            if not query_str:
                results.append(reindex_item)
                for stream in streams:
                    results.append(get_as_item(stream))
            else:
                for stream in streams:
                    if query_str in stream.name.lower() or (
                            stream.description and query_str.lower()
                            in stream.description.lower()):
                        results.append(get_as_item(stream))

                # reindex goes at the end of the list if we are searching for a stream
                results.append(reindex_item)

        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 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()

            cmdline_to_procs = get_cmdline_to_procs()
            matched = [
                elem[0] for elem in process.extract(
                    query_str, cmdline_to_procs.keys(), limit=15)
            ]

            extra_actions = []
            if any([symbol in query_str for symbol in "*?[]"]):
                extra_actions = [
                    v0.FuncAction(
                        "Terminate by glob",
                        lambda: list(
                            map(lambda p: p.terminate(),
                                globsearch_procs(query_str))),
                    ),
                    v0.FuncAction(
                        "Kill by glob",
                        lambda: list(
                            map(lambda p: p.kill(), globsearch_procs(query_str)
                                )),
                    ),
                ]
            for m in matched:
                for p in cmdline_to_procs[m]:
                    results.append(get_as_item(p, *extra_actions))

            # filtering step
            results = [r for r in results if r is not None]

        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