diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 345937e4..e08b3207 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; Blender's screen layout (`kit/intern/screen`, ported from `editors/screen`: areas on a graph of shared edges that split, join, dock and resize, regions that resize, hide and flip, saved as JSON); 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; Blender's screen layout (`kit/intern/screen`, ported from `editors/screen`: areas on a graph of shared edges that split, join, dock and resize, regions that resize, hide and flip, saved as JSON); 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). Touch screens and trackpad gestures live in the kit, not the hosts: `kit/intern/kit_touch.c` is one state machine (Android's model: taps, long presses, scrolls past the touch slop, a second finger's pan, pinch and turn as Blender's `MOUSEPAN` / `MOUSEZOOM` / `MOUSEROTATE`) with the fling in `kit_fling.c` (`VelocityTracker`, `OverScroller`), and every host (Win32 `WM_POINTER`, X11 XInput 2, Wayland `wl_touch` and pointer gestures, Cocoa's magnify and rotate, Android) only forwards contacts to `BK_touch` and trackpad gestures to `BK_magnify` / `BK_rotate` ([docs/touch.md](docs/touch.md)). 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 33f34d2c..7b98c8cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **Touch screens and trackpad gestures, one model on every platform.** The kit turns a host's contacts into what its widgets know (`BK_touch(ctx, id, BK_TOUCH_DOWN/MOVE/UP/CANCEL, x, y, time_ms, mods)`, `kit/intern/kit_touch.c`), with Android's numbers: a finger on a widget that drags (sliders, fields, scrollbars, the node editor) is the pointer at once; anywhere else a tap is a click, half a second held still is the context menu (a right press), and a move past the 8 dp touch slop scrolls exactly as far as the finger went (from just past the slop) and flings on along `OverScroller`'s curve. A second finger cancels what the first did (as `BK_cancel`) and the two pan (Blender's `MOUSEPAN`), magnify (`MOUSEZOOM`) and rotate (`MOUSEROTATE`) about their centre. Trackpad pinches and turns come in through `BK_magnify` / `BK_rotate` (GHOST's `GHOST_kTrackpadEventMagnify` / `Rotate`); custom nodes get them as `BK_CUSTOM_MAGNIFY` / `ROTATE` and "events" nodes as `BK_EV_GESTURE`, and events made from a finger carry `BK_FROM_TOUCH`. `BK_custom_set_touch(node, BK_TOUCH_MODE_SCROLL / POINTER / RAW)` says what a finger does on a custom node (RAW: every contact as `BK_CUSTOM_TOUCH`; the Dear ImGui adapter uses POINTER). In the node editor two fingers pan the view and a pinch zooms about them. Hosts only forward: Windows through `WM_POINTER` (touch only; no promoted mouse clicks or press-and-hold right click; `WM_POINTERCAPTURECHANGED` cancels), X11 through XInput 2.2 touch (libXi loaded at run time) and XInput 2.4 pinches, Wayland through `wl_touch` and `zwp_pointer_gestures_v1`, macOS through `magnifyWithEvent:` / `rotateWithEvent:`, and Android hands every pointer over (its own touch code is gone). Rust: `on_pan(|e: &PanEvent, ..|)` (before the scroll; `cx.stop_propagation()` takes the drag), `on_pinch(|e: &PinchEvent, ..|)`, `on_rotate(|e: &RotateEvent, ..|)` (rsx `onPan` / `onPinch` / `onRotate`) and, headless, `App::simulate_touch`, `simulate_magnify`, `simulate_rotate`. Details that a plain mapping gets wrong: a two-finger update waits until both fingers moved, so a pan does not wobble the zoom or angle; a finger that lands on a fling stops it without clicking; a finger's double tap may land one widget unit away (the mouse's 4 px is too tight); a finger's drag never warps the system pointer; no hover stays behind a lifted finger; `BK_cancel` now cancels an unmoved press too (a box select a second finger interrupted deselects nothing) and every contact, and a window that loses the focus cancels them; a cancelled link drag in the node editor puts back the link it took off an input (`node_link_cancel`), and `Delete` / `X` do nothing mid link or value drag. Rust's `ScrollWheelEvent::position` now comes from the event (a finger's scroll moves no pointer), and a diagonal finger scroll no longer loses an axis. Docs: [docs/touch.md](docs/touch.md). **C API changes:** the `BK_window_wm(win, "touch_drag", 1, 0)` key is removed; call `BK_custom_set_touch(node, BK_TOUCH_MODE_POINTER)` on the custom node instead. A raw `BK_EV_WHEEL` event's text is now `"mods button phase x y"` (where the scroll is, relative to the node). - **Android scrolling the way Android does it, a rubber band past the ends, and an opt-in smooth wheel.** The touch fling is a port of Android's: `VelocityTracker`'s least squares fit of the last 100 ms of touches (batched touches included) and `OverScroller`'s spline fling with its friction (`kit/intern/kit_fling.c`), not an exponential decay on a two-point velocity; a drag starts from just past the touch slop, so the content no longer jumps by it. New: `BK_scroll_phase` (`BK_SCROLL_WHEEL`/`DRAG`/`FLING`/`END`) tells a view how a scroll came, and Rust's `ScrollWheelEvent::phase` carries it. `Options::overscroll` (off by default, as in Blender) makes a list stretch past either end with UIScrollView's curve while the finger drags (a fling's momentum stretches it less) and spring back when it lifts; the Android demo turns it on. `Options::smooth_wheel` (off by default) eases a wheel notch in over a few frames, as macOS does, instead of scrolling at once. A scroll now moves a list exactly as far as asked in both directions: it used to be turned into a position through estimated heights, so going up through items not yet measured moved the content by whatever the estimates were off by (10 % too far in a test from the middle of 200 000 messages, while down was exact); the list now walks the distance item by item from the anchor at the next layout, measuring what it passes (`view/relative.rs`). The Android Rust demo's chat is a million messages. Checked on a 90 Hz phone: dragging past the top stretches the first message about 400 px and it settles back at rest. - **Android runs at the display's fastest refresh rate.** Some phones (ColorOS) held the app to 60 Hz on a 90 Hz panel. `kit_window_android.c` now names the fastest mode (at the current size, whatever the panel offers) on the window with `preferredDisplayModeId` / `preferredRefreshRate`, in JNI from the activity's `onWindowFocusChanged` callback (it runs on the UI thread, so no Java class is needed), and also votes with `ANativeWindow_setFrameRate`. An animating pass that drew nothing no longer spins the loop (it waits `IDLE_FRAME_MS`). `-DBUI_ANDROID_FRAME_LOG` logs frames and CPU time per second to logcat (tag `BUI`). Checked on a 90 Hz phone: 60 Hz before, 90 Hz after. - **Inline layout, as browsers do it.** A block's inline content is laid out in lines by an algorithm of its own (`tree/inline.rs`, `layout/inline.rs`, `linebreak.rs`), not as a wrapping flex row of words. The builder collects the content into one string (white space collapsing across elements; a segment break removed between ideographs or next to U+200B; only space, tab, newline, CR and FF collapsible), finds its line-break opportunities once with UAX #14 (`unicode-linebreak`), tailored by `word-break: break-all | keep-all`, `line-break: anywhere | loose | normal | strict` (small kana, iteration marks), `hyphens` and `overflow-wrap` (a last resort), and the `white-space` of the nearest common ancestor at an element boundary; an atomic inline breaks as an ideograph. Lines fill greedily; spaces at a line's end hang (`pre-wrap`) or go (collapsible), `break-spaces` breaks after each one, `pre` keeps them; a line box is its strut and its items on the baseline, or at its top, middle or bottom (`vertical-align`); `text-align: start | end` (by `direction`), `justify` (the free space shared over the spaces), `justify-all`, `match-parent` and `text-align-last`; preserved tabs advance to the next tab stop (`tab-size`) from the line's start; a soft hyphen breaks and shows a hyphen there; `text-wrap: balance` evens a paragraph of up to 6 lines; `text-autospace` puts 1/8 em between ideographs and Latin letters or digits; `text-transform: full-width | full-size-kana`. Inline boxes with margin, border and padding take room at their edges and paint each line's fragment (background, borders). The `ch` unit is the font's "0"; the root's background paints under negative z-index layers (it is the canvas's). Han characters in a Japanese or Korean paragraph keep its faces word by word (`BUI_FONT_HAN_JA` / `BUI_FONT_HAN_KO` text flags). Web-platform-tests: **4,860 of 7,135 that run pass (68.1%)** (from 1,978 of 6,172), now with the scripted tests running (below). diff --git a/CMakeLists.txt b/CMakeLists.txt index 8db9c0c8..ea148f2f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -122,6 +122,10 @@ if(BUI_BUILD_TESTS) if(BUI_BENCH_NO_IME) target_compile_definitions(bui_ime_bench PRIVATE BENCH_NO_IME) endif() + # touch screens: taps, scrolls and flings, a second finger's gesture, raw contacts, cancels + 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 18bf05f5..49c0e18a 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ If you're starting fresh in Python, the Blender components are the friendliest. - 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. - **Blender's screen layout**: areas you resize by dragging the edges between them (Shift moves aligned edges, Ctrl snaps), split, join and dock by dragging a corner, swap with Ctrl, maximize with Ctrl+Space; headers, toolbars and sidebars that resize, hide and flip; panels that reorder and pin; the arrangement saved and restored as JSON ([Screens, areas and regions](https://bui.preetham.top/docs/concepts/screens/)). +- **Touch screens and trackpad gestures**, one model on every platform: a tap clicks, a drag scrolls exactly with the finger and flings on (Android's `OverScroller`), a long press opens the context menu, and two fingers pan, pinch and turn (Blender's `MOUSEPAN` / `MOUSEZOOM` / `MOUSEROTATE`); trackpad pinches and turns reach the same places. Windows (`WM_POINTER`), X11 (XInput 2), Wayland, macOS trackpads and Android forward to the kit; Rust has `on_pan`, `on_pinch` and `on_rotate` ([docs/touch.md](docs/touch.md)). - **Blender's Dark and Light themes**, switchable at run time, and **your own themes** from a JSON file (gpui-kit's format, Blender's color names, per-widget corners and borders; [docs/theming.md](docs/theming.md)). ### Python @@ -250,7 +251,7 @@ If you're starting fresh in Python, the Blender components are the friendliest. - **Damage rendering**: an idle UI costs 0% CPU, and a hover redraws only the widget it touches. - **Opt-in GPU renderer** (Direct3D 11 on Windows, OpenGL 3.3 on Linux), modeled on Blender's instanced widget drawing. It draws the same pixels as the CPU raster. - **GPU effects**: your own GLSL pixel shader in a canvas (`BK_ITEM_EFFECT`, Rust `Painter::effect`), run on Direct3D 11 and OpenGL in paint order with an image as the fallback; the compile log comes back as a string. -- **Android** (`platform/android`, [docs/android.md](docs/android.md)): the kit's window host on a `NativeActivity`, so C, Lua and Rust apps run as on a desktop (`Application::run`, `bui.open`); damage-driven rendering, touch scrolling and the soft keyboard; `python platform/android/build.py [--lua DIR | --rust CRATE]` makes a signed APK of 1 to 2 MB. Run on an emulator; the arm64 builds were not run. +- **Android** (`platform/android`, [docs/android.md](docs/android.md)): the kit's window host on a `NativeActivity`, so C, Lua and Rust apps run as on a desktop (`Application::run`, `bui.open`); damage-driven rendering, [touch](docs/touch.md) (taps, flings, long presses, pinches) and the soft keyboard; `python platform/android/build.py [--lua DIR | --rust CRATE]` makes a signed APK of 1 to 2 MB. Run on an emulator; the arm64 builds were not run. - **GPU render targets**: an effect can draw into a texture (`RenderTarget`, `BUI_target_create`, `Painter::effect_to`, `Rgba8` / `Rgba16F` / `Rgba32F`) and sample it in a later pass, so simulations can feed back on themselves. Tested on Direct3D 11; the OpenGL backend has the same code and has not been run. - In the benchmark, **2–4× less CPU per frame than gpui-fast**, with **less RAM** and a **~5 ms first frame**. - **Blender's text**: Inter (Blender's UI font) is embedded and rendered with FreeType the way Blender renders it, so text looks the same on every platform. On the GPU, glyphs are drawn from their outlines with [Slug](https://github.com/EricLengyel/Slug), falling back to a per-glyph atlas like Blender's. diff --git a/bindings/d/source/bui/context.d b/bindings/d/source/bui/context.d index 560b8a3a..65525330 100644 --- a/bindings/d/source/bui/context.d +++ b/bindings/d/source/bui/context.d @@ -12,10 +12,12 @@ module bui.context; import core.stdc.stdlib : cfree = free, malloc; import core.stdc.string : memcpy; +import core.memory : GC; import bui.errors : BuiException; import bui.gpu : BuiRaster; import bui.internal.callback : CallbackBox; +import bui.internal.collected : deferFree, freeCollected; import bui.internal.refs : ensureRefHooks; import bui.internal.util : cslice, cstr; import bui.kit; @@ -50,6 +52,9 @@ struct ImeState { } /// One instance of a node tree. +/// What a collected context calls back: nothing (every callback NULL, which the kit checks). +private __gshared BKHost noHost; + final class Context { /// The C handle, for calls into the raw `bui.kit` API. BKContext* handle; @@ -71,6 +76,7 @@ final class Context { throw new BuiException("Context", "no root node"); } ensureRefHooks(); + freeCollected(); rootNode = root; handle = BK_context_new(root.handle); if (handle is null) { @@ -88,7 +94,17 @@ final class Context { } ~this() { - windows = 0; // only reachable at teardown; a finalizer cannot throw + if (GC.inFinalizer) { + // the root and the host handlers may be gone already (bui.internal.collected): the + // kit calls no D code for this context any more, and frees it at a safe point + if (handle !is null) { + BK_context_set_host(handle, &noHost); + deferFree(handle, true); + handle = null; + } + return; + } + windows = 0; free(); } @@ -169,6 +185,7 @@ final class Context { } auto c = ctx(); check(); + freeCollected(); const n = BK_render(c, raster, width, height, full ? 1 : 0); check(); return n; @@ -256,6 +273,34 @@ final class Context { return changed; } + /// A touch screen contact: `phase` is `BK_TOUCH_DOWN` / `MOVE` / `UP` / `CANCEL`, `timeMs` + /// the event's own time on any monotonic clock (<= 0: now). + bool touch(int id, int phase, float x, float y, double timeMs = 0, int mods = 0) { + auto c = ctx(); + check(); + const changed = BK_touch(c, id, phase, x, y, timeMs, mods) != 0; + check(); + return changed; + } + + /// A trackpad pinch about `x`, `y`: `delta` is the scale change (0.1 = 10% larger). + 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; + } + + /// A trackpad turn about `x`, `y`, in degrees (> 0 counter-clockwise). + 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 02b2c2e8..cdba0dd7 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 host's id of the contact and its `BK_TOUCH_*` phase. + int touchId; + int touchPhase; + /// `BK_CUSTOM_MAGNIFY`: the scale change (0.1 = 10% larger). + float magnify; + /// `BK_CUSTOM_ROTATE`: degrees, > 0 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,11 @@ void setCursor(Node node, int cursor) { BK_custom_set_cursor(requireHandle(node, "Custom.setCursor", "no custom node"), cursor); } +/// What a finger that lands on the node does (`BK_TOUCH_MODE_*`; `BK_TOUCH_MODE_SCROLL` by default). +void setTouch(Node node, int mode) { + BK_custom_set_touch(requireHandle(node, "Custom.setTouch", "no custom node"), mode); +} + /// Non-zero while the custom node has keyboard focus. bool hasFocus(Node node) { return BK_custom_has_focus(requireHandle(node, "Custom.hasFocus", "no custom node")) != 0; diff --git a/bindings/d/source/bui/internal/collected.d b/bindings/d/source/bui/internal/collected.d new file mode 100644 index 00000000..57530193 --- /dev/null +++ b/bindings/d/source/bui/internal/collected.d @@ -0,0 +1,69 @@ +/* Native objects whose D wrappers the garbage collector finalized, freed later at a safe point. + * + * The GC finalizes in no particular order, so a finalizer must not reach any other D object: a + * handler store, what a wrapper keeps alive, a custom node's handlers. Freeing a native node or + * context there also calls back into D through the kit's hooks (BK_set_ref_hooks: GC.addRoot / + * removeRoot, which a finalizer may not call). So a finalizer only cuts the native object's links + * to D and queues it here, on a lock-free list in malloc'd memory (allowed in a finalizer, from + * whichever thread collects); `freeCollected` frees the queue from ordinary code, contexts before + * nodes (a context goes before its root). Whatever is still queued when the program ends is left + * to the process teardown. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ +module bui.internal.collected; + +import core.atomic : atomicExchange, atomicLoad, cas; +import core.stdc.stdlib : cfree = free, malloc; + +import bui.kit; + +private struct Entry { + void* handle; + bool context; /* a BKContext, else a BKNode */ + Entry* next; +} + +private shared(Entry*) g_queue; + +/// Queue a native node or context for `freeCollected`. Finalizer-safe: no GC memory, no D calls. +package(bui) void deferFree(void* handle, bool context) nothrow @nogc { + auto e = cast(Entry*) malloc(Entry.sizeof); + if (e is null) { + return; /* no memory: the native object leaks, which beats a crash */ + } + e.handle = handle; + e.context = context; + shared(Entry*) old; + do { + old = atomicLoad(g_queue); + e.next = cast(Entry*) old; + } while (!cas(&g_queue, old, cast(shared(Entry*)) e)); +} + +/// Free what finalizers queued: every context, then every node. Call from ordinary code only. +package(bui) void freeCollected() { + auto all = cast(Entry*) atomicExchange(&g_queue, cast(shared(Entry*)) null); + foreach (pass; 0 .. 2) { + const contexts = pass == 0; + for (auto e = all; e !is null; e = e.next) { + if (e.context != contexts || e.handle is null) { + continue; + } + if (contexts) { + BK_context_free(cast(BKContext*) e.handle); + } + else { + auto node = cast(BKNode*) e.handle; + if (auto parent = BK_node_parent(node)) { + BK_node_remove(parent, node); + } + BK_node_free(node); + } + } + } + while (all !is null) { + auto next = all.next; + cfree(all); + all = next; + } +} diff --git a/bindings/d/source/bui/kit.d b/bindings/d/source/bui/kit.d index a686c152..f86fe69e 100644 --- a/bindings/d/source/bui/kit.d +++ b/bindings/d/source/bui/kit.d @@ -34,6 +34,7 @@ enum BK_ALT = 4; enum BK_BUTTON1 = 8; enum BK_BUTTON2 = 16; enum BK_BUTTON3 = 32; +enum BK_FROM_TOUCH = 64; /* the kit's own: raw events made from touch contacts (BK_touch) */ /* ---- cursors ------------------------------------------------------------- */ enum BK_CURSOR_DEFAULT = 0; @@ -74,6 +75,10 @@ enum BK_EV_KEYRELEASE = 20; enum BK_EV_AREA = 21; /* a screen's areas: a = child index, b = BK_AREA_* */ enum BK_EV_MOVE = 22; /* a panel moved: a = old index, b = new index */ enum BK_EV_RESIZE = 23; /* a region resized, hidden or shown: a = size, b = hidden */ +/* a pinch or turn over an "events" node: ref = "mods kind x y" (kind BK_GESTURE_*), a = amount */ +enum BK_EV_GESTURE = 26; +enum BK_GESTURE_MAGNIFY = 1; +enum BK_GESTURE_ROTATE = 2; /* ---- geometry ------------------------------------------------------------ */ enum BK_GEOM_NONE = 0; @@ -133,6 +138,20 @@ 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; /* one contact (BK_TOUCH_MODE_RAW): touch_id, touch_phase, x, y */ +enum BK_CUSTOM_MAGNIFY = 11; /* magnify: a pinch about x, y */ +enum BK_CUSTOM_ROTATE = 12; /* rotate: a turn about x, y */ + +/* what a finger that lands on a custom node does (BK_custom_set_touch) */ +enum BK_TOUCH_MODE_SCROLL = 0; +enum BK_TOUCH_MODE_POINTER = 1; +enum BK_TOUCH_MODE_RAW = 2; + +/* ---- touch contacts (BK_touch) ------------------------------------------- */ +enum BK_TOUCH_DOWN = 0; +enum BK_TOUCH_MOVE = 1; +enum BK_TOUCH_UP = 2; +enum BK_TOUCH_CANCEL = 3; /* ---- IME ----------------------------------------------------------------- */ enum BK_IME_COMPOSITION_START = 0; @@ -277,6 +296,10 @@ struct BKCustomEvent { float wheel_y; const(char)* text; const(char)* keysym; + int touch_id; + int touch_phase; + float magnify; + float rotate; } alias BKCustomEventFn = @@ -576,6 +599,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 mode); int BK_custom_has_focus(BKNode* node); BKContext* BK_node_context(const(BKNode)* node); @@ -618,6 +642,9 @@ int BK_release(BKContext* ctx, int x, int y, int mods); int BK_motion(BKContext* ctx, int x, int y, int mods); 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_touch(BKContext* ctx, int id, int phase, float x, float y, double time_ms, 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); 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); diff --git a/bindings/d/source/bui/node.d b/bindings/d/source/bui/node.d index 9960a577..2df3d6d9 100644 --- a/bindings/d/source/bui/node.d +++ b/bindings/d/source/bui/node.d @@ -17,8 +17,11 @@ */ module bui.node; +import core.memory : GC; + import bui.errors : BuiException; import bui.image : Image; +import bui.internal.collected : deferFree, freeCollected; import bui.internal.refs : ensureRefHooks; import bui.internal.util : cslice, cstr; import bui.kit; @@ -31,11 +34,12 @@ struct NodeEvent { Node node; /// `BK_EV_*`. int kind; - /// The kit's payload: a callback object, a C string for raw key events, or null. + /// The kit's payload: a callback object, a C string for raw events and gestures, or null. void* ref_; double a; double b; - /// The key text for `BK_EV_KEY` / `BK_EV_KEYRELEASE`, else empty. + /// The text of a raw event (`BK_EV_PRESS` .. `BK_EV_WHEEL`, `BK_EV_KEYRELEASE`) or a gesture + /// (`BK_EV_GESTURE`: "mods kind x y"), else empty. const(char)[] text; } @@ -257,6 +261,7 @@ final class Node { /// Create a node of `type` (`"frame"`, `"button"`, `"slider"`, ...). this(string type) { ensureRefHooks(); + freeCollected(); handle = BK_node_new(cstr(type)); if (handle is null) { throw new BuiException("Node", "unknown node type '" ~ type ~ "'"); @@ -278,9 +283,27 @@ final class Node { } ~this() { + if (GC.inFinalizer) { + collected(); + return; + } free(); } + /// The GC finalized this wrapper (see bui.internal.collected): the D objects it reaches may be + /// gone already, so only native links are cut here and the node is freed at the next safe + /// point. A borrowed wrapper's node is the kit's. + private void collected() { + auto h = handle; + if (h is null || !owned) { + return; + } + handle = null; + BK_node_set_ref(h, null); + BK_custom_set(h, null, null); /* a custom node's handlers are D objects; 0 for other nodes */ + deferFree(h, false); + } + /// Free the C node. A rooted tree's C-owned children are freed by the kit; /// wrapper-owned children are detached and live on until their wrappers go. /// A borrowed wrapper only drops its handlers here; the kit owns its node. @@ -460,8 +483,8 @@ final class Node { /// away. Only an owned node reaches here; a borrowed wrapper has no say /// over the kit's native node. A detached D-owned child survives the free, /// so it takes its own subtree's entries into its own store while entries - /// for the freed tree go away. No allocation: this also runs from the GC - /// finalizer. + /// for the freed tree go away. Not from a GC finalizer: that path is + /// `collected`, which reaches no D object. private void dropHandlers(BKNode* h) { auto owner = handlerOwner(); auto store = owner is null ? &store_ : &owner.store_; @@ -848,7 +871,8 @@ final class Node { return; } const(char)[] text; - if (kind == BK_EV_KEY || kind == BK_EV_KEYRELEASE) { + if ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || 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/d/tests/run.d b/bindings/d/tests/run.d index c10d3f20..72cd790f 100644 --- a/bindings/d/tests/run.d +++ b/bindings/d/tests/run.d @@ -30,6 +30,8 @@ void main() { testTree(); testMenus(); testCustom(); + testTouch(); + testCollected(); testHostErrors(); testTheme(); testCss(); @@ -349,6 +351,112 @@ private void testCustom() { root.free(); } +/* Touch screens and trackpad gestures: a tap clicks, a spread over an "events" node and a + * trackpad pinch are BK_EV_GESTURE, a raw custom node gets its contacts as they are. */ +private void testTouch() { + import std.conv : to; + import std.string : split; + + auto root = new Node("column"); + int clicks; + auto button = new Node("button"); + button.set("text", "Go"); + button.onClick((NodeEvent) { + ++clicks; + }); + root.add(button); + auto pad = new Node("canvas"); + pad.set("events", 1); + pad.set("height", 200); + string[] gestures; + double[] amounts; + pad.on(BK_EV_GESTURE, (NodeEvent e) { + gestures ~= e.text.idup; + amounts ~= e.a; + }); + root.add(pad); + int[3][] touches; + auto raw = new Node("custom"); + setCustom(raw, CustomHandlers( + (Node, CustomEvent e) { + if (e.type == BK_CUSTOM_TOUCH) { + touches ~= [e.touchId, e.touchPhase, e.mods]; + } + return e.type == BK_CUSTOM_TOUCH ? 1 : 0; + }, + null, null, null, 200, 100)); + setTouch(raw, BK_TOUCH_MODE_RAW); + root.add(raw); + + auto context = new Context(root); + auto raster = new Raster(400, 500); + context.render(raster, true); + + const b = button.rect(); + const bx = b[0] + b[2] / 2, by = b[1] + b[3] / 2; + context.touch(1, BK_TOUCH_DOWN, bx, by); + check(clicks == 0, "touch: no click before the finger lifts"); + context.touch(1, BK_TOUCH_UP, bx + 2, by); + check(clicks == 1, "touch: a tap clicks"); + + const p = pad.rect(); + const cx = p[0] + p[2] / 2, cy = p[1] + p[3] / 2; + context.touch(2, BK_TOUCH_DOWN, cx - 20, cy); + context.touch(3, BK_TOUCH_DOWN, cx + 20, cy); + foreach (i; 1 .. 4) { + context.touch(2, BK_TOUCH_MOVE, cx - 20 - 10 * i, cy); + context.touch(3, BK_TOUCH_MOVE, cx + 20 + 10 * i, cy); + } + context.touch(2, BK_TOUCH_UP, cx - 50, cy); + context.touch(3, BK_TOUCH_UP, cx + 50, cy); + check(gestures.length == 3, "touch: a spread is three magnify gestures"); + const fields = gestures[0].split(" "); + check((fields[0].to!int & BK_FROM_TOUCH) != 0, "touch: gesture mods carry BK_FROM_TOUCH"); + check(fields[1].to!int == BK_GESTURE_MAGNIFY && amounts[0] > 0, "touch: a spread magnifies"); + check(fields[2].to!int == cx - p[0] && fields[3].to!int == cy - p[1], "touch: gesture centre"); + + gestures = null; + amounts = null; + check(context.magnify(cx, cy, 0.25f), "magnify changed something"); + check(gestures.length == 1 && amounts[0] == 0.25f, "magnify: a gesture event"); + check(gestures[0] == "0 1 " ~ (cx - p[0]).to!string ~ " " ~ (cy - p[1]).to!string, + "magnify: gesture text"); + + const r = raw.rect(); + context.touch(4, BK_TOUCH_DOWN, r[0] + 10, r[1] + 10); + context.touch(4, BK_TOUCH_CANCEL, r[0] + 10, r[1] + 10); + check(touches.length == 2 && touches[0][0] == 4 && touches[0][1] == BK_TOUCH_DOWN && + touches[1][1] == BK_TOUCH_CANCEL && (touches[0][2] & BK_FROM_TOUCH) != 0, + "touch: raw custom contacts"); + + raster.free(); + context.free(); + root.free(); +} + +/* Wrappers the garbage collector finalizes: their native nodes and contexts are queued and freed at + * the next safe point, never from the finalizer, which must reach no other D object (the crash + * this guards against was a finalizer walking a handler store the GC had already freed). */ +private void testCollected() { + foreach (i; 0 .. 20) { + auto root = new Node("column"); + root.add(new Node("button")); + auto custom = new Node("custom"); + setCustom(custom, CustomHandlers((Node, CustomEvent) { return 0; }, null, null, null, 10, 10)); + root.add(custom); + root.on(BK_EV_CLICK, (NodeEvent) {}); + auto context = new Context(root); + auto raster = new Raster(64, 64); + context.render(raster, true); + raster.free(); + new Node("label"); // detached, never freed by hand + } + GC.collect(); + auto after = new Node("frame"); // frees what the collection queued + check(after.handle !is null, "collected: a node after a collection"); + after.free(); +} + private void testHostErrors() { auto root = new Node("frame"); auto label = new Node("label"); diff --git a/bindings/go/bui/bui.go b/bindings/go/bui/bui.go index 459f7df9..2c84de47 100644 --- a/bindings/go/bui/bui.go +++ b/bindings/go/bui/bui.go @@ -167,7 +167,7 @@ func goHostEmit(id C.uintptr_t, n *C.BKNode, kind C.int, ref C.uintptr_t, a, b C } e := Event{Node: wrap(n), Kind: k, A: float64(a), B: float64(b)} switch k { - case EventKey, EventKeyRelease: + case EventKey, EventKeyRelease, EventGesture: if ref != 0 { e.Text = C.GoString(C.bui_go_text(ref)) } diff --git a/bindings/go/bui/bui_test.go b/bindings/go/bui/bui_test.go index 0e4e0392..8f93dbdd 100644 --- a/bindings/go/bui/bui_test.go +++ b/bindings/go/bui/bui_test.go @@ -3,6 +3,7 @@ package bui import ( + "fmt" "runtime" "strings" "testing" @@ -40,6 +41,60 @@ func TestPropertiesAndTree(t *testing.T) { } } +// A tap clicks; a spread over an "events" node and a trackpad pinch are EventGesture. +func TestTouchAndGestures(t *testing.T) { + root := NewNode("column") + defer root.Free() + b := NewNode("button").Set("text", "Go") + pad := NewNode("canvas").Set("events", 1).Set("height", 120) + root.Add(b).Add(pad) + clicks := 0 + b.OnClick(func(Event) { clicks++ }) + var gestures []Event + pad.On(EventGesture, func(e Event) { gestures = append(gestures, e) }) + ctx := NewContext(root) + defer ctx.Free() + r := NewRaster(320, 240) + defer r.Free() + ctx.Render(r, 320, 240, true) + + x, y := b.Rect().Center() + ctx.Touch(1, TouchDown, float32(x), float32(y), 0, 0) + if clicks != 0 { + t.Errorf("clicked before the finger lifted") + } + ctx.Touch(1, TouchUp, float32(x+2), float32(y), 0, 0) + if clicks != 1 { + t.Errorf("a tap: clicks %d", clicks) + } + + pr := pad.Rect() + cx, cy := pr.Center() + fx, fy := float32(cx), float32(cy) + ctx.Touch(2, TouchDown, fx-20, fy, 0, 0) + ctx.Touch(3, TouchDown, fx+20, fy, 0, 0) + for i := float32(1); i <= 3; i++ { + ctx.Touch(2, TouchMove, fx-20-10*i, fy, 0, 0) + ctx.Touch(3, TouchMove, fx+20+10*i, fy, 0, 0) + } + ctx.Touch(2, TouchUp, fx-50, fy, 0, 0) + ctx.Touch(3, TouchUp, fx+50, fy, 0, 0) + if len(gestures) != 3 { + t.Fatalf("a spread: %d gestures", len(gestures)) + } + var mods, kind, gx, gy int + fmt.Sscan(gestures[0].Text, &mods, &kind, &gx, &gy) + if mods&FromTouch == 0 || kind != GestureMagnify || gestures[0].A <= 0 || gx != cx-pr.X || gy != cy-pr.Y { + t.Errorf("a spread: %q, a %v", gestures[0].Text, gestures[0].A) + } + + gestures = nil + if !ctx.Magnify(cx, cy, 0.25, 0) || len(gestures) != 1 || gestures[0].A != 0.25 || + gestures[0].Text != fmt.Sprintf("0 %d %d %d", GestureMagnify, cx-pr.X, cy-pr.Y) { + t.Errorf("a trackpad pinch: %+v", gestures) + } +} + func TestEventsHeadless(t *testing.T) { root := NewNode("column").Set("padding", 8) defer root.Free() diff --git a/bindings/go/bui/context.go b/bindings/go/bui/context.go index ca159e0f..cc4322da 100644 --- a/bindings/go/bui/context.go +++ b/bindings/go/bui/context.go @@ -133,6 +133,22 @@ func (c *Context) Scroll(x, y int, dx, dy float32, mods int) bool { return settled(C.BK_scroll(c.h, C.int(x), C.int(y), C.float(dx), C.float(dy), C.int(mods))) } +// Touch sends a touch screen contact: phase is TouchDown, TouchMove, TouchUp or TouchCancel, +// timeMs the event's own time on any monotonic clock (<= 0: now). +func (c *Context) Touch(id, phase int, x, y float32, timeMs float64, mods int) bool { + return settled(C.BK_touch(c.h, C.int(id), C.int(phase), C.float(x), C.float(y), C.double(timeMs), C.int(mods))) +} + +// Magnify is a trackpad pinch about (x, y): delta is the scale change (0.1 = 10% larger). +func (c *Context) Magnify(x, y int, delta float32, mods int) bool { + return settled(C.BK_magnify(c.h, C.int(x), C.int(y), C.float(delta), C.int(mods))) +} + +// Rotate is a trackpad turn about (x, y), in degrees (> 0 counter-clockwise). +func (c *Context) Rotate(x, y int, degrees float32, mods int) bool { + return settled(C.BK_rotate(c.h, C.int(x), C.int(y), C.float(degrees), C.int(mods))) +} + // Key presses a key: the text it types and its X11 keysym ("Return", "a", // "Up"); either may be empty. func (c *Context) Key(text, keysym string, mods int) bool { diff --git a/bindings/go/bui/node.go b/bindings/go/bui/node.go index c55c8579..6081cbcf 100644 --- a/bindings/go/bui/node.go +++ b/bindings/go/bui/node.go @@ -40,7 +40,10 @@ const ( EventArea EventKind = C.BK_EV_AREA // a screen's area: A = its child index, B = BK_AREA_* EventMove EventKind = C.BK_EV_MOVE // a panel was dragged to a new place: A = old index, B = new index EventResize EventKind = C.BK_EV_RESIZE // an area's region was resized, hidden or shown: A = size, B = hidden - eventKindCount = int(EventResize) + 1 + // a pinch or a turn over a node with "events": Text = "mods kind x y" (kind GestureMagnify or + // GestureRotate, x, y its centre relative to the node), A = the scale change or degrees + EventGesture EventKind = C.BK_EV_GESTURE + eventKindCount = int(EventGesture) + 1 ) // valid reports a kind a node can have a handler for. @@ -62,6 +65,22 @@ const ( Button1 = C.BK_BUTTON1 Button2 = C.BK_BUTTON2 Button3 = C.BK_BUTTON3 + // FromTouch marks the raw events and gestures the kit made from touch screen contacts. + FromTouch = C.BK_FROM_TOUCH +) + +// The kinds of an EventGesture. +const ( + GestureMagnify = C.BK_GESTURE_MAGNIFY + GestureRotate = C.BK_GESTURE_ROTATE +) + +// Touch contact phases (Context.Touch). +const ( + TouchDown = C.BK_TOUCH_DOWN + TouchMove = C.BK_TOUCH_MOVE + TouchUp = C.BK_TOUCH_UP + TouchCancel = C.BK_TOUCH_CANCEL ) // Rect is a node's box in window pixels. diff --git a/bindings/imgui/imgui_impl_bui.cpp b/bindings/imgui/imgui_impl_bui.cpp index e3ae3e7b..de15a349 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); + // a finger (the kit made the event from a touch contact) or the mouse + 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; @@ -414,6 +416,8 @@ static int Bui_Event(void* data, BKNode* node, const BKCustomEvent* e) bd->ButtonsDown = 0; bd->SuperDown = false; break; + default: // pinches, turns and raw contacts: ImGui has none + return 0; } InputHappened(bd); return used; @@ -673,6 +677,7 @@ bool ImGui_ImplBUI_Init(BKNode* node, ImGui_ImplBUI_FrameFn frame, void* user, c cls.free = Bui_Free; cls.natural_w = cls.natural_h = 1; // takes the room its layout gives it ("fill") BK_custom_set(node, &cls, bd); + BK_custom_set_touch(node, BK_TOUCH_MODE_POINTER); // ImGui owns its drags: sliders, window moves bd->FramesPending = bd->Config.SettleFrames; // new windows size themselves over a few frames BK_custom_request_frame(node, 0); return true; diff --git a/bindings/imgui/tests/test_imgui_bui.cpp b/bindings/imgui/tests/test_imgui_bui.cpp index 99492091..787f07b9 100644 --- a/bindings/imgui/tests/test_imgui_bui.cpp +++ b/bindings/imgui/tests/test_imgui_bui.cpp @@ -279,6 +279,32 @@ int main() CHECK(T.clicks == 1, "button clicked once (%d)", T.clicks); } + // -- touch: a tap clicks as a touch screen, a finger drags a slider at once (BK_TOUCH_MODE_POINTER) -- + { + ImGuiIO& io = ImGui::GetIO(); + const ImVec2 c = Center(T.button); + BK_touch(g_ctx, 1, BK_TOUCH_DOWN, c.x, c.y, 0, 0); + Render(2); + CHECK(io.MouseSource == ImGuiMouseSource_TouchScreen, "a finger is ImGui's touch screen (%d)", (int)io.MouseSource); + BK_touch(g_ctx, 1, BK_TOUCH_UP, c.x, c.y, 0, 0); + Render(3); + CHECK(T.clicks == 2, "a tap clicked the button (%d)", T.clicks); + const float x0 = T.slider_rc.Min.x + 2, x1 = T.slider_rc.Min.x + T.slider_w - 2, y = Center(T.slider_rc).y; + T.slider = 0.0f; + BK_touch(g_ctx, 2, BK_TOUCH_DOWN, x0, y, 0, 0); + Render(2); + for (int i = 1; i <= 10; i++) + { + BK_touch(g_ctx, 2, BK_TOUCH_MOVE, x0 + (x1 - x0) * i / 10, y, 0, 0); + Render(1); + } + BK_touch(g_ctx, 2, BK_TOUCH_UP, x1, y, 0, 0); + Render(3); + CHECK(T.slider > 0.95f, "a finger dragged the slider to %.3f", T.slider); + Move(c.x, c.y); + CHECK(io.MouseSource == ImGuiMouseSource_Mouse, "the mouse again (%d)", (int)io.MouseSource); + } + // -- text input: typing, editing, cursor shape, select all + copy -- { const ImVec2 c = Center(T.input); diff --git a/bindings/lua/src/bui_context.c b/bindings/lua/src/bui_context.c index 7a106115..91d46bdc 100644 --- a/bindings/lua/src/bui_context.c +++ b/bindings/lua/src/bui_context.c @@ -136,7 +136,11 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d lua_pushvalue(L, -3); lua_pushnumber(L, a); lua_pushnumber(L, b); - if (lua_pcall(L, 3, 0, 0) != LUA_OK) { + /* raw events and gestures: their text ("mods button ...", "mods kind x y") */ + const int text = ref && ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || + kind == BK_EV_KEYRELEASE || kind == BK_EV_GESTURE); + if (text) lua_pushstring(L, (const char *)ref); + if (lua_pcall(L, 3 + text, 0, 0) != LUA_OK) { luabui_report_error(L); } if (closing) g_closing = notice.outer; @@ -333,6 +337,35 @@ static int l_ctx_scroll(lua_State *L) { return 1; } +/* ctx:touch(id, phase, x, y [, time_ms [, mods]]): a touch screen contact (bui.TOUCH_*) */ +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); + double time_ms = luaL_optnumber(L, 6, 0.0); + int mods = (int)luaL_optinteger(L, 7, 0); + lua_pushboolean(L, BK_touch(cud->ctx, id, phase, x, y, time_ms, mods)); + return 1; +} + +/* ctx:magnify / ctx:rotate(x, y, amount [, mods]): a trackpad pinch or turn about x, y */ +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; @@ -740,6 +773,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 ac77a1a9..c4029357 100644 --- a/bindings/lua/src/bui_lua.c +++ b/bindings/lua/src/bui_lua.c @@ -877,6 +877,9 @@ BUI_LUA_ENTRY int luaopen_bui(lua_State *L) { /* screens: areas made / closed / dragged out, panels moved, regions resized */ lua_pushinteger(L, BK_EV_AREA); lua_setfield(L, -2, "EV_AREA"); lua_pushinteger(L, BK_EV_MOVE); lua_setfield(L, -2, "EV_MOVE"); lua_pushinteger(L, BK_EV_RESIZE); lua_setfield(L, -2, "EV_RESIZE"); + /* pinches and turns over "events" nodes: the handler's 4th argument is "mods kind x y" */ + lua_pushinteger(L, BK_EV_GESTURE); lua_setfield(L, -2, "EV_GESTURE"); + lua_pushinteger(L, BK_GESTURE_MAGNIFY); lua_setfield(L, -2, "GESTURE_MAGNIFY"); lua_pushinteger(L, BK_GESTURE_ROTATE); lua_setfield(L, -2, "GESTURE_ROTATE"); lua_pushinteger(L, BK_AREA_NEW); lua_setfield(L, -2, "AREA_NEW"); lua_pushinteger(L, BK_AREA_CLOSE); lua_setfield(L, -2, "AREA_CLOSE"); lua_pushinteger(L, BK_AREA_WINDOW); lua_setfield(L, -2, "AREA_WINDOW"); @@ -894,6 +897,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 contact 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"); @@ -944,6 +952,13 @@ BUI_LUA_ENTRY int luaopen_bui(lua_State *L) { lua_pushinteger(L, BK_CUSTOM_KEYUP); lua_setfield(L, -2, "CUSTOM_KEYUP"); lua_pushinteger(L, BK_CUSTOM_FOCUS); lua_setfield(L, -2, "CUSTOM_FOCUS"); lua_pushinteger(L, BK_CUSTOM_BLUR); lua_setfield(L, -2, "CUSTOM_BLUR"); + lua_pushinteger(L, BK_CUSTOM_TOUCH); lua_setfield(L, -2, "CUSTOM_TOUCH"); + lua_pushinteger(L, BK_CUSTOM_MAGNIFY); lua_setfield(L, -2, "CUSTOM_MAGNIFY"); + lua_pushinteger(L, BK_CUSTOM_ROTATE); lua_setfield(L, -2, "CUSTOM_ROTATE"); + /* What a finger does on a custom node (node:custom_set_touch) */ + lua_pushinteger(L, BK_TOUCH_MODE_SCROLL); lua_setfield(L, -2, "TOUCH_MODE_SCROLL"); + lua_pushinteger(L, BK_TOUCH_MODE_POINTER); lua_setfield(L, -2, "TOUCH_MODE_POINTER"); + lua_pushinteger(L, BK_TOUCH_MODE_RAW); lua_setfield(L, -2, "TOUCH_MODE_RAW"); /* IME composition event kinds (ctx:ime_event) */ lua_pushinteger(L, BK_IME_COMPOSITION_START); lua_setfield(L, -2, "IME_COMPOSITION_START"); diff --git a/bindings/lua/src/bui_node.c b/bindings/lua/src/bui_node.c index 37f85445..ce11f401 100644 --- a/bindings/lua/src/bui_node.c +++ b/bindings/lua/src/bui_node.c @@ -1124,7 +1124,7 @@ static int custom_event_cb(void *data, BKNode *node, const BKCustomEvent *e) { return 0; } luabui_push_node(L, node); - lua_createtable(L, 0, 10); + lua_createtable(L, 0, 14); lua_pushinteger(L, e->type); lua_setfield(L, -2, "type"); lua_pushnumber(L, e->x); lua_setfield(L, -2, "x"); lua_pushnumber(L, e->y); lua_setfield(L, -2, "y"); @@ -1135,6 +1135,10 @@ static int custom_event_cb(void *data, BKNode *node, const BKCustomEvent *e) { lua_pushnumber(L, e->wheel_y); lua_setfield(L, -2, "wheel_y"); lua_pushstring(L, e->text ? e->text : ""); lua_setfield(L, -2, "text"); lua_pushstring(L, e->keysym ? e->keysym : ""); lua_setfield(L, -2, "keysym"); + lua_pushinteger(L, e->touch_id); lua_setfield(L, -2, "touch_id"); + lua_pushinteger(L, e->touch_phase); lua_setfield(L, -2, "touch_phase"); + lua_pushnumber(L, e->magnify); lua_setfield(L, -2, "magnify"); + lua_pushnumber(L, e->rotate); lua_setfield(L, -2, "rotate"); if (lua_pcall(L, 2, 1, 0) != LUA_OK) { luabui_report_error(L); lua_pop(L, 1); /* class */ @@ -1321,6 +1325,12 @@ static int l_node_custom_set_cursor(lua_State *L) { return 0; } +static int l_node_custom_set_touch(lua_State *L) { + luabui_Node *ud = CHECK_NODE(L, 1); + if (ud->node) BK_custom_set_touch(ud->node, (int)luaL_checkinteger(L, 2)); + return 0; +} + static int l_node_custom_has_focus(lua_State *L) { luabui_Node *ud = CHECK_NODE(L, 1); lua_pushboolean(L, ud->node ? BK_custom_has_focus(ud->node) : 0); @@ -1399,6 +1409,7 @@ static const luaL_Reg node_methods[] = { {"custom_data", l_node_custom_data}, {"custom_request_frame", l_node_custom_request_frame}, {"custom_set_cursor", l_node_custom_set_cursor}, + {"custom_set_touch", l_node_custom_set_touch}, {"custom_has_focus", l_node_custom_has_focus}, {"ramp_active", l_node_ramp_active}, {"geom_manager", l_node_geom_manager}, diff --git a/bindings/lua/tests/test_context.lua b/bindings/lua/tests/test_context.lua index 36100dc7..5da8ca13 100644 --- a/bindings/lua/tests/test_context.lua +++ b/bindings/lua/tests/test_context.lua @@ -84,6 +84,71 @@ ctx:context_menu(100, 100, 0) -- Scroll ctx:scroll(50, 50, 10.5, -20.3, 0) +-- ── Touch screens and trackpad gestures ───────────────────────────── + +do + local troot = bui.Node("column") + local tbtn = bui.Node("button") + tbtn:set("text", "Go") + local taps = 0 + tbtn:on(bui.EV_CLICK, function() taps = taps + 1 end) + local pad = bui.Node("canvas") + pad:set("events", 1) + pad:set("height", 200) + local gestures = {} + pad:on(bui.EV_GESTURE, function(_, amount, _, text) gestures[#gestures + 1] = {amount, text} end) + local touches = {} + local raw = bui.Node("custom") + raw:custom_set({natural_w = 200, natural_h = 100, on_event = function(_, e) + if e.type == bui.CUSTOM_TOUCH then touches[#touches + 1] = {e.touch_id, e.touch_phase, e.mods} end + return e.type == bui.CUSTOM_TOUCH + end}) + raw:custom_set_touch(bui.TOUCH_MODE_RAW) + troot:add(tbtn) + troot:add(pad) + troot:add(raw) + local tctx = bui.Context(troot) + tctx:render(400, 500, 1) + local bx, by, bw, bh = tbtn:rect() + local x, y = bx + bw // 2, by + bh // 2 + -- a tap is a click once the finger lifts + tctx:touch(1, bui.TOUCH_DOWN, x, y) + check(taps == 0, "touch: clicked before the finger lifted") + tctx:touch(1, bui.TOUCH_UP, x + 2, y, 0, 0) + check(taps == 1, "touch: a tap did not click, taps " .. taps) + -- two fingers spreading over the pad: magnify gestures about their centre + local px, py, pw, ph = pad:rect() + local cx, cy = px + pw // 2, py + ph // 2 + tctx:touch(2, bui.TOUCH_DOWN, cx - 20, cy) + tctx:touch(3, bui.TOUCH_DOWN, cx + 20, cy) + for i = 1, 3 do + tctx:touch(2, bui.TOUCH_MOVE, cx - 20 - 10 * i, cy) + tctx:touch(3, bui.TOUCH_MOVE, cx + 20 + 10 * i, cy) + end + tctx:touch(2, bui.TOUCH_UP, cx - 50, cy) + tctx:touch(3, bui.TOUCH_UP, cx + 50, cy) + check(#gestures == 3, "touch: expected 3 magnify gestures, got " .. #gestures) + local mods, kind, gx, gy = gestures[1][2]:match("^(%d+) (%d+) (%-?%d+) (%-?%d+)$") + check(tonumber(mods) & bui.MOD_FROM_TOUCH ~= 0, "touch: gesture mods lack MOD_FROM_TOUCH") + check(tonumber(kind) == bui.GESTURE_MAGNIFY and gestures[1][1] > 0, "touch: not a spread") + check(tonumber(gx) == cx - px and tonumber(gy) == cy - py, "touch: gesture centre " .. gestures[1][2]) + -- a trackpad pinch + gestures = {} + check(tctx:magnify(cx, cy, 0.25), "magnify changed nothing") + check(#gestures == 1 and gestures[1][2] == string.format("0 %d %d %d", bui.GESTURE_MAGNIFY, cx - px, cy - py) + and math.abs(gestures[1][1] - 0.25) < 1e-6, "magnify: no gesture event") + tctx:rotate(cx, cy, -15) + check(#gestures == 2 and gestures[2][1] == -15, "rotate: no gesture event") + -- a raw custom node gets its contacts as they are + local rx, ry = raw:rect() + tctx:touch(4, bui.TOUCH_DOWN, rx + 10, ry + 10) + tctx:touch(4, bui.TOUCH_CANCEL, rx + 10, ry + 10) + check(#touches == 2 and touches[1][1] == 4 and touches[1][2] == bui.TOUCH_DOWN + and touches[2][2] == bui.TOUCH_CANCEL and touches[1][3] & bui.MOD_FROM_TOUCH ~= 0, + "touch: raw custom contacts " .. #touches) + tctx:free() +end + -- ── Cursor ─────────────────────────────────────────────────────────── local cursor = ctx:cursor() diff --git a/bindings/node/README.md b/bindings/node/README.md index 8c4ebd25..271ede8a 100644 --- a/bindings/node/README.md +++ b/bindings/node/README.md @@ -56,10 +56,15 @@ win.body.appendChild(button) globals, for DOM-based frameworks), and `bui build` bundling with the Bun plugin a `@blender-ui/*` package declares (`"bui": { "bunPlugin" }`). - **Events:** `addEventListener` for `click`, `mousedown`, `mouseup`, - `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input` - and `change` arrive from the UI thread; other types fire through + `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input`, + `change`, and the touch screen / trackpad gestures `pinch` (`delta`: the + scale change), `rotate` (`delta`: degrees, counter-clockwise) and `pan` + (`deltaX` / `deltaY`: pixels the content follows the fingers; `phase`: + `drag`, `fling` or `end`) arrive from the UI thread; other types fire through `dispatchEvent`. - They bubble through the tree, and `stopPropagation()` works. + - An element listening for `pan` takes the drag, as CSS's + `touch-action: none`: nothing under it scrolls by touch. - They arrive after BUI has handled them, so `preventDefault()` only marks the event. - **Frames and measurement:** `win.requestAnimationFrame(cb)` is paced by the diff --git a/bindings/node/dom.js b/bindings/node/dom.js index fc5b8101..22e937af 100644 --- a/bindings/node/dom.js +++ b/bindings/node/dom.js @@ -23,7 +23,7 @@ const MOTION_PROPS = { } const EVENT_BITS = { click: 1, mousedown: 2, mouseup: 4, mousemove: 8, mouseenter: 16, mouseleave: 16, - wheel: 32, keydown: 64, keyup: 128, change: 256, input: 512, + wheel: 32, keydown: 64, keyup: 128, change: 256, input: 512, pinch: 1024, rotate: 2048, pan: 4096, } const BUTTONS = ['left', 'middle', 'right'] // DOM: these don't bubble @@ -57,7 +57,14 @@ class BuiEvent { this.clientY = this.y = raw.y this.button = raw.button this.detail = raw.clickCount - this.deltaY = -raw.delta * 100 // DOM: positive scrolls down + // wheel: the DOM's, positive scrolls down; pan: pixels the content follows the fingers (x right, + // y down) + this.deltaX = raw.deltaX + this.deltaY = raw.kind === 'wheel' ? -raw.delta * 100 : raw.deltaY + // pinch: the scale change (0.1 = 10% larger); rotate: degrees, positive counter-clockwise + this.delta = raw.delta + // pan: 'drag', 'fling' or 'end' + this.phase = raw.phase ?? undefined this.key = raw.key ?? undefined this.char = raw.keyChar ?? undefined this.shiftKey = raw.shift diff --git a/bindings/node/host.js b/bindings/node/host.js index 265eda99..8402a166 100644 --- a/bindings/node/host.js +++ b/bindings/node/host.js @@ -98,6 +98,7 @@ const EVENTS = { onClick: 'click', onMouseDown: 'mousedown', onMouseUp: 'mouseup', onMouseMove: 'mousemove', onMouseEnter: 'mouseenter', onMouseLeave: 'mouseleave', onWheel: 'wheel', onKeyDown: 'keydown', onKeyUp: 'keyup', onInput: 'input', onChange: 'change', + onPinch: 'pinch', onRotate: 'rotate', onPan: 'pan', } const TEXT_INPUTS = new Set(['textarea']) const ATTR_ALIASES = { className: 'class', htmlFor: 'for', tabIndex: 'tabindex' } diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts index 8155fb77..3c9fec7e 100644 --- a/bindings/node/index.d.ts +++ b/bindings/node/index.d.ts @@ -44,7 +44,7 @@ export interface LayerShellOptions { } export type EventType = 'click' | 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' | - 'wheel' | 'keydown' | 'keyup' | 'change' | 'input' + 'wheel' | 'keydown' | 'keyup' | 'change' | 'input' | 'pinch' | 'rotate' | 'pan' export class BuiEvent { type: EventType @@ -56,7 +56,16 @@ export class BuiEvent { y: number button: number detail: number + /** `pan`: pixels the content follows the fingers, right (0 for other events). */ + deltaX: number + /** `wheel`: the DOM's, positive scrolls down; `pan`: pixels the content follows the fingers, down. */ deltaY: number + /** `pinch`: the scale change since the last one (0.1 = 10% larger: a zoom is multiplied by + * `1 + delta`); `rotate`: degrees since the last one, positive counter-clockwise. */ + delta: number + /** `pan`: `'drag'` while a finger is down, `'fling'` as the content coasts on, `'end'` when it + * lifted (deltas 0). */ + phase?: 'drag' | 'fling' | 'end' key?: string char?: string shiftKey: boolean @@ -357,6 +366,13 @@ export class Window { mouseDown (x: number, y: number): void /** Let go of the left button (tests). */ mouseUp (x: number, y: number): void + /** A touch screen contact (tests): `id` tells the fingers apart; taps, scrolls, pans, pinches and + * turns follow. */ + touch (id: number, phase: 'down' | 'move' | 'up' | 'cancel', x: number, y: number): void + /** A trackpad pinch (tests): `delta` is the scale change (0.1 = 10% larger). */ + pinch (x: number, y: number, delta: number): void + /** A trackpad turn (tests): degrees, positive counter-clockwise. */ + rotate (x: number, y: number, degrees: number): void close (): void /** `focus` / `blur`: the window got or lost the keyboard focus. */ on (event: 'close' | 'focus' | 'blur', listener: () => void): this diff --git a/bindings/node/index.js b/bindings/node/index.js index d4c32ca6..cb0f1bb9 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -45,6 +45,7 @@ const { Motions } = require('./anim') const LAYERS = ['background', 'bottom', 'top', 'overlay'] const EDGES = ['top', 'bottom', 'left', 'right'] const KEYBOARD = ['none', 'exclusive', 'on-demand'] +const TOUCH_PHASES = ['down', 'move', 'up', 'cancel'] function oneOf (what, value, names) { if (value != null && !names.includes(value)) { @@ -208,6 +209,26 @@ class Window { this.app.native.simulatePointer(this.id, 2, x, y) } + /** A touch screen contact at (x, y) (tests): `id` tells the fingers apart; taps, scrolls, pans, + * pinches and turns follow. */ + touch (id, phase, x, y) { + oneOf('touch phase', String(phase), TOUCH_PHASES) + this.flush() + this.app.native.simulateTouch(this.id, id, TOUCH_PHASES.indexOf(phase), x, y) + } + + /** A trackpad pinch at (x, y) (tests): `delta` is the scale change (0.1 = 10% larger). */ + pinch (x, y, delta) { + this.flush() + this.app.native.simulateGesture(this.id, 0, x, y, delta) + } + + /** A trackpad turn at (x, y) (tests): degrees, positive counter-clockwise. */ + rotate (x, y, degrees) { + this.flush() + this.app.native.simulateGesture(this.id, 1, x, y, degrees) + } + close () { this.flush() this.app.native.closeWindow(this.id) diff --git a/bindings/node/test/native.test.js b/bindings/node/test/native.test.js index d3c09747..12016e55 100644 --- a/bindings/node/test/native.test.js +++ b/bindings/node/test/native.test.js @@ -197,3 +197,44 @@ test('window kinds: layer-shell names are checked', (t) => { assert.throws(() => app.window({ layerShell: { keyboard: 'all' } }), /layerShell.keyboard/) app.window({ alwaysOnTop: true, frame: false, layerShell: { layer: 'top', anchor: ['top', 'left'], exclusiveZone: 24 } }) }) + +test('touch screen and trackpad gestures: pinch, rotate and pan bubble with their amounts (headless)', async (t) => { + const { App, EVENT_BITS } = require('..') + const { applyProps, NO_PROPS } = require('../host') + const app = new App({ headless: true }) + t.after(() => app.quit()) + const win = app.window({ width: 300, height: 200 }) + win.body.style = 'margin: 0' + const map = win.createElement('div') + map.style = 'width: 300px; height: 200px' + win.body.appendChild(map) + const got = { pinch: [], rotate: [], pan: [] } + applyProps(map, NO_PROPS, { onPinch: (e) => got.pinch.push(e), onRotate: (e) => got.rotate.push(e), onPan: (e) => got.pan.push(e) }) + const bubbled = [] + win.body.addEventListener('pan', (e) => bubbled.push(e.currentTarget === win.body && e.target === map)) + assert.deepStrictEqual([EVENT_BITS.pinch, EVENT_BITS.rotate, EVENT_BITS.pan], [1024, 2048, 4096]) + const tick = () => new Promise(r => setTimeout(r, 30)) + await map.getBoundingClientRect() // laid out: the gestures find it + + win.pinch(120, 80, 0.25) + win.rotate(120, 80, 30) + await tick() + assert.strictEqual(got.pinch.length, 1) + assert.strictEqual(got.pinch[0].type, 'pinch') + assert.deepStrictEqual([got.pinch[0].x, got.pinch[0].y, got.pinch[0].delta], [120, 80, 0.25]) + assert.deepStrictEqual([got.rotate.length, got.rotate[0].delta], [1, 30]) + + // a finger dragged up 58 px (8 of them the touch slop): the content follows it by 50 + win.touch(1, 'down', 150, 150) + for (let i = 1; i <= 4; i++) win.touch(1, 'move', 150, 150 - 14.5 * i) + await tick() + await new Promise(r => setTimeout(r, 60)) // rest before lifting: no fling + win.touch(1, 'up', 150, 92) + await tick() + const drags = got.pan.filter((e) => e.phase === 'drag') + assert.ok(drags.length > 0 && drags.every((e) => e.type === 'pan' && e.deltaX === 0), 'vertical drags') + const dy = drags.reduce((s, e) => s + e.deltaY, 0) + assert.ok(Math.abs(dy + 50) < 0.5, `followed by ${dy}`) + assert.strictEqual(got.pan.at(-1).phase, 'end') + assert.ok(bubbled.length === got.pan.length && bubbled.every(Boolean), 'pan bubbles once through the JS tree') +}) diff --git a/bindings/python/bui/components/core.py b/bindings/python/bui/components/core.py index 4da3e66d..6707f00d 100644 --- a/bindings/python/bui/components/core.py +++ b/bindings/python/bui/components/core.py @@ -20,9 +20,16 @@ EV_SUBMIT, EV_VIEW, EV_SCROLL, EV_CONFIGURE, EV_KEYRELEASE) = range(8, 21) # A screen's areas, a panel moved, a region resized: delivered to _on_area, _on_move, _on_resize. EV_AREA, EV_MOVE, EV_RESIZE = range(21, 24) +# A pinch or turn over an "events" node: ref "mods kind x y" (kind GESTURE_*), a = the amount. +EV_GESTURE = 26 +GESTURE_MAGNIFY, GESTURE_ROTATE = 1, 2 -# Modifier bits for KitContext input calls. +# Modifier bits for KitContext input calls. FROM_TOUCH marks raw events made from touch contacts. SHIFT, CTRL, ALT, BUTTON1 = 1, 2, 4, 8 +FROM_TOUCH = 64 + +# KitContext.touch phases (BK_TOUCH_*). +TOUCH_DOWN, TOUCH_MOVE, TOUCH_UP, TOUCH_CANCEL = range(4) # Cursor ids (BK_CURSOR_*). CURSORS = (None, "ew", "ns", "text", "crosshair", "hand", "move", "none") diff --git a/bindings/python/src/buipy_kit.c b/bindings/python/src/buipy_kit.c index f66eb7e7..41eb0b5e 100644 --- a/bindings/python/src/buipy_kit.c +++ b/bindings/python/src/buipy_kit.c @@ -1516,6 +1516,13 @@ static const char *event_method(int kind) } } +/* Raw events ("events" nodes) and gestures: their ref is a C string, not a Python object. */ +static int ref_is_text(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) { @@ -1534,8 +1541,7 @@ static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, d } r = PyObject_CallMethod(target, method, "ii", (int)a, (int)b); } - else if ((kind >= BK_EV_PRESS && kind <= BK_EV_WHEEL) || kind == BK_EV_KEYRELEASE) { - /* raw events: ref is a C string */ + else if (ref_is_text(kind)) { r = PyObject_CallMethod(target, "_on_event", "isdd", kind, ref ? (const char *)ref : "", a, b); } @@ -1615,8 +1621,8 @@ 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) { - payload = PyUnicode_FromString(ref ? (const char *)ref : ""); /* raw events: a C string */ + if (ref_is_text(kind)) { + payload = PyUnicode_FromString(ref ? (const char *)ref : ""); } else { payload = Py_NewRef(ref ? (PyObject *)ref : Py_None); @@ -1799,6 +1805,40 @@ static PyObject *kitctx_wheel(KitContextObject *self, PyObject *args) return PyBool_FromLong(r); } +static PyObject *kitctx_touch(KitContextObject *self, PyObject *args) +{ + int id, phase, mods = 0; + float x, y; + double time_ms = 0.0; + if (!PyArg_ParseTuple(args, "iiff|di:touch", &id, &phase, &x, &y, &time_ms, &mods)) { + return NULL; + } + const int r = BK_touch(self->ctx, id, phase, x, y, time_ms, mods); + if (buipy_restore_error()) { + return NULL; + } + return PyBool_FromLong(r); +} + +/* magnify / rotate: a trackpad pinch or turn about x, y */ +#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 (buipy_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; @@ -2091,6 +2131,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, time_ms=0, mods=0): a touch screen contact (TOUCH_DOWN/MOVE/UP/CANCEL)"}, + {"magnify", (PyCFunction)kitctx_magnify, METH_VARARGS, + "magnify(x, y, delta, mods=0): a trackpad pinch (0.1 = 10% larger)"}, + {"rotate", (PyCFunction)kitctx_rotate, METH_VARARGS, + "rotate(x, y, degrees, mods=0): a trackpad 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_components.py b/bindings/python/tests/test_components.py index 554a99d5..5be14f15 100644 --- a/bindings/python/tests/test_components.py +++ b/bindings/python/tests/test_components.py @@ -1150,6 +1150,50 @@ def test_node_editor_height(): Driver(short, default, size=(500, 900)) assert short.h == 8 * u and default.h == 14 * u + +def test_touch_and_gestures(): + from bui.components.core import (EV_GESTURE, FROM_TOUCH, GESTURE_MAGNIFY, TOUCH_DOWN, + TOUCH_MOVE, TOUCH_UP) + + class Pad(Column): # an "events" node: raw events reach _on_event, gestures as text + def __init__(self): + super().__init__(Label("pad"), Label("pad"), Label("pad")) + self.set("events", True) + self.log = [] + + def _on_event(self, kind, ref, a, b): + self.log.append((kind, ref, a)) + + clicks = [] + button = Button("Go", on_click=lambda: clicks.append(1)) + pad = Pad() + d = Driver(button, pad) + # a tap is a click once the finger lifts + x, y = d.center(button) + d.ctx.touch(1, TOUCH_DOWN, x, y) + assert not clicks + d.ctx.touch(1, TOUCH_UP, x + 2, y) + assert clicks == [1], clicks + # two fingers spreading over the pad: magnify gestures about their centre + px, py = d.center(pad) + d.ctx.touch(2, TOUCH_DOWN, px - 20, py, 0.0) + d.ctx.touch(3, TOUCH_DOWN, px + 20, py, 0.0) + for i in range(1, 4): + d.ctx.touch(2, TOUCH_MOVE, px - 20 - 10 * i, py) + d.ctx.touch(3, TOUCH_MOVE, px + 20 + 10 * i, py) + d.ctx.touch(2, TOUCH_UP, px - 50, py) + d.ctx.touch(3, TOUCH_UP, px + 50, py) + gestures = [(ref, a) for kind, ref, a in pad.log if kind == EV_GESTURE] + assert len(gestures) == 3, pad.log + mods, kind, gx, gy = (int(v) for v in gestures[0][0].split()) + assert mods & FROM_TOUCH and kind == GESTURE_MAGNIFY and gestures[0][1] > 0, gestures + assert (gx, gy) == (px - pad.x, py - pad.y), (gx, gy) + # a trackpad pinch + pad.log.clear() + assert d.ctx.magnify(px, py, 0.25) + assert pad.log == [(EV_GESTURE, "0 1 %d %d" % (px - pad.x, py - pad.y), 0.25)], pad.log + + def main() -> int: tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")] for t in tests: diff --git a/bindings/ruby/ext/bui/bui_context.c b/bindings/ruby/ext/bui/bui_context.c index 9490dc6a..a7db45dd 100644 --- a/bindings/ruby/ext/bui/bui_context.c +++ b/bindings/ruby/ext/bui/bui_context.c @@ -19,10 +19,11 @@ static const char *const k_event_names[] = { NULL, "change", "click", "call", "rename", "activate", "toggle", "browse", "press", "release", "double", "motion", "enter", "leave", "key", "wheel", "submit", "view", "scroll", "configure", "key_release", + "area", "move", "resize", "a11y_tree", "a11y_action", "gesture", }; #define EVENT_KINDS ((int)(sizeof(k_event_names) / sizeof(k_event_names[0]))) /* a new BK_EV_* needs its name here */ -_Static_assert(BK_EV_KEYRELEASE == EVENT_KINDS - 1, "an event kind without a name"); +_Static_assert(BK_EV_GESTURE == EVENT_KINDS - 1, "an event kind without a name"); static ID g_event_ids[EVENT_KINDS]; /* -------------------------------------------------------------------- */ @@ -105,6 +106,7 @@ static VALUE emit_body(VALUE p) switch (e->kind) { case BK_EV_KEY: case BK_EV_KEYRELEASE: + case BK_EV_GESTURE: /* "mods kind x y" */ text = bui_str((const char *)e->ref); /* "text\tkeysym" */ break; case BK_EV_RENAME: @@ -321,6 +323,31 @@ static VALUE context_scroll(int argc, VALUE *argv, VALUE self) ctx, bui_int(x), bui_int(y), (float)bui_num(dx), (float)bui_num(dy), mods_of(mods))); } +/* touch(id, phase, x, y, time_ms = 0, mods = 0): a touch screen contact (BUI::TOUCH_*); time_ms + * is the event's own time on any monotonic clock (<= 0: now). */ +static VALUE context_touch(int argc, VALUE *argv, VALUE self) +{ + VALUE id, phase, x, y, time_ms, mods; + rb_scan_args(argc, argv, "42", &id, &phase, &x, &y, &time_ms, &mods); + BKContext *ctx = bui_context_ptr(self); + return changed(BK_touch(ctx, bui_int(id), bui_int(phase), (float)bui_num(x), (float)bui_num(y), + NIL_P(time_ms) ? 0.0 : bui_num(time_ms), mods_of(mods))); +} + +#define GESTURE_INPUT(name, call) \ + static VALUE context_##name(int argc, VALUE *argv, VALUE self) \ + { \ + VALUE x, y, amount, mods; \ + rb_scan_args(argc, argv, "31", &x, &y, &amount, &mods); \ + BKContext *ctx = bui_context_ptr(self); \ + return changed(call(ctx, bui_int(x), bui_int(y), (float)bui_num(amount), mods_of(mods))); \ + } + +/* magnify(x, y, delta, mods = 0): a trackpad pinch (0.1 = 10% larger); + * rotate(x, y, degrees, mods = 0): a trackpad turn (> 0 counter-clockwise) */ +GESTURE_INPUT(magnify, BK_magnify) +GESTURE_INPUT(rotate, BK_rotate) + /* key(text, keysym = nil, mods = 0): a key typing text ("" for none), with * its X11 keysym ("Return", "Up", "a"). */ static VALUE context_key(int argc, VALUE *argv, VALUE self) @@ -688,6 +715,14 @@ void bui_init_context(void) rb_define_const(bui_mBUI, "SHIFT", INT2NUM(BK_SHIFT)); rb_define_const(bui_mBUI, "CTRL", INT2NUM(BK_CTRL)); rb_define_const(bui_mBUI, "ALT", INT2NUM(BK_ALT)); + /* raw events and gestures made from touch contacts carry it in their mods */ + rb_define_const(bui_mBUI, "FROM_TOUCH", INT2NUM(BK_FROM_TOUCH)); + rb_define_const(bui_mBUI, "TOUCH_DOWN", INT2NUM(BK_TOUCH_DOWN)); + rb_define_const(bui_mBUI, "TOUCH_MOVE", INT2NUM(BK_TOUCH_MOVE)); + rb_define_const(bui_mBUI, "TOUCH_UP", INT2NUM(BK_TOUCH_UP)); + rb_define_const(bui_mBUI, "TOUCH_CANCEL", INT2NUM(BK_TOUCH_CANCEL)); + rb_define_const(bui_mBUI, "GESTURE_MAGNIFY", INT2NUM(BK_GESTURE_MAGNIFY)); + rb_define_const(bui_mBUI, "GESTURE_ROTATE", INT2NUM(BK_GESTURE_ROTATE)); bui_cContext = rb_define_class_under(bui_mBUI, "Context", rb_cObject); rb_define_alloc_func(bui_cContext, context_alloc); @@ -708,6 +743,9 @@ void bui_init_context(void) rb_define_method(bui_cContext, "context_menu", context_context_menu, -1); rb_define_method(bui_cContext, "wheel", context_wheel, -1); rb_define_method(bui_cContext, "scroll", context_scroll, -1); + rb_define_method(bui_cContext, "touch", context_touch, -1); + rb_define_method(bui_cContext, "magnify", context_magnify, -1); + rb_define_method(bui_cContext, "rotate", context_rotate, -1); rb_define_method(bui_cContext, "key", context_key, -1); rb_define_method(bui_cContext, "key_release", context_key_release, -1); rb_define_method(bui_cContext, "button", context_button, -1); diff --git a/bindings/ruby/lib/bui/event.rb b/bindings/ruby/lib/bui/event.rb index 9af55a70..69428ced 100644 --- a/bindings/ruby/lib/bui/event.rb +++ b/bindings/ruby/lib/bui/event.rb @@ -9,7 +9,8 @@ module BUI # new value for :change, a row index for :rename and :activate, the size # for :configure, the modifiers (BUI::SHIFT | BUI::CTRL | BUI::ALT) for keys # text the typed text and the X11 keysym of :key ("a\ta", "\tReturn"), a new - # name for :rename + # name for :rename, "mods kind x y" for :gesture (kind BUI::GESTURE_*, x, y + # its centre relative to the node; a = the scale change or degrees) # item the BUI::TreeItem of a :toggle Event = Struct.new(:node, :kind, :a, :b, :text, :item) do alias_method :x, :a diff --git a/bindings/ruby/lib/bui/node.rb b/bindings/ruby/lib/bui/node.rb index 702778a7..c330c98a 100644 --- a/bindings/ruby/lib/bui/node.rb +++ b/bindings/ruby/lib/bui/node.rb @@ -81,7 +81,8 @@ def visible=(on) # Events the kit sends only to nodes that ask for them ("events"), and :view # ("viewevents"). - RAW_EVENTS = %i[press release double motion enter leave key wheel submit configure key_release].freeze + RAW_EVENTS = %i[press release double motion enter leave key wheel submit configure key_release + gesture].freeze # Handles a kind of event (BUI::EVENT_KINDS), replacing the last handler; the # block gets a BUI::Event. Without a block, removes it. Returns self. diff --git a/bindings/ruby/test/test_events.rb b/bindings/ruby/test/test_events.rb index 64322e54..7d7ba385 100644 --- a/bindings/ruby/test/test_events.rb +++ b/bindings/ruby/test/test_events.rb @@ -101,6 +101,45 @@ def test_a_handler_may_free_its_context root.free end + def test_touch_and_gestures + root = BUI::Node.new("column") + button = BUI::Node.new("button").set(text: "Go") + pad = BUI::Node.new("canvas").set(height: 120) + root << button << pad + clicks = 0 + button.on_click { clicks += 1 } + gestures = [] + pad.on(:gesture) { |e| gestures << [e.text, e.a] } + show(root, 320, 240) do |ctx, _raster| + # a tap is a click once the finger lifts + x, y = button.rect.center + ctx.touch(1, BUI::TOUCH_DOWN, x, y) + assert_equal 0, clicks + ctx.touch(1, BUI::TOUCH_UP, x + 2, y) + assert_equal 1, clicks + # two fingers spreading over the pad: magnify gestures about their centre + cx, cy = pad.rect.center + ctx.touch(2, BUI::TOUCH_DOWN, cx - 20, cy) + ctx.touch(3, BUI::TOUCH_DOWN, cx + 20, cy) + (1..3).each do |i| + ctx.touch(2, BUI::TOUCH_MOVE, cx - 20 - (10 * i), cy) + ctx.touch(3, BUI::TOUCH_MOVE, cx + 20 + (10 * i), cy) + end + ctx.touch(2, BUI::TOUCH_UP, cx - 50, cy) + ctx.touch(3, BUI::TOUCH_UP, cx + 50, cy) + assert_equal 3, gestures.size + mods, kind, gx, gy = gestures.first[0].split.map(&:to_i) + assert_equal BUI::FROM_TOUCH, mods & BUI::FROM_TOUCH + assert_equal BUI::GESTURE_MAGNIFY, kind + assert_operator gestures.first[1], :>, 0 + assert_equal [cx - pad.rect.x, cy - pad.rect.y], [gx, gy] + # a trackpad pinch + gestures.clear + assert ctx.magnify(cx, cy, 0.25) + assert_equal [["0 #{BUI::GESTURE_MAGNIFY} #{cx - pad.rect.x} #{cy - pad.rect.y}", 0.25]], gestures + end + end + def test_other_threads_queue_work ran = [] Thread.new { BUI.on_main { ran << Thread.current } }.join diff --git a/bindings/rust/blenderui-jsview/src/lib.rs b/bindings/rust/blenderui-jsview/src/lib.rs index 52060681..a75cd647 100644 --- a/bindings/rust/blenderui-jsview/src/lib.rs +++ b/bindings/rust/blenderui-jsview/src/lib.rs @@ -19,8 +19,8 @@ pub mod motion; pub mod shell; /// An event from a window (`kind`: click, mousedown, mouseup, mousemove, -/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, frame, -/// close). +/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, pinch, +/// rotate, pan, frame, close). #[derive(Clone, Debug, Default)] pub struct Event { pub kind: String, @@ -32,7 +32,14 @@ pub struct Event { /// 0 left, 1 middle, 2 right (DOM numbering). pub button: u32, pub click_count: u32, + /// `wheel`: lines (positive scrolls the content up); `pinch`: the scale change (0.1 = 10% + /// larger); `rotate`: degrees, positive counter-clockwise. pub delta: f64, + /// `pan`: logical pixels the content follows the fingers, x right, y down. + pub delta_x: f64, + pub delta_y: f64, + /// `pan`: "drag" while a finger is down, "fling" as the content coasts on, "end" when it lifted. + pub phase: Option<&'static str>, pub key: Option, pub key_char: Option, pub value: Option, @@ -146,6 +153,9 @@ pub mod ev { pub const KEY_UP: u32 = 128; pub const CHANGE: u32 = 256; pub const INPUT: u32 = 512; + pub const PINCH: u32 = 1024; + pub const ROTATE: u32 = 2048; + pub const PAN: u32 = 4096; } // ========================================================================== @@ -417,6 +427,9 @@ impl JsView { } fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div { + fn at(e: &mut Event, p: Point) { + (e.x, e.y) = (f64::from(p.x.0), f64::from(p.y.0)); + } let base = Event { window: self.window, target: id, ..Default::default() }; let send = { let t = self.sink.clone(); @@ -489,6 +502,32 @@ impl JsView { e.delta = w.delta as f64; mods(&mut e, &w.modifiers); }); + on!(ev::PINCH, on_pinch, |e, p| { + e.kind = "pinch".into(); + at(&mut e, p.position); + e.delta = f64::from(p.delta); + mods(&mut e, &p.modifiers); + }); + on!(ev::ROTATE, on_rotate, |e, r| { + e.kind = "rotate".into(); + at(&mut e, r.position); + e.delta = f64::from(r.degrees); + mods(&mut e, &r.modifiers); + }); + // Stopping the propagation here takes the drag (nothing scrolls under an element listening + // for `pan`, CSS's `touch-action: none`): JavaScript hears of it later, on its own thread. + on!(ev::PAN, on_pan, |e, p| { + e.kind = "pan".into(); + at(&mut e, p.position); + (e.delta_x, e.delta_y) = (f64::from(p.delta.x.0), f64::from(p.delta.y.0)); + e.phase = Some(match p.phase { + ScrollPhase::Wheel => "wheel", + ScrollPhase::Drag => "drag", + ScrollPhase::Fling => "fling", + ScrollPhase::End => "end", + }); + mods(&mut e, &p.modifiers); + }); on!(ev::KEY_DOWN, on_key_down, |e, k| { e.kind = "keydown".into(); e.key = Some(k.keystroke.key.clone()); @@ -730,6 +769,32 @@ pub fn simulate_pointer(cx: &mut App, window: u32, kind: u32, x: f64, y: f64) { } } +/// A touch screen contact at (x, y) in window `window` (tests; logical pixels): `id` tells the +/// fingers apart, `phase` 0 down, 1 move, 2 up, 3 cancel. +pub fn simulate_touch(cx: &mut App, window: u32, id: i32, phase: u32, x: f64, y: f64) { + if let Some(h) = cx.global::().windows.get(&window).cloned() { + let phase = match phase { + 0 => TouchPhase::Down, + 1 => TouchPhase::Move, + 2 => TouchPhase::Up, + _ => TouchPhase::Cancel, + }; + cx.simulate_touch(h.id, id, phase, x as f32, y as f32); + } +} + +/// A trackpad gesture at (x, y) in window `window` (tests; logical pixels): `kind` 0 pinches by +/// `amount` (the scale change), 1 turns by `amount` degrees. +pub fn simulate_gesture(cx: &mut App, window: u32, kind: u32, x: f64, y: f64, amount: f64) { + if let Some(h) = cx.global::().windows.get(&window).cloned() { + let (x, y, amount) = (x as f32, y as f32, amount as f32); + match kind { + 0 => cx.simulate_magnify(h.id, x, y, amount), + _ => cx.simulate_rotate(h.id, x, y, amount), + } + } +} + // ========================================================================== // Measuring (benchmarks): the same counters as bench/common/measure.rs. diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rs index 42978ec3..9132b974 100644 --- a/bindings/rust/blenderui-node/src/lib.rs +++ b/bindings/rust/blenderui-node/src/lib.rs @@ -31,7 +31,8 @@ type Tsfn = ThreadsafeFunction; // Values crossing the boundary /// An event from a window (`kind`: click, mousedown, mouseup, mousemove, -/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, frame, close). +/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, pinch, rotate, pan, frame, +/// close); the fields as in `blenderui_jsview::Event`. #[napi(object)] #[derive(Clone, Default)] pub struct BuiEvent { @@ -45,6 +46,9 @@ pub struct BuiEvent { pub button: u32, pub click_count: u32, pub delta: f64, + pub delta_x: f64, + pub delta_y: f64, + pub phase: Option, pub key: Option, pub key_char: Option, pub value: Option, @@ -62,7 +66,8 @@ impl From for BuiEvent { fn from(e: view::Event) -> BuiEvent { BuiEvent { kind: e.kind, window: e.window, target: e.target, x: e.x, y: e.y, button: e.button, - click_count: e.click_count, delta: e.delta, key: e.key, key_char: e.key_char, value: e.value, + click_count: e.click_count, delta: e.delta, delta_x: e.delta_x, delta_y: e.delta_y, + phase: e.phase.map(str::to_owned), key: e.key, key_char: e.key_char, value: e.value, checked: e.checked, number: e.number, shift: e.shift, ctrl: e.ctrl, alt: e.alt, values: e.values, } } @@ -550,6 +555,19 @@ impl NativeApp { pub fn simulate_pointer(&self, window: u32, kind: u32, x: f64, y: f64) { self.link.send(move |cx| view::simulate_pointer(cx, window, kind, x, y)); } + + /// A touch screen contact in window `window` (tests; logical pixels): `phase` 0 down, 1 move, 2 up, 3 cancel. + #[napi] + pub fn simulate_touch(&self, window: u32, id: i32, phase: u32, x: f64, y: f64) { + self.link.send(move |cx| view::simulate_touch(cx, window, id, phase, x, y)); + } + + /// A trackpad gesture in window `window` (tests; logical pixels): `kind` 0 pinches by `amount` + /// (the scale change), 1 turns by `amount` degrees. + #[napi] + pub fn simulate_gesture(&self, window: u32, kind: u32, x: f64, y: f64, amount: f64) { + self.link.send(move |cx| view::simulate_gesture(cx, window, kind, x, y, amount)); + } } // ========================================================================== diff --git a/bindings/rust/blenderui-qjs/src/lib.rs b/bindings/rust/blenderui-qjs/src/lib.rs index 09be85dc..eddb06c5 100644 --- a/bindings/rust/blenderui-qjs/src/lib.rs +++ b/bindings/rust/blenderui-qjs/src/lib.rs @@ -332,6 +332,9 @@ fn event_object<'js>(ctx: &Ctx<'js>, e: view::Event) -> rquickjs::Result c_int; pub fn BK_scroll_px(ctx: *mut BKContext, x: c_int, y: c_int, dx: f32, dy: f32, mods: c_int) -> c_int; + pub fn BK_touch(ctx: *mut BKContext, id: c_int, phase: c_int, x: f32, y: f32, time_ms: f64, 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_taken(ctx: *mut BKContext); diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs index 3c295cbd..ad2369b6 100644 --- a/bindings/rust/blenderui/src/element.rs +++ b/bindings/rust/blenderui/src/element.rs @@ -58,6 +58,9 @@ pub(crate) struct Listeners { pub mouse_move: Vec>, pub hover: Vec>, pub scroll: Vec>, + pub pan: Vec>, + pub pinch: Vec>, + pub rotate: Vec>, pub key_down: Vec>, pub key_up: Vec>, pub change: Vec>, @@ -374,6 +377,22 @@ impl Div { self.listeners_mut().scroll.push(Box::new(f)); self } + /// A finger dragging the content (a touch scroll and its fling), before it scrolls: stop the + /// propagation to take it (see [`PanEvent`]). + pub fn on_pan(mut self, f: impl Fn(&PanEvent, &mut Window, &mut App) + 'static) -> Self { + self.listeners_mut().pan.push(Box::new(f)); + self + } + /// Two fingers spreading or closing, or a trackpad pinch (see [`PinchEvent`]). + pub fn on_pinch(mut self, f: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self { + self.listeners_mut().pinch.push(Box::new(f)); + self + } + /// Two fingers turning, or a trackpad turn (see [`RotateEvent`]). + pub fn on_rotate(mut self, f: impl Fn(&RotateEvent, &mut Window, &mut App) + 'static) -> Self { + self.listeners_mut().rotate.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 e5ed48ee..3cf1d1be 100644 --- a/bindings/rust/blenderui/src/events.rs +++ b/bindings/rust/blenderui/src/events.rs @@ -95,6 +95,70 @@ pub struct ScrollWheelEvent { pub modifiers: Modifiers, } +/// Content a finger (or two) drags: the scroll a touch screen makes, Blender's MOUSEPAN +/// (`on_pan`). It comes before the scroll; a listener that calls `cx.stop_propagation()` takes +/// it, and nothing scrolls (a map that pans itself). +#[derive(Clone, Debug)] +pub struct PanEvent { + /// Where the drag began (the fingers' centre for two), relative to the window. + pub position: Point, + /// Logical pixels the content follows the fingers since the last one: x right, y down. Each + /// axis can come as an event of its own; the last one (`ScrollPhase::End`) is zero. + pub delta: Point, + /// `Drag` while a finger is down, `Fling` as the content coasts on after it, `End` when it + /// lifted. + pub phase: ScrollPhase, + pub modifiers: Modifiers, +} + +/// A pinch: two fingers spreading or closing about their centre, or a trackpad's (Blender's +/// MOUSEZOOM; `on_pinch`). +#[derive(Clone, Debug)] +pub struct PinchEvent { + /// The centre: between the fingers, or the pointer for a trackpad. + pub position: Point, + /// The scale change since the last one: 0.1 is 10% larger, -0.1 10% smaller (a zoom is + /// multiplied by `1.0 + delta`). + pub delta: f32, + pub modifiers: Modifiers, + /// From a touch screen (`false`: a trackpad). + pub touch: bool, +} + +/// A turn of two fingers about their centre, or a trackpad's (Blender's MOUSEROTATE; +/// `on_rotate`). +#[derive(Clone, Debug)] +pub struct RotateEvent { + /// The centre: between the fingers, or the pointer for a trackpad. + pub position: Point, + /// Degrees since the last one, positive counter-clockwise. + pub degrees: f32, + pub modifiers: Modifiers, + /// From a touch screen (`false`: a trackpad). + pub touch: bool, +} + +/// One step of a touch screen contact ([`App::simulate_touch`](crate::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 { + Self::Down => sys::BK_TOUCH_DOWN, + Self::Move => sys::BK_TOUCH_MOVE, + Self::Up => sys::BK_TOUCH_UP, + Self::Cancel => sys::BK_TOUCH_CANCEL, + } + } +} + /// A key: `key` is the keysym (`"a"`, `"Return"`, `"Left"` ...). #[derive(Clone, Debug)] pub struct Keystroke { diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index 061b0cac..faa0f7b1 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -1087,6 +1087,29 @@ impl App { }); } + /// A touch screen contact at (x, y), logical pixels: `id` tells the fingers apart. The kit's + /// touch model makes of the contacts what it makes of a real screen's (taps, scrolls and + /// flings, long presses, two-finger pans, pinches and turns). + pub fn simulate_touch(&mut self, window: WindowId, id: i32, phase: TouchPhase, x: f32, y: f32) { + self.input(window, |ctx, s| unsafe { + sys::BK_touch(ctx, id, phase.to_kit(), x * s, y * s, 0.0, 0); + }); + } + + /// A trackpad pinch at (x, y): `delta` is the scale change (0.1 = 10% larger). + pub fn simulate_magnify(&mut self, window: WindowId, x: f32, y: f32, delta: f32) { + self.input(window, |ctx, s| unsafe { + sys::BK_magnify(ctx, (x * s) as c_int, (y * s) as c_int, delta, 0); + }); + } + + /// A trackpad turn at (x, y): degrees, positive counter-clockwise. + pub fn simulate_rotate(&mut self, window: WindowId, x: f32, y: f32, degrees: f32) { + self.input(window, |ctx, s| unsafe { + sys::BK_rotate(ctx, (x * s) as c_int, (y * s) as c_int, degrees, 0); + }); + } + /// Type text / press a key (`keysym` as in Tk: "Return", "BackSpace", "a" ...). pub fn simulate_key(&mut self, window: WindowId, text: &str, keysym: &str) { let (t, k) = (CString::new(text).unwrap_or_default(), CString::new(keysym).unwrap_or_default()); @@ -2347,9 +2370,10 @@ impl Window { self.lent_bounds.first().map(|&(k, _)| k) } + /// True when a listener stopped the propagation (it took the event). 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(); self.lent_bounds.clear(); @@ -2369,11 +2393,13 @@ impl Window { } cur = frame.nodes[i].parent; } + let stopped = !app.propagate; app.propagate = true; self.lent_bounds.clear(); if self.frame.is_none() { self.frame = Some(frame); } + stopped } /// The element keys under the pointer, and (when the pointer moved: `measure`) whether it is over @@ -2600,19 +2626,34 @@ impl Window { } sys::BK_EV_WHEEL => { let (modifiers, _) = self.pointer_event(&ev.text); - // the third number of the text: how the scroll came (BK_scroll_phase) - let phase = ScrollPhase::from_kit(ev.text.split_whitespace().nth(2).and_then(|v| v.parse().ok()).unwrap_or(0)); - let (px_, py_) = self.pointer; + // after "mods button": how the scroll came (BK_scroll_phase), then where, relative + // to the canvas (a touch scroll moves no pointer there) + let mut rest = ev.text.split_whitespace().skip(2).map(|v| v.parse::().unwrap_or(0)); + let phase = ScrollPhase::from_kit(rest.next().unwrap_or(0)); + let (px_, py_) = match (rest.next(), rest.next()) { + (Some(ex), Some(ey)) => (ex as f32 / self.scale, ey as f32 / self.scale), + _ => self.pointer, + }; // `b`: the exact device pixels of a touch drag (BK_scroll_px), 0 for a wheel notch let pixels = (ev.b != 0.0).then(|| ev.b as f32 / self.scale); - let e = ScrollWheelEvent { position: point(px(px_), px(py_)), delta: ev.a as f32, pixels, phase, modifiers }; + let position = point(px(px_), px(py_)); let path = self.path_at(px_, py_); - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); + let Some(&deepest) = path.last() else { return }; + if phase != ScrollPhase::Wheel { + // a finger drags the content: `on_pan` first, which may take it (a sideways + // touch scroll comes as Shift + wheel) + let d = px(pixels.unwrap_or(0.0)); + let delta = if modifiers.shift { point(d, px(0.0)) } else { point(px(0.0), d) }; + if self.emit(app, deepest, &PanEvent { position, delta, phase, modifiers }, |l| l.pan.iter().collect()) { + return; + } } + let e = ScrollWheelEvent { position, delta: ev.a as f32, pixels, phase, modifiers }; + self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); // a touch drag follows the finger: it snaps no step (browsers snap such a gesture at its end) self.scroll_by(&path, -pixels.unwrap_or(ev.a as f32 * 40.0), modifiers.shift, pixels.is_none()); } + 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(); @@ -2645,6 +2686,26 @@ impl Window { } } + /// A pinch or a turn (`BK_EV_GESTURE`: text "mods kind x y", device pixels from the canvas; `a` + /// the amount): `on_pinch` / `on_rotate` from the element under its centre up. + 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 Some(&deepest) = self.path_at(x, y).last() else { return }; + let (position, modifiers, touch) = (point(px(x), px(y)), Modifiers::from_kit(mods), mods & sys::BK_FROM_TOUCH != 0); + let amount = ev.a as f32; + match kind { + sys::BK_GESTURE_MAGNIFY => { + self.emit(app, deepest, &PinchEvent { position, delta: amount, modifiers, touch }, |l| l.pinch.iter().collect()); + } + sys::BK_GESTURE_ROTATE => { + self.emit(app, deepest, &RotateEvent { position, degrees: amount, modifiers, touch }, |l| l.rotate.iter().collect()); + } + _ => {} + } + } + /// A click on element `target`: its `
` opens or closes, its listeners run, its window /// control acts. fn click(&mut self, app: &mut App, target: Key, e: &ClickEvent) { @@ -2783,8 +2844,12 @@ impl Window { 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 { + // where an earlier scroll of this turn put it (a diagonal touch scroll comes as two + // events before the next layout), else where it was drawn + let (sx, sy) = self.state.scroll.get(key).copied().unwrap_or(n.scroll_pos); + // a wheel over content with no vertical range scrolls it sideways; a finger keeps to + // the axis it moved along + let (nx, ny) = if horizontal || (ry <= 0.0 && snaps) { ((sx + dy).clamp(0.0, rx), sy) } else { (sx, (sy + dy).clamp(0.0, ry)) diff --git a/bindings/rust/blenderui/tests/suite/main.rs b/bindings/rust/blenderui/tests/suite/main.rs index 4d72291d..3eac4ad1 100644 --- a/bindings/rust/blenderui/tests/suite/main.rs +++ b/bindings/rust/blenderui/tests/suite/main.rs @@ -56,6 +56,7 @@ mod text_overflow; mod text_translate; mod textarea_grow; mod titlebar; +mod touch; mod vector_transforms; mod vlist; mod vlist_custom; diff --git a/bindings/rust/blenderui/tests/suite/touch.rs b/bindings/rust/blenderui/tests/suite/touch.rs new file mode 100644 index 00000000..f6bac77c --- /dev/null +++ b/bindings/rust/blenderui/tests/suite/touch.rs @@ -0,0 +1,134 @@ +//! Touch screens and trackpads: `on_pinch`, `on_rotate` and `on_pan` listeners, a tap's click and +//! a finger's scroll, driven through `simulate_touch` / `simulate_magnify` / `simulate_rotate` +//! (the kit's touch model, as a window host feeds it). + +use std::sync::Mutex; + +use blenderui::prelude::*; + +fn open(cx: &mut App, w: f32, h: f32, v: V) -> WindowHandle { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(w), px(h)) })), + ..Default::default() + }; + cx.open_window(opts, |_, cx| cx.new(|_| v)).unwrap() +} + +fn rows() -> Div { + let mut rows = div().flex().flex_col(); + for i in 0..40 { + rows = rows.child(div().h(px(20.0)).child(format!("Row {i}"))); + } + rows +} + +static PINCHES: Mutex> = Mutex::new(Vec::new()); +static TURNS: Mutex> = Mutex::new(Vec::new()); + +struct Map; + +impl Render for Map { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .id("map") + .w(px(300.0)) + .h(px(200.0)) + .on_pinch(|e, _, _| PINCHES.lock().unwrap().push((e.delta, e.position.x.0, e.position.y.0, e.touch))) + .on_rotate(|e, _, _| TURNS.lock().unwrap().push((e.degrees, e.touch))) + } +} + +#[test] +fn two_fingers_pinch_and_turn_an_element_and_so_does_a_trackpad() { + Application::headless().run(|cx| { + let win = open(cx, 300.0, 200.0, Map); + cx.draw(win.id); + // spread from 100 px apart to 200 about (150, 100) + cx.simulate_touch(win.id, 1, TouchPhase::Down, 100.0, 100.0); + cx.simulate_touch(win.id, 2, TouchPhase::Down, 200.0, 100.0); + for i in 1..=5 { + let d = 10.0 * i as f32; + cx.simulate_touch(win.id, 1, TouchPhase::Move, 100.0 - d, 100.0); + cx.simulate_touch(win.id, 2, TouchPhase::Move, 200.0 + d, 100.0); + } + cx.simulate_touch(win.id, 1, TouchPhase::Up, 50.0, 100.0); + cx.simulate_touch(win.id, 2, TouchPhase::Up, 250.0, 100.0); + let pinches = std::mem::take(&mut *PINCHES.lock().unwrap()); + assert_eq!(pinches.len(), 5, "{pinches:?}"); + let scale: f32 = pinches.iter().map(|p| 1.0 + p.0).product(); + assert!((scale - 2.0).abs() < 1e-3, "scale {scale}"); + assert!(pinches.iter().all(|p| (p.1 - 150.0).abs() < 1.0 && (p.2 - 100.0).abs() < 1.0 && p.3)); + assert!(TURNS.lock().unwrap().is_empty(), "a straight spread is no turn"); + + // a trackpad's pinch and turn: not from a touch screen + cx.simulate_magnify(win.id, 120.0, 80.0, 0.25); + cx.simulate_rotate(win.id, 120.0, 80.0, 30.0); + let pinches = std::mem::take(&mut *PINCHES.lock().unwrap()); + assert_eq!(pinches.len(), 1); + assert!((pinches[0].0 - 0.25).abs() < 1e-6 && !pinches[0].3); + assert_eq!(*TURNS.lock().unwrap(), vec![(30.0, false)]); + }); +} + +static CLICKS: Mutex = Mutex::new(0); +static PANS: Mutex> = Mutex::new(Vec::new()); +static TAKE_PANS: Mutex = Mutex::new(false); + +struct Page; + +impl Render for Page { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + app() + .child(div().id("top").h(px(20.0)).on_click(|_, _, _| *CLICKS.lock().unwrap() += 1).child("top")) + .child(rows()) + .on_pan(|e, _, cx| { + PANS.lock().unwrap().push((e.delta.x.0, e.delta.y.0, e.phase)); + if *TAKE_PANS.lock().unwrap() { + cx.stop_propagation(); + } + }) + } +} + +#[test] +fn a_tap_clicks_and_a_finger_scrolls_unless_a_pan_listener_takes_it() { + Application::headless().run(|cx| { + let win = open(cx, 300.0, 200.0, Page); + cx.draw(win.id); + cx.draw(win.id); + // a tap on the first row: a click + cx.simulate_touch(win.id, 1, TouchPhase::Down, 20.0, 10.0); + cx.simulate_touch(win.id, 1, TouchPhase::Up, 21.0, 10.0); + assert_eq!(*CLICKS.lock().unwrap(), 1); + + // a finger dragged up by 58 px (8 of them the touch slop) scrolls the page by 50, with + // the pointer left elsewhere: the scroll is where the finger is + cx.simulate_mouse_move(win.id, -10.0, -10.0); + let at = cx.element_bounds(win.id, "top").unwrap().origin.y; + cx.simulate_touch(win.id, 2, TouchPhase::Down, 150.0, 150.0); + for i in 1..=4 { + cx.simulate_touch(win.id, 2, TouchPhase::Move, 150.0, 150.0 - 14.5 * i as f32); + } + cx.draw(win.id); + let moved = at - cx.element_bounds(win.id, "top").unwrap().origin.y; + assert!((moved - 50.0).abs() < 0.5, "scrolled {moved}"); + let pans = std::mem::take(&mut *PANS.lock().unwrap()); + assert!(pans.iter().all(|p| p.2 == ScrollPhase::Drag && p.0 == 0.0), "{pans:?}"); + assert!((pans.iter().map(|p| p.1).sum::() + 50.0).abs() < 0.5, "{pans:?}"); + // rested before lifting: the end, no fling, and no click + std::thread::sleep(std::time::Duration::from_millis(60)); + cx.simulate_touch(win.id, 2, TouchPhase::Up, 150.0, 92.0); + assert_eq!(PANS.lock().unwrap().last().map(|p| p.2), Some(ScrollPhase::End)); + assert_eq!(*CLICKS.lock().unwrap(), 1); + + // a pan listener that stops the propagation takes the drag: nothing scrolls + *TAKE_PANS.lock().unwrap() = true; + let before = cx.element_bounds(win.id, "top").unwrap().origin.y; + cx.simulate_touch(win.id, 3, TouchPhase::Down, 150.0, 150.0); + cx.simulate_touch(win.id, 3, TouchPhase::Move, 150.0, 100.0); + cx.simulate_touch(win.id, 3, TouchPhase::Cancel, 150.0, 100.0); + cx.draw(win.id); + assert_eq!(cx.element_bounds(win.id, "top").unwrap().origin.y, before); + assert!(!PANS.lock().unwrap().is_empty()); + }); +} diff --git a/docs/android.md b/docs/android.md index b6f788ea..21f8f870 100644 --- a/docs/android.md +++ b/docs/android.md @@ -35,7 +35,7 @@ Needs the Android SDK (`ANDROID_HOME`; build-tools, platform 34), an NDK (the ne | **Rust** | an ordinary `blenderui` app in a `staticlib` crate with `blenderui::android_main!(run);`, where `run` is the `fn()` a desktop `main` would call (`platform/android/rust`) | `--rust CRATE` | | **Lua** | an ordinary BUI Lua script, `assets/main.lua`, ending in `bui.open{root=...}` or `bui.Window(...)` + `bui.run()`; `require` finds your other `.lua` files and `bui.lua` in the APK | `--lua DIR` | | **JavaScript** | an ordinary `@blender-ui/native`, React, Vue or Svelte app (`.js`, `.jsx`, `.vue`, `.svelte`); it is bundled into one script (`bui bundle`, needs Bun) and runs on QuickJS (`bindings/rust/blenderui-qjs`, the engine `bui build` embeds), as `assets/main.js`; `console.log` goes to logcat (tag `bui-js`) | `--js ENTRY` | -| **Dear ImGui** | an ordinary ImGui frame function in a C++ file with `bui_app_main` (`ImGui_ImplBUI_CreateApp` / `RunApp`; `platform/android/imgui_app.cpp`), plus `BK_window_wm(win, "touch_drag", 1, 0)` so a drag is ImGui's (sliders, window moves) | `--imgui [FILE]` | +| **Dear ImGui** | an ordinary ImGui frame function in a C++ file with `bui_app_main` (`ImGui_ImplBUI_CreateApp` / `RunApp`; `platform/android/imgui_app.cpp`); a drag is ImGui's (sliders, window moves), since the adapter puts its node in `BK_TOUCH_MODE_POINTER` | `--imgui [FILE]` | | **C** | `void bui_app_main(void)`: build nodes, `BK_context_new`, `BK_window_new`, `BK_window_run` (`platform/android/demo.c`) | the default | Python, Qt, tkinter and D are not available on Android: each needs its @@ -70,14 +70,16 @@ A real app is SpotiTube-sized: a library crate shared with the desktop `main`, p and locked. Idle cost: 0 CPU ticks in 10 s on the emulator, for the C and the Rust app. - **Scale.** A CSS pixel is a dp, as in Chrome on Android: the kit's scale is the screen density (`dpi / 160`), so Rust layout and Blender's 20-unit widgets come out at a phone's size. -- **Touch.** One finger is the pointer. A tap is a click (sent when the finger lifts in place). A drag - that starts on a widget that drags (sliders, number fields, text, scrollbars, panels) drags it; - anywhere else it scrolls. The content follows the finger exactly (`BK_scroll_px`: the distance in - pixels, not a wheel notch per touch event) and keeps going after the finger lifts at the velocity of - the last 100 ms, slowing down the way UIScrollView does (0.998 per millisecond); a touch stops it. A - touch in the 20 dp strip at the right edge of a custom or canvas node is the app's press and drag - (a list's scrollbar thumb), so a huge list can be dragged to any place. Two fingers always scroll. `BK_window_wm(win, "touch_drag", 1, 0)` gives - the drags of custom and canvas nodes to the app instead (a paint app); by default they scroll. +- **Touch.** The host forwards every pointer of a motion event (batched history first) to the kit's + touch model (`BK_touch`), the same one every window host uses: see [touch.md](touch.md). A tap + is a click, a drag that starts on a widget that drags (sliders, number fields, text, scrollbars) + drags it, and anywhere else it scrolls, following the finger exactly and flinging on along + Android's `OverScroller` curve when it lifts; a touch stops the fling. A long press opens the + context menu, and two fingers pan, pinch and turn. A touch in the 20 dp strip at the right edge + of a custom or canvas node is the app's press and drag (a list's scrollbar thumb), so a huge list + can be dragged to any place. The old `BK_window_wm(win, "touch_drag", 1, 0)` key is gone: a custom + node that wants a finger's drag (a paint app) calls `BK_custom_set_touch(node, + BK_TOUCH_MODE_POINTER)`, or `BK_TOUCH_MODE_RAW` for every contact. - **Back.** The Back key is the key `Escape`. It closes a popup or leaves a text field first; a Rust key listener that acts on it calls `app.prevent_default()` (C bindings: `BK_key_taken`), and only a Back nothing took finishes the activity. An app with screens of its own walks back through them @@ -124,6 +126,6 @@ Run on an x86_64 emulator (API 33): the C demo, the Lua app (a button callback u Rust app (a button, a text input, scrolling with the scrollbar). The arm64-v8a builds of all three compile and link but were not run on a device. -Not done: a GPU renderer (OpenGL ES would reuse `gpu_gl.c`, untested), long-press as right-click, pinch, +Not done: a GPU renderer (OpenGL ES would reuse `gpu_gl.c`, untested), IME composition, a clipboard beyond the app's own, cutout insets beyond the content rectangle, and touch text selection in Rust pages (a drag scrolls). diff --git a/docs/c-api.md b/docs/c-api.md index f56c2c3a..a91dbed7 100644 --- a/docs/c-api.md +++ b/docs/c-api.md @@ -77,16 +77,16 @@ int main(void) | **Nodes** | `BK_node_new(type)`, `BK_node_add(parent, child, index)` (0 for a node under itself), `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_cancel` (the host lost the pointer mid-press: a drag is cancelled as on Escape and the press ends with no click), `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). `BK_configure(ctx, w, h)` reports a new window size (`BK_EV_CONFIGURE`) without drawing, so a host whose handlers rebuild the tree (the Rust binding) can do that before the first draw at the new size; `BK_render` calls it itself. | +| **Context** | `BK_context_new(root)`: input state, popups, focus, undo. Input goes in with `BK_press`, `BK_release`, `BK_motion`, `BK_cancel` (the host lost the pointer mid-press: the pressed widget's interaction is cancelled as on Escape, moved or not, the press ends with no click, and every touch contact is cancelled; window hosts call it when the window loses the focus), `BK_wheel`, `BK_scroll`, `BK_scroll_px`, `BK_key`, `BK_key_release`, `BK_button`, `BK_context_menu`, touch screens and trackpads with `BK_touch`, `BK_magnify`, `BK_rotate` (see [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). `BK_configure(ctx, w, h)` reports a new window size (`BK_EV_CONFIGURE`) without drawing, so a host whose handlers rebuild the tree (the Rust binding) can do that before the first draw at the new size; `BK_render` calls it itself. | | **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. | +| **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` / `GESTURE` (a pinch or turn: `ref` = `"mods kind x y"`, `a` = the amount), plus `VIEW` and `SCROLL` for scrolling. Events the kit makes from a finger carry `BK_FROM_TOUCH` in their mods. | | **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`, `hit_test` (the parts of a title bar the app draws: `"override"` 2), `move`, `timer`, `run`, `pump`, `quit` | | **GPU rendering** | `BUI_gpu_set_default(1)` (all new windows), `BK_window_set_gpu(win, 1)` (one window), `BK_window_gpu(win)` (1 once frames draw on the GPU). `BUI_GPU=1/0` overrides. On Windows, `BUI_gpu_set_api(BUI_GPU_API_D3D12)` picks Direct3D 12 and `BUI_gpu_set_adapter(BUI_GPU_ADAPTER_HIGH_PERFORMANCE)` the discrete GPU of a hybrid laptop (`BUI_GPU_API` / `BUI_GPU_ADAPTER` override). For your own rasters: `BUI_raster_gpu_attach(r, hwnd_or_NULL, wait)`, `BUI_raster_gpu_poll`, `BUI_raster_is_gpu`. | | **Theme** | `BK_set_theme("dark" / "light")` (Blender's Dark or Light preset; every context relayouts and redraws), `BK_theme_name()`, `BK_theme_color(key, rgba)` (`"region_bg"`, `"text"`, `"regular.inner"`, or the plain-English and Blender keys of a theme file: `"button.background"`, `"user_interface.wcol_regular.inner"`). Your own themes: `BK_theme_load_file(path)` / `BK_theme_load_json(text)` register the themes of a JSON theme file (-1 and `BK_theme_error()` on a mistake), `BK_set_theme(name)` chooses one, `BK_theme_set_color(key, rgba)` / `BK_theme_set_num(key, v)` change one value of the active theme (colors, `roundness`, `border.width`, `corners.top_left`, ...), `BK_set_font_size(points)` sets the UI text size; see [theming.md](theming.md). Without a call, `BUI_THEME=dark\|light` picks the theme. `BK_set_scale` sets the UI scale; `BK_set_text_shadow(0)` turns off Blender's UI text shadows (on by default; Python turns them off). | | **Text** | `BUI_text_measure`, `BUI_raster_text`, `BUI_text_add_font(family, flags, data, len)` (register a font; needed on wasm), `BUI_text_font_dir(i, buf, cap)` (the font folders the engine reads files from), `BUI_text_vmetrics(family, flags, &ascent, &descent, &gap)` (a font's vertical metrics in em, for line heights and baselines); text flags `BUI_FONT_BOLD`, `BUI_FONT_ITALIC`, and `BUI_FONT_HAN_JA` / `BUI_FONT_HAN_KO` (Han in the run is drawn as Japanese / Korean, for text drawn a word at a time) | | **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, pinches and turns as `BK_CUSTOM_MAGNIFY` / `ROTATE`; what a finger does on it is `BK_custom_set_touch(node, BK_TOUCH_MODE_SCROLL / POINTER / RAW)`, see [touch.md](touch.md#custom-nodes)), `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). | | **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. | | **GPU effects** | Your own pixel shader over a canvas item: `BK_effect_create(name, source, n_inputs, n_floats)` (an id > 0, 0 for bad arguments), `BK_effect_free`, `BK_effect_error(id)` (the compile/link log of the last GPU attempt: "" when fine, NULL for an unknown id), then a `BK_ITEM_EFFECT` canvas item (`effect`, `effect_inputs[8]` BUI textures, `effect_floats`; its image is the fallback), or `BUI_raster_effect` on a raster. The source is GLSL with a small compat set, compiled at run time by Direct3D 11 (`d3dcompiler_47.dll`, loaded dynamically) and OpenGL; the software raster draws the fallback. See [GPU effects](../website/src/content/docs/rust/gpu-effects.mdx). | diff --git a/docs/rust.md b/docs/rust.md index 62e0963b..0240172f 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -445,12 +445,33 @@ gets `on_click`. | `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | yes | | `on_hover` | `bool`: entered / left | no | | `on_scroll_wheel` | `ScrollWheelEvent { position, delta, pixels, phase, modifiers }` | yes | +| `on_pan` | `PanEvent { position, delta, phase, modifiers }`: a finger (or two) dragging the content, before it scrolls | yes | +| `on_pinch` | `PinchEvent { position, delta, modifiers, touch }`: two fingers or a trackpad pinch | yes | +| `on_rotate` | `RotateEvent { position, degrees, modifiers, touch }`: two fingers or a trackpad turn | 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 | Positions are logical pixels. Clicking an element focuses it; key events go to the focused element and bubble up. `cx.stop_propagation()` stops bubbling. +### Touch screens and trackpads + +A finger works as on a phone: a tap is a click, a drag scrolls (sliders and text fields drag +instead), a long press is a right press (the context menu), and two fingers pan, pinch and turn. The kit does this +for every platform ([touch.md](touch.md)); the element only listens: + +- `on_pan(|e: &PanEvent, window, cx| ..)` runs before the scroll. `e.delta` is the logical + pixels the content follows the fingers (x right, y down; each axis may come as its own event), + `e.phase` is `ScrollPhase::Drag`, then `Fling` as it coasts on, then `End` (zero delta). Call + `cx.stop_propagation()` to take the drag: nothing scrolls (a map that pans itself). +- `on_pinch(|e: &PinchEvent, ..| ..)`: `e.delta` is the scale change since the last one (0.1 is + 10% larger: multiply a zoom by `1.0 + e.delta`) about `e.position`. +- `on_rotate(|e: &RotateEvent, ..| ..)`: `e.degrees` since the last one, positive counter-clockwise. + +`e.touch` is `true` for a touch screen's two fingers and `false` for a trackpad. In `rsx!` they +are `onPan`, `onPinch` and `onRotate`. A `ScrollWheelEvent`'s `position` is where the scroll is +(a finger's scroll moves no pointer), and a diagonal finger drag scrolls both axes. + ### Selecting text Text in elements is selectable like on a web page: press and drag (across words, @@ -630,6 +651,10 @@ Application::headless().run(|cx| { ``` Also `simulate_mouse_move`, `simulate_scroll`, `simulate_key(text, keysym)`, `simulate_key_with` (Ctrl, Shift), `simulate_click_with`, and `simulate_press`, `simulate_release`, `simulate_cancel` (the host lost the pointer: no release, no click, a drag goes back) and `simulate_drag(from, to)` for a held button. +Touch: `simulate_touch(win.id, id, TouchPhase::Down | Move | Up | Cancel, x, y)` feeds one contact +to the kit's touch model as a window host does (taps, scrolls, flings, two-finger gestures), and +`simulate_magnify(win.id, x, y, delta)` / `simulate_rotate(win.id, x, y, degrees)` are a +trackpad's pinch and turn (`tests/suite/touch.rs`). The kit has global state, so one `Application` runs at a time per process (`run` takes a lock; parallel tests queue up). diff --git a/docs/touch.md b/docs/touch.md new file mode 100644 index 00000000..df1eb138 --- /dev/null +++ b/docs/touch.md @@ -0,0 +1,223 @@ +# Touch screens and trackpad gestures + +A finger on a BUI window works as it does on a phone: a tap is a click, a drag scrolls and flings, +a long press opens the context menu, and two fingers pan, pinch and turn. Trackpad pinches and +turns reach the same places. The model lives in the kit (`kit/intern/kit_touch.c`), so it is the +same on every platform; a window host only forwards the contacts it gets (`BK_touch`) and the +trackpad's gestures (`BK_magnify`, `BK_rotate`). + +The numbers and curves are Android's (`ViewConfiguration`, `VelocityTracker`, `OverScroller`), and +the gestures land where Blender's trackpad events do: GHOST's `GHOST_kTrackpadEventScroll`, +`GHOST_kTrackpadEventMagnify` and `GHOST_kTrackpadEventRotate` become the window manager's +`MOUSEPAN`, `MOUSEZOOM` and `MOUSEROTATE` (`view2d_ops.cc`: `view_pan`, `view_zoom`). + +## What a finger does + +| Contact | Result | +|---|---| +| One finger on a widget with a drag of its own (slider, number or text field, scrollbar, node editor, a `BK_TOUCH_MODE_POINTER` custom node, the scrollbar strip at a page's right edge) | The pointer at once: motion, press, drag, release, with `BK_FROM_TOUCH` in the mods | +| One finger anywhere else, lifted in place | A click (a tap); two taps are a double click. For fingers the double-click slop is one widget unit | +| Held still for half a second (`DEFAULT_LONG_PRESS_TIMEOUT`) | A right press: the context menu (`BK_context_menu`) | +| Moved past the touch slop (8 dp, `TOUCH_SLOP`) | Scrolls what is under where it went down, exactly as far as it went (`BK_scroll_px` with `BK_SCROLL_DRAG`), from just past the slop so the content does not jump (RecyclerView's way) | +| Lifted while moving | The content flings on at the finger's velocity along `OverScroller`'s curve (`BK_SCROLL_FLING`, then `BK_SCROLL_END`). `BK_animating` is non-zero meanwhile and each `BK_render` steps it | +| A finger that lands on a fling | Stops it and clicks nothing | +| A second finger | Cancels what the first one did, as `BK_cancel` (a dragged value goes back, nothing is clicked). The two are a gesture until they lift | +| Two fingers moving together | Scroll (`MOUSEPAN`) | +| Two fingers spreading / turning | Magnify / rotate about their centre (`MOUSEZOOM`, `MOUSEROTATE`, as `BK_magnify`, `BK_rotate`) | +| `BK_TOUCH_CANCEL` | The platform took the contact back (a system gesture, a lost capture): nothing it did is kept | + +More rules: + +- Hosts report fingers one at a time, so a two-finger update waits until both moved (or one moved + twice). A pure pan does not wobble the spread and angle between them. +- After a gesture, no finger is the pointer again until all have lifted. A third finger is + followed but unused; up to ten contacts are followed. +- While a menu is open or a tool runs (the eyedropper), every finger is the pointer. +- No hover stays behind a finger: the pointer leaves when the finger that was it lifts. +- `BK_cancel` and a window losing the focus cancel every contact that is down. +- A finger's drag never warps the system pointer (the mouse's endless number-field drag does). +- A scroll keeps to its axis; a diagonal drag scrolls both. +- In the node editor two fingers pan the view and a pinch (or a trackpad's) zooms about the + centre. A link drag that is cancelled puts back a link it took off an input (`node_link_cancel`), + and `Delete` / `X` do nothing in the middle of a link or value drag. + +## C API (`kit/include/BUI_kit.h`) + +```c +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, double time_ms, int mods); +int BK_magnify(BKContext *ctx, int x, int y, float delta, int mods); /* trackpad pinch */ +int BK_rotate(BKContext *ctx, int x, int y, float degrees, int mods); /* trackpad turn */ +``` + +- `id` is the platform's id of the contact (unique while it is down). +- `x`, `y` are window pixels, as for `BK_motion`. A cancel's position is not used. +- `time_ms` is the event's own time in milliseconds on any monotonic clock; only differences + count (the fling's velocity). `<= 0` means now. +- `mods` are `BK_SHIFT | BK_CTRL | BK_ALT`. Hosts never pass `BK_FROM_TOUCH`: the kit sets it on + the pointer, scroll and gesture events it makes from contacts, so raw handlers and custom nodes + can tell a finger from the mouse. + +### Sign conventions + +| Value | Meaning | +|---|---| +| `BK_magnify` `delta` | The scale change since the last one: 0.1 is 10% larger, -0.1 smaller (`NSEvent.magnification`'s units). A zoom is multiplied by `1 + delta` | +| `BK_rotate` `degrees` | Degrees since the last one, positive counter-clockwise (`NSEvent.rotation`) | +| A pan | The content follows the fingers: a finger moving up scrolls the content up | + +### Forwarding contacts from your own host + +```c +/* one contact of a touch screen event: its id, phase and window position */ +static void on_touch(BKContext *ctx, int id, int kind, float x, float y, double ms, int mods) +{ + int phase = kind == MY_DOWN ? BK_TOUCH_DOWN : + kind == MY_UP ? BK_TOUCH_UP : + kind == MY_MOVE ? BK_TOUCH_MOVE : BK_TOUCH_CANCEL; + if (BK_touch(ctx, id, phase, x, y, ms, mods)) { + request_redraw(); + } +} + +/* a trackpad's pinch and turn about the pointer */ +BK_magnify(ctx, px, py, scale_change, mods); +BK_rotate(ctx, px, py, degrees_ccw, mods); + +/* every frame: render while the kit animates (a fling) */ +while (BK_animating(ctx)) { + BK_render(ctx, raster, w, h, 0); + present(); +} +``` + +Send a moved contact's batched history first, then its current place. Don't also send the mouse +messages a platform makes from a finger: the kit's model is the only one. + +### Raw events + +An `"events"` node gets `BK_EV_GESTURE` for a pinch or a turn over it: `ref` is +`"mods kind x y"` (`kind` `BK_GESTURE_MAGNIFY` or `BK_GESTURE_ROTATE`, `x`, `y` its centre relative +to the node) and `a` is the amount. A pan is a scroll: `BK_EV_WHEEL`, whose text is now +`"mods button phase x y"` (the phase is `BK_SCROLL_*`, `x`, `y` where the scroll is, relative to +the node: a finger's scroll moves no pointer there) and whose `b` is the exact pixels of +`BK_scroll_px`. + +### Custom nodes + +A custom node chooses what a finger does on it with `BK_custom_set_touch(node, mode)`: + +| Mode | A finger on the node | +|---|---| +| `BK_TOUCH_MODE_SCROLL` (default) | As on a phone: a tap is a click, a drag scrolls (the node gets `BK_CUSTOM_WHEEL`), the widget-unit strip at its right edge is its scrollbar's press and drag, two fingers pan, pinch and turn | +| `BK_TOUCH_MODE_POINTER` | The pointer at once: press, drag, release are the node's (Dear ImGui's sliders and window moves; the ImGui adapter sets it). Two fingers still pan, pinch and turn | +| `BK_TOUCH_MODE_RAW` | Every contact that begins over the node arrives as `BK_CUSTOM_TOUCH`, any number at once; the node does its own gestures | + +Pinches and turns (two fingers or a trackpad) arrive as `BK_CUSTOM_MAGNIFY` / `BK_CUSTOM_ROTATE`. +`BKCustomEvent` has the fields for them: `touch_id` and `touch_phase` (`BK_TOUCH_*`) for +`BK_CUSTOM_TOUCH`, `magnify` and `rotate` for the gestures, with `x`, `y` relative to the node. + +```c +static int paint_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + Paint *p = data; + switch (e->type) { + case BK_CUSTOM_TOUCH: /* one finger of many, as it is */ + if (e->touch_phase == BK_TOUCH_DOWN) stroke_begin(p, e->touch_id, e->x, e->y); + else if (e->touch_phase == BK_TOUCH_MOVE) stroke_add(p, e->touch_id, e->x, e->y); + else stroke_end(p, e->touch_id, e->touch_phase == BK_TOUCH_CANCEL); + break; + case BK_CUSTOM_MAGNIFY: /* a trackpad pinch (raw fingers make none) */ + p->zoom *= 1.0f + e->magnify; + break; + default: + return 0; + } + BK_node_invalidate(node); + return 1; +} + +BKCustomClass cls = {.event = paint_event, .draw = paint_draw}; +BK_custom_set(node, &cls, paint); +BK_custom_set_touch(node, BK_TOUCH_MODE_RAW); +``` + +## Platforms + +| Platform | Touch screen | Trackpad pinch and turn | +|---|---|---| +| Windows (`kit_window_win32.c`) | `WM_POINTER` (Windows 8 and later). Touch only: pen and mouse stay mouse messages. Windows makes no promoted mouse clicks or press-and-hold right click of the handled contacts. Physical-pixel positions are mapped to the client as the mouse's; `WM_POINTERCAPTURECHANGED` and a system-cancelled contact are `BK_TOUCH_CANCEL`; event times come from the performance counter | Not sent by the host | +| Linux X11 (`kit_window_x11.c`) | XInput 2.2 touch through libXi, loaded at run time (`libXi.so.6`) when the headers were there at build time; touch screens only (direct-touch devices). Without libXi the server emulates the pointer for the first finger, as before | XInput 2.4 pinch (libXi 1.8): `BK_magnify` and `BK_rotate` | +| Linux Wayland (`kit_window_wayland.c`) | `wl_touch` | `zwp_pointer_gestures_v1` pinch (when wayland-protocols has pointer-gestures at build time): `BK_magnify` and `BK_rotate` | +| macOS (`kit_window_cocoa.m`) | - | `magnifyWithEvent:` and `rotateWithEvent:` (`NSEvent.magnification`, `NSEvent.rotation`) | +| Android (`kit_window_android.c`) | Every pointer of a motion event, batched history first | - | +| Your own host, headless | Call `BK_touch`, `BK_magnify`, `BK_rotate` | | + +On Android the old Android-only touch code is gone, and so is `BK_window_wm(win, "touch_drag", 1, 0)`: +call `BK_custom_set_touch(node, BK_TOUCH_MODE_POINTER)` on the custom node instead (the Dear ImGui +adapter does this for its node). + +## Rust + +`blenderui` gives elements three listeners, from the element under the gesture's centre up: + +```rust +div() + .on_pan(|e: &PanEvent, _, cx| { + // e.delta: logical pixels the content follows the fingers (x right, y down) + // e.phase: ScrollPhase::Drag, then Fling, then End + cx.stop_propagation(); // take the drag: nothing scrolls + }) + .on_pinch(|e: &PinchEvent, _, _| { /* zoom *= 1.0 + e.delta, about e.position */ }) + .on_rotate(|e: &RotateEvent, _, _| { /* e.degrees, positive counter-clockwise */ }) +``` + +- `PanEvent { position, delta: Point, phase: ScrollPhase, modifiers }` comes before the + scroll; each axis may come as an event of its own, and the `End` one is zero. +- `PinchEvent { position, delta, modifiers, touch }` and `RotateEvent { position, degrees, + modifiers, touch }`: `touch` is `false` for a trackpad. +- In `rsx!`: `onPan`, `onPinch`, `onRotate`. +- `ScrollWheelEvent::position` is where the scroll is (a finger's scroll moves no pointer), and a + diagonal finger scroll keeps both axes. + +`blenderui-sys` has `BK_EV_GESTURE`, `BK_GESTURE_*`, `BK_FROM_TOUCH`, `BK_TOUCH_*` and the three +functions. + +## Other bindings + +The other language bindings expose the same calls and the same raw `BK_EV_GESTURE` event (its +text is "mods kind x y"), with the constants for the phases, kinds, modes and `BK_FROM_TOUCH`: + +| Binding | Calls | +| --- | --- | +| Python | `ctx.touch(id, phase, x, y, time_ms=0, mods=0)`, `ctx.magnify(x, y, delta, mods=0)`, `ctx.rotate(x, y, degrees, mods=0)`; `EV_GESTURE`, `TOUCH_*`, `GESTURE_*`, `FROM_TOUCH` | +| Lua | `ctx:touch(id, phase, x, y [, time_ms [, mods]])`, `ctx:magnify(x, y, delta [, mods])`, `ctx:rotate(...)`, `node:custom_set_touch(mode)`; raw handlers get the event text as a 4th argument | +| D | `Context.touch(id, phase, x, y, timeMs = 0, mods = 0)`, `Context.magnify`, `Context.rotate`, `setTouch(node, mode)`; `CustomEvent.touchId / touchPhase / magnify / rotate` | +| Ruby | `Context#touch(id, phase, x, y, time_ms = 0, mods = 0)`, `#magnify`, `#rotate`; `node.on(:gesture)` | +| Go | `(*Context).Touch(id, phase, x, y, timeMs, mods)`, `Magnify`, `Rotate`; `EventGesture` | +| Dear ImGui | the adapter sets `BK_TOUCH_MODE_POINTER` on its node and reports fingers as `ImGuiMouseSource_TouchScreen` | + +## Testing + +Headless, drive contacts as a host would: + +- C: call `BK_touch` with ids and phases and `BK_render` between them (`tests/touch_test.c`, run by + `ctest` as `bui_touch_test`: taps, scrolls and flings, a second finger's gesture, raw contacts, + cancels, the node editor, menus). +- Rust: `cx.simulate_touch(win.id, id, TouchPhase::Down | Move | Up | Cancel, x, y)` and the + trackpad's `cx.simulate_magnify(win.id, x, y, delta)` and `cx.simulate_rotate(win.id, x, y, + degrees)` (`bindings/rust/blenderui/tests/suite/touch.rs`). + +```rust +// two fingers spread from 100 px apart to 200 about (150, 100): the element's pinches +// multiply to 2.0 +cx.simulate_touch(win.id, 1, TouchPhase::Down, 100.0, 100.0); +cx.simulate_touch(win.id, 2, TouchPhase::Down, 200.0, 100.0); +for i in 1..=5 { + let d = 10.0 * i as f32; + cx.simulate_touch(win.id, 1, TouchPhase::Move, 100.0 - d, 100.0); + cx.simulate_touch(win.id, 2, TouchPhase::Move, 200.0 + d, 100.0); +} +cx.simulate_touch(win.id, 1, TouchPhase::Up, 50.0, 100.0); +cx.simulate_touch(win.id, 2, TouchPhase::Up, 250.0, 100.0); +``` diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt index b01f08af..e39241a2 100644 --- a/kit/CMakeLists.txt +++ b/kit/CMakeLists.txt @@ -35,6 +35,7 @@ add_library(bui_kit STATIC intern/screen/screen_ops.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 @@ -394,6 +395,13 @@ 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 (wayland-protocols 1.4+): touchpad pinches, as GHOST + 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 0558197e..b71ab8e1 100644 --- a/kit/include/BUI_kit.h +++ b/kit/include/BUI_kit.h @@ -69,8 +69,18 @@ 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 is the kit's own: it marks the + * pointer, scroll and gesture events it makes from touch screen contacts (BK_touch), so raw event + * handlers and custom nodes can tell a finger from the mouse. 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 { @@ -118,9 +128,16 @@ enum { BK_EV_RESIZE, /* an area's region was resized, hidden or shown: a = size, b = hidden */ /* Accessibility (see BK_a11y_set_subtree), on a node holding a host subtree, or the root: */ BK_EV_A11Y_TREE, /* a screen reader reads this window now: set your subtrees (on the root) */ - BK_EV_A11Y_ACTION /* a screen reader asks for an action on a subtree node: ref = BKA11yRequest * */ + BK_EV_A11Y_ACTION, /* a screen reader asks for an action on a subtree node: ref = BKA11yRequest * */ + /* A pinch or a turn over an "events" node (two fingers, or a trackpad: BK_magnify / BK_rotate): + * ref = "mods kind x y", kind BK_GESTURE_*, x, y its centre relative to the node; a = the amount: + * MAGNIFY the scale change (0.1 = 10% larger), ROTATE degrees (> 0 counter-clockwise). */ + BK_EV_GESTURE }; +/* BK_EV_GESTURE kinds: Blender's MOUSEZOOM and MOUSEROTATE. A pan is a scroll (BK_scroll_px). */ +enum { BK_GESTURE_MAGNIFY = 1, BK_GESTURE_ROTATE = 2 }; + typedef struct BKHost { void *data; void (*request)(void *data); /* schedule a render */ @@ -725,7 +742,9 @@ 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 screen contacts as BK_custom_set_touch says (BK_TOUCH_MODE_*), and pinches and turns + * (two fingers or a trackpad) as MAGNIFY / ROTATE. * 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 */ @@ -737,6 +756,23 @@ enum { BK_CUSTOM_KEYUP, /* keysym */ BK_CUSTOM_FOCUS, /* keyboard focus gained */ BK_CUSTOM_BLUR, /* keyboard focus lost */ + BK_CUSTOM_TOUCH, /* one contact (BK_TOUCH_MODE_RAW): touch_id, touch_phase, x, y */ + BK_CUSTOM_MAGNIFY, /* magnify: a pinch about x, y */ + BK_CUSTOM_ROTATE, /* rotate: a turn about x, y */ +}; + +/* What a touch screen finger that lands on a custom node does (BK_custom_set_touch). */ +enum { + /* The default, as on a phone: a tap is a click, a drag scrolls (the node gets wheel events; a + * contact in the widget-unit strip at its right edge is its scrollbar's: a press and a drag) and + * two fingers pan, pinch and turn. */ + BK_TOUCH_MODE_SCROLL = 0, + /* The finger is the pointer: a press at once, and its drag is the node's (ImGui's sliders and + * window moves); two fingers still pan, pinch and turn. */ + BK_TOUCH_MODE_POINTER, + /* Every contact that begins over the node arrives as BK_CUSTOM_TOUCH, any number at once, and + * the node does its own gestures. */ + BK_TOUCH_MODE_RAW, }; typedef struct BKCustomEvent { @@ -749,6 +785,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 id of the contact (unique while it is down) */ + int touch_phase; /* TOUCH: BK_TOUCH_DOWN / MOVE / UP / CANCEL */ + float magnify; /* MAGNIFY: scale change since the last one (0.1 = 10% larger) */ + float rotate; /* ROTATE: degrees since the last one, > 0 counter-clockwise */ } BKCustomEvent; typedef struct BKCustomClass { @@ -772,6 +812,8 @@ 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); +/* What a finger that lands on the node does: BK_TOUCH_MODE_* (BK_TOUCH_MODE_SCROLL by default). */ +void BK_custom_set_touch(BKNode *node, int mode); int BK_custom_has_focus(BKNode *node); /* The context a node is shown in (NULL while detached). */ BKContext *BK_node_context(const BKNode *node); @@ -831,9 +873,11 @@ int BK_needs_render(BKContext *ctx); int BK_press(BKContext *ctx, int x, int y, int mods); int BK_release(BKContext *ctx, int x, int y, int mods); int BK_motion(BKContext *ctx, int x, int y, int mods); -/* The host lost the pointer mid-press (a cancelled touch, a lost pointer capture, a dialog): Blender's - * EVT_BUT_CANCEL. A drag is cancelled as Escape cancels it (the value goes back), a modal ends, and the - * press ends where the pointer last was, with no click and no BK_EV_RELEASE. */ +/* The host lost the pointer mid-press (a lost pointer capture, a dialog): Blender's EVT_BUT_CANCEL. + * The pressed widget's interaction is cancelled whether it was dragged or not (a dragged value goes + * back, as with Escape), a modal ends, and the press ends where the pointer last was, with no click + * and no BK_EV_RELEASE. Every touch contact down is cancelled too (BK_TOUCH_CANCEL): the window + * hosts do all of this when the window loses the focus. */ int BK_cancel(BKContext *ctx, int mods); int BK_wheel(BKContext *ctx, int x, int y, int delta, int mods); /* Precise scrolling (touchpads, tilt wheels): dx, dy in wheel notches, @@ -857,6 +901,40 @@ enum { BK_SCROLL_END = 4, /* the finger lifted */ }; void BK_scroll_phase(BKContext *ctx, int phase); + +/* -- Touch screens and trackpad gestures ----------------------------------------------------- + * A host sends every contact of a touch screen: `id` is the platform's (unique while the finger is + * down), x, y window pixels as for BK_motion, `time_ms` the event's own time in milliseconds on any + * monotonic clock (only differences count; <= 0: now) for the fling's velocity. The kit turns them + * into what its widgets know, one model on every platform (Android's): + * - a finger that lands on a widget with a drag of its own (a slider, a number or text field, a + * scrollbar, an editor; BK_TOUCH_MODE_POINTER custom nodes) is the pointer at once: press, + * drag, release, with BK_FROM_TOUCH in the mods; + * - anywhere else the finger waits: lifted in place it is a click (a tap; two are a double + * click), held still for half a second it opens the context menu (BK_context_menu), moved past + * the touch slop it scrolls what is under it exactly as far as it went (BK_scroll_px with + * BK_SCROLL_DRAG) and when it lifts the content flings on along Android's curve + * (BK_SCROLL_FLING, then BK_SCROLL_END; BK_animating is non-zero meanwhile). A finger that + * lands on a fling stops it and clicks nothing; + * - a second finger cancels what the first one did (as BK_cancel: a dragged value goes back, + * nothing is clicked) and the two are a gesture until they lift: moving together they scroll + * (Blender's MOUSEPAN), spreading they magnify and turning they rotate about their centre + * (MOUSEZOOM, MOUSEROTATE: as BK_magnify, BK_rotate). No finger is the pointer again until all + * have lifted; + * - a custom node in BK_TOUCH_MODE_RAW gets the contacts that begin over it as they are; + * - no hover is left behind: the pointer leaves when the finger lifts. + * BK_TOUCH_CANCEL: the platform took the contact back (a system gesture, a lost capture); nothing + * it did is kept, and its x, y are not used. 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, double time_ms, int mods); +/* A trackpad pinch (GHOST_kTrackpadEventMagnify, Blender's MOUSEZOOM) about x, y: `delta` is the + * scale change since the last one (0.1 = 10% larger). The node editor zooms; custom nodes get + * BK_CUSTOM_MAGNIFY and "events" nodes BK_EV_GESTURE. */ +int BK_magnify(BKContext *ctx, int x, int y, float delta, int mods); +/* A trackpad turn (GHOST_kTrackpadEventRotate, MOUSEROTATE) about x, y: degrees since the last + * one, > 0 counter-clockwise (as NSEvent.rotation). */ +int BK_rotate(BKContext *ctx, int x, int y, float degrees, int mods); + int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods); /* Called by a binding while it handles a key's raw event (BK_EV_KEY) when it acted on the key: * BK_key then returns 1 and no widget or shortcut sees the key. A host acts on a key BK_key diff --git a/kit/intern/kit_color.c b/kit/intern/kit_color.c index fb075bd0..5dd5c522 100644 --- a/kit/intern/kit_color.c +++ b/kit/intern/kit_color.c @@ -241,7 +241,7 @@ static void picker_free(BKNode *n) } const BKClass bk_cls_picker = {.name = "picker", .a11y_role = BK_ROLE_DIALOG, - .flags = CLS_INTERACTIVE | CLS_POPUP, + .flags = CLS_INTERACTIVE | CLS_POPUP | CLS_DRAGS, .free_ext = picker_free, .measure = picker_measure, .arrange = picker_arrange, @@ -854,7 +854,7 @@ static int ramp_color_set(BKNode *n, const float c[4]) } const BKClass bk_cls_ramp = {.name = "ramp", .a11y_role = BK_ROLE_GROUP, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, /* half the width of a stop marker: it goes out at the ends. Below the * band (1.1u + 1) a marker is 1.6 times that tall, so it ends at * 1.548u + 1, within a pixel of the node's 1.6u: the margin covers it. */ @@ -1223,7 +1223,7 @@ static int curve_get_num(BKNode *n, const char *key, double *r) } const BKClass bk_cls_curve = {.name = "curve", .a11y_role = BK_ROLE_GROUP, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, .init = curve_init, .free_ext = curve_free, .measure = curve_measure, @@ -1323,7 +1323,7 @@ static void normal_draw(BKNode *n) } const BKClass bk_cls_normal = {.name = "normal", .a11y_role = BK_ROLE_GROUP, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, .cursor = BK_CURSOR_CROSSHAIR, .init = normal_init, .measure = normal_measure, diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index 7a5f55de..c4fd6ccc 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -1708,6 +1708,7 @@ BKContext *BK_context_new(BKNode *root) ctx->cursor = BK_CURSOR_DEFAULT; ctx->layout_dirty = true; ctx->full_dirty = true; + bk_touch_init(&ctx->touch); if (root) { root->ctx_root = ctx; } @@ -1978,7 +1979,7 @@ void bk_ctx_dirty_rect(BKContext *ctx, BKRect r) ctx->dirty[ctx->ndirty++] = r; } -static bool is_within(const BKNode *n, const BKNode *subtree) +bool bk_is_within(const BKNode *n, const BKNode *subtree) { for (; n; n = n->parent) { if (n == subtree) { @@ -1995,7 +1996,7 @@ void bk_forget(BKContext *ctx, BKNode *subtree) undo_forget(ctx, subtree); bk_a11y_forget(ctx, subtree); for (int i = ctx->nanim - 1; i >= 0; i--) { - if (is_within(ctx->anim[i], subtree)) { + if (bk_is_within(ctx->anim[i], subtree)) { const int last = --ctx->nanim; ctx->anim[i] = ctx->anim[last]; ctx->anim_start[i] = ctx->anim_start[last]; @@ -2003,36 +2004,37 @@ void bk_forget(BKContext *ctx, BKNode *subtree) } } for (int i = 0; i < ctx->nmulti; i++) { - if (is_within(ctx->multi[i], subtree)) { + if (bk_is_within(ctx->multi[i], subtree)) { ctx->nmulti = 0; break; } } - if (ctx->hover && is_within(ctx->hover, subtree)) { + if (ctx->hover && bk_is_within(ctx->hover, subtree)) { ctx->hover = NULL; } - if (ctx->grab && is_within(ctx->grab, subtree)) { + if (ctx->grab && bk_is_within(ctx->grab, subtree)) { ctx->grab = NULL; } - if (ctx->focus && is_within(ctx->focus, subtree)) { + if (ctx->focus && bk_is_within(ctx->focus, subtree)) { BKNode *f = ctx->focus; ctx->focus = NULL; bk_te_free(f->edit); f->edit = NULL; } - if (ctx->modal && is_within(ctx->modal, subtree)) { + if (ctx->modal && bk_is_within(ctx->modal, subtree)) { ctx->modal = NULL; } - if (ctx->tip_node && is_within(ctx->tip_node, subtree)) { + if (ctx->tip_node && bk_is_within(ctx->tip_node, subtree)) { ctx->tip_node = NULL; ctx->tip_shown = 0; } - if (ctx->last_click_node && is_within(ctx->last_click_node, subtree)) { + if (ctx->last_click_node && bk_is_within(ctx->last_click_node, subtree)) { ctx->last_click_node = NULL; } + bk_touch_forget(&ctx->touch, subtree); /* 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)) { + if (ctx->popups[i]->parent && bk_is_within(ctx->popups[i]->parent, subtree)) { bk_close_popups_after(ctx, i > 0 ? ctx->popups[i - 1] : NULL); break; } @@ -2618,6 +2620,7 @@ static int render_frame(BKContext *ctx, BuiRaster *r, int w, int h, int full) BK_anim_tick(bk_time()); /* motions write their values (nodes damage themselves) */ } anim_step(ctx); + bk_touch_frame(ctx); /* a fling's step (it scrolls: before the layout) */ BK_configure(ctx, w, h); if (BUI_raster_width(r) != w || BUI_raster_height(r) != h) { ctx->layout_dirty = true; @@ -2811,10 +2814,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 a finger's: a warp moves the mouse, not the finger, so the next + * touch would count the wrap again (and the system pointer would jump). */ +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; + return ctx->host.warp && !(mods & BK_FROM_TOUCH) && ctx->grab && ctx->dragging && + !BK_HTML(ctx->grab) && ctx->grab->cls->drag_cursor == BK_CURSOR_NONE; } static void wrap_pointer(BKContext *ctx, int x, int y) @@ -2906,7 +2912,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; @@ -2996,8 +3002,9 @@ static int in_BK_press(BKContext *ctx, int x, int y, int mods) bk_invalidate(target); BKEvent e = make_event(ctx, target, x, y, mods); const double now = bk_time(); + const int dbl_px = (mods & BK_FROM_TOUCH) ? bk_unit() : DOUBLE_CLICK_PX; /* a finger lands wider */ if (ctx->last_click_node == target && now - ctx->last_click_t < DOUBLE_CLICK_S && - abs(x - ctx->last_click_x) <= DOUBLE_CLICK_PX && abs(y - ctx->last_click_y) <= DOUBLE_CLICK_PX) + abs(x - ctx->last_click_x) <= dbl_px && abs(y - ctx->last_click_y) <= dbl_px) { ctx->last_click_node = NULL; bk_event(target, BK_EV_DOUBLE, mods, &e); @@ -3027,7 +3034,7 @@ static int in_BK_press(BKContext *ctx, int x, int y, int mods) * is sent and no menu item is picked. */ static int end_press(BKContext *ctx, int x, int y, int mods, bool cancelled) { - 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; @@ -3124,7 +3131,12 @@ void bk_cancel_press(BKContext *ctx, int mods) bk_end_modal(ctx); } else if (ctx->grab) { - cancel_drag(ctx); + /* unlike Escape, also a press that has not moved yet: its release would still act (an + * unmoved press on the node editor's empty space deselects everything) */ + if (ctx->grab->cls->cancel) { + ctx->grab->cls->cancel(ctx->grab); + ctx->has_ungrab = false; + } end_press(ctx, ctx->pointer_x, ctx->pointer_y, mods, true); } } @@ -3316,6 +3328,22 @@ static BKNode *deepest(BKNode *n, int x, int y) return n; } +BKNode *bk_wheel_target(BKContext *ctx, int x, int y) +{ + BKNode *target = hit_all(ctx, x, y); + if (!target && ctx->root && y >= ctx->header_h) { + target = deepest(ctx->root, x, y); /* non-interactive area: let containers scroll */ + } + return target; +} + +/* What precise scrolls and gestures at x, y go to first: the custom node that holds the pointer + * (an ImGui drag), else the one under it; nothing while a modal tool runs. */ +static BKNode *pointer_target(BKContext *ctx, int x, int y) +{ + return BK_IS_CUSTOM(ctx->grab) ? ctx->grab : (ctx->modal ? NULL : hit_all(ctx, x, y)); +} + /* `px`: the exact distance in pixels (BK_scroll_px; same sign as `delta`), 0 for a plain wheel step. * Scroll containers and raw events use it, other widgets keep the step. `horizontal`: a sideways * wheel or swipe, sent on as Shift + wheel to the widgets; the region only scrolls vertically, so @@ -3323,10 +3351,7 @@ static BKNode *deepest(BKNode *n, int x, int y) static int in_BK_wheel(BKContext *ctx, int x, int y, int delta, float px, int mods, bool horizontal) { hide_tooltip(ctx); - BKNode *target = hit_all(ctx, x, y); - if (!target && ctx->root && y >= ctx->header_h) { - target = deepest(ctx->root, x, y); /* non-interactive area: let containers scroll */ - } + BKNode *target = bk_wheel_target(ctx, x, y); for (BKNode *n = target; n; n = n->parent) { if (!NODE_ENABLED(n)) { continue; @@ -3820,15 +3845,6 @@ int BK_eval_number(const char *expr, double *r_value) /** \} */ -/* Public input entry points: mark the input scope (undo grouping) and report - * the view changes the event caused (scrollbars follow). */ -#define INPUT_ENTRY(call) \ - ctx->in_input++; \ - const int r = call; \ - ctx->in_input--; \ - bk_views_check(ctx); \ - return r - int BK_press(BKContext *ctx, int x, int y, int mods) { INPUT_ENTRY(in_BK_press(ctx, x, y, mods)); @@ -3844,11 +3860,18 @@ int BK_motion(BKContext *ctx, int x, int y, int mods) INPUT_ENTRY(in_BK_motion(ctx, x, y, mods)); } -int BK_cancel(BKContext *ctx, int mods) +int bk_cancel_pointer(BKContext *ctx, int mods) { INPUT_ENTRY(in_BK_cancel(ctx, mods)); } +int BK_cancel(BKContext *ctx, int mods) +{ + const bool touched = ctx->touch.state != BK_TOUCH_IDLE; + bk_touch_cancel_all(ctx); /* a finger's press is cancelled there */ + return bk_cancel_pointer(ctx, mods) | touched; +} + int BK_wheel(BKContext *ctx, int x, int y, int delta, int mods) { INPUT_ENTRY(in_BK_wheel(ctx, x, y, delta, 0.0f, mods, false)); @@ -3873,7 +3896,7 @@ void BK_key_taken(BKContext *ctx) 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 = pointer_target(ctx, x, y); if (BK_IS_CUSTOM(t) && NODE_ENABLED(t)) { if (dx == 0.0f && dy == 0.0f) { return 0; @@ -3903,14 +3926,62 @@ void BK_scroll_phase(BKContext *ctx, int phase) ctx->scroll_phase = phase; } +BKNode *bk_gesture_target(BKContext *ctx, int x, int y) +{ + BKNode *t = pointer_target(ctx, x, y); + return t ? t : (ctx->modal ? NULL : bk_wheel_target(ctx, x, y)); +} + +/* Blender's MOUSEZOOM / MOUSEROTATE reach the view under them (view2d_ops.cc): the first of + * `target` and its parents with a gesture hook takes it (the node editor zooms, a custom node + * gets BK_CUSTOM_MAGNIFY / ROTATE). An "events" target hears of it first, as of a wheel. */ +static int in_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float amount, int mods) +{ + if (ctx->modal || amount == 0.0f) { + return 0; + } + hide_tooltip(ctx); + int r = 0; + for (BKNode *n = target; n; n = n->parent) { + if (!NODE_ENABLED(n)) { + continue; + } + if (n == target && (n->flags & NF_EVENTS)) { + char buf[64]; + snprintf(buf, sizeof(buf), "%d %d %d %d", mods, kind, x - n->x, y - n->y); + bk_emit(n, BK_EV_GESTURE, buf, amount, 0.0); + r = 1; + } + BKEvent e = make_event(ctx, n, x, y, mods); + if (n->cls->gesture && n->cls->gesture(n, &e, kind, amount)) { + return 1; + } + } + return r; +} + +int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float amount, int mods) +{ + INPUT_ENTRY(in_gesture(ctx, target, x, y, kind, amount, mods)); +} + +int BK_magnify(BKContext *ctx, int x, int y, float delta, int mods) +{ + mods &= BK_SHIFT | BK_CTRL | BK_ALT; + return bk_gesture(ctx, bk_gesture_target(ctx, x, y), x, y, BK_GESTURE_MAGNIFY, delta, mods); +} + +int BK_rotate(BKContext *ctx, int x, int y, float degrees, int mods) +{ + mods &= BK_SHIFT | BK_CTRL | BK_ALT; + return bk_gesture(ctx, bk_gesture_target(ctx, x, y), x, y, BK_GESTURE_ROTATE, degrees, mods); +} + int BK_scroll_px(BKContext *ctx, int x, int y, float dx, float dy, int mods) { const float notch = 2.0f * (float)bk_unit(); if (dx == 0.0f && dy == 0.0f && ctx->scroll_phase == BK_SCROLL_END) { - BKNode *t = hit_all(ctx, x, y); - if (!t && ctx->root && y >= ctx->header_h) { - t = deepest(ctx->root, x, y); - } + BKNode *t = bk_wheel_target(ctx, x, y); if (!t) { return 0; } @@ -3918,7 +3989,7 @@ int BK_scroll_px(BKContext *ctx, int x, int y, float dx, float dy, int mods) bk_event(t, BK_EV_WHEEL, mods, &e); return 1; } - BKNode *t = BK_IS_CUSTOM(ctx->grab) ? ctx->grab : (ctx->modal ? NULL : hit_all(ctx, x, y)); + BKNode *t = pointer_target(ctx, x, y); if (BK_IS_CUSTOM(t) && NODE_ENABLED(t)) { return BK_scroll(ctx, x, y, dx / notch, dy / notch, mods); /* custom nodes take notches */ } @@ -4022,7 +4093,9 @@ static void raw_event(BKNode *n, int kind, int mods, const BKEvent *e, int butto } snprintf(buf, sizeof(buf), "%d %d", mods, button); if (kind == BK_EV_WHEEL && e) { - snprintf(buf, sizeof(buf), "%d %d %d", mods, button, e->phase); /* the third: BK_scroll_phase */ + /* the third: BK_scroll_phase; then where it is, relative to the node (a touch scroll moves + * no pointer there) */ + snprintf(buf, sizeof(buf), "%d %d %d %d %d", mods, button, e->phase, e->lx, e->ly); bk_emit(n, kind, buf, e->delta, e->wheel_y); /* b: the exact pixels of BK_scroll_px, else 0 */ return; } @@ -4168,7 +4241,7 @@ static void undo_forget(BKContext *ctx, BKNode *subtree) const int pos = ctx->undo_pos; int new_pos = pos; for (int i = 0; i < ctx->nundo; i++) { - if (is_within(ctx->undo[i].node, subtree)) { + if (bk_is_within(ctx->undo[i].node, subtree)) { undo_entry_free(&ctx->undo[i]); if (i < pos) { new_pos--; @@ -4204,7 +4277,8 @@ bool bk_animations_enabled(void) int BK_animating(BKContext *ctx) { /* motions need frames from the kit only when it runs their clock (else the host draws them) */ - return ctx->nanim > 0 || bk_custom_animating(ctx) || (!BK_anim_host_clock() && BK_anim_active()); + return ctx->nanim > 0 || bk_custom_animating(ctx) || bk_touch_animating(ctx) || + (!BK_anim_host_clock() && BK_anim_active()); } static float anim_target(const BKNode *n) @@ -4317,6 +4391,7 @@ BKNode *bk_next_editable(BKNode *from, int dir) void bk_window_focus(BKContext *ctx, BKWindow *win, const BKWindowCallbacks *cb, int active) { if (!active) { + bk_touch_cancel_all(ctx); /* the fingers' lifts may go to another window now */ /* pie_handler WINDEACTIVATE: the pie key may be released outside, so cancel the pie */ ctx->key_held[0] = '\0'; if (ctx->npopups && ctx->popups[ctx->npopups - 1]->cls == &bk_cls_pie) { diff --git a/kit/intern/kit_custom.c b/kit/intern/kit_custom.c index 70d9784c..1742c153 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 touch_mode; /* BK_TOUCH_MODE_* (BK_custom_set_touch) */ struct BKCustom *next; /* every custom node (any context) */ } BKCustom; @@ -198,6 +199,22 @@ static int custom_wheel(BKNode *n, BKEvent *e) return 1; /* never scroll the region under an embedded UI */ } +static int custom_gesture(BKNode *n, BKEvent *e, int kind, float amount) +{ + BKCustomEvent ce; + memset(&ce, 0, sizeof(ce)); + ce.type = kind == BK_GESTURE_MAGNIFY ? BK_CUSTOM_MAGNIFY : BK_CUSTOM_ROTATE; + ce.mods = e->mods; + if (kind == BK_GESTURE_MAGNIFY) { + ce.magnify = amount; + } + else { + ce.rotate = amount; + } + bk_custom_event(n, &ce, e->x, e->y); + return 1; /* as the wheel: nothing under an embedded UI zooms */ +} + static void custom_finish_edit(BKNode *n, bool confirm) { (void)confirm; @@ -227,6 +244,7 @@ const BKClass bk_cls_custom = {.name = "custom", .leave = custom_leave, .key = custom_key, .wheel = custom_wheel, + .gesture = custom_gesture, .cursor_at = custom_cursor_at, .finish_edit = custom_finish_edit}; @@ -262,6 +280,10 @@ void bk_ctx_arm_timer(BKContext *ctx) due = c->wake_at; } } + const double press = bk_touch_due(ctx); /* a finger held still: its long press */ + if (press > 0.0 && (due == 0.0 || press < due)) { + due = press; + } if (due == 0.0 || !ctx->host.schedule) { ctx->custom_timer_due = due; return; @@ -279,6 +301,7 @@ void bk_ctx_arm_timer(BKContext *ctx) void bk_custom_timer(BKContext *ctx) { ctx->custom_timer_due = 0.0; + bk_touch_tick(ctx); /* a long press that is due */ bk_image_tick(); /* animated images whose frame is due (they damage themselves) */ const double now = bk_time() + 0.002; /* timers fire a little early */ bool any = false; @@ -398,6 +421,40 @@ void BK_custom_set_cursor(BKNode *node, int cursor) } } +void BK_custom_set_touch(BKNode *node, int mode) +{ + BKCustom *c = cust(node); + if (c && mode >= BK_TOUCH_MODE_SCROLL && mode <= BK_TOUCH_MODE_RAW) { + c->touch_mode = mode; + } +} + +int bk_custom_touch_mode(const BKNode *n) +{ + const BKCustom *c = cust(n); + /* raw contacts need someone to take them */ + return c && (c->touch_mode != BK_TOUCH_MODE_RAW || c->cls.event) ? c->touch_mode : + BK_TOUCH_MODE_SCROLL; +} + +int bk_custom_touch(BKNode *n, int id, int phase, int x, int y, int mods) +{ + if (phase == BK_TOUCH_DOWN) { + BKContext *ctx = bk_ctx(n); + if (ctx && ctx->focus != n) { /* as a click does (custom_press) */ + bk_end_edit(ctx, true); + 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 85a55fc3..92a390e0 100644 --- a/kit/intern/kit_intern.h +++ b/kit/intern/kit_intern.h @@ -8,6 +8,7 @@ #include "BUI_kit.h" #include "image/image.h" +#include "kit_touch.h" typedef unsigned char uchar; @@ -339,6 +340,9 @@ typedef struct BKClass { int (*key_up)(BKNode *n, BKEvent *e); /* a key release, sent to the top popup */ void (*popup_pick)(BKNode *n, void *data); /* a menu this node opened: the picked item's `data` */ int (*wheel)(BKNode *n, BKEvent *e); + /* a pinch or a turn about e->x, e->y (BK_GESTURE_*: the scale change, degrees counter-clockwise); + * 1 when used */ + int (*gesture)(BKNode *n, BKEvent *e, int kind, float amount); 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); @@ -385,6 +389,8 @@ enum { CLS_POPUP = 1 << 2, CLS_BUTTONS = 1 << 3, /* middle / right presses arrive as press, drag, release with * BK_BUTTON2 / BK_BUTTON3 in the event's mods (editors) */ + CLS_DRAGS = 1 << 4, /* a drag of its own (a slider, a field, an editor): a finger that lands + * on it is pressed at once; elsewhere a finger's drag scrolls (kit_touch.c) */ }; enum { DRAG_GROUP_TOGGLE = 1, DRAG_GROUP_PANEL = 2 }; @@ -539,6 +545,18 @@ void bk_window_focus(BKContext *ctx, BKWindow *win, const BKWindowCallbacks *cb, * the pointer from a press for a move, so its release won't come): no click or BK_EV_RELEASE, a * drag's value back, a modal ended. */ void bk_cancel_press(BKContext *ctx, int mods); +/* bk_cancel_press as an input of its own (BK_cancel without the touches): 1 when a press ended. */ +int bk_cancel_pointer(BKContext *ctx, int mods); +bool bk_is_within(const BKNode *n, const BKNode *subtree); /* n is subtree or inside it */ + +/* Input entry points: mark the input scope (undo grouping) and report the view changes the event + * caused (scrollbars follow). */ +#define INPUT_ENTRY(call) \ + ctx->in_input++; \ + const int r = call; \ + ctx->in_input--; \ + bk_views_check(ctx); \ + return r bool bk_contains(const BKNode *n, int x, int y); /* Whole pixels out of a fractional scroll distance: the part below one pixel stays in `*rem` * and carries into the next event, so slow smooth scrolling never rounds away to nothing. */ @@ -691,6 +709,7 @@ 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 */ + BKTouch touch; /* touch screen contacts (kit_touch.c) */ /* every live context (BK_set_theme redraws them all) */ BKContext *next_ctx; /* its accessibility tree, made when a screen reader first asks (a11y/a11y.c) */ @@ -710,6 +729,14 @@ int bk_custom_event(BKNode *n, BKCustomEvent *e, int wx, int wy); void bk_custom_frames(BKContext *ctx); /* BK_render: frame callbacks due */ bool bk_custom_animating(BKContext *ctx); /* a visible node wants the next frame */ void bk_custom_timer(BKContext *ctx); /* BK_TIMER_CUSTOM fired */ +int bk_custom_touch_mode(const BKNode *n); /* BK_TOUCH_MODE_* (a custom node's, else SCROLL) */ +/* One contact of a BK_TOUCH_MODE_RAW node (BK_CUSTOM_TOUCH; the first one down takes the focus). */ +int bk_custom_touch(BKNode *n, int id, int phase, int x, int y, int mods); +/* Pinches and turns (kit_core.c): the node they go to at x, y, and the first of `target` and its + * parents that takes one ("events" nodes get BK_EV_GESTURE on the way). */ +BKNode *bk_wheel_target(BKContext *ctx, int x, int y); /* the widget there, else the deepest node */ +BKNode *bk_gesture_target(BKContext *ctx, int x, int y); +int bk_gesture(BKContext *ctx, BKNode *target, int x, int y, int kind, float amount, int mods); /* Arms the context's frame timer (BK_TIMER_CUSTOM) for the earliest of its * custom nodes' wakes and its animated images' next frames. */ void bk_ctx_arm_timer(BKContext *ctx); diff --git a/kit/intern/kit_nodes.c b/kit/intern/kit_nodes.c index c3cddad1..39db77f3 100644 --- a/kit/intern/kit_nodes.c +++ b/kit/intern/kit_nodes.c @@ -62,6 +62,9 @@ typedef struct NodeEdit { BKNode *hit; /* node pressed */ int link_node, link_sock; /* the fixed end of a dragged link */ bool link_from_output; + /* M_LINK: the link the drag took off an input (from, out, to, in), put back by a cancel + * (node_link_cancel); picked_from < 0: none */ + int picked_from, picked_out, picked_to, picked_in; int value_node, value_sock; double value_start; BKNode *ctl_node; /* the control pressed (M_CONTROL), or the one whose menu is open */ @@ -1137,8 +1140,13 @@ static int editor_press(BKNode *e, BKEvent *ev) d->link_node = old.from; d->link_sock = old.out; d->link_from_output = true; + d->picked_from = old.from; + d->picked_out = old.out; + d->picked_to = old.to; + d->picked_in = old.in; } else { + d->picked_from = -1; d->link_node = ni; d->link_sock = k; d->link_from_output = !input; @@ -1362,6 +1370,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->picked_from >= 0) { /* node_link_cancel: the graph 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); } @@ -1370,7 +1381,15 @@ static int editor_wheel(BKNode *e, BKEvent *ev) { NodeEdit *d = ed(e); const float step = 2.0f * u(); /* view2d scroll step */ - if (EV_CTRL(ev)) { /* VIEW2D_OT_scroll_right / left */ + if (ev->wheel_y != 0.0f) { /* MOUSEPAN (view_pan_invoke): the view follows the fingers exactly */ + if (EV_SHIFT(ev)) { + d->panx += ev->wheel_y; + } + else { + d->pany += ev->wheel_y; + } + } + else if (EV_CTRL(ev)) { /* VIEW2D_OT_scroll_right / left */ d->panx += ev->delta * step; } else if (EV_SHIFT(ev)) { /* VIEW2D_OT_scroll_up / down */ @@ -1383,9 +1402,23 @@ static int editor_wheel(BKNode *e, BKEvent *ev) return 1; } +/* MOUSEZOOM about the fingers or the pointer (view_zoomstep_apply_ex); no rotation in 2D views. */ +static int editor_gesture(BKNode *e, BKEvent *ev, int kind, float amount) +{ + if (kind != BK_GESTURE_MAGNIFY) { + return 0; + } + zoom_at(e, 1.0f + amount, ev->x, ev->y); + return 1; +} + static int editor_key(BKNode *e, BKEvent *ev) { const char *k = ev->keysym; + const Mode mode = ed(e)->mode; + if ((bk_keysym_is(k, "x") || bk_keysym_is(k, "Delete")) && (mode == M_LINK || mode == M_VALUE)) { + return 1; /* the drag holds node indices a delete would shift */ + } if (bk_keysym_is(k, "x") || bk_keysym_is(k, "Delete")) { /* NODE_OT_delete */ bk_emit(e, BK_EV_CHANGE, NULL, EV_DELETE, 0); return 1; @@ -1495,7 +1528,7 @@ static int editor_get_num(BKNode *e, const char *key, double *r) } const BKClass bk_cls_nodeeditor = {.name = "nodeeditor", .a11y_role = BK_ROLE_GROUP, - .flags = CLS_INTERACTIVE | CLS_BUTTONS, + .flags = CLS_INTERACTIVE | CLS_BUTTONS | CLS_DRAGS, .init = editor_init, .free_ext = editor_free, .measure = editor_measure, @@ -1509,6 +1542,7 @@ const BKClass bk_cls_nodeeditor = {.name = "nodeeditor", .a11y_role = BK_ROLE_GR .cancel = editor_cancel, .popup_pick = editor_popup_pick, .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_textarea.c b/kit/intern/kit_textarea.c index 62b6989b..99e99351 100644 --- a/kit/intern/kit_textarea.c +++ b/kit/intern/kit_textarea.c @@ -988,7 +988,7 @@ static void ta_draw(BKNode *n) } const BKClass bk_cls_textarea = {.name = "textarea", .a11y_role = BK_ROLE_MULTILINE_TEXT_INPUT, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, .cursor = BK_CURSOR_TEXT, .init = ta_init, .free_ext = ta_free, diff --git a/kit/intern/kit_touch.c b/kit/intern/kit_touch.c new file mode 100644 index 00000000..d0cdbdd4 --- /dev/null +++ b/kit/intern/kit_touch.c @@ -0,0 +1,510 @@ +/* Touch screens (BK_touch): a host's contacts turned into what the widgets know, one model on + * every platform, Android's (View.onTouchEvent, ScrollView, ViewConfiguration): + * + * - a finger that lands on a widget with a drag of its own (CLS_DRAGS: sliders, fields, editors; + * a BK_TOUCH_MODE_POINTER custom node; the scrollbar strip at a page's right edge) is the + * pointer at once: motion, press, drags, release, with BK_FROM_TOUCH in the mods; + * - anywhere else it waits (TAP): lifted in place it is a click, held still for + * DEFAULT_LONG_PRESS_TIMEOUT it is a right press (BK_context_menu), and moved past the touch + * slop it scrolls the content under where it went down (BK_scroll_px, BK_SCROLL_DRAG), from + * just past the slop so the content does not jump by it (RecyclerView's way). When it lifts the + * content flings on at its velocity (kit_fling.c: VelocityTracker, OverScroller), stepped by + * BK_render while BK_animating says so. A finger that lands on a fling stops it, and is no tap; + * - a second finger cancels what the first one did, as a lost pointer does (bk_cancel_pointer, + * Blender's EVT_BUT_CANCEL: a dragged value goes back, nothing is clicked), and the two are a + * gesture until one lifts. Their centre scrolls like one finger (GHOST's trackpad Scroll, + * Blender's MOUSEPAN), their spread magnifies and their angle rotates about the centre + * (GHOST_kTrackpadEventMagnify / Rotate: MOUSEZOOM, MOUSEROTATE). Hosts report the fingers one + * at a time, so an update waits until both moved (or one moved twice): a pure pan is no wobble + * of the spread and angle between them. Afterwards no finger is the pointer until all lifted; + * - a BK_TOUCH_MODE_RAW custom node gets the contacts that begin over it as they are; + * - the pointer leaves when a finger that was it lifts: no hover stays behind a finger. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#include +#include + +#include "kit_intern.h" + +#define TOUCH_SLOP_DP 8.0f /* ViewConfiguration.TOUCH_SLOP */ +#define LONG_PRESS_S 0.5 /* ViewConfiguration.DEFAULT_LONG_PRESS_TIMEOUT */ +#define OFF (-100000) /* the pointer left the window (where the hosts put a leave) */ +#define MIN_MAGNIFY 1e-4f /* smaller spread changes are no pinch (a pan's rounding) */ +#define MIN_DEGREES 0.01f + +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +void bk_touch_init(BKTouch *t) +{ + memset(t, 0, sizeof(*t)); + t->lead = t->pair[0] = t->pair[1] = -1; +} + +void bk_touch_forget(BKTouch *t, const BKNode *subtree) +{ + for (int i = 0; i < BK_MAX_TOUCH; i++) { + BKContact *c = &t->c[i]; + if (c->role == BK_CONTACT_RAW && bk_is_within(c->raw, subtree)) { + c->role = BK_CONTACT_IDLE; /* its node is gone: the rest of the contact is nobody's */ + c->raw = NULL; + } + } + if (t->pinch_target && bk_is_within(t->pinch_target, subtree)) { + t->pinch_target = NULL; /* the gesture goes on with what is under its centre */ + } +} + +static int px(float v) +{ + return (int)floorf(v + 0.5f); +} + +static int find(const BKTouch *t, int id) +{ + for (int i = 0; i < BK_MAX_TOUCH; i++) { + if (t->c[i].role != BK_CONTACT_FREE && t->c[i].id == id) { + return i; + } + } + return -1; +} + +/* No finger is the pointer any more: it leaves, as the hosts send a mouse leave. */ +static void leave(BKContext *ctx) +{ + BK_motion(ctx, OFF, OFF, BK_FROM_TOUCH); +} + +/* The content under the scroll's anchor follows the fingers by (fx, fy) pixels. */ +static int scroll(BKContext *ctx, float fx, float fy, int phase, int mods) +{ + BKTouch *t = &ctx->touch; + BK_scroll_phase(ctx, phase); + const int r = BK_scroll_px(ctx, t->anchor_x, t->anchor_y, -fx, fy, mods | BK_FROM_TOUCH); + BK_scroll_phase(ctx, BK_SCROLL_WHEEL); + return r; +} + +static int raw(BKContext *ctx, const BKContact *c, int phase, int mods) +{ + if (!c->raw) { + return 0; + } + INPUT_ENTRY(bk_custom_touch(c->raw, c->id, phase, px(c->x), px(c->y), mods | BK_FROM_TOUCH)); +} + +/* Whether a finger that lands on `n` at x is the pointer at once: the widget drags. */ +static bool presses(const BKContext *ctx, const BKNode *n, int x) +{ + if (ctx->modal) { + return true; /* a tool runs (the eyedropper): the finger is its pointer */ + } + if (!n || !NODE_ENABLED(n)) { + return false; + } + if (BK_IS_CUSTOM(n) || n->cls == &bk_cls_canvas) { + /* a page or an embedded UI scrolls, unless it asked; the strip at its right edge is its + * scrollbar (a list's thumb), so a huge list can be dragged to any place */ + return bk_custom_touch_mode(n) == BK_TOUCH_MODE_POINTER || x >= n->x + n->w - bk_unit(); + } + return (n->cls->flags & CLS_DRAGS) != 0; +} + +/* A first finger (no other on the one-finger path or in a gesture). */ +static int begin_lead(BKContext *ctx, int i, double t_ms, int mods) +{ + BKTouch *t = &ctx->touch; + BKContact *c = &t->c[i]; + const int x = px(c->x), y = px(c->y); + c->role = BK_CONTACT_LEAD; + t->lead = i; + t->down_x = t->last_x = c->x; + t->down_y = t->last_y = c->y; + t->anchor_x = x; + t->anchor_y = y; + bk_vt_clear(&t->vt); + bk_vt_add(&t->vt, t_ms, c->x, c->y); + if (t->fling_t0 > 0.0) { /* caught: the finger holds the content, it clicks nothing */ + t->fling_t0 = 0.0; + t->state = BK_TOUCH_SCROLL; + return 1; + } + if (presses(ctx, BK_hit_at(ctx, x, y), x)) { + t->state = BK_TOUCH_PRESS; + BK_motion(ctx, x, y, mods | BK_FROM_TOUCH); + BK_press(ctx, x, y, mods | BK_FROM_TOUCH | BK_BUTTON1); + return 1; + } + t->state = BK_TOUCH_TAP; /* the kit hears of it once it is known which */ + t->long_press_at = bk_time() + LONG_PRESS_S; + bk_ctx_arm_timer(ctx); + return 0; +} + +static void pair_metrics(const BKTouch *t, float *r_cx, float *r_cy, float *r_dist, float *r_angle) +{ + const BKContact *a = &t->c[t->pair[0]], *b = &t->c[t->pair[1]]; + *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_angle = atan2f(b->y - a->y, b->x - a->x); +} + +/* A second finger: the first one's interaction ends with nothing applied, the two are a gesture. */ +static int begin_pinch(BKContext *ctx, int i, int mods) +{ + BKTouch *t = &ctx->touch; + const int first = t->lead; + const BKTouchState was = t->state; + int r = 0; + if (was == BK_TOUCH_PRESS) { + r = bk_cancel_pointer(ctx, mods | BK_FROM_TOUCH); + leave(ctx); + } + t->c[first].role = t->c[i].role = BK_CONTACT_PAIR; + t->pair[0] = first; + t->pair[1] = i; + t->lead = -1; + t->state = BK_TOUCH_PINCH; + t->moved = 0; + t->long_press_at = 0.0; + float cx, cy; + pair_metrics(t, &cx, &cy, &t->dist, &t->angle); + /* from the centre now, also mid scroll: the point it followed is not where the centre is */ + t->last_x = cx; + t->last_y = cy; + if (was != BK_TOUCH_SCROLL) { + t->anchor_x = px(cx); + t->anchor_y = px(cy); + } + t->pinch_target = bk_gesture_target(ctx, px(cx), px(cy)); + return r | 1; +} + +static int pinch_update(BKContext *ctx, int mods) +{ + BKTouch *t = &ctx->touch; + float cx, cy, dist, angle; + pair_metrics(t, &cx, &cy, &dist, &angle); + const float fx = cx - t->last_x, fy = cy - t->last_y; + const float magnify = t->dist > 1.0f ? dist / t->dist - 1.0f : 0.0f; + float turn = angle - t->angle; + while (turn > (float)M_PI) { + turn -= 2.0f * (float)M_PI; + } + while (turn < -(float)M_PI) { + turn += 2.0f * (float)M_PI; + } + const float degrees = -turn * (180.0f / (float)M_PI); /* y points down: a counter-clockwise turn lowers the angle */ + t->last_x = cx; + t->last_y = cy; + t->dist = dist; + t->angle = angle; + t->moved = 0; + int r = 0; + if (fx != 0.0f || fy != 0.0f) { + r |= scroll(ctx, fx, fy, BK_SCROLL_DRAG, mods); + } + const int x = px(cx), y = px(cy); + BKNode *target = t->pinch_target ? t->pinch_target : bk_gesture_target(ctx, x, y); + if (fabsf(magnify) > MIN_MAGNIFY) { + r |= bk_gesture(ctx, target, x, y, BK_GESTURE_MAGNIFY, magnify, mods | BK_FROM_TOUCH); + } + if (fabsf(degrees) > MIN_DEGREES) { + r |= bk_gesture(ctx, target, x, y, BK_GESTURE_ROTATE, degrees, mods | BK_FROM_TOUCH); + } + return r; +} + +static void fling_start(BKContext *ctx, double t_ms) +{ + BKTouch *t = &ctx->touch; + float vx, vy; + if (!bk_vt_velocity(&t->vt, t_ms, &vx, &vy)) { + return; /* it rested before lifting */ + } + const bool fx = bk_fling_start(&t->fling_x, vx, bk_scale_fac); + const bool fy = bk_fling_start(&t->fling_y, vy, bk_scale_fac); + if (!fx && !fy) { + return; + } + const BKFling none = {0.0f, 1.0f}; + if (!fx) { + t->fling_x = none; + } + if (!fy) { + t->fling_y = none; + } + t->fling_done_x = t->fling_done_y = 0.0f; + t->fling_t0 = bk_time(); + bk_ctx_request(ctx); /* the frames that step it (BK_animating) */ +} + +static int lead_move(BKContext *ctx, BKContact *c, double t_ms, int mods) +{ + BKTouch *t = &ctx->touch; + const int m = mods | BK_FROM_TOUCH; + switch (t->state) { + case BK_TOUCH_PRESS: + return BK_motion(ctx, px(c->x), px(c->y), m | BK_BUTTON1); + case BK_TOUCH_TAP: { + const float dx = c->x - t->down_x, dy = c->y - t->down_y, slop = TOUCH_SLOP_DP * bk_scale_fac; + bk_vt_add(&t->vt, t_ms, c->x, c->y); + if (dx * dx + dy * dy <= slop * slop) { + return 0; + } + /* not a click: a scroll, from just past the slop (RecyclerView's dy -= mTouchSlop: the slop + * is the finger's, not the content's, so the content does not jump by it) */ + t->state = BK_TOUCH_SCROLL; + t->long_press_at = 0.0; + t->last_x = t->down_x + (fabsf(dx) > slop ? copysignf(slop, dx) : 0.0f); + t->last_y = t->down_y + (fabsf(dy) > slop ? copysignf(slop, dy) : 0.0f); + break; + } + case BK_TOUCH_SCROLL: + bk_vt_add(&t->vt, t_ms, c->x, c->y); + break; + default: + return 0; + } + const float fx = c->x - t->last_x, fy = c->y - t->last_y; + t->last_x = c->x; + t->last_y = c->y; + return fx != 0.0f || fy != 0.0f ? scroll(ctx, fx, fy, BK_SCROLL_DRAG, mods) : 0; +} + +/* The lead lifted (UP) or was taken back (CANCEL). */ +static int lead_end(BKContext *ctx, BKContact *c, int phase, double t_ms, int mods) +{ + BKTouch *t = &ctx->touch; + const int m = mods | BK_FROM_TOUCH, x = px(c->x), y = px(c->y); + const bool up = phase == BK_TOUCH_UP; + int r = 0; + switch (t->state) { + case BK_TOUCH_TAP: + if (up) { /* lifted in place: the click */ + BK_motion(ctx, x, y, m); + BK_press(ctx, x, y, m | BK_BUTTON1); + BK_release(ctx, x, y, m); + leave(ctx); + r = 1; + } + break; + case BK_TOUCH_PRESS: + r = up ? BK_release(ctx, x, y, m) : bk_cancel_pointer(ctx, m); + leave(ctx); + break; + case BK_TOUCH_SCROLL: + r = scroll(ctx, 0.0f, 0.0f, BK_SCROLL_END, mods); /* a list lets go of a stretch */ + if (up) { + bk_vt_add(&t->vt, t_ms, c->x, c->y); + fling_start(ctx, t_ms); + } + break; + default: /* SPENT: a long press opened its menu */ + break; + } + t->lead = -1; + t->long_press_at = 0.0; + return r; +} + +/* One of the pair lifted or was taken back: the gesture ends, the other finger does nothing more. */ +static int pair_end(BKContext *ctx, int i, int phase, int mods) +{ + BKTouch *t = &ctx->touch; + const unsigned bit = i == t->pair[0] ? 1u : 2u; + int r = 0; + if (phase == BK_TOUCH_UP && (t->moved & bit)) { + r |= pinch_update(ctx, mods); /* the move it held; a cancel drops it with the rest */ + } + r |= scroll(ctx, 0.0f, 0.0f, BK_SCROLL_END, mods); + const int other = t->pair[0] == i ? t->pair[1] : t->pair[0]; + t->c[other].role = BK_CONTACT_IDLE; + t->pair[0] = t->pair[1] = -1; + t->pinch_target = NULL; + t->state = BK_TOUCH_SPENT; + return r; +} + +static int contact_down(BKContext *ctx, int id, float x, float y, double t_ms, int mods) +{ + BKTouch *t = &ctx->touch; + int i = 0; + while (i < BK_MAX_TOUCH && t->c[i].role != BK_CONTACT_FREE) { + i++; + } + if (i == BK_MAX_TOUCH) { + return 0; /* an eleventh finger: not followed */ + } + BKContact *c = &t->c[i]; + c->id = id; + c->x = x; + c->y = y; + c->raw = NULL; + c->role = BK_CONTACT_IDLE; + if (!ctx->modal && !ctx->npopups) { /* menus and tools take every finger as the pointer's */ + BKNode *hit = BK_hit_at(ctx, px(x), px(y)); + if (BK_IS_CUSTOM(hit) && NODE_ENABLED(hit) && bk_custom_touch_mode(hit) == BK_TOUCH_MODE_RAW) { + c->role = BK_CONTACT_RAW; + c->raw = hit; + return raw(ctx, c, BK_TOUCH_DOWN, mods); + } + } + switch (t->state) { + case BK_TOUCH_IDLE: + return begin_lead(ctx, i, t_ms, mods); + case BK_TOUCH_TAP: + case BK_TOUCH_PRESS: + case BK_TOUCH_SCROLL: + return begin_pinch(ctx, i, mods); + default: + return 0; /* a third finger, or one after a gesture: followed, unused */ + } +} + +/* MOVE, UP or CANCEL of contact i, at its new position. */ +static int contact_update(BKContext *ctx, int i, int phase, double t_ms, int mods) +{ + BKTouch *t = &ctx->touch; + BKContact *c = &t->c[i]; + switch (c->role) { + case BK_CONTACT_RAW: + return raw(ctx, c, phase, mods); + case BK_CONTACT_LEAD: + return phase == BK_TOUCH_MOVE ? lead_move(ctx, c, t_ms, mods) : + lead_end(ctx, c, phase, t_ms, mods); + case BK_CONTACT_PAIR: { + if (phase != BK_TOUCH_MOVE) { + return pair_end(ctx, i, phase, mods); + } + const unsigned bit = i == t->pair[0] ? 1u : 2u; + const bool again = (t->moved & bit) != 0; + t->moved |= bit; + return again || t->moved == 3u ? pinch_update(ctx, mods) : 0; + } + default: + return 0; + } +} + +/* Contact i is gone: its slot frees, and with the last finger that was not raw the fingers are + * free to be the pointer again. */ +static void contact_free(BKTouch *t, int i) +{ + t->c[i].role = BK_CONTACT_FREE; + t->c[i].raw = NULL; + for (int k = 0; k < BK_MAX_TOUCH; k++) { + const BKContactRole role = t->c[k].role; + if (role != BK_CONTACT_FREE && role != BK_CONTACT_RAW) { + return; + } + } + t->state = BK_TOUCH_IDLE; + t->lead = -1; +} + +int BK_touch(BKContext *ctx, int id, int phase, float x, float y, double time_ms, int mods) +{ + if (!ctx || phase < BK_TOUCH_DOWN || phase > BK_TOUCH_CANCEL) { + return 0; + } + BKTouch *t = &ctx->touch; + const double t_ms = time_ms > 0.0 ? time_ms : bk_time() * 1000.0; + mods &= BK_SHIFT | BK_CTRL | BK_ALT; /* buttons and BK_FROM_TOUCH are the kit's to set */ + int i = find(t, id); + if (phase == BK_TOUCH_DOWN) { + int r = 0; + if (i >= 0) { /* its lift was lost: what it did is not kept */ + r = contact_update(ctx, i, BK_TOUCH_CANCEL, t_ms, mods); + contact_free(t, i); + } + return contact_down(ctx, id, x, y, t_ms, mods) | r; + } + if (i < 0) { + return 0; /* not followed (an eleventh finger, or one that began before a cancel) */ + } + BKContact *c = &t->c[i]; + if (phase != BK_TOUCH_CANCEL) { /* a cancel has no place of its own (wl_touch.cancel) */ + c->x = x; + c->y = y; + } + const int r = contact_update(ctx, i, phase, t_ms, mods); + if (phase != BK_TOUCH_MOVE) { + contact_free(t, i); + } + return r; +} + +void bk_touch_cancel_all(BKContext *ctx) +{ + BKTouch *t = &ctx->touch; + bool down = false; + for (int i = 0; i < BK_MAX_TOUCH; i++) { + BKContact *c = &t->c[i]; + if (c->role == BK_CONTACT_RAW) { + raw(ctx, c, BK_TOUCH_CANCEL, 0); + c->role = BK_CONTACT_IDLE; + c->raw = NULL; + } + else if (c->role == BK_CONTACT_LEAD) { + lead_end(ctx, c, BK_TOUCH_CANCEL, 0.0, 0); + c->role = BK_CONTACT_IDLE; + } + else if (c->role == BK_CONTACT_PAIR && t->state == BK_TOUCH_PINCH) { + pair_end(ctx, i, BK_TOUCH_CANCEL, 0); + c->role = BK_CONTACT_IDLE; + } + down |= c->role != BK_CONTACT_FREE; + } + /* the fingers still down are followed until they lift (their ups may never come: a new down + * with the same id replaces one) */ + t->state = down ? BK_TOUCH_SPENT : BK_TOUCH_IDLE; +} + +double bk_touch_due(const BKContext *ctx) +{ + return ctx->touch.state == BK_TOUCH_TAP ? ctx->touch.long_press_at : 0.0; +} + +void bk_touch_tick(BKContext *ctx) +{ + BKTouch *t = &ctx->touch; + if (t->state != BK_TOUCH_TAP || t->long_press_at <= 0.0 || bk_time() + 0.002 < t->long_press_at) { + return; + } + /* held in place: a right press (the context menu), and the finger does nothing more */ + t->long_press_at = 0.0; + const int x = px(t->down_x), y = px(t->down_y); + if (BK_context_menu(ctx, x, y, BK_FROM_TOUCH)) { + BK_button(ctx, x, y, 3, 1, BK_FROM_TOUCH); + t->state = BK_TOUCH_SPENT; + } +} + +void bk_touch_frame(BKContext *ctx) +{ + BKTouch *t = &ctx->touch; + bk_touch_tick(ctx); /* hosts without timers: the long press comes with a render */ + if (t->fling_t0 <= 0.0) { + return; + } + const double elapsed = (bk_time() - t->fling_t0) * 1000.0; + bool done_x, done_y; + const float x = bk_fling_at(&t->fling_x, elapsed, &done_x); + const float y = bk_fling_at(&t->fling_y, elapsed, &done_y); + scroll(ctx, x - t->fling_done_x, y - t->fling_done_y, BK_SCROLL_FLING, 0); + t->fling_done_x = x; + t->fling_done_y = y; + if (done_x && done_y) { + t->fling_t0 = 0.0; + } +} + +bool bk_touch_animating(const BKContext *ctx) +{ + return ctx->touch.fling_t0 > 0.0; +} diff --git a/kit/intern/kit_touch.h b/kit/intern/kit_touch.h new file mode 100644 index 00000000..15b9b47c --- /dev/null +++ b/kit/intern/kit_touch.h @@ -0,0 +1,77 @@ +/* Touch screens (BK_touch): the state machine that turns a host's contacts into the pointer, + * scrolls, flings and gestures the widgets know, the same on every platform. See kit_touch.c. + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#ifndef KIT_TOUCH_H +#define KIT_TOUCH_H + +#include + +#include "kit_fling.h" + +typedef struct BKNode BKNode; +typedef struct BKContext BKContext; + +#define BK_MAX_TOUCH 10 /* contacts followed at once; more are ignored until one lifts */ + +/* What one contact is (BKContact.role). */ +typedef enum { + BK_CONTACT_FREE = 0, /* the slot is unused */ + BK_CONTACT_LEAD, /* the finger of the one-finger path (BKTouch.state says which) */ + BK_CONTACT_PAIR, /* one of the gesture's two fingers */ + BK_CONTACT_RAW, /* a BK_TOUCH_MODE_RAW custom node's (BKContact.raw) */ + BK_CONTACT_IDLE, /* followed until it lifts, used for nothing (a third finger, a cancel) */ +} BKContactRole; + +typedef struct BKContact { + int id; /* the host's */ + BKContactRole role; + float x, y; /* its last position, window pixels */ + BKNode *raw; /* BK_CONTACT_RAW: the custom node it belongs to */ +} BKContact; + +/* What the fingers that are not raw do together. */ +typedef enum { + BK_TOUCH_IDLE = 0, /* none down */ + BK_TOUCH_TAP, /* one finger, not moved: a click if it lifts, the context menu if held */ + BK_TOUCH_PRESS, /* one finger on a widget that drags: the pointer, pressed */ + BK_TOUCH_SCROLL, /* one finger scrolls the content */ + BK_TOUCH_PINCH, /* two fingers: pan, magnify, rotate */ + BK_TOUCH_SPENT, /* a gesture or a long press ended: nothing until every finger lifted */ +} BKTouchState; + +typedef struct BKTouch { + BKContact c[BK_MAX_TOUCH]; + BKTouchState state; + int lead; /* the one-finger path's contact (TAP, PRESS, SCROLL), else -1 */ + int pair[2]; /* PINCH: its contacts, else -1 */ + float down_x, down_y; /* where the lead went down (the slop and the long press) */ + float last_x, last_y; /* the scroll's last point: the lead's, or the pair's centre */ + int anchor_x, anchor_y; /* what scrolls is under here: where the scroll began */ + float dist, angle; /* PINCH: the fingers' spread and angle at the last update */ + unsigned moved; /* PINCH: bit 0 / 1, that finger moved since the last update */ + BKNode *pinch_target; /* PINCH: magnify / rotate go to it (NULL: under the centre) */ + double long_press_at; /* TAP: bk_time() the context menu opens at, 0 none */ + BKVelocityTracker vt; /* SCROLL: the lead's touches */ + /* the fling after a one-finger scroll (Android's OverScroller, per axis) */ + BKFling fling_x, fling_y; + float fling_done_x, fling_done_y; + double fling_t0; /* bk_time() it began, 0: no fling */ +} BKTouch; + +void bk_touch_init(BKTouch *t); +/* The nodes of `subtree` are going: contacts and the pinch let go of them. */ +void bk_touch_forget(BKTouch *t, const BKNode *subtree); +/* Every contact down is cancelled: nothing they did is kept (BK_cancel, the window lost focus). */ +void bk_touch_cancel_all(BKContext *ctx); +/* The context's frame timer (bk_ctx_arm_timer): when the long press is due (bk_time), 0 none; + * and its tick, which opens the context menu when it is. */ +double bk_touch_due(const BKContext *ctx); +void bk_touch_tick(BKContext *ctx); +/* BK_render, before the layout: the fling's step. True while one runs (BK_animating). */ +void bk_touch_frame(BKContext *ctx); +bool bk_touch_animating(const BKContext *ctx); + +#endif diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.c index ead04f5c..18ffc906 100644 --- a/kit/intern/kit_widgets.c +++ b/kit/intern/kit_widgets.c @@ -901,7 +901,7 @@ static int panel_a11y_do(BKNode *n, int item, int action) const BKClass bk_cls_panel = {.name = "panel", .a11y_role = BK_ROLE_GROUP, .a11y_do = panel_a11y_do, .draw_tree = panel_draw_tree, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, .drag_group = DRAG_GROUP_PANEL, .init = panel_init, .measure = panel_measure, @@ -1546,7 +1546,7 @@ static void sb_init(BKNode *n) } const BKClass bk_cls_scrollbar = {.name = "scrollbar", .a11y_role = BK_ROLE_SCROLL_BAR, - .flags = CLS_INTERACTIVE, + .flags = CLS_INTERACTIVE | CLS_DRAGS, .init = sb_init, .measure = sb_measure, .draw = sb_draw, @@ -2422,7 +2422,7 @@ static void number_draw(BKNode *n) } #define NUMBER_CLASS_COMMON \ - .flags = CLS_INTERACTIVE | CLS_VALUE, .cursor = BK_CURSOR_EW, \ + .flags = CLS_INTERACTIVE | CLS_VALUE | CLS_DRAGS, .cursor = BK_CURSOR_EW, \ .drag_cursor = BK_CURSOR_NONE, .measure = number_measure, .press = number_press, \ .dbl = number_dbl, .drag = number_drag, .release = number_release, .key = number_key, \ .move = number_move, .leave = number_leave, .cursor_at = number_cursor_at, \ @@ -2655,7 +2655,7 @@ static void text_draw(BKNode *n) } #define TEXT_CLASS_COMMON \ - .flags = CLS_INTERACTIVE | CLS_VALUE, .cursor = BK_CURSOR_TEXT, .measure = text_measure, \ + .flags = CLS_INTERACTIVE | CLS_VALUE | CLS_DRAGS, .cursor = BK_CURSOR_TEXT, .measure = text_measure, \ .draw = text_draw, .press = text_press, .dbl = text_dbl, .drag = text_drag, \ .key = text_key, .cursor_at = text_cursor_at, .finish_edit = text_finish, \ .to_text = text_to_text, .from_text = text_from_text, .reset = text_reset, \ @@ -3257,7 +3257,7 @@ static void swatch_draw(BKNode *n) } const BKClass bk_cls_swatch = {.name = "swatch", .a11y_role = BK_ROLE_COLOR_WELL, - .flags = CLS_INTERACTIVE | CLS_VALUE, + .flags = CLS_INTERACTIVE | CLS_VALUE | CLS_DRAGS, .init = swatch_init, .measure = swatch_measure, .draw = swatch_draw, diff --git a/kit/intern/kit_window_android.c b/kit/intern/kit_window_android.c index 38b573e2..a28c8556 100644 --- a/kit/intern/kit_window_android.c +++ b/kit/intern/kit_window_android.c @@ -7,8 +7,9 @@ * - Damage driven: the loop sleeps in ALooper until a touch, key, timer, wake or frame request. * Only the damaged rectangles are converted (B,G,R,A raster words to the surface's R,G,B,X * bytes) and locked; while the kit animates, the buffer queue paces the loop to the display. - * - Touch: one finger is the pointer (a tap is a click), a drag that starts on a widget that does - * not drag scrolls, two fingers scroll, and the pointer leaves with the last finger. + * - Touch: every pointer of a motion event goes to the kit's touch model (BK_touch, kit_touch.c), + * the batched moves first: taps, scrolls and flings, long presses and two-finger gestures are + * the same as in every other window host. * - Keys: key events (KeyEvent.getUnicodeChar through JNI) and the soft keyboard while a field is * being edited (BK_ime_state). No IME composition yet. * @@ -38,14 +39,10 @@ # include # include "GPU_raster.h" -# include "kit_fling.h" # include "android_native_app_glue.h" # define MAX_TIMERS 16 # define IDLE_FRAME_MS 4.0 /* an animating pass that drew nothing waits this long (under any panel's frame) */ -# define TOUCH_SLOP_DP 8.0f -/* a touch this close to the right edge of a custom node is the app's: its scrollbar */ -# define EDGE_DP 20.0f # define WINDOW_FORMAT_RGBX 0x2 typedef struct Timer { @@ -73,18 +70,6 @@ struct BKWindow { Timer timers[MAX_TIMERS]; char *clipboard; int px, py; /* last pointer position */ - /* touch */ - int pointer_down, scrolling, draggable; - int pending_tap; /* a finger is down on something that does not drag: a click if it lifts in place */ - int drag_custom; /* custom and canvas nodes take drags (BK_window_wm "touch_drag"); else they scroll */ - float down_x, down_y, scroll_x, scroll_y; - /* momentum: the touches of a one-finger scroll (Android's VelocityTracker) and the fling after it - * (Android's OverScroller spline, one per axis) */ - BKVelocityTracker vt; - BKFling fling_x, fling_y; - float fling_done_x, fling_done_y; /* the distance of each already scrolled */ - double fling_ms; - int fling; }; static BKWindow *g_win; @@ -645,228 +630,51 @@ static int32_t on_key(BKWindow *win, AInputEvent *e) return 0; } -/* Widgets that use a drag themselves; a drag that starts anywhere else scrolls the page. A custom - * or canvas node (a Rust page is one) scrolls unless the app asks for its drags. */ -static int drags(const BKWindow *win, const BKNode *n) +/* One pointer of a motion event at its sample `h` (the batched ones, then the current one: -1). */ +static void touch_pointer(BKWindow *win, const AInputEvent *e, size_t i, int h, int phase) { - static const char *const types[] = {"slider", "number", "scrollbar", "text", "textarea", "panel", - "nodeeditor", "curve", "ramp", "picker", "normal", "swatch", - "histogram", "eyedropper"}; - const char *t = n ? BK_node_type(n) : ""; - if (win->drag_custom && (strcmp(t, "custom") == 0 || strcmp(t, "canvas") == 0)) { - return 1; - } - for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) { - if (strcmp(t, types[i]) == 0) { - return 1; - } - } - return 0; -} - -/* A touch in the strip at the right edge of a custom or canvas node: the app draws its scrollbar - * there (a list's thumb), so the touch is its press and drag, not a scroll. */ -static int on_edge(const BKWindow *win, const BKNode *n, float x) -{ - const char *t = n ? BK_node_type(n) : ""; - if (strcmp(t, "custom") != 0 && strcmp(t, "canvas") != 0) { - return 0; - } - int r[4]; - BK_node_rect(n, r); - return x >= (float)(r[0] + r[2]) - EDGE_DP * win->density; -} - -static void pointer_up(BKWindow *win, float x, float y) -{ - if (win->pointer_down) { - BK_motion(win->ctx, (int)x, (int)y, 0); - BK_release(win->ctx, (int)x, (int)y, 0); - win->pointer_down = 0; - } - BK_motion(win->ctx, -1, -1, 0); /* no hover once the finger is gone */ -} - -/* A press that turned into a scroll, or a touch the system cancelled, ends with nothing applied - * (BK_cancel: no motion, no click, a drag's value back), and no hover once the finger is gone. */ -static void cancel_press(BKWindow *win) -{ - if (win->pointer_down) { - BK_cancel(win->ctx, 0); - win->pointer_down = 0; - } - BK_motion(win->ctx, -1, -1, 0); -} - -/* Scrolls the content under (x, y) by (dx, dy) pixels; `phase` (BK_SCROLL_*) tells a list whether a - * finger is on it (it stretches past an end until the finger lifts) or it coasts. */ -static void scroll_px(BKWindow *win, float x, float y, float dx, float dy, int phase) -{ - BK_motion(win->ctx, (int)x, (int)y, 0); /* a page that scrolls under the pointer needs to know it */ - BK_scroll_phase(win->ctx, phase); - BK_scroll_px(win->ctx, (int)x, (int)y, dx, dy, 0); /* the content follows the finger exactly */ - BK_scroll_phase(win->ctx, BK_SCROLL_WHEEL); - BK_motion(win->ctx, -1, -1, 0); /* a scrolling touch is no hover: nothing under it lights up */ -} - -static void scroll_by(BKWindow *win, float x, float y, float *last_x, float *last_y) -{ - scroll_px(win, x, y, *last_x - x, y - *last_y, BK_SCROLL_DRAG); - *last_x = x; - *last_y = y; -} - -/* The finger lifted: a list lets go of a stretch (nothing to scroll). */ -static void scroll_end(BKWindow *win, float x, float y) -{ - scroll_px(win, x, y, 0.0f, 0.0f, BK_SCROLL_END); -} - -/* The finger lifted while scrolling: carry on at its velocity (Android's: a least squares fit of the - * last 100 ms of touches, none when the finger rested before lifting), along OverScroller's spline. */ -static void fling_start(BKWindow *win, double now) -{ - float vx, vy; - if (!bk_vt_velocity(&win->vt, now, &vx, &vy)) { - return; - } - const int fx = bk_fling_start(&win->fling_x, vx, win->density); - const int fy = bk_fling_start(&win->fling_y, vy, win->density); - if (!fx) { - win->fling_x.distance_px = 0.0f; - win->fling_x.duration_ms = 1.0f; - } - if (!fy) { - win->fling_y.distance_px = 0.0f; - win->fling_y.duration_ms = 1.0f; - } - if (fx || fy) { - win->fling = 1; - win->fling_ms = now; - win->fling_done_x = win->fling_done_y = 0.0f; - } -} - -static void fling_step(BKWindow *win) -{ - const double elapsed = now_ms() - win->fling_ms; - bool done_x, done_y; - const float x = bk_fling_at(&win->fling_x, elapsed, &done_x); - const float y = bk_fling_at(&win->fling_y, elapsed, &done_y); - scroll_px(win, (float)win->px, (float)win->py, -(x - win->fling_done_x), y - win->fling_done_y, BK_SCROLL_FLING); - win->fling_done_x = x; - win->fling_done_y = y; - win->fling = !(done_x && done_y); - win->dirty = 1; -} - -/* The touches of pointer 0 in `e`, the batched ones first, to the velocity tracker. */ -static void track(BKWindow *win, const AInputEvent *e) -{ - const size_t n = AMotionEvent_getHistorySize(e); - for (size_t i = 0; i < n; i++) { - bk_vt_add(&win->vt, (double)AMotionEvent_getHistoricalEventTime(e, i) * 1.0e-6, - AMotionEvent_getHistoricalX(e, 0, i) - (float)win->ox, AMotionEvent_getHistoricalY(e, 0, i) - (float)win->oy); - } - bk_vt_add(&win->vt, (double)AMotionEvent_getEventTime(e) * 1.0e-6, AMotionEvent_getX(e, 0) - (float)win->ox, - AMotionEvent_getY(e, 0) - (float)win->oy); + const float x = h < 0 ? AMotionEvent_getX(e, i) : AMotionEvent_getHistoricalX(e, i, (size_t)h); + const float y = h < 0 ? AMotionEvent_getY(e, i) : AMotionEvent_getHistoricalY(e, i, (size_t)h); + const int64_t ns = h < 0 ? AMotionEvent_getEventTime(e) : AMotionEvent_getHistoricalEventTime(e, (size_t)h); + BK_touch(win->ctx, AMotionEvent_getPointerId(e, i), phase, x - (float)win->ox, y - (float)win->oy, + (double)ns * 1.0e-6, 0); } static int32_t on_touch(BKWindow *win, AInputEvent *e) { - const int32_t action = AMotionEvent_getAction(e) & AMOTION_EVENT_ACTION_MASK; + const int32_t action = AMotionEvent_getAction(e); const size_t count = AMotionEvent_getPointerCount(e); - const float x = AMotionEvent_getX(e, 0) - (float)win->ox; - const float y = AMotionEvent_getY(e, 0) - (float)win->oy; - const float slop = TOUCH_SLOP_DP * win->density; - switch (action) { + const size_t index = (size_t)((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> + AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); + switch (action & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_DOWN: - win->down_x = win->scroll_x = x; - win->down_y = win->scroll_y = y; - win->scrolling = win->fling = 0; /* a touch stops a fling */ - bk_vt_clear(&win->vt); /* the velocity of a scroll counts from the touch down */ - track(win, e); - BK_motion(win->ctx, (int)x, (int)y, 0); - win->draggable = drags(win, BK_hover(win->ctx)) || on_edge(win, BK_hover(win->ctx), x); - if (win->draggable) { /* a slider, a text field ...: it gets the press now */ - BK_press(win->ctx, (int)x, (int)y, 0); - win->pointer_down = 1; - } - else { /* a tap or a scroll: the kit hears of it once we know which */ - win->pending_tap = 1; - } - break; case AMOTION_EVENT_ACTION_POINTER_DOWN: - if (count >= 2) { /* a second finger: scroll instead of drag */ - if (!win->scrolling) { - win->pending_tap = 0; - cancel_press(win); - win->scrolling = 1; - } - /* from the two fingers' middle now, even mid scroll: the one finger's point it followed - * until now is not where the middle is (no jump) */ - win->scroll_x = (AMotionEvent_getX(e, 0) + AMotionEvent_getX(e, 1)) * 0.5f - (float)win->ox; - win->scroll_y = (AMotionEvent_getY(e, 0) + AMotionEvent_getY(e, 1)) * 0.5f - (float)win->oy; - } - break; - case AMOTION_EVENT_ACTION_MOVE: - track(win, e); - if (win->scrolling && count >= 2) { - scroll_by(win, (AMotionEvent_getX(e, 0) + AMotionEvent_getX(e, 1)) * 0.5f - (float)win->ox, - (AMotionEvent_getY(e, 0) + AMotionEvent_getY(e, 1)) * 0.5f - (float)win->oy, - &win->scroll_x, &win->scroll_y); - } - else if (win->scrolling) { /* a one-finger scroll */ - scroll_by(win, x, y, &win->scroll_x, &win->scroll_y); - } - else if (win->pending_tap) { - const float dx = x - win->down_x, dy = y - win->down_y; - if (dx * dx + dy * dy > slop * slop) { /* not a click: scroll, from where the finger went down */ - win->pending_tap = 0; - win->scrolling = 1; - /* the slop is the finger's, not the content's: the scroll starts from just past it, so the - * content does not jump by the slop (what RecyclerView does) */ - win->scroll_x = x - (fabsf(dx) > slop ? copysignf(slop, dx) : dx); - win->scroll_y = y - (fabsf(dy) > slop ? copysignf(slop, dy) : dy); - scroll_by(win, x, y, &win->scroll_x, &win->scroll_y); - } - } - else if (win->pointer_down) { - BK_motion(win->ctx, (int)x, (int)y, BK_BUTTON1); - } + touch_pointer(win, e, index, -1, BK_TOUCH_DOWN); break; + case AMOTION_EVENT_ACTION_UP: case AMOTION_EVENT_ACTION_POINTER_UP: - if (count <= 2) { - win->scrolling = 0; - } + touch_pointer(win, e, index, -1, BK_TOUCH_UP); break; - case AMOTION_EVENT_ACTION_UP: - if (win->scrolling) { /* a one-finger scroll (two fingers cleared it when one lifted) */ - scroll_end(win, x, y); - track(win, e); - fling_start(win, (double)AMotionEvent_getEventTime(e) * 1.0e-6); - } - win->scrolling = 0; - if (win->pending_tap) { /* lifted in place: the click */ - win->pending_tap = 0; - BK_motion(win->ctx, (int)x, (int)y, 0); - BK_press(win->ctx, (int)x, (int)y, 0); - win->pointer_down = 1; + case AMOTION_EVENT_ACTION_MOVE: { + /* the batched samples first: the fling's velocity fits them, as VelocityTracker does */ + const int n = (int)AMotionEvent_getHistorySize(e); + for (int h = 0; h <= n; h++) { + for (size_t i = 0; i < count; i++) { + touch_pointer(win, e, i, h < n ? h : -1, BK_TOUCH_MOVE); + } } - pointer_up(win, x, y); break; + } case AMOTION_EVENT_ACTION_CANCEL: - if (win->scrolling) { - scroll_end(win, x, y); + for (size_t i = 0; i < count; i++) { + touch_pointer(win, e, i, -1, BK_TOUCH_CANCEL); } - win->scrolling = win->pending_tap = win->fling = 0; - cancel_press(win); break; default: return 0; } - win->px = (int)x; - win->py = (int)y; + win->px = (int)(AMotionEvent_getX(e, 0) - (float)win->ox); + win->py = (int)(AMotionEvent_getY(e, 0) - (float)win->oy); win->dirty = 1; return 1; } @@ -991,7 +799,7 @@ static int wait_ms(const BKWindow *win) /* With no surface nothing can be drawn, so a pending frame must not keep the loop spinning: it * waits for the surface (APP_CMD_INIT_WINDOW wakes the looper). */ if (atomic_load(&g_wake_flag) || - (win && (win->fling || (g_app->window && (win->dirty || win->want_frame))))) { + (win && g_app->window && (win->dirty || win->want_frame))) { return 0; } double next = 0.0; @@ -1069,9 +877,6 @@ static void step(int block) return; } fire_timers(win); - if (win->fling) { - fling_step(win); - } if (win->retry_ms != 0.0 && win->retry_ms <= now_ms()) { win->dirty = 1; /* the failed present's turn (`draw` clears it) */ } @@ -1299,9 +1104,12 @@ void *BK_window_handle(BKWindow *win) void BK_window_wm(BKWindow *win, const char *key, double a, double b) { - if (strcmp(key, "touch_drag") == 0) { /* the only request an Android window has */ - win->drag_custom = a != 0.0; - } + /* an Android window has no requests: what a finger does to a custom node is the node's + * (BK_custom_set_touch) */ + (void)win; + (void)key; + (void)a; + (void)b; } int BK_window_wm_get(BKWindow *win, const char *key, double *r_a, double *r_b) diff --git a/kit/intern/kit_window_cocoa.m b/kit/intern/kit_window_cocoa.m index ff99e7f5..9b32363c 100644 --- a/kit/intern/kit_window_cocoa.m +++ b/kit/intern/kit_window_cocoa.m @@ -556,6 +556,32 @@ - (void)scrollWheel:(NSEvent *)ev } } +/* GHOST_SystemCocoa::handleMouseEvent's trackpad gestures: NSEventTypeMagnify + * (GHOST_kTrackpadEventMagnify) and NSEventTypeRotate (GHOST_kTrackpadEventRotate). BK_magnify + * and BK_rotate take NSEvent's own units: the scale change (0.1 = 10% larger) and degrees, + * counter-clockwise positive, so neither is scaled nor negated as GHOST does for its integer + * deltas. A render follows from the kit's request, as for scrolling. */ +- (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 62e46890..db9bcf6b 100644 --- a/kit/intern/kit_window_wayland.c +++ b/kit/intern/kit_window_wayland.c @@ -33,6 +33,9 @@ # ifdef BUI_WL_CURSOR_SHAPE # include "cursor-shape-v1-client-protocol.h" # endif +# ifdef BUI_WL_POINTER_GESTURES +# include "pointer-gestures-unstable-v1-client-protocol.h" +# endif # include "xdg-decoration-unstable-v1-client-protocol.h" # include "xdg-shell-client-protocol.h" @@ -53,6 +56,7 @@ # define MAX_TIMERS 16 # define MAX_RECTS 32 # define MAX_OUTPUTS 8 +# define MAX_CONTACTS 10 /* touch screen fingers followed at once (as the kit's BK_MAX_TOUCH) */ /* -- libxkbcommon, loaded on first use -- */ @@ -149,6 +153,13 @@ typedef struct { int scale, w, h; } Output; +/* A wl_touch contact that is down: up and cancel carry no position, so its last one is kept. */ +typedef struct { + BKWindow *win; /* the window it went down on; NULL: the slot is free */ + int32_t id; + float x, y; /* raster pixels */ +} Contact; + static struct { struct wl_display *display; struct wl_registry *registry; @@ -165,6 +176,13 @@ static struct { struct wl_seat *seat; struct wl_pointer *pointer; struct wl_keyboard *keyboard; + struct wl_touch *touch; /* while the seat has a touch screen */ + Contact contacts[MAX_CONTACTS]; +# ifdef BUI_WL_POINTER_GESTURES + struct zwp_pointer_gestures_v1 *pointer_gestures; + struct zwp_pointer_gesture_pinch_v1 *pinch; /* of the pointer */ + double pinch_scale; /* the pinch's scale at its last event (1 at its begin), 0 none */ +# 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 */ @@ -542,6 +560,12 @@ static void apply_cursor(BKWindow *win) (int)image->hotspot_y / g.cursor_scale); } +/* A surface-local coordinate (compositor units) in the window's raster pixels. */ +static double surface_px(const BKWindow *win, wl_fixed_t v) +{ + return wl_fixed_to_double(v) * win->bscale; +} + static void pointer_enter(void *d, struct wl_pointer *p, uint32_t serial, struct wl_surface *s, wl_fixed_t x, wl_fixed_t y) { @@ -549,8 +573,8 @@ static void pointer_enter(void *d, struct wl_pointer *p, uint32_t serial, struct g.pointer_win = win; g.pointer_serial = serial; if (win) { - g.px = wl_fixed_to_double(x) * win->bscale; - g.py = wl_fixed_to_double(y) * win->bscale; + g.px = surface_px(win, x); + g.py = surface_px(win, y); apply_cursor(win); BK_motion(win->ctx, (int)g.px, (int)g.py, mods_now()); } @@ -572,8 +596,8 @@ static void pointer_motion(void *d, struct wl_pointer *p, uint32_t time, wl_fixe { BKWindow *win = g.pointer_win; if (win) { - g.px = wl_fixed_to_double(x) * win->bscale; - g.py = wl_fixed_to_double(y) * win->bscale; + g.px = surface_px(win, x); + g.py = surface_px(win, y); BK_motion(win->ctx, (int)g.px, (int)g.py, mods_now()); } } @@ -630,6 +654,135 @@ static struct wl_pointer_listener pointer_listener = { .enter = pointer_enter, .leave = pointer_leave, .motion = pointer_motion, .button = pointer_button, .axis = pointer_axis}; +# ifdef BUI_WL_POINTER_GESTURES +/* -- seat: touchpad pinches (zwp_pointer_gestures_v1, as GHOST_SystemWayland's gesture_pinch) -- + * About the pointer, whose motion stops while the fingers pinch. `scale` is the spread over the + * begin's, so the change since the last event is scale / last - 1 (NSEvent.magnification's + * units); `rotation` is degrees clockwise since the last event, BK_rotate's counter-clockwise. */ + +static void pinch_begin(void *d, struct zwp_pointer_gesture_pinch_v1 *p, uint32_t serial, + uint32_t time, struct wl_surface *s, uint32_t fingers) +{ + 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.pointer_win; + if (!win || g.pinch_scale <= 0.0) { + return; + } + const int x = (int)g.px, y = (int)g.py, mods = mods_now() & ~BK_BUTTON1; + const double s = wl_fixed_to_double(scale); + if (s > 0.0 && s != g.pinch_scale) { + BK_magnify(win->ctx, x, y, (float)(s / g.pinch_scale - 1.0), mods); + g.pinch_scale = s; + } + if (rotation != 0) { + BK_rotate(win->ctx, x, y, (float)-wl_fixed_to_double(rotation), mods); + } +} + +static void pinch_end(void *d, struct zwp_pointer_gesture_pinch_v1 *p, uint32_t serial, + uint32_t time, int32_t cancelled) +{ + g.pinch_scale = 0.0; +} + +static struct zwp_pointer_gesture_pinch_v1_listener pinch_listener = { + .begin = pinch_begin, .update = pinch_update, .end = pinch_end}; + +/* The pointer's pinch, once both the pointer and the gestures global are there. */ +static void pinch_attach(void) +{ + if (g.pointer_gestures && g.pointer && !g.pinch) { + g.pinch = zwp_pointer_gestures_v1_get_pinch_gesture(g.pointer_gestures, g.pointer); + zwp_pointer_gesture_pinch_v1_add_listener(g.pinch, &pinch_listener, NULL); + } +} +# endif + +/* -- seat: touch screen (wl_touch; compositors send no pointer for it) -- + * Each contact goes to the window it went down on, in raster pixels as the pointer's; `time` is + * the event's, in milliseconds. A frame only groups contacts: each is sent as it comes. */ + +static Contact *contact_find(int32_t id) +{ + for (int i = 0; i < MAX_CONTACTS; i++) { + if (g.contacts[i].win && g.contacts[i].id == id) { + return &g.contacts[i]; + } + } + return NULL; +} + +/* The contact lifts (BK_TOUCH_UP) or is taken back (BK_TOUCH_CANCEL); its slot is free. */ +static void contact_end(Contact *c, int phase, uint32_t time) +{ + BKWindow *win = c->win; + c->win = NULL; + BK_touch(win->ctx, c->id, phase, c->x, c->y, (double)time, mods_now()); +} + +/* Every contact still down is cancelled: the compositor took them, the touch screen went, or + * (`only` non-NULL) that window closes. */ +static void contacts_cancel(const BKWindow *only) +{ + for (int i = 0; i < MAX_CONTACTS; i++) { + if (g.contacts[i].win && (!only || g.contacts[i].win == only)) { + contact_end(&g.contacts[i], BK_TOUCH_CANCEL, 0 /* now */); + } + } +} + +static void touch_down(void *d, struct wl_touch *t, uint32_t serial, uint32_t time, + struct wl_surface *s, int32_t id, wl_fixed_t x, wl_fixed_t y) +{ + g.serial = serial; + BKWindow *win = find_window(s); + if (!win || !win->open) { + return; + } + Contact *c = contact_find(id); /* its up was lost: the kit replaces it */ + for (int i = 0; !c && i < MAX_CONTACTS; i++) { + c = g.contacts[i].win ? NULL : &g.contacts[i]; + } + if (!c) { + return; /* more fingers than the kit follows */ + } + *c = (Contact){win, id, (float)surface_px(win, x), (float)surface_px(win, y)}; + BK_touch(win->ctx, id, BK_TOUCH_DOWN, c->x, c->y, (double)time, mods_now()); +} + +static void touch_up(void *d, struct wl_touch *t, uint32_t serial, uint32_t time, int32_t id) +{ + g.serial = serial; + Contact *c = contact_find(id); + if (c) { + contact_end(c, BK_TOUCH_UP, time); + } +} + +static void touch_motion(void *d, struct wl_touch *t, uint32_t time, int32_t id, wl_fixed_t x, + wl_fixed_t y) +{ + Contact *c = contact_find(id); + if (c) { + c->x = (float)surface_px(c->win, x); + c->y = (float)surface_px(c->win, y); + BK_touch(c->win->ctx, id, BK_TOUCH_MOVE, c->x, c->y, (double)time, mods_now()); + } +} + +static void touch_cancel(void *d, struct wl_touch *t) +{ + contacts_cancel(NULL); +} + +static struct wl_touch_listener touch_listener = { + .down = touch_down, .up = touch_up, .motion = touch_motion, .cancel = touch_cancel}; + /* -- seat: keyboard -- */ static void keyboard_keymap(void *d, struct wl_keyboard *kb, uint32_t format, int32_t fd, @@ -736,11 +889,28 @@ 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_KEYBOARD) && !g.keyboard) { g.keyboard = wl_seat_get_keyboard(seat); wl_keyboard_add_listener(g.keyboard, &keyboard_listener, NULL); } + if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !g.touch) { + g.touch = wl_seat_get_touch(seat); + wl_touch_add_listener(g.touch, &touch_listener, NULL); + } + else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && g.touch) { /* the touch screen went */ + contacts_cancel(NULL); + if (wl_touch_get_version(g.touch) >= WL_TOUCH_RELEASE_SINCE_VERSION) { + wl_touch_release(g.touch); + } + else { + wl_touch_destroy(g.touch); + } + g.touch = NULL; + } } static struct wl_seat_listener seat_listener = {.capabilities = seat_capabilities}; @@ -935,6 +1105,12 @@ static void registry_global(void *d, struct wl_registry *reg, uint32_t name, con else if (!strcmp(iface, wp_cursor_shape_manager_v1_interface.name)) { g.cursor_shape_manager = wl_registry_bind(reg, name, &wp_cursor_shape_manager_v1_interface, 1); } +# endif +# ifdef BUI_WL_POINTER_GESTURES + else if (!strcmp(iface, zwp_pointer_gestures_v1_interface.name)) { + g.pointer_gestures = wl_registry_bind(reg, name, &zwp_pointer_gestures_v1_interface, 1); + pinch_attach(); + } # endif else if (!strcmp(iface, wl_seat_interface.name) && !g.seat) { g.seat = wl_registry_bind(reg, name, &wl_seat_interface, BK_MIN(version, 5u)); @@ -978,6 +1154,10 @@ static void fill_listeners(void) fill_noop(&frame_listener, sizeof(frame_listener)); fill_noop(&pointer_listener, sizeof(pointer_listener)); fill_noop(&keyboard_listener, sizeof(keyboard_listener)); + fill_noop(&touch_listener, sizeof(touch_listener)); +# ifdef BUI_WL_POINTER_GESTURES + fill_noop(&pinch_listener, sizeof(pinch_listener)); +# endif fill_noop(&seat_listener, sizeof(seat_listener)); fill_noop(&offer_listener, sizeof(offer_listener)); fill_noop(&device_listener, sizeof(device_listener)); @@ -1174,6 +1354,7 @@ static void close_window(BKWindow *win) g.keyboard_win = NULL; g.repeat_key = 0; } + contacts_cancel(win); /* their ups would find no window */ 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 c31810e9..e9134cea 100644 --- a/kit/intern/kit_window_win32.c +++ b/kit/intern/kit_window_win32.c @@ -824,6 +824,65 @@ static const char *vk_keysym(WPARAM vk, char *buf) return NULL; } +/* -- touch -- + * Touch contacts come as pointer messages (Windows 8 and later). Handled here, Windows makes no + * mouse messages of them (no promoted clicks, no press-and-hold right click), so the kit's touch + * model (BK_touch: taps, scrolls, flings, two-finger gestures) is the only one. Pen and mouse + * pointers go on to DefWindowProc, which sends them as mouse messages: a pen is the mouse, as in + * Blender without its tablet API. Positions are physical pixels (per-monitor DPI aware), mapped + * to the client as the mouse's are. */ +# ifdef WM_POINTERDOWN +typedef BOOL(WINAPI *GetPointerTypeFn)(UINT32, POINTER_INPUT_TYPE *); +typedef BOOL(WINAPI *GetPointerInfoFn)(UINT32, POINTER_INFO *); + +/* The touch pointer's info, or false for a pen, the mouse, or a system without the API. */ +static bool touch_info(UINT32 id, POINTER_INFO *r) +{ + static GetPointerTypeFn get_type; + static GetPointerInfoFn get_info; + static int looked_up; + if (!looked_up) { + looked_up = 1; + HMODULE user32 = GetModuleHandleW(L"user32.dll"); + get_type = user32 ? (GetPointerTypeFn)(void *)GetProcAddress(user32, "GetPointerType") : NULL; + get_info = user32 ? (GetPointerInfoFn)(void *)GetProcAddress(user32, "GetPointerInfo") : NULL; + } + POINTER_INPUT_TYPE type; + return get_type && get_info && get_type(id, &type) && type == PT_TOUCH && get_info(id, r); +} + +/* WM_POINTERDOWN / UPDATE / UP: 1 when it was a touch (handled), 0 for DefWindowProc. */ +static int touch_message(BKWindow *win, UINT msg, WPARAM wp) +{ + const UINT32 id = GET_POINTERID_WPARAM(wp); + POINTER_INFO pi; + if (!touch_info(id, &pi)) { + return 0; + } + int phase = msg == WM_POINTERDOWN ? BK_TOUCH_DOWN : msg == WM_POINTERUP ? BK_TOUCH_UP : BK_TOUCH_MOVE; + if (pi.pointerFlags & POINTER_FLAG_CANCELED) { + phase = BK_TOUCH_CANCEL; /* the system took it (an edge swipe) */ + } + else if (phase == BK_TOUCH_MOVE && !(pi.pointerFlags & POINTER_FLAG_INCONTACT)) { + return 1; /* not touching (a lifted contact's last update) */ + } + if (phase == BK_TOUCH_DOWN) { + SetFocus(win->hwnd); + } + POINT p = pi.ptPixelLocation; + ScreenToClient(win->hwnd, &p); + /* the event's own time for the fling's velocity: the performance counter, when it was kept */ + double ms = 0.0; + if (pi.PerformanceCount) { + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + ms = (double)pi.PerformanceCount * 1000.0 / (double)freq.QuadPart; + } + BK_touch(win->ctx, (int)id, phase, (float)p.x, (float)p.y, ms, mods_now(0, 0)); + return 1; +} +# endif + static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { BKWindow *win = (BKWindow *)GetWindowLongPtrW(hwnd, GWLP_USERDATA); @@ -1001,6 +1060,18 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) case WM_RBUTTONDOWN: BK_context_menu(ctx, GET_X_LPARAM(lp), GET_Y_LPARAM(lp), mods_now(wp, 1)); return 0; +# ifdef WM_POINTERDOWN + case WM_POINTERDOWN: + case WM_POINTERUPDATE: + case WM_POINTERUP: + if (touch_message(win, msg, wp)) { + return 0; + } + break; + case WM_POINTERCAPTURECHANGED: /* another window took the contact: it ends with nothing kept */ + BK_touch(ctx, (int)GET_POINTERID_WPARAM(wp), BK_TOUCH_CANCEL, 0.0f, 0.0f, 0.0, 0); + break; +# endif case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: diff --git a/kit/intern/kit_window_x11.c b/kit/intern/kit_window_x11.c index 9d07d739..4851689d 100644 --- a/kit/intern/kit_window_x11.c +++ b/kit/intern/kit_window_x11.c @@ -26,6 +26,16 @@ # include # include # include +/* XInput 2.2 touch screens (and 2.4 touchpad pinches) when the libXi headers are there; without + * them a touch screen stays the server's emulated pointer. */ +# if defined(__has_include) +# if __has_include() +# include +# endif +# endif +# ifdef XI_TouchBegin +# define BK_X11_XI2 +# endif # include # include @@ -43,6 +53,11 @@ * X11 headers (every Linux wheel) imports fine on servers and containers * without X11, and draws native windows wherever X11 (or XWayland) exists. * Every Xlib function below goes through a pointer filled by dlsym. */ +# ifdef BK_X11_XI2 /* libX11's generic event cookies (libX11 1.4, which every XI 2.2 server has) */ +# define BK_X11_XI2_FUNCS(F) F(XQueryExtension) F(XGetEventData) F(XFreeEventData) +# else +# define BK_X11_XI2_FUNCS(F) +# endif # define BK_X11_FUNCS(F) F(XAllocSizeHints) \ F(XChangeProperty) \ F(XCheckTypedWindowEvent) \ @@ -96,7 +111,8 @@ F(XMatchVisualInfo) \ F(XCreateColormap) \ F(XFreeColormap) \ - F(XGetWindowAttributes) + F(XGetWindowAttributes) \ + BK_X11_XI2_FUNCS(F) # define BK_X11_DECL(f) static __typeof__(&f) p_##f; BK_X11_FUNCS(BK_X11_DECL) @@ -178,6 +194,41 @@ static int x11_load(void) # define XFreeColormap (*p_XFreeColormap) # define XGetWindowAttributes (*p_XGetWindowAttributes) +# ifdef BK_X11_XI2 +# define XQueryExtension (*p_XQueryExtension) +# define XGetEventData (*p_XGetEventData) +# define XFreeEventData (*p_XFreeEventData) + +/* libXi, loaded with the display: without it (or on a server older than XI 2.2) the server + * emulates the pointer for a touch screen's first finger, as before. */ +# define BK_XI_FUNCS(F) F(XIQueryVersion) F(XISelectEvents) F(XIQueryDevice) F(XIFreeDeviceInfo) +BK_XI_FUNCS(BK_X11_DECL) + +/* The XInput 2 minor version libXi takes: 2 touch, 4 also gestures (libXi 1.8); 0 no libXi. */ +static int xi_load(void) +{ + void *lib = dlopen("libXi.so.6", RTLD_NOW | RTLD_LOCAL); + if (!lib) { + lib = dlopen("libXi.so", RTLD_NOW | RTLD_LOCAL); + } + if (!lib) { + return 0; + } + BK_XI_FUNCS(BK_X11_LOAD) +# ifdef XI_GesturePinchBegin + if (dlsym(lib, "XIGrabPinchGestureBegin")) { /* new in libXi 1.8, with the gesture events */ + return 4; + } +# endif + return 2; +} + +# define XIQueryVersion (*p_XIQueryVersion) +# define XISelectEvents (*p_XISelectEvents) +# define XIQueryDevice (*p_XIQueryDevice) +# define XIFreeDeviceInfo (*p_XIFreeDeviceInfo) +# endif + # define MAX_TIMERS 64 typedef struct Timer { @@ -204,6 +255,9 @@ struct BKWindow { double frame_start, frame_due; float scale; int w, h; +# ifdef XI_GesturePinchBegin + double pinch_scale; /* an XI 2.4 pinch's scale at its last event (1 at its begin) */ +# endif Timer timers[MAX_TIMERS]; Cursor cursors[12]; struct BKWindow *next; @@ -217,6 +271,11 @@ static int (*g_stop)(void) = NULL; static void (*g_wake_cb)(void) = NULL; static int g_wake_pipe[2] = {-1, -1}; static char *g_clip_text = NULL; /* what we own on CLIPBOARD */ +# ifdef BK_X11_XI2 +/* XInputExtension's major opcode (extension opcodes are >= 128): 0 without XI 2.2 touch; and the + * minor version the server took (2, or 4 with gestures). */ +static int g_xi_opcode = 0, g_xi_minor = 0; +# endif static double now_ms(void) { @@ -225,6 +284,20 @@ static double now_ms(void) return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6; } +# ifdef BK_X11_XI2 +/* XI 2.2 touch events (2.4 pinches) on this display when libXi and the server have them. */ +static void xi_init(void) +{ + int opcode = 0, event, error, major = 2, minor = xi_load(); + if (minor && XQueryExtension(g_dpy, "XInputExtension", &opcode, &event, &error) && + XIQueryVersion(g_dpy, &major, &minor) == Success && major == 2 && minor >= 2) + { + g_xi_opcode = opcode; /* the server's version, never above the one asked */ + g_xi_minor = minor; + } +} +# endif + static int open_display(void) { if (g_dpy) { @@ -243,6 +316,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(); +# endif return 1; } @@ -582,6 +658,123 @@ static void handle_key(BKWindow *win, XKeyEvent *ke, int press) BK_key(win->ctx, printable ? text : "", name, mods); } +# ifdef BK_X11_XI2 +/* -- XInput 2 touch screens and touchpad pinches (all gestures are the kit's: kit_touch.c) -- */ + +/* Touch events (and pinches) on the window, from every master device. Selecting touches makes the + * server send this window a touch screen's contacts instead of its emulated pointer (XI 2.2). */ +static void xi_select(Window xid) +{ + if (!g_xi_opcode) { + return; + } + unsigned char bits[XIMaskLen(XI_LASTEVENT)]; + memset(bits, 0, sizeof(bits)); + XISetMask(bits, XI_TouchBegin); /* the three together, or BadValue */ + XISetMask(bits, XI_TouchUpdate); + XISetMask(bits, XI_TouchEnd); +# ifdef XI_GesturePinchBegin + if (g_xi_minor >= 4) { + XISetMask(bits, XI_GesturePinchBegin); + XISetMask(bits, XI_GesturePinchUpdate); + XISetMask(bits, XI_GesturePinchEnd); + } +# endif + XIEventMask mask = {XIAllMasterDevices, (int)sizeof(bits), bits}; + XISelectEvents(g_dpy, xid, &mask, 1); +} + +/* A touch screen's contacts (XIDirectTouch) are touches; a touchpad's (XIDependentTouch) are + * already the pointer's motion. */ +static bool xi_direct_touch(int device) +{ + int n = 0; + XIDeviceInfo *info = XIQueryDevice(g_dpy, device, &n); + bool direct = false; + for (int i = 0; info && i < n; i++) { + for (int k = 0; k < info[i].num_classes; k++) { + const XIAnyClassInfo *c = info[i].classes[k]; + direct |= c->type == XITouchClass && ((const XITouchClassInfo *)c)->mode == XIDirectTouch; + } + } + if (info) { + XIFreeDeviceInfo(info); + } + return direct; +} + +/* XI_TouchBegin / Update / End: one contact, `detail` its id, at window pixels as MotionNotify's. + * An update with XITouchPendingEnd is a finger already lifted whose end waits for a grab: it + * moves, and its XI_TouchEnd lifts it. */ +static void xi_touch(int evtype, const XIDeviceEvent *de) +{ + BKWindow *win = find_window(de->event); + if (!win || !win->xid || (evtype == XI_TouchBegin && !xi_direct_touch(de->sourceid))) { + return; /* a touchpad's contact is never down, so its updates and end are not followed */ + } + const int phase = evtype == XI_TouchBegin ? BK_TOUCH_DOWN : + evtype == XI_TouchUpdate ? BK_TOUCH_MOVE : + BK_TOUCH_UP; + BK_touch(win->ctx, de->detail, phase, (float)de->event_x, (float)de->event_y, (double)de->time, + mods_of((unsigned)de->mods.effective)); +} + +# ifdef XI_GesturePinchBegin +/* XI 2.4 touchpad pinch: `scale` is the fingers' spread over the begin's, so the change since the + * last event is scale / last - 1 (NSEvent.magnification's units); `delta_angle` is degrees + * clockwise since the last event, BK_rotate's are counter-clockwise. A cancelled end applies + * nothing. */ +static void xi_pinch(int evtype, const XIGesturePinchEvent *ge) +{ + BKWindow *win = find_window(ge->event); + if (!win || !win->xid) { + return; + } + if (evtype == XI_GesturePinchBegin) { + win->pinch_scale = 1.0; + return; + } + if (evtype == XI_GesturePinchEnd && (ge->flags & XIGesturePinchEventCancelled)) { + return; + } + const int x = (int)ge->event_x, y = (int)ge->event_y; + const int mods = mods_of((unsigned)ge->mods.effective); + if (ge->scale > 0.0 && ge->scale != win->pinch_scale) { + if (win->pinch_scale > 0.0) { /* 0: its begin went to another window */ + BK_magnify(win->ctx, x, y, (float)(ge->scale / win->pinch_scale - 1.0), mods); + } + win->pinch_scale = ge->scale; + } + if (ge->delta_angle != 0.0) { + BK_rotate(win->ctx, x, y, (float)-ge->delta_angle, mods); + } +} +# endif + +/* A GenericEvent: XInput 2's from our selections, others ignored. */ +static void xi_event(XGenericEventCookie *cookie) +{ + if (!g_xi_opcode || cookie->extension != g_xi_opcode || !XGetEventData(g_dpy, cookie)) { + return; + } + switch (cookie->evtype) { + case XI_TouchBegin: + case XI_TouchUpdate: + case XI_TouchEnd: + xi_touch(cookie->evtype, (const XIDeviceEvent *)cookie->data); + break; +# ifdef XI_GesturePinchBegin + case XI_GesturePinchBegin: + case XI_GesturePinchUpdate: + case XI_GesturePinchEnd: + xi_pinch(cookie->evtype, (const XIGesturePinchEvent *)cookie->data); + break; +# endif + } + XFreeEventData(g_dpy, cookie); +} +# endif + static void close_window(BKWindow *win) { if (!win->xid) { @@ -614,6 +807,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 xany.window: the cookie's data names it */ + xi_event(&ev->xcookie); + return; + } +# endif BKWindow *win = find_window(ev->xany.window); if (!win || !win->xid) { return; @@ -778,6 +977,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/platform/android/imgui_app.cpp b/platform/android/imgui_app.cpp index f9150e53..e1be71aa 100644 --- a/platform/android/imgui_app.cpp +++ b/platform/android/imgui_app.cpp @@ -1,11 +1,10 @@ /* A Dear ImGui app: ImGui::* calls inside `frame`, in a BUI window (bindings/imgui). The kit's window - * host is the activity's surface, so this is the code it would be on a desktop, plus one line: - * a drag on the ImGui node is ImGui's (sliders, window moves), not a scroll. + * host is the activity's surface, so this is the code it would be on a desktop (a drag on the ImGui + * node is ImGui's, sliders and window moves, as the backend sets BK_TOUCH_MODE_POINTER). * * SPDX-License-Identifier: GPL-2.0-or-later */ -#include "BUI_kit.h" #include "bui_app.h" #include "imgui.h" #include "imgui_impl_bui.h" @@ -40,7 +39,6 @@ void bui_app_main(void) { ImGui::CreateContext(); ImGui_ImplBUI_App *app = ImGui_ImplBUI_CreateApp("Dear ImGui", 360, 720, frame, nullptr); - BK_window_wm(ImGui_ImplBUI_AppWindow(app), "touch_drag", 1, 0); ImGui_ImplBUI_RunApp(app); ImGui_ImplBUI_DestroyApp(app); ImGui::DestroyContext(); diff --git a/tests/touch_test.c b/tests/touch_test.c new file mode 100644 index 00000000..c30929ef --- /dev/null +++ b/tests/touch_test.c @@ -0,0 +1,623 @@ +/* Touch screens and trackpad gestures (BK_touch, BK_magnify, BK_rotate), driven the way a window + * host feeds them: taps, the pointer on widgets that drag, one-finger scrolls and their fling, a + * long press, a second finger's cancel and gesture, raw contacts of custom nodes, lost contacts. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#include +#include +#include +#include +#include +#ifdef _WIN32 +# include +#else +# include +#endif + +#include "BUI_kit.h" +#include "GPU_raster.h" + +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 }; +#define TIMER_FRAME (-1) /* the context's frame timer (custom nodes, the long press) */ + +static void sleep_ms(int ms) +{ +#ifdef _WIN32 + Sleep((DWORD)ms); +#else + usleep((useconds_t)ms * 1000); +#endif +} + +/* -- a host that logs what the kit tells it ----------------------------------------------- */ + +typedef struct Ev { + BKNode *node; + int kind; + char text[64]; + double a, b; +} Ev; + +static Ev g_ev[512]; +static int g_nev, g_warps; + +static void host_emit(void *data, BKNode *node, int kind, void *ref, double a, double b) +{ + (void)data; + if (g_nev == (int)(sizeof(g_ev) / sizeof(g_ev[0]))) { + return; + } + Ev *e = &g_ev[g_nev++]; + e->node = node; + e->kind = kind; + e->a = a; + e->b = b; + e->text[0] = 0; + if (ref && kind != BK_EV_CALL && kind != BK_EV_A11Y_ACTION && kind != BK_EV_CHANGE && + kind != BK_EV_CLICK) + { + snprintf(e->text, sizeof(e->text), "%s", (const char *)ref); + } +} + +static void host_warp(void *data, int x, int y) +{ + (void)data; + (void)x; + (void)y; + g_warps++; +} + +static void host_noop(void *data) +{ + (void)data; +} + +static int count(int kind) +{ + int n = 0; + for (int i = 0; i < g_nev; i++) { + n += g_ev[i].kind == kind; + } + return n; +} + +static const Ev *last(int kind) +{ + for (int i = g_nev - 1; i >= 0; i--) { + if (g_ev[i].kind == kind) { + return &g_ev[i]; + } + } + return NULL; +} + +static int text_int(const Ev *e, int field) +{ + int v[6] = {0}; + sscanf(e->text, "%d %d %d %d %d %d", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]); + return v[field]; +} + +static BKContext *context(BKNode *root) +{ + BKContext *ctx = BK_context_new(root); + BKHost host; + memset(&host, 0, sizeof(host)); + host.request = host_noop; + host.warp = host_warp; + host.emit = host_emit; + BK_context_set_host(ctx, &host); + g_nev = g_warps = 0; + return ctx; +} + +static BuiRaster *g_raster; + +static void render(BKContext *ctx) +{ + BK_render(ctx, g_raster, W, H, 0); +} + +static void centre(BKNode *n, int *x, int *y) +{ + int r[4]; + BK_node_rect(n, r); + *x = r[0] + r[2] / 2; + *y = r[1] + r[3] / 2; +} + +/* a finger's whole path from (x0, y0) to (x1, y1), `steps` moves `dt` ms apart from `t` */ +static double drag(BKContext *ctx, int id, float x0, float y0, float x1, float y1, int steps, double t, double dt) +{ + BK_touch(ctx, id, BK_TOUCH_DOWN, x0, y0, t, 0); + for (int i = 1; i <= steps; i++) { + t += dt; + BK_touch(ctx, id, BK_TOUCH_MOVE, x0 + (x1 - x0) * i / steps, y0 + (y1 - y0) * i / steps, t, 0); + } + return t; +} + +/* -- widgets -------------------------------------------------------------------------------- */ + +static void test_tap_and_pointer(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *button = BK_node_new("button"); + BK_set_str(button, "text", "Go"); + BKNode *num = BK_node_new("number"); + BK_set_num(num, "max", 1000); + BK_set_num(num, "value", 10); + BK_node_add(col, button, -1); + BK_node_add(col, num, -1); + BKContext *ctx = context(col); + render(ctx); + int bx, by, nx, ny; + centre(button, &bx, &by); + centre(num, &nx, &ny); + + /* a tap on a button: one click, nothing hovered once the finger is gone */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, (float)bx, (float)by, 0, 0); + CHECK(count(BK_EV_CLICK) == 0); /* not before it lifts: it could still become a scroll */ + BK_touch(ctx, 1, BK_TOUCH_UP, (float)bx + 2, (float)by, 0, 0); + CHECK(count(BK_EV_CLICK) == 1); + CHECK(BK_hover(ctx) == NULL); + + /* a finger that moves past the slop is a scroll, not a click */ + g_nev = 0; + const double t = drag(ctx, 2, (float)bx, (float)by, (float)bx, (float)by + 40, 4, 1000.0, 10.0); + BK_touch(ctx, 2, BK_TOUCH_UP, (float)bx, (float)by + 40, t + 100.0, 0); /* rested: no fling */ + CHECK(count(BK_EV_CLICK) == 0); + CHECK(!BK_animating(ctx)); + + /* a number field drags at once (the pointer), with no warp at the window edge */ + g_nev = 0; + drag(ctx, 3, (float)nx, (float)ny, (float)W - 2, (float)ny, 8, 0, 0); + const double dragged = BK_get_num(num, "value"); + CHECK(dragged > 10.0); + BK_touch(ctx, 3, BK_TOUCH_UP, (float)W - 2, (float)ny, 0, 0); + CHECK(g_warps == 0); + CHECK(BK_get_num(num, "value") == dragged); + CHECK(BK_hover(ctx) == NULL); + CHECK(BK_focus(ctx) == NULL); /* a drag is no click: no text editing */ + + /* a second finger cancels the drag: the value goes back, as with Escape */ + BK_set_num(num, "value", 10); + drag(ctx, 4, (float)nx, (float)ny, (float)nx + 60, (float)ny, 4, 0, 0); + CHECK(BK_get_num(num, "value") > 10.0); + BK_touch(ctx, 5, BK_TOUCH_DOWN, (float)nx, (float)ny + 80, 0, 0); + CHECK(BK_get_num(num, "value") == 10.0); + BK_touch(ctx, 4, BK_TOUCH_UP, (float)nx + 60, (float)ny, 0, 0); + /* the finger left behind is no pointer: lifting it over the button clicks nothing */ + g_nev = 0; + BK_touch(ctx, 5, BK_TOUCH_MOVE, (float)bx, (float)by, 0, 0); + BK_touch(ctx, 5, BK_TOUCH_UP, (float)bx, (float)by, 0, 0); + CHECK(count(BK_EV_CLICK) == 0); + CHECK(BK_focus(ctx) == NULL); + + /* a cancelled contact keeps nothing, and its later events do nothing */ + drag(ctx, 6, (float)nx, (float)ny, (float)nx + 60, (float)ny, 4, 0, 0); + BK_touch(ctx, 6, BK_TOUCH_CANCEL, (float)nx + 60, (float)ny, 0, 0); + CHECK(BK_get_num(num, "value") == 10.0); + CHECK(BK_touch(ctx, 6, BK_TOUCH_MOVE, (float)nx + 90, (float)ny, 0, 0) == 0); + + /* BK_cancel (a lost capture, the window losing focus) cancels the finger's drag too */ + drag(ctx, 7, (float)nx, (float)ny, (float)nx + 60, (float)ny, 4, 0, 0); + CHECK(BK_cancel(ctx, 0) != 0); + CHECK(BK_get_num(num, "value") == 10.0); + CHECK(BK_touch(ctx, 7, BK_TOUCH_MOVE, (float)nx + 90, (float)ny, 0, 0) == 0); + BK_touch(ctx, 7, BK_TOUCH_UP, (float)nx + 90, (float)ny, 0, 0); + + /* a lost lift: the same id going down again ends what it did first */ + drag(ctx, 8, (float)nx, (float)ny, (float)nx + 60, (float)ny, 4, 0, 0); + BK_touch(ctx, 8, BK_TOUCH_DOWN, (float)bx, (float)by, 0, 0); + CHECK(BK_get_num(num, "value") == 10.0); + BK_touch(ctx, 8, BK_TOUCH_UP, (float)bx, (float)by, 0, 0); + + /* two taps in a row on the number field: a double click (its text editing) */ + BK_touch(ctx, 9, BK_TOUCH_DOWN, (float)nx, (float)ny, 0, 0); + BK_touch(ctx, 9, BK_TOUCH_UP, (float)nx, (float)ny, 0, 0); + CHECK(BK_focus(ctx) == num); /* a number field's click edits its text */ + BK_key(ctx, "", "Escape", 0); + + BK_context_free(ctx); + BK_node_free(col); +} + +/* -- scrolls on an "events" page (as the Rust and Python hosts draw theirs) ------------------- */ + +static void test_scroll_and_fling(void) +{ + BKNode *page = BK_node_new("canvas"); + BK_set_num(page, "events", 1); + BKNode *root = BK_node_new("frame"); + BK_node_add(root, page, -1); + BK_geom_set_manager(page, BK_GEOM_PLACE); + BK_geom_set(page, "relwidth", 1.0); + BK_geom_set(page, "relheight", 1.0); + BKContext *ctx = context(root); + render(ctx); + + /* the scroll starts past the slop and follows the finger exactly, at the point it began */ + double t = drag(ctx, 1, 100, 200, 100, 100, 10, 1000.0, 10.0); + float total = 0.0f; + int drags = 0, last_x = -1, last_y = -1; + for (int i = 0; i < g_nev; i++) { + if (g_ev[i].kind == BK_EV_WHEEL && text_int(&g_ev[i], 2) == BK_SCROLL_DRAG) { + total += (float)g_ev[i].b; + drags++; + CHECK((text_int(&g_ev[i], 0) & BK_FROM_TOUCH) != 0); + last_x = text_int(&g_ev[i], 3); + last_y = text_int(&g_ev[i], 4); + } + } + CHECK(drags > 0); + /* 100 px less the 8 px slop, the content up with the finger (negative: it goes up) */ + CHECK(fabsf(total + 92.0f) < 1.0f); + CHECK(last_x == 100 && last_y == 200); + CHECK(count(BK_EV_PRESS) == 0 && count(BK_EV_MOTION) == 0); /* a scroll is no pointer, no hover */ + + /* lifted while moving: the end, then a fling on Android's curve, stepped by renders */ + g_nev = 0; + BK_touch(ctx, 1, BK_TOUCH_UP, 100, 100, t, 0); + const Ev *end = last(BK_EV_WHEEL); + CHECK(end && text_int(end, 2) == BK_SCROLL_END && end->b == 0.0); + CHECK(BK_animating(ctx)); + float flung = 0.0f; + for (int i = 0; i < 400 && BK_animating(ctx); i++) { + sleep_ms(4); + const int before = g_nev; + render(ctx); + for (int k = before; k < g_nev; k++) { + if (g_ev[k].kind == BK_EV_WHEEL) { + CHECK(text_int(&g_ev[k], 2) == BK_SCROLL_FLING); + flung += (float)g_ev[k].b; + } + } + } + CHECK(!BK_animating(ctx)); + CHECK(flung < -50.0f); /* on up the way the finger went */ + + /* a finger that rested before lifting does not fling */ + g_nev = 0; + t = drag(ctx, 2, 100, 200, 100, 100, 10, 5000.0, 10.0); + BK_touch(ctx, 2, BK_TOUCH_UP, 100, 100, t + 200.0, 0); + CHECK(!BK_animating(ctx)); + + /* a finger that lands on a fling stops it, and is no tap */ + t = drag(ctx, 3, 100, 200, 100, 100, 10, 9000.0, 10.0); + BK_touch(ctx, 3, BK_TOUCH_UP, 100, 100, t, 0); + CHECK(BK_animating(ctx)); + g_nev = 0; + BK_touch(ctx, 4, BK_TOUCH_DOWN, 150, 150, 0, 0); + CHECK(!BK_animating(ctx)); + BK_touch(ctx, 4, BK_TOUCH_UP, 150, 150, 0, 0); + CHECK(count(BK_EV_PRESS) == 0); + + /* a tap: press and release with BK_FROM_TOUCH, then the pointer leaves */ + g_nev = 0; + BK_touch(ctx, 5, BK_TOUCH_DOWN, 150, 150, 0, 0); + BK_touch(ctx, 5, BK_TOUCH_UP, 150, 150, 0, 0); + const Ev *press = last(BK_EV_PRESS); + CHECK(press && (text_int(press, 0) & BK_FROM_TOUCH) && text_int(press, 1) == 1); + CHECK(count(BK_EV_RELEASE) == 1); + CHECK(last(BK_EV_LEAVE) != NULL); + CHECK(BK_hover(ctx) == NULL); + + /* held still: a right press (the context menu), and lifting clicks nothing */ + g_nev = 0; + BK_touch(ctx, 6, BK_TOUCH_DOWN, 150, 150, 0, 0); + BK_timer(ctx, TIMER_FRAME); /* too early: nothing */ + CHECK(count(BK_EV_PRESS) == 0); + sleep_ms(520); + BK_timer(ctx, TIMER_FRAME); + press = last(BK_EV_PRESS); + CHECK(press && text_int(press, 1) == 3); + BK_touch(ctx, 6, BK_TOUCH_UP, 150, 150, 0, 0); + CHECK(count(BK_EV_PRESS) == 1); + + /* -- two fingers: a pure pan scrolls and is no pinch or turn ---------------------------- */ + g_nev = 0; + BK_touch(ctx, 10, BK_TOUCH_DOWN, 100, 150, 0, 0); + BK_touch(ctx, 11, BK_TOUCH_DOWN, 200, 150, 0, 0); + for (int i = 1; i <= 5; i++) { /* the host reports the fingers one by one */ + BK_touch(ctx, 10, BK_TOUCH_MOVE, 100, 150.0f + 10 * i, 0, 0); + BK_touch(ctx, 11, BK_TOUCH_MOVE, 200, 150.0f + 10 * i, 0, 0); + } + total = 0.0f; + for (int i = 0; i < g_nev; i++) { + if (g_ev[i].kind == BK_EV_WHEEL && text_int(&g_ev[i], 2) == BK_SCROLL_DRAG) { + total += (float)g_ev[i].b; + } + } + CHECK(fabsf(total - 50.0f) < 0.5f); /* down with the fingers */ + CHECK(count(BK_EV_GESTURE) == 0); + CHECK(count(BK_EV_PRESS) == 0); + BK_touch(ctx, 10, BK_TOUCH_UP, 100, 200, 0, 0); + BK_touch(ctx, 11, BK_TOUCH_UP, 200, 200, 0, 0); + + /* a spread: magnify about the centre, the steps' product the whole spread */ + g_nev = 0; + BK_touch(ctx, 12, BK_TOUCH_DOWN, 150, 100, 0, 0); + BK_touch(ctx, 13, BK_TOUCH_DOWN, 250, 100, 0, 0); + for (int i = 1; i <= 5; i++) { + BK_touch(ctx, 12, BK_TOUCH_MOVE, 150.0f - 10 * i, 100, 0, 0); + BK_touch(ctx, 13, BK_TOUCH_MOVE, 250.0f + 10 * i, 100, 0, 0); + } + double scale = 1.0; + int gestures = 0; + for (int i = 0; i < g_nev; i++) { + if (g_ev[i].kind == BK_EV_GESTURE) { + CHECK(text_int(&g_ev[i], 1) == BK_GESTURE_MAGNIFY); + CHECK((text_int(&g_ev[i], 0) & BK_FROM_TOUCH) != 0); + CHECK(text_int(&g_ev[i], 2) == 200 && text_int(&g_ev[i], 3) == 100); + scale *= 1.0 + g_ev[i].a; + gestures++; + } + } + CHECK(gestures == 5); + CHECK(fabs(scale - 2.0) < 1e-3); /* 100 px apart to 200 */ + BK_touch(ctx, 12, BK_TOUCH_UP, 100, 100, 0, 0); + BK_touch(ctx, 13, BK_TOUCH_UP, 300, 100, 0, 0); + + /* a quarter turn counter-clockwise (on screen) is +90 degrees */ + g_nev = 0; + BK_touch(ctx, 14, BK_TOUCH_DOWN, 150, 150, 0, 0); + BK_touch(ctx, 15, BK_TOUCH_DOWN, 250, 150, 0, 0); + double degrees = 0.0; + for (int i = 1; i <= 9; i++) { + const double a = -(M_PI / 2) * i / 9; /* y points down: counter-clockwise is negative */ + BK_touch(ctx, 14, BK_TOUCH_MOVE, (float)(200 - 50 * cos(a)), (float)(150 - 50 * sin(a)), 0, 0); + BK_touch(ctx, 15, BK_TOUCH_MOVE, (float)(200 + 50 * cos(a)), (float)(150 + 50 * sin(a)), 0, 0); + } + for (int i = 0; i < g_nev; i++) { + if (g_ev[i].kind == BK_EV_GESTURE && text_int(&g_ev[i], 1) == BK_GESTURE_ROTATE) { + degrees += g_ev[i].a; + } + } + CHECK(fabs(degrees - 90.0) < 0.5); + /* a third finger is followed and ignored */ + CHECK(BK_touch(ctx, 16, BK_TOUCH_DOWN, 50, 50, 0, 0) == 0); + BK_touch(ctx, 16, BK_TOUCH_UP, 50, 50, 0, 0); + BK_touch(ctx, 14, BK_TOUCH_UP, 0, 0, 0, 0); + g_nev = 0; + BK_touch(ctx, 15, BK_TOUCH_UP, 250, 150, 0, 0); /* the finger left of a gesture clicks nothing */ + CHECK(count(BK_EV_PRESS) == 0); + + /* trackpads: BK_magnify / BK_rotate, without BK_FROM_TOUCH */ + g_nev = 0; + BK_magnify(ctx, 120, 130, 0.25f, BK_CTRL | BK_FROM_TOUCH); + BK_rotate(ctx, 120, 130, -15.0f, 0); + const Ev *g = &g_ev[0]; + CHECK(g_nev == 2 && g->kind == BK_EV_GESTURE && text_int(g, 0) == BK_CTRL); + CHECK(text_int(g, 1) == BK_GESTURE_MAGNIFY && fabs(g->a - 0.25) < 1e-6); + CHECK(text_int(g, 2) == 120 && text_int(g, 3) == 130); + CHECK(text_int(&g_ev[1], 1) == BK_GESTURE_ROTATE && g_ev[1].a == -15.0); + + BK_context_free(ctx); + BK_node_free(root); +} + +/* -- the node editor: two fingers pan and zoom (MOUSEPAN, MOUSEZOOM), and cancel a press ---- */ + +static void test_node_editor(void) +{ + BKNode *ed = BK_node_new("nodeeditor"); + for (int i = 0; i < 2; i++) { + BKNode *n = BK_node_new("graphnode"); + BK_set_str(n, "label", i ? "Math" : "Value"); + BK_set_num(n, "nx", i * 220.0); + const char *sockets[] = {"o|Value|float", "i|A|float|0.5"}; + BK_set_strs(n, "items", sockets, i ? 2 : 1); + BK_set_num(n, "selected", 1); + BK_node_add(ed, n, -1); + } + BKContext *ctx = context(ed); + render(ctx); + const double zoom = BK_get_num(ed, "zoom"), pany = BK_get_num(ed, "pany"); + + /* a finger on empty space presses at once (a box select), and a second finger cancels it: + * the unmoved press deselects nothing (its release would have) */ + BK_touch(ctx, 1, BK_TOUCH_DOWN, 380, 280, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, 300, 280, 0, 0); + CHECK(BK_get_num(BK_node_child(ed, 0), "selected") == 1.0); + CHECK(BK_get_num(BK_node_child(ed, 1), "selected") == 1.0); + /* moving together pans the view with the fingers */ + for (int i = 1; i <= 4; i++) { + BK_touch(ctx, 1, BK_TOUCH_MOVE, 380, 280.0f - 5 * i, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 300, 280.0f - 5 * i, 0, 0); + } + CHECK(fabs(BK_get_num(ed, "pany") - (pany - 20.0)) < 0.5); + CHECK(BK_get_num(ed, "zoom") == zoom); + /* spreading zooms about their centre */ + BK_touch(ctx, 1, BK_TOUCH_MOVE, 400, 260, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, 280, 260, 0, 0); + CHECK(fabs(BK_get_num(ed, "zoom") - zoom * 1.5) < 1e-3); + BK_touch(ctx, 1, BK_TOUCH_UP, 400, 260, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, 280, 260, 0, 0); + CHECK(BK_get_num(BK_node_child(ed, 0), "selected") == 1.0); + + /* a trackpad pinch zooms too */ + const double z = BK_get_num(ed, "zoom"); + BK_magnify(ctx, 200, 150, -0.2f, 0); + CHECK(fabs(BK_get_num(ed, "zoom") - z * 0.8) < 1e-3); + + BK_context_free(ctx); + BK_node_free(ed); +} + +/* -- custom nodes: raw contacts, the default gestures, the pointer mode ---------------------- */ + +typedef struct Log { + int type[256], id[256], phase[256], mods[256]; + float x[256], magnify[256], rotate[256], wheel_y[256]; + int n; +} Log; + +static int custom_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + (void)node; + Log *l = (Log *)data; + if (l->n < 256) { + l->type[l->n] = e->type; + l->id[l->n] = e->touch_id; + l->phase[l->n] = e->touch_phase; + l->mods[l->n] = e->mods; + l->x[l->n] = e->x; + l->magnify[l->n] = e->magnify; + l->rotate[l->n] = e->rotate; + l->wheel_y[l->n] = e->wheel_y; + l->n++; + } + return 1; +} + +static int find_type(const Log *l, int type) +{ + for (int i = 0; i < l->n; i++) { + if (l->type[i] == type) { + return i; + } + } + return -1; +} + +static void test_custom(void) +{ + static Log log; + BKNode *col = BK_node_new("column"); + BKNode *node = BK_node_new("custom"); + BKCustomClass cls; + memset(&cls, 0, sizeof(cls)); + cls.event = custom_event; + cls.natural_w = 300; + cls.natural_h = 200; + BK_custom_set(node, &cls, &log); + BK_node_add(col, node, -1); + BKContext *ctx = context(col); + render(ctx); + int r[4]; + BK_node_rect(node, r); + const float cx = (float)(r[0] + 100), cy = (float)(r[1] + 100); + + /* raw: every contact as it is, two fingers no gesture */ + BK_custom_set_touch(node, BK_TOUCH_MODE_RAW); + memset(&log, 0, sizeof(log)); + BK_touch(ctx, 7, BK_TOUCH_DOWN, cx, cy, 0, 0); + BK_touch(ctx, 8, BK_TOUCH_DOWN, cx + 50, cy, 0, 0); + BK_touch(ctx, 8, BK_TOUCH_MOVE, cx + 80, cy, 0, 0); + BK_touch(ctx, 7, BK_TOUCH_UP, cx, cy, 0, 0); + BK_touch(ctx, 8, BK_TOUCH_CANCEL, cx + 80, cy, 0, 0); + int touches = 0; + for (int i = 0; i < log.n; i++) { + if (log.type[i] == BK_CUSTOM_TOUCH) { + touches++; + CHECK(log.mods[i] & BK_FROM_TOUCH); + } + } + CHECK(touches == 5); + CHECK(find_type(&log, BK_CUSTOM_FOCUS) >= 0); /* the first contact takes the focus, as a click */ + int k = find_type(&log, BK_CUSTOM_TOUCH); + CHECK(k >= 0 && log.id[k] == 7 && log.phase[k] == BK_TOUCH_DOWN && fabsf(log.x[k] - 100.0f) < 1.0f); + CHECK(log.phase[log.n - 1] == BK_TOUCH_CANCEL && log.id[log.n - 1] == 8); + CHECK(find_type(&log, BK_CUSTOM_PRESS) < 0 && find_type(&log, BK_CUSTOM_MAGNIFY) < 0); + + /* a raw node freed while a finger is on it: the rest of the contact goes nowhere */ + BK_touch(ctx, 9, BK_TOUCH_DOWN, cx, cy, 0, 0); + BK_node_remove(col, node); + memset(&log, 0, sizeof(log)); + BK_touch(ctx, 9, BK_TOUCH_MOVE, cx + 10, cy, 0, 0); + BK_touch(ctx, 9, BK_TOUCH_UP, cx + 10, cy, 0, 0); + CHECK(log.n == 0); + BK_node_add(col, node, -1); + render(ctx); + + /* the default: a drag scrolls it (wheel notches), two fingers pinch it */ + BK_custom_set_touch(node, BK_TOUCH_MODE_SCROLL); + memset(&log, 0, sizeof(log)); + drag(ctx, 1, cx, cy, cx, cy + 60, 6, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_DOWN, cx + 60, cy + 60, 0, 0); + BK_touch(ctx, 1, BK_TOUCH_MOVE, cx - 30, cy + 60, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_MOVE, cx + 90, cy + 60, 0, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, cx - 30, cy + 60, 0, 0); + BK_touch(ctx, 2, BK_TOUCH_UP, cx + 90, cy + 60, 0, 0); + k = find_type(&log, BK_CUSTOM_WHEEL); + CHECK(k >= 0 && log.wheel_y[k] > 0.0f && (log.mods[k] & BK_FROM_TOUCH)); + k = find_type(&log, BK_CUSTOM_MAGNIFY); + CHECK(k >= 0 && fabsf(log.magnify[k] - 1.0f) < 1e-3f); /* 60 px apart to 120 */ + CHECK(find_type(&log, BK_CUSTOM_PRESS) < 0); + /* a trackpad turn */ + memset(&log, 0, sizeof(log)); + BK_rotate(ctx, (int)cx, (int)cy, 30.0f, 0); + CHECK(log.n == 1 && log.type[0] == BK_CUSTOM_ROTATE && log.rotate[0] == 30.0f); + + /* the scrollbar strip at its right edge is a press, as is any place in the pointer mode */ + memset(&log, 0, sizeof(log)); + BK_touch(ctx, 3, BK_TOUCH_DOWN, (float)(r[0] + r[2] - 4), cy, 0, 0); + CHECK(find_type(&log, BK_CUSTOM_PRESS) >= 0); + BK_touch(ctx, 3, BK_TOUCH_UP, (float)(r[0] + r[2] - 4), cy, 0, 0); + BK_custom_set_touch(node, BK_TOUCH_MODE_POINTER); + memset(&log, 0, sizeof(log)); + BK_touch(ctx, 4, BK_TOUCH_DOWN, cx, cy, 0, 0); + k = find_type(&log, BK_CUSTOM_PRESS); + CHECK(k >= 0 && (log.mods[k] & BK_FROM_TOUCH)); + BK_touch(ctx, 4, BK_TOUCH_MOVE, cx + 40, cy, 0, 0); + CHECK(log.type[log.n - 1] == BK_CUSTOM_MOTION); + BK_touch(ctx, 4, BK_TOUCH_UP, cx + 40, cy, 0, 0); + CHECK(find_type(&log, BK_CUSTOM_RELEASE) >= 0); + + BK_context_free(ctx); + BK_node_free(col); +} + +/* -- menus: a tap opens one, and the finger leaving does not close it ------------------------ */ + +static void test_menu(void) +{ + BKNode *col = BK_node_new("column"); + BKNode *menu = BK_node_new("menubutton"); + BK_set_str(menu, "text", "File"); + BKMenuSpec items[3]; + memset(items, 0, sizeof(items)); + const char *names[] = {"New", "Open", "Save"}; + for (int i = 0; i < 3; i++) { + items[i].text = names[i]; + items[i].checked = -1; + items[i].enabled = 1; + } + BK_menubutton_set_items(menu, items, 3); + BK_node_add(col, menu, -1); + BKContext *ctx = context(col); + render(ctx); + int x, y; + centre(menu, &x, &y); + BK_touch(ctx, 1, BK_TOUCH_DOWN, (float)x, (float)y, 0, 0); + BK_touch(ctx, 1, BK_TOUCH_UP, (float)x, (float)y, 0, 0); + render(ctx); + CHECK(BK_popup_count(ctx) == 1); + BK_context_free(ctx); + BK_node_free(col); +} + +int main(void) +{ + g_raster = BUI_raster_create(W, H); + test_tap_and_pointer(); + test_scroll_and_fling(); + test_node_editor(); + test_custom(); + test_menu(); + BUI_raster_free(g_raster); + printf(g_fail ? "touch: FAILED\n" : "touch: 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 de3bd60d..c49f2da9 100644 --- a/website/src/content/docs/c/c-api.mdx +++ b/website/src/content/docs/c/c-api.mdx @@ -5,7 +5,7 @@ description: Use BUI's runtime directly from C. Nodes, properties, layout, the c section: C & C++ order: 10 languages: ["c", "cpp"] -sources: ["docs/c-api.md", "kit/include/BUI_kit.h", "gpu/include/GPU_raster.h", "examples/kit_hello.c", "examples/CMakeLists.txt", "kit/intern/kit_core.c", "CMakeLists.txt"] +sources: ["docs/c-api.md", "kit/include/BUI_kit.h", "gpu/include/GPU_raster.h", "examples/kit_hello.c", "examples/CMakeLists.txt", "kit/intern/kit_core.c", "kit/intern/kit_touch.c", "CMakeLists.txt"] --- **The kit is BUI's runtime, written in C, and `BUI_kit.h` is its whole public API.** Use it directly and you get Blender's widgets, layout, input handling and damage rendering with nothing in between: no interpreter, no garbage collector, one static library. @@ -186,7 +186,9 @@ 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_cancel` (the host lost the pointer mid-press: a drag is cancelled as Escape cancels it and the press ends with no click), `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_cancel` (the host lost the pointer mid-press: the pressed widget's interaction is cancelled as Escape cancels it, moved or not, the press ends with no click, and every finger on the screen is cancelled too), `BK_wheel`, `BK_scroll` (precise deltas), `BK_scroll_px` (exact pixels), `BK_key`, `BK_key_release`, `BK_button` and `BK_context_menu`. Each returns non-zero when something changed. + +**Touch screens and trackpads** go in through `BK_touch(ctx, id, BK_TOUCH_DOWN | MOVE | UP | CANCEL, x, y, time_ms, mods)`, one call per finger, and `BK_magnify` / `BK_rotate` for a trackpad's pinch and turn. The kit makes taps, scrolls, flings, long presses and two-finger gestures of them, the same on every platform, and marks what it makes with `BK_FROM_TOUCH` in the mods. The window hosts do this for you; [Touch and gestures](../../concepts/touch/) has the model and a host example. **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. @@ -204,7 +206,7 @@ Your `emit` callback gets `(data, node, kind, ref, a, b)`. The `kind`s you'll us | `BK_EV_SUBMIT` | A text field was confirmed with Enter | | `BK_EV_RENAME`, `BK_EV_ACTIVATE`, `BK_EV_TOGGLE`, `BK_EV_BROWSE` | List and tree renames, double-clicks, toggle columns, path-field browse buttons | -Set a node's `"events"` property to also get raw input: `PRESS`, `RELEASE`, `DOUBLE`, `MOTION`, `ENTER`, `LEAVE`, `KEY`, `KEYRELEASE`, `WHEEL` and `CONFIGURE`. Scroll views add `VIEW` (with `"viewevents"`) and `SCROLL`. +Set a node's `"events"` property to also get raw input: `PRESS`, `RELEASE`, `DOUBLE`, `MOTION`, `ENTER`, `LEAVE`, `KEY`, `KEYRELEASE`, `WHEEL`, `CONFIGURE` and `GESTURE` (a pinch or a turn: `ref` is `"mods kind x y"`, `a` the amount). Scroll views add `VIEW` (with `"viewevents"`) and `SCROLL`. Keyboard shortcuts are one line: `BK_bind(ctx, "ctrl+s", ref)` sends `BK_EV_CALL` with your `ref`. @@ -247,6 +249,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. +- **`BK_custom_set_touch(node, mode)`** decides what a finger does on the node: `BK_TOUCH_MODE_SCROLL` (the default: a tap clicks, a drag scrolls), `BK_TOUCH_MODE_POINTER` (the finger is the pointer, for your own drags) or `BK_TOUCH_MODE_RAW` (every contact arrives as `BK_CUSTOM_TOUCH` with `touch_id` and `touch_phase`). Pinches and turns arrive as `BK_CUSTOM_MAGNIFY` and `BK_CUSTOM_ROTATE` (`e->magnify`, `e->rotate`). ## Everything else diff --git a/website/src/content/docs/concepts/android.mdx b/website/src/content/docs/concepts/android.mdx index ec89fa70..f784a282 100644 --- a/website/src/content/docs/concepts/android.mdx +++ b/website/src/content/docs/concepts/android.mdx @@ -3,7 +3,7 @@ title: Android description: Run BUI on a phone from C, Lua or Rust with the same code as on a desktop. One NativeActivity, no Java and no Gradle, damage-driven software rendering, touch that scrolls, the soft keyboard, and an APK of about 1 to 2 MB. section: Concepts order: 69 -sources: ["kit/intern/kit_window_android.c", "platform/android/bui_android.c", "platform/android/bui_app.h", "platform/android/fonts.c", "platform/android/demo.c", "platform/android/lua_app.c", "platform/android/rust/src/lib.rs", "platform/android/js/src/lib.rs", "platform/android/imgui_app.cpp", "bindings/rust/blenderui-qjs/src/lib.rs", "platform/android/CMakeLists.txt", "platform/android/AndroidManifest.xml", "platform/android/build.py", "examples/android/main.lua", "docs/android.md"] +sources: ["kit/intern/kit_window_android.c", "kit/intern/kit_touch.c", "bindings/imgui/imgui_impl_bui.cpp", "platform/android/bui_android.c", "platform/android/bui_app.h", "platform/android/fonts.c", "platform/android/demo.c", "platform/android/lua_app.c", "platform/android/rust/src/lib.rs", "platform/android/js/src/lib.rs", "platform/android/imgui_app.cpp", "bindings/rust/blenderui-qjs/src/lib.rs", "platform/android/CMakeLists.txt", "platform/android/AndroidManifest.xml", "platform/android/build.py", "examples/android/main.lua", "docs/android.md"] --- On Android the kit's window is the activity's surface (`kit/intern/kit_window_android.c`, which implements `BK_window_*` like the Windows and Linux hosts do). An app opens a window and runs it exactly as on a desktop, so Rust, Lua and C apps are the code they would be anywhere else. Nothing changes for other platforms: the Android code is in `platform/android`, the kit's Android-only branches and `if(ANDROID)` blocks. @@ -92,12 +92,11 @@ static void frame(void *) { ImGui::ShowDemoWindow(); } void bui_app_main(void) { ImGui::CreateContext(); ImGui_ImplBUI_App *app = ImGui_ImplBUI_CreateApp("App", 360, 720, frame, nullptr); - BK_window_wm(ImGui_ImplBUI_AppWindow(app), "touch_drag", 1, 0); // a drag is ImGui's ImGui_ImplBUI_RunApp(app); } ``` -`build.py --imgui app.cpp` (no file: the demo in `platform/android/imgui_app.cpp`). About 1.8 MB. +`build.py --imgui app.cpp` (no file: the demo in `platform/android/imgui_app.cpp`). A finger's drag is ImGui's (sliders, window moves): the adapter puts its node in `BK_TOUCH_MODE_POINTER`. About 1.8 MB. @@ -132,7 +131,7 @@ Python, Qt, tkinter and D need their runtime on the device and are not available - **Damage driven.** The thread sleeps until a touch, key, timer or frame request, and only the damaged rectangles are converted and locked. An idle app uses no CPU. - **Scale.** A CSS pixel is a dp, as in Chrome on Android. -- **Touch.** One finger is the pointer and a tap is a click. A drag that starts on a widget that drags (sliders, text, scrollbars) drags it; anywhere else it scrolls, following the finger exactly and carrying on after it lifts with the deceleration of iOS's scroll views. A touch at the right edge of a custom node drags the app's scrollbar, so a list of millions of rows can be dragged to any place. Two fingers always scroll. +- **Touch.** The host hands every finger to the kit's touch model, the same one every window host uses ([Touch and gestures](../touch/)). A tap is a click. A drag that starts on a widget that drags (sliders, text, scrollbars) drags it; anywhere else it scrolls, following the finger exactly and flinging on after it lifts along Android's own `OverScroller` curve. A long press opens the context menu, and two fingers pan, pinch and turn. A touch at the right edge of a custom node drags the app's scrollbar, so a list of millions of rows can be dragged to any place. A custom node that wants the finger's drag for itself (a paint app) calls `BK_custom_set_touch(node, BK_TOUCH_MODE_POINTER)`; the old `"touch_drag"` window key is gone. - **Back.** The Back key arrives as `Escape`. A key listener that closes something on it calls `app.prevent_default()`; only a Back that nothing took closes the app, so an app walks back through its own screens. - **Keyboard.** It opens while a text field is edited (through the input method manager, since the activity's view is not a text editor); keys arrive as key events. Predictive keyboards and IME composition are not wired up yet. - **Lifecycle.** One activity: launching the app while it runs brings it back, and after Back finishes it the next launch runs `bui_app_main` again from a fresh start, even in the same process. A Lua script that fails shows its error on screen, also after it opened its window. @@ -141,5 +140,5 @@ Python, Qt, tkinter and D need their runtime on the device and are not available - **Size.** About 1.1 MB per ABI for the C demo, 1.4 MB with Lua and 2.0 MB with Rust (arm64-v8a). -The C, Lua, Rust and JavaScript (React, Vue, Svelte) apps run on an x86_64 emulator (API 33). The arm64 builds compile and link but were not run on a device. There is no GPU renderer, long-press, pinch or IME composition yet. +The C, Lua, Rust and JavaScript (React, Vue, Svelte) apps run on an x86_64 emulator (API 33). The arm64 builds compile and link but were not run on a device. There is no GPU renderer or IME composition yet. diff --git a/website/src/content/docs/concepts/touch.mdx b/website/src/content/docs/concepts/touch.mdx new file mode 100644 index 00000000..27eca012 --- /dev/null +++ b/website/src/content/docs/concepts/touch.mdx @@ -0,0 +1,140 @@ +--- +title: Touch and gestures +description: Taps, scrolls that fling, long presses, and two-finger pans, pinches and turns on every touch screen and trackpad, from one model in the kit, with the APIs to use the gestures yourself. +section: Concepts +order: 52 +languages: ["c", "rust"] +sources: ["kit/include/BUI_kit.h", "kit/intern/kit_touch.c", "kit/intern/kit_fling.c", "kit/intern/kit_core.c", "kit/intern/kit_nodes.c", "kit/intern/kit_custom.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", "kit/intern/kit_window_android.c", "kit/CMakeLists.txt", "bindings/imgui/imgui_impl_bui.cpp", "bindings/rust/blenderui/src/events.rs", "bindings/rust/blenderui/src/element.rs", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/tests/suite/touch.rs", "tests/touch_test.c", "docs/touch.md"] +--- + +Put a finger on a BUI window and it works the way a phone does. A tap clicks, a drag scrolls and flings on, a long press opens the context menu, and two fingers pan, pinch and turn. A trackpad's pinch and turn reach the same places. You get this on every platform without writing any code, and you can listen for the gestures when you want them. + +The model lives in the **kit**, BUI's runtime written in C (`kit/intern/kit_touch.c`). A window host only forwards the contacts it gets, so a finger behaves the same on Windows, Linux and Android. The numbers and curves are Android's (`ViewConfiguration`, `VelocityTracker`, `OverScroller`). The gestures land where Blender's trackpad events do: GHOST's Scroll, Magnify and Rotate events become `MOUSEPAN`, `MOUSEZOOM` and `MOUSEROTATE`. + +## What a finger does + +| You do | You get | +| --- | --- | +| Put a finger on a slider, number field, text field, scrollbar or the node editor | The finger is the pointer at once: it drags the widget | +| Tap anywhere else | A click. Two taps are a double click | +| Hold still for half a second | The context menu (a right press) | +| Drag more than 8 dp | The content under the finger scrolls exactly as far as the finger went, without jumping by those 8 dp | +| Lift while moving | The content flings on, slowing down along Android's curve | +| Touch a fling | It stops, and nothing is clicked | +| Add a second finger | What the first one did is cancelled (a dragged value goes back). The two fingers are now a gesture | +| Move two fingers together | The content pans | +| Spread or turn two fingers | A pinch or a turn about their centre | + +A few details make it feel right: + +- **No wobble.** Systems report fingers one at a time, so BUI waits until both moved before it updates a gesture. A pure pan never jitters the zoom or the angle. +- **No hover left behind.** The pointer leaves when the finger lifts. +- **Nothing stuck.** When the window loses the focus, or the system takes a contact back (an edge swipe), every finger is cancelled and nothing it started is kept. +- **Wider double taps.** Two taps count as a double click within one widget unit, not the mouse's 4 px. +- **No pointer jumps.** A finger's drag never warps the system pointer. +- **Menus and tools first.** While a menu is open or a tool runs (the eyedropper), every finger is the pointer. + +In the node editor, two fingers pan the view and a pinch zooms about the fingers. A link drag that gets cancelled puts back the link it took off an input, as Blender's `node_link_cancel` does. + +## Use the gestures yourself + + + + +```rust +div() + .w(px(300.0)) + .h(px(200.0)) + .on_pan(|e: &PanEvent, _, cx| { + // e.delta: how far the content follows the fingers (x right, y down) + // e.phase: ScrollPhase::Drag, then Fling, then End + cx.stop_propagation(); // take the drag: nothing scrolls + }) + .on_pinch(|e: &PinchEvent, _, _| println!("zoom x{}", 1.0 + e.delta)) + .on_rotate(|e: &RotateEvent, _, _| println!("turn {} deg", e.degrees)) +``` + +In `rsx!` the attributes are `onPan`, `onPinch` and `onRotate`. `e.touch` is `false` when a trackpad made the pinch or turn. See [Rust events](../../rust/events/#touch-screens-and-trackpads). + + + + +```c +static int paint_event(void *data, BKNode *node, const BKCustomEvent *e) +{ + Paint *p = data; + switch (e->type) { + case BK_CUSTOM_TOUCH: /* every finger, as it is */ + if (e->touch_phase == BK_TOUCH_DOWN) stroke_begin(p, e->touch_id, e->x, e->y); + else if (e->touch_phase == BK_TOUCH_MOVE) stroke_add(p, e->touch_id, e->x, e->y); + else stroke_end(p, e->touch_id, e->touch_phase == BK_TOUCH_CANCEL); + break; + case BK_CUSTOM_MAGNIFY: /* a trackpad pinch */ + p->zoom *= 1.0f + e->magnify; + break; + default: + return 0; + } + BK_node_invalidate(node); + return 1; +} + +BK_custom_set(node, &cls, paint); /* cls.event = paint_event */ +BK_custom_set_touch(node, BK_TOUCH_MODE_RAW); +``` + +A custom node picks what a finger does on it with `BK_custom_set_touch`: `BK_TOUCH_MODE_SCROLL` (the default: tap and scroll, two fingers pan, pinch and turn), `BK_TOUCH_MODE_POINTER` (the finger is your pointer, as Dear ImGui's node uses) or `BK_TOUCH_MODE_RAW` (every contact as `BK_CUSTOM_TOUCH`). An `"events"` node gets `BK_EV_GESTURE` for a pinch or a turn. + + + + +The other language bindings expose the same calls. + +### Which way is positive + +| Value | Meaning | +| --- | --- | +| A pinch's delta | The scale change since the last one: 0.1 is 10% larger, -0.1 smaller. Multiply a zoom by `1 + delta` | +| A turn's degrees | Since the last one, positive counter-clockwise (as macOS's `NSEvent.rotation`) | +| A pan | The content follows the fingers: a finger moving up moves the content up | + +## Platforms + +| Platform | Touch screen | Trackpad pinch and turn | +| --- | --- | --- | +| Windows | `WM_POINTER` touch contacts. Pen and mouse stay mouse input, and Windows adds no clicks or press-and-hold right clicks of its own | Not sent | +| Linux, X11 | XInput 2.2 touch, through libXi loaded at run time. Without it, the first finger is the server's emulated mouse | XInput 2.4 pinches (libXi 1.8) | +| Linux, Wayland | `wl_touch` | `zwp_pointer_gestures_v1` pinches | +| macOS | None | `magnifyWithEvent:` and `rotateWithEvent:` | +| Android | Every pointer of a motion event | None | + +## Your own host + +If you draw BUI into your own window, send each contact with `BK_touch` and a trackpad's gestures with `BK_magnify` and `BK_rotate`. Don't also send the mouse events a platform makes from a finger. + +```c +int phase = down ? BK_TOUCH_DOWN : up ? BK_TOUCH_UP : cancelled ? BK_TOUCH_CANCEL : BK_TOUCH_MOVE; +if (BK_touch(ctx, contact_id, phase, x, y, event_time_ms, mods)) + request_redraw(); + +BK_magnify(ctx, px, py, scale_change, mods); /* a trackpad pinch about the pointer */ +BK_rotate(ctx, px, py, degrees_ccw, mods); /* a trackpad turn */ + +while (BK_animating(ctx)) /* a fling steps with each render */ + draw_frame(); +``` + +`x` and `y` are window pixels, as for `BK_motion`. `event_time_ms` is the event's own time on any steady clock (0 means now); the fling's speed comes from it. + +## Test it without a screen + +- **C:** call `BK_touch` with ids and phases. `tests/touch_test.c` covers taps, scrolls and flings, two-finger gestures, raw contacts, cancels, the node editor and menus. +- **Rust:** `cx.simulate_touch(win.id, id, TouchPhase::Down, x, y)` (then `Move`, `Up` or `Cancel`), and `cx.simulate_magnify` / `cx.simulate_rotate` for a trackpad. See `bindings/rust/blenderui/tests/suite/touch.rs`. + +## Next steps + + + Run BUI on a phone, where touch is the only input. + The native windows that forward the fingers. + Every listener, including on_pan, on_pinch and on_rotate. + diff --git a/website/src/content/docs/javascript/native-api.mdx b/website/src/content/docs/javascript/native-api.mdx index 7678abc5..378d9c27 100644 --- a/website/src/content/docs/javascript/native-api.mdx +++ b/website/src/content/docs/javascript/native-api.mdx @@ -109,7 +109,11 @@ button.addEventListener('click', (event) => { }) ``` -The events are `click`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input` and `change`. The event object carries `target`, `currentTarget`, `clientX`/`clientY`, `button`, `deltaY`, `key`, the modifier flags (`shiftKey`, `ctrlKey`, `altKey`, `metaKey`) and `timeStamp`. +The events are `click`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`, `mouseleave`, `wheel`, `keydown`, `keyup`, `input` and `change`, and the touch screen and trackpad gestures `pinch`, `rotate` and `pan`. The event object carries `target`, `currentTarget`, `clientX`/`clientY`, `button`, `deltaX`/`deltaY`, `delta`, `phase`, `key`, the modifier flags (`shiftKey`, `ctrlKey`, `altKey`, `metaKey`) and `timeStamp`. + +- **`pinch`**: `delta` is the scale change since the last one (0.1 is 10% larger: multiply a zoom by `1 + delta`), about `clientX`/`clientY`. +- **`rotate`**: `delta` is the degrees turned since the last one, positive counter-clockwise. +- **`pan`**: `deltaX`/`deltaY` are the pixels the content follows the fingers (x right, y down); `phase` is `'drag'` while a finger is down, `'fling'` as the content coasts on, and `'end'` when it lifted. An element listening for `pan` takes the drag, like CSS's `touch-action: none`: nothing under it scrolls by touch. - **They bubble**, except `mouseenter` and `mouseleave`, as in the DOM. `stopPropagation()` and `stopImmediatePropagation()` work. - **`event.target`** is the deepest element listening for that event type. @@ -164,7 +168,7 @@ win.setProgressBar(0.5) ## Testing without a window -`new App({ headless: true })` renders off-screen. Combine it with `win.click(x, y)` and `win.screenshot()` to test a UI in CI: +`new App({ headless: true })` renders off-screen. Combine it with `win.click(x, y)` and `win.screenshot()` to test a UI in CI (`win.mouseMove`, `win.mouseDown` and `win.mouseUp` drive the pointer, `win.touch(id, phase, x, y)` a touch screen's fingers, and `win.pinch(x, y, delta)` and `win.rotate(x, y, degrees)` a trackpad's gestures): ```js title="test.js" const { App } = require('@blender-ui/native') diff --git a/website/src/content/docs/javascript/react.mdx b/website/src/content/docs/javascript/react.mdx index 15064559..90468f61 100644 --- a/website/src/content/docs/javascript/react.mdx +++ b/website/src/content/docs/javascript/react.mdx @@ -116,7 +116,7 @@ To render into a window you opened yourself, use `createRoot(window)`, then `roo Host components are HTML elements, as in React DOM: - **`className`** takes Tailwind classes. **`style`** takes a string, an object or a signal. **`htmlFor`** and boolean attributes work. -- **Mouse, keyboard and form events** work: `onClick`, `onMouseDown`, `onMouseUp`, `onMouseMove`, `onMouseEnter`, `onMouseLeave`, `onWheel`, `onKeyDown`, `onKeyUp`, `onInput` and `onChange`. They bubble, and `stopPropagation` works. +- **Mouse, keyboard and form events** work: `onClick`, `onMouseDown`, `onMouseUp`, `onMouseMove`, `onMouseEnter`, `onMouseLeave`, `onWheel`, `onKeyDown`, `onKeyUp`, `onInput` and `onChange`, and the touch screen and trackpad gestures `onPinch`, `onRotate` and `onPan` (the event fields are on the [native API](/docs/javascript/native-api) page). They bubble, and `stopPropagation` works. - **`onChange` follows React DOM:** on a text field it fires on every edit. On checkboxes, radios, selects and other controls it fires when the value changes, even if the control's `type` changes later. - **Handlers run as discrete updates,** so a click's state change commits immediately. diff --git a/website/src/content/docs/rust/events.mdx b/website/src/content/docs/rust/events.mdx index a9ce2ffa..f27d590e 100644 --- a/website/src/content/docs/rust/events.mdx +++ b/website/src/content/docs/rust/events.mdx @@ -1,10 +1,10 @@ --- title: Events -description: Respond to clicks, keys, the wheel and form changes, update your view with cx.listener, and paint your own content on a canvas. +description: Respond to clicks, keys, the wheel, touch gestures and form changes, update your view with cx.listener, and paint your own content on a canvas. section: Rust order: 70 languages: ["rust"] -sources: ["docs/rust.md", "bindings/rust/blenderui/src/events.rs", "bindings/rust/blenderui/src/element.rs", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/src/paint.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui/tests/suite/headless.rs", "bindings/rust/blenderui/examples/showcase.rs"] +sources: ["docs/rust.md", "bindings/rust/blenderui/src/events.rs", "bindings/rust/blenderui/src/element.rs", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/src/paint.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui/tests/suite/headless.rs", "bindings/rust/blenderui/tests/suite/touch.rs", "bindings/rust/blenderui/examples/showcase.rs"] --- A UI that doesn't answer back is just a picture. **Events are how your code hears the user**: a click, a key, a dragged slider. Attach a listener to any element, change your state, and BUI redraws what changed. @@ -49,6 +49,9 @@ If you use [hooks](../hooks/) instead, you don't need either: writing a signal r | `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, pixels, phase, modifiers }` | Yes | +| `on_pan` | `PanEvent { position, delta, phase, modifiers }`: fingers dragging the content, before it scrolls | Yes | +| `on_pinch` | `PinchEvent { position, delta, modifiers, touch }`: two fingers or a trackpad pinch | Yes | +| `on_rotate` | `RotateEvent { position, degrees, modifiers, touch }`: two fingers or a trackpad turn | Yes | | `on_key_down`, `on_key_up` | `KeyDownEvent` / `KeyUpEvent { keystroke }` | Yes, from the focused element | | `on_change`, `on_input` | `ChangeEvent { value, checked, number }` | Yes | @@ -59,7 +62,7 @@ The details: - **`Modifiers`** has `shift`, `control` and `alt`. - **`ClickEvent::click_count()`** tells a double-click from a single one. - **`ScrollWheelEvent::phase`** is how the scroll came: `Wheel` (a notch or touchpad), `Drag` (a finger moves the content), `Fling` (it coasts on) or `End` (the finger lifted, `delta` 0). A list uses it to stretch past an end while the finger is down and spring back when it lifts. -- **`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). Its `position` is where the scroll is, even for a finger, which moves no pointer. - **`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. @@ -75,6 +78,42 @@ rsx! { } ``` +## Touch screens and trackpads + +On a touch screen a tap is a click, a drag scrolls and flings, a long press opens the context menu, and two fingers pan, pinch and turn. You get that without writing anything. To use the gestures yourself, listen for them: + +- **`on_pan`** runs before the content scrolls. `delta` is how far the content follows the fingers, in logical pixels (x right, y down); `phase` is `Drag`, then `Fling` as it coasts, then `End` with a zero delta. Call `cx.stop_propagation()` to take the drag, and nothing scrolls. +- **`on_pinch`**: `delta` is the scale change since the last event. 0.1 is 10% larger, so multiply your zoom by `1.0 + delta`. +- **`on_rotate`**: `degrees` since the last event, positive counter-clockwise. +- **`touch`** is `true` for two fingers on a screen and `false` for a trackpad. + + + + +```rust +rsx! { +
+} +``` + + + + +```rust +div().w(px(300.0)).h(px(200.0)) + .on_pan(|e: &PanEvent, _, cx| { println!("pan {:?}", e.delta); cx.stop_propagation(); }) + .on_pinch(|e: &PinchEvent, _, _| println!("zoom x{}", 1.0 + e.delta)) + .on_rotate(|e: &RotateEvent, _, _| println!("turn {} deg", e.degrees)) +``` + + + + +In a test, `cx.simulate_touch(win.id, id, TouchPhase::Down, x, y)` (then `Move`, `Up` or `Cancel`) plays one finger, and `cx.simulate_magnify` / `cx.simulate_rotate` play a trackpad. [Touch and gestures](../../concepts/touch/) explains the whole model. + ## Focus and bubbling - **Clicking an element focuses it.** Key events go to the focused element, then bubble up through its ancestors. diff --git a/website/src/content/docs/rust/headless-testing.mdx b/website/src/content/docs/rust/headless-testing.mdx index 28a67238..090abd7e 100644 --- a/website/src/content/docs/rust/headless-testing.mdx +++ b/website/src/content/docs/rust/headless-testing.mdx @@ -4,7 +4,7 @@ description: Run your Rust UI without a window, click and type into it from a te section: Rust order: 80 languages: ["rust"] -sources: ["docs/rust.md", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/tests/suite/headless.rs", "bindings/rust/blenderui/tests/suite/animation.rs", "bindings/rust/blenderui/tests/suite/rsx.rs", "bindings/rust/blenderui/tests/suite/hooks.rs", "bindings/rust/blenderui/tests/suite/parity.rs", "bindings/rust/blenderui/tests/wpt/main.rs", "bindings/rust/blenderui/examples/hello.rs"] +sources: ["docs/rust.md", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/tests/suite/headless.rs", "bindings/rust/blenderui/tests/suite/animation.rs", "bindings/rust/blenderui/tests/suite/rsx.rs", "bindings/rust/blenderui/tests/suite/hooks.rs", "bindings/rust/blenderui/tests/suite/parity.rs", "bindings/rust/blenderui/tests/suite/touch.rs", "bindings/rust/blenderui/tests/wpt/main.rs", "bindings/rust/blenderui/examples/hello.rs"] --- The best UI bug is the one your test catches before anyone sees it. **BUI can run your whole app off-screen**: same code, same layout, same pixels, no window. Your tests click buttons, type text, scroll lists and check the result, in plain `cargo test`, on CI machines with no display. @@ -59,6 +59,8 @@ Run it with `cargo test`. Here's what each piece does: | `simulate_click_with(window, x, y, ctrl, shift)`, `simulate_key_with(window, text, keysym, ctrl, shift)` | The same with modifier keys held (Shift+click, Ctrl+A) | | `simulate_scroll(window, x, y, lines)` | Turn the wheel at a point: positive `lines` scroll the content up, negative scroll down | | `simulate_key(window, text, keysym)` | Type text, or press a key by its X11 keysym name: `"Return"`, `"BackSpace"`, `"a"` … | +| `simulate_touch(window, id, phase, x, y)` | One finger of a touch screen: `TouchPhase::Down`, `Move`, `Up` or `Cancel`, with `id` telling fingers apart. A tap clicks, a drag scrolls, two fingers pinch and turn, as on a real screen | +| `simulate_magnify(window, x, y, delta)`, `simulate_rotate(window, x, y, degrees)` | A trackpad's pinch (0.1 is 10% larger) and turn (positive counter-clockwise) | Coordinates are logical pixels. Each call handles the events it caused and re-renders before returning, so you can assert right after it. @@ -190,6 +192,7 @@ cargo test --test suite parity:: -- --nocapture # print the HTML and CSS covera | `tests/suite/animation.rs` | Keyframes, fill modes, easing, transitions and the virtual clock | | `tests/suite/effects.rs` | Filters, transforms, clip paths, masks, blend modes, scroll snap, Blender components | | `tests/suite/basic_css.rs`, `tests/suite/modern_css.rs` | Borders, counters, `styled`, variables, grid areas, selectors, at-rules | +| `tests/suite/touch.rs` | Taps, a finger's scroll, `on_pan`, `on_pinch` and `on_rotate` | | `tests/suite/parity.rs` | The coverage numbers | ### The web-platform-tests