13.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(value)

Bases: enum.IntEnum

The flags passed to Plugin.on_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).

DESKTOP = 4096

The content of the Desktop has changed (common and/or user’s). It can be because its structure has been modified (folders), or because some files/shortcuts have been added, modified, moved or removed.

Keypirinha groups events from the file system a little before sending them to the plugins by waiting a couple of seconds in order to avoid flooding the plugins.

IMPORTANT: Keypirinha will never send this notification if it is installed in one of the Desktop folders.

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 = 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 = 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).

STARTMENU = 8192

The content of the Start Menu has changed (common and/or user’s). It can be because its structure has been modified (folders), or because some files/shortcuts have been added, modified, moved or removed.

Keypirinha groups events from the file system a little before sending them to the plugins by waiting a couple of seconds in order to avoid flooding the plugins.

IMPORTANT: Keypirinha will never send this notification if it is installed in one of the Start Menu folders.

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(value)

Bases: enum.IntEnum

The CatalogItem.args_hint() property of CatalogItem.

ACCEPTED = 1

The item object optionally accepts arguments

FORBIDDEN = 0

The item object does not accept arguments

REQUIRED = 2

The item object requires arguments

class keypirinha.ItemCategory(value)

Bases: enum.IntEnum

The CatalogItem.category() property of CatalogItem.

Item’s category ID reflects the content of CatalogItem.target() (i.e. not CatalogItem.raw_args() or CatalogItem.displayed_args()) and it helps the plugin to know what a given item is about.

Note that it’s almost solely for the exclusive use of the plugin as Keypirinha interprets this value only if the ID is a standard one (i.e. ERROR, FILE, …) and for displaying purpose. For example, a FILE item will automatically be given an icon from the OS by Keypirinha if it doesn’t have one already and if it has to be displayed on the GUI.

When creating items, it is recommended to use a standard category as much as possible and only if its meaning perfectly matches the content of CatalogItem.target(). Otherwise, plugin developer may prefer to create their own set of category IDs, starting with ItemCategory.USER_BASE + 1. Example:

MY_CUSTOM_ITEMCAT = keypirinha.ItemCategory.USER_BASE + 1
MY_SECOND_CUSTOM_ITEMCAT = keypirinha.ItemCategory.USER_BASE + 2

Important

Category IDs are internally registered on a per-plugin basis. There will be no collision if two plugins, may they have the same parent package or not, define a category having the value USER_BASE + 1 with a different meaning.

CMDLINE = 30

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

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 = 50

math, programming language, …)

Type

Item is an expression that has to be evaluated (e.g.

FILE = 20

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

KEYWORD = 10

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

REFERENCE = 60

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

URL = 40

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

USER_BASE = 1000

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

USER_MAX = 4294967294

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

class keypirinha.ItemHitHint(value)

Bases: enum.IntEnum

The CatalogItem.hit_hint() property of CatalogItem.

IGNORE = 1

The item object will not be added to History

KEEPALL = 0

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

NOARGS = 2

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

class keypirinha.Match(value)

Bases: enum.IntEnum

Match methods

ANY = 0

Match any item

DEFAULT = 1000

FUZZY

Type

Default behavior

FUZZY = 1000

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

class keypirinha.Sort(value)

Bases: enum.IntEnum

Sort methods

DEFAULT = 1000

SCORE_DESC

Type

Default behavior

LABEL_ASC = 200

Sort results alphabetically by label (ascending)

NONE = 0

Do not sort items

SCORE_DESC = 1000

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

TARGET_ASC = 100

Sort results alphabetically by target (ascending)

keypirinha.arch()

Return current architecture model (i.e. x86 or x64)

keypirinha.computer_name()

Return 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()

Return the full path to Keypirinha’s bootstrap executable (i.e. not the architecture-specific 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. Thus it is the responsibility of the caller to create it if needed.

keypirinha.label()

Return 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.

Prefer to use Plugin.get_package_cache_path() when possible.

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. Thus it is the responsibility of the caller to create it if needed.

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

Load an icon if it has not been loaded already and return 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 below 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

A handle to the icon. IconHandle.free() must be called explicitly 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

  • The lifetime of a loaded icon resource is tied to the lifetime of the package that owns this resource.

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

  • 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 following image formats are supported: ICO, PNG and JPEG.

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

  • The image dimensions required at runtime by the application depend 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

      • @C:\Dir\App.exe,0

keypirinha.load_settings(package_full_name=None)

Return 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 (but recommended) because the application has the ability to match a calling thread with its source Package. Nevertheless, this association mechanism might fail in some rare conditions, in which case the application falls back on using the passed package name.

Warning

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

keypirinha.name()

Return 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()

Return a list of the names of the packages that are currently loaded.

keypirinha.packages_path()

Deprecated since version 2.1: Use live_package_dir() instead

keypirinha.pid()

Return the main process ID of the application.

Note

This function should be preferred over os.getpid() if you want to get the PID of Keypirinha. Keypirinha’s architecture might change in the future and, for example, 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()

Return the Settings object associated with the application.

Note

  • Settings might change at any time if the end-user decides to edit the configuration file. In thise case, the application will notify every loaded plugins by calling Plugin.on_events() 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_events() 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)

Return a boolean to indicate whether the current task (thread) should return as soon as possible, without completing 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 turns 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 function 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 and equivalent one. For example a Plugin.on_suggest() call has been made right after the current one because the end-user is still typing.

  • 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()

Return current user’s name.

This is the name used when looking for user-specific configuration files.

keypirinha.version()

Return 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 v2
version() <= (1, 1) # test if version is less than or equal to v1.1
keypirinha.version_string()

Return 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. Prefer version() if the intent is to compare versions.