検索
ホームページバックエンド開発Python チュートリアルコマンド データベースを使用してランチャー拡張機能を開発する

週末、私は 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 を開く機能を追加します。 Vim コマンド URL を開くには、ウェブブラウザをインポートし、on_enter アクションを変更する必要があります。

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 インポートを追加しました
  • HideWindowAction を OpenUrlAction に置き換えました
  • コマンドの 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

以上がコマンド データベースを使用してランチャー拡張機能を開発するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python Switchステートメントとは何ですか?Python Switchステートメントとは何ですか?Apr 30, 2025 pm 02:08 PM

この記事では、バージョン3.10で導入されたPythonの新しい「マッチ」ステートメントについて説明します。これは、他の言語のスイッチステートメントに相当するものです。コードの読みやすさを向上させ、従来のif-elif-elよりもパフォーマンスの利点を提供します

Pythonの例外グループとは何ですか?Pythonの例外グループとは何ですか?Apr 30, 2025 pm 02:07 PM

Python 3.11の例外グループは、複数の例外を同時に処理することで、同時シナリオと複雑な操作でエラー管理を改善します。

Pythonの関数注釈とは何ですか?Pythonの関数注釈とは何ですか?Apr 30, 2025 pm 02:06 PM

Pythonの関数注釈は、タイプチェック、ドキュメント、およびIDEサポートの関数にメタデータを追加します。それらはコードの読みやすさ、メンテナンスを強化し、API開発、データサイエンス、ライブラリの作成において重要です。

Pythonのユニットテストとは何ですか?Pythonのユニットテストとは何ですか?Apr 30, 2025 pm 02:05 PM

この記事では、Pythonの単体テスト、その利点、およびそれらを効果的に書く方法について説明します。テスト用のUnittestやPytestなどのツールを強調しています。

Pythonのアクセス仕様とは何ですか?Pythonのアクセス仕様とは何ですか?Apr 30, 2025 pm 02:03 PM

記事では、Pythonのアクセス仕様について説明します。Pythonは、厳格な執行ではなく、クラスメンバーの可視性を示すために命名規則を使用します。

Pythonの__init __()とは何ですか?また、セルフはどのように役割を果たしますか?Pythonの__init __()とは何ですか?また、セルフはどのように役割を果たしますか?Apr 30, 2025 pm 02:02 PM

記事では、Pythonの\ _ \ _ init \ _ \ _()メソッドと、オブジェクト属性の初期化における自己の役割について説明します。 \ _ \ _ init \ _ \ _()に対するその他のクラス方法と継承の影響についてもカバーされています。

Pythonの@ClassMethod、@StaticMethod、およびインスタンスメソッドの違いは何ですか?Pythonの@ClassMethod、@StaticMethod、およびインスタンスメソッドの違いは何ですか?Apr 30, 2025 pm 02:01 PM

この記事では、@ClassMethod、@StaticMethod、およびPythonのインスタンスメソッドの違いについて説明し、そのプロパティ、ユースケース、および利点を詳述します。必要な機能とDAに基づいて適切な方法タイプを選択する方法を説明します

Pythonアレイに要素をどのように追加しますか?Pythonアレイに要素をどのように追加しますか?Apr 30, 2025 am 12:19 AM

inpython、youappendelementStoalistusingtheappend()method.1)useappend()forsingleelements:my_list.append(4).2)useextend()or = formultipleElements:my_list.extend(another_list)ormy_list = [4,5,6] .3)forspecificpositions:my_list.insert(1,5).beaware

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター