Modal keymap customization from an addon is not restored properly #60766

Closed
opened 4 years ago by rboxman · 61 comments

System Information
Operating system: Win10
Graphics card: nVidia Quadro 600

Blender Version
Broken: 2.80 (sub 41), branch: master, commit date: 2019-01-22 16:54, hash: 25889423d3
Worked: unsure

Short description of error
It seems that if an addon makes a customization to a modal keymap, this customization only works until you restart blender. After restart, the keymap is not restored properly (left blank) and the only way to fix is to disable/re-enable the addon again.

Exact steps for others to reproduce the error

  • Install and Enable the attached .py addon

    • It adds a modal keymap for circle select (makes it so that circle select is active only if you hold down the C key)
  • Save Preferences

  • Notice that things work correctly. Circle select is only active while holding down the C key

  • Restart blender

  • Notice the keymap no longer works. Check the keymap in user preferences and notice that the new entry is actually blanked out

init.py

**System Information** Operating system: Win10 Graphics card: nVidia Quadro 600 **Blender Version** Broken: 2.80 (sub 41), branch: master, commit date: 2019-01-22 16:54, hash: 25889423d324 Worked: unsure **Short description of error** It seems that if an addon makes a customization to a modal keymap, this customization only works until you restart blender. After restart, the keymap is not restored properly (left blank) and the only way to fix is to disable/re-enable the addon again. **Exact steps for others to reproduce the error** - Install and Enable the attached .py addon - It adds a modal keymap for circle select (makes it so that circle select is active only if you hold down the C key) - Save Preferences - Notice that things work correctly. Circle select is only active while holding down the C key - Restart blender - Notice the keymap no longer works. Check the keymap in user preferences and notice that the new entry is actually blanked out [__init__.py](https://archive.blender.org/developer/F6370806/__init__.py)
Poster

Added subscriber: @rboxman

Added subscriber: @rboxman
Collaborator

#66655 was marked as duplicate of this issue

#66655 was marked as duplicate of this issue
Collaborator

#62745 was marked as duplicate of this issue

#62745 was marked as duplicate of this issue
Collaborator

blender/blender-addons#63221 was marked as duplicate of this issue

blender/blender-addons#63221 was marked as duplicate of this issue
Collaborator

blender/blender-addons#59113 was marked as duplicate of this issue

blender/blender-addons#59113 was marked as duplicate of this issue
ideasman42 was assigned by ZedDB 4 years ago
ZedDB commented 4 years ago
Collaborator

Added subscribers: @domlysz, @Jayanam

Added subscribers: @domlysz, @Jayanam

Added subscriber: @Symstract

Added subscriber: @Symstract
ZedDB commented 4 years ago
Collaborator

Added subscribers: @JoseConseco, @brecht

Added subscribers: @JoseConseco, @brecht

Added subscriber: @RainerTrummer

Added subscriber: @RainerTrummer

The same issue happens when you define a complete new tool with a shortcut using bl_keymap. On first Add-on activation, the shortcut works. On restarting Blender, it is non-functional. But if you reload all scripts while Blender is still running, the shortcut works again. I have used this class from the Templates to verify this behavior:

bl_info = {
    "name": "Shortcutter",
    "author": "Bug Reporter",
    "version": (1, 0),
    "blender": (2, 80, 0),
}

import bpy
from bpy.types import WorkSpaceTool

class MyTool(WorkSpaceTool):
    bl_space_type='VIEW_3D'
    bl_context_mode='OBJECT'

    # The prefix of the idname should be your add-on name.
    bl_idname = "my_template.my_circle_select"
    bl_label = "My Circle Select"
    bl_description = (
        "This is a tooltip\n"
        "with multiple lines"
    )
    bl_icon = "ops.generic.select_circle"
    bl_widget = None
    bl_keymap = (
        ("view3d.select_circle", {"type": 'LEFTMOUSE', "value": 'PRESS'},
         {"properties": [("wait_for_input", False)]}),
        ("view3d.select_circle", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True},
         {"properties": [("mode", 'SUB'), ("wait_for_input", False)]}),
    )

    def draw_settings(context, layout, tool):
        props = tool.operator_properties("view3d.select_circle")
        layout.prop(props, "mode")
        layout.prop(props, "radius")


