Skip to content

types #

App-model types.

Action #

Bases: CommandRule, Generic[P, R]

An Action is a callable object with menu placement, keybindings, and metadata.

This is the "complete" representation of a command. Including a pointer to the actual callable object, as well as any additional menu and keybinding rules. Most commands and menu items will be represented by Actions, and registered using register_action.

Parameters:

Name Type Description Default
callback Callable[~P, ~R] | str

A function to call when the associated command id is executed. If a string is provided, it must be a fully qualified name to a callable python object. This usually takes the form of {obj.__module__}:{obj.__qualname__} (e.g. my_package.a_module:some_function)

required
menus list[MenuRule] | None

(Optional) Menus to which this action should be added. Note that menu items in the sequence may be supplied as a plain string, which will be converted to a MenuRule with the string as the id field.

None
keybindings list[KeyBindingRule] | None

(Optional) Default keybinding(s) that will trigger this command.

None
palette bool

Whether to add this command to the global Command Palette during registration.

True

CommandRule #

Bases: _BaseModel

Data representing a command and its presentation.

Presentation of contributed commands depends on the containing menu. The Command Palette, for instance, prefixes commands with their category, allowing for easy grouping. However, the Command Palette doesn't show icons nor disabled commands. Menus, on the other hand, shows disabled items as grayed out, but don't show the category label.

Parameters:

Name Type Description Default
id str

A global identifier for the command.

required
title str

Title by which the command is represented in the UI.

required
category str | None

(Optional) Category string by which the command may be grouped in the UI

None
tooltip str | None

(Optional) Tooltip to show when hovered.

None
status_tip str | None

(Optional) Help message to show in the status bar when a button representing this command is hovered (for backends that support it).

None
icon Icon | None

(Optional) Icon used to represent this command, e.g. on buttons or in menus. These may be iconify keys, such as fa6-solid:arrow-down, or superqt.fonticon keys, such as fa6s.arrow_down, or a path to a local .svg file using the file URI scheme. Note that on Windows the file URI scheme should always start with file:/// (three slashes)

None
icon_visible_in_menu bool

Whether to show the icon in menus (for backends that support it). If False, only the title will be shown. By default, True.

True
enablement Expr | None

(Optional) Condition which must be true to enable the command in the UI (menu and keybindings). Does not prevent executing the command by other means, like the execute_command API.

None
short_title str | None

(Optional) Short title by which the command is represented in the UI. Menus pick either title or short_title depending on the context in which they show commands.

None
toggled ToggleRule | Expr | None

(Optional) Condition under which the command should appear checked/toggled in any GUI representation (like a menu or button).

None

Icon #

Bases: _BaseModel

Icons used to represent commands, or submenus.

May provide both a light and dark variant. If only one is provided, it is used in all theme types.

Parameters:

Name Type Description Default
dark str | None

Icon path when a dark theme is used. These may be iconify keys, such as fa6-solid:arrow-down, or superqt.fonticon keys, such as fa6s.arrow_down

None
light str | None

Icon path when a light theme is used. These may be iconify keys, such as fa6-solid:arrow-down, or superqt.fonticon keys, such as fa6s.arrow_down

None

KeyBinding #

KeyBinding(*, parts: list[SimpleKeyBinding])

KeyBinding. May be a multi-part "Chord" (e.g. 'Ctrl+K Ctrl+C').

This is the primary representation of a fully resolved keybinding. For consistency in the downstream API, it should be preferred to SimpleKeyBinding, even when there is only a single part in the keybinding (i.e. when it is not a chord.)

Chords (two separate keypress actions) are expressed as a string by separating the two keypress codes with a space. For example, 'Ctrl+K Ctrl+C'.

Parameters:

Name Type Description Default
parts List[SimpleKeyBinding]

The parts of the keybinding. There must be at least one part.

required
Source code in app_model/types/_keys/_keybindings.py
191
192
def __init__(self, *, parts: list[SimpleKeyBinding]):
    self.parts = parts

part0 property #

part0: SimpleKeyBinding

Return the first part of this keybinding.

All keybindings have at least one part.

from_int classmethod #

from_int(key_int: int, os: Optional[OperatingSystem] = None) -> KeyBinding

Create a KeyBinding from an integer.

