Skip to content

Pythonic begin/end interface (adding "with" support) #255

Closed

Description

I'm wondering if you would be open to augmenting some imgui return values with context manager (with block ...) support. This would allow exceptions to propagate normally in imgui code and make forgetting to imgui.end*() or accidentally calling imgui.end*() when you aren't supposed to impossible.

The issue:

def open_file_window():
    imgui.begin("Example Window")
    if imgui.button('Potentially raises..'):
        raise OSError('could not open file...')
    imgui.end()

The above code will cause a crash when called because the exception prevents the imgui.end from executing. It is not uncommon for the location where an exception is generated to be unequipped to actually handle the exception, so I would like to be able to let the exception propagate up, where I could then catch it and e.g. display a friendly error to the user in a designated error window. However, this is currently not possible because letting the exception propagate prevents the end call from running, causing a crash when the frame ends.

Desired solution:
Make the return value of imgui.begin* calls have __enter__ and __exit__ methods with the __exit__ calling the corresponding imgui.end* function so that the following would be possible:

def open_file_window():
    with imgui.begin("Example Window"):
        if imgui.button('Potentially raises..'):
            raise OSError('could not open file...')

Notice how there is no need to call imgui.end() in the above code, the context manager does it automatically, whether an exception is raised or not. This ensures that all begins have ends, preventing the imgui stack from becoming unbalanced.

Potential implementation
Currently, I count 13 imgui.begin* functions with the following return values:

  1. begin -> tuple[expanded: bool, opened: bool]
  2. begin_child -> visible: bool
  3. begin_tooltip -> None
  4. begin_main_menu_bar -> opened: bool x
  5. begin_menu_bar -> opened: bool x
  6. begin_menu -> opened: bool x
  7. begin_popup -> opened: bool x
  8. begin_popup_modal -> tuple[opened: bool, visible: bool] x
  9. begin_popup_context_item -> opened: bool x
  10. begin_popup_context_window -> opened: bool x
  11. begin_drag_drop_source -> dragging: bool x
  12. begin_drag_drop_target -> hovered: bool x
  13. begin_group -> None

All of these need to be closed with the corresponding end function, with all of the ones 4 - 12 (marked with x) needing to be ended conditionally only if the opened/dragging/hovered variable is True. There are 3 types of existing return values here: None, bool, or a tuple. The goal is to change the return value only in a way that is fully backwards compatible, so that people may continue manually ending if they choose to. We could use NamedTuple or a C struct for any of these, I'll just use NamedTuple for example.

  1. Case tuple: Replace with a NamedTuple that has enter and exit methods
class BeginReturn(NamedTuple):
    expanded: bool
    opened: bool

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        imgui.end()

As a bonus, this makes code much easier to read since the tuple elements are given names

  1. Case bool: Replace with NamedTuple that has enter, exit, and bool methods, and previous return value as attribute.
class BeginChildReturn(NamedTuple):
    visible: bool

    def __bool__(self):
        return self.visible

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        imgui.end_child()
  1. Case None: Replace with empty NamedTuple that has enter, exit.
class BeginToolTip(NamedTuple):
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        imgui.end_tooltip()
  1. Case where something needs to be closed only if opened/dragging/hovered was True: same as previous but check value in the exit method
class BeginMainMenuBar(NamedTuple):
    opened: bool

    def __bool__(self):
        return self.opened

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.opened:
            imgui.close_main_menu_bar()

Example client usages

Continues to work:

imgui.begin("Example: child region")
imgui.begin_child("region", 150, -50, border=True)
imgui.text("inside region")
imgui.end_child()
imgui.text("outside region")
imgui.end()

Can be replaced by:

with imgui.begin("Example: child region"):
    with imgui.begin_child("region", 150, -50, border=True):
        imgui.text("inside region")
    imgui.text("outside region")

Continues to work:

if imgui.begin_main_menu_bar():
    # first menu dropdown
    if imgui.begin_menu('File', True):
        imgui.menu_item('New', 'Ctrl+N', False, True)
        imgui.menu_item('Open ...', 'Ctrl+O', False, True)
        # submenu
        if imgui.begin_menu('Open Recent', True):
            imgui.menu_item('doc.txt', None, False, True)
            imgui.end_menu()
        imgui.end_menu()
    imgui.end_main_menu_bar()

Can be replaced by:

with imgui.begin_main_menu_bar() as bar:
    if bar.opened:
        # first menu dropdown
        with imgui.begin_menu('File', True) as file_menu:
            if file_menu.opened:
                imgui.menu_item('New', 'Ctrl+N', False, True)
                imgui.menu_item('Open ...', 'Ctrl+O', False, True)
                # submenu
                with imgui.begin_menu('Open Recent', True) as open_recent_menu:
                    if open_recent_menu.opened:
                        imgui.menu_item('doc.txt', None, False, True)

Continues to work:

imgui.begin("Example: simple popup modal")
if imgui.button("Open Modal popup"):
    imgui.open_popup("select-popup")
    imgui.same_line()
    if imgui.begin_popup_modal("select-popup")[0]:
        imgui.text("Select an option:")
        imgui.separator()
        imgui.selectable("One")
        imgui.selectable("Two")
        imgui.selectable("Three")
        imgui.end_popup()
imgui.end()

Can be replaced with:

with imgui.begin("Example: simple popup modal")
    if imgui.button("Open Modal popup"):
        imgui.open_popup("select-popup")
    imgui.same_line()
    with imgui.begin_popup_modal("select-popup") as popup:
        if popup.opened:
            imgui.text("Select an option:")
            imgui.separator()
            imgui.selectable("One")
            imgui.selectable("Two")
            imgui.selectable("Three")

I am aware that this effectively doubles the indentation for those items that are conditionally closed, which is something to consider. If this was deemed unacceptable, we could additionally add a custom exception ImguiBreakWithStatement that could be used like:

class BeginReturn(NamedTuple):
    expanded: bool
    opened: bool

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        imgui.end()
        return exc_type is ImguiBreakWithStatement # if return value is truthy, exception is not reraised
with imgui.begin("Example: simple popup modal")
    if imgui.button("Open Modal popup"):
        imgui.open_popup("select-popup")
    imgui.same_line()
    with imgui.begin_popup_modal("select-popup") as popup:
        if not popup.opened:
            raise ImguiBreakWithStatement
        imgui.text("Select an option:")
        imgui.separator()
        imgui.selectable("One")
        imgui.selectable("Two")
        imgui.selectable("Three")

This would remove extra level of indentation at the cost of introducing this idiom.

What are you thoughts on this proposal? I would be happy to help implement it if you were open to it.

Activity

  1. KinoxKlark commented on Feb 1, 2022

    @KinoxKlark
    Member

    Yes, I agree, this is a great idea, thanks for the suggestion.

    Unfortunately, I won't be able to invest the time needed for this dev in the coming days. But if you feel to implement it, I'll accept the PR :)

  2. inequity commented on Feb 8, 2022

    @inequity

    @KinoxKlark Maybe add 'todo' to this issue if you like the idea

  3. added
    todo
    on Feb 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussiontodo

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions