Adds operator handlers to operators. #117912

Open
Jaume Bellet wants to merge 2 commits from JaumeBellet/blender:pr-0011-operator-handlers into main

When changing the target branch, be careful to rebase the branch in your fork to match. See documentation.
First-time contributor

Allows executing python code pre and post execution.

Motivation

I have found a needed to do something from python, when an operator is being executed.

Usage examples

  • An add-on is doing managing with geometry and needs to perform something when vertices are deleted.
  • An add-on could use translate operator to move something it controls, related to vertices positions.

Benefits

  • Addon's are not abusing on timers
  • Code if more event focused

Desing

desing

Python example code

import bpy

#custom bpy operators
class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        return {'FINISHED'}

bpy.utils.register_class(SimpleOperator)


# Any Python object can act as the handler owner.
owner = object()

# Poll
def handler_poll_true(context, event, params):
    return True

def handler_poll_false(context, event, params):
    return False

def handler_poll(context, event, params, arg):
    return arg == True

# Callbacks
def pre_invoke_callback(context, event, params):
    print("[PRE] invoke", params)
def post_invoke_callback(context, event, params, ret_code):
    print("[POST] invoke", params, "returned", ret_code)
    
def pre_invoke_callback_owner(context, event, params):
    print("[PRE] invoke (with owner)", params)
def post_invoke_callback_owner(context, event, params, ret_code):
    print("[POST] invoke (with owner)", params, "returned", ret_code)

def pre_invoke_callback_args(context, event, params, args):
    print("[PRE] invoke args", args, params)
def post_invoke_callback_args(context, event, params, ret_code, args):
    print("[POST] invoke args", params, "returned", ret_code, "args", args)

def pre_invoke_callback_owner_args(context, event, params, args):
    print("[PRE] invoke (with owner) args:", args, params)
def post_invoke_callback_owner_args(ctx, evt, params, ret_code, args):
    print("[POST] invoke (with owner)", params , "returned", ret_code, "args:", args)

def pre_invoke_callback_override(context, event, params):
    print ("Overrided")
    return False


def modal_callback(context, event, params, ret_code):
    print (context.active_object)
    print (event)
    print ("modal")
    
def modal_callback_args(context, event, params, ret_code, args):
    print (context.active_object)
    print (event.mouse_x, event.mouse_y)
    print ("modal", args)
    
def modal_end_callback(context, event, params, ret_code):
    print("modal end", ret_code)

def pre_invoke_custom_op_callback(context, event, params):
    print("[PRE] invoke custom operator", params )
def post_invoke_custom_op_callback(context, event, params, ret_code):
    print("[POST] invoke custom operator", params, ret_code)
    
# Registration
bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback)
bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback)

bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(cb=pre_invoke_callback_args, poll = handler_poll, args=(False,))
bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(cb=post_invoke_callback_args, args=(1,))

bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback_owner, owner)
bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback_owner, owner)

bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback_owner_args, owner,(1,))
bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback_owner_args, owner,(1,))

bpy.ops.object.simple_operator.handlers.invoke_pre.append(pre_invoke_custom_op_callback)
bpy.ops.object.simple_operator.handlers.invoke_post.append(post_invoke_custom_op_callback)

#Showing the splash will not print "overrided" and do anything
bpy.ops.wm.splash.handlers.invoke_pre.append(pre_invoke_callback_override)


# Unregistration
# Remove one handler from pre_invoke
bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.remove(pre_invoke_callback)
#remove all handlers from post_invoke owned
bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.remove(owner=owner)

# Remove all handlers owned
bpy.ops.remove_handlers(owner=owner)

# calling the MESH_OT_primitive_cube_add operator should output
"""
[POST] invoke {'size': 2.0, 'calc_uvs': False, 'enter_editmode': True, 'align': 0, 'location': (0.0, 0.0, 0.0), 'rotation': (0.0, 0.0, 0.0), 'scale': (1.0, 1.0, 1.0)} returned {'FINISHED'}
[POST] invoke args {'size': 2.0, 'calc_uvs': False, 'enter_editmode': True, 'align': 0, 'location': (0.0, 0.0, 0.0), 'rotation': (0.0, 0.0, 0.0), 'scale': (1.0, 1.0, 1.0)} returned {'FINISHED'} args 1
"""
# calling the OBJECT_OT_simple_operator()
# bpy.ops.object.simple_operator()
"""
[PRE] invoke custom operator {}
[POST] invoke custom operator {'FINISHED'}
"""

