diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b98c8cf..78b429e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,6 +96,30 @@ All notable changes to **blenderui** (BUI). The format follows `muted=` and `volume=`) and Lua; the Blender-style controls get a mute button. Videos autoplay with sound now (they were silent): mute one with `muted`. Tested on Windows; the macOS and Linux outputs are written against their documented APIs and untried. +- **Rust: `on_key_press`, `scroll` from any source, and what leaves the tree.** `keypress` follows `keydown` for a key that + types. `scroll` fires for every scroll container that moved (also `set_scroll_offset` or a layout change), not only the wheel. + When the element that holds the pointer is removed, `pointercancel` and `lostpointercapture` go out and the capture ends; + a removed focused element no longer keeps the focus. +- **JavaScript: the whole set of HTML events.** `addEventListener` now takes `dblclick`, `auxclick`, `contextmenu`, `mouseover`/`mouseout`, + every `pointer*` event, `keypress`, `focus`/`blur`/`focusin`/`focusout`, `scroll` and Blender's `pressdrag`, with the capture + phase (`{ capture: true }`, `once`, `event.eventPhase`), `buttons`, `pointerId` / `pointerType`, and `el.setPointerCapture()` / + `releasePointerCapture()` / `hasPointerCapture()`. The native listener mask is now two words (`LISTEN` carries 62 bits), and the + window's own `focus` / `blur` are told from an element's by the target. +- **Rust: Blender's press-drag.** `on_press_drag` (`PressDragEvent`, `DragDirection`, `DRAG_THRESHOLD`): once per press, from the first + move more than 3 pixels from where the button went down, with the direction to the nearest of eight, as Blender's + `KM_PRESS_DRAG` and `WM_event_drag_direction` (`wm_event_system.cc`, `wm_event_query.cc`). +- **Rust: every HTML event, with capture and bubbling.** A listener for each `on*` event: `on_double_click`, + `on_aux_click`, `on_context_menu`, `on_mouse_enter` / `leave` / `over` / `out`, the pointer events + (`on_pointer_down` / `up` / `move` / `enter` / `leave` / `over` / `out` / `cancel` and the pointer capture pair, with a + `PointerEvent`), `on_focus` / `blur` / `focus_in` / `focus_out`, `on_scroll` and `on_wheel`, and a `_capture` twin of + each (`onClickCapture` in `rsx!`) for the pass from the root down to the target. `cx.stop_propagation()` ends the pass it + is in. `window.set_pointer_capture(cx)` holds the pointer for an element, so a drag keeps hearing the moves and the + release outside it; `on_mouse_event` / `on_key_event` / `on_window_event` hear every event of a kind in the window, in + both passes, as gpui's `on_mouse_event` does (`DispatchPhase::Capture` / `Bubble`). A press fires `pointerdown` before + `mousedown`, and a move `pointermove` before `mousemove`. One listener list per element holds them all (a frame + skips the walk for kinds nothing listens for). The touch and trackpad gestures (`on_pan`, `on_pinch`, `on_rotate`) go + through both passes too, with their `_capture` twins. Not there yet: the `touch*` events, drag-and-drop, clipboard, media + and CSS animation events. `App::simulate_button` clicks with the middle or secondary button in tests. - **Animation: GSAP and Motion on one engine** (feature `anim`, on by default; `BUI_ANIM` in CMake). One C engine in the kit (`kit/intern/anim`, `BUI_anim.h`) runs every animation, so Rust, JavaScript, Python, Lua and C animate the same way and none carries its own. Eases: every name of GSAP, Motion, CSS and Blender, `cubic-bezier()`, @@ -127,6 +151,11 @@ All notable changes to **blenderui** (BUI). The format follows ### Changed - **Rust: boxes lay out at fractional positions, as in a browser.** A flex item a quarter of 190px is 47.5px wide (it was rounded to 48), and `element_bounds` reports what `getBoundingClientRect` would. Painting snaps each edge of a box's background, border and image to its nearest device pixel, so edges stay crisp and neighbouring boxes still meet; a canvas's own drawing stays anti-aliased, as a browser canvas. +- **Rust: pointer events cost less.** The hit test keeps an index of every box's subtree and the rectangle around it + (built on the first hit test of a frame, dropped when a redraw or a scroll moves boxes) and skips the subtrees a point is + not in; an event kind nothing in the frame listens for skips the walk, window-wide listeners have a list of their own, and + a move that ends over the same elements stops after the hit test without allocating. 3000 boxes: a move 46 to 12 µs, a + click 130 to 57 µs (`examples/events_bench.rs`, headless, release, against main before the event API). - **Kit: a layout arranges only the nodes that changed.** A node is arranged again when it or a node under it measured again, or when its place changed; the rest keep their places. A frame where one label changes among 3300 nodes: 0.26 ms instead of 0.31 ms. A change of theme, scale or font still arranges every node. - **Kit: a layout change redraws only what moved.** A layout used to redraw the whole window. Now each widget's place on screen is compared with where the last frame drew it, and only widgets that moved, resized, appeared or @@ -212,6 +241,12 @@ All notable changes to **blenderui** (BUI). The format follows - `:nth-last-child(An+B of S)` counts the following siblings that match `S` (it saw none, since they aren't built when rules match; `S` may name the element's ancestors). - `light-dark()`, the system colors (`Canvas`, `LinkText` ...) and `@media (prefers-color-scheme)` follow the theme's mode (they were always dark). Light mode uses a browser's light system colors. Windows re-render when the theme changes, with no `notify_all()` needed. - **Windows: the system's maximize button maximizes again.** The kit took every press on a maximize button as the app's, so on a window with the system's title bar the press went to the app and Windows never maximized; only a title bar the app draws (`WindowDecorations::Client`) hands its maximize button's presses to the app now. +- **Rust: an element the layout moved under a pointer that stayed still was never entered** (`mouseenter`, `mouseover`, + `pointerenter`, `on_hover` and their leave twins didn't fire; only `:hover` followed): the hover update after each frame fires events now. +- **Rust: `cx.notify()` in a listener didn't render the window it ran in** (that window is out of the list while it runs): + every call that lends a window out renders it again after a `notify`, not only `WindowHandle::update`. +- **Rust: a `render` that reads `window.is_hovered(..)` or `focused_id()` follows them.** Since a hover or a press over + plain content renders nothing, a view that read them kept the old answer; it renders again when what it read changes. - **Android: the app runs again after Back.** The host's state (`g_quit`, the wake callback, keep-alive, the stop check) starts over on each `BK_android_attach`, so a relaunch in the same process is not a dead window; the activity is `singleTask`, so a second launch brings the running one back instead of attaching a second activity. `BK_android_detach` (new; `android_main` calls it before the glue frees the app) ends wakes from other threads, which used the freed looper. A Lua script that fails after opening its window shows its error (the error window came back NULL and crashed). A second finger joining a one-finger scroll no longer jumps it; `BK_window_timer` returns -1 (not 0) when the window's timers are full, as `BUI_kit.h` says; a failed window allocation returns NULL (the C demo checks it); a frame whose post fails is redrawn. `build.py` aligns the APK with `zipalign 4` (the libraries are deflated: `-P 16` aligned nothing and failed on build-tools 34) and builds a Rust app's crate with `--lib`. - **WebAssembly: an unstyled canvas keeps its size after a zoom.** At a pixel ratio of 1 its CSS size was not pinned, so after a zoom or a move to a retina screen it grew on every frame; every resize now sizes the backing store and pins it. `build.py --serve` serves `.wasm` and `.js` with their web types on Windows (the override was set on a `functools.partial`, where it did nothing). The wasm workflow runs on changes to the kit, the GPU raster, core and blenderui too, and the smoke test's click check compares against the hovered button, so it can fail. - **QuickJS (`bui run`, `bui build`, Android `--js`): timers set from promise jobs run.** A `setTimeout` made in a `.then` was missed (a headless app quit with it pending, a windowed one stalled until the next event); timers now run one task at a time with the promise jobs after each, as in HTML's event loop, and the next deadline is read after the last job. A pump that runs out of rounds with work left schedules the next one. `setTimeout(f, Infinity)` (or `NaN`, negative, past 2^31-1 ms) is a 0 ms delay, as in browsers, instead of panicking the runtime. diff --git a/README.md b/README.md index 8b427c14..d752f29f 100644 --- a/README.md +++ b/README.md @@ -1370,6 +1370,11 @@ run time, and every open window relayouts and redraws: | Dear ImGui | Its Blender style follows the kit's theme (pick it before the backend starts) | | Any app, no code change | `BUI_THEME=light` (or `dark`) | +

+ The same dashboard in seven themes, one cut after another: Blender Dark, Blender Light, Catppuccin Mocha, Nord, Dracula, Gruvbox and Tokyo Night +
One dashboard, seven themes: Blender's Dark and Light, then five theme files +

