Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: linux port
Preetham Pemmasani9e29320257e1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ebd2b91..71b7242 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,7 @@ All notable changes to **blenderui** (BUI). The format follows- **Threshold:** the movement inside the drag threshold is ignored, so values don't jump when a drag starts.- **Clicks:** Ctrl+click types a value. A drag that changed nothing counts as a click.- **Escape** cancels a drag and restores the values.+- **Dropdown chevrons** are drawn as thick as the shader's menu triangle bars.- **Checkboxes:** the checkmark is the one Blender's widget shader draws (two 0.14-unit bars, `ROUNDBOX_TRIA_CHECK`), so it fits inside the box. Label text starts right after the box.- **Labels without icons** are inset one pixel instead of a text margin (`BUT_NO_TEXT_PADDING`), so right-aligned property labels line up as in Blender.- **`Split`** is its own `split` layout, with its columns `columnspace` (0.4 units) apart, as `Layout::split` spaces them.@@ -51,10 +52,30 @@ All notable changes to **blenderui** (BUI). The format follows- header widgets start at `panel_label_offset`, and the title follows them.### Added (components)+- **`NodeEditor` / `Node`** (`kit/intern/kit_nodes.c`): Blender's node editor canvas, ported from `space_node` (`node_draw.cc`, `drawnode.cc`, `node_select.cc`, `node_relationships.cc`) and `view2d_ops.cc`.+ - **Drawing:**+ - nodes with headers in the theme's node-class colors and outlines for selected and active nodes;+ - sockets colored by type;+ - number fields on unlinked inputs;+ - bezier links (`noodle_curving` 4), colored by socket type;+ - Blender's dot grid.+ - **Editing:** select (Shift toggles), move (Ctrl snaps), box select, drag sockets to link, drag a linked input to pick its link up, Ctrl+RMB to cut links, drag input fields to change values.+ - **View and keys:** MMB pans and Ctrl+MMB zooms; the wheel zooms about the cursor (Ctrl/Shift+wheel pans). X / Delete deletes, A / Alt+A selects or deselects all, H collapses, Home frames all.+- **`Area` / `AreaHeader`**: an editor area. A 1.3-unit header (`HEADERY`) with the editor-type menu, items laid out from `UI_HEADER_OFFSET`, and `Spacer()`s pushing the rest right; the editor fills the space below.+- **Middle and right mouse buttons for editors:** classes flagged `CLS_BUTTONS` get middle and right presses as press, drag and release, with `BK_BUTTON2` / `BK_BUTTON3` in the event's modifiers.- **`Sidebar`**: an editor's N-panel. Panels with a `category` show under vertical tabs with rotated labels (`panel_category_tabs_draw_all`); Ctrl+Wheel cycles them.- **`fill=True`**: in a column, the component takes the spare height, as a region fills its area.- **`tools/blender_compare.py`**: renders BUI's version of a piece of Blender's UI next to a capture from a real Blender. **`tools/png_pixels.py`** reads pixels from PNGs.+### Added (platforms)+- **Linux: native windows on X11** (`kit/intern/kit_window_x11.c`, the same `BK_window_*` API as Win32). Wayland sessions run it through XWayland.+ - **Input:** button and key mapping after Blender's `GHOST_SystemX11`; key repeat filtered.+ - **Window:** `Xft.dpi` scale, `CLIPBOARD` copy and paste, cursors (hidden while scrubbing), pointer warp, size hints.+ - **Loop:** timers, frame pacing and a pipe for cross-thread wakes, in one `select()` loop.+ - **Drawing:** damaged rectangles are put with `XPutImage`.+- The window host is now split by platform: `kit_window_win32.c`, `kit_window_x11.c` and `kit_window_null.c` (others).+- **The C libraries and the Python module build on Linux:** missing POSIX headers fixed, `libm` linked, position-independent code. All C and Python suites pass on Linux (Kali under WSLg), including a new native-window smoke test (`tests/window_smoke.c`).+### Added (JavaScript: `@blender-ui/native` 0.2.0, `@blender-ui/react` 0.1.0)- **`@blender-ui/native`** (`bindings/node`, napi-rs crate `blenderui-node`): BUI from JavaScript in native windows, GPUIX style, on **Node.js and Bun**.- A DOM-like API: `createElement`, `setAttribute`, `appendChild`, `insertBefore`, `addEventListener` (events bubble; `stopPropagation` works), `requestAnimationFrame`, `getBoundingClientRect`, `screenshot`.diff --git a/CMakeLists.txt b/CMakeLists.txtindex de59e88..f5f8843 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -15,6 +15,8 @@ file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/bindings/python/bui/_version.py" _bui_REGEX "^__version__")string(REGEX MATCH "[0-9]+[.][0-9]+[.][0-9]+" BUI_VERSION "${_bui_version_line}")project(bui LANGUAGES C CXX VERSION ${BUI_VERSION})+# static libraries end up in shared modules (Python, Node) on Linux and macOS+set(CMAKE_POSITION_INDEPENDENT_CODE ON)option(BUI_BUILD_TESTS "Build BUI test executables" ON)option(BUI_BUILD_EXAMPLES "Build BUI example applications" OFF)@@ -56,6 +58,11 @@ if(BUI_BUILD_TESTS)enable_testing()add_subdirectory(core/tests)add_subdirectory(gpu/tests)+ # the native window host (Win32 / X11): exits 77 (skipped) without a display+ add_executable(bui_window_smoke tests/window_smoke.c)+ target_link_libraries(bui_window_smoke PRIVATE bui::kit)+ add_test(NAME bui_window_smoke COMMAND bui_window_smoke)+ set_tests_properties(bui_window_smoke PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)endif()if(BUI_BUILD_PYTHON_BINDINGS)diff --git a/bindings/python/CMakeLists.txt b/bindings/python/CMakeLists.txtindex 794c14d..3f0a62b 100644--- a/bindings/python/CMakeLists.txt+++ b/bindings/python/CMakeLists.txt@@ -77,6 +77,12 @@ if(BUI_BUILD_TESTS)WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})set_tests_properties(buipy_components PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")+ add_test(+ NAME buipy_nodes+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_nodes.py+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}+ )+ set_tests_properties(buipy_nodes PROPERTIES ENVIRONMENT "PYTHONPATH=${BUIPY_TEST_PYTHONPATH}")add_test(NAME buipy_tk_compatCOMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_tk_compat.pydiff --git a/bindings/python/bui/components/__init__.py b/bindings/python/bui/components/__init__.pyindex 438b576..75a87a0 100644--- a/bindings/python/bui/components/__init__.py+++ b/bindings/python/bui/components/__init__.py@@ -26,11 +26,12 @@ SPDX-License-Identifier: GPL-2.0-or-later"""from bui.components.app import App-from bui.components.containers import (Box, Column, Grid, Panel, Row, ScrollView, Sidebar, SideTabs,+from bui.components.containers import (Area, AreaHeader, Box, Column, Grid, Panel, Row, ScrollView, Sidebar, SideTabs,Split, Tabs, VectorField)from bui.components.core import Component, ValueComponent, unitfrom bui.components.editors import (ColorRamp, ColorStop, CurveMapping, Histogram, NormalBall,Popover)+from bui.components.nodes import Node, NodeEditorfrom bui.components.menus import Menu, MenuBar, MenuButton, MenuItem, PieMenufrom bui.components.templates import IDSelector, PathFieldfrom bui.components.views import GridView, ListView, TreeItem, TreeView@@ -42,7 +43,7 @@ from bui.components.widgets import (Button, Checkbox, ColorSwatch, Decorator, Dr__all__ = ["App", "Component", "ValueComponent", "unit",# layout- "Column", "Row", "Split", "Grid", "Box", "Panel", "Tabs", "SideTabs", "Sidebar", "ScrollView",+ "Column", "Row", "Split", "Grid", "Box", "Panel", "Tabs", "SideTabs", "Sidebar", "ScrollView", "Area", "AreaHeader","VectorField",# widgets"Label", "Separator", "Spacer", "ProgressBar", "Button", "IconButton", "Toggle",@@ -54,5 +55,5 @@ __all__ = ["Menu", "MenuItem", "MenuButton", "MenuBar", "PieMenu", "Popover",# editors & templates"ColorRamp", "ColorStop", "CurveMapping", "NormalBall", "Histogram",- "IDSelector", "PathField",+ "IDSelector", "PathField", "NodeEditor", "Node",]diff --git a/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc b/bindings/python/bui/components/__pycache__/__init__.cpython-314.pycindex 200373d..930bf50 100644Binary files a/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc and b/bindings/python/bui/components/__pycache__/__init__.cpython-314.pyc differdiff --git a/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc b/bindings/python/bui/components/__pycache__/containers.cpython-314.pycindex d40bf8a..ae25aa4 100644Binary files a/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc and b/bindings/python/bui/components/__pycache__/containers.cpython-314.pyc differdiff --git a/bindings/python/bui/components/__pycache__/nodes.cpython-314.pyc b/bindings/python/bui/components/__pycache__/nodes.cpython-314.pycnew file mode 100644index 0000000..c43cf53Binary files /dev/null and b/bindings/python/bui/components/__pycache__/nodes.cpython-314.pyc differdiff --git a/bindings/python/bui/components/containers.py b/bindings/python/bui/components/containers.pyindex 007cefd..7c9ee69 100644--- a/bindings/python/bui/components/containers.py+++ b/bindings/python/bui/components/containers.py@@ -255,3 +255,71 @@ class VectorField(Column):def _field_changed(self, _v):if self.on_change is not None:self.on_change(self.value)+++# Blender's editor-type menu (ED_area_type_hud / space_type_menu): groups of (name, icon).+EDITOR_TYPES = [+ [("3D Viewport", "VIEW3D"), ("Image Editor", "IMAGE"), ("UV Editor", "UV"),+ ("Compositor", "NODE_COMPOSITING"), ("Texture Node Editor", "NODE_TEXTURE"),+ ("Geometry Node Editor", "GEOMETRY_NODES"), ("Shader Editor", "NODE_MATERIAL"),+ ("Video Sequencer", "SEQUENCE"), ("Movie Clip Editor", "TRACKER")],+ [("Dope Sheet", "ACTION"), ("Timeline", "TIME"), ("Graph Editor", "GRAPH"),+ ("Drivers", "DRIVER"), ("Nonlinear Animation", "NLA")],+ [("Text Editor", "TEXT"), ("Python Console", "CONSOLE"), ("Info", "INFO")],+ [("Outliner", "OUTLINER"), ("Properties", "PROPERTIES"), ("File Browser", "FILEBROWSER"),+ ("Asset Browser", "ASSET_MANAGER"), ("Spreadsheet", "SPREADSHEET"),+ ("Preferences", "PREFERENCES")],+]+++class AreaHeader(Component):+ """An editor's header region (``ED_region_header_layout``): 1.3 units tall,+ items left to right from the corner offset; a ``Spacer()`` pushes the rest+ to the right (``layout.separator_spacer()``)."""++ TYPE = "areaheader"++ def __init__(self, *children: Component, **kw):+ super().__init__(**kw)+ for c in children:+ c.weight = 0 if not isinstance(c, _spacer_type()) else c.weight+ self.add(*children)+++def _spacer_type():+ from .widgets import Spacer+ return Spacer+++class Area(Column):+ """A Blender area: the header with the editor-type menu, then the editor.++ Area("Geometry Node Editor", NodeEditor(...), header=[MenuButton("View", [...])],+ on_editor=lambda name: ...)+ """++ def __init__(self, editor: str, body: Component, *, header: Sequence[Component] = (),+ on_editor: Optional[Callable[[str], None]] = None, **kw):+ from .menus import MenuButton, MenuItem+ self.editor, self.on_editor = editor, on_editor+ icon = next((i for group in EDITOR_TYPES for n, i in group if n == editor), "QUESTION")+ items = []+ for g, group in enumerate(EDITOR_TYPES):+ if g:+ items.append(None)+ for name, ic in group:+ items.append(MenuItem(name, (lambda n=name: self._pick(n)), icon=ic,+ checked=None))+ self.editor_button = MenuButton("", items, icon=icon, description="Editor Type")+ self.header = AreaHeader(self.editor_button, *header)+ body.set("fill", True)+ kw.setdefault("fill", True) # an area fills its place in the screen+ super().__init__(self.header, body, spacing=0, **kw)+ self.body = body++ def _pick(self, name: str) -> None:+ self.editor = name+ icon = next((i for group in EDITOR_TYPES for n, i in group if n == name), "QUESTION")+ self.editor_button.set("icon", icon)+ if self.on_editor is not None:+ self.on_editor(name)diff --git a/bindings/python/bui/components/nodes.py b/bindings/python/bui/components/nodes.pynew file mode 100644index 0000000..b7a92f0--- /dev/null+++ b/bindings/python/bui/components/nodes.py@@ -0,0 +1,214 @@+"""The node editor: Blender's node canvas (space_node), drawn and driven in C.++ a = Node("Value", outputs=[("Value", "float")], location=(-200, 0), kind="input")+ b = Node("Math", inputs=[("Value", "float", 0.5), ("Value", "float", 0.5)],+ outputs=[("Value", "float")], location=(0, 0), kind="converter")+ NodeEditor([a, b], links=[(a, 0, b, 0)], fill=True)++Interactions follow Blender:+- LMB on a node selects it (Shift toggles), and dragging moves the selection (Ctrl snaps).+- LMB drag on empty space box-selects; a click there deselects.+- LMB drag from a socket makes a link. Dragging from a linked input picks its link up.+- Ctrl+RMB drag cuts links; MMB pans (Ctrl+MMB zooms); the wheel zooms (Ctrl/Shift+wheel pans).+- X / Delete deletes the selection, A / Alt+A selects / deselects all, H collapses, Home frames all.+- Drag an unlinked input's field to change it.++SPDX-License-Identifier: GPL-2.0-or-later+"""++from __future__ import annotations++from typing import Callable, Optional, Sequence++from .core import EV_CHANGE, Component++# node class header colors (userdef_default_theme.c: space_node)+NODE_CLASS_COLORS = {+ "input": "#83314a", "output": "#3e232a", "shader": "#2b652b", "texture": "#79461d",+ "color": "#6e6e23", "vector": "#3c3c83", "converter": "#246283", "geometry": "#1d725e",+ "attribute": "#1d2546", "group": "#3b5959", "filter": "#412b51", "script": "#203c3c",+ "matte": "#5a3838", "distort": "#3e5a5b", "layout": "#6c696f", "pattern": "#4f4f4f",+}++EV_MOVED, EV_SELECT, EV_VALUE, EV_COLLAPSE, EV_LINKS, EV_DELETE, EV_ORDER = 1, 2, 3, 4, 10, 11, 12+++def _rgba(color) -> tuple:+ if isinstance(color, str):+ h = color.lstrip("#")+ return tuple(int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4)) + (1.0,)+ c = tuple(float(v) for v in color)+ return c if len(c) == 4 else c + (1.0,)+++class Node(Component):+ """One node. ``inputs`` are ``(name, type)`` or ``(name, type, value)`` (a+ value draws a field while the input is unlinked); ``outputs`` are+ ``(name, type)``. Types color the sockets: float, int, bool, vector, color,+ shader, geometry, string, object, image, collection, texture, material,+ rotation, menu, matrix. ``kind`` picks the header color (see+ NODE_CLASS_COLORS) or pass ``color=``."""++ TYPE = "graphnode"++ def __init__(self, title: str = "Node", *, inputs: Sequence = (), outputs: Sequence = (),+ location=(0.0, 0.0), width: float = 140.0, kind: str = "converter",+ color=None, collapsed: bool = False,+ on_change: Optional[Callable[["Node", int, object], None]] = None):+ super().__init__()+ self.title = title+ self.on_change = on_change+ self._inputs = [tuple(i) for i in inputs]+ self._outputs = [tuple(o) for o in outputs]+ self.set("label", title)+ self.set("color", _rgba(color if color is not None else NODE_CLASS_COLORS.get(kind, "#4f4f4f")))+ self.location = location+ self.set("nwidth", float(width))+ if collapsed:+ self.set("collapsed", True)+ self._push_sockets()++ def _push_sockets(self) -> None:+ items = []+ for o in self._outputs:+ items.append("o|%s|%s" % (o[0], o[1] if len(o) > 1 else "float"))+ for i in self._inputs:+ value = ""+ if len(i) > 2 and i[2] is not None:+ value = str(int(i[2])) if (i[1] == "int") else "%.3f" % float(i[2])+ items.append("i|%s|%s|%s" % (i[0], i[1] if len(i) > 1 else "float", value))+ self.set("items", items)++ @property+ def location(self) -> tuple:+ return (self.get("nx"), self.get("ny"))++ @location.setter+ def location(self, xy) -> None:+ self.set("nx", float(xy[0]))+ self.set("ny", float(xy[1]))++ @property+ def selected(self) -> bool:+ return bool(self.get("selected"))++ @selected.setter+ def selected(self, v: bool) -> None:+ self.set("selected", bool(v))++ @property+ def collapsed(self) -> bool:+ return bool(self.get("collapsed"))++ @collapsed.setter+ def collapsed(self, v: bool) -> None:+ self.set("collapsed", bool(v))++ def input_value(self, index: int):+ """The current value of input ``index`` (None without a field)."""+ k = 0+ for s in self.strs("items"):+ parts = s.split("|")+ if parts[0] == "i":+ if k == index:+ if len(parts) < 4 or parts[3] == "":+ return None+ return int(parts[3]) if parts[2] == "int" else float(parts[3])+ k += 1+ raise IndexError(index)++ def _on_event(self, kind, ref, a, b):+ if kind != EV_CHANGE or self.on_change is None:+ return+ what = {EV_MOVED: "location", EV_SELECT: "select", EV_VALUE: "value",+ EV_COLLAPSE: "collapsed"}.get(int(a))+ if what == "value":+ self.on_change(self, "value", (int(b), self.input_value(int(b))))+ elif what == "location":+ self.on_change(self, what, self.location)+ elif what:+ self.on_change(self, what, bool(b))+++class NodeEditor(Component):+ """Blender's node editor canvas. ``links`` are ``(from_node, output,+ to_node, input)`` with nodes or their indices. ``on_links(links)`` runs+ after the user links, relinks or cuts; ``on_delete(nodes)`` when X /+ Delete asks to delete the selection (remove them to delete)."""++ TYPE = "nodeeditor"++ def __init__(self, nodes: Sequence[Node] = (), *, links: Sequence = (),+ on_links: Optional[Callable[[list], None]] = None,+ on_delete: Optional[Callable[[list], None]] = None, **kw):+ super().__init__(**{k: v for k, v in kw.items()+ if k in ("description", "enabled", "visible", "weight", "fill")})+ self.on_links, self.on_delete = on_links, on_delete+ self._nodes: list = []+ for n in nodes:+ self.add_node(n)+ self.links = links++ @property+ def nodes(self) -> list:+ return list(self._nodes)++ def add_node(self, node: Node) -> Node:+ self._nodes.append(node)+ self.add(node)+ return node++ def remove_node(self, node: Node) -> None:+ links = [l for l in self.links if l[0] is not node and l[2] is not node]+ self._nodes.remove(node)+ self.remove(node)+ self.links = links++ @property+ def links(self) -> list:+ out = []+ for s in self.strs("items"):+ a, o, b, i = (int(v) for v in s.split())+ if a < len(self._nodes) and b < len(self._nodes):+ out.append((self._nodes[a], o, self._nodes[b], i))+ return out++ @links.setter+ def links(self, links) -> None:+ def idx(n):+ return n if isinstance(n, int) else self._nodes.index(n)+ self.set("items", ["%d %d %d %d" % (idx(a), o, idx(b), i) for a, o, b, i in links])++ @property+ def selected(self) -> list:+ return [n for n in self._nodes if n.selected]++ @property+ def zoom(self) -> float:+ return self.get("zoom")++ @zoom.setter+ def zoom(self, z: float) -> None:+ self.set("zoom", float(z))++ def view_all(self) -> None:+ self.set("view_all", 1.0)++ def _sync_order(self) -> None:+ """C raises the clicked node to the top: follow its child order."""+ self._nodes = list(self.children)++ def _on_event(self, kind, ref, a, b):+ if kind != EV_CHANGE:+ return+ if int(a) == EV_ORDER:+ self._sync_order()+ elif int(a) == EV_LINKS and self.on_links is not None:+ self.on_links(self.links)+ elif int(a) == EV_DELETE:+ doomed = self.selected+ if self.on_delete is not None:+ self.on_delete(doomed)+ else:+ for n in doomed:+ self.remove_node(n)diff --git a/bindings/python/tests/test_nodes.py b/bindings/python/tests/test_nodes.pynew file mode 100644index 0000000..b36f2b2--- /dev/null+++ b/bindings/python/tests/test_nodes.py@@ -0,0 +1,152 @@+"""Node editor and area header: links, cut, move, select, delete, values, pan, zoom.++SPDX-License-Identifier: GPL-2.0-or-later+"""+import os+import sys+from types import SimpleNamespace++sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))++from bui.components import (App, Area, Label, MenuButton, Node, NodeEditor, # noqa: E402+ Spacer, unit)++M0 = SimpleNamespace(shift=False, ctrl=False, alt=False, button1=False)+M1 = SimpleNamespace(shift=False, ctrl=False, alt=False, button1=True)+CTRL = SimpleNamespace(shift=False, ctrl=True, alt=False, button1=False)+++def make():+ a = Node("Value", outputs=[("Value", "float")], location=(0, 0), kind="input")+ b = Node("Math", inputs=[("A", "float", 0.5), ("B", "float", 0.25)],+ outputs=[("Result", "float")], location=(300, 0))+ ed = NodeEditor([a, b], fill=True)+ app = App("nodes", (800, 500), ed, padding=0)+ app.render_raster()+ ed.set("zoom", 1.0)+ ed.set("panx", 50.0)+ ed.set("pany", 50.0)+ app.render_raster()+ return app, ed, a, b+++def to_screen(ed, gx, gy):+ x, y, w, h = ed.rect+ return int(x + ed.get("panx") + gx * ed.get("zoom")), int(y + ed.get("pany") + gy * ed.get("zoom"))+++def out_socket(ed, node, k=0):+ gx, gy = node.location+ return to_screen(ed, gx + node.get("nwidth"), gy + 20 + 5 + k * 22 + 10)+++def in_socket(ed, node, k):+ gx, gy = node.location+ outs = sum(1 for s in node.strs("items") if s.startswith("o|"))+ return to_screen(ed, gx, gy + 20 + 5 + (outs + k) * 22 + 10)+++def drag(app, p0, p1, steps=4, m=M1):+ app.press(*p0, M0)+ for i in range(1, steps + 1):+ app.motion(p0[0] + (p1[0] - p0[0]) * i // steps, p0[1] + (p1[1] - p0[1]) * i // steps, m)+ app.release(*p1, M0)+ app.render_raster()+++def test_link_and_relink():+ app, ed, a, b = make()+ seen = []+ ed.on_links = seen.append+ drag(app, out_socket(ed, a), in_socket(ed, b, 1))+ assert ed.links == [(a, 0, b, 1)], ed.links+ assert seen and seen[-1] == ed.links+ # dragging from the linked input picks the link up; dropping on A relinks+ drag(app, in_socket(ed, b, 1), in_socket(ed, b, 0))+ assert ed.links == [(a, 0, b, 0)], ed.links+ # dropping on nothing removes it+ drag(app, in_socket(ed, b, 0), to_screen(ed, 150, 300))+ assert ed.links == [], ed.links+++def test_cut_links():+ app, ed, a, b = make()+ ed.links = [(a, 0, b, 0)]+ x0, y0 = out_socket(ed, a)+ x1, y1 = in_socket(ed, b, 0)+ mx = (x0 + x1) // 2+ app.ctx.context_menu(mx, min(y0, y1) - 40, 2) # Ctrl+RMB press+ for y in range(min(y0, y1) - 40, max(y0, y1) + 41, 10):+ app.motion(mx, y, CTRL)+ app.ctx.button(mx, max(y0, y1) + 40, 3, True, 2)+ assert ed.links == [], ed.links+++def test_select_move_delete():+ app, ed, a, b = make()+ moved = []+ b.on_change = lambda n, what, v: moved.append((what, v))+ title = to_screen(ed, 300 + 70, 10)+ drag(app, title, (title[0] + 40, title[1] + 20))+ assert b.selected and not a.selected+ assert b.location == (340.0, 20.0), b.location+ assert ("location", (340.0, 20.0)) in moved, moved+ # box select both+ drag(app, to_screen(ed, -20, -20), to_screen(ed, 500, 200))+ assert a.selected and b.selected+ # click on empty space deselects+ p = to_screen(ed, 150, 350)+ app.press(*p, M0)+ app.release(*p, M0)+ assert not a.selected and not b.selected+ # X deletes the selection+ a.selected = True+ app.motion(*p, M0)+ app.key("x", "x", 0, M0)+ assert ed.nodes == [b], ed.nodes+++def test_value_field_and_view():+ app, ed, a, b = make()+ changes = []+ b.on_change = lambda n, what, v: changes.append((what, v))+ x, y = in_socket(ed, b, 0)+ drag(app, (x + 60, y), (x + 110, y))+ assert abs(b.input_value(0) - 1.0) < 1e-6, b.input_value(0)+ assert changes and changes[-1][0] == "value"+ # MMB pans+ px = ed.get("panx")+ app.ctx.button(400, 300, 2, False, 0)+ app.motion(450, 300, M0)+ app.ctx.button(450, 300, 2, True, 0)+ assert ed.get("panx") == px + 50+ # the wheel zooms about the cursor+ z = ed.zoom+ app.wheel(400, 300, 1, M0)+ assert ed.zoom > z+++def test_area_header():+ picked = []+ ed = NodeEditor()+ area = Area("Geometry Node Editor", ed, header=[MenuButton("View", ["Frame All"]), Spacer(),+ Label("Right")], on_editor=picked.append)+ app = App("area", (600, 400), area, padding=0)+ app.render_raster()+ hx, hy, hw, hh = area.header.rect+ assert hh == round(26 * unit() / 20), hh+ assert ed.rect[1] == hy + hh and ed.rect[3] == 400 - hh, (ed.rect, area.header.rect)+ assert area.editor_button.rect[0] == hx + round(8 * unit() / 20)+ area._pick("Shader Editor")+ assert picked == ["Shader Editor"]+++def main():+ for name, fn in list(globals().items()):+ if name.startswith("test_"):+ fn()+ print("ok")+++if __name__ == "__main__":+ main()diff --git a/bindings/python/tests/test_render.py b/bindings/python/tests/test_render.pyindex 511f897..4a5e4fb 100644--- a/bindings/python/tests/test_render.py+++ b/bindings/python/tests/test_render.py@@ -82,7 +82,7 @@ def test_damage_reaches_right_edge():def test_window_matches_buffer_after_real_events():"""Drive the native window with real Win32 messages and compare what thewindow shows with the frame buffer."""- if not host.native_available():+ if not host.native_available() or sys.platform != "win32":returnimport ctypesimport timediff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rsindex f8e9b78..196b039 100644--- a/bindings/rust/blenderui-sys/build.rs+++ b/bindings/rust/blenderui-sys/build.rs@@ -49,6 +49,9 @@ fn main() {println!("cargo:rustc-link-lib={lib}");}} else {+ if target == "linux" || target.ends_with("bsd") {+ println!("cargo:rustc-link-lib=X11"); // the native window host+ }println!("cargo:rustc-link-lib=m");println!("cargo:rustc-link-lib=pthread");}diff --git a/core/CMakeLists.txt b/core/CMakeLists.txtindex d3a96e9..bcea937 100644--- a/core/CMakeLists.txt+++ b/core/CMakeLists.txt@@ -65,4 +65,7 @@ endif()find_package(Threads REQUIRED)target_link_libraries(bui_core PUBLIC Threads::Threads)+if(UNIX)+ target_link_libraries(bui_core PUBLIC m)+endif()diff --git a/core/intern/bui_system_stubs.c b/core/intern/bui_system_stubs.cindex fc22396..ca70cde 100644--- a/core/intern/bui_system_stubs.c+++ b/core/intern/bui_system_stubs.c@@ -10,6 +10,7 @@# include <windows.h>#else# include <time.h>+# include <unistd.h> /* sysconf */#endifvoid BLI_system_backtrace(FILE *fp)diff --git a/core/intern/guardedalloc.c b/core/intern/guardedalloc.cindex e3137f8..fdfce74 100644--- a/core/intern/guardedalloc.c+++ b/core/intern/guardedalloc.c@@ -2,6 +2,9 @@* SPDX-License-Identifier: GPL-2.0-or-later */#include <stdlib.h>#include <string.h>+#ifdef __GLIBC__+# include <malloc.h> /* malloc_usable_size */+#endif#include "BLI_compiler_attrs.h"#include "BLI_utildefines.h"diff --git a/docs/components.md b/docs/components.mdindex 8257357..5dd3f1d 100644--- a/docs/components.md+++ b/docs/components.md@@ -177,6 +177,38 @@ item. Right-clicking a value opens its context menu (Copy, Paste, Reset).| `IDSelector` | `IDSelector(items, value, *, icon="MESH_DATA", fake_user=False, on_change, on_new, on_unlink)`: Blender's `template_ID` || `PathField` | `PathField(label, value, *, directory=False, on_browse=None, on_change=None)` |+## Node editor and areas++```python+from bui.components import Area, MenuButton, Node, NodeEditor, Spacer++value = Node("Value", outputs=[("Value", "float")], location=(-200, 0), kind="input")+math = Node("Math", inputs=[("A", "float", 0.5), ("B", "float", 0.5)],+ outputs=[("Result", "float")], location=(0, 0), kind="converter")+editor = NodeEditor([value, math], links=[(value, 0, math, 0)],+ on_links=lambda links: print(links))+area = Area("Geometry Node Editor", editor,+ header=[MenuButton("View", ["Frame All"]), Spacer()],+ on_editor=print)+```++- **`Node`**:+ - `inputs` are `(name, type)` or `(name, type, value)`; a value draws a field while the input is unlinked.+ - `outputs` are `(name, type)`, and types color the sockets.+ - `kind` picks the header color (`input`, `output`, `shader`, `texture`, `color`, `vector`, `converter`, `geometry`, `group` …), or pass `color=`.+ - `on_change(node, what, value)` reports `location`, `select`, `value` and `collapsed`.+- **`NodeEditor`**:+ - `links` are `(from_node, output, to_node, input)`.+ - `on_links(links)` runs after the user links, relinks or cuts.+ - `on_delete(nodes)` runs on X / Delete; without it, the editor removes the selected nodes itself.+- **Editing, as in Blender:**+ - click selects (Shift toggles); dragging moves the selection (Ctrl snaps);+ - dragging on empty space box-selects;+ - dragging from a socket links; dragging a linked input picks its link up;+ - Ctrl+RMB drag cuts links.+- **View:** MMB pans, Ctrl+MMB and the wheel zoom, Ctrl/Shift+wheel pan, and Home frames everything.+- **`Area`**: a 1.3-unit header with the editor-type menu, then the editor filling the rest. A `Spacer()` in `header` pushes the items after it to the right.+## InteractionsAll of these come from Blender and run in C, in every API (components,diff --git a/examples/__pycache__/components_demo.cpython-314.pyc b/examples/__pycache__/components_demo.cpython-314.pycindex 7899fa3..698b8bf 100644Binary files a/examples/__pycache__/components_demo.cpython-314.pyc and b/examples/__pycache__/components_demo.cpython-314.pyc differdiff --git a/examples/components_demo.py b/examples/components_demo.pyindex 6183f6b..c988961 100644--- a/examples/components_demo.py+++ b/examples/components_demo.py@@ -29,7 +29,8 @@ from bui.components import (App, Box, Button, Checkbox, ColorRamp, ColorSwatch,MenuBar, MenuItem, NormalBall, NumberField, NumberSlider, Panel,PathField, PieMenu, Popover, ProgressBar, Row, ScrollView,SearchField, Separator, SideTabs, Split, Tabs, TextField, Toggle,- TreeItem, TreeView, VectorField)+ TreeItem, TreeView, VectorField, Area, MenuButton, Node,+ NodeEditor, Spacer)def page(*children):@@ -223,6 +224,31 @@ class Status(Label):self.text = text+def nodes_page(status):+ """A Geometry Node Editor area: drag sockets to link, Ctrl+RMB to cut, MMB to pan."""+ grp_in = Node("Group Input", outputs=[("Geometry", "geometry")], location=(-420, 0),+ kind="group")+ noise = Node("Noise Texture", inputs=[("Scale", "float", 5.0), ("Detail", "float", 2.0),+ ("Roughness", "float", 0.5)],+ outputs=[("Fac", "float"), ("Color", "color")], location=(-420, 120),+ kind="texture")+ setpos = Node("Set Position", inputs=[("Geometry", "geometry"), ("Offset", "vector")],+ outputs=[("Geometry", "geometry")], location=(-120, 0), kind="geometry")+ combine = Node("Combine XYZ", inputs=[("X", "float", 0.0), ("Y", "float", 0.0),+ ("Z", "float", 0.0)],+ outputs=[("Vector", "vector")], location=(-250, 180), kind="converter")+ grp_out = Node("Group Output", inputs=[("Geometry", "geometry")], location=(140, 0),+ kind="group")+ ed = NodeEditor([grp_in, noise, combine, setpos, grp_out],+ links=[(grp_in, 0, setpos, 0), (noise, 0, combine, 2),+ (combine, 0, setpos, 1), (setpos, 0, grp_out, 0)],+ on_links=lambda links: status.set("text", "%d links" % len(links)))+ return Area("Geometry Node Editor", ed,+ header=[MenuButton("View", ["Frame All"]), MenuButton("Select", ["All"]),+ MenuButton("Add", ["Math", "Mix"]), Spacer()],+ on_editor=lambda name: status.set("text", "Editor: " + name))++def build() -> App:status = Status("Q: pie menu · right-click values · drag panel grips", align="left",icon="INFO")@@ -268,6 +294,7 @@ def build() -> App:("MATERIAL", "Material", material_page()),("OUTLINER", "Outliner", outliner_page(status)),("PREFERENCES", "Preferences", prefs_page(status)),+ ("GEOMETRY_NODES", "Nodes", nodes_page(status)),])app = App("BUI — Blender components", (520, 900), pages,diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.hindex 88da064..06e9caf 100644--- a/gpu/include/GPU_raster.h+++ b/gpu/include/GPU_raster.h@@ -20,6 +20,7 @@* SPDX-License-Identifier: GPL-2.0-or-later */#pragma once+#include <stddef.h>#include <stdint.h>#include "GPU_backend_sink.h"diff --git a/gpu/intern/gpu_d3d11.c b/gpu/intern/gpu_d3d11.cindex d2e3c9d..ef674ce 100644--- a/gpu/intern/gpu_d3d11.c+++ b/gpu/intern/gpu_d3d11.c@@ -1128,6 +1128,8 @@ int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h)#else /* !_WIN32: no GPU backend yet; every raster stays in software */+# include "gpu_d3d11.h"+int bui_gpu_slug_on(BuiGpu *g){(void)g;diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txtindex 3ebd92f..aad7fbe 100644--- a/kit/CMakeLists.txt+++ b/kit/CMakeLists.txt@@ -14,9 +14,12 @@ add_library(bui_kit STATICintern/kit_color.cintern/kit_frame.cintern/kit_textarea.c- intern/kit_window.c+ intern/kit_window_win32.c+ intern/kit_window_x11.c+ intern/kit_window_null.cintern/kit_icons_svg.cintern/kit_regions.c+ intern/kit_nodes.cextern/nanosvg/blender_nanosvg.cextern/nanosvg/blender_raster.c)@@ -35,4 +38,12 @@ if(NOT MSVC)endif()if(WIN32)target_link_libraries(bui_kit PRIVATE user32 gdi32)+elseif(UNIX AND NOT APPLE)+ # Native windows on X11 (Wayland sessions run it through XWayland).+ find_package(X11)+ if(X11_FOUND)+ target_compile_definitions(bui_kit PRIVATE BUI_WINDOW_X11)+ target_include_directories(bui_kit PRIVATE ${X11_INCLUDE_DIR})+ target_link_libraries(bui_kit PUBLIC ${X11_LIBRARIES})+ endif()endif()diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.hindex 0105be6..7ac3e71 100644--- a/kit/include/BUI_kit.h+++ b/kit/include/BUI_kit.h@@ -25,7 +25,7 @@ typedef struct BKContext BKContext;typedef struct BKTreeItem BKTreeItem;/* Modifier / button state bits for input calls. */-enum { BK_SHIFT = 1, BK_CTRL = 2, BK_ALT = 4, BK_BUTTON1 = 8 };+enum { BK_SHIFT = 1, BK_CTRL = 2, BK_ALT = 4, BK_BUTTON1 = 8, BK_BUTTON2 = 16, BK_BUTTON3 = 32 };/* Mouse cursors requested through BKHost.set_cursor. */enum {diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.cindex f4eeef2..d133711 100644--- a/kit/intern/kit_core.c+++ b/kit/intern/kit_core.c@@ -144,7 +144,7 @@ static int g_gen = 1; /* layout generation for the natural-size cache */static const BKClass *const g_classes[] = {&bk_cls_column, &bk_cls_row, &bk_cls_split, &bk_cls_grid, &bk_cls_box,- &bk_cls_panel, &bk_cls_tabs, &bk_cls_sidetabs, &bk_cls_sidebar, &bk_cls_scroll, &bk_cls_scrollbar,+ &bk_cls_panel, &bk_cls_tabs, &bk_cls_sidetabs, &bk_cls_sidebar, &bk_cls_nodeeditor, &bk_cls_graphnode, &bk_cls_areaheader, &bk_cls_scroll, &bk_cls_scrollbar,&bk_cls_label, &bk_cls_separator, &bk_cls_progress, &bk_cls_button,&bk_cls_toggle, &bk_cls_checkbox, &bk_cls_decorator, &bk_cls_text,&bk_cls_search, &bk_cls_hotkey, &bk_cls_number, &bk_cls_slider,@@ -2117,6 +2117,7 @@ static int in_BK_press(BKContext *ctx, int x, int y, int mods)ctx->press_y = y;ctx->dragging = false;ctx->has_ungrab = false;+ ctx->press_button = 1;ctx->off_x = ctx->off_y = 0;if (ctx->modal) {BKEvent e = make_event(ctx, ctx->modal, x, y, mods);@@ -2244,8 +2245,22 @@ static int in_BK_release(BKContext *ctx, int x, int y, int mods)static void raw_event(BKNode *n, int kind, int mods, const BKEvent *e, int button);+static BKNode *buttons_target(BKContext *ctx, int x, int y)+{+ if (ctx->modal || ctx->npopups) {+ return NULL;+ }+ BKNode *n = hit_all(ctx, x, y);+ return n && (n->cls->flags & CLS_BUTTONS) && NODE_ENABLED(n) ? n : NULL;+}+static int in_BK_context_menu(BKContext *ctx, int x, int y, int mods){+ if (buttons_target(ctx, x, y) && !ctx->grab) { /* an editor takes the right button */+ const int r = in_BK_press(ctx, x, y, mods | BK_BUTTON3);+ ctx->press_button = 3;+ return r;+ }hide_tooltip(ctx);if (ctx->modal) {bk_end_modal(ctx);@@ -3029,6 +3044,25 @@ int BK_key_release(BKContext *ctx, const char *keysym, int mods)int BK_button(BKContext *ctx, int x, int y, int button, int release, int mods){+ if (button == 2 || button == 3) { /* editors: middle drags, right drags */+ const int bit = button == 2 ? BK_BUTTON2 : BK_BUTTON3;+ if (!release && button == 2 && !ctx->grab && buttons_target(ctx, x, y)) {+ ctx->in_input++;+ in_BK_press(ctx, x, y, mods | bit);+ ctx->press_button = button;+ ctx->in_input--;+ bk_views_check(ctx);+ return 1;+ }+ if (release && ctx->grab && ctx->press_button == button) {+ ctx->press_button = 0;+ ctx->in_input++;+ in_BK_release(ctx, x, y, mods | bit);+ ctx->in_input--;+ bk_views_check(ctx);+ return 1;+ }+ }BKNode *under = hit_all(ctx, x, y);if (!under || !(under->flags & NF_EVENTS)) {return 0;diff --git a/kit/intern/kit_draw.c b/kit/intern/kit_draw.cindex fb7279e..1b512e7 100644--- a/kit/intern/kit_draw.c+++ b/kit/intern/kit_draw.c@@ -556,7 +556,8 @@ static void shape_preset_trias_from_rect_menu(WidgetTrias *tria, const BKRect *rstatic void draw_menu_chevron(const WidgetTrias *t, const float c[4]){- const float s = t->size * 0.42f, lw = BK_MAX(1.2f, 0.075f * bk_unit());+ /* ROUNDBOX_TRIA_MENU: bars 0.17 thick at 0.8 of the tria size */+ const float s = t->size * 0.42f, lw = BK_MAX(1.0f, 0.17f * 0.8f * t->size);const float cx = t->center[0], cy = t->center[1];BUI_raster_line(bk_draw.r, cx - s, cy - s * 0.4f, cx, cy + s * 0.5f, lw, c);BUI_raster_line(bk_draw.r, cx, cy + s * 0.5f, cx + s, cy - s * 0.4f, lw, c);diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.hindex 9278198..3f03008 100644--- a/kit/intern/kit_intern.h+++ b/kit/intern/kit_intern.h@@ -254,6 +254,8 @@ enum {CLS_INTERACTIVE = 1 << 0,CLS_VALUE = 1 << 1, /* has the value shortcuts and context menu */CLS_POPUP = 1 << 2,+ CLS_BUTTONS = 1 << 3, /* middle / right presses arrive as press, drag, release with+ * BK_BUTTON2 / BK_BUTTON3 in the event's mods (editors) */};enum { DRAG_GROUP_TOGGLE = 1, DRAG_GROUP_PANEL = 2 };@@ -461,6 +463,7 @@ struct BKContext {bool dragging;int press_x, press_y, off_x, off_y, skip_x, skip_y;int ungrab_x, ungrab_y; /* where a continuous drag puts the pointer back */+ int press_button; /* the button that started the grab (1, 2, 3) */bool has_ungrab;bool has_skip;int pointer_x, pointer_y;@@ -533,6 +536,7 @@ BKMenuSpec *bk_menuspec_copy(const BKMenuSpec *items, int n);int bk_tree_columns_from_icons(BKNode *n);/* Classes (kit_widgets.c, kit_views.c, kit_color.c, kit_menus.c) */+extern const BKClass bk_cls_nodeeditor, bk_cls_graphnode, bk_cls_areaheader;extern const BKClass bk_cls_column, bk_cls_row, bk_cls_split, bk_cls_grid, bk_cls_box, bk_cls_panel,bk_cls_tabs, bk_cls_sidetabs, bk_cls_sidebar, bk_cls_scroll, bk_cls_scrollbar, bk_cls_label, bk_cls_separator,bk_cls_progress, bk_cls_button, bk_cls_toggle, bk_cls_checkbox, bk_cls_decorator,diff --git a/kit/intern/kit_nodes.c b/kit/intern/kit_nodes.cnew file mode 100644index 0000000..e56ca57--- /dev/null+++ b/kit/intern/kit_nodes.c@@ -0,0 +1,1241 @@+/* The node editor: a View2D canvas of nodes, sockets and links.+ *+ * Ported from Blender's space_node: node_draw.cc (node_update_basis,+ * node_draw_basis, the dot grid), drawnode.cc (node_link_bezier_handles,+ * link drawing), node_select.cc / node_relationships.cc (select, move, link+ * drag, picking up a linked input, cut links) and view2d_ops.cc (pan, zoom).+ *+ * The editor ("nodeeditor") holds its nodes as children ("graphnode"). A+ * node's sockets are its `items`: "i|Name|type|value" for inputs (value may be+ * empty when the input has no field), "o|Name|type" for outputs. The editor's+ * `items` are its links: "from_node from_output to_node to_input" (indices+ * among the editor's nodes and among each node's outputs / inputs).+ *+ * Events (BK_EV_CHANGE): on a node, a = 1 moved, 2 selection, 3 input value+ * (b = input index), 4 collapsed; on the editor, a = 10 links changed,+ * 11 delete the selected nodes.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include "kit_intern.h"++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* node_intern.hh, in units of U.widget_unit = 20 at scale 1 */+#define NODE_DY 20.0f+#define NODE_DYS 10.0f+#define NODE_ITEM_SPACING_Y 2.0f+#define NODE_SOCKSIZE 5.0f+#define BASIS_RAD 4.0f+#define NODE_LINK_RESOL 12+#define NOODLE_CURVING 4.0f /* theme space_node.noodle_curving */++enum { EV_MOVED = 1, EV_SELECT = 2, EV_VALUE = 3, EV_COLLAPSE = 4, EV_LINKS = 10, EV_DELETE = 11 };++/* -------------------------------------------------------------------- */+/** \name Data+ * \{ */++typedef struct GNode {+ float x, y, width; /* Blender units (node.location, node.width), y down */+ bool collapsed, active;+} GNode;++typedef enum { M_NONE, M_PAN, M_ZOOM, M_MOVE, M_BOX, M_LINK, M_VALUE, M_CUT } Mode;++#define MAX_CUT 256++typedef struct NodeEdit {+ float zoom, panx, pany; /* screen = n->x + pan + graph * scale * zoom */+ Mode mode;+ /* drag scratch */+ float start_panx, start_pany, start_zoom;+ int press_x, press_y;+ BKNode *hit; /* node pressed */+ int link_node, link_sock; /* the fixed end of a dragged link */+ bool link_from_output;+ int value_node, value_sock;+ double value_start;+ bool shift;+ float cut[MAX_CUT][2];+ int ncut;+ int cur_x, cur_y;+} NodeEdit;++static int u(void)+{+ return bk_unit();+}++static NodeEdit *ed(const BKNode *n)+{+ return (NodeEdit *)n->ext;+}++static GNode *gn(const BKNode *n)+{+ return (GNode *)n->ext;+}++static float scale_of(const BKNode *e)+{+ return bk_scale_fac * ed(e)->zoom;+}++/* graph -> screen */+static float sx(const BKNode *e, float gx)+{+ return (float)e->x + ed(e)->panx + gx * scale_of(e);+}++static float sy(const BKNode *e, float gy)+{+ return (float)e->y + ed(e)->pany + gy * scale_of(e);+}++static float gx_of(const BKNode *e, float x)+{+ return (x - (float)e->x - ed(e)->panx) / scale_of(e);+}++static float gy_of(const BKNode *e, float y)+{+ return (y - (float)e->y - ed(e)->pany) / scale_of(e);+}++/* A socket from the node's items. */+typedef struct Sock {+ bool input;+ char name[64], type[24], value[32];+ int item; /* index in items */+} Sock;++static bool sock_parse(const char *s, Sock *r)+{+ memset(r, 0, sizeof(*r));+ if (!s || (s[0] != 'i' && s[0] != 'o') || s[1] != '|') {+ return false;+ }+ r->input = s[0] == 'i';+ const char *p = s + 2;+ char *fields[3] = {r->name, r->type, r->value};+ const int sizes[3] = {sizeof(r->name), sizeof(r->type), sizeof(r->value)};+ for (int f = 0; f < 3 && *p; f++) {+ const char *end = strchr(p, '|');+ const int len = end ? (int)(end - p) : (int)strlen(p);+ snprintf(fields[f], (size_t)sizes[f], "%.*s", len, p);+ if (!end) {+ break;+ }+ p = end + 1;+ }+ return true;+}++/* The k-th output / input of a node. */+static bool sock_get(const BKNode *node, bool input, int k, Sock *r)+{+ int count = 0;+ for (int i = 0; i < node->items.n; i++) {+ Sock s;+ if (sock_parse(node->items.v[i], &s) && s.input == input) {+ if (count++ == k) {+ *r = s;+ r->item = i;+ return true;+ }+ }+ }+ return false;+}++static int sock_count(const BKNode *node, bool input)+{+ int count = 0;+ for (int i = 0; i < node->items.n; i++) {+ Sock s;+ count += sock_parse(node->items.v[i], &s) && s.input == input;+ }+ return count;+}++/* std_node_socket_colors (node_socket.cc), Blender 4.x / 5.x */+static void socket_color(const char *type, float c[4])+{+ static const struct {+ const char *name;+ uint32_t rgb;+ } colors[] = {+ {"float", 0xa1a1a1}, {"value", 0xa1a1a1}, {"int", 0x598c5c},+ {"bool", 0xcca6d6}, {"boolean", 0xcca6d6}, {"vector", 0x6363c7},+ {"color", 0xc7c729}, {"rgba", 0xc7c729}, {"shader", 0x63c763},+ {"geometry", 0x00d6a3}, {"string", 0x70b2ff}, {"object", 0xed9e5c},+ {"image", 0x633863}, {"collection", 0xf5f5f5}, {"texture", 0x9e4fa3},+ {"material", 0xeb7582}, {"rotation", 0xa663c7}, {"menu", 0x4d4d4d},+ {"matrix", 0x4d1a75}, {"bundle", 0x52525e}, {"closure", 0x3d3d47},+ };+ uint32_t rgb = 0xa1a1a1;+ for (size_t i = 0; i < sizeof(colors) / sizeof(colors[0]); i++) {+ if (strcmp(type, colors[i].name) == 0) {+ rgb = colors[i].rgb;+ }+ }+ c[0] = ((rgb >> 16) & 255) / 255.0f;+ c[1] = ((rgb >> 8) & 255) / 255.0f;+ c[2] = (rgb & 255) / 255.0f;+ c[3] = 1.0f;+}++/* A link "a b c d". */+typedef struct Link {+ int from, out, to, in;+} Link;++static int links_get(const BKNode *e, Link *out, int max)+{+ int count = 0;+ for (int i = 0; i < e->items.n && count < max; i++) {+ Link l;+ if (sscanf(e->items.v[i], "%d %d %d %d", &l.from, &l.out, &l.to, &l.in) == 4 && l.from >= 0 &&+ l.to >= 0 && l.from < e->nkids && l.to < e->nkids)+ {+ out[count++] = l;+ }+ }+ return count;+}++static void links_set_ex(BKNode *e, const Link *l, int count, bool notify)+{+ char **v = (char **)calloc((size_t)BK_MAX(1, count), sizeof(char *));+ for (int i = 0; i < count; i++) {+ char buf[64];+ snprintf(buf, sizeof(buf), "%d %d %d %d", l[i].from, l[i].out, l[i].to, l[i].in);+ v[i] = buf[0] ? strdup(buf) : NULL;+ }+ bk_strs_set(&e->items, (const char *const *)v, count);+ for (int i = 0; i < count; i++) {+ free(v[i]);+ }+ free(v);+ bk_invalidate(e);+ if (notify) {+ bk_emit(e, BK_EV_CHANGE, NULL, EV_LINKS, count);+ }+}++static void links_set(BKNode *e, const Link *l, int count)+{+ links_set_ex(e, l, count, true);+}++#define MAX_LINKS 1024++static bool input_linked(const BKNode *e, int node, int in, Link *r)+{+ Link l[MAX_LINKS];+ const int count = links_get(e, l, MAX_LINKS);+ for (int i = 0; i < count; i++) {+ if (l[i].to == node && l[i].in == in) {+ if (r) {+ *r = l[i];+ }+ return true;+ }+ }+ return false;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Node layout (node_update_basis), in graph units+ * \{ */++static float node_height(const BKNode *node)+{+ if (gn(node)->collapsed) {+ return NODE_DY;+ }+ const int rows = sock_count(node, false) + sock_count(node, true);+ return NODE_DY + NODE_DYS / 2 + rows * (NODE_DY + NODE_ITEM_SPACING_Y) + NODE_DYS / 2;+}++/* The row center of a socket (outputs first, then inputs). */+static float socket_y(const BKNode *node, bool input, int k)+{+ const GNode *g = gn(node);+ if (g->collapsed) {+ return g->y + NODE_DY * 0.5f;+ }+ const int row = input ? sock_count(node, false) + k : k;+ return g->y + NODE_DY + NODE_DYS / 2 + row * (NODE_DY + NODE_ITEM_SPACING_Y) + NODE_DY * 0.5f;+}++static float socket_x(const BKNode *node, bool input)+{+ return input ? gn(node)->x : gn(node)->x + gn(node)->width;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Graph nodes+ * \{ */++static void gnode_init(BKNode *n)+{+ GNode *g = (GNode *)calloc(1, sizeof(GNode));+ g->width = 140.0f; /* the default node width */+ n->ext = g;+ n->color[0] = 0.18f; /* header: a converter-ish default */+ n->color[1] = 0.18f;+ n->color[2] = 0.18f;+ n->color[3] = 1.0f;+}++static void gnode_free(BKNode *n)+{+ free(n->ext);+ n->ext = NULL;+}++static int gnode_set_num(BKNode *n, const char *key, double v)+{+ GNode *g = gn(n);+ if (strcmp(key, "nx") == 0) {+ g->x = (float)v;+ }+ else if (strcmp(key, "ny") == 0) {+ g->y = (float)v;+ }+ else if (strcmp(key, "nwidth") == 0) {+ g->width = (float)BK_MAX(40.0, v);+ }+ else if (strcmp(key, "collapsed") == 0) {+ g->collapsed = v != 0;+ }+ else if (strcmp(key, "selected") == 0) {+ n->flags = v != 0 ? (n->flags | NF_SELECTED) : (n->flags & ~NF_SELECTED);+ }+ else if (strcmp(key, "active") == 0) {+ g->active = v != 0;+ }+ else {+ return 0;+ }+ if (n->parent) {+ bk_invalidate(n->parent);+ }+ return 1;+}++static int gnode_get_num(BKNode *n, const char *key, double *r)+{+ const GNode *g = gn(n);+ if (strcmp(key, "nx") == 0) {+ *r = g->x;+ }+ else if (strcmp(key, "ny") == 0) {+ *r = g->y;+ }+ else if (strcmp(key, "nwidth") == 0) {+ *r = g->width;+ }+ else if (strcmp(key, "collapsed") == 0) {+ *r = g->collapsed;+ }+ else if (strcmp(key, "selected") == 0) {+ *r = (n->flags & NF_SELECTED) != 0;+ }+ else if (strcmp(key, "active") == 0) {+ *r = g->active;+ }+ else {+ return 0;+ }+ return 1;+}++static void gnode_measure(BKNode *n, int *rw, int *rh)+{+ *rw = *rh = 0;+}++const BKClass bk_cls_graphnode = {.name = "graphnode",+ .init = gnode_init,+ .free_ext = gnode_free,+ .measure = gnode_measure,+ .set_num = gnode_set_num,+ .get_num = gnode_get_num};++/** \} */++/* -------------------------------------------------------------------- */+/** \name Drawing (node_draw.cc)+ * \{ */++static void color_u(uint32_t rgba, float c[4])+{+ c[0] = ((rgba >> 24) & 255) / 255.0f;+ c[1] = ((rgba >> 16) & 255) / 255.0f;+ c[2] = ((rgba >> 8) & 255) / 255.0f;+ c[3] = (rgba & 255) / 255.0f;+}++/* UI_view2d_dot_grid_draw: dots at the grid levels, the finer ones fading in */+static void draw_grid(BKNode *e)+{+ float c[4];+ color_u(0x303030ff, c); /* space_node.grid */+ const float s = scale_of(e);+ const float base = NODE_DY; /* one widget unit in graph space */+ const int levels = 3; /* theme grid_levels */+ for (int level = levels - 1; level >= 0; level--) {+ const float step = base * powf(5.0f, (float)level) * s; /* screen pixels between dots */+ if (step < 4.0f * bk_scale_fac) {+ continue;+ }+ /* fade a level in as its dots spread apart */+ const float fade = BK_CLAMP((step - 4.0f * bk_scale_fac) / (12.0f * bk_scale_fac), 0.0f, 1.0f);+ float dc[4] = {c[0], c[1], c[2], fade};+ const float r = BK_MAX(0.75f, 1.0f * bk_scale_fac * (level ? 1.25f : 1.0f));+ const float ox = fmodf(ed(e)->panx, step), oy = fmodf(ed(e)->pany, step);+ for (float y = (float)e->y + oy - step; y < e->y + e->h + step; y += step) {+ for (float x = (float)e->x + ox - step; x < e->x + e->w + step; x += step) {+ if (x >= e->x && y >= e->y) {+ bk_fill_f(x - r * 0.5f, y - r * 0.5f, r, r, dc);+ }+ }+ }+ }+}++/* node_link_bezier_handles + evaluation: NODE_LINK_RESOL * 2 segments */+static void bezier_points(float x0, float y0, float x3, float y3, float pts[][2], int n)+{+ const float dist = NOODLE_CURVING * 0.10f * fabsf(x0 - x3);+ const float x1 = x0 + dist, x2 = x3 - dist;+ for (int i = 0; i <= n; i++) {+ const float t = (float)i / n, it = 1.0f - t;+ const float a = it * it * it, b = 3 * it * it * t, cc = 3 * it * t * t, d = t * t * t;+ pts[i][0] = a * x0 + b * x1 + cc * x2 + d * x3;+ pts[i][1] = a * y0 + b * y0 + cc * y3 + d * y3;+ }+}++static void draw_noodle(float x0, float y0, float x3, float y3, const float color[4], bool hi,+ float zoom)+{+ enum { N = NODE_LINK_RESOL * 2 };+ float pts[N + 1][2];+ bezier_points(x0, y0, x3, y3, pts, N);+ /* node_draw_link: an outline in the wire color, the link color inside */+ const float th = BK_MAX(1.0f, 1.5f * bk_scale_fac * BK_MIN(1.0f, zoom * 1.25f));+ float wire[4];+ color_u(0x1a1a1aff, wire); /* space_node.wire */+ float inner[4];+ memcpy(inner, color, sizeof(inner));+ if (hi) { /* edge_select: links of selected nodes brighten */+ for (int k = 0; k < 3; k++) {+ inner[k] = inner[k] + (1.0f - inner[k]) * 0.5f;+ }+ }+ for (int i = 0; i < N; i++) {+ bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], wire, th + 2.0f * bk_scale_fac);+ }+ for (int i = 0; i < N; i++) {+ bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], inner, th);+ }+}++static void draw_socket(float x, float y, const char *type, float s)+{+ float c[4], o[4] = {0.0f, 0.0f, 0.0f, 0.6f};+ socket_color(type, c);+ const float r = NODE_SOCKSIZE * s;+ bk_circle(x, y, r + BK_MAX(1.0f, bk_scale_fac), o);+ bk_circle(x, y, r, c);+}++/* A node's input field: a number button with the name on the left. */+static void draw_input_field(BKRect r, const char *name, const char *value)+{+ BKWCol w;+ bk_widget_state(&w, &bk_theme.num, 0);+ bk_widget_numbut(&w, &r, 0, CNR_ALL);+ BKRect lr = r, vr = r;+ const float vw = bk_text_width(value, -1, false);+ lr.xmax = (int)(r.xmax - vw - bk_pad());+ bk_text_in(&lr, name, w.text, BK_ALIGN_LEFT, false);+ bk_text_in(&vr, value, w.text, BK_ALIGN_RIGHT, false);+}++static void draw_node(BKNode *e, BKNode *node, int index)+{+ const GNode *g = gn(node);+ const float s = scale_of(e);+ const float x = sx(e, g->x), y = sy(e, g->y);+ const float w = g->width * s, h = node_height(node) * s, hh = NODE_DY * s;+ if (x > e->x + e->w || y > e->y + e->h || x + w < e->x || y + h < e->y) {+ return;+ }+ const float rad = BASIS_RAD * s;+ const bool selected = (node->flags & NF_SELECTED) != 0;+ /* node_draw_shadow */+ const float shadow[4] = {0.0f, 0.0f, 0.0f, 0.25f};+ bk_roundbox(x - 1.0f * s, y + 1.0f * s, w + 2.0f * s, h + 2.0f * s, rad + s, CNR_ALL, shadow);+ /* body (TH_NODE) and header (the node class color) */+ float body[4], head[4];+ color_u(0x303030ff, body); /* space_node.syntaxl */+ memcpy(head, node->color, sizeof(head));+ head[3] = 1.0f;+ bk_roundbox(x, y, w, h, rad, CNR_ALL, body);+ bk_roundbox(x, y, w, hh, rad, g->collapsed ? CNR_ALL : (CNR_TL | CNR_TR), head);+ /* the outline: node_outline, or select / active */+ float line[4];+ color_u(g->active && selected ? 0xffffffff : (selected ? 0xed5700ff : 0xffffff26), line);+ BuiWidgetBase wb = {{x, y, w, h}, rad, rad - 1.0f, CNR_ALL};+ memcpy(wb.outline, line, sizeof(line));+ wb.pixelsize = selected ? 1.5f * bk_scale_fac : 1.0f;+ BUI_raster_widget_base(bk_draw.r, &wb);++ const float prev = bk_text_scale;+ bk_text_scale = ed(e)->zoom;+ /* header: the collapse arrow, then the title (node_draw_basis) */+ uchar tc[4] = {230, 230, 230, 255};+ const float arrow_x = x + 0.5f * u() * ed(e)->zoom;+ bk_icon(bk_icons_lookup(g->collapsed ? "RIGHTARROW" : "DOWNARROW_HLT"), arrow_x,+ y + hh * 0.5f, tc, 0.8f, 0.8f * u() * ed(e)->zoom);+ if (s > 0.3f) {+ BKRect tr = bk_rect((int)(x + 1.0f * u() * ed(e)->zoom - bk_pad()), (int)y,+ (int)(w - 1.2f * u() * ed(e)->zoom), (int)hh);+ bk_text_in(&tr, node->label ? node->label : "", tc, BK_ALIGN_LEFT, false);+ }+ /* sockets and their rows */+ for (int pass = 0; pass < 2; pass++) {+ const bool input = pass == 1;+ const int count = sock_count(node, input);+ for (int k = 0; k < count; k++) {+ Sock so;+ sock_get(node, input, k, &so);+ const float cy = sy(e, socket_y(node, input, k));+ if (!g->collapsed && s > 0.3f) {+ const float m = NODE_DYS * s; /* content margin */+ BKRect row = bk_rect((int)(x + m), (int)(cy - hh * 0.5f), (int)(w - 2 * m), (int)hh);+ if (input && so.value[0] && !input_linked(e, index, k, NULL)) {+ draw_input_field(row, so.name, so.value);+ }+ else {+ uchar lc[4];+ memcpy(lc, bk_theme.text, 4);+ bk_text_in_pad(&row, so.name, lc, input ? BK_ALIGN_LEFT : BK_ALIGN_RIGHT, false, 0);+ }+ }+ draw_socket(input ? x : x + w, cy, so.type, s);+ }+ }+ bk_text_scale = prev;+}++static void link_ends(const BKNode *e, const Link *l, float *x0, float *y0, float *x1, float *y1)+{+ const BKNode *a = e->kids[l->from], *b = e->kids[l->to];+ *x0 = sx(e, socket_x(a, false));+ *y0 = sy(e, socket_y(a, false, l->out));+ *x1 = sx(e, socket_x(b, true));+ *y1 = sy(e, socket_y(b, true, l->in));+}++static void editor_draw(BKNode *e)+{+ float back[4];+ color_u(0x1d1d1dff, back); /* space_node.back */+ bk_fill_f((float)e->x, (float)e->y, (float)e->w, (float)e->h, back);+ bk_clip_push(e->x, e->y, e->w, e->h);+ draw_grid(e);+ NodeEdit *d = ed(e);+ /* links under the nodes */+ Link l[MAX_LINKS];+ const int count = links_get(e, l, MAX_LINKS);+ for (int i = 0; i < count; i++) {+ Sock so;+ if (!sock_get(e->kids[l[i].from], false, l[i].out, &so)) {+ continue;+ }+ float c[4], x0, y0, x1, y1;+ socket_color(so.type, c);+ link_ends(e, &l[i], &x0, &y0, &x1, &y1);+ const bool hi = (e->kids[l[i].from]->flags | e->kids[l[i].to]->flags) & NF_SELECTED;+ draw_noodle(x0, y0, x1, y1, c, hi, d->zoom);+ }+ for (int i = 0; i < e->nkids; i++) {+ if (e->kids[i]->cls == &bk_cls_graphnode && NODE_VISIBLE(e->kids[i])) {+ draw_node(e, e->kids[i], i);+ }+ }+ /* the link being dragged (node_draw_link_dragged) */+ if (d->mode == M_LINK) {+ Sock so;+ BKNode *fixed = e->kids[d->link_node];+ sock_get(fixed, !d->link_from_output, d->link_sock, &so);+ float c[4];+ socket_color(so.type, c);+ const float fx = sx(e, socket_x(fixed, !d->link_from_output));+ const float fy = sy(e, socket_y(fixed, !d->link_from_output, d->link_sock));+ if (d->link_from_output) {+ draw_noodle(fx, fy, (float)d->cur_x, (float)d->cur_y, c, true, d->zoom);+ }+ else {+ draw_noodle((float)d->cur_x, (float)d->cur_y, fx, fy, c, true, d->zoom);+ }+ }+ /* box select (WM_gesture_box) */+ if (d->mode == M_BOX) {+ const float x0 = (float)BK_MIN(d->press_x, d->cur_x), y0 = (float)BK_MIN(d->press_y, d->cur_y);+ const float bw = (float)abs(d->cur_x - d->press_x), bh = (float)abs(d->cur_y - d->press_y);+ const float fill[4] = {1.0f, 1.0f, 1.0f, 0.05f}, edge[4] = {1.0f, 1.0f, 1.0f, 0.6f};+ bk_fill_f(x0, y0, bw, bh, fill);+ BUI_raster_frame_rect(bk_draw.r, x0, y0, bw, bh, 1.0f, edge);+ }+ /* the cut line (WM_gesture_lines) */+ if (d->mode == M_CUT) {+ const float c[4] = {1.0f, 1.0f, 1.0f, 0.7f};+ for (int i = 0; i + 1 < d->ncut; i++) {+ bk_line(d->cut[i][0], d->cut[i][1], d->cut[i + 1][0], d->cut[i + 1][1], c, 1.0f);+ }+ }+ bk_clip_pop();+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Picking+ * \{ */++/* The topmost node under a point (the last drawn wins). */+static int node_at(const BKNode *e, int x, int y)+{+ const float gx = gx_of(e, (float)x), gy = gy_of(e, (float)y);+ for (int i = e->nkids - 1; i >= 0; i--) {+ const BKNode *node = e->kids[i];+ const GNode *g = gn(node);+ if (gx >= g->x && gx <= g->x + g->width && gy >= g->y && gy <= g->y + node_height(node)) {+ return i;+ }+ }+ return -1;+}++/* node_find_indicated_socket: the socket near a point. */+static bool socket_at(const BKNode *e, int x, int y, int *r_node, bool *r_input, int *r_k)+{+ const float s = scale_of(e);+ const float reach = BK_MAX(6.0f, (NODE_SOCKSIZE + 4.0f) * s);+ float best = reach * reach;+ bool found = false;+ for (int i = e->nkids - 1; i >= 0; i--) {+ const BKNode *node = e->kids[i];+ for (int pass = 0; pass < 2; pass++) {+ const bool input = pass == 1;+ const int count = sock_count(node, input);+ for (int k = 0; k < count; k++) {+ const float dx = sx(e, socket_x(node, input)) - x, dy = sy(e, socket_y(node, input, k)) - y;+ const float d2 = dx * dx + dy * dy;+ if (d2 < best) {+ best = d2;+ *r_node = i;+ *r_input = input;+ *r_k = k;+ found = true;+ }+ }+ }+ }+ return found;+}++/* An unlinked input's field under a point. */+static bool field_at(const BKNode *e, int x, int y, int *r_node, int *r_k)+{+ const int i = node_at(e, x, y);+ if (i < 0 || gn(e->kids[i])->collapsed) {+ return false;+ }+ const BKNode *node = e->kids[i];+ const float s = scale_of(e);+ const float gx0 = sx(e, gn(node)->x) + NODE_DYS * s, gx1 = gx0 + (gn(node)->width - 2 * NODE_DYS) * s;+ if (x < gx0 || x > gx1) {+ return false;+ }+ const int count = sock_count(node, true);+ for (int k = 0; k < count; k++) {+ Sock so;+ sock_get(node, true, k, &so);+ const float cy = sy(e, socket_y(node, true, k));+ if (so.value[0] && fabsf(y - cy) <= NODE_DY * s * 0.5f && !input_linked(e, i, k, NULL)) {+ *r_node = i;+ *r_k = k;+ return true;+ }+ }+ return false;+}++/** \} */++/* -------------------------------------------------------------------- */+/** \name Operators+ * \{ */++static void select_node(BKNode *e, BKNode *node, bool on)+{+ const bool was = (node->flags & NF_SELECTED) != 0;+ node->flags = on ? (node->flags | NF_SELECTED) : (node->flags & ~NF_SELECTED);+ if (was != on) {+ bk_emit(node, BK_EV_CHANGE, NULL, EV_SELECT, on);+ }+}++static void set_active(BKNode *e, BKNode *node)+{+ for (int i = 0; i < e->nkids; i++) {+ gn(e->kids[i])->active = e->kids[i] == node;+ }+}++/* node_sort: the active node draws on top. Moves the node to the end of the+ * children; link indices follow. */+static void raise_node(BKNode *e, int index)+{+ if (index < 0 || index == e->nkids - 1) {+ return;+ }+ BKNode *node = e->kids[index];+ for (int i = index; i < e->nkids - 1; i++) {+ e->kids[i] = e->kids[i + 1];+ }+ e->kids[e->nkids - 1] = node;+ /* remap links: index -> last, the ones after it shift down */+ Link l[MAX_LINKS];+ const int count = links_get(e, l, MAX_LINKS);+ const int last = e->nkids - 1;+ for (int i = 0; i < count; i++) {+ int *ends[2] = {&l[i].from, &l[i].to};+ for (int k = 0; k < 2; k++) {+ *ends[k] = *ends[k] == index ? last : (*ends[k] > index ? *ends[k] - 1 : *ends[k]);+ }+ }+ if (count) {+ links_set_ex(e, l, count, false); /* the same links, renumbered */+ }+ bk_emit(e, BK_EV_CHANGE, NULL, EV_LINKS + 2, index); /* a = 12: node order changed */+}++static void view_all(BKNode *e)+{+ NodeEdit *d = ed(e);+ if (e->nkids == 0) {+ d->zoom = 1.0f;+ d->panx = e->w * 0.5f;+ d->pany = e->h * 0.5f;+ return;+ }+ float x0 = 1e30f, y0 = 1e30f, x1 = -1e30f, y1 = -1e30f;+ for (int i = 0; i < e->nkids; i++) {+ const GNode *g = gn(e->kids[i]);+ x0 = BK_MIN(x0, g->x);+ y0 = BK_MIN(y0, g->y);+ x1 = BK_MAX(x1, g->x + g->width);+ y1 = BK_MAX(y1, g->y + node_height(e->kids[i]));+ }+ const float margin = 2.0f * u();+ const float bw = (x1 - x0) * bk_scale_fac, bh = (y1 - y0) * bk_scale_fac;+ float z = BK_MIN((e->w - 2 * margin) / BK_MAX(1.0f, bw), (e->h - 2 * margin) / BK_MAX(1.0f, bh));+ d->zoom = BK_CLAMP(z, 0.09f, 1.0f); /* space_node_view_flag: don't zoom past 1 */+ d->panx = e->w * 0.5f - (x0 + x1) * 0.5f * scale_of(e);+ d->pany = e->h * 0.5f - (y0 + y1) * 0.5f * scale_of(e);+}++static void zoom_at(BKNode *e, float factor, int x, int y)+{+ NodeEdit *d = ed(e);+ const float gx = gx_of(e, (float)x), gy = gy_of(e, (float)y);+ d->zoom = BK_CLAMP(d->zoom * factor, 0.09f, 2.31f); /* SpaceNode v2d min/max zoom */+ d->panx = x - e->x - gx * scale_of(e);+ d->pany = y - e->y - gy * scale_of(e);+ bk_invalidate(e);+}++static bool segments_cross(const float a[2], const float b[2], const float c[2], const float d[2])+{+ const float d1 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);+ const float d2 = (b[0] - a[0]) * (d[1] - a[1]) - (b[1] - a[1]) * (d[0] - a[0]);+ const float d3 = (d[0] - c[0]) * (a[1] - c[1]) - (d[1] - c[1]) * (a[0] - c[0]);+ const float d4 = (d[0] - c[0]) * (b[1] - c[1]) - (d[1] - c[1]) * (b[0] - c[0]);+ return (d1 > 0) != (d2 > 0) && (d3 > 0) != (d4 > 0);+}++/* NODE_OT_links_cut: remove the links the stroke crosses. */+static void cut_links(BKNode *e)+{+ NodeEdit *d = ed(e);+ Link l[MAX_LINKS], keep[MAX_LINKS];+ const int count = links_get(e, l, MAX_LINKS);+ int kept = 0;+ enum { N = NODE_LINK_RESOL * 2 };+ for (int i = 0; i < count; i++) {+ float x0, y0, x1, y1, pts[N + 1][2];+ link_ends(e, &l[i], &x0, &y0, &x1, &y1);+ bezier_points(x0, y0, x1, y1, pts, N);+ bool cut = false;+ for (int a = 0; a < N && !cut; a++) {+ for (int b = 0; b + 1 < d->ncut && !cut; b++) {+ cut = segments_cross(pts[a], pts[a + 1], d->cut[b], d->cut[b + 1]);+ }+ }+ if (!cut) {+ keep[kept++] = l[i];+ }+ }+ if (kept != count) {+ links_set(e, keep, kept);+ }+}++/* node_link_insert / add: an input takes one link, replacing the old one. */+static void add_link(BKNode *e, int from, int out, int to, int in)+{+ if (from == to) {+ return;+ }+ Link l[MAX_LINKS];+ int count = links_get(e, l, MAX_LINKS), w = 0;+ for (int i = 0; i < count; i++) {+ if (!(l[i].to == to && l[i].in == in)) {+ l[w++] = l[i];+ }+ }+ if (w < MAX_LINKS) {+ l[w++] = (Link){from, out, to, in};+ }+ links_set(e, l, w);+}++static void remove_input_link(BKNode *e, int to, int in)+{+ Link l[MAX_LINKS];+ int count = links_get(e, l, MAX_LINKS), w = 0;+ for (int i = 0; i < count; i++) {+ if (!(l[i].to == to && l[i].in == in)) {+ l[w++] = l[i];+ }+ }+ links_set(e, l, w);+}++static void set_input_value(BKNode *node, int k, double v)+{+ Sock so;+ if (!sock_get(node, true, k, &so)) {+ return;+ }+ const bool is_int = strcmp(so.type, "int") == 0;+ char buf[160];+ if (is_int) {+ snprintf(buf, sizeof(buf), "i|%s|%s|%d", so.name, so.type, (int)v);+ }+ else {+ snprintf(buf, sizeof(buf), "i|%s|%s|%.3f", so.name, so.type, v);+ }+ free(node->items.v[so.item]);+ node->items.v[so.item] = strdup(buf);+ bk_invalidate(node->parent);+ bk_emit(node, BK_EV_CHANGE, NULL, EV_VALUE, k);+}++static int editor_press(BKNode *e, BKEvent *ev)+{+ NodeEdit *d = ed(e);+ d->press_x = d->cur_x = ev->x;+ d->press_y = d->cur_y = ev->y;+ d->start_panx = d->panx;+ d->start_pany = d->pany;+ d->start_zoom = d->zoom;+ d->shift = EV_SHIFT(ev);+ d->hit = NULL;+ if (ev->mods & BK_BUTTON2) { /* VIEW2D_OT_pan, Ctrl: VIEW2D_OT_zoom */+ d->mode = EV_CTRL(ev) ? M_ZOOM : M_PAN;+ return 1;+ }+ if (ev->mods & BK_BUTTON3) { /* Ctrl+RMB: NODE_OT_links_cut */+ d->mode = EV_CTRL(ev) ? M_CUT : M_NONE;+ d->ncut = 0;+ return 1;+ }+ int ni, k;+ bool input;+ if (socket_at(e, ev->x, ev->y, &ni, &input, &k)) { /* NODE_OT_link */+ Link old;+ if (input && input_linked(e, ni, k, &old)) {+ /* pick up the link from the input: drag it from its output */+ remove_input_link(e, ni, k);+ d->link_node = old.from;+ d->link_sock = old.out;+ d->link_from_output = true;+ }+ else {+ d->link_node = ni;+ d->link_sock = k;+ d->link_from_output = !input;+ }+ d->mode = M_LINK;+ bk_invalidate(e);+ return 1;+ }+ if (field_at(e, ev->x, ev->y, &ni, &k)) { /* a node's number field */+ Sock so;+ sock_get(e->kids[ni], true, k, &so);+ d->mode = M_VALUE;+ d->value_node = ni;+ d->value_sock = k;+ d->value_start = atof(so.value);+ return 1;+ }+ const int i = node_at(e, ev->x, ev->y);+ if (i >= 0) { /* NODE_OT_select, then NODE_OT_translate on drag */+ BKNode *node = e->kids[i];+ const GNode *g = gn(node);+ const float s = scale_of(e);+ /* the collapse arrow in the header */+ if (ev->x < sx(e, g->x) + 1.0f * u() * d->zoom && ev->y < sy(e, g->y) + NODE_DY * s) {+ gn(node)->collapsed = !g->collapsed;+ bk_emit(node, BK_EV_CHANGE, NULL, EV_COLLAPSE, gn(node)->collapsed);+ d->mode = M_NONE;+ bk_invalidate(e);+ return 1;+ }+ if (EV_SHIFT(ev)) {+ select_node(e, node, !(node->flags & NF_SELECTED) || !g->active);+ }+ else if (!(node->flags & NF_SELECTED)) {+ for (int j = 0; j < e->nkids; j++) {+ select_node(e, e->kids[j], e->kids[j] == node);+ }+ }+ if (node->flags & NF_SELECTED) {+ set_active(e, node);+ }+ raise_node(e, i);+ d->hit = node;+ d->mode = M_MOVE;+ for (int j = 0; j < e->nkids; j++) { /* remember where they began */+ e->kids[j]->drag_x0 = gn(e->kids[j])->x;+ e->kids[j]->drag_start = gn(e->kids[j])->y;+ }+ bk_invalidate(e);+ return 1;+ }+ d->mode = M_BOX; /* tweak on empty space: box select; a click deselects */+ return 1;+}++static int editor_drag(BKNode *e, BKEvent *ev)+{+ NodeEdit *d = ed(e);+ d->cur_x = ev->x;+ d->cur_y = ev->y;+ switch (d->mode) {+ case M_PAN:+ d->panx = d->start_panx + ev->dx;+ d->pany = d->start_pany + ev->dy;+ break;+ case M_ZOOM: {+ const float f = powf(1.005f, (float)(ev->dx - ev->dy));+ d->zoom = d->start_zoom;+ d->panx = d->start_panx;+ d->pany = d->start_pany;+ zoom_at(e, f, d->press_x, d->press_y);+ break;+ }+ case M_MOVE: {+ const float s = scale_of(e);+ for (int j = 0; j < e->nkids; j++) {+ BKNode *node = e->kids[j];+ if (node->flags & NF_SELECTED) {+ float nx = (float)node->drag_x0 + ev->dx / s, ny = (float)node->drag_start + ev->dy / s;+ if (EV_CTRL(ev)) { /* snapping to the grid */+ nx = roundf(nx / NODE_DY) * NODE_DY;+ ny = roundf(ny / NODE_DY) * NODE_DY;+ }+ gn(node)->x = nx;+ gn(node)->y = ny;+ }+ }+ break;+ }+ case M_VALUE: {+ BKNode *node = e->kids[d->value_node];+ Sock so;+ sock_get(node, true, d->value_sock, &so);+ const bool is_int = strcmp(so.type, "int") == 0;+ /* numedit_but_NUM: floats 0.01 per pixel (Shift: a tenth), ints 1/16 */+ const double fac = is_int ? 1.0 / 16.0 : (EV_SHIFT(ev) ? 0.001 : 0.01);+ double v = d->value_start + ev->dx * fac;+ if (EV_CTRL(ev)) {+ v = is_int ? 10.0 * (long)(v / 10.0) : round(v * 10.0) * 0.1;+ }+ set_input_value(node, d->value_sock, v);+ break;+ }+ case M_CUT:+ if (d->ncut < MAX_CUT) {+ d->cut[d->ncut][0] = (float)ev->x;+ d->cut[d->ncut][1] = (float)ev->y;+ d->ncut++;+ }+ break;+ default:+ break;+ }+ bk_invalidate(e);+ return 1;+}++static int editor_release(BKNode *e, BKEvent *ev)+{+ NodeEdit *d = ed(e);+ const Mode mode = d->mode;+ d->mode = M_NONE;+ switch (mode) {+ case M_LINK: {+ int ni, k;+ bool input;+ if (socket_at(e, ev->x, ev->y, &ni, &input, &k) && input == d->link_from_output) {+ if (d->link_from_output) {+ add_link(e, d->link_node, d->link_sock, ni, k);+ }+ else {+ add_link(e, ni, k, d->link_node, d->link_sock);+ }+ }+ break;+ }+ case M_MOVE:+ if (ev->dragged) {+ for (int j = 0; j < e->nkids; j++) {+ if (e->kids[j]->flags & NF_SELECTED) {+ bk_emit(e->kids[j], BK_EV_CHANGE, NULL, EV_MOVED, 0);+ }+ }+ }+ else if (d->hit && !d->shift) { /* a click selects only that node */+ for (int j = 0; j < e->nkids; j++) {+ select_node(e, e->kids[j], e->kids[j] == d->hit);+ }+ }+ break;+ case M_BOX: {+ if (!ev->dragged) {+ for (int j = 0; j < e->nkids; j++) {+ select_node(e, e->kids[j], false);+ }+ break;+ }+ const float x0 = gx_of(e, (float)BK_MIN(d->press_x, ev->x));+ const float x1 = gx_of(e, (float)BK_MAX(d->press_x, ev->x));+ const float y0 = gy_of(e, (float)BK_MIN(d->press_y, ev->y));+ const float y1 = gy_of(e, (float)BK_MAX(d->press_y, ev->y));+ for (int j = 0; j < e->nkids; j++) {+ const GNode *g = gn(e->kids[j]);+ const bool in = g->x < x1 && g->x + g->width > x0 && g->y < y1 &&+ g->y + node_height(e->kids[j]) > y0;+ if (in) {+ select_node(e, e->kids[j], true);+ }+ else if (!d->shift) {+ select_node(e, e->kids[j], false);+ }+ }+ break;+ }+ case M_CUT:+ cut_links(e);+ break;+ default:+ break;+ }+ bk_invalidate(e);+ return 1;+}++static void editor_cancel(BKNode *e)+{+ NodeEdit *d = ed(e);+ if (d->mode == M_MOVE) {+ for (int j = 0; j < e->nkids; j++) {+ gn(e->kids[j])->x = (float)e->kids[j]->drag_x0;+ gn(e->kids[j])->y = (float)e->kids[j]->drag_start;+ }+ }+ else if (d->mode == M_PAN || d->mode == M_ZOOM) {+ d->panx = d->start_panx;+ d->pany = d->start_pany;+ d->zoom = d->start_zoom;+ }+ else if (d->mode == M_VALUE) {+ set_input_value(e->kids[d->value_node], d->value_sock, d->value_start);+ }+ d->mode = M_NONE;+ bk_invalidate(e);+}++static int editor_wheel(BKNode *e, BKEvent *ev)+{+ NodeEdit *d = ed(e);+ const float step = 2.0f * u(); /* view2d scroll step */+ if (EV_CTRL(ev)) { /* VIEW2D_OT_scroll_right / left */+ d->panx += ev->delta * step;+ }+ else if (EV_SHIFT(ev)) { /* VIEW2D_OT_scroll_up / down */+ d->pany += ev->delta * step;+ }+ else { /* VIEW2D_OT_zoom_in / out about the cursor */+ zoom_at(e, ev->delta > 0 ? 1.25f : 0.8f, ev->x, ev->y);+ }+ bk_invalidate(e);+ return 1;+}++static int editor_key(BKNode *e, BKEvent *ev)+{+ const char *k = ev->keysym;+ if (bk_keysym_is(k, "x") || bk_keysym_is(k, "Delete")) { /* NODE_OT_delete */+ bk_emit(e, BK_EV_CHANGE, NULL, EV_DELETE, 0);+ return 1;+ }+ if (bk_keysym_is(k, "a")) { /* NODE_OT_select_all, Alt: deselect */+ for (int j = 0; j < e->nkids; j++) {+ select_node(e, e->kids[j], !EV_ALT(ev));+ }+ bk_invalidate(e);+ return 1;+ }+ if (bk_keysym_is(k, "Home")) { /* NODE_OT_view_all */+ view_all(e);+ bk_invalidate(e);+ return 1;+ }+ if (bk_keysym_is(k, "h") && !EV_CTRL(ev)) { /* NODE_OT_hide_toggle */+ for (int j = 0; j < e->nkids; j++) {+ if (e->kids[j]->flags & NF_SELECTED) {+ gn(e->kids[j])->collapsed = !gn(e->kids[j])->collapsed;+ bk_emit(e->kids[j], BK_EV_CHANGE, NULL, EV_COLLAPSE, gn(e->kids[j])->collapsed);+ }+ }+ bk_invalidate(e);+ return 1;+ }+ return 0;+}++static void editor_init(BKNode *e)+{+ NodeEdit *d = (NodeEdit *)calloc(1, sizeof(NodeEdit));+ d->zoom = 1.0f;+ d->panx = d->pany = -1e30f; /* centered on the first layout */+ e->ext = d;+}++static void editor_free(BKNode *e)+{+ free(e->ext);+ e->ext = NULL;+}++static void editor_measure(BKNode *e, int *rw, int *rh)+{+ *rw = 20 * u();+ *rh = 14 * u();+}++static void editor_arrange(BKNode *e)+{+ NodeEdit *d = ed(e);+ if (d->panx < -1e29f && e->w > 0) {+ view_all(e);+ }+ for (int i = 0; i < e->nkids; i++) { /* nodes are drawn by the editor */+ e->kids[i]->x = e->kids[i]->y = e->kids[i]->w = e->kids[i]->h = 0;+ }+}++static BKNode *editor_hit(BKNode *e, int x, int y)+{+ return e;+}++static int editor_cursor_at(BKNode *e, int x, int y)+{+ return ed(e)->mode == M_PAN ? BK_CURSOR_MOVE : BK_CURSOR_DEFAULT;+}++static int editor_set_num(BKNode *e, const char *key, double v)+{+ NodeEdit *d = ed(e);+ if (strcmp(key, "zoom") == 0) {+ d->zoom = (float)BK_CLAMP(v, 0.09, 2.31);+ }+ else if (strcmp(key, "view_all") == 0) {+ view_all(e);+ }+ else if (strcmp(key, "panx") == 0) {+ d->panx = (float)v;+ }+ else if (strcmp(key, "pany") == 0) {+ d->pany = (float)v;+ }+ else {+ return 0;+ }+ bk_invalidate(e);+ return 1;+}++static int editor_get_num(BKNode *e, const char *key, double *r)+{+ if (strcmp(key, "zoom") == 0) {+ *r = ed(e)->zoom;+ return 1;+ }+ if (strcmp(key, "panx") == 0 || strcmp(key, "pany") == 0) {+ *r = key[3] == 'x' ? ed(e)->panx : ed(e)->pany;+ return 1;+ }+ return 0;+}++const BKClass bk_cls_nodeeditor = {.name = "nodeeditor",+ .flags = CLS_INTERACTIVE | CLS_BUTTONS,+ .init = editor_init,+ .free_ext = editor_free,+ .measure = editor_measure,+ .arrange = editor_arrange,+ .draw = editor_draw,+ .draw_tree = editor_draw,+ .hit = editor_hit,+ .press = editor_press,+ .drag = editor_drag,+ .release = editor_release,+ .cancel = editor_cancel,+ .wheel = editor_wheel,+ .key = editor_key,+ .cursor_at = editor_cursor_at,+ .set_num = editor_set_num,+ .get_num = editor_get_num};++/** \} */diff --git a/kit/intern/kit_regions.c b/kit/intern/kit_regions.cindex e84a415..c8c6017 100644--- a/kit/intern/kit_regions.c+++ b/kit/intern/kit_regions.c@@ -297,3 +297,87 @@ const BKClass bk_cls_sidebar = {.name = "sidebar",.wheel = sidebar_wheel};/** \} */++/* -------------------------------------------------------------------- */+/** \name Area header (ED_region_header_layout)+ * \{ */++/* HEADERY: 20 + HEADER_PADDING_Y (6), scaled */+static int header_h(void)+{+ return bk_iround(26.0f * bk_scale_fac);+}++static bool is_spacer(const BKNode *c)+{+ return c->cls == &bk_cls_separator && c->weight > 0.0f;+}++static void areaheader_measure(BKNode *n, int *rw, int *rh)+{+ const int gap = bk_iround(0.2f * u());+ int w = bk_iround(8.0f * bk_scale_fac) * 2;+ for (int i = 0; i < n->nkids; i++) {+ if (NODE_VISIBLE(n->kids[i]) && !is_spacer(n->kids[i])) {+ int cw, ch;+ bk_natural(n->kids[i], &cw, &ch);+ w += cw + gap;+ }+ }+ *rw = w;+ *rh = header_h();+}++/* Items from UI_HEADER_OFFSET, left to right, buttons one unit tall and+ * centered; spacers (layout.separator_spacer) share the spare width. */+static void areaheader_arrange(BKNode *n)+{+ const int gap = bk_iround(0.2f * u()), ofs = bk_iround(8.0f * bk_scale_fac);+ int used = 0, spacers = 0;+ for (int i = 0; i < n->nkids; i++) {+ BKNode *c = n->kids[i];+ if (!NODE_VISIBLE(c)) {+ continue;+ }+ if (is_spacer(c)) {+ spacers++;+ continue;+ }+ int cw, ch;+ bk_natural(c, &cw, &ch);+ used += cw + gap;+ }+ const int spare = BK_MAX(0, n->w - 2 * ofs - used);+ const int y = n->y + (n->h - u()) / 2;+ int x = n->x + ofs;+ for (int i = 0; i < n->nkids; i++) {+ BKNode *c = n->kids[i];+ if (!NODE_VISIBLE(c)) {+ continue;+ }+ if (is_spacer(c)) {+ const int sw = spacers ? spare / spacers : 0;+ bk_arrange(c, x, y, sw, u());+ x += sw;+ continue;+ }+ int cw, ch;+ bk_natural(c, &cw, &ch);+ bk_arrange(c, x, y, cw, u());+ x += cw + gap;+ }+}++static void areaheader_draw(BKNode *n)+{+ /* TH_HEADER of the editors (space_view3d.header and friends) */+ const uchar c[4] = {0x30, 0x30, 0x30, 0xff};+ bk_fill(n->x, n->y, n->w, n->h, c);+}++const BKClass bk_cls_areaheader = {.name = "areaheader",+ .measure = areaheader_measure,+ .arrange = areaheader_arrange,+ .draw = areaheader_draw};++/** \} */diff --git a/kit/intern/kit_window_null.c b/kit/intern/kit_window_null.cnew file mode 100644index 0000000..115000d--- /dev/null+++ b/kit/intern/kit_window_null.c@@ -0,0 +1,81 @@+/* No native window host on this platform: BK_window_supported() returns 0+ * and hosts use Tk/Qt.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include "kit_intern.h"++#if !defined(_WIN32) && !defined(BUI_WINDOW_X11)+++int BK_window_supported(void)+{+ return 0;+}+BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)+{+ return NULL;+}+void BK_window_free(BKWindow *win) {}+void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb) {}+void BK_window_show(BKWindow *win) {}+void BK_window_close(BKWindow *win) {}+int BK_window_is_open(BKWindow *win)+{+ return 0;+}+void BK_window_set_title(BKWindow *win, const char *title) {}+void BK_window_set_size(BKWindow *win, int width, int height) {}+void BK_window_get_size(BKWindow *win, int *w, int *h)+{+ *w = *h = 0;+}+BuiRaster *BK_window_raster(BKWindow *win)+{+ return NULL;+}+void BK_window_set_gpu(BKWindow *win, int on) {}+int BK_window_gpu(BKWindow *win)+{+ return 0;+}+int BK_window_frames(BKWindow *win)+{+ return 0;+}+void BK_window_render_now(BKWindow *win) {}+int BK_window_timer(BKWindow *win, int ms)+{+ return 0;+}+void BK_window_cancel_timer(BKWindow *win, int id) {}+void BK_window_request_frame(BKWindow *win, int vsync) {}+void *BK_window_handle(BKWindow *win)+{+ return NULL;+}+void BK_window_wm(BKWindow *win, const char *key, double a, double b) {}+int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)+{+ *r_a = *r_b = 0.0;+ return 0;+}+void BK_window_run(void) {}+int BK_window_pump(void)+{+ return 0;+}+void BK_window_quit(void) {}+void BK_window_set_stop_check(int (*stop)(void)) {}+int BK_window_wake_init(void (*cb)(void))+{+ (void)cb;+ return 0;+}+void BK_window_wake(void) {}+void BK_window_set_keep_alive(int on)+{+ (void)on;+}++#endifdiff --git a/kit/intern/kit_window.c b/kit/intern/kit_window_win32.csimilarity index 93%rename from kit/intern/kit_window.crename to kit/intern/kit_window_win32.cindex c73eac5..e055c6f 100644--- a/kit/intern/kit_window.c+++ b/kit/intern/kit_window_win32.c@@ -1,4 +1,5 @@-/* Native window host (Win32).+/* Native window host (Win32). Other platforms: kit_window_x11.c (X11),+ * kit_window_null.c (none).** A plain HWND that owns a BuiRaster and drives a BKContext: mouse and* keyboard messages go straight to BK_* input, redraw requests coalesce into@@ -6,8 +7,6 @@* BUI_raster_present_native. Nothing on the input -> render -> present path* leaves C. Animations run vsync-paced (DwmFlush).*- * Other platforms: BK_window_supported() returns 0 (hosts use Tk/Qt).- ** SPDX-License-Identifier: GPL-2.0-or-later */#include <stdio.h>@@ -946,76 +945,4 @@ int BK_window_pump(void)return g_open;}-#else /* !_WIN32 */--int BK_window_supported(void)-{- return 0;-}-BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)-{- return NULL;-}-void BK_window_free(BKWindow *win) {}-void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb) {}-void BK_window_show(BKWindow *win) {}-void BK_window_close(BKWindow *win) {}-int BK_window_is_open(BKWindow *win)-{- return 0;-}-void BK_window_set_title(BKWindow *win, const char *title) {}-void BK_window_set_size(BKWindow *win, int width, int height) {}-void BK_window_get_size(BKWindow *win, int *w, int *h)-{- *w = *h = 0;-}-BuiRaster *BK_window_raster(BKWindow *win)-{- return NULL;-}-void BK_window_set_gpu(BKWindow *win, int on) {}-int BK_window_gpu(BKWindow *win)-{- return 0;-}-int BK_window_frames(BKWindow *win)-{- return 0;-}-void BK_window_render_now(BKWindow *win) {}-int BK_window_timer(BKWindow *win, int ms)-{- return 0;-}-void BK_window_cancel_timer(BKWindow *win, int id) {}-void BK_window_request_frame(BKWindow *win, int vsync) {}-void *BK_window_handle(BKWindow *win)-{- return NULL;-}-void BK_window_wm(BKWindow *win, const char *key, double a, double b) {}-int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)-{- *r_a = *r_b = 0.0;- return 0;-}-void BK_window_run(void) {}-int BK_window_pump(void)-{- return 0;-}-void BK_window_quit(void) {}-void BK_window_set_stop_check(int (*stop)(void)) {}-int BK_window_wake_init(void (*cb)(void))-{- (void)cb;- return 0;-}-void BK_window_wake(void) {}-void BK_window_set_keep_alive(int on)-{- (void)on;-}--#endif+#endif /* _WIN32 */diff --git a/kit/intern/kit_window_x11.c b/kit/intern/kit_window_x11.cnew file mode 100644index 0000000..03c8745--- /dev/null+++ b/kit/intern/kit_window_x11.c@@ -0,0 +1,910 @@+/* Native window host (X11, also Wayland through XWayland).+ *+ * The same BK_window_* API as kit_window_win32.c, on Xlib: input events go+ * straight to BK_* input (button and key mapping after Blender's+ * GHOST_SystemX11), redraw requests coalesce into one render per loop turn,+ * and the damaged rectangles of the CPU raster are put with XPutImage.+ * Timers, the cross-thread wake (a pipe) and frame pacing run in the select()+ * loop.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include "kit_intern.h"++#ifdef BUI_WINDOW_X11++# include <X11/Xatom.h>+# include <X11/Xlib.h>+# include <X11/Xresource.h>+# include <X11/Xutil.h>+# include <X11/cursorfont.h>+# include <X11/keysym.h>++# include <errno.h>+# include <fcntl.h>+# include <math.h>+# include <stdio.h>+# include <stdlib.h>+# include <string.h>+# include <sys/select.h>+# include <time.h>+# include <unistd.h>++# define MAX_TIMERS 64++typedef struct Timer {+ int id; /* > 0 user timer, -1 the tooltip timer, 0 free */+ double due;+} Timer;++struct BKWindow {+ Window xid;+ BKContext *ctx;+ BKHost prev;+ BuiRaster *raster;+ BKWindowCallbacks cb;+ XImage *image;+ GC gc;+ int render_pending, frames, cursor, tip_id, next_timer, full;+ int want_frame, frame_vsync;+ double frame_start;+ float scale;+ int w, h;+ Timer timers[MAX_TIMERS];+ Cursor cursors[8];+ struct BKWindow *next;+};++static Display *g_dpy = NULL;+static Atom a_delete, a_clipboard, a_utf8, a_targets, a_bui_sel;+static BKWindow *g_windows = NULL;+static int g_open = 0, g_quit = 0, g_keep_alive = 0;+static int (*g_stop)(void) = NULL;+static void (*g_wake_cb)(void) = NULL;+static int g_wake_pipe[2] = {-1, -1};+static char *g_clip_text = NULL; /* what we own on CLIPBOARD */++static double now_ms(void)+{+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;+}++static int open_display(void)+{+ if (g_dpy) {+ return 1;+ }+ XInitThreads();+ g_dpy = XOpenDisplay(NULL);+ if (!g_dpy) {+ return 0;+ }+ a_delete = XInternAtom(g_dpy, "WM_DELETE_WINDOW", False);+ a_clipboard = XInternAtom(g_dpy, "CLIPBOARD", False);+ a_utf8 = XInternAtom(g_dpy, "UTF8_STRING", False);+ a_targets = XInternAtom(g_dpy, "TARGETS", False);+ a_bui_sel = XInternAtom(g_dpy, "BUI_SELECTION", False);+ return 1;+}++int BK_window_supported(void)+{+ return open_display();+}++/* Xft.dpi, as GHOST_SystemX11 reads it, else 96. */+static float display_scale(void)+{+ const char *env = getenv("BUI_UI_SCALE");+ if (env) {+ return (float)atof(env);+ }+ float dpi = 96.0f;+ char *rms = XResourceManagerString(g_dpy);+ if (rms) {+ XrmInitialize();+ XrmDatabase db = XrmGetStringDatabase(rms);+ char *type = NULL;+ XrmValue value;+ if (db && XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value) && value.addr) {+ dpi = (float)atof(value.addr);+ }+ if (db) {+ XrmDestroyDatabase(db);+ }+ }+ return BK_MAX(1.0f, dpi / 96.0f);+}++static BKWindow *find_window(Window xid)+{+ for (BKWindow *w = g_windows; w; w = w->next) {+ if (w->xid == xid) {+ return w;+ }+ }+ return NULL;+}++/* -- host callbacks -- */++static void host_request(void *data)+{+ BKWindow *win = (BKWindow *)data;+ if (win->xid) {+ win->render_pending = 1;+ }+}++/* GHOST_WindowX11::setWindowCursorShape */+static void host_set_cursor(void *data, int c)+{+ BKWindow *win = (BKWindow *)data;+ if (!win->xid) {+ return;+ }+ c = BK_CLAMP(c, 0, 7);+ win->cursor = c;+ if (!win->cursors[c]) {+ if (c == BK_CURSOR_NONE) { /* an empty 1x1 bitmap */+ static char zero = 0;+ Pixmap p = XCreateBitmapFromData(g_dpy, win->xid, &zero, 1, 1);+ XColor black = {0};+ win->cursors[c] = XCreatePixmapCursor(g_dpy, p, p, &black, &black, 0, 0);+ XFreePixmap(g_dpy, p);+ }+ else {+ static const unsigned shapes[8] = {XC_left_ptr, XC_sb_h_double_arrow,+ XC_sb_v_double_arrow, XC_xterm, XC_crosshair,+ XC_hand2, XC_fleur, XC_left_ptr};+ win->cursors[c] = XCreateFontCursor(g_dpy, shapes[c]);+ }+ }+ XDefineCursor(g_dpy, win->xid, win->cursors[c]);+ XFlush(g_dpy);+}++static void host_warp(void *data, int x, int y)+{+ BKWindow *win = (BKWindow *)data;+ if (win->xid) {+ XWarpPointer(g_dpy, None, win->xid, 0, 0, 0, 0, x, y);+ XFlush(g_dpy);+ }+}++static void handle_event(XEvent *ev);++/* GHOST_SystemX11::getClipboard: ask the owner, wait for its answer. */+static char *host_clipboard_get(void *data)+{+ BKWindow *win = (BKWindow *)data;+ if (XGetSelectionOwner(g_dpy, a_clipboard) == win->xid && g_clip_text) {+ return strdup(g_clip_text);+ }+ XConvertSelection(g_dpy, a_clipboard, a_utf8, a_bui_sel, win->xid, CurrentTime);+ XFlush(g_dpy);+ const double until = now_ms() + 300.0;+ while (now_ms() < until) {+ XEvent ev;+ if (XCheckTypedWindowEvent(g_dpy, win->xid, SelectionNotify, &ev)) {+ if (ev.xselection.property == None) {+ return NULL;+ }+ Atom type;+ int format;+ unsigned long n, after;+ unsigned char *prop = NULL;+ XGetWindowProperty(g_dpy, win->xid, a_bui_sel, 0, 1 << 24, True, AnyPropertyType, &type,+ &format, &n, &after, &prop);+ char *out = prop ? strndup((const char *)prop, n) : NULL;+ if (prop) {+ XFree(prop);+ }+ return out;+ }+ usleep(2000);+ }+ return NULL;+}++static void host_clipboard_set(void *data, const char *text)+{+ BKWindow *win = (BKWindow *)data;+ free(g_clip_text);+ g_clip_text = strdup(text ? text : "");+ XSetSelectionOwner(g_dpy, a_clipboard, win->xid, CurrentTime);+ XFlush(g_dpy);+}++static Timer *timer_slot(BKWindow *win, int id)+{+ for (int i = 0; i < MAX_TIMERS; i++) {+ if (win->timers[i].id == id) {+ return &win->timers[i];+ }+ }+ for (int i = 0; i < MAX_TIMERS; i++) {+ if (win->timers[i].id == 0) {+ return &win->timers[i];+ }+ }+ return NULL;+}++static void host_schedule(void *data, int ms, int timer)+{+ BKWindow *win = (BKWindow *)data;+ win->tip_id = timer;+ Timer *t = timer_slot(win, -1);+ if (t) {+ t->id = -1;+ t->due = now_ms() + ms;+ }+}++static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b)+{+ BKWindow *win = (BKWindow *)data;+ if (win->prev.emit) {+ win->prev.emit(win->prev.data, node, kind, ref, a, b);+ }+}++/* -- rendering -- */++static void present(BKWindow *win, int all)+{+ const int w = BUI_raster_width(win->raster), h = BUI_raster_height(win->raster);+ if (!win->image || win->image->width != w || win->image->height != h) {+ if (win->image) {+ win->image->data = NULL; /* the raster owns the pixels */+ XDestroyImage(win->image);+ }+ Visual *vis = DefaultVisual(g_dpy, DefaultScreen(g_dpy));+ win->image = XCreateImage(g_dpy, vis, 24, ZPixmap, 0, NULL, (unsigned)w, (unsigned)h, 32,+ w * 4);+ all = 1;+ }+ /* 0xAARRGGBB words are B, G, R, A bytes: the 24-bit TrueColor layout */+ win->image->data = (char *)BUI_raster_pixels(win->raster);+ if (all) {+ XPutImage(g_dpy, win->xid, win->gc, win->image, 0, 0, 0, 0, (unsigned)w, (unsigned)h);+ }+ else {+ const int(*rects)[4];+ const int n = BUI_raster_damage(win->raster, &rects);+ for (int i = 0; i < n; i++) {+ XPutImage(g_dpy, win->xid, win->gc, win->image, rects[i][0], rects[i][1], rects[i][0],+ rects[i][1], (unsigned)rects[i][2], (unsigned)rects[i][3]);+ }+ }+ XFlush(g_dpy);+}++static void do_render(BKWindow *win)+{+ const int w = BK_MAX(1, win->w), h = BK_MAX(1, win->h);+ const int resized = BUI_raster_width(win->raster) != w || BUI_raster_height(win->raster) != h;+ const int regions = BK_render(win->ctx, win->raster, w, h, win->full || resized);+ if (regions || resized || win->full) {+ present(win, resized || win->full);+ win->frames++;+ }+ win->full = 0;+}++static double refresh_ms(void)+{+ return 1000.0 / 60.0;+}++static void render_window(BKWindow *win)+{+ if (win->want_frame && win->cb.on_frame) {+ win->want_frame = 0;+ win->frame_start = now_ms();+ win->cb.on_frame(win->cb.data, win);+ }+ win->render_pending = 0;+ do_render(win);+ if (win->want_frame) {+ bk_frame_ms = now_ms() - win->frame_start;+ bk_frame_budget_ms = win->frame_vsync ? refresh_ms() : 0.0;+ win->render_pending = 1;+ }+ else {+ bk_frame_ms = 0.0;+ }+ if (BK_animating(win->ctx)) {+ win->render_pending = 1; /* paced by the loop's frame wait */+ }+}++/* -- input mapping (GHOST_SystemX11::processEvent) -- */++static int mods_of(unsigned state)+{+ int m = 0;+ if (state & ShiftMask) {+ m |= BK_SHIFT;+ }+ if (state & ControlMask) {+ m |= BK_CTRL;+ }+ if (state & Mod1Mask) {+ m |= BK_ALT;+ }+ if (state & Button1Mask) {+ m |= BK_BUTTON1;+ }+ return m;+}++static void handle_key(BKWindow *win, XKeyEvent *ke, int press)+{+ char text[32] = {0};+ KeySym sym = 0;+ const int len = XLookupString(ke, text, sizeof(text) - 1, &sym, NULL);+ text[BK_MAX(0, len)] = 0;+ const char *name = XKeysymToString(sym); /* the X keysym names Tk and BUI use */+ if (!name) {+ name = "";+ }+ const int mods = mods_of(ke->state);+ if (!press) {+ BK_key_release(win->ctx, name, mods);+ return;+ }+ /* control characters are not text */+ const int printable = len > 0 && (unsigned char)text[0] >= 0x20 && text[0] != 0x7f &&+ !(mods & BK_CTRL);+ BK_key(win->ctx, printable ? text : "", name, mods);+}++static void close_window(BKWindow *win)+{+ if (!win->xid) {+ return;+ }+ XDestroyWindow(g_dpy, win->xid);+ XFlush(g_dpy);+ win->xid = 0;+ g_open--;+}++static void handle_event(XEvent *ev)+{+ if (ev->type == SelectionRequest) { /* someone pastes what we copied */+ XSelectionRequestEvent *rq = &ev->xselectionrequest;+ XSelectionEvent sn = {SelectionNotify, 0, True, rq->display, rq->requestor, rq->selection,+ rq->target, None, rq->time};+ if (rq->target == a_targets) {+ Atom targets[] = {a_targets, a_utf8, XA_STRING};+ XChangeProperty(g_dpy, rq->requestor, rq->property, XA_ATOM, 32, PropModeReplace,+ (unsigned char *)targets, 3);+ sn.property = rq->property;+ }+ else if ((rq->target == a_utf8 || rq->target == XA_STRING) && g_clip_text) {+ XChangeProperty(g_dpy, rq->requestor, rq->property, rq->target, 8, PropModeReplace,+ (unsigned char *)g_clip_text, (int)strlen(g_clip_text));+ sn.property = rq->property;+ }+ XSendEvent(g_dpy, rq->requestor, False, 0, (XEvent *)&sn);+ return;+ }+ BKWindow *win = find_window(ev->xany.window);+ if (!win || !win->xid) {+ return;+ }+ BKContext *ctx = win->ctx;+ switch (ev->type) {+ case Expose:+ if (ev->xexpose.count == 0) {+ win->full = 1;+ win->render_pending = 1;+ }+ break;+ case ConfigureNotify:+ if (ev->xconfigure.width != win->w || ev->xconfigure.height != win->h) {+ win->w = ev->xconfigure.width;+ win->h = ev->xconfigure.height;+ win->render_pending = 1;+ }+ break;+ case MotionNotify:+ BK_motion(ctx, ev->xmotion.x, ev->xmotion.y, mods_of(ev->xmotion.state));+ break;+ case LeaveNotify:+ if (!(ev->xcrossing.state & (Button1Mask | Button2Mask | Button3Mask))) {+ BK_motion(ctx, -100000, -100000, 0);+ }+ break;+ case ButtonPress: {+ const XButtonEvent *b = &ev->xbutton;+ const int mods = mods_of(b->state);+ switch (b->button) {+ case Button1:+ XSetInputFocus(g_dpy, win->xid, RevertToParent, CurrentTime);+ BK_press(ctx, b->x, b->y, mods | BK_BUTTON1);+ break;+ case Button2:+ BK_button(ctx, b->x, b->y, 2, 0, mods);+ break;+ case Button3:+ BK_context_menu(ctx, b->x, b->y, mods);+ break;+ case Button4: /* wheel up */+ case Button5:+ BK_wheel(ctx, b->x, b->y, b->button == Button4 ? 1 : -1, mods & ~BK_BUTTON1);+ break;+ case 6: /* horizontal wheel: Shift+wheel, as GHOST maps it */+ case 7:+ BK_wheel(ctx, b->x, b->y, b->button == 6 ? 1 : -1, (mods & ~BK_BUTTON1) | BK_SHIFT);+ break;+ }+ break;+ }+ case ButtonRelease: {+ const XButtonEvent *b = &ev->xbutton;+ const int mods = mods_of(b->state) & ~BK_BUTTON1;+ if (b->button == Button1) {+ BK_release(ctx, b->x, b->y, mods);+ }+ else if (b->button == Button2 || b->button == Button3) {+ BK_button(ctx, b->x, b->y, (int)b->button == Button2 ? 2 : 3, 1, mods);+ }+ break;+ }+ case KeyPress:+ case KeyRelease:+ if (ev->type == KeyRelease && XEventsQueued(g_dpy, QueuedAfterReading)) {+ /* autorepeat: a release followed by a press at the same time */+ XEvent next;+ XPeekEvent(g_dpy, &next);+ if (next.type == KeyPress && next.xkey.time == ev->xkey.time &&+ next.xkey.keycode == ev->xkey.keycode)+ {+ break;+ }+ }+ handle_key(win, &ev->xkey, ev->type == KeyPress);+ break;+ case ClientMessage:+ if ((Atom)ev->xclient.data.l[0] == a_delete) {+ if (!win->cb.on_close || win->cb.on_close(win->cb.data, win)) {+ close_window(win);+ }+ }+ break;+ }+}++/* -- windows -- */++BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height)+{+ if (!open_display()) {+ return NULL;+ }+ BKWindow *win = (BKWindow *)calloc(1, sizeof(BKWindow));+ win->ctx = ctx;+ win->prev = ctx->host;+ win->raster = BUI_raster_create(1, 1);+ win->next_timer = 1;+ win->scale = display_scale();+ BK_set_scale(win->scale);+ win->w = (int)(width * win->scale);+ win->h = (int)(height * win->scale);+ const int screen = DefaultScreen(g_dpy);+ XSetWindowAttributes attr;+ memset(&attr, 0, sizeof(attr));+ attr.background_pixel = BlackPixel(g_dpy, screen);+ attr.event_mask = ExposureMask | StructureNotifyMask | PointerMotionMask | ButtonPressMask |+ ButtonReleaseMask | KeyPressMask | KeyReleaseMask | LeaveWindowMask |+ FocusChangeMask;+ win->xid = XCreateWindow(g_dpy, RootWindow(g_dpy, screen), 0, 0, (unsigned)win->w,+ (unsigned)win->h, 0, CopyFromParent, InputOutput, CopyFromParent,+ CWBackPixel | CWEventMask, &attr);+ if (!win->xid) {+ BUI_raster_free(win->raster);+ free(win);+ return NULL;+ }+ XSetWMProtocols(g_dpy, win->xid, &a_delete, 1);+ win->gc = XCreateGC(g_dpy, win->xid, 0, NULL);+ BK_window_set_title(win, title);+ win->next = g_windows;+ g_windows = win;+ g_open++;+ BKHost host = {win, host_request, host_set_cursor, host_warp,+ host_clipboard_get, host_clipboard_set, host_schedule, host_emit};+ BK_context_set_host(ctx, &host);+ return win;+}++void BK_window_free(BKWindow *win)+{+ if (!win) {+ return;+ }+ close_window(win);+ for (BKWindow **p = &g_windows; *p; p = &(*p)->next) {+ if (*p == win) {+ *p = win->next;+ break;+ }+ }+ if (win->image) {+ win->image->data = NULL;+ XDestroyImage(win->image);+ }+ if (win->gc) {+ XFreeGC(g_dpy, win->gc);+ }+ if (win->ctx) {+ BK_context_set_host(win->ctx, &win->prev);+ }+ BUI_raster_free(win->raster);+ free(win);+}++void BK_window_set_callbacks(BKWindow *win, const BKWindowCallbacks *cb)+{+ win->cb = *cb;+}++void BK_window_show(BKWindow *win)+{+ if (win->xid) {+ XMapWindow(g_dpy, win->xid);+ XFlush(g_dpy);+ win->render_pending = 1;+ }+}++void BK_window_close(BKWindow *win)+{+ close_window(win);+}++int BK_window_is_open(BKWindow *win)+{+ return win && win->xid != 0;+}++void BK_window_set_title(BKWindow *win, const char *title)+{+ if (!win->xid) {+ return;+ }+ const char *t = title ? title : "";+ XChangeProperty(g_dpy, win->xid, XInternAtom(g_dpy, "_NET_WM_NAME", False), a_utf8, 8,+ PropModeReplace, (const unsigned char *)t, (int)strlen(t));+ XStoreName(g_dpy, win->xid, t);+ XFlush(g_dpy);+}++void BK_window_set_size(BKWindow *win, int width, int height)+{+ if (win->xid) {+ /* X resizes asynchronously; take the size now, as Win32's SetWindowPos+ * does (a ConfigureNotify from the window manager corrects it later) */+ win->w = BK_MAX(1, (int)(width * win->scale));+ win->h = BK_MAX(1, (int)(height * win->scale));+ XResizeWindow(g_dpy, win->xid, (unsigned)win->w, (unsigned)win->h);+ XFlush(g_dpy);+ win->render_pending = 1;+ }+}++void BK_window_get_size(BKWindow *win, int *w, int *h)+{+ *w = win->xid ? win->w : 0;+ *h = win->xid ? win->h : 0;+}++BuiRaster *BK_window_raster(BKWindow *win)+{+ return win->raster;+}++void BK_window_set_gpu(BKWindow *win, int on)+{+ (void)win;+ (void)on; /* the X11 host presents the CPU raster */+}++int BK_window_gpu(BKWindow *win)+{+ return 0;+}++int BK_window_frames(BKWindow *win)+{+ return win->frames;+}++void BK_window_render_now(BKWindow *win)+{+ if (win->xid) {+ win->full = 1;+ render_window(win);+ }+}++int BK_window_timer(BKWindow *win, int ms)+{+ const int id = win->next_timer++;+ Timer *t = timer_slot(win, id);+ if (t) {+ t->id = id;+ t->due = now_ms() + BK_MAX(0, ms);+ }+ return id;+}++void BK_window_cancel_timer(BKWindow *win, int id)+{+ for (int i = 0; i < MAX_TIMERS; i++) {+ if (win->timers[i].id == id) {+ win->timers[i].id = 0;+ }+ }+}++void BK_window_request_frame(BKWindow *win, int vsync)+{+ win->want_frame = 1;+ win->frame_vsync = vsync;+ win->render_pending = 1;+}++void *BK_window_handle(BKWindow *win)+{+ return (void *)(uintptr_t)win->xid;+}++/* GHOST_WindowX11: size hints for minsize / maxsize / resizable, moves for pos */+void BK_window_wm(BKWindow *win, const char *key, double a, double b)+{+ if (!win->xid) {+ return;+ }+ if (!strcmp(key, "pos")) {+ XMoveWindow(g_dpy, win->xid, (int)a, (int)b);+ }+ else if (!strcmp(key, "minsize") || !strcmp(key, "maxsize") || !strcmp(key, "resizable")) {+ XSizeHints *hints = XAllocSizeHints();+ long supplied;+ XGetWMNormalHints(g_dpy, win->xid, hints, &supplied);+ if (!strcmp(key, "minsize")) {+ hints->flags |= PMinSize;+ hints->min_width = (int)(a * win->scale);+ hints->min_height = (int)(b * win->scale);+ }+ else if (!strcmp(key, "maxsize")) {+ hints->flags |= PMaxSize;+ hints->max_width = (int)(a * win->scale);+ hints->max_height = (int)(b * win->scale);+ }+ else if (a == 0 || b == 0) { /* not resizable along an axis: pin it */+ hints->flags |= PMinSize | PMaxSize;+ hints->min_width = hints->max_width = a == 0 ? win->w : 1;+ hints->min_height = hints->max_height = b == 0 ? win->h : 1;+ if (a != 0) {+ hints->max_width = 1 << 15;+ }+ if (b != 0) {+ hints->max_height = 1 << 15;+ }+ }+ XSetWMNormalHints(g_dpy, win->xid, hints);+ XFree(hints);+ }+ else if (!strcmp(key, "lift")) {+ XRaiseWindow(g_dpy, win->xid);+ }+ else if (!strcmp(key, "lower")) {+ XLowerWindow(g_dpy, win->xid);+ }+ else if (!strcmp(key, "focus")) {+ XSetInputFocus(g_dpy, win->xid, RevertToParent, CurrentTime);+ }+ XFlush(g_dpy);+}++int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b)+{+ *r_a = *r_b = 0.0;+ if (!g_dpy) {+ return 0;+ }+ const int screen = DefaultScreen(g_dpy);+ if (!strcmp(key, "screen")) {+ *r_a = DisplayWidth(g_dpy, screen);+ *r_b = DisplayHeight(g_dpy, screen);+ return 1;+ }+ if (!strcmp(key, "scale")) {+ *r_a = *r_b = win ? win->scale : display_scale();+ return 1;+ }+ if (!win || !win->xid) {+ return 0;+ }+ if (!strcmp(key, "pointer") || !strcmp(key, "pos")) {+ Window root, child;+ int rx, ry, wx, wy;+ unsigned mask;+ XQueryPointer(g_dpy, win->xid, &root, &child, &rx, &ry, &wx, &wy, &mask);+ if (!strcmp(key, "pointer")) {+ *r_a = rx;+ *r_b = ry;+ }+ else {+ *r_a = rx - wx;+ *r_b = ry - wy;+ }+ return 1;+ }+ return 0;+}++/* -- the loop -- */++static void run_timers(void)+{+ const double t = now_ms();+ for (BKWindow *win = g_windows; win; win = win->next) {+ for (int i = 0; i < MAX_TIMERS && win->xid; i++) {+ Timer *tm = &win->timers[i];+ if (tm->id != 0 && tm->due <= t) {+ const int id = tm->id;+ tm->id = 0;+ if (id == -1) {+ BK_timer(win->ctx, win->tip_id);+ }+ else if (win->cb.on_timer) {+ win->cb.on_timer(win->cb.data, win, id);+ }+ }+ }+ }+}++/* Milliseconds until the next timer or frame (-1: nothing to wait for). */+static double next_wait(void)+{+ double wait = -1.0;+ const double t = now_ms();+ for (BKWindow *win = g_windows; win; win = win->next) {+ if (!win->xid) {+ continue;+ }+ if (win->render_pending) {+ return 0.0;+ }+ for (int i = 0; i < MAX_TIMERS; i++) {+ if (win->timers[i].id != 0) {+ const double d = BK_MAX(0.0, win->timers[i].due - t);+ wait = wait < 0 ? d : BK_MIN(wait, d);+ }+ }+ }+ return wait;+}++static void drain_wake(void)+{+ char buf[64];+ while (g_wake_pipe[0] >= 0 && read(g_wake_pipe[0], buf, sizeof(buf)) > 0) {+ }+ if (g_wake_cb) {+ g_wake_cb();+ }+}++/* One turn: events, timers, renders; blocks up to `block_ms` (-1: forever). */+static void turn(double block_ms)+{+ const int fd = ConnectionNumber(g_dpy);+ if (!XPending(g_dpy) && block_ms != 0.0) {+ fd_set set;+ FD_ZERO(&set);+ FD_SET(fd, &set);+ int maxfd = fd;+ if (g_wake_pipe[0] >= 0) {+ FD_SET(g_wake_pipe[0], &set);+ maxfd = BK_MAX(maxfd, g_wake_pipe[0]);+ }+ struct timeval tv, *ptv = NULL;+ if (block_ms > 0.0) {+ tv.tv_sec = (long)(block_ms / 1000.0);+ tv.tv_usec = (long)(fmod(block_ms, 1000.0) * 1000.0);+ ptv = &tv;+ }+ if (select(maxfd + 1, &set, NULL, NULL, ptv) > 0 && g_wake_pipe[0] >= 0 &&+ FD_ISSET(g_wake_pipe[0], &set))+ {+ drain_wake();+ }+ }+ while (XPending(g_dpy)) {+ XEvent ev;+ XNextEvent(g_dpy, &ev);+ handle_event(&ev);+ }+ run_timers();+ int rendered = 0;+ for (BKWindow *win = g_windows; win; win = win->next) {+ if (win->xid && win->render_pending) {+ render_window(win);+ rendered |= win->render_pending; /* animating: another frame wanted */+ }+ }+ if (rendered) {+ usleep((useconds_t)(refresh_ms() * 1000.0)); /* pace animation frames */+ }+}++void BK_window_set_stop_check(int (*stop)(void))+{+ g_stop = stop;+}++void BK_window_quit(void)+{+ g_quit = 1;+ BK_window_wake();+}++void BK_window_run(void)+{+ if (!g_dpy) {+ return;+ }+ g_quit = 0;+ while ((g_open > 0 || g_keep_alive) && !g_quit) {+ turn(next_wait());+ if (g_stop && g_stop()) {+ break;+ }+ }+}++int BK_window_pump(void)+{+ if (g_dpy) {+ turn(0.0);+ }+ return g_open;+}++int BK_window_wake_init(void (*cb)(void))+{+ g_wake_cb = cb;+ if (g_wake_pipe[0] < 0 && pipe(g_wake_pipe) == 0) {+ fcntl(g_wake_pipe[0], F_SETFL, O_NONBLOCK);+ fcntl(g_wake_pipe[1], F_SETFL, O_NONBLOCK);+ }+ return g_wake_pipe[0] >= 0;+}++/* Thread-safe: wakes the loop, which calls the wake callback. */+void BK_window_wake(void)+{+ if (g_wake_pipe[1] >= 0) {+ const char c = 1;+ (void)!write(g_wake_pipe[1], &c, 1);+ }+}++void BK_window_set_keep_alive(int on)+{+ g_keep_alive = on;+}++#endif /* BUI_WINDOW_X11 */diff --git a/tests/window_smoke.c b/tests/window_smoke.cnew file mode 100644index 0000000..4fff0b2--- /dev/null+++ b/tests/window_smoke.c@@ -0,0 +1,64 @@+/* Native window smoke test: opens a window with a node editor, renders,+ * runs timers and the loop, and quits. Exit 0 when frames were presented,+ * 77 (skipped) without a display.+ *+ * SPDX-License-Identifier: GPL-2.0-or-later */++#include <stdio.h>++#include "BUI_kit.h"++static int g_ticks = 0;++static void on_timer(void *data, BKWindow *win, int id)+{+ BKContext *ctx = (BKContext *)data;+ g_ticks++;+ /* some input through the same path the window uses */+ BK_motion(ctx, 100, 100, 0);+ BK_wheel(ctx, 200, 150, 1, 0);+ if (g_ticks < 5) {+ BK_window_timer(win, 50);+ }+ else {+ BK_window_quit();+ }+}++int main(void)+{+ if (!BK_window_supported()) {+ printf("no display: skipped\n");+ return 77;+ }+ BKNode *ed = BK_node_new("nodeeditor");+ for (int i = 0; i < 2; i++) {+ BKNode *n = BK_node_new("graphnode");+ BK_set_str(n, "label", i ? "Math" : "Value");+ BK_set_num(n, "nx", i * 220.0);+ const char *sockets[] = {"o|Value|float", "i|A|float|0.5"};+ BK_set_strs(n, "items", sockets, i ? 2 : 1);+ BK_node_add(ed, n, -1);+ }+ const char *links[] = {"0 0 1 0"};+ BK_set_strs(ed, "items", links, 1);+ BKContext *ctx = BK_context_new(ed);+ BKWindow *win = BK_window_new(ctx, "BUI X11 smoke", 480, 320);+ if (!win) {+ printf("window failed\n");+ return 1;+ }+ BKWindowCallbacks cb = {ctx, on_timer, NULL, NULL};+ BK_window_set_callbacks(win, &cb);+ BK_window_show(win);+ BK_window_timer(win, 300);+ BK_window_run();+ const int frames = BK_window_frames(win);+ int w, h;+ BK_window_get_size(win, &w, &h);+ printf("frames %d ticks %d size %dx%d\n", frames, g_ticks, w, h);+ BK_window_free(win);+ BK_context_free(ctx);+ BK_node_free(ed);+ return frames > 0 && g_ticks >= 5 ? 0 : 1;+}