コード例 #1
0
 def on_event(self, event, extension):
     tmpSymbols = []
     tmpKey = event.get_argument()
     if tmpKey == None:
         return RenderResultListAction([
             ExtensionResultItem(
                 icon='images/icon.png',
                 name='Please specify the desired symbol set',
                 on_enter=DoNothingAction())
         ])
     elif tmpKey.upper() in mySymbols:
         for tmpMatch in mySymbols[tmpKey.upper()]:
             tmpSymbols.append(
                 ExtensionResultItem(
                     icon='images/icon.png',
                     name=tmpMatch,
                     description='Copy ' + tmpMatch + ' to clipboard',
                     on_enter=CopyToClipboardAction(tmpMatch)))
         return RenderResultListAction(tmpSymbols)
     else:
         return RenderResultListAction([
             ExtensionResultItem(icon='images/icon.png',
                                 name='Unknown code...',
                                 on_enter=DoNothingAction())
         ])
コード例 #2
0
 def on_event(self, event, extension) -> BaseAction:
     try:
         data = event.get_data()
         action = data.get("action", None)
         if action == "read_passphrase":
             self.read_verify_passphrase()
             return DoNothingAction()
         if action == "activate_entry":
             keyword = data.get("keyword", None)
             entry = data.get("entry", None)
             extension.set_active_entry(keyword, entry)
             prev_query_arg = data.get("prev_query_arg", None)
             extension.set_active_entry_search_restore(
                 entry, prev_query_arg)
             extension.add_recent_active_entry(entry)
             return SetUserQueryAction("{} {}".format(keyword, entry))
         if action == "show_notification":
             Notify.Notification.new(data.get("summary")).show()
     except KeepassxcCliNotFoundError:
         return render.cli_not_found_error()
     except KeepassxcFileNotFoundError:
         return render.db_file_not_found_error()
     except KeepassxcCliError as exc:
         return render.keepassxc_cli_error(exc.message)
     return DoNothingAction()
コード例 #3
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('&', '&') if title else '',
            description=desc.replace('&', '&') 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())
コード例 #4
0
    def courses(self, query):
        logger.info("in courses")
        site = self.preferences['site']
        token = self.preferences['token']
        starred = self.preferences['courses_type'] == "Starred"
        data = get_service(
            'core_course_get_enrolled_courses_by_timeline_classification',
            token,
            site,
            classification="inprogress")

        if "exception" in data:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name=data["message"],
                                    on_enter=DoNothingAction())
            ])
        items = []
        for course in data['courses']:
            if query.lower() not in course['fullname'].lower():
                continue
            if starred and course["isfavourite"] is False:
                continue
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=f"{course['fullname']}",
                                    on_enter=OpenUrlAction(course['viewurl'])))
        if not items:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name="Nothing to Show",
                                    on_enter=DoNothingAction()))

        return RenderResultListAction(items)
コード例 #5
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(),
    )
コード例 #6
0
 def on_event(self, event, extension):
     data = event.get_data()
     # 数据库路径没配置
     if isinstance(data, ValueError):
         os.system("gedit " + os.path.join(dir_path, "config.py"))
     # 数据库路径或密码没验证成功
     if isinstance(data, IOError):
         os.system("gedit " + os.path.join(dir_path, "config.py"))
     # 参数填写错误
     if isinstance(data, AttributeError):
         pass
     # 添加密码
     if isinstance(data, list):
         print data, extension.db
         if len(data) != 4:
             return RenderResultListAction([
                 ExtensionResultItem(icon='images/icon.png',
                                     name='%s' % "参数填写错误",
                                     on_enter=DoNothingAction())
             ])
         else:
             title = data[-3]
             username = data[-2]
             pwd = data[-1]
             groups = extension.db.groups
             if len(groups) == 1:
                 extension.db.add_entry(groups[0], title, username, pwd)
                 extension.db.save()
             else:
                 extension.db.add_entry(groups[1], title, username, pwd)
                 extension.db.save()
             os.system("notify-send -i " + os.path.join(
                 os.path.join(dir_path, "images"), "icon.png") +
                       " 'KeePass' '密码添加成功'")
コード例 #7
0
 def do_nothing_result(self, text, icon=extension_icon, description=""):
     return RenderResultListAction([
         ExtensionResultItem(icon=extension_icon,
                             name=text,
                             description=description,
                             on_enter=DoNothingAction())
     ])
コード例 #8
0
ファイル: main.py プロジェクト: brpaz/ulauncher-dockerhub
    def search_repositories(self, query):
        """ Shows the a list of DockerHub repositories """
        if len(query) < 3:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Keep typing to search on Docker Hub ...',
                    highlightable=False,
                    on_enter=DoNothingAction())
            ])

        repos = self.dockerhub.search_repos(query)

        items = []

        if not repos:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="No results found matching your criteria",
                    highlightable=False,
                    on_enter=HideWindowAction())
            ])

        for repo in repos[:8]:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name="%s 🟊 %s" %
                                    (repo["name"], repo["stars"]),
                                    description=repo["description"],
                                    on_enter=OpenUrlAction(repo["url"])))

        return RenderResultListAction(items)
コード例 #9
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)
コード例 #10
0
    def process_empty_query(self) -> BaseAction:
        """
        Show something if query is empty
        """
        try:
            recently_modified = ls_dir(self.get_notes_path(),
                                       self.get_note_file_extensions())
        except SearchError as exc:
            return RenderResultListAction(
                [error_item(exc.message, exc.details)])

        items = [
            ExtensionResultItem(
                icon="images/notes-nv.svg",
                name="Please enter search query...",
                on_enter=DoNothingAction(),
            )
        ]

        for fn in recently_modified[:MAX_RESULTS_VISIBLE]:
            items.append(
                ExtensionResultItem(
                    icon="images/note.svg",
                    name=fn,
                    on_enter=callable_action(
                        self.open_note, os.path.join(self.get_notes_path(),
                                                     fn)),
                ))
        return RenderResultListAction(items)
コード例 #11
0
    def get_action_to_render(self, name, description, on_enter=None):
        item = ExtensionResultItem(name=name,
                                   description=description,
                                   icon=self.icon_file,
                                   on_enter=on_enter or DoNothingAction())

        return RenderResultListAction([item])
コード例 #12
0
ファイル: main.py プロジェクト: torbenal/ulauncher-bitwarden
def more_results_available_item(cnt):
    return ExtensionSmallResultItem(
        icon=EMPTY_ICON,
        name="...{} more results available, please refine the search query...".
        format(cnt),
        on_enter=DoNothingAction(),
    )
コード例 #13
0
def keepassxc_cli_error_item(message):
    return ExtensionResultItem(
        icon=ERROR_ICON,
        name="Error while calling keepassxc CLI",
        description=message,
        on_enter=DoNothingAction(),
    )
コード例 #14
0
    def build_result_item(self, page):
        """ Builds a result item object """

        browser_action = OpenUrlAction(page['url'])
        hawkeye_action = RunScriptAction('hawkeye --uri="%s"' % page['url'],
                                         [])

        epiphany_action = RunScriptAction(
            'epiphany-browser "%s"' % page['url'], [])

        if self.preferences['primary_action'] == "Hawkeye Quicklook":
            on_enter = hawkeye_action
        elif self.preferences['primary_action'] == "Gnome Web":
            on_enter = epiphany_action
        else:
            on_enter = browser_action

        if self.preferences['secondary_action'] == "None":
            on_alt_enter = DoNothingAction()
        elif self.preferences['secondary_action'] == "Hawkeye Quicklook":
            on_alt_enter = hawkeye_action
        elif self.preferences['secondary_action'] == "Gnome Web":
            on_alt_enter = epiphany_action
        else:
            on_alt_enter = browser_action

        return ExtensionResultItem(icon='images/icon.png',
                                   name=page['name'],
                                   description=page['category'],
                                   on_enter=on_enter,
                                   on_alt_enter=on_alt_enter)
コード例 #15
0
ファイル: BaseMode.py プロジェクト: mat1010/Ulauncher
 def handle_key_press_event(self, widget, event, query):
     """
     :param Gdk.Widget widget:
     :param Gdk.EventKey event:
     :param ~ulauncher.modes.Query.Query query:
     :rtype: :class:`BaseAction`
     """
     return DoNothingAction()