Source code in app_model/types/_keys/_keybindings.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
@classmethod
def from_int(
    cls, key_int: int, os: Optional[OperatingSystem] = None
) -> "KeyBinding":
    """Create a KeyBinding from an integer."""
    # a multi keybinding is represented as an integer
    # with the first_part in the lowest 16 bits,
    # the second_part in the next 16 bits, etc.
    first_part = key_int & 0x0000FFFF
    chord_part = (key_int & 0xFFFF0000) >> 16
    if chord_part != 0:
        return cls(
            parts=[
                SimpleKeyBinding.from_int(first_part, os),
                SimpleKeyBinding.from_int(chord_part, os),
            ]
        )
    return cls(parts=[SimpleKeyBinding.from_int(first_part, os)])

from_str classmethod #

from_str(key_str: str) -> KeyBinding

Parse a string into a SimpleKeyBinding.

Source code in app_model/types/_keys/_keybindings.py
217
218
219
220
221
@classmethod
def from_str(cls, key_str: str) -> "KeyBinding":
    """Parse a string into a SimpleKeyBinding."""
    parts = [SimpleKeyBinding.from_str(part) for part in key_str.split()]
    return cls(parts=parts)

to_int #

to_int(os: Optional[OperatingSystem] = None) -> int

Convert this KeyBinding to an integer representation.

Source code in app_model/types/_keys/_keybindings.py
242
243
244
245
246
247
248
249
250
251
252
def to_int(self, os: Optional[OperatingSystem] = None) -> int:
    """Convert this KeyBinding to an integer representation."""
    if len(self.parts) > 2:  # pragma: no cover
        raise NotImplementedError(
            "Cannot represent chords with more than 2 parts as int"
        )
    os = OperatingSystem.current() if os is None else os
    parts = [part.to_int(os) for part in self.parts]
    if len(parts) == 2:
        return KeyChord(*parts)
    return parts[0]

to_text #

to_text(os: Optional[OperatingSystem] = None, use_symbols: bool = False, joinchar: str = '+') -> str

Get a text representation of this KeyBinding.

Optionally, the string representation can be constructed with symbols like ↵ for Enter or OS specific ones like ⌘ for Meta on MacOS. If no symbols should be used, the string representation will use the OS specific names for the keys like Cmd for Meta or Option for Ctrl on MacOS.

Also, a join character can be defined. By default + is used.

Source code in app_model/types/_keys/_keybindings.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def to_text(
    self,
    os: Optional[OperatingSystem] = None,
    use_symbols: bool = False,
    joinchar: str = "+",
) -> str:
    """Get a text representation of this KeyBinding.

    Optionally, the string representation can be constructed with symbols
    like ↵ for Enter or OS specific ones like ⌘ for Meta on MacOS. If no symbols
    should be used, the string representation will use the OS specific names
    for the keys like `Cmd` for Meta or `Option` for Ctrl on MacOS.

    Also, a join character can be defined. By default `+` is used.
    """
    return " ".join(
        part.to_text(os=os, use_symbols=use_symbols, joinchar=joinchar)
        for part in self.parts
    )

validate classmethod #

validate(v: Any) -> KeyBinding

Validate a SimpleKeyBinding.

Source code in app_model/types/_keys/_keybindings.py
294
295
296
297
298
299
300
301
302
303
304
305
@classmethod
def validate(cls, v: Any) -> "KeyBinding":
    """Validate a SimpleKeyBinding."""
    if isinstance(v, KeyBinding):
        return v
    if isinstance(v, SimpleKeyBinding):
        return cls(parts=[v])
    if isinstance(v, int):
        return cls.from_int(v)
    if isinstance(v, str):
        return cls.from_str(v)
    raise TypeError("invalid keybinding")  # pragma: no cover

KeyBindingRule #

Bases: _BaseModel

Data representing a keybinding and when it should be active.

This model lacks a corresponding command. That gets linked up elsewhere, such as below in Action.

Values can be expressed as either a string (e.g. "Ctrl+O") or an integer, using combinations of KeyMod and KeyCode, (e.g. KeyMod.CtrlCmd | KeyCode.KeyO).

Parameters:

Name Type Description Default
primary int | str | None

(Optional) Key combo, (e.g. Ctrl+O).

None
win int | str | None

(Optional) Windows specific key combo.

None
mac int | str | None

(Optional) MacOS specific key combo.

None
linux int | str | None

(Optional) Linux specific key combo.

None
when Expr | None

(Optional) Condition when the keybingding is active.

None
weight int

