Esempio n. 1
0
def get_volume_actions(query: str = "") -> RenderResultListAction:
    volume_actions = list()
    if query.isdecimal():
        volume_actions.append(
            ExtensionResultItem(icon='images/Flat Mixer.png',
                                name='Set volume',
                                on_enter=ExtensionCustomAction(
                                    ('volume', query), False)))
        return RenderResultListAction(volume_actions)
    for act in VOLUME_ACTIONS:
        for keyword in VOLUME_ACTIONS[act][1]:
            if query in keyword:
                volume_actions.append(VOLUME_ACTIONS[act][0])
                break
    return RenderResultListAction(volume_actions)
Esempio n. 2
0
    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]:
            if 'error' in cheat:
                items.append(ExtensionResultItem(icon='images/error.png',
                                                 name=cheat['error'],
                                                 on_enter=HideWindowAction()))
            else:
                if 'url' in cheat:
                    uri = cheat['path']
                    icon = 'images/url.png'
                else:
                    uri = 'file://%s' % cheat['path']
                    icon = 'images/icon.png'
                
                open_file_action = OpenAction(cheat['path'])
                open_in_hawkeye_action = RunScriptAction('%s --uri="%s"' % (hawkeye_bin, uri), [])

                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=icon,
                                                 name=cheat['normalized_name'],
                                                 on_enter=primary_action,
                                                 on_alt_enter=secondary_action))

        return RenderResultListAction(items)
    def on_event(self, event, extension):

        gr = int(event.get_argument())

        if gr > 0:
            gr = (gr * 1.618) - gr
            items = []
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Golden ratio: %s' % gr,
                    description='Press \'enter\' to copy to clipboard.',
                    on_enter=CopyToClipboardAction(str(gr))))

        return RenderResultListAction(items)
Esempio n. 4
0
 def on_event(self, event, extension):
     try:
         spotify_bus = get_spotify_bus()
     except dbus.exceptions.DBusException:
         return RenderResultListAction(
             [
                 ExtensionResultItem(
                     icon='images/icon.png',
                     name='Run Spotify desktop app first',
                     on_enter=LaunchAppAction(spotify_app_path)
                 ),
             ]
         )
     keep_open = boolify(extension.preferences.get('keep_open'))
     return RenderResultListAction(get_menu_items(spotify_bus, keep_open))
Esempio n. 5
0
 def item_create_note_from_clipboard(self,
                                     new_note_filename: str) -> ResultItem:
     """
     Construct "Create note from clipboard" result item
     """
     return ExtensionResultItem(
         icon="images/create-note.svg",
         name="Create note from clipboard",
         description=new_note_filename,
         on_enter=callable_action(
             self.create_note_from_clipboard,
             os.path.join(self.get_notes_path(), new_note_filename),
         ),
         highlightable=False,
     )
Esempio n. 6
0
def error_item(message: str, details: Optional[str] = None) -> ResultItem:
    """
    Show small result item with error icon and a message.
    """
    if not details:
        return ExtensionSmallResultItem(icon="images/error.svg",
                                        name=message,
                                        on_enter=DoNothingAction())

    return ExtensionResultItem(
        icon="images/error.svg",
        name=message,
        description=details,
        on_enter=DoNothingAction(),
    )
Esempio n. 7
0
def quick_capture_note(content):
    return [
        ExtensionResultItem(
            icon=ICON_ADD_FILE,
            name="Quick Capture",
            on_enter=ExtensionCustomAction(
                {
                    "type": "quick-capture",
                    "content": content
                },
                keep_app_open=True),
        ),
        ExtensionResultItem(
            icon=ICON_ADD_FILE,
            name="Quick Capture to Note",
            on_enter=ExtensionCustomAction(
                {
                    "type": "quick-capture-to-note",
                    "content": content
                },
                keep_app_open=True,
            ),
        ),
    ]