+ **Your own themes.** A theme file is JSON in the shape of gpui-kit's, with Blender's names for the colors (`user_interface.wcol_regular.inner`, or in plain English `button.background`). It starts from Dark or Light and lists only what it changes: colors, a few short palette names (`background`, `primary.background`) that fill in diff --git a/bindings/node/README.md b/bindings/node/README.md index edd350aa..140e0131 100644 --- a/bindings/node/README.md +++ b/bindings/node/README.md @@ -55,14 +55,18 @@ win.body.appendChild(button) `@blender-ui/native/globals` (`document`, `window` and the node classes as 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`, - `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. +- **Events:** `addEventListener` for `click`, `dblclick`, `auxclick`, + `contextmenu`, the `mouse*` and `pointer*` events (`pointerdown`, `pointerup`, + `pointermove`, `pointerenter`, `pointerleave`, `pointerover`, `pointerout`, + `pointercancel`, `gotpointercapture`, `lostpointercapture`), `wheel`, + `keydown`, `keypress`, `keyup`, `focus`, `blur`, `focusin`, `focusout`, + `scroll`, `pressdrag` (Blender's press-drag), `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 capture and bubble through the tree (`addEventListener(type, fn, { capture: true, once: true })`), + and `stopPropagation()` works. `el.setPointerCapture()` keeps the pointer for an element. - 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 diff --git a/bindings/node/dom.js b/bindings/node/dom.js index 22e937af..0b356ec0 100644 --- a/bindings/node/dom.js +++ b/bindings/node/dom.js @@ -14,20 +14,27 @@ const { isSignal, effect, unowned, memo } = require('./signals') const { vars: checkVars } = require('./validate') // Keep in sync with bindings/rust/blenderui-node/src/lib.rs. -const OP = { CREATE: 0, TEXT: 1, SET_ATTR: 2, REMOVE_ATTR: 3, APPEND: 4, INSERT: 5, REMOVE: 6, SET_TEXT: 7, LISTEN: 8, FREE: 9, MOTION: 10 } +const OP = { CREATE: 0, TEXT: 1, SET_ATTR: 2, REMOVE_ATTR: 3, APPEND: 4, INSERT: 5, REMOVE: 6, SET_TEXT: 7, LISTEN: 8, FREE: 9, MOTION: 10, CAPTURE: 11 } // Motion's props (keep in sync with MotionProp::parse, bindings/rust/blenderui-jsview/src/motion.rs) const MOTION_PROPS = { initial: 0, animate: 1, exit: 2, whileHover: 3, whileTap: 4, whileFocus: 5, transition: 6, style: 7, variants: 8, whileInView: 9, whileDrag: 10, viewport: 11, drag: 12, dragConstraints: 13, dragElastic: 14, dragMomentum: 15, dragSnapToOrigin: 16, layout: 17 } +// one bit per native listener (`ev` in blenderui-jsview); more than 31, so they travel as two words 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, pinch: 1024, rotate: 2048, pan: 4096, + click: 2 ** 0, mousedown: 2 ** 1, mouseup: 2 ** 2, mousemove: 2 ** 3, mouseenter: 2 ** 4, mouseleave: 2 ** 4, + wheel: 2 ** 5, keydown: 2 ** 6, keyup: 2 ** 7, change: 2 ** 8, input: 2 ** 9, + pinch: 2 ** 10, rotate: 2 ** 11, pan: 2 ** 12, + dblclick: 2 ** 13, auxclick: 2 ** 14, contextmenu: 2 ** 15, mouseover: 2 ** 16, mouseout: 2 ** 17, + pointerdown: 2 ** 18, pointerup: 2 ** 19, pointermove: 2 ** 20, pointerenter: 2 ** 21, pointerleave: 2 ** 22, + pointerover: 2 ** 23, pointerout: 2 ** 24, pointercancel: 2 ** 25, gotpointercapture: 2 ** 26, lostpointercapture: 2 ** 27, + keypress: 2 ** 28, focus: 2 ** 29, blur: 2 ** 30, focusin: 2 ** 31, focusout: 2 ** 32, pressdrag: 2 ** 33, scroll: 2 ** 34, } +const WORD = 2 ** 31 const BUTTONS = ['left', 'middle', 'right'] // DOM: these don't bubble -const NO_BUBBLE = new Set(['mouseenter', 'mouseleave']) +const NO_BUBBLE = new Set(['mouseenter', 'mouseleave', 'pointerenter', 'pointerleave', 'focus', 'blur', 'scroll']) const ELEMENT_NODE = 1, TEXT_NODE = 3, COMMENT_NODE = 8, FRAGMENT_NODE = 11 const XHTML = 'http://www.w3.org/1999/xhtml' @@ -56,6 +63,17 @@ class BuiEvent { this.clientX = this.x = raw.x this.clientY = this.y = raw.y this.button = raw.button + this.buttons = raw.buttons + this.pointerId = 1 + this.pointerType = 'mouse' + this.isPrimary = true + this.pressure = raw.buttons ? 0.5 : 0 + this.eventPhase = 0 // 1 capturing, 2 at the target, 3 bubbling + this.direction = raw.direction ?? undefined // `pressdrag`: 'east' ... 'southeast' + this.startX = raw.dx // `pressdrag`: where the press started + this.startY = raw.dy + this.scrollLeft = raw.dx // `scroll`: the new offsets + this.scrollTop = raw.dy this.detail = raw.clickCount // wheel: the DOM's, positive scrolls down; pan: pixels the content follows the fingers (x right, // y down) @@ -662,27 +680,50 @@ class Element extends Node { if (t !== '' && t != null) this.appendChild(this._createText(isSignal(t) ? t : String(t))) } - /** Any event type; those BUI reports (`EVENT_BITS`) arrive from the UI thread. */ - addEventListener (type, fn) { - const listeners = (this._listeners ??= new Map()) + /** Any event type; those BUI reports (`EVENT_BITS`) arrive from the UI thread. `options`: `true` / `{ capture: true }` + * listens in the capture phase (ancestors first), `{ once: true }` removes the listener after its first call. */ + addEventListener (type, fn, options) { + const capture = options === true || (options != null && typeof options === 'object' && options.capture === true) + const once = options != null && typeof options === 'object' && options.once === true + const listeners = (capture ? (this._capture ??= new Map()) : (this._listeners ??= new Map())) let set = listeners.get(type) - if (!set) listeners.set(type, (set = new Set())) - set.add(fn) + if (!set) listeners.set(type, (set = new Map())) + if (!set.has(fn)) set.set(fn, once) this._listen() } - removeEventListener (type, fn) { - this._listeners?.get(type)?.delete(fn) + removeEventListener (type, fn, options) { + const capture = options === true || (options != null && typeof options === 'object' && options.capture === true) + ;(capture ? this._capture : this._listeners)?.get(type)?.delete(fn) this._listen() } + /** HTML `setPointerCapture`: the element keeps the pointer events (also out of it) until the button is released. + * Call it from a `pointerdown` / `mousedown` handler. */ + setPointerCapture (_pointerId) { this._pointerCapture(true) } + + releasePointerCapture (_pointerId) { this._pointerCapture(false) } + + hasPointerCapture (_pointerId) { return (this._x?.captured ?? false) === true } + + _pointerCapture (on) { + const w = this.ownerWindow + if (w === null || (this._x?.captured ?? false) === on) return + ;(this._x ??= {}).captured = on + this._listen() // it needs `lostpointercapture` to know when the host lets go + w._op(OP.CAPTURE, this.id, on ? 1 : 0) + } + _listen () { let bits = 0 - if (this._listeners !== null) for (const [type, set] of this._listeners) if (set.size) bits |= EVENT_BITS[type] ?? 0 + for (const map of [this._listeners, this._capture]) { + if (map != null) for (const [type, set] of map) if (set.size) bits = orBits(bits, EVENT_BITS[type] ?? 0) + } + if (this._x?.captured) bits = orBits(bits, EVENT_BITS.lostpointercapture) if (bits !== this._bits) { this._bits = bits const w = this.ownerWindow - if (w !== null) w._op(OP.LISTEN, this.id, bits) + if (w !== null) w._op(OP.LISTEN, this.id, bits % WORD, Math.floor(bits / WORD)) } } @@ -690,7 +731,7 @@ class Element extends Node { win._op(OP.CREATE, this.id, win._s(this.localName)) const a = this._attrs if (a !== null) for (let i = 0; i < a.length; i += 2) win._op(OP.SET_ATTR, this.id, win._s(a[i]), win._s(a[i + 1])) - if (this._bits !== 0) win._op(OP.LISTEN, this.id, this._bits) + if (this._bits !== 0) win._op(OP.LISTEN, this.id, this._bits % WORD, Math.floor(this._bits / WORD)) const m = this._x?.motion if (m) for (const k in m) win._motionOp(this.id, MOTION_PROPS[k], m[k]) } @@ -708,6 +749,7 @@ class Element extends Node { x.checked = raw.checked x.number = raw.number } + if (raw.kind === 'lostpointercapture' && this._x !== null) this._x.captured = false this._propagate(new BuiEvent(raw, this)) } @@ -721,18 +763,30 @@ class Element extends Node { } _propagate (e) { - for (let n = this; n !== null; n = n.parentNode) { - const set = n._listeners?.get(e.type) - if (set && set.size) { - e.currentTarget = n - for (const fn of [...set]) { - try { fn.call(n, e) } catch (err) { queueMicrotask(() => { throw err }) } - if (e.immediatePropagationStopped) break - } + // the target's ancestors, innermost first + const up = [] + for (let n = this.parentNode; n !== null; n = n.parentNode) up.push(n) + const stopped = () => e.cancelBubble === true + const own = e instanceof BuiEvent // a DOM Event keeps its own phase + const run = (n, map, phase) => { + const set = map?.get(e.type) + if (!set || set.size === 0) return + e.currentTarget = n + if (own) e.eventPhase = phase + for (const [fn, once] of [...set]) { + if (once) set.delete(fn) + try { fn.call(n, e) } catch (err) { queueMicrotask(() => { throw err }) } + if (e.immediatePropagationStopped) break } - if (e.cancelBubble || !e.bubbles) break } + // capture: from the root down to the target's parent, then at the target + for (let i = up.length - 1; i >= 0 && !stopped(); i--) run(up[i], up[i]._capture, 1) + if (!stopped()) run(this, this._capture, 2) + if (!stopped() && !e.immediatePropagationStopped) run(this, this._listeners, 2) + // bubble + if (e.bubbles) for (let i = 0; i < up.length && !stopped(); i++) run(up[i], up[i]._listeners, 3) e.currentTarget = null + if (own) e.eventPhase = 0 } /** Web Animations: `animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: 'ease-out' })`, @@ -750,9 +804,16 @@ class Element extends Node { } } +function orBits (a, b) { + // a | b for bits above 31 + const [al, ah, bl, bh] = [a % WORD, Math.floor(a / WORD), b % WORD, Math.floor(b / WORD)] + return ((al | bl) >>> 0) + ((ah | bh) >>> 0) * WORD +} + // listeners (a Map), their native bits, and the rarely used extras (form // state from events, the style object): on the prototype until an element has them Element.prototype._listeners = null +Element.prototype._capture = null Element.prototype._bits = 0 Element.prototype._x = null diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts index 3c9fec7e..86a37411 100644 --- a/bindings/node/index.d.ts +++ b/bindings/node/index.d.ts @@ -43,8 +43,22 @@ export interface LayerShellOptions { keyboard?: 'none' | 'exclusive' | 'on-demand' } -export type EventType = 'click' | 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' | - 'wheel' | 'keydown' | 'keyup' | 'change' | 'input' | 'pinch' | 'rotate' | 'pan' +export type EventType = 'click' | 'dblclick' | 'auxclick' | 'contextmenu' | + 'mousedown' | 'mouseup' | 'mousemove' | 'mouseenter' | 'mouseleave' | 'mouseover' | 'mouseout' | + 'pointerdown' | 'pointerup' | 'pointermove' | 'pointerenter' | 'pointerleave' | 'pointerover' | 'pointerout' | + 'pointercancel' | 'gotpointercapture' | 'lostpointercapture' | + 'wheel' | 'keydown' | 'keypress' | 'keyup' | 'focus' | 'blur' | 'focusin' | 'focusout' | + /** Blender's press-drag: a button held and the pointer moved past 3 pixels (once per press). */ + 'pressdrag' | 'scroll' | 'change' | 'input' | + /** Touch screens and trackpads. */ + 'pinch' | 'rotate' | 'pan' + +export interface ListenerOptions { + /** Listen while the event travels down to the target (ancestors first). */ + capture?: boolean + /** Remove the listener after its first call. */ + once?: boolean +} export class BuiEvent { type: EventType @@ -55,6 +69,22 @@ export class BuiEvent { x: number y: number button: number + /** The buttons held (1 left, 2 right, 4 middle). */ + buttons: number + pointerId: number + pointerType: 'mouse' + isPrimary: boolean + pressure: number + /** 1 capturing, 2 at the target, 3 bubbling. */ + eventPhase: number + /** `pressdrag`: `'east'`, `'northeast'`, ... `'southeast'`. */ + direction?: string + /** `pressdrag`: where the press started. */ + startX: number + startY: number + /** `scroll`: the new offsets. */ + scrollLeft: number + scrollTop: number detail: number /** `pan`: pixels the content follows the fingers, right (0 for other events). */ deltaX: number @@ -294,8 +324,12 @@ export class Element extends Node { toggleAttribute (name: string, force?: boolean): boolean getAttributeNames (): string[] /** Any type; BUI's own (`EventType`) arrive from the UI thread. */ - addEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: unknown): void - removeEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: unknown): void + addEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: boolean | ListenerOptions): void + removeEventListener (type: EventType | (string & {}), listener: (event: BuiEvent) => void, options?: boolean | ListenerOptions): void + /** Keep the pointer events (also out of the element) until the button is released; call it in `pointerdown`. */ + setPointerCapture (pointerId?: number): void + releasePointerCapture (pointerId?: number): void + hasPointerCapture (pointerId?: number): boolean /** Run the listeners for `event.type` here (and up, if it bubbles). */ dispatchEvent (event: { type: string, bubbles?: boolean }): boolean /** Web Animations, run by the engine: `animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300, easing: 'ease-out' })`. diff --git a/bindings/node/index.js b/bindings/node/index.js index cb0f1bb9..22d8430b 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -418,7 +418,7 @@ class App { win._frame() return } - if (raw.kind === 'focus' || raw.kind === 'blur') { + if ((raw.kind === 'focus' || raw.kind === 'blur') && raw.target === 0xffffffff) { // the window's own win._emit(raw.kind) return } diff --git a/bindings/node/test/native.test.js b/bindings/node/test/native.test.js index 12016e55..47176bfd 100644 --- a/bindings/node/test/native.test.js +++ b/bindings/node/test/native.test.js @@ -238,3 +238,46 @@ test('touch screen and trackpad gestures: pinch, rotate and pan bubble with thei 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') }) + +test('HTML events: capture phase, pointer events, capture of the pointer, dblclick (headless)', async (t) => { + const app = new App({ headless: true }) + t.after(() => app.quit()) + const win = app.window({ width: 300, height: 200 }) + win.body.style = 'margin: 0' + const outer = win.createElement('div') + outer.style = { width: 200, height: 100, padding: 10 } + const inner = win.createElement('div') + inner.style = { width: 100, height: 50, backgroundColor: '#00f' } + outer.appendChild(inner) + win.body.appendChild(outer) + await inner.getBoundingClientRect() + + const log = [] + const tick = () => new Promise(resolve => setTimeout(resolve, 30)) + outer.addEventListener('pointerdown', e => log.push(`outer capture ${e.eventPhase} ${e.target === inner}`), true) + outer.addEventListener('pointerdown', e => log.push(`outer bubble ${e.eventPhase}`)) + inner.addEventListener('pointerdown', e => { + log.push(`inner ${e.eventPhase} ${e.pointerType}`) + inner.setPointerCapture(e.pointerId) + }) + inner.addEventListener('pointermove', e => log.push(`inner move ${Math.round(e.x)}`)) + inner.addEventListener('pointerup', () => log.push('inner up')) + inner.addEventListener('dblclick', e => log.push(`dblclick ${e.detail}`)) + let once = 0 + inner.addEventListener('click', () => once++, { once: true }) + inner.addEventListener('pressdrag', e => log.push(`pressdrag ${e.direction}`)) + + win.mouseMove(30, 30) + win.mouseDown(30, 30) + await tick() + assert.deepStrictEqual(log.filter(x => !x.startsWith('inner move')).slice(0, 3), ['outer capture 1 true', 'inner 2 mouse', 'outer bubble 3'], 'capture first, then the target, then bubbling') + assert.ok(inner.hasPointerCapture(1), 'captured') + win.mouseMove(250, 150) // far outside the element + await tick() + assert.ok(log.includes('inner move 250'), 'a captured pointer is heard outside the element: ' + log) + assert.ok(log.includes('pressdrag east') || log.some(x => x.startsWith('pressdrag')), 'press-drag: ' + log) + win.mouseUp(250, 150) + await tick() + assert.ok(log.includes('inner up'), 'the release goes to the element that holds the pointer') + assert.ok(!inner.hasPointerCapture(1), 'released with the button') +}) diff --git a/bindings/rust/blenderui-jsview/src/lib.rs b/bindings/rust/blenderui-jsview/src/lib.rs index a75cd647..2e65e895 100644 --- a/bindings/rust/blenderui-jsview/src/lib.rs +++ b/bindings/rust/blenderui-jsview/src/lib.rs @@ -18,9 +18,9 @@ use blenderui::prelude::*; pub mod motion; pub mod shell; -/// An event from a window (`kind`: click, mousedown, mouseup, mousemove, -/// mouseenter, mouseleave, wheel, keydown, keyup, change, input, pinch, -/// rotate, pan, frame, close). +/// An event from a window (`kind`: the DOM name of an `ev` bit, such as click, +/// mousedown, pointermove, wheel, keydown, focus, scroll, pressdrag, change, +/// input, pinch, rotate or pan; or frame, close). #[derive(Clone, Debug, Default)] pub struct Event { pub kind: String, @@ -32,6 +32,13 @@ pub struct Event { /// 0 left, 1 middle, 2 right (DOM numbering). pub button: u32, pub click_count: u32, + /// The DOM `buttons` bits held (1 left, 2 right, 4 middle). + pub buttons: u32, + /// `pressdrag`: the compass direction; `pointer*`: the pointer type. + pub direction: Option, + /// `pressdrag`: where the press started; `scroll`: the scroll offsets. + pub dx: f64, + pub dy: f64, /// `wheel`: lines (positive scrolls the content up); `pinch`: the scale change (0.1 = 10% /// larger); `rotate`: degrees, positive counter-clockwise. pub delta: f64, @@ -52,6 +59,9 @@ pub struct Event { pub values: Option>, } +/// `Event::target` of the window own `focus` and `blur` (an element gets its node). +pub const WINDOW: u32 = u32::MAX; + /// Where a window's events go (called on the UI thread). pub type Sink = Arc; @@ -136,26 +146,49 @@ pub mod op { pub const INSERT: i32 = 5; // parent, child, before pub const REMOVE: i32 = 6; // parent, child pub const SET_TEXT: i32 = 7; // id, s(text) - pub const LISTEN: i32 = 8; // id, event bits (replaces) + pub const LISTEN: i32 = 8; // id, event bits low 31, high bits (replaces) pub const FREE: i32 = 9; // id - pub const MOTION: i32 = 10; // id, which (motion::MotionProp::parse), index into the commit's motion props + pub const MOTION: i32 = 10; // id, which (motion::MotionProp::parse), index into the commit motion props + pub const CAPTURE: i32 = 11; // id, 1 hold the pointer for it / 0 let go } /// Event bits (`LISTEN`), matching `bindings/node/index.js`. pub mod ev { - pub const CLICK: u32 = 1; - pub const MOUSE_DOWN: u32 = 2; - pub const MOUSE_UP: u32 = 4; - pub const MOUSE_MOVE: u32 = 8; - pub const HOVER: u32 = 16; - pub const WHEEL: u32 = 32; - pub const KEY_DOWN: u32 = 64; - 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; + pub const CLICK: u64 = 1 << 0; + pub const MOUSE_DOWN: u64 = 1 << 1; + pub const MOUSE_UP: u64 = 1 << 2; + pub const MOUSE_MOVE: u64 = 1 << 3; + pub const HOVER: u64 = 1 << 4; + pub const WHEEL: u64 = 1 << 5; + pub const KEY_DOWN: u64 = 1 << 6; + pub const KEY_UP: u64 = 1 << 7; + pub const CHANGE: u64 = 1 << 8; + pub const INPUT: u64 = 1 << 9; + pub const PINCH: u64 = 1 << 10; + pub const ROTATE: u64 = 1 << 11; + pub const PAN: u64 = 1 << 12; + pub const DOUBLE_CLICK: u64 = 1 << 13; + pub const AUX_CLICK: u64 = 1 << 14; + pub const CONTEXT_MENU: u64 = 1 << 15; + pub const MOUSE_OVER: u64 = 1 << 16; + pub const MOUSE_OUT: u64 = 1 << 17; + pub const POINTER_DOWN: u64 = 1 << 18; + pub const POINTER_UP: u64 = 1 << 19; + pub const POINTER_MOVE: u64 = 1 << 20; + pub const POINTER_ENTER: u64 = 1 << 21; + pub const POINTER_LEAVE: u64 = 1 << 22; + pub const POINTER_OVER: u64 = 1 << 23; + pub const POINTER_OUT: u64 = 1 << 24; + pub const POINTER_CANCEL: u64 = 1 << 25; + pub const GOT_CAPTURE: u64 = 1 << 26; + pub const LOST_CAPTURE: u64 = 1 << 27; + pub const KEY_PRESS: u64 = 1 << 28; + pub const FOCUS: u64 = 1 << 29; + pub const BLUR: u64 = 1 << 30; + pub const FOCUS_IN: u64 = 1 << 31; + pub const FOCUS_OUT: u64 = 1 << 32; + pub const PRESS_DRAG: u64 = 1 << 33; + pub const SCROLL: u64 = 1 << 34; } // ========================================================================== @@ -169,7 +202,7 @@ struct JsNode { /// The `style` attribute, parsed once when set (renders reuse it). style: Option>, children: Vec, - events: u32, + events: u64, /// Motion's props (`initial`, `animate` ...), when it has any. motion: Option>, /// JavaScript removed it, and its `exit` animation runs first: the presence it goes with (0: none). @@ -240,7 +273,7 @@ impl JsView { } fn apply(&mut self, ops: &[i32], strings: &[String], motion: &mut [Option], - tags: &mut HashMap) { + tags: &mut HashMap, capture: &mut Vec<(i32, bool)>) { let s = |k: i32| strings.get(k as usize).map(String::as_str).unwrap_or(""); let mut i = 0; while i < ops.len() { @@ -322,10 +355,14 @@ impl JsView { i += 3; } op::LISTEN => { - let bits = a(2) as u32; + let bits = u64::from(a(2) as u32) | (u64::from(a(3) as u32) << 31); if let Some(n) = self.node(a(1)) { n.events = bits; } + i += 4; + } + op::CAPTURE => { + capture.push((a(1), a(2) != 0)); i += 3; } op::MOTION => { @@ -426,7 +463,7 @@ impl JsView { d.into_any_element() } - fn listeners(&self, mut d: Div, id: u32, bits: u32) -> Div { + fn listeners(&self, mut d: Div, id: u32, bits: u64) -> Div { fn at(e: &mut Event, p: Point) { (e.x, e.y) = (f64::from(p.x.0), f64::from(p.y.0)); } @@ -468,14 +505,14 @@ impl JsView { } on!(ev::CLICK, on_click, |e, c| { e.kind = "click".into(); - (e.x, e.y) = (c.up.position.x.0 as f64, c.up.position.y.0 as f64); + at(&mut e, c.up.position); e.button = button(&c.up.button); e.click_count = c.down.click_count as u32; mods(&mut e, &c.up.modifiers); }); on!(ev::MOUSE_DOWN, on_any_mouse_down, |e, m| { e.kind = "mousedown".into(); - (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64); + at(&mut e, m.position); e.button = button(&m.button); e.click_count = m.click_count as u32; mods(&mut e, &m.modifiers); @@ -483,14 +520,14 @@ impl JsView { for b in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] { on!(ev::MOUSE_UP, on_mouse_up(b.clone()), |e, m| { e.kind = "mouseup".into(); - (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64); + at(&mut e, m.position); e.button = button(&m.button); mods(&mut e, &m.modifiers); }); } on!(ev::MOUSE_MOVE, on_mouse_move, |e, m| { e.kind = "mousemove".into(); - (e.x, e.y) = (m.position.x.0 as f64, m.position.y.0 as f64); + at(&mut e, m.position); mods(&mut e, &m.modifiers); }); on!(@ false, ev::HOVER, on_hover, |e, h| { @@ -498,7 +535,7 @@ impl JsView { }); on!(ev::WHEEL, on_scroll_wheel, |e, w| { e.kind = "wheel".into(); - (e.x, e.y) = (w.position.x.0 as f64, w.position.y.0 as f64); + at(&mut e, w.position); e.delta = w.delta as f64; mods(&mut e, &w.modifiers); }); @@ -548,6 +585,96 @@ impl JsView { e.kind = "input".into(); (e.value, e.checked, e.number) = (Some(c.value.clone()), c.checked, c.number); }); + // the rest of HTML events, as tables: the Rust method, the DOM name + macro_rules! pointer { + ($($bit:ident, $method:ident, $name:expr;)*) => {$( + on!(ev::$bit, $method, |e, p| { + e.kind = $name.into(); + at(&mut e, p.position); + e.button = p.button.as_ref().map_or(0, button); + e.buttons = u32::from(p.buttons); + e.click_count = p.click_count as u32; + e.direction = Some("mouse".into()); + mods(&mut e, &p.modifiers); + }); + )*}; + } + pointer! { + POINTER_DOWN, on_pointer_down, "pointerdown"; + POINTER_UP, on_pointer_up, "pointerup"; + POINTER_MOVE, on_pointer_move, "pointermove"; + POINTER_OVER, on_pointer_over, "pointerover"; + POINTER_OUT, on_pointer_out, "pointerout"; + POINTER_CANCEL, on_pointer_cancel, "pointercancel"; + GOT_CAPTURE, on_got_pointer_capture, "gotpointercapture"; + LOST_CAPTURE, on_lost_pointer_capture, "lostpointercapture"; + } + on!(@ false, ev::POINTER_ENTER, on_pointer_enter, |e, p| { + e.kind = "pointerenter".into(); + at(&mut e, p.position); + e.direction = Some("mouse".into()); + }); + on!(@ false, ev::POINTER_LEAVE, on_pointer_leave, |e, p| { + e.kind = "pointerleave".into(); + at(&mut e, p.position); + e.direction = Some("mouse".into()); + }); + macro_rules! hover { + ($($bit:ident, $method:ident, $name:expr;)*) => {$( + on!(ev::$bit, $method, |e, m| { + e.kind = $name.into(); + at(&mut e, m.position); + mods(&mut e, &m.modifiers); + }); + )*}; + } + hover! { + MOUSE_OVER, on_mouse_over, "mouseover"; + MOUSE_OUT, on_mouse_out, "mouseout"; + } + macro_rules! click { + ($($bit:ident, $method:ident, $name:expr;)*) => {$( + on!(ev::$bit, $method, |e, c| { + e.kind = $name.into(); + at(&mut e, c.up.position); + e.button = button(&c.up.button); + e.click_count = c.down.click_count as u32; + mods(&mut e, &c.up.modifiers); + }); + )*}; + } + click! { + DOUBLE_CLICK, on_double_click, "dblclick"; + AUX_CLICK, on_aux_click, "auxclick"; + } + on!(ev::CONTEXT_MENU, on_context_menu, |e, c| { + e.kind = "contextmenu".into(); + at(&mut e, c.position); + e.button = 2; + mods(&mut e, &c.modifiers); + }); + on!(ev::KEY_PRESS, on_key_press, |e, k| { + e.kind = "keypress".into(); + e.key = Some(k.keystroke.key.clone()); + e.key_char = k.keystroke.key_char.clone(); + mods(&mut e, &k.keystroke.modifiers); + }); + on!(@ false, ev::FOCUS, on_focus, |e, _f| { e.kind = "focus".into(); }); + on!(@ false, ev::BLUR, on_blur, |e, _f| { e.kind = "blur".into(); }); + on!(ev::FOCUS_IN, on_focus_in, |e, _f| { e.kind = "focusin".into(); }); + on!(ev::FOCUS_OUT, on_focus_out, |e, _f| { e.kind = "focusout".into(); }); + on!(ev::PRESS_DRAG, on_press_drag, |e, p| { + e.kind = "pressdrag".into(); + at(&mut e, p.position); + (e.dx, e.dy) = (p.start.x.0 as f64, p.start.y.0 as f64); + e.button = button(&p.button); + e.direction = Some(format!("{:?}", p.direction).to_lowercase()); + mods(&mut e, &p.modifiers); + }); + on!(@ false, ev::SCROLL, on_scroll, |e, sc| { + e.kind = "scroll".into(); + (e.dx, e.dy) = (sc.offset.x.0 as f64, sc.offset.y.0 as f64); + }); d } } @@ -597,7 +724,7 @@ pub fn init(cx: &mut App, sink: Sink) { cx.on_window_activation(|id, active, cx| { let Some(w) = cx.global::().by_native.get(&id.0).copied() else { return }; let kind = if active { "focus" } else { "blur" }; - cx.global::().0(Event { kind: kind.into(), window: w, ..Default::default() }); + cx.global::().0(Event { kind: kind.into(), window: w, target: WINDOW, ..Default::default() }); }); cx.on_window_closed(|id, cx| { let Some(w) = cx.global::().by_native.get(&id.0).copied() else { return }; @@ -665,8 +792,15 @@ pub fn commit(cx: &mut App, window: u32, ops: &[i32], strings: &[String], mut pr } } let mut tags = std::mem::take(&mut cx.global_mut::().tags); - handle.update(cx, |v, w, _| { - v.apply(ops, strings, &mut props, &mut tags); + handle.update(cx, |v, w, app| { + let mut capture = Vec::new(); + v.apply(ops, strings, &mut props, &mut tags, &mut capture); + for (id, on) in capture { + let Some(n) = v.nodes.get(&(id as u32)) else { continue }; + // its key: an `id` attribute value, else "n" (as `build` gives it) + let key = n.attrs.iter().find(|(k, _)| k == "id").map_or_else(|| n.key.clone(), |(_, v)| v.clone()); + if on { w.capture_pointer_for(app, &key) } else { w.release_pointer_capture(app) } + } if !animated { w.refresh(); // this window only } else if !v.frame_scheduled { diff --git a/bindings/rust/blenderui-macros/src/component.rs b/bindings/rust/blenderui-macros/src/component.rs index 169817c9..bbd49b55 100644 --- a/bindings/rust/blenderui-macros/src/component.rs +++ b/bindings/rust/blenderui-macros/src/component.rs @@ -4,14 +4,17 @@ //! #[component] //! fn profile(username: &str, likes: u32) { //! let (n, set_n) = use_state(likes); -//! rsx! { {username} " " {n()} } +//! rsx! { {username.to_string()} " " {n()} } //! } //! // used as //! ``` //! //! Expands to a props struct named like the function, with an `IntoElement` //! impl that runs the body in a component scope (hooks, context). `&str` -//! props are stored as `String`; the body still sees `&str`. +//! props are stored as `String`; the body still sees `&str`, and an element +//! owns its text, so `{username}` needs `.to_string()`. For text shown as it +//! is, take a `SharedString` prop: `` borrows the +//! literal (no allocation) and `{username}` needs no conversion. use proc_macro::{Delimiter, Group, TokenStream, TokenTree}; diff --git a/bindings/rust/blenderui-node/src/lib.rs b/bindings/rust/blenderui-node/src/lib.rs index 9132b974..5c1ab101 100644 --- a/bindings/rust/blenderui-node/src/lib.rs +++ b/bindings/rust/blenderui-node/src/lib.rs @@ -45,6 +45,10 @@ pub struct BuiEvent { /// 0 left, 1 middle, 2 right (DOM numbering). pub button: u32, pub click_count: u32, + pub buttons: u32, + pub direction: Option, + pub dx: f64, + pub dy: f64, pub delta: f64, pub delta_x: f64, pub delta_y: f64, @@ -66,8 +70,9 @@ 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, 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, + click_count: e.click_count, buttons: e.buttons, direction: e.direction, dx: e.dx, dy: e.dy, 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, } } diff --git a/bindings/rust/blenderui-qjs/src/lib.rs b/bindings/rust/blenderui-qjs/src/lib.rs index eddb06c5..f9b86df6 100644 --- a/bindings/rust/blenderui-qjs/src/lib.rs +++ b/bindings/rust/blenderui-qjs/src/lib.rs @@ -331,6 +331,10 @@ fn event_object<'js>(ctx: &Ctx<'js>, e: view::Event) -> rquickjs::Result) -> impl IntoElement { + let cols = 70; + let mut root = div().id("root").size_full().flex().flex_wrap(); + for i in 0..self.cells { + let mut cell = div().w(px(10.0)).h(px(10.0)); + if self.listen { + cell = cell + .on_click(|_, _, _| { HEARD.fetch_add(1, Relaxed); }) + .on_mouse_move(|_, _, _| { HEARD.fetch_add(1, Relaxed); }) + .on_hover(|_, _, _| { HEARD.fetch_add(1, Relaxed); }); + } + // a few levels around it, as real views nest + let mut el = cell; + for _ in 0..self.depth { + el = div().child(el); + } + root = root.child(el); + let _ = (i, cols); + } + root + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +fn run(label: &str, cells: usize, listen: bool, depth: usize) { + Application::headless().run(move |cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(700.0), px(600.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, move |_, cx| cx.new(|_| Grid { cells, listen, depth })).unwrap().id; + cx.draw(w); + cx.draw(w); + let (mut mv, mut click) = (Vec::new(), Vec::new()); + for round in 0..5 { + // pointer moves across the grid: every one enters another box + let t = Instant::now(); + let n = 400; + for k in 0..n { + let x = 5.0 + ((k * 13 + round) % 690) as f32; + let y = 5.0 + ((k * 7) % 590) as f32; + cx.simulate_mouse_move(w, x, y); + } + mv.push(t.elapsed().as_secs_f64() * 1e6 / n as f64); + let t = Instant::now(); + let n = 100; + for k in 0..n { + cx.simulate_click(w, 5.0 + (k % 690) as f32, 5.0 + (k % 590) as f32); + } + click.push(t.elapsed().as_secs_f64() * 1e6 / n as f64); + } + println!("{label:<34} move {:>8.1} us click {:>8.1} us", median(mv), median(click)); + }); +} + +fn main() { + run(" 10 boxes, none listen", 10, false, 1); + run(" 500 boxes, all listen, depth 1", 500, true, 1); + run(" 3000 boxes, none listen, depth 1", 3000, false, 1); + run(" 3000 boxes, all listen, depth 1", 3000, true, 1); + run(" 3000 boxes, all listen, depth 6", 3000, true, 6); + println!("(heard {})", HEARD.load(Relaxed)); +} diff --git a/bindings/rust/blenderui/src/a11y.rs b/bindings/rust/blenderui/src/a11y.rs index c3041cba..026a0afb 100644 --- a/bindings/rust/blenderui/src/a11y.rs +++ b/bindings/rust/blenderui/src/a11y.rs @@ -323,7 +323,7 @@ impl Accessibility { | Role::Tab | Role::MenuItem | Role::MenuItemCheckBox | Role::MenuItemRadio | Role::Summary | Role::ListBoxOption | Role::TreeItem | Role::Slider | Role::SpinButton | Role::TextInput | Role::ComboBox | Role::SearchInput | Role::MultilineTextInput); - let clicks = f.el(i).and_then(|e| e.listeners.as_deref()).is_some_and(|l| !l.click.is_empty()); + let clicks = f.el(i).and_then(|e| e.listeners.as_deref()).is_some_and(|l| l.hears(crate::events::EventKind::Click.bit())); if interactive || clicks || attr("tabindex").is_some_and(|t| t.trim() != "-1") { s |= flags::FOCUSABLE; } diff --git a/bindings/rust/blenderui/src/anim.rs b/bindings/rust/blenderui/src/anim.rs index f80cb573..0ad53dfb 100644 --- a/bindings/rust/blenderui/src/anim.rs +++ b/bindings/rust/blenderui/src/anim.rs @@ -1676,6 +1676,9 @@ impl Animations { if faded { crate::layout::inherit_at(nodes, styles, (0..dirty.len()).filter(|&j| dirty[j])); } + if moved { + frame.moved(); + } self.running = running; Some((std::mem::take(dirty), running)) } diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs index ad2369b6..865e3dec 100644 --- a/bindings/rust/blenderui/src/element.rs +++ b/bindings/rust/blenderui/src/element.rs @@ -16,8 +16,28 @@ pub type SharedString = Cow<'static, str>; /// state across renders. pub type ElementId = SharedString; -/// An event listener, owned by its element (moved into the frame, never shared). -pub(crate) type Listener = Box; +/// One listener: the event it hears, in which pass, and whether it hears the whole window. Owned by its +/// element (moved into the frame, never shared); the closure takes any event type and does nothing +/// with the others, so one list holds every kind of listener. +pub(crate) struct Entry { + pub kind: EventKind, + /// Heard on the way down (the capture pass) rather than on the way up. + pub capture: bool, + /// Hears every event of its kind in the window, wherever it happens (gpui's `on_mouse_event`). + pub wide: bool, + pub call: EntryFn, +} + +/// What an [`Entry`] calls: the event (of any type: the closure picks its own), the pass, the window and the app. +pub(crate) type EntryFn = Box; + +/// The listeners of an element, in the order they were added. +#[derive(Default)] +pub(crate) struct Listeners { + pub entries: Vec, + /// The kinds among `entries` (bits of `EventKind::bit`): a window skips the walk for the rest. + pub kinds: u64, +} /// Work an element postpones until the window can lend itself: it receives /// the window and app and finishes the element (children, styles) in place. @@ -50,27 +70,62 @@ pub(crate) fn resolve_deferred(el: &mut AnyElement, window: &mut Window, app: &m /// Custom painting (gpui's `canvas()` element). pub(crate) type PaintFn = Box, &mut crate::paint::Painter, &App)>; -#[derive(Default)] -pub(crate) struct Listeners { - pub click: Vec>, - pub mouse_down: Vec<(Option, Listener)>, - pub mouse_up: Vec<(Option, Listener)>, - 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>, - pub input: Vec>, +/// The window-wide listeners' event types: which kind each one is. +pub trait WindowEvent: 'static { + const KIND: EventKind; +} +impl WindowEvent for MouseDownEvent { + const KIND: EventKind = EventKind::MouseDown; +} +impl WindowEvent for MouseUpEvent { + const KIND: EventKind = EventKind::MouseUp; +} +impl WindowEvent for MouseMoveEvent { + const KIND: EventKind = EventKind::MouseMove; +} +impl WindowEvent for ScrollWheelEvent { + const KIND: EventKind = EventKind::Wheel; +} +impl WindowEvent for KeyDownEvent { + const KIND: EventKind = EventKind::KeyDown; +} +impl WindowEvent for KeyUpEvent { + const KIND: EventKind = EventKind::KeyUp; +} +impl WindowEvent for PanEvent { + const KIND: EventKind = EventKind::Pan; +} +impl WindowEvent for PinchEvent { + const KIND: EventKind = EventKind::Pinch; +} +impl WindowEvent for RotateEvent { + const KIND: EventKind = EventKind::Rotate; +} + +/// `on_x` and `on_x_capture` for each `name, capture_name => Kind, EventType` line. +macro_rules! listeners { + ($( $(#[$doc:meta])* $name:ident, $capture:ident => $kind:ident, $event:ty; )*) => {$( + $(#[$doc])* + pub fn $name(self, f: impl Fn(&$event, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::$kind, false, f) + } + $(#[$doc])* + /// (The capture pass: from the root down to the target.) + pub fn $capture(self, f: impl Fn(&$event, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::$kind, true, f) + } + )*}; } impl Listeners { /// A press on the element does something: it is the app's, even inside a drag area. pub(crate) fn take_presses(&self) -> bool { - !(self.click.is_empty() && self.mouse_down.is_empty() && self.mouse_up.is_empty()) + self.hears(EventKind::PRESSES) + } + + /// The element itself (not a window-wide listener of it) hears one of the kinds in `mask` (`bit`s). + pub(crate) fn hears(&self, mask: u64) -> bool { + self.kinds & mask != 0 && self.entries.iter().any(|e| !e.wide && e.kind.bit() & mask != 0) } } @@ -342,74 +397,176 @@ impl Div { } // -- events ---------------------------------------------------------------------------- - /// Click (press and release on this element); bubbles to ancestors. - pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().click.push(Box::new(f)); - self - } - pub fn on_mouse_down(mut self, button: MouseButton, - f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_down.push((Some(button), Box::new(f))); + // + // HTML's `on*` events, one method each (`onClick` is `.on_click`, in `rsx!` too), and `_capture` for + // the pass that runs from the root down to the target before the usual one back up (`onClickCapture`). + // A listener gets the event, the window and the app; `window.stop_propagation()` ends the pass. + + fn listen(mut self, kind: EventKind, capture: bool, + f: impl Fn(&E, &mut Window, &mut App) + 'static) -> Self { + self.push_entry(Entry { + kind, + capture, + wide: false, + call: Box::new(move |e, _, w, a| { + if let Some(e) = e.downcast_ref::() { + f(e, w, a); + } + }), + }); self } - pub fn on_any_mouse_down(mut self, - f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_down.push((None, Box::new(f))); - self - } - pub fn on_mouse_up(mut self, button: MouseButton, - f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_up.push((Some(button), Box::new(f))); - self - } - pub fn on_mouse_move(mut self, - f: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_move.push(Box::new(f)); - self - } - /// Called with `true` when the pointer enters, `false` when it leaves. - pub fn on_hover(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().hover.push(Box::new(f)); - self - } - pub fn on_scroll_wheel(mut self, - f: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().scroll.push(Box::new(f)); - self + + fn push_entry(&mut self, entry: Entry) { + let ls = self.listeners_mut(); + ls.kinds |= entry.kind.bit(); + ls.entries.push(entry); } - /// 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 + + /// Hears every event of its kind in the window, whatever element it happens on, in both passes: a + /// drag that leaves its element keeps hearing the moves and the release (gpui's `on_mouse_event`). + /// `E` is the event the listener takes: `MouseMoveEvent`, `MouseDownEvent`, `MouseUpEvent`, + /// `ScrollWheelEvent`, `PanEvent`, `PinchEvent`, `RotateEvent`, `KeyDownEvent` or `KeyUpEvent`. + pub fn on_mouse_event(self, f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.on_window_event(E::KIND, f) } - /// 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 + + /// [`on_mouse_event`](Self::on_mouse_event) for the keyboard. + pub fn on_key_event(self, f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.on_window_event(E::KIND, f) } - /// 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)); + + /// The window-wide listener of any event kind and type (the pointer events take this form). + pub fn on_window_event(mut self, kind: EventKind, + f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.push_entry(Entry { + kind, + capture: false, + wide: true, + call: Box::new(move |e, phase, w, a| { + if let Some(e) = e.downcast_ref::() { + f(e, phase, w, a); + } + }), + }); 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 + + /// Press with `button` (and the capture pass of it). + pub fn on_mouse_down(self, button: MouseButton, + f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, false, move |e: &MouseDownEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - pub fn on_key_up(mut self, f: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().key_up.push(Box::new(f)); - self + pub fn on_mouse_down_capture(self, button: MouseButton, + f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, true, move |e: &MouseDownEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - /// Form controls: the committed value changed (`change` in HTML). - pub fn on_change(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().change.push(Box::new(f)); - self + pub fn on_mouse_up(self, button: MouseButton, + f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseUp, false, move |e: &MouseUpEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - /// Form controls: every edit (`input` in HTML). - pub fn on_input(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().input.push(Box::new(f)); - self + pub fn on_mouse_up_capture(self, button: MouseButton, + f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseUp, true, move |e: &MouseUpEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) + } + /// Press with any button (`mousedown`). + pub fn on_any_mouse_down(self, f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, false, f) + } + + /// Called with `true` when the pointer enters, `false` when it leaves (does not bubble). + pub fn on_hover(self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::Hover, false, f) + } + + listeners! { + /// `click`: press and release on this element; bubbles. + on_click, on_click_capture => Click, ClickEvent; + /// `dblclick` + on_double_click, on_double_click_capture => DoubleClick, ClickEvent; + /// `auxclick`: a click with a button other than the main one. + on_aux_click, on_aux_click_capture => AuxClick, ClickEvent; + /// `contextmenu` + on_context_menu, on_context_menu_capture => ContextMenu, ContextMenuEvent; + /// `mousemove` + on_mouse_move, on_mouse_move_capture => MouseMove, MouseMoveEvent; + /// `mouseenter`: this element only (no bubbling, and its children don't count as leaving). + on_mouse_enter, on_mouse_enter_capture => MouseEnter, MouseMoveEvent; + /// `mouseleave` + on_mouse_leave, on_mouse_leave_capture => MouseLeave, MouseMoveEvent; + /// `mouseover`: bubbles, also from the children. + on_mouse_over, on_mouse_over_capture => MouseOver, MouseMoveEvent; + /// `mouseout` + on_mouse_out, on_mouse_out_capture => MouseOut, MouseMoveEvent; + /// `wheel` + on_scroll_wheel, on_scroll_wheel_capture => Wheel, ScrollWheelEvent; + /// `wheel` (HTML's name for `on_scroll_wheel`) + on_wheel, on_wheel_capture => Wheel, ScrollWheelEvent; + /// A finger dragging the content (a touch scroll and its fling), before it scrolls: stop the + /// propagation to take it (see [`PanEvent`]). + on_pan, on_pan_capture => Pan, PanEvent; + /// Two fingers spreading or closing, or a trackpad pinch (see [`PinchEvent`]). + on_pinch, on_pinch_capture => Pinch, PinchEvent; + /// Two fingers turning, or a trackpad turn (see [`RotateEvent`]). + on_rotate, on_rotate_capture => Rotate, RotateEvent; + /// `pointerdown` + on_pointer_down, on_pointer_down_capture => PointerDown, PointerEvent; + /// `pointerup` + on_pointer_up, on_pointer_up_capture => PointerUp, PointerEvent; + /// `pointermove` + on_pointer_move, on_pointer_move_capture => PointerMove, PointerEvent; + /// `pointerenter` (no bubbling) + on_pointer_enter, on_pointer_enter_capture => PointerEnter, PointerEvent; + /// `pointerleave` + on_pointer_leave, on_pointer_leave_capture => PointerLeave, PointerEvent; + /// `pointerover` + on_pointer_over, on_pointer_over_capture => PointerOver, PointerEvent; + /// `pointerout` + on_pointer_out, on_pointer_out_capture => PointerOut, PointerEvent; + /// `pointercancel` + on_pointer_cancel, on_pointer_cancel_capture => PointerCancel, PointerEvent; + /// `gotpointercapture`: `Window::set_pointer_capture` took the pointer for this element. + on_got_pointer_capture, on_got_pointer_capture_capture => GotPointerCapture, PointerEvent; + /// `lostpointercapture` + on_lost_pointer_capture, on_lost_pointer_capture_capture => LostPointerCapture, PointerEvent; + /// `keydown`: goes to the focused element. + on_key_down, on_key_down_capture => KeyDown, KeyDownEvent; + /// `keypress`: after `keydown`, for a key that types a character. + on_key_press, on_key_press_capture => KeyPress, KeyPressEvent; + /// `keyup` + on_key_up, on_key_up_capture => KeyUp, KeyUpEvent; + /// `focus` (no bubbling) + on_focus, on_focus_capture => Focus, FocusEvent; + /// `blur` (no bubbling) + on_blur, on_blur_capture => Blur, FocusEvent; + /// `focusin`: like `focus`, and it bubbles. + on_focus_in, on_focus_in_capture => FocusIn, FocusEvent; + /// `focusout` + on_focus_out, on_focus_out_capture => FocusOut, FocusEvent; + /// Blender's press-drag: a button is held and the pointer moved past the drag threshold (once per press). + on_press_drag, on_press_drag_capture => PressDrag, PressDragEvent; + /// `scroll`: this element's scroll position changed (no bubbling). + on_scroll, on_scroll_capture => Scroll, ScrollEvent; + /// Form controls: the committed value changed (`change` in HTML). + on_change, on_change_capture => Change, ChangeEvent; + /// Form controls: every edit (`input` in HTML). + on_input, on_input_capture => Input, ChangeEvent; } // -- state styles (gpui's .hover(|s| ...), CSS :hover / :active / :focus) ---------------- diff --git a/bindings/rust/blenderui/src/events.rs b/bindings/rust/blenderui/src/events.rs index 3cf1d1be..b5ecc5f5 100644 --- a/bindings/rust/blenderui/src/events.rs +++ b/bindings/rust/blenderui/src/events.rs @@ -177,6 +177,9 @@ pub struct KeyUpEvent { pub keystroke: Keystroke, } +/// `keypress`: a key that types a character (the event is a [`KeyDownEvent`] too: HTML's `KeyboardEvent`). +pub type KeyPressEvent = KeyDownEvent; + /// A form control's value (`input`, `select`, `textarea` ...). #[derive(Clone, Debug, Default)] pub struct ChangeEvent { @@ -187,3 +190,208 @@ pub struct ChangeEvent { /// Numbers, ranges and selects (the selected index). pub number: f64, } + +/// HTML's two passes over the elements an event goes through: down from the root to the target +/// (`Capture`), then back up (`Bubble`). A listener of the whole window hears both. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DispatchPhase { + Capture, + Bubble, +} + +impl DispatchPhase { + #[must_use] + pub const fn bubble(self) -> bool { + matches!(self, Self::Bubble) + } + + #[must_use] + pub const fn capture(self) -> bool { + matches!(self, Self::Capture) + } +} + +/// Which event a listener hears: HTML's `on*` attributes, one for one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum EventKind { + // mouse + Click, + DoubleClick, + AuxClick, + ContextMenu, + MouseDown, + MouseUp, + MouseMove, + MouseEnter, + MouseLeave, + MouseOver, + MouseOut, + Wheel, + // touch and trackpad gestures (Blender's MOUSEPAN, MOUSEZOOM, MOUSEROTATE) + Pan, + Pinch, + Rotate, + // pointer + PointerDown, + PointerUp, + PointerMove, + PointerEnter, + PointerLeave, + PointerOver, + PointerOut, + PointerCancel, + GotPointerCapture, + LostPointerCapture, + // keyboard + KeyDown, + KeyPress, + KeyUp, + // focus + Focus, + Blur, + FocusIn, + FocusOut, + // Blender's press-drag (`KM_PRESS_DRAG`) + PressDrag, + // the rest + Scroll, + Hover, + Change, + Input, +} + +impl EventKind { + /// Whether it goes up to the ancestors after the target (`mouseenter`, `focus`, `scroll` ... don't). + #[must_use] + pub const fn bubbles(self) -> bool { + !matches!( + self, + Self::MouseEnter | Self::MouseLeave | Self::PointerEnter | Self::PointerLeave | Self::Focus | Self::Blur + | Self::Scroll | Self::Hover | Self::GotPointerCapture | Self::LostPointerCapture + ) + } + + pub(crate) const fn bit(self) -> u64 { + 1 << self as u8 + } + + /// The kinds a press on an element fires (`bit`s). + pub(crate) const PRESSES: u64 = Self::Click.bit() | Self::DoubleClick.bit() | Self::AuxClick.bit() + | Self::ContextMenu.bit() | Self::MouseDown.bit() | Self::MouseUp.bit() | Self::PointerDown.bit() + | Self::PointerUp.bit() | Self::PressDrag.bit(); +} + +/// Who a pointer is (HTML's `pointerType`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PointerType { + Mouse, + Pen, + Touch, +} + +/// HTML's `PointerEvent`: what `pointerdown`, `pointermove`, `pointerup`, `pointerenter`, `pointerleave`, +/// `pointerover`, `pointerout`, `pointercancel` and the capture events carry. The mouse is pointer 1. +#[derive(Clone, Debug)] +pub struct PointerEvent { + pub pointer_id: i32, + pub pointer_type: PointerType, + pub is_primary: bool, + /// The button that changed (`None` for moves and the like). + pub button: Option, + /// The buttons held, as the DOM's `buttons` bits: 1 left, 2 right, 4 middle. + pub buttons: u8, + pub position: Point, + pub modifiers: Modifiers, + /// 0.5 while a button is held, else 0 (a mouse has no pressure of its own). + pub pressure: f32, + pub click_count: usize, +} + +impl PointerEvent { + pub(crate) fn mouse(position: Point, button: Option, held: Option, + modifiers: Modifiers, click_count: usize) -> Self { + let bits = |b: MouseButton| match b { + MouseButton::Left => 1, + MouseButton::Right => 2, + MouseButton::Middle => 4, + }; + Self { + pointer_id: 1, + pointer_type: PointerType::Mouse, + is_primary: true, + button, + buttons: held.map_or(0, bits), + position, + modifiers, + pressure: if held.is_some() { 0.5 } else { 0.0 }, + click_count, + } + } +} + +/// `contextmenu`: the secondary button (or the menu key) asked for a context menu. +#[derive(Clone, Debug)] +pub struct ContextMenuEvent { + pub position: Point, + pub modifiers: Modifiers, +} + +/// `focus`, `blur`, `focusin` and `focusout`. +#[derive(Clone, Copy, Debug, Default)] +pub struct FocusEvent; + +/// `scroll`: a scroll container moved. +#[derive(Clone, Debug)] +pub struct ScrollEvent { + /// Where its content is scrolled to (from the top left). + pub offset: Point, +} + +/// The eight directions of a drag (Blender's `KM_DIRECTION_*`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DragDirection { + East, + NorthEast, + North, + NorthWest, + West, + SouthWest, + South, + SouthEast, +} + +impl DragDirection { + /// The direction of the move from `from` to `to` (y grows downward), as `WM_event_drag_direction` rounds it: + /// to the nearest of eight. + #[must_use] + pub fn of(from: Point, to: Point) -> Self { + let (dx, dy) = (to.x.0 - from.x.0, from.y.0 - to.y.0); // up is positive, as in Blender + match (4.0 * dy.atan2(dx) / std::f32::consts::PI).round() as i32 { + 0 => Self::East, + 1 => Self::NorthEast, + 2 => Self::North, + 3 => Self::NorthWest, + -1 => Self::SouthEast, + -2 => Self::South, + -3 => Self::SouthWest, + _ => Self::West, + } + } +} + +/// Blender's press-drag (`KM_PRESS_DRAG`, "click-drag"): a button is held and the pointer has moved past the +/// drag threshold ([`DRAG_THRESHOLD`] pixels). It comes once per press, from the first move past it. +#[derive(Clone, Debug)] +pub struct PressDragEvent { + pub button: MouseButton, + /// Where the button was pressed. + pub start: Point, + pub position: Point, + pub modifiers: Modifiers, + pub direction: DragDirection, +} + +/// How far (logical pixels, either way) a held pointer moves before it is a drag: Blender's +/// `U.drag_threshold_mouse` (3). +pub const DRAG_THRESHOLD: f32 = 3.0; diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs index 49619ebb..d6420948 100644 --- a/bindings/rust/blenderui/src/layout.rs +++ b/bindings/rust/blenderui/src/layout.rs @@ -57,6 +57,9 @@ fn child_key(parent: Key, tag: &str, n: usize) -> Key { hash_parts(&[&parent.to_le_bytes(), tag.as_bytes(), &(n as u64).to_le_bytes()]) } +/// Boxes from the root down to one: an event's path (no allocation for a tree this deep). +pub(crate) type Path = smallvec::SmallVec<[usize; 16]>; + /// The key of the `` element. pub(crate) const ROOT_KEY: Key = 0x68746d6c; // "html" @@ -345,8 +348,47 @@ pub(crate) struct BoxNode { pub(crate) struct Frame { pub nodes: Vec, els: Vec, + /// The kinds of event something in this frame listens for (bits of `EventKind::bit`). + pub listen: u64, + /// The boxes with a listener that hears the whole window, in document order (usually none). + pub wide: Vec, pub title: Option, by_key: std::cell::OnceCell>, + /// Where each box's subtree is, for the pointer's hit test (built on the first one; dropped when + /// boxes move: [`moved`](Frame::moved)). + hit_index: std::cell::OnceCell, +} + +/// For every box: the end of its subtree in the arena (boxes come parents first, a subtree is the run +/// after its root), and the rectangle holding the boxes in it. A hit test skips a whole subtree its point +/// is not in. `None` when the arena is not laid out that way (the hit test scans every box then). +struct HitIndex(Option<(Vec, Vec>)>); + +impl HitIndex { + fn build(nodes: &[BoxNode]) -> Self { + let n = nodes.len(); + let mut end: Vec = (1..=n as u32).collect(); + let mut descendants = vec![0u32; n]; + let mut area: Vec> = nodes.iter().map(|b| b.bounds).collect(); + for j in (0..n).rev() { + let Some(p) = nodes[j].parent else { continue }; + if p >= j { + return Self(None); + } + end[p] = end[p].max(end[j]); + descendants[p] += 1 + descendants[j]; + let (a, b) = (area[p], area[j]); + let (x0, y0) = (a.origin.x.min(b.origin.x), a.origin.y.min(b.origin.y)); + let (x1, y1) = ((a.origin.x + a.size.width).max(b.origin.x + b.size.width), + (a.origin.y + a.size.height).max(b.origin.y + b.size.height)); + area[p] = rect(x0, y0, x1 - x0, y1 - y0); + } + // a subtree is the run after its root: nothing else in it + if (0..n).any(|i| end[i] - i as u32 - 1 != descendants[i]) { + return Self(None); + } + Self(Some((end, area))) + } } /// Measure contexts of taffy leaves. Compared across frames: an unchanged @@ -2861,9 +2903,10 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca caches.shapes.clear(); caches.styles_limit = (caches.taffy.style_count() * 2).max(STYLES_MAX); } - let Frame { mut nodes, mut els, .. } = recycle; + let Frame { mut nodes, mut els, mut wide, .. } = recycle; nodes.clear(); els.clear(); + wide.clear(); if caches.matched.author != caches.author.hash || caches.matched.map.len() > 50_000 { caches.matched.map.clear(); caches.matched.author = caches.author.hash; @@ -2986,7 +3029,15 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca } drop(s); let _s = span(Phase::Place); - let mut frame = Frame { nodes, els, title, by_key: Default::default() }; + let (listen, any_wide) = els.iter().filter_map(|e| e.listeners.as_deref()) + .fold((0, false), |(m, w), l| (m | l.kinds, w || l.entries.iter().any(|en| en.wide))); + if any_wide { + wide.extend((0..nodes.len() as u32).filter(|&i| { + let e = nodes[i as usize].el; + e != NONE && els[e as usize].listeners.as_deref().is_some_and(|l| l.entries.iter().any(|en| en.wide)) + })); + } + let mut frame = Frame { nodes, els, listen, wide, title, by_key: Default::default(), hit_index: Default::default() }; box_of.clear(); for (i, n) in frame.nodes.iter().enumerate() { if let Some(t) = n.taffy { @@ -3060,6 +3111,7 @@ pub(crate) fn replace(frame: &mut Frame, viewport: (f32, f32), state: &UiState, port: rect(0.0, 0.0, viewport.0, viewport.1), within: rect(0.0, 0.0, viewport.0, viewport.1) }; walk.place(&mut frame.nodes, root, 0.0, 0.0, None, (0.0, 0.0)); finish(&mut frame.nodes, styles, acc); + frame.moved(); true } @@ -3386,15 +3438,32 @@ impl Frame { } } + /// The boxes moved (a redraw, a scroll): the hit test's index of where they are is stale. + pub(crate) fn moved(&mut self) { + self.hit_index.take(); + } + /// Element boxes from the root down to the topmost box under (x, y). - pub(crate) fn hit_path(&self, x: f32, y: f32, styles: &StyleStore) -> Vec { + pub(crate) fn hit_path(&self, x: f32, y: f32, styles: &StyleStore) -> Path { self.path_to(self.hit_box(x, y, styles)) } /// The topmost box under (x, y): a word, a text run, an element ... pub(crate) fn hit_box(&self, x: f32, y: f32, styles: &StyleStore) -> Option { let mut best: Option<(i32, usize)> = None; - for (i, n) in self.nodes.iter().enumerate() { + let nodes = &self.nodes; + let index = self.hit_index.get_or_init(|| HitIndex::build(nodes)).0.as_ref(); + let mut next = 0; + while next < nodes.len() { + let (i, n) = (next, &nodes[next]); + next += 1; + // a box that is hidden, clipped away or has the point outside everything under it: its whole + // subtree is out (a clip only narrows what is under a box; visibility is inherited) + if let Some((end, area)) = index + && (!n.visible || n.clip.is_some_and(|c| !c.contains(x, y)) || !area[i].contains(x, y)) { + next = end[i] as usize; + continue; + } if !n.visible || n.taffy.is_none() || !styles[n.style].pointer_events { continue; } @@ -3411,8 +3480,8 @@ impl Frame { } /// The element boxes from the root down to the element that box `hit` belongs to. - pub(crate) fn path_to(&self, hit: Option) -> Vec { - let mut path = Vec::new(); + pub(crate) fn path_to(&self, hit: Option) -> Path { + let mut path = Path::new(); let mut cur = hit.map(|b| self.nodes[b].owner); while let Some(i) = cur { if self.nodes[i].el != NONE { diff --git a/bindings/rust/blenderui/src/motion/element.rs b/bindings/rust/blenderui/src/motion/element.rs index 23fadfa6..ed434fa9 100644 --- a/bindings/rust/blenderui/src/motion/element.rs +++ b/bindings/rust/blenderui/src/motion/element.rs @@ -734,6 +734,7 @@ impl Elements { } } self.clear_shift(); + frame.moved(); } // a moved clip: the frame is placed again first, and the states follow that placement Some(!(reclip || self.reclip) && self.in_view(frame, viewport)) diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index faa0f7b1..0b2ef3b8 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -13,10 +13,10 @@ use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; -use crate::element::{AnyElement, IntoElement, Listener, Listeners, SharedString}; +use crate::element::{AnyElement, IntoElement, Listeners, SharedString}; use crate::events::*; use crate::geometry::{point, px, size, Bounds, Pixels, Size}; -use crate::layout::{id_key, layout, Content, Frame, Key, LayoutCaches, UiState}; +use crate::layout::{id_key, layout, Content, Frame, Key, LayoutCaches, UiState, ROOT_KEY}; use crate::prof::{self, span, Phase}; use crate::style::AppRegion; use crate::window_kind::{WindowControlArea, WindowDecorations, WindowKind}; @@ -188,14 +188,7 @@ impl WindowHandle { /// Update the root view with its window. pub fn update(&self, cx: &mut App, f: impl FnOnce(&mut V, &mut Window, &mut Context) -> R) -> Option { - let notified = cx.notified; - cx.with_window(self.id.0, |w, cx| { - let r = self.entity.update(cx, |v, cx| f(v, w, cx)); - if cx.notified != notified { - w.refresh(); // `cx.notify()` ran while this window was out of the list - } - r - }) + cx.with_window(self.id.0, |w, cx| self.entity.update(cx, |v, cx| f(v, w, cx))) } } @@ -735,7 +728,12 @@ impl App { fn with_window(&mut self, id: usize, f: impl FnOnce(&mut Window, &mut App) -> R) -> Option { let mut w = self.windows.get_mut(id)?.take()?; + let notified = self.notified; let r = f(&mut w, self); + // the window is out of the list while it runs: a `notify` in what it called missed it + if self.notified != notified { + w.refresh(); + } // closed by the app (`remove_window`): its close hooks, now that it is back let closing = w.life == Life::Closing; if closing { @@ -1044,6 +1042,24 @@ impl App { }); } + /// Click with the middle or the secondary button at (x, y) (as a window sends it: the secondary + /// button's click arrives as its release alone). The left button is [`simulate_click`](Self::simulate_click). + pub fn simulate_button(&mut self, window: WindowId, x: f32, y: f32, button: MouseButton) { + let code = match button { + MouseButton::Left => return self.simulate_click(window, x, y), + MouseButton::Middle => 2, + MouseButton::Right => 3, + }; + self.simulate_mouse_move(window, x, y); + self.input(window, |ctx, s| unsafe { + let (x, y) = ((x * s) as c_int, (y * s) as c_int); + if button == MouseButton::Middle { + sys::BK_button(ctx, x, y, code, 0, 0); + } + sys::BK_button(ctx, x, y, code, 1, 0); + }); + } + /// Press at `from`, drag to `to` and release there. pub fn simulate_drag(&mut self, window: WindowId, from: (f32, f32), to: (f32, f32)) { self.simulate_mouse_move(window, from.0, from.1); @@ -1321,6 +1337,10 @@ struct Glide { duration: f32, } +/// `Window::state_read` bits: the view read the hover (`is_hovered`) or the focus (`focused_id`). +const READ_HOVER: u8 = 1; +const READ_FOCUS: u8 = 2; + /// A window (gpui's `Window`): its kit context, layout and interaction state. pub struct Window { id: usize, @@ -1383,6 +1403,28 @@ pub struct Window { pointer: (f32, f32), pressed: Vec, press_button: MouseButton, + /// How many presses in a row the last one was (a double click's second is 2). + press_count: usize, + /// Where the button went down, and whether its press-drag has come (Blender's `KM_PRESS_DRAG`, once per press). + press_start: (f32, f32), + press_drag_sent: bool, + /// The element that holds the pointer (HTML's pointer capture): while one does, the pointer's events go + /// to it, wherever the pointer is. + capture: Option, + /// The element whose listener is running (what [`Window::set_pointer_capture`] holds the pointer for). + current: Option, + /// The elements under the pointer, outermost first: the order of what it enters and leaves. + hover_path: Vec, + /// Scratch for the hit test of a pointer move (kept so a move allocates nothing). + path_buf: Vec, + /// Capture events raised by a listener: fired when the event it is in has gone through (the frame is + /// lent to that one meanwhile). + later: Vec<(EventKind, Key, PointerEvent)>, + /// The interaction states the view read while it rendered (`READ_HOVER`: `is_hovered`, `READ_FOCUS`: + /// `focused_id`): it renders again when they change, as it does for a style that depends on them. + state_read: Cell, + /// Where each scroll container was when its `scroll` event last went out (a scroll from any source). + scroll_seen: HashMap, /// A scrollbar thumb being dragged: the container and where on the thumb it was grabbed. sb_drag: Option<(Key, f32)>, /// `data-stick="bottom"` containers: the scroll range last frame (to see when content grew). @@ -1471,6 +1513,16 @@ impl Window { pointer: (-1.0, -1.0), pressed: Vec::new(), press_button: MouseButton::Left, + press_count: 1, + press_start: (0.0, 0.0), + press_drag_sent: false, + capture: None, + current: None, + hover_path: Vec::new(), + path_buf: Vec::new(), + later: Vec::new(), + state_read: Cell::new(0), + scroll_seen: HashMap::new(), sb_drag: None, stuck: HashMap::new(), selector: Selector::default(), @@ -1733,6 +1785,7 @@ impl Window { /// The `.id()` of the focused element, if any. pub fn focused_id(&self) -> Option<&str> { + self.state_read.set(self.state_read.get() | READ_FOCUS); self.state.focused_id.as_deref() } @@ -1740,16 +1793,11 @@ impl Window { /// Its ancestors in the last frame are within focus (`:focus-within`), as a press makes them. pub fn focus_id(&mut self, id: &str) { let key = id_key(id); - let mut path = vec![key]; - if let Some(f) = self.frame.as_ref() { - let mut at = f.by_key().get(&key).and_then(|&i| f.nodes[i].parent); - while let Some(p) = at { - path.push(f.nodes[p].key); - at = f.nodes[p].parent; - } + let mut path = self.path_to_key(key); + if path.is_empty() { + path.push(key); // not drawn yet } - path.reverse(); - self.set_focus(&path); + self.focus_path(&path); self.state.focused_id = Some(id.to_owned()); self.dirty = true; } @@ -1765,6 +1813,7 @@ impl Window { /// Is the element with `.id(id)` hovered? pub fn is_hovered(&self, id: &str) -> bool { + self.state_read.set(self.state_read.get() | READ_HOVER); self.state.hovered.contains(&id_key(id)) } @@ -1939,7 +1988,7 @@ impl Window { fn press_is_quiet(&self, path: &[Key]) -> bool { let Some(f) = &self.frame else { return false }; let plain = |k: &Key| f.by_key().get(k).and_then(|&i| f.el(i)).is_none_or(|e| !e.reactive); - !self.caches.state_rules && path.iter().all(plain) && self.state.focused.as_ref().is_none_or(plain) + !self.caches.state_rules && self.state_read.get() & READ_FOCUS == 0 && path.iter().all(plain) && self.state.focused.as_ref().is_none_or(plain) } fn select_press(&mut self, x: f32, y: f32, shift: bool) -> bool { @@ -1996,6 +2045,7 @@ impl Window { self.dirty = false; self.scrolled = false; self.scroll_read.set(false); + self.state_read.set(0); let root = { let _s = span(Phase::Render); crate::hooks::begin(self.id); @@ -2059,6 +2109,7 @@ impl Window { // container sticks to its end (animations follow it: see scroll_frame) self.scroll_free = !sticks && !self.scroll_read.get(); self.present(app, frame, None); + self.forget_removed(app); if stuck { self.dirty = true; } @@ -2328,7 +2379,9 @@ impl Window { #[cfg(feature = "a11y")] self.publish_a11y(&frame); self.frame = Some(frame); + // what the layout moved under a pointer that stayed still is entered or left self.update_hover(app, false); + self.fire_scrolls(app); drop(_rest); prof::frame_done(); } @@ -2362,58 +2415,156 @@ impl Window { f.hit_path(x, y, &self.caches.styles).into_iter().map(|i| f.nodes[i].key).collect() } - /// Call the listeners `pick` selects, from element `key` up to the root. - /// The frame is moved out of the window meanwhile, so listeners can take - /// `&mut Window` while the frame lends them out: no copies, no `Rc`. /// The element the event its listeners are running for fired on (`None` outside one). pub(crate) fn event_target(&self) -> Option { 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>) -> bool { + /// Deliver `e` of `kind` to element `target` as HTML does: down from the root to it (the capture pass), + /// then back up (the bubbling pass, when `kind` bubbles), with the window-wide listeners heard before and + /// after both. A listener that calls `stop_propagation` ends the pass it is in. The frame is moved out + /// of the window meanwhile, so listeners can take `&mut Window` while the frame lends them out: no + /// copies, no `Rc` (the bounds of the event's path stay readable: `bounds_of`). True when a listener + /// stopped the propagation (it took the event). + fn fire(&mut self, app: &mut App, kind: EventKind, target: Key, e: &E) -> bool { let Some(frame) = self.frame.take() else { return false }; + if frame.listen & kind.bit() == 0 { + self.frame = Some(frame); + return false; + } app.propagate = true; - let mut cur = frame.by_key().get(&key).copied(); + let entries = |i: usize| frame.el(i).and_then(|el| el.listeners.as_deref()).map(|l| &l.entries[..]); + let path = frame.path_to(frame.by_key().get(&target).copied()); + // reused, so an event allocates nothing once it has grown self.lent_bounds.clear(); - let mut node = cur; - while let Some(i) = node { - self.lent_bounds.push((frame.nodes[i].key, frame.nodes[i].bounds)); - node = frame.nodes[i].parent; - } - 'up: while let Some(i) = cur { - if let Some(ls) = frame.el(i).and_then(|e| e.listeners.as_deref()) { - for l in pick(ls) { - l(e, self, app); + self.lent_bounds.extend(path.iter().rev().map(|&i| (frame.nodes[i].key, frame.nodes[i].bounds))); + let any = e as &dyn Any; + // every element of the window, for the listeners that hear all of it + let wide = |this: &mut Self, app: &mut App, phase: DispatchPhase| { + for &i in &frame.wide { + let i = i as usize; + for en in entries(i).into_iter().flatten().filter(|en| en.wide && en.kind == kind) { + this.current = Some(frame.nodes[i].key); + (en.call)(any, phase, this, app); if !app.propagate { - break 'up; + return; } } } - cur = frame.nodes[i].parent; + }; + wide(self, app, DispatchPhase::Capture); + 'pass: { + if !app.propagate { + break 'pass; + } + for &i in &path { + for en in entries(i).into_iter().flatten().filter(|en| en.capture && !en.wide && en.kind == kind) { + self.current = Some(frame.nodes[i].key); + (en.call)(any, DispatchPhase::Capture, self, app); + if !app.propagate { + break 'pass; + } + } + } + let up = if kind.bubbles() { path.len() } else { path.len().min(1) }; + for &i in path.iter().rev().take(up) { + for en in entries(i).into_iter().flatten().filter(|en| !en.capture && !en.wide && en.kind == kind) { + self.current = Some(frame.nodes[i].key); + (en.call)(any, DispatchPhase::Bubble, self, app); + if !app.propagate { + break 'pass; + } + } + } + wide(self, app, DispatchPhase::Bubble); } let stopped = !app.propagate; app.propagate = true; + self.current = None; self.lent_bounds.clear(); if self.frame.is_none() { self.frame = Some(frame); } + self.fire_later(app); stopped } - /// The element keys under the pointer, and (when the pointer moved: `measure`) whether it is over - /// text that can be selected. - fn hover_target(&mut self, measure: bool) -> (Vec, Option) { - let Some(f) = &self.frame else { return (Vec::new(), Some(false)) }; + /// The capture events that listeners raised, once the event they were in is done. + fn fire_later(&mut self, app: &mut App) { + while self.frame.is_some() && !self.later.is_empty() { + let (kind, key, e) = self.later.remove(0); + self.fire(app, kind, key, &e); + } + } + + /// Hold the pointer for the element whose listener is running (HTML's `setPointerCapture`): its + /// pointer and mouse events go to that element, also after the pointer left it or the window, until the + /// button is released or [`release_pointer_capture`](Self::release_pointer_capture). A drag starts here. + pub fn set_pointer_capture(&mut self, app: &mut App) { + if let Some(key) = self.current { + self.capture_key(app, key); + } + } + + /// [`set_pointer_capture`](Self::set_pointer_capture) for the element `id` (its `.id(..)`), from outside + /// its listener (a binding that learns of the request after the event). + pub fn capture_pointer_for(&mut self, app: &mut App, id: &str) { + self.capture_key(app, id_key(id)); + } + + fn capture_key(&mut self, app: &mut App, key: Key) { + if self.capture != Some(key) { + self.release_pointer_capture(app); + self.capture = Some(key); + let e = self.pointer_event(None, self.held(), 0); + self.later.push((EventKind::GotPointerCapture, key, e)); + self.fire_later(app); + } + } + + /// Let go of the pointer (HTML's `releasePointerCapture`). + pub fn release_pointer_capture(&mut self, app: &mut App) { + if let Some(key) = self.capture.take() { + let e = self.pointer_event(None, self.held(), 0); + self.later.push((EventKind::LostPointerCapture, key, e)); + self.fire_later(app); + } + } + + /// Whether the element `id` (its `.id(..)`) holds the pointer. + #[must_use] + pub fn has_pointer_capture(&self, id: &str) -> bool { + self.capture == Some(id_key(id)) + } + + /// The button held down, if any. + fn held(&self) -> Option { + (!self.pressed.is_empty()).then_some(self.press_button) + } + + /// A pointer event at the pointer's place. + fn pointer_event(&self, button: Option, held: Option, clicks: usize) -> PointerEvent { + PointerEvent::mouse(point(px(self.pointer.0), px(self.pointer.1)), button, held, Modifiers::default(), clicks) + } + + /// Where the pointer's events go: the element that holds it, else the one under it (else the root, + /// which the window-wide listeners hear through). + fn pointer_target(&self) -> Key { + self.capture.or_else(|| self.hover_path.last().copied()).unwrap_or(ROOT_KEY) + } + + /// The element keys under the pointer (into `path`), and (when the pointer moved: `measure`) whether + /// it is over text that can be selected. + fn hover_target(&mut self, measure: bool, path: &mut Vec) -> Option { + path.clear(); + let Some(f) = &self.frame else { return Some(false) }; let (x, y) = self.pointer; let hit = f.hit_box(x, y, &self.caches.styles); - let path = f.path_to(hit).into_iter().map(|i| f.nodes[i].key).collect(); - let over = measure.then(|| hit.is_some_and(|i| { + path.extend(f.path_to(hit).into_iter().map(|i| f.nodes[i].key)); + measure.then(|| hit.is_some_and(|i| { let mut cx = Cx { frame: f, styles: &self.caches.styles, text: &mut self.caches.text }; crate::selection::is_text(&mut cx, i, x, y) - })); - (path, over) + })) } /// The pointer's cursor: that of the deepest element under it that sets one @@ -2433,46 +2584,62 @@ impl Window { } } - fn update_hover(&mut self, app: &mut App, fire: bool) { - let (path, over_text) = self.hover_target(fire); + /// What is under the pointer: its cursor, `:hover`, and the elements it entered and left hear so + /// (`measure`: it moved, so whether it is over text is measured again). + fn update_hover(&mut self, app: &mut App, measure: bool) { + // the elements under the pointer, into a buffer that stays: most moves end where this returns + let mut path = std::mem::take(&mut self.path_buf); + let over_text = self.hover_target(measure, &mut path); self.set_cursor(&path, over_text); - let now: KeySet = path.iter().copied().collect(); - if now == self.state.hovered { + if path == self.hover_path { + self.path_buf = path; return; } - let entered: Vec = now.difference(&self.state.hovered).copied().collect(); - let left: Vec = self.state.hovered.difference(&now).copied().collect(); + let now: KeySet = path.iter().copied().collect(); + let entered: Vec = path.iter().copied().filter(|k| !self.state.hovered.contains(k)).collect(); + let left: Vec = self.hover_path.iter().rev().copied().filter(|k| !now.contains(k)).collect(); + let (old_deepest, new_deepest) = (self.hover_path.last().copied(), path.last().copied()); // a restyle (a render) only where something answers to the pointer: a `:hover` rule in the - // sheet, or a `.hover()` refinement / Motion props on an element it entered or left - let restyle = self.frame.as_ref().is_some_and(|f| { + // sheet, or a `.hover()` refinement / Motion props on an element it entered or left, or a view + // that read `is_hovered` + let restyle = self.state_read.get() & READ_HOVER != 0 || self.frame.as_ref().is_some_and(|f| { entered.iter().chain(&left).any(|k| { f.by_key().get(k).is_some_and(|&i| self.caches.state_rules || f.el(i).is_none_or(|e| e.reactive)) }) }); self.state.hovered = now; - if fire { - // hover listeners don't bubble: each element hears its own enter / leave - for (keys, on) in [(left, false), (entered, true)] { - for k in keys { - let Some(frame) = self.frame.take() else { return }; - let el = frame.by_key().get(&k).and_then(|&i| frame.el(i)); - if let Some(ls) = el.and_then(|e| e.listeners.as_deref()) { - for l in &ls.hover { - l(&on, self, app); - } - } - if self.frame.is_none() { - self.frame = Some(frame); - } - } - } + // the path becomes the hover path; the old one's buffer is the next scratch + self.path_buf = std::mem::replace(&mut self.hover_path, path); + // out, leave, over, enter (HTML's order); enter and leave go to each element on its own, so a + // child doesn't make its parent leave + let held = self.held(); + let pe = self.pointer_event(None, held, 0); + let me = MouseMoveEvent { position: pe.position, pressed_button: held, modifiers: Modifiers::default() }; + if let Some(k) = old_deepest.filter(|_| new_deepest != old_deepest) { + self.fire(app, EventKind::PointerOut, k, &pe); + self.fire(app, EventKind::MouseOut, k, &me); + } + for &k in &left { + self.fire(app, EventKind::PointerLeave, k, &pe); + self.fire(app, EventKind::MouseLeave, k, &me); + self.fire(app, EventKind::Hover, k, &false); + } + if let Some(k) = new_deepest.filter(|_| new_deepest != old_deepest) { + self.fire(app, EventKind::PointerOver, k, &pe); + self.fire(app, EventKind::MouseOver, k, &me); + } + for &k in &entered { + self.fire(app, EventKind::PointerEnter, k, &pe); + self.fire(app, EventKind::MouseEnter, k, &me); + self.fire(app, EventKind::Hover, k, &true); } if restyle { self.dirty = true; } } - fn pointer_event(&self, text: &str) -> (Modifiers, MouseButton) { + /// The modifiers and the button of a pointer event's text. + fn parse_pointer(&self, text: &str) -> (Modifiers, MouseButton) { let mut it = text.split_whitespace().map(|v| v.parse::().unwrap_or(0)); let mods = it.next().unwrap_or(0); let button = match it.next().unwrap_or(1) { @@ -2496,14 +2663,32 @@ impl Window { button == MouseButton::Left && self.selector.release() } - /// Focus the element `key` (path: its ancestors, for `:focus-within`). - fn set_focus(&mut self, path: &[Key]) { - self.state.focused = path.last().copied(); + /// Move the focus to the element at the end of `path` (its ancestors, for `:focus-within`) without + /// events; the element that had it. + fn focus_path(&mut self, path: &[Key]) -> Option { + let old = std::mem::replace(&mut self.state.focused, path.last().copied()); self.state.focus_path = path.iter().copied().collect(); self.state.focused_id = self.frame.as_ref().and_then(|f| { let i = *f.by_key().get(path.last()?)?; f.el(i)?.id.as_ref().map(|s| s.to_string()) }); + old + } + + /// Focus the element at the end of `path` (its ancestors, for `:focus-within`): `blur` and `focusout` for + /// the one that had it, `focus` and `focusin` for the one that has it now. + fn set_focus(&mut self, app: &mut App, path: &[Key]) { + let (old, new) = (self.focus_path(path), path.last().copied()); + if old != new { + if let Some(k) = old { + self.fire(app, EventKind::Blur, k, &FocusEvent); + self.fire(app, EventKind::FocusOut, k, &FocusEvent); + } + if let Some(k) = new { + self.fire(app, EventKind::Focus, k, &FocusEvent); + self.fire(app, EventKind::FocusIn, k, &FocusEvent); + } + } } fn dispatch(&mut self, ev: RawEvent, app: &mut App) { @@ -2555,11 +2740,23 @@ impl Window { if self.select_drag(x, y) { self.selection_changed(app, true); } - let (modifiers, _) = self.pointer_event(&ev.text); - let pressed = (!self.pressed.is_empty()).then_some(self.press_button); - let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: pressed, modifiers }; - if let Some(deepest) = self.state_deepest() { - self.emit(app, deepest, &e, |l| l.mouse_move.iter().collect()); + let (modifiers, _) = self.parse_pointer(&ev.text); + let held = self.held(); + let target = self.pointer_target(); + let mut pe = self.pointer_event(None, held, 0); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerMove, target, &pe); + let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: held, modifiers }; + self.fire(app, EventKind::MouseMove, target, &e); + // Blender's press-drag: the first move past the drag threshold of a held button + if let Some(button) = held.filter(|_| !self.press_drag_sent) { + let (sx, sy) = self.press_start; + if (x - sx).abs() > DRAG_THRESHOLD || (y - sy).abs() > DRAG_THRESHOLD { + self.press_drag_sent = true; + let (start, at) = (point(px(sx), px(sy)), point(px(x), px(y))); + let e = PressDragEvent { button, start, position: at, modifiers, direction: DragDirection::of(start, at) }; + self.fire(app, EventKind::PressDrag, target, &e); + } } } sys::BK_EV_LEAVE => { @@ -2568,7 +2765,7 @@ impl Window { } sys::BK_EV_PRESS | sys::BK_EV_DOUBLE => { self.pointer = (x, y); - let (modifiers, button) = self.pointer_event(&ev.text); + let (modifiers, button) = self.parse_pointer(&ev.text); // a title bar's drag area: the window manager moves the window (Windows does it // without the press reaching the app) if button == MouseButton::Left && self.control_area_at(x, y) == Some(WindowControlArea::Drag) { @@ -2587,17 +2784,20 @@ impl Window { let quiet = self.press_is_quiet(&path); self.press_quiet = quiet; self.press_button = button; + self.press_count = if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 }; + self.press_start = (x, y); + self.press_drag_sent = false; self.state.active = path.iter().copied().collect(); - self.set_focus(&path); - self.pressed = path.clone(); + self.set_focus(app, &path); + self.pressed.clone_from(&path); self.dirty |= !quiet; self.caches.anim.pointer_down(&path, x, y); - let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, - click_count: if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 } }; - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &e, |l| l.mouse_down.iter() - .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); - } + let target = self.capture.or(path.last().copied()).unwrap_or(ROOT_KEY); + let mut pe = self.pointer_event(Some(button), Some(button), self.press_count); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerDown, target, &pe); + let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: self.press_count }; + self.fire(app, EventKind::MouseDown, target, &e); if selected { // a press that renders draws the selection with it; a quiet one draws it now self.selection_changed(app, quiet); @@ -2607,25 +2807,41 @@ impl Window { if self.sb_drag.take().is_some() { return; } - let (modifiers, button) = self.pointer_event(&ev.text); - let path = self.path_at(x, y); + self.pointer = (x, y); + let (modifiers, button) = self.parse_pointer(&ev.text); + let path = self.capture.map_or_else(|| self.path_at(x, y), |k| self.path_to_key(k)); + let target = path.last().copied().unwrap_or(ROOT_KEY); + let mut pe = self.pointer_event(Some(button), None, self.press_count); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerUp, target, &pe); let up = MouseUpEvent { button, position: point(px(x), px(y)), modifiers }; - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &up, |l| l.mouse_up.iter() - .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); - } + self.fire(app, EventKind::MouseUp, target, &up); // click: the deepest element under both press and release - let common = self.pressed.iter().zip(&path).take_while(|(a, b)| a == b) - .map(|(a, _)| *a).last(); + let common = if self.pressed.is_empty() && button != MouseButton::Left { + path.last().copied() // a button a window reports by its release alone + } else { + self.pressed.iter().zip(&path).take_while(|(a, b)| a == b).map(|(a, _)| *a).last() + }; // a press that selected text is a selection, not a click (as in a browser) let dragged = self.end_press(button); - if let (Some(target), MouseButton::Left, false) = (common, button, dragged) { - let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: 1 }; - self.click(app, target, &ClickEvent { down, up }); + if let (Some(target), false) = (common, dragged) { + let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: self.press_count }; + let e = ClickEvent { down, up }; + if button == MouseButton::Left { + self.click(app, target, &e); + } else { + self.fire(app, EventKind::AuxClick, target, &e); + if button == MouseButton::Right { + let at = point(px(x), px(y)); + self.fire(app, EventKind::ContextMenu, target, &ContextMenuEvent { position: at, modifiers }); + } + } } + // the pointer is let go when its button is + self.release_pointer_capture(app); } sys::BK_EV_WHEEL => { - let (modifiers, _) = self.pointer_event(&ev.text); + let (modifiers, _) = self.parse_pointer(&ev.text); // 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)); @@ -2638,19 +2854,19 @@ impl Window { let pixels = (ev.b != 0.0).then(|| ev.b as f32 / self.scale); let position = point(px(px_), px(py_)); let path = self.path_at(px_, py_); - let Some(&deepest) = path.last() else { return }; + let target = path.last().copied().unwrap_or(ROOT_KEY); 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()) { + if self.fire(app, EventKind::Pan, target, &PanEvent { position, delta, phase, modifiers }) { 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.fire(app, EventKind::Wheel, target, &e); + // `scroll` follows the frame that moves it; 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), @@ -2660,8 +2876,7 @@ impl Window { let key = parts.next().unwrap_or("").to_owned(); let ks = Keystroke { key, key_char: (!ch.is_empty()).then_some(ch), modifiers: Modifiers::from_kit(ev.a as i32) }; - let target = self.state.focused.or_else(|| self.state_deepest()) - .unwrap_or(crate::layout::ROOT_KEY); + let target = self.state.focused.or_else(|| self.state_deepest()).unwrap_or(ROOT_KEY); if ev.kind == sys::BK_EV_KEY { self.selection_key(&ks, app); let page = match ks.key.to_ascii_lowercase().as_str() { @@ -2669,8 +2884,15 @@ impl Window { "pageup" => -1.0, _ => 0.0, }; + // `keypress`: a key that types a character + let types = ks.key_char.is_some() && !ks.modifiers.control && !ks.modifiers.alt; + let down = KeyDownEvent { keystroke: ks }; app.default_prevented = false; - self.emit(app, target, &KeyDownEvent { keystroke: ks }, |l| l.key_down.iter().collect()); + self.fire(app, EventKind::KeyDown, target, &down); + // as in a browser, a `keydown` whose default was prevented types nothing: no `keypress` + if types && !app.default_prevented { + self.fire(app, EventKind::KeyPress, target, &down); + } if std::mem::take(&mut app.default_prevented) && !self.ctx.is_null() { // SAFETY: the live context; the kit is delivering this key (BK_key) now. unsafe { sys::BK_key_taken(self.ctx) }; @@ -2679,7 +2901,7 @@ impl Window { self.scroll_page(page); } } else { - self.emit(app, target, &KeyUpEvent { keystroke: ks }, |l| l.key_up.iter().collect()); + self.fire(app, EventKind::KeyUp, target, &KeyUpEvent { keystroke: ks }); } } _ => {} @@ -2692,25 +2914,28 @@ impl Window { 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 target = self.path_at(x, y).last().copied().unwrap_or(ROOT_KEY); 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()); + self.fire(app, EventKind::Pinch, target, &PinchEvent { position, delta: amount, modifiers, touch }); } sys::BK_GESTURE_ROTATE => { - self.emit(app, deepest, &RotateEvent { position, degrees: amount, modifiers, touch }, |l| l.rotate.iter().collect()); + self.fire(app, EventKind::Rotate, target, &RotateEvent { position, degrees: amount, modifiers, touch }); } _ => {} } } - /// A click on element `target`: its `
` opens or closes, its listeners run, its window - /// control acts. + /// A click on element `target`: its `
` opens or closes, its listeners run (`dblclick` too + /// for the second press), its window control acts. fn click(&mut self, app: &mut App, target: Key, e: &ClickEvent) { self.toggle_details(target); - self.emit(app, target, e, |l| l.click.iter().collect()); + self.fire(app, EventKind::Click, target, e); + if e.down.click_count == 2 { + self.fire(app, EventKind::DoubleClick, target, e); + } self.run_control_area(target); } @@ -2741,7 +2966,7 @@ impl Window { } Some(Action::Focus) => { let path: Vec = f.path_to(Some(i)).into_iter().map(|j| f.nodes[j].key).collect(); - self.set_focus(&path); + self.set_focus(app, &path); } Some(Action::Expand | Action::Collapse) => self.toggle_details(ev.key), Some(Action::ScrollIntoView) => self.reveal = Some(Reveal { key: ev.key, at: 0.0, glide: None }), @@ -2750,6 +2975,50 @@ impl Window { self.dirty = true; } + /// What left the tree no longer holds the pointer or the focus: the pointer is cancelled (`pointercancel` + /// and `lostpointercapture` go to the root), and key events go back to where the pointer is. + fn forget_removed(&mut self, app: &mut App) { + let Some(frame) = &self.frame else { return }; + let gone = |k: Option| k.is_some_and(|k| !frame.by_key().contains_key(&k)); + let (capture_gone, focus_gone) = (gone(self.capture), gone(self.state.focused)); + if capture_gone { + self.capture = None; + let e = self.pointer_event(None, self.held(), 0); + self.fire(app, EventKind::PointerCancel, ROOT_KEY, &e); + self.fire(app, EventKind::LostPointerCapture, ROOT_KEY, &e); + } + if focus_gone { + self.state.focused = None; + self.state.focus_path.clear(); + self.state.focused_id = None; + } + } + + /// `scroll` for every scroll container that moved since its last one, whatever moved it (the wheel, + /// `set_scroll_offset`, a glide, a layout that changed its range). Costs nothing unless something listens. + fn fire_scrolls(&mut self, app: &mut App) { + let Some(frame) = &self.frame else { return }; + if frame.listen & EventKind::Scroll.bit() == 0 { + return; + } + let mut moved: smallvec::SmallVec<[(Key, (f32, f32)); 4]> = smallvec::SmallVec::new(); + for n in frame.nodes.iter().filter(|n| n.scroll_range != (0.0, 0.0)) { + match self.scroll_seen.insert(n.key, n.scroll_pos) { + Some(was) if was != n.scroll_pos => moved.push((n.key, n.scroll_pos)), + _ => {} + } + } + for (key, at) in moved { + self.fire(app, EventKind::Scroll, key, &ScrollEvent { offset: point(px(at.0), px(at.1)) }); + } + } + + /// Element keys from the root to the element `key` (empty when it isn't in this frame). + fn path_to_key(&self, key: Key) -> Vec { + let Some(f) = &self.frame else { return Vec::new() }; + f.path_to(f.by_key().get(&key).copied()).into_iter().map(|i| f.nodes[i].key).collect() + } + fn state_deepest(&self) -> Option { self.path_at(self.pointer.0, self.pointer.1).last().copied() } @@ -2869,7 +3138,7 @@ impl Window { /// (a `change` on its element), or areas and regions moved (the content follows: a render). fn screen_event(&mut self, target: &crate::screen::Target, ev: &RawEvent, app: &mut App) { if let Some((key, e)) = crate::screen::change_event(target, &self.screens, ev.node, ev.kind, ev.a, ev.b) { - self.emit(app, key, &e, |l| l.change.iter().collect()); + self.fire(app, EventKind::Change, key, &e); } self.dirty = true; } @@ -2906,8 +3175,8 @@ impl Window { } _ => {} } - self.emit(app, key, &e, |l| l.input.iter().collect()); - self.emit(app, key, &e, |l| l.change.iter().collect()); + self.fire(app, EventKind::Input, key, &e); + self.fire(app, EventKind::Change, key, &e); self.dirty = true; } sys::BK_EV_CLICK => { @@ -2916,7 +3185,7 @@ impl Window { modifiers: Modifiers::default(), click_count: 1 }; let up = MouseUpEvent { button: MouseButton::Left, position: point(px(x), px(y)), modifiers: Modifiers::default() }; - self.emit(app, key, &ClickEvent { down, up }, |l| l.click.iter().collect()); + self.fire(app, EventKind::Click, key, &ClickEvent { down, up }); self.run_control_area(key); self.dirty = true; } diff --git a/bindings/rust/blenderui/tests/suite/events_dom.rs b/bindings/rust/blenderui/tests/suite/events_dom.rs new file mode 100644 index 00000000..9732b445 --- /dev/null +++ b/bindings/rust/blenderui/tests/suite/events_dom.rs @@ -0,0 +1,492 @@ +//! HTML's events: the capture pass before the bubbling one, `stopPropagation`, `mouseenter` against +//! `mouseover`, listeners of the whole window, pointer capture, the pointer events, focus and scroll. + +use std::sync::Mutex; + +use blenderui::prelude::*; + +static LOG: Mutex> = Mutex::new(Vec::new()); + +fn log(s: &str) { + LOG.lock().unwrap().push(s.to_owned()); +} + +fn take() -> Vec { + std::mem::take(&mut *LOG.lock().unwrap()) +} + +/// A tree of three boxes inside each other, a box beside them, and a scroller. +struct Page; + +impl Render for Page { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("body").size_full() + .child( + div().id("outer").absolute().left(px(0.0)).top(px(0.0)).w(px(200.0)).h(px(200.0)) + .on_click_capture(|_, _, _| log("outer capture")) + .on_click(|_, _, _| log("outer bubble")) + .on_mouse_enter(|_, _, _| log("outer enter")) + .on_mouse_leave(|_, _, _| log("outer leave")) + .on_mouse_over(|_, _, _| log("outer over")) + .on_mouse_out(|_, _, _| log("outer out")) + .child( + div().id("inner").absolute().left(px(50.0)).top(px(50.0)).w(px(100.0)).h(px(100.0)) + .on_click_capture(|_, _, _| log("inner capture")) + .on_click(|_, _, _| log("inner bubble")) + .on_double_click(|_, _, _| log("inner dblclick")) + .on_aux_click(|_, _, _| log("inner auxclick")) + .on_context_menu(|e, _, _| log(&format!("inner contextmenu {}", e.position.x.0 as i32))) + .on_pointer_down(|_, _, _| log("inner pointerdown")) + .on_press_drag(|e, _, _| log(&format!("inner pressdrag {:?}", e.direction))) + .on_any_mouse_down(|_, _, _| log("inner mousedown")) + .on_mouse_enter(|_, _, _| log("inner enter")) + .on_mouse_leave(|_, _, _| log("inner leave")) + .on_mouse_over(|_, _, _| log("inner over")) + .on_mouse_out(|_, _, _| log("inner out")), + ), + ) + .child( + div().id("side").absolute().left(px(300.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_mouse_enter(|_, _, _| log("side enter")), + ) + } +} + +fn open(cx: &mut App) -> WindowId { + blenderui::motion::lag_smoothing(0.0, 0.0); + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(500.0), px(300.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| Page)).unwrap().id; + cx.draw(w); + w +} + +#[test] +fn passes_and_enter_leave() { + Application::headless().run(|cx| { + let w = open(cx); + // capture runs from the root down, then bubble back up + cx.simulate_click(w, 100.0, 100.0); + let l = take(); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("outer capture") < at("inner capture") && at("inner capture") < at("inner bubble") + && at("inner bubble") < at("outer bubble"), "click: {l:?}"); + // entering the inner box: over bubbles (and the pointer came from outside everything), enter is + // for each element on its own, outermost first + assert!(l.contains(&"outer enter".to_owned()) && l.contains(&"inner enter".to_owned()), "enter: {l:?}"); + assert!(at("outer enter") < at("inner enter"), "outermost first: {l:?}"); + + // from the inner box to the outer one: the inner box is left, the outer one is not + take(); + cx.simulate_mouse_move(w, 20.0, 20.0); + let l = take(); + assert!(l.contains(&"inner leave".to_owned()) && !l.contains(&"outer leave".to_owned()), "leave: {l:?}"); + assert!(l.contains(&"inner out".to_owned()), "out bubbles from the left box: {l:?}"); + assert!(!l.contains(&"outer enter".to_owned()), "no second enter for the parent: {l:?}"); + + // out of everything + take(); + cx.simulate_mouse_move(w, 450.0, 250.0); + let l = take(); + assert!(l.contains(&"outer leave".to_owned()), "left it: {l:?}"); + }); +} + +#[test] +fn pointer_events_come_before_mouse_events() { + Application::headless().run(|cx| { + let w = open(cx); + take(); + cx.simulate_press(w, 100.0, 100.0); + let l = take(); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("inner pointerdown") < at("inner mousedown"), "{l:?}"); + cx.simulate_release(w, 100.0, 100.0); + }); +} + +static WIDE: Mutex> = Mutex::new(Vec::new()); + +/// A drag: it takes the pointer on press, and hears the moves and the release wherever they are. +struct Drag; + +impl Render for Drag { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("page").size_full() + .child( + div().id("handle").absolute().left(px(10.0)).top(px(10.0)).w(px(50.0)).h(px(50.0)) + .on_pointer_down(|_, window, app| { + window.set_pointer_capture(app); + WIDE.lock().unwrap().push("down".into()); + }) + .on_pointer_move(|e, _, _| WIDE.lock().unwrap().push(format!("move {}", e.position.x.0 as i32))) + .on_pointer_up(|_, _, _| WIDE.lock().unwrap().push("up".into())) + .on_got_pointer_capture(|_, _, _| WIDE.lock().unwrap().push("got".into())) + .on_lost_pointer_capture(|_, _, _| WIDE.lock().unwrap().push("lost".into())), + ) + .child( + // hears everything in the window, in both passes + div().id("watcher") + .on_mouse_event(|e: &MouseMoveEvent, phase, _, _| { + WIDE.lock().unwrap().push(format!("wide {:?} {}", phase, e.position.x.0 as i32)); + }), + ) + } +} + +#[test] +fn pointer_capture_and_window_wide_listeners() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(500.0), px(300.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| Drag)).unwrap().id; + cx.draw(w); + cx.simulate_mouse_move(w, 30.0, 30.0); + WIDE.lock().unwrap().clear(); + cx.simulate_press(w, 30.0, 30.0); + // far outside the handle: the handle still hears the pointer + cx.simulate_mouse_move(w, 400.0, 200.0); + cx.simulate_release(w, 400.0, 200.0); + let l = std::mem::take(&mut *WIDE.lock().unwrap()); + assert!(l.contains(&"got".to_owned()), "took the pointer: {l:?}"); + assert!(l.contains(&"move 400".to_owned()), "heard a move far outside: {l:?}"); + assert!(l.contains(&"up".to_owned()), "and the release: {l:?}"); + assert!(l.contains(&"lost".to_owned()), "and let go with the button: {l:?}"); + // the window-wide listener: capture pass before bubble pass, for a move anywhere + let cap = l.iter().position(|x| x == "wide Capture 400"); + let bub = l.iter().position(|x| x == "wide Bubble 400"); + assert!(cap.is_some() && bub.is_some() && cap < bub, "both passes: {l:?}"); + + // without capture, the handle hears nothing far away + WIDE.lock().unwrap().clear(); + cx.simulate_mouse_move(w, 450.0, 250.0); + let l = std::mem::take(&mut *WIDE.lock().unwrap()); + assert!(!l.iter().any(|x| x.starts_with("move")), "no capture, no move: {l:?}"); + }); +} + +struct Stop; + +impl Render for Stop { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("a").size_full() + .on_click(|_, _, _| log("a bubble")) + .child( + div().id("b").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_click_capture(|_, _, app| { + log("b capture"); + app.stop_propagation(); + }) + .on_click(|_, _, _| log("b bubble")) + .child(div().id("c").size_full().on_click(|_, _, _| log("c bubble"))), + ) + } +} + +#[test] +fn stop_propagation_in_the_capture_pass() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Stop)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 50.0, 50.0); + assert_eq!(take(), ["b capture"], "stopped on the way down: nothing below or after it hears the click"); + }); +} + +struct Focus; + +impl Render for Focus { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("page").size_full() + .child(div().id("one").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_focus(|_, _, _| log("one focus")).on_blur(|_, _, _| log("one blur")) + .on_focus_in(|_, _, _| log("one focusin")).on_focus_out(|_, _, _| log("one focusout"))) + .child(div().id("two").absolute().left(px(200.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_focus(|_, _, _| log("two focus")).on_blur(|_, _, _| log("two blur"))) + .child( + div().id("scroller").absolute().left(px(0.0)).top(px(150.0)).w(px(100.0)).h(px(100.0)) + .overflow_y_scroll() + .on_scroll(|e, _, _| log(&format!("scroll {}", e.offset.y.0 as i32))) + .child(div().h(px(500.0)).w(px(50.0))), + ) + } +} + +#[test] +fn focus_and_scroll() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Focus)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 50.0, 50.0); + assert_eq!(take(), ["one focus", "one focusin"], "focused"); + cx.simulate_click(w, 250.0, 50.0); + assert_eq!(take(), ["one blur", "one focusout", "two focus"], "focus moves: out of one, into two"); + cx.simulate_scroll(w, 50.0, 200.0, -1); + let l = take(); + assert!(l.iter().any(|x| x.starts_with("scroll ") && x != "scroll 0"), "the scroller scrolled: {l:?}"); + }); +} + +#[test] +fn double_click_and_the_other_buttons() { + Application::headless().run(|cx| { + let w = open(cx); + take(); + cx.simulate_click(w, 100.0, 100.0); + cx.simulate_click(w, 100.0, 100.0); + let l = take(); + assert_eq!(l.iter().filter(|x| *x == "inner bubble").count(), 2, "two clicks: {l:?}"); + assert_eq!(l.iter().filter(|x| *x == "inner dblclick").count(), 1, "one double click: {l:?}"); + + take(); + cx.simulate_button(w, 100.0, 100.0, MouseButton::Right); + let l = take(); + assert!(l.contains(&"inner auxclick".to_owned()) && l.contains(&"inner contextmenu 100".to_owned()), "{l:?}"); + assert!(!l.contains(&"inner bubble".to_owned()), "a right click isn't a click: {l:?}"); + }); +} + +struct Rsx; + +impl Render for Rsx { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + rsx! { +
+
+
+ } + } +} + +#[test] +fn rsx_spellings() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Rsx)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 20.0, 20.0); + let l = take(); + assert!(l.contains(&"rsx pointerdown".to_owned()) && l.contains(&"rsx enter".to_owned()), "{l:?}"); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("rsx capture") < at("rsx bubble"), "{l:?}"); + }); +} + +#[test] +fn press_drag_comes_once_past_the_threshold() { + Application::headless().run(|cx| { + let w = open(cx); + cx.simulate_mouse_move(w, 100.0, 100.0); + take(); + cx.simulate_press(w, 100.0, 100.0); + cx.simulate_mouse_move(w, 102.0, 100.0); // 2 px: not a drag (Blender's threshold is 3) + assert!(!take().iter().any(|x| x.starts_with("inner pressdrag"))); + cx.simulate_mouse_move(w, 110.0, 100.0); + cx.simulate_mouse_move(w, 130.0, 100.0); + let l = take(); + assert_eq!(l.iter().filter(|x| x.starts_with("inner pressdrag")).count(), 1, "once per press: {l:?}"); + assert!(l.contains(&"inner pressdrag East".to_owned()), "to the right: {l:?}"); + cx.simulate_release(w, 130.0, 100.0); + }); +} + +/// A frame renders again for a hover only when something is styled by it. The built-in sheets style nothing +/// by interaction but links (`a:hover`), which the frame knows by the tag: another rule there needs the +/// frame to learn about it (`layout::div_states`). +#[test] +fn the_built_in_sheets_only_style_links_by_hover() { + for css in [blenderui::html::UA_CSS, blenderui::html::UA_STYLED_CSS] { + assert_eq!(css.matches(":hover").count(), css.matches("a:hover").count(), "a hover rule that isn't a link's"); + assert_eq!(css.matches(":active").count(), 0, ":active in a built-in sheet"); + assert_eq!(css.matches(":focus").count(), 0, ":focus in a built-in sheet"); + } +} + +struct Hover; + +impl Render for Hover { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + // the first renders count: they are what a hover would make again + RENDERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + div().size_full() + .child(div().id("plain").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0))) + .child(div().id("styled").absolute().left(px(200.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .hover(|s| s.bg(rgb(0xff0000)))) + } +} + +static RENDERS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +#[test] +fn hover_renders_again_only_when_styled_by_it() { + use std::sync::atomic::Ordering::Relaxed; + Application::headless().run(|cx| { + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Hover)).unwrap().id; + cx.draw(w); + // with a hover style somewhere, the pointer entering an element renders again + let before = RENDERS.load(Relaxed); + cx.simulate_mouse_move(w, 250.0, 50.0); + assert!(RENDERS.load(Relaxed) > before, "styled by hover: rendered again"); + }); +} + +struct Plain; + +static PLAIN_RENDERS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +impl Render for Plain { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + PLAIN_RENDERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // a window-wide listener on the root: the elements the pointer goes over have none of their own + div().size_full() + .on_mouse_event(|e: &MouseMoveEvent, phase, _, _| { + if phase.bubble() && e.position.x.0 < 100.0 { + log("over a"); + } + }) + .child(div().id("a").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0))) + .child(div().id("b").absolute().left(px(200.0)).top(px(0.0)).w(px(100.0)).h(px(100.0))) + } +} + +#[test] +fn nothing_styled_by_hover_means_no_render() { + use std::sync::atomic::Ordering::Relaxed; + Application::headless().run(|cx| { + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Plain)).unwrap().id; + cx.draw(w); + cx.simulate_mouse_move(w, 250.0, 50.0); // into the window (the root, which listens, is entered) + take(); + let before = PLAIN_RENDERS.load(Relaxed); + for x in [50.0, 250.0, 50.0, 250.0] { + cx.simulate_mouse_move(w, x, 50.0); + } + assert_eq!(PLAIN_RENDERS.load(Relaxed), before, "moving over unstyled elements doesn't render the view"); + assert!(take().contains(&"over a".to_owned()), "and the listeners still hear the moves"); + }); +} + +struct Moves { + moved: bool, +} + +impl Render for Moves { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let left = if self.moved { 0.0 } else { 300.0 }; + div().size_full() + .child(div().id("mover").absolute().left(px(left)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_mouse_enter(|_, _, _| log("mover enter")) + .on_mouse_leave(|_, _, _| log("mover leave"))) + } +} + +/// The layout moves an element under a pointer that stays still (a page opening under the mouse): the +/// element is entered, as in a browser, which does it on the next frame. +#[test] +fn an_element_that_arrives_under_the_pointer_is_entered() { + Application::headless().run(|cx| { + let h = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Moves { moved: false })).unwrap(); + let w = h.id; + cx.draw(w); + cx.simulate_mouse_move(w, 50.0, 50.0); + take(); + h.update(cx, |v, _, cx| { + v.moved = true; + cx.notify(); + }); + cx.draw(w); + assert_eq!(take(), ["mover enter"], "arrived under the pointer"); + h.update(cx, |v, _, cx| { + v.moved = false; + cx.notify(); + }); + cx.draw(w); + assert_eq!(take(), ["mover leave"], "and left when it went"); + }); +} + +struct Gone { + show: bool, + offset: bool, +} + +impl Render for Gone { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let mut page = div().id("page").w(px(800.0)).h(px(600.0)) + .on_window_event(EventKind::PointerCancel, |_: &PointerEvent, _, _, _| log("cancel")) + .on_window_event(EventKind::LostPointerCapture, |_: &PointerEvent, _, _, _| log("lost")) + .on_key_press(|e, _, _| log(&format!("keypress {}", e.keystroke.key_char.clone().unwrap_or_default()))) + .on_key_down(|_, _, _| log("keydown")) + .child( + div().id("scroller").absolute().left(px(300.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .overflow_y_scroll() + .on_scroll(|e, _, _| log(&format!("scroll {}", e.offset.y.0 as i32))) + .child(div().h(px(500.0)).w(px(50.0))), + ); + if self.show { + page = page.child( + div().id("handle").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_pointer_down(|_, window, app| window.set_pointer_capture(app)) + .on_focus(|_, _, _| log("focus")), + ); + } + let _ = self.offset; + page + } +} + +#[test] +fn removed_elements_let_go_and_other_scrolls_and_keypress() { + Application::headless().run(|cx| { + let h = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Gone { show: true, offset: false })).unwrap(); + let w = h.id; + cx.draw(w); + take(); + + // a scroll from code (not the wheel) is a scroll event too + h.update(cx, |_, window, cx| { + window.set_scroll_offset("scroller", 0.0, 40.0); + cx.notify(); + }); + cx.draw(w); + assert!(take().contains(&"scroll 40".to_owned()), "set_scroll_offset"); + + // the element that holds the pointer and the focus goes away: both are let go + cx.simulate_press(w, 50.0, 50.0); + take(); + h.update(cx, |v, _, cx| { + v.show = false; + cx.notify(); + }); + cx.draw(w); + let l = take(); + assert!(l.contains(&"cancel".to_owned()) && l.contains(&"lost".to_owned()), "pointer cancelled: {l:?}"); + assert_eq!(h.update(cx, |_, window, _| window.focused_id().is_none()), Some(true), "no focus on what is gone"); + cx.simulate_release(w, 50.0, 50.0); + + // keypress follows keydown for a key that types, and not for a shortcut + cx.simulate_click(w, 200.0, 200.0); // focus goes to the page's area + take(); + cx.simulate_key(w, "a", "a"); + assert_eq!(take(), ["keydown", "keypress a"]); + cx.simulate_key_with(w, "a", "a", true, false); + assert_eq!(take(), ["keydown"], "ctrl+a isn't typing"); + }); +} diff --git a/bindings/rust/blenderui/tests/suite/hover_styles.rs b/bindings/rust/blenderui/tests/suite/hover_styles.rs new file mode 100644 index 00000000..00cb4a36 --- /dev/null +++ b/bindings/rust/blenderui/tests/suite/hover_styles.rs @@ -0,0 +1,75 @@ +//! Every way to style by hover still works now that a hover renders only when something depends on it. + +use blenderui::prelude::*; + +struct Page; + +impl Render for Page { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + rsx! { + + +
+
+
+
+
+ + } + } +} + +fn height(cx: &mut App, w: WindowId, id: &str) -> f32 { + cx.element_bounds(w, id).unwrap().size.height +} + +#[test] +fn hover_styles_all_work() { + Application::headless().run(|cx| { + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Page)).unwrap().id; + cx.draw(w); + for (id, rest, hovered) in [("tw", 16.0, 48.0), ("sheet", 16.0, 70.0), ("attr", 16.0, 56.0), ("inl", 16.0, 50.0)] { + let b = cx.element_bounds(w, id).unwrap(); + assert_eq!(height(cx, w, id), rest, "{id} at rest"); + cx.simulate_mouse_move(w, b.origin.x + 2.0, b.origin.y + 2.0); + cx.draw(w); + assert_eq!(height(cx, w, id), hovered, "{id} hovered"); + cx.simulate_mouse_move(w, 400.0, 400.0); + cx.draw(w); + assert_eq!(height(cx, w, id), rest, "{id} left"); + } + // group-hover: the child follows its parent + let g = cx.element_bounds(w, "grp").unwrap(); + assert_eq!(height(cx, w, "kid"), 8.0); + cx.simulate_mouse_move(w, g.origin.x + 30.0, g.origin.y + 2.0); + cx.draw(w); + assert_eq!(height(cx, w, "kid"), 36.0, "the child of a hovered group"); + }); +} + +struct Tip; + +impl Render for Tip { + fn render(&mut self, window: &mut Window, _: &mut Context) -> impl IntoElement { + // a view that reads the hover state while it renders: it renders again when that changes + let hovered = window.is_hovered("target"); + div().size_full() + .child(div().id("target").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0))) + .children(hovered.then(|| div().id("tip").absolute().left(px(200.0)).top(px(0.0)).w(px(30.0)).h(px(30.0)))) + } +} + +#[test] +fn a_view_that_reads_hover_in_render_follows_it() { + Application::headless().run(|cx| { + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Tip)).unwrap().id; + cx.draw(w); + assert!(cx.element_bounds(w, "tip").is_none()); + cx.simulate_mouse_move(w, 50.0, 50.0); + cx.draw(w); + assert!(cx.element_bounds(w, "tip").is_some(), "shown while hovered"); + cx.simulate_mouse_move(w, 400.0, 250.0); + cx.draw(w); + assert!(cx.element_bounds(w, "tip").is_none(), "gone when it isn't"); + }); +} diff --git a/bindings/rust/blenderui/tests/suite/main.rs b/bindings/rust/blenderui/tests/suite/main.rs index 3eac4ad1..0428eeb3 100644 --- a/bindings/rust/blenderui/tests/suite/main.rs +++ b/bindings/rust/blenderui/tests/suite/main.rs @@ -12,11 +12,13 @@ mod css_redraw; mod css_spec; mod damage_drag; mod effects; +mod events_dom; mod features; mod font_fallback; mod gpu_turn; mod headless; mod hooks; +mod hover_styles; mod images; mod listener_bounds; mod modern_css; diff --git a/bindings/rust/blenderui/tests/suite/touch.rs b/bindings/rust/blenderui/tests/suite/touch.rs index f6bac77c..18531ba3 100644 --- a/bindings/rust/blenderui/tests/suite/touch.rs +++ b/bindings/rust/blenderui/tests/suite/touch.rs @@ -132,3 +132,33 @@ fn a_tap_clicks_and_a_finger_scrolls_unless_a_pan_listener_takes_it() { assert!(!PANS.lock().unwrap().is_empty()); }); } + +static ORDER: Mutex> = Mutex::new(Vec::new()); + +struct Nested; + +impl Render for Nested { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let log = |s: &'static str| move |_: &PinchEvent, _: &mut Window, _: &mut App| ORDER.lock().unwrap().push(s); + div() + .w(px(300.0)) + .h(px(200.0)) + .on_pinch_capture(log("outer capture")) + .on_pinch(log("outer")) + .child(div().id("inner").w(px(300.0)).h(px(200.0)).on_pinch(log("inner"))) + .on_mouse_event(|_: &RotateEvent, phase, _, _| { + ORDER.lock().unwrap().push(if phase.capture() { "wide capture" } else { "wide bubble" }); + }) + } +} + +#[test] +fn gestures_take_the_capture_and_bubbling_passes() { + Application::headless().run(|cx| { + let win = open(cx, 300.0, 200.0, Nested); + cx.draw(win.id); + cx.simulate_magnify(win.id, 120.0, 80.0, 0.25); + cx.simulate_rotate(win.id, 120.0, 80.0, 30.0); + assert_eq!(*ORDER.lock().unwrap(), ["outer capture", "inner", "outer", "wide capture", "wide bubble"]); + }); +} diff --git a/docs/images/themes.gif b/docs/images/themes.gif new file mode 100644 index 00000000..f6702bd4 Binary files /dev/null and b/docs/images/themes.gif differ diff --git a/docs/rust.md b/docs/rust.md index be2848cc..67ca3b66 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -437,22 +437,44 @@ gets `on_click`. ## Events +Every HTML `on*` event has a listener, named in snake case (`onPointerDown` is +`.on_pointer_down`, in `rsx!` too). A listener gets the event, the `Window` and +the `App`. + | Listener | Event | Bubbles | | ------------------------------------------ | ------------------------------------------------------- | ------- | -| `on_click` | `ClickEvent { down, up }` (press and release on the element) | yes | +| `on_click`, `on_double_click`, `on_aux_click` | `ClickEvent { down, up }` (press and release on the element; `auxclick`: middle or secondary button) | yes | +| `on_context_menu` | `ContextMenuEvent { position, modifiers }` | yes | | `on_mouse_down(button, ..)`, `on_any_mouse_down` | `MouseDownEvent { button, position, modifiers, click_count }` | yes | | `on_mouse_up(button, ..)` | `MouseUpEvent` | yes | -| `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | yes | +| `on_mouse_move`, `on_mouse_over`, `on_mouse_out` | `MouseMoveEvent { position, pressed_button, modifiers }` | yes | +| `on_mouse_enter`, `on_mouse_leave` | `MouseMoveEvent` (this element only) | no | | `on_hover` | `bool`: entered / left | no | -| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, pixels, phase, modifiers }` | yes | +| `on_pointer_down` / `up` / `move` / `over` / `out` / `cancel` | `PointerEvent { pointer_id, pointer_type, is_primary, button, buttons, position, modifiers, pressure, click_count }` | yes | +| `on_pointer_enter` / `leave`, `on_got_pointer_capture` / `on_lost_pointer_capture` | `PointerEvent` | no | +| `on_press_drag` | `PressDragEvent { button, start, position, modifiers, direction }`: Blender's `KM_PRESS_DRAG`, once per press past `DRAG_THRESHOLD` (3 px) | yes | +| `on_scroll_wheel` (`on_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_scroll` | `ScrollEvent { offset }`: a scroll container moved, whatever moved it | no | +| `on_key_down`, `on_key_up`, `on_key_press` | `KeyDownEvent { keystroke: Keystroke { key, key_char, modifiers } }` (`KeyUpEvent`; `KeyPressEvent` for a key that types) | yes (from the focused element) | +| `on_focus`, `on_blur` / `on_focus_in`, `on_focus_out` | `FocusEvent` | no / yes | | `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. +to the focused element and bubble up. An event goes down from the root to the +target first (the `_capture` twin of every listener: `on_click_capture`, +`onClickCapture` in `rsx!`), then back up; `cx.stop_propagation()` ends the +pass it is in. `window.set_pointer_capture(cx)` (from a listener) keeps the +pointer's events on that element until the button is released, and +`on_mouse_event` / `on_key_event` / `on_window_event` hear every event of a +kind in the window in both passes, with the `DispatchPhase` (gpui's +`on_mouse_event`). A hover, press or focus change renders the view again only +when something answers to it (a `:hover` / `:active` / `:focus` rule, a +`.hover()` style, Motion gestures, a listener on the element, or a `render` +that read `window.is_hovered(..)` / `focused_id()`). `App::simulate_button` +clicks with the middle or secondary button in tests. ### Touch screens and trackpads @@ -651,7 +673,7 @@ 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. +Also `simulate_mouse_move`, `simulate_button(x, y, MouseButton::Right)` (middle or secondary click), `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 diff --git a/website/WRITING.md b/website/WRITING.md index 3b18b5ee..e67fa517 100644 --- a/website/WRITING.md +++ b/website/WRITING.md @@ -423,6 +423,25 @@ A misspelled name fails the build. The same icons work inline: ``` +### LoopVideo + +```mdx + +``` + +A short silent clip that plays by itself and loops, on the same hatched stage as a +`
`. Use it for a few seconds and a few hundred KB (this one is 135 KB); anything longer +or bigger is a ``, which downloads nothing until the reader presses play. Readers who +ask their system for less motion see the `poster` instead. Files go in `public/videos` and +`public/images`. + ### Kbd, Badge, Hatch, PageStatusList ```mdx diff --git a/website/public/images/themes-poster.png b/website/public/images/themes-poster.png new file mode 100644 index 00000000..3e7d750d Binary files /dev/null and b/website/public/images/themes-poster.png differ diff --git a/website/public/videos/themes.mp4 b/website/public/videos/themes.mp4 new file mode 100644 index 00000000..1c100ade Binary files /dev/null and b/website/public/videos/themes.mp4 differ diff --git a/website/src/components/docs/LoopVideo.astro b/website/src/components/docs/LoopVideo.astro new file mode 100644 index 00000000..a28d9572 --- /dev/null +++ b/website/src/components/docs/LoopVideo.astro @@ -0,0 +1,63 @@ +--- +/** + * A short silent clip that plays by itself, over and over, on the hatched stage of
. + * + * + * + * For clips of a few seconds and a few hundred KB (a theme showcase, a small animation). Longer or + * larger video belongs in , which downloads nothing until the reader presses play. The + * clip is muted, has no controls and stays still for readers who ask for less motion: they see the poster. + */ +import { href } from "../../lib/docs"; + +interface Props { + src: string; + poster: string; + alt: string; + caption?: string; + /** Natural size in CSS pixels, so the page doesn't jump while the clip loads. */ + width?: number; + height?: number; +} + +const { src, poster, alt, caption, width, height } = Astro.props; +--- + +
+
+ +
+ {caption &&
} +
+ + + + diff --git a/website/src/components/docs/index.ts b/website/src/components/docs/index.ts index 2e52e2d2..abe06139 100644 --- a/website/src/components/docs/index.ts +++ b/website/src/components/docs/index.ts @@ -8,6 +8,7 @@ export { default as ComingSoon } from "./ComingSoon.astro"; export { default as Compare } from "./Compare.astro"; export { default as Figure } from "./Figure.astro"; export { default as LazyVideo } from "./LazyVideo.astro"; +export { default as LoopVideo } from "./LoopVideo.astro"; export { default as Hatch } from "./Hatch.astro"; export { default as Kbd } from "./Kbd.astro"; export { default as LangTabs } from "./LangTabs.astro"; diff --git a/website/src/content/docs/concepts/theming.mdx b/website/src/content/docs/concepts/theming.mdx index 13064c85..e502b345 100644 --- a/website/src/content/docs/concepts/theming.mdx +++ b/website/src/content/docs/concepts/theming.mdx @@ -169,6 +169,15 @@ The scale is clamped to 0.5–4. By default it follows the display's DPI (see [W A **theme file** adds your own themes to Dark and Light. It's JSON in the shape of [gpui-kit's themes](https://github.com/longbridge/gpui-kit), with Blender's names for the colors, so you can write one by hand or take a name straight from Blender's theme editor. + +
diff --git a/website/src/content/docs/javascript/native-api.mdx b/website/src/content/docs/javascript/native-api.mdx index 212c9dca..76f4f8fa 100644 --- a/website/src/content/docs/javascript/native-api.mdx +++ b/website/src/content/docs/javascript/native-api.mdx @@ -109,13 +109,14 @@ button.addEventListener('click', (event) => { }) ``` -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`. +The events are `click`, `dblclick`, `auxclick`, `contextmenu`, `mousedown`, `mouseup`, `mousemove`, `mouseenter`, `mouseleave`, `mouseover`, `mouseout`, `pointerdown`, `pointerup`, `pointermove`, `pointerenter`, `pointerleave`, `pointerover`, `pointerout`, `pointercancel`, `gotpointercapture`, `lostpointercapture`, `wheel`, `keydown`, `keypress`, `keyup`, `focus`, `blur`, `focusin`, `focusout`, `scroll`, `pressdrag`, `input` and `change`, and the touch screen and trackpad gestures `pinch`, `rotate` and `pan`. The event object carries `target`, `currentTarget`, `eventPhase`, `clientX`/`clientY`, `button`, `buttons`, `pointerId`, `pointerType`, `deltaX`/`deltaY`, `delta`, `phase`, `key`, the modifier flags (`shiftKey`, `ctrlKey`, `altKey`, `metaKey`) and `timeStamp`. `pressdrag` (Blender's press-drag: a button held and the pointer moved more than 3 pixels, once per press) adds `direction` (`'east'` … `'southeast'`) and `startX`/`startY`; `scroll` adds `scrollLeft`/`scrollTop`. - **`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. +- **They capture and bubble**, as in the DOM: `addEventListener(type, fn, { capture: true })` hears an event on its way down, ancestors first, and `{ once: true }` removes the listener after one call. `mouseenter`, `mouseleave`, `pointerenter`, `pointerleave`, `focus`, `blur` and `scroll` don't bubble. `stopPropagation()` and `stopImmediatePropagation()` work. +- **`el.setPointerCapture()`** keeps the pointer for an element, also when it leaves it or the window, until the button is released (`releasePointerCapture()`, `hasPointerCapture()`). Call it in a `pointerdown` handler, as in the DOM: a drag that follows the pointer out of its element is built on it. - **`event.target`** is the deepest element listening for that event type. - **`preventDefault()` only marks the event.** Events reach JavaScript after BUI has already handled them, so it can't cancel what BUI did. - **Form controls** keep their latest value: read `el.value` or `el.checked` after an `input` or `change` event. diff --git a/website/src/content/docs/javascript/svelte.mdx b/website/src/content/docs/javascript/svelte.mdx index f08c40fa..f5209c0f 100644 --- a/website/src/content/docs/javascript/svelte.mdx +++ b/website/src/content/docs/javascript/svelte.mdx @@ -84,7 +84,7 @@ To mount into a window you opened yourself, use `createRoot(window)`, then `root Elements are HTML elements, as in the browser: - **`class`** takes Tailwind classes, and `class={{ on: active }}` objects and arrays work. **`style`** takes a string; `style:color={c}` directives work. -- **Mouse, keyboard and form events** work: `onclick`, `onmousedown`, `onmouseup`, `onmousemove`, `onmouseenter`, `onmouseleave`, `onwheel`, `onkeydown`, `onkeyup`, `oninput` and `onchange`. They bubble, and `stopPropagation` works. Svelte delegates most of them to the window's body, as on the web. +- **Mouse, keyboard and form events** work: `onclick`, `onmousedown`, `onmouseup`, `onmousemove`, `onmouseenter`, `onmouseleave`, `ondblclick`, `oncontextmenu`, `onpointerdown`, `onpointerup`, `onpointermove`, `onfocus`, `onblur`, `onscroll`, `onwheel`, `onkeydown`, `onkeyup`, `oninput` and `onchange`. They bubble, and `stopPropagation` works. Svelte delegates most of them to the window's body, as on the web. - **Bindings:** `bind:value`, `bind:checked`, `bind:group` and `bind:this` work. - **Blocks:** `{#if}`, `{#each}` (keyed too), `{#await}`, `{#key}` and snippets with `{@render}` work, and so do context, `onMount` and `onDestroy`. - **Transitions** (`transition:`, `in:`, `out:`) run on the animation engine through `el.animate()`: an outro keeps its element until it ends. See [Svelte transitions](../animation/#svelte-transitions). `use:motion` and the `spring` and `tweened` stores are not built. diff --git a/website/src/content/docs/rust/events.mdx b/website/src/content/docs/rust/events.mdx index f27d590e..e83c59c5 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, touch gestures and form changes, update your view with cx.listener, and paint your own content on a canvas. +description: Respond to every HTML event (mouse, pointer, keys, focus, wheel, scroll, form changes) and touch gestures, with capture and bubbling, pointer capture and window-wide listeners, 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/tests/suite/touch.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/events_dom.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. @@ -41,26 +41,47 @@ If you use [hooks](../hooks/) instead, you don't need either: writing a signal r ## Every listener +Every HTML `on*` event has a listener, named the same in snake case (`onPointerDown` is `.on_pointer_down`). A listener gets the event, the `Window` and the `App`. + | Listener | Event | Bubbles | | --- | --- | --- | | `on_click` | `ClickEvent { down, up }`: a press and release on the element | Yes | +| `on_double_click` | `ClickEvent` (`click_count()` is 2) | Yes | +| `on_aux_click` | `ClickEvent`: a click with the middle or secondary button | Yes | +| `on_context_menu` | `ContextMenuEvent { position, modifiers }` | Yes | | `on_mouse_down(button, f)`, `on_any_mouse_down(f)` | `MouseDownEvent { button, position, modifiers, click_count }` | Yes | | `on_mouse_up(button, f)` | `MouseUpEvent { button, position, modifiers }` | Yes | | `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | Yes | +| `on_mouse_enter`, `on_mouse_leave` | `MouseMoveEvent`: this element only; moving into a child doesn't leave it | No | +| `on_mouse_over`, `on_mouse_out` | `MouseMoveEvent`: also from the children | 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_pointer_down`, `on_pointer_up`, `on_pointer_move` | `PointerEvent` | Yes | +| `on_pointer_enter`, `on_pointer_leave` | `PointerEvent` | No | +| `on_pointer_over`, `on_pointer_out`, `on_pointer_cancel` | `PointerEvent` (`pointercancel`: the element that held the pointer left the tree) | Yes | +| `on_got_pointer_capture`, `on_lost_pointer_capture` | `PointerEvent` | No | +| `on_press_drag` | `PressDragEvent { button, start, position, modifiers, direction }`: Blender's press-drag, once per press, from the first move more than 3 pixels from where the button went down | Yes | +| `on_scroll_wheel` (or `on_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_scroll` | `ScrollEvent { offset }`: a scroll container moved, whatever moved it (the wheel, `set_scroll_offset`) | No | | `on_key_down`, `on_key_up` | `KeyDownEvent` / `KeyUpEvent { keystroke }` | Yes, from the focused element | +| `on_key_press` | `KeyPressEvent` (a `KeyDownEvent`): after `keydown`, for a key that types a character (not with ctrl or alt) | Yes | +| `on_focus`, `on_blur` | `FocusEvent` | No | +| `on_focus_in`, `on_focus_out` | `FocusEvent` | Yes | | `on_change`, `on_input` | `ChangeEvent { value, checked, number }` | Yes | +Each has a `_capture` twin (`on_click_capture` …) that hears the event on the way down, before the target (see [the two passes](#the-two-passes)). Touch, drag-and-drop, clipboard, media and CSS animation events (`touchstart`, `dragstart`, `paste`, `ended`, `transitionend` …) are not there yet. + The details: - **Positions** are in logical pixels (they don't change with display scaling). - **`MouseButton`** is `Left`, `Right` or `Middle`. - **`Modifiers`** has `shift`, `control` and `alt`. -- **`ClickEvent::click_count()`** tells a double-click from a single one. +- **`PointerEvent`** has `pointer_id` (the mouse is 1), `pointer_type`, `is_primary`, `button`, `buttons` (bits: 1 left, 2 right, 4 middle), `position`, `modifiers`, `pressure` and `click_count`. A press fires `pointerdown` and then `mousedown`; a move fires `pointermove` and then `mousemove`. +- **`on_context_menu` and `on_aux_click`** run when the secondary or middle button is released (a window reports the secondary button's click that way). +- **`ClickEvent::click_count()`** tells a double-click from a single one. A double click is Blender's rule: the same button pressed again within 350 ms without moving past the drag threshold. +- **`PressDragEvent::direction`** is one of eight (`DragDirection::East` … `SouthEast`), rounded to the nearest as Blender's `WM_event_drag_direction` does. The threshold is `DRAG_THRESHOLD` (3 logical pixels, Blender's `U.drag_threshold_mouse`). - **`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). 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`. @@ -114,11 +135,19 @@ div().w(px(300.0)).h(px(200.0)) 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 +## The two passes + +An event goes through the elements twice, as in a browser. First down from the root to the target (the **capture** pass, the `_capture` listeners), then back up (the **bubbling** pass, the ordinary listeners). `cx.stop_propagation()` ends the pass it is called in, so a capture listener can keep an event from reaching its target. + +```rust +div() + .on_click_capture(|_, _, cx| { println!("first"); cx.stop_propagation(); }) // nothing below hears the click + .child(button().on_click(|_, _, _| println!("never"))) +``` -- **Clicking an element focuses it.** Key events go to the focused element, then bubble up through its ancestors. -- **Most events bubble**: a click on a `` inside a `