PyAPI: New KeyConfig Utils #110030

Open
Demeter Dzadik wants to merge 4 commits from Mets/blender:new-keyconfig-utils into main

When changing the target branch, be careful to rebase the branch in your fork to match. See documentation.
Member

I like to provide hotkeys for the functionality in my add-ons. However, I find working with the PyAPI for hotkeys frustrating, so I ended up writing a fairly big layer on top of it to make that easier. But now I have to maintain copies of this code across all my repositories.

Instead of doing that, I decided to try and re-write said code to a higher standard, and try to get it into core Blender.
Below are examples of how addons currently register hotkeys, vs how they would do so with the PR.

The PR also includes example code that can be accessed from Text Editor->Templates->Python (Hotkey Simple, Hotkey Advanced)

Not 100% sure if this is the right file to place this code.


Current way addons add hotkeys

import bpy

wm = bpy.context.window_manager
# Pitfall 1: You must know not to use .user or .default or .active, as those won't do what you expect.
kconf = wm.keyconfigs.addon
# Pitfall 2: If Blender is running in background, keyconfigs will be None.
if kconf:
    # Pitfall 3: Must ensure that KeyMap exists.
    keymap = kconf.keymaps.get('Weight Paint')
    if not keymap:
        # Pitfall 4: Must provide correct space_type and region_type, as defined in keymap_hierarchy.py.
        keymap = kconf.keymaps.new('Weight Paint', space_type='EMPTY', region_type='WINDOW')

    # Pitfall 5: No reasonable way at all to check for conflicts.
    keymap.keymap_items.new(
        'object.location_clear',
        type = 'NUMPAD_5',    # Pitfall 6: Valid values for "type" are very hard to find.
        value = 'PRESS',      # Pitfall 7: Parameter names like "type" and "value" are misleading at best.
    )

Proposed way addons could add hotkeys

from bpy_extras.keyconfig_utils import addon_hotkey_register, KeyMapException

addon_hotkey_register(
    keymap_name='Weight Paint',     # Invalid value results in error, showing valid options.
    op_idname='object.location_clear',
    key_id='NUMPAD_5',              # Invalid value results in error, showing valid options.
    event_type='PRESS',              # Invalid value results in error, showing valid options.

    add_on_conflict=True,         # If there's a conflict, still add this hotkey.
    warn_on_conflict=True       # If there's a conflict, print a warning to console.
    error_on_conflict=False,         # If there's a conflict, don't raise an Exception.
)

Previous code in this file (keyconfig_utils.py) seems somewhat unloved:

  • Even though they are utility functions for addon developers, there are no references to them in Blender's own addons or addons-contrib repos.
  • The keyconfig_test() function and its corresponding operator, PREFERENCES_OT_keyconfig_test, fails to execute due to a _kmistr function that is straight up non-existent.

Perhaps these functions should just be removed?


Feedback welcome.

I like to provide hotkeys for the functionality in my add-ons. However, I find working with the PyAPI for hotkeys frustrating, so I ended up writing a fairly big layer on top of it to make that easier. But now I have to maintain copies of this code across all my repositories. Instead of doing that, I decided to try and re-write said code to a higher standard, and try to get it into core Blender. Below are examples of how addons currently register hotkeys, vs how they would do so with the PR. The PR also includes example code that can be accessed from Text Editor->Templates->Python (Hotkey Simple, Hotkey Advanced) Not 100% sure if this is the right file to place this code. --------------------------------------------------- ### Current way addons add hotkeys ```python import bpy wm = bpy.context.window_manager # Pitfall 1: You must know not to use .user or .default or .active, as those won't do what you expect. kconf = wm.keyconfigs.addon # Pitfall 2: If Blender is running in background, keyconfigs will be None. if kconf: # Pitfall 3: Must ensure that KeyMap exists. keymap = kconf.keymaps.get('Weight Paint') if not keymap: # Pitfall 4: Must provide correct space_type and region_type, as defined in keymap_hierarchy.py. keymap = kconf.keymaps.new('Weight Paint', space_type='EMPTY', region_type='WINDOW') # Pitfall 5: No reasonable way at all to check for conflicts. keymap.keymap_items.new( 'object.location_clear', type = 'NUMPAD_5', # Pitfall 6: Valid values for "type" are very hard to find. value = 'PRESS', # Pitfall 7: Parameter names like "type" and "value" are misleading at best. ) ``` ### Proposed way addons could add hotkeys ```python from bpy_extras.keyconfig_utils import addon_hotkey_register, KeyMapException addon_hotkey_register( keymap_name='Weight Paint', # Invalid value results in error, showing valid options. op_idname='object.location_clear', key_id='NUMPAD_5', # Invalid value results in error, showing valid options. event_type='PRESS', # Invalid value results in error, showing valid options. add_on_conflict=True, # If there's a conflict, still add this hotkey. warn_on_conflict=True # If there's a conflict, print a warning to console. error_on_conflict=False, # If there's a conflict, don't raise an Exception. ) ``` --------------------------------------------------- Previous code in this file (`keyconfig_utils.py`) seems somewhat unloved: - Even though they are utility functions for addon developers, there are no references to them in Blender's own addons or addons-contrib repos. - The keyconfig_test() function and its corresponding operator, PREFERENCES_OT_keyconfig_test, fails to execute due to a _kmistr function that is straight up non-existent. Perhaps these functions should just be removed? --------------------------------------------------- Feedback welcome.
Demeter Dzadik added 1 commit 2023-07-12 21:09:22 +02:00
Demeter Dzadik added 1 commit 2023-07-12 21:09:38 +02:00
Campbell Barton was assigned by Demeter Dzadik 2023-07-12 21:13:01 +02:00
Demeter Dzadik added this to the Python API project 2023-07-12 21:13:18 +02:00
Campbell Barton was unassigned by Hans Goudey 2023-07-12 22:18:53 +02:00
Hans Goudey requested review from Campbell Barton 2023-07-12 22:18:58 +02:00