def register():
    bpy.utils.register_tool(MyTool, after={"builtin.scale_cage"}, separator=True, group=True)

def unregister():
    bpy.utils.unregister_tool(MyTool)

if __name__ == "__main__":
    register()
The same issue happens when you define a complete new tool with a shortcut using **bl_keymap**. On first Add-on activation, the shortcut works. On restarting Blender, it is non-functional. But if you reload all scripts while Blender is still running, the shortcut works again. I have used this class from the Templates to verify this behavior: ``` bl_info = { "name": "Shortcutter", "author": "Bug Reporter", "version": (1, 0), "blender": (2, 80, 0), } import bpy from bpy.types import WorkSpaceTool class MyTool(WorkSpaceTool): bl_space_type='VIEW_3D' bl_context_mode='OBJECT' # The prefix of the idname should be your add-on name. bl_idname = "my_template.my_circle_select" bl_label = "My Circle Select" bl_description = ( "This is a tooltip\n" "with multiple lines" ) bl_icon = "ops.generic.select_circle" bl_widget = None bl_keymap = ( ("view3d.select_circle", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("wait_for_input", False)]}), ("view3d.select_circle", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'SUB'), ("wait_for_input", False)]}), ) def draw_settings(context, layout, tool): props = tool.operator_properties("view3d.select_circle") layout.prop(props, "mode") layout.prop(props, "radius") def register(): bpy.utils.register_tool(MyTool, after={"builtin.scale_cage"}, separator=True, group=True) def unregister(): bpy.utils.unregister_tool(MyTool) if __name__ == "__main__": register() ```
hlorus commented 4 years ago

Added subscriber: @hlorus

Added subscriber: @hlorus

Added subscriber: @MizManFryinPan

Added subscriber: @MizManFryinPan
ZedDB commented 4 years ago
Collaborator

Added subscribers: @mano-wii, @ideasman42

Added subscribers: @mano-wii, @ideasman42

Is this something that's on the ToDo list for 2.81 already? Or is there a workaround for it? Not being able to have modifier keys for custom tools limits the use quite a bit.

Is this something that's on the ToDo list for 2.81 already? Or is there a workaround for it? Not being able to have modifier keys for custom tools limits the use quite a bit.

Added subscriber: @chaos-4

Added subscriber: @chaos-4

Added subscriber: @artoonick

Added subscriber: @artoonick

Added subscriber: @Khemadeva

Added subscriber: @Khemadeva
xdanic commented 4 years ago

Added subscriber: @xdanic

Added subscriber: @xdanic
cyso commented 4 years ago

Added subscriber: @cyso

Added subscriber: @cyso

Added subscriber: @TedNielsen

Added subscriber: @TedNielsen

Added subscriber: @testure

Added subscriber: @testure
nosaka commented 4 years ago

Added subscriber: @nosaka

Added subscriber: @nosaka

Added subscriber: @derksen

Added subscriber: @derksen

when will solve this problem? I can't advance because of it in my development

when will solve this problem? I can't advance because of it in my development

Hi @derksen , if you are looking for a workaound for the problem of custom tools not working on Blender restart, you will find it in addons/mesh_snap_utilities_line/init.py
A simplified version of it is in: https://raw.githubusercontent.com/Shriinivas/blenderbezierutils/master/blenderbezierutils.py
(Essentially, you would need to register the tool and keymap in some roundabout way)

Hi @derksen , if you are looking for a workaound for the problem of custom tools not working on Blender restart, you will find it in addons/mesh_snap_utilities_line/__init__.py A simplified version of it is in: https://raw.githubusercontent.com/Shriinivas/blenderbezierutils/master/blenderbezierutils.py (Essentially, you would need to register the tool and keymap in some roundabout way)

