From 7a385b0a963fe9781252e7940814a10246262d46 Mon Sep 17 00:00:00 2001 From: Walter Stanish Date: Fri, 13 Nov 2026 20:13:51 +1100 Subject: [PATCH 1/4] kit: multi-touch screens and trackpad gestures One finger is the pointer: it taps, drags number fields and sliders, opens menus and picks rows, and leaves no hover behind. A second finger cancels what the first was doing (as Escape cancels a drag) and the two become a gesture until both lift: moving together scrolls the view under them, spreading zooms (BK_magnify), turning rotates (BK_rotate). These are GHOST's trackpad Scroll / Magnify / Rotate events (Blender's MOUSEPAN / MOUSEZOOM / MOUSEROTATE); the node editor pans and zooms on them. API (BUI_kit.h): BK_touch(ctx, id, phase, x, y, mods) with BK_TOUCH_DOWN / MOVE / UP / CANCEL, BK_magnify, BK_rotate, the BK_FROM_TOUCH modifier bit; custom nodes get BK_CUSTOM_MAGNIFY / ROTATE, or every contact as BK_CUSTOM_TOUCH after BK_custom_set_touch(node, 1). BKCustomEvent gains touch_id, touch_phase, magnify, rotate at its end. Window hosts: - Win32: WM_TOUCH (RegisterTouchWindow); touch-made mouse messages and press-and-hold right clicks are dropped. - X11: XInput 2.2 touch events, libXi loaded at run time; compiled only where XInput2.h exists, and without XI 2.2 touches stay emulated mouse input as before. - Wayland: wl_touch (with cancel) and the pointer-gestures pinch. - Cocoa: magnifyWithEvent: / rotateWithEvent: (untested here: no macOS). Internals: the state machine is kit/intern/kit_touch.c; gesture delivery (bk_gesture) sits beside BK_scroll in kit_core.c, which renames its static hit_all() to bk_ctx_hit() so kit_touch.c can share it; BKClass gains a `gesture` hook (the node editor implements it). Bindings: Python KitContext.touch / magnify / rotate, Lua ctx:touch / magnify / rotate with bui.TOUCH_*, D Context.touch / magnify / rotate and setTouch (with the BKCustomEvent fields), blenderui-sys declarations; Dear ImGui reports touch as ImGuiMouseSource_TouchScreen. Tests: tests/touch_test.c (taps, cancel, second-finger cancel of a drag, menus, region pan, node editor pinch/pan, custom default and raw, freed node mid-touch, capacity), Python test_nodes.py, Lua test_context.lua, D tests/run.d. Docs: docs/touch.md, website Touch and gestures page, c-api, README, ARCHITECTURE, CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PJcXdyFRKBApKEvWpKoMpY --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 15 + CMakeLists.txt | 4 + README.md | 1 + bindings/d/source/bui/context.d | 28 ++ bindings/d/source/bui/custom.d | 17 + bindings/d/source/bui/kit.d | 18 + bindings/d/tests/run.d | 30 ++ bindings/imgui/imgui_impl_bui.cpp | 8 +- bindings/lua/src/bui_context.c | 30 ++ bindings/lua/src/bui_lua.c | 5 + bindings/lua/tests/test_context.lua | 10 + bindings/python/src/buipy_kit.c | 39 ++ bindings/python/tests/test_nodes.py | 22 + bindings/rust/blenderui-sys/src/lib.rs | 12 + docs/c-api.md | 4 +- docs/touch.md | 94 +++++ kit/CMakeLists.txt | 7 + kit/include/BUI_kit.h | 52 ++- kit/intern/kit_core.c | 114 +++++- kit/intern/kit_custom.c | 33 ++ kit/intern/kit_intern.h | 40 ++ kit/intern/kit_nodes.c | 20 + kit/intern/kit_touch.c | 299 ++++++++++++++ kit/intern/kit_window_cocoa.m | 23 ++ kit/intern/kit_window_wayland.c | 164 ++++++++ kit/intern/kit_window_win32.c | 53 +++ kit/intern/kit_window_x11.c | 91 +++++ tests/touch_test.c | 424 ++++++++++++++++++++ website/src/content/docs/c/c-api.mdx | 3 +- website/src/content/docs/concepts/touch.mdx | 101 +++++ 31 files changed, 1737 insertions(+), 26 deletions(-) create mode 100644 docs/touch.md create mode 100644 kit/intern/kit_touch.c create mode 100644 tests/touch_test.c create mode 100644 website/src/content/docs/concepts/touch.mdx diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a59c55a3..8fadbefc 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -65,7 +65,7 @@ include `ui/`.) | `gpu/` | The draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend that *records and forwards*: with a sink installed it emits screen-space primitives (`GPU_backend_sink.h`); without one it discards them. Theme colors reach the GPU layer through function-pointer hooks. | **Builds + tested** | | `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types and stub implementations (`intern/bui_stubs.cc`). | **Builds** | | `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Kept for reference and porting work; **not compiled by default** (`-DBUI_BUILD_UI=ON` builds it as `bui_ui`). `kit/` re-ports what it needs in C. | **Compiles + links** (opt-in) | -| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; Blender's file browser; images (`kit/intern/image`: Blender's imbuf design, one format table over Wuffs, libjpeg-turbo, libwebp and BUI's HDR/PNM/SVG readers in `kit/extern`, decode at the drawn size, a worker pool and a memory-budgeted cache; see [the Images page](https://bui.preetham.top/docs/concepts/images/)); damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11 and Cocoa (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_cocoa.m`; `kit_window_null.c` elsewhere). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (experimental: checked by CI and tried by hand on two Apple Silicon Macs) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** | +| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; touch screens and trackpad gestures (`kit_touch.c`: one finger is the pointer, two are GHOST's trackpad pan / magnify / rotate); Blender's file browser; images (`kit/intern/image`: Blender's imbuf design, one format table over Wuffs, libjpeg-turbo, libwebp and BUI's HDR/PNM/SVG readers in `kit/extern`, decode at the drawn size, a worker pool and a memory-budgeted cache; see [the Images page](https://bui.preetham.top/docs/concepts/images/)); damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11 and Cocoa (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_cocoa.m`; `kit_window_null.c` elsewhere). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (experimental: checked by CI and tried by hand on two Apple Silicon Macs) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** | | `api/` | `bui_c_api.h` — small stable C ABI: version info + sink/viewport plumbing for hosts and bindings. | **Builds + tested** | | `bindings/python/` | `buipy` CPython extension (no third-party deps; Dear ImGui is compiled into it, `blenderui.imgui`, so a process holds one kit) + `bui` package: `bui.components` (Blender component library), `bui.qtsyntax` / `bui.tksyntax` (Qt / tkinter APIs as thin facades over the kit), `bui.host` (native or Tk windows), `SvgSink` headless renderer, `bui.qt.BuiCanvas` PySide6/PyQt6 widget. | **Builds + tested** | | `bindings/imgui/` | Dear ImGui (vendored, 1.93.1 WIP) on BUI: `imgui_impl_bui` platform + renderer backend hosted in a kit `custom` node (input, cursors, clipboard, DPI, damage-driven frames) drawing through `BUI_raster_mesh` and BUI textures; Blender style and Inter font; the C API (`cimgui.h`) and the generator behind the Python and Rust bindings; the Blender-widgets build (`blender/`, `-DBUI_IMGUI_BLENDER_WIDGETS=ON`). Gate: `-DBUI_BUILD_IMGUI` (ON with C++). | **Builds + tested** | diff --git a/CHANGELOG.md b/CHANGELOG.md index da50e881..c0990549 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,21 @@ All notable changes to **blenderui** (BUI). The format follows ### Added - **D bindings** (`bindings/d`): a DUB package with raw `extern(C)` declarations for the whole kit, GPU and stable C API, plus idiomatic wrappers for nodes, contexts, windows, menus, rasters, images, video, canvases, trees, text areas, custom nodes and themes. The kit is built through CMake from `preBuildCommands`, ownership follows the Python binding's reference-hook model, and `dub run --config=test` covers the wrappers, raw API, events, menus and host errors end to end. Examples: `hello.d` and `headless.d`. - **D HTML, CSS and RSX** (`bindings/d`): `bui.html` adds an `Element` tree and tag constructors, `bui.css` a selector cascade with a practical CSS subset, and `bui.rsx` a compile-time `rsx!` mixin that lowers markup and `{expression}` values to `Element` calls. `Document` realises the styled tree as kit nodes with flex, grid and table layout, widgets, dynamic `:hover`/`:active` states through `Element.setState` and `Document.restyle`, and in-place text updates through `Element.setText`. Tag constructors use `body_`, `template_`, `object_` and `select_` where D or the existing API already uses the name; markup keeps the HTML spelling. `dub run --config=rsx` opens the new example, and `--config=test` covers the cascade, realiser and RSX. The D wrappers also follow the kit's current header: focus callbacks, `Context.hitAt`, custom theme files, text shadows, font size and transparent rasters. +- **Touch screens and trackpad gestures.** One finger is the pointer: it taps, drags number fields and sliders, opens + menus and picks rows, and leaves no hover behind. A second finger cancels what the first was doing (as Escape + cancels a drag: values go back, nothing is clicked) and the two become a gesture until both lift. Moving them + together scrolls the view under them, spreading them zooms (`BK_magnify`), turning them rotates (`BK_rotate`). These + are GHOST's trackpad Scroll / Magnify / Rotate events (Blender's MOUSEPAN / MOUSEZOOM / MOUSEROTATE); the node editor + pans and zooms on them. New C API: `BK_touch(ctx, id, phase, x, y, mods)` with `BK_TOUCH_DOWN` / `MOVE` / `UP` / + `CANCEL`, `BK_magnify`, `BK_rotate`, the `BK_FROM_TOUCH` modifier bit, and for custom nodes `BK_CUSTOM_TOUCH`, + `BK_CUSTOM_MAGNIFY`, `BK_CUSTOM_ROTATE` with `BKCustomEvent.touch_id`, `touch_phase`, `magnify`, `rotate`, and + `BK_custom_set_touch(node, 1)` to receive every contact raw. Window hosts: `WM_TOUCH` on Windows (touch-made mouse + messages and press-and-hold are dropped), XInput 2.2 touch on X11 (libXi loaded at run time; older servers keep + emulated mouse input), `wl_touch` and the pointer-gestures pinch on Wayland, `magnifyWithEvent:` / + `rotateWithEvent:` on macOS. Dear ImGui reports touch as `ImGuiMouseSource_TouchScreen`. Python + `KitContext.touch` / `magnify` / `rotate`, Lua `ctx:touch` / `magnify` / `rotate` with `bui.TOUCH_*`, D + `Context.touch` / `magnify` / `rotate` and `setTouch`, and `blenderui-sys` declarations. `tests/touch_test.c`; [docs/touch.md](docs/touch.md) and the website's Touch and + gestures page. ## [0.5.1] - 2026-11-13 diff --git a/CMakeLists.txt b/CMakeLists.txt index 6971d522..9b7f7624 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -108,6 +108,10 @@ if(BUI_BUILD_TESTS) if(BUI_BENCH_NO_IME) target_compile_definitions(bui_ime_bench PRIVATE BENCH_NO_IME) endif() + # touch screens and trackpad gestures: the pointer, a second finger's gesture, raw contacts + add_executable(bui_touch_test tests/touch_test.c) + target_link_libraries(bui_touch_test PRIVATE bui::kit) + add_test(NAME bui_touch_test COMMAND bui_touch_test) add_executable(bui_theme_test tests/theme_test.c) target_link_libraries(bui_theme_test PRIVATE bui::kit) add_test(NAME bui_theme_test COMMAND bui_theme_test) diff --git a/README.md b/README.md index f8892f91..6eebfb3b 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ If you're starting fresh in Python, the Blender components are the friendliest. - Ctrl+Wheel steps values, Ctrl+C / Ctrl+V copy values, Backspace resets. - **Drag across checkboxes** to set them all. - Press-drag-release menus, pie menus that pick on key release as in Blender (sub-pies, a "More" level, numpad directions, underlined letters), and **Blender's fuzzy menu search**: "ad cu" finds "Add Cube", typos are forgiven, recent picks rank first. +- **Touch screens and trackpad gestures**: one finger taps and drags like the mouse, two fingers scroll, pinch-zoom and turn (Windows, X11, Wayland; trackpad pinch on Wayland and macOS). See [docs/touch.md](docs/touch.md). - **Ctrl+Z / Ctrl+Shift+Z** on every UI edit, and inside a text field while you type; Tab between fields. - Blender's float display precision, multi-field vertical drags, and panels that collapse with Blender's animation. - The HSV color wheel, color ramps, curves, trees, lists, text areas, canvases, a node editor and Blender's File Browser. diff --git a/bindings/d/source/bui/context.d b/bindings/d/source/bui/context.d index 6124465b..5cda9627 100644 --- a/bindings/d/source/bui/context.d +++ b/bindings/d/source/bui/context.d @@ -248,6 +248,34 @@ final class Context { return changed; } + /// A touch screen contact (`BK_TOUCH_DOWN` / `MOVE` / `UP` / `CANCEL`): one finger is the + /// pointer, two pan, magnify and rotate. + bool touch(int id, int phase, float x, float y, int mods = 0) { + auto c = ctx(); + check(); + const changed = BK_touch(c, id, phase, x, y, mods) != 0; + check(); + return changed; + } + + /// Trackpad pinch: `delta` is the scale change (0.1 = 10% larger), about `x`, `y`. + bool magnify(int x, int y, float delta, int mods = 0) { + auto c = ctx(); + check(); + const changed = BK_magnify(c, x, y, delta, mods) != 0; + check(); + return changed; + } + + /// Trackpad turn in degrees, positive counter-clockwise, about `x`, `y`. + bool rotate(int x, int y, float degrees, int mods = 0) { + auto c = ctx(); + check(); + const changed = BK_rotate(c, x, y, degrees, mods) != 0; + check(); + return changed; + } + /// Key press with the character `text` and the key name `keysym`. bool key(string text, string keysym = null, int mods = 0) { auto c = ctx(); diff --git a/bindings/d/source/bui/custom.d b/bindings/d/source/bui/custom.d index 5ae501d9..3fb8d67a 100644 --- a/bindings/d/source/bui/custom.d +++ b/bindings/d/source/bui/custom.d @@ -31,6 +31,13 @@ struct CustomEvent { const(char)[] text; /// The key name, for `BK_CUSTOM_KEY` / `BK_CUSTOM_KEYUP`. const(char)[] keysym; + /// `BK_CUSTOM_TOUCH`: the contact's id and `BK_TOUCH_*` phase. + int touchId; + int touchPhase; + /// `BK_CUSTOM_MAGNIFY`: scale change (0.1 = 10% larger). + float magnify; + /// `BK_CUSTOM_ROTATE`: degrees, positive counter-clockwise. + float rotate; } /// The custom node's implementations. @@ -107,6 +114,10 @@ final class Custom { event.wheelY = raw.wheel_y; event.text = cslice(raw.text); event.keysym = cslice(raw.keysym); + event.touchId = raw.touch_id; + event.touchPhase = raw.touch_phase; + event.magnify = raw.magnify; + event.rotate = raw.rotate; try { return self.handlers.onEvent(wrapper, event); } @@ -217,6 +228,12 @@ void setCursor(Node node, int cursor) { BK_custom_set_cursor(need(node, "setCursor"), cursor); } +/// `true`: every touch contact that begins over the node arrives as `BK_CUSTOM_TOUCH`, with no +/// pointer emulation or gestures; `false` (the default): as the pointer and gestures. +void setTouch(Node node, bool raw) { + BK_custom_set_touch(need(node, "setTouch"), raw ? 1 : 0); +} + /// Non-zero while the custom node has keyboard focus. bool hasFocus(Node node) { return BK_custom_has_focus(need(node, "hasFocus")) != 0; diff --git a/bindings/d/source/bui/kit.d b/bindings/d/source/bui/kit.d index 545b4670..f28c4d51 100644 --- a/bindings/d/source/bui/kit.d +++ b/bindings/d/source/bui/kit.d @@ -34,6 +34,13 @@ enum BK_ALT = 4; enum BK_BUTTON1 = 8; enum BK_BUTTON2 = 16; enum BK_BUTTON3 = 32; +enum BK_FROM_TOUCH = 64; + +/* ---- touch phases (BK_touch) --------------------------------------------- */ +enum BK_TOUCH_DOWN = 0; +enum BK_TOUCH_MOVE = 1; +enum BK_TOUCH_UP = 2; +enum BK_TOUCH_CANCEL = 3; /* ---- cursors ------------------------------------------------------------- */ enum BK_CURSOR_DEFAULT = 0; @@ -130,6 +137,9 @@ enum BK_CUSTOM_KEY = 6; enum BK_CUSTOM_KEYUP = 7; enum BK_CUSTOM_FOCUS = 8; enum BK_CUSTOM_BLUR = 9; +enum BK_CUSTOM_TOUCH = 10; +enum BK_CUSTOM_MAGNIFY = 11; +enum BK_CUSTOM_ROTATE = 12; /* ---- IME ----------------------------------------------------------------- */ enum BK_IME_COMPOSITION_START = 0; @@ -266,6 +276,10 @@ struct BKCustomEvent { float wheel_y; const(char)* text; const(char)* keysym; + int touch_id; + int touch_phase; + float magnify; + float rotate; } alias BKCustomEventFn = @@ -535,6 +549,7 @@ int BK_custom_set(BKNode* node, const(BKCustomClass)* cls, void* data); void* BK_custom_data(BKNode* node); void BK_custom_request_frame(BKNode* node, int ms); void BK_custom_set_cursor(BKNode* node, int cursor); +void BK_custom_set_touch(BKNode* node, int raw); int BK_custom_has_focus(BKNode* node); BKContext* BK_node_context(const(BKNode)* node); @@ -579,6 +594,9 @@ int BK_wheel(BKContext* ctx, int x, int y, int delta, int mods); int BK_scroll(BKContext* ctx, int x, int y, float dx, float dy, int mods); int BK_key(BKContext* ctx, const(char)* text, const(char)* keysym, int mods); int BK_context_menu(BKContext* ctx, int x, int y, int mods); +int BK_touch(BKContext* ctx, int id, int phase, float x, float y, int mods); +int BK_magnify(BKContext* ctx, int x, int y, float delta, int mods); +int BK_rotate(BKContext* ctx, int x, int y, float degrees, int mods); /* -- input methods --------------------------------------------------------- */ int BK_ime_event(BKContext* ctx, int type, const(BKImeEvent)* e); diff --git a/bindings/d/tests/run.d b/bindings/d/tests/run.d index e41bb66c..bb40242b 100644 --- a/bindings/d/tests/run.d +++ b/bindings/d/tests/run.d @@ -113,6 +113,15 @@ private void testRenderAndInput() { context.release(x, y, 0); check(clicks == 1, "click callback"); + context.touch(1, BK_TOUCH_DOWN, x, y); + context.touch(1, BK_TOUCH_UP, x, y); + check(clicks == 2, "a tap clicks"); + context.touch(1, BK_TOUCH_DOWN, x, y); + context.touch(2, BK_TOUCH_DOWN, x + 30, y); + context.touch(1, BK_TOUCH_UP, x, y); + context.touch(2, BK_TOUCH_UP, x + 30, y); + check(clicks == 2, "a second finger cancels the tap"); + auto hit = context.hitAt(x, y); bool inside = false; for (auto node = hit; node !is null; node = node.parent()) { @@ -340,6 +349,27 @@ private void testCustom() { context.release(rect[0] + rect[2] / 2, rect[1] + rect[3] / 2, 0); check(events >= 1, "custom event callback"); + float magnified = 0, turned = 0; + int touches; + auto gestures = setCustom(node, CustomHandlers( + (Node, CustomEvent e) { + magnified += e.type == BK_CUSTOM_MAGNIFY ? e.magnify : 0; + turned += e.type == BK_CUSTOM_ROTATE ? e.rotate : 0; + touches += e.type == BK_CUSTOM_TOUCH && e.touchId == 7; + return 1; + }, + null, null, (Node) {}, 80, 40)); + const cx = rect[0] + rect[2] / 2, cy = rect[1] + rect[3] / 2; + check(context.magnify(cx, cy, 0.5f), "magnify used"); + check(context.rotate(cx, cy, -10.0f), "rotate used"); + check(magnified == 0.5f && turned == -10.0f, "gesture values"); + node.setTouch(true); + context.touch(7, BK_TOUCH_DOWN, cx, cy); + context.touch(7, BK_TOUCH_MOVE, cx + 3, cy); + context.touch(7, BK_TOUCH_UP, cx + 3, cy); + check(touches == 3, "raw touches"); + check(gestures.pendingError() is null, "no gesture callback exception"); + raster.free(); context.free(); root.free(); diff --git a/bindings/imgui/imgui_impl_bui.cpp b/bindings/imgui/imgui_impl_bui.cpp index e3ae3e7b..dfee6a7e 100644 --- a/bindings/imgui/imgui_impl_bui.cpp +++ b/bindings/imgui/imgui_impl_bui.cpp @@ -354,13 +354,15 @@ static int Bui_Event(void* data, BKNode* node, const BKCustomEvent* e) const ImGuiKey key = (e->type == BK_CUSTOM_KEY || e->type == BK_CUSTOM_KEYUP) ? KeysymToImGuiKey(e->keysym, &pulse) : ImGuiKey_None; if (e->type != BK_CUSTOM_FOCUS && e->type != BK_CUSTOM_BLUR) UpdateModifiers(bd, io, e, key); + // the kit's touch pointer (BK_touch): ImGui then skips hover between taps + const ImGuiMouseSource source = (e->mods & BK_FROM_TOUCH) ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse; switch (e->type) { case BK_CUSTOM_PRESS: case BK_CUSTOM_RELEASE: { const int b = MouseButton(e->button); - io.AddMouseSourceEvent(ImGuiMouseSource_Mouse); + io.AddMouseSourceEvent(source); io.AddMousePosEvent(e->x, e->y); if (b >= 0) { @@ -371,7 +373,7 @@ static int Bui_Event(void* data, BKNode* node, const BKCustomEvent* e) break; } case BK_CUSTOM_MOTION: - io.AddMouseSourceEvent(ImGuiMouseSource_Mouse); + io.AddMouseSourceEvent(source); io.AddMousePosEvent(e->x, e->y); break; case BK_CUSTOM_LEAVE: @@ -379,7 +381,7 @@ static int Bui_Event(void* data, BKNode* node, const BKCustomEvent* e) io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); break; case BK_CUSTOM_WHEEL: - io.AddMouseSourceEvent(ImGuiMouseSource_Mouse); + io.AddMouseSourceEvent(source); io.AddMousePosEvent(e->x, e->y); io.AddMouseWheelEvent(-e->wheel_x, e->wheel_y); // ImGui: wheel_x > 0 scrolls left break; diff --git a/bindings/lua/src/bui_context.c b/bindings/lua/src/bui_context.c index 30da6ec1..adf0fa86 100644 --- a/bindings/lua/src/bui_context.c +++ b/bindings/lua/src/bui_context.c @@ -313,6 +313,33 @@ static int l_ctx_scroll(lua_State *L) { return 1; } +static int l_ctx_touch(lua_State *L) { + luabui_Context *cud = CHECK_CTX(L, 1); + if (!cud->ctx) return 0; + int id = (int)luaL_checkinteger(L, 2); + int phase = (int)luaL_checkinteger(L, 3); + float x = (float)luaL_checknumber(L, 4); + float y = (float)luaL_checknumber(L, 5); + int mods = (int)luaL_optinteger(L, 6, 0); + lua_pushboolean(L, BK_touch(cud->ctx, id, phase, x, y, mods)); + return 1; +} + +/* ctx:magnify(x, y, delta, mods) / ctx:rotate(x, y, degrees, mods) */ +static int ctx_gesture(lua_State *L, int (*call)(BKContext *, int, int, float, int)) { + luabui_Context *cud = CHECK_CTX(L, 1); + if (!cud->ctx) return 0; + int x = (int)luaL_checkinteger(L, 2); + int y = (int)luaL_checkinteger(L, 3); + float amount = (float)luaL_checknumber(L, 4); + int mods = (int)luaL_optinteger(L, 5, 0); + lua_pushboolean(L, call(cud->ctx, x, y, amount, mods)); + return 1; +} + +static int l_ctx_magnify(lua_State *L) { return ctx_gesture(L, BK_magnify); } +static int l_ctx_rotate(lua_State *L) { return ctx_gesture(L, BK_rotate); } + static int l_ctx_key(lua_State *L) { luabui_Context *cud = CHECK_CTX(L, 1); if (!cud->ctx) return 0; @@ -658,6 +685,9 @@ static const luaL_Reg ctx_methods[] = { {"motion", l_ctx_motion}, {"wheel", l_ctx_wheel}, {"scroll", l_ctx_scroll}, + {"touch", l_ctx_touch}, + {"magnify", l_ctx_magnify}, + {"rotate", l_ctx_rotate}, {"key", l_ctx_key}, {"key_release", l_ctx_key_release}, {"button", l_ctx_button}, diff --git a/bindings/lua/src/bui_lua.c b/bindings/lua/src/bui_lua.c index 944cfeff..75390d84 100644 --- a/bindings/lua/src/bui_lua.c +++ b/bindings/lua/src/bui_lua.c @@ -567,6 +567,11 @@ BUI_LUA_ENTRY int luaopen_bui(lua_State *L) { lua_pushinteger(L, BK_SHIFT); lua_setfield(L, -2, "MOD_SHIFT"); lua_pushinteger(L, BK_CTRL); lua_setfield(L, -2, "MOD_CTRL"); lua_pushinteger(L, BK_ALT); lua_setfield(L, -2, "MOD_ALT"); lua_pushinteger(L, BK_BUTTON1); lua_setfield(L, -2, "MOD_BUTTON1"); lua_pushinteger(L, BK_BUTTON2); lua_setfield(L, -2, "MOD_BUTTON2"); lua_pushinteger(L, BK_BUTTON3); lua_setfield(L, -2, "MOD_BUTTON3"); + lua_pushinteger(L, BK_FROM_TOUCH); lua_setfield(L, -2, "MOD_FROM_TOUCH"); + + /* Touch phases (ctx:touch) */ + lua_pushinteger(L, BK_TOUCH_DOWN); lua_setfield(L, -2, "TOUCH_DOWN"); lua_pushinteger(L, BK_TOUCH_MOVE); lua_setfield(L, -2, "TOUCH_MOVE"); + lua_pushinteger(L, BK_TOUCH_UP); lua_setfield(L, -2, "TOUCH_UP"); lua_pushinteger(L, BK_TOUCH_CANCEL); lua_setfield(L, -2, "TOUCH_CANCEL"); /* Image formats */ lua_pushinteger(L, BK_IMAGE_NONE); lua_setfield(L, -2, "IMAGE_NONE"); lua_pushinteger(L, BK_IMAGE_PNG); lua_setfield(L, -2, "IMAGE_PNG"); diff --git a/bindings/lua/tests/test_context.lua b/bindings/lua/tests/test_context.lua index 36100dc7..20f0204b 100644 --- a/bindings/lua/tests/test_context.lua +++ b/bindings/lua/tests/test_context.lua @@ -84,6 +84,16 @@ ctx:context_menu(100, 100, 0) -- Scroll ctx:scroll(50, 50, 10.5, -20.3, 0) +-- Touch: one finger is the pointer, a second makes a pinch +check(ctx:touch(1, bui.TOUCH_DOWN, 50, 50, 0), "touch down not used") +ctx:touch(2, bui.TOUCH_DOWN, 90, 50, 0) +ctx:touch(2, bui.TOUCH_MOVE, 120.5, 50, 0) +ctx:touch(1, bui.TOUCH_UP, 50, 50, 0) +ctx:touch(2, bui.TOUCH_CANCEL, 120.5, 50, 0) +check(not ctx:touch(42, bui.TOUCH_MOVE, 1, 1, 0), "unknown contact used") +ctx:magnify(50, 50, 0.1, 0) +ctx:rotate(50, 50, -5.0, 0) + -- ── Cursor ─────────────────────────────────────────────────────────── local cursor = ctx:cursor() diff --git a/bindings/python/src/buipy_kit.c b/bindings/python/src/buipy_kit.c index fe38f3b5..df160bce 100644 --- a/bindings/python/src/buipy_kit.c +++ b/bindings/python/src/buipy_kit.c @@ -1679,6 +1679,39 @@ static PyObject *kitctx_wheel(KitContextObject *self, PyObject *args) return PyBool_FromLong(r); } +/* Touch screens and trackpad gestures (BK_touch, BK_magnify, BK_rotate). */ +static PyObject *kitctx_touch(KitContextObject *self, PyObject *args) +{ + int id, phase, mods = 0; + float x, y; + if (!PyArg_ParseTuple(args, "iiff|i:touch", &id, &phase, &x, &y, &mods)) { + return NULL; + } + const int r = BK_touch(self->ctx, id, phase, x, y, mods); + if (restore_error()) { + return NULL; + } + return PyBool_FromLong(r); +} + +#define GESTURE(name, call) \ + static PyObject *kitctx_##name(KitContextObject *self, PyObject *args) \ + { \ + int x, y, mods = 0; \ + float amount; \ + if (!PyArg_ParseTuple(args, "iif|i:" #name, &x, &y, &amount, &mods)) { \ + return NULL; \ + } \ + const int r = call(self->ctx, x, y, amount, mods); \ + if (restore_error()) { \ + return NULL; \ + } \ + return PyBool_FromLong(r); \ + } + +GESTURE(magnify, BK_magnify) +GESTURE(rotate, BK_rotate) + static PyObject *kitctx_key(KitContextObject *self, PyObject *args) { const char *text, *keysym; @@ -1971,6 +2004,12 @@ static PyMethodDef kitctx_methods[] = { {"motion", (PyCFunction)kitctx_motion, METH_VARARGS, "motion(x, y, mods)"}, {"context_menu", (PyCFunction)kitctx_context_menu, METH_VARARGS, "Right click."}, {"wheel", (PyCFunction)kitctx_wheel, METH_VARARGS, "wheel(x, y, delta, mods)"}, + {"touch", (PyCFunction)kitctx_touch, METH_VARARGS, + "touch(id, phase, x, y, mods): a touch screen contact; phase 0 down, 1 move, 2 up, 3 cancel"}, + {"magnify", (PyCFunction)kitctx_magnify, METH_VARARGS, + "magnify(x, y, delta, mods): pinch, delta = scale change (0.1 = 10% larger)"}, + {"rotate", (PyCFunction)kitctx_rotate, METH_VARARGS, + "rotate(x, y, degrees, mods): turn, > 0 counter-clockwise"}, {"key", (PyCFunction)kitctx_key, METH_VARARGS, "key(text, keysym, mods)"}, {"focus_node", (PyCFunction)kitctx_focus_node, METH_O, "focus_node(node): start editing a text node (None ends editing)."}, diff --git a/bindings/python/tests/test_nodes.py b/bindings/python/tests/test_nodes.py index b36f2b29..2a0aa0ff 100644 --- a/bindings/python/tests/test_nodes.py +++ b/bindings/python/tests/test_nodes.py @@ -126,6 +126,28 @@ def test_value_field_and_view(): assert ed.zoom > z +def test_touch_and_trackpad(): + app, ed, a, b = make() + ctx = app.ctx + # two fingers spread: the view zooms about them; moved together: it pans + z = ed.zoom + ctx.touch(1, 0, 300.0, 300.0, 0) + ctx.touch(2, 0, 400.0, 300.0, 0) + assert ctx.touch(1, 1, 270.0, 300.0, 0) and ctx.touch(2, 1, 430.0, 300.0, 0) + assert ed.zoom > z * 1.3, (z, ed.zoom) + px, z = ed.get("panx"), ed.zoom + ctx.touch(1, 1, 300.0, 300.0, 0) + ctx.touch(2, 1, 460.0, 300.0, 0) + assert abs(ed.get("panx") - (px + 30)) < 1e-3 and abs(ed.zoom - z) < 1e-5, (px, ed.get("panx")) + ctx.touch(1, 2, 300.0, 300.0, 0) + ctx.touch(2, 3, 460.0, 300.0, 0) + assert not ctx.touch(9, 1, 0.0, 0.0, 0) # an unknown contact + # a trackpad pinch zooms too; the editor does not rotate + z = ed.zoom + assert ctx.magnify(400, 300, -0.25, 0) and ed.zoom < z + assert not ctx.rotate(400, 300, 15.0, 0) + + def test_area_header(): picked = [] ed = NodeEditor() diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs index ddae9d6b..e4d5dcc0 100644 --- a/bindings/rust/blenderui-sys/src/lib.rs +++ b/bindings/rust/blenderui-sys/src/lib.rs @@ -55,6 +55,14 @@ pub const BK_SHIFT: c_int = 1; pub const BK_CTRL: c_int = 2; pub const BK_ALT: c_int = 4; pub const BK_BUTTON1: c_int = 8; +/// Pointer events the kit made from a touch screen contact (`BK_touch`). +pub const BK_FROM_TOUCH: c_int = 64; + +// Touch phases (`BK_touch`). +pub const BK_TOUCH_DOWN: c_int = 0; +pub const BK_TOUCH_MOVE: c_int = 1; +pub const BK_TOUCH_UP: c_int = 2; +pub const BK_TOUCH_CANCEL: c_int = 3; // Geometry managers and anchors. pub const BK_GEOM_NONE: c_int = 0; @@ -354,6 +362,10 @@ unsafe extern "C" { pub fn BK_release(ctx: *mut BKContext, x: c_int, y: c_int, mods: c_int) -> c_int; pub fn BK_motion(ctx: *mut BKContext, x: c_int, y: c_int, mods: c_int) -> c_int; pub fn BK_wheel(ctx: *mut BKContext, x: c_int, y: c_int, delta: c_int, mods: c_int) -> c_int; + pub fn BK_touch(ctx: *mut BKContext, id: c_int, phase: c_int, x: f32, y: f32, mods: c_int) + -> c_int; + pub fn BK_magnify(ctx: *mut BKContext, x: c_int, y: c_int, delta: f32, mods: c_int) -> c_int; + pub fn BK_rotate(ctx: *mut BKContext, x: c_int, y: c_int, degrees: f32, mods: c_int) -> c_int; pub fn BK_key(ctx: *mut BKContext, text: *const c_char, keysym: *const c_char, mods: c_int) -> c_int; pub fn BK_key_release(ctx: *mut BKContext, keysym: *const c_char, mods: c_int) -> c_int; diff --git a/docs/c-api.md b/docs/c-api.md index 2756c7f6..9dc5195f 100644 --- a/docs/c-api.md +++ b/docs/c-api.md @@ -77,7 +77,7 @@ int main(void) | **Nodes** | `BK_node_new(type)`, `BK_node_add(parent, child, index)`, `BK_node_remove`, `BK_node_child(_count)`, `BK_node_parent`, `BK_node_rect`, `BK_node_natural`, `BK_node_invalidate`, `BK_node_relayout`, `BK_node_free` | | **Properties** | `BK_set_num / BK_set_str / BK_set_color / BK_set_strs` and `BK_get_*`, by name (`"value"`, `"text"`, `"label"`, `"min"`, `"items"`, `"enabled"` ...). `"set_value"` sets a value *and* notifies. | | **Geometry** | `BK_geom_set_manager(node, BK_GEOM_PACK / GRID / PLACE)`, `BK_geom_set(node, key, v)` (`side`, `fill`, `expand`, `anchor`, `padx0`..., `row`, `column`, `sticky`, `x`, `relx`, `reqwidth` ...), `BK_frame_grid_weight`. Children of `frame` and `canvas` nodes. | -| **Context** | `BK_context_new(root)`: input state, popups, focus, undo. Input goes in with `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_key`, `BK_key_release`, `BK_button`, `BK_context_menu` (input methods: `BK_ime_event`, `BK_ime_state`, see below); frames come out of `BK_render(ctx, raster, w, h, full)`, which returns the number of redrawn regions (0 means nothing changed). | +| **Context** | `BK_context_new(root)`: input state, popups, focus, undo. Input goes in with `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_key`, `BK_key_release`, `BK_button`, `BK_context_menu`, touch screens with `BK_touch` and trackpad gestures with `BK_magnify` / `BK_rotate` ([touch.md](touch.md)) (input methods: `BK_ime_event`, `BK_ime_state`, see below); frames come out of `BK_render(ctx, raster, w, h, full)`, which returns the number of redrawn regions (0 means nothing changed). | | **Host** | `BKHost`: `request` (schedule a render), `set_cursor`, `warp`, clipboard, `schedule` (timers), `emit` (events). A `BKWindow` provides all of them. | | **Events** | `emit(data, node, kind, ref, a, b)`. Kinds: `BK_EV_CHANGE`, `CLICK`, `CALL` (menu item or hotkey), `RENAME`, `ACTIVATE`, `TOGGLE`, `BROWSE`, `SUBMIT`. With the `"events"` property you also get raw `PRESS` / `RELEASE` / `DOUBLE` / `MOTION` / `ENTER` / `LEAVE` / `KEY` / `KEYRELEASE` / `WHEEL` / `CONFIGURE`, plus `VIEW` and `SCROLL` for scrolling. | | **Windows** | `BK_window_new`, `show`, `close`, `set_title`, `set_size`, `wm(key, a, b)` (position, topmost, alpha, override, transparent, resizable, minsize, state; on Wayland also layer and anchor for wlr-layer-shell), callbacks `on_timer`, `on_close`, `on_frame`, `on_focus`, `timer`, `run`, `pump`, `quit` | @@ -86,7 +86,7 @@ int main(void) | **Text** | `BUI_text_measure`, `BUI_raster_text`, `BUI_text_add_font(family, flags, data, len)` (register a font; needed on wasm) | | **Raster alpha** | `BUI_raster_set_alpha(r, 1)` keeps premultiplied alpha in a CPU raster, `BUI_raster_clear` makes it transparent, `BUI_raster_alpha` reads the setting. An opaque raster draws the same bytes as before. | | **Specialised** | Canvas display list (`BK_canvas_set_item`), text area (`BK_textarea_*`), trees (`BK_tree_item_*`), menus (`BK_open_menu`, `BK_open_pie`), the hit test (`BK_hit_at`), color ramps and curves, `BK_undo` / `BK_redo` | -| **Custom nodes** | A `custom` node draws and handles input itself: `BK_custom_set(node, &cls, data)` with `event` (pointer with all three buttons and a grab, precise wheel via `BK_scroll`, keys and text while focused, key releases, focus), `frame` (called by `BK_render` when requested with `BK_custom_request_frame(node, ms)`: immediate-mode UIs build their frame there) and `draw` (raster + rect). `BK_custom_set_cursor`, `BK_node_context`. Dear ImGui runs on it: [../bindings/imgui](../bindings/imgui/README.md). | +| **Custom nodes** | A `custom` node draws and handles input itself: `BK_custom_set(node, &cls, data)` with `event` (pointer with all three buttons and a grab, precise wheel via `BK_scroll`, keys and text while focused, key releases, focus), `frame` (called by `BK_render` when requested with `BK_custom_request_frame(node, ms)`: immediate-mode UIs build their frame there) and `draw` (raster + rect). `BK_custom_set_cursor`, `BK_node_context`. Touch arrives as the pointer plus `WHEEL` / `MAGNIFY` / `ROTATE` gestures, or every contact as `BK_CUSTOM_TOUCH` after `BK_custom_set_touch(node, 1)`. Dear ImGui runs on it: [../bindings/imgui](../bindings/imgui/README.md). | | **File browser** | `BK_node_new("filebrowser")`: Blender's File Browser in any window. Strings `dir`, `file`, `button`, `search`; numbers `mode` (0 open, 1 save, 2 directory), `multiple`, `hidden`, `sort`, `invert`; list `filters` (`"Label\tpattern ..."`); read `state` and `result`. `BK_file_dialog(title, mode, dir, file, filters, n, multiple, &paths)` runs one in its own window and returns the number of chosen paths (free them with `BK_file_dialog_free`). | | **Meshes and textures** | `BUI_texture_create/update/free` (RGBA8, shared by every raster and GPU device), `BUI_raster_mesh(r, vertices, n, indices, n_idx, flags, tex, clip, ox, oy)`: indexed triangles with position, UV and color, straight-alpha blending, per-call clip; the same pixels on the software raster, Direct3D 11 and OpenGL. | diff --git a/docs/touch.md b/docs/touch.md new file mode 100644 index 00000000..05b4537a --- /dev/null +++ b/docs/touch.md @@ -0,0 +1,94 @@ +# Touch screens and trackpad gestures + +BUI's widgets work with fingers. On a touch screen, one finger is the pointer: tap a button, +drag a number field or a slider, open a menu and tap a row. Two fingers scroll, zoom and turn +what is under them. A trackpad pinch zooms the same way. The native window hosts do this for +you; if you host the kit yourself, three calls feed it. + +## What a finger does + +| Fingers | What happens | +|---|---| +| **One** | It is the pointer: it moves there, presses, drags and releases, as the left mouse button does. When it lifts, the pointer leaves, so no hover highlight or tooltip stays behind. Pointer events made this way carry `BK_FROM_TOUCH` in their mods. | +| **A second one** | Whatever the first finger was doing is cancelled, as Esc cancels a drag in Blender: a dragged value goes back, a pressed button is not clicked, a number field does not start editing. The two fingers are now a gesture. | +| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. | +| **Two, spreading or pinching** | Magnify about their centre (`BK_magnify`). The node editor zooms. | +| **Two, turning** | Rotate about their centre (`BK_rotate`). | +| **After a gesture** | No finger becomes the pointer again until every finger has lifted, so lifting one finger of a pinch never clicks what is under the other. | +| **More than two** | Followed, not used, up to ten contacts. | + +Blender has no touch-screen input, so there is no source to follow for touch itself. One finger +does what X11, Wayland compositors and Windows do for windows that don't know about touch. Two +fingers send the events Blender gets from a trackpad: GHOST's `Scroll`, `Magnify` and `Rotate` +trackpad events, which Blender reads as `MOUSEPAN`, `MOUSEZOOM` and `MOUSEROTATE`. + +## Window hosts + +| Host | Touch screen | Trackpad pinch / rotate | +|---|---|---| +| **Windows** | `WM_TOUCH` (the window is registered with `RegisterTouchWindow`). The mouse messages Windows makes from touches are ignored, and press-and-hold no longer turns into a right click. | Precision touchpads send pinches as Ctrl + wheel, as before. | +| **X11** | XInput 2.2 touch events (`XI_TouchBegin` / `Update` / `End`). libXi is loaded at run time like libX11; without it, or with an older server, touches stay emulated mouse input as before. | Not sent by X11 touchpad drivers. | +| **Wayland** | `wl_touch`, including `cancel` when the compositor takes the touches for a system gesture. | `zwp_pointer_gestures_v1` pinch: scale and rotation, as GHOST_SystemWayland reads them. | +| **macOS** | No touch screens. | `magnifyWithEvent:` and `rotateWithEvent:`, as GHOST_SystemCocoa. | + +## Hosting the kit yourself + +```c +/* every contact of a touch screen, in window pixels; id is the platform's */ +BK_touch(ctx, id, BK_TOUCH_DOWN, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_MOVE, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_UP, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_CANCEL, x, y, mods); /* the platform took it back */ + +/* trackpad gestures, at the pointer */ +BK_magnify(ctx, x, y, 0.1f, mods); /* 10% larger since the last event */ +BK_rotate(ctx, x, y, 5.0f, mods); /* degrees, > 0 counter-clockwise */ +``` + +Each call returns non-zero when something changed. A `BK_TOUCH_DOWN` for an id that is still +down ends the old contact first (its up was lost). Moves and ups for unknown ids are ignored. +Don't also send the mouse events your platform makes from the same touches. + +The same calls are on every binding: `ctx.touch(id, phase, x, y, mods)`, +`ctx.magnify(x, y, delta, mods)` and `ctx.rotate(x, y, degrees, mods)` in Python (phase 0 down, +1 move, 2 up, 3 cancel); `ctx:touch(...)`, `ctx:magnify(...)` and `ctx:rotate(...)` with +`bui.TOUCH_DOWN` ... `bui.TOUCH_CANCEL` in Lua; `context.touch(...)`, `magnify` and `rotate` +with `BK_TOUCH_*` in D (and `node.setTouch(true)` for custom nodes); `BK_touch`, `BK_magnify` +and `BK_rotate` in `blenderui-sys`. + +## Custom nodes + +By default a `custom` node gets touch the way it gets the mouse: `BK_CUSTOM_PRESS`, `MOTION` and +`RELEASE` from the first finger (with `BK_FROM_TOUCH` in `mods`), then, for two fingers, +`BK_CUSTOM_WHEEL` (the pan, in wheel notches like `BK_scroll`'s), `BK_CUSTOM_MAGNIFY` +(`e->magnify`) and `BK_CUSTOM_ROTATE` (`e->rotate`). Trackpad gestures arrive as the same +`MAGNIFY` and `ROTATE` events. The Dear ImGui backend reports touch as +`ImGuiMouseSource_TouchScreen`. + +A node that does its own multi-touch asks for every contact instead: + +```c +BK_custom_set_touch(node, 1); + +static int my_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + if (e->type == BK_CUSTOM_TOUCH) { + /* e->touch_id, e->touch_phase (BK_TOUCH_DOWN / MOVE / UP / CANCEL), e->x, e->y */ + return 1; + } + return 0; +} +``` + +Every contact that begins over the node then arrives as `BK_CUSTOM_TOUCH`, with no pointer +emulation and no gestures. The first finger gives the node keyboard focus, as a click does. +Fingers that begin elsewhere still work the rest of the UI. While a menu or popup is open, +touches take the normal path, so a tap outside closes the menu. + +## Limits + +- A continuous drag (a number field) still moves the system mouse pointer back where the drag + began when the finger lifts, as it does for the mouse. +- One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). +- Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between + the two fingers' events. Nothing waits for a platform's frame grouping yet. diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt index e91065bb..ec6c317e 100644 --- a/kit/CMakeLists.txt +++ b/kit/CMakeLists.txt @@ -26,6 +26,7 @@ add_library(bui_kit STATIC intern/kit_regions.c intern/kit_nodes.c intern/kit_custom.c + intern/kit_touch.c intern/kit_filebrowser.c # without BUI_FILEBROWSER: BK_file_dialog's stub only # images and video (Blender's imbuf design): see intern/image/image.h intern/image/imbuf.c @@ -190,6 +191,12 @@ elseif(UNIX AND NOT APPLE) list(APPEND _wl_xml ${_wl_cursor_shape} ${_wl_tablet}) target_compile_definitions(bui_kit PRIVATE BUI_WL_CURSOR_SHAPE) endif() + # pointer-gestures: touchpad pinches become BK_magnify / BK_rotate (GHOST's gesture_pinch) + set(_wl_gestures ${BUI_WL_PROTOCOLS}/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml) + if(EXISTS ${_wl_gestures}) + list(APPEND _wl_xml ${_wl_gestures}) + target_compile_definitions(bui_kit PRIVATE BUI_WL_POINTER_GESTURES) + endif() foreach(_x ${_wl_xml}) get_filename_component(_n ${_x} NAME_WE) add_custom_command( diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h index a6890fd9..a6f50e10 100644 --- a/kit/include/BUI_kit.h +++ b/kit/include/BUI_kit.h @@ -69,8 +69,17 @@ typedef struct BKNode BKNode; 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, BK_BUTTON2 = 16, BK_BUTTON3 = 32 }; +/* Modifier / button state bits for input calls. BK_FROM_TOUCH marks the pointer events the kit + * makes from a touch screen contact (BK_touch); hosts never pass it. */ +enum { + BK_SHIFT = 1, + BK_CTRL = 2, + BK_ALT = 4, + BK_BUTTON1 = 8, + BK_BUTTON2 = 16, + BK_BUTTON3 = 32, + BK_FROM_TOUCH = 64 +}; /* Mouse cursors requested through BKHost.set_cursor. */ enum { @@ -535,7 +544,12 @@ void BK_node_set_image_frame(BKNode *node, int frame); * - `draw` with the raster, clipped to the redrawn region inside the node. * It may be called several times per render (one per damaged region) and * for regions other widgets damaged, so it must draw the current state - * without changing it. + * without changing it; + * - touch (BK_touch): by default one finger is the pointer (PRESS / MOTION / + * RELEASE with BK_FROM_TOUCH in mods) and two fingers are a gesture: WHEEL + * (pan), MAGNIFY and ROTATE, the events trackpads send too (BK_magnify, + * BK_rotate). After BK_custom_set_touch(node, 1) it gets every contact that + * begins over it as TOUCH events instead, and does its own gestures. * Positions are in raster pixels relative to the node's top-left corner. */ enum { BK_CUSTOM_PRESS = 1, /* button: 1 left, 2 middle, 3 right */ @@ -547,6 +561,9 @@ enum { BK_CUSTOM_KEYUP, /* keysym */ BK_CUSTOM_FOCUS, /* keyboard focus gained */ BK_CUSTOM_BLUR, /* keyboard focus lost */ + BK_CUSTOM_TOUCH, /* touch_id, touch_phase (BK_custom_set_touch) */ + BK_CUSTOM_MAGNIFY, /* magnify */ + BK_CUSTOM_ROTATE, /* rotate */ }; typedef struct BKCustomEvent { @@ -559,6 +576,10 @@ typedef struct BKCustomEvent { float wheel_y; /* notches; > 0: scroll up (wheel turned away) */ const char *text; /* KEY: UTF-8 text the key typed ("" for none) */ const char *keysym; /* KEY / KEYUP: X11 keysym name ("Return", "a", "F1"; "" for none) */ + int touch_id; /* TOUCH: the host's contact id */ + int touch_phase; /* TOUCH: BK_TOUCH_DOWN / MOVE / UP / CANCEL */ + float magnify; /* MAGNIFY: scale change, 0.1 = 10% larger */ + float rotate; /* ROTATE: degrees, > 0 counter-clockwise */ } BKCustomEvent; typedef struct BKCustomClass { @@ -582,6 +603,9 @@ void *BK_custom_data(BKNode *node); void BK_custom_request_frame(BKNode *node, int ms); /* Pointer shape over the node (BK_CURSOR_*), applied right away when hovered. */ void BK_custom_set_cursor(BKNode *node, int cursor); +/* 1: contacts that begin over the node arrive as BK_CUSTOM_TOUCH events (every finger, no + * pointer emulation, no gestures); 0 (the default): as the pointer and gestures. */ +void BK_custom_set_touch(BKNode *node, int raw); int BK_custom_has_focus(BKNode *node); /* The context a node is shown in (NULL while detached). */ BKContext *BK_node_context(const BKNode *node); @@ -643,6 +667,28 @@ int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods); int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods); int BK_context_menu(BKContext *ctx, int x, int y, int mods); +/* -- Touch screens and trackpad gestures ---------------------------------------------------- + * Hosts send every contact of a touch screen (window pixels, any number of fingers; `id` is the + * platform's, unique while the finger is down). The kit turns them into what widgets know: + * - one finger is the pointer: moves there, presses, drags, releases (BK_FROM_TOUCH in mods), + * and leaves no hover behind; + * - a second finger cancels what the first one did (as Escape cancels a drag: a dragged value + * goes back, a pressed button is not clicked) and the two become a gesture until both lift: + * moving them together scrolls the region or view under them, spreading them is BK_magnify + * and turning them is BK_rotate, about their centre; + * - custom nodes that asked for raw touches (BK_custom_set_touch) get each contact instead. + * CANCEL: the platform took the contact back (a system gesture); nothing it did is kept. + * + * Magnify and rotate are GHOST's trackpad events (GHOST_kTrackpadEventMagnify / Rotate, which + * Blender reads as MOUSEZOOM / MOUSEROTATE); hosts send them for trackpad pinches too. + * Each returns non-zero when something changed. */ +enum { BK_TOUCH_DOWN = 0, BK_TOUCH_MOVE, BK_TOUCH_UP, BK_TOUCH_CANCEL }; +int BK_touch(BKContext *ctx, int id, int phase, float x, float y, int mods); +/* delta: scale change since the last event (0.1 = 10% larger), about x, y */ +int BK_magnify(BKContext *ctx, int x, int y, float delta, int mods); +/* degrees since the last event, > 0 counter-clockwise, about x, y */ +int BK_rotate(BKContext *ctx, int x, int y, float degrees, int mods); + /* -- Input methods (IME) ------------------------------------------------------ * Blender's model (GHOST_ImeWin32, wmIMEData, the text button's IME handling), one API for every * window host and binding. The IME is off until a text field or text area is being edited and diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index 877530fb..33a2a35e 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -1410,6 +1410,7 @@ BKContext *BK_context_new(BKNode *root) ctx->cursor = BK_CURSOR_DEFAULT; ctx->layout_dirty = true; ctx->full_dirty = true; + bk_touch_init(ctx); if (root) { root->ctx_root = ctx; } @@ -1726,6 +1727,16 @@ void bk_forget(BKContext *ctx, BKNode *subtree) if (ctx->last_click_node && is_within(ctx->last_click_node, subtree)) { ctx->last_click_node = NULL; } + for (int i = 0; i < BK_MAX_TOUCH; i++) { /* its raw contacts are ignored until they lift */ + BKTouchPoint *tp = &ctx->touch.pts[i]; + if (tp->role == BK_TP_RAW && is_within(tp->raw, subtree)) { + tp->role = BK_TP_DEAD; + tp->raw = NULL; + } + } + if (ctx->touch.target && is_within(ctx->touch.target, subtree)) { + ctx->touch.target = NULL; + } /* popups owned by the subtree */ for (int i = 0; i < ctx->npopups; i++) { if (ctx->popups[i]->parent && is_within(ctx->popups[i]->parent, subtree)) { @@ -1875,8 +1886,6 @@ static int drag_toggle_apply(BKContext *ctx, BKNode *under) return 1; } -static BKNode *hit_all(BKContext *ctx, int x, int y); - /* drag_toggle_set_xy_xy (interface_handlers.cc): touch every toggle whose rect the segment from * the last pointer position to this one crosses (BLI_rctf_isect_segment), so fast drags don't * skip buttons; the segment is sampled every 2 px through the regular hit test. Panel headers @@ -1894,7 +1903,7 @@ static int drag_toggle_segment(BKContext *ctx, int x, int y) for (int i = 0; i <= steps; i++) { const int sx = x0 + (int)lroundf((x - x0) * (float)i / steps); const int sy = y0 + (int)lroundf((y - y0) * (float)i / steps); - changed |= drag_toggle_apply(ctx, hit_all(ctx, sx, sy)); + changed |= drag_toggle_apply(ctx, bk_ctx_hit(ctx, sx, sy)); } ctx->dt_last_x = x; ctx->dt_last_y = y; @@ -2284,7 +2293,7 @@ int BK_render(BKContext *ctx, BuiRaster *r, int w, int h, int full) #define DOUBLE_CLICK_PX 4 #define TOOLTIP_DELAY_MS 500 /* UI_TOOLTIP_DELAY 0.5 */ -static BKNode *hit_all(BKContext *ctx, int x, int y) +BKNode *bk_ctx_hit(BKContext *ctx, int x, int y) { for (int i = ctx->npopups - 1; i >= 0; i--) { if (bk_contains(ctx->popups[i], x, y)) { @@ -2472,7 +2481,7 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods) } BKEvent e = make_event(ctx, g, x, y, mods); g->cls->move(g, &e); - BKNode *under = hit_all(ctx, x, y); + BKNode *under = bk_ctx_hit(ctx, x, y); if (under != ctx->hover) { set_hover(ctx, under); } @@ -2503,7 +2512,7 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods) if (ctx->dt_active) { /* Blender: drag across toggles */ changed |= drag_toggle_segment(ctx, x, y); } - BKNode *under = hit_all(ctx, x, y); + BKNode *under = bk_ctx_hit(ctx, x, y); if (under != ctx->hover) { set_hover(ctx, under); changed = 1; @@ -2513,7 +2522,7 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods) } return changed; } - BKNode *under = hit_all(ctx, x, y); + BKNode *under = bk_ctx_hit(ctx, x, y); if (under != ctx->hover) { set_hover(ctx, under); changed = 1; @@ -2584,7 +2593,7 @@ static int in_BK_press(BKContext *ctx, int x, int y, int mods) return 1; } } - BKNode *target = hit_all(ctx, x, y); + BKNode *target = bk_ctx_hit(ctx, x, y); if (ctx->focus && target != ctx->focus) { end_edit(ctx, true); } @@ -2688,7 +2697,7 @@ static int in_BK_release(BKContext *ctx, int x, int y, int mods) ctx->off_x = ctx->off_y = 0; ctx->pointer_x = x; ctx->pointer_y = y; - set_hover(ctx, hit_all(ctx, x, y)); + set_hover(ctx, bk_ctx_hit(ctx, x, y)); update_cursor(ctx); return 1; } @@ -2700,7 +2709,7 @@ static BKNode *buttons_target(BKContext *ctx, int x, int y) if (ctx->modal || ctx->npopups) { return NULL; } - BKNode *n = hit_all(ctx, x, y); + BKNode *n = bk_ctx_hit(ctx, x, y); return n && (n->cls->flags & CLS_BUTTONS) && NODE_ENABLED(n) ? n : NULL; } @@ -2723,7 +2732,7 @@ static int in_BK_context_menu(BKContext *ctx, int x, int y, int mods) if (ctx->focus) { end_edit(ctx, true); } - BKNode *under = hit_all(ctx, x, y); + BKNode *under = bk_ctx_hit(ctx, x, y); if (under && (under->flags & NF_EVENTS)) { /* bindings see it first */ BKEvent e = make_event(ctx, under, x, y, mods); raw_event(under, BK_EV_PRESS, mods, &e, 3); @@ -2732,7 +2741,7 @@ static int in_BK_context_menu(BKContext *ctx, int x, int y, int mods) for (int i = 0; i < ctx->npopups; i++) { in_popup |= bk_contains(ctx->popups[i], x, y); } - BKNode *target = hit_all(ctx, x, y); + BKNode *target = bk_ctx_hit(ctx, x, y); if (!in_popup) { BK_close_popups(ctx); } @@ -2865,7 +2874,7 @@ static BKNode *deepest(BKNode *n, int x, int y) static int in_BK_wheel(BKContext *ctx, int x, int y, int delta, int mods) { hide_tooltip(ctx); - BKNode *target = hit_all(ctx, x, y); + BKNode *target = bk_ctx_hit(ctx, x, y); if (!target && ctx->root && y >= ctx->header_h) { target = deepest(ctx->root, x, y); /* non-interactive area: let containers scroll */ } @@ -3376,7 +3385,7 @@ int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods) int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods) { - BKNode *t = BK_IS_CUSTOM(ctx->grab) ? ctx->grab : (ctx->modal ? NULL : hit_all(ctx, x, y)); + BKNode *t = BK_IS_CUSTOM(ctx->grab) ? ctx->grab : (ctx->modal ? NULL : bk_ctx_hit(ctx, x, y)); if (BK_IS_CUSTOM(t) && NODE_ENABLED(t)) { if (dx == 0.0f && dy == 0.0f) { return 0; @@ -3401,6 +3410,79 @@ int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods) return r; } +/* Touch and trackpad gestures, as Blender's MOUSEPAN / MOUSEZOOM / MOUSEROTATE reach the view + * under them (view2d_ops.cc): the first of `target` and its parents that takes the gesture. + * A custom node always does (it gets WHEEL in notches as BK_scroll's, MAGNIFY, ROTATE), so the + * region under an embedded UI never moves, as with the wheel (custom_wheel). */ +int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float a, float b, int mods) +{ + if (ctx->modal) { + return 0; + } + hide_tooltip(ctx); + for (BKNode *n = target; n; n = n->parent) { + if (!NODE_ENABLED(n)) { + continue; + } + if (BK_IS_CUSTOM(n)) { + BKCustomEvent ce; + memset(&ce, 0, sizeof(ce)); + ce.mods = mods; + if (kind == BK_GESTURE_PAN) { + const float step = 2.0f * bk_unit(); /* the region's pixels per wheel notch */ + ce.type = BK_CUSTOM_WHEEL; + ce.wheel_x = -a / step; /* content follows the fingers: moving left scrolls right */ + ce.wheel_y = b / step; + } + else if (kind == BK_GESTURE_MAGNIFY) { + ce.type = BK_CUSTOM_MAGNIFY; + ce.magnify = a; + } + else { + ce.type = BK_CUSTOM_ROTATE; + ce.rotate = a; + } + ctx->in_input++; + bk_custom_event(n, &ce, x, y); + ctx->in_input--; + return 1; + } + if (n->cls->gesture) { + BKEvent e = make_event(ctx, n, x, y, mods); + e.gesture = kind; + e.pan_x = kind == BK_GESTURE_PAN ? a : 0.0f; + e.pan_y = kind == BK_GESTURE_PAN ? b : 0.0f; + e.magnify = kind == BK_GESTURE_MAGNIFY ? a : 0.0f; + e.rotate = kind == BK_GESTURE_ROTATE ? a : 0.0f; + ctx->in_input++; + const int used = n->cls->gesture(n, &e); + ctx->in_input--; + if (used) { + bk_views_check(ctx); /* scrollbars follow */ + return 1; + } + } + } + return 0; +} + +static BKNode *gesture_target(BKContext *ctx, int x, int y) +{ + return BK_IS_CUSTOM(ctx->grab) ? ctx->grab : bk_ctx_hit(ctx, x, y); +} + +int BK_magnify(BKContext *ctx, int x, int y, float delta, int mods) +{ + return delta != 0.0f && + bk_gesture(ctx, gesture_target(ctx, x, y), x, y, BK_GESTURE_MAGNIFY, delta, 0.0f, mods); +} + +int BK_rotate(BKContext *ctx, int x, int y, float degrees, int mods) +{ + return degrees != 0.0f && + bk_gesture(ctx, gesture_target(ctx, x, y), x, y, BK_GESTURE_ROTATE, degrees, 0.0f, mods); +} + int BK_context_menu(BKContext *ctx, int x, int y, int mods) { INPUT_ENTRY(in_BK_context_menu(ctx, x, y, mods)); @@ -3463,7 +3545,7 @@ int BK_button(BKContext *ctx, int x, int y, int button, int release, int mods) return 1; } } - BKNode *under = hit_all(ctx, x, y); + BKNode *under = bk_ctx_hit(ctx, x, y); if (!under || !(under->flags & NF_EVENTS)) { return 0; } @@ -3787,7 +3869,7 @@ void bk_window_focus(BKContext *ctx, BKWindow *win, const BKWindowCallbacks *cb, BKNode *BK_hit_at(BKContext *ctx, int x, int y) { - return hit_all(ctx, x, y); + return bk_ctx_hit(ctx, x, y); } /** \} */ diff --git a/kit/intern/kit_custom.c b/kit/intern/kit_custom.c index 70d9784c..3f872b20 100644 --- a/kit/intern/kit_custom.c +++ b/kit/intern/kit_custom.c @@ -24,6 +24,7 @@ typedef struct BKCustom { double wake_at; /* frame due at this bk_time() (0 = none) */ int framed; /* frame ran at least once */ int last_w, last_h; + int raw_touch; /* BK_custom_set_touch: contacts arrive as BK_CUSTOM_TOUCH */ struct BKCustom *next; /* every custom node (any context) */ } BKCustom; @@ -398,6 +399,38 @@ void BK_custom_set_cursor(BKNode *node, int cursor) } } +void BK_custom_set_touch(BKNode *node, int raw) +{ + BKCustom *c = cust(node); + if (c) { + c->raw_touch = raw != 0; + } +} + +bool bk_custom_takes_touch(const BKNode *n) +{ + const BKCustom *c = cust(n); + return c && c->raw_touch && c->cls.event; +} + +/* A contact of a node that takes raw touches: the first one down gives it keyboard focus, as a + * click does (custom_press). */ +int bk_custom_touch(BKNode *n, int id, int phase, int x, int y, int mods) +{ + BKContext *ctx = bk_ctx(n); + if (phase == BK_TOUCH_DOWN && ctx && ctx->focus != n) { + BK_focus_node(ctx, NULL); /* ends another field's edit */ + take_focus(n); + } + BKCustomEvent ce; + memset(&ce, 0, sizeof(ce)); + ce.type = BK_CUSTOM_TOUCH; + ce.mods = mods; + ce.touch_id = id; + ce.touch_phase = phase; + return bk_custom_event(n, &ce, x, y); +} + int BK_custom_has_focus(BKNode *node) { BKContext *ctx = bk_ctx(node); diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h index e46dc1be..e0c16e6d 100644 --- a/kit/intern/kit_intern.h +++ b/kit/intern/kit_intern.h @@ -298,8 +298,14 @@ typedef struct BKEvent { const char *text; const char *keysym; float wheel_x, wheel_y; /* BK_scroll: precise deltas (custom nodes) */ + /* BKClass.gesture: Blender's MOUSEPAN (pan_x, pan_y: pixels the content follows), + * MOUSEZOOM (magnify: scale change) and MOUSEROTATE (rotate: degrees, > 0 counter-clockwise) */ + int gesture; /* BK_GESTURE_* */ + float pan_x, pan_y, magnify, rotate; } BKEvent; +enum { BK_GESTURE_PAN = 1, BK_GESTURE_MAGNIFY, BK_GESTURE_ROTATE }; + #define EV_SHIFT(e) (((e)->mods & BK_SHIFT) != 0) #define EV_CTRL(e) (((e)->mods & BK_CTRL) != 0) #define EV_ALT(e) (((e)->mods & BK_ALT) != 0) @@ -330,6 +336,7 @@ typedef struct BKClass { int (*key)(BKNode *n, BKEvent *e); int (*key_up)(BKNode *n, BKEvent *e); /* a key release, sent to the top popup */ int (*wheel)(BKNode *n, BKEvent *e); + int (*gesture)(BKNode *n, BKEvent *e); /* touch / trackpad pan, magnify, rotate; 1 = used */ int (*cursor_at)(BKNode *n, int x, int y); void (*finish_edit)(BKNode *n, bool confirm); int (*context_items)(BKNode *n, BKMenuSpec *items, int max); @@ -561,6 +568,27 @@ typedef struct BKUndo { #define BK_MAX_UNDO 128 #define BK_MAX_MULTI 32 #define BK_MAX_ANIM 32 +#define BK_MAX_TOUCH 10 /* contacts followed at once; more are ignored */ + +/* One finger on the screen (kit_touch.c). */ +typedef struct BKTouchPoint { + int id; /* the host's contact id */ + int role; /* BK_TP_*: free, the default path, a raw custom node's, or ignored */ + float x, y; /* last position, window pixels */ + BKNode *raw; /* BK_TP_RAW: the custom node that takes it */ +} BKTouchPoint; +enum { BK_TP_FREE = 0, BK_TP_DEFAULT, BK_TP_RAW, BK_TP_DEAD }; + +typedef struct BKTouch { + BKTouchPoint pts[BK_MAX_TOUCH]; + int pointer; /* the contact that is the pointer, -1 none */ + int g0, g1; /* the gesture's two contacts, -1 none */ + bool latched; /* a gesture ran: no pointer until every contact lifted */ + BKNode *target; /* what the gesture began over (scroll target) */ + int start_x, start_y; /* the gesture's first centre */ + float cx, cy, dist, ang; /* its centre, spread and angle at the last update */ + float rest_x, rest_y; /* pan not yet sent as whole wheel steps (pixels) */ +} BKTouch; struct BKContext { BKNode *root, *header; @@ -620,6 +648,8 @@ struct BKContext { int next_button; /* the button the next in_BK_press / in_BK_release is for (0 = 1) */ int in_custom_frame; /* inside custom frame callbacks: no host requests */ double custom_timer_due; /* armed BK_TIMER_CUSTOM (bk_time), 0 = none */ + /* touch screen contacts and their gesture (kit_touch.c) */ + BKTouch touch; /* every live context (BK_set_theme redraws them all) */ BKContext *next_ctx; }; @@ -642,6 +672,16 @@ void bk_custom_timer(BKContext *ctx); /* BK_TIMER_CUSTOM fired */ void bk_ctx_arm_timer(BKContext *ctx); bool bk_animations_enabled(void); /* BK_set_animations: off = reduced motion */ void bk_update_cursor(BKContext *ctx); +/* Raw touches (BK_custom_set_touch): whether n takes them, and one contact for it. */ +bool bk_custom_takes_touch(const BKNode *n); +int bk_custom_touch(BKNode *n, int id, int phase, int x, int y, int mods); + +/* The topmost node at x, y: popups, then the header, then the root. */ +BKNode *bk_ctx_hit(BKContext *ctx, int x, int y); +/* Touch / trackpad gestures (kit_core.c): a BK_GESTURE_* event at x, y for `target` and its + * parents (a custom node, a class with a gesture hook); 0 when none took it. */ +int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float a, float b, int mods); +void bk_touch_init(BKContext *ctx); void bk_undo_record(BKNode *n, int kind); void bk_anim_start(BKNode *n); diff --git a/kit/intern/kit_nodes.c b/kit/intern/kit_nodes.c index 2fc09a0e..1809292a 100644 --- a/kit/intern/kit_nodes.c +++ b/kit/intern/kit_nodes.c @@ -1136,6 +1136,25 @@ static int editor_wheel(BKNode *e, BKEvent *ev) return 1; } +/* Touch and trackpad gestures (view2d_ops.cc): MOUSEPAN moves the view with the fingers + * (view_pan_invoke), MOUSEZOOM zooms about them (view_zoomdrag_invoke); no rotation. */ +static int editor_gesture(BKNode *e, BKEvent *ev) +{ + NodeEdit *d = ed(e); + if (ev->gesture == BK_GESTURE_PAN) { + d->panx += ev->pan_x; + d->pany += ev->pan_y; + } + else if (ev->gesture == BK_GESTURE_MAGNIFY) { + zoom_at(e, 1.0f + ev->magnify, ev->x, ev->y); + } + else { + return 0; + } + bk_invalidate(e); + return 1; +} + static int editor_key(BKNode *e, BKEvent *ev) { const char *k = ev->keysym; @@ -1258,6 +1277,7 @@ const BKClass bk_cls_nodeeditor = {.name = "nodeeditor", .release = editor_release, .cancel = editor_cancel, .wheel = editor_wheel, + .gesture = editor_gesture, .key = editor_key, .cursor_at = editor_cursor_at, .set_num = editor_set_num, diff --git a/kit/intern/kit_touch.c b/kit/intern/kit_touch.c new file mode 100644 index 00000000..7a0a9c15 --- /dev/null +++ b/kit/intern/kit_touch.c @@ -0,0 +1,299 @@ +/* Touch screens (BK_touch): the contacts a host sends, turned into what the widgets know. + * + * Blender has no touch screen input; this follows what X11, Wayland compositors and Windows do + * for windows that are not touch aware (the first finger is the mouse), and gives two fingers + * the trackpad's events, GHOST_kTrackpadEventScroll / Magnify / Rotate (MOUSEPAN, MOUSEZOOM, + * MOUSEROTATE in Blender), about the fingers' centre: + * - one finger: motion to it, press, drags, release, then the pointer leaves (no hover stays); + * - a second finger: the first one's interaction is cancelled as Escape cancels a drag + * (kit_core.c's in_BK_key) and released away from every widget, so nothing is clicked; + * then the two are a gesture until either lifts, and no finger is the pointer again until + * all of them lifted (a lifted pinch must not click what is under the remaining finger); + * - a custom node that asked for raw touches (BK_custom_set_touch) gets each contact that began + * over it, and nothing else does. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#include +#include + +#include "kit_intern.h" + +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +#define OFF (-100000) /* where the pointer goes when its finger lifts, as hosts send a leave */ + +void bk_touch_init(BKContext *ctx) +{ + memset(&ctx->touch, 0, sizeof(ctx->touch)); + ctx->touch.pointer = ctx->touch.g0 = ctx->touch.g1 = -1; +} + +static int px(float v) +{ + return (int)floorf(v + 0.5f); +} + +static int find_point(const BKTouch *t, int id) +{ + for (int i = 0; i < BK_MAX_TOUCH; i++) { + if (t->pts[i].role != BK_TP_FREE && t->pts[i].id == id) { + return i; + } + } + return -1; +} + +/* How many default-path contacts other than `self` are down; *r_other is one of them. */ +static int count_others(const BKTouch *t, int self, int *r_other) +{ + int n = 0; + for (int i = 0; i < BK_MAX_TOUCH; i++) { + if (i != self && t->pts[i].role == BK_TP_DEFAULT) { + *r_other = i; + n++; + } + } + return n; +} + +static bool any_default(const BKTouch *t) +{ + for (int i = 0; i < BK_MAX_TOUCH; i++) { + if (t->pts[i].role == BK_TP_DEFAULT) { + return true; + } + } + return false; +} + +/* The custom node taking raw touches at x, y: the nearest custom node there, if it asked. */ +static BKNode *raw_target(BKContext *ctx, int x, int y) +{ + if (ctx->modal || ctx->npopups) { /* the press path closes popups / feeds the tool */ + return NULL; + } + for (BKNode *n = bk_ctx_hit(ctx, x, y); n; n = n->parent) { + if (BK_IS_CUSTOM(n)) { + return NODE_ENABLED(n) && bk_custom_takes_touch(n) ? n : NULL; + } + } + return NULL; +} + +static int deliver_raw(BKContext *ctx, const BKTouchPoint *p, int phase, int mods) +{ + ctx->in_input++; + const int r = bk_custom_touch(p->raw, p->id, phase, px(p->x), px(p->y), mods); + ctx->in_input--; + bk_views_check(ctx); + return r; +} + +/* The pointer's finger no longer is one: undo what it did, as Escape does to a drag, and end the + * press away from every widget (buttons are not clicked, number fields do not start editing). */ +static void abort_pointer(BKContext *ctx, int mods) +{ + BKTouch *t = &ctx->touch; + if (t->pointer < 0) { + return; + } + t->pointer = -1; + if (ctx->grab && ctx->dragging && ctx->grab->cls->cancel) { + ctx->grab->cls->cancel(ctx->grab); + ctx->has_ungrab = false; + } + BK_release(ctx, OFF, OFF, mods); + BK_motion(ctx, OFF, OFF, BK_FROM_TOUCH); +} + +static void gesture_metrics(const BKTouch *t, float *r_cx, float *r_cy, float *r_dist, + float *r_ang) +{ + const BKTouchPoint *a = &t->pts[t->g0], *b = &t->pts[t->g1]; + *r_cx = 0.5f * (a->x + b->x); + *r_cy = 0.5f * (a->y + b->y); + *r_dist = hypotf(b->x - a->x, b->y - a->y); + *r_ang = atan2f(b->y - a->y, b->x - a->x); +} + +static void gesture_begin(BKContext *ctx, int i0, int i1) +{ + BKTouch *t = &ctx->touch; + t->g0 = i0; + t->g1 = i1; + t->latched = true; + gesture_metrics(t, &t->cx, &t->cy, &t->dist, &t->ang); + t->start_x = px(t->cx); + t->start_y = px(t->cy); + t->target = bk_ctx_hit(ctx, t->start_x, t->start_y); + t->rest_x = t->rest_y = 0.0f; +} + +static void gesture_end(BKTouch *t) +{ + t->g0 = t->g1 = -1; + t->target = NULL; +} + +/* A pan nothing took: the region or scroll view under the gesture's start scrolls one wheel + * notch per 2 widget units the fingers moved (in_BK_wheel's step), the content following them. */ +static int pan_steps(BKContext *ctx, float dx, float dy, int mods) +{ + BKTouch *t = &ctx->touch; + const float step = 2.0f * bk_unit(); + int r = 0; + t->rest_x += dx; + t->rest_y += dy; + for (int i = 0; i < 8 && fabsf(t->rest_y) >= step; i++) { /* down: the content goes down */ + const int d = t->rest_y > 0.0f ? 1 : -1; + t->rest_y -= d * step; + r |= BK_wheel(ctx, t->start_x, t->start_y, d, mods); + } + for (int i = 0; i < 8 && fabsf(t->rest_x) >= step; i++) { /* Shift + wheel, as BK_scroll */ + const int d = t->rest_x > 0.0f ? 1 : -1; + t->rest_x -= d * step; + r |= BK_wheel(ctx, t->start_x, t->start_y, d, mods | BK_SHIFT); + } + return r; +} + +static int gesture_update(BKContext *ctx, int mods) +{ + BKTouch *t = &ctx->touch; + float cx, cy, dist, ang; + gesture_metrics(t, &cx, &cy, &dist, &ang); + const float dx = cx - t->cx, dy = cy - t->cy; + const float magnify = t->dist > 1.0f ? dist / t->dist - 1.0f : 0.0f; + float turn = ang - t->ang; + while (turn > (float)M_PI) { + turn -= 2.0f * (float)M_PI; + } + while (turn < -(float)M_PI) { + turn += 2.0f * (float)M_PI; + } + /* y points down on screen: a counter-clockwise turn lowers the angle */ + const float degrees = -turn * (180.0f / (float)M_PI); + t->cx = cx; + t->cy = cy; + t->dist = dist; + t->ang = ang; + const int x = px(cx), y = px(cy); + int r = 0; + if (dx != 0.0f || dy != 0.0f) { + r |= bk_gesture(ctx, t->target, x, y, BK_GESTURE_PAN, dx, dy, mods) || + pan_steps(ctx, dx, dy, mods); + } + if (magnify != 0.0f) { + r |= bk_gesture(ctx, t->target, x, y, BK_GESTURE_MAGNIFY, magnify, 0.0f, mods); + } + if (degrees != 0.0f) { + r |= bk_gesture(ctx, t->target, x, y, BK_GESTURE_ROTATE, degrees, 0.0f, mods); + } + return r; +} + +static int touch_down(BKContext *ctx, int id, float x, float y, int mods) +{ + BKTouch *t = &ctx->touch; + int i = 0; + while (i < BK_MAX_TOUCH && t->pts[i].role != BK_TP_FREE) { + i++; + } + if (i == BK_MAX_TOUCH) { + return 0; + } + BKTouchPoint *p = &t->pts[i]; + p->id = id; + p->x = x; + p->y = y; + p->raw = raw_target(ctx, px(x), px(y)); + if (p->raw) { + p->role = BK_TP_RAW; + return deliver_raw(ctx, p, BK_TOUCH_DOWN, mods); + } + p->role = BK_TP_DEFAULT; + const int tm = mods | BK_FROM_TOUCH; + int other = -1; + const int others = count_others(t, i, &other); + if (others == 0 && !t->latched) { + t->pointer = i; + BK_motion(ctx, px(x), px(y), tm); + BK_press(ctx, px(x), px(y), tm | BK_BUTTON1); + return 1; + } + if (others == 1 && t->g0 < 0 && !ctx->modal) { + abort_pointer(ctx, tm); + gesture_begin(ctx, other, i); + return 1; + } + return 0; /* a third finger, or one while a tool runs: followed, not used */ +} + +/* MOVE, UP or CANCEL of contact i. */ +static int touch_update(BKContext *ctx, int i, int phase, int mods) +{ + BKTouch *t = &ctx->touch; + BKTouchPoint *p = &t->pts[i]; + const int tm = mods | BK_FROM_TOUCH; + const int x = px(p->x), y = px(p->y); + if (p->role == BK_TP_RAW) { + return deliver_raw(ctx, p, phase, mods); + } + if (p->role != BK_TP_DEFAULT) { + return 0; + } + if (i == t->pointer) { + if (phase == BK_TOUCH_MOVE) { + return BK_motion(ctx, x, y, tm | BK_BUTTON1); + } + if (phase == BK_TOUCH_CANCEL) { + abort_pointer(ctx, tm); + return 1; + } + t->pointer = -1; + BK_release(ctx, x, y, tm); + BK_motion(ctx, OFF, OFF, BK_FROM_TOUCH); + return 1; + } + if (i == t->g0 || i == t->g1) { + if (phase == BK_TOUCH_MOVE) { + return gesture_update(ctx, tm); + } + gesture_end(t); + return 1; + } + return 0; +} + +int BK_touch(BKContext *ctx, int id, int phase, float x, float y, int mods) +{ + BKTouch *t = &ctx->touch; + mods &= ~(BK_BUTTON1 | BK_BUTTON2 | BK_BUTTON3 | BK_FROM_TOUCH); + int i = find_point(t, id); + if (phase == BK_TOUCH_DOWN) { + int r = 0; + if (i >= 0) { /* its up was lost: what it did is not kept */ + r |= touch_update(ctx, i, BK_TOUCH_CANCEL, mods); + t->pts[i].role = BK_TP_FREE; + } + return touch_down(ctx, id, x, y, mods) | r; + } + if (i < 0 || phase < BK_TOUCH_MOVE || phase > BK_TOUCH_CANCEL) { + return 0; + } + BKTouchPoint *p = &t->pts[i]; + p->x = x; + p->y = y; + const int r = touch_update(ctx, i, phase, mods); + if (phase != BK_TOUCH_MOVE) { + p->role = BK_TP_FREE; + p->raw = NULL; + if (!any_default(t)) { + t->latched = false; + } + } + return r; +} diff --git a/kit/intern/kit_window_cocoa.m b/kit/intern/kit_window_cocoa.m index d54c09ee..5cd7760d 100644 --- a/kit/intern/kit_window_cocoa.m +++ b/kit/intern/kit_window_cocoa.m @@ -556,6 +556,29 @@ - (void)scrollWheel:(NSEvent *)ev } } +/* GHOST_SystemCocoa::handleMouseEvent NSEventTypeMagnify / NSEventTypeRotate: trackpad pinches + * and turns at the pointer (GHOST_kTrackpadEventMagnify / Rotate). magnification is the scale + * change, rotation degrees counter-clockwise, as BK_magnify and BK_rotate take them. */ +- (void)magnifyWithEvent:(NSEvent *)ev +{ + if (!bk || bk->disabled) { + return; + } + int x, y; + event_px(bk, ev, &x, &y); + BK_magnify(bk->ctx, x, y, (float)[ev magnification], mods_of([ev modifierFlags]) & ~BK_BUTTON1); +} + +- (void)rotateWithEvent:(NSEvent *)ev +{ + if (!bk || bk->disabled) { + return; + } + int x, y; + event_px(bk, ev, &x, &y); + BK_rotate(bk->ctx, x, y, [ev rotation], mods_of([ev modifierFlags]) & ~BK_BUTTON1); +} + /* -- keys (GHOST_WindowViewCocoa.hh keyDown: / HANDLE_KEY_EVENT) -- */ /* Handling keyDown: here (not calling super) also keeps AppKit from beeping. */ diff --git a/kit/intern/kit_window_wayland.c b/kit/intern/kit_window_wayland.c index c0e833e2..b394d322 100644 --- a/kit/intern/kit_window_wayland.c +++ b/kit/intern/kit_window_wayland.c @@ -34,6 +34,9 @@ # include "cursor-shape-v1-client-protocol.h" # endif # include "xdg-decoration-unstable-v1-client-protocol.h" +# ifdef BUI_WL_POINTER_GESTURES +# include "pointer-gestures-unstable-v1-client-protocol.h" +# endif # include "xdg-shell-client-protocol.h" # include @@ -53,6 +56,7 @@ # define MAX_TIMERS 16 # define MAX_RECTS 32 # define MAX_OUTPUTS 8 +# define MAX_TOUCHES 10 /* as the kit's BK_MAX_TOUCH */ /* -- libxkbcommon, loaded on first use -- */ @@ -164,6 +168,19 @@ static struct { struct wl_seat *seat; struct wl_pointer *pointer; struct wl_keyboard *keyboard; + struct wl_touch *touch; + struct { + int used; + int32_t id; + BKWindow *win; /* the surface it went down on (wl_touch.up / motion do not say) */ + double x, y; /* raster pixels */ + } touches[MAX_TOUCHES]; +# ifdef BUI_WL_POINTER_GESTURES + struct zwp_pointer_gestures_v1 *gestures; + struct zwp_pointer_gesture_pinch_v1 *pinch; /* of the pointer, made once both exist */ + BKWindow *pinch_win; + double pinch_scale; /* the last update's (scale is since the pinch began) */ +# endif struct wl_data_device_manager *data_manager; struct wl_data_device *data_device; struct wl_data_offer *offer; /* the clipboard, with a text mime type */ @@ -730,11 +747,138 @@ static void run_repeat(void) } } +/* -- seat: touch screen (wl_touch), into BK_touch -- */ + +static int touch_slot(int32_t id) +{ + for (int i = 0; i < MAX_TOUCHES; i++) { + if (g.touches[i].used && g.touches[i].id == id) { + return i; + } + } + return -1; +} + +static void touch_down(void *d, struct wl_touch *t, uint32_t serial, uint32_t time, + struct wl_surface *surface, int32_t id, wl_fixed_t x, wl_fixed_t y) +{ + BKWindow *win = find_window(surface); + g.serial = serial; + int i = touch_slot(id); + for (int j = 0; i < 0 && j < MAX_TOUCHES; j++) { + i = g.touches[j].used ? -1 : j; + } + if (!win || i < 0) { + return; + } + g.touches[i].used = 1; + g.touches[i].id = id; + g.touches[i].win = win; + g.touches[i].x = wl_fixed_to_double(x) * win->bscale; + g.touches[i].y = wl_fixed_to_double(y) * win->bscale; + BK_touch(win->ctx, id, BK_TOUCH_DOWN, (float)g.touches[i].x, (float)g.touches[i].y, + mods_now() & ~BK_BUTTON1); +} + +static void touch_up(void *d, struct wl_touch *t, uint32_t serial, uint32_t time, int32_t id) +{ + const int i = touch_slot(id); + g.serial = serial; + if (i >= 0) { + g.touches[i].used = 0; + if (g.touches[i].win) { + BK_touch(g.touches[i].win->ctx, id, BK_TOUCH_UP, (float)g.touches[i].x, + (float)g.touches[i].y, mods_now() & ~BK_BUTTON1); + } + } +} + +static void touch_motion(void *d, struct wl_touch *t, uint32_t time, int32_t id, wl_fixed_t x, + wl_fixed_t y) +{ + const int i = touch_slot(id); + BKWindow *win = i >= 0 ? g.touches[i].win : NULL; + if (win) { + g.touches[i].x = wl_fixed_to_double(x) * win->bscale; + g.touches[i].y = wl_fixed_to_double(y) * win->bscale; + BK_touch(win->ctx, id, BK_TOUCH_MOVE, (float)g.touches[i].x, (float)g.touches[i].y, + mods_now() & ~BK_BUTTON1); + } +} + +/* The compositor took every touch point (a system gesture): none of them is kept. */ +static void touch_cancel(void *d, struct wl_touch *t) +{ + for (int i = 0; i < MAX_TOUCHES; i++) { + if (g.touches[i].used && g.touches[i].win) { + BK_touch(g.touches[i].win->ctx, g.touches[i].id, BK_TOUCH_CANCEL, (float)g.touches[i].x, + (float)g.touches[i].y, 0); + } + g.touches[i].used = 0; + } +} + +static struct wl_touch_listener touch_listener = { + .down = touch_down, .up = touch_up, .motion = touch_motion, .cancel = touch_cancel}; + +/* -- seat: touchpad pinch (pointer-gestures), as GHOST_SystemWayland's gesture_pinch -- */ + +# ifdef BUI_WL_POINTER_GESTURES +static void pinch_begin(void *d, struct zwp_pointer_gesture_pinch_v1 *p, uint32_t serial, + uint32_t time, struct wl_surface *surface, uint32_t fingers) +{ + g.pinch_win = find_window(surface); + g.pinch_scale = 1.0; +} + +static void pinch_update(void *d, struct zwp_pointer_gesture_pinch_v1 *p, uint32_t time, + wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) +{ + BKWindow *win = g.pinch_win; + const double s = wl_fixed_to_double(scale); + if (!win || s <= 0.0) { + return; + } + const int mods = mods_now() & ~BK_BUTTON1; + /* scale is since the pinch began; rotation is degrees since the last update, clockwise */ + BK_magnify(win->ctx, (int)g.px, (int)g.py, (float)(s / g.pinch_scale - 1.0), mods); + if (win == g.pinch_win) { /* the magnify may have closed it */ + BK_rotate(win->ctx, (int)g.px, (int)g.py, (float)-wl_fixed_to_double(rotation), mods); + } + g.pinch_scale = s; +} + +static void pinch_end(void *d, struct zwp_pointer_gesture_pinch_v1 *p, uint32_t serial, + uint32_t time, int32_t cancelled) +{ + g.pinch_win = NULL; +} + +static struct zwp_pointer_gesture_pinch_v1_listener pinch_listener = { + .begin = pinch_begin, .update = pinch_update, .end = pinch_end}; + +/* The pinch needs the pointer and the gestures global, which may come in either order. */ +static void pinch_attach(void) +{ + if (g.gestures && g.pointer && !g.pinch) { + g.pinch = zwp_pointer_gestures_v1_get_pinch_gesture(g.gestures, g.pointer); + zwp_pointer_gesture_pinch_v1_add_listener(g.pinch, &pinch_listener, NULL); + } +} +# endif + static void seat_capabilities(void *d, struct wl_seat *seat, uint32_t caps) { if ((caps & WL_SEAT_CAPABILITY_POINTER) && !g.pointer) { g.pointer = wl_seat_get_pointer(seat); wl_pointer_add_listener(g.pointer, &pointer_listener, NULL); +# ifdef BUI_WL_POINTER_GESTURES + pinch_attach(); +# endif + } + if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !g.touch) { + g.touch = wl_seat_get_touch(seat); + wl_touch_add_listener(g.touch, &touch_listener, NULL); } if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !g.keyboard) { g.keyboard = wl_seat_get_keyboard(seat); @@ -939,6 +1083,12 @@ static void registry_global(void *d, struct wl_registry *reg, uint32_t name, con g.seat = wl_registry_bind(reg, name, &wl_seat_interface, BK_MIN(version, 5u)); wl_seat_add_listener(g.seat, &seat_listener, NULL); } +# ifdef BUI_WL_POINTER_GESTURES + else if (!strcmp(iface, zwp_pointer_gestures_v1_interface.name)) { + g.gestures = wl_registry_bind(reg, name, &zwp_pointer_gestures_v1_interface, 1); + pinch_attach(); + } +# endif else if (!strcmp(iface, wl_data_device_manager_interface.name)) { g.data_manager = wl_registry_bind(reg, name, &wl_data_device_manager_interface, 1); } @@ -976,6 +1126,10 @@ static void fill_listeners(void) fill_noop(&buffer_listener, sizeof(buffer_listener)); fill_noop(&frame_listener, sizeof(frame_listener)); fill_noop(&pointer_listener, sizeof(pointer_listener)); + fill_noop(&touch_listener, sizeof(touch_listener)); +# ifdef BUI_WL_POINTER_GESTURES + fill_noop(&pinch_listener, sizeof(pinch_listener)); +# endif fill_noop(&keyboard_listener, sizeof(keyboard_listener)); fill_noop(&seat_listener, sizeof(seat_listener)); fill_noop(&offer_listener, sizeof(offer_listener)); @@ -1173,6 +1327,16 @@ static void close_window(BKWindow *win) g.keyboard_win = NULL; g.repeat_key = 0; } + for (int i = 0; i < MAX_TOUCHES; i++) { /* its fingers' remaining events go nowhere */ + if (g.touches[i].win == win) { + g.touches[i].win = NULL; + } + } +# ifdef BUI_WL_POINTER_GESTURES + if (g.pinch_win == win) { + g.pinch_win = NULL; + } +# endif role_destroy(win); wl_surface_destroy(win->surface); buf_destroy(&win->bufs[0]); diff --git a/kit/intern/kit_window_win32.c b/kit/intern/kit_window_win32.c index 375468be..ba27c37c 100644 --- a/kit/intern/kit_window_win32.c +++ b/kit/intern/kit_window_win32.c @@ -591,6 +591,48 @@ static int mods_now(WPARAM wp, int mouse) return m; } +/* -- touch screens: WM_TOUCH into BK_touch -- */ + +/* Mouse messages Windows makes from a touch (GetMessageExtraInfo: MI_WP_SIGNATURE, with the + * touch bit; pen ones lack it and stay mouse input). The touches came as WM_TOUCH already. */ +static int mouse_from_touch(void) +{ + return ((DWORD)GetMessageExtraInfo() & 0xFFFFFF80u) == 0xFF515780u; +} + +# ifndef WM_TABLET_QUERYSYSTEMGESTURESTATUS +# define WM_TABLET_QUERYSYSTEMGESTURESTATUS 0x02CC +# endif +# define BK_TABLET_DISABLE_PRESSANDHOLD 0x00000001 +# define BK_TABLET_DISABLE_FLICKS 0x00010000 + +static void handle_touch(BKWindow *win, HWND hwnd, WPARAM wp, LPARAM lp) +{ + TOUCHINPUT in[16]; + const UINT n = BK_MIN(LOWORD(wp), (UINT)(sizeof(in) / sizeof(in[0]))); + if (!GetTouchInputInfo((HTOUCHINPUT)lp, n, in, sizeof(TOUCHINPUT))) { + return; + } + POINT origin = {0, 0}; + ClientToScreen(hwnd, &origin); + for (UINT i = 0; i < n && win->hwnd; i++) { + const DWORD f = in[i].dwFlags; + const int phase = (f & TOUCHEVENTF_DOWN) ? BK_TOUCH_DOWN : + (f & TOUCHEVENTF_UP) ? BK_TOUCH_UP : + (f & TOUCHEVENTF_MOVE) ? BK_TOUCH_MOVE : + -1; + if (phase < 0) { + continue; + } + if (phase == BK_TOUCH_DOWN) { + SetFocus(hwnd); /* as WM_LBUTTONDOWN */ + } + /* hundredths of a physical screen pixel */ + BK_touch(win->ctx, (int)in[i].dwID, phase, in[i].x / 100.0f - origin.x, + in[i].y / 100.0f - origin.y, mods_now(0, 0)); + } +} + static const char *vk_keysym(WPARAM vk, char *buf) { switch (vk) { @@ -634,6 +676,9 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) return DefWindowProcW(hwnd, msg, wp, lp); } BKContext *ctx = win->ctx; + if (msg >= WM_MOUSEFIRST && msg <= WM_MBUTTONDBLCLK && mouse_from_touch()) { + return 0; /* moves and buttons made from a touch (WM_TOUCH has it); wheels are not */ + } switch (msg) { case WM_BK_RENDER: if (win->want_frame && win->cb.on_frame) { @@ -769,6 +814,13 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } return 0; } + case WM_TOUCH: + handle_touch(win, hwnd, wp, lp); + CloseTouchInputHandle((HTOUCHINPUT)lp); + return 0; + case WM_TABLET_QUERYSYSTEMGESTURESTATUS: + /* no press-and-hold right click ring, no flicks: a held finger is a held press */ + return BK_TABLET_DISABLE_PRESSANDHOLD | BK_TABLET_DISABLE_FLICKS; case WM_MOUSEWHEEL: { POINT p = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)}; ScreenToClient(hwnd, &p); @@ -967,6 +1019,7 @@ BKWindow *BK_window_new(BKContext *ctx, const char *title, int width, int height return NULL; } SetWindowLongPtrW(win->hwnd, GWLP_USERDATA, (LONG_PTR)win); + RegisterTouchWindow(win->hwnd, 0); /* touches as WM_TOUCH (BK_touch), not as the mouse */ g_open++; if (BUI_gpu_default()) { gpu_attach(win); diff --git a/kit/intern/kit_window_x11.c b/kit/intern/kit_window_x11.c index 171464d8..d2bea645 100644 --- a/kit/intern/kit_window_x11.c +++ b/kit/intern/kit_window_x11.c @@ -26,6 +26,13 @@ # include # include # include +/* Touch screens through XInput 2.2 when its header is there (libXi is loaded at run time too). */ +# if defined(__has_include) +# if __has_include() +# include +# define BK_X11_XI2 +# endif +# endif # include # include @@ -215,6 +222,55 @@ 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 */ +/* -- touch screens (XInput 2.2), optional -- */ + +# ifdef BK_X11_XI2 +static int g_xi_opcode = -1; /* the XInput extension's major opcode, -1: no touch */ +static Status (*p_XIQueryVersion)(Display *, int *, int *); +static int (*p_XISelectEvents)(Display *, Window, XIEventMask *, int); +static Bool (*p_XGetEventData)(Display *, XGenericEventCookie *); +static void (*p_XFreeEventData)(Display *, XGenericEventCookie *); +static Bool (*p_XQueryExtension)(Display *, const char *, int *, int *, int *); + +/* After the display opened: XInput 2.2 with touch events, or nothing changes. */ +static void xi_init(Display *dpy) +{ + void *xi = dlopen("libXi.so.6", RTLD_NOW | RTLD_LOCAL); + void *x11 = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL); /* x11_load's, counted again */ + if (!xi || !x11) { + return; + } + *(void **)&p_XIQueryVersion = dlsym(xi, "XIQueryVersion"); + *(void **)&p_XISelectEvents = dlsym(xi, "XISelectEvents"); + *(void **)&p_XGetEventData = dlsym(x11, "XGetEventData"); + *(void **)&p_XFreeEventData = dlsym(x11, "XFreeEventData"); + *(void **)&p_XQueryExtension = dlsym(x11, "XQueryExtension"); + int op, ev, err, major = 2, minor = 2; + if (p_XIQueryVersion && p_XISelectEvents && p_XGetEventData && p_XFreeEventData && + p_XQueryExtension && p_XQueryExtension(dpy, "XInputExtension", &op, &ev, &err) && + p_XIQueryVersion(dpy, &major, &minor) == Success && (major > 2 || minor >= 2)) + { + g_xi_opcode = op; + } +} + +/* Touches on the window come as touch events (the server then sends it no emulated pointer + * events for them). */ +static void xi_select(Window xid) +{ + if (g_xi_opcode < 0) { + return; + } + unsigned char bits[XIMaskLen(XI_LASTEVENT)]; + memset(bits, 0, sizeof(bits)); + XISetMask(bits, XI_TouchBegin); + XISetMask(bits, XI_TouchUpdate); + XISetMask(bits, XI_TouchEnd); + XIEventMask mask = {XIAllMasterDevices, (int)sizeof(bits), bits}; + p_XISelectEvents(g_dpy, xid, &mask, 1); +} +# endif + static double now_ms(void) { struct timespec ts; @@ -240,6 +296,9 @@ static int open_display(void) a_utf8 = XInternAtom(g_dpy, "UTF8_STRING", False); a_targets = XInternAtom(g_dpy, "TARGETS", False); a_bui_sel = XInternAtom(g_dpy, "BUI_SELECTION", False); +# ifdef BK_X11_XI2 + xi_init(g_dpy); +# endif return 1; } @@ -560,6 +619,29 @@ static void handle_key(BKWindow *win, XKeyEvent *ke, int press) BK_key(win->ctx, printable ? text : "", name, mods); } +# ifdef BK_X11_XI2 +static void handle_touch(XGenericEventCookie *c) +{ + if (c->extension != g_xi_opcode || !p_XGetEventData(g_dpy, c)) { + return; + } + const XIDeviceEvent *de = (const XIDeviceEvent *)c->data; + const int phase = c->evtype == XI_TouchBegin ? BK_TOUCH_DOWN : + c->evtype == XI_TouchUpdate ? BK_TOUCH_MOVE : + c->evtype == XI_TouchEnd ? BK_TOUCH_UP : + -1; + BKWindow *win = phase >= 0 ? find_window(de->event) : NULL; + if (win && win->xid) { + if (phase == BK_TOUCH_DOWN) { + XSetInputFocus(g_dpy, win->xid, RevertToParent, CurrentTime); /* as Button1 */ + } + BK_touch(win->ctx, de->detail, phase, (float)de->event_x, (float)de->event_y, + mods_of((unsigned)de->mods.effective)); + } + p_XFreeEventData(g_dpy, c); +} +# endif + static void close_window(BKWindow *win) { if (!win->xid) { @@ -592,6 +674,12 @@ static void handle_event(XEvent *ev) XSendEvent(g_dpy, rq->requestor, False, 0, (XEvent *)&sn); return; } +# ifdef BK_X11_XI2 + if (ev->type == GenericEvent) { /* no window field: its own lookup */ + handle_touch(&ev->xcookie); + return; + } +# endif BKWindow *win = find_window(ev->xany.window); if (!win || !win->xid) { return; @@ -759,6 +847,9 @@ static bool create_xid(BKWindow *win, bool transparent) return false; } XSetWMProtocols(g_dpy, win->xid, &a_delete, 1); +# ifdef BK_X11_XI2 + xi_select(win->xid); +# endif win->gc = XCreateGC(g_dpy, win->xid, 0, NULL); BK_window_set_title(win, win->title); BUI_raster_set_alpha(win->raster, win->depth == 32); diff --git a/tests/touch_test.c b/tests/touch_test.c new file mode 100644 index 00000000..2b94f5a6 --- /dev/null +++ b/tests/touch_test.c @@ -0,0 +1,424 @@ +/* Touch screens and trackpad gestures (BK_touch, BK_magnify, BK_rotate) driven by synthetic + * contacts, the way a window host feeds them: one finger is the pointer, a second cancels it and + * makes a gesture (pan, magnify, rotate), raw contacts reach custom nodes that ask for them. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#include +#include +#include +#include + +#include "BUI_kit.h" +#include "GPU_raster.h" + +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +static int g_fail = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + g_fail = 1; \ + } \ + } while (0) + +enum { W = 400, H = 300 }; + +static BuiRaster *g_raster; +static int g_clicks; + +static void host_noop(void *data) {} +static void host_cursor(void *data, int c) {} +static void host_warp(void *data, int x, int y) {} +static char *host_clip_get(void *data) +{ + return NULL; +} +static void host_clip_set(void *data, const char *t) {} +static void host_schedule(void *data, int ms, int timer) {} +static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b) +{ + if (kind == BK_EV_CLICK) { + g_clicks++; + } +} + +static BKContext *context(BKNode *root) +{ + BKContext *ctx = BK_context_new(root); + const BKHost host = {NULL, host_noop, host_cursor, host_warp, + host_clip_get, host_clip_set, host_schedule, host_emit}; + BK_context_set_host(ctx, &host); + BK_render(ctx, g_raster, W, H, 1); + return ctx; +} + +static void centre(BKNode *n, float *r_x, float *r_y) +{ + int r[4]; + BK_node_rect(n, r); + *r_x = r[0] + r[2] * 0.5f; + *r_y = r[1] + r[3] * 0.5f; +} + +/* -- a custom node that records what it gets -- */ + +typedef struct Log { + int press, release, motion, wheel, magnify, rotate, touch_down, touch_move, touch_up, + touch_cancel; + int touch_mods; /* BK_FROM_TOUCH seen on pointer events */ + float wheel_y, magnify_sum, rotate_sum; + int last_id; +} Log; + +static int log_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + Log *l = (Log *)data; + switch (e->type) { + case BK_CUSTOM_PRESS: + l->press++; + l->touch_mods |= e->mods & BK_FROM_TOUCH; + break; + case BK_CUSTOM_RELEASE: + l->release++; + break; + case BK_CUSTOM_MOTION: + l->motion++; + break; + case BK_CUSTOM_WHEEL: + l->wheel++; + l->wheel_y += e->wheel_y; + break; + case BK_CUSTOM_MAGNIFY: + l->magnify++; + l->magnify_sum += e->magnify; + break; + case BK_CUSTOM_ROTATE: + l->rotate++; + l->rotate_sum += e->rotate; + break; + case BK_CUSTOM_TOUCH: + l->last_id = e->touch_id; + l->touch_down += e->touch_phase == BK_TOUCH_DOWN; + l->touch_move += e->touch_phase == BK_TOUCH_MOVE; + l->touch_up += e->touch_phase == BK_TOUCH_UP; + l->touch_cancel += e->touch_phase == BK_TOUCH_CANCEL; + break; + } + return 1; +} + +static BKNode *custom_node(Log *l) +{ + BKNode *n = BK_node_new("custom"); + BKCustomClass cls; + memset(&cls, 0, sizeof(cls)); + cls.event = log_event; + cls.natural_w = W; + cls.natural_h = 200; + BK_custom_set(n, &cls, l); + return n; +} + +/* -- one finger: the pointer -- */ + +static void test_tap_and_cancel(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *button = BK_node_new("button"); + BK_set_str(button, "label", "Tap"); + BK_node_add(col, button, -1); + BKContext *ctx = context(col); + float x, y; + centre(button, &x, &y); + + g_clicks = 0; + CHECK(BK_touch(ctx, 7, BK_TOUCH_DOWN, x, y, 0)); + CHECK(BK_touch(ctx, 7, BK_TOUCH_UP, x, y, 0)); + CHECK(g_clicks == 1); + CHECK(BK_hover(ctx) == NULL); /* a lifted finger leaves no hover behind */ + + /* the platform took the contact back: no click */ + g_clicks = 0; + BK_touch(ctx, 8, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 8, BK_TOUCH_CANCEL, x, y, 0); + CHECK(g_clicks == 0); + + /* a second finger turns the press into a gesture: no click, then or after */ + g_clicks = 0; + BK_touch(ctx, 1, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, x + 40, y, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, x + 40, y, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, x + 1, y, 0); /* still latched: not the pointer */ + BK_touch(ctx, 1, BK_TOUCH_UP, x + 1, y, 0); + CHECK(g_clicks == 0); + + /* after every finger lifted, a tap is a tap again */ + BK_touch(ctx, 3, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 3, BK_TOUCH_UP, x, y, 0); + CHECK(g_clicks == 1); + + /* moves and ups of unknown contacts are ignored */ + CHECK(BK_touch(ctx, 99, BK_TOUCH_MOVE, x, y, 0) == 0); + CHECK(BK_touch(ctx, 99, BK_TOUCH_UP, x, y, 0) == 0); + BK_context_free(ctx); + BK_node_free(col); +} + +static void test_drag_cancelled_by_second_finger(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *num = BK_node_new("number"); + BK_set_num(num, "value", 5.0); + BK_node_add(col, num, -1); + BKContext *ctx = context(col); + float x, y; + centre(num, &x, &y); + + BK_touch(ctx, 1, BK_TOUCH_DOWN, x, y, 0); + for (int i = 1; i <= 10; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, x + i * 8, y, 0); + } + CHECK(BK_get_num(num, "value") != 5.0); /* one finger drags the value */ + BK_touch(ctx, 2, BK_TOUCH_DOWN, x, y + 30, 0); + CHECK(BK_get_num(num, "value") == 5.0); /* the second finger cancels it, as Escape */ + BK_touch(ctx, 1, BK_TOUCH_UP, x + 80, y, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, x, y + 30, 0); + CHECK(BK_get_num(num, "value") == 5.0); + CHECK(BK_focus(ctx) == NULL); /* and does not start editing the text */ + BK_context_free(ctx); + BK_node_free(col); +} + +/* a tap opens a menu, which stays open with no finger down; a tap on a row picks it */ +static void test_menu(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *dd = BK_node_new("dropdown"); + const char *items[] = {"One", "Two", "Three"}; + BK_set_strs(dd, "items", items, 3); + BK_node_add(col, dd, -1); + BKContext *ctx = context(col); + float x, y; + centre(dd, &x, &y); + BK_touch(ctx, 1, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, x, y, 0); + BK_render(ctx, g_raster, W, H, 0); + CHECK(BK_popup_count(ctx) == 1); + if (BK_popup_count(ctx) == 1) { + BKNode *menu = BK_popup(ctx, 0); + const int rows = BK_menu_row_count(menu); + int r[4]; + BK_menu_row_rect(menu, rows - 1, r); + const float mx = r[0] + r[2] * 0.5f, my = r[1] + r[3] * 0.5f; + BK_touch(ctx, 2, BK_TOUCH_DOWN, mx, my, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, mx, my, 0); + BK_render(ctx, g_raster, W, H, 0); + CHECK(BK_popup_count(ctx) == 0); + CHECK(BK_get_num(dd, "value") != 0.0); + } + BK_context_free(ctx); + BK_node_free(col); +} + +/* -- two fingers: gestures -- */ + +static void test_pan_scrolls_region(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *first = NULL; + for (int i = 0; i < 60; i++) { + BKNode *b = BK_node_new("button"); + BK_set_str(b, "label", "Row"); + BK_node_add(col, b, -1); + first = first ? first : b; + } + BKContext *ctx = context(col); + int r0[4], r1[4]; + BK_node_rect(first, r0); + g_clicks = 0; + /* two fingers move up together: the content follows them */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 180, 200, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 220, 200, 0); + for (int i = 1; i <= 10; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 180, 200 - i * 12, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 220, 200 - i * 12, 0); + } + BK_touch(ctx, 1, BK_TOUCH_UP, 180, 80, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 220, 80, 0); + BK_render(ctx, g_raster, W, H, 1); + BK_node_rect(first, r1); + CHECK(r1[1] < r0[1]); + CHECK(r0[1] - r1[1] > 60); /* about the 120 px the fingers moved */ + CHECK(g_clicks == 0); + BK_context_free(ctx); + BK_node_free(col); +} + +static void test_node_editor(void) +{ + BKNode *editor = BK_node_new("nodeeditor"); + BKContext *ctx = context(editor); + const double zoom0 = BK_get_num(editor, "zoom"); + + /* spread: zoom in about the fingers */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 150, 150, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 250, 150, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, 125, 150, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 275, 150, 0); + CHECK(BK_get_num(editor, "zoom") > zoom0 * 1.3); + const double zoom1 = BK_get_num(editor, "zoom"); + const double panx1 = BK_get_num(editor, "panx"); + /* together to the right: the view pans with them, 40 px (not a wheel zoom) */ + BK_touch(ctx, 1, BK_TOUCH_MOVE, 165, 150, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 315, 150, 0); + CHECK(fabs(BK_get_num(editor, "panx") - (panx1 + 40.0)) < 1e-3); + CHECK(fabs(BK_get_num(editor, "zoom") - zoom1) < 1e-6); + BK_touch(ctx, 1, BK_TOUCH_UP, 165, 150, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 315, 150, 0); + + /* a trackpad pinch (BK_magnify) zooms the same way */ + const double zoom2 = BK_get_num(editor, "zoom"); + CHECK(BK_magnify(ctx, 200, 150, -0.2f, 0)); + CHECK(BK_get_num(editor, "zoom") < zoom2); + CHECK(BK_rotate(ctx, 200, 150, 10.0f, 0) == 0); /* the editor does not rotate */ + CHECK(BK_magnify(ctx, 200, 150, 0.0f, 0) == 0); + BK_context_free(ctx); + BK_node_free(editor); +} + +/* -- custom nodes -- */ + +static void test_custom_default(void) +{ + Log l; + memset(&l, 0, sizeof(l)); + BKNode *col = BK_node_new("column"); + BKNode *c = custom_node(&l); + BK_node_add(col, c, -1); + BKContext *ctx = context(col); + float x, y; + centre(c, &x, &y); + + BK_touch(ctx, 1, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, x + 5, y, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, x + 5, y, 0); + CHECK(l.press == 1 && l.release == 1 && l.motion >= 1); + CHECK(l.touch_mods == BK_FROM_TOUCH); + CHECK(l.touch_down == 0); + + /* two fingers: the first press is released, then pan, magnify and rotate arrive */ + memset(&l, 0, sizeof(l)); + BK_touch(ctx, 1, BK_TOUCH_DOWN, x - 40, y, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, x + 40, y, 0); + CHECK(l.press == 1 && l.release == 1); + BK_touch(ctx, 1, BK_TOUCH_MOVE, x - 40, y + 20, 0); /* down: wheel up */ + BK_touch(ctx, 2, BK_TOUCH_MOVE, x + 40, y + 20, 0); + CHECK(l.wheel >= 1 && l.wheel_y > 0.0f); + BK_touch(ctx, 1, BK_TOUCH_MOVE, x - 80, y + 20, 0); /* spread */ + BK_touch(ctx, 2, BK_TOUCH_MOVE, x + 80, y + 20, 0); + CHECK(l.magnify >= 1 && l.magnify_sum > 0.5f); + /* turn counter-clockwise on screen: the right finger goes up, the left one down */ + const float a = 20.0f * (float)M_PI / 180.0f; + BK_touch(ctx, 1, BK_TOUCH_MOVE, x - 80 * cosf(a), y + 20 + 80 * sinf(a), 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, x + 80 * cosf(a), y + 20 - 80 * sinf(a), 0); + CHECK(l.rotate >= 1 && fabsf(l.rotate_sum - 20.0f) < 0.5f); + BK_touch(ctx, 1, BK_TOUCH_UP, 0, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 0, 0, 0); + CHECK(l.press == 1); /* no second press while the gesture ran */ + + /* trackpad gestures reach it too */ + memset(&l, 0, sizeof(l)); + CHECK(BK_magnify(ctx, (int)x, (int)y, 0.25f, 0) && l.magnify == 1 && l.magnify_sum == 0.25f); + CHECK(BK_rotate(ctx, (int)x, (int)y, -15.0f, 0) && l.rotate == 1 && l.rotate_sum == -15.0f); + BK_context_free(ctx); + BK_node_free(col); +} + +static void test_custom_raw(void) +{ + Log l; + memset(&l, 0, sizeof(l)); + BKNode *col = BK_node_new("column"); + BKNode *c = custom_node(&l); + BK_custom_set_touch(c, 1); + BKNode *button = BK_node_new("button"); + BK_set_str(button, "label", "Below"); + BK_node_add(col, c, -1); + BK_node_add(col, button, -1); + BKContext *ctx = context(col); + float x, y, bx, by; + centre(c, &x, &y); + centre(button, &bx, &by); + + /* three fingers on the node: each one arrives as it is, no pointer, no gesture */ + for (int id = 10; id < 13; id++) { + BK_touch(ctx, id, BK_TOUCH_DOWN, x + (id - 10) * 30, y, 0); + } + CHECK(l.touch_down == 3 && l.press == 0 && l.last_id == 12); + CHECK(BK_custom_has_focus(c)); /* the first finger focused it, as a click does */ + BK_touch(ctx, 11, BK_TOUCH_MOVE, x + 35, y + 10, 0); + CHECK(l.touch_move == 1 && l.last_id == 11 && l.magnify == 0 && l.wheel == 0); + + /* a finger that lands outside is the pointer as usual, even meanwhile */ + g_clicks = 0; + BK_touch(ctx, 20, BK_TOUCH_DOWN, bx, by, 0); + BK_touch(ctx, 20, BK_TOUCH_UP, bx, by, 0); + CHECK(g_clicks == 1); + + BK_touch(ctx, 10, BK_TOUCH_UP, x, y, 0); + BK_touch(ctx, 12, BK_TOUCH_CANCEL, x, y, 0); + CHECK(l.touch_up == 1 && l.touch_cancel == 1); + + /* the node goes away while a finger is on it: the rest of that contact is dropped */ + BK_node_remove(col, c); + BK_node_free(c); + CHECK(BK_touch(ctx, 11, BK_TOUCH_MOVE, x, y, 0) == 0); + CHECK(BK_touch(ctx, 11, BK_TOUCH_UP, x, y, 0) == 0); + BK_context_free(ctx); + BK_node_free(col); +} + +static void test_capacity(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *button = BK_node_new("button"); + BK_node_add(col, button, -1); + BKContext *ctx = context(col); + for (int id = 0; id < 20; id++) { /* more fingers than followed: no harm */ + BK_touch(ctx, id, BK_TOUCH_DOWN, 10.0f + id, 10.0f, 0); + } + for (int id = 0; id < 20; id++) { + BK_touch(ctx, id, BK_TOUCH_MOVE, 30.0f + id, 40.0f, 0); + BK_touch(ctx, id, BK_TOUCH_UP, 30.0f + id, 40.0f, 0); + } + /* a down for a contact still down (its up was lost) ends the old one first */ + float x, y; + centre(button, &x, &y); + g_clicks = 0; + BK_touch(ctx, 5, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 5, BK_TOUCH_DOWN, x, y, 0); + BK_touch(ctx, 5, BK_TOUCH_UP, x, y, 0); + CHECK(g_clicks == 1); + BK_context_free(ctx); + BK_node_free(col); +} + +int main(void) +{ + g_raster = BUI_raster_create(W, H); + test_tap_and_cancel(); + test_drag_cancelled_by_second_finger(); + test_menu(); + test_pan_scrolls_region(); + test_node_editor(); + test_custom_default(); + test_custom_raw(); + test_capacity(); + BUI_raster_free(g_raster); + printf(g_fail ? "touch_test: FAILED\n" : "touch_test: ok\n"); + return g_fail; +} diff --git a/website/src/content/docs/c/c-api.mdx b/website/src/content/docs/c/c-api.mdx index 3e993840..6b9f12b5 100644 --- a/website/src/content/docs/c/c-api.mdx +++ b/website/src/content/docs/c/c-api.mdx @@ -186,7 +186,7 @@ The host is a struct of optional callbacks: A `BKWindow` fills in all of them except `emit`, which you keep. If you host the kit yourself, the [embedding page](../embedding/) shows how. -**Input goes in** through `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_scroll` (precise deltas), `BK_key`, `BK_key_release`, `BK_button` and `BK_context_menu`. Each returns non-zero when something changed. +**Input goes in** through `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_scroll` (precise deltas), `BK_key`, `BK_key_release`, `BK_button` and `BK_context_menu`; touch screens through `BK_touch` and trackpad pinches through `BK_magnify` and `BK_rotate` ([Touch and gestures](/docs/concepts/touch)). Each returns non-zero when something changed. **Input methods (IME)** follow Blender's model (`GHOST_ImeWin32`, `wmIMEData`). The IME is off until a text field or text area is being edited, so shortcuts keep working with a CJK keyboard. A window host forwards the platform's composition events with `BK_ime_event(ctx, BK_IME_COMPOSITION_START | BK_IME_COMPOSITION | BK_IME_COMPOSITION_END, &event)`, where `BKImeEvent` carries the committed `result`, the `composite` text still being composed, the IME `cursor_pos` and the `sel_start`/`sel_end` clause being converted. After each render it calls `BK_ime_state(ctx, &state)`, which returns non-zero only when the IME must be started, ended or moved (`state.enabled`, `state.restart`, `state.x`, `state.y` is where the candidate window goes). The kit draws the composition underlined at the caret and inserts the result like typed text. The Windows window host does all of this; an embedder with its own window can use the same two calls. Number fields and password fields take no IME. @@ -247,6 +247,7 @@ BK_custom_set(node, &cls, my_data); - **`frame`** runs at the start of `BK_render` when you asked with `BK_custom_request_frame(node, ms)`: the place for immediate-mode UIs to build their frame. - **`draw`** gets the raster and the node's rect. It may be called several times per render, once per damaged region, so it must draw the current state without changing it. - **`BK_custom_set_cursor(node, cursor)`** sets the pointer shape over the node. +- **Touch** arrives as the pointer (with `BK_FROM_TOUCH` in `mods`) and two-finger `BK_CUSTOM_WHEEL`, `BK_CUSTOM_MAGNIFY` and `BK_CUSTOM_ROTATE` events. After **`BK_custom_set_touch(node, 1)`** every contact that begins over the node arrives as `BK_CUSTOM_TOUCH` (`touch_id`, `touch_phase`) instead ([Touch and gestures](/docs/concepts/touch#custom-nodes)). ## Everything else diff --git a/website/src/content/docs/concepts/touch.mdx b/website/src/content/docs/concepts/touch.mdx new file mode 100644 index 00000000..1c72e386 --- /dev/null +++ b/website/src/content/docs/concepts/touch.mdx @@ -0,0 +1,101 @@ +--- +title: Touch and gestures +description: One finger is the pointer, two fingers pan, zoom and turn, trackpad pinches zoom too. Touch screens on Windows, X11 and Wayland; trackpad gestures on Wayland and macOS; raw contacts for custom nodes. +section: Concepts +order: 55 +languages: ["python", "rust", "javascript", "c"] +sources: ["docs/touch.md", "kit/include/BUI_kit.h", "kit/intern/kit_touch.c", "kit/intern/kit_core.c", "kit/intern/kit_custom.c", "kit/intern/kit_nodes.c", "kit/intern/kit_window_win32.c", "kit/intern/kit_window_x11.c", "kit/intern/kit_window_wayland.c", "kit/intern/kit_window_cocoa.m", "bindings/imgui/imgui_impl_bui.cpp", "tests/touch_test.c"] +--- + +BUI's widgets work with fingers. On a touch screen, one finger is the pointer: tap a button, +drag a number field or a slider, open a menu and tap a row. Two fingers scroll, zoom and turn +what is under them. A trackpad pinch zooms the same way. The native window hosts do this for +you; if you host the kit yourself, three calls feed it. + +## What a finger does + +| Fingers | What happens | +|---|---| +| **One** | It is the pointer: it moves there, presses, drags and releases, as the left mouse button does. When it lifts, the pointer leaves, so no hover highlight or tooltip stays behind. Pointer events made this way carry `BK_FROM_TOUCH` in their mods. | +| **A second one** | Whatever the first finger was doing is cancelled, as Esc cancels a drag in Blender: a dragged value goes back, a pressed button is not clicked, a number field does not start editing. The two fingers are now a gesture. | +| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. | +| **Two, spreading or pinching** | Magnify about their centre (`BK_magnify`). The node editor zooms. | +| **Two, turning** | Rotate about their centre (`BK_rotate`). | +| **After a gesture** | No finger becomes the pointer again until every finger has lifted, so lifting one finger of a pinch never clicks what is under the other. | +| **More than two** | Followed, not used, up to ten contacts. | + +Blender has no touch-screen input, so there is no source to follow for touch itself. One finger +does what X11, Wayland compositors and Windows do for windows that don't know about touch. Two +fingers send the events Blender gets from a trackpad: GHOST's `Scroll`, `Magnify` and `Rotate` +trackpad events, which Blender reads as `MOUSEPAN`, `MOUSEZOOM` and `MOUSEROTATE`. + +## Window hosts + +| Host | Touch screen | Trackpad pinch / rotate | +|---|---|---| +| **Windows** | `WM_TOUCH` (the window is registered with `RegisterTouchWindow`). The mouse messages Windows makes from touches are ignored, and press-and-hold no longer turns into a right click. | Precision touchpads send pinches as Ctrl + wheel, as before. | +| **X11** | XInput 2.2 touch events (`XI_TouchBegin` / `Update` / `End`). libXi is loaded at run time like libX11; without it, or with an older server, touches stay emulated mouse input as before. | Not sent by X11 touchpad drivers. | +| **Wayland** | `wl_touch`, including `cancel` when the compositor takes the touches for a system gesture. | `zwp_pointer_gestures_v1` pinch: scale and rotation, as GHOST_SystemWayland reads them. | +| **macOS** | No touch screens. | `magnifyWithEvent:` and `rotateWithEvent:`, as GHOST_SystemCocoa. | + +## Hosting the kit yourself + +```c +/* every contact of a touch screen, in window pixels; id is the platform's */ +BK_touch(ctx, id, BK_TOUCH_DOWN, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_MOVE, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_UP, x, y, mods); +BK_touch(ctx, id, BK_TOUCH_CANCEL, x, y, mods); /* the platform took it back */ + +/* trackpad gestures, at the pointer */ +BK_magnify(ctx, x, y, 0.1f, mods); /* 10% larger since the last event */ +BK_rotate(ctx, x, y, 5.0f, mods); /* degrees, > 0 counter-clockwise */ +``` + +Each call returns non-zero when something changed. A `BK_TOUCH_DOWN` for an id that is still +down ends the old contact first (its up was lost). Moves and ups for unknown ids are ignored. +Don't also send the mouse events your platform makes from the same touches. + +The same calls are on every binding: `ctx.touch(id, phase, x, y, mods)`, +`ctx.magnify(x, y, delta, mods)` and `ctx.rotate(x, y, degrees, mods)` in Python (phase 0 down, +1 move, 2 up, 3 cancel); `ctx:touch(...)`, `ctx:magnify(...)` and `ctx:rotate(...)` with +`bui.TOUCH_DOWN` ... `bui.TOUCH_CANCEL` in Lua; `context.touch(...)`, `magnify` and `rotate` +with `BK_TOUCH_*` in D (and `node.setTouch(true)` for custom nodes); `BK_touch`, `BK_magnify` +and `BK_rotate` in `blenderui-sys`. + +## Custom nodes + +By default a `custom` node gets touch the way it gets the mouse: `BK_CUSTOM_PRESS`, `MOTION` and +`RELEASE` from the first finger (with `BK_FROM_TOUCH` in `mods`), then, for two fingers, +`BK_CUSTOM_WHEEL` (the pan, in wheel notches like `BK_scroll`'s), `BK_CUSTOM_MAGNIFY` +(`e->magnify`) and `BK_CUSTOM_ROTATE` (`e->rotate`). Trackpad gestures arrive as the same +`MAGNIFY` and `ROTATE` events. The Dear ImGui backend reports touch as +`ImGuiMouseSource_TouchScreen`. + +A node that does its own multi-touch asks for every contact instead: + +```c +BK_custom_set_touch(node, 1); + +static int my_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + if (e->type == BK_CUSTOM_TOUCH) { + /* e->touch_id, e->touch_phase (BK_TOUCH_DOWN / MOVE / UP / CANCEL), e->x, e->y */ + return 1; + } + return 0; +} +``` + +Every contact that begins over the node then arrives as `BK_CUSTOM_TOUCH`, with no pointer +emulation and no gestures. The first finger gives the node keyboard focus, as a click does. +Fingers that begin elsewhere still work the rest of the UI. While a menu or popup is open, +touches take the normal path, so a tap outside closes the menu. + +## Limits + +- A continuous drag (a number field) still moves the system mouse pointer back where the drag + began when the finger lifts, as it does for the mouse. +- One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). +- Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between + the two fingers' events. Nothing waits for a platform's frame grouping yet. From e38a818c081d9263afa2a1dfba5b7df22630731e Mon Sep 17 00:00:00 2001 From: BUI contributor Date: Fri, 13 Nov 2026 10:08:21 +0000 Subject: [PATCH 2/4] touch: address CodeRabbit review of #42 - kit_nodes.c: a cancelled link drag puts back the link it picked up from an input (Blender's node_link_cancel leaves the graph as it was). A second finger, and Escape during a mouse link drag, no longer drop the link. - kit_touch.c: a second finger cancels the first one's press even when it has not moved yet; before, the release still ran and an unmoved box-select press in the node editor deselected every node. - kit_core.c: continuous() takes the event's mods and is false for BK_FROM_TOUCH. A finger's drag no longer wraps at the window edge: the host's warp moves the mouse, not the finger, so every move at the edge counted the wrap again and the value ran away. Touch drags also no longer warp the mouse pointer back on release. - kit_window_win32.c: WM_TOUCH reads every record of the batch (16 on the stack, the heap beyond) and looks the window up again before each one, so a callback that closes or frees the window ends the loop instead of reading freed memory; reopen() (transparency / layering) registers the new HWND for touch. - c-api.mdx: relative links to the touch page, as the rest of the page. - tests/touch_test.c: link pick-up cancelled before and after moving, a pinch on empty canvas keeps the selection, a drag resting at the window edge keeps its value and never warps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PJcXdyFRKBApKEvWpKoMpY --- docs/touch.md | 5 +- kit/intern/kit_core.c | 11 +- kit/intern/kit_nodes.c | 11 ++ kit/intern/kit_touch.c | 6 +- kit/intern/kit_window_win32.c | 59 +++++++---- tests/touch_test.c | 105 +++++++++++++++++++- website/src/content/docs/c/c-api.mdx | 4 +- website/src/content/docs/concepts/touch.mdx | 5 +- 8 files changed, 171 insertions(+), 35 deletions(-) diff --git a/docs/touch.md b/docs/touch.md index 05b4537a..8c93f41b 100644 --- a/docs/touch.md +++ b/docs/touch.md @@ -87,8 +87,9 @@ touches take the normal path, so a tap outside closes the menu. ## Limits -- A continuous drag (a number field) still moves the system mouse pointer back where the drag - began when the finger lifts, as it does for the mouse. +- A finger's drag never wraps at the window edge and never moves the system mouse pointer (the + hidden-pointer drag of number fields is for the mouse); a number field dragged by touch stops + changing at the edge. - One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). - Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between the two fingers' events. Nothing waits for a platform's frame grouping yet. diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index 33a2a35e..57c630b1 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -2422,10 +2422,13 @@ void bk_update_cursor(BKContext *ctx) update_cursor(ctx); } -static bool continuous(BKContext *ctx) +/* A drag with the hidden pointer that wraps at the window edge and comes back where it began + * (USE_CONT_MOUSE_CORRECT). Not for a finger: warping moves the mouse, not the finger, so its + * next position would count the wrap again. */ +static bool continuous(BKContext *ctx, int mods) { return ctx->host.warp && ctx->grab && ctx->dragging && !BK_HTML(ctx->grab) && - ctx->grab->cls->drag_cursor == BK_CURSOR_NONE; + ctx->grab->cls->drag_cursor == BK_CURSOR_NONE && !(mods & BK_FROM_TOUCH); } static void wrap_pointer(BKContext *ctx, int x, int y) @@ -2517,7 +2520,7 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods) set_hover(ctx, under); changed = 1; } - if (continuous(ctx)) { + if (continuous(ctx, mods)) { wrap_pointer(ctx, x, y); } return changed; @@ -2647,7 +2650,7 @@ static int in_BK_release(BKContext *ctx, int x, int y, int mods) } return 1; } - const bool was_continuous = continuous(ctx); + const bool was_continuous = continuous(ctx, mods); const int vx = x + ctx->off_x, vy = y + ctx->off_y; BKNode *grab = ctx->grab; ctx->dt_active = 0; diff --git a/kit/intern/kit_nodes.c b/kit/intern/kit_nodes.c index 1809292a..f5d6cb80 100644 --- a/kit/intern/kit_nodes.c +++ b/kit/intern/kit_nodes.c @@ -57,6 +57,8 @@ typedef struct NodeEdit { BKNode *hit; /* node pressed */ int link_node, link_sock; /* the fixed end of a dragged link */ bool link_from_output; + bool link_picked; /* the drag took a link off an input: a cancel puts it back */ + int picked_from, picked_out, picked_to, picked_in; int value_node, value_sock; double value_start; bool shift; @@ -912,11 +914,17 @@ static int editor_press(BKNode *e, BKEvent *ev) d->link_node = old.from; d->link_sock = old.out; d->link_from_output = true; + d->link_picked = true; + d->picked_from = old.from; + d->picked_out = old.out; + d->picked_to = old.to; + d->picked_in = old.in; } else { d->link_node = ni; d->link_sock = k; d->link_from_output = !input; + d->link_picked = false; } d->mode = M_LINK; bk_invalidate(e); @@ -1115,6 +1123,9 @@ static void editor_cancel(BKNode *e) else if (d->mode == M_VALUE) { set_input_value(e->kids[d->value_node], d->value_sock, d->value_start); } + else if (d->mode == M_LINK && d->link_picked) { /* node_link_cancel: the graph is as it was */ + add_link(e, d->picked_from, d->picked_out, d->picked_to, d->picked_in); + } d->mode = M_NONE; bk_invalidate(e); } diff --git a/kit/intern/kit_touch.c b/kit/intern/kit_touch.c index 7a0a9c15..b4ac25c3 100644 --- a/kit/intern/kit_touch.c +++ b/kit/intern/kit_touch.c @@ -93,7 +93,9 @@ static int deliver_raw(BKContext *ctx, const BKTouchPoint *p, int phase, int mod } /* The pointer's finger no longer is one: undo what it did, as Escape does to a drag, and end the - * press away from every widget (buttons are not clicked, number fields do not start editing). */ + * press away from every widget (buttons are not clicked, number fields do not start editing). + * Unlike Escape this also cancels a press that has not moved yet: its release would still act + * (an unmoved box-select press in the node editor deselects everything). */ static void abort_pointer(BKContext *ctx, int mods) { BKTouch *t = &ctx->touch; @@ -101,7 +103,7 @@ static void abort_pointer(BKContext *ctx, int mods) return; } t->pointer = -1; - if (ctx->grab && ctx->dragging && ctx->grab->cls->cancel) { + if (ctx->grab && ctx->grab->cls->cancel) { ctx->grab->cls->cancel(ctx->grab); ctx->has_ungrab = false; } diff --git a/kit/intern/kit_window_win32.c b/kit/intern/kit_window_win32.c index ba27c37c..7aaaa0d4 100644 --- a/kit/intern/kit_window_win32.c +++ b/kit/intern/kit_window_win32.c @@ -606,30 +606,44 @@ static int mouse_from_touch(void) # define BK_TABLET_DISABLE_PRESSANDHOLD 0x00000001 # define BK_TABLET_DISABLE_FLICKS 0x00010000 -static void handle_touch(BKWindow *win, HWND hwnd, WPARAM wp, LPARAM lp) -{ - TOUCHINPUT in[16]; - const UINT n = BK_MIN(LOWORD(wp), (UINT)(sizeof(in) / sizeof(in[0]))); - if (!GetTouchInputInfo((HTOUCHINPUT)lp, n, in, sizeof(TOUCHINPUT))) { +/* A WM_TOUCH batch: one record per contact. Each BK_touch can run host callbacks that close or + * free the window, so the window is looked up again before every record: BK_window_free clears + * GWLP_USERDATA first, a closed window's handle is no longer a window, and reopen() leaves the + * old handle without one. */ +static void handle_touch(HWND hwnd, WPARAM wp, LPARAM lp) +{ + TOUCHINPUT stack[16]; + const UINT n = LOWORD(wp); + TOUCHINPUT *in = n <= 16 ? stack : (TOUCHINPUT *)malloc(sizeof(TOUCHINPUT) * n); + if (!in) { return; } - POINT origin = {0, 0}; - ClientToScreen(hwnd, &origin); - for (UINT i = 0; i < n && win->hwnd; i++) { - const DWORD f = in[i].dwFlags; - const int phase = (f & TOUCHEVENTF_DOWN) ? BK_TOUCH_DOWN : - (f & TOUCHEVENTF_UP) ? BK_TOUCH_UP : - (f & TOUCHEVENTF_MOVE) ? BK_TOUCH_MOVE : - -1; - if (phase < 0) { - continue; - } - if (phase == BK_TOUCH_DOWN) { - SetFocus(hwnd); /* as WM_LBUTTONDOWN */ + if (GetTouchInputInfo((HTOUCHINPUT)lp, n, in, sizeof(TOUCHINPUT))) { + POINT origin = {0, 0}; + ClientToScreen(hwnd, &origin); + for (UINT i = 0; i < n; i++) { + BKWindow *win = IsWindow(hwnd) ? (BKWindow *)GetWindowLongPtrW(hwnd, GWLP_USERDATA) : NULL; + if (!win) { + break; + } + const DWORD f = in[i].dwFlags; + const int phase = (f & TOUCHEVENTF_DOWN) ? BK_TOUCH_DOWN : + (f & TOUCHEVENTF_UP) ? BK_TOUCH_UP : + (f & TOUCHEVENTF_MOVE) ? BK_TOUCH_MOVE : + -1; + if (phase < 0) { + continue; + } + if (phase == BK_TOUCH_DOWN) { + SetFocus(hwnd); /* as WM_LBUTTONDOWN */ + } + /* hundredths of a physical screen pixel */ + BK_touch(win->ctx, (int)in[i].dwID, phase, in[i].x / 100.0f - origin.x, + in[i].y / 100.0f - origin.y, mods_now(0, 0)); } - /* hundredths of a physical screen pixel */ - BK_touch(win->ctx, (int)in[i].dwID, phase, in[i].x / 100.0f - origin.x, - in[i].y / 100.0f - origin.y, mods_now(0, 0)); + } + if (in != stack) { + free(in); } } @@ -815,7 +829,7 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) return 0; } case WM_TOUCH: - handle_touch(win, hwnd, wp, lp); + handle_touch(hwnd, wp, lp); CloseTouchInputHandle((HTOUCHINPUT)lp); return 0; case WM_TABLET_QUERYSYSTEMGESTURESTATUS: @@ -1211,6 +1225,7 @@ static int reopen(BKWindow *win, LONG_PTR ex) } SetWindowLongPtrW(old, GWLP_USERDATA, 0); /* the old window's messages end here */ SetWindowLongPtrW(h, GWLP_USERDATA, (LONG_PTR)win); + RegisterTouchWindow(h, 0); /* as BK_window_new: touches keep coming as WM_TOUCH */ win->hwnd = h; timers_rearm(win); DestroyWindow(old); diff --git a/tests/touch_test.c b/tests/touch_test.c index 2b94f5a6..41c996d3 100644 --- a/tests/touch_test.c +++ b/tests/touch_test.c @@ -29,10 +29,14 @@ enum { W = 400, H = 300 }; static BuiRaster *g_raster; static int g_clicks; +static int g_warps; static void host_noop(void *data) {} static void host_cursor(void *data, int c) {} -static void host_warp(void *data, int x, int y) {} +static void host_warp(void *data, int x, int y) +{ + g_warps++; +} static char *host_clip_get(void *data) { return NULL; @@ -290,6 +294,103 @@ static void test_node_editor(void) BK_node_free(editor); } +/* Two nodes, A's output linked into B's input; the view at zoom 1, pan (50, 50). */ +static BKNode *graph(BKNode **r_b) +{ + BKNode *editor = BK_node_new("nodeeditor"); + BKNode *a = BK_node_new("graphnode"), *b = BK_node_new("graphnode"); + const char *a_items[] = {"o|Value|float"}; + const char *b_items[] = {"o|Result|float", "i|A|float|0.5"}; + BK_set_strs(a, "items", a_items, 1); + BK_set_strs(b, "items", b_items, 2); + BK_set_num(b, "nx", 300.0); + BK_node_add(editor, a, -1); + BK_node_add(editor, b, -1); + const char *links[] = {"0 0 1 0"}; + BK_set_strs(editor, "items", links, 1); + *r_b = b; + return editor; +} + +static void place_view(BKContext *ctx, BKNode *editor) +{ + BK_set_num(editor, "zoom", 1.0); + BK_set_num(editor, "panx", 50.0); + BK_set_num(editor, "pany", 50.0); + BK_render(ctx, g_raster, W, H, 1); +} + +/* A second finger keeps what the first one's press began from changing the graph. */ +static void test_node_editor_cancel(void) +{ + BKNode *b; + BKNode *editor = graph(&b); + BKContext *ctx = context(editor); + place_view(ctx, editor); + int r[4]; + BK_node_rect(editor, r); + /* B's input socket: its left edge, below the header and the output row */ + const float sx = r[0] + 50 + 300, sy = r[1] + 50 + (20 + 5 + 22 + 10); + + /* pressing a linked input picks its link up; a pinch must put it back */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, sx, sy, 0); + CHECK(BK_strs_count(editor, "items") == 0); /* picked up */ + BK_touch(ctx, 2, BK_TOUCH_DOWN, sx + 60, sy + 60, 0); + CHECK(BK_strs_count(editor, "items") == 1); + BK_touch(ctx, 1, BK_TOUCH_UP, sx, sy, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, sx + 60, sy + 60, 0); + CHECK(BK_strs_count(editor, "items") == 1); + /* the same once the link was dragged away */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, sx, sy, 0); + for (int i = 1; i <= 5; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, sx - i * 10, sy + i * 6, 0); + } + BK_touch(ctx, 2, BK_TOUCH_DOWN, sx + 60, sy + 60, 0); + CHECK(BK_strs_count(editor, "items") == 1); + BK_touch(ctx, 1, BK_TOUCH_UP, sx, sy, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, sx + 60, sy + 60, 0); + CHECK(BK_strs_count(editor, "items") == 1); + + /* a pinch that begins on empty canvas keeps the selection (an unmoved box press deselects) */ + BK_set_num(b, "selected", 1.0); + BK_touch(ctx, 1, BK_TOUCH_DOWN, r[0] + 60.0f, r[1] + H - 40.0f, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, r[0] + 160.0f, r[1] + H - 40.0f, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, r[0] + 60.0f, r[1] + H - 40.0f, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, r[0] + 160.0f, r[1] + H - 40.0f, 0); + CHECK(BK_get_num(b, "selected") == 1.0); + BK_context_free(ctx); + BK_node_free(editor); +} + +/* A finger at the window edge does not wrap like the hidden mouse pointer does: the host's warp + * moves the mouse, not the finger, so the drag would run away. */ +static void test_drag_at_edge(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *num = BK_node_new("number"); + BK_set_num(num, "value", 0.0); + BK_node_add(col, num, -1); + BKContext *ctx = context(col); + float x, y; + centre(num, &x, &y); + g_warps = 0; + BK_touch(ctx, 1, BK_TOUCH_DOWN, x, y, 0); + for (int i = 1; i <= 20; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, x + (W - 4 - x) * i / 20.0f, y, 0); + } + const double at_edge = BK_get_num(num, "value"); + CHECK(at_edge > 0.0); + for (int i = 0; i < 5; i++) { /* the finger rests there */ + BK_touch(ctx, 1, BK_TOUCH_MOVE, W - 4, y, 0); + } + CHECK(BK_get_num(num, "value") == at_edge); + BK_touch(ctx, 1, BK_TOUCH_UP, W - 4, y, 0); + CHECK(BK_get_num(num, "value") == at_edge); + CHECK(g_warps == 0); /* the mouse pointer was never moved, not even back on release */ + BK_context_free(ctx); + BK_node_free(col); +} + /* -- custom nodes -- */ static void test_custom_default(void) @@ -415,6 +516,8 @@ int main(void) test_menu(); test_pan_scrolls_region(); test_node_editor(); + test_node_editor_cancel(); + test_drag_at_edge(); test_custom_default(); test_custom_raw(); test_capacity(); diff --git a/website/src/content/docs/c/c-api.mdx b/website/src/content/docs/c/c-api.mdx index 6b9f12b5..2b8ae6ca 100644 --- a/website/src/content/docs/c/c-api.mdx +++ b/website/src/content/docs/c/c-api.mdx @@ -186,7 +186,7 @@ The host is a struct of optional callbacks: A `BKWindow` fills in all of them except `emit`, which you keep. If you host the kit yourself, the [embedding page](../embedding/) shows how. -**Input goes in** through `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_scroll` (precise deltas), `BK_key`, `BK_key_release`, `BK_button` and `BK_context_menu`; touch screens through `BK_touch` and trackpad pinches through `BK_magnify` and `BK_rotate` ([Touch and gestures](/docs/concepts/touch)). Each returns non-zero when something changed. +**Input goes in** through `BK_press`, `BK_release`, `BK_motion`, `BK_wheel`, `BK_scroll` (precise deltas), `BK_key`, `BK_key_release`, `BK_button` and `BK_context_menu`; touch screens through `BK_touch` and trackpad pinches through `BK_magnify` and `BK_rotate` ([Touch and gestures](../../concepts/touch/)). Each returns non-zero when something changed. **Input methods (IME)** follow Blender's model (`GHOST_ImeWin32`, `wmIMEData`). The IME is off until a text field or text area is being edited, so shortcuts keep working with a CJK keyboard. A window host forwards the platform's composition events with `BK_ime_event(ctx, BK_IME_COMPOSITION_START | BK_IME_COMPOSITION | BK_IME_COMPOSITION_END, &event)`, where `BKImeEvent` carries the committed `result`, the `composite` text still being composed, the IME `cursor_pos` and the `sel_start`/`sel_end` clause being converted. After each render it calls `BK_ime_state(ctx, &state)`, which returns non-zero only when the IME must be started, ended or moved (`state.enabled`, `state.restart`, `state.x`, `state.y` is where the candidate window goes). The kit draws the composition underlined at the caret and inserts the result like typed text. The Windows window host does all of this; an embedder with its own window can use the same two calls. Number fields and password fields take no IME. @@ -247,7 +247,7 @@ BK_custom_set(node, &cls, my_data); - **`frame`** runs at the start of `BK_render` when you asked with `BK_custom_request_frame(node, ms)`: the place for immediate-mode UIs to build their frame. - **`draw`** gets the raster and the node's rect. It may be called several times per render, once per damaged region, so it must draw the current state without changing it. - **`BK_custom_set_cursor(node, cursor)`** sets the pointer shape over the node. -- **Touch** arrives as the pointer (with `BK_FROM_TOUCH` in `mods`) and two-finger `BK_CUSTOM_WHEEL`, `BK_CUSTOM_MAGNIFY` and `BK_CUSTOM_ROTATE` events. After **`BK_custom_set_touch(node, 1)`** every contact that begins over the node arrives as `BK_CUSTOM_TOUCH` (`touch_id`, `touch_phase`) instead ([Touch and gestures](/docs/concepts/touch#custom-nodes)). +- **Touch** arrives as the pointer (with `BK_FROM_TOUCH` in `mods`) and two-finger `BK_CUSTOM_WHEEL`, `BK_CUSTOM_MAGNIFY` and `BK_CUSTOM_ROTATE` events. After **`BK_custom_set_touch(node, 1)`** every contact that begins over the node arrives as `BK_CUSTOM_TOUCH` (`touch_id`, `touch_phase`) instead ([Touch and gestures](../../concepts/touch/#custom-nodes)). ## Everything else diff --git a/website/src/content/docs/concepts/touch.mdx b/website/src/content/docs/concepts/touch.mdx index 1c72e386..922e0574 100644 --- a/website/src/content/docs/concepts/touch.mdx +++ b/website/src/content/docs/concepts/touch.mdx @@ -94,8 +94,9 @@ touches take the normal path, so a tap outside closes the menu. ## Limits -- A continuous drag (a number field) still moves the system mouse pointer back where the drag - began when the finger lifts, as it does for the mouse. +- A finger's drag never wraps at the window edge and never moves the system mouse pointer (the + hidden-pointer drag of number fields is for the mouse); a number field dragged by touch stops + changing at the edge. - One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). - Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between the two fingers' events. Nothing waits for a platform's frame grouping yet. From 749909ff5d6c3c2cdbc523776cd6c0e11f66ba05 Mon Sep 17 00:00:00 2001 From: BUI contributor Date: Fri, 13 Nov 2026 10:41:09 +0000 Subject: [PATCH 3/4] touch: gestures for any element, on_gesture in blenderui Kit: - New node property "gestures": a node with it takes touch and trackpad gestures over it as BK_EV_GESTURE (ref "mods kind x y", kind BK_GESTURE_PAN / MAGNIFY / ROTATE, now public in BUI_kit.h; a / b the amounts) instead of the kit scrolling for it. Nodes with only "events" (Tk bindings, Qt handlers) are unchanged. - The two fingers' moves are paired into one gesture update (a finger that moves again alone, or lifts, sends what it held), so a pure pan no longer wobbles the zoom and angle between the fingers' events. blenderui: - on_gesture(|e: &GestureEvent, window, cx|) on every element; GestureEvent { kind: GestureKind, position, dx, dy, magnify, degrees, modifiers, touch }; rsx! takes onGesture. The canvas sets "gestures". - A pan no listener stops scrolls the page and reaches on_scroll_wheel, with the new ScrollWheelEvent::touch set (delta * WHEEL_LINE_PX = the fingers' pixels); the virtual list and data table then follow the fingers exactly. - App::simulate_touch (TouchPhase), simulate_magnify, simulate_rotate. Bindings: BK_EV_GESTURE and the kinds in blenderui-sys, D and Lua. Python reads its ref as text (it would have taken it for a PyObject); D passes the text on in NodeEvent. Tests: touch_test.c (the property: pan, pinch, turn, trackpad, and "events" alone still scrolling); blenderui headless test (listeners, stopped and unstopped pans, wheel touch flag, trackpad). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PJcXdyFRKBApKEvWpKoMpY --- CHANGELOG.md | 9 ++ bindings/d/source/bui/kit.d | 5 + bindings/d/source/bui/node.d | 4 +- bindings/lua/src/bui_lua.c | 1 + bindings/python/src/buipy_kit.c | 11 ++- bindings/python/tests/test_nodes.py | 3 +- bindings/rust/blenderui-sys/src/lib.rs | 11 +++ bindings/rust/blenderui/src/element.rs | 6 ++ bindings/rust/blenderui/src/events.rs | 61 ++++++++++++ .../rust/blenderui/src/table/data_table.rs | 9 +- bindings/rust/blenderui/src/vlist/element.rs | 8 +- bindings/rust/blenderui/src/window.rs | 95 ++++++++++++++++-- bindings/rust/blenderui/tests/headless.rs | 79 +++++++++++++++ docs/rust.md | 3 +- docs/touch.md | 42 +++++++- kit/include/BUI_kit.h | 10 +- kit/intern/kit_core.c | 14 ++- kit/intern/kit_intern.h | 6 +- kit/intern/kit_touch.c | 14 ++- tests/touch_test.c | 96 +++++++++++++++++++ website/src/content/docs/concepts/touch.mdx | 42 +++++++- website/src/content/docs/rust/events.mdx | 6 +- 22 files changed, 503 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0990549..a21cd48f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,15 @@ All notable changes to **blenderui** (BUI). The format follows `KitContext.touch` / `magnify` / `rotate`, Lua `ctx:touch` / `magnify` / `rotate` with `bui.TOUCH_*`, D `Context.touch` / `magnify` / `rotate` and `setTouch`, and `blenderui-sys` declarations. `tests/touch_test.c`; [docs/touch.md](docs/touch.md) and the website's Touch and gestures page. +- **Gestures for your own content.** A node with the new `"gestures"` property takes touch and trackpad gestures as + `BK_EV_GESTURE` (ref `"mods kind x y"`, `BK_GESTURE_PAN` / `MAGNIFY` / `ROTATE`, a / b the amounts) instead of the + kit scrolling for it; nodes with only `"events"` are unchanged. The two fingers' moves are paired into one update, + so a pan no longer wobbles the zoom. **Rust:** `on_gesture(|e: &GestureEvent, ..|)` on every element + (`GestureEvent { kind: GestureKind, position, dx, dy, magnify, degrees, modifiers, touch }`, `onGesture` in `rsx!`); + a pan no listener stops scrolls the page and reaches `on_scroll_wheel` with the new `ScrollWheelEvent::touch` + (`delta * WHEEL_LINE_PX` = the fingers' pixels), and the virtual list and data table follow the fingers exactly. + `App::simulate_touch` (`TouchPhase`), `simulate_magnify`, `simulate_rotate`. `BK_EV_GESTURE` and the kinds in + `blenderui-sys`, D and Lua; Python and D read its text. ## [0.5.1] - 2026-11-13 diff --git a/bindings/d/source/bui/kit.d b/bindings/d/source/bui/kit.d index f28c4d51..871b62c8 100644 --- a/bindings/d/source/bui/kit.d +++ b/bindings/d/source/bui/kit.d @@ -78,6 +78,11 @@ enum BK_EV_VIEW = 17; enum BK_EV_SCROLL = 18; enum BK_EV_CONFIGURE = 19; enum BK_EV_KEYRELEASE = 20; +/// "gestures" nodes: text = "mods kind x y", a, b = amounts (see BK_GESTURE_*). +enum BK_EV_GESTURE = 21; +enum BK_GESTURE_PAN = 1; +enum BK_GESTURE_MAGNIFY = 2; +enum BK_GESTURE_ROTATE = 3; /* ---- geometry ------------------------------------------------------------ */ enum BK_GEOM_NONE = 0; diff --git a/bindings/d/source/bui/node.d b/bindings/d/source/bui/node.d index 89f6b543..294e9d4d 100644 --- a/bindings/d/source/bui/node.d +++ b/bindings/d/source/bui/node.d @@ -27,7 +27,7 @@ struct NodeEvent { void* ref_; double a; double b; - /// The key text for `BK_EV_KEY` / `BK_EV_KEYRELEASE`, else empty. + /// The key text for `BK_EV_KEY` / `BK_EV_KEYRELEASE`, "mods kind x y" for `BK_EV_GESTURE`, else empty. const(char)[] text; } @@ -366,7 +366,7 @@ final class Node { return; } const(char)[] text; - if (kind == BK_EV_KEY || kind == BK_EV_KEYRELEASE) { + if (kind == BK_EV_KEY || kind == BK_EV_KEYRELEASE || kind == BK_EV_GESTURE) { text = cslice(cast(const(char)*) ref_); } auto event = NodeEvent(this, kind, ref_, a, b, text); diff --git a/bindings/lua/src/bui_lua.c b/bindings/lua/src/bui_lua.c index 75390d84..2ed61d8b 100644 --- a/bindings/lua/src/bui_lua.c +++ b/bindings/lua/src/bui_lua.c @@ -552,6 +552,7 @@ BUI_LUA_ENTRY int luaopen_bui(lua_State *L) { lua_pushinteger(L, BK_EV_WHEEL); lua_setfield(L, -2, "EV_WHEEL"); lua_pushinteger(L, BK_EV_SUBMIT); lua_setfield(L, -2, "EV_SUBMIT"); lua_pushinteger(L, BK_EV_VIEW); lua_setfield(L, -2, "EV_VIEW"); lua_pushinteger(L, BK_EV_SCROLL); lua_setfield(L, -2, "EV_SCROLL"); lua_pushinteger(L, BK_EV_CONFIGURE); lua_setfield(L, -2, "EV_CONFIGURE");lua_pushinteger(L, BK_EV_KEYRELEASE); lua_setfield(L, -2, "EV_KEYRELEASE"); + lua_pushinteger(L, BK_EV_GESTURE); lua_setfield(L, -2, "EV_GESTURE"); /* Cursor constants */ lua_pushinteger(L, BK_CURSOR_DEFAULT); lua_setfield(L, -2, "CURSOR_DEFAULT"); lua_pushinteger(L, BK_CURSOR_EW); lua_setfield(L, -2, "CURSOR_EW"); diff --git a/bindings/python/src/buipy_kit.c b/bindings/python/src/buipy_kit.c index df160bce..ddbba187 100644 --- a/bindings/python/src/buipy_kit.c +++ b/bindings/python/src/buipy_kit.c @@ -1412,6 +1412,13 @@ static void host_schedule(void *data, int ms, int timer) Py_XDECREF(a); } +/* Raw events ("events" / "gestures" nodes) carry a C string in `ref`; the others a PyObject. */ +static int raw_text_event(int kind) +{ + return (kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || kind == BK_EV_KEYRELEASE || + kind == BK_EV_GESTURE; +} + static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b) { if (kind == BK_EV_CALL && ref) { @@ -1423,7 +1430,7 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d return; } PyObject *r; - if ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || kind == BK_EV_KEYRELEASE) { + if (raw_text_event(kind)) { /* raw events: ref is a C string */ r = PyObject_CallMethod(target, "_on_event", "isdd", kind, ref ? (const char *)ref : "", a, b); @@ -1495,7 +1502,7 @@ static void defer_emit(BKNode *node, int kind, void *ref, double a, double b) return; } PyObject *payload; - if ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || kind == BK_EV_KEYRELEASE) { + if (raw_text_event(kind)) { payload = PyUnicode_FromString(ref ? (const char *)ref : ""); /* raw events: a C string */ } else { diff --git a/bindings/python/tests/test_nodes.py b/bindings/python/tests/test_nodes.py index 2a0aa0ff..2c4c794d 100644 --- a/bindings/python/tests/test_nodes.py +++ b/bindings/python/tests/test_nodes.py @@ -133,7 +133,8 @@ def test_touch_and_trackpad(): z = ed.zoom ctx.touch(1, 0, 300.0, 300.0, 0) ctx.touch(2, 0, 400.0, 300.0, 0) - assert ctx.touch(1, 1, 270.0, 300.0, 0) and ctx.touch(2, 1, 430.0, 300.0, 0) + assert not ctx.touch(1, 1, 270.0, 300.0, 0) # held until the other finger moves too + assert ctx.touch(2, 1, 430.0, 300.0, 0) assert ed.zoom > z * 1.3, (z, ed.zoom) px, z = ed.get("panx"), ed.zoom ctx.touch(1, 1, 300.0, 300.0, 0) diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs index e4d5dcc0..0b6806db 100644 --- a/bindings/rust/blenderui-sys/src/lib.rs +++ b/bindings/rust/blenderui-sys/src/lib.rs @@ -49,6 +49,17 @@ pub const BK_EV_VIEW: c_int = 17; pub const BK_EV_SCROLL: c_int = 18; pub const BK_EV_CONFIGURE: c_int = 19; pub const BK_EV_KEYRELEASE: c_int = 20; +/// A touch / trackpad gesture over a node with the "gestures" property: +/// text = "mods kind x y", a, b = the amounts (see `BK_GESTURE_*`). +pub const BK_EV_GESTURE: c_int = 21; + +// `BK_EV_GESTURE` kinds. +/// Two fingers moved together: a, b = pixels the content follows. +pub const BK_GESTURE_PAN: c_int = 1; +/// Pinch: a = scale change (0.1 = 10% larger). +pub const BK_GESTURE_MAGNIFY: c_int = 2; +/// Turn: a = degrees, positive counter-clockwise. +pub const BK_GESTURE_ROTATE: c_int = 3; // Modifier bits for input calls. pub const BK_SHIFT: c_int = 1; diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs index b9a46955..d9e9f67c 100644 --- a/bindings/rust/blenderui/src/element.rs +++ b/bindings/rust/blenderui/src/element.rs @@ -57,6 +57,7 @@ pub(crate) struct Listeners { pub mouse_move: Vec>, pub hover: Vec>, pub scroll: Vec>, + pub gesture: Vec>, pub key_down: Vec>, pub key_up: Vec>, pub change: Vec>, @@ -350,6 +351,11 @@ impl Div { self.listeners_mut().scroll.push(Box::new(f)); self } + /// Touch screen and trackpad gestures: pan, magnify and rotate (see [`GestureEvent`]). + pub fn on_gesture(mut self, f: impl Fn(&GestureEvent, &mut Window, &mut App) + 'static) -> Self { + self.listeners_mut().gesture.push(Box::new(f)); + self + } pub fn on_key_down(mut self, f: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static) -> Self { self.listeners_mut().key_down.push(Box::new(f)); self diff --git a/bindings/rust/blenderui/src/events.rs b/bindings/rust/blenderui/src/events.rs index c167bb29..a26d8e87 100644 --- a/bindings/rust/blenderui/src/events.rs +++ b/bindings/rust/blenderui/src/events.rs @@ -58,12 +58,73 @@ impl ClickEvent { } } +/// Pixels one wheel line scrolls a page; a touch pan's `delta` is its pixels over this. +pub const WHEEL_LINE_PX: f32 = 40.0; + #[derive(Clone, Debug)] pub struct ScrollWheelEvent { pub position: Point, /// Lines: positive scrolls the content up (wheel away from the user). pub delta: f32, pub modifiers: Modifiers, + /// Two fingers on a touch screen, not a wheel or trackpad: `delta` is then the pixels the + /// fingers moved over [`WHEEL_LINE_PX`], so `delta * WHEEL_LINE_PX` keeps the content under + /// them. `modifiers.shift` marks the horizontal part of a pan. + pub touch: bool, +} + +/// One step of a touch screen contact (`App::simulate_touch`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TouchPhase { + Down, + Move, + Up, + /// The platform took the contact back: nothing it did is kept. + Cancel, +} + +impl TouchPhase { + pub(crate) const fn to_kit(self) -> i32 { + match self { + TouchPhase::Down => blenderui_sys::BK_TOUCH_DOWN, + TouchPhase::Move => blenderui_sys::BK_TOUCH_MOVE, + TouchPhase::Up => blenderui_sys::BK_TOUCH_UP, + TouchPhase::Cancel => blenderui_sys::BK_TOUCH_CANCEL, + } + } +} + +/// What a [`GestureEvent`] is: Blender's MOUSEPAN, MOUSEZOOM and MOUSEROTATE. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GestureKind { + /// Two fingers moved together: `dx`, `dy`. + Pan, + /// A pinch: `magnify`. + Magnify, + /// A turn: `degrees`. + Rotate, +} + +/// A touch screen or trackpad gesture (`on_gesture`). +/// +/// Two fingers on a touch screen pan, magnify and rotate about their centre; trackpads send +/// magnify and rotate. A listener that calls `cx.stop_propagation()` keeps a pan from also +/// scrolling the page (and from reaching `on_scroll_wheel` listeners). +#[derive(Clone, Debug)] +pub struct GestureEvent { + pub kind: GestureKind, + /// The gesture's centre: between the fingers, or the pointer for a trackpad. + pub position: Point, + /// `Pan`: pixels the fingers moved since the last event (the content should follow). + pub dx: f32, + pub dy: f32, + /// `Magnify`: scale change since the last event (0.1 = 10% larger). + pub magnify: f32, + /// `Rotate`: degrees since the last event, positive counter-clockwise. + pub degrees: f32, + pub modifiers: Modifiers, + /// From a touch screen (`false`: a trackpad). + pub touch: bool, } /// A key: `key` is the keysym (`"a"`, `"Return"`, `"Left"` ...). diff --git a/bindings/rust/blenderui/src/table/data_table.rs b/bindings/rust/blenderui/src/table/data_table.rs index 919978b7..b254f183 100644 --- a/bindings/rust/blenderui/src/table/data_table.rs +++ b/bindings/rust/blenderui/src/table/data_table.rs @@ -16,7 +16,7 @@ use blenderui_table::Size; use crate::element::{canvas_with, Div}; use crate::html::div; use crate::css::Decl; -use crate::{px, AnyElement, App, Entity, IntoElement, MouseButton, ParentElement, Pixels, Styled, Window}; +use crate::{px, AnyElement, App, Entity, IntoElement, MouseButton, ParentElement, Pixels, Styled, Window, WHEEL_LINE_PX}; type Listener = Box; @@ -195,7 +195,12 @@ impl IntoElement for DataTable { dispatch(state, &up, w, cx); }) .on_scroll_wheel(move |e, w, cx| { - state.update(cx, |s, _| s.wheel(e.delta, e.modifiers.shift, w)); + state.update(cx, |s, _| if e.touch { // the rows follow the fingers + let px = -f64::from(e.delta * WHEEL_LINE_PX); + if e.modifiers.shift { s.scroll_by_px(px, 0.0, w) } else { s.scroll_by_px(0.0, px, w) } + } else { + s.wheel(e.delta, e.modifiers.shift, w) + }); dispatch(state, &wh, w, cx); }) .on_key_down(move |e, w, cx| { diff --git a/bindings/rust/blenderui/src/vlist/element.rs b/bindings/rust/blenderui/src/vlist/element.rs index 0a5a1304..54db98f2 100644 --- a/bindings/rust/blenderui/src/vlist/element.rs +++ b/bindings/rust/blenderui/src/vlist/element.rs @@ -14,7 +14,7 @@ use super::state::{ListState, ViewInfo}; use crate::css::Decl; use crate::element::{canvas_with, Div}; use crate::html::div; -use crate::{px, AnyElement, App, Entity, IntoElement, MouseButton, ParentElement, Styled, Window}; +use crate::{px, AnyElement, App, Entity, IntoElement, MouseButton, ParentElement, Styled, Window, WHEEL_LINE_PX}; type Listener = Rc)>; @@ -115,9 +115,11 @@ impl IntoElement for VariableList i32 { + text.split_whitespace().next().and_then(|v| v.parse().ok()).unwrap_or(0) +} + // ========================================================================== // Kit callbacks @@ -935,6 +961,8 @@ impl Window { sys::BK_geom_set(canvas, c"relwidth".as_ptr(), 1.0); sys::BK_geom_set(canvas, c"relheight".as_ptr(), 1.0); sys::BK_set_num(canvas, c"events".as_ptr(), 1.0); + // touch and trackpad gestures come here (BK_EV_GESTURE), not as kit scrolling + sys::BK_set_num(canvas, c"gestures".as_ptr(), 1.0); let ctx = sys::BK_context_new(root); let host = sys::BKHost { data: id as *mut c_void, @@ -1224,9 +1252,10 @@ impl Window { /// Call the listeners `pick` selects, from element `key` up to the root. /// The frame is moved out of the window meanwhile, so listeners can take /// `&mut Window` while the frame lends them out: no copies, no `Rc`. + /// Calls the listeners from `key` up; true when one stopped the propagation. fn emit(&mut self, app: &mut App, key: Key, e: &E, - pick: impl Fn(&Listeners) -> Vec<&Listener>) { - let Some(frame) = self.frame.take() else { return }; + pick: impl Fn(&Listeners) -> Vec<&Listener>) -> bool { + let Some(frame) = self.frame.take() else { return false }; app.propagate = true; let mut cur = frame.by_key().get(&key).copied(); 'up: while let Some(i) = cur { @@ -1240,10 +1269,12 @@ impl Window { } cur = frame.nodes[i].parent; } + let stopped = !app.propagate; app.propagate = true; if self.frame.is_none() { self.frame = Some(frame); } + stopped } fn update_hover(&mut self, app: &mut App, fire: bool) { @@ -1378,13 +1409,9 @@ impl Window { sys::BK_EV_WHEEL => { let (modifiers, _) = self.pointer_event(&ev.text); let (px_, py_) = self.pointer; - let e = ScrollWheelEvent { position: point(px(px_), px(py_)), delta: ev.a as f32, modifiers }; - let path = self.path_at(px_, py_); - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); - } - self.scroll_by(&path, -(ev.a as f32) * 40.0, modifiers.shift); + self.wheel(app, (px_, py_), ev.a as f32, modifiers, kit_mods(&ev.text) & sys::BK_FROM_TOUCH != 0); } + sys::BK_EV_GESTURE => self.gesture(app, &ev), sys::BK_EV_KEY | sys::BK_EV_KEYRELEASE => { let mut parts = ev.text.splitn(2, '\t'); let ch = parts.next().unwrap_or("").to_owned(); @@ -1403,6 +1430,58 @@ impl Window { } } + /// A wheel step (or a touch pan in lines): `on_scroll_wheel`, then the scroll container. + fn wheel(&mut self, app: &mut App, at: (f32, f32), lines: f32, modifiers: Modifiers, touch: bool) { + let e = ScrollWheelEvent { position: point(px(at.0), px(at.1)), delta: lines, modifiers, touch }; + let path = self.path_at(at.0, at.1); + if let Some(&deepest) = path.last() { + self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); + } + self.scroll_by(&path, -lines * WHEEL_LINE_PX, modifiers.shift); + } + + /// BK_EV_GESTURE: text "mods kind x y" (device pixels from the canvas), a and b the amounts. + /// `on_gesture` listeners get it; a pan nobody stopped then scrolls like a wheel, so pages + /// scroll with two fingers and `on_scroll_wheel` sees it (with `touch` set). + fn gesture(&mut self, app: &mut App, ev: &RawEvent) { + let mut it = ev.text.split_whitespace().map(|v| v.parse::().unwrap_or(0)); + let (mods, kind) = (it.next().unwrap_or(0), it.next().unwrap_or(0)); + let (x, y) = (it.next().unwrap_or(0) as f32 / self.scale, it.next().unwrap_or(0) as f32 / self.scale); + let kind = match kind { + sys::BK_GESTURE_PAN => GestureKind::Pan, + sys::BK_GESTURE_MAGNIFY => GestureKind::Magnify, + sys::BK_GESTURE_ROTATE => GestureKind::Rotate, + _ => return, + }; + let (a, b) = (ev.a as f32, ev.b as f32); + let pan = kind == GestureKind::Pan; + let modifiers = Modifiers::from_kit(mods); + let touch = mods & sys::BK_FROM_TOUCH != 0; + let e = GestureEvent { + kind, + position: point(px(x), px(y)), + dx: if pan { a / self.scale } else { 0.0 }, + dy: if pan { b / self.scale } else { 0.0 }, + magnify: if kind == GestureKind::Magnify { a } else { 0.0 }, + degrees: if kind == GestureKind::Rotate { a } else { 0.0 }, + modifiers, + touch, + }; + self.pointer = (x, y); + let stopped = match self.path_at(x, y).last() { + Some(&deepest) => self.emit(app, deepest, &e, |l| l.gesture.iter().collect()), + None => false, + }; + if pan && !stopped { + if e.dy != 0.0 { + self.wheel(app, (x, y), e.dy / WHEEL_LINE_PX, modifiers, touch); + } + if e.dx != 0.0 { // Shift + wheel: positive scrolls left, as the fingers move right + self.wheel(app, (x, y), e.dx / WHEEL_LINE_PX, Modifiers { shift: true, ..modifiers }, touch); + } + } + } + fn state_deepest(&self) -> Option { self.path_at(self.pointer.0, self.pointer.1).last().copied() } diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/headless.rs index 37387ed5..fb4d81f0 100644 --- a/bindings/rust/blenderui/tests/headless.rs +++ b/bindings/rust/blenderui/tests/headless.rs @@ -359,3 +359,82 @@ fn canvas_image_and_video_sources() { assert_eq!(pixel(&img, s, s), 0x0000ff, "the image's pixel shows"); }); } + +/// Touch and trackpad gestures reach `on_gesture`; a pan nobody stops scrolls like the wheel, +/// with `touch` set on the wheel event. +#[test] +fn gestures_reach_listeners_and_pans_scroll() { + use std::cell::RefCell; + thread_local! { + static GESTURES: RefCell> = const { RefCell::new(Vec::new()) }; + static WHEELS: RefCell> = const { RefCell::new(Vec::new()) }; + } + struct Touchy; + impl Render for Touchy { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + body() + .m_0() + // on the body: every unstopped pan bubbles here, over the map or the list + .on_scroll_wheel(|e, _, _| WHEELS.with(|w| w.borrow_mut().push((e.delta, e.touch)))) + .child(div().id("map").w(px(200.0)).h(px(100.0)).on_gesture(|e, _, cx| { + GESTURES.with(|g| g.borrow_mut().push(e.clone())); + if e.kind == GestureKind::Pan { + cx.stop_propagation(); // the map pans itself: the page stays put + } + })) + .child( + div().id("list").h(px(100.0)).overflow_y_scroll() + .child(div().id("row0").h(px(100.0))) + .child(div().h(px(200.0))), + ) + } + } + let (down, mv, up) = (TouchPhase::Down, TouchPhase::Move, TouchPhase::Up); + Application::headless().run(|cx| { + let id = open(cx, 200.0, 200.0, Touchy).id; + cx.draw(id); + // pinch on the map: 80 px apart to 120 px + cx.simulate_touch(id, 1, down, 60.0, 50.0); + cx.simulate_touch(id, 2, down, 140.0, 50.0); + cx.simulate_touch(id, 1, mv, 40.0, 50.0); + cx.simulate_touch(id, 2, mv, 160.0, 50.0); + // both fingers 20 px down: a pan the map stops + cx.simulate_touch(id, 1, mv, 40.0, 70.0); + cx.simulate_touch(id, 2, mv, 160.0, 70.0); + cx.simulate_touch(id, 1, up, 40.0, 70.0); + cx.simulate_touch(id, 2, up, 160.0, 70.0); + let got = GESTURES.with(|g| g.borrow_mut().drain(..).collect::>()); + let mag: Vec<_> = got.iter().filter(|e| e.kind == GestureKind::Magnify).collect(); + assert_eq!(mag.len(), 1, "{got:?}"); + assert!((mag[0].magnify - 0.5).abs() < 1e-3 && mag[0].touch, "{:?}", mag[0]); + assert!((mag[0].position.x.0 - 100.0).abs() < 1.0 && (mag[0].position.y.0 - 50.0).abs() < 1.0); + let pans: Vec<_> = got.iter().filter(|e| e.kind == GestureKind::Pan).collect(); + assert_eq!(pans.len(), 1, "{got:?}"); + assert!(pans[0].dx.abs() < 1e-3 && (pans[0].dy - 20.0).abs() < 1e-3, "{:?}", pans[0]); + assert!(got.iter().all(|e| e.kind != GestureKind::Rotate), "a pure pinch and pan do not turn"); + assert!(WHEELS.with(|w| w.borrow().is_empty()), "a stopped pan scrolls nothing"); + + // a pan over the list nobody stops: the list scrolls 30 px, its wheel listener sees touch + let before = cx.element_bounds(id, "row0").unwrap().origin.y; + cx.simulate_touch(id, 1, down, 60.0, 170.0); + cx.simulate_touch(id, 2, down, 140.0, 170.0); + cx.simulate_touch(id, 1, mv, 60.0, 140.0); + cx.simulate_touch(id, 2, mv, 140.0, 140.0); + cx.simulate_touch(id, 1, up, 60.0, 140.0); + cx.simulate_touch(id, 2, up, 140.0, 140.0); + cx.draw(id); + let after = cx.element_bounds(id, "row0").unwrap().origin.y; + assert!((before - after - 30.0).abs() < 1e-3, "content follows the fingers: {before} -> {after}"); + let wheels = WHEELS.with(|w| w.borrow_mut().drain(..).collect::>()); + assert_eq!(wheels.len(), 1, "{wheels:?}"); + assert!(wheels[0].1 && (wheels[0].0 * WHEEL_LINE_PX + 30.0).abs() < 1e-3, "{wheels:?}"); + + // trackpad: magnify and rotate at the pointer, not from a touch screen + cx.simulate_magnify(id, 100.0, 50.0, -0.2); + cx.simulate_rotate(id, 100.0, 50.0, 15.0); + let got = GESTURES.with(|g| g.borrow_mut().drain(..).collect::>()); + assert_eq!(got.len(), 2, "{got:?}"); + assert!(got[0].kind == GestureKind::Magnify && (got[0].magnify + 0.2).abs() < 1e-6 && !got[0].touch); + assert!(got[1].kind == GestureKind::Rotate && got[1].degrees == 15.0 && !got[1].touch); + }); +} diff --git a/docs/rust.md b/docs/rust.md index a2f02eac..225f2806 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -428,7 +428,8 @@ gets `on_click`. | `on_mouse_up(button, ..)` | `MouseUpEvent` | yes | | `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | yes | | `on_hover` | `bool`: entered / left | no | -| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, modifiers }` | yes | +| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, modifiers, touch }` | yes | +| `on_gesture` | `GestureEvent { kind, position, dx, dy, magnify, degrees, modifiers, touch }`: touch pan / pinch / turn, trackpad pinch / turn ([touch.md](touch.md)) | yes | | `on_key_down`, `on_key_up` | `KeyDownEvent { keystroke: Keystroke { key, key_char, modifiers } }` | yes (from the focused element) | | `on_change`, `on_input` | `ChangeEvent { value, checked, number }` | yes | diff --git a/docs/touch.md b/docs/touch.md index 8c93f41b..b4806ede 100644 --- a/docs/touch.md +++ b/docs/touch.md @@ -56,6 +56,46 @@ The same calls are on every binding: `ctx.touch(id, phase, x, y, mods)`, with `BK_TOUCH_*` in D (and `node.setTouch(true)` for custom nodes); `BK_touch`, `BK_magnify` and `BK_rotate` in `blenderui-sys`. +## Gestures for your own elements and windows + +Kit widgets react to gestures by themselves (scroll views scroll, the node editor pans and +zooms). Your own content can take them too. + +**Rust (`blenderui`):** every element can listen. + +```rust +div().id("map").on_gesture(|e, window, cx| { + match e.kind { + GestureKind::Pan => { /* e.dx, e.dy: the fingers' movement, in logical pixels */ } + GestureKind::Magnify => { /* e.magnify: 0.1 = 10% larger, about e.position */ } + GestureKind::Rotate => { /* e.degrees, positive counter-clockwise */ } + } + cx.stop_propagation(); // a stopped pan does not also scroll the page +}) +``` + +`GestureEvent { kind, position, dx, dy, magnify, degrees, modifiers, touch }` bubbles like the +other events. `touch` is `false` for a trackpad pinch or turn. A pan that no listener stops then +scrolls the scroll container under it and reaches `on_scroll_wheel` listeners, with +`ScrollWheelEvent::touch` set and `delta` in lines (`delta * WHEEL_LINE_PX` is the pixels the +fingers moved). Pages written for the wheel scroll with two fingers without any change; the +virtual list and the data table use that to keep their rows under the fingers. +`rsx!` takes `onGesture={...}`. Tests can drive it with `cx.simulate_touch(window, id, +TouchPhase::Down, x, y)`, `simulate_magnify` and `simulate_rotate`. + +**C and the other bindings:** give a node the `"gestures"` property +(`BK_set_num(node, "gestures", 1)`). Gestures over it or its children then come to your +`BKHost.emit` as `BK_EV_GESTURE`, and the kit doesn't scroll anything for them: + +| Field | Value | +|---|---| +| `ref` | `"mods kind x y"`: `mods` with `BK_FROM_TOUCH` for a touch screen; `kind` `BK_GESTURE_PAN`, `MAGNIFY` or `ROTATE`; `x`, `y` the gesture's centre, relative to the node | +| `a`, `b` | Pan: the pixels moved. Magnify: `a` = scale change. Rotate: `a` = degrees | + +Nodes with only `"events"` (Tk bindings, Qt event handlers) are unchanged: two fingers still +scroll under them. The two fingers' moves are paired into one update, so a pan sends no magnify +or rotate of its own and a pinch sends no pan. + ## Custom nodes By default a `custom` node gets touch the way it gets the mouse: `BK_CUSTOM_PRESS`, `MOTION` and @@ -91,5 +131,3 @@ touches take the normal path, so a tap outside closes the menu. hidden-pointer drag of number fields is for the mouse); a number field dragged by touch stops changing at the edge. - One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). -- Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between - the two fingers' events. Nothing waits for a platform's frame grouping yet. diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h index a6f50e10..d5d12cd9 100644 --- a/kit/include/BUI_kit.h +++ b/kit/include/BUI_kit.h @@ -121,9 +121,17 @@ enum { BK_EV_VIEW, /* scrolled view changed (nodes with "viewevents") */ BK_EV_SCROLL, /* scrollbar request: a = 0 moveto (b = fraction), 1 units, 2 pages (b = count) */ BK_EV_CONFIGURE, /* geometry changed ("events" nodes): a = width, b = height */ - BK_EV_KEYRELEASE /* ref = "\tkeysym", a = mods */ + BK_EV_KEYRELEASE, /* ref = "\tkeysym", a = mods */ + /* Touch / trackpad gesture over a node with the "gestures" property, which takes it: + * ref = "mods kind x y" (kind BK_GESTURE_*; x, y: the gesture's centre, relative to the node), + * PAN: a, b = pixels moved (the content follows the fingers); MAGNIFY: a = scale change + * (0.1 = 10% larger); ROTATE: a = degrees, > 0 counter-clockwise. */ + BK_EV_GESTURE }; +/* BK_EV_GESTURE kinds, as Blender's MOUSEPAN / MOUSEZOOM / MOUSEROTATE. */ +enum { BK_GESTURE_PAN = 1, BK_GESTURE_MAGNIFY, BK_GESTURE_ROTATE }; + typedef struct BKHost { void *data; void (*request)(void *data); /* schedule a render */ diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index 57c630b1..5ec02ccf 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -787,6 +787,7 @@ static const struct { {"opaque", NF_OPAQUE, false}, {"html", NF_HTML, true}, /* Chrome's form-control look (kit_widgets.c) */ {"bare", NF_BARE, false}, + {"gestures", NF_GESTURES, false}, {"active_default", NF_ACTIVE_DEFAULT, false}, }; @@ -3415,8 +3416,9 @@ int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods) /* Touch and trackpad gestures, as Blender's MOUSEPAN / MOUSEZOOM / MOUSEROTATE reach the view * under them (view2d_ops.cc): the first of `target` and its parents that takes the gesture. - * A custom node always does (it gets WHEEL in notches as BK_scroll's, MAGNIFY, ROTATE), so the - * region under an embedded UI never moves, as with the wheel (custom_wheel). */ + * A node with "gestures" always does (the host gets BK_EV_GESTURE: an HTML document, a canvas, + * a whole window's root), and so does a custom node (WHEEL in notches as BK_scroll's, MAGNIFY, + * ROTATE), so the region under them never moves, as with the wheel (custom_wheel). */ int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float a, float b, int mods) { if (ctx->modal) { @@ -3427,6 +3429,14 @@ int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float a, if (!NODE_ENABLED(n)) { continue; } + if (n->flags & NF_GESTURES) { + char buf[96]; + snprintf(buf, sizeof(buf), "%d %d %d %d", mods, kind, x - n->x, y - n->y); + ctx->in_input++; + bk_emit(n, BK_EV_GESTURE, buf, a, b); + ctx->in_input--; + return 1; + } if (BK_IS_CUSTOM(n)) { BKCustomEvent ce; memset(&ce, 0, sizeof(ce)); diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h index e0c16e6d..debf61af 100644 --- a/kit/intern/kit_intern.h +++ b/kit/intern/kit_intern.h @@ -300,12 +300,10 @@ typedef struct BKEvent { float wheel_x, wheel_y; /* BK_scroll: precise deltas (custom nodes) */ /* BKClass.gesture: Blender's MOUSEPAN (pan_x, pan_y: pixels the content follows), * MOUSEZOOM (magnify: scale change) and MOUSEROTATE (rotate: degrees, > 0 counter-clockwise) */ - int gesture; /* BK_GESTURE_* */ + int gesture; /* BK_GESTURE_* (BUI_kit.h) */ float pan_x, pan_y, magnify, rotate; } BKEvent; -enum { BK_GESTURE_PAN = 1, BK_GESTURE_MAGNIFY, BK_GESTURE_ROTATE }; - #define EV_SHIFT(e) (((e)->mods & BK_SHIFT) != 0) #define EV_CTRL(e) (((e)->mods & BK_CTRL) != 0) #define EV_ALT(e) (((e)->mods & BK_ALT) != 0) @@ -403,6 +401,7 @@ enum { NF_ACTIVE_DEFAULT = 1 << 26, /* buttons: UI_BUT_ACTIVE_DEFAULT (drawn with the select colors) */ NF_DEFAULT_SET = 1 << 27, /* `defval` was set: by "default", or by the first "value" a widget got */ NF_BARE = 1 << 28, /* "bare": an HTML text field with no frame (CSS `border-style: none`) */ + NF_GESTURES = 1 << 29, /* "gestures": touch / trackpad gestures go to the host (BK_EV_GESTURE) */ }; #define BK_HTML(n) (((n)->flags & NF_HTML) != 0) @@ -588,6 +587,7 @@ typedef struct BKTouch { int start_x, start_y; /* the gesture's first centre */ float cx, cy, dist, ang; /* its centre, spread and angle at the last update */ float rest_x, rest_y; /* pan not yet sent as whole wheel steps (pixels) */ + int held; /* 1 g0 / 2 g1: moved, its update waits for the other finger */ } BKTouch; struct BKContext { diff --git a/kit/intern/kit_touch.c b/kit/intern/kit_touch.c index b4ac25c3..6e64bd39 100644 --- a/kit/intern/kit_touch.c +++ b/kit/intern/kit_touch.c @@ -132,12 +132,14 @@ static void gesture_begin(BKContext *ctx, int i0, int i1) t->start_y = px(t->cy); t->target = bk_ctx_hit(ctx, t->start_x, t->start_y); t->rest_x = t->rest_y = 0.0f; + t->held = 0; } static void gesture_end(BKTouch *t) { t->g0 = t->g1 = -1; t->target = NULL; + t->held = 0; } /* A pan nothing took: the region or scroll view under the gesture's start scrolls one wheel @@ -261,8 +263,18 @@ static int touch_update(BKContext *ctx, int i, int phase, int mods) return 1; } if (i == t->g0 || i == t->g1) { + /* One update per pair of moves: hosts report the fingers one by one, so updating after each + * would make a pure pan wobble the spread and angle between them. A finger that moves again + * while the other stays put, or lifts, sends what it held. */ + const int bit = i == t->g0 ? 1 : 2; + if (phase == BK_TOUCH_MOVE && !t->held) { + t->held = bit; + return 0; + } + const int r = t->held ? gesture_update(ctx, tm) : 0; + t->held = phase == BK_TOUCH_MOVE && t->held == bit ? bit : 0; if (phase == BK_TOUCH_MOVE) { - return gesture_update(ctx, tm); + return r; } gesture_end(t); return 1; diff --git a/tests/touch_test.c b/tests/touch_test.c index 41c996d3..a13c25af 100644 --- a/tests/touch_test.c +++ b/tests/touch_test.c @@ -30,6 +30,12 @@ enum { W = 400, H = 300 }; static BuiRaster *g_raster; static int g_clicks; static int g_warps; +/* BK_EV_GESTURE as a host gets it */ +static struct { + int count[4]; /* by kind */ + int mods, kind, x, y; + double a, b, pan_x, pan_y, magnify, degrees; +} g_gesture; static void host_noop(void *data) {} static void host_cursor(void *data, int c) {} @@ -48,6 +54,25 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d if (kind == BK_EV_CLICK) { g_clicks++; } + if (kind == BK_EV_GESTURE && + sscanf((const char *)ref, "%d %d %d %d", &g_gesture.mods, &g_gesture.kind, &g_gesture.x, + &g_gesture.y) == 4 && + g_gesture.kind >= BK_GESTURE_PAN && g_gesture.kind <= BK_GESTURE_ROTATE) + { + g_gesture.count[g_gesture.kind]++; + g_gesture.a = a; + g_gesture.b = b; + if (g_gesture.kind == BK_GESTURE_PAN) { + g_gesture.pan_x += a; + g_gesture.pan_y += b; + } + else if (g_gesture.kind == BK_GESTURE_MAGNIFY) { + g_gesture.magnify += a; + } + else { + g_gesture.degrees += a; + } + } } static BKContext *context(BKNode *root) @@ -391,6 +416,76 @@ static void test_drag_at_edge(void) BK_node_free(col); } +/* A node with "gestures" (an HTML document, a window's root) gets them as BK_EV_GESTURE and + * takes them; one with only "events" (Tk bindings) still scrolls as before. */ +static void test_gestures_property(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *first = NULL; + for (int i = 0; i < 60; i++) { + BKNode *b = BK_node_new("button"); + BK_set_str(b, "label", "Row"); + BK_node_add(col, b, -1); + first = first ? first : b; + } + BK_set_num(col, "gestures", 1.0); + BKContext *ctx = context(col); + int r0[4], r1[4]; + BK_node_rect(first, r0); + memset(&g_gesture, 0, sizeof(g_gesture)); + /* pan: 60 px down, then 30 px left */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 150, 100, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 250, 100, 0); + for (int i = 1; i <= 3; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 150, 100 + i * 20, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 250, 100 + i * 20, 0); + } + BK_touch(ctx, 1, BK_TOUCH_MOVE, 120, 160, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 220, 160, 0); + CHECK(g_gesture.count[BK_GESTURE_PAN] == 4); /* one per pair of moves */ + CHECK(g_gesture.count[BK_GESTURE_MAGNIFY] == 0 && g_gesture.count[BK_GESTURE_ROTATE] == 0); + CHECK(fabs(g_gesture.pan_x + 30.0) < 1e-3 && fabs(g_gesture.pan_y - 60.0) < 1e-3); + CHECK(g_gesture.mods & BK_FROM_TOUCH); + CHECK(g_gesture.x == 170 && g_gesture.y == 160); /* the centre, relative to the node */ + /* spread to twice the distance, then turn 30 degrees counter-clockwise */ + BK_touch(ctx, 1, BK_TOUCH_MOVE, 70, 160, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 270, 160, 0); + CHECK(g_gesture.count[BK_GESTURE_MAGNIFY] == 1 && fabs(g_gesture.magnify - 1.0) < 1e-4); + const float a = 30.0f * (float)M_PI / 180.0f; + BK_touch(ctx, 1, BK_TOUCH_MOVE, 170 - 100 * cosf(a), 160 + 100 * sinf(a), 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 170 + 100 * cosf(a), 160 - 100 * sinf(a), 0); + CHECK(fabs(g_gesture.degrees - 30.0) < 0.5); + BK_touch(ctx, 1, BK_TOUCH_UP, 0, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 0, 0, 0); + BK_render(ctx, g_raster, W, H, 1); + BK_node_rect(first, r1); + CHECK(r1[1] == r0[1]); /* the host took the pan: the region did not scroll */ + /* a trackpad pinch and turn (BK_magnify, BK_rotate) come the same way, without the touch bit */ + memset(&g_gesture, 0, sizeof(g_gesture)); + CHECK(BK_magnify(ctx, 40, 30, 0.25f, BK_CTRL)); + CHECK(g_gesture.kind == BK_GESTURE_MAGNIFY && g_gesture.a == 0.25 && g_gesture.mods == BK_CTRL); + CHECK(BK_rotate(ctx, 40, 30, -12.0f, 0) && g_gesture.degrees == -12.0); + + /* "events" alone: a pan still scrolls the region and no gesture is sent */ + BK_set_num(col, "gestures", 0.0); + BK_set_num(col, "events", 1.0); + memset(&g_gesture, 0, sizeof(g_gesture)); + BK_touch(ctx, 1, BK_TOUCH_DOWN, 180, 200, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 220, 200, 0); + for (int i = 1; i <= 10; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 180, 200 - i * 12, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 220, 200 - i * 12, 0); + } + BK_touch(ctx, 1, BK_TOUCH_UP, 180, 80, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 220, 80, 0); + BK_render(ctx, g_raster, W, H, 1); + BK_node_rect(first, r1); + CHECK(r1[1] < r0[1] - 60); + CHECK(g_gesture.count[BK_GESTURE_PAN] == 0); + BK_context_free(ctx); + BK_node_free(col); +} + /* -- custom nodes -- */ static void test_custom_default(void) @@ -518,6 +613,7 @@ int main(void) test_node_editor(); test_node_editor_cancel(); test_drag_at_edge(); + test_gestures_property(); test_custom_default(); test_custom_raw(); test_capacity(); diff --git a/website/src/content/docs/concepts/touch.mdx b/website/src/content/docs/concepts/touch.mdx index 922e0574..25d60e16 100644 --- a/website/src/content/docs/concepts/touch.mdx +++ b/website/src/content/docs/concepts/touch.mdx @@ -63,6 +63,46 @@ The same calls are on every binding: `ctx.touch(id, phase, x, y, mods)`, with `BK_TOUCH_*` in D (and `node.setTouch(true)` for custom nodes); `BK_touch`, `BK_magnify` and `BK_rotate` in `blenderui-sys`. +## Gestures for your own elements and windows + +Kit widgets react to gestures by themselves (scroll views scroll, the node editor pans and +zooms). Your own content can take them too. + +**Rust (`blenderui`):** every element can listen. + +```rust +div().id("map").on_gesture(|e, window, cx| { + match e.kind { + GestureKind::Pan => { /* e.dx, e.dy: the fingers' movement, in logical pixels */ } + GestureKind::Magnify => { /* e.magnify: 0.1 = 10% larger, about e.position */ } + GestureKind::Rotate => { /* e.degrees, positive counter-clockwise */ } + } + cx.stop_propagation(); // a stopped pan does not also scroll the page +}) +``` + +`GestureEvent { kind, position, dx, dy, magnify, degrees, modifiers, touch }` bubbles like the +other events. `touch` is `false` for a trackpad pinch or turn. A pan that no listener stops then +scrolls the scroll container under it and reaches `on_scroll_wheel` listeners, with +`ScrollWheelEvent::touch` set and `delta` in lines (`delta * WHEEL_LINE_PX` is the pixels the +fingers moved). Pages written for the wheel scroll with two fingers without any change; the +virtual list and the data table use that to keep their rows under the fingers. +`rsx!` takes `onGesture={...}`. Tests can drive it with `cx.simulate_touch(window, id, +TouchPhase::Down, x, y)`, `simulate_magnify` and `simulate_rotate`. + +**C and the other bindings:** give a node the `"gestures"` property +(`BK_set_num(node, "gestures", 1)`). Gestures over it or its children then come to your +`BKHost.emit` as `BK_EV_GESTURE`, and the kit doesn't scroll anything for them: + +| Field | Value | +|---|---| +| `ref` | `"mods kind x y"`: `mods` with `BK_FROM_TOUCH` for a touch screen; `kind` `BK_GESTURE_PAN`, `MAGNIFY` or `ROTATE`; `x`, `y` the gesture's centre, relative to the node | +| `a`, `b` | Pan: the pixels moved. Magnify: `a` = scale change. Rotate: `a` = degrees | + +Nodes with only `"events"` (Tk bindings, Qt event handlers) are unchanged: two fingers still +scroll under them. The two fingers' moves are paired into one update, so a pan sends no magnify +or rotate of its own and a pinch sends no pan. + ## Custom nodes By default a `custom` node gets touch the way it gets the mouse: `BK_CUSTOM_PRESS`, `MOTION` and @@ -98,5 +138,3 @@ touches take the normal path, so a tap outside closes the menu. hidden-pointer drag of number fields is for the mouse); a number field dragged by touch stops changing at the edge. - One finger never scrolls; scrolling takes two (as in Blender, where a single drag edits). -- Each finger's move is its own update, so a pan may wobble the zoom by a rounding error between - the two fingers' events. Nothing waits for a platform's frame grouping yet. diff --git a/website/src/content/docs/rust/events.mdx b/website/src/content/docs/rust/events.mdx index 04abd684..439df4ad 100644 --- a/website/src/content/docs/rust/events.mdx +++ b/website/src/content/docs/rust/events.mdx @@ -48,7 +48,8 @@ If you use [hooks](../hooks/) instead, you don't need either: writing a signal r | `on_mouse_up(button, f)` | `MouseUpEvent { button, position, modifiers }` | Yes | | `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | Yes | | `on_hover` | `bool`: `true` when the pointer enters, `false` when it leaves | No | -| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, modifiers }` | Yes | +| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, modifiers, touch }` | Yes | +| `on_gesture` | `GestureEvent { kind, position, dx, dy, magnify, degrees, modifiers, touch }` | Yes | | `on_key_down`, `on_key_up` | `KeyDownEvent` / `KeyUpEvent { keystroke }` | Yes, from the focused element | | `on_change`, `on_input` | `ChangeEvent { value, checked, number }` | Yes | @@ -58,7 +59,8 @@ The details: - **`MouseButton`** is `Left`, `Right` or `Middle`. - **`Modifiers`** has `shift`, `control` and `alt`. - **`ClickEvent::click_count()`** tells a double-click from a single one. -- **`ScrollWheelEvent::delta`** is in lines; positive scrolls the content up (the wheel turned away from you). +- **`ScrollWheelEvent::delta`** is in lines; positive scrolls the content up (the wheel turned away from you). `touch` marks a two-finger pan on a touch screen: `delta * WHEEL_LINE_PX` is then the pixels the fingers moved. +- **`GestureEvent`** is a touch pan (`dx`, `dy`), pinch (`magnify`, 0.1 = 10% larger) or turn (`degrees`, positive counter-clockwise), or a trackpad pinch or turn (`touch` false), at `position`. `cx.stop_propagation()` keeps a pan from also scrolling the page. See [Touch and gestures](../../concepts/touch/). - **`Keystroke`** has `key` (the key's name: `"a"`, `"Return"`, `"Left"` …), `key_char` (the typed text, if any) and `modifiers`. - **`ChangeEvent`** carries `value` (the text), `checked` (checkboxes and radios) and `number` (numbers, ranges, and a select's index). `on_input` and `on_change` both fire when the value changes. [The three looks](../styled-and-blender-components/#form-controls) lists what each control sends. From 47857277a834d861a626ff9ef47e3bb7aa842b5f Mon Sep 17 00:00:00 2001 From: Walter Stanish Date: Fri, 13 Nov 2026 22:30:25 +1100 Subject: [PATCH 4/4] touch: keep pans to their axis, drop a cancelled finger's held move Review follow-ups on #42: - Exclude horizontal touch components from vertical scrolling. Every kit scroller (lists, trees, grids, text areas, scroll views, the region) reads Shift + wheel as vertical, so the sideways steps of a touch pan scrolled them vertically. in_BK_wheel now gives a sideways touch step (BK_FROM_TOUCH | BK_SHIFT) to bindings only (Tk's ), and pan_steps no longer passes the keyboard's Shift on vertical steps. blenderui: a vertical pan keeps to its axis (scroll_by's exact_axis: no sideways fallback for a container without vertical range), the keyboard's Shift no longer turns it sideways, and the virtual list ignores the sideways part. - Discard pending gesture movement on cancellation: a cancelled gesture finger drops the move it held for its partner instead of sending it (an up still sends it). - Gestures over no widget reach the containers under them, as the wheel does (deepest()), so a "gestures" root gets them over empty space. - NF_GESTURES moves to bit 30: the merge with main (#33, Qt parity) brought NF_SELECT on bit 29, the bit NF_GESTURES had, so "select" (a held-in button) took gestures and every "gestures" node (the blenderui canvas) drew held in. Git saw no conflict: the two lines are apart. - After the merge with main: a pinch that begins on one of the new node controls (#38) does not press it (touch_test.c), and the blank lines between test_node_controls_validated / test_touch_and_trackpad / control_pos in test_nodes.py the web merge dropped. Tests: touch_test.c (sideways pan scrolls nothing and still reaches a binding, the keyboard's Shift on a vertical pan, a cancel dropping the held move, an up sending it, node controls, "gestures" and "select" being separate flags); blenderui headless (sideways pan over a vertical list, a vertical pan over a horizontal strip, the wheel still scrolling the strip). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PJcXdyFRKBApKEvWpKoMpY --- CHANGELOG.md | 6 ++ bindings/python/tests/test_nodes.py | 44 ++++----- bindings/rust/blenderui/src/events.rs | 3 +- bindings/rust/blenderui/src/vlist/element.rs | 3 + bindings/rust/blenderui/src/window.rs | 14 +-- bindings/rust/blenderui/tests/headless.rs | 63 +++++++++++++ docs/touch.md | 8 +- kit/intern/kit_core.c | 9 ++ kit/intern/kit_intern.h | 2 +- kit/intern/kit_touch.c | 8 +- tests/touch_test.c | 96 ++++++++++++++++++++ website/src/content/docs/concepts/touch.mdx | 8 +- 12 files changed, 228 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 676073db..87d3b22b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,12 @@ All notable changes to **blenderui** (BUI). The format follows `blenderui-sys`, D and Lua; Python and D read its text. - **Qt syntax:** containers drawn the Blender way (`QStackedWidget`, `QToolBox` as Blender panels, `QSplitter` with region edges to drag, `QToolBar`, `QDockWidget`, `QTabBar`, and `QMainWindow.addToolBar` / `addDockWidget` / `setStatusBar`); model/view (`QStandardItemModel`, `QStringListModel`, the abstract models, `QListView`, `QTreeView`, `QTableView` in Blender's tree list); real `QMessageBox` and `QInputDialog` dialogs; `QSettings` (an INI file with Qt's groups and arrays), `QKeySequence`, `QShortcut` and `QClipboard`; `blockSignals`, dynamic properties, `findChildren`, point mapping, `showEvent` / `hideEvent` and the descriptive properties on every widget. Actions shared by menus, tool buttons and shortcuts (`QAction` with visibility, data, tips and shortcuts bound on its window, `QActionGroup`, a real `QToolButton`, menu sections and corner widgets, `triggered` up to the menu bar), `QButtonGroup` ids, Qt's full layout API (`QBoxLayout` directions, `insert*`, `takeAt`, `replaceWidget`, `QSpacerItem`, grid cell queries and minimum sizes, `QFormLayout` rows), `QDialogButtonBox` (which `QMessageBox` and `QInputDialog` now use), `QAbstractSpinBox`, validators and `maxLength` on `QLineEdit`, spin box prefix / wrapping / special value text, slider tracking and page steps, combo box icons, models and popups, checkable `QGroupBox`, `QFrame` boxes and lines, a `QStatusBar` with permanent widgets, window states, opacity and size limits through the host, `startTimer`, `QFontMetrics`, `QPalette` from Blender's theme, `QCursor.pos`, `QScreen`, and the context-menu policies. Dates and times: `QDate`, `QTime`, `QDateTime` with Qt's format strings, `QDateTimeEdit` / `QDateEdit` / `QTimeEdit` as Blender's aligned number fields, and `QCalendarWidget`. Measured by the new `tools/qt_coverage.py` against Qt's headers: 57% of the core widget classes' methods (was 21% by the same count), 37% across all 142 classes. - **Kit:** a `select` node flag draws a button held in (Blender's `UI_SELECT`, for checked push buttons), and a separator with `vertical` draws its line across a row (`uiButSeparatorLine.is_vertical`). +- **Touch pans keep to their axis.** The sideways part of a pan no longer scrolls the kit's vertical scrollers (lists, + trees, grids, text areas, scroll views, the region): they read Shift + wheel as vertical, so those steps now reach + only bindings. A Shift held on the keyboard no longer turns a vertical pan sideways. In `blenderui`, a vertical + pan no longer scrolls a horizontal-only container, and the virtual list ignores the sideways part. A cancelled + gesture finger drops the move it held instead of sending it. Gestures over empty space reach the containers + under them (a `"gestures"` root with no widget under the fingers), as the wheel does. ### Fixed - **Python components:** `NodeEditor` follows `add`, `insert`, `remove`, `replace` and `clear` (its `nodes` and `links` went stale when diff --git a/bindings/python/tests/test_nodes.py b/bindings/python/tests/test_nodes.py index 2516b550..adf2df06 100644 --- a/bindings/python/tests/test_nodes.py +++ b/bindings/python/tests/test_nodes.py @@ -126,27 +126,6 @@ def test_value_field_and_view(): assert ed.zoom > z -def test_touch_and_trackpad(): - app, ed, a, b = make() - ctx = app.ctx - # two fingers spread: the view zooms about them; moved together: it pans - z = ed.zoom - ctx.touch(1, 0, 300.0, 300.0, 0) - ctx.touch(2, 0, 400.0, 300.0, 0) - assert not ctx.touch(1, 1, 270.0, 300.0, 0) # held until the other finger moves too - assert ctx.touch(2, 1, 430.0, 300.0, 0) - assert ed.zoom > z * 1.3, (z, ed.zoom) - px, z = ed.get("panx"), ed.zoom - ctx.touch(1, 1, 300.0, 300.0, 0) - ctx.touch(2, 1, 460.0, 300.0, 0) - assert abs(ed.get("panx") - (px + 30)) < 1e-3 and abs(ed.zoom - z) < 1e-5, (px, ed.get("panx")) - ctx.touch(1, 2, 300.0, 300.0, 0) - ctx.touch(2, 3, 460.0, 300.0, 0) - assert not ctx.touch(9, 1, 0.0, 0.0, 0) # an unknown contact - # a trackpad pinch zooms too; the editor does not rotate - z = ed.zoom - assert ctx.magnify(400, 300, -0.25, 0) and ed.zoom < z - assert not ctx.rotate(400, 300, 15.0, 0) def control_pos(ed, node, k): """The center of control ``k``: below the header and the outputs, in the padded block.""" gx, gy = node.location @@ -212,6 +191,29 @@ def test_node_controls_validated(): raise AssertionError("an unknown control kind was accepted") +def test_touch_and_trackpad(): + app, ed, a, b = make() + ctx = app.ctx + # two fingers spread: the view zooms about them; moved together: it pans + z = ed.zoom + ctx.touch(1, 0, 300.0, 300.0, 0) + ctx.touch(2, 0, 400.0, 300.0, 0) + assert not ctx.touch(1, 1, 270.0, 300.0, 0) # held until the other finger moves too + assert ctx.touch(2, 1, 430.0, 300.0, 0) + assert ed.zoom > z * 1.3, (z, ed.zoom) + px, z = ed.get("panx"), ed.zoom + ctx.touch(1, 1, 300.0, 300.0, 0) + ctx.touch(2, 1, 460.0, 300.0, 0) + assert abs(ed.get("panx") - (px + 30)) < 1e-3 and abs(ed.zoom - z) < 1e-5, (px, ed.get("panx")) + ctx.touch(1, 2, 300.0, 300.0, 0) + ctx.touch(2, 3, 460.0, 300.0, 0) + assert not ctx.touch(9, 1, 0.0, 0.0, 0) # an unknown contact + # a trackpad pinch zooms too; the editor does not rotate + z = ed.zoom + assert ctx.magnify(400, 300, -0.25, 0) and ed.zoom < z + assert not ctx.rotate(400, 300, 15.0, 0) + + def test_area_header(): picked = [] ed = NodeEditor() diff --git a/bindings/rust/blenderui/src/events.rs b/bindings/rust/blenderui/src/events.rs index a26d8e87..535e856a 100644 --- a/bindings/rust/blenderui/src/events.rs +++ b/bindings/rust/blenderui/src/events.rs @@ -69,7 +69,8 @@ pub struct ScrollWheelEvent { pub modifiers: Modifiers, /// Two fingers on a touch screen, not a wheel or trackpad: `delta` is then the pixels the /// fingers moved over [`WHEEL_LINE_PX`], so `delta * WHEEL_LINE_PX` keeps the content under - /// them. `modifiers.shift` marks the horizontal part of a pan. + /// them. `modifiers.shift` marks the horizontal part of a pan (and only that): a listener that + /// scrolls one way should ignore the other. pub touch: bool, } diff --git a/bindings/rust/blenderui/src/vlist/element.rs b/bindings/rust/blenderui/src/vlist/element.rs index 54db98f2..35779760 100644 --- a/bindings/rust/blenderui/src/vlist/element.rs +++ b/bindings/rust/blenderui/src/vlist/element.rs @@ -114,6 +114,9 @@ impl IntoElement for VariableList false, }; if pan && !stopped { - if e.dy != 0.0 { - self.wheel(app, (x, y), e.dy / WHEEL_LINE_PX, modifiers, touch); + if e.dy != 0.0 { // the keyboard's Shift does not turn the fingers' vertical sideways + self.wheel(app, (x, y), e.dy / WHEEL_LINE_PX, Modifiers { shift: false, ..modifiers }, touch); } if e.dx != 0.0 { // Shift + wheel: positive scrolls left, as the fingers move right self.wheel(app, (x, y), e.dx / WHEEL_LINE_PX, Modifiers { shift: true, ..modifiers }, touch); @@ -1506,15 +1506,17 @@ impl Window { } } - /// Scroll the innermost scroll container along `path` that can move. - fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool) { + /// Scroll the innermost scroll container along `path` that can move. A wheel scrolls a + /// container with no vertical range sideways; a touch pan (`exact_axis`) keeps to its axis, + /// the fingers having said which way they went. + fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool, exact_axis: bool) { let Some(f) = &self.frame else { return }; for key in path.iter().rev() { let Some(&i) = f.by_key().get(key) else { continue }; let n = &f.nodes[i]; let (rx, ry) = n.scroll_range; let (sx, sy) = n.scroll_pos; - let (nx, ny) = if horizontal || ry <= 0.0 { + let (nx, ny) = if horizontal || (ry <= 0.0 && !exact_axis) { ((sx + dy).clamp(0.0, rx), sy) } else { (sx, (sy + dy).clamp(0.0, ry)) diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/headless.rs index fb4d81f0..f0d26d7d 100644 --- a/bindings/rust/blenderui/tests/headless.rs +++ b/bindings/rust/blenderui/tests/headless.rs @@ -368,6 +368,7 @@ fn gestures_reach_listeners_and_pans_scroll() { thread_local! { static GESTURES: RefCell> = const { RefCell::new(Vec::new()) }; static WHEELS: RefCell> = const { RefCell::new(Vec::new()) }; + static SIDEWAYS: RefCell> = const { RefCell::new(Vec::new()) }; } struct Touchy; impl Render for Touchy { @@ -384,6 +385,7 @@ fn gestures_reach_listeners_and_pans_scroll() { })) .child( div().id("list").h(px(100.0)).overflow_y_scroll() + .on_scroll_wheel(|e, _, _| SIDEWAYS.with(|s| s.borrow_mut().push(e.modifiers.shift))) .child(div().id("row0").h(px(100.0))) .child(div().h(px(200.0))), ) @@ -429,6 +431,23 @@ fn gestures_reach_listeners_and_pans_scroll() { assert_eq!(wheels.len(), 1, "{wheels:?}"); assert!(wheels[0].1 && (wheels[0].0 * WHEEL_LINE_PX + 30.0).abs() < 1e-3, "{wheels:?}"); + // sideways over the list (it scrolls only vertically): it stays put, and the wheel + // listener sees the movement as a horizontal (Shift) touch step + let before = cx.element_bounds(id, "row0").unwrap().origin.y; + cx.simulate_touch(id, 1, down, 60.0, 150.0); + cx.simulate_touch(id, 2, down, 140.0, 150.0); + cx.simulate_touch(id, 1, mv, 20.0, 150.0); + cx.simulate_touch(id, 2, mv, 100.0, 150.0); + cx.simulate_touch(id, 1, up, 20.0, 150.0); + cx.simulate_touch(id, 2, up, 100.0, 150.0); + cx.draw(id); + assert_eq!(cx.element_bounds(id, "row0").unwrap().origin.y, before, "a sideways pan scrolls nothing vertically"); + let wheels = WHEELS.with(|w| w.borrow_mut().drain(..).collect::>()); + assert_eq!(wheels.len(), 1, "{wheels:?}"); + assert!(wheels[0].1, "{wheels:?}"); + assert_eq!(SIDEWAYS.with(|s| s.borrow_mut().drain(..).collect::>()), vec![false, true], + "the list's listener saw the vertical pan, then the sideways one with shift"); + // trackpad: magnify and rotate at the pointer, not from a touch screen cx.simulate_magnify(id, 100.0, 50.0, -0.2); cx.simulate_rotate(id, 100.0, 50.0, 15.0); @@ -438,3 +457,47 @@ fn gestures_reach_listeners_and_pans_scroll() { assert!(got[1].kind == GestureKind::Rotate && got[1].degrees == 15.0 && !got[1].touch); }); } + +/// A vertical touch pan does not scroll a container that only scrolls sideways (the wheel does, +/// as a convenience for mice without a horizontal wheel). +#[test] +fn vertical_touch_pan_keeps_a_horizontal_strip() { + struct Strip; + impl Render for Strip { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + body().m_0().child( + div().id("strip").w(px(200.0)).h(px(100.0)).overflow_x_scroll() + .child(div().id("wide").w(px(600.0)).h(px(100.0))), + ) + } + } + Application::headless().run(|cx| { + let id = open(cx, 200.0, 200.0, Strip).id; + cx.draw(id); + let x0 = cx.element_bounds(id, "wide").unwrap().origin.x; + let (down, mv, up) = (TouchPhase::Down, TouchPhase::Move, TouchPhase::Up); + // upwards: the direction that would scroll a container forwards + cx.simulate_touch(id, 1, down, 60.0, 80.0); + cx.simulate_touch(id, 2, down, 140.0, 80.0); + cx.simulate_touch(id, 1, mv, 60.0, 30.0); + cx.simulate_touch(id, 2, mv, 140.0, 30.0); + cx.simulate_touch(id, 1, up, 60.0, 30.0); + cx.simulate_touch(id, 2, up, 140.0, 30.0); + cx.draw(id); + assert_eq!(cx.element_bounds(id, "wide").unwrap().origin.x, x0, "a vertical pan moved the strip"); + // a sideways pan does scroll it, following the fingers + cx.simulate_touch(id, 1, down, 100.0, 50.0); + cx.simulate_touch(id, 2, down, 160.0, 50.0); + cx.simulate_touch(id, 1, mv, 60.0, 50.0); + cx.simulate_touch(id, 2, mv, 120.0, 50.0); + cx.simulate_touch(id, 1, up, 60.0, 50.0); + cx.simulate_touch(id, 2, up, 120.0, 50.0); + cx.draw(id); + let x1 = cx.element_bounds(id, "wide").unwrap().origin.x; + assert!((x0 - x1 - 40.0).abs() < 1e-3, "the strip follows the fingers: {x0} -> {x1}"); + // the mouse wheel still scrolls it sideways, as before + cx.simulate_scroll(id, 100.0, 50.0, -1); + cx.draw(id); + assert!(cx.element_bounds(id, "wide").unwrap().origin.x < x1, "the wheel no longer scrolls the strip"); + }); +} diff --git a/docs/touch.md b/docs/touch.md index b4806ede..2eff7c84 100644 --- a/docs/touch.md +++ b/docs/touch.md @@ -11,11 +11,12 @@ you; if you host the kit yourself, three calls feed it. |---|---| | **One** | It is the pointer: it moves there, presses, drags and releases, as the left mouse button does. When it lifts, the pointer leaves, so no hover highlight or tooltip stays behind. Pointer events made this way carry `BK_FROM_TOUCH` in their mods. | | **A second one** | Whatever the first finger was doing is cancelled, as Esc cancels a drag in Blender: a dragged value goes back, a pressed button is not clicked, a number field does not start editing. The two fingers are now a gesture. | -| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. | +| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. Kit scroll views only scroll vertically, so the sideways part of a pan moves nothing there. Bindings still get it as Shift + wheel, for Tk's ``. A Shift held on the keyboard doesn't turn a vertical pan sideways. | | **Two, spreading or pinching** | Magnify about their centre (`BK_magnify`). The node editor zooms. | | **Two, turning** | Rotate about their centre (`BK_rotate`). | | **After a gesture** | No finger becomes the pointer again until every finger has lifted, so lifting one finger of a pinch never clicks what is under the other. | | **More than two** | Followed, not used, up to ten contacts. | +| **Cancelled** | The platform took a contact back (`BK_TOUCH_CANCEL`): what it did as the pointer is undone, and a gesture finger's last, unsent move is dropped. A finger that lifts normally sends it. | Blender has no touch-screen input, so there is no source to follow for touch itself. One finger does what X11, Wayland compositors and Windows do for windows that don't know about touch. Two @@ -78,7 +79,10 @@ div().id("map").on_gesture(|e, window, cx| { other events. `touch` is `false` for a trackpad pinch or turn. A pan that no listener stops then scrolls the scroll container under it and reaches `on_scroll_wheel` listeners, with `ScrollWheelEvent::touch` set and `delta` in lines (`delta * WHEEL_LINE_PX` is the pixels the -fingers moved). Pages written for the wheel scroll with two fingers without any change; the +fingers moved). The horizontal part comes as a separate event with `modifiers.shift` set, so a +listener that scrolls one way should ignore the other. Unlike the wheel, a touch pan never +scrolls a container along the other axis: a vertical pan over a strip that only scrolls sideways +leaves it alone. Pages written for the wheel scroll with two fingers without any change; the virtual list and the data table use that to keep their rows under the fingers. `rsx!` takes `onGesture={...}`. Tests can drive it with `cx.simulate_touch(window, id, TouchPhase::Down, x, y)`, `simulate_magnify` and `simulate_rotate`. diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index a494e3ba..0902e0ed 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -2883,6 +2883,9 @@ static int in_BK_wheel(BKContext *ctx, int x, int y, int delta, int mods) if (!target && ctx->root && y >= ctx->header_h) { target = deepest(ctx->root, x, y); /* non-interactive area: let containers scroll */ } + /* the sideways steps of a touch pan (kit_touch.c): every kit scroller is vertical and reads + * Shift + wheel as vertical, so only bindings get them (Tk's ) */ + const bool sideways = (mods & (BK_FROM_TOUCH | BK_SHIFT)) == (BK_FROM_TOUCH | BK_SHIFT); for (BKNode *n = target; n; n = n->parent) { if (!NODE_ENABLED(n)) { continue; @@ -2892,6 +2895,9 @@ static int in_BK_wheel(BKContext *ctx, int x, int y, int delta, int mods) if (n == target) { bk_event(n, BK_EV_WHEEL, mods, &e); } + if (sideways) { + return 0; + } if (n->cls->wheel ? n->cls->wheel(n, &e) : ((n->cls->flags & CLS_VALUE) && bk_value_wheel(n, &e))) { @@ -3425,6 +3431,9 @@ int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float a, if (ctx->modal) { return 0; } + if (!target && ctx->root && y >= ctx->header_h) { + target = deepest(ctx->root, x, y); /* over no widget: its containers, as in_BK_wheel */ + } hide_tooltip(ctx); for (BKNode *n = target; n; n = n->parent) { if (!NODE_ENABLED(n)) { diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h index 57fe04d3..d2e6915e 100644 --- a/kit/intern/kit_intern.h +++ b/kit/intern/kit_intern.h @@ -402,8 +402,8 @@ enum { NF_ACTIVE_DEFAULT = 1 << 26, /* buttons: UI_BUT_ACTIVE_DEFAULT (drawn with the select colors) */ NF_DEFAULT_SET = 1 << 27, /* `defval` was set: by "default", or by the first "value" a widget got */ NF_BARE = 1 << 28, /* "bare": an HTML text field with no frame (CSS `border-style: none`) */ - NF_GESTURES = 1 << 29, /* "gestures": touch / trackpad gestures go to the host (BK_EV_GESTURE) */ NF_SELECT = 1 << 29, /* "select": held selected by the host (UI_SELECT: a checked push button) */ + NF_GESTURES = 1 << 30, /* "gestures": touch / trackpad gestures go to the host (BK_EV_GESTURE) */ }; #define BK_HTML(n) (((n)->flags & NF_HTML) != 0) diff --git a/kit/intern/kit_touch.c b/kit/intern/kit_touch.c index 6e64bd39..a10c98d2 100644 --- a/kit/intern/kit_touch.c +++ b/kit/intern/kit_touch.c @@ -154,9 +154,10 @@ static int pan_steps(BKContext *ctx, float dx, float dy, int mods) for (int i = 0; i < 8 && fabsf(t->rest_y) >= step; i++) { /* down: the content goes down */ const int d = t->rest_y > 0.0f ? 1 : -1; t->rest_y -= d * step; - r |= BK_wheel(ctx, t->start_x, t->start_y, d, mods); + r |= BK_wheel(ctx, t->start_x, t->start_y, d, mods & ~BK_SHIFT); } - for (int i = 0; i < 8 && fabsf(t->rest_x) >= step; i++) { /* Shift + wheel, as BK_scroll */ + /* Shift + wheel, as BK_scroll: with BK_FROM_TOUCH it reaches bindings only (in_BK_wheel) */ + for (int i = 0; i < 8 && fabsf(t->rest_x) >= step; i++) { const int d = t->rest_x > 0.0f ? 1 : -1; t->rest_x -= d * step; r |= BK_wheel(ctx, t->start_x, t->start_y, d, mods | BK_SHIFT); @@ -271,7 +272,8 @@ static int touch_update(BKContext *ctx, int i, int phase, int mods) t->held = bit; return 0; } - const int r = t->held ? gesture_update(ctx, tm) : 0; + /* an up sends the move it held; a cancel drops it, as it drops the rest of the contact */ + const int r = t->held && phase != BK_TOUCH_CANCEL ? gesture_update(ctx, tm) : 0; t->held = phase == BK_TOUCH_MOVE && t->held == bit ? bit : 0; if (phase == BK_TOUCH_MOVE) { return r; diff --git a/tests/touch_test.c b/tests/touch_test.c index a13c25af..976cd762 100644 --- a/tests/touch_test.c +++ b/tests/touch_test.c @@ -31,6 +31,7 @@ static BuiRaster *g_raster; static int g_clicks; static int g_warps; /* BK_EV_GESTURE as a host gets it */ +static int g_wheel_raw, g_wheel_raw_mods; /* BK_EV_WHEEL to "events" nodes */ static struct { int count[4]; /* by kind */ int mods, kind, x, y; @@ -54,6 +55,10 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d if (kind == BK_EV_CLICK) { g_clicks++; } + if (kind == BK_EV_WHEEL) { + g_wheel_raw++; + sscanf((const char *)ref, "%d", &g_wheel_raw_mods); + } if (kind == BK_EV_GESTURE && sscanf((const char *)ref, "%d %d %d %d", &g_gesture.mods, &g_gesture.kind, &g_gesture.x, &g_gesture.y) == 4 && @@ -376,6 +381,22 @@ static void test_node_editor_cancel(void) BK_touch(ctx, 2, BK_TOUCH_UP, sx + 60, sy + 60, 0); CHECK(BK_strs_count(editor, "items") == 1); + /* a node's checkbox: a tap toggles it, a pinch that begins on it does not */ + const char *b_ctl[] = {"o|Result|float", "c|Wire|0", "i|A|float|0.5"}; + BK_set_strs(b, "items", b_ctl, 3); + BK_render(ctx, g_raster, W, H, 1); + /* the control row: below the header and the output, in the padded block */ + const float cx = r[0] + 50 + 300 + 30; /* its left part: the node runs past the window */ + const float cy = r[1] + 50 + (20 + 5 + 22 + 2.5f + 10); + BK_touch(ctx, 1, BK_TOUCH_DOWN, cx, cy, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, cx, cy, 0); + CHECK(strcmp(BK_strs_get(b, "items", 1), "c|Wire|1") == 0); + BK_touch(ctx, 1, BK_TOUCH_DOWN, cx, cy, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, cx + 60, cy + 60, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, cx, cy, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, cx + 60, cy + 60, 0); + CHECK(strcmp(BK_strs_get(b, "items", 1), "c|Wire|1") == 0); + /* a pinch that begins on empty canvas keeps the selection (an unmoved box press deselects) */ BK_set_num(b, "selected", 1.0); BK_touch(ctx, 1, BK_TOUCH_DOWN, r[0] + 60.0f, r[1] + H - 40.0f, 0); @@ -429,6 +450,8 @@ static void test_gestures_property(void) first = first ? first : b; } BK_set_num(col, "gestures", 1.0); + /* its own flag: not another one's bit ("select", a held-in button, came in at the same time) */ + CHECK(BK_get_num(col, "gestures") == 1.0 && BK_get_num(col, "select") == 0.0); BKContext *ctx = context(col); int r0[4], r1[4]; BK_node_rect(first, r0); @@ -486,6 +509,77 @@ static void test_gestures_property(void) BK_node_free(col); } +/* Every kit scroller is vertical and reads Shift + wheel as vertical too: a sideways touch pan + * must not scroll them. Its steps still reach "events" nodes (Tk's ). */ +static void test_sideways_pan(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *first = NULL; + for (int i = 0; i < 60; i++) { + BKNode *b = BK_node_new("button"); + BK_set_str(b, "label", "Row"); + BK_set_num(b, "events", 1.0); /* each widget bound, as Tk programs do */ + BK_node_add(col, b, -1); + first = first ? first : b; + } + BKContext *ctx = context(col); + int r0[4], r1[4]; + BK_node_rect(first, r0); + g_wheel_raw = 0; + /* the fingers go 150 px left, Shift held on the keyboard as well */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 250, 200, BK_SHIFT); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 300, 200, BK_SHIFT); + for (int i = 1; i <= 10; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 250 - i * 15, 200, BK_SHIFT); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 300 - i * 15, 200, BK_SHIFT); + } + BK_touch(ctx, 1, BK_TOUCH_UP, 100, 200, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 150, 200, 0); + BK_render(ctx, g_raster, W, H, 1); + BK_node_rect(first, r1); + CHECK(r1[1] == r0[1]); /* nothing scrolled */ + CHECK(g_wheel_raw > 0 && (g_wheel_raw_mods & BK_SHIFT)); /* the binding still sees it */ + /* and the keyboard's Shift does not make a vertical pan sideways */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 180, 200, BK_SHIFT); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 220, 200, BK_SHIFT); + for (int i = 1; i <= 10; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 180, 200 - i * 12, BK_SHIFT); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 220, 200 - i * 12, BK_SHIFT); + } + BK_touch(ctx, 1, BK_TOUCH_UP, 180, 80, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 220, 80, 0); + BK_render(ctx, g_raster, W, H, 1); + BK_node_rect(first, r1); + CHECK(r1[1] < r0[1] - 60); + BK_context_free(ctx); + BK_node_free(col); +} + +/* A cancelled gesture finger drops the move it held for its partner. */ +static void test_cancel_discards_held_move(void) +{ + BKNode *col = BK_node_new("column"); + BK_set_num(col, "gestures", 1.0); + BKContext *ctx = context(col); + memset(&g_gesture, 0, sizeof(g_gesture)); + BK_touch(ctx, 1, BK_TOUCH_DOWN, 150, 100, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 250, 100, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, 150, 160, 0); /* held: waits for finger 2 */ + BK_touch(ctx, 2, BK_TOUCH_CANCEL, 250, 100, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, 150, 160, 0); + CHECK(g_gesture.count[BK_GESTURE_PAN] == 0 && g_gesture.count[BK_GESTURE_MAGNIFY] == 0 && + g_gesture.count[BK_GESTURE_ROTATE] == 0); + /* a finger that lifts normally still sends what it held */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 150, 100, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 250, 100, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, 150, 160, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, 150, 160, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 250, 100, 0); + CHECK(g_gesture.count[BK_GESTURE_PAN] == 1); + BK_context_free(ctx); + BK_node_free(col); +} + /* -- custom nodes -- */ static void test_custom_default(void) @@ -614,6 +708,8 @@ int main(void) test_node_editor_cancel(); test_drag_at_edge(); test_gestures_property(); + test_sideways_pan(); + test_cancel_discards_held_move(); test_custom_default(); test_custom_raw(); test_capacity(); diff --git a/website/src/content/docs/concepts/touch.mdx b/website/src/content/docs/concepts/touch.mdx index 25d60e16..0373bf5d 100644 --- a/website/src/content/docs/concepts/touch.mdx +++ b/website/src/content/docs/concepts/touch.mdx @@ -18,11 +18,12 @@ you; if you host the kit yourself, three calls feed it. |---|---| | **One** | It is the pointer: it moves there, presses, drags and releases, as the left mouse button does. When it lifts, the pointer leaves, so no hover highlight or tooltip stays behind. Pointer events made this way carry `BK_FROM_TOUCH` in their mods. | | **A second one** | Whatever the first finger was doing is cancelled, as Esc cancels a drag in Blender: a dragged value goes back, a pressed button is not clicked, a number field does not start editing. The two fingers are now a gesture. | -| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. | +| **Two, moving together** | Pan. The scroll view or region under them scrolls, and the content follows the fingers. The node editor pans its view. Kit scroll views only scroll vertically, so the sideways part of a pan moves nothing there. Bindings still get it as Shift + wheel, for Tk's ``. A Shift held on the keyboard doesn't turn a vertical pan sideways. | | **Two, spreading or pinching** | Magnify about their centre (`BK_magnify`). The node editor zooms. | | **Two, turning** | Rotate about their centre (`BK_rotate`). | | **After a gesture** | No finger becomes the pointer again until every finger has lifted, so lifting one finger of a pinch never clicks what is under the other. | | **More than two** | Followed, not used, up to ten contacts. | +| **Cancelled** | The platform took a contact back (`BK_TOUCH_CANCEL`): what it did as the pointer is undone, and a gesture finger's last, unsent move is dropped. A finger that lifts normally sends it. | Blender has no touch-screen input, so there is no source to follow for touch itself. One finger does what X11, Wayland compositors and Windows do for windows that don't know about touch. Two @@ -85,7 +86,10 @@ div().id("map").on_gesture(|e, window, cx| { other events. `touch` is `false` for a trackpad pinch or turn. A pan that no listener stops then scrolls the scroll container under it and reaches `on_scroll_wheel` listeners, with `ScrollWheelEvent::touch` set and `delta` in lines (`delta * WHEEL_LINE_PX` is the pixels the -fingers moved). Pages written for the wheel scroll with two fingers without any change; the +fingers moved). The horizontal part comes as a separate event with `modifiers.shift` set, so a +listener that scrolls one way should ignore the other. Unlike the wheel, a touch pan never +scrolls a container along the other axis: a vertical pan over a strip that only scrolls sideways +leaves it alone. Pages written for the wheel scroll with two fingers without any change; the virtual list and the data table use that to keep their rows under the fingers. `rsx!` takes `onGesture={...}`. Tests can drive it with `cx.simulate_touch(window, id, TouchPhase::Down, x, y)`, `simulate_magnify` and `simulate_rotate`.