Пример #1
0
    def on_event(self, event, extension):
        icon = "images/icon.png"
        items = []
        arg = event.get_argument()
        hosts = extension.parse_ssh_config()
        hosts += extension.parse_known_hosts()

        hosts.sort()

        if arg is not None and len(arg) > 0:
            hosts = [x for x in hosts if arg in x]

        for host in hosts:
            items.append(
                ExtensionResultItem(
                    icon=icon,
                    name=host,
                    description="Connect to '{}' with SSH".format(host),
                    on_enter=ExtensionCustomAction(host, keep_app_open=False)))

        # If there are no results, let the user connect to the specified server.
        if len(items) <= 0:
            items.append(
                ExtensionResultItem(
                    icon=icon,
                    name=arg,
                    description="Connect to {} with SSH".format(arg),
                    on_enter=ExtensionCustomAction(arg, keep_app_open=False)))

        return RenderResultListAction(items)
Пример #2
0
    def build_bookmark_items(self, bookmarks, start_index):
        items = []

        prev_data = {'type': 'bookmarks', 'start': start_index - self.limit}
        if start_index >= self.limit:
            items.append(ExtensionResultItem(icon='images/prev.png',
                                             name='Previous bookmarks',
                                             on_enter=ExtensionCustomAction(prev_data, keep_app_open=True)))

        for bookmark in bookmarks[start_index:start_index + self.limit]:
            if bookmark.private:
                icon = 'images/lock.png'
            else:
                icon = 'images/bookmark.png'
            bookmark_data = {'type': 'bookmark', 'url': bookmark.url, 'browser': self.browser}
            tag_data = {'type': 'tags', 'tags': bookmark.tags}
            items.append(ExtensionResultItem(icon=icon,
                                             name=bookmark.description,
                                             description=bookmark.url,
                                             on_enter=ExtensionCustomAction(bookmark_data),
                                             on_alt_enter=ExtensionCustomAction(tag_data, keep_app_open=True)))

        next_data = {'type': 'bookmarks', 'start': start_index + self.limit}
        if start_index + self.limit < bookmarks.__len__():
            items.append(ExtensionResultItem(icon='images/next.png',
                                             name='Next bookmarks',
                                             on_enter=ExtensionCustomAction(next_data, keep_app_open=True)))
        return items
Пример #3
0
    def make_stop_menu(self, stop: Stop, back: str) -> BaseAction:
        items = [
            ExtensionResultItem(
                icon="images/icon.png",
                name="Departures",
                highlightable=False,
                on_enter=SetUserQueryAction(f"{self.kw} departures {stop.id}"))
        ]

        if self.fav_has(stop.id):
            items.append(
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Remove from favorites",
                    highlightable=False,
                    on_enter=ExtensionCustomAction(f"remove {stop.id}")))
        else:
            items.append(
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Add to favorites",
                    highlightable=False,
                    on_enter=ExtensionCustomAction(f"add {stop.id}")))

        items.append(
            ExtensionResultItem(icon="images/icon.png",
                                name="Back",
                                highlightable=False,
                                on_enter=SetUserQueryAction(back + "`")))
        return RenderResultListAction(items)
Пример #4
0
 def generate_results(self, event):
     for (pid, cmd, path, arg) in get_process_list():
         name = ('%s' % (cmd))
         description = ('PID: %s\t command: %s ' % (pid, path))
         if len(arg) > 0:
             description += '\nargs: %s' % arg
         on_enter = {'alt_enter': False, 'pid': pid, 'cmd': cmd}
         on_enter['keyword'] = event.get_keyword()
         on_enter['argument'] = event.get_argument()
         on_alt_enter = on_enter.copy()
         on_alt_enter['alt_enter'] = True
         if event.get_argument():
             if event.get_argument() in cmd or event.get_argument() == pid:
                 yield ExtensionResultItem(
                     icon=exec_icon,
                     name=name,
                     description=description,
                     on_enter=ExtensionCustomAction(on_enter),
                     on_alt_enter=ExtensionCustomAction(on_alt_enter,
                                                        keep_app_open=True))
         else:
             yield ExtensionResultItem(
                 icon=exec_icon,
                 name=name,
                 description=description,
                 on_enter=ExtensionCustomAction(on_enter),
                 on_alt_enter=ExtensionCustomAction(on_alt_enter,
                                                    keep_app_open=True))