@Khemadeva (Shrinivas) , thanks, I'll try this for the instrument. What about saving the shortcuts in the settings addon? that doesn't work either

@Khemadeva (Shrinivas) , thanks, I'll try this for the instrument. What about saving the shortcuts in the settings addon? that doesn't work either

@derksen Maybe there is also an option for saving the shortcuts in the workaround. Just check keys.py in snap utilities.
I am an add-on developer and faced the same issue in my tool. I got the pointer about this workaround from one of the users (thanks @nosaka).

@derksen Maybe there is also an option for saving the shortcuts in the workaround. Just check keys.py in snap utilities. I am an add-on developer and faced the same issue in my tool. I got the pointer about this workaround from one of the users (thanks @nosaka).

Added subscriber: @bblanimation

Added subscriber: @bblanimation
zgorg commented 3 years ago

Added subscriber: @zgorg

Added subscriber: @zgorg
zgorg commented 3 years ago

I think this is a high priority subject around keys save and more clear information about this
I tried to modify a key and at the same add another one. I had to change addon_keymaps to user_keymaps = - [ ] but I could not register the other shortcut at the same time so I put user_keymaps in the settings too and I get back and all the default keys in mesh of all maps were erased. I had a save. but doing this because my shortcut was never registred. I see kmi.active=True on old scripts but I never found an explanation. some people use timers other handlers and I saw an update on a property from addon pref. why to go there? well I'm still a noob but it's not possible to improve this to be more easy to use? I think this is a priority as the fact to have new keys in new versions added to own keys config. I don't show the answer of Brecht about this again...I saw a script to find duplicates that's a good begining

I think this is a high priority subject around keys save and more clear information about this I tried to modify a key and at the same add another one. I had to change addon_keymaps to user_keymaps = - [ ] but I could not register the other shortcut at the same time so I put user_keymaps in the settings too and I get back and all the default keys in mesh of all maps were erased. I had a save. but doing this because my shortcut was never registred. I see kmi.active=True on old scripts but I never found an explanation. some people use timers other handlers and I saw an update on a property from addon pref. why to go there? well I'm still a noob but it's not possible to improve this to be more easy to use? I think this is a priority as the fact to have new keys in new versions added to own keys config. I don't show the answer of Brecht about this again...I saw a script to find duplicates that's a good begining
zgorg commented 3 years ago

This comment was removed by @zgorg

*This comment was removed by @zgorg*
xiwei commented 3 years ago

Added subscriber: @xiwei

Added subscriber: @xiwei
Collaborator

Added subscriber: @lichtwerk

Added subscriber: @lichtwerk
Collaborator

This looks like it could use some attention? (will dare setting to High prio...)

This looks like it could use some attention? (will dare setting to High prio...)

Added subscriber: @maxivazquez

Added subscriber: @maxivazquez
ivpe commented 3 years ago

Added subscriber: @ivpe

Added subscriber: @ivpe
ivpe commented 3 years ago

I think problem hidden here

 \blender-2.82-e5b788bad8bc-windows64\2.82\scripts\modules\bpy\utils\__init__.py
    # Convert the class into a ToolDef.
    def tool_from_class(tool_cls):
        # Convert class to tuple, store in the class for removal.
        tool_def = ToolDef.from_dict({
            "idname": tool_cls.bl_idname,
            "label": tool_cls.bl_label,
            "description": getattr(tool_cls, "bl_description", tool_cls.__doc__),
            "icon": getattr(tool_cls, "bl_icon", None),
            "cursor": getattr(tool_cls, "bl_cursor", None),
            "widget": getattr(tool_cls, "bl_widget", None),
            "keymap": getattr(tool_cls, "bl_keymap", None),
            "data_block": getattr(tool_cls, "bl_data_block", None),
            "operator": getattr(tool_cls, "bl_operator", None),
            "draw_settings": getattr(tool_cls, "draw_settings", None),
            "draw_cursor": getattr(tool_cls, "draw_cursor", None),
        })
        tool_cls._bl_tool = tool_def

        keymap_data = tool_def.keymap
        if keymap_data is not None:
            if context_mode is None:
                context_descr = "All"
            else:
                context_descr = context_mode.replace("_", " ").title()
            from bpy import context
            wm = context.window_manager
            kc = wm.keyconfigs.default  #  <-------------------------<-----------------------< HERE
            if callable(keymap_data[0]):
                cls._km_action_simple(kc, context_descr, tool_def.label, keymap_data)
        return tool_def