コード例 #16
0
def no_input_item():
    return [
        ExtensionResultItem(
            icon=ICON_FILE,
            name='No input',
            on_enter=DoNothingAction()
        )
    ]
コード例 #17
0
def no_action():
    return [
        ExtensionResultItem(
            icon=constants.ICON_FILE,
            name='No results',
            on_enter=DoNothingAction()
        )
    ]
コード例 #18
0
    def on_event(self, event, extension):
        data = event.get_data()
        type = data.get("type")

        if type == "select":
            extension.snippet = data.get("snippet")
            extension.state = "var"
        elif type == "cancel":
            extension.reset()
            return SetUserQueryAction("")

        next_variable = extension.snippet.next_variable()
        if extension.state == "var" and next_variable:
            keyword = extension.preferences["snippets_keyword"]
            extension.variable = next_variable
            return ActionList([
                SetUserQueryAction(keyword + " "),
                RenderResultListAction(
                    show_var_input(extension.snippet, next_variable,
                                   next_variable.get("default", "")))
            ])

        try:
            copy_mode = extension.preferences["snippets_copy_mode"]
            if extension.snippet.file_path_template:
                try:
                    file_path = extension.snippet.render_to_file_path(
                        copy_mode=copy_mode)
                    self._notify(extension,
                                 file_path,
                                 title="Snippet written to file")
                except FileExistsError as e:
                    self._notify(extension,
                                 e.args[0],
                                 title="File already exists")
                return HideWindowAction()
            else:
                (mimetype,
                 snippet) = extension.snippet.render(copy_mode=copy_mode)

                action = None
                if copy_mode == "xsel":
                    copy_to_clipboard_xsel(snippet, mimetype)
                    action = HideWindowAction()
                elif copy_mode == "wl":
                    copy_to_clipboard_wl(snippet, mimetype)
                    action = HideWindowAction()
                else:
                    action = CopyToClipboardAction(snippet)

                self._notify(extension, snippet, mimetype)
                return action
        except Exception as e:
            logger.exception(e)
            return RenderResultListAction(
                [ExtensionResultItem(name=str(e), on_enter=DoNothingAction())])
        finally:
            extension.reset()
コード例 #19
0
ファイル: old.py プロジェクト: TomNWainwright/dotfiles
def RenderError(error):
    items = []
    items.append(
        ExtensionResultItem(icon='images/error.png',
                            name=error['title'],
                            description=error['description'],
                            on_enter=DoNothingAction()))

    return items
コード例 #20
0
    def get_open_in_terminal_script(self, path):
        """ Returns the script based on the type of terminal """
        terminal_emulator = self.preferences['terminal_emulator']

        # some terminals might work differently. This is already prepared for that.
        if terminal_emulator in ['gnome-terminal', 'terminator', 'tilix', 'xfce-terminal']:
            return RunScriptAction(terminal_emulator, ['--working-directory', path])

        return DoNothingAction()
コード例 #21
0
ファイル: main.py プロジェクト: thiagoa/ulauncher-chrome-tabs
    def on_event(self, event, extension):
        tabId = event.get_data()

        extension.send_ws_message(json.dumps({
            'action': MESSAGING_ACTION_FOCUS_TAB,
            'tabId': tabId
        }))

        return DoNothingAction()
コード例 #22
0
def lang_items(from_lang, to_lang):
    return [
        ExtensionResultItem(icon=ICON_FILE,
                            name='Translating {} -> {}'.format(
                                from_lang, lang),
                            description='With Google Translation engine',
                            on_enter=DoNothingAction())
        for lang in to_lang.split('+')
    ]