Пример #5
0
    def gen_select_project_results(self, query, extension):
        time_entry_description = query[3:]

        no_project_action = ExtensionCustomAction({
            "action":
            "start_in_project",
            "pid":
            None,
            "time_entry_description":
            time_entry_description
        })
        no_project_result = self.gen_result_item(
            "No project", "Select to start time entry without a project.",
            no_project_action)

        results = [no_project_result]
        for project_id, project_name in extension.project_map.items():
            name = project_name
            description = "Select to start time entry for that project."
            start_in_project_action = ExtensionCustomAction({
                "action":
                "start_in_project",
                "pid":
                project_id,
                "time_entry_description":
                time_entry_description
            })
            results.append(
                self.gen_result_item(name, description,
                                     start_in_project_action))

        return results
Пример #6
0
    def on_event(self, event, extension):
        items = []
 
        items.append(ExtensionResultItem(
             icon='images/icon.png',
             name="Sentence",
             highlightable=False,
             on_enter=ExtensionCustomAction(
                 {'type': TYPE_SENTENCE})
        ))

        items.append(ExtensionResultItem(
             icon='images/icon.png',
             name="Paragraph",
             highlightable=False,
             on_enter=ExtensionCustomAction(
                 {'type': TYPE_PARAGRAPH})
         ))

        items.append(ExtensionResultItem(
            icon='images/icon.png', 
            name="Text",
            highlightable=False,
            on_enter=ExtensionCustomAction(
                 {'type': TYPE_TEXT})
        ))

        return RenderResultListAction(items)
Пример #7
0
class KeywordQueryEventListener(EventListener):

    def on_event(self, event, extension):
        path = event.get_argument()
        print "path is %s " % path
        items = []
		items.append(ExtensionResultItem(icon='images/icon.png',
                                            name='jump to %s' % path,
                                            description='jump to here and open in file',
                                            on_enter=ExtensionCustomAction(path)))


        query_result = List_choice().get_top_five(path)
        # if path is a new one,so result return
        if len(query_result) != 0:
            for i in range(len(query_result)):
                # print "get result %d" % i
                # print "it is %s" %query_result[i]
                items.append(ExtensionResultItem(icon='images/icon.png',
                                            name='jump to %s' % query_result[i][0],
                                            description='jump to here and open in file',
                                            on_enter=ExtensionCustomAction(query_result[i][0])))
        else:
            items.append(ExtensionResultItem(icon='images/icon.png',
                                            name='jump to %s (new)' % path,
                                            description='jump to here and open in file',
                                            on_enter=ExtensionCustomAction(path)))
        return RenderResultListAction(items)
Пример #8
0
def get_menu_items(spotify_bus, keep_open=True):
    spotify_properties = dbus.Interface(spotify_bus, properites_interface)
    meta_data = spotify_properties.Get(player_interface, 'Metadata')
    status = spotify_properties.Get(player_interface, 'PlaybackStatus')
    artist_name = ', '.join(meta_data['xesam:artist']).encode('utf8')
    track_name = meta_data['xesam:title'].encode('utf8')
    album_name = meta_data['xesam:album'].encode('utf8')
    items = [
        ExtensionResultItem(
            icon='images/play.png' if status == 'Paused' else 'images/pause.png',
            name='{} - {}'.format(artist_name, track_name),
            description='Album: {}     ({})'.format(album_name, status),
            on_enter=ExtensionCustomAction('PlayPause', keep_app_open=keep_open),
        ),
        ExtensionResultItem(
            icon='images/next.png',
            name='Next track',
            on_enter=ExtensionCustomAction('Next', keep_app_open=keep_open),
        ),
        ExtensionResultItem(
            icon='images/prev.png',
            name='Previous track',
            on_enter=ExtensionCustomAction('Previous', keep_app_open=keep_open),
        ),
    ]
    return items