Esempio n. 8
0
    def handle_empty_word() -> List[ExtensionResultItem]:
        """Returns the elements to display when an empty word is given to the extension.

        Returns:
            List[ExtensionResultItem]: All elements to be shown by the extension.
        """
        return [
            ExtensionResultItem(
                icon="images/icon.png",
                name="Palabra vacía",
                description=
                "Ingrese una palabra para buscar en el diccionario.",
                on_enter=HideWindowAction(),
            )
        ]
    def on_event(self, event, extension):

        argument = event.get_argument()
        min_length = 2
        arg_length = len(argument) if argument else 0
        delta = min_length - arg_length

        if delta > 0:
            msg = 'Type {} more letter{} to enable auto-complete'.format(
                delta, 's' if delta > 1 else '')
            return RenderResultListAction(
                [ExtensionResultItem(icon='images/icon.png', name=msg)])

        executables = extension.get_executables(argument)[:7]
        items = []
        for i in executables:
            data = {'item': i, 'argument': argument}
            items.append(
                ExtensionResultItem(icon=self.icon,
                                    name=i,
                                    description=extension.get_description(i),
                                    on_enter=ExtensionCustomAction(data)))

        return RenderResultListAction(items)
Esempio n. 10
0
    def build_results_list(self, apps):
        """ Build sites list """
        items = []
        LOGGER.debug(apps)

        for app in apps:
            app_url = self.heroku_client.DASHBOARD_URL + "/apps/" + app['name']
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=app["name"],
                                    on_enter=OpenUrlAction(app_url),
                                    on_alt_enter=OpenUrlAction(
                                        app['web_url'])))

        return items
Esempio n. 11
0
 def _control_panel(self, spotify_status):
     return RenderResultListAction([
         ExtensionResultItem(
             icon=cs.IconPaths.PLAY if spotify_status.playback_status
             == cs.States.PAUSED else cs.IconPaths.PAUSE,
             name=self._format(self._name_line, spotify_status),
             description=self._format(self._description_line,
                                      spotify_status),
             on_enter=ExtensionCustomAction(cs.Actions.PLAY_PAUSE,
                                            keep_app_open=self.keep_open),
         ),
         ExtensionResultItem(
             icon=cs.IconPaths.NEXT,
             name='Next track',
             on_enter=ExtensionCustomAction(cs.Actions.NEXT,
                                            keep_app_open=self.keep_open),
         ),
         ExtensionResultItem(
             icon=cs.IconPaths.PREVIOUS,
             name='Previous track',
             on_enter=ExtensionCustomAction(cs.Actions.PREVIOUS,
                                            keep_app_open=self.keep_open),
         ),
     ])
Esempio n. 12
0
    def show_menu(self):
        """ Show the main extension menu, when the user types the extension keyword without arguments """
        keyword = self.preferences["kw"]

        menu = [
            ExtensionResultItem(
                icon='images/icon.png',
                name="My",
                description=
                "Your personal menu with shortcuts for your Issues, Merge Requests and more",
                highlightable=False,
                on_enter=SetUserQueryAction("%s my" % keyword)),
            ExtensionResultItem(
                icon='images/icon.png',
                name="Project Search",
                description=
                "Search public projects in the entire GitLab platform",
                highlightable=False,
                on_enter=SetUserQueryAction("%s search " % keyword)),
            ExtensionResultItem(
                icon='images/icon.png',
                name="My Projects",
                description="List the projects you are a member of",
                highlightable=False,
                on_enter=SetUserQueryAction("%s projects " % keyword)),
            ExtensionResultItem(icon='images/icon.png',
                                name="My Projects (Starred)",
                                description="List your starred projects",
                                highlightable=False,
                                on_enter=SetUserQueryAction("%s starred " %
                                                            keyword)),
            ExtensionResultItem(icon='images/icon.png',
                                name="My Groups",
                                description="List the groups you belong",
                                highlightable=False,
                                on_enter=SetUserQueryAction("%s groups " %
                                                            keyword)),
            ExtensionResultItem(icon='images/icon.png',
                                name="GitLab Website",
                                description="Opens the GitLab website",
                                highlightable=False,
                                on_enter=OpenUrlAction(self.gitlab.url)),
            ExtensionResultItem(
                icon='images/icon.png',
                name="GitLab Status",
                description="Opens the GitLab status page",
                highlightable=False,
                on_enter=OpenUrlAction("https://status.gitlab.com")),
        ]

        return RenderResultListAction(menu)
