11.2.1. keypirinha module

The keypirinha module is the main module of the API. It implements and exposes the functions and classes necessary to develop a new plugin for Keypirinha.

class keypirinha.Events

Bases: enum.IntEnum

The flags passed to Plugin.on_events().

APPCONFIG = <Events.APPCONFIG: 1>

Application configuration has changed. Either because of a manual modification by the user, or because a change to an environment variable has impacted at least one value (in which case this flag is combined with ENV).

ENV = <Events.ENV: 256>

At least one environment variable has been added/removed/modified. Note that if this change impacts application and/or package configuration, this flag is combined with APPCONFIG and/or PACKCONFIG.

NETOPTIONS = <Events.NETOPTIONS: 1024>

System’s network settings have been modified (via the Internet Properties dialog for example), and plugins that perform network requests should update their state. Practically, it means keypirinha_net.build_urllib_opener() should be called in order to get a new opener object. This event usually goes along with the APPCONFIG event, but developer should not rely on this behavior.

PACKCONFIG = <Events.PACKCONFIG: 2>

Package configuration has changed. Either because of a manual modification by the user, or because a change to an environment variable has impacted at least one value (in which case this flag is combined with ENV).

STORAGEDEV = <Events.STORAGEDEV: 512>

One or several logical volume have been inserted, removed, connected or disconnected. This event can be related to a storage device, a media or a network volume.

class keypirinha.ItemArgsHint

Bases: enum.IntEnum

The CatalogItem.args_hint() property of CatalogItem.

ACCEPTED = <ItemArgsHint.ACCEPTED: 1>

The item object optionally accepts arguments

FORBIDDEN = <ItemArgsHint.FORBIDDEN: 0>

The item object does not accept arguments

REQUIRED = <ItemArgsHint.REQUIRED: 2>

The item object requires arguments

class keypirinha.ItemCategory

Bases: enum.IntEnum

The CatalogItem.category() property of CatalogItem.

CMDLINE = <ItemCategory.CMDLINE: 30>

Item is a command line to be executed, given as-is to the operating system

ERROR = <ItemCategory.ERROR: 1>

An “error” item that cannot be executed. It is destined to show a warning/error message in the results list where a specific result would normally be expected by the user. It will be accepted by the application only as a suggestion. It cannot be part of the Catalog. The best usage example for it can be found in the official Calc plugin, which sets an ERROR item as a suggestion to indicate user her mathematical expression could not be evaluated. ERROR items should be created with Plugin.create_error_item().

EXPRESSION = <ItemCategory.EXPRESSION: 50>

Item is an expression that has to be evaluated (e.g. – math, programming language, ...)

FILE = <ItemCategory.FILE: 20>

Item is a path to a file/dir/executable/...

KEYWORD = <ItemCategory.KEYWORD: 10>

Item is a keyword that will be triggered by the application or a plugin (i.e.: an internal command)

REFERENCE = <ItemCategory.REFERENCE: 60>

Item is a reference/id that can be used/interpreted only by the plugin that created the CatalogItem object

URL = <ItemCategory.URL: 40>

Item is a url (http/ftp/mailto/...)

USER_BASE = <ItemCategory.USER_BASE: 1000>

Base category id for third-party plugins. Allowed range is [USER_BASE, USER_MAX].

USER_MAX = <ItemCategory.USER_MAX: 4294967294>

Maximum category id for third-party plugins. Allowed range is [USER_BASE, USER_MAX].

class keypirinha.ItemHitHint

Bases: enum.IntEnum

The CatalogItem.hit_hint() property of CatalogItem.

IGNORE = <ItemHitHint.IGNORE: 1>

The item object will not be added to History

KEEPALL = <ItemHitHint.KEEPALL: 0>

The item object will be added to History, including its arguments, if any

NOARGS = <ItemHitHint.NOARGS: 2>

The initial item object selected by the user will be added to History (omitting its arguments, if any)

class keypirinha.Match

Bases: enum.IntEnum

Match methods

ANY = <Match.ANY: 0>

Match any item

DEFAULT = <Match.FUZZY: 1000>

Default behaviorFUZZY

FUZZY = <Match.FUZZY: 1000>

Match items against user’s search terms using a fuzzy algorithm

class keypirinha.Sort

Bases: enum.IntEnum

Sort methods

DEFAULT = <Sort.SCORE_DESC: 1000>