Пример #9
0
    def _generate_item(
        self,
        title: str = '',
        desc: str = '',
        icon: str = '',
        small: bool = False,
        action: Union[dict, BaseAction] = DoNothingAction(),
        alt_action: Union[dict, BaseAction] = DoNothingAction(),
        keep_open: bool = False
    ) -> Union[ExtensionResultItem, ExtensionSmallResultItem]:

        if isinstance(action, dict):
            action['_keep_app_open'] = keep_open
            action = ExtensionCustomAction(action, keep_app_open=keep_open)
        if isinstance(alt_action, dict):
            alt_action['_keep_app_open'] = keep_open
            alt_action = ExtensionCustomAction(alt_action,
                                               keep_app_open=keep_open)

        if small:
            item = ExtensionSmallResultItem
        else:
            item = ExtensionResultItem

        return item(
            name=title.replace('&', '&#38;') if title else '',
            description=desc.replace('&', '&#38;') if desc else '',
            icon=icon if icon else self.ICONS['main'],
            on_enter=action if action else DoNothingAction(),
            on_alt_enter=alt_action if alt_action else DoNothingAction())
Пример #10
0
    def on_event(self, event, extension):
        if event.get_keyword() == 'notes':
            resNotes = []
            f = open(notesFilePath, 'r')
            lines = f.read().split('\n')
            f.close()

            notes = getNotes()
            for note in notes:
                note['mode'] = ''
                if event.get_argument() == 'delete' or event.get_argument(
                ) == 'del' or event.get_argument() == 'd':
                    note['mode'] = 'deleteNote'
                if event.get_argument() == 'copy' or event.get_argument(
                ) == 'c':
                    note['mode'] = 'copyToClipboard'
                resNotes.append(
                    ExtensionResultItem(icon='note.png',
                                        name=note['data'],
                                        description='',
                                        on_enter=ExtensionCustomAction(
                                            note, keep_app_open=True)))
            return RenderResultListAction(resNotes)

        if event.get_keyword() == 'note':
            note = {}
            note['data'] = event.get_argument()
            note['mode'] = 'addNewNote'
            return RenderResultListAction([
                ExtensionResultItem(icon='note.png',
                                    name='New Note:',
                                    description=note['data'],
                                    on_enter=ExtensionCustomAction(
                                        note, keep_app_open=True))
            ])
Пример #11
0
def create_note_item(note, idx_item):
    """
    Create item linking to a database note
    :param note:
    :param idx_item:
    :return:
    """
    # HACK: Using note from Notes or FTS table
    if 'id' in note:
        note_id = note['id']
    elif 'uid' in note:
        note_id = note['uid']
    else:
        raise Exception

    return ExtensionSmallResultItem(
        icon='images/joplin.png',
        name=note['title'],
        # description=note['body'],
        on_enter=ExtensionCustomAction(
            {
                'func': open_note_edition_action,
                'uid': note_id
            },
            keep_app_open=True),
        on_alt_enter=ExtensionCustomAction(
            {
                'func': imfeelinglucky_action,
                'uid': note_id
            },
            keep_app_open=True),
    )
Пример #12
0
    def show_menu(self):
        keyword = self.keyword

        items = []

        items.append(
            ExtensionResultItem(name="Create Task",
                                description="Create a new task",
                                icon="images/create.png",
                                on_enter=SetUserQueryAction("%s create " % keyword))
        )

        items.append(
            ExtensionResultItem(name="Today Tasks",
                                description="Today task list",
                                icon="images/today.png",
                                on_enter=ExtensionCustomAction({"action": "today"}, keep_app_open=True))
        )

        items.append(
            ExtensionResultItem(name="Projects",
                                description="Project list",
                                icon="images/projects.png",
                                on_enter=ExtensionCustomAction({"action": "projects"}, keep_app_open=True))
        )

        return RenderResultListAction(items)
Пример #13
0
    def on_event(self, event, extension):
        reload(config)
        try:
            if config.database_path == "" or config.master_key == "":
                raise ValueError("您尚未配置数据库路径或密码,请按回车配置")
            try:
                extension.db = PyKeePass(config.database_path,
                                         password=config.master_key)
            except:
                raise IOError("数据库或密码错误,回车后请重新配置")
            arg = event.get_argument()
            args_list = None
            try:
                args_list = arg.split(" ")
            except:
                pass
            if len(args_list) >= 1:
                arg = args_list[0]
                if arg == "add":
                    return RenderResultListAction([
                        ExtensionResultItem(icon='images/icon.png',
                                            name='%s' % "添加密码到数据库",
                                            on_enter=ExtensionCustomAction(
                                                args_list, keep_app_open=True))
                    ])
                else:
                    if len(args_list) > 1:
                        raise AttributeError("参数填写错误")
                    # 执行密码查询
                    items = []
                    for e in extension.db.entries:
                        title = e.title
                        name = e.username
                        if title is None:
                            title = ""
                        if name is None:
                            name = ""
                        if arg in title or arg in name:
                            items.append(
                                ExtensionResultItem(
                                    icon='images/icon.png',
                                    name='%s' % title,
                                    description='%s' % name,
                                    on_enter=CopyToClipboardAction(
                                        e.password)))
                    return RenderResultListAction(items)

        except (ValueError, IOError, AttributeError), e:
            print type(e)
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name='%s' % e.message,
                                    on_enter=ExtensionCustomAction(
                                        e, keep_app_open=True))
            ])
Пример #14
0
    def on_event(self, event, extension):
        items = []
        query = event.get_argument()

        if str(query).split(' ')[0] == 'in':
            items.insert(
                0,
                ExtensionResultItem(
                    icon='images/icon_go.png',
                    name='Resume time tracking',
                    description=
                    'Create the start of a new time entry, using your last description as title',
                    on_enter=ExtensionCustomAction({'call': 'resume'})))
            if len(str(query).split(' ')) > 1:
                description = str(query).partition(' ')[2]
                items.insert(
                    0,
                    ExtensionResultItem(
                        icon='images/icon_go.png',
                        name=description,
                        description=
                        'Create the start of a new time entry, using this as title',
                        on_enter=ExtensionCustomAction({
                            'call': 'new',
                            'message': description
                        })))
        if str(query).split(' ')[0] == 'out':
            items.insert(
                0,
                ExtensionResultItem(
                    icon='images/icon_stop.png',
                    name='Stop current tracking',
                    description=
                    'Stops tracking and writes recorded time to Clockify API',
                    on_enter=ExtensionCustomAction({'call': 'end'})))
        if str(query).split(' ')[0] == 'status':
            items.insert(
                0,
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Status of current tracking',
                    description=
                    'Get the name and the duration of the currently running tracking',
                    on_enter=ExtensionCustomAction({'call': 'status'})))

        items.append(
            ExtensionResultItem(
                icon='images/icon.png',
                name='Open time tracker',
                description='Opens Clockify website in your webbrowser',
                on_enter=OpenUrlAction(url=tracker_url)))

        return RenderResultListAction(items)
Пример #15
0
    def on_event(self, event, extension):
        items = []
        logger.info('preferences %s' % json.dumps(extension.preferences))

        #       for i in range(5):
        #       item_name = extension.preferences['item_name']

        #       Create Connect entry for the menu
        data = {
            'action_name': 'Connect',
            'action_icon': 'images/Connect.png',
            'action_command': 'connect',
            'action_description': 'Connect VPN'
        }
        items.append(
            ExtensionResultItem(icon=data['action_icon'],
                                name=data['action_name'],
                                description=data['action_description'],
                                on_enter=ExtensionCustomAction(
                                    data, keep_app_open=False)))

        #       Create disconnect entry for the menu
        data = {
            'action_name': 'Disconnect',
            'action_icon': 'images/Disconnect.png',
            'action_command': 'disconnect',
            'action_description': 'Disconnect VPN'
        }
        items.append(
            ExtensionResultItem(icon=data['action_icon'],
                                name=data['action_name'],
                                description=data['action_description'],
                                on_enter=ExtensionCustomAction(
                                    data, keep_app_open=False)))

        #       Create reconnect entry for the menu
        data = {
            'action_name': 'Reconnect',
            'action_icon': 'images/Reconnect.png',
            'action_command': 'reconnect',
            'action_description': 'Reconnect VPN'
        }
        items.append(
            ExtensionResultItem(icon=data['action_icon'],
                                name=data['action_name'],
                                description=data['action_description'],
                                on_enter=ExtensionCustomAction(
                                    data, keep_app_open=False)))

        return RenderResultListAction(items)
