13.2.7. Plugin class

class keypirinha.Plugin

Base class for third-party plugins.

Note

Methods prefixed with on_ are the only ones called by the application.

_debug = False

Flag to enable/disable output of dbg().

Warning

Redistributed plugins must always have this flag disabled.

__init__()

Plugin’s default constructor. When implementing a new plugin, it is good practice to call it:

def __init__(self):
    super().__init__()
on_start()

This is the first method called by the application after a plugin has been instanciated.

What should be done in this method:

  • Read configuration file(s)

  • Read state data from package’s cache, if any, that may be needed elsewhere in this plugin

  • Do any heavy, one-time, initialization (i.e. instead of doing it from __init__ or even on_catalog() for example)

See also

See the Loading section for more information about the plugin loading process. And Messages Workflow.

on_catalog()

Plugin is requested to setup its catalog by calling either set_catalog() or merge_catalog().

Note

  • This method may be called at any time, and not necessarily at start-time.

  • Since this method may be called several times during instance’s lifetime, one-time initialization, if any, must always be done in on_start().

See also

See the Loading section for more information about the plugin loading process. And Messages Workflow.

on_suggest(user_input, items_chain=[])

Called when the user is typing their search terms or item’s arguments.

When no item has been selected yet by the user, the items_chain list is empty and user_input is a string containing the initial search terms. In that case, this SUGGEST message has been broadcasted to every loaded plugin.

Otherwise, this SUGGEST message has been sent to this plugin only and items_chain is a non-empty list that contains one or more CatalogItem object(s) that belong to this plugin and user_input is a string typed by the user that is meant to be the arguments of the lastly selected item (i.e. items_chain[-1]).

More precisely, items_chain contains the full history of the items that have been selected by the user during this search session, plugins usually only need to deal with the last and/or the first item(s) in the items_chain list (i.e. items_chain[-1] and/or items_chain[0]; which may be equal).

If the plugin implements this method, it is expected to set its suggestions catalog by using set_suggestions(). The list of suggestions may be empty.

See also

See the Messages Workflow section.

on_execute(catalog_item, catalog_action=None)

Called once the user has selected an item and wants to launch it, optionally using the passed action.

catalog_item is the selected CatalogItem object to execute, belonging to this plugin.

catalog_action is either None or a CatalogAction object; it might not have been created by this plugin though, in which case keypirinha_util.execute_default_action() may be of interest.

See also

See the Messages Workflow section.

on_activated()

Called when the LaunchBox has been invoked by the user, either by typing the dedicated global hotkey, or by using the contextual menu of the application icon located in the system tray.

Note

The ACTIVATED message automatically discards any pending DEACTIVATED message in the queue. As a result, an ACTIVATED message is not always followed by a DEACTIVATED message. For example, if your plugin takes more time to process the ACTIVATED message than the end-user to perform her search and deactivate the window and then re-activate it, the plugin will receive a new ACTIVATED message without being notified about the DEACTIVATED event that occurred in between.

See also

on_deactivated()

on_deactivated()

Called when the LaunchBox has been hidden. Either because an item has been executed for example, or because the user canceled her search.

Note

A DEACTIVATED message is not always preceded by an ACTIVATED message. See the note in on_activated() documentation for more information.

See also

on_activated()

on_events(flags)

Called when some event(s) occurred.

flags can be one or several flags defined in Events.

Note

While Keypirinha tries to group flags at a given time in order to reduce the number of calls made to this method, calls are still made in a real-time fashion to ensure plugins get notified as soon as possible. In other words, there is no waiting mechanism involved to accumulate these flags and plugin developer should not expect flags to be always grouped.

id()

Get the id number (int) of this plugin.

This id uniquely identifies this plugin during the current session only.

full_name()

Get the fully qualified name of this plugin.

name()

Deprecated since version 2.9: Use full_name() instead

package_full_name()

Get the fully qualified name of this plugin’s parent package.

package_name()

Deprecated since version 2.9: Use package_full_name() instead

set_catalog(catalog_items)

Replace current plugin’s catalog by catalog_items, which must be a list of CatalogItem objects, created by this plugin. Note that the list may be empty if you wish to clear plugin’s catalog.

Internally calls self.merge_catalog(catalog_items, True)

See also

merge_catalog()

merge_catalog(catalog_items, erase_untouched_items)

Merge current plugin’s catalog with catalog_items, which must be a list of CatalogItem objects that have been created by this plugin.

