Python: add Python API for layout panels #116949

Merged
Jacques Lucke merged 10 commits from JacquesLucke/blender:layout-panel-python into main 2024-01-11 19:08:54 +01:00
Member

This adds a Python API for layout panels that have been introduced in #113584. Two new methods on UILayout are added:

  • .panel(idname, text="...", default_closed=False) -> Optional[UILayout]
  • .panel_prop(owner, prop_name, text="...") -> Optional[UILayout]

Both create a panel and return None if the panel is collapsed. The difference lies in how the open-close-state is stored. The first method internally manages the open-close-state based on the provided identifier. The second one allows for providing a boolean property that stores whether the panel is open. This is useful when creating a dynamic of panels and when it is difficult to create a unique idname.

For the .panel(...) method, a new internal map on Panel is created which keeps track of all the panel states based on the idname. Currently, there is no mechanism for freeing any elements once they have been added to the map. This is unlikely to cause a problem anytime soon, but we might need some kind of garbage collection in the future.

import bpy
from bpy.props import BoolProperty

class LayoutDemoPanel(bpy.types.Panel):
    bl_label = "Layout Panel Demo"
    bl_idname = "SCENE_PT_layout_panel"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "scene"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        
        layout.label(text="Before")

        if panel := layout.panel("my_panel_id", text="Hello World", default_closed=False):
            panel.label(text="Success")

        if panel := layout.panel_prop(scene, "show_demo_panel", text="My Panel"):
            panel.prop(scene, "frame_start")
            panel.prop(scene, "frame_end")
            
        layout.label(text="After")


bpy.utils.register_class(LayoutDemoPanel)
bpy.types.Scene.show_demo_panel = BoolProperty(default=False)

image

This adds a Python API for layout panels that have been introduced in #113584. Two new methods on `UILayout` are added: * `.panel(idname, text="...", default_closed=False) -> Optional[UILayout]` * `.panel_prop(owner, prop_name, text="...") -> Optional[UILayout]` Both create a panel and return `None` if the panel is collapsed. The difference lies in how the open-close-state is stored. The first method internally manages the open-close-state based on the provided identifier. The second one allows for providing a boolean property that stores whether the panel is open. This is useful when creating a dynamic of panels and when it is difficult to create a unique idname. For the `.panel(...)` method, a new internal map on `Panel` is created which keeps track of all the panel states based on the idname. Currently, there is no mechanism for freeing any elements once they have been added to the map. This is unlikely to cause a problem anytime soon, but we might need some kind of garbage collection in the future. ```python import bpy from bpy.props import BoolProperty class LayoutDemoPanel(bpy.types.Panel): bl_label = "Layout Panel Demo" bl_idname = "SCENE_PT_layout_panel" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "scene" def draw(self, context): layout = self.layout scene = context.scene layout.label(text="Before") if panel := layout.panel("my_panel_id", text="Hello World", default_closed=False): panel.label(text="Success") if panel := layout.panel_prop(scene, "show_demo_panel", text="My Panel"): panel.prop(scene, "frame_start") panel.prop(scene, "frame_end") layout.label(text="After") bpy.utils.register_class(LayoutDemoPanel) bpy.types.Scene.show_demo_panel = BoolProperty(default=False) ``` ![image](/attachments/a5324fed-9132-4791-963a-2d605abe0fe5)
Jacques Lucke added 1 commit 2024-01-09 16:38:48 +01:00
Jacques Lucke requested review from Brecht Van Lommel 2024-01-09 17:28:54 +01:00
Jacques Lucke requested review from Campbell Barton 2024-01-09 17:28:54 +01:00
Jacques Lucke requested review from Lukas Tönne 2024-01-09 17:28:54 +01:00
Jacques Lucke requested review from Hans Goudey 2024-01-09 17:28:55 +01:00
Hans Goudey approved these changes 2024-01-09 17:45:32 +01:00
@ -1051,0 +1072,4 @@
"UILayout",
"",
"Sub-layout to put items in. May be none in which case the panel collapsed");
RNA_def_function_return(func, parm);
Member

How about will be None if the panel is collapsed. Seems less vague that way

