首頁 > 後端開發 > Python教學 > 使用命令資料庫開發 ulauncher 擴展

使用命令資料庫開發 ulauncher 擴展

Susan Sarandon
發布: 2025-01-06 20:19:41
原創
721 人瀏覽過

週末,我透過 Reddit 找到了一個項目,涉及 Flow Launcher 的插件。我為我的 Ubuntu Linux 環境創建了一個 fzf 和 rofi 版本,然後想,將其移植到 uLauncher 有多難?

Develop a ulauncher extension with a command database

在這裡我記錄了我所做的事情。

1.在~/.local/share/ulauncher/extensions/裡面

建立一個新目錄。就我而言,我創建了 ~/.local/share/ulauncher/extensions/com.github.ubuntupunk.ulauncher-vim

2. 觸摸以下文件:

├── images
│   └── icon.png
├── versions.json
├── manifest.json
└── main.py
登入後複製

3. 在 versions.json 中放置以下樣板:

[
  {"required_api_version": "2", "commit": "master"}
]
登入後複製

4. 在manifest.json中

{
  "required_api_version": "2",
  "name": "Demo extension",
  "description": "Extension Description",
  "developer_name": "John Doe",
  "icon": "images/icon.png",
  "options": {
    "query_debounce": 0.1
  },
  "preferences": [
    {
      "id": "demo_kw",
      "type": "keyword",
      "name": "Demo",
      "description": "Demo extension",
      "default_value": "dm"
    }
  ]
}
登入後複製

5. 在main.py中

from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import KeywordQueryEvent, ItemEnterEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction
from ulauncher.api.shared.action.HideWindowAction import HideWindowAction


class DemoExtension(Extension):

    def __init__(self):
        super().__init__()
        self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())


class KeywordQueryEventListener(EventListener):

    def on_event(self, event, extension):
        items = []
        for i in range(5):
            items.append(ExtensionResultItem(icon='images/icon.png',
                                             name='Item %s' % i,
                                             description='Item description %s' % i,
                                             on_enter=HideWindowAction()))

        return RenderResultListAction(items)

if __name__ == '__main__':
    DemoExtension().run()
登入後複製

6.現在編輯manifest.json

{
  "required_api_version": "2",
  "name": "Vim Prompter",
  "description": "Vim cheatsheet helper",
  "developer_name": "David Robert Lewis",
  "icon": "images/icon.png",
  "options": {
    "query_debounce": 0.1
  },
  "preferences": [
    {
      "id": "vm_kw",
      "type": "keyword",
      "name": "Vim",
      "description": "Search for Vim commands",
      "default_value": "vm"
    }
  ]
登入後複製

7.在main.py中新增命令載入功能

class VmExtension(Extension):
    def load_vim_commands(self):
        """Load Vim commands from JSON file."""
        package_dir = os.path.dirname(os.path.abspath(__file__))
        full_path = os.path.join(package_dir, 'db', 'commands.json')   
        with open(full_path, 'r') as file:
            return json.load(file)

    def __init__(self):
        super().__init__()
        self.vim_commands = self.load_vim_commands()
        self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())
登入後複製

8. 使用以下內容建立 db 資料夾:

commands.json

範例結構:

{
  "categories": {
    "navigation": {
      "name": "Navigation",
      "patterns": [
        "scroll",
        "jump",
        "goto",
        "position"
      ],
      "subcategories": {
        "cursor": {
          "name": "Cursor Movement",
          "patterns": [
            "move[s]? cursor",
            "^[hjkl]$",
            "^[HJKL]$",
            "^[wWeEbB]$"
          ]
        },
登入後複製

您可以在此處查看完整的commands.json。

9. 修改KeywordQueryEventListener以實作搜尋功能。

class KeywordQueryEventListener(EventListener):
    def on_event(self, event, extension):
        query = event.get_argument() or ""
        items = []

        # If no query, show all commands (limited to first 8)
        commands_to_show = extension.vim_commands

        # If there's a query, filter commands
        if query:
            commands_to_show = [
                cmd for cmd in extension.vim_commands
                if query.lower() in cmd['command'].lower() or 
                   query.lower() in cmd['description'].lower()
            ]

        # Limit results to first 8 matches
        for cmd in commands_to_show[:8]:
            items.append(ExtensionResultItem(
                icon='images/icon.png',
                name=cmd['command'],
                description=f"{cmd['name']} - {cmd['description']}",
                on_enter=HideWindowAction()
            ))

        return RenderResultListAction(items)
登入後複製

10.新增URL開啟功能。我們需要匯入 webbrowser 並修改 on_enter 操作以開啟 Vim 命令 URL

from ulauncher.api.shared.action.OpenUrlAction import OpenUrlAction

class KeywordQueryEventListener(EventListener):
    def on_event(self, event, extension):
        query = event.get_argument() or ""
        items = []

        commands_to_show = extension.vim_commands

        if query:
            commands_to_show = [
                cmd for cmd in extension.vim_commands
                if query.lower() in cmd['command'].lower() or 
                   query.lower() in cmd['description'].lower()
            ]

        for cmd in commands_to_show[:8]:
            url = f"https://vim.rtorr.com/#:~:text={cmd['rtorr_description']}"
            items.append(ExtensionResultItem(
                icon='images/icon.png',
                name=cmd['command'],
                description=f"{cmd['name']} - {cmd['description']}",
                on_enter=OpenUrlAction(url)
            ))

        return RenderResultListAction(items)
登入後複製

11. 主要變化是:

  • 新增了 OpenUrlAction 導入
  • 用 OpenUrlAction 取代 HideWindowAction
  • 使用指令的 rtorr_description 建構 URL

12.完整的項目代碼可以在這裡查看:

ulauncher-vim 倉庫

以及此處的 ulauncher 擴充

參考

  1. https://dev.to/brpaz/an-introduction-to-ulauncher-extension-development-1m69
  2. https://ext.ulauncher.io/-/github-ubuntupunk-ulauncher-vim

以上是使用命令資料庫開發 ulauncher 擴展的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板