Пример #16
0
 def build_tag_items(self, tags, user_keyword):
     items = []
     for tag in tags:
         data = {'type': 'pinboard', 'tags': [tag], 'browser': self.browser}
         items.append(ExtensionResultItem(icon='images/tag.png',
                                          name=tag,
                                          on_enter=SetUserQueryAction('%s %s' % (user_keyword, tag)),
                                          on_alt_enter=ExtensionCustomAction(data)))
     if items:
         data = {'type': 'pinboard', 'tags': tags, 'browser': self.browser}
         items.append(ExtensionResultItem(icon='images/tag.png',
                                          name='#all',
                                          on_enter=SetUserQueryAction('%s %s' % (user_keyword, '/'.join(tags))),
                                          on_alt_enter=ExtensionCustomAction(data)))
     return items
Пример #17
0
    def get_projects(self, query: str):
        projects = self.vscode.get_projects(self.preferences)

        if query:
            projects = [
                item for item in projects
                if query.strip().lower() in item['name'].lower()
            ]

        if not projects:
            return self.show_no_results_message(query)

        items = []
        for project in projects[:MAX_PROJECTS_IN_LIST]:
            icon = 'images/icon.png'

            if project['type'] == 'workspace':
                icon = 'images/code-dark-icon.png'

            items.append(
                ExtensionResultItem(icon=icon,
                                    name=project['name'],
                                    description=project['path'],
                                    on_enter=ExtensionCustomAction(
                                        {'path': project['path']}),
                                    on_alt_enter=OpenAction(project['path'])))

        return RenderResultListAction(items)
Пример #18
0
    def create_result_item(self, window):
        # icon as Pixbuf is not supported; saving it on the disk as a workaround
        icon = window.get_icon()
        icon_name = window.get_class_group_name()
        icon_type = 'ico'
        icon_path = '/tmp/{}.{}'.format(icon_name, icon_type)

        window_desc = window.get_name()

        if self.workspace_indicator:
            window_desc = '({}) {}'.format(window.workspace_id, window_desc)

        if not os.path.exists(icon_path):
            save_result = icon.savev(icon_path, icon_type, [], [])
            if not save_result:
                logger.error(
                    'Unable to write to /tmp. Using default icon as a fallback.'
                )
                icon_path = 'images/switch.png'

        return ExtensionResultItem(icon=icon_path,
                                   name=window.get_class_group_name(),
                                   description=window_desc,
                                   on_enter=ExtensionCustomAction(
                                       {'xid': window.get_xid()}))
Пример #19
0
 def to_extension_item(self):
     return ExtensionResultItem(icon=self.icon,
                                name=self.app_name,
                                description=self.title,
                                selected_by_default=self.is_last,
                                on_enter=ExtensionCustomAction(
                                    self.id, keep_app_open=False))
Пример #20
0
    def on_event(self, event, extension):
        json_preferences = json.dumps(extension.preferences)
        logger.info(f'preferences {json_preferences}')

        query = event.get_argument()
        script = copyq_script_getAll
        script = copyq_script_getMatches % query if query else copyq_script_getAll
        proc = subprocess.check_output(
            ['copyq', '-'], input=script, encoding='utf8')
        json_arr = json.loads(proc)

        items = []
        for obj in json_arr:
            # item_name = html.escape(obj['text'].replace('\n', ' '))
            text = obj['text']
            item_name = html.escape(
                " ".join(filter(None, text.replace("\n", " ").split(" "))))

            # text = html.escape(" ".join(filter(None, text.replace("\n", " ").split(" "))))

            item_row = obj['row']
            item_types = ", ".join(obj['mimetypes'])
            data = {'row': item_row}
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=item_name,
                                    description=f'{item_row}: {item_types}',
                                    on_enter=ExtensionCustomAction(
                                        data, keep_app_open=False)))

        return RenderResultListAction(items[:10])