I think it would be better to put this PR on hold and handle this as a design task.

Some of these pitfalls have reasonable solutions without having to add a wrapper API.
Even if we do end up having a wrapper API like this, solving these pitfalls in the underlying API is still preferable.

  • Pitfalls 3 & 4 seem like issues that should be resolved without requiring a wrapper API. It may be best for Blender to register all key-map types before add-ons load, so get(...) returns a valid key-map if the name matches a default key-map which Blender uses.
  • Mechanically checking for a key conflict isn't reliable as some operators pass through and we want to allow using the same keys for multiple operators.
  • Raising an exception if there is a conflict seems error prone, wouldn't this mean that a change or customization to Blender's key-map could break an add-on? In that case users might want to be warned of an issue at most, failing to load properly seems like something we would want to avoid.

EDIT: submitted a PR to address pitfall 3 & 4, #110092.

I think it would be better to put this PR on hold and handle this as a design task. Some of these pitfalls have reasonable solutions without having to add a wrapper API. Even if we do end up having a wrapper API like this, solving these pitfalls in the underlying API is still preferable. - Pitfalls 3 & 4 seem like issues that should be resolved without requiring a wrapper API. It may be best for Blender to register all key-map types before add-ons load, so `get(...)` returns a valid key-map if the name matches a default key-map which Blender uses. - Mechanically checking for a key conflict isn't reliable as some operators pass through and we want to allow using the same keys for multiple operators. - Raising an exception if there is a conflict seems error prone, wouldn't this mean that a change or customization to Blender's key-map could break an add-on? In that case users might want to be warned of an issue at most, failing to load properly seems like something we would want to avoid. ---- EDIT: submitted a PR to address pitfall 3 & 4, #110092.
Demeter Dzadik added 1 commit 2023-08-03 18:17:44 +02:00
Three flags to control behaviour if the added hotkey would result
in a conflict:
add_on_conflict=True: Still add the hotkey as requested by caller.
warn_on_conflict=True: Print a warning into the console.
error_on_conflict=False: Raise a KeyMapException on conflict.
Demeter Dzadik added 1 commit 2023-08-03 19:11:06 +02:00
Author
Member

Raising an exception if there is a conflict seems error prone, wouldn't this mean that a change or customization to Blender's key-map could break an add-on? In that case users might want to be warned of an issue at most, failing to load properly seems like something we would want to avoid.

I added a few flags for different behaviours to handle conflicts, and updated the 2nd code block in the PR description to explain each.

> Raising an exception if there is a conflict seems error prone, wouldn't this mean that a change or customization to Blender's key-map could break an add-on? In that case users might want to be warned of an issue at most, failing to load properly seems like something we would want to avoid. I added a few flags for different behaviours to handle conflicts, and updated the 2nd code block in the PR description to explain each.
Merge conflict checking is in progress. Try again in few moments.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u new-keyconfig-utils:Mets-new-keyconfig-utils
git checkout Mets-new-keyconfig-utils
Sign in to join this conversation.
No reviewers
No Label
Interest
Alembic
Interest
Animation & Rigging
Interest
Asset System
Interest
Audio
Interest
Automated Testing
Interest
Blender Asset Bundle
Interest
BlendFile
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
Interest
EEVEE & Viewport
Interest
Freestyle
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
ID Management
Interest
Images & Movies
Interest
Import Export
Interest
Line Art
Interest
Masking
Interest
Metal
Interest
Modeling
Interest
Modifiers
Interest
Motion Tracking
Interest
Nodes & Physics
Interest
OpenGL
Interest
Overlay
Interest
Overrides
Interest
Performance
Interest
Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds & Tests
Interest
Python API
Interest
Render & Cycles
Interest
Render Pipeline
Interest
Sculpt, Paint & Texture
Interest
Text Editor
Interest
Translations
Interest
Triaging
Interest
Undo
Interest
USD
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Interest
Video Sequencer
Interest
Virtual Reality
Interest
Vulkan
Interest
Wayland
Interest
Workbench
Interest: X11
Legacy
Asset Browser Project
Legacy
Blender 2.8 Project
Legacy
Milestone 1: Basic, Local Asset Browser
Legacy
OpenGL Error
Meta
Good First Issue
Meta
Papercut
Meta
Retrospective
Meta
Security
Module
Animation & Rigging
Module
Core
Module
Development Management
Module
EEVEE & Viewport
Module
Grease Pencil
Module
Modeling
Module
Nodes & Physics
Module
Pipeline, Assets & IO
Module
Platforms, Builds & Tests
Module
Python API
Module
Render & Cycles
Module
Sculpt, Paint & Texture
Module
Triaging
Module
User Interface
Module
VFX & Video
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
2 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: blender/blender#110030
No description provided.