Esempio n. 13
0
def cli_not_found_error() -> BaseAction:
    """
    Was not able to execute keepassxc-cli because it was either
    not found or wrong permissions
    """
    return RenderResultListAction([
        ExtensionResultItem(
            icon="images/error.svg",
            name="Cannot execute keepassxc-cli",
            # pylint: disable=line-too-long
            description=
            "Please make sure keepassxc-cli is installed and accessible",  # noqa: E501
            on_enter=DoNothingAction(),
        )
    ])
Esempio n. 14
0
    def render_top_stories(self, stories, page_number):
        import timeago

        items = []
        for story in stories:
            # Determine what url to use
            if (self.preferences.OPEN_MODE):
                url = 'https://news.ycombinator.com/item?id=%d' % story.item_id
            else: # open_mode == 'URL'
                url = story.url
            
            # '3 hours ago'-type time display
            formatted_time = timeago.format(story.time, utils.get_current_time())

            # Item info
            number_of_comments = story.descendants
            description = "%s Comments | %s | %s points | by %s " % (number_of_comments,
                                                                     formatted_time,
                                                                     story.score,
                                                                     story.by)

            # Add a last item to load the next 5 top stories
            items.append(ExtensionResultItem(icon='images/story.png',
                                name="%s" % story.title,
                                description=description,
                                highlightable=True,
                                on_enter=OpenUrlAction(url)))

        # Item to get to the neext page
        items.append(ExtensionResultItem(icon='images/next.png',
                                name='Load Next Page!',
                                description="The same as running 'hn %s'" % str( page_number + 1 ),
                                highlightable=True,
                                on_enter=SetUserQueryAction( 'hn top %s' % str( page_number + 1 ) )))

        return items
Esempio n. 15
0
 def on_event(self, event, extension):
     items = []
     logger.info('preferences %s' % json.dumps(extension.preferences))
     
     today = datetime.date.today().strftime("%d %B, %Y")
     time = datetime.datetime.now().strftime("%H:%M")
     
     items.append(ExtensionResultItem(icon='images/icon.png',
                                      name=f'{time} | {today}',
                                      description='',
                                      on_enter=CopyToClipboardAction(
                                          '{0:%Y-%m-%d %H:%M}'.format(datetime.datetime.now()))))
     
     
     return RenderResultListAction(items)
Esempio n. 16
0
    def get_rendered_list(self):
        api_token = self.extension.api_token
        api = todoist.TodoistAPI(api_token)
        api.sync()

        tasks = []

        for item in api.items.all(filt=self.today_tasks_filter):
            logger.debug(item)
            tasks.append(
                ExtensionResultItem(icon=self.extension.get_icon(),
                                    name="%s" % (str(item["content"])),
                                    on_enter=HideWindowAction()))

        return tasks
Esempio n. 17
0
def select_note(notes: List[Note], limit=10):
    return [
        ExtensionResultItem(
            icon=ICON_FILE,
            name=note.name,
            description=note.description,
            on_enter=ExtensionCustomAction(
                {
                    "type": "select-note",
                    "note": note
                },
                keep_app_open=True,
            ),
        ) for note in notes[:limit]
    ]
Esempio n. 18
0
    def show_available_docs(self, event, filter_term=None):
        """ Displays a list of available docs """
        docs = self.searcher.get_available_docs(filter_term)

        items = []

        if not docs:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name='No results found',
                                    on_enter=HideWindowAction())
            ])

        for doc in docs[:8]:
            items.append(
                ExtensionResultItem(
                    icon=doc['icon'],
                    name=doc['name'],
                    description=doc['description'],
                    on_alt_enter=OpenUrlAction(doc['url']),
                    on_enter=SetUserQueryAction(
                        "%s %s > " % (event.get_keyword(), doc['key']))))

        return RenderResultListAction(items)
Esempio n. 19
0
    def on_event(self, event, extension):
        token = extension.token
        if not token:
            return self.get_error_result()

        habits = self.get_habits(token, extension.only_pending)
        items = []
        for habit in habits:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=habit.get('name'),
                                    description=habit.get('name'),
                                    on_enter=HideWindowAction()))

        return RenderResultListAction(items)
Esempio n. 20
0
    def show_expansions_list(self, expansions):
        """ Shows the expansions list """

        items = []

        for item in expansions[:8]:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=item['normalized_name'],
                    description=
                    'Select to fill placeholders and copy the contents to the clipboard',
                    on_enter=ExtensionCustomAction(item)))

        return RenderResultListAction(items)
Esempio n. 21
0
    def on_event(self, event, extension):
        items = []
        expression = event.get_argument()
        try:
            result = str(eval(expression, {
                '__builtins__': None,
                'math': math
            }))

            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Expr: %s = %s' % (expression, result),
                    description='Press \'enter\' to copy to clipboard.',
                    on_enter=CopyToClipboardAction(result)))
        except NameError as errorMessage:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Expr: %s' % errorMessage,
                    description='Expression has Error.',
                    on_enter=CopyToClipboardAction(errorMessage)))

        return RenderResultListAction(items)
Esempio n. 22
0
 def show_signal_options(self, data):
     result_items = []
     options = [('TERM', '15 TERM (default)'), ('KILL', '9 KILL'),
                ('HUP', '1 HUP')]
     for sig, name in options:
         on_enter = data.copy()
         on_enter['alt_enter'] = False
         on_enter['signal'] = sig
         result_items.append(
             ExtensionResultItem(icon=ext_icon,
                                 name=name,
                                 description='',
                                 highlightable=False,
                                 on_enter=ExtensionCustomAction(on_enter)))
     return RenderResultListAction(result_items)
Esempio n. 23
0
    def on_event(self, event, extension):
        items = []
        query = event.get_argument()
        if query:
            dictionaries = get_dictionaries(extension.preferences)

            if extension.preferences["matching"] == "regex":
                result_list = [
                    w for w in extension.word_list
                    if re.search(r'^{}'.format(query), w.get_search_name())
                ]
            else:
                result_list = CustomSortedList(query, min_score=60)
                result_list.extend(extension.word_list)

            for result in result_list[:9]:
                word, language = str(result).split('/')

                items.append(
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name=word,
                        description="Language: {}".format(language),
                        on_enter=OpenUrlAction(
                            dictionaries.get(language, DEFAULT_DICTIONARY) %
                            word)))

        else:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name="Type in the word...",
                    description="",
                ))

        return RenderResultListAction(items)
Esempio n. 24
0
    def on_event(self, event, extension):
        """Handles the event."""

        query = event.get_argument() or ""

        if not query:
            return extension.show_menu()

        # Get the action based on the search terms
        search = re.findall(r"^search(.*)?$", query, re.IGNORECASE)
        repos = re.findall(r"^projects(.*)?$", query, re.IGNORECASE)
        groups = re.findall(r"^groups(.*)?$", query, re.IGNORECASE)
        starred = re.findall(r"^starred(.*)?$", query, re.IGNORECASE)
        account = re.findall(r"^my(.*)?$", query, re.IGNORECASE)

        try:
            if account:
                return extension.show_my_menu(account[0])

            if search:
                return extension.search_projects(search[0],
                                                 PROJECTS_SEARCH_TYPE_PUBLIC)

            if repos:
                return extension.search_projects(repos[0],
                                                 PROJECTS_SEARCH_TYPE_MEMBER)

            if starred:
                return extension.search_projects(starred[0],
                                                 PROJECTS_SEARCH_TYPE_STARRED)

            if groups:
                return extension.list_groups(groups[0])

            return extension.search_projects(query,
                                             PROJECTS_SEARCH_TYPE_MEMBER)

        except gitlab.GitlabError as exc:
            LOGGER.error(exc)
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="An error ocurred when connecting to GitLab",
                    description=str(exc),
                    highlightable=False,
                    on_enter=HideWindowAction(),
                )
            ])