Пример #21
0
    def show_options_menu(self, query):
        """ Shoe some general configuration options for the extension """
        items = [
            ExtensionResultItem(
                icon='images/icon.png',
                name='Open DevDocs.io',
                description='Opens DevDocs on your default browser',
                highlightable=False,
                on_enter=OpenUrlAction("https://devdocs.io/")),
            ExtensionResultItem(
                icon='images/icon.png',
                name='Open cache folder',
                description=
                "Opens the folder where the documentation cache is stored",
                highlightable=False,
                on_enter=OpenAction(self.devdocs_svc.cache_dir)),
            ExtensionResultItem(
                icon='images/icon.png',
                name='Index Documentation',
                description=
                "This process might take a while. You will receive a notification when finished.",
                highlightable=False,
                on_enter=ExtensionCustomAction([]))
        ]

        return RenderResultListAction(items)
Пример #22
0
    def on_event(self, event, extension):

        items = []

        query = event.get_argument() or ""
        split_query = query.partition(" ")

        keyword = split_query[0]
        data = split_query[2]

        if keyword != "add":

            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name='Please use the keyword "add"',
                                    description='Example: add %s' % data,
                                    highlightable=False,
                                    on_enter=DoNothingAction()))

            return RenderResultListAction(items)

        else:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name="Press enter to add: %s" % (data),
                                    highlightable=False,
                                    on_enter=ExtensionCustomAction(
                                        data, keep_app_open=True)))

            return RenderResultListAction(items)
Пример #23
0
    def on_event(self, event, extension):
        arg = event.get_argument()
        items = []

        if arg is None:
            items = self.__help()
        else:
            try:
                results = locator.run(arg)
                alt_action = ExtensionCustomAction(results, True)
                for file in results:
                    items.append(
                        ExtensionSmallResultItem(icon='images/ok.png',
                                                 name=str(file, 'utf-8'),
                                                 on_enter=OpenAction(file),
                                                 on_alt_enter=alt_action))
            except Exception as e:
                error_info = str(e)
                items = [
                    ExtensionSmallResultItem(
                        icon='images/error.png',
                        name=error_info,
                        on_enter=CopyToClipboardAction(error_info))
                ]

        return RenderResultListAction(items)
Пример #24
0
    def on_event(self, event, extension):
        keyword = event.get_keyword()
        query = event.get_argument()

        if query == None:
            return None

        notebooks = extension.get_notebooks()

        # Sort by note count. The notebook with the most notes should be on top.
        notebooks.sort(key=lambda x: x['note_count'], reverse=True)

        results = []

        print(extension.limit)

        for notebook in notebooks[:extension.limit]:
            data = {
                'text': query,
                'type': keyword,
                'notebookId': notebook['id']
            }
            results.append(ExtensionResultItem(icon='images/icon.png',
                                               name="Add %s to notebook %s" % (keyword, notebook['title']),
                                               on_enter=ExtensionCustomAction(data, keep_app_open=False)))

        return RenderResultListAction(results)
Пример #25
0
 def render_search_results(self, keyword, entries, extension):
     max_items = extension.get_max_result_items()
     items = []
     if not entries:
         items.append(NO_SEARCH_RESULTS_ITEM)
     else:
         for e in entries[:max_items]:
             action = ExtensionCustomAction(
                 {
                     "action": "activate_entry",
                     "entry": e,
                     "keyword": keyword
                 },
                 keep_app_open=True,
             )
             items.append(
                 ExtensionResultItem(
                     icon=ITEM_ICON,
                     name=e["name"],
                     description=self.bitwarden.get_entry_details(
                         e["id"])["username"],
                     on_enter=action,
                 ))
         if len(entries) > max_items:
             items.append(
                 more_results_available_item(len(entries) - max_items))
     return RenderResultListAction(items)
Пример #26
0
 def gen_repo_item(self, repo):
     icon = repo["tool"]
     open_action = ExtensionCustomAction({"action": "open", "repo": repo})
     return ExtensionResultItem(icon=f"images/{icon}.png",
                                name=repo["name"],
                                description=repo["path"],
                                on_enter=open_action)
Пример #27
0
def formatEntry(icon, query, entry):
    entryArr = entry.strip().split('\n')
    context = []
    pos = 0

    if query:
        line = next(l for l in entryArr if query in l.lower())
        pos = entryArr.index(line)

    if pos > 0:
        line = entryArr[pos - 1].strip()
        if line:
            context.append('...' + line)

    context.append(entryArr[pos])

    if len(entryArr) > pos + 1:
        line = entryArr[pos + 1].strip()
        if line:
            context.append(line + '...')

    return ExtensionSmallResultItem(
        icon     = icon,
        name     = '\n'.join(context),
        on_enter = ExtensionCustomAction(entry)
    )
Пример #28
0
    def search_tabs(self, event):
        """ Search tabs """

        if not self.brotab_client.is_installed():
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Brotab is not installed on your system",
                    description="Press enter to open install instructions.",
                    highlightable=False,
                    on_enter=OpenUrlAction("https://github.com/balta2ar/brotab#installation"),
                )
            ])

        items = []
        tabs = self.brotab_client.search_tabs(event.get_argument())

        for tab in tabs[:DISPLAY_MAX_RESULTS]:
            data = {"tab": tab["prefix"], "mode": self.mode}

            items.append(
                ExtensionSmallResultItem(
                    icon="images/%s" % tab["icon"],
                    name=tab["name"],
                    description=tab["url"],
                    on_enter=ExtensionCustomAction(data),
                    on_alt_enter=CopyToClipboardAction(tab["url"]),
                ))

        if not items:
            return self.show_no_results_message()

        return RenderResultListAction(items)
Пример #29
0
    def show_applications(self, query):
        """ shows the list of available applications known by the extension """
        apps = self.shortcuts_service.get_applications(query)

        if not apps:
            return RenderResultListAction([
                ExtensionSmallResultItem(
                    icon='images/icon.png',
                    name='No applications found matching your criteria',
                    highlightable=False,
                    on_enter=HideWindowAction())
            ])

        items = []
        for app in apps[:15]:
            items.append(
                ExtensionSmallResultItem(icon=app['icon'],
                                         name=app['name'],
                                         on_enter=ExtensionCustomAction({
                                             "action":
                                             "show",
                                             "app":
                                             app,
                                         }),
                                         on_alt_enter=OpenUrlAction(
                                             app['reference_url'])))
        return RenderResultListAction(items)
Пример #30
0
    def on_event(self, event, extension):
        items = []

        lc = psutil.net_connections("inet")
        def get_pid_name(name):
            try:
                return check_output(["ps", "-p", name, "-o", "comm="])
            except Exception:
                return None

        listeners = []
        for c in lc:
            (ip, port) = c.laddr

            if c.type == socket.SOCK_STREAM and c.status == psutil.CONN_LISTEN:
                pid_name = "(unknown)"
                if c.pid:
                    name = get_pid_name(str(c.pid))
                    if name:
                        pid_name = name.strip()
                listeners.append([pid_name, str(ip) , str(port)])
        col_width = max(len(listener[0]) for listener in listeners) + 2

        for listener in listeners:
            address = listener[1] + ":" + listener[2]
            data = {"action": ACTION_GOTO_ADDR, "address": address}
            items.append(ExtensionResultItem(icon=ICON_PATH,
                                             name=listener[0].ljust(
                                                 col_width) + address,
                description="Browse to " + address,
                on_enter=ExtensionCustomAction(data, keep_app_open=False)))

        return RenderResultListAction(items)