Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

kit once

Preetham Pemmasanieeb4cfff3552
diff --git a/bindings/python/CMakeLists.txt b/bindings/python/CMakeLists.txt
index 3136a83..5b459db 100644
--- a/bindings/python/CMakeLists.txt
+++ b/bindings/python/CMakeLists.txt
@@ -21,23 +21,18 @@ set_target_properties(buipy PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bindings/python$<0:>
)
-# Dear ImGui (bindings/imgui) for Python: the _buiimgui extension behind blenderui.imgui /
-# bui.imgui. Its API is generated from imgui.h (src/buiimgui_gen.inc, bindings/imgui/gen).
+# Dear ImGui (bindings/imgui) for Python: blenderui.imgui / bui.imgui. Its API is generated from
+# imgui.h (src/buiimgui_gen.inc, bindings/imgui/gen). It is compiled INTO buipy rather than built
+# as a second extension: every Python extension links the kit statically, and two copies in one
+# process means two sets of state and, on macOS, the Objective-C classes of kit_window_cocoa.m
+# registered twice ("Class BUIKitView is implemented in both ..."). buipy.imgui_module() hands
+# out the module; with ImGui off nothing of it is in buipy. (CMake links as C++ for the .cpp.)
if(TARGET bui_cimgui)
- Python3_add_library(_buiimgui MODULE WITH_SOABI src/buiimgui_module.cpp)
- target_link_libraries(_buiimgui PRIVATE bui_cimgui)
+ target_sources(buipy PRIVATE src/buiimgui_module.cpp)
+ target_link_libraries(buipy PRIVATE bui_cimgui)
+ target_compile_definitions(buipy PRIVATE BUI_PY_IMGUI=1)
if(MSVC)
- target_compile_options(_buiimgui PRIVATE /bigobj)
- endif()
- set_target_properties(_buiimgui PROPERTIES
- LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bindings/python$<0:>
- RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bindings/python$<0:>
- )
- if(MINGW) # Python 3.8+ does not look on PATH for a module's DLLs: carry the MinGW runtime inside
- target_link_options(_buiimgui PRIVATE -static-libgcc -static)
- endif()
- if(SKBUILD)
- install(TARGETS _buiimgui LIBRARY DESTINATION . RUNTIME DESTINATION .)
+ set_source_files_properties(src/buiimgui_module.cpp PROPERTIES COMPILE_OPTIONS /bigobj)
endif()
endif()
@@ -130,7 +125,7 @@ if(BUI_BUILD_TESTS)
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_video.py
)
set_tests_properties(buipy_video PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")
- if(TARGET _buiimgui)
+ if(TARGET bui_cimgui)
add_test(
NAME buipy_imgui
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_imgui.py
diff --git a/bindings/python/bui/__init__.py b/bindings/python/bui/__init__.py
index 1134dbf..ba39e4a 100644
--- a/bindings/python/bui/__init__.py
+++ b/bindings/python/bui/__init__.py
@@ -195,8 +195,6 @@ def set_theme(name: str = "dark") -> None:
from bui import theme as _theme
buipy.kit_set_theme(str(name))
_theme._sync()
- if "_buiimgui" in sys.modules: # the Dear ImGui extension has its own kit
- sys.modules["_buiimgui"].set_theme(str(name))
def theme_name() -> str:
diff --git a/bindings/python/bui/imgui.py b/bindings/python/bui/imgui.py
index 520d43a..e6dc848 100644
--- a/bindings/python/bui/imgui.py
+++ b/bindings/python/bui/imgui.py
@@ -38,9 +38,17 @@ from __future__ import annotations
import ctypes
-import _buiimgui
-from _buiimgui import * # noqa: F401,F403 (functions, types, constants)
-from _buiimgui import App
+import buipy
+
+try:
+ # Dear ImGui lives inside buipy (one kit per process); this is its `_buiimgui` module
+ _buiimgui = buipy.imgui_module()
+except AttributeError:
+ raise ImportError(
+ "this buipy was built without Dear ImGui (CMake option BUI_BUILD_IMGUI)") from None
+
+from _buiimgui import * # noqa: E402,F401,F403 (functions, types, constants)
+from _buiimgui import App # noqa: E402
__all__ = [n for n in dir(_buiimgui) if not n.startswith("_")] + [
"run", "HeadlessApp", "im_col32", "payload_data", "BK_SHIFT", "BK_CTRL", "BK_ALT"]
diff --git a/bindings/python/src/buiimgui_module.cpp b/bindings/python/src/buiimgui_module.cpp
index ce3efb9..cb74013 100644
--- a/bindings/python/src/buiimgui_module.cpp
+++ b/bindings/python/src/buiimgui_module.cpp
@@ -3,6 +3,10 @@
// HeadlessApp). The API itself is generated from imgui.h (buiimgui_gen.inc); this file
// adds the BUI app (window or headless) and the module init.
//
+// This is not a separate extension: it is compiled into `buipy` so the process holds ONE copy
+// of the kit (one set of Cocoa classes, one NSApp, one theme). buipy.imgui_module() creates
+// the `_buiimgui` module object on first use.
+//
// SPDX-License-Identifier: GPL-2.0-or-later
#include "buiimgui_rt.h"
@@ -318,7 +322,7 @@ static PyObject* bi_set_scale(PyObject*, PyObject* args)
Py_RETURN_NONE;
}
-// This extension carries its own copy of the kit: bui.set_theme() forwards here.
+// The kit is shared with buipy: this is the same theme bui.set_theme() sets.
extern "C" int BK_set_theme(const char* name);
extern "C" const char* BK_theme_name(void);
@@ -383,7 +387,10 @@ static struct PyModuleDef bi_moduledef = {
-1, nullptr,
};
-PyMODINIT_FUNC PyInit__buiimgui(void)
+// The `_buiimgui` module object, created once (its types are process-wide).
+static PyObject* bi_module = nullptr;
+
+static PyObject* bi_create_module(void)
{
PyObject* m = PyModule_Create(&bi_moduledef);
if (m == nullptr)
@@ -411,3 +418,35 @@ PyMODINIT_FUNC PyInit__buiimgui(void)
PyModule_AddStringConstant(m, bi_str_consts[i][0], bi_str_consts[i][1]);
return m;
}
+
+// buipy.imgui_module(): the `_buiimgui` module, created on first call (a program that never
+// touches Dear ImGui does not pay for its 400 functions and types) and registered in
+// sys.modules so `import _buiimgui` keeps working.
+static PyObject* bi_imgui_module(PyObject*, PyObject*)
+{
+ if (bi_module == nullptr)
+ {
+ PyObject* m = bi_create_module();
+ if (m == nullptr)
+ return nullptr;
+ if (PyDict_SetItemString(PyImport_GetModuleDict(), "_buiimgui", m) < 0)
+ {
+ Py_DECREF(m);
+ return nullptr;
+ }
+ bi_module = m;
+ }
+ Py_INCREF(bi_module);
+ return bi_module;
+}
+
+static PyMethodDef bi_buipy_methods[] = {
+ { "imgui_module", bi_imgui_module, METH_NOARGS, "imgui_module() -> the Dear ImGui module (bui.imgui)" },
+ { nullptr, nullptr, 0, nullptr },
+};
+
+// Called by PyInit_buipy (BUI_PY_IMGUI: the build has Dear ImGui).
+extern "C" int buipy_imgui_init(PyObject* buipy)
+{
+ return PyModule_AddFunctions(buipy, bi_buipy_methods);
+}
diff --git a/bindings/python/src/buipy_module.c b/bindings/python/src/buipy_module.c
index 19aa213..97d0640 100644
--- a/bindings/python/src/buipy_module.c
+++ b/bindings/python/src/buipy_module.c
@@ -1302,6 +1302,9 @@ BuiRaster *buipy_raster_of(PyObject *obj)
int buipy_kit_init(PyObject *module); /* buipy_kit.c */
int buipy_video_init(PyObject *module); /* buipy_video.c */
+#ifdef BUI_PY_IMGUI
+int buipy_imgui_init(PyObject *module); /* buiimgui_module.cpp: Dear ImGui, in the same binary */
+#endif
PyMODINIT_FUNC PyInit_buipy(void)
{
@@ -1313,7 +1316,11 @@ PyMODINIT_FUNC PyInit_buipy(void)
return NULL;
}
if (PyModule_AddObjectRef(m, "Raster", (PyObject *)&BuiPyRaster_Type) < 0 ||
- buipy_kit_init(m) < 0 || buipy_video_init(m) < 0)
+ buipy_kit_init(m) < 0 || buipy_video_init(m) < 0
+#ifdef BUI_PY_IMGUI
+ || buipy_imgui_init(m) < 0
+#endif
+ )
{
Py_DECREF(m);
return NULL;
diff --git a/bindings/python/tests/test_imgui.py b/bindings/python/tests/test_imgui.py
index 716f595..cb2da1d 100644
--- a/bindings/python/tests/test_imgui.py
+++ b/bindings/python/tests/test_imgui.py
@@ -10,14 +10,17 @@ ctest (buipy_imgui).
SPDX-License-Identifier: GPL-2.0-or-later
"""
+import glob
import math
import os
+import subprocess
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import bui # noqa: E402,F401 (locates the build tree)
+import buipy # noqa: E402
import blenderui.imgui as imgui # noqa: E402
import bui.imgui as bui_imgui # noqa: E402
@@ -183,7 +186,8 @@ class ImGuiTest(unittest.TestCase):
self.assertEqual(imgui.WINDOW_NO_TITLE_BAR, imgui.ImGuiWindowFlags_NoTitleBar)
self.assertEqual(imgui.KEY_A, imgui.ImGuiKey_A)
self.assertEqual(imgui.COL_TEXT, 0)
- import _buiimgui
+ import _buiimgui # the module buipy.imgui_module() creates, also registered by name
+ self.assertIs(_buiimgui, imgui._buiimgui)
self.assertGreater(_buiimgui._sizeof("ImGuiIO"), 1000)
self.assertIn("ImGui::Button", imgui.button.__doc__)
self.assertEqual(imgui.im_col32(255, 0, 0), 0xFF0000FF)
@@ -427,5 +431,50 @@ class ImGuiTest(unittest.TestCase):
self.app.render(2)
+class OneKitTest(unittest.TestCase):
+ """Dear ImGui is compiled into buipy: a process holds ONE copy of the kit.
+
+ Two extensions linking the kit statically registered the Cocoa classes of
+ kit_window_cocoa.m twice on macOS ("Class BUIKitView is implemented in both ...") and
+ kept two copies of the kit's state elsewhere."""
+
+ def test_no_second_extension(self):
+ here = os.path.dirname(os.path.abspath(buipy.__file__))
+ self.assertEqual(glob.glob(os.path.join(here, "_buiimgui*")), [])
+
+ def test_kit_state_is_shared(self):
+ # a second kit would keep its own theme: setting it through one is seen through the other
+ was = buipy.kit_theme_name()
+ other = "light" if was == "dark" else "dark"
+ try:
+ imgui.set_theme(other)
+ self.assertEqual(buipy.kit_theme_name(), other)
+ bui.set_theme(was)
+ self.assertEqual(imgui.theme_name(), was)
+ finally:
+ buipy.kit_set_theme(was)
+
+ def test_loading_both_registers_nothing_twice(self):
+ code = "import buipy, blenderui.imgui, sys; sys.exit(0 if 'imgui_module' in dir(buipy) else 1)"
+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(sys.path))
+ r = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertNotIn("is implemented in both", r.stderr) # the Objective-C runtime's warning
+
+ @unittest.skipUnless(sys.platform == "darwin", "Cocoa host classes")
+ def test_cocoa_classes_come_from_buipy(self):
+ import ctypes
+ objc = ctypes.CDLL("/usr/lib/libobjc.A.dylib")
+ objc.objc_getClass.restype = ctypes.c_void_p
+ objc.objc_getClass.argtypes = [ctypes.c_char_p]
+ objc.class_getImageName.restype = ctypes.c_char_p
+ objc.class_getImageName.argtypes = [ctypes.c_void_p]
+ for name in (b"BUIKitNSWindow", b"BUIKitView", b"BUIKitWindowDelegate", b"BUIKitAppDelegate"):
+ cls = objc.objc_getClass(name)
+ self.assertTrue(cls, name)
+ self.assertEqual(os.path.realpath(objc.class_getImageName(cls).decode()),
+ os.path.realpath(buipy.__file__), name)
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/pyproject.toml b/pyproject.toml
index 26338ef..0d21954 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -52,9 +52,8 @@ blenderui-tk = "bui.tksyntax.__main__:main" # blenderui-tk app.py == python -m
[tool.scikit-build]
minimum-version = "build-system.requires"
cmake.version = ">=3.20"
-# the core extension and Dear ImGui's (_buiimgui, behind blenderui.imgui): both are
-# installed by bindings/python/CMakeLists.txt, so both must be built
-build.targets = ["buipy", "_buiimgui"]
+# one extension: buipy, with Dear ImGui (blenderui.imgui) compiled in so a process holds one kit
+build.targets = ["buipy"]
wheel.packages = [] # CMake installs bui/, blenderui/ and buipy
wheel.exclude = ["**/__pycache__/**"]
sdist.exclude = ["reference/", "build*/", ".github/", "**/__pycache__/", "*.pyd", "*.so"]