Esempio n. 25
0
 def show_clipboard_list(self, text):
     '''
     Show the list of possible clipboard conversions
     '''
     text = text.strip()
     items = [
         {
             'name': 'Straight slashes (/)',
             'result': text.replace('\\', '/'),
         },
         {
             'name': 'Backward slashes (\\)',
             'result': text.replace('/', '\\'),
         },
         {
             'name': 'Escaped backward slashes (\\\\)',
             'result': text.replace('/', '\\').replace('\\', '\\\\'),
         },
         {
             'name': 'Unescaped backward slashes (\\)',
             'result': text.replace('\\\\', '\\'),
         },
         {
             'name': 'Unescaped straight slashes (/)',
             'result': text.replace('\\\\', '\\').replace('\\', '/'),
         },
         {
             'name': 'Add double quotes',
             'result': '"' + text + '"',
         },
         {
             'name': 'Add single quotes',
             'result': "'" + text + "'",
         },
         {
             'name': 'Remove quotes',
             'result': text.replace('"', '').replace("'", ''),
         },
     ]
     results_list = []
     for item in items:
         results_list.append(
             ExtensionResultItem(
                 icon='images/icon.png',
                 name=item.get('name'),
                 description=item.get('result'),
                 on_enter=CopyToClipboardAction(item.get('result'))))
     return RenderResultListAction(results_list)
Esempio n. 26
0
    def on_event(self, event, extension):
        query = event.get_argument()

        if query:
            query = query.split()
            url = query[0] if match('\w+://',
                                    query[0]) else 'http://' + query[0]
            custom = query[1] if len(query) > 1 else None

            if custom and not (5 <= len(custom) <= 30
                               and custom.replace("_", "").isalnum()):
                name = 'Invalid custom name'
                description = 'Must be 5-30 characters long and contain only english characters.'
                on_enter = HideWindowAction()
            else:
                try:
                    urlopen(url)
                except (URLError, ValueError):
                    name = 'Not a valid URL'
                    description = 'Please check if this URL actually exists and try again'
                    on_enter = HideWindowAction()
                else:
                    req_url = 'https://is.gd/create.php?format=simple&url=%s' % url

                    if custom:
                        req_url += '&shorturl=%s' % custom

                    request = get(req_url)

                    if request.status_code == 200:
                        short = request.text
                        name = 'Shortened URL: %s' % short
                        description = 'Copy to clipboard'
                        on_enter = CopyToClipboardAction(short)
                    else:
                        name = ('Oops... (Error: %s - %s)' %
                                (request.status_code,
                                 self.errors[request.status_code][0]))
                        description = self.errors[request.status_code][1]
                        on_enter = HideWindowAction()

            item = [
                ExtensionResultItem(icon='images/icon.png',
                                    name=name,
                                    description=description,
                                    on_enter=on_enter)
            ]
            return RenderResultListAction(item)
Esempio n. 27
0
    def on_event(self, event, extension):

        description = "Type in your query and press Enter..."

        url = "https://laravel.com/docs/"

        if event.get_argument() != None:
            description = url + event.get_argument()

        return RenderResultListAction([
            ExtensionResultItem(
                icon='icons/laravel.svg',
                name='Laravel Search',
                description=description,
                on_enter=OpenUrlAction(url + (event.get_argument() or '')))
        ])
Esempio n. 28
0
 def on_event(self, event, extension):
     items = []
     arg = event.get_argument()
     if arg:
         result_list = SortedList(arg, min_score=40, limit=10)
         result_list.extend(extension.character_list)
         for char in result_list:
             image_path = get_character_icon(char)
             items.append(
                 ExtensionResultItem(
                     icon=image_path,
                     name=char.name + " - " + char.character,
                     description=char.block + " - " + char.code,
                     on_enter=CopyToClipboardAction(char.character),
                 ))
     return RenderResultListAction(items)
Esempio n. 29
0
    def on_event(self, event, extension):

        data = event.get_data()
        path = data['path']

        results = []
        for item in self.build_actions(path):

            (verb, action) = item
            results.append(
                ExtensionResultItem(icon='images/papirus-gear-128.png',
                                    name='{verb} {path}'.format(verb=verb,
                                                                path=path),
                                    on_enter=action))

        return RenderResultListAction(results)
Esempio n. 30
0
    def list_passwords(self, query):
        """ Lists passwords from LastPass vault """

        try:
            pwds = self.lp.get_passwords(query)

            return self.list_passwords_result(pwds)

        except LastPassError as e:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name=e.output,
                                    description='LastPass Error',
                                    highlightable=False,
                                    on_enter=HideWindowAction())
            ])