### Install pyFlowLauncher Source: https://context7.com/garulf/pyflowlauncher/llms.txt Install the library using pip. Use the `[all]` extra for compatibility with Python versions older than 3.11. ```bash pip install pyflowlauncher[all] ``` -------------------------------- ### Install pyflowlauncher with all extras Source: https://github.com/garulf/pyflowlauncher/blob/main/README.md Install the pyflowlauncher package including all optional dependencies. This is recommended for supporting Python versions older than 3.11. ```python python -m pip install pyflowlauncher[all] ``` -------------------------------- ### Example of Scoring Results Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/scoring_results.md This example demonstrates how to use the scoring utility provided by PyFlowLauncher. ```python # This is a placeholder for the actual code from example1.py # In a real scenario, this would contain Python code for scoring results. print("Scoring results example") ``` -------------------------------- ### Registering Query and Action Methods Source: https://context7.com/garulf/pyflowlauncher/llms.txt Demonstrates registering both a `query` method and a custom `open_settings` action method using the `@plugin.on_method` decorator. Flow Launcher calls methods by their lowercased function name. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: r = Result( Title="Open settings", SubTitle="Click to trigger the 'open_settings' action", JsonRPCAction={"method": "open_settings", "parameters": []}, ) return send_results([r]) @plugin.on_method def open_settings(params: list) -> None: # Flow Launcher calls this when the user selects the result above pass plugin.run() ``` -------------------------------- ### Basic Plugin with Query Method Source: https://context7.com/garulf/pyflowlauncher/llms.txt Defines a simple plugin that responds to queries with a greeting and the user's input. The `plugin.run()` call should be the last line of your entry point. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: results = [ Result( Title="Hello from pyFlowLauncher", SubTitle=f"You typed: {query}", IcoPath="icon.png", ) ] return send_results(results) plugin.run() ``` -------------------------------- ### Plugin Initialization and Query Method Source: https://context7.com/garulf/pyflowlauncher/llms.txt Demonstrates how to initialize the Plugin class and register a 'query' method using the @plugin.on_method decorator. This method handles user input and returns a list of Result objects. ```APIDOC ## Plugin Initialization and Query Method ### Description This example shows the basic setup for a pyFlowLauncher plugin. It initializes the `Plugin` class, defines a `query` method decorated with `@plugin.on_method` to handle user input, and returns a `ResultResponse` containing a simple result. ### Method `@plugin.on_method` decorator for registering the `query` function. ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: results = [ Result( Title="Hello from pyFlowLauncher", SubTitle=f"You typed: {query}", IcoPath="icon.png", ) ] return send_results(results) plugin.run() ``` ### Response #### Success Response (ResultResponse) - **results** (list[Result]) - A list of Result objects to display to the user. #### Response Example ```json { "results": [ { "Title": "Hello from pyFlowLauncher", "SubTitle": "You typed: [user input]", "IcoPath": "icon.png" } ] } ``` ``` -------------------------------- ### Plugin Filesystem Helpers in pyFlowLauncher Source: https://context7.com/garulf/pyflowlauncher/llms.txt Illustrates how to use `run_dir`, `root_dir`, and `manifest` helpers provided by the `Plugin` class to access plugin-specific file paths and manifest information. `run_dir` points to the script's directory, `root_dir` to the plugin's root containing `plugin.json`, and `manifest` loads the plugin's configuration. ```python from pyflowlauncher import Plugin plugin = Plugin() # Absolute path to the script directory print(plugin.run_dir) # e.g. PosixPath('/plugins/MyPlugin/src') # Absolute path to the plugin root (where plugin.json lives) print(plugin.root_dir()) # e.g. PosixPath('/plugins/MyPlugin') # Full manifest contents manifest = plugin.manifest() print(manifest["Name"]) # "MyPlugin" print(manifest["Version"]) # "1.0.0" ``` -------------------------------- ### Registering Query and Action Methods Source: https://context7.com/garulf/pyflowlauncher/llms.txt Illustrates how to register both a 'query' method for displaying results and a custom 'open_settings' action method using the @plugin.on_method decorator. The 'query' method returns a result that, when selected, triggers the 'open_settings' action. ```APIDOC ## Registering Query and Action Methods ### Description This example demonstrates registering two methods: `query` for handling user input and `open_settings` for performing an action. The `query` method returns a `Result` object configured with a `JsonRPCAction` that calls the `open_settings` method when selected by the user. ### Method `@plugin.on_method` decorator for registering both `query` and `open_settings` functions. ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: r = Result( Title="Open settings", SubTitle="Click to trigger the 'open_settings' action", JsonRPCAction={"method": "open_settings", "parameters": []}, ) return send_results([r]) @plugin.on_method def open_settings(params: list) -> None: # Flow Launcher calls this when the user selects the result above pass plugin.run() ``` ### Response #### Success Response (ResultResponse for query, None for open_settings) - **query method**: Returns a `ResultResponse` containing a single `Result` object. - **open_settings method**: Returns `None` as it performs an action. #### Response Example ```json // Response from query method: { "results": [ { "Title": "Open settings", "SubTitle": "Click to trigger the 'open_settings' action", "JsonRPCAction": {"method": "open_settings", "parameters": []} } ] } // Response from open_settings method (typically no direct response to Flow Launcher): null ``` ``` -------------------------------- ### Basic Plugin with Function Query Source: https://github.com/garulf/pyflowlauncher/blob/main/README.md Create a basic plugin using a function as the query method. Ensure to import necessary classes and use `send_results` to return the query results. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: r = Result( Title="This is a title!", SubTitle="This is the subtitle!", IcoPath="icon.png" ) return send_results([r]) plugin.run() ``` -------------------------------- ### Programmatically Registering Methods Source: https://context7.com/garulf/pyflowlauncher/llms.txt Shows how to register methods programmatically using `plugin.add_method` or `plugin.add_methods`. This is useful for dynamic method creation or when using the `Method` class pattern. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() def query(query: str) -> ResultResponse: return send_results([Result(Title="Result from add_method", SubTitle=query)]) def context_menu(data: list) -> ResultResponse: return send_results([Result(Title="Context menu item")]) plugin.add_methods([query, context_menu]) plugin.run() ``` -------------------------------- ### Programmatic Method Registration Source: https://context7.com/garulf/pyflowlauncher/llms.txt Shows how to register methods programmatically using `plugin.add_method` for a single function and `plugin.add_methods` for a list of functions. This is useful for dynamic method registration. ```APIDOC ## Programmatic Method Registration ### Description This example demonstrates registering plugin methods programmatically using `plugin.add_method` for a single function and `plugin.add_methods` for multiple functions. This approach is useful when methods are generated dynamically or when not using decorators. ### Method `plugin.add_method(callable)`: Registers a single callable. `plugin.add_methods(iterable_of_callables)`: Registers multiple callables. ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() def query(query: str) -> ResultResponse: return send_results([Result(Title="Result from add_method", SubTitle=query)]) def context_menu(data: list) -> ResultResponse: return send_results([Result(Title="Context menu item")]) plugin.add_methods([query, context_menu]) plugin.run() ``` ### Response #### Success Response (ResultResponse) - **query method**: Returns a `ResultResponse` with results based on the query. - **context_menu method**: Returns a `ResultResponse` with context menu items. #### Response Example ```json // Example response from query method: { "results": [ { "Title": "Result from add_method", "SubTitle": "[user query]" } ] } // Example response from context_menu method: { "results": [ { "Title": "Context menu item" } ] } ``` ``` -------------------------------- ### Using Built-in Icons in Flow Launcher Plugins Source: https://context7.com/garulf/pyflowlauncher/llms.txt Demonstrates how to use predefined icon constants from the `pyflowlauncher.icons` module to set the icon for search results. These constants resolve to absolute paths when running within Flow Launcher. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse from pyflowlauncher import icons plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: results = [ Result(Title="Admin action", IcoPath=icons.ADMIN), Result(Title="Error state", IcoPath=icons.ERROR), Result(Title="Open folder", IcoPath=icons.FOLDER), Result(Title="Open browser", IcoPath=icons.BROWSER), Result(Title="Copy link", IcoPath=icons.COPYLINK), Result(Title="Settings", IcoPath=icons.SETTINGS), Result(Title="GitHub", IcoPath=icons.GITHUB), Result(Title="Warning", IcoPath=icons.WARNING), ] return send_results(results) plugin.run() ``` -------------------------------- ### Import and Use Launcher Icons Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/Launcher_Icons.md Import icons from the `icons` module to use them in your plugin. Ensure PyFlowLauncher can locate the Flow Launcher directory to avoid blank icons. ```python from PyFlowLauncher.icons import FlowSystemIcon # Example usage of an icon icon_path = FlowSystemIcon.Application ``` -------------------------------- ### Registering Method and Inline JsonRPCAction Source: https://context7.com/garulf/pyflowlauncher/llms.txt Demonstrates using `plugin.action` to register a method and immediately generate a `JsonRPCAction` dictionary. This simplifies embedding actions within `Result` objects. ```APIDOC ## Registering Method and Inline JsonRPCAction ### Description This example utilizes `plugin.action(method, parameters)` to register a callable (`copy_text`) and directly obtain a `JsonRPCAction` dictionary. This dictionary can then be embedded within a `Result` object, streamlining the process of defining actions that trigger specific methods. ### Method `plugin.action(method, parameters)`: Registers a callable and returns a `JsonRPCAction` dict. `@plugin.on_method`: Decorator used for the `query` method. ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() def copy_text(text: str) -> None: import subprocess subprocess.run(["clip"], input=text.encode()) @plugin.on_method def query(query: str) -> ResultResponse: r = Result( Title="Copy to clipboard", SubTitle="Click to copy the query text", JsonRPCAction=plugin.action(copy_text, [query]), ) return send_results([r]) plugin.run() ``` ### Response #### Success Response (ResultResponse) - **query method**: Returns a `ResultResponse` containing a `Result` object with an embedded `JsonRPCAction`. #### Response Example ```json { "results": [ { "Title": "Copy to clipboard", "SubTitle": "Click to copy the query text", "JsonRPCAction": {"method": "copy_text", "parameters": ["[user query]"]} } ] } ``` ``` -------------------------------- ### pyflowlauncher.api Source: https://context7.com/garulf/pyflowlauncher/llms.txt The `pyflowlauncher.api` module offers functions to send commands to Flow Launcher via JSON-RPC actions. These functions return `JsonRPCAction` dictionaries that can be assigned to a `Result`'s `JsonRPCAction` field or returned directly from an action method. Note that API calls are not permitted within `query` or `context_menu` methods. ```APIDOC ## `pyflowlauncher.api` — Send commands to Flow Launcher The `api` module provides functions that return `JsonRPCAction` dicts targeting the `Flow.Launcher.*` namespace. Assign the return value to a `Result`'s `JsonRPCAction` field or return it directly from an action method. **API calls cannot be used from `query` or `context_menu` methods.** ```python from pyflowlauncher import Plugin, Result, send_results import pyflowlauncher.api as api from pyflowlauncher.result import ResultResponse, JsonRPCAction plugin = Plugin() @plugin.on_method def open_url_action() -> JsonRPCAction: return api.open_url("https://github.com/Garulf/pyFlowLauncher") @plugin.on_method def query(query: str) -> ResultResponse: results = [ Result(Title="Change query", JsonRPCAction=api.change_query("new query ")), Result(Title="Run shell command", JsonRPCAction=api.shell_run("notepad.exe")), Result(Title="Copy to clipboard", JsonRPCAction=api.copy_to_clipboard("Hello!")), Result(Title="Open directory", JsonRPCAction=api.open_directory("C:\\Users")), Result(Title="Show message", JsonRPCAction=api.show_msg("Hi", "Hello from plugin")), Result(Title="Open URL", JsonRPCAction=plugin.action(open_url_action)), Result(Title="Hide launcher", JsonRPCAction=api.hide_app()), Result(Title="Reload plugins", JsonRPCAction=api.reload_plugins()), ] return send_results(results) plugin.run() ``` **Full list of `api` functions:** | Function | Description | |---|---| | `change_query(query, requery)` | Change the launcher's search box text | | `shell_run(command, filename)` | Execute a shell command | | `close_app()` | Close Flow Launcher | | `hide_app()` | Hide the launcher window | | `show_app()` | Show the launcher window | | `show_msg(title, sub_title, ico_path)` | Display a notification message | | `open_setting_dialog()` | Open the Flow Launcher settings dialog | | `start_loading_bar()` | Show the loading progress indicator | | `stop_loading_bar()` | Hide the loading progress indicator | | `reload_plugins()` | Reload all installed plugins | | `copy_to_clipboard(text, direct_copy, show_default_notification)` | Copy text to clipboard | | `open_directory(directory_path, filename_or_filepath)` | Open a folder in Explorer | | `open_url(url, in_private)` | Open a URL in the default browser | | `open_uri(uri)` | Launch an application via a URI scheme | ``` -------------------------------- ### plugin.settings Source: https://context7.com/garulf/pyflowlauncher/llms.txt Accesses the settings dictionary provided by Flow Launcher, allowing plugins to read configuration values defined in their manifest. ```APIDOC ## `plugin.settings` Reads plugin settings from Flow Launcher. ### Description The `settings` property provides access to the configuration dictionary that Flow Launcher passes in the JSON-RPC payload. Settings keys and their default values are typically declared in the plugin's `plugin.json` manifest file. ### Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: settings = plugin.settings max_results = int(settings.get("max_results", 5)) results = [ Result(Title=f"Item {i}", SubTitle=f"max_results setting = {max_results}") for i in range(max_results) ] return send_results(results) plugin.run() ``` ``` -------------------------------- ### Registering Method and Embedding JsonRPCAction Source: https://context7.com/garulf/pyflowlauncher/llms.txt Uses `plugin.action` to register a method and immediately generate a `JsonRPCAction` dictionary for embedding in a `Result`. This avoids manual string management for method names. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() def copy_text(text: str) -> None: import subprocess subprocess.run(["clip"], input=text.encode()) @plugin.on_method def query(query: str) -> ResultResponse: r = Result( Title="Copy to clipboard", SubTitle="Click to copy the query text", JsonRPCAction=plugin.action(copy_text, [query]), ) return send_results([r]) plugin.run() ``` -------------------------------- ### Method Class Source: https://context7.com/garulf/pyflowlauncher/llms.txt Provides a structured, class-based approach for implementing plugin methods, allowing for instance state and inheritance. ```APIDOC ## `Method` Class-based plugin method implementation. ### Description `Method` is an abstract base class designed for creating structured, class-based plugin methods. To use it, subclass `Method`, implement the `__call__` method, accumulate results using `self.add_result(result)`, and finally return the results with `self.return_results()`. This pattern is particularly useful for complex methods that can benefit from instance state or object-oriented design principles. ### Example ```python from pyflowlauncher import Plugin, Result, Method from pyflowlauncher.result import ResultResponse plugin = Plugin() class Query(Method): def __call__(self, query: str) -> ResultResponse: items = ["apple", "banana", "cherry"] for item in items: if query.lower() in item: self.add_result(Result( Title=item.capitalize(), SubTitle=f"Matched query: {query}", IcoPath="icon.png", )) return self.return_results() plugin.add_method(Query()) plugin.run() ``` ``` -------------------------------- ### Registering Plugin Methods with add_method Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/Plugin methods.md Alternatively, you can register a custom method using the `add_method` function from the `Plugin` class. This provides another way to make your plugin methods accessible. ```python from flowlauncher import Plugin class Main(Plugin): def __init__(self): super().__init__() self.add_method(self.method_two) def method_two(self, query): return query if __name__ == "__main__": Main() ``` -------------------------------- ### Registering and Adding Methods to Results with action Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/Plugin methods.md The `action` method allows you to register a method and add it to a Result in a single operation. This is useful for directly associating an action with a search result. ```python from flowlauncher import Plugin class Main(Plugin): def __init__(self): super().__init__() @Plugin.action def method_three(self, query): return query if __name__ == "__main__": Main() ``` -------------------------------- ### Send Commands to Flow Launcher via API Source: https://context7.com/garulf/pyflowlauncher/llms.txt The `pyflowlauncher.api` module provides functions to generate `JsonRPCAction` dictionaries for interacting with Flow Launcher. These actions can be assigned to a `Result`'s `JsonRPCAction` field or returned directly from an action method. API calls are not permitted within `query` or `context_menu` methods. ```python from pyflowlauncher import Plugin, Result, send_results import pyflowlauncher.api as api from pyflowlauncher.result import ResultResponse, JsonRPCAction plugin = Plugin() @plugin.on_method def open_url_action() -> JsonRPCAction: return api.open_url("https://github.com/Garulf/pyFlowLauncher") @plugin.on_method def query(query: str) -> ResultResponse: results = [ Result(Title="Change query", JsonRPCAction=api.change_query("new query ")), Result(Title="Run shell command", JsonRPCAction=api.shell_run("notepad.exe")), Result(Title="Copy to clipboard", JsonRPCAction=api.copy_to_clipboard("Hello!")), Result(Title="Open directory", JsonRPCAction=api.open_directory("C:\\Users")), Result(Title="Show message", JsonRPCAction=api.show_msg("Hi", "Hello from plugin")), Result(Title="Open URL", JsonRPCAction=plugin.action(open_url_action)), Result(Title="Hide launcher", JsonRPCAction=api.hide_app()), Result(Title="Reload plugins", JsonRPCAction=api.reload_plugins()), ] return send_results(results) plugin.run() ``` -------------------------------- ### Attach Actions to Results with result.add_action Source: https://context7.com/garulf/pyflowlauncher/llms.txt Bind a JSONRPC action to a result using 'result.add_action(method, parameters, dont_hide_after_action)'. Specify the method by its '__name__'. Set 'dont_hide_after_action=True' to keep the launcher visible after the action executes. ```python from pyflowlauncher import Plugin, Result, send_results, api from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def example_method() -> None: # called when user selects the result pass @plugin.on_method def query(query: str) -> ResultResponse: r = Result(Title="Trigger example_method", SubTitle="Press Enter") r.add_action(example_method, dont_hide_after_action=True) return send_results([r]) plugin.run() ``` -------------------------------- ### Advanced Plugin with Method Class Source: https://github.com/garulf/pyflowlauncher/blob/main/README.md Develop an advanced plugin by defining a class that inherits from `Method` to handle queries. Use `self.add_result` and `self.return_results` for managing and returning results. ```python from pyflowlauncher import Plugin, Result, Method from pyflowlauncher.result import ResultResponse plugin = Plugin() class Query(Method): def __call__(self, query: str) -> ResultResponse: r = Result( Title="This is a title!", SubTitle="This is the subtitle!" ) self.add_result(r) return self.return_results() plugin.add_method(Query()) plugin.run() ``` -------------------------------- ### Read Plugin Settings with plugin.settings Source: https://context7.com/garulf/pyflowlauncher/llms.txt Access plugin settings defined in 'plugin.json' via the 'settings' property. This allows your plugin to dynamically adjust its behavior based on user-configured options. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def query(query: str) -> ResultResponse: settings = plugin.settings max_results = int(settings.get("max_results", 5)) results = [ Result(Title=f"Item {i}", SubTitle=f"max_results setting = {max_results}") for i in range(max_results) ] return send_results(results) plugin.run() ``` -------------------------------- ### Filter and Score Results with Fuzzy Matching Source: https://context7.com/garulf/pyflowlauncher/llms.txt Use `score_results` to filter and rank a list of results based on a query using Flow Launcher's fuzzy matching algorithm. It sets `Result.Score` and `Result.TitleHighlightData` on matches and yields only those meeting the precision threshold. This replicates native fuzzy-match behavior. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse from pyflowlauncher.utils import score_results plugin = Plugin() ITEMS = ["Python", "PyCharm", "Pylint", "pytest", "pip", "Poetry"] @plugin.on_method def query(query: str) -> ResultResponse: results = [Result(Title=name, SubTitle=f"Tool: {name}") for name in ITEMS] # score_results filters and ranks by fuzzy match; yields matching Results only matched = list(score_results(query, results, score_cutoff=20, match_on_empty_query=True)) return send_results(matched) plugin.run() ``` -------------------------------- ### score_results Source: https://context7.com/garulf/pyflowlauncher/llms.txt `score_results` filters and ranks results using Flow Launcher's fuzzy matching algorithm. It sets `Result.Score` and `Result.TitleHighlightData` on matches and yields only results that meet the specified precision threshold, replicating Flow Launcher's native fuzzy-match behavior. ```APIDOC ## `score_results` — Filter and score results using Flow Launcher's algorithm `score_results(query, results, score_cutoff, match_on_empty_query)` is a generator that runs pyFlowLauncher's built-in string-matcher on each result's `Title`, sets `Result.Score` and `Result.TitleHighlightData` on matches, and yields only results that meet the precision threshold. This replicates Flow Launcher's native fuzzy-match behavior. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse from pyflowlauncher.utils import score_results plugin = Plugin() ITEMS = ["Python", "PyCharm", "Pylint", "pytest", "pip", "Poetry"] @plugin.on_method def query(query: str) -> ResultResponse: results = [Result(Title=name, SubTitle=f"Tool: {name}") for name in ITEMS] # score_results filters and ranks by fuzzy match; yields matching Results only matched = list(score_results(query, results, score_cutoff=20, match_on_empty_query=True)) return send_results(matched) plugin.run() ``` ``` -------------------------------- ### Class-based Plugin Method with Method Source: https://context7.com/garulf/pyflowlauncher/llms.txt Implement complex plugin logic using class-based methods by subclassing 'Method'. Accumulate results using 'self.add_result()' and return them with 'self.return_results()'. This pattern is useful for methods requiring instance state or inheritance. ```python from pyflowlauncher import Plugin, Result, Method from pyflowlauncher.result import ResultResponse plugin = Plugin() class Query(Method): def __call__(self, query: str) -> ResultResponse: items = ["apple", "banana", "cherry"] for item in items: if query.lower() in item: self.add_result(Result( Title=item.capitalize(), SubTitle=f"Matched query: {query}", IcoPath="icon.png", )) return self.return_results() plugin.add_method(Query()) plugin.run() ``` -------------------------------- ### Registering Plugin Methods with on_method Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/Plugin methods.md Use the `on_method` decorator to register a custom method for your plugin. This method can then be triggered by Flow Launcher. ```python from flowlauncher import Plugin class Main(Plugin): def __init__(self): super().__init__() @Plugin.on_method def method_one(self, query): return query if __name__ == "__main__": Main() ``` -------------------------------- ### Format Results with send_results Source: https://context7.com/garulf/pyflowlauncher/llms.txt Convert an iterable of 'Result' objects into the 'ResultResponse' dictionary required by Flow Launcher using 'send_results(results, settings)'. Optionally, push settings changes back to the launcher within the same response. ```python from pyflowlauncher import Result, send_results results = [ Result(Title="First result", SubTitle="Score 80", Score=80), Result(Title="Second result", SubTitle="Score 50", Score=50), ] # Returns: {'result': [...], 'SettingsChange': None} response = send_results(results) # Push a settings change alongside results response_with_settings = send_results(results, settings={"last_query": "hello"}) ``` -------------------------------- ### Result Class Source: https://context7.com/garulf/pyflowlauncher/llms.txt Represents a single result item displayed in Flow Launcher, mapping directly to the launcher's result schema. ```APIDOC ## `Result` Represents a single result item. ### Description `Result` is a dataclass that directly corresponds to Flow Launcher's result schema. The `Title` field is the only mandatory field. Several optional fields are available to control aspects such as the subtitle, icon, associated action, score, text for clipboard copying, autocomplete suggestions, icon rounding, glyph icons, and rich preview content. ### Parameters - **Title** (str): Required. The main title of the result item. - **SubTitle** (str, optional): The subtitle displayed below the title. - **IcoPath** (str, optional): Path to an icon for the result item. - **Score** (int, optional): A score to influence the item's ranking. - **CopyText** (str, optional): Text to be copied to the clipboard when the result is actioned. - **AutoCompleteText** (str, optional): Text to be used for autocomplete suggestions. - **RoundedIcon** (bool, optional): Whether to display the icon with rounded corners. - **Glyph** (Glyph, optional): A glyph icon to display. - **Preview** (PreviewInfo, optional): Information for a rich preview. ### Example ```python from pyflowlauncher import Result from pyflowlauncher.result import Glyph, PreviewInfo r = Result( Title="Open GitHub", SubTitle="Navigate to github.com", IcoPath="images/github.png", Score=90, CopyText="https://github.com", AutoCompleteText="github ", RoundedIcon=True, Glyph=Glyph(Glyph="\uE8A7", FontFamily="Segoe MDL2 Assets"), Preview=PreviewInfo( PreviewImagePath="images/preview.png", Description="GitHub – code hosting platform", IsMedia=False, PreviewDeligate=None, ), ) ``` ``` -------------------------------- ### Send API Request from a Method Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/API Requests.md Use this to send an API request within a custom method in your plugin. ```python from flowlauncher import FlowLauncher class Main(FlowLauncher): def query(self, query): return [ { "title": "Result 1", "description": "This is the first result.", """ """ } ] def custom_method(self): # Example of sending an API request from a custom method self.show_msg_dialog("Hello from custom method!") if __name__ == "__main__": Main() ``` -------------------------------- ### send_results Source: https://context7.com/garulf/pyflowlauncher/llms.txt Formats a collection of Result objects into the JSON-RPC response structure expected by Flow Launcher. ```APIDOC ## `send_results(results, settings)` Format results for the JSON-RPC response. ### Description This function converts an iterable of `Result` objects into the `ResultResponse` dictionary format required by Flow Launcher. It can also optionally include a `settings` dictionary to push configuration changes back to the launcher within the same response. ### Parameters - **results** (iterable): An iterable (e.g., a list) of `Result` objects to be displayed. - **settings** (dict, optional): A dictionary containing settings changes to be sent back to Flow Launcher. ### Returns - **ResultResponse** (dict): A dictionary formatted for the JSON-RPC response, containing the results and any settings changes. ### Example ```python from pyflowlauncher import Result, send_results results = [ Result(Title="First result", SubTitle="Score 80", Score=80), Result(Title="Second result", SubTitle="Score 50", Score=50), ] # Returns: {'result': [...], 'SettingsChange': None} response = send_results(results) # Push a settings change alongside results response_with_settings = send_results(results, settings={"last_query": "hello"}) ``` ``` -------------------------------- ### Send API Request from a Result Source: https://github.com/garulf/pyflowlauncher/blob/main/docs/guide/API Requests.md Use this to change the query in Flow Launcher when a user selects a result from your plugin. ```python from flowlauncher import FlowLauncher class Main(FlowLauncher): def query(self, query): # Example of sending an API request to change the query self.change_query("new query") return [ { "title": "Result 1", "description": "This is the first result.", """ """ } ] if __name__ == "__main__": Main() ``` -------------------------------- ### Representing a Result Item with Result Source: https://context7.com/garulf/pyflowlauncher/llms.txt Use the 'Result' dataclass to map directly to Flow Launcher's result schema. 'Title' is mandatory, while other fields like 'SubTitle', 'IcoPath', 'Score', and 'Preview' offer extensive customization. ```python from pyflowlauncher import Result from pyflowlauncher.result import Glyph, PreviewInfo r = Result( Title="Open GitHub", SubTitle="Navigate to github.com", IcoPath="images/github.png", Score=90, CopyText="https://github.com", AutoCompleteText="github ", RoundedIcon=True, Glyph=Glyph(Glyph="\uE8A7", FontFamily="Segoe MDL2 Assets"), Preview=PreviewInfo( PreviewImagePath="images/preview.png", Description="GitHub – code hosting platform", IsMedia=False, PreviewDeligate=None, ), ) ``` -------------------------------- ### string_matcher Source: https://context7.com/garulf/pyflowlauncher/llms.txt `string_matcher` provides a low-level fuzzy string matching capability. It returns a `MatchData` object containing a boolean indicating if a match was found, an integer score representing relevance, and a list of character indices for highlighting. ```APIDOC ## `string_matcher` — Low-level fuzzy string matching `string_matcher(query, text, ignore_case, query_search_precision)` returns a `MatchData` object with `matched` (bool), `score` (int), and `index_list` (character positions of matched characters for highlight rendering). Results are LRU-cached for performance. ```python from pyflowlauncher.string_matcher import string_matcher, SearchPrecision result = string_matcher("pfl", "pyFlowLauncher", ignore_case=True, query_search_precision=SearchPrecision.LOW) print(result.matched) # True print(result.score) # integer relevance score print(result.index_list) # e.g. [0, 2, 4] — highlight positions ``` ``` -------------------------------- ### Handle Exceptions with plugin.on_except Source: https://context7.com/garulf/pyflowlauncher/llms.txt Register a handler for specific exception types raised within plugin methods. The handler receives the exception instance and can return a ResultResponse to display an error to the user. ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_except(ValueError) def handle_value_error(e: ValueError) -> ResultResponse: return send_results([Result(Title="Invalid input", SubTitle=str(e))]) @plugin.on_method def query(query: str) -> ResultResponse: if not query.isdigit(): raise ValueError(f"'{query}' is not a number") return send_results([Result(Title=f"Number: {query}")]) plugin.run() ``` -------------------------------- ### Result.add_action Source: https://context7.com/garulf/pyflowlauncher/llms.txt Attaches a JsonRPC action to a result item, allowing it to trigger a registered method when selected. ```APIDOC ## `result.add_action(method, parameters, dont_hide_after_action)` Attach a JsonRPC action to a result. ### Description This method sets the `JsonRPCAction` field for a `Result` object. It binds the action to a registered method identified by its `__name__`. You can optionally prevent the launcher from hiding after the action fires by setting `dont_hide_after_action` to `True`. ### Parameters - **method** (callable): The method to be called when the action is triggered. - **parameters** (dict, optional): Parameters to pass to the method. - **dont_hide_after_action** (bool, optional): If `True`, the Flow Launcher window will remain open after the action is executed. ### Example ```python from pyflowlauncher import Plugin, Result, send_results, api from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_method def example_method() -> None: # This method is called when the user selects the result pass @plugin.on_method def query(query: str) -> ResultResponse: r = Result(Title="Trigger example_method", SubTitle="Press Enter") r.add_action(example_method, dont_hide_after_action=True) return send_results([r]) plugin.run() ``` ``` -------------------------------- ### Low-Level Fuzzy String Matching Source: https://context7.com/garulf/pyflowlauncher/llms.txt The `string_matcher` function provides low-level fuzzy string matching capabilities. It returns a `MatchData` object indicating if a match occurred, its score, and the character indices for highlighting. Results are LRU-cached for performance. ```python from pyflowlauncher.string_matcher import string_matcher, SearchPrecision result = string_matcher("pfl", "pyFlowLauncher", ignore_case=True, query_search_precision=SearchPrecision.LOW) print(result.matched) # True print(result.score) # integer relevance score print(result.index_list) # e.g. [0, 2, 4] — highlight positions ``` -------------------------------- ### plugin.on_except / plugin.add_exception_handler Source: https://context7.com/garulf/pyflowlauncher/llms.txt Registers a handler that is called when a specific exception type is raised within a registered method. The handler receives the exception instance and can return a ResultResponse to display an error to the user. ```APIDOC ## `plugin.on_except(ExceptionType)` Registers a handler for specific exceptions. ### Description This decorator registers a function to handle exceptions of a specified type that occur within registered methods. The handler receives the exception object and can return a `ResultResponse` to inform the user of the error. ### Parameters - **ExceptionType** (type): The type of exception to catch (e.g., `ValueError`). ### Example ```python from pyflowlauncher import Plugin, Result, send_results from pyflowlauncher.result import ResultResponse plugin = Plugin() @plugin.on_except(ValueError) def handle_value_error(e: ValueError) -> ResultResponse: return send_results([Result(Title="Invalid input", SubTitle=str(e))]) @plugin.on_method def query(query: str) -> ResultResponse: if not query.isdigit(): raise ValueError(f"'{query}' is not a number") return send_results([Result(Title=f"Number: {query}")]) plugin.run() ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.