How about `will be None if the panel is collapsed`. Seems less vague that way
JacquesLucke marked this conversation as resolved
Hans Goudey reviewed 2024-01-09 17:47:47 +01:00
@ -1051,0 +1063,4 @@
func = RNA_def_function(srna, "panel", "rna_uiLayoutPanel");
RNA_def_function_ui_description(
func, "Sub-layout. Items placed in this sublayout are placed into a collapsable panel");
RNA_def_function_flag(func, FUNC_USE_CONTEXT);
Member

Am I missing where the documentation for the property argument to rna_uiLayoutPanel is?

Am I missing where the documentation for the `property` argument to `rna_uiLayoutPanel` is?
Member

I think this gets defined by api_ui_item_rna_common below.

I think this gets defined by `api_ui_item_rna_common` below.
Member

Oh, right. Might be worth adding it manually though, to give it a nice description

Oh, right. Might be worth adding it manually though, to give it a nice description
JacquesLucke marked this conversation as resolved
Lukas Tönne approved these changes 2024-01-09 17:54:37 +01:00

I think manually providing a boolean should be more the exception. Storing the state in the region would be consistent with most panels. I think that requires giving some subpanel idname instead.

I'm not sure if this should be handled through optional keyword arguments or different API functions. In #116646 the issue of adding buttons to the header layout also came up. This would probably be another API function that returns two values. So it would be good to think about what this would look like all together.

There should also be some API docs explaining this mechanism for storing the panel state in a boolean property, it's not obvious.

I think manually providing a boolean should be more the exception. Storing the state in the region would be consistent with most panels. I think that requires giving some subpanel idname instead. I'm not sure if this should be handled through optional keyword arguments or different API functions. In #116646 the issue of adding buttons to the header layout also came up. This would probably be another API function that returns two values. So it would be good to think about what this would look like all together. There should also be some API docs explaining this mechanism for storing the panel state in a boolean property, it's not obvious.
Jacques Lucke added 4 commits 2024-01-10 12:46:04 +01:00
Author
Member

The API now supports creating layout panels using either just an idname or a custom boolean property.

Supporting showing a more complex layout in the panel header requires a bit more refactoring internally. I think it's a good thing to do, but a bit too much for this patch. Nevertheless, here are some ideas for how the API could work. Those ideas don't conflict with the API implemented in this patch, which should remain useful even if an additional API is added.

struct PanelLayout {
    uiLayout *header;
    uiLayout *body;
};

PanelLayout panel = uiLayoutPanel(...);
uiItemL(panel.header, "My Panel", ICON_NONE);
if (panel.body) {
    uiItemL(panel.body, "Label inside panel");
}
panel_header = layout.panel_header(idname)
panel_header.label(text="My Panel")
if panel := panel_header.body():
    panel.label(text="Label inside panel")

# Same with `.panel_header_prop(...)`
The API now supports creating layout panels using either just an idname or a custom boolean property. Supporting showing a more complex layout in the panel header requires a bit more refactoring internally. I think it's a good thing to do, but a bit too much for this patch. Nevertheless, here are some ideas for how the API could work. Those ideas don't conflict with the API implemented in this patch, which should remain useful even if an additional API is added. ```cpp struct PanelLayout { uiLayout *header; uiLayout *body; }; PanelLayout panel = uiLayoutPanel(...); uiItemL(panel.header, "My Panel", ICON_NONE); if (panel.body) { uiItemL(panel.body, "Label inside panel"); } ``` ```python panel_header = layout.panel_header(idname) panel_header.label(text="My Panel") if panel := panel_header.body(): panel.label(text="Label inside panel") # Same with `.panel_header_prop(...)` ```
Brecht Van Lommel requested changes 2024-01-10 17:39:40 +01:00
@ -1051,0 +1084,4 @@
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED);
api_ui_item_common_text(func);
RNA_def_boolean(func,
"open_by_default",

Why not match the naming and default value of regular panels, so default_closed=False?

Mainly the different default behavior seems confusing to me.

Why not match the naming and default value of regular panels, so `default_closed=False`? Mainly the different default behavior seems confusing to me.
JacquesLucke marked this conversation as resolved
@ -1051,0 +1099,4 @@
RNA_def_function_ui_description(
func,
"Similar to `.panel(...)` but instead of storing whether it is open or closed in the "
"region, it is stored in the provided boolean property. This can be used when creating a "

To me the reason would be more:

This should be used when multiple instances of the same panel can exist. For example one for every item in a collection property or list.

Generating a unique idname is not difficult, just not advisable for such cases.

To me the reason would be more: ``` This should be used when multiple instances of the same panel can exist. For example one for every item in a collection property or list. ``` Generating a unique idname is not difficult, just not advisable for such cases.
JacquesLucke marked this conversation as resolved
panel_header = layout.panel_header(idname)
panel_header.label(text="My Panel")
if panel := panel_header.body():
    panel.label(text="Label inside panel")

# Same with `.panel_header_prop(...)`

I think just returning a tuple with two layouts would be simpler, where the body layout can be None if closed.

> ```python > panel_header = layout.panel_header(idname) > panel_header.label(text="My Panel") > if panel := panel_header.body(): > panel.label(text="Label inside panel") > > # Same with `.panel_header_prop(...)` > ``` I think just returning a tuple with two layouts would be simpler, where the body layout can be None if closed.
Author
Member

I haven't seen that before in Blender. How does one return a new tuple from a RNA function?

I haven't seen that before in Blender. How does one return a new tuple from a RNA function?

See rna_Object_ray_cast for an example.

See `rna_Object_ray_cast` for an example.
Jacques Lucke added 3 commits 2024-01-11 11:07:58 +01:00
Author
Member

Thanks. Yes it seems fine to return both layouts in a tuple then.

I do still wonder whether you have an opinion on the two questions mentioned in the patch description.

Thanks. Yes it seems fine to return both layouts in a tuple then. I do still wonder whether you have an opinion on the two questions mentioned in the patch description.

Questions:

  • Should we enforce rules for the idname, such as having an __LP__ (LP = layout panel) infix? Can be a bit annoying sometimes, but might help avoiding name collisions by forcing addon developers to have a separate prefix (which could be the addon name) and a suffix.
  • Should the open-close-state map be stored in the ARegion or Panel? Both could work, but I found the live-time a bit less predictable so far, but maybe that is because I mostly tried to handle instanced panels, which are more complex, so far.

I think the simplest thing from the API point of view would be to store it in the panel, which then also means you don't need strict idnames because they are automatically scoped to avoid conflicts.

It's not clear to me why there would be a difference in lifetime depending if it's in the region or panel.

> Questions: > * Should we enforce rules for the idname, such as having an `__LP__` (LP = layout panel) infix? Can be a bit annoying sometimes, but might help avoiding name collisions by forcing addon developers to have a separate prefix (which could be the addon name) and a suffix. > * Should the open-close-state map be stored in the `ARegion` or `Panel`? Both could work, but I found the live-time a bit less predictable so far, but maybe that is because I mostly tried to handle instanced panels, which are more complex, so far. I think the simplest thing from the API point of view would be to store it in the panel, which then also means you don't need strict idnames because they are automatically scoped to avoid conflicts. It's not clear to me why there would be a difference in lifetime depending if it's in the region or panel.
Brecht Van Lommel approved these changes 2024-01-11 16:17:00 +01:00
Jacques Lucke added 2 commits 2024-01-11 18:31:18 +01:00
buildbot/vexp-code-patch-lint Build done. Details
buildbot/vexp-code-patch-linux-x86_64 Build done. Details
buildbot/vexp-code-patch-darwin-x86_64 Build done. Details
buildbot/vexp-code-patch-windows-amd64 Build done. Details
buildbot/vexp-code-patch-darwin-arm64 Build done. Details
buildbot/vexp-code-patch-coordinator Build done. Details
3112936b62
move layout panel state from ARegion to Panel
Author
Member

@blender-bot build

@blender-bot build
Jacques Lucke merged commit 8896446f7e into main 2024-01-11 19:08:54 +01:00
Jacques Lucke deleted branch layout-panel-python 2024-01-11 19:08:56 +01:00
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
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
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
4 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#116949
No description provided.