11.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.
It is good for:
- Reading configuration file(s)
- Reading state data from package’s cache, if any, that may be needed elsewhere in this plugin
- Doing any heavy, one-time, initialization (i.e. instead of doing it
from
__init__or evenon_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()ormerge_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_init().
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 her 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
SUGGESTmessage has been broadcasted to every loaded plugin.Otherwise, this
SUGGESTmessage has been sent to this plugin only and items_chain is a non-empty list that contains one or moreCatalogItemobject(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]).While in that case, 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 first and/or the last item(s) in the items_chain list (i.e.
items_chain[0]and/oritems_chain[-1]; which may be equal).If the plugin implements this method, it is expected to setup 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
CatalogItemobject to execute, belonging to this plugin.catalog_action is either
Noneor aCatalogActionobject; it might not have been created by this plugin though, in which casekeypirinha_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
ACTIVATEDmessage automatically discards any pendingDEACTIVATEDmessage in the queue. As a result, anACTIVATEDmessage is not always followed by aDEACTIVATEDmessage. For example, if your plugin takes more time to process theACTIVATEDmessage than the end-user to perform her search and deactivate the window and then re-activate it, the plugin will receive a newACTIVATEDmessage without being notified about theDEACTIVATEDevent that occurred in between.See also
-
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
DEACTIVATEDmessage is not always preceded by anACTIVATEDmessage. See the note inon_activated()documentation for more information.See also
-
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 plugin gets 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.
See also
-
name()¶ Deprecated since version 2.9: Use
full_name()instead
-
package_full_name()¶ Get the fully qualified name of this plugin’s parent package.
See also
-
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
CatalogItemobjects, 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(catalog_items, erase_untouched_items)¶ Merge current plugin’s catalog with catalog_items, which must be a list of
CatalogItemobjects 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
-
clear_actions(category=None)¶ Clear the list of actions associated to a given
ItemCategory, or clear all actions associated to this plugin if category isNone.See also
-
create_action(name, label, short_desc='', data_bag='')¶ Create a
CatalogActionobject.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: Raises: ValueError– Action could not be created due to one or more invalid passed argument.Warning
CatalogActionobjects must always be created using this method.See also
- name (str) – The name of the action, normally lowercased, no space.
Words can be separated by an underscore (
-
create_error_item(label, short_desc, target='error', icon_handle=None, data_bag=None)¶ Create and return a
CatalogItemobject of theItemCategory.ERRORcategory.Note
- An
ERRORitem will only be accepted by the application as a suggestion. It cannot be part of plugin’s Catalog. - Only one
ERRORitem is allowed per batch of suggestions. If plugin sends a list of suggestion containing severalERRORitems, only the first one will be kept. - short_desc will be copied to label if label is empty to
limit unpexpected behavior (items with an empty label are filtered
out by the application so the
ERRORitem would not be displayed).
See also
- An
-
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
CatalogItemobject.CatalogItemis 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.KEYWORDwhereas its argument might represent a mathematicalItemCategory.EXPRESSIONfor example. In that case, this argument should beKEYWORDto reflect the content of the target property. Prefercreate_error_item()to easily create an item of theItemCategory.ERRORcategory. - 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 isItemCategory.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.ACCEPTEDis 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 leftFalseunless 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 leftNone. 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: Warning
CatalogItemobjects must always be created using this method.Note
str(item_object)is equivalent toitem_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.
See also
- category (ItemCategory) – The category of the target of this
item. Indeed, the target might be a
-
dbg(*objects, *, sep=' ')¶ Log an 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._debugflag isTrue.Warning
Use this method only temporarily, in order to debug your plugin. May you wish to redistribute it. The
keypirinha.Plugin._debugflag must be left untouched and no call to this method should be present in plugin’s source code.
-
err(*objects, *, sep=' ')¶ Log an error message.
objects and sep arguments are handled the same way than
print().
-
find_resources(name_pattern)¶ Returns 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()¶ Returns plugin’s friendly (short) name.
See also
-
get_package_cache_path(create=False)¶ Returns 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, it’s 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 without creating a mess in plugin’s logic.
Raises: RuntimeError– Failed to get package’s cache directoryOSError– Failed to create the directory (in case create argument isTrue).
See also
-
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().
-
load_binary_resource(relative_path)¶ Returns a
bytesobject holding the unmodified content of the specified resource.Raises: FileNotFoundError– The resource could not be found.IOError– Error while opening or reading the resource.RuntimeError– Unexpected/Unknown error.
Note
For performance reason, the MemoryError exception will be raised if the specified file size is bigger than 16MB (16777216 bytes).
-
load_icon(sources, force_reload=False)¶ Loads or gets an
IconHandle. Seeload_icon()for more details.
-
load_settings()¶ Returns the
keypirinha.Settingsobject associated with the parent Package.Note
- The configuration files will be loaded only the first time this
method is called. Any subsequent call will return a new
keypirinha.Settingsobject pointing to the same data block. - When the application detects that one or several configuration
files have been modified in a Package, it will automatically
re-read the files (only if they were previously loaded), then will
notify every related plugin via a call to
Plugin.on_config_changed(). - In case
Plugin.on_config_changed()is called, plugins will not have to callPlugin.load_settings()again if they already hold akeypirinha.Settingsobject.
See also
- The configuration files will be loaded only the first time this
method is called. Any subsequent call will return a new
-
load_text_resource(relative_path)¶ Returns a string object holding the content of the specified resource.
May raise the same exceptions than the load_binary_resource() method, plus the
TypeErrorexception if resource’s content could not be Unicode decoded.
-
log(*objects, *, sep=' ', level=1, lineno=-1)¶ Logs a message.
-
set_actions(category, actions_list)¶ Associate a given list of
CatalogActionto anItemCategory.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
CatalogActionobjects that have been created withcreate_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()returnsFalse.Return type: See also
-
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 her current search terms. This method is meant to be called from
on_suggest().suggestions must be a list of
CatalogItemobjects.match_method must be a
Matchvalue.sort_method must be a
Sortvalue.Note
The match_method and sort_method arguments are taken into account by the application only when the user has selected an item. In other words, when the items_chain argument of
on_suggest()is not empty.
-
should_terminate(wait_seconds=None)¶ Returns a boolean to indicate whether the current task should return as soon as possible, without finishing 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
- When calling code is from a
Plugin, it is preferred to call this method instead of thekeypirinha.should_terminate()function as it is potentially faster. - Check the documentation of
keypirinha.should_terminate()to know more about the meaning of the returned value.
See also
- When calling code is from a
-