erase_untouched_items is a boolean flag to indicate if items related to this plugin, that were already present in the catalog and that were not present in the given catalog_items list, should be erased from the catalog after other items have been merged.

See also

set_catalog()

clear_actions(category=None)

Clear the list of actions associated to a given ItemCategory, or clear all actions associated to this plugin if category is None.

create_action(name, label, short_desc='', data_bag='')

Create a CatalogAction object.

Parameters
  • name (str) – The name of the action, normally lowercased, no space. Words can be separated by an underscore (_).

  • label (str) – The display name of the action. This is the value the user will see.

  • short_desc (str) – An optional one-line description of the item. It will be displayed right under the label on the GUI.

  • data_bag (str) – The data bag is a string container, exclusively for the use of this plugin. Entirely optional and never read by the application.

Returns

The newly created action, associated to this plugin.

Return type

CatalogAction

Raises

ValueError – Action could not be created due to one or more invalid passed argument.

Warning

CatalogAction objects must always be created using this method.

create_error_item(label, short_desc, target='error', icon_handle=None, data_bag=None)

Create and return a CatalogItem object of the ItemCategory.ERROR category.

Note

  • An ERROR item will only be accepted by the application as a suggestion. It cannot be part of plugin’s Catalog.

  • Only one ERROR item is allowed per batch of suggestions. If plugin sends a list of suggestion containing several ERROR items, only the first one will be kept.

  • short_desc will be copied to label if label is empty to limit unexpected behavior (items with an empty label are filtered out by the application so the ERROR item would not be displayed).

See also

create_item()

create_item(category, label, short_desc, target, args_hint, hit_hint, loop_on_suggest=False, icon_handle=None, data_bag=None)

Create and return a CatalogItem object.

CatalogItem is the angular stone of Keypirinha. It is the only data unit a plugin can use to be referenced in the central Catalog.

Parameters
  • category (ItemCategory) – The category of the target of this item. Indeed, the target might be a ItemCategory.KEYWORD whereas its argument might represent a mathematical ItemCategory.EXPRESSION for example. In that case, this argument should be KEYWORD to reflect the content of the target property. Prefer create_error_item() to easily create an item of the ItemCategory.ERROR category.

  • label (str) – The display name of the item. This is the value the user will see. It must not be empty.

  • short_desc (str) – An optional one-line description of the item. It will be displayed right under the label on the GUI.

  • target (str) – This is the main property of CatalogItem, the plugin can put whatever it needs to differentiate this item among others. This value cannot be null unless category is ItemCategory.ERROR.

  • args_hint (ItemArgsHint) – Indicates how the GUI should behave with this item when it comes to specifying its arguments. For example, if target is the path to an executabe file (in which case category should be ItemCategory.FILE), user might expect to be able to add extra arguments before executing this item: ItemArgsHint.ACCEPTED is the logical choice here.

  • hit_hint (ItemHitHint) – Indicates how the application should deal with this item once it has been executed by the user, regarding the History.

  • loop_on_suggest (bool) – Indicates the GUI should call on_suggest() as long as this flag is raised. This argument should be left False unless you know what you are doing.

  • icon_handle (IconHandle) – An optional icon handle to associate with this item. Keypirinha always tries to find the icon to an item that fits the best. For example, if item is a ItemCategory.FILE, the system icon normally associated with it will be displayed to the user so icon_handle should be left None. Otherwise, the application will try to fall back to plugin’s default icon, if any. Eventually, if no icon could be associated to this item, the default application icon will displayed.

  • data_bag (str) – An arbitrary string for the exclusive use of the plugin. The data bag is a modifiable and persistent property that will never be interpreted by the application and that can be used to transport some data meant to be associated with this specific item.

Returns

The newly created item, associated to this plugin.

Return type

CatalogItem

Warning

CatalogItem objects must always be created using this method.

Note

  • str(item_object) is equivalent to item_object.label().

  • May you wish to compare two item objects, the __eq__, __ne__, __lt__, __le__, __gt__, __ge__ and __hash__ operators are implemented. They are fast and cheap since they use the internal unique id of the item, which is computed at construction time or when its arguments are updated.

dbg(*objects, sep=' ')

Log a debug message.

objects and sep arguments are handled the same way than print().

Note

By default, this method will produce no output unless the keypirinha.Plugin._debug flag is True.

Warning

Use this method only temporarily, in order to debug your plugin. May you wish to redistribute it. The keypirinha.Plugin._debug flag must be left untouched and no call to this method should be present in plugin’s source code.

See also

info(), warn(), err()

err(*objects, sep=' ')

Log an error message.

objects and sep arguments are handled the same way than print().

See also

info(), warn(), dbg()

find_resources(name_pattern)

Return a list of resources in this package that match a given pattern.

Parameters

name_pattern (str) – The pattern to match the name part of the resource(s). Accepted wildcards are * (i.e.: matches zero or several characters), and ? (matches a single character).

Returns

The list of the relative paths to the matched resources. May be empty.

Return type

list

friendly_name()

Return plugin’s friendly (short) name. I.e. its class name.

get_package_cache_path(create=False)

Return the absolute path to package’s cache directory.

It is the responsibility of the caller to create it if it doesn’t exist (either manually or by setting the ‘create’ argument to True). However, its parent directory is guaranteed to exist. The create flag allows to ask this method to create the directory for you.

The cache directory (or temp directory) of a Package is common to every plugin of a same package and provides a physical storage area that can be used by plugins to store temporary data that may be manually deleted by the end-user between two runtime sessions.

Raises
  • RuntimeError – Failed to get package’s cache directory

  • OSError – Failed to create the directory (in case create argument is True).

has_resource(relative_path)

Check if plugin’s parent package embeds a specific resource.

Parameters

relative_path (str) – The relative path to the desired resource file located in the package. Examples: resource.png, subdir/resource.png.

info(*objects, sep=' ')

Log an informational message.

objects and sep arguments are handled the same way than print().

See also

warn(), err(), dbg()

load_binary_resource(relative_path)

Return a bytes object holding the unmodified content of the specified resource.

Raises

Note

For performance reason, the MemoryError exception is raised if the specified file size is bigger than 16MB (16777216 bytes).

load_icon(sources, force_reload=False)

Load or get an IconHandle. See load_icon() for more details.

load_settings()

Return the keypirinha.Settings object associated with the parent Package.

Note

  • The configuration file(s) will be loaded only the first time this method is called. Any subsequent call will return a new keypirinha.Settings object pointing to the same data block.

  • When the application detects that one or several configuration files have been modified in a Package, it is automatically re-read the files (only if they were previously loaded), then will notify every related plugin via a call to Plugin.on_events().

  • It is not necessary to re-call this method upon a Plugin.on_events() if you already have a keypirinha.Settings object associated to this plugin. The application update user’s configuration data upon file change.

See also

settings()

load_text_resource(relative_path)

Return a str object holding the content of the specified resource.

May raise the same exceptions than load_binary_resource(), plus the TypeError exception if resource’s content could not be decoded (Unicode error).

log(*objects, sep=' ', level=1, lineno=- 1)

Log a message.

Warning

This method is not meant to be used directly, prefer to call the info(), warn(), err() or dbg() methods instead.

set_actions(category, actions_list)

Associate a given list of CatalogAction to an ItemCategory.

Parameters
  • category (ItemCategory) – The category of item to associate the actions with. If needed, you can assign the same list of actions with several categories by calling this method several times.

  • actions_list (list) – A list of CatalogAction objects that have been created with create_action().

Returns

The actual number of actions taken into account. Actions are filtered out when they don’t belong to this plugin for example, or if CatalogAction.valid() returns False.

Return type

int

set_default_icon(icon_handle)

Set the default icon of the catalog items created by this plugin.

Parameters

icon_handle (IconHandle) – the default icon handle to be used

set_suggestions(suggestions, match_method=<Match.FUZZY: 1000>, sort_method=<Sort.SCORE_DESC: 1000>)

Offer some suggestions to the user according to the current search terms. This method is meant to be called from on_suggest().

suggestions must be a list of CatalogItem objects.

match_method must be a Match value.

sort_method must be a Sort value.

Note

The match_method and sort_method arguments are taken into account by the application only if the user has selected an item already (i.e. not at first step of the search). That is, when the items_chain argument of on_suggest() is not empty.

should_terminate(wait_seconds=None)

Return a boolean to indicate whether the current task should return as soon as possible, without completing its job.

Plugins should call this method frequently. Especially at I/O operations boundaries (storage accesses and network communications).

See keypirinha.should_terminate() for more info about the wait_seconds parameter.

Note

warn(*objects, sep=' ')

Log a warning message.

objects and sep arguments are handled the same way than print().

See also

info(), err(), dbg()