Internal weight used to sort keybindings. This is not part of the plugin schema

0

validate classmethod #

validate(value: Any) -> KeyBindingRule

Validate keybinding rule.

Source code in app_model/types/_keybinding_rule.py
80
81
82
83
84
85
@classmethod
def validate(cls, value: Any) -> "KeyBindingRule":
    """Validate keybinding rule."""
    if isinstance(value, StandardKeyBinding):
        return value.to_keybinding_rule()
    return super().validate(value)

KeyChord #

KeyChord(first_part: int, second_part: int)

Bases: int

KeyChord is an integer combination of two key combos.

It could be two KeyCombo KeyCode, or int.

Parameters:

Name Type Description Default
first_part KeyCombo | int

The first part of the chord.

required
second_part KeyCombo | int

The second part of the chord.

required
Source code in app_model/types/_keys/_key_codes.py
804
805
806
def __init__(self, first_part: int, second_part: int):
    self._first_part = first_part
    self._second_part = second_part

KeyCode #

Bases: IntEnum

Virtual Key Codes, the integer value does not hold any inherent meaning.

This is the primary internal representation of a key.

from_event_code classmethod #

from_event_code(event_code: int) -> KeyCode

Return the KeyCode associated with the given event code.

Returns KeyCode.UNKNOWN if no KeyCode is associated with the event code.

Source code in app_model/types/_keys/_key_codes.py
194
195
196
197
198
199
200
@classmethod
def from_event_code(cls, event_code: int) -> 'KeyCode':
    """Return the `KeyCode` associated with the given event code.

    Returns `KeyCode.UNKNOWN` if no `KeyCode` is associated with the event code.
    """
    return _EVENTCODE_TO_KEYCODE.get(event_code, KeyCode.UNKNOWN)

from_string classmethod #

from_string(string: str) -> KeyCode

Return the KeyCode associated with the given string.

Returns KeyCode.UNKNOWN if no KeyCode is associated with the string.

Source code in app_model/types/_keys/_key_codes.py
186
187
188
189
190
191
192
@classmethod
def from_string(cls, string: str) -> 'KeyCode':
    """Return the `KeyCode` associated with the given string.

    Returns `KeyCode.UNKNOWN` if no `KeyCode` is associated with the string.
    """
    return keycode_from_string(string)

os_name #

os_name(os: Optional[OperatingSystem] = None) -> str

Get a string representation of this KeyCode using the OS specific naming for the key.

This differs from __str__ since with it a normalized representation (constant to all OSes) is given. Sometimes these representations coincide but not always! Some examples: * KeyCode.Enter is represented by Enter (__str__ represents it as Enter) * KeyCode.Meta is represented by Win on Windows, Super on Linux and Cmd on MacOS (__str__ represents it as Meta)

If no OS is given, the current detected one is used.

Source code in app_model/types/_keys/_key_codes.py
172
173
174
175
176
177
178
179
180
181
182
183
184
def os_name(self, os: Optional[OperatingSystem] = None) -> str:
    """Get a string representation of this `KeyCode` using the OS specific naming for the key.

    This differs from `__str__` since with it a normalized representation (constant to all OSes) is given.
    Sometimes these representations coincide but not always! Some examples:
        * `KeyCode.Enter` is represented by `Enter` (`__str__` represents it as `Enter`)
        * `KeyCode.Meta` is represented by `Win` on Windows, `Super` on Linux and `Cmd` on MacOS
        (`__str__` represents it as `Meta`)

    If no OS is given, the current detected one is used.
    """
    os = OperatingSystem.current() if os is None else os
    return keycode_to_os_name(self, os)

os_symbol #

os_symbol(os: Optional[OperatingSystem] = None) -> str

Get a string representation of this KeyCode using a symbol/OS specific symbol.

Some examples: * KeyCode.Enter is represented by * KeyCode.Meta is represented by on Windows, Super on Linux and on MacOS

If no OS is given, the current detected one is used.

Source code in app_model/types/_keys/_key_codes.py
160
161
162
163
164
165
166
167
168
169
170
def os_symbol(self, os: Optional[OperatingSystem] = None) -> str:
    """Get a string representation of this `KeyCode` using a symbol/OS specific symbol.

    Some examples:
        * `KeyCode.Enter` is represented by `↵`
        * `KeyCode.Meta` is represented by `⊞` on Windows, `Super` on Linux and `⌘` on MacOS

    If no OS is given, the current detected one is used.
    """
    os = OperatingSystem.current() if os is None else os
    return keycode_to_os_symbol(self, os)

KeyCombo #

KeyCombo(modifiers: KeyMod, key: KeyCode = KeyCode.UNKNOWN)

Bases: int

KeyCombo is an integer combination of one or more.

KeyMod and KeyCode.

Source code in app_model/types/_keys/_key_codes.py
774
775
776
def __init__(self, modifiers: KeyMod, key: KeyCode = KeyCode.UNKNOWN):
    self._modifiers = modifiers
    self._key = key

KeyMod #

Bases: IntFlag

A Flag indicating keyboard modifiers.

MenuItem #

Bases: MenuItemBase

Combination of a Command and conditions for menu presentation.

This object is mostly constructed by register_action right before menu item registration.

Parameters:

Name Type Description Default
command CommandRule

CommandRule to execute when this menu item is selected.

required
alt CommandRule | None

(Optional) Alternate command to execute when this menu item is selected, (e.g. when the Alt-key is held when opening the menu)

None

MenuItemBase #

Bases: _BaseModel

Data representing where and when a menu item should be shown.

Parameters:

Name Type Description Default
when Expr | None

(Optional) Condition which must be true to show the item.

None
group str | None

(Optional) Menu group to which this item should be added. Menu groups are sortable strings (like '1_cutandpaste'). 'navigation' is a special group that always appears at the top of a menu. If not provided, the item is added in the last group of the menu.

None
order float | None

(Optional) Order of the item within its group. Note, order is not part of the plugin schema, plugins may provide it using the group key and the syntax 'group@order'. If not provided, items are sorted by title.

None

MenuRule #

Bases: MenuItemBase

A MenuRule defines a menu location and conditions for presentation.

It does not define an actual command. That is done in either MenuItem or Action.

Parameters:

Name Type Description Default
id str

Menu in which to place this item.

required

OperatingSystem #

Bases: Enum

Operating system enum.

is_linux property #

is_linux: bool

Returns True if the current operating system is Linux.

is_mac property #

is_mac: bool

Returns True if the current operating system is MacOS.

is_windows property #

is_windows: bool

Returns True if the current operating system is Windows.

current staticmethod #

current() -> OperatingSystem

Return the current operating system as enum.

Source code in app_model/types/_constants.py
14
15
16
17
@staticmethod
def current() -> "OperatingSystem":
    """Return the current operating system as enum."""
    return _CURRENT

SimpleKeyBinding #

Bases: BaseModel

Represent a simple combination modifier(s) and a key, e.g. Ctrl+A.

Parameters:

Name Type Description Default
ctrl bool

Whether the "Ctrl" modifier is active.

False
shift bool

Whether the "Shift" modifier is active.

False
alt bool

Whether the "Alt" modifier is active.

False
meta bool

Whether the "Meta" modifier is active.

False
key KeyCode | None

The key that is pressed (e.g. KeyCode.A)

None

from_int classmethod #

from_int(key_int: int, os: Optional[OperatingSystem] = None) -> SimpleKeyBinding

Create a SimpleKeyBinding from an integer.

Source code in app_model/types/_keys/_keybindings.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
@classmethod
def from_int(
    cls, key_int: int, os: Optional[OperatingSystem] = None
) -> "SimpleKeyBinding":
    """Create a SimpleKeyBinding from an integer."""
    ctrl_cmd = bool(key_int & KeyMod.CtrlCmd)
    win_ctrl = bool(key_int & KeyMod.WinCtrl)
    shift = bool(key_int & KeyMod.Shift)
    alt = bool(key_int & KeyMod.Alt)

    os = OperatingSystem.current() if os is None else os
    ctrl = win_ctrl if os.is_mac else ctrl_cmd
    meta = ctrl_cmd if os.is_mac else win_ctrl
    key = key_int & 0x000000FF  # keycode mask

    return cls(ctrl=ctrl, shift=shift, alt=alt, meta=meta, key=key)

from_str classmethod #

from_str(key_str: str) -> SimpleKeyBinding

Parse a string into a SimpleKeyBinding.

Source code in app_model/types/_keys/_keybindings.py
71
72
73
74
75
76
@classmethod
def from_str(cls, key_str: str) -> "SimpleKeyBinding":
    """Parse a string into a SimpleKeyBinding."""
    mods, remainder = _parse_modifiers(key_str.strip())
    key = KeyCode.from_string(remainder)
    return cls(**mods, key=key)