bpy.ops.transform.translate.handlers.modal.append(cb = modal_callback_args, args = (1,))
bpy.ops.transform.translate.handlers.modal.append(cb= modal_callback, poll = handler_poll_false)
bpy.ops.transform.translate.handlers.modal_end.append(modal_end_callback)

# Moving an object should output
"""
<bpy_struct, Object("Cube.001") at 0x0000028E8F0D7E08>
246 572
modal 1
...
modal end {'FINISHED'}
"""


def selection_cb(context, event, params,ret):
    print("SELECT", params, ret)
    
bpy.ops.view3d.select.handlers.invoke_post.append(selection_cb)

# Click on 3D view should output
"""
SELECT {'extend': True, 'deselect': True, 'toggle': True, 'deselect_all': False, 'center': True, 'enumerate': True, 'object': True, 'location': (222, 123)} {'PASS_THROUGH', 'FINISHED'}
"""

More

This was previously submitted on phabricator D10579 and

Allows executing python code pre and post execution. ## Motivation I have found a needed to do something from python, when an operator is being executed. ## Usage examples - An add-on is doing managing with geometry and needs to perform something when vertices are deleted. - An add-on could use translate operator to move something it controls, related to vertices positions. ## Benefits - Addon's are not abusing on timers - Code if more event focused ## Desing ![desing](https://tornavis.org/mblender_patches/patches/mb-0011-operator-handlers.svg) ## Python example code ```Py import bpy #custom bpy operators class SimpleOperator(bpy.types.Operator): """Tooltip""" bl_idname = "object.simple_operator" bl_label = "Simple Object Operator" @classmethod def poll(cls, context): return context.active_object is not None def execute(self, context): return {'FINISHED'} bpy.utils.register_class(SimpleOperator) # Any Python object can act as the handler owner. owner = object() # Poll def handler_poll_true(context, event, params): return True def handler_poll_false(context, event, params): return False def handler_poll(context, event, params, arg): return arg == True # Callbacks def pre_invoke_callback(context, event, params): print("[PRE] invoke", params) def post_invoke_callback(context, event, params, ret_code): print("[POST] invoke", params, "returned", ret_code) def pre_invoke_callback_owner(context, event, params): print("[PRE] invoke (with owner)", params) def post_invoke_callback_owner(context, event, params, ret_code): print("[POST] invoke (with owner)", params, "returned", ret_code) def pre_invoke_callback_args(context, event, params, args): print("[PRE] invoke args", args, params) def post_invoke_callback_args(context, event, params, ret_code, args): print("[POST] invoke args", params, "returned", ret_code, "args", args) def pre_invoke_callback_owner_args(context, event, params, args): print("[PRE] invoke (with owner) args:", args, params) def post_invoke_callback_owner_args(ctx, evt, params, ret_code, args): print("[POST] invoke (with owner)", params , "returned", ret_code, "args:", args) def pre_invoke_callback_override(context, event, params): print ("Overrided") return False def modal_callback(context, event, params, ret_code): print (context.active_object) print (event) print ("modal") def modal_callback_args(context, event, params, ret_code, args): print (context.active_object) print (event.mouse_x, event.mouse_y) print ("modal", args) def modal_end_callback(context, event, params, ret_code): print("modal end", ret_code) def pre_invoke_custom_op_callback(context, event, params): print("[PRE] invoke custom operator", params ) def post_invoke_custom_op_callback(context, event, params, ret_code): print("[POST] invoke custom operator", params, ret_code) # Registration bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback) bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback) bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(cb=pre_invoke_callback_args, poll = handler_poll, args=(False,)) bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(cb=post_invoke_callback_args, args=(1,)) bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback_owner, owner) bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback_owner, owner) bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.append(pre_invoke_callback_owner_args, owner,(1,)) bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.append(post_invoke_callback_owner_args, owner,(1,)) bpy.ops.object.simple_operator.handlers.invoke_pre.append(pre_invoke_custom_op_callback) bpy.ops.object.simple_operator.handlers.invoke_post.append(post_invoke_custom_op_callback) #Showing the splash will not print "overrided" and do anything bpy.ops.wm.splash.handlers.invoke_pre.append(pre_invoke_callback_override) # Unregistration # Remove one handler from pre_invoke bpy.ops.mesh.primitive_cube_add.handlers.invoke_pre.remove(pre_invoke_callback) #remove all handlers from post_invoke owned bpy.ops.mesh.primitive_cube_add.handlers.invoke_post.remove(owner=owner) # Remove all handlers owned bpy.ops.remove_handlers(owner=owner) # calling the MESH_OT_primitive_cube_add operator should output """ [POST] invoke {'size': 2.0, 'calc_uvs': False, 'enter_editmode': True, 'align': 0, 'location': (0.0, 0.0, 0.0), 'rotation': (0.0, 0.0, 0.0), 'scale': (1.0, 1.0, 1.0)} returned {'FINISHED'} [POST] invoke args {'size': 2.0, 'calc_uvs': False, 'enter_editmode': True, 'align': 0, 'location': (0.0, 0.0, 0.0), 'rotation': (0.0, 0.0, 0.0), 'scale': (1.0, 1.0, 1.0)} returned {'FINISHED'} args 1 """ # calling the OBJECT_OT_simple_operator() # bpy.ops.object.simple_operator() """ [PRE] invoke custom operator {} [POST] invoke custom operator {'FINISHED'} """ bpy.ops.transform.translate.handlers.modal.append(cb = modal_callback_args, args = (1,)) bpy.ops.transform.translate.handlers.modal.append(cb= modal_callback, poll = handler_poll_false) bpy.ops.transform.translate.handlers.modal_end.append(modal_end_callback) # Moving an object should output """ <bpy_struct, Object("Cube.001") at 0x0000028E8F0D7E08> 246 572 modal 1 ... modal end {'FINISHED'} """ def selection_cb(context, event, params,ret): print("SELECT", params, ret) bpy.ops.view3d.select.handlers.invoke_post.append(selection_cb) # Click on 3D view should output """ SELECT {'extend': True, 'deselect': True, 'toggle': True, 'deselect_all': False, 'center': True, 'enumerate': True, 'object': True, 'location': (222, 123)} {'PASS_THROUGH', 'FINISHED'} """ ``` ## More This was previously submitted on phabricator [D10579](https://archive.blender.org/developer/D10579) and
Jaume Bellet added 1 commit 2024-02-06 18:32:35 +01:00
Allows executing python code pre and post execution.
Iliya Katushenock added this to the Python API project 2024-02-06 18:34:56 +01:00
Jaume Bellet added 1 commit 2024-02-06 20:42:00 +01:00
First-time contributor

This doesn't perfectly match the handler behavior I'd like to see for switching to/from a WorkSpaceTool but it's better than a timer that I currently have to use. I hope this is merged.

This doesn't perfectly match the handler behavior I'd like to see for switching to/from a WorkSpaceTool but it's better than a timer that I currently have to use. I hope this is merged.
Author
First-time contributor

#118026 allows to set callbacks on WorkspaceTool set / unset.

It should also be possible using the handlers introduced on this PR, using it over tool_set_by_id operator. On PRE , the current Tool is the previous tool, and on POST, the current tool is the one user has been selected, which should match the operator parameters.

#118026 allows to set callbacks on WorkspaceTool set / unset. It should also be possible using the handlers introduced on this PR, using it over tool_set_by_id operator. On PRE , the current Tool is the previous tool, and on POST, the current tool is the one user has been selected, which should match the operator parameters.
This pull request has changes conflicting with the target branch.
  • source/blender/python/intern/bpy_rna.h

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u pr-0011-operator-handlers:JaumeBellet-pr-0011-operator-handlers
git checkout JaumeBellet-pr-0011-operator-handlers
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
Code Documentation
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
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
Viewport & EEVEE
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
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
Module
Viewport & EEVEE
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Severity
High
Severity
Low
Severity
Normal
Severity
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#117912
No description provided.