I've tested it with kc = wm.keyconfigs.user, everything work's well.
API: keyconfigs.default
API: keyconfigs.user

I think problem hidden here ``` \blender-2.82-e5b788bad8bc-windows64\2.82\scripts\modules\bpy\utils\__init__.py ``` ``` # Convert the class into a ToolDef. def tool_from_class(tool_cls): # Convert class to tuple, store in the class for removal. tool_def = ToolDef.from_dict({ "idname": tool_cls.bl_idname, "label": tool_cls.bl_label, "description": getattr(tool_cls, "bl_description", tool_cls.__doc__), "icon": getattr(tool_cls, "bl_icon", None), "cursor": getattr(tool_cls, "bl_cursor", None), "widget": getattr(tool_cls, "bl_widget", None), "keymap": getattr(tool_cls, "bl_keymap", None), "data_block": getattr(tool_cls, "bl_data_block", None), "operator": getattr(tool_cls, "bl_operator", None), "draw_settings": getattr(tool_cls, "draw_settings", None), "draw_cursor": getattr(tool_cls, "draw_cursor", None), }) tool_cls._bl_tool = tool_def keymap_data = tool_def.keymap if keymap_data is not None: if context_mode is None: context_descr = "All" else: context_descr = context_mode.replace("_", " ").title() from bpy import context wm = context.window_manager kc = wm.keyconfigs.default # <-------------------------<-----------------------< HERE if callable(keymap_data[0]): cls._km_action_simple(kc, context_descr, tool_def.label, keymap_data) return tool_def ``` I've tested it with kc = wm.keyconfigs.user, everything work's well. [API: keyconfigs.default](https://docs.blender.org/api/current/bpy.types.KeyConfigurations.html#bpy.types.KeyConfigurations.default) [API: keyconfigs.user](https://docs.blender.org/api/current/bpy.types.KeyConfigurations.html#bpy.types.KeyConfigurations.user)

Added subscriber: @Lambdadelta

Added subscriber: @Lambdadelta

If it's so, then one line in function unregister_tool *(scripts\modules\bpy\utils_init_.py)*should be changed same way from

kc = wm.keyconfigs.default

to
kc = wm.keyconfigs.user
otherwise addon will throw error when you deactivate it

If it's so, then one line in function unregister_tool *(scripts\modules\bpy\utils\__init__.py)*should be changed same way from ``` kc = wm.keyconfigs.default ``` to ```kc = wm.keyconfigs.user``` otherwise addon will throw error when you deactivate it
yursiv commented 3 years ago

Added subscriber: @yursiv

Added subscriber: @yursiv

Added subscriber: @lobnico

Added subscriber: @lobnico

@Lambdadelta
All good for now, thanks for quick workaround

@Lambdadelta All good for now, thanks for quick workaround

Tested the fix provided by @Lambdadelta and can confirm this works! Attatching a diff for merging in case one of the devs wants to use it.

workspace_tool_fix.diff

Tested the fix provided by @Lambdadelta and can confirm this works! Attatching a diff for merging in case one of the devs wants to use it. [workspace_tool_fix.diff](https://archive.blender.org/developer/F8299337/workspace_tool_fix.diff)

Added subscriber: @karmaral

Added subscriber: @karmaral

Added subscriber: @SpectreFirst

Added subscriber: @SpectreFirst

I want to bump this, since fix seems to be really so simple (one line of code). @ideasman42

I want to bump this, since fix seems to be really so simple (one line of code). @ideasman42

Added subscriber: @RayMairlot

Added subscriber: @RayMairlot
Collaborator

Added subscriber: @LucaRood-3

Added subscriber: @LucaRood-3

Added subscriber: @vitorbalbio-3

Added subscriber: @vitorbalbio-3

Added subscriber: @ckohl_art

Added subscriber: @ckohl_art
Owner

Changed status from 'Confirmed' to: 'Needs User Info'

Changed status from 'Confirmed' to: 'Needs User Info'
Owner

As far as I can see this is working as expected.

  • The default key-map is not saved in preferences, this is used unless customizations have been made.
  • The preferences key-map is saved, this is only for the user to edit via the key-map editor.

So it's correct for the tool to load a keymap to the 'default' keymap, allowing the user to overlay changes to this in the 'user' keymap.

If registering tools writes into the user keymap, there is no way for users to make changes ontop of the default.


Keeping this open in case there is a use-case I'm missing here. Otherwise I think this can be closed.

Most likely this is something that should be documented in more detail.

As far as I can see this is working as expected. - The default key-map is not saved in preferences, this is used unless customizations have been made. - The preferences key-map is saved, this is only for the user to edit via the key-map editor. So it's correct for the tool to load a keymap to the 'default' keymap, allowing the user to overlay changes to this in the 'user' keymap. If registering tools writes into the user keymap, there is no way for users to make changes ontop of the default. ---- Keeping this open in case there is a use-case I'm missing here. Otherwise I think this can be closed. Most likely this is something that should be documented in more detail.
Poster

Hmm, I'm not sure I follow completely. How would you implement the issue described in the original part of the report where I want to enable circle select only while I'm holding down the C key. Or are you saying that such a thing cannot be done within an addon?

This works in my script that's attached but only until I restart blender. Once I restart it looks like my saved keymap has been overwritten and I have to manually reload the addon for it to be brought back.

Hmm, I'm not sure I follow completely. How would you implement the issue described in the original part of the report where I want to enable circle select only while I'm holding down the C key. Or are you saying that such a thing cannot be done within an addon? This works in my script that's attached but only until I restart blender. Once I restart it looks like my saved keymap has been overwritten and I have to manually reload the addon for it to be brought back.
hlorus commented 3 years ago

I can reproduce this by adding a bl_info dictionary to the Ui Tool Simple template and registering it as an addon as @RainerTrummer pointed out.

The next time i start blender and activate the tool i get following error in the console:
WARN (wm.keymap): /home/david/blender-git/blender/source/blender/windowmanager/intern/wm_keymap.c:469 WM_keymap_poll: empty keymap '3D View Tool: Object, My Circle Select'

After running the "Reload Scripts" operator that error won't show up and the tool works as expected again.

I can reproduce this by adding a bl_info dictionary to the Ui Tool Simple template and registering it as an addon as @RainerTrummer pointed out. The next time i start blender and activate the tool i get following error in the console: WARN (wm.keymap): /home/david/blender-git/blender/source/blender/windowmanager/intern/wm_keymap.c:469 WM_keymap_poll: empty keymap '3D View Tool: Object, My Circle Select' After running the "Reload Scripts" operator that error won't show up and the tool works as expected again.
nosaka commented 3 years ago

If so, "bl_keymap" should be removed from WorkSpaceTool.
A setting that disappears on reboot makes no sense and will only mislead add-on developers.

If so, "bl_keymap" should be removed from WorkSpaceTool. A setting that disappears on reboot makes no sense and will only mislead add-on developers.
Owner

Changed status from 'Needs User Info' to: 'Archived'

Changed status from 'Needs User Info' to: 'Archived'
ideasman42 closed this issue 3 years ago
Owner

Committed e8dd96516c with disallows extending modal keymaps as it's not the intended use of add-on keymaps - which is to allow adding short-cuts which call operators defined by the add-ons.

Using add-on keymaps to customize existing modal key-maps basically worked in some cases by accident.

Disabling this as it's a customization which can be made by the keymap editor.

Committed e8dd96516c with disallows extending modal keymaps as it's not the intended use of add-on keymaps - which is to allow adding short-cuts which call operators defined by the add-ons. Using add-on keymaps to customize existing modal key-maps basically worked in some cases by accident. Disabling this as it's a customization which can be made by the keymap editor.
Owner

@nosaka, issues with WorkSpaceTool keymaps should be reported separately since it's not related to modal keymaps.

@nosaka, issues with `WorkSpaceTool` keymaps should be reported separately since it's not related to modal keymaps.
hlorus commented 3 years ago

@ideasman42
The Issue described in #66655 (which was merged with this Task) still persist. Looks like it is a separate issue and should be reopened.

@ideasman42 The Issue described in #66655 (which was merged with this Task) still persist. Looks like it is a separate issue and should be reopened.
Owner

Re-opening tasks that were closed as duplicate, I'll look into those since they aren't related to modal key-maps.

Re-opening tasks that were closed as duplicate, I'll look into those since they aren't related to modal key-maps.

Added subscriber: @stjerneidioten

Added subscriber: @stjerneidioten
Sign in to join this conversation.
No Label
Interest/Alembic
Interest/Animation & Rigging
Interest/Asset Browser
Interest/Asset Browser Project Overview
Interest/Audio
Interest/Automated Testing
Interest/Blender Asset Bundle
Interest/Collada
Interest/Compositing
Interest/Core
Interest/Cycles
Interest/Dependency Graph
Interest/Development Management
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/Modeling
Interest/Modifiers
Interest/Motion Tracking
Interest/Nodes & Physics
Interest/Overrides
Interest/Performance
Interest/Performance
Interest/Physics
Interest/Pipeline, Assets & I/O
Interest/Platforms, Builds, Tests & Devices
Interest/Translations
Interest/Undo
Interest/USD
Interest/Video Sequencer
legacy module/Animation & Rigging
legacy module/Core
legacy module/Development Management
legacy module/Eevee & Viewport
legacy module/Grease Pencil
legacy module/Modeling
legacy module/Nodes & Physics
legacy module/Pipeline, Assets & IO
legacy module/Platforms, Builds, Tests & Devices
legacy module/Python API
legacy module/Rendering & Cycles
legacy module/Sculpt, Paint & Texture
legacy module/Triaging
legacy module/User Interface
legacy module/VFX & Video
legacy project/1.0.0-beta.2
legacy project/Asset Browser (Archived)
legacy project/BF Blender: 2.8
legacy project/BF Blender: After Release
legacy project/BF Blender: Next
legacy project/BF Blender: Regressions
legacy project/BF Blender: Unconfirmed
legacy project/Blender 2.70
legacy project/Code Quest
legacy project/Datablocks and Libraries
legacy project/Eevee
legacy project/Game Animation
legacy project/Game Audio
legacy project/Game Data Conversion
legacy project/Game Engine
legacy project/Game Logic
legacy project/Game Physics
legacy project/Game Python
legacy project/Game Rendering
legacy project/Game UI
legacy project/GPU / Viewport
legacy project/GSoC
legacy project/Infrastructure: Websites
legacy project/LibOverrides - Usability and UX
legacy project/Milestone 1: Basic, Local Asset Browser
legacy project/Nodes
legacy project/OpenGL Error
legacy project/Papercut
legacy project/Pose Library Basics
legacy project/Python API
legacy project/Render & Cycles
legacy project/Render Pipeline
legacy project/Retrospective
legacy project/Sculpt, Paint & Texture
legacy project/Text Editor
legacy project/Tracker Curfew
legacy project/Triaging
legacy project/User Interface
legacy project/UV Editing
legacy project/VFX & Video
legacy project/Virtual Reality
legacy project/Wintab High Frequency
Meta/Good First Issue
Meta/Papercut
migration/requires-manual-verification
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 & Devices
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 Information 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
34 Participants
Notifications
Due Date

No due date set.

Dependencies

No dependencies set.

Reference: blender/blender#60766
Loading…
There is no content yet.