is_modifier_key #

is_modifier_key() -> bool

Return true if this is a modifier key.

Source code in app_model/types/_keys/_keybindings.py
30
31
32
33
34
35
36
37
38
def is_modifier_key(self) -> bool:
    """Return true if this is a modifier key."""
    return self.key in (
        KeyCode.Alt,
        KeyCode.Shift,
        KeyCode.Ctrl,
        KeyCode.Meta,
        KeyCode.UNKNOWN,
    )

to_int #

to_int(os: Optional[OperatingSystem] = None) -> int

Convert this SimpleKeyBinding to an integer representation.

Source code in app_model/types/_keys/_keybindings.py
101
102
103
104
105
106
107
108
109
110
111
112
113
def to_int(self, os: Optional[OperatingSystem] = None) -> int:
    """Convert this SimpleKeyBinding to an integer representation."""
    os = OperatingSystem.current() if os is None else os
    mods: KeyMod = KeyMod.NONE
    if self.ctrl:
        mods |= KeyMod.WinCtrl if os.is_mac else KeyMod.CtrlCmd
    if self.shift:
        mods |= KeyMod.Shift
    if self.alt:
        mods |= KeyMod.Alt
    if self.meta:
        mods |= KeyMod.CtrlCmd if os.is_mac else KeyMod.WinCtrl
    return mods | (self.key or 0)

to_text #

to_text(os: Optional[OperatingSystem] = None, use_symbols: bool = False, joinchar: str = '+') -> str

Get a user-facing string representation of this SimpleKeyBinding.

Optionally, the string representation can be constructed with symbols like ↵ for Enter or OS specific ones like ⌘ for Meta on MacOS. If no symbols should be used, the string representation will use the OS specific names for the keys like Cmd for Meta or Option for Ctrl on MacOS.

Also, a join character can be defined. By default + is used.

Source code in app_model/types/_keys/_keybindings.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def to_text(
    self,
    os: Optional[OperatingSystem] = None,
    use_symbols: bool = False,
    joinchar: str = "+",
) -> str:
    """Get a user-facing string representation of this SimpleKeyBinding.

    Optionally, the string representation can be constructed with symbols
    like ↵ for Enter or OS specific ones like ⌘ for Meta on MacOS. If no symbols
    should be used, the string representation will use the OS specific names
    for the keys like `Cmd` for Meta or `Option` for Ctrl on MacOS.

    Also, a join character can be defined. By default `+` is used.
    """
    os = OperatingSystem.current() if os is None else os
    keybinding_elements = [*self._mods2keycodes()]
    if self.key:
        keybinding_elements.append(self.key)

    return joinchar.join(
        kbe.os_symbol(os=os) if use_symbols else kbe.os_name(os=os)
        for kbe in keybinding_elements
    )

StandardKeyBinding #

Bases: Enum

to_keybinding_rule #

to_keybinding_rule() -> KeyBindingRule

Return KeyBindingRule for this StandardKeyBinding.

Source code in app_model/types/_keys/_standard_bindings.py
77
78
79
80
81
def to_keybinding_rule(self) -> "KeyBindingRule":
    """Return KeyBindingRule for this StandardKeyBinding."""
    from .._keybinding_rule import KeyBindingRule

    return KeyBindingRule(**_STANDARD_KEY_MAP[self])

SubmenuItem #

Bases: MenuItemBase

Point to another Menu that will be displayed as a submenu.

Parameters:

Name Type Description Default
submenu str

Menu to insert as a submenu.

required
title str

Title of this submenu, shown in the UI.

required
icon Icon | None

(Optional) Icon used to represent this submenu. These may be iconify keys, such as fa6-solid:arrow-down, or superqt.fonticon keys, such as fa6s.arrow_down

None
enablement Expr | None

(Optional) Condition which must be true to enable the submenu. Disabled submenus appear grayed out in the UI, and cannot be selected. By default, submenus are enabled.

None

ToggleRule #

Bases: _BaseModel

More detailed description of a toggle rule.

Parameters:

Name Type Description Default
condition Expr | None

(Optional) Condition under which the command should appear checked/toggled in any GUI representation (like a menu or button).

None
get_current Callable[list, bool] | None

Function that returns the current state of the toggle.

None