Default behaviorSCORE_DESC

LABEL_ASC = <Sort.LABEL_ASC: 200>

Sort results alphabetically by label (ascending)

NONE = <Sort.NONE: 0>

Do not sort items

SCORE_DESC = <Sort.SCORE_DESC: 1000>

Sort results by descending score (for now, this sort method must be combined with Match.FUZZY).

TARGET_ASC = <Sort.TARGET_ASC: 100>

Sort results alphabetically by target (ascending)

keypirinha.arch()

Returns application’s architecture model (i.e.: x32 or x64).

keypirinha.computer_name()

Returns computer’s NetBIOS name. This is the name used when looking for computer-specific configuration files.

keypirinha.delay(seconds, func)

Schedules a call to func in seconds seconds (float).

TO BE IMPLEMENTED

Raises:ValueErrorseconds value is invalid or func is not a callable.

Warning

callable must call should_terminate() as frequently as possible during loops, or at boundaries of lengthy operations (typically I/O operations like disk accesses and network communications).

keypirinha.exe_path()

Returns the path to Keypirinha’s executable.

keypirinha.installed_package_dir(package_full_name=None)

Get the path of an installed package (i.e.: *.keypirinha-package), or the base directory for Installed Packages (Downloaded) if package_full_name is not specified.

The base directory should look similar to %APPDATA%/Keypirinha/InstalledPackages in installed mode and X:/Keypirinha/portable/Profile/InstalledPackages in portable mode.

Note

The base directory is guaranteed to exist, but not the package itself.

keypirinha.label()

Returns application’s display name (e.g.: Keypirinha).

keypirinha.live_package_dir(package_full_name=None)

Get the directory of a live package, or the base directory for Live Packages in case package_full_name is not specified.

The base directory should look similar to %APPDATA%/Keypirinha/Packages in installed mode and X:/Keypirinha/portable/Profile/Packages in portable mode.

Note

The base directory is guaranteed to exist, but not the directory of the given package.

keypirinha.load_icon(sources, force_reload=False, package_full_name=None)

Loads an icon if it has not been loaded already and returns a handle to it.

Parameters:
  • sources (list) – Can be a string in case of a single source or a list of strings. This argument allows to specify one or several image files that are meant to represent the same icon, with different sizes. For example, you may want to specify a single .ico file that holds all the desired dimensions, or a list containing several .png files. See the Notes for more info.
  • force_reload (bool) – Force the icon to be reloaded. Raising this flag may impact user experience quite significantly because of bad performances. It is recommended to ensure icon sources really have been modified since the last time it has been loaded.
  • package_full_name (str) – The name of the Package to which this icon will be attached. The lifetime of an icon handle is bound to the lifetime of its parent Package. If the Package gets unloaded or reloaded, its resources will be freed automatically and any handle pointing to those resources will become invalid. This argument is optional because the application has the ability to match a calling thread with its source Package. Nevertheless, in some rare conditions (e.g.: the calling thread is a Python thread), this association might fail.
Returns:

An handle to the icon. IconHandle.free() must be called explicitely if you plan to reload, override this icon.

Return type:

IconHandle

Raises:

ValueError – The specified sources could not be read or loaded.

Warning

Use Plugin.load_icon() instead when possible when call site is in Plugin.

Note

  • An icon is associated with a package. So is its lifetime unless IconHandle.free() is called.

  • Two IconHandle objects may point to the same icon resource. If IconHandle.free() is called on one of them, the second object will point to a non-existing icon unless Plugin.load_icon() or load_icon() is called with the exact same sources list, for the same package.

  • The uniqueness of an icon is defined by its associated package and its sources list.

  • The following image formats are supported: ICO, PNG and JPEG.

  • Formats can be mixed in the list passed as sources argument.

  • The sizes required at runtime by the application depends on system settings and application settings. However, in order to have a good user experience, an icon should be available in the following sizes: 16x16, 32x32, 48x48 and 256x256 pixels. If a required size has not been provided, the application will get the next greater size and scale down the image to the required dimensions with the best available quality filter.

  • The paths passed via the sources argument can point to:

    • A resource file (i.e.: a file stored in Package’s archive or directory). Example: res://PackageName/icon.png (PackageName is redundant but mandatory). See Plugin.package_full_name() to get full package name of a plugin.

    • A cached file (i.e.: a file stored in Package’s Cache directory). Example: cache://PackageName/icon-file.ico (PackageName is redundant but mandatory)

    • A Shell Resource Location, which is formated that way: "@<PE-path>,[-]<stringID>", where <PE-path> is the path to an executable or a DLL (environment variables are expanded), stringID is the ID of the icon to load from the module (if prefixed with -), or the zero-based index of the resource to load from the module (no prefix). Examples:

      • @shell32.dll,-12692
      • @%SystemRoot%\system32\shell32.dll,-12690