コード例 #23
0
ファイル: main.py プロジェクト: zoni/ulauncher-meet
    def on_event(self, event, extension):
        items = []

        user_inputs = event.get_query().split()

        items = []

        if len(user_inputs) == 1 or user_inputs[1] in 'new':
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='New',
                    description='Start new meeting',
                    on_enter=OpenUrlAction('https://meet.google.com/new')))
        if len(user_inputs) == 1:
            for meeting in saved_meetings:
                items.append(
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name='Join %s' % meeting.name,
                        description='Join https://meet.google.com/%s' %
                        meeting.id,
                        on_enter=OpenUrlAction('https://meet.google.com/%s' %
                                               meeting.id)))
        if len(user_inputs) > 1:
            meet_id = user_inputs[1]
            if saved_meetings is None:
                items.append(
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name='Saved meetings misformed',
                        description=
                        'Please fix saved meetings in extension properties',
                        on_enter=DoNothingAction()))
            else:
                for meeting in saved_meetings:
                    if in_saved_meeting(meet_id, meeting):
                        items.append(
                            ExtensionResultItem(
                                icon='images/icon.png',
                                name='Join %s' % meeting.name,
                                description='Join https://meet.google.com/%s' %
                                meeting.id,
                                on_enter=OpenUrlAction(
                                    'https://meet.google.com/%s' %
                                    meeting.id)))

            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Join meeting',
                    description='Join https://meet.google.com/%s' % meet_id,
                    on_enter=OpenUrlAction('https://meet.google.com/%s' %
                                           meet_id)))

        return RenderResultListAction(items)
コード例 #24
0
def generate_launcher_item(item):
    script = item.get('script', 'Missing script...') or 'Missing script...'
    description = item[
        'description'] + ' • ' + script if 'description' in item else script

    return ExtensionResultItem(
        icon=get_icon(item.get('icon')),
        name=item.get('name', script) or script,
        description=description,
        on_enter=RunScriptAction(script) if script else DoNothingAction())
コード例 #25
0
def item_more_results_available(cnt: int) -> ResultItem:
    """
    Item showing how many more results are available
    """
    return ExtensionSmallResultItem(
        icon="images/empty.png",
        name="...{} more results available, please refine the search query...".
        format(cnt),
        on_enter=DoNothingAction(),
    )
コード例 #26
0
    def events(self, query):
        logger.info("in events")
        site = self.preferences['site']
        token = self.preferences['token']
        data = get_service('core_calendar_get_calendar_upcoming_view', token,
                           site)
        if "exception" in data:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name=data["message"],
                                    on_enter=DoNothingAction())
            ])
        items = []
        for event in data['events']:
            # convert epoch time to readable
            time = datetime.datetime.fromtimestamp(
                event['timestart']).strftime("%d/%m/%y, %H:%M")
            # TODO handle idn and url better?
            try:
                idn = event['course']['id']
            except:
                idn = ''
            try:
                url = event['url']
            except:
                url = ''
            if query.lower() not in event['name'].lower():
                continue
            items.append(
                (ExtensionResultItem(icon='images/icon.png',
                                     name=f"{idn} - {event['name']}:   {time}",
                                     on_enter=OpenUrlAction(url)),
                 event['timestart']))
        # Sort by time
        items.sort(key=lambda x: x[1])
        items = [x[0] for x in items]
        if not items:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name="Nothing to Show",
                                    on_enter=DoNothingAction()))

        return RenderResultListAction(items)
コード例 #27
0
    def on_event(self, event, extension):
        """ Handles the event """
        fd_cmd = extension.preferences["fd_cmd"]
        if shutil.which(fd_cmd) is None:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name=
                    f"Command {fd_cmd} is not found, please install it first",
                    on_enter=HideWindowAction())
            ])

        query = event.get_argument()

        if not query or len(query) < 3:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Keep typing your search criteria ...",
                    on_enter=DoNothingAction())
            ])

        keyword = event.get_keyword()
        keyword_id = None
        # Find the keyword id using the keyword (since the keyword can be changed by users)
        for kw_id, kw in list(extension.preferences.items()):
            if kw == keyword:
                keyword_id = kw_id

        file_type = FILE_SEARCH_ALL
        if keyword_id == "ff_kw":
            file_type = FILE_SEARCH_FILE
        elif keyword_id == "fd_kw":
            file_type = FILE_SEARCH_DIRECTORY

        results = extension.search(query.strip(), file_type, fd_cmd)

        if not results:
            return RenderResultListAction([
                ExtensionResultItem(icon="images/icon.png",
                                    name=f"No Results found matching {query}",
                                    on_enter=HideWindowAction())
            ])

        items = []
        for result in results[:15]:
            items.append(
                ExtensionSmallResultItem(
                    icon=result["icon"],
                    name=result["path"].decode("utf-8"),
                    on_enter=OpenAction(result["path"].decode("utf-8")),
                    on_alt_enter=extension.get_open_in_terminal_script(
                        result["path"].decode("utf-8"))))

        return RenderResultListAction(items)
コード例 #28
0
ファイル: main.py プロジェクト: null011/ulauncher-searchploit
    def on_event(self, event, extension):

        query = event.get_argument()

        if not query:
            return RenderResultListAction([
                ExtensionResultItem(
                    name="Search '%s'" % query,
                    description='No results. Try searching something else :)',
                    icon=icon,
                    on_enter=DoNothingAction())
            ])

        results = []

        ss_results = extension.searchsploit(query,
                                            extension.preferences['ss_path'])

        if not ss_results['RESULTS_EXPLOIT']:
            return RenderResultListAction([
                ExtensionResultItem(
                    name="Search '%s'" % query,
                    description='No results. Try searching something else :)',
                    icon=icon,
                    on_enter=DoNothingAction())
            ])

        for i in ss_results['RESULTS_EXPLOIT'][0:11]:

            copy_cmd = "searchsploit -m {}".format(i['Path'])
            description = "Date: {Date} EDB-ID: {EDB-ID} Author: {Author} Platform: {Platform}".format(
                **i)

            results.append(
                ExtensionResultItem(
                    name=i['Title'],
                    description=description,
                    icon=icon,
                    on_enter=CopyToClipboardAction(text=copy_cmd)))

        return RenderResultListAction(results)
コード例 #29
0
	def on_event(self, event, extension):

		search_term = ''.join(['%', event.get_argument().replace('%', ''), '%']) if event.get_argument() else None
		if not search_term:
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name='Type in paste name...',
									on_enter=DoNothingAction())
			])
		search_terms = event.get_argument().replace('%', '').split(' ')
		search_term = ' '.join(search_terms)
		print(search_terms)
		print(' '.join(search_terms))
		if search_terms[0] == 'create':
			try:
				if not search_terms[1] and not search_terms[2]:
					return RenderResultListAction([
						ExtensionResultItem(icon=extension_icon,
											name='Type in new paste name and value',
											on_enter=DoNothingAction()),
						ExtensionResultItem(
											name='Format: [prefix] create <name of new paste> <value of new paste>',
											on_enter=DoNothingAction())
					])
			except: 
				return RenderResultListAction([
						ExtensionResultItem(icon=extension_icon,
											name='Type in new paste name and value',
											on_enter=DoNothingAction()),
						ExtensionResultItem(
											name='Format: [prefix] create <name of new paste> <value of new paste>',
											on_enter=DoNothingAction())
					])
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name="Create paste \"" + search_terms[1] + "\" with value \"" + ' '.join(x for x in search_terms[2:])+"\"",
									on_enter=pe.registerPaste(search_terms[1]," ".join(x for x in search_terms[2:])))
			])

		items = []
		try:
			for row in pe.getPastes(' '.join(search_terms)):
				if len(items) < 8:
					items.append(ExtensionResultItem(icon=extension_icon,
													 name="Copy paste: "+row['name'].capitalize(),
													 on_enter=CopyToClipboardAction(row['value'])))
		except:
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name='No pastes found with name "'+ ' '.join(search_terms)+ '"',
									on_enter=DoNothingAction()),
				ExtensionResultItem(icon=extension_icon,
									name='Add a paste with "cp create <name> <value>"',
									on_enter=DoNothingAction())
			])
		return RenderResultListAction(items)
コード例 #30
0
def ask_to_enter_query() -> BaseAction:
    """
    Ask user to start entering the search query
    """
    return RenderResultListAction([
        ExtensionResultItem(
            icon="images/keepassxc-search.svg",
            name="Enter search query...",
            description="Please enter your search query",
            on_enter=DoNothingAction(),
        )
    ])