keypirinha.load_settings(package_full_name=None)

Returns the Settings object associated with a package.

Parameters:package_full_name (str) – The name of the Package to load/get the settings from. This argument is optional because the application has the ability to match a calling thread with its source Package. Nevertheless, in some rare conditions (e.g.: the calling thread is a Python thread), this association might fail.

Warning

Plugin.load_settings() must be called instead, whenever it is possible.

keypirinha.name()

Returns application’s name (e.g.: keypirinha).

keypirinha.package_cache_dir(package_full_name=None)

Get the cache directory of a package, or its base directory if package_full_name is not specified.

The base directory should look similar to %LOCALAPPDATA%/Keypirinha/Packages in installed mode and X:/Keypirinha/portable/Local/Packages in portable mode.

Note

The base directory is guaranteed to exist, but not the directory of the given package.

keypirinha.package_path(full_name)

Deprecated since version 2.1: Use live_package_dir() instead

keypirinha.packages_list()

Returns the list of the names of the currently loaded packages.

keypirinha.packages_path()

Deprecated since version 2.1: Use live_package_dir() instead

keypirinha.pid()

Returns the main process ID of the application.

Note

You should use this function instead of os.getpid() if you want to get the PID of Keypirinha. Keypirinha’s architecture might change in the future and Python plugins may have a dedicated process, separated from application’s main process. This function will always return the PID of the main process of the application.

keypirinha.settings()

Returns the Settings object associated with the application.

Note

  • Settings might change at any time if the end-user decides to edit the configuration file. Once she did, the application will notify every loaded plugins by calling Plugin.on_config_changed() with the Events.APPCONFIG flag.
  • The values returned by the Settings object are always up-to-date so you do not have to get a new object in case of a Plugin.on_config_changed() notification.
  • If the end-user did not overwrite any default value (e.g.: empty configuration file), the dictionary will always be populated with the values in use (i.e.: the default ones).
keypirinha.should_terminate(wait_seconds=None)

Indicates whether the current task (i.e.: thread) should return as soon as possible, without finishing its job.

Delayed tasks (i.e.: scheduled with delay()) must call this function frequently. Especially at I/O operations boundaries (storage accesses and network communications).

The optional wait_seconds argument allows to wait for a given amout of seconds before returning (can be a float), unless the return value is True before the end of the period. This is useful in case you don’t want to handle an incoming message from the application (typically Plugin.on_suggest()) too quickly/often in order to avoid any flooding due to user typing her search (hard-drive scratching, IPC queries, network requests, ...).

Returns:True indicates the current task should immediately return and discard its results. The reasons this method might return True are:
  • Application is terminating
  • The package and/or plugin that owns the current task is being (or has been) reloaded.
  • The plugin message has been obsoleted by a new one. For example a Plugin.on_suggest() call has been made right after the current one because end-user’s search input has been updated.
  • The current task is taking too long
  • Any other reason due to an internal failure and that requires the application to free its resources
Return type:bool

Warning

If calling from a Plugin, Plugin.should_terminate() should always be preferred as it is faster.

keypirinha.user_config_dir()

Get the path to the directory dedicated to user’s configuration.

The base directory should look similar to %APPDATA%/Keypirinha/User in installed mode and X:/Keypirinha/portable/Profile/User in portable mode.

Note

The directory is guaranteed to exist.

keypirinha.user_name()

Returns current user’s name. This is the name used when looking for user-specific configuration files.

keypirinha.version()

Returns application’s version in a tuple of unsigned integers that can be used for comparison. Format is (major, minor, patch).

Examples:

version() > (2)     # test if version is strictly greater than "2"
version() <= (1, 1) # test if version is less than or equal to "1.1"
keypirinha.version_string()

Returns application’s version in a dotted string as in M.mm.pppp where M is the major version number, m the minor number, and p is the patch revision. Use the version() function to perform comparison tests.