From c6f18cba28927eb292c8791bb981dc93dbde2dae Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:36:19 +0530 Subject: [PATCH 01/14] move a11y --- ARCHITECTURE.md | 4 ++-- bindings/rust/Cargo.toml | 2 +- bindings/rust/blenderui-sys/Cargo.toml | 4 ++-- bindings/rust/blenderui-sys/build.rs | 2 +- bindings/rust/scripts/vendor_c.py | 4 ++-- features.json | 2 +- kit/CMakeLists.txt | 12 ++++++------ kit/intern/a11y/a11y.c | 4 ++-- kit/intern/a11y/a11y.h | 2 +- {a11y => platform/a11y}/Cargo.toml | 2 +- {a11y => platform/a11y}/include/bui_a11y.h | 2 +- {a11y => platform/a11y}/src/adapter.rs | 0 {a11y => platform/a11y}/src/ffi.rs | 0 {a11y => platform/a11y}/src/lib.rs | 0 {a11y => platform/a11y}/src/node.rs | 0 {a11y => platform/a11y}/src/tree.rs | 0 tools/bump_version.py | 2 +- 17 files changed, 21 insertions(+), 21 deletions(-) rename {a11y => platform/a11y}/Cargo.toml (98%) rename {a11y => platform/a11y}/include/bui_a11y.h (95%) rename {a11y => platform/a11y}/src/adapter.rs (100%) rename {a11y => platform/a11y}/src/ffi.rs (100%) rename {a11y => platform/a11y}/src/lib.rs (100%) rename {a11y => platform/a11y}/src/node.rs (100%) rename {a11y => platform/a11y}/src/tree.rs (100%) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7a4e0652..ef397f76 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -66,8 +66,8 @@ include `ui/`.) | `gpu/` | The draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend that *records and forwards*: with a sink installed it emits screen-space primitives (`GPU_backend_sink.h`); without one it discards them. Theme colors reach the GPU layer through function-pointer hooks. | **Builds + tested** | | `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types and stub implementations (`intern/bui_stubs.cc`). | **Builds** | | `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Kept for reference and porting work; **not compiled by default** (`-DBUI_BUILD_UI=ON` builds it as `bui_ui`). `kit/` re-ports what it needs in C. | **Compiles + links** (opt-in) | -| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Blender's screen layout (`kit/intern/screen`, ported from `editors/screen`: areas on a graph of shared edges that split, join, dock and resize, regions that resize, hide and flip, saved as JSON); Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; Blender's file browser; images (`kit/intern/image`: Blender's imbuf design, one format table over Wuffs, libjpeg-turbo, libwebp, libtiff, OpenEXRCore, libavif, libjxl, the OS's HEIC decoder and BUI's HDR/PNM/SVG readers in `kit/extern`, decode at the drawn size, a worker pool and a memory-budgeted cache; see [the Images page](https://bui.preetham.top/docs/concepts/images/)); damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11, Wayland, Cocoa and Android (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_wayland.c`, `kit_window_cocoa.m`, `kit_window_android.c`; `kit_window_null.c` elsewhere); the desktop shell (`kit/intern/shell`: tray icons, notifications, taskbar progress, recent files); one accessibility tree per window (`kit/intern/a11y`, served to screen readers by `a11y/`). Touch screens and trackpad gestures live in the kit, not the hosts: `kit/intern/kit_touch.c` is one state machine (Android's model: taps, long presses, scrolls past the touch slop, a second finger's pan, pinch and turn as Blender's `MOUSEPAN` / `MOUSEZOOM` / `MOUSEROTATE`) with the fling in `kit_fling.c` (`VelocityTracker`, `OverScroller`), and every host (Win32 `WM_POINTER`, X11 XInput 2, Wayland `wl_touch` and pointer gestures, Cocoa's magnify and rotate, Android) only forwards contacts to `BK_touch` and trackpad gestures to `BK_magnify` / `BK_rotate` ([docs/touch.md](docs/touch.md)). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (checked by CI and tried by hand on three Macs: two Apple Silicon, one Intel) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** | -| `a11y/` | `bui-a11y`, a Rust crate: the kit's accessibility trees as AccessKit trees, served to UI Automation on Windows through the window's `WM_GETOBJECT`. The only code that uses AccessKit; C API in `a11y/include/bui_a11y.h`. Gate: `-DBUI_A11Y=ON` (needs cargo); on for Rust and Node. | **Builds + tested** (Windows) | +| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Blender's screen layout (`kit/intern/screen`, ported from `editors/screen`: areas on a graph of shared edges that split, join, dock and resize, regions that resize, hide and flip, saved as JSON); Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; Blender's file browser; images (`kit/intern/image`: Blender's imbuf design, one format table over Wuffs, libjpeg-turbo, libwebp, libtiff, OpenEXRCore, libavif, libjxl, the OS's HEIC decoder and BUI's HDR/PNM/SVG readers in `kit/extern`, decode at the drawn size, a worker pool and a memory-budgeted cache; see [the Images page](https://bui.preetham.top/docs/concepts/images/)); damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11, Wayland, Cocoa and Android (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_wayland.c`, `kit_window_cocoa.m`, `kit_window_android.c`; `kit_window_null.c` elsewhere); the desktop shell (`kit/intern/shell`: tray icons, notifications, taskbar progress, recent files); one accessibility tree per window (`kit/intern/a11y`, served to screen readers by `platform/a11y/`). Touch screens and trackpad gestures live in the kit, not the hosts: `kit/intern/kit_touch.c` is one state machine (Android's model: taps, long presses, scrolls past the touch slop, a second finger's pan, pinch and turn as Blender's `MOUSEPAN` / `MOUSEZOOM` / `MOUSEROTATE`) with the fling in `kit_fling.c` (`VelocityTracker`, `OverScroller`), and every host (Win32 `WM_POINTER`, X11 XInput 2, Wayland `wl_touch` and pointer gestures, Cocoa's magnify and rotate, Android) only forwards contacts to `BK_touch` and trackpad gestures to `BK_magnify` / `BK_rotate` ([docs/touch.md](docs/touch.md)). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (checked by CI and tried by hand on three Macs: two Apple Silicon, one Intel) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** | +| `platform/a11y/` | `bui-a11y`, a Rust crate: the kit's accessibility trees as AccessKit trees, served to UI Automation on Windows through the window's `WM_GETOBJECT`. The only code that uses AccessKit; C API in `platform/a11y/include/bui_a11y.h`. Gate: `-DBUI_A11Y=ON` (needs cargo); on for Rust and Node. | **Builds + tested** (Windows) | | `api/` | `bui_c_api.h` — small stable C ABI: version info + sink/viewport plumbing for hosts and bindings. | **Builds + tested** | | `bindings/python/` | `buipy` CPython extension (no third-party deps; Dear ImGui is compiled into it, `blenderui.imgui`, so a process holds one kit) + `bui` package: `bui.components` (Blender component library), `bui.qtsyntax` / `bui.tksyntax` (Qt / tkinter APIs as thin facades over the kit), `bui.host` (native or Tk windows), `SvgSink` headless renderer, `bui.qt.BuiCanvas` PySide6/PyQt6 widget. | **Builds + tested** | | `bindings/imgui/` | Dear ImGui (vendored, 1.93.1 WIP) on BUI: `imgui_impl_bui` platform + renderer backend hosted in a kit `custom` node (input, cursors, clipboard, DPI, damage-driven frames) drawing through `BUI_raster_mesh` and BUI textures; Blender style and Inter font; the C API (`cimgui.h`) and the generator behind the Python and Rust bindings; the Blender-widgets build (`blender/`, `-DBUI_IMGUI_BLENDER_WIDGETS=ON`). Gate: `-DBUI_BUILD_IMGUI` (ON with C++). | **Builds + tested** | diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.toml index 68eafc37..fd54a504 100644 --- a/bindings/rust/Cargo.toml +++ b/bindings/rust/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["blenderui-paint", "blenderui-vlist", "blenderui-table", "blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui", "blenderui-jsview", "blenderui-node", "blenderui-qjs", "blenderui-imgui", "blenderui-web", "../../a11y"] +members = ["blenderui-paint", "blenderui-vlist", "blenderui-table", "blenderui-sys", "blenderui-tailwind", "blenderui-macros", "blenderui", "blenderui-jsview", "blenderui-node", "blenderui-qjs", "blenderui-imgui", "blenderui-web", "../../platform/a11y"] exclude = ["bench", "blenderui-table-gpui"] [workspace.package] diff --git a/bindings/rust/blenderui-sys/Cargo.toml b/bindings/rust/blenderui-sys/Cargo.toml index fee357b2..a301800d 100644 --- a/bindings/rust/blenderui-sys/Cargo.toml +++ b/bindings/rust/blenderui-sys/Cargo.toml @@ -48,7 +48,7 @@ freetype = [] # Text through the vendored FreeType like Blender's BLF filebrowser = [] # Blender's File Browser anim = [] # animation: GSAP and Motion (kit/intern/anim) shell = [] # the desktop shell: tray icons, notifications, taskbar progress, recent files -a11y = ["dep:bui-a11y"] # screen readers: the kit's accessibility trees and their adapters (a11y/) +a11y = ["dep:bui-a11y"] # screen readers: the kit's accessibility trees and their adapters (platform/a11y/) # The Lua host (bindings/lua: bui-lua, bui.so). features.json lists it, so it is here too; the # crate's C sources (vendored for crates.io) leave bindings/lua out, so turning it on builds # nothing more for Rust. @@ -64,7 +64,7 @@ imgui-blender-widgets = ["imgui"] [dependencies] # the kit's accessibility adapters (AccessKit); its C ABI links with the kit -bui-a11y = { path = "../../../a11y", version = "0.5.1", optional = true } +bui-a11y = { path = "../../../platform/a11y", version = "0.5.1", optional = true } [build-dependencies] cmake = "0.1" diff --git a/bindings/rust/blenderui-sys/build.rs b/bindings/rust/blenderui-sys/build.rs index bb1a3ad5..6fc0af28 100644 --- a/bindings/rust/blenderui-sys/build.rs +++ b/bindings/rust/blenderui-sys/build.rs @@ -166,7 +166,7 @@ fn main() { println!("cargo:rustc-link-lib=m"); println!("cargo:rustc-link-lib=pthread"); } - for dir in ["kit", "gpu", "core", "CMakeLists.txt", "bindings/imgui", "a11y/include"] { + for dir in ["kit", "gpu", "core", "CMakeLists.txt", "bindings/imgui", "platform/a11y/include"] { println!("cargo:rerun-if-changed={}", root.join(dir).display()); } println!("cargo:rerun-if-env-changed=BUI_SOURCE_DIR"); diff --git a/bindings/rust/scripts/vendor_c.py b/bindings/rust/scripts/vendor_c.py index 18855ae4..93fbfa60 100644 --- a/bindings/rust/scripts/vendor_c.py +++ b/bindings/rust/scripts/vendor_c.py @@ -26,9 +26,9 @@ ROOT = Path(__file__).resolve().parents[3] DEST = ROOT / "bindings" / "rust" / "blenderui-sys" / "csrc" # --dest moves it -# a11y/include: the C ABI of bui-a11y, which the kit includes with `a11y` (the crate itself is a +# platform/a11y/include: the C ABI of bui-a11y, which the kit includes with `a11y` (the crate itself is a # dependency of blenderui-sys, published on its own) -DIRS = ["core", "types", "gpu", "compat", "kit", "api", "bindings/imgui", "platform/wasm", "a11y/include"] +DIRS = ["core", "types", "gpu", "compat", "kit", "api", "bindings/imgui", "platform/wasm", "platform/a11y/include"] FILES = ["CMakeLists.txt", "features.json", "features.cmake", "LICENSE", "bindings/python/bui/_version.py", "ui/CMakeLists.txt"] # relative directories (from ROOT) never needed by the crate's CMake configuration SKIP_DIRS = {"core/tests", "gpu/tests", "bindings/imgui/gen"} diff --git a/features.json b/features.json index 9ac24756..1188e6c0 100644 --- a/features.json +++ b/features.json @@ -23,7 +23,7 @@ {"name": "shell", "option": "BUI_SHELL", "default": true, "group": "ui", "markers": ["createTray", "notify", "setProgressBar", "addRecentDocument"], "doc": "The desktop shell: tray icons and their menus, notifications, taskbar progress, recent files (kit/intern/shell; the system's libraries loaded at run time)"}, {"name": "filebrowser", "option": "BUI_FILEBROWSER", "default": true, "group": "ui", "tags": ["filebrowser"], "markers": ["fileDialog", "file_dialog", "filebrowser"], "doc": "Blender's File Browser (the filebrowser node and BK_file_dialog)"}, {"name": "imgui", "option": "BUI_BUILD_IMGUI", "default": true, "cargo_default": false, "group": "ui", "doc": "Dear ImGui on BUI (C++; the blenderui-imgui crate and Python's blenderui.imgui turn it on)"}, - {"name": "a11y", "option": "BUI_A11Y", "default": false, "cargo_default": true, "group": "ui", "doc": "Screen readers: each window's accessibility tree, served to UI Automation (Windows) through AccessKit (the a11y/ crate; C builds run cargo for it)"}, + {"name": "a11y", "option": "BUI_A11Y", "default": false, "cargo_default": true, "group": "ui", "doc": "Screen readers: each window's accessibility tree, served to UI Automation (Windows) through AccessKit (the platform/a11y/ crate; C builds run cargo for it)"}, {"name": "lua", "option": "BUI_BUILD_LUA_BINDINGS", "default": false, "group": "ui", "doc": "Lua 5.4 host (bui-lua executable and bui.so/bui.dll loadable module)"} ], "runtimes": [ diff --git a/kit/CMakeLists.txt b/kit/CMakeLists.txt index e39241a2..5ac84e26 100644 --- a/kit/CMakeLists.txt +++ b/kit/CMakeLists.txt @@ -79,26 +79,26 @@ else() endif() # Accessibility (intern/a11y): each context's tree, and the adapter that serves it to screen -# readers (bui-a11y, the Rust crate in a11y/ with AccessKit); without it, the API alone. +# readers (bui-a11y, the Rust crate in platform/a11y/ with AccessKit); without it, the API alone. if(BUI_A11Y) target_sources(bui_kit PRIVATE intern/a11y/a11y.c) - target_include_directories(bui_kit PRIVATE ${BUI_SOURCE_DIR}/a11y/include) + target_include_directories(bui_kit PRIVATE ${BUI_SOURCE_DIR}/platform/a11y/include) # A Rust program links bui-a11y itself (blenderui-sys depends on the crate and turns this off); # C builds get it from cargo, as a static library. option(BUI_A11Y_CARGO "Build bui-a11y with cargo and link it (BUI_A11Y)" ON) if(BUI_A11Y_CARGO) find_program(BUI_CARGO cargo) if(NOT BUI_CARGO) - message(FATAL_ERROR "BUI_A11Y needs cargo (Rust) to build a11y/: install it, or -DBUI_A11Y=OFF") + message(FATAL_ERROR "BUI_A11Y needs cargo (Rust) to build platform/a11y/: install it, or -DBUI_A11Y=OFF") endif() set(_a11y_dir ${CMAKE_CURRENT_BINARY_DIR}/a11y) set(_a11y_lib ${_a11y_dir}/release/${CMAKE_STATIC_LIBRARY_PREFIX}bui_a11y${CMAKE_STATIC_LIBRARY_SUFFIX}) - file(GLOB _a11y_src ${BUI_SOURCE_DIR}/a11y/src/*.rs) + file(GLOB _a11y_src ${BUI_SOURCE_DIR}/platform/a11y/src/*.rs) add_custom_command(OUTPUT ${_a11y_lib} COMMAND ${CMAKE_COMMAND} -E env CARGO_TARGET_DIR=${_a11y_dir} ${BUI_CARGO} rustc --release --lib --crate-type staticlib - --manifest-path ${BUI_SOURCE_DIR}/a11y/Cargo.toml - DEPENDS ${_a11y_src} ${BUI_SOURCE_DIR}/a11y/Cargo.toml + --manifest-path ${BUI_SOURCE_DIR}/platform/a11y/Cargo.toml + DEPENDS ${_a11y_src} ${BUI_SOURCE_DIR}/platform/a11y/Cargo.toml COMMENT "bui-a11y (cargo)" USES_TERMINAL) add_custom_target(bui_a11y_cargo DEPENDS ${_a11y_lib}) add_dependencies(bui_kit bui_a11y_cargo) diff --git a/kit/intern/a11y/a11y.c b/kit/intern/a11y/a11y.c index b537f3b8..05585245 100644 --- a/kit/intern/a11y/a11y.c +++ b/kit/intern/a11y/a11y.c @@ -22,8 +22,8 @@ #include "bui_a11y.h" #include "kit_intern.h" -/* bui-a11y mirrors the struct (a11y/src/node.rs asserts the same size) */ -_Static_assert(sizeof(BKA11yNode) == 72 + 4 * sizeof(void *), "BKA11yNode changed: update a11y/src/node.rs"); +/* bui-a11y mirrors the struct (platform/a11y/src/node.rs asserts the same size) */ +_Static_assert(sizeof(BKA11yNode) == 72 + 4 * sizeof(void *), "BKA11yNode changed: update platform/a11y/src/node.rs"); /* A host's subtree, copied: the nodes, then their strings (one block). */ typedef struct BKA11ySub { diff --git a/kit/intern/a11y/a11y.h b/kit/intern/a11y/a11y.h index dd9dbb2e..77b088d2 100644 --- a/kit/intern/a11y/a11y.h +++ b/kit/intern/a11y/a11y.h @@ -1,6 +1,6 @@ /* Accessibility, the kit's side (BUI_kit.h "accessibility"): each context's tree, built from its * nodes and the subtrees hosts attach (a11y.c), served to the platform by the window hosts through - * bui-a11y (a11y/include/bui_a11y.h). Without the "a11y" feature (BUI_A11Y off) a11y_off.c keeps + * bui-a11y (platform/a11y/include/bui_a11y.h). Without the "a11y" feature (BUI_A11Y off) a11y_off.c keeps * the API and builds nothing. * * SPDX-License-Identifier: GPL-2.0-or-later */ diff --git a/a11y/Cargo.toml b/platform/a11y/Cargo.toml similarity index 98% rename from a11y/Cargo.toml rename to platform/a11y/Cargo.toml index aa80262e..29ae8246 100644 --- a/a11y/Cargo.toml +++ b/platform/a11y/Cargo.toml @@ -4,7 +4,7 @@ description = "Screen-reader accessibility for the BUI kit: its flat node trees # a member of the Rust bindings' workspace: one version and lock with the crates that use it, and # blenderui-sys can be packaged against it before it is on crates.io (`cargo package -p bui-a11y # -p blenderui-sys`) -workspace = "../bindings/rust" +workspace = "../../bindings/rust" version.workspace = true edition.workspace = true license.workspace = true diff --git a/a11y/include/bui_a11y.h b/platform/a11y/include/bui_a11y.h similarity index 95% rename from a11y/include/bui_a11y.h rename to platform/a11y/include/bui_a11y.h index 393b4f22..87925d02 100644 --- a/a11y/include/bui_a11y.h +++ b/platform/a11y/include/bui_a11y.h @@ -1,4 +1,4 @@ -/* bui-a11y's C ABI (a11y/src/ffi.rs): the platform accessibility adapter of a native window, fed +/* bui-a11y's C ABI (platform/a11y/src/ffi.rs): the platform accessibility adapter of a native window, fed * the kit's flat trees (BKA11yNode, BUI_kit.h) and turning them into AccessKit updates. Only the * kit calls it (kit/intern/a11y and the window hosts). * diff --git a/a11y/src/adapter.rs b/platform/a11y/src/adapter.rs similarity index 100% rename from a11y/src/adapter.rs rename to platform/a11y/src/adapter.rs diff --git a/a11y/src/ffi.rs b/platform/a11y/src/ffi.rs similarity index 100% rename from a11y/src/ffi.rs rename to platform/a11y/src/ffi.rs diff --git a/a11y/src/lib.rs b/platform/a11y/src/lib.rs similarity index 100% rename from a11y/src/lib.rs rename to platform/a11y/src/lib.rs diff --git a/a11y/src/node.rs b/platform/a11y/src/node.rs similarity index 100% rename from a11y/src/node.rs rename to platform/a11y/src/node.rs diff --git a/a11y/src/tree.rs b/platform/a11y/src/tree.rs similarity index 100% rename from a11y/src/tree.rs rename to platform/a11y/src/tree.rs diff --git a/tools/bump_version.py b/tools/bump_version.py index 752e53b3..0ebf94ac 100644 --- a/tools/bump_version.py +++ b/tools/bump_version.py @@ -141,7 +141,7 @@ def put(path: Path, text: str) -> None: put(ws, text[: m.start(1)] + section + text[m.end(1):]) # sibling path dependencies of the published crates: `blenderui-x = { path = "..", version = ".." }` - # (and `bui-a11y`, which lives in a11y/ but is versioned with the workspace) + # (and `bui-a11y`, which lives in platform/a11y/ but is versioned with the workspace) for toml in sorted(RUST.glob("*/Cargo.toml")): lines = read(toml).splitlines(keepends=True) out = [] From e9e5e01c25ffeedd5ed7ae193d7047ac551831a1 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:36:20 +0530 Subject: [PATCH 02/14] core fixes --- bindings/rust/blenderui-sys/src/lib.rs | 3 + bindings/rust/blenderui/src/anim.rs | 13 +- bindings/rust/blenderui/src/element.rs | 4 + bindings/rust/blenderui/src/layout.rs | 60 +- bindings/rust/blenderui/src/paint.rs | 590 +++++- bindings/rust/blenderui/src/style.rs | 122 +- bindings/rust/blenderui/src/widgets.rs | 21 +- bindings/rust/blenderui/src/window.rs | 62 +- .../rust/blenderui/tests/suite/effects.rs | 173 ++ .../rust/blenderui/tests/suite/events_dom.rs | 243 +++ docs/effects-performance.md | 5 +- docs/rust.md | 2 +- gpu/include/GPU_raster.h | 5 + gpu/intern/gpu_d3d11_shaders.h | 1711 ++++++++++++----- gpu/intern/gpu_effect.c | 43 +- gpu/intern/gpu_gl.c | 50 +- gpu/intern/gpu_raster.c | 104 +- gpu/shaders/bui_ui.hlsl | 57 +- gpu/tests/test_gpu_effect.c | 6 +- gpu/tests/test_gpu_parity.c | 8 + kit/include/BUI_kit.h | 6 +- kit/intern/kit_core.c | 12 +- kit/intern/kit_frame.c | 21 +- 23 files changed, 2665 insertions(+), 656 deletions(-) diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs index 59bbd9c6..a1ca3688 100644 --- a/bindings/rust/blenderui-sys/src/lib.rs +++ b/bindings/rust/blenderui-sys/src/lib.rs @@ -125,6 +125,9 @@ pub const BK_ITEM_ROUNDRECT: c_int = 7; pub const BK_ITEM_EFFECT: c_int = 8; /// A GPU pass into a render target (`BUI_target_create`): see `effect_target`. pub const BK_ITEM_PASS: c_int = 9; +/// CSS `box-shadow`: 8 coords (the shadow's box, then the box casting it), `radius` the shadow's corner, +/// `size` the caster's, `width` the blur's sigma (see `BUI_kit.h`). +pub const BK_ITEM_SHADOW: c_int = 10; /// The most textures an effect samples, the most floats it reads, the longest source (bytes). pub const BK_EFFECT_MAX_INPUTS: usize = 8; diff --git a/bindings/rust/blenderui/src/anim.rs b/bindings/rust/blenderui/src/anim.rs index 0ad53dfb..dce1ae10 100644 --- a/bindings/rust/blenderui/src/anim.rs +++ b/bindings/rust/blenderui/src/anim.rs @@ -738,7 +738,6 @@ enum Val { Len(Length), Len2(Length, Length), Shadows(Vec), - TextShadow(Option), Visible(bool), Z(Option), Lh(LineHeight), @@ -819,7 +818,7 @@ fn get(f: Field, c: &Computed) -> Option { Filter => Val::Filters(c.effects.as_ref().map(|e| e.filter.clone()).unwrap_or_default()), Backdrop => Val::Filters(c.effects.as_ref().map(|e| e.backdrop.clone()).unwrap_or_default()), BoxShadow => Val::Shadows(c.shadows.clone()), - TextShadow => Val::TextShadow(c.text_shadow), + TextShadow => Val::Shadows(c.text_shadow.clone()), Other(_) => return None, }) } @@ -898,7 +897,7 @@ fn set(f: Field, c: &mut Computed, v: Val) { } } (BoxShadow, Val::Shadows(x)) => c.shadows = x, - (TextShadow, Val::TextShadow(x)) => c.text_shadow = x, + (TextShadow, Val::Shadows(x)) => c.text_shadow = x, _ => {} } } @@ -1117,14 +1116,6 @@ fn lerp(a: &Val, b: &Val, t: f32, u: &Units) -> Option { }; Val::Shadows((0..n).map(|i| mix_shadow(&pad(x, y, i), &pad(y, x, i), t)).collect::>()?) } - (Val::TextShadow(x), Val::TextShadow(y)) => { - let (p, q) = (x.unwrap_or(NO_SHADOW), y.unwrap_or(NO_SHADOW)); - if x.is_none() && y.is_none() { - Val::TextShadow(None) - } else { - Val::TextShadow(mix_shadow(&p, &q, t)) - } - } (Val::Visible(x), Val::Visible(y)) => Val::Visible(if t <= 0.0 { *x } else if t >= 1.0 { diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs index 675daff1..36ccfb53 100644 --- a/bindings/rust/blenderui/src/element.rs +++ b/bindings/rust/blenderui/src/element.rs @@ -359,6 +359,10 @@ impl Div { pub fn step(self, v: f64) -> Self { self.attr("step", v.to_string()) } + /// The decimals a number field or slider shows (Blender's property precision, 0 to 6). + pub fn precision(self, decimals: u8) -> Self { + self.attr("precision", decimals.to_string()) + } pub fn src(self, path: impl Into) -> Self { self.attr("src", path) } diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs index d29b422f..2069766b 100644 --- a/bindings/rust/blenderui/src/layout.rs +++ b/bindings/rust/blenderui/src/layout.rs @@ -77,7 +77,23 @@ pub(crate) struct UiState { /// Popovers and modal dialogs shown (`:popover-open`, `:modal`), by `Window::show_popover`. pub popover_open: KeySet, pub scroll: KeyMap, - pub checked: KeyMap, + /// A checkbox's or radio's state the user set, and its `checked` attribute when they did: theirs + /// holds until the app gives it another `checked` (see [`UiState::checked`]; the window drops + /// the record then, so the app's value holds from there on). + pub checked: KeyMap, +} + +impl UiState { + /// Whether the control `key` with the `checked` attribute `attr` is checked: as the user left it, + /// while the app's `checked` is the one they changed it from; else as the app says. So a control + /// kept in the app's state follows it, and one it leaves alone keeps the user's choice (a + /// browser's checkedness, set again by a changed attribute as a framework sets it). + pub(crate) fn checked(&self, key: Key, attr: bool) -> bool { + match self.checked.get(&key) { + Some(&(user, at)) if at == attr => user, + _ => attr, + } + } } // ========================================================================== @@ -313,7 +329,7 @@ pub(crate) struct ElData { pub later: smallvec::SmallVec<[(u16, u32); 1]>, } -const NONE: u32 = u32::MAX; +pub(crate) const NONE: u32 = u32::MAX; pub(crate) struct BoxNode { pub parent: Option, @@ -344,6 +360,10 @@ pub(crate) struct BoxNode { // filled after layout pub bounds: Bounds, pub clip: Option>, + /// The nearest box above this one whose `overflow` clips it to rounded corners (`NONE`: none): + /// `clip` is that box's padding box as a rectangle, paint cuts the corners (its bounds are read + /// when painting, so a box moved without a new layout keeps its clip). + pub round: u32, pub opacity: f32, pub visible: bool, pub scroll_range: (f32, f32), @@ -844,7 +864,7 @@ impl Subject for NodeRef<'_> { "active" => self.state.active.contains(&key), "focus" | "focus-visible" => self.state.focused == Some(key), "focus-within" => self.state.focus_path.contains(&key), - "checked" => self.state.checked.get(&key).copied().unwrap_or(self.own_attr("checked").is_some()), + "checked" => self.state.checked(key, self.own_attr("checked").is_some()), "disabled" => self.own_attr("disabled").is_some(), "enabled" => self.own_attr("disabled").is_none(), "link" | "any-link" => self.tag() == "a" && self.own_attr("href").is_some(), @@ -1087,7 +1107,7 @@ impl Subject for DivSubject<'_, '_> { "active" => self.state.active.contains(&key), "focus" | "focus-visible" => self.state.focused == Some(key), "focus-within" => self.state.focus_path.contains(&key), - "checked" => self.state.checked.get(&key).copied().unwrap_or(self.attr("checked").is_some()), + "checked" => self.state.checked(key, self.attr("checked").is_some()), "disabled" => self.attr("disabled").is_some(), "enabled" => self.attr("disabled").is_none(), "required" => self.attr("required").is_some(), @@ -1558,6 +1578,7 @@ impl<'a> Builder<'a> { styled: false, bounds: rect(0.0, 0.0, 0.0, 0.0), clip: None, + round: NONE, opacity: 1.0, visible: true, scroll_range: (0.0, 0.0), @@ -3061,7 +3082,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca } let mut walk = Walk { t: taffy, box_of, state, vp: viewport, styles, text: tc, seq: 0, 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_id, 0.0, 0.0, None, (0.0, 0.0)); + walk.place(&mut frame.nodes, root_id, 0.0, 0.0, (None, NONE), (0.0, 0.0)); finish(&mut frame.nodes, styles, acc); styles.end_frame(); frame @@ -3121,7 +3142,7 @@ pub(crate) fn replace(frame: &mut Frame, viewport: (f32, f32), state: &UiState, let LayoutCaches { styles, text, taffy, box_of, acc, .. } = caches; let mut walk = Walk { t: taffy, box_of, state, vp: viewport, styles, text, seq: 0, 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)); + walk.place(&mut frame.nodes, root, 0.0, 0.0, (None, NONE), (0.0, 0.0)); finish(&mut frame.nodes, styles, acc); frame.moved(); true @@ -3147,7 +3168,8 @@ struct Walk<'a> { impl Walk<'_> { /// `cb`: the origin of the containing block of absolutely positioned /// descendants (taffy places those relative to it, not to their parent). - fn place(&mut self, nodes: &mut [BoxNode], id: NodeId, ox: f32, oy: f32, clip: Option>, + #[allow(clippy::too_many_arguments)] + fn place(&mut self, nodes: &mut [BoxNode], id: NodeId, ox: f32, oy: f32, (clip, round): (Option>, u32), cb: (f32, f32)) { let l = *self.t.layout(id); let (mut x, mut y) = (ox + l.location.x, oy + l.location.y); @@ -3158,14 +3180,16 @@ impl Walk<'_> { y += dy; } let mut child_clip = clip; + let mut child_round = round; let (mut sx, mut sy) = (0.0, 0.0); let mut port = None; if let Some(i) = self.box_of.get(slot(id)).filter(|&&b| b != NONE).map(|&b| b as usize) { let st = &self.styles[nodes[i].style]; let u = st.units(self.vp); - // a word carries its owner's style: the owner's translate already moved the line it is in, - // unless the owner is an inline element (no box of its own to carry it) - let own_translate = !matches!(nodes[i].content, Content::Word { .. }) || nodes[nodes[i].owner].taffy.is_none(); + // a box without a style of its own (a word, a text run, an anonymous line box) carries its + // owner's: the owner's translate already moved it, unless the owner is an inline element + // (no box of its own to carry it) + let own_translate = owns_style(&nodes[i].content) || nodes[nodes[i].owner].taffy.is_none(); if own_translate { x += st.translate.0.resolve(&u, w); y += st.translate.1.resolve(&u, h); @@ -3179,9 +3203,13 @@ impl Walk<'_> { } nodes[i].bounds = rect(x, y, w, h); nodes[i].clip = clip; + nodes[i].round = round; nodes[i].seq = self.seq; self.seq += 1; - if let Some(cr) = clip_edges(st) { + // an anonymous box carries its owner's style: the owner's `clip` and `overflow` are its own, + // not cut again at the anonymous box + let own = owns_style(&nodes[i].content); + if let Some(cr) = clip_edges(st).filter(|_| own) { // edges from the border box's top-left corner; auto = that edge let e = |k: usize, auto: f32, basis: f32| cr[k].map_or(auto, |l| l.resolve(&u, basis)); let (top, right, bottom, left) = (e(0, 0.0, h), e(1, w, w), e(2, h, h), e(3, 0.0, w)); @@ -3193,7 +3221,7 @@ impl Walk<'_> { nodes[i].clip = Some(r); child_clip = Some(r); } - if overflow_clips(st) { + if own && overflow_clips(st) { let ov = st.layout.overflow; let b = l.border; let pad = rect(x + b.left, y + b.top, (w - b.left - b.right).max(0.0), @@ -3202,6 +3230,10 @@ impl Walk<'_> { Some(c) => c.intersect(&pad), None => pad, }); + // rounded corners clip too (CSS Backgrounds 3 §5.3): paint cuts them + if st.radius.iter().any(|r| *r != crate::geometry::Length::Px(0.0)) { + child_round = i as u32; + } // `hidden` is a scroll container too, scrolled by programs only: its range moves it, // the user's scrolling (scrollbars, wheel: `scroll_range`) is `scroll`'s let scrolls = |o: Overflow| matches!(o, Overflow::Scroll | Overflow::Hidden); @@ -3233,6 +3265,7 @@ impl Walk<'_> { place_folded_text(nodes, i, k, rect(x, y, w, h), &l, self.styles, self.text); // the text is clipped by its container's `overflow` nodes[k].clip = child_clip; + nodes[k].round = child_round; nodes[k].seq = self.seq; self.seq += 1; } @@ -3252,7 +3285,7 @@ impl Walk<'_> { Position::Fixed => (0.0, 0.0), _ => inner, }; - self.place(nodes, k, kx, ky, child_clip, cb); + self.place(nodes, k, kx, ky, (child_clip, child_round), cb); } (self.port, self.within) = saved; } @@ -3373,6 +3406,7 @@ fn finish(nodes: &mut [BoxNode], styles: &StyleStore, acc: &mut Vec), /// A GPU pass into a render target (see [`Painter::effect_to`]): not drawn into the canvas. Pass(Box), + /// CSS `box-shadow` (an outer one): the coords are the shadow's box, then the box casting it (the + /// shadow shows only outside that); `radius` is the shadow's corner, `cast_radius` the caster's, + /// `sigma` the blur's (a Gaussian; 0 a hard edge). + Shadow { radius: f32, cast_radius: f32, sigma: f32 }, } /// What [`Painter::effect_to`] records: the render target, the effect (0: a fill), its textures and floats. @@ -399,6 +403,9 @@ pub struct Painter { gpu: bool, /// The text selection to highlight (set before each paint; None: nothing is selected). pub(crate) sel: Option, + /// Device pixels per logical one of what this paints (0 before a frame sets it: 1), so that + /// clips cut along device rows ([`rounded_strips`]). + scale: f32, } impl Painter { @@ -447,6 +454,11 @@ impl Painter { let len = self.text[*start as usize..].iter().position(|&b| b == 0).unwrap_or(0); return Some([c[0], c[1], c[0] + len as f32 * size, c[1] + size * 1.5]); } + if let (Kind::Shadow { sigma, .. }, [x0, y0, x1, y1, ..]) = (kind, c) { + // the shadow's box (the caster's is under it) as far as the blur reaches + let g = 3.0 * sigma; + return Some([x0.min(*x1) - g, y0.min(*y1) - g, x0.max(*x1) + g, y0.max(*y1) + g]); + } let (mut x0, mut y0, mut x1, mut y1) = (c[0], c[1], c[0], c[1]); for xy in c.as_chunks::<2>().0 { x0 = x0.min(xy[0]); @@ -534,6 +546,11 @@ impl Painter { *width *= mean; } Kind::Oval { width, .. } | Kind::Line { width } => *width *= mean, + Kind::Shadow { radius, cast_radius, sigma } => { + *radius *= sx.min(sy); + *cast_radius *= sx.min(sy); + *sigma *= mean; + } // anchored at its top left: the size follows the height Kind::Text { size, .. } => *size *= sy, _ => {} @@ -572,6 +589,8 @@ impl Painter { Kind::Line { width } | Kind::Oval { width, .. } | Kind::Rect { width, .. } if width > 0.0 => { width * 0.5 + 1.0 } + // a Gaussian's reach + Kind::Shadow { sigma, .. } => 3.0 * sigma + 1.0, _ => 0.0, }; for p in xy.as_chunks::<2>().0 { @@ -635,6 +654,20 @@ impl Painter { Self::corners(bounds), fill); } + /// CSS `box-shadow` (an outer one): the rounded box `shadow` (corner `radius`) blurred by a + /// Gaussian of `sigma`, in `color`, showing only outside the rounded box `cast` (corner + /// `cast_radius`) that casts it. + fn shadow(&mut self, (shadow, radius): (Bounds, f32), (cast, cast_radius): (Bounds, f32), sigma: f32, + color: Rgba) { + if color.is_transparent() || shadow.size.width <= 0.0 || shadow.size.height <= 0.0 { + return; + } + let corners = |b: Bounds| [b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height]; + let coords: Vec = corners(shadow).into_iter().chain(corners(cast)).collect(); + self.push(Kind::Shadow { radius: radius.max(0.0), cast_radius: cast_radius.max(0.0), sigma: sigma.max(0.0) }, + Coords::Heap(coords), color); + } + /// An ellipse inscribed in `bounds`. pub fn oval(&mut self, bounds: Bounds, fill: impl Into, outline: impl Into, width: f32) { @@ -826,6 +859,13 @@ impl Painter { ci.width = (width * scale).max(1.0); } Kind::Polygon => ci.type_ = sys::BK_ITEM_POLYGON, + Kind::Shadow { radius, cast_radius, sigma } => { + ci.type_ = sys::BK_ITEM_SHADOW; + ci.radius = radius * scale; + ci.size = cast_radius * scale; + ci.width = sigma * scale; + ci.no_hit = 1; + } Kind::Arc { start, extent } => { ci.type_ = sys::BK_ITEM_ARC; ci.start = *start; @@ -1006,6 +1046,9 @@ impl Painter { Kind::Oval { outline, width } => (1u8, outline.to_array().map(f32::to_bits), width.to_bits()).hash(h), Kind::Line { width } => (2u8, width.to_bits()).hash(h), Kind::Polygon => 3u8.hash(h), + Kind::Shadow { radius, cast_radius, sigma } => { + (11u8, radius.to_bits(), cast_radius.to_bits(), sigma.to_bits()).hash(h) + } Kind::Arc { start, extent } => (4u8, start.to_bits(), extent.to_bits()).hash(h), Kind::Text { start, size, flags } => { let t = &self.text[*start as usize..]; @@ -1053,10 +1096,41 @@ pub(crate) fn border_widths(c: &Computed, w: f32) -> [f32; 4] { [lp(b.top, w), lp(b.right, w), lp(b.bottom, w), lp(b.left, w)] } +/// The box's largest corner radius, at most half its shorter side: one radius for what draws a +/// single one (shadows, outlines, layers' masks). fn radius_px(c: &Computed, b: Bounds, vp: (f32, f32)) -> f32 { + corner_radii(c, b, vp).into_iter().fold(0.0, f32::max).min(b.size.width.min(b.size.height) / 2.0) +} + +/// The corner radii of box `b` (top-left, top-right, bottom-right, bottom-left), shrunk together +/// where two on one side would overlap (CSS Backgrounds 3 §5.5). +fn corner_radii(c: &Computed, b: Bounds, vp: (f32, f32)) -> [f32; 4] { + if c.radius.iter().all(|r| *r == crate::geometry::Length::Px(0.0)) { + return [0.0; 4]; + } let u = c.units(vp); - let m = b.size.width.min(b.size.height); - c.radius.iter().map(|r| r.resolve(&u, m)).fold(0.0, f32::max).min(m / 2.0) + let (w, h) = (b.size.width, b.size.height); + let r: [f32; 4] = std::array::from_fn(|k| c.radius[k].resolve(&u, w.min(h)).max(0.0)); + let f = [w / (r[0] + r[1]), h / (r[1] + r[2]), w / (r[2] + r[3]), h / (r[3] + r[0])] + .into_iter() + .filter(|f| f.is_finite()) + .fold(1.0f32, f32::min) + .max(0.0); + r.map(|v| v * f) +} + +/// Whether all four radii are one (the kit's rounded box draws those). +fn one_radius(r: &[f32; 4]) -> bool { + r.iter().all(|v| (v - r[0]).abs() < 0.01) +} + +/// The radii of box `b`'s corners on a box `d` inside it on every side (a border, padding or +/// content box): each smaller by how far in it is, never below 0. +fn radii_inside(r: [f32; 4], b: Bounds, d: Bounds) -> [f32; 4] { + let (l, t) = (d.origin.x - b.origin.x, d.origin.y - b.origin.y); + let rt = b.origin.x + b.size.width - d.origin.x - d.size.width; + let bm = b.origin.y + b.size.height - d.origin.y - d.size.height; + [(r[0] - l.max(t)).max(0.0), (r[1] - rt.max(t)).max(0.0), (r[2] - rt.max(bm)).max(0.0), (r[3] - l.max(bm)).max(0.0)] } /// Paint every box of `frame`, in stacking order. `scale`: device pixels @@ -1075,6 +1149,7 @@ pub(crate) fn paint_frame(frame: &Frame, styles: &StyleStore, tc: &mut TextCache pub(crate) fn snapshot(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, keep: &dyn Fn(usize) -> bool, area: Bounds, vp: (f32, f32), scale: f32, app: &crate::window::App) -> Option> { let mut p = Painter::new(); + p.scale = scale; with_scratch(|s| { let PaintScratch { order, mats, .. } = s; order.clear(); @@ -1108,6 +1183,7 @@ pub(crate) fn snapshot(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, k fn paint_frame_with(s: &mut PaintScratch, frame: &Frame, styles: &StyleStore, tc: &mut TextCache, p: &mut Painter, vp: (f32, f32), scale: f32, app: &crate::window::App) { let PaintScratch { order, mats, done, tour, subs } = s; + p.scale = scale; order.clear(); match frame.order_modified(styles) { Some(o) => order.extend(o), @@ -1558,7 +1634,8 @@ fn paint_list(cx: &mut LayerCx, list: &[usize], p: &mut Painter, root: Option f32 { let outline = c.outline.0 + c.outline.2.max(0.0); - let shadows = c.shadows.iter().filter(|s| !s.inset).map(|s| s.x.abs().max(s.y.abs()) + s.blur + s.spread.max(0.0)); + // a blur is a Gaussian of half its radius: it reaches three of those (see `Painter::shadow`) + let shadows = c.shadows.iter().filter(|s| !s.inset).map(|s| s.x.abs().max(s.y.abs()) + 1.5 * s.blur + s.spread.max(0.0)); let image = c.effects.as_ref().and_then(|e| e.border_image.as_ref()).into_iter().flat_map(|bi| bi.outset).filter_map(|o| match o { Side::Len(Length::Px(v)) => Some(v), _ => None, @@ -1585,8 +1662,8 @@ fn spill(n: &BoxNode, c: &Computed) -> Option<(f32, f32)> { Content::Element | Content::Replaced(_) if n.taffy.is_some() && n.marker.is_none() => { Some((paint_reach(c), paint_reach(c))) } - Content::Word { .. } if c.text_shadow.is_none() => Some((c.font_size, c.font_size + decoration_reach(c))), - Content::Text(t) if (n.taffy.is_some() || n.folded) && c.text_shadow.is_none() => { + Content::Word { .. } if c.text_shadow.is_empty() => Some((c.font_size, c.font_size + decoration_reach(c))), + Content::Text(t) if (n.taffy.is_some() || n.folded) && c.text_shadow.is_empty() => { // each char advances by its width and the letter spacing (paint_text_line) let bytes = t.len() as f32 + 1.0; Some((bytes * (c.font_size + c.letter_spacing.abs()), bytes * c.line_px().max(c.font_size) + decoration_reach(c))) @@ -1706,6 +1783,7 @@ fn paint_layer_inner(cx: &mut LayerCx, root: usize, list: &[usize], p: &mut Pain let rel_opacity = (n.opacity / base.max(1e-6)).min(1.0); // the content, painted at full opacity relative to the root let mut sub = Painter::new(); + sub.scale = cx.scale; paint_list(cx, list, &mut sub, Some(root), n.opacity); inside.append(&mut sub.widgets); // the clip the layer is under is applied when its image is drawn: its @@ -2127,16 +2205,7 @@ fn redundant_background(frame: &Frame, styles: &StyleStore, n: &BoxNode) -> bool fn paint_inline_boxes(frame: &Frame, styles: &StyleStore, i: usize, p: &mut Painter) { let n = &frame.nodes[i]; let b = n.bounds; - let mut chain: smallvec::SmallVec<[usize; 4]> = smallvec::SmallVec::new(); - let mut o = Some(n.owner); - while let Some(k) = o.filter(|&k| k < frame.nodes.len()) { - let m = &frame.nodes[k]; - if m.taffy.is_some() || !matches!(m.content, Content::Element) || styles[m.style].display != DisplayKind::Inline { - break; - } - chain.push(k); - o = m.parent; - } + let chain = inline_boxes(frame, styles, i); // the item's baseline: where its own style's text sits in its box let c = &styles[n.style]; let base = text::baseline(b.origin.y, b.size.height, c.font_size, c.font_id); @@ -2212,12 +2281,17 @@ fn run_gap<'f>(frame: &'f Frame, styles: &StyleStore, tc: &mut TextCache, i: usi let looks = n.style == m.style || (c.font_size == d.font_size && text::flags(c) == text::flags(d) && c.color == d.color && c.underline == d.underline && c.line_through == d.line_through && c.overline == d.overline - && c.text_shadow.is_none() && d.text_shadow.is_none() && c.opacity == d.opacity); + && c.text_shadow.is_empty() && d.text_shadow.is_empty() && c.opacity == d.opacity); // (letter spacing paints per character, the same in a run: alike on both sides it joins) if !looks || (n.bounds.origin.y - m.bounds.origin.y).abs() > 0.01 || c.letter_spacing != d.letter_spacing || c.word_spacing != 0.0 || d.word_spacing != 0.0 { return None; } + // a word that paints a fragment of its inline box (a highlight) paints it after the run's first + // word drew the run: over the run's text, so it starts a run of its own + if inline_boxes(frame, styles, i).iter().any(|&b| paints_fragment(&styles[frame.nodes[b].style])) { + return None; + } let (prev, word) = (frame.text(k), frame.text(i)); if [prev, between, word].iter().any(|s| s.contains(['\t', crate::linebreak::SOFT_HYPHEN])) { return None; @@ -2236,6 +2310,29 @@ fn run_gap<'f>(frame: &'f Frame, styles: &StyleStore, tc: &mut TextCache, i: usi } } +/// The inline boxes line item `i` is in, innermost first (up to the first that isn't one). +fn inline_boxes(frame: &Frame, styles: &StyleStore, i: usize) -> smallvec::SmallVec<[usize; 4]> { + let mut chain = smallvec::SmallVec::new(); + let mut o = Some(frame.nodes[i].owner); + while let Some(k) = o.filter(|&k| k < frame.nodes.len()) { + let m = &frame.nodes[k]; + if m.taffy.is_some() || !matches!(m.content, Content::Element) || styles[m.style].display != DisplayKind::Inline { + break; + } + chain.push(k); + o = m.parent; + } + chain +} + +/// Whether an inline box paints a fragment under its words: a background or an image, borders, a +/// shadow or an outline (see [`paint_inline_boxes`]). +fn paints_fragment(c: &Computed) -> bool { + !c.background.is_transparent() || c.gradient.is_some() || c.images.is_some() || !c.shadows.is_empty() + || c.outline.0 > 0.0 + || (0..4).any(|k| !c.border_color[k].is_transparent() && border_widths(c, 0.0)[k] > 0.0) +} + /// The last word box of the run word box `i` starts (`i` itself when none continues it). fn run_after(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize) -> usize { let mut j = i; @@ -2248,6 +2345,18 @@ fn run_after(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize) - fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize, p: &mut Painter, vp: (f32, f32), app: &crate::window::App) { let n = &frame.nodes[i]; + // under a box whose `overflow` rounds its corners: what this paints there is cut to them after + let rounded = (n.round != crate::layout::NONE).then_some((n.round as usize, p.items.len())); + paint_node_items(frame, styles, tc, i, p, vp, app); + if let Some((round, from)) = rounded { + clip_to_rounded(p, from, frame, styles, round, vp); + } +} + +/// What box `i` paints (see [`paint_node`]). +fn paint_node_items(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize, p: &mut Painter, + vp: (f32, f32), app: &crate::window::App) { + let n = &frame.nodes[i]; let c = &styles[n.style]; p.through = !c.pointer_events; p.snap = true; // a CSS box (a canvas's own drawing turns it off) @@ -2488,19 +2597,15 @@ fn paint_text_line_as(p: &mut Painter, tc: &mut TextCache, c: &Computed, s: &str let s: std::borrow::Cow = if c.small_caps { s.to_uppercase().into() } else { s.into() }; let size_draw = if c.small_caps { size * 0.8 } else { size }; let top = text::item_top(base, size_draw); - if let Some(sh) = c.text_shadow { - p.styled_text(x + sh.x, top + sh.y, &s, size_draw, flags, sh.color); - } - if c.letter_spacing != 0.0 { - let mut cx = x; - for ch in s.chars() { - let t = ch.to_string(); - p.styled_text(cx, top, &t, size_draw, flags, c.color); - cx += tc.width(&t, size_draw, flags) + c.letter_spacing; + // shadows under the text, the first on top: each the run itself, moved (and blurred) + for sh in c.text_shadow.iter().rev() { + if sh.blur > 0.0 { + blurred_run(p, tc, (&s, c.letter_spacing), (x + sh.x, top + sh.y), (size_draw, flags), sh.color, sh.blur / 2.0); + } else { + text_run(p, tc, (&s, c.letter_spacing), (x + sh.x, top + sh.y), (size_draw, flags), sh.color); } - } else { - p.styled_text(x, top, &s, size_draw, flags, c.color); } + text_run(p, tc, (&s, c.letter_spacing), (x, top), (size_draw, flags), c.color); if c.underline || c.line_through || c.overline { let w = width.unwrap_or_else(|| tc.width(s.trim_end(), size_draw, flags)); let thick = decoration_thickness(c); @@ -2519,6 +2624,71 @@ fn paint_text_line_as(p: &mut Painter, tc: &mut TextCache, c: &Computed, s: &str } } +/// A line of text `s` at (`x`, `top`): one run, or with `letter-spacing` each character spaced +/// out (the text and each of its shadows place their glyphs alike). +fn text_run(p: &mut Painter, tc: &mut TextCache, (s, spacing): (&str, f32), (x, top): (f32, f32), (size, flags): (f32, i32), + color: Rgba) { + if spacing == 0.0 { + p.styled_text(x, top, s, size, flags, color); + return; + } + let mut cx = x; + let mut buf = [0u8; 4]; + for ch in s.chars() { + let t: &str = ch.encode_utf8(&mut buf); + p.styled_text(cx, top, t, size, flags, color); + cx += tc.width(t, size, flags) + spacing; + } +} + +/// [`text_run`] blurred by a Gaussian of `sigma` (a `text-shadow`'s blur): rasterized once, +/// blurred, and kept as an image by what it looks like (a line that moves draws the same one). +#[allow(clippy::too_many_arguments)] +fn blurred_run(p: &mut Painter, tc: &mut TextCache, run: (&str, f32), at: (f32, f32), font: (f32, i32), color: Rgba, + sigma: f32) { + use std::hash::{Hash, Hasher}; + thread_local! { + static BLURRED: std::cell::RefCell>> = std::cell::RefCell::new(HashMap::new()); + } + let mut sub = Painter::new(); + let scale = if p.scale > 0.0 { p.scale } else { 1.0 }; + sub.scale = scale; + text_run(&mut sub, tc, run, at, font, color); + let Some(ink) = sub.extent(tc) else { return }; + // as far as the blur reaches + let g = 3.0 * sigma; + let area = rect(ink.origin.x - g, ink.origin.y - g, ink.size.width + 2.0 * g, ink.size.height + 2.0 * g); + let (x0, y0, w, h) = device_rect(area, scale); + if w == 0 || h == 0 || w > crate::effects::MAX_RASTER || h > crate::effects::MAX_RASTER { + return; + } + let placed = rect(x0 / scale, y0 / scale, w as f32 / scale, h as f32 / scale); + let key = { + let mut hh = key_hasher(); + sub.content_hash(&mut hh, placed, placed.origin.x, placed.origin.y); + (sigma.to_bits(), scale.to_bits(), w, h).hash(&mut hh); + hh.finish() + }; + let img = BLURRED.with(|m| m.borrow().get(&key).cloned()).or_else(|| { + let mut px = sub.rasterize_argb(scale, x0, y0, w, h)?; + crate::effects::blur_argb(&mut px, sigma * scale); + let img = Arc::new(Image::from_argb(&px)?); + BLURRED.with(|m| { + let mut m = m.borrow_mut(); + if m.len() > 128 { + m.clear(); + } + m.insert(key, img.clone()); + }); + Some(img) + }); + if let Some(img) = img { + let snap = std::mem::replace(&mut p.snap, false); + p.image(placed, &img); + p.snap = snap; + } +} + /// The thickness a decoration line draws at: `text-decoration-thickness`, else 1/14 em. fn decoration_thickness(c: &Computed) -> f32 { c.decoration_thickness.unwrap_or(c.font_size / 14.0).max(1.0) @@ -2569,21 +2739,21 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba return; } let r = radius_px(c, b, vp); - // outer shadows, the first on top (CSS Backgrounds 6.1); an empty box's spread still shows + // each corner's own radius (`border-radius: 56px 56px 6px 6px`): drawn as one rounded box when + // they are one, else as a polygon + let radii = corner_radii(c, b, vp); + // outer shadows, the first on top (CSS Backgrounds 6.1); an empty box's spread still shows. Each + // is the border box moved and spread, blurred by a Gaussian of half the blur radius (7.2), and + // shows only outside the border box (7.1.1) for s in c.shadows.iter().rev().filter(|s| !s.inset) { - let steps = (s.blur / 2.0).ceil().clamp(1.0, 8.0) as usize; - for k in 0..steps { - let grow = s.spread + s.blur * (k as f32 + 1.0) / (steps as f32 + 1.0); - let a = s.color.a / steps as f32 * if s.blur > 0.0 { 1.0 } else { steps as f32 }; - let (w, h) = (b.size.width + 2.0 * grow, b.size.height + 2.0 * grow); - if w <= 0.0 || h <= 0.0 { - continue; - } - let sb = rect(b.origin.x + s.x - grow, b.origin.y + s.y - grow, w, h); - // square corners stay square under spread; the blur rounds them - let corner = if r > 0.0 { (r + grow).max(0.0) } else { (grow - s.spread).max(0.0) }; - p.quad(sb, corner, s.color.alpha(a), Rgba::TRANSPARENT, 0.0); + let (w, h) = (b.size.width + 2.0 * s.spread, b.size.height + 2.0 * s.spread); + if w <= 0.0 || h <= 0.0 { + continue; } + let sb = rect(b.origin.x + s.x - s.spread, b.origin.y + s.y - s.spread, w, h); + // square corners stay square under spread + let corner = if r > 0.0 { (r + s.spread).max(0.0) } else { 0.0 }; + p.shadow((sb, corner), (b, r), s.blur / 2.0, s.color); } if b.size.width <= 0.0 && b.size.height <= 0.0 { return; @@ -2598,6 +2768,7 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba let clip_box = edge_box(c, b, c.bg_clip, &bw); let clip_box = if local { clip_box.intersect(&edge_box(c, b, BoxEdge::Padding, &bw)) } else { clip_box }; let clip_r = (r - (clip_box.origin.x - b.origin.x)).max(0.0); + let clip_radii = radii_inside(radii, b, clip_box); let origin_area = |st: &crate::style::ImageStyle| { if st.bg_fixed { return rect(0.0, 0.0, vp.0, vp.1); @@ -2611,7 +2782,11 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba } }; if !(skip_background && c.bg_clip == BoxEdge::Border) && !c.background.is_transparent() { - p.quad(clip_box, clip_r, c.background, Rgba::TRANSPARENT, 0.0); + if one_radius(&clip_radii) { + p.quad(clip_box, clip_r, c.background, Rgba::TRANSPARENT, 0.0); + } else { + p.polygon(&rounded_points(clip_box, clip_radii), c.background); + } } if let Some(g) = &c.gradient { // a gradient is an image with no natural size: sized, positioned and repeated as one @@ -2632,7 +2807,7 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba None => p.with_clip(t, |p| paint_gradient(p, g, t)), } }); - if clip_r > 0.0 { with_rounded_clip(p, clip_box, clip_r, tiles) } else { tiles(p) } + if clip_radii.iter().any(|r| *r > 0.0) { with_rounded_clip(p, clip_box, clip_radii, tiles) } else { tiles(p) } } if let Some(st) = c.images.as_deref().filter(|st| st.bg_url.is_some()) { // `background-origin` positions the image, `-attachment: fixed` against the viewport @@ -2660,7 +2835,7 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba } }; if pad_r > 0.0 { - with_rounded_clip(p, pad, pad_r, paint); + with_rounded_clip(p, pad, radii_inside(radii, b, pad), paint); } else { p.with_clip(pad, paint); } @@ -2679,6 +2854,8 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba let styles: [BorderStyle; 4] = std::array::from_fn(|k| c.border_style[k]); let widths: [f32; 4] = std::array::from_fn(|k| if visible.contains(&k) { bw[k] } else { 0.0 }); paint_edges(p, b, widths, c.border_color, styles); + } else if uniform && !one_radius(&radii) { + stroke_rounded4(p, b, radii, bw[0], c.border_color[0]); } else if uniform { // the kit draws an outline inside its rectangle, as a border is inside the border box p.quad(b, r, Rgba::TRANSPARENT, c.border_color[0], bw[0]); @@ -2719,25 +2896,49 @@ const CORNERVEC: [[f32; 2]; 9] = [ /// edge's start), with each point's outward normal direction: 0 top, /// 1 right, 2 bottom, 3 left (corners split at their middle). fn rounded_path(b: Bounds, r: f32) -> Vec<(f32, f32, usize)> { - let (x0, y0, x1, y1) = (b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height); let r = r.min(b.size.width / 2.0).min(b.size.height / 2.0).max(0.0); + rounded_path4(b, [r; 4]) +} + +/// [`rounded_path`] with a radius a corner (top-left, top-right, bottom-right, bottom-left; each +/// fits its sides already, see [`corner_radii`]). +fn rounded_path4(b: Bounds, r: [f32; 4]) -> Vec<(f32, f32, usize)> { + let (x0, y0, x1, y1) = (b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height); + let [tl, tr, br, bl] = r.map(|v| v.max(0.0)); let mut pts = Vec::with_capacity(40); // top-right, bottom-right, bottom-left, top-left corners, like Blender's round_box edges for (k, v) in CORNERVEC.iter().enumerate() { - pts.push((x1 - r + v[0] * r, y0 + r - (1.0 - v[1]) * r, if k < 5 { 0 } else { 1 })); + pts.push((x1 - tr + v[0] * tr, y0 + tr - (1.0 - v[1]) * tr, if k < 5 { 0 } else { 1 })); } for (k, v) in CORNERVEC.iter().enumerate() { - pts.push((x1 - r + (1.0 - v[1]) * r, y1 - r + v[0] * r, if k < 5 { 1 } else { 2 })); + pts.push((x1 - br + (1.0 - v[1]) * br, y1 - br + v[0] * br, if k < 5 { 1 } else { 2 })); } for (k, v) in CORNERVEC.iter().enumerate() { - pts.push((x0 + r - v[0] * r, y1 - r + (1.0 - v[1]) * r, if k < 5 { 2 } else { 3 })); + pts.push((x0 + bl - v[0] * bl, y1 - bl + (1.0 - v[1]) * bl, if k < 5 { 2 } else { 3 })); } for (k, v) in CORNERVEC.iter().enumerate() { - pts.push((x0 + r - (1.0 - v[1]) * r, y0 + r - v[0] * r, if k < 5 { 3 } else { 0 })); + pts.push((x0 + tl - (1.0 - v[1]) * tl, y0 + tl - v[0] * tl, if k < 5 { 3 } else { 0 })); } pts } +/// The points of a rounded box's outline ([`rounded_path4`]). +fn rounded_points(b: Bounds, r: [f32; 4]) -> Vec<(f32, f32)> { + rounded_path4(b, r).into_iter().map(|(x, y, _)| (x, y)).collect() +} + +/// The ring between the rounded box `b` (radii `r`) and the one `w` inside it: one polygon of +/// both outlines (even-odd fills the ring), joined where each starts. +fn stroke_rounded4(p: &mut Painter, b: Bounds, r: [f32; 4], w: f32, color: Rgba) { + let inner = rect(b.origin.x + w, b.origin.y + w, (b.size.width - 2.0 * w).max(0.0), (b.size.height - 2.0 * w).max(0.0)); + let mut pts = rounded_points(b, r); + let hole = rounded_points(inner, r.map(|v| (v - w).max(0.0))); + pts.push(pts[0]); + pts.extend(hole.iter().copied()); + pts.push(hole[0]); + p.polygon(&pts, color); +} + /// Non-solid uniform borders on a rounded box: dashes and dots follow the /// curve, `double` is two rounded lines, and groove / ridge / inset / outset /// shade each side's part of the path. @@ -2833,11 +3034,15 @@ fn gradient_image(g: &crate::style::Gradient, w: f32, h: f32) -> Option Image::from_argb(&radial_pixels(g, &r, iw, ih))?, + crate::style::GradientShape::Linear { .. } => { + let mut gp = Painter::new(); + let area = rect(0.0, 0.0, iw as f32, ih as f32); + gp.with_clip(area, |gp| paint_gradient(gp, g, area)); + Image::from_argb(&gp.rasterize(1.0, 0.0, 0.0, iw, ih)?.to_argb())? + } + }); GRADIENTS.with(|m| { let mut m = m.borrow_mut(); if m.len() > 64 { @@ -2848,6 +3053,47 @@ fn gradient_image(g: &crate::style::Gradient, w: f32, h: f32) -> Option crate::effects::Argb { + use crate::style::RadialSize; + let (bw, bh) = (w as f32, h as f32); + let (cx, cy) = (r.at[0].at(bw), r.at[1].at(bh)); + // the distances to the sides, and the corner farthest / closest + let (dx_near, dx_far) = (cx.abs().min((bw - cx).abs()), cx.abs().max((bw - cx).abs())); + let (dy_near, dy_far) = (cy.abs().min((bh - cy).abs()), cy.abs().max((bh - cy).abs())); + let (rx, ry) = match r.size { + RadialSize::Radii(x, y) => (x.at(bw), y.at(bh)), + RadialSize::Extent { corner, farthest } => { + let (sx, sy) = if farthest { (dx_far, dy_far) } else { (dx_near, dy_near) }; + match (r.circle, corner) { + (true, false) => if farthest { (sx.max(sy), sx.max(sy)) } else { (sx.min(sy), sx.min(sy)) }, + (true, true) => { + let d = sx.hypot(sy); + (d, d) + } + (false, false) => (sx, sy), + // the side's aspect, grown until it passes through the corner (that is, by √2) + (false, true) => (sx * std::f32::consts::SQRT_2, sy * std::f32::consts::SQRT_2), + } + } + }; + let (rx, ry) = (rx.max(1e-3), ry.max(1e-3)); + let stops = g.resolved(rx); + let mut px = vec![0u32; w * h]; + for (j, row) in px.chunks_exact_mut(w).enumerate() { + let dy = (j as f32 + 0.5 - cy) / ry; + for (i, out) in row.iter_mut().enumerate() { + let dx = (i as f32 + 0.5 - cx) / rx; + let c = gradient_at(&stops, dx.hypot(dy)); + let a = c.a.clamp(0.0, 1.0); + let ch = |v: f32| (v.clamp(0.0, 1.0) * a * 255.0 + 0.5) as u32; + *out = ((a * 255.0 + 0.5) as u32) << 24 | ch(c.r) << 16 | ch(c.g) << 8 | ch(c.b); + } + } + crate::effects::Argb { w, h, px } +} + /// A sub-rectangle of an image (whole pixels), cached. fn crop(img: &Arc, x: u32, y: u32, w: u32, h: u32) -> Option> { if w == 0 || h == 0 || x + w > img.width || y + h > img.height { @@ -3070,34 +3316,198 @@ fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba { a: a.a + (b.a - a.a) * t } } -/// Runs `f` clipped to the rounded box `b` (radius `r`): one clip for the -/// straight middle, and thin rows across the corners, each as wide as the -/// rounded outline at its height (gradients have no rounded fill of their own). -fn with_rounded_clip(p: &mut Painter, b: Bounds, r: f32, f: impl Fn(&mut Painter)) { +/// Runs `f` clipped to the rounded box `b` (radii as [`corner_radii`]): what it paints is cut to +/// the corners after ([`round_items`]; gradients have no rounded fill of their own). +fn with_rounded_clip(p: &mut Painter, b: Bounds, r: [f32; 4], f: impl FnOnce(&mut Painter)) { + let from = p.items.len(); + p.with_clip(b, f); + round_items(p, from, b, r); +} + +/// The rounded box `b` (radii `r`) as rectangles that cover it once: rows one device pixel tall +/// across the corners (`scale` device pixels per logical one), each as wide as the rounded outline +/// at its height, and the straight middle. Each sits inside its device rows (a clip is cut to whole +/// pixels, so neighbours never share one), and rows with the same edges in device pixels are one. +fn rounded_strips(b: Bounds, r: [f32; 4], scale: f32) -> Vec> { + let s = if scale > 0.0 { scale } else { 1.0 }; let (x, y, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); - let r = r.min(w / 2.0).min(h / 2.0); - if r < 0.5 { - p.with_clip(b, |p| f(p)); + let [tl, tr, br, bl] = r; + let (top, bottom) = (tl.max(tr), bl.max(br)); + if (top * s < 0.5 && bottom * s < 0.5) || w <= 0.0 || h <= 0.0 { + return vec![b]; + } + // whole device rows from `k0` to `k1` (exclusive), as a clip + let rows = |k0: i64, k1: i64, l: f32, rr: f32| rect(l, (k0 as f32 + 0.02) / s, rr - l, (k1 - k0) as f32 / s - 0.04 / s); + // how far in the outline is at depth `d` into a corner of radius `r` + let inset = |r: f32, d: f32| if d >= r { 0.0 } else { r - (r * r - (r - d.max(0.0)).powi(2)).max(0.0).sqrt() }; + // the top band's device rows, the straight middle's, the bottom band's + let t0 = (y * s).floor() as i64; + let t1 = ((y + top) * s).ceil() as i64; + let b1 = ((y + h) * s).ceil() as i64; + let b0 = (((y + h - bottom) * s).floor() as i64).max(t1).min(b1); + let t1 = t1.min(b1); + let mut out: Vec> = Vec::new(); + // a run of rows with the same edges in device pixels: (first row, left, right) + let mut run: Option<(i64, i64, i64)> = None; + let mut corner_rows = |ks: std::ops::Range, out: &mut Vec>| { + for k in ks.clone() { + let yc = (k as f32 + 0.5) / s; + let (dt, db) = (yc - y, y + h - yc); + let left = inset(tl, dt).max(inset(bl, db)); + let right = inset(tr, dt).max(inset(br, db)); + let (l, rr) = (((x + left) * s).floor() as i64, ((x + w - right) * s).ceil() as i64); + match run { + Some((_, pl, pr)) if pl == l && pr == rr => continue, + Some((k0, pl, pr)) if pr > pl => out.push(rows(k0, k, (pl as f32 + 0.02) / s, (pr as f32 - 0.02) / s)), + _ => {} + } + run = Some((k, l, rr)); + } + if let Some((k0, pl, pr)) = run.take() + && pr > pl + { + out.push(rows(k0, ks.end, (pl as f32 + 0.02) / s, (pr as f32 - 0.02) / s)); + } + }; + corner_rows(t0..t1, &mut out); + if b0 > t1 { + out.push(rows(t1, b0, x, x + w)); + } + corner_rows(b0..b1, &mut out); + out +} + +/// The items from `from` on (what one box painted) cut to the rounded corners of box `round`, whose +/// `overflow` clips them (its padding box: see [`round_items`]). +fn clip_to_rounded(p: &mut Painter, from: usize, frame: &Frame, styles: &StyleStore, round: usize, vp: (f32, f32)) { + // items over a widget start a canvas of their own at their index: leave those as they are + if p.segments.last().is_some_and(|&seg| seg as usize > from) { return; } - p.with_clip(rect(x, y + r, w, h - 2.0 * r), |p| f(p)); - const ROW: f32 = 0.5; // device rows at 2x - let rows = (r / ROW).ceil() as usize; - for k in 0..rows { - let y0 = k as f32 * ROW; - let rh = ROW.min(r - y0); - let dy = r - (y0 + rh / 2.0); // distance from the corner centres' line - let inset = r - (r * r - dy * dy).max(0.0).sqrt(); - let rw = w - 2.0 * inset; - if rw <= 0.0 { + let n = &frame.nodes[round]; + let c = &styles[n.style]; + let b = n.bounds; + let bw = border_widths(c, b.size.width); + let pad = rect(b.origin.x + bw[3], b.origin.y + bw[0], (b.size.width - bw[1] - bw[3]).max(0.0), + (b.size.height - bw[0] - bw[2]).max(0.0)); + round_items(p, from, pad, radii_inside(corner_radii(c, b, vp), b, pad)); +} + +/// The items from `from` on cut to the rounded box `b` (radii `r`): only those reaching into a +/// corner (the rest are inside it already, as far as their rectangular clip lets them). A filled +/// box or a convex polygon (a gradient's band) becomes its part inside, anti-aliased (the rounded +/// box is convex too); anything else is drawn once in each of [`rounded_strips`]. +fn round_items(p: &mut Painter, from: usize, b: Bounds, r: [f32; 4]) { + if r.iter().all(|v| *v * p.scale.max(1.0) < 0.5) || p.items.len() <= from { + return; + } + let (x0, y0, x1, y1) = (b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height); + let corners = [rect(x0, y0, r[0], r[0]), rect(x1 - r[1], y0, r[1], r[1]), rect(x1 - r[2], y1 - r[2], r[2], r[2]), + rect(x0, y1 - r[3], r[3], r[3])]; + let mut strips: Option>> = None; + let mut outline: Option> = None; + for it in p.items.split_off(from) { + let Some([ax0, ay0, ax1, ay1]) = p.item_area(&it.kind, &it.coords) else { + p.items.push(it); + continue; + }; + let area = rect(ax0, ay0, ax1 - ax0, ay1 - ay0); + let area = it.clip.map_or(area, |c| c.intersect(&area)); + let reaches = corners.iter().any(|k| { + let o = k.intersect(&area); + k.size.width > 0.0 && o.size.width > 0.0 && o.size.height > 0.0 + }); + if !reaches { + p.items.push(it); + continue; + } + // its shape, when it is a convex one filled + let shape: Option> = match (&it.kind, it.coords.as_slice()) { + (Kind::Rect { radius, width, .. }, [x, y, xe, ye, ..]) if *width <= 0.0 => { + let own = rect(x.min(*xe), y.min(*ye), (xe - x).abs(), (ye - y).abs()); + Some(rounded_points(own, [radius.min(own.size.width.min(own.size.height) / 2.0); 4])) + } + (Kind::Polygon, xy) => { + let pts: Vec<(f32, f32)> = xy.as_chunks::<2>().0.iter().map(|q| (q[0], q[1])).collect(); + convex(&pts).then_some(pts) + } + _ => None, + }; + if let Some(shape) = shape { + let cut = clip_convex(&shape, outline.get_or_insert_with(|| rounded_points(b, r))); + if cut.len() >= 3 { + p.items.push(Item { kind: Kind::Polygon, coords: Coords::of_points(&cut), snap: false, ..it }); + } + continue; + } + for strip in strips.get_or_insert_with(|| rounded_strips(b, r, p.scale)).iter() { + let cut = it.clip.map_or(*strip, |c| c.intersect(strip)); + let o = cut.intersect(&area); + if o.size.width > 0.0 && o.size.height > 0.0 { + p.items.push(Item { clip: Some(cut), ..it.clone() }); + } + } + } +} + +/// Whether the polygon `pts` is convex (every turn the same way; a straight run turns neither). +fn convex(pts: &[(f32, f32)]) -> bool { + let n = pts.len(); + if n < 3 { + return false; + } + let mut sign = 0.0f32; + for k in 0..n { + let (a, b, c) = (pts[k], pts[(k + 1) % n], pts[(k + 2) % n]); + let turn = (b.0 - a.0) * (c.1 - b.1) - (b.1 - a.1) * (c.0 - b.0); + if turn.abs() < 1e-6 { + continue; + } + if sign == 0.0 { + sign = turn.signum(); + } else if turn.signum() != sign { + return false; + } + } + sign != 0.0 +} + +/// The convex polygon `subject` cut to the convex polygon `clip` (Sutherland-Hodgman). +fn clip_convex(subject: &[(f32, f32)], clip: &[(f32, f32)]) -> Vec<(f32, f32)> { + // which side is inside: the clip's winding + let area: f32 = clip.iter().zip(clip.iter().cycle().skip(1)).map(|(a, b)| a.0 * b.1 - b.0 * a.1).sum(); + let sign = if area >= 0.0 { 1.0 } else { -1.0 }; + let mut out = subject.to_vec(); + for k in 0..clip.len() { + let (a, b) = (clip[k], clip[(k + 1) % clip.len()]); + if (b.0 - a.0).abs() < 1e-6 && (b.1 - a.1).abs() < 1e-6 { continue; } - p.with_clip(rect(x + inset, y + y0, rw, rh), |p| f(p)); - p.with_clip(rect(x + inset, y + h - y0 - rh, rw, rh), |p| f(p)); + let side = |q: (f32, f32)| sign * ((b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0)); + let input = std::mem::take(&mut out); + for (j, &cur) in input.iter().enumerate() { + let prev = input[(j + input.len() - 1) % input.len()]; + let (sc, sp) = (side(cur), side(prev)); + if sc >= 0.0 { + if sp < 0.0 { + let t = sp / (sp - sc); + out.push((prev.0 + (cur.0 - prev.0) * t, prev.1 + (cur.1 - prev.1) * t)); + } + out.push(cur); + } else if sp >= 0.0 { + let t = sp / (sp - sc); + out.push((prev.0 + (cur.0 - prev.0) * t, prev.1 + (cur.1 - prev.1) * t)); + } + } + if out.is_empty() { + break; + } } + out } -/// Colour at position `t` (0..1) along a gradient's resolved `stops`. +/// Colour at position `t` (0..1) along a gradient's resolved `stops`, mixed in premultiplied +/// alpha (CSS Images 4 §3.5.4: a fade to `transparent` is not darkened by its black). fn gradient_at(stops: &[(Rgba, f32)], t: f32) -> Rgba { let Some(&(first, p0)) = stops.first() else { return Rgba::TRANSPARENT }; if t <= p0 { @@ -3106,29 +3516,39 @@ fn gradient_at(stops: &[(Rgba, f32)], t: f32) -> Rgba { for w in stops.windows(2) { let ((c0, a), (c1, b)) = (w[0], w[1]); if t <= b { - return if b - a < 1e-6 { c1 } else { mix(c0, c1, (t - a) / (b - a)) }; + return if b - a < 1e-6 { c1 } else { mix_premultiplied(c0, c1, (t - a) / (b - a)) }; } } stops[stops.len() - 1].0 } +/// `a` to `b` by `t` with their colours weighted by their alpha. +fn mix_premultiplied(a: Rgba, b: Rgba, t: f32) -> Rgba { + let alpha = a.a + (b.a - a.a) * t; + if alpha <= 1e-6 { + return Rgba::TRANSPARENT; + } + let ch = |x: f32, y: f32| (x * a.a + (y * b.a - x * a.a) * t) / alpha; + Rgba { r: ch(a.r, b.r), g: ch(a.g, b.g), b: ch(a.b, b.b), a: alpha } +} + /// Gradients as bands: horizontal/vertical strips, or rings for radial ones. fn paint_gradient(p: &mut Painter, g: &crate::style::Gradient, b: Bounds) { const BANDS: usize = 48; let (x, y, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); - if g.radial { - let stops = g.resolved((w * w + h * h).sqrt() / 2.0); - for k in (0..BANDS).rev() { - let t = (k as f32 + 0.5) / BANDS as f32; - let f = (k + 1) as f32 / BANDS as f32; - let (rw, rh) = (w * f * std::f32::consts::SQRT_2, h * f * std::f32::consts::SQRT_2); - p.oval(rect(x + (w - rw) / 2.0, y + (h - rh) / 2.0, rw, rh), gradient_at(&stops, t), - Rgba::TRANSPARENT, 0.0); + let angle_deg = match g.shape { + crate::style::GradientShape::Radial(_) => { + // every pixel its own colour: rings of a colour each band where the stops fade, and + // stacked translucent ones add up + if let Some(img) = gradient_image(g, w, h) { + p.image(b, &img); + } + return; } - return; - } + crate::style::GradientShape::Linear { angle_deg } => angle_deg, + }; // angle: 180deg = to bottom, 90deg = to right - let a = g.angle_deg.to_radians(); + let a = angle_deg.to_radians(); let (dx, dy) = (a.sin(), -a.cos()); let len = (w * dx.abs() + h * dy.abs()).max(1.0); let (cx, cy) = (x + w / 2.0, y + h / 2.0); diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs index cc8b4591..6da795b4 100644 --- a/bindings/rust/blenderui/src/style.rs +++ b/bindings/rust/blenderui/src/style.rs @@ -217,13 +217,40 @@ pub struct CounterOps { #[derive(Clone, Debug, PartialEq)] pub struct Gradient { - pub radial: bool, - pub angle_deg: f32, + pub shape: GradientShape, /// Colour stops, with their positions on the gradient line when given (`50%`, `75px`, /// `calc(100% - 10px)`). pub stops: Vec<(Rgba, Option)>, } +/// Which way a gradient runs (CSS Images 3 §3.1, §3.2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum GradientShape { + /// Along a line at `angle_deg` (0 = to top, 90 = to right). + Linear { angle_deg: f32 }, + /// Out from a centre: a circle or an ellipse. + Radial(Radial), +} + +/// A `radial-gradient()`'s ending shape: a circle (one radius) or an ellipse, its size and its +/// centre (`at `, against the box). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Radial { + pub circle: bool, + pub size: RadialSize, + pub at: [Pos; 2], +} + +/// How big a radial gradient's ending shape is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RadialSize { + /// `closest-side`, `farthest-side`, `closest-corner`, `farthest-corner` (the default). + Extent { corner: bool, farthest: bool }, + /// The radii, x and y (a circle's are the same length); a percentage is of the box's + /// width / height. + Radii(Pos, Pos), +} + impl Gradient { /// The stops at fractions of a gradient line `len` px long (CSS Images 3 §3.5.3: a first or /// last stop without a position is at the start or end, a position before an earlier one is @@ -567,7 +594,8 @@ pub struct Computed { pub marker_inside: bool, /// `quotes`: None = the default curly quotes. pub quotes: Option<(String, String)>, - pub text_shadow: Option, + /// `text-shadow`: the first on top. + pub text_shadow: Vec, pub decoration_color: Option, pub decoration_style: DecoStyle, /// `text-decoration-thickness` in px (None: auto / from-font). @@ -696,7 +724,7 @@ impl Default for Computed { snap_align: (0, 0), marker_inside: false, quotes: None, - text_shadow: None, + text_shadow: Vec::new(), decoration_color: None, decoration_style: DecoStyle::Solid, decoration_thickness: None, @@ -774,7 +802,7 @@ impl Computed { caption_bottom: parent.caption_bottom, marker_inside: parent.marker_inside, quotes: parent.quotes.clone(), - text_shadow: parent.text_shadow, + text_shadow: parent.text_shadow.clone(), vars: parent.vars, layout: Style { display: Display::Block, direction: parent.layout.direction, ..Default::default() }, ..Computed::default() @@ -1777,25 +1805,26 @@ fn grid_line(v: &[Tok]) -> Option>> { pub(crate) fn gradient(ctx: &Ctx, t: &Tok) -> Option { let Tok::Func(fx) = t else { return None }; let (f, args) = (&fx.name, &fx.args); - let radial = f.contains("radial"); if !f.contains("gradient") { return None; } - let mut angle = 180.0; + let radial = f.contains("radial"); + let mut shape = if radial { GradientShape::Radial(radial_shape(ctx, &[])?) } else { GradientShape::Linear { angle_deg: 180.0 } }; let mut first = 0; if let Some(a) = args.first() { match a.first() { - Some(Tok::Dim(v, u)) if u == "deg" || u == "turn" || u == "rad" => { - angle = match u.as_ref() { + Some(Tok::Dim(v, u)) if !radial && (u == "deg" || u == "turn" || u == "rad") => { + let angle_deg = match u.as_ref() { "turn" => v * 360.0, "rad" => v.to_degrees(), _ => *v, }; + shape = GradientShape::Linear { angle_deg }; first = 1; } - Some(Tok::Ident(s)) if s == "to" => { + Some(Tok::Ident(s)) if !radial && s == "to" => { let dirs: Vec<&str> = a[1..].iter().filter_map(Tok::ident).collect(); - angle = match dirs.as_slice() { + let angle_deg = match dirs.as_slice() { ["top"] => 0.0, ["right"] => 90.0, ["left"] => 270.0, @@ -1805,9 +1834,14 @@ pub(crate) fn gradient(ctx: &Ctx, t: &Tok) -> Option { } _ => if dirs.contains(&"right") { 135.0 } else { 225.0 }, }; + shape = GradientShape::Linear { angle_deg }; + first = 1; + } + // `circle`, `ellipse 40px 20px`, `farthest-side at 20% 30%`, `at center`: no colour in it + _ if radial && !a.iter().any(|t| color(t, ctx.c.color).is_some()) => { + shape = GradientShape::Radial(radial_shape(ctx, a)?); first = 1; } - Some(Tok::Ident(s)) if radial && !parse_color(s).is_some() => first = 1, _ => {} } } @@ -1821,7 +1855,46 @@ pub(crate) fn gradient(ctx: &Ctx, t: &Tok) -> Option { } stops.extend(at.into_iter().map(|a| (c, Some(a)))); } - (!stops.is_empty()).then_some(Gradient { radial, angle_deg: angle, stops }) + (!stops.is_empty()).then_some(Gradient { shape, stops }) +} + +/// A `radial-gradient()`'s first argument: `[circle | ellipse] [ | ] [at ]` +/// in any order before `at` (CSS Images 3 §3.2.1). Empty: an ellipse to the farthest corner, centred. +fn radial_shape(c: &Ctx, v: &[Tok]) -> Option { + let (head, at) = match v.iter().position(|t| t.ident() == Some("at")) { + Some(k) => (&v[..k], position(c, &v[k + 1..])?), + None => (v, [Pos::CENTER; 2]), + }; + let mut circle = None; + let mut extent = None; + let mut radii: Vec = Vec::new(); + for t in head { + match t.ident() { + Some("circle") => circle = Some(true), + Some("ellipse") => circle = Some(false), + Some("closest-side") => extent = Some((false, false)), + Some("farthest-side") => extent = Some((false, true)), + Some("closest-corner") => extent = Some((true, false)), + Some("farthest-corner") => extent = Some((true, true)), + Some(_) => return None, + None => radii.push(match length(t)? { + Length::Percent(p) => Pos { frac: p / 100.0, px: 0.0 }, + l => Pos { frac: 0.0, px: l.to_px(&c.u)? }, + }), + } + } + // one radius is a circle's (and a length, not a percentage); two, an ellipse's + let circle = circle.unwrap_or(radii.len() == 1); + let size = match radii.as_slice() { + [] => { + let (corner, farthest) = extent.unwrap_or((true, true)); + RadialSize::Extent { corner, farthest } + } + [r] if circle && r.frac == 0.0 && extent.is_none() => RadialSize::Radii(*r, *r), + [rx, ry] if !circle && extent.is_none() => RadialSize::Radii(*rx, *ry), + _ => return None, + }; + Some(Radial { circle, size, at }) } fn shadows(ctx: &Ctx, v: &[Tok]) -> Option> { @@ -3772,24 +3845,13 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{ } true }), - h("text-shadow", |c, v| { - if kw(v) == Some("none") { - c.c.text_shadow = None; - return true; - } - let first: Vec = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]).to_vec(); - let lens: Vec = first.iter().filter_map(|t| length(t).and_then(|l| l.to_px(&c.u))).collect(); - let col = first.iter() - .find_map(|t| color(t, c.c.color).filter(|_| !matches!(t, Tok::Dim(..) | Tok::Num(_)))) - .unwrap_or(c.c.color); - match lens.as_slice() { - [x, y, rest @ ..] => { - c.c.text_shadow = Some(Shadow { x: *x, y: *y, blur: rest.first().copied().unwrap_or(0.0), - spread: 0.0, color: col, inset: false }); - true - } - _ => false, + // `box-shadow`'s list, without `inset` or a spread (CSS Text Decoration 3 §4) + h("text-shadow", |c, v| match shadows(c, v) { + Some(l) if l.iter().all(|s| !s.inset && s.spread == 0.0) => { + c.c.text_shadow = l; + true } + _ => false, }), h("text-decoration-color", |c, v| v.first().and_then(|t| color(t, c.c.color)) .map(|col| c.c.decoration_color = Some(col)).is_some()), diff --git a/bindings/rust/blenderui/src/widgets.rs b/bindings/rust/blenderui/src/widgets.rs index 27560ec9..65efffe6 100644 --- a/bindings/rust/blenderui/src/widgets.rs +++ b/bindings/rust/blenderui/src/widgets.rs @@ -69,11 +69,16 @@ pub(crate) struct WidgetSpec { pub min: f64, pub max: f64, pub step: f64, + /// `precision`: the decimals a number field or slider shows (Blender's property precision); + /// `None`: none for a whole-number step, else Blender's default. + pub precision: Option, pub items: Vec, pub color: Option, pub placeholder: String, /// ``: on_input / on_change fire per keystroke (the kit's "live"), not on Enter or blur. pub live: bool, + /// The element's own `checked` attribute (the app's), which a user's change is kept against. + pub attr_checked: bool, pub disabled: bool, pub name: Option, /// Drawn like a browser's form control (plain HTML outside `styled`); @@ -169,10 +174,12 @@ impl WidgetSpec { min: num("min").unwrap_or(f64::NEG_INFINITY), max: num("max").unwrap_or(f64::INFINITY), step: num("step").unwrap_or(1.0), + precision: num("precision").map(|p| p.clamp(0.0, 6.0) as u8), items: Vec::new(), color: None, placeholder: attr(attrs, "placeholder").unwrap_or("").to_owned(), live: attr(attrs, "live").is_some(), + attr_checked: false, disabled: attr(attrs, "disabled").is_some(), name: attr(attrs, "name").map(str::to_owned), html: false, @@ -195,9 +202,7 @@ impl WidgetSpec { /// `attrs`: the element's attributes (already moved out of `d`). pub(crate) fn from_element(d: &Div, attrs: &Attrs, key: Key, state: &UiState) -> Option { let num = |k: &str| attr(attrs, k).and_then(|v| v.trim().parse::().ok()); - let checked = || { - state.checked.get(&key).copied().unwrap_or(attr(attrs, "checked").is_some()) - }; + let checked = || state.checked(key, attr(attrs, "checked").is_some()); let mut s; match d.tag { "button" => { @@ -314,6 +319,7 @@ impl WidgetSpec { } _ => return None, } + s.attr_checked = attr(attrs, "checked").is_some(); Some(s) } } @@ -620,7 +626,7 @@ fn sync(n: *mut sys::BKNode, old: Option<&WidgetSpec>, spec: &WidgetSpec) { } } } - if old.is_none_or(|o| (o.min, o.max, o.step) != (spec.min, spec.max, spec.step)) + if old.is_none_or(|o| (o.min, o.max, o.step, o.precision) != (spec.min, spec.max, spec.step, spec.precision)) && matches!(spec.kind, WKind::Number | WKind::Slider) { if spec.min.is_finite() { @@ -630,9 +636,10 @@ fn sync(n: *mut sys::BKNode, old: Option<&WidgetSpec>, spec: &WidgetSpec) { set_num(c"max", spec.max); } set_num(c"step", spec.step); - if spec.step.fract() == 0.0 { - set_num(c"precision", 0.0); - } + // Blender's default (3) unless asked, or the step is a whole number; set every time, so a + // step that turns fractional shows its decimals again + let whole = spec.step.fract() == 0.0; + set_num(c"precision", f64::from(spec.precision.unwrap_or(if whole { 0 } else { 3 }))); } if old.is_none_or(|o| (&o.items, &o.groups, o.html) != (&spec.items, &spec.groups, spec.html)) && spec.kind == WKind::Select { diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index 0302be8d..22dc03c4 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -113,6 +113,17 @@ impl WeakEntity { pub fn update(&self, cx: &mut App, f: impl FnOnce(&mut T, &mut Context) -> R) -> Option { self.upgrade_in(cx).map(|e| e.update(cx, f)) } + + /// An element listener that updates this entity (what [`Context::listener`] makes), for code + /// that builds elements away from `render`'s context: a screen's editor factories, say. + pub fn listener( + self, + f: impl Fn(&mut T, &E, &mut Window, &mut Context) + 'static, + ) -> impl Fn(&E, &mut Window, &mut App) + 'static { + move |e: &E, window: &mut Window, cx: &mut App| { + self.update(cx, |this, cx| f(this, e, window, cx)); + } + } } /// The app, seen from inside an entity (gpui's `Context`); derefs to [`App`]. @@ -153,10 +164,7 @@ impl Context<'_, T> { &self, f: impl Fn(&mut T, &E, &mut Window, &mut Context) + 'static, ) -> impl Fn(&E, &mut Window, &mut App) + 'static { - let weak = self.entity.downgrade(); - move |e: &E, window: &mut Window, cx: &mut App| { - weak.update(cx, |this, cx| f(this, e, window, cx)); - } + self.entity.downgrade().listener(f) } } @@ -463,6 +471,9 @@ pub struct App { windows: Vec>>, /// How many windows are lent to callbacks right now. lent: usize, + /// A simulated input is inside the kit (`input`): its events reach the listeners as they come, the + /// windows render once the kit returns (as a native window's frame comes after its events). + in_kit: bool, entities: Vec, headless: bool, real_clock: bool, @@ -531,7 +542,7 @@ impl App { /// follow the virtual one tests step with [`App::advance_clock`]. fn create(headless: bool, real_clock: bool) -> App { crate::motion::start_clock(real_clock); - App { windows: Vec::new(), lent: 0, entities: Vec::new(), headless, real_clock, globals: HashMap::new(), propagate: true, + App { windows: Vec::new(), lent: 0, in_kit: false, entities: Vec::new(), headless, real_clock, globals: HashMap::new(), propagate: true, default_prevented: false, remote: None, close_hooks: Vec::new(), closed_later: None, activation_hooks: Vec::new(), shell_hooks: Vec::new(), notified: 0, shutdown_later: false, theme_seen: crate::theme_generation() } @@ -872,6 +883,8 @@ impl App { unsafe { sys::BK_window_timer(n, 0) }; } Some(_) => {} + // inside the kit: not under its feet (a render can free the widget it is handling) + None if self.in_kit => {} None => { self.with_window(id, |w, app| w.update(app)); } @@ -1025,12 +1038,17 @@ impl App { fn input(&mut self, window: WindowId, f: impl FnOnce(*mut sys::BKContext, f32)) { self.flush(); - if let Some(w) = self.window(window) { - if w.frame.is_none() { - return; - } - f(w.ctx, w.scale); - } + let Some((ctx, scale)) = self.window(window).filter(|w| w.frame.is_some()).map(|w| (w.ctx, w.scale)) else { + return; + }; + // as the native loop delivers them (`Application::run`): the kit's events reach the listeners + // during the call, so a key listener's `prevent_default` takes the key from Blender's own + // handling, as it does in a window. `self` isn't touched until the call returns. + let outer = APP.with(|a| a.replace(std::ptr::from_mut(self))); + let was = std::mem::replace(&mut self.in_kit, true); + f(ctx, scale); + self.in_kit = was; + APP.with(|a| a.set(outer)); self.flush(); } @@ -2035,8 +2053,10 @@ impl Window { self.cursor } - /// A text field (the kit's editor) has the keyboard. - fn text_field_focused(&self) -> bool { + /// A text field (one of Blender's text widgets) is being typed in. Keys typed there still reach + /// the page's key listeners, as a browser's do: check this to keep single-key shortcuts from + /// firing while the user types. + pub fn text_field_focused(&self) -> bool { // SAFETY: a live context. unsafe { !sys::BK_focus(self.ctx).is_null() } } @@ -2145,6 +2165,10 @@ impl Window { crate::widgets::WidgetAsk::Ensure(spec) => widgets.ensure(canvas, key, spec, scale), crate::widgets::WidgetAsk::Height(w) => (0.0, widgets.height_for(key, w, scale)), }); + // a checkbox / radio the app gave another `checked` since the user changed it is the app's + // again, for good (see `UiState::checked`) + let widgets = &self.widgets; + self.state.checked.retain(|k, &mut (_, at)| widgets.nodes.get(k).is_none_or(|w| w.spec.attr_checked == at)); crate::vlist::run_after_layout(&frame, self, app); // `data-stick="bottom"`: a scroll container that grew goes to its end // (`"bottom"`: only if it was at the end; `"always"`: whatever it showed) @@ -2806,7 +2830,9 @@ impl Window { self.dirty = true; } } - sys::BK_EV_MOTION | sys::BK_EV_ENTER => { + // an enter carries no position (the kit's `set_hover`): the motion after it does + sys::BK_EV_ENTER => {} + sys::BK_EV_MOTION => { self.pointer = (x, y); if self.sb_drag.is_some() { self.drag_scrollbar(y); @@ -3241,14 +3267,16 @@ impl Window { sys::BK_EV_CHANGE => { let e = self.widgets.read(key); let kind = self.widgets.nodes.get(&key).map(|w| w.spec.kind); + // the user's state, kept against the app's `checked` they changed it from + let app_checked = |w: &crate::widgets::Widgets, k: Key| w.nodes.get(&k).is_some_and(|n| n.spec.attr_checked); match kind { Some(WKind::Checkbox) => { - self.state.checked.insert(key, e.checked); + self.state.checked.insert(key, (e.checked, app_checked(&self.widgets, key))); } Some(WKind::Radio) if e.checked => { - self.state.checked.insert(key, true); + self.state.checked.insert(key, (true, app_checked(&self.widgets, key))); for other in self.widgets.radio_group(key) { - self.state.checked.insert(other, false); + self.state.checked.insert(other, (false, app_checked(&self.widgets, other))); self.widgets.set_value(other, 0.0); } } diff --git a/bindings/rust/blenderui/tests/suite/effects.rs b/bindings/rust/blenderui/tests/suite/effects.rs index baa87b52..cb4243d1 100644 --- a/bindings/rust/blenderui/tests/suite/effects.rs +++ b/bindings/rust/blenderui/tests/suite/effects.rs @@ -1,5 +1,6 @@ //! Pixel effects (filter, backdrop-filter, mix-blend-mode, clip-path, mask, //! rotate / skew / scale transforms), rounded dashed borders, border-image, +//! box and text shadows, radial gradients, per-corner radii, rounded `overflow`, //! table column sizing, scroll snapping, overflow-wrap in inline text and //! the capitalized Blender components, end to end on headless pages. @@ -257,3 +258,175 @@ fn blender_components_are_elements() { #[allow(dead_code)] const _BASE: &str = BASE; + +#[test] +fn rounded_gradient_keeps_its_corners_in_a_layer() { + // a turned or filtered box is drawn through a layer: its gradient is cut to the rounded box by + // clips there too (an empty clip used to mean none: the whole gradient, square) + Application::headless().run(|cx| { + let (_, at) = page(cx, 300.0, 140.0, " + html, body { margin: 0; background: #000 } + .b { position: absolute; top: 20px; width: 80px; height: 80px; border-radius: 40px; + background: linear-gradient(#f00, #00f) } + #t { left: 20px; transform: rotate(45deg) } #f { left: 160px; filter: opacity(0.99) } + ", || body().child(div().id("t").class("b")).child(div().id("f").class("b"))); + // inside the turned square, outside the circle it is + assert_eq!(at(60.0, 11.0), 0x000000, "turned: the corner is cut"); + assert_ne!(at(60.0, 60.0), 0x000000, "turned: the middle shows"); + assert_eq!(at(164.0, 24.0), 0x000000, "in a layer: the corner is cut"); + assert_ne!(at(200.0, 60.0), 0x000000, "in a layer: the middle shows"); + }); +} + +#[test] +fn box_shadow_rings_and_blurs() { + Application::headless().run(|cx| { + let (_, at) = page(cx, 400.0, 200.0, " + html, body { margin: 0; background: #fff } + #ring { position: absolute; left: 30px; top: 30px; width: 60px; height: 60px; border-radius: 50%; + box-shadow: 0 0 0 6px #f00 } + #soft { position: absolute; left: 200px; top: 50px; width: 100px; height: 60px; background: #fff; + box-shadow: 0 0 20px #000 } + ", || body().child(div().id("ring")).child(div().id("soft"))); + // the shadow is only outside the box (CSS Backgrounds 3 §7.1.1): an empty box shows its ring + assert_eq!(at(60.0, 60.0), 0xffffff, "inside the empty box"); + assert!(near(at(60.0, 27.0), 0xff0000, 8), "the spread ring: {:06x}", at(60.0, 27.0)); + // a Gaussian falloff out from the edge: darkest by it, lighter step by step, no bands + let row: Vec = (0..30).map(|d| rgb_of(at(301.0 + d as f32, 80.0)).0).collect(); + assert!(row[0] < 160 && row[29] > 245, "falls off: {row:?}"); + for w in row.windows(2) { + assert!(w[1] >= w[0] && w[1] - w[0] <= 14, "smooth: {row:?}"); + } + assert_eq!(at(250.0, 80.0), 0xffffff, "the box covers its own shadow"); + }); +} + +#[test] +fn radial_gradient_position_size_and_fade() { + Application::headless().run(|cx| { + let (_, at) = page(cx, 400.0, 300.0, " + html, body { margin: 0; background: #fff } + #g { position: absolute; left: 0; top: 0; width: 400px; height: 300px; + background: radial-gradient(60px circle at 100px 90px, #ff0000, transparent) } + ", || body().child(div().id("g"))); + assert!(near(at(100.0, 90.0), 0xff0000, 12), "centred where it says: {:06x}", at(100.0, 90.0)); + assert_eq!(at(200.0, 150.0), 0xffffff, "past its radius: nothing"); + // halfway out: red over white, never darkened by the transparent end's black + let (r, g, b) = rgb_of(at(130.0, 90.0)); + assert!(r >= 250 && (g - b).abs() <= 3 && g > 80 && g < 200, "a premultiplied fade: {r} {g} {b}"); + }); +} + +#[test] +fn each_corner_has_its_own_radius() { + Application::headless().run(|cx| { + let (_, at) = page(cx, 200.0, 240.0, " + html, body { margin: 0; background: #000 } + #d { position: absolute; left: 20px; top: 20px; width: 120px; height: 200px; background: #0f0; + border-radius: 56px 56px 6px 6px } + #e { position: absolute; left: 150px; top: 20px; width: 40px; height: 40px; + border: 4px solid #f00; border-radius: 20px 0 0 0 } + ", || body().child(div().id("d")).child(div().id("e"))); + assert_eq!(at(25.0, 25.0), 0x000000, "a 56px top corner is cut"); + assert_eq!(at(24.0, 216.0), 0x00ff00, "a 6px bottom corner nearly square"); + assert_eq!(at(187.0, 22.0), 0xff0000, "a square corner's border"); + assert_eq!(at(152.0, 22.0), 0x000000, "a round corner's border is cut"); + }); +} + +#[test] +fn overflow_hidden_rounds_what_it_holds() { + Application::headless().run(|cx| { + let (_, at) = page(cx, 300.0, 140.0, " + html, body { margin: 0; background: #000 } + .box { position: absolute; top: 20px; width: 100px; height: 100px; border-radius: 30px; overflow: hidden } + .in { width: 100px; height: 100px; background: #00f } + #a { left: 20px } #c { left: 160px } + .cv { position: absolute; left: 0; top: 0; width: 100px; height: 100px } + ", || { + body().child(div().id("a").class("box").child(div().class("in"))) + .child(div().id("c").class("box").child(canvas(|b, p| p.fill(b, rgb(0xff0000))).class("cv"))) + }); + assert_eq!(at(23.0, 23.0), 0x000000, "a child's square corner is cut"); + assert_eq!(at(70.0, 70.0), 0x0000ff, "its middle shows"); + assert_eq!(at(163.0, 117.0), 0x000000, "a canvas's corner is cut"); + assert_eq!(at(210.0, 70.0), 0xff0000, "its middle shows"); + }); +} + +#[test] +fn text_shadow_follows_the_text() { + // each shadow is the text moved: its letters spaced as the text's, its blur a blur + Application::headless().run(|cx| { + let (_, at) = page(cx, 400.0, 160.0, " + html, body { margin: 0; background: #fff } + #t { position: absolute; left: 10px; top: 10px; font-size: 30px; letter-spacing: 14px; color: #000; + text-shadow: 0 60px 0 #f00, 0 100px 4px #00f } + ", || body().child(div().id("t").child("SPACED"))); + let span_of = |y0: f32, y1: f32, hit: &dyn Fn(u32) -> bool| { + let xs: Vec = (0..400).map(|x| x as f32) + .filter(|&x| (0..((y1 - y0) as i32)).any(|dy| hit(at(x, y0 + dy as f32)))).collect(); + (xs.first().copied().unwrap_or(0.0), xs.last().copied().unwrap_or(0.0)) + }; + let text = span_of(10.0, 50.0, &|p| rgb_of(p).0 < 80); + let shadow = span_of(70.0, 110.0, &|p| { let (r, g, b) = rgb_of(p); r > 200 && g < 80 && b < 80 }); + assert!((text.0 - shadow.0).abs() <= 1.0 && (text.1 - shadow.1).abs() <= 1.0, + "the shadow is as wide as the spaced text: {text:?} {shadow:?}"); + // a blurred shadow has no hard pixels and reaches past its letters + let blue = (110..160).flat_map(|y| (0..400).map(move |x| (x as f32, y as f32))) + .map(|(x, y)| rgb_of(at(x, y))).filter(|(r, g, b)| b > r && b > g).count(); + assert!(blue > 400, "the blurred shadow shows: {blue}"); + }); +} + +#[test] +fn an_anonymous_box_does_not_clip_again() { + // a canvas after a block in an `overflow: hidden` box sits in an anonymous line box that carries + // the box's style: the clip is the box's padding box, not cut again at the anonymous box + Application::headless().run(|cx| { + let (_, at) = page(cx, 300.0, 200.0, " + html, body { margin: 0; background: #000 } + .lcd { position: absolute; left: 20px; top: 20px; width: 200px; height: 100px; overflow: hidden } + .head { height: 20px } + .viz { position: absolute; left: 10px; top: 50px; width: 180px; height: 36px } + ", || body().child(div().class("lcd").child(div().class("head")) + .child(canvas(|b, p| p.fill(b, rgb(0xff0000))).class("viz")))); + assert_eq!(at(120.0, 85.0), 0xff0000, "the canvas paints"); + }); +} + +#[test] +fn translate_moves_inline_content_once() { + // loose text after a block goes in an anonymous line box: the box's `translate` moves it once + Application::headless().run(|cx| { + let (_, moved) = page(cx, 300.0, 200.0, " + html, body { margin: 0; background: #fff; color: #000; font-size: 20px } + .t { position: absolute; left: 20px; top: 20px; translate: 0px 40px; width: 200px } + ", || body().child(div().class("t").child(div().child("AAAA")).child("BBBB"))); + let (_, placed) = page(cx, 300.0, 200.0, " + html, body { margin: 0; background: #fff; color: #000; font-size: 20px } + .t { position: absolute; left: 20px; top: 60px; width: 200px } + ", || body().child(div().class("t").child(div().child("AAAA")).child("BBBB"))); + for y in (0..200).step_by(2) { + for x in (0..300).step_by(2) { + assert_eq!(moved(x as f32, y as f32), placed(x as f32, y as f32), "pixel {x},{y}"); + } + } + }); +} + +#[test] +fn a_highlighted_span_keeps_every_word() { + // the words of a text draw as one run from its first word; a later word's highlight (its inline + // box's fragment) is painted with that word, so it must not cover the run's text + Application::headless().run(|cx| { + let (_, at) = page(cx, 400.0, 60.0, " + html, body { margin: 0; background: #fff; color: #000; font-size: 20px } + .hl { background: #b8cdf2 } + ", || body().child(div().css("padding", "10px").child(span().class("hl").child("aaaa bbbb cccc")).child(" after"))); + // dark glyph pixels in the right half of the highlight (the second and third words) + let ink = (40..140).flat_map(|x| (10..34).map(move |y| (x as f32, y as f32))) + .filter(|&(x, y)| rgb_of(at(x, y)).0 < 90).count(); + assert!(ink > 40, "the later words show over their highlight: {ink} dark pixels"); + }); +} diff --git a/bindings/rust/blenderui/tests/suite/events_dom.rs b/bindings/rust/blenderui/tests/suite/events_dom.rs index 9732b445..eff71f8d 100644 --- a/bindings/rust/blenderui/tests/suite/events_dom.rs +++ b/bindings/rust/blenderui/tests/suite/events_dom.rs @@ -490,3 +490,246 @@ fn removed_elements_let_go_and_other_scrolls_and_keypress() { assert_eq!(take(), ["keydown"], "ctrl+a isn't typing"); }); } + +static OVER: Mutex> = Mutex::new(Vec::new()); + +/// A drag that crosses one of Blender's widgets. +struct DragOverWidget; + +impl Render for DragOverWidget { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("page").size_full() + .child( + div().id("grip").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)) + .on_pointer_move(|e, _, _| OVER.lock().unwrap().push((e.position.x.0 as i32, e.position.y.0 as i32))), + ) + .child(div().absolute().left(px(200.0)).top(px(100.0)).child(Checkbox().id("cb"))) + } +} + +/// The pointer coming back onto the page from a widget is an enter with no position: it moves +/// nothing (it used to be a move to (0, 0) mid-drag). +#[test] +fn a_drag_across_a_widget_never_jumps_to_the_corner() { + Application::headless().run(|cx| { + 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(|_| DragOverWidget)).unwrap().id; + cx.draw(w); + let cb = cx.element_bounds(w, "cb").expect("the checkbox"); + let (cx_, cy_) = (cb.origin.x + cb.size.width / 2.0, cb.origin.y + cb.size.height / 2.0); + OVER.lock().unwrap().clear(); + cx.simulate_press(w, 30.0, 30.0); + for (x, y) in [(100.0, 60.0), (cx_, cy_), (cx_ + 2.0, cy_), (300.0, 200.0), (320.0, 210.0)] { + cx.simulate_mouse_move(w, x, y); + } + cx.simulate_release(w, 320.0, 210.0); + let moves = OVER.lock().unwrap().clone(); + assert!(!moves.is_empty(), "the drag is heard"); + assert!(!moves.contains(&(0, 0)), "no move to the corner: {moves:?}"); + }); +} + +static RESETS: Mutex> = Mutex::new(Vec::new()); + +/// A page that acts on Backspace itself, over one of Blender's sliders. +struct TakesKeys { + take: bool, +} + +impl Render for TakesKeys { + fn render(&mut self, w: &mut Window, _: &mut Context) -> impl IntoElement { + // keys go to the focused element: the page's, as an app focuses its root + if w.focused_id().is_none() { + w.focus_id("root"); + } + let take = self.take; + div().id("root").size_full().attr("tabindex", "0") + .on_key_down(move |e: &KeyDownEvent, _, cx| { + if take && e.keystroke.key == "BackSpace" { + cx.prevent_default(); + } + }) + .child(NumberSlider().id("s").min(0.0).max(10.0).value("7").w(px(200.0)) + .on_change(|e: &ChangeEvent, _, _| RESETS.lock().unwrap().push(e.number))) + } +} + +/// A key a page listener takes (`prevent_default`) is not Blender's too (Backspace over a slider +/// resets it): in a headless run as in a window, the listener hears the key while the kit delivers it. +#[test] +fn a_key_the_page_takes_is_not_the_widgets() { + for take in [false, true] { + 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(400.0), px(200.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| TakesKeys { take })).unwrap().id; + cx.draw(w); + let b = cx.element_bounds(w, "s").expect("the slider"); + let y = b.origin.y + b.size.height / 2.0; + // away from its default first (Backspace resets to it) + cx.simulate_drag(w, (b.origin.x + 150.0, y), (b.origin.x + 30.0, y)); + cx.draw(w); + RESETS.lock().unwrap().clear(); + cx.simulate_mouse_move(w, b.origin.x + 30.0, y); + cx.simulate_key(w, "", "BackSpace"); + cx.draw(w); + let changed = !RESETS.lock().unwrap().is_empty(); + assert_eq!(changed, !take, "take {take}: the slider reset {changed}"); + }); + } +} + +/// Two radios kept in the app's state (`view`), and a box `:checked` styles after the first. +struct Views { + grid: bool, +} + +impl Render for Views { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + div().size_full() + .child(style().child("#mark { width: 10px; height: 10px } #list:checked ~ #mark { width: 50px }")) + .child(Radio().id("list").attr("name", "view").checked(!self.grid) + .on_change(cx.listener(|this, e: &ChangeEvent, _, cx| if e.checked { this.grid = false; cx.notify(); }))) + .child(Radio().id("grid").attr("name", "view").checked(self.grid) + .on_change(cx.listener(|this, e: &ChangeEvent, _, cx| if e.checked { this.grid = true; cx.notify(); }))) + .child(div().id("mark")) + .child(div().id("code").w(px(40.0)).h(px(40.0)) + .on_click(cx.listener(|this, _, _, cx| { this.grid = false; cx.notify(); }))) + } +} + +/// A control kept in the app's state follows it after the user clicked it: the app's next +/// `checked` wins over the click (it used to keep the user's state for good). +#[test] +fn a_controlled_radio_follows_the_app_after_a_click() { + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(400.0), px(200.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| Views { grid: false })).unwrap().id; + cx.draw(w); + let mark = |cx: &mut App| cx.element_bounds(w, "mark").expect("mark").size.width; + assert_eq!(mark(cx), 50.0, "List starts checked"); + let g = cx.element_bounds(w, "grid").expect("grid"); + cx.simulate_click(w, g.origin.x + g.size.width / 2.0, g.origin.y + g.size.height / 2.0); + cx.draw(w); + assert_eq!(mark(cx), 10.0, "the user picked Grid"); + let c = cx.element_bounds(w, "code").expect("code"); + cx.simulate_click(w, c.origin.x + 5.0, c.origin.y + 5.0); + cx.draw(w); + assert_eq!(mark(cx), 50.0, "the app set List again: it shows"); + }); +} + +/// A composer whose field is a new one after each send (a new id: the value is cleared). +struct Composer { + sent: Vec, +} + +impl Render for Composer { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + if w.focused_id().is_none() { + w.focus_id("root"); + } + div().id("root").size_full().attr("tabindex", "0") + .child(TextField().id(format!("field{}", self.sent.len())).w(px(200.0)) + .on_change(cx.listener(|this, e: &ChangeEvent, _, cx| { + if !e.value.is_empty() { + this.sent.push(e.value.clone()); + cx.notify(); + } + }))) + } +} + +/// The Enter that sends takes the field away (a render replaces it) while the kit is still handling +/// that key: the render waits until the kit is done, as a window's next frame does. +#[test] +fn a_field_its_own_enter_replaces_survives() { + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(400.0), px(200.0)), + })), + ..Default::default() + }; + let h = cx.open_window(opts, |_, cx| cx.new(|_| Composer { sent: Vec::new() })).unwrap(); + let w = h.id; + for (k, msg) in ["hi", "again"].into_iter().enumerate() { + cx.draw(w); + let b = cx.element_bounds(w, &format!("field{k}")).expect("the field"); + cx.simulate_click(w, b.origin.x + 20.0, b.origin.y + b.size.height / 2.0); + for c in msg.chars() { + let s = c.to_string(); + cx.simulate_key(w, &s, &s); + } + cx.simulate_key(w, "", "Return"); + } + cx.draw(w); + let sent = h.update(cx, |v, _, _| v.sent.clone()).unwrap_or_default(); + assert_eq!(sent, ["hi", "again"]); + }); +} + +struct Adder { + added: usize, + keys: String, +} + +impl Render for Adder { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + if w.focused_id().is_none() { + w.focus_id("root"); + } + div().id("root").size_full().attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, _| this.keys.push_str(&e.keystroke.key))) + .child(Button().id(format!("add{}", self.added)).child("Add").w(px(120.0)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.added += 1; + cx.notify(); + }))) + } +} + +/// The button clicked is rebuilt away (a new id): the keys typed next, before the pointer moves, +/// still reach the page under the pointer, as Blender sends a key to the region under the cursor. +#[test] +fn keys_after_a_click_that_rebuilds_the_button_reach_the_page() { + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(400.0), px(200.0)), + })), + ..Default::default() + }; + let h = cx.open_window(opts, |_, cx| cx.new(|_| Adder { added: 0, keys: String::new() })).unwrap(); + let w = h.id; + cx.draw(w); + let b = cx.element_bounds(w, "add0").expect("the button"); + cx.simulate_click(w, b.origin.x + b.size.width / 2.0, b.origin.y + b.size.height / 2.0); + for c in ["o", "k"] { + cx.simulate_key(w, c, c); + } + cx.draw(w); + let (added, keys) = h.update(cx, |v, _, _| (v.added, v.keys.clone())).unwrap_or_default(); + assert_eq!((added, keys.as_str()), (1, "ok")); + }); +} diff --git a/docs/effects-performance.md b/docs/effects-performance.md index bcc469d6..64aeedd4 100644 --- a/docs/effects-performance.md +++ b/docs/effects-performance.md @@ -247,8 +247,9 @@ frame. maps each box to a fixed number of display items, and a layer's image replaces the items of its whole subtree. The full repaint of the 300-row page takes about 0.4 ms. -- **CSS gradients are drawn again each frame.** Unlike `border-image` - gradients, they aren't cached as images, which is why the turning +- **Linear CSS gradients are drawn again each frame.** Unlike `border-image` + gradients and radial ones (a colour a pixel, kept as an image by size), they + aren't cached as images, which is why the turning gradient backdrop costs 5.5 ms a frame where the turning cover image costs 2.1 ms. - **Headless redraws repeat.** `App::draw` flushes twice, and a window still diff --git a/docs/rust.md b/docs/rust.md index 67ca3b66..e111fceb 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -755,7 +755,7 @@ the result is cached, so a page that doesn't change costs nothing. `border-image` (gradients and PNGs, slice, width, outset, `stretch` / `repeat` / `round` / `space`, `fill`) draws the nine slices. -Also rendered: every `border-style` and `outline-style` (`dashed`, `dotted`, `double`, `groove`, `ridge`, `inset`, `outset`, following rounded corners with Blender's corner tessellation), `text-decoration-style` (including `wavy`), `-thickness` and `text-underline-offset`, `background-clip` / `background-origin` (`border-box`, `padding-box`, `content-box`), `background-attachment: fixed`, `clip: rect()` on absolutely positioned boxes, counters (`counter-reset` / `-increment` / `-set` with `counter()` and `counters()` in `content`), `empty-cells`, `list-style-image`, `word-break: break-all`, `overflow-wrap: anywhere | break-word` and `tab-size`. +Also rendered: `radial-gradient()` with its shape (`circle` / `ellipse`), size (`closest-side` … `farthest-corner` or radii) and `at` position, every gradient mixed in premultiplied alpha; a radius for each corner (`border-radius: 56px 56px 6px 6px`); `overflow` clipping what it holds to its rounded corners; `box-shadow` blurred as a Gaussian and drawn only outside its box; `text-shadow` lists, each blurred and spaced as its text. Also: every `border-style` and `outline-style` (`dashed`, `dotted`, `double`, `groove`, `ridge`, `inset`, `outset`, following rounded corners with Blender's corner tessellation), `text-decoration-style` (including `wavy`), `-thickness` and `text-underline-offset`, `background-clip` / `background-origin` (`border-box`, `padding-box`, `content-box`), `background-attachment: fixed`, `clip: rect()` on absolutely positioned boxes, counters (`counter-reset` / `-increment` / `-set` with `counter()` and `counters()` in `content`), `empty-cells`, `list-style-image`, `word-break: break-all`, `overflow-wrap: anywhere | break-word` and `tab-size`. Also supported: `background-image: url()` (every image format) with `background-size` / `-position` (`-x` / `-y`) / `-repeat`, `object-fit` / `object-position`, logical border longhands (`border-inline-width` ...), `text-wrap-mode`, `white-space-collapse`, `scale`, `@container` size queries (`container-type`, `container-name`), `@font-face` (local font files) and `@property` initial values. diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.h index 5c4ca9b2..88c46b95 100644 --- a/gpu/include/GPU_raster.h +++ b/gpu/include/GPU_raster.h @@ -190,6 +190,11 @@ void BUI_raster_end_frame_region(BuiRaster *r, int x, int y, int w, int h); * `size` pixels from `alpha`. */ void BUI_raster_shadow( BuiRaster *r, float x, float y, float w, float h, float radius, float size, float alpha); +/* CSS `box-shadow` (an outer one): the rounded box `shape` (x, y, w, h; corner `radius`) blurred by a + * Gaussian of `sigma` (0: a hard edge), in straight `rgba`, drawn only outside the rounded box `box` + * (corner `box_radius`), the element's border box, which covers it. */ +void BUI_raster_box_shadow(BuiRaster *r, const float shape[4], float radius, float sigma, const float rgba[4], + const float box[4], float box_radius); void BUI_raster_triangles(BuiRaster *r, const float (*coords)[2], const float (*colors)[4], diff --git a/gpu/intern/gpu_d3d11_shaders.h b/gpu/intern/gpu_d3d11_shaders.h index 9ca5f75e..239b7060 100644 --- a/gpu/intern/gpu_d3d11_shaders.h +++ b/gpu/intern/gpu_d3d11_shaders.h @@ -208,11 +208,11 @@ const BYTE g_vs_quad[] = }; const BYTE g_ps_quad[] = { - 68, 88, 66, 67, 33, 89, - 159, 42, 207, 166, 181, 7, - 8, 72, 45, 119, 225, 156, - 93, 140, 1, 0, 0, 0, - 220, 70, 0, 0, 3, 0, + 68, 88, 66, 67, 156, 104, + 40, 189, 247, 140, 194, 29, + 250, 185, 154, 77, 51, 11, + 124, 14, 1, 0, 0, 0, + 40, 90, 0, 0, 3, 0, 0, 0, 44, 0, 0, 0, 32, 1, 0, 0, 84, 1, 0, 0, 73, 83, 71, 78, @@ -265,8 +265,8 @@ const BYTE g_ps_quad[] = 15, 0, 0, 0, 83, 86, 95, 84, 97, 114, 103, 101, 116, 0, 171, 171, 83, 72, - 68, 82, 128, 69, 0, 0, - 64, 0, 0, 0, 96, 17, + 68, 82, 204, 88, 0, 0, + 64, 0, 0, 0, 51, 22, 0, 0, 88, 24, 0, 4, 0, 112, 16, 0, 0, 0, 0, 0, 85, 85, 0, 0, @@ -2620,29 +2620,105 @@ const BYTE g_ps_quad[] = 16, 0, 0, 0, 0, 0, 50, 0, 0, 12, 98, 0, 16, 0, 0, 0, 0, 0, - 166, 27, 16, 0, 1, 0, + 166, 27, 16, 0, 3, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 0, 0, 0, 63, 0, 0, 0, 0, 6, 17, + 16, 0, 3, 0, 0, 0, + 0, 0, 0, 8, 98, 0, + 16, 0, 0, 0, 0, 0, + 86, 6, 16, 128, 65, 0, + 0, 0, 0, 0, 0, 0, + 6, 17, 16, 0, 0, 0, + 0, 0, 50, 0, 0, 13, + 50, 0, 16, 0, 1, 0, + 0, 0, 230, 26, 16, 0, + 3, 0, 0, 0, 2, 64, + 0, 0, 0, 0, 0, 63, + 0, 0, 0, 63, 0, 0, + 0, 0, 0, 0, 0, 0, + 6, 16, 16, 128, 65, 0, + 0, 0, 7, 0, 0, 0, + 0, 0, 0, 9, 98, 0, + 16, 0, 0, 0, 0, 0, + 86, 6, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, + 6, 1, 16, 128, 65, 0, + 0, 0, 1, 0, 0, 0, + 29, 0, 0, 10, 50, 0, 16, 0, 1, 0, 0, 0, - 54, 0, 0, 5, 18, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 150, 5, 16, 0, + 0, 0, 0, 0, 60, 0, + 0, 7, 130, 0, 16, 0, + 0, 0, 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, - 1, 64, 0, 0, 0, 0, - 0, 0, 56, 0, 0, 7, - 34, 0, 16, 0, 1, 0, - 0, 0, 42, 16, 16, 0, - 6, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 128, 62, - 0, 0, 0, 7, 50, 0, + 10, 0, 16, 0, 1, 0, + 0, 0, 52, 0, 0, 7, + 18, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 0, 0, 0, 0, 26, 0, + 16, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 18, 0, 16, 0, 1, 0, 0, 0, - 150, 5, 16, 0, 0, 0, - 0, 0, 70, 0, 16, 0, + 10, 0, 16, 0, 1, 0, + 0, 0, 10, 16, 16, 128, + 65, 0, 0, 0, 7, 0, + 0, 0, 15, 0, 0, 7, + 34, 0, 16, 0, 0, 0, + 0, 0, 150, 5, 16, 0, + 0, 0, 0, 0, 150, 5, + 16, 0, 0, 0, 0, 0, + 75, 0, 0, 5, 34, 0, + 16, 0, 0, 0, 0, 0, + 26, 0, 16, 0, 0, 0, + 0, 0, 0, 0, 0, 8, + 34, 0, 16, 0, 0, 0, + 0, 0, 26, 0, 16, 0, + 0, 0, 0, 0, 10, 16, + 16, 128, 65, 0, 0, 0, + 7, 0, 0, 0, 55, 0, + 0, 9, 34, 0, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 0, 0, 0, 0, 0, + 10, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 0, + 0, 0, 0, 0, 29, 0, + 0, 7, 66, 0, 16, 0, + 0, 0, 0, 0, 1, 64, + 0, 0, 0, 0, 0, 191, + 26, 0, 16, 0, 0, 0, + 0, 0, 31, 0, 4, 3, + 42, 0, 16, 0, 0, 0, + 0, 0, 54, 0, 0, 8, + 242, 32, 16, 0, 0, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 62, 0, + 0, 1, 21, 0, 0, 1, + 50, 0, 0, 12, 194, 0, + 16, 0, 0, 0, 0, 0, + 166, 30, 16, 0, 1, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 63, + 0, 0, 0, 63, 6, 20, + 16, 0, 1, 0, 0, 0, + 49, 0, 0, 7, 18, 0, + 16, 0, 1, 0, 0, 0, + 26, 16, 16, 0, 7, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 63, 31, 0, + 4, 3, 10, 0, 16, 0, 1, 0, 0, 0, 0, 0, 0, 8, 50, 0, 16, 0, - 1, 0, 0, 0, 70, 0, + 1, 0, 0, 0, 230, 10, 16, 128, 65, 0, 0, 0, - 1, 0, 0, 0, 70, 16, + 0, 0, 0, 0, 70, 16, 16, 0, 0, 0, 0, 0, 50, 0, 0, 13, 194, 0, 16, 0, 1, 0, 0, 0, @@ -2659,579 +2735,1326 @@ const BYTE g_ps_quad[] = 1, 0, 0, 0, 70, 0, 16, 128, 129, 0, 0, 0, 1, 0, 0, 0, 29, 0, - 0, 10, 50, 0, 16, 0, - 2, 0, 0, 0, 2, 64, + 0, 10, 194, 0, 16, 0, + 1, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 70, 0, 16, 0, 1, 0, + 6, 4, 16, 0, 1, 0, 0, 0, 60, 0, 0, 7, - 130, 0, 16, 0, 0, 0, - 0, 0, 26, 0, 16, 0, - 2, 0, 0, 0, 10, 0, - 16, 0, 2, 0, 0, 0, - 52, 0, 0, 7, 18, 0, - 16, 0, 2, 0, 0, 0, + 66, 0, 16, 0, 1, 0, + 0, 0, 58, 0, 16, 0, + 1, 0, 0, 0, 42, 0, + 16, 0, 1, 0, 0, 0, + 52, 0, 0, 7, 130, 0, + 16, 0, 1, 0, 0, 0, 26, 0, 16, 0, 1, 0, + 0, 0, 10, 0, 16, 0, + 1, 0, 0, 0, 15, 0, + 0, 7, 18, 0, 16, 0, + 1, 0, 0, 0, 70, 0, + 16, 0, 1, 0, 0, 0, + 70, 0, 16, 0, 1, 0, + 0, 0, 75, 0, 0, 5, + 18, 0, 16, 0, 1, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, 0, 0, - 0, 8, 18, 0, 16, 0, - 2, 0, 0, 0, 10, 0, - 16, 0, 2, 0, 0, 0, - 26, 16, 16, 128, 65, 0, + 0, 8, 146, 0, 16, 0, + 1, 0, 0, 0, 6, 12, + 16, 0, 1, 0, 0, 0, + 86, 21, 16, 128, 65, 0, 0, 0, 6, 0, 0, 0, - 15, 0, 0, 7, 18, 0, + 55, 0, 0, 9, 18, 0, 16, 0, 1, 0, 0, 0, - 70, 0, 16, 0, 1, 0, - 0, 0, 70, 0, 16, 0, - 1, 0, 0, 0, 75, 0, - 0, 5, 18, 0, 16, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 58, 0, 16, 0, 1, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, - 0, 0, 0, 8, 18, 0, + 29, 0, 0, 7, 34, 0, 16, 0, 1, 0, 0, 0, 10, 0, 16, 0, 1, 0, - 0, 0, 26, 16, 16, 128, - 65, 0, 0, 0, 6, 0, - 0, 0, 55, 0, 0, 9, - 130, 0, 16, 0, 0, 0, - 0, 0, 58, 0, 16, 0, - 0, 0, 0, 0, 10, 0, - 16, 0, 2, 0, 0, 0, - 10, 0, 16, 0, 1, 0, - 0, 0, 0, 0, 0, 8, - 98, 0, 16, 0, 0, 0, - 0, 0, 86, 6, 16, 128, - 65, 0, 0, 0, 0, 0, - 0, 0, 6, 17, 16, 0, + 0, 0, 42, 16, 16, 0, + 6, 0, 0, 0, 31, 0, + 4, 3, 26, 0, 16, 0, + 1, 0, 0, 0, 54, 0, + 0, 8, 242, 32, 16, 0, + 0, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, - 0, 9, 98, 0, 16, 0, - 0, 0, 0, 0, 166, 11, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 62, 0, 0, 1, 21, 0, + 0, 1, 14, 32, 0, 7, + 18, 0, 16, 0, 1, 0, + 0, 0, 10, 0, 16, 0, + 1, 0, 0, 0, 42, 16, + 16, 0, 6, 0, 0, 0, + 0, 0, 0, 8, 18, 0, + 16, 0, 1, 0, 0, 0, + 10, 0, 16, 128, 65, 0, + 0, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 128, 63, 56, 0, 0, 7, + 34, 0, 16, 0, 1, 0, + 0, 0, 10, 0, 16, 0, + 1, 0, 0, 0, 10, 0, + 16, 0, 1, 0, 0, 0, + 50, 0, 0, 10, 18, 0, + 16, 0, 1, 0, 0, 0, + 10, 0, 16, 128, 65, 0, + 0, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 64, 1, 64, 0, 0, + 0, 0, 64, 64, 56, 0, + 0, 7, 18, 0, 16, 0, + 1, 0, 0, 0, 10, 0, + 16, 0, 1, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 18, 0, 0, 1, + 49, 0, 0, 7, 34, 0, + 16, 0, 1, 0, 0, 0, + 42, 16, 16, 0, 6, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 128, 62, 31, 0, + 4, 3, 26, 0, 16, 0, + 1, 0, 0, 0, 0, 0, + 0, 8, 98, 0, 16, 0, + 1, 0, 0, 0, 166, 11, + 16, 128, 65, 0, 0, 0, + 0, 0, 0, 0, 6, 17, + 16, 0, 0, 0, 0, 0, + 50, 0, 0, 13, 50, 0, + 16, 0, 2, 0, 0, 0, + 230, 26, 16, 0, 1, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 63, 0, 0, + 0, 63, 0, 0, 0, 0, + 0, 0, 0, 0, 86, 21, 16, 128, 65, 0, 0, 0, + 6, 0, 0, 0, 0, 0, + 0, 9, 98, 0, 16, 0, 1, 0, 0, 0, 86, 6, 16, 128, 129, 0, 0, 0, - 0, 0, 0, 0, 29, 0, + 1, 0, 0, 0, 6, 1, + 16, 128, 65, 0, 0, 0, + 2, 0, 0, 0, 29, 0, 0, 10, 50, 0, 16, 0, - 1, 0, 0, 0, 2, 64, + 2, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 150, 5, 16, 0, 0, 0, + 150, 5, 16, 0, 1, 0, 0, 0, 60, 0, 0, 7, - 18, 0, 16, 0, 1, 0, + 130, 0, 16, 0, 1, 0, 0, 0, 26, 0, 16, 0, - 1, 0, 0, 0, 10, 0, - 16, 0, 1, 0, 0, 0, - 52, 0, 0, 7, 34, 0, - 16, 0, 1, 0, 0, 0, - 42, 0, 16, 0, 0, 0, + 2, 0, 0, 0, 10, 0, + 16, 0, 2, 0, 0, 0, + 52, 0, 0, 7, 18, 0, + 16, 0, 2, 0, 0, 0, + 42, 0, 16, 0, 1, 0, 0, 0, 26, 0, 16, 0, - 0, 0, 0, 0, 0, 0, - 0, 8, 34, 0, 16, 0, - 1, 0, 0, 0, 26, 0, - 16, 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, 0, + 0, 8, 18, 0, 16, 0, + 2, 0, 0, 0, 10, 0, + 16, 0, 2, 0, 0, 0, 26, 16, 16, 128, 65, 0, 0, 0, 6, 0, 0, 0, 15, 0, 0, 7, 34, 0, - 16, 0, 0, 0, 0, 0, - 150, 5, 16, 0, 0, 0, + 16, 0, 1, 0, 0, 0, + 150, 5, 16, 0, 1, 0, 0, 0, 150, 5, 16, 0, - 0, 0, 0, 0, 75, 0, + 1, 0, 0, 0, 75, 0, 0, 5, 34, 0, 16, 0, - 0, 0, 0, 0, 26, 0, - 16, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 26, 0, + 16, 0, 1, 0, 0, 0, 0, 0, 0, 8, 34, 0, - 16, 0, 0, 0, 0, 0, - 26, 0, 16, 0, 0, 0, + 16, 0, 1, 0, 0, 0, + 26, 0, 16, 0, 1, 0, 0, 0, 26, 16, 16, 128, 65, 0, 0, 0, 6, 0, 0, 0, 55, 0, 0, 9, - 34, 0, 16, 0, 0, 0, - 0, 0, 10, 0, 16, 0, - 1, 0, 0, 0, 26, 0, - 16, 0, 1, 0, 0, 0, - 26, 0, 16, 0, 0, 0, - 0, 0, 29, 0, 0, 7, - 66, 0, 16, 0, 0, 0, + 34, 0, 16, 0, 1, 0, + 0, 0, 58, 0, 16, 0, + 1, 0, 0, 0, 10, 0, + 16, 0, 2, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 0, 32, 0, 8, + 18, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 1, 0, 0, 0, 1, 64, 0, 0, - 0, 0, 0, 191, 26, 0, - 16, 0, 0, 0, 0, 0, - 29, 0, 0, 7, 18, 0, - 16, 0, 1, 0, 0, 0, + 0, 0, 0, 63, 18, 0, + 0, 1, 0, 0, 0, 8, + 194, 0, 16, 0, 0, 0, + 0, 0, 166, 14, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 6, 20, 16, 0, + 0, 0, 0, 0, 50, 0, + 0, 10, 34, 0, 16, 0, + 1, 0, 0, 0, 58, 16, + 16, 128, 65, 0, 0, 0, + 1, 0, 0, 0, 1, 64, + 0, 0, 0, 0, 0, 63, 58, 0, 16, 0, 0, 0, - 0, 0, 42, 16, 16, 0, - 6, 0, 0, 0, 60, 0, - 0, 7, 66, 0, 16, 0, - 0, 0, 0, 0, 42, 0, - 16, 0, 0, 0, 0, 0, - 10, 0, 16, 0, 1, 0, - 0, 0, 31, 0, 4, 3, - 42, 0, 16, 0, 0, 0, - 0, 0, 54, 0, 0, 8, - 242, 32, 16, 0, 0, 0, + 0, 0, 50, 0, 0, 9, + 66, 0, 16, 0, 1, 0, + 0, 0, 58, 16, 16, 0, + 1, 0, 0, 0, 1, 64, + 0, 0, 0, 0, 0, 63, + 58, 0, 16, 0, 0, 0, + 0, 0, 56, 0, 0, 10, + 114, 0, 16, 0, 2, 0, + 0, 0, 166, 26, 16, 0, + 6, 0, 0, 0, 2, 64, + 0, 0, 0, 0, 64, 192, + 0, 0, 64, 64, 153, 108, + 32, 64, 0, 0, 0, 0, + 52, 0, 0, 7, 162, 0, + 16, 0, 1, 0, 0, 0, + 86, 5, 16, 0, 1, 0, + 0, 0, 6, 4, 16, 0, + 2, 0, 0, 0, 51, 0, + 0, 7, 98, 0, 16, 0, + 1, 0, 0, 0, 166, 10, + 16, 0, 1, 0, 0, 0, + 86, 7, 16, 0, 1, 0, + 0, 0, 0, 0, 0, 8, + 66, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 56, 0, + 0, 7, 130, 0, 16, 0, + 1, 0, 0, 0, 42, 0, + 16, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 128, 62, 14, 0, 0, 7, + 18, 0, 16, 0, 2, 0, + 0, 0, 1, 64, 0, 0, + 243, 4, 53, 63, 42, 16, + 16, 0, 6, 0, 0, 0, + 14, 0, 0, 7, 130, 0, + 16, 0, 1, 0, 0, 0, + 58, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 2, 0, 0, 0, 50, 0, + 0, 9, 34, 0, 16, 0, + 1, 0, 0, 0, 42, 0, + 16, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 62, 26, 0, 16, 0, + 1, 0, 0, 0, 50, 0, + 0, 13, 98, 0, 16, 0, + 2, 0, 0, 0, 246, 30, + 16, 0, 1, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 63, + 0, 0, 0, 63, 0, 0, + 0, 0, 86, 21, 16, 128, + 65, 0, 0, 0, 6, 0, + 0, 0, 0, 0, 0, 8, + 130, 0, 16, 0, 2, 0, + 0, 0, 58, 0, 16, 0, + 0, 0, 0, 0, 26, 0, + 16, 128, 65, 0, 0, 0, + 1, 0, 0, 0, 0, 0, + 0, 8, 130, 0, 16, 0, + 2, 0, 0, 0, 58, 0, + 16, 128, 193, 0, 0, 0, + 2, 0, 0, 0, 26, 0, + 16, 0, 2, 0, 0, 0, + 51, 0, 0, 7, 130, 0, + 16, 0, 2, 0, 0, 0, + 58, 0, 16, 0, 2, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 0, 56, 0, + 0, 7, 18, 0, 16, 0, + 3, 0, 0, 0, 26, 16, + 16, 0, 6, 0, 0, 0, + 26, 16, 16, 0, 6, 0, + 0, 0, 50, 0, 0, 10, + 130, 0, 16, 0, 2, 0, + 0, 0, 58, 0, 16, 128, + 65, 0, 0, 0, 2, 0, + 0, 0, 58, 0, 16, 0, + 2, 0, 0, 0, 10, 0, + 16, 0, 3, 0, 0, 0, + 52, 0, 0, 7, 130, 0, + 16, 0, 2, 0, 0, 0, + 58, 0, 16, 0, 2, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 0, 75, 0, + 0, 5, 130, 0, 16, 0, + 2, 0, 0, 0, 58, 0, + 16, 0, 2, 0, 0, 0, + 0, 0, 0, 7, 18, 0, + 16, 0, 4, 0, 0, 0, + 58, 0, 16, 0, 2, 0, + 0, 0, 42, 0, 16, 0, + 2, 0, 0, 0, 54, 0, + 0, 6, 34, 0, 16, 0, + 4, 0, 0, 0, 10, 0, + 16, 128, 65, 0, 0, 0, + 4, 0, 0, 0, 0, 0, + 0, 7, 98, 0, 16, 0, + 3, 0, 0, 0, 166, 10, + 16, 0, 0, 0, 0, 0, + 6, 1, 16, 0, 4, 0, + 0, 0, 56, 0, 0, 7, + 98, 0, 16, 0, 3, 0, + 0, 0, 6, 0, 16, 0, + 2, 0, 0, 0, 86, 6, + 16, 0, 3, 0, 0, 0, + 49, 0, 0, 10, 50, 0, + 16, 0, 4, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 150, 5, 16, 0, + 3, 0, 0, 0, 49, 0, + 0, 10, 194, 0, 16, 0, + 4, 0, 0, 0, 86, 9, + 16, 0, 3, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 30, 0, 0, 8, + 50, 0, 16, 0, 4, 0, + 0, 0, 70, 0, 16, 128, + 65, 0, 0, 0, 4, 0, + 0, 0, 230, 10, 16, 0, + 4, 0, 0, 0, 43, 0, + 0, 5, 50, 0, 16, 0, + 4, 0, 0, 0, 70, 0, + 16, 0, 4, 0, 0, 0, + 56, 0, 0, 9, 194, 0, + 16, 0, 4, 0, 0, 0, + 86, 9, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 86, 9, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 50, 0, 0, 15, 194, 0, + 16, 0, 4, 0, 0, 0, + 166, 14, 16, 0, 4, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 22, 247, 159, 61, + 22, 247, 159, 61, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 24, 235, + 107, 62, 24, 235, 107, 62, + 50, 0, 0, 13, 194, 0, + 16, 0, 4, 0, 0, 0, + 166, 14, 16, 0, 4, 0, + 0, 0, 86, 9, 16, 128, + 129, 0, 0, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 135, 137, 142, 62, + 135, 137, 142, 62, 50, 0, + 0, 13, 98, 0, 16, 0, + 3, 0, 0, 0, 166, 11, + 16, 0, 4, 0, 0, 0, + 86, 6, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 128, 63, + 0, 0, 128, 63, 0, 0, + 0, 0, 56, 0, 0, 7, + 98, 0, 16, 0, 3, 0, + 0, 0, 86, 6, 16, 0, + 3, 0, 0, 0, 86, 6, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 7, 98, 0, + 16, 0, 3, 0, 0, 0, + 86, 6, 16, 0, 3, 0, + 0, 0, 86, 6, 16, 0, + 3, 0, 0, 0, 14, 0, + 0, 7, 98, 0, 16, 0, + 3, 0, 0, 0, 6, 1, + 16, 0, 4, 0, 0, 0, + 86, 6, 16, 0, 3, 0, + 0, 0, 0, 0, 0, 8, + 98, 0, 16, 0, 3, 0, + 0, 0, 86, 6, 16, 128, + 65, 0, 0, 0, 3, 0, + 0, 0, 6, 1, 16, 0, + 4, 0, 0, 0, 0, 0, + 0, 8, 130, 0, 16, 0, + 2, 0, 0, 0, 42, 0, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 7, 130, 0, + 16, 0, 2, 0, 0, 0, + 58, 0, 16, 0, 2, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 63, 56, 0, + 0, 7, 34, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 1, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 15, 0, 0, 7, + 66, 0, 16, 0, 3, 0, + 0, 0, 166, 26, 16, 0, + 6, 0, 0, 0, 166, 26, + 16, 0, 6, 0, 0, 0, + 14, 0, 0, 8, 34, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 128, 65, 0, + 0, 0, 3, 0, 0, 0, + 42, 0, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 34, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 3, 0, 0, 0, 1, 64, + 0, 0, 59, 170, 184, 63, + 25, 0, 0, 5, 34, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 130, 0, 16, 0, 2, 0, + 0, 0, 58, 0, 16, 0, + 2, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 50, 0, 0, 9, 34, 0, + 16, 0, 1, 0, 0, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 128, 62, 26, 0, + 16, 0, 1, 0, 0, 0, + 0, 0, 0, 8, 34, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, 8, + 34, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 2, 0, 0, 0, 26, 0, + 16, 128, 193, 0, 0, 0, + 3, 0, 0, 0, 51, 0, + 0, 7, 34, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 0, 50, 0, 0, 10, + 34, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 3, 0, 0, 0, 10, 0, + 16, 0, 3, 0, 0, 0, + 52, 0, 0, 7, 34, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 0, 75, 0, + 0, 5, 34, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 0, 0, 0, 7, 18, 0, + 16, 0, 4, 0, 0, 0, + 42, 0, 16, 0, 2, 0, + 0, 0, 26, 0, 16, 0, + 3, 0, 0, 0, 54, 0, + 0, 6, 34, 0, 16, 0, + 4, 0, 0, 0, 10, 0, + 16, 128, 65, 0, 0, 0, + 4, 0, 0, 0, 0, 0, + 0, 7, 162, 0, 16, 0, + 3, 0, 0, 0, 166, 10, + 16, 0, 0, 0, 0, 0, + 6, 4, 16, 0, 4, 0, + 0, 0, 56, 0, 0, 7, + 162, 0, 16, 0, 3, 0, + 0, 0, 6, 0, 16, 0, + 2, 0, 0, 0, 86, 13, + 16, 0, 3, 0, 0, 0, + 49, 0, 0, 10, 50, 0, + 16, 0, 4, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 214, 5, 16, 0, + 3, 0, 0, 0, 49, 0, + 0, 10, 194, 0, 16, 0, + 4, 0, 0, 0, 86, 13, + 16, 0, 3, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 30, 0, 0, 8, + 50, 0, 16, 0, 4, 0, + 0, 0, 70, 0, 16, 128, + 65, 0, 0, 0, 4, 0, + 0, 0, 230, 10, 16, 0, + 4, 0, 0, 0, 43, 0, + 0, 5, 50, 0, 16, 0, + 4, 0, 0, 0, 70, 0, + 16, 0, 4, 0, 0, 0, + 56, 0, 0, 9, 194, 0, + 16, 0, 4, 0, 0, 0, + 86, 13, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 86, 13, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 50, 0, 0, 15, 194, 0, + 16, 0, 4, 0, 0, 0, + 166, 14, 16, 0, 4, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 22, 247, 159, 61, + 22, 247, 159, 61, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 24, 235, + 107, 62, 24, 235, 107, 62, + 50, 0, 0, 13, 194, 0, + 16, 0, 4, 0, 0, 0, + 166, 14, 16, 0, 4, 0, + 0, 0, 86, 13, 16, 128, + 129, 0, 0, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 135, 137, 142, 62, + 135, 137, 142, 62, 50, 0, + 0, 13, 162, 0, 16, 0, + 3, 0, 0, 0, 166, 14, + 16, 0, 4, 0, 0, 0, + 86, 13, 16, 128, 129, 0, + 0, 0, 3, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 128, 63, + 0, 0, 0, 0, 0, 0, + 128, 63, 56, 0, 0, 7, + 162, 0, 16, 0, 3, 0, + 0, 0, 86, 13, 16, 0, + 3, 0, 0, 0, 86, 13, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 7, 162, 0, + 16, 0, 3, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 86, 13, 16, 0, + 3, 0, 0, 0, 14, 0, + 0, 7, 162, 0, 16, 0, + 3, 0, 0, 0, 6, 4, + 16, 0, 4, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 0, 0, 0, 8, + 162, 0, 16, 0, 3, 0, + 0, 0, 86, 13, 16, 128, + 65, 0, 0, 0, 3, 0, + 0, 0, 6, 4, 16, 0, + 4, 0, 0, 0, 0, 0, + 0, 8, 34, 0, 16, 0, + 3, 0, 0, 0, 58, 0, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 7, 130, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 0, + 1, 0, 0, 0, 14, 0, + 0, 8, 130, 0, 16, 0, + 3, 0, 0, 0, 58, 0, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 42, 0, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 10, 162, 0, + 16, 0, 3, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 63, 0, 0, 0, 0, + 59, 170, 184, 63, 25, 0, + 0, 5, 130, 0, 16, 0, + 3, 0, 0, 0, 58, 0, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 7, 34, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 3, 0, 0, 0, 56, 0, + 0, 7, 34, 0, 16, 0, + 3, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 50, 0, 0, 9, + 130, 0, 16, 0, 2, 0, + 0, 0, 58, 0, 16, 0, + 2, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 50, 0, 0, 9, + 34, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 1, 64, + 0, 0, 0, 0, 128, 62, + 26, 0, 16, 0, 1, 0, + 0, 0, 0, 0, 0, 8, + 34, 0, 16, 0, 3, 0, + 0, 0, 58, 0, 16, 0, + 0, 0, 0, 0, 26, 0, + 16, 128, 65, 0, 0, 0, + 1, 0, 0, 0, 0, 0, + 0, 8, 34, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 2, 0, 0, 0, + 26, 0, 16, 128, 193, 0, + 0, 0, 3, 0, 0, 0, + 51, 0, 0, 7, 34, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 0, 50, 0, + 0, 10, 34, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 10, 0, 16, 0, 3, 0, + 0, 0, 52, 0, 0, 7, + 34, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 3, 0, 0, 0, 1, 64, + 0, 0, 0, 0, 0, 0, + 75, 0, 0, 5, 34, 0, + 16, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 0, 0, 0, 7, + 18, 0, 16, 0, 4, 0, + 0, 0, 42, 0, 16, 0, + 2, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 54, 0, 0, 6, 34, 0, + 16, 0, 4, 0, 0, 0, + 10, 0, 16, 128, 65, 0, + 0, 0, 4, 0, 0, 0, + 0, 0, 0, 7, 162, 0, + 16, 0, 3, 0, 0, 0, + 166, 10, 16, 0, 0, 0, + 0, 0, 6, 4, 16, 0, + 4, 0, 0, 0, 56, 0, + 0, 7, 162, 0, 16, 0, + 3, 0, 0, 0, 6, 0, + 16, 0, 2, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 49, 0, 0, 10, + 50, 0, 16, 0, 4, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 62, 0, - 0, 1, 21, 0, 0, 1, - 14, 32, 0, 7, 66, 0, + 0, 0, 0, 0, 214, 5, + 16, 0, 3, 0, 0, 0, + 49, 0, 0, 10, 194, 0, + 16, 0, 4, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 30, 0, + 0, 8, 50, 0, 16, 0, + 4, 0, 0, 0, 70, 0, + 16, 128, 65, 0, 0, 0, + 4, 0, 0, 0, 230, 10, + 16, 0, 4, 0, 0, 0, + 43, 0, 0, 5, 50, 0, + 16, 0, 4, 0, 0, 0, + 70, 0, 16, 0, 4, 0, + 0, 0, 56, 0, 0, 9, + 194, 0, 16, 0, 4, 0, + 0, 0, 86, 13, 16, 128, + 129, 0, 0, 0, 3, 0, + 0, 0, 86, 13, 16, 128, + 129, 0, 0, 0, 3, 0, + 0, 0, 50, 0, 0, 15, + 194, 0, 16, 0, 4, 0, + 0, 0, 166, 14, 16, 0, + 4, 0, 0, 0, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 22, 247, + 159, 61, 22, 247, 159, 61, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 24, 235, 107, 62, 24, 235, + 107, 62, 50, 0, 0, 13, + 194, 0, 16, 0, 4, 0, + 0, 0, 166, 14, 16, 0, + 4, 0, 0, 0, 86, 13, + 16, 128, 129, 0, 0, 0, + 3, 0, 0, 0, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 135, 137, + 142, 62, 135, 137, 142, 62, + 50, 0, 0, 13, 162, 0, + 16, 0, 3, 0, 0, 0, + 166, 14, 16, 0, 4, 0, + 0, 0, 86, 13, 16, 128, + 129, 0, 0, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 128, 63, 0, 0, 0, 0, + 0, 0, 128, 63, 56, 0, + 0, 7, 162, 0, 16, 0, + 3, 0, 0, 0, 86, 13, + 16, 0, 3, 0, 0, 0, + 86, 13, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 162, 0, 16, 0, 3, 0, + 0, 0, 86, 13, 16, 0, + 3, 0, 0, 0, 86, 13, + 16, 0, 3, 0, 0, 0, + 14, 0, 0, 7, 162, 0, + 16, 0, 3, 0, 0, 0, + 6, 4, 16, 0, 4, 0, + 0, 0, 86, 13, 16, 0, + 3, 0, 0, 0, 0, 0, + 0, 8, 162, 0, 16, 0, + 3, 0, 0, 0, 86, 13, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 6, 4, + 16, 0, 4, 0, 0, 0, + 0, 0, 0, 8, 34, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 128, 65, 0, + 0, 0, 3, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 130, 0, 16, 0, 3, 0, + 0, 0, 26, 0, 16, 0, + 1, 0, 0, 0, 26, 0, + 16, 0, 1, 0, 0, 0, + 14, 0, 0, 8, 130, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 128, 65, 0, + 0, 0, 3, 0, 0, 0, + 42, 0, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 10, + 162, 0, 16, 0, 3, 0, + 0, 0, 86, 13, 16, 0, + 3, 0, 0, 0, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 63, 0, 0, + 0, 0, 59, 170, 184, 63, + 25, 0, 0, 5, 130, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 34, 0, 16, 0, 3, 0, + 0, 0, 58, 0, 16, 0, + 3, 0, 0, 0, 26, 0, + 16, 0, 3, 0, 0, 0, + 50, 0, 0, 9, 130, 0, + 16, 0, 2, 0, 0, 0, + 26, 0, 16, 0, 3, 0, + 0, 0, 58, 0, 16, 0, + 1, 0, 0, 0, 58, 0, + 16, 0, 2, 0, 0, 0, + 50, 0, 0, 9, 34, 0, + 16, 0, 1, 0, 0, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 128, 62, 26, 0, + 16, 0, 1, 0, 0, 0, + 0, 0, 0, 8, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, - 0, 0, 42, 16, 16, 0, - 6, 0, 0, 0, 0, 0, - 0, 8, 66, 0, 16, 0, - 0, 0, 0, 0, 42, 0, - 16, 128, 65, 0, 0, 0, - 0, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 128, 63, - 56, 0, 0, 7, 130, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, 8, + 130, 0, 16, 0, 0, 0, + 0, 0, 58, 0, 16, 128, + 193, 0, 0, 0, 0, 0, + 0, 0, 26, 0, 16, 0, + 2, 0, 0, 0, 51, 0, + 0, 7, 130, 0, 16, 0, + 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, - 42, 0, 16, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 0, 50, 0, 0, 10, + 130, 0, 16, 0, 0, 0, + 0, 0, 58, 0, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 58, 0, 16, 0, + 0, 0, 0, 0, 10, 0, + 16, 0, 3, 0, 0, 0, + 52, 0, 0, 7, 130, 0, + 16, 0, 0, 0, 0, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 0, 0, 75, 0, + 0, 5, 130, 0, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 0, 0, 0, 0, 0, + 0, 0, 0, 7, 18, 0, + 16, 0, 3, 0, 0, 0, + 58, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, + 2, 0, 0, 0, 54, 0, + 0, 6, 34, 0, 16, 0, + 3, 0, 0, 0, 10, 0, + 16, 128, 65, 0, 0, 0, + 3, 0, 0, 0, 0, 0, + 0, 7, 194, 0, 16, 0, + 0, 0, 0, 0, 166, 10, + 16, 0, 0, 0, 0, 0, + 6, 4, 16, 0, 3, 0, + 0, 0, 56, 0, 0, 7, + 194, 0, 16, 0, 0, 0, + 0, 0, 6, 0, 16, 0, + 2, 0, 0, 0, 166, 14, + 16, 0, 0, 0, 0, 0, + 49, 0, 0, 10, 50, 0, + 16, 0, 2, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 230, 10, 16, 0, + 0, 0, 0, 0, 49, 0, + 0, 10, 50, 0, 16, 0, + 3, 0, 0, 0, 230, 10, + 16, 0, 0, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 30, 0, 0, 8, + 50, 0, 16, 0, 2, 0, + 0, 0, 70, 0, 16, 128, + 65, 0, 0, 0, 2, 0, + 0, 0, 70, 0, 16, 0, + 3, 0, 0, 0, 43, 0, + 0, 5, 50, 0, 16, 0, + 2, 0, 0, 0, 70, 0, + 16, 0, 2, 0, 0, 0, + 56, 0, 0, 9, 50, 0, + 16, 0, 3, 0, 0, 0, + 230, 10, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, + 230, 10, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, + 50, 0, 0, 15, 50, 0, + 16, 0, 3, 0, 0, 0, + 70, 0, 16, 0, 3, 0, + 0, 0, 2, 64, 0, 0, + 22, 247, 159, 61, 22, 247, + 159, 61, 0, 0, 0, 0, + 0, 0, 0, 0, 2, 64, + 0, 0, 24, 235, 107, 62, + 24, 235, 107, 62, 0, 0, + 0, 0, 0, 0, 0, 0, + 50, 0, 0, 13, 50, 0, + 16, 0, 3, 0, 0, 0, + 70, 0, 16, 0, 3, 0, + 0, 0, 230, 10, 16, 128, + 129, 0, 0, 0, 0, 0, + 0, 0, 2, 64, 0, 0, + 135, 137, 142, 62, 135, 137, + 142, 62, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, - 0, 10, 66, 0, 16, 0, + 0, 13, 194, 0, 16, 0, + 0, 0, 0, 0, 6, 4, + 16, 0, 3, 0, 0, 0, + 166, 14, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 128, 63, 0, 0, + 128, 63, 56, 0, 0, 7, + 194, 0, 16, 0, 0, 0, + 0, 0, 166, 14, 16, 0, + 0, 0, 0, 0, 166, 14, + 16, 0, 0, 0, 0, 0, + 56, 0, 0, 7, 194, 0, + 16, 0, 0, 0, 0, 0, + 166, 14, 16, 0, 0, 0, + 0, 0, 166, 14, 16, 0, + 0, 0, 0, 0, 14, 0, + 0, 7, 194, 0, 16, 0, + 0, 0, 0, 0, 6, 4, + 16, 0, 2, 0, 0, 0, + 166, 14, 16, 0, 0, 0, + 0, 0, 0, 0, 0, 8, + 194, 0, 16, 0, 0, 0, + 0, 0, 166, 14, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 6, 4, 16, 0, + 2, 0, 0, 0, 0, 0, + 0, 8, 66, 0, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 128, 65, 0, 0, 0, 0, 0, 0, 0, 42, 0, + 16, 0, 0, 0, 0, 0, + 56, 0, 0, 7, 130, 0, + 16, 0, 0, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 0, + 1, 0, 0, 0, 14, 0, + 0, 8, 130, 0, 16, 0, + 0, 0, 0, 0, 58, 0, 16, 128, 65, 0, 0, 0, - 0, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 0, 64, - 1, 64, 0, 0, 0, 0, - 64, 64, 56, 0, 0, 7, - 66, 0, 16, 0, 0, 0, - 0, 0, 42, 0, 16, 0, + 0, 0, 0, 0, 42, 0, + 16, 0, 3, 0, 0, 0, + 56, 0, 0, 10, 194, 0, + 16, 0, 0, 0, 0, 0, + 166, 14, 16, 0, 0, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 63, + 59, 170, 184, 63, 25, 0, + 0, 5, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 56, 0, 0, 7, 66, 0, 16, 0, 0, 0, 0, 0, - 42, 0, 16, 0, 0, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 42, 0, 16, 0, + 0, 0, 0, 0, 50, 0, + 0, 9, 18, 0, 16, 0, + 1, 0, 0, 0, 42, 0, + 16, 0, 0, 0, 0, 0, + 58, 0, 16, 0, 1, 0, + 0, 0, 58, 0, 16, 0, + 2, 0, 0, 0, 21, 0, + 0, 1, 21, 0, 0, 1, + 56, 0, 0, 7, 66, 0, + 16, 0, 0, 0, 0, 0, + 10, 0, 16, 0, 1, 0, + 0, 0, 58, 16, 16, 0, + 6, 0, 0, 0, 0, 32, + 0, 7, 34, 0, 16, 0, + 0, 0, 0, 0, 26, 0, + 16, 0, 0, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 63, 56, 0, 0, 7, + 34, 0, 16, 0, 0, 0, + 0, 0, 26, 0, 16, 0, + 0, 0, 0, 0, 42, 0, + 16, 0, 0, 0, 0, 0, + 56, 32, 0, 7, 34, 0, + 16, 0, 0, 0, 0, 0, + 26, 0, 16, 0, 0, 0, 0, 0, 58, 16, 16, 0, - 6, 0, 0, 0, 0, 32, - 0, 7, 34, 0, 16, 0, - 0, 0, 0, 0, 26, 0, + 2, 0, 0, 0, 56, 0, + 0, 7, 114, 32, 16, 0, + 0, 0, 0, 0, 86, 5, 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 0, 0, - 0, 63, 56, 32, 0, 7, + 70, 18, 16, 0, 2, 0, + 0, 0, 54, 0, 0, 5, 130, 32, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, - 0, 0, 0, 0, 42, 0, - 16, 0, 0, 0, 0, 0, - 54, 0, 0, 8, 114, 32, + 0, 0, 0, 0, 62, 0, + 0, 1, 21, 0, 0, 1, + 32, 0, 0, 7, 34, 0, 16, 0, 0, 0, 0, 0, - 2, 64, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, + 10, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 7, 0, 0, 0, 31, 0, + 4, 3, 26, 0, 16, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 62, 0, 0, 1, - 21, 0, 0, 1, 32, 0, - 0, 7, 34, 0, 16, 0, - 0, 0, 0, 0, 10, 0, - 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 7, 0, - 0, 0, 31, 0, 4, 3, - 26, 0, 16, 0, 0, 0, - 0, 0, 0, 0, 0, 8, - 98, 0, 16, 0, 0, 0, - 0, 0, 6, 17, 16, 0, + 0, 8, 98, 0, 16, 0, 0, 0, 0, 0, 6, 17, - 16, 128, 65, 0, 0, 0, - 1, 0, 0, 0, 14, 32, - 0, 7, 98, 0, 16, 0, - 0, 0, 0, 0, 86, 6, 16, 0, 0, 0, 0, 0, - 166, 27, 16, 0, 1, 0, - 0, 0, 0, 0, 0, 8, - 242, 0, 16, 0, 1, 0, - 0, 0, 70, 30, 16, 128, - 65, 0, 0, 0, 2, 0, - 0, 0, 70, 30, 16, 0, - 5, 0, 0, 0, 50, 0, - 0, 9, 242, 0, 16, 0, - 1, 0, 0, 0, 166, 10, + 6, 17, 16, 128, 65, 0, + 0, 0, 1, 0, 0, 0, + 14, 32, 0, 7, 98, 0, 16, 0, 0, 0, 0, 0, - 70, 14, 16, 0, 1, 0, - 0, 0, 70, 30, 16, 0, - 2, 0, 0, 0, 0, 0, + 86, 6, 16, 0, 0, 0, + 0, 0, 166, 27, 16, 0, + 1, 0, 0, 0, 0, 0, 0, 8, 242, 0, 16, 0, - 2, 0, 0, 0, 70, 30, + 1, 0, 0, 0, 70, 30, 16, 128, 65, 0, 0, 0, - 3, 0, 0, 0, 70, 30, - 16, 0, 4, 0, 0, 0, + 2, 0, 0, 0, 70, 30, + 16, 0, 5, 0, 0, 0, 50, 0, 0, 9, 242, 0, - 16, 0, 2, 0, 0, 0, + 16, 0, 1, 0, 0, 0, 166, 10, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, - 2, 0, 0, 0, 70, 30, - 16, 0, 3, 0, 0, 0, + 1, 0, 0, 0, 70, 30, + 16, 0, 2, 0, 0, 0, 0, 0, 0, 8, 242, 0, 16, 0, 2, 0, 0, 0, - 70, 14, 16, 128, 65, 0, - 0, 0, 1, 0, 0, 0, - 70, 14, 16, 0, 2, 0, + 70, 30, 16, 128, 65, 0, + 0, 0, 3, 0, 0, 0, + 70, 30, 16, 0, 4, 0, 0, 0, 50, 0, 0, 9, - 242, 0, 16, 0, 1, 0, - 0, 0, 86, 5, 16, 0, + 242, 0, 16, 0, 2, 0, + 0, 0, 166, 10, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 2, 0, 0, 0, - 70, 14, 16, 0, 1, 0, - 0, 0, 54, 32, 0, 5, - 130, 0, 16, 0, 1, 0, - 0, 0, 58, 0, 16, 0, - 1, 0, 0, 0, 56, 0, - 0, 7, 114, 32, 16, 0, - 0, 0, 0, 0, 246, 15, + 70, 30, 16, 0, 3, 0, + 0, 0, 0, 0, 0, 8, + 242, 0, 16, 0, 2, 0, + 0, 0, 70, 14, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 70, 14, 16, 0, + 2, 0, 0, 0, 50, 0, + 0, 9, 242, 0, 16, 0, + 1, 0, 0, 0, 86, 5, + 16, 0, 0, 0, 0, 0, + 70, 14, 16, 0, 2, 0, + 0, 0, 70, 14, 16, 0, + 1, 0, 0, 0, 54, 32, + 0, 5, 130, 0, 16, 0, + 1, 0, 0, 0, 58, 0, 16, 0, 1, 0, 0, 0, - 70, 2, 16, 0, 1, 0, - 0, 0, 54, 0, 0, 5, - 130, 32, 16, 0, 0, 0, - 0, 0, 58, 0, 16, 0, - 1, 0, 0, 0, 62, 0, - 0, 1, 21, 0, 0, 1, - 32, 0, 0, 7, 34, 0, + 56, 0, 0, 7, 114, 32, 16, 0, 0, 0, 0, 0, - 10, 0, 16, 0, 0, 0, - 0, 0, 1, 64, 0, 0, - 8, 0, 0, 0, 31, 0, - 4, 3, 26, 0, 16, 0, - 0, 0, 0, 0, 0, 0, - 0, 8, 98, 0, 16, 0, - 0, 0, 0, 0, 6, 17, + 246, 15, 16, 0, 1, 0, + 0, 0, 70, 2, 16, 0, + 1, 0, 0, 0, 54, 0, + 0, 5, 130, 32, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 62, 0, 0, 1, 21, 0, + 0, 1, 32, 0, 0, 7, + 34, 0, 16, 0, 0, 0, + 0, 0, 10, 0, 16, 0, + 0, 0, 0, 0, 1, 64, + 0, 0, 8, 0, 0, 0, + 31, 0, 4, 3, 26, 0, 16, 0, 0, 0, 0, 0, - 6, 17, 16, 128, 65, 0, - 0, 0, 1, 0, 0, 0, - 15, 0, 0, 7, 130, 0, + 0, 0, 0, 8, 98, 0, 16, 0, 0, 0, 0, 0, - 150, 5, 16, 0, 0, 0, + 6, 17, 16, 0, 0, 0, + 0, 0, 6, 17, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 15, 0, 0, 7, + 130, 0, 16, 0, 0, 0, 0, 0, 150, 5, 16, 0, - 0, 0, 0, 0, 75, 0, - 0, 5, 130, 0, 16, 0, - 0, 0, 0, 0, 58, 0, + 0, 0, 0, 0, 150, 5, 16, 0, 0, 0, 0, 0, - 0, 0, 0, 8, 18, 0, - 16, 0, 1, 0, 0, 0, - 58, 0, 16, 128, 65, 0, - 0, 0, 0, 0, 0, 0, - 42, 16, 16, 0, 1, 0, - 0, 0, 0, 32, 0, 7, + 75, 0, 0, 5, 130, 0, + 16, 0, 0, 0, 0, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 18, 0, 16, 0, 1, 0, - 0, 0, 10, 0, 16, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 0, 63, - 51, 0, 0, 9, 34, 0, + 0, 0, 58, 0, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 42, 16, 16, 0, + 1, 0, 0, 0, 0, 32, + 0, 7, 18, 0, 16, 0, + 1, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, - 42, 0, 16, 128, 129, 0, - 0, 0, 0, 0, 0, 0, - 26, 0, 16, 128, 129, 0, - 0, 0, 0, 0, 0, 0, - 52, 0, 0, 9, 66, 0, + 1, 64, 0, 0, 0, 0, + 0, 63, 51, 0, 0, 9, + 34, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 128, + 129, 0, 0, 0, 0, 0, + 0, 0, 26, 0, 16, 128, + 129, 0, 0, 0, 0, 0, + 0, 0, 52, 0, 0, 9, + 66, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 128, + 129, 0, 0, 0, 0, 0, + 0, 0, 26, 0, 16, 128, + 129, 0, 0, 0, 0, 0, + 0, 0, 14, 0, 0, 10, + 66, 0, 16, 0, 1, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 128, 63, 0, 0, + 128, 63, 0, 0, 128, 63, + 0, 0, 128, 63, 42, 0, 16, 0, 1, 0, 0, 0, - 42, 0, 16, 128, 129, 0, - 0, 0, 0, 0, 0, 0, - 26, 0, 16, 128, 129, 0, - 0, 0, 0, 0, 0, 0, - 14, 0, 0, 10, 66, 0, + 56, 0, 0, 7, 34, 0, 16, 0, 1, 0, 0, 0, - 2, 64, 0, 0, 0, 0, - 128, 63, 0, 0, 128, 63, - 0, 0, 128, 63, 0, 0, - 128, 63, 42, 0, 16, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, 56, 0, - 0, 7, 34, 0, 16, 0, - 1, 0, 0, 0, 42, 0, + 0, 7, 66, 0, 16, 0, + 1, 0, 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, 26, 0, 16, 0, 1, 0, - 0, 0, 56, 0, 0, 7, + 0, 0, 50, 0, 0, 9, + 130, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 1, 64, + 0, 0, 95, 174, 170, 60, + 1, 64, 0, 0, 54, 90, + 174, 189, 50, 0, 0, 9, + 130, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 226, 118, + 56, 62, 50, 0, 0, 9, + 130, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 4, 29, + 169, 190, 50, 0, 0, 9, 66, 0, 16, 0, 1, 0, - 0, 0, 26, 0, 16, 0, + 0, 0, 42, 0, 16, 0, + 1, 0, 0, 0, 58, 0, + 16, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 56, 247, + 127, 63, 56, 0, 0, 7, + 130, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 0, 1, 0, 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, + 49, 0, 0, 9, 18, 0, + 16, 0, 2, 0, 0, 0, + 42, 0, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, + 26, 0, 16, 128, 129, 0, + 0, 0, 0, 0, 0, 0, 50, 0, 0, 9, 130, 0, 16, 0, 1, 0, 0, 0, - 42, 0, 16, 0, 1, 0, + 58, 0, 16, 0, 1, 0, 0, 0, 1, 64, 0, 0, - 95, 174, 170, 60, 1, 64, - 0, 0, 54, 90, 174, 189, - 50, 0, 0, 9, 130, 0, + 0, 0, 0, 192, 1, 64, + 0, 0, 219, 15, 201, 63, + 1, 0, 0, 7, 130, 0, 16, 0, 1, 0, 0, 0, - 42, 0, 16, 0, 1, 0, - 0, 0, 58, 0, 16, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 226, 118, 56, 62, - 50, 0, 0, 9, 130, 0, - 16, 0, 1, 0, 0, 0, - 42, 0, 16, 0, 1, 0, + 10, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 4, 29, 169, 190, - 50, 0, 0, 9, 66, 0, + 1, 0, 0, 0, 50, 0, + 0, 9, 34, 0, 16, 0, + 1, 0, 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, 42, 0, 16, 0, 1, 0, 0, 0, 58, 0, 16, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 56, 247, 127, 63, - 56, 0, 0, 7, 130, 0, - 16, 0, 1, 0, 0, 0, - 42, 0, 16, 0, 1, 0, - 0, 0, 26, 0, 16, 0, 1, 0, 0, 0, 49, 0, - 0, 9, 18, 0, 16, 0, - 2, 0, 0, 0, 42, 0, - 16, 128, 129, 0, 0, 0, - 0, 0, 0, 0, 26, 0, - 16, 128, 129, 0, 0, 0, - 0, 0, 0, 0, 50, 0, - 0, 9, 130, 0, 16, 0, - 1, 0, 0, 0, 58, 0, - 16, 0, 1, 0, 0, 0, - 1, 64, 0, 0, 0, 0, - 0, 192, 1, 64, 0, 0, - 219, 15, 201, 63, 1, 0, - 0, 7, 130, 0, 16, 0, - 1, 0, 0, 0, 10, 0, - 16, 0, 2, 0, 0, 0, - 58, 0, 16, 0, 1, 0, - 0, 0, 50, 0, 0, 9, - 34, 0, 16, 0, 1, 0, - 0, 0, 26, 0, 16, 0, - 1, 0, 0, 0, 42, 0, - 16, 0, 1, 0, 0, 0, - 58, 0, 16, 0, 1, 0, - 0, 0, 49, 0, 0, 8, - 66, 0, 16, 0, 1, 0, - 0, 0, 42, 0, 16, 128, - 65, 0, 0, 0, 0, 0, - 0, 0, 42, 0, 16, 0, - 0, 0, 0, 0, 1, 0, - 0, 7, 66, 0, 16, 0, + 0, 8, 66, 0, 16, 0, 1, 0, 0, 0, 42, 0, + 16, 128, 65, 0, 0, 0, + 0, 0, 0, 0, 42, 0, + 16, 0, 0, 0, 0, 0, + 1, 0, 0, 7, 66, 0, 16, 0, 1, 0, 0, 0, - 1, 64, 0, 0, 219, 15, - 73, 192, 0, 0, 0, 7, - 34, 0, 16, 0, 1, 0, - 0, 0, 42, 0, 16, 0, - 1, 0, 0, 0, 26, 0, - 16, 0, 1, 0, 0, 0, - 51, 0, 0, 8, 66, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 1, 64, 0, 0, + 219, 15, 73, 192, 0, 0, + 0, 7, 34, 0, 16, 0, + 1, 0, 0, 0, 42, 0, 16, 0, 1, 0, 0, 0, - 42, 0, 16, 128, 65, 0, - 0, 0, 0, 0, 0, 0, - 26, 0, 16, 0, 0, 0, - 0, 0, 52, 0, 0, 8, - 34, 0, 16, 0, 0, 0, + 26, 0, 16, 0, 1, 0, + 0, 0, 51, 0, 0, 8, + 66, 0, 16, 0, 1, 0, 0, 0, 42, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0, 26, 0, 16, 0, - 0, 0, 0, 0, 49, 0, - 0, 8, 66, 0, 16, 0, + 0, 0, 0, 0, 52, 0, + 0, 8, 34, 0, 16, 0, 0, 0, 0, 0, 42, 0, - 16, 0, 1, 0, 0, 0, - 42, 0, 16, 128, 65, 0, - 0, 0, 1, 0, 0, 0, - 29, 0, 0, 8, 34, 0, + 16, 128, 65, 0, 0, 0, + 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, - 26, 0, 16, 0, 0, 0, - 0, 0, 26, 0, 16, 128, - 65, 0, 0, 0, 0, 0, - 0, 0, 1, 0, 0, 7, + 49, 0, 0, 8, 66, 0, + 16, 0, 0, 0, 0, 0, + 42, 0, 16, 0, 1, 0, + 0, 0, 42, 0, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 29, 0, 0, 8, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, - 0, 0, 0, 0, 42, 0, - 16, 0, 0, 0, 0, 0, - 55, 0, 0, 10, 34, 0, + 0, 0, 0, 0, 26, 0, + 16, 128, 65, 0, 0, 0, + 0, 0, 0, 0, 1, 0, + 0, 7, 34, 0, 16, 0, + 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, - 26, 0, 16, 0, 0, 0, - 0, 0, 26, 0, 16, 128, - 65, 0, 0, 0, 1, 0, + 42, 0, 16, 0, 0, 0, + 0, 0, 55, 0, 0, 10, + 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, - 1, 0, 0, 0, 50, 0, - 0, 9, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, + 16, 128, 65, 0, 0, 0, + 1, 0, 0, 0, 26, 0, + 16, 0, 1, 0, 0, 0, + 50, 0, 0, 9, 34, 0, 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 131, 249, - 34, 62, 1, 64, 0, 0, - 0, 0, 0, 63, 14, 0, - 0, 7, 66, 0, 16, 0, - 0, 0, 0, 0, 58, 0, + 26, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 131, 249, 34, 62, 1, 64, + 0, 0, 0, 0, 0, 63, + 14, 0, 0, 7, 66, 0, 16, 0, 0, 0, 0, 0, - 42, 16, 16, 0, 1, 0, - 0, 0, 51, 0, 0, 7, - 66, 0, 16, 0, 0, 0, - 0, 0, 42, 0, 16, 0, - 0, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 128, 63, - 65, 0, 0, 5, 130, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 42, 16, 16, 0, + 1, 0, 0, 0, 51, 0, + 0, 7, 66, 0, 16, 0, + 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, - 26, 0, 16, 0, 0, 0, - 0, 0, 0, 0, 0, 8, - 34, 0, 16, 0, 0, 0, - 0, 0, 58, 0, 16, 128, - 65, 0, 0, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 128, 63, 65, 0, 0, 5, + 130, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, - 0, 0, 0, 0, 50, 0, - 0, 15, 226, 0, 16, 0, - 1, 0, 0, 0, 86, 5, + 0, 0, 0, 0, 0, 0, + 0, 8, 34, 0, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 128, 65, 0, 0, 0, + 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, + 50, 0, 0, 15, 226, 0, + 16, 0, 1, 0, 0, 0, + 86, 5, 16, 0, 0, 0, + 0, 0, 2, 64, 0, 0, + 0, 0, 0, 0, 0, 0, + 192, 64, 0, 0, 192, 64, + 0, 0, 192, 64, 2, 64, + 0, 0, 0, 0, 0, 0, + 0, 0, 64, 192, 0, 0, + 0, 192, 0, 0, 128, 192, + 50, 32, 0, 16, 226, 0, + 16, 0, 1, 0, 0, 0, + 86, 14, 16, 128, 129, 0, + 0, 0, 1, 0, 0, 0, 2, 64, 0, 0, 0, 0, - 0, 0, 0, 0, 192, 64, - 0, 0, 192, 64, 0, 0, - 192, 64, 2, 64, 0, 0, + 0, 0, 0, 0, 128, 63, + 0, 0, 128, 191, 0, 0, + 128, 191, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, - 64, 192, 0, 0, 0, 192, - 0, 0, 128, 192, 50, 32, - 0, 16, 226, 0, 16, 0, + 128, 191, 0, 0, 0, 64, + 0, 0, 0, 64, 0, 0, + 0, 10, 226, 0, 16, 0, 1, 0, 0, 0, 86, 14, - 16, 128, 129, 0, 0, 0, - 1, 0, 0, 0, 2, 64, - 0, 0, 0, 0, 0, 0, - 0, 0, 128, 63, 0, 0, - 128, 191, 0, 0, 128, 191, + 16, 0, 1, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 128, 191, - 0, 0, 0, 64, 0, 0, - 0, 64, 0, 0, 0, 10, - 226, 0, 16, 0, 1, 0, - 0, 0, 86, 14, 16, 0, - 1, 0, 0, 0, 2, 64, - 0, 0, 0, 0, 0, 0, 0, 0, 128, 191, 0, 0, - 128, 191, 0, 0, 128, 191, - 50, 0, 0, 12, 226, 0, + 128, 191, 50, 0, 0, 12, + 226, 0, 16, 0, 0, 0, + 0, 0, 86, 14, 16, 0, + 1, 0, 0, 0, 166, 10, 16, 0, 0, 0, 0, 0, - 86, 14, 16, 0, 1, 0, - 0, 0, 166, 10, 16, 0, - 0, 0, 0, 0, 2, 64, - 0, 0, 0, 0, 0, 0, + 2, 64, 0, 0, 0, 0, + 0, 0, 0, 0, 128, 63, 0, 0, 128, 63, 0, 0, - 128, 63, 0, 0, 128, 63, - 56, 0, 0, 7, 226, 0, + 128, 63, 56, 0, 0, 7, + 226, 0, 16, 0, 0, 0, + 0, 0, 86, 14, 16, 0, + 0, 0, 0, 0, 246, 31, + 16, 0, 1, 0, 0, 0, + 56, 0, 0, 7, 114, 32, 16, 0, 0, 0, 0, 0, - 86, 14, 16, 0, 0, 0, - 0, 0, 246, 31, 16, 0, - 1, 0, 0, 0, 56, 0, - 0, 7, 114, 32, 16, 0, - 0, 0, 0, 0, 6, 0, + 6, 0, 16, 0, 1, 0, + 0, 0, 150, 7, 16, 0, + 0, 0, 0, 0, 54, 0, + 0, 5, 130, 32, 16, 0, + 0, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, - 150, 7, 16, 0, 0, 0, - 0, 0, 54, 0, 0, 5, - 130, 32, 16, 0, 0, 0, + 62, 0, 0, 1, 21, 0, + 0, 1, 32, 0, 0, 7, + 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, - 1, 0, 0, 0, 62, 0, - 0, 1, 21, 0, 0, 1, - 32, 0, 0, 7, 18, 0, - 16, 0, 0, 0, 0, 0, - 10, 0, 16, 0, 0, 0, - 0, 0, 1, 64, 0, 0, - 9, 0, 0, 0, 31, 0, - 4, 3, 10, 0, 16, 0, - 0, 0, 0, 0, 0, 0, - 0, 8, 50, 0, 16, 0, - 0, 0, 0, 0, 70, 16, - 16, 0, 0, 0, 0, 0, - 70, 16, 16, 128, 65, 0, - 0, 0, 1, 0, 0, 0, - 54, 0, 0, 6, 66, 0, + 0, 0, 0, 0, 1, 64, + 0, 0, 9, 0, 0, 0, + 31, 0, 4, 3, 10, 0, 16, 0, 0, 0, 0, 0, - 26, 0, 16, 128, 65, 0, - 0, 0, 0, 0, 0, 0, - 14, 0, 0, 7, 50, 0, + 0, 0, 0, 8, 50, 0, 16, 0, 0, 0, 0, 0, - 134, 0, 16, 0, 0, 0, - 0, 0, 166, 26, 16, 0, - 1, 0, 0, 0, 15, 0, - 0, 7, 130, 0, 16, 0, - 0, 0, 0, 0, 70, 0, + 70, 16, 16, 0, 0, 0, + 0, 0, 70, 16, 16, 128, + 65, 0, 0, 0, 1, 0, + 0, 0, 54, 0, 0, 6, + 66, 0, 16, 0, 0, 0, + 0, 0, 26, 0, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 14, 0, 0, 7, + 50, 0, 16, 0, 0, 0, + 0, 0, 134, 0, 16, 0, + 0, 0, 0, 0, 166, 26, + 16, 0, 1, 0, 0, 0, + 15, 0, 0, 7, 130, 0, 16, 0, 0, 0, 0, 0, 70, 0, 16, 0, 0, 0, - 0, 0, 75, 0, 0, 5, + 0, 0, 70, 0, 16, 0, + 0, 0, 0, 0, 75, 0, + 0, 5, 18, 0, 16, 0, + 1, 0, 0, 0, 58, 0, + 16, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 18, 0, + 16, 0, 1, 0, 0, 0, + 10, 0, 16, 128, 65, 0, + 0, 0, 1, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 128, 63, 50, 32, 0, 9, 18, 0, 16, 0, 1, 0, - 0, 0, 58, 0, 16, 0, - 0, 0, 0, 0, 0, 0, - 0, 8, 18, 0, 16, 0, - 1, 0, 0, 0, 10, 0, - 16, 128, 65, 0, 0, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 128, 63, - 50, 32, 0, 9, 18, 0, + 0, 0, 10, 0, 16, 0, + 1, 0, 0, 0, 42, 16, 16, 0, 1, 0, 0, 0, - 10, 0, 16, 0, 1, 0, - 0, 0, 42, 16, 16, 0, - 1, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 0, 63, - 0, 0, 0, 8, 130, 0, - 16, 0, 0, 0, 0, 0, - 58, 0, 16, 128, 65, 0, - 0, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, - 128, 63, 52, 0, 0, 7, + 0, 63, 0, 0, 0, 8, 130, 0, 16, 0, 0, 0, + 0, 0, 58, 0, 16, 128, + 65, 0, 0, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 128, 63, 52, 0, + 0, 7, 130, 0, 16, 0, + 0, 0, 0, 0, 58, 0, + 16, 0, 0, 0, 0, 0, + 1, 64, 0, 0, 0, 0, + 0, 0, 75, 0, 0, 5, + 66, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, - 0, 0, 0, 0, 1, 64, - 0, 0, 0, 0, 0, 0, - 75, 0, 0, 5, 66, 0, + 0, 0, 0, 0, 16, 0, + 0, 7, 130, 0, 16, 0, + 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, - 58, 0, 16, 0, 0, 0, + 70, 18, 16, 0, 3, 0, 0, 0, 16, 0, 0, 7, - 130, 0, 16, 0, 0, 0, + 18, 0, 16, 0, 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, 70, 18, - 16, 0, 3, 0, 0, 0, - 16, 0, 0, 7, 18, 0, - 16, 0, 0, 0, 0, 0, - 70, 2, 16, 0, 0, 0, - 0, 0, 70, 18, 16, 0, - 4, 0, 0, 0, 52, 0, - 0, 10, 146, 0, 16, 0, - 0, 0, 0, 0, 6, 12, + 16, 0, 4, 0, 0, 0, + 52, 0, 0, 10, 146, 0, 16, 0, 0, 0, 0, 0, - 2, 64, 0, 0, 0, 0, + 6, 12, 16, 0, 0, 0, + 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 47, 0, 0, 5, - 18, 0, 16, 0, 0, 0, - 0, 0, 10, 0, 16, 0, - 0, 0, 0, 0, 56, 0, - 0, 7, 18, 0, 16, 0, + 0, 0, 0, 0, 47, 0, + 0, 5, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 0, 0, - 128, 65, 25, 0, 0, 5, - 18, 0, 16, 0, 0, 0, - 0, 0, 10, 0, 16, 0, - 0, 0, 0, 0, 50, 0, - 0, 9, 34, 0, 16, 0, - 0, 0, 0, 0, 58, 0, + 56, 0, 0, 7, 18, 0, 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 174, 71, - 97, 63, 1, 64, 0, 0, - 143, 194, 245, 61, 56, 0, - 0, 7, 18, 0, 16, 0, + 10, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 0, 0, 128, 65, 25, 0, + 0, 5, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, - 1, 64, 0, 0, 154, 153, - 25, 63, 50, 0, 0, 9, - 114, 0, 16, 0, 0, 0, - 0, 0, 70, 18, 16, 0, - 2, 0, 0, 0, 86, 5, + 50, 0, 0, 9, 34, 0, 16, 0, 0, 0, 0, 0, - 6, 0, 16, 0, 0, 0, - 0, 0, 56, 32, 0, 7, - 130, 0, 16, 0, 0, 0, - 0, 0, 10, 0, 16, 0, - 1, 0, 0, 0, 58, 16, + 58, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 174, 71, 97, 63, 1, 64, + 0, 0, 143, 194, 245, 61, + 56, 0, 0, 7, 18, 0, + 16, 0, 0, 0, 0, 0, + 10, 0, 16, 0, 0, 0, + 0, 0, 1, 64, 0, 0, + 154, 153, 25, 63, 50, 0, + 0, 9, 114, 0, 16, 0, + 0, 0, 0, 0, 70, 18, 16, 0, 2, 0, 0, 0, - 56, 0, 0, 7, 114, 32, + 86, 5, 16, 0, 0, 0, + 0, 0, 6, 0, 16, 0, + 0, 0, 0, 0, 56, 32, + 0, 7, 130, 0, 16, 0, + 0, 0, 0, 0, 10, 0, + 16, 0, 1, 0, 0, 0, + 58, 16, 16, 0, 2, 0, + 0, 0, 56, 0, 0, 7, + 114, 32, 16, 0, 0, 0, + 0, 0, 246, 15, 16, 0, + 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, - 246, 15, 16, 0, 0, 0, - 0, 0, 70, 2, 16, 0, - 0, 0, 0, 0, 54, 0, - 0, 5, 130, 32, 16, 0, - 0, 0, 0, 0, 58, 0, + 54, 0, 0, 5, 130, 32, 16, 0, 0, 0, 0, 0, - 62, 0, 0, 1, 21, 0, - 0, 1, 54, 0, 0, 8, - 242, 32, 16, 0, 0, 0, - 0, 0, 2, 64, 0, 0, + 58, 0, 16, 0, 0, 0, + 0, 0, 62, 0, 0, 1, + 21, 0, 0, 1, 54, 0, + 0, 8, 242, 32, 16, 0, + 0, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 62, 0, - 0, 1 + 0, 0, 0, 0, 0, 0, + 62, 0, 0, 1 }; const BYTE g_vs_tri[] = { diff --git a/gpu/intern/gpu_effect.c b/gpu/intern/gpu_effect.c index 809f716c..ad0db03f 100644 --- a/gpu/intern/gpu_effect.c +++ b/gpu/intern/gpu_effect.c @@ -22,7 +22,8 @@ * types float int bool vec2 vec3 vec4 (also float2 float3 float4); no matrices, no arrays of * other than U; the GLSL built-ins mix fract mod clamp step smoothstep abs sign floor ceil min * max pow exp exp2 log sqrt inversesqrt sin cos tan asin acos atan length distance dot - * normalize, and atan2(y, x) (as Blender's compat does for GLSL). + * normalize, atan(y, x) and atan2(y, x) (as Blender's compat does for GLSL); integer >> << & | ^. + * Names HLSL reserves (`line`, `point`, `sample`...) are free to use: they are renamed for it. * * SPDX-License-Identifier: GPL-2.0-or-later */ @@ -321,6 +322,27 @@ static size_t call_end(const char *src, size_t n, size_t open, int *r_comma) return n; } +/* Words HLSL keeps for itself that GLSL leaves free to name things with (a variable called `line`): + * renamed `bui_` where they are names. */ +static int hlsl_reserved(const char *w, size_t len) +{ + static const char *const words[] = { + "line", "lineadj", "point", "triangle", "triangleadj", "sample", + "matrix", "vector", "string", "pass", "technique", "compile", + "register", "packoffset", "half", "snorm", "unorm", "linear", + "nointerpolation", "groupshared", "shared", "extern", "inline", "cbuffer", + "tbuffer", "texture", "sampler", "export", "row_major", "column_major", + "globallycoherent", "stateblock", "dword", "fixed", "interface", "class", + "noise", + }; + for (size_t k = 0; k < sizeof(words) / sizeof(words[0]); k++) { + if (len == strlen(words[k]) && strncmp(w, words[k], len) == 0) { + return 1; + } + } + return 0; +} + static void hlsl_rewrite(StrBuf *s, const char *src, size_t n) { size_t i = 0; @@ -360,10 +382,27 @@ static void hlsl_rewrite(StrBuf *s, const char *src, size_t n) sb_add(s, "))"); i = close + 1; } - else { + else if (hlsl_reserved(src + i, j - i) && !(i > 0 && src[i - 1] == '#')) { /* not `#line` */ + sb_add(s, "bui_"); sb_range(s, src + i, j - i); i = j; } + else { + /* GLSL's two-argument atan(y, x) is HLSL's atan2 */ + size_t at = j; + while (at < n && (src[at] == ' ' || src[at] == '\t')) { + at++; + } + int two = 0; + if (j - i == 4 && strncmp(src + i, "atan", 4) == 0 && at < n && src[at] == '(') { + call_end(src, n, at, &two); + } + sb_add(s, two ? "atan2" : ""); + if (!two) { + sb_range(s, src + i, j - i); + } + i = j; + } } } diff --git a/gpu/intern/gpu_gl.c b/gpu/intern/gpu_gl.c index 5af7e2d6..579d29e5 100644 --- a/gpu/intern/gpu_gl.c +++ b/gpu/intern/gpu_gl.c @@ -503,6 +503,29 @@ static const char *const k_fs_quad = " acc.rgb = c.rgb * a + acc.rgb * (1.0 - a);\n" " acc.a = a + acc.a * (1.0 - a);\n" "}\n" + "vec2 erf2(vec2 x)\n" + "{\n" + " vec2 sg = sign(x), a = abs(x);\n" + " vec2 t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;\n" + " t *= t;\n" + " return sg - sg / (t * t);\n" + "}\n" + "float shadow_gauss(vec2 p, vec2 hb, float corner, float sigma)\n" + "{\n" + " float lo = p.y - hb.y, hi = p.y + hb.y;\n" + " float start = clamp(-3.0 * sigma, lo, hi), end = clamp(3.0 * sigma, lo, hi);\n" + " float dy = (end - start) * 0.25, k = 0.70710678 / sigma;\n" + " float norm = dy / (2.50662827 * sigma);\n" + " float y = start + dy * 0.5, v = 0.0;\n" + " for (int i = 0; i < 4; i++) {\n" + " float delta = min(hb.y - corner - abs(p.y - y), 0.0);\n" + " float curved = hb.x - corner + sqrt(max(0.0, corner * corner - delta * delta));\n" + " vec2 e = erf2((p.x + vec2(curved, -curved)) * k);\n" + " v += 0.5 * (e.x - e.y) * exp(-(y * y) / (2.0 * sigma * sigma)) * norm;\n" + " y += dy;\n" + " }\n" + " return v;\n" + "}\n" "vec4 premul(vec4 c, float cov)\n" "{\n" " float a = sat(c.a * cov);\n" @@ -740,17 +763,30 @@ static const char *const k_fs_quad = " return mix(top, bot, f.y) * v_p.y;\n" " }\n" " if (kind == K_SHADOW) {\n" - " float rad = v_p.y, size = v_p.z, alpha = v_p.w;\n" + " float rad = v_p.y, size = v_p.z, gain = v_p.w;\n" " vec2 hb = R.zw * 0.5;\n" " vec2 c = R.xy + hb;\n" - " float d = sd_box(s, c + vec2(0.0, size * 0.25), hb, rad, 15u);\n" - " float dbox = sd_box(s, c, hb, rad, 15u);\n" - " if (dbox <= -0.5 || d >= size) {\n" + " vec2 bhb = v_c1.zw * 0.5;\n" + " float dbox = sd_box(s, v_c1.xy + bhb, bhb, v_uv.x, 15u);\n" + " if (dbox <= -0.5) {\n" " return vec4(0.0);\n" " }\n" - " float t = 1.0 - sat(d / size);\n" - " t = t * t * (3.0 - 2.0 * t);\n" - " return vec4(0.0, 0.0, 0.0, sat(t * alpha * sat(0.5 + dbox)));\n" + " float t;\n" + " if (v_uv.y < 0.5) {\n" + " float d = sd_box(s, c, hb, rad, 15u);\n" + " if (d >= size) {\n" + " return vec4(0.0);\n" + " }\n" + " t = 1.0 - sat(d / size);\n" + " t = t * t * (3.0 - 2.0 * t);\n" + " }\n" + " else if (size < 0.25) {\n" + " t = sat(0.5 - sd_box(s, c, hb, rad, 15u));\n" + " }\n" + " else {\n" + " t = shadow_gauss(s - c, hb, rad, size);\n" + " }\n" + " return premul(v_c0, t * gain * sat(0.5 + dbox));\n" " }\n" " if (kind == K_GRADIENT) {\n" " vec2 uv = sat((s - R.xy) / R.zw);\n" diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.c index 9816b255..e705f3bf 100644 --- a/gpu/intern/gpu_raster.c +++ b/gpu/intern/gpu_raster.c @@ -1807,45 +1807,95 @@ void BUI_raster_end_frame_region(BuiRaster *r, int rx, int ry, int rw, int rh) } } -SHAPE_INLINE void shadow_keep( - BuiRaster *r, float x, float y, float w, float h, float radius, float size, float alpha, const int keep) -{ - if (w <= 0.0f || h <= 0.0f || size <= 0.0f || alpha <= 0.0f) { +/* erf, to 5e-4 (Abramowitz & Stegun 7.1.27). */ +static inline float erf_approx(float x) +{ + const float s = x < 0.0f ? -1.0f : 1.0f, a = fabsf(x); + float t = 1.0f + (0.278393f + (0.230389f + 0.078108f * (a * a)) * a) * a; + t *= t; + return s - s / (t * t); +} + +/* A rounded box (half size hw, hh, corner `corner`) blurred by a Gaussian of `sigma`, at (px, py) + * from its centre: exact along x (erf), four samples along y (Evan Wallace, "Fast Rounded Rectangle + * Shadows"). Kept in step with shadow_gauss in bui_ui.hlsl and gpu_gl.c. */ +static float shadow_gauss(float px, float py, float hw, float hh, float corner, float sigma) +{ + const float low = py - hh, high = py + hh; + const float start = clampf(-3.0f * sigma, low, high), end = clampf(3.0f * sigma, low, high); + const float dy = (end - start) * 0.25f, k = 0.70710678f / sigma; + const float norm = dy / (2.50662827f * sigma); + float y = start + dy * 0.5f, v = 0.0f; + for (int i = 0; i < 4; i++, y += dy) { + const float delta = fminf(hh - corner - fabsf(py - y), 0.0f); + const float curved = hw - corner + sqrtf(fmaxf(0.0f, corner * corner - delta * delta)); + const float along = 0.5f * (erf_approx((px + curved) * k) - erf_approx((px - curved) * k)); + v += along * expf(-(y * y) / (2.0f * sigma * sigma)) * norm; + } + return v; +} + +/* A shadow: the rounded box `shape` (x, y, w, h; corner `rad`) faded out, in `rgba` times `gain` + * (saturating), drawn only outside the rounded box `box` (corner `brad`), which covers it. + * `gauss` 0: a menu's, fading over `size` pixels (smoothstep); 1: CSS `box-shadow`'s, the shape + * blurred by a Gaussian of sigma `size` (under a quarter pixel: a hard, antialiased edge). The + * GPU draws it in BG_SHADOW (bui_ui.hlsl). */ +SHAPE_INLINE void shadow_keep(BuiRaster *r, const float shape[4], float rad, const float box[4], float brad, + float size, int gauss, const float rgba[4], float gain, const int keep) +{ + const float x = shape[0], y = shape[1], w = shape[2], h = shape[3]; + if (w <= 0.0f || h <= 0.0f || rgba[3] <= 0.0f || gain <= 0.0f || (!gauss && size <= 0.0f)) { return; } + const float reach = (gauss ? 3.0f * size : size) + 1.0f; int x0, y0, x1, y1; - if (!clip_box(r, x - size, y - size * 0.5f, x + w + size, y + h + size * 1.5f, &x0, &y0, &x1, - &y1)) - { + if (!clip_box(r, x - reach, y - reach, x + w + reach, y + h + reach, &x0, &y0, &x1, &y1)) { return; } - const float hw = w * 0.5f, hh = h * 0.5f; - const float rad = clampf(radius, 0.0f, fminf(hw, hh)); + const float hw = w * 0.5f, hh = h * 0.5f, cx = x + hw, cy = y + hh; + rad = clampf(rad, 0.0f, fminf(hw, hh)); + const float bhw = fmaxf(box[2], 0.0f) * 0.5f, bhh = fmaxf(box[3], 0.0f) * 0.5f; + const float bcx = box[0] + bhw, bcy = box[1] + bhh; + brad = clampf(brad, 0.0f, fminf(bhw, bhh)); if (r->gpu) { BuiGpuInst *in = gpu_inst(r, BG_SHADOW, x0, y0, x1, y1); if (in) { v4(in->rect, x, y, w, h); - v4(in->p, BG_SHADOW, rad, size, alpha); + v4(in->p, BG_SHADOW, rad, size, gain); + c4(in->c0, rgba); + v4(in->c1, box[0], box[1], box[2], box[3]); + v4(in->uv, brad, (float)gauss, 0.0f, 0.0f); } return; } - /* Light comes from above: the shadow sits slightly lower. */ - const float cx = x + hw, cy = y + hh + size * 0.25f; - const Paint black = {0x000000u, 256}; + const Paint p = paint_from(KEEP_ALPHA(keep), rgba); + const int hard = gauss && size < 0.25f; for (int py = y0; py < y1; py++) { uint32_t *row = r->pix + (size_t)py * r->w; const float sy = (float)py + 0.5f; for (int px = x0; px < x1; px++) { const float sx = (float)px + 0.5f; - const float d = sd_widget_box(sx, sy, cx, cy, hw, hh, rad, BUI_CORNER_ALL); - /* Only outside the box itself (the popup covers the inside). */ - const float dbox = sd_widget_box(sx, sy, x + hw, y + hh, hw, hh, rad, BUI_CORNER_ALL); - if (dbox <= -0.5f || d >= size) { + /* only outside the box (it covers the inside) */ + const float dbox = sd_widget_box(sx, sy, bcx, bcy, bhw, bhh, brad, BUI_CORNER_ALL); + if (dbox <= -0.5f) { continue; } - float t = 1.0f - clampf(d / size, 0.0f, 1.0f); - t = t * t * (3.0f - 2.0f * t); /* smoothstep falloff */ - put_cov(row + px, black, t * alpha * clampf(0.5f + dbox, 0.0f, 1.0f), keep); + float t; + if (hard) { + t = clampf(0.5f - sd_widget_box(sx, sy, cx, cy, hw, hh, rad, BUI_CORNER_ALL), 0.0f, 1.0f); + } + else if (gauss) { + t = shadow_gauss(sx - cx, sy - cy, hw, hh, rad, size); + } + else { + const float d = sd_widget_box(sx, sy, cx, cy, hw, hh, rad, BUI_CORNER_ALL); + if (d >= size) { + continue; + } + t = 1.0f - clampf(d / size, 0.0f, 1.0f); + t = t * t * (3.0f - 2.0f * t); /* smoothstep falloff */ + } + put_cov(row + px, p, t * gain * clampf(0.5f + dbox, 0.0f, 1.0f), keep); } } } @@ -1853,7 +1903,19 @@ SHAPE_INLINE void shadow_keep( void BUI_raster_shadow( BuiRaster *r, float x, float y, float w, float h, float radius, float size, float alpha) { - BY_ALPHA(r, shadow_keep, r, x, y, w, h, radius, size, alpha); + if (size <= 0.0f || alpha <= 0.0f) { + return; + } + /* light comes from above: the shadow sits slightly lower than the box */ + const float shape[4] = {x, y + size * 0.25f, w, h}, box[4] = {x, y, w, h}; + const float black[4] = {0.0f, 0.0f, 0.0f, 1.0f}; + BY_ALPHA(r, shadow_keep, r, shape, radius, box, radius, size, 0, black, alpha); +} + +void BUI_raster_box_shadow(BuiRaster *r, const float shape[4], float radius, float sigma, const float rgba[4], + const float box[4], float box_radius) +{ + BY_ALPHA(r, shadow_keep, r, shape, radius, box, box_radius, fmaxf(sigma, 0.0f), 1, rgba, 1.0f); } #define POLY_SUBSAMPLES 4 diff --git a/gpu/shaders/bui_ui.hlsl b/gpu/shaders/bui_ui.hlsl index b6966566..997f60d8 100644 --- a/gpu/shaders/bui_ui.hlsl +++ b/gpu/shaders/bui_ui.hlsl @@ -92,6 +92,34 @@ float sd_box(float2 s, float2 c, float2 hb, float rad, uint corners) return length(q) - r; } +// erf, to 5e-4 (Abramowitz & Stegun 7.1.27). +float2 erf2(float2 x) +{ + const float2 sg = sign(x), a = abs(x); + float2 t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; + t *= t; + return sg - sg / (t * t); +} + +// A rounded box (half size hb, corner `corner`) blurred by a Gaussian of `sigma`, at p from its +// centre: exact along x, four samples along y (Evan Wallace). gpu_raster.c shadow_gauss. +float shadow_gauss(float2 p, float2 hb, float corner, float sigma) +{ + const float lo = p.y - hb.y, hi = p.y + hb.y; + const float start = clamp(-3.0 * sigma, lo, hi), end = clamp(3.0 * sigma, lo, hi); + const float dy = (end - start) * 0.25, k = 0.70710678 / sigma; + const float norm = dy / (2.50662827 * sigma); + float y = start + dy * 0.5, v = 0.0; + [unroll] for (int i = 0; i < 4; i++) { + const float delta = min(hb.y - corner - abs(p.y - y), 0.0); + const float curved = hb.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); + const float2 e = erf2((p.x + float2(curved, -curved)) * k); + v += 0.5 * (e.x - e.y) * exp(-(y * y) / (2.0 * sigma * sigma)) * norm; + y += dy; + } + return v; +} + // Source-over of a straight color into a premultiplied accumulator. void over(inout float4 acc, float4 c, float cov) { @@ -356,17 +384,32 @@ float4 ps_quad(VOut v) : SV_Target return lerp(top, bot, f.y) * v.p.y; } if (kind == K_SHADOW) { - const float rad = v.p.y, size = v.p.z, alpha = v.p.w; + // gpu_raster.c shadow_keep: the shape R (corner p.y) faded out (uv.y 0: a menu's smoothstep over + // p.z; 1: a Gaussian of sigma p.z), in c0 times p.w, only outside the box c1 (corner uv.x) + const float rad = v.p.y, size = v.p.z, gain = v.p.w; const float2 hb = R.zw * 0.5; const float2 c = R.xy + hb; - const float d = sd_box(s, c + float2(0.0, size * 0.25), hb, rad, 15u); - const float dbox = sd_box(s, c, hb, rad, 15u); - if (dbox <= -0.5 || d >= size) { + const float2 bhb = v.c1.zw * 0.5; + const float dbox = sd_box(s, v.c1.xy + bhb, bhb, v.uv.x, 15u); + if (dbox <= -0.5) { return 0.0; } - float t = 1.0 - saturate(d / size); - t = t * t * (3.0 - 2.0 * t); - return float4(0.0, 0.0, 0.0, saturate(t * alpha * saturate(0.5 + dbox))); + float t; + if (v.uv.y < 0.5) { + const float d = sd_box(s, c, hb, rad, 15u); + if (d >= size) { + return 0.0; + } + t = 1.0 - saturate(d / size); + t = t * t * (3.0 - 2.0 * t); + } + else if (size < 0.25) { + t = saturate(0.5 - sd_box(s, c, hb, rad, 15u)); + } + else { + t = shadow_gauss(s - c, hb, rad, size); + } + return premul(v.c0, t * gain * saturate(0.5 + dbox)); } if (kind == K_GRADIENT) { const float2 uv = saturate((s - R.xy) / R.zw); diff --git a/gpu/tests/test_gpu_effect.c b/gpu/tests/test_gpu_effect.c index bfa5ce60..3c8d043e 100644 --- a/gpu/tests/test_gpu_effect.c +++ b/gpu/tests/test_gpu_effect.c @@ -34,7 +34,8 @@ static const char *k_gradient = " return vec4(mix(vec3(uv.x, uv.y, U[0]), t.rgb, U[1]), 1.0);\n" "}\n"; -/* the dialect's constructs: splat constructors, casts, loops, mod, fract, atan2, inversesqrt */ +/* the dialect's constructs: splat constructors, casts, loops, mod, fract, atan2, atan(y, x), + * inversesqrt, integer bit operations, a name HLSL reserves (`line`) */ static const char *k_dialect = "vec4 effect(vec2 p) {\n" " float s = 0.0;\n" @@ -42,6 +43,9 @@ static const char *k_dialect = " float a = float(int(2.7));\n" /* 2 */ " vec3 c = vec3(0.25) + vec3(a * 0.125, s * 0.25, mod(7.5, 2.0) / 3.0 - 0.25);\n" " c.z += atan2(1.0, 1.0) * 0.0 + inversesqrt(4.0) * 0.0 + fract(3.25) * 0.0;\n" + " float line = atan(1.0, 1.0) * 0.0;\n" /* GLSL's atan(y, x); a word HLSL keeps */ + " int bits = (13 >> 2) & 1;\n" /* 1 */ + " c.z += line + float(bits - 1);\n" " return vec4(c, 1.0);\n" /* (.5, .5, .5) */ "}\n"; diff --git a/gpu/tests/test_gpu_parity.c b/gpu/tests/test_gpu_parity.c index 20119454..9593bc9a 100644 --- a/gpu/tests/test_gpu_parity.c +++ b/gpu/tests/test_gpu_parity.c @@ -143,6 +143,14 @@ static void scene(BuiRaster *r, int pass) BUI_raster_hsv_circle(r, 320, 210, 30, 0.9f); const float light[3] = {-0.5f, 0.6f, 0.8f}, sph[4] = {0.6f, 0.4f, 0.2f, 1}; BUI_raster_sphere(r, 400, 210, 30, light, sph); + /* CSS box shadows: blurred and moved, a hard ring round an empty box, a blur wider than its box */ + const float sh_c[4] = {0.1f, 0.1f, 0.4f, 0.6f}, ring_c[4] = {0.9f, 0.2f, 0.2f, 1}; + const float sh_box[4] = {40, 380, 70, 40}, sh_shape[4] = {44, 390, 70, 40}; + BUI_raster_box_shadow(r, sh_shape, 10, 8, sh_c, sh_box, 10); + const float ring_box[4] = {150, 380, 40, 40}, ring_shape[4] = {146, 376, 48, 48}; + BUI_raster_box_shadow(r, ring_shape, 24, 0, ring_c, ring_box, 20); + const float dot_box[4] = {240, 395, 6, 6}, dot_shape[4] = {240, 399, 6, 6}; + BUI_raster_box_shadow(r, dot_shape, 3, 12, sh_c, dot_box, 3); uint32_t img[16 * 12]; for (int i = 0; i < 16 * 12; i++) { img[i] = ((i % 16 + i / 16) & 1) ? 0xFFFF8000u : 0x80202080u; diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h index b71ab8e1..cd71ba29 100644 --- a/kit/include/BUI_kit.h +++ b/kit/include/BUI_kit.h @@ -656,7 +656,11 @@ void BK_image_exit(void); /* joins the workers, frees the cache */ /* -- canvas (Tk Canvas, QPainter)-------------------------------------------------- */ enum { BK_ITEM_RECT, BK_ITEM_OVAL, BK_ITEM_LINE, BK_ITEM_POLYGON, BK_ITEM_TEXT, BK_ITEM_ARC, - BK_ITEM_IMAGE, BK_ITEM_ROUNDRECT, BK_ITEM_EFFECT, BK_ITEM_PASS }; + BK_ITEM_IMAGE, BK_ITEM_ROUNDRECT, BK_ITEM_EFFECT, BK_ITEM_PASS, BK_ITEM_SHADOW }; +/* BK_ITEM_SHADOW: CSS `box-shadow` (an outer one). 8 coords: the shadow's box x0 y0 x1 y1 (offset + * and spread already applied), then the box that casts it, x0 y0 x1 y1 (the shadow is drawn only + * outside it). `radius`: the shadow box's corner radius; `size`: the casting box's; `width`: the + * blur's Gaussian sigma (0: a hard edge); `fill`: the colour. */ typedef struct BKCanvasItem { int id, type; const float *coords; /* x0 y0 x1 y1 ... in canvas space */ diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index c4fd6ccc..55a5bf8f 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -3250,7 +3250,13 @@ static int in_BK_key(BKContext *ctx, const char *text, const char *keysym, int m snprintf(ctx->key_held, sizeof(ctx->key_held), "%s", e.keysym); ctx->interaction++; ctx->key_taken = 0; - for (BKNode *n = ctx->focus ? ctx->focus : ctx->hover; n; n = n->parent) { + /* from the hovered widget, or over none from what is under the pointer (Blender: the region + * under the cursor), also when a rebuild took the hovered widget away before a move */ + BKNode *start = ctx->hover; + if (!start && ctx->root && ctx->pointer_y >= ctx->header_h) { + start = deepest(ctx->root, ctx->pointer_x, ctx->pointer_y); + } + for (BKNode *n = ctx->focus ? ctx->focus : start; n; n = n->parent) { if (n->flags & NF_EVENTS) { /* Tk/Qt key bindings see the key first */ bk_event(n, BK_EV_KEY, mods, &e); break; @@ -3289,10 +3295,6 @@ static int in_BK_key(BKContext *ctx, const char *text, const char *keysym, int m } /* bubble up to a handler: from the hovered widget, or over none from what is under the pointer * (Blender's region and area keymaps: Ctrl+Space anywhere in an editor) */ - BKNode *start = ctx->hover; - if (!start && ctx->root && ctx->pointer_y >= ctx->header_h) { - start = deepest(ctx->root, ctx->pointer_x, ctx->pointer_y); - } for (BKNode *n = start; n; n = n->parent) { if (!NODE_ENABLED(n)) { continue; diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.c index 00d7dea3..afd0c277 100644 --- a/kit/intern/kit_frame.c +++ b/kit/intern/kit_frame.c @@ -948,6 +948,9 @@ static bool citem_bbox_ex(const CItem *ci, float b[4], bool tight) /* a line has no area: a hit gets it at least a few pixels of thickness around it */ float m = tight ? (it->type == BK_ITEM_LINE ? BK_MAX(it->width * 0.5f, 3.0f) : 0.0f) : (it->width > 0 ? it->width : 1.0f) + 3.0f; + if (it->type == BK_ITEM_SHADOW && !tight) { + m = 3.0f * it->width + 2.0f; /* a Gaussian's reach (3 sigma) */ + } if (it->type == BK_ITEM_TEXT && tight) { if (!ci->text) { return false; @@ -1318,6 +1321,17 @@ static void canvas_item_draw(BuiRaster *r, const CItem *ci, float ox, float oy, } break; } + case BK_ITEM_SHADOW: { + if (it->ncoords < 8 || !fill) { + return; + } + const float shape[4] = {ox + BK_MIN(p[0], p[2]), oy + BK_MIN(p[1], p[3]), fabsf(p[2] - p[0]), + fabsf(p[3] - p[1])}; + const float box[4] = {ox + BK_MIN(p[4], p[6]), oy + BK_MIN(p[5], p[7]), fabsf(p[6] - p[4]), + fabsf(p[7] - p[5])}; + BUI_raster_box_shadow(r, shape, it->radius, it->width, it->fill, box, it->size); + break; + } case BK_ITEM_OVAL: { if (it->ncoords < 4) { return; @@ -1792,8 +1806,11 @@ int BK_canvas_rasterize(const BKCanvasItem *items, int n, float x0, float y0, in for (int i = 0; i < n; i++) { const BKCanvasItem *it = &ci[i].it; if (it->clip_on) { - BUI_raster_set_clip(r, (int)floorf(it->clip[0] - x0), (int)floorf(it->clip[1] - y0), - (int)ceilf(it->clip[2]), (int)ceilf(it->clip[3])); + const int cw = (int)ceilf(it->clip[2]), ch = (int)ceilf(it->clip[3]); + if (cw <= 0 || ch <= 0) { + continue; /* an empty clip shows nothing (set_clip would take it as none), as on screen */ + } + BUI_raster_set_clip(r, (int)floorf(it->clip[0] - x0), (int)floorf(it->clip[1] - y0), cw, ch); } canvas_item_draw(r, &ci[i], -x0, -y0, NULL); if (it->clip_on) { From af3c247e468df973de2242e03a1da3b9f26b922e Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:36:21 +0530 Subject: [PATCH 03/14] add demos --- demos/Cargo.toml | 2 +- demos/README.md | 64 +- demos/src/bin/aero.rs | 829 +++++++++++++ demos/src/bin/amp.rs | 823 +++++++++++++ demos/src/bin/ascii.rs | 381 ++++++ demos/src/bin/bui_calendar.rs | 1314 ++++++++++++++++++++ demos/src/bin/bui_chat.rs | 1271 +++++++++++++++++++ demos/src/bin/bui_files.rs | 1805 +++++++++++++++++++++++++++ demos/src/bin/bui_mail.rs | 1463 ++++++++++++++++++++++ demos/src/bin/bui_notes.rs | 1697 +++++++++++++++++++++++++ demos/src/bin/bui_sheet.rs | 2174 +++++++++++++++++++++++++++++++++ demos/src/bin/bui_timer.rs | 1326 ++++++++++++++++++++ demos/src/bin/bui_writer.rs | 1958 +++++++++++++++++++++++++++++ demos/src/bin/clock.rs | 637 ++++++++++ demos/src/bin/dream.rs | 751 ++++++++++++ demos/src/bin/failed.rs | 51 +- demos/src/bin/headphones.rs | 618 ++++++++++ demos/src/bin/hud.rs | 976 +++++++++++++++ demos/src/bin/intro.rs | 737 +++++++++++ demos/src/bin/morning.rs | 80 +- demos/src/bin/phantom.rs | 62 +- demos/src/bin/tasks.rs | 981 +++++++++++++++ demos/src/bin/velvet.rs | 63 +- demos/src/bin/y2k.rs | 706 +++++++++++ demos/src/canvas.rs | 12 + demos/src/color.rs | 14 + demos/src/control.rs | 113 ++ demos/src/ease.rs | 39 + demos/src/lib.rs | 81 +- demos/src/pen.rs | 73 ++ demos/src/story.rs | 102 ++ demos/src/text.rs | 35 + 32 files changed, 21048 insertions(+), 190 deletions(-) create mode 100644 demos/src/bin/aero.rs create mode 100644 demos/src/bin/amp.rs create mode 100644 demos/src/bin/ascii.rs create mode 100644 demos/src/bin/bui_calendar.rs create mode 100644 demos/src/bin/bui_chat.rs create mode 100644 demos/src/bin/bui_files.rs create mode 100644 demos/src/bin/bui_mail.rs create mode 100644 demos/src/bin/bui_notes.rs create mode 100644 demos/src/bin/bui_sheet.rs create mode 100644 demos/src/bin/bui_timer.rs create mode 100644 demos/src/bin/bui_writer.rs create mode 100644 demos/src/bin/clock.rs create mode 100644 demos/src/bin/dream.rs create mode 100644 demos/src/bin/headphones.rs create mode 100644 demos/src/bin/hud.rs create mode 100644 demos/src/bin/intro.rs create mode 100644 demos/src/bin/tasks.rs create mode 100644 demos/src/bin/y2k.rs create mode 100644 demos/src/color.rs create mode 100644 demos/src/control.rs create mode 100644 demos/src/ease.rs create mode 100644 demos/src/pen.rs create mode 100644 demos/src/story.rs create mode 100644 demos/src/text.rs diff --git a/demos/Cargo.toml b/demos/Cargo.toml index ee1bb930..b7687d9f 100644 --- a/demos/Cargo.toml +++ b/demos/Cargo.toml @@ -3,7 +3,7 @@ name = "bui-demos" version = "0.0.0" edition = "2024" publish = false -description = "Small demos built on BUI: shader components, glass UI, a Blender-style CI pipeline and a motion editor." +description = "Demos built on BUI: shader components, glass and skeuomorphic apps, menus, players and portfolio motion." # Standalone: not a member of bindings/rust's workspace, so the main tree is untouched. [workspace] diff --git a/demos/README.md b/demos/README.md index 679314a5..70ac5056 100644 --- a/demos/README.md +++ b/demos/README.md @@ -14,8 +14,70 @@ cargo workspace, so it never touches `bindings/rust`'s build. | Velvet Menu | `cargo run --release --bin velvet` | a Persona-style main menu for a tech app: an underwater shader, a tilted heavy-italic menu where the selection snaps forward on a red slash (hover or ↑/↓), Enter / click opens a sub-menu that follows the arrows, C / Esc closes. Laid out in `rem` on a 1280 x 720 canvas sized to the window, so it stays sharp. `-- --storyboard DIR` drives it headlessly | | Phantom | `cargo run --release --bin phantom` | a Persona 5-style menu for the same app: a shader scene (red room, spinning starburst, star, ink slash) under ransom-note type, every letter its own font, tilt and box; the selection's letters pop onto coloured blocks, Enter slams in the sub-menu card | | Morning | `cargo run --release --bin morning` | a pinch folds a full-screen page into its card in a stack (cloned from `ref/testanim.mp4`): the page washes out, shrinks onto its card and goes dark while the stack zooms up behind it, its three cards fanning in. Pinch on a trackpad or touch screen to scrub it (letting go finishes the way you were going); Space folds, Escape opens, a click does either | +| HUD Shell | `cargo run --release --bin hud` | a heads-up-display desktop: a taskbar whose slots launch, focus and minimise apps; a launcher, right-click choice lists, slide-in notifications, typed status lines, bio-monitor bars, and a GPU minimap radar in the clock box over a scanline shader that tears on every launch. Keys: S, 1-7, Tab, X, W, N, Esc | +| Breeze | `cargo run --release --bin aero` | a Frutiger Aero music app: a shader sky (clouds, sun flare, droplets, swaying grass) under CSS glass panels, and it plays: click a track, drag the scrubber and the volume fader, like, shuffle, skip; play / pause cross-fade (scale + blur); shader cover art. Space, ← / →, ↑ / ↓, N / P | +| Lagoon | `cargo run --release --bin amp` | a skinned 2000s MP3 player in three docked windows: a `Painter` spectrum analyzer (click: oscilloscope) that follows the EQ, a stepped marquee, ten draggable EQ bands with a live curve and presets that slide in, a playlist (select, double-click, add / remove / shuffle / sort); EQ and PL fold their windows | +| Dayline | `cargo run --release --bin tasks` | a dark desktop planner with a white task sheet: checking draws the tick, strikes the title and folds the row out (Undo toast), groups fold under their chevrons, the selection pill glides, the detail pane staggers in with a streak, a progress ring and subtasks you type in place; search filters as you type, list or board. ↑ / ↓, Space, Enter, Esc, Ctrl K | +| Clock | `cargo run --release --bin clock` | a soft-UI clock app on two phones in two looks that cross-fade (CSS-variable shadows, painted hands and arcs): a live analog face, alarm switches that spring across, a stopwatch whose 60-tick ring fills with laps dropping in, and a glossy timer knob you drag or scroll whose glowing arc drains as it counts down. The gear or T switches the look | +| Headphones | `cargo run --release --bin headphones` | a split light / dark Bluetooth headphone controller: the control surface is laid out twice and clipped either side of a seam you can drag through it. Draggable / scrollable LEFT / RIGHT knobs (LINK keeps their offset), GAIN / MIX faders, a LPASS / HPASS pair, ANC / AMBIENT, SPATIAL, SYNC, presets that glide every value, power, a live stereo meter | +| Orbit Messenger | `cargo run --release --bin y2k` | a Y2K chat client over a liquid-chrome metaball shader (iridescent film, one blob follows the pointer): aqua glass panels, orb avatars, sliding pill tabs; send with Enter for a starburst and a typed reply, BUZZ! shakes the window, discs download in Files, and a mood fader retints the whole chrome world | +| Dreamlog | `cargo run --release --bin dream` | a Dreamcore dream journal over one GPU shader (a pastel field with a rainbow and a checkerboard floor, endless pool rooms, a night field) through a worn VHS tape: eyes in the clouds follow the pointer, a dream-depth dial makes it stranger, the door crosses into the next place through a bloom, and waking up never works. ↑ / ↓, D, W, Space | +| Intro | `cargo run --release --bin intro` | a portfolio that opens as a terminal on a liquid-metal shader frame (it types its command; Return runs it, Esc skips) and hands over to the hero, stat counters counting up; then a page that scrolls with inertia (wheel, keys, drag-fling) into a glass carousel that springs between products: drag / swipe, ← / →, Shift + wheel, buttons, auto-advance every 3.5 s unless hovered | +| ASCII Field | `cargo run --release --bin ascii` | a dark portfolio over one GPU shader: a drifting FBM scene drawn as 5 × 5 bitmap glyphs per cell, lit into code by a halo round the pointer that eases in and out; cards with a pointer-following glow that lift, and a `Painter` glyph field that morphs and brightens near the pointer | -`src/menu.rs` (the commands and the selection state) and `src/canvas.rs` (a design canvas that fits the window crisply) are shared by the two menus. `src/lib.rs` is shared by all of them: the window, the shader + software fallback (`Fx`, with an optional pre-pass into a render target), the clock, `--screenshot out.png` (off-screen, software), scripted headless runs and GPU stills. +## Blender UI apps + +Everyday apps built only from what Blender's interface has, for Blender users who want to know what it can do outside Blender: Blender's screen of areas (split, join, maximize them, each with its editor-type menu, header, toolbar, sidebar and footer), Blender's own widgets (number fields you drag or type math into, sliders, menus, the colour picker, checkboxes, radios, text fields), panels and Blender's theme. Everything in them works. + +| App | Run | What it shows | +|---|---|---| +| BUI Mail | `cargo run --release --bin bui_mail` | an email client: folders, list and reader as areas you split / maximize; search that filters as you type; account and sort menus; a checkbox per row with Shift / Ctrl ranges; drag a message onto a folder; conversations as panels; label colours from Blender's colour picker; rules with number fields; reply / forward with a signature menu and uploading attachments; a send you can undo; every action undoable. J / K, E, R, S, Ctrl+Z | +| BUI Chat | `cargo run --release --bin bui_chat` | a community chat: the server rail is a toolbar region, threads open in the sidebar region, split chat areas each keep their own channel; reactions, replies, threads, a composer answered by invented members, a live member filter; a voice channel with `Painter` level meters and a volume slider each; settings (status menu, name colour, accent radios, a UI-scale slider) that apply at once | +| BUI Files | `cargo run --release --bin bui_files` | a file explorer on the real file system, read-only: places and a folder tree, list or thumbnail grid (real PNG thumbnails), image and text preview, sort and live filter, box select, type-ahead; rename, new folder, copy with progress, drag-move, delete and undo, all inside a sandbox in the temp folder; Blender's own File Browser one click away | +| BUI Timer | `cargo run --release --bin bui_timer` | clocks: world clock faces, alarms (number fields you scrub to set the time), several timers with rings, stopwatch laps with best / worst, Pomodoro with a focus mode that maximizes its area, workspaces that remember their layout, an accent colour that recolours Blender's widgets, chimes, tray and taskbar progress | +| BUI Notes | `cargo run --release --bin bui_notes` | a block wiki: a page tree you drag to reorder and nest, a slash menu, Markdown shortcuts, to-dos, toggles, lists, quotes, callouts and code; a task database as a table (status menus, hour fields) and a kanban board you drag cards across; search; two pages side by side; undo / redo | +| BUI Writer | `cargo run --release --bin bui_writer` | a word processor: a ribbon of Blender widgets (style and font menus, size field, colour pickers, B / I / U), A4 pages with a ruler you drag and real pagination, rich text with a caret and selection, tables, lists, find & replace, spelling, comments, a navigator of headings, zoom, Markdown export | +| BUI Sheet | `cargo run --release --bin bui_sheet` | a spreadsheet: a formula engine (cell and range refs across sheets, `SUM AVERAGE MIN MAX COUNT IF ROUND` ..., cycle and error detection), number formats, fill handle, copy / paste shifting refs, column resize and sort, sheet tabs, a live chart area of the selection, undo / redo; only the visible cells are built | +| BUI Calendar | `cargo run --release --bin bui_calendar` | a calendar: day, week, month and agenda views; drag on empty time to create, drag to move, drag the edge to resize; overlapping events in columns; weekly repeats, all-day events, time zones, calendars you show and colour; an event editor of Blender fields (length takes math); a now line; undo / redo | + +Every app takes `-- --storyboard DIR`, which drives all of it headlessly and saves frames. + +### What Blender's UI can and can't do (from Rust, today) + +What building these found. "With a workaround" says how the apps do it. + +| | | +|---|---| +| **As it is** | Blender's areas: split, join, dock, maximize, the editor-type menu, header / toolbar / sidebar / footer regions, saved layouts (workspaces) | +| | Blender's widgets with Blender's behaviour: drag a number to change it, double-click to type (math such as `25*60` works), Ctrl+Z, Esc; sliders, menus, the colour picker, checkboxes, radios, progress bars; `.precision(n)` for the decimals shown | +| | Text fields that report every keystroke (`attr("live", "")`, as Blender's search fields) or the confirmed edit | +| | Keyboard shortcuts: `window.text_field_focused()` keeps single-key shortcuts quiet while the user types; `cx.prevent_default()` takes a key from Blender's own handling (its Ctrl+Z widget undo, a hovered widget's keys) | +| | Panels (`details` / `summary`), Blender's theme and theme colours, `Painter` drawing, GPU shaders, CSS layout, effects and animation, springs | +| | Desktop: notifications, a tray icon, taskbar progress, Blender's File Browser | +| **With a workaround** | Drag and drop between elements: an element's position is known while rendering, so the apps keep the drop targets from the last render | +| | Rich text: Blender's text fields hold plain text; the writer keeps its own text model and draws styled runs | +| | Clearing a field after a send: a value is pushed only when it changes, so the field gets a new id | +| | Long lists and grids: build the visible rows only (the `blenderui-vlist` / `blenderui-table` crates do this) | +| | Toggle buttons: Blender's `Button` has no pressed state, so toggles are styled boxes | +| | Tall headers or footers: Blender's header regions keep Blender's height; taller content goes in the main view | +| **Not possible yet** | Popup and context menus other than a `Dropdown`, and hover tooltips | +| | Anything drawn over a Blender widget: widgets are always on top, so a dialog can't cover a field | +| | The node editor | +| | Starting a text edit from code, and text layout queries (the caret by line) | +| | Blender's widgets follow Blender's UI scale, not CSS sizes | + +Shared by the demos (`src/`): + +- `lib.rs`: the window, the shader + software fallback (`Fx`, with an optional pre-pass into a render target), the clock (`now`, virtual in a headless run so storyboards are deterministic), `--screenshot out.png` (off-screen, software), `--size WxH`, scripted headless runs and GPU stills. +- `story.rs`: `--storyboard DIR` runs, which click, type, hover and press keys through a demo and save frames along the virtual clock. +- `canvas.rs`: a design canvas that fits the window crisply (layout in `rem`), and placing on it. +- `control.rs`: knobs, faders and scrubbers (`Dial`, `draggable`: drag with pointer capture, or the wheel), and dial arcs with a glow. +- `pen.rs`: a `Painter` that draws in a design box's own units (dials, icons), and colour mixing. +- `ease.rs`: the curves the hand-driven motion is made of. `text.rs`: a typed-into text draft. `color.rs`: `#rrggbb` to and from numbers. +- `lib.rs` also has `act` (a listener from a view's weak handle, for a screen's editor factories) and `area_id` (element ids for an editor shown in two areas). +- `menu.rs`: the commands and the selection state of the two menus (Velvet, Phantom). + +Every demo with interaction takes `-- --storyboard DIR`, and every shader demo `-- --frames DIR` (GPU stills). Without a GPU, each shader draws its flat fallback colour. Build output goes to `demos/target/` (ignored). Delete it to reclaim the space. diff --git a/demos/src/bin/aero.rs b/demos/src/bin/aero.rs new file mode 100644 index 00000000..2d8f3f7c --- /dev/null +++ b/demos/src/bin/aero.rs @@ -0,0 +1,829 @@ +//! Breeze: a Frutiger Aero music player on BUI. A GPU shader paints the world behind the app: +//! a deep blue sky, drifting clouds, the sun with its rays and lens ghosts, droplets on the glass +//! and a meadow of grass blades swaying in the wind. Over it, glossy glass (CSS `backdrop-filter: +//! blur() saturate()`, rim light, a gloss band) holds a streaming app: a sidebar of playlists, an +//! album with shader cover art, a track list and a player bar. +//! +//! It plays: time runs, the now-playing row's equalizer bounces, the track ends into the next one. +//! Click a track to play it, the round buttons or Space to play / pause (the icons cross-fade: +//! scale .25 -> 1, blur 4px -> 0), drag or click the scrubber to seek and the fader for volume +//! (← / → seek, ↑ / ↓ volume, N / P skip), the ✓ to like. +//! +//! Motion: the panels rise in on first light (60 ms apart), the rows after them (40 ms apart); +//! hover and selection are 120-160 ms colour transitions, presses scale to 0.96. +//! +//! `cargo run --release --bin aero` +//! `-- --storyboard DIR` drives it headlessly and saves frames; `-- --frames DIR` renders the sky +//! and the cover art off-screen on the GPU. + +use std::sync::OnceLock; + +use blenderui::prelude::*; +use bui_demos::canvas::{rem, rem_css, Fit}; +use bui_demos::control::{draggable, Axis, Dial}; +use bui_demos::{arg, focus_root, gpu_stills, now, run_with, story::story, Fx, Script}; + +/// U[0] = time, U[1] = the music's energy (0 paused). +const SKY: &str = r" +float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } +float noise(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); + return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y); +} +float fbm(vec2 p) { + float v = 0.0; float a = 0.5; + for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } + return v; +} +// one layer of blades: n per screen height, tips no higher than `top`, swaying with the wind +float blades(vec2 q, float y, float n, float top, float seed, float t) { + float h = clamp(1.0 - y, 0.0, 1.0); + float wind = 0.5 + 0.5 * sin(t * 0.7 + q.x * 1.3 + seed); + float x = q.x * n + (0.6 * sin(t * 1.6 + q.x * 2.7 + seed) * wind + 0.4) * h * n * 0.09; + float id = floor(x); float f = fract(x) - 0.5; + float r = hash(vec2(id, seed)); + float tip = top + 0.16 * r; + float lean = (r - 0.5) * 1.6 * (y - tip) / max(1.0 - tip, 0.01); + float w = 0.46 * smoothstep(tip, 1.05, y); + return step(tip, y) * smoothstep(w, w * 0.55, abs(f - lean * 0.5)); +} +vec4 effect(vec2 p) { + float t = U[0]; float beat = U[1]; + vec2 uv = p / box_size; float a = box_size.x / box_size.y; + vec2 q = vec2(uv.x * a, uv.y); + // sky: deep blue up top, pale at the horizon + vec3 c = mix(vec3(0.07, 0.36, 0.86), vec3(0.55, 0.83, 1.0), smoothstep(0.0, 0.78, uv.y)); + // clouds, thinning towards the horizon + float cl = fbm(q * vec2(2.4, 5.0) + vec2(t * 0.018, 0.0)); + float cl2 = fbm(q * vec2(5.0, 9.0) + vec2(t * 0.03, 3.0)); + float cloud = smoothstep(0.52, 0.78, cl * 0.8 + cl2 * 0.3) * (1.0 - smoothstep(0.2, 0.68, uv.y)); + c = mix(c, vec3(0.97, 0.99, 1.0), cloud * 0.9); + // the sun, its rays and the lens ghosts running through the middle + vec2 sp = vec2(0.9 * a, 0.12); + vec2 dv = q - sp; float d = length(dv); + float ang = atan2(dv.y, dv.x); + c += vec3(1.0, 0.97, 0.86) * (0.018 / (d + 0.012)) * (1.0 + 0.25 * beat); + c += vec3(1.0, 0.95, 0.8) * pow(0.5 + 0.5 * sin(ang * 14.0 + t * 0.15), 10.0) * exp(-d * 2.6) * 0.35; + vec2 axis = vec2(0.5 * a, 0.5) - sp; + for (int k = 1; k < 4; k++) { + float fk = float(k); + vec2 g = sp + axis * (0.55 * fk); + float gr = 0.03 + 0.025 * fk; + float ring = smoothstep(gr, gr * 0.7, length(q - g)) * 0.06; + c += vec3(0.6, 0.9 - 0.1 * fk, 1.0) * ring; + } + // a meadow: the hill, then three layers of blades, far to near + float hill = 0.74 + 0.04 * sin(q.x * 2.1 + 0.4) + 0.025 * sin(q.x * 5.7 + 1.0); + float field = smoothstep(hill - 0.004, hill + 0.004, uv.y); + vec3 grass = mix(vec3(0.55, 0.86, 0.25), vec3(0.12, 0.45, 0.05), smoothstep(hill, 1.0, uv.y)); + c = mix(c, grass, field); + float b1 = blades(q, uv.y, 70.0, hill - 0.05, 1.0, t); + c = mix(c, vec3(0.42, 0.78, 0.18) * (0.75 + 0.35 * uv.y), b1 * 0.9); + float b2 = blades(q, uv.y, 38.0, hill - 0.02, 2.0, t * 1.1); + c = mix(c, vec3(0.3, 0.68, 0.1) * (0.8 + 0.3 * (1.0 - uv.y)), b2); + float b3 = blades(q, uv.y, 17.0, 0.86, 3.0, t * 1.2); + c = mix(c, vec3(0.2, 0.55, 0.08) + 0.12 * vec3(0.6, 0.8, 0.2) * smoothstep(0.86, 0.95, uv.y), b3); + // droplets on the glass, upper right: dark rim, bright cap, a glint + vec2 gq = q * 11.0; + vec2 id = floor(gq); vec2 f = fract(gq) - 0.5; + float hd = hash(id + 7.0); + vec2 jit = (vec2(hash(id + 1.3), hash(id + 2.9)) - 0.5) * 0.5; + float rad = 0.12 + 0.22 * hash(id + 4.4); + float side = smoothstep(0.52, 0.8, uv.x) * (1.0 - smoothstep(0.55, 0.75, uv.y)); + if (hd > 0.7 && side > 0.0) { + float dd = length(f - jit); + float inside = smoothstep(rad, rad * 0.85, dd) * side; + float rim = smoothstep(rad * 0.6, rad, dd) * inside; + float glint = smoothstep(rad * 0.32, 0.0, length(f - jit + vec2(rad * 0.35, rad * 0.38))); + c = mix(c, c * 1.12 + 0.06, inside); + c -= rim * 0.1; + c += glint * inside * 0.9; + } + // bubbles drifting up from the meadow + vec2 bq = q * vec2(9.0, 6.0) + vec2(0.0, t * 0.12); + vec2 bid = floor(bq); vec2 bf = fract(bq) - 0.5; + float hb = hash(bid + 11.0); + if (hb > 0.88) { + float br = 0.12 + 0.12 * hash(bid + 5.0); + float bd = length(bf - (vec2(hash(bid), hash(bid + 3.0)) - 0.5) * 0.4); + float ring = smoothstep(br, br * 0.8, bd) - smoothstep(br * 0.8, br * 0.55, bd); + c += vec3(0.85, 0.95, 1.0) * ring * 0.35 * smoothstep(0.95, 0.4, uv.y); + } + c *= 1.0 - 0.18 * length(uv - vec2(0.5, 0.45)); + c += (hash(p + fract(t) * 13.0) - 0.5) * 0.015; + return vec4(clamp(c, 0.0, 1.0), 1.0); +} +"; + +/// U[0] = time, U[1] = hue turn, U[2] = playing (0 / 1). The album art: a glass orb over a +/// sunrise sea, its insides swirling while the album plays. Rounded corners are its own alpha. +const COVER: &str = r" +vec3 hue(float h) { return clamp(abs(fract(h + vec3(0.0, 0.66, 0.33)) * 6.0 - 3.0) - 1.0, 0.0, 1.0); } +vec4 effect(vec2 p) { + float t = U[0]; vec2 uv = p / box_size; + vec3 c = mix(vec3(1.0, 0.78, 0.55), vec3(0.2, 0.55, 0.95), smoothstep(0.1, 0.62, uv.y)); + c = mix(c, vec3(0.05, 0.3, 0.6) + 0.12 * sin(uv.x * 40.0 + t * 2.0 * U[2]) * smoothstep(0.62, 1.0, uv.y), + smoothstep(0.6, 0.64, uv.y)); + vec2 o = uv - vec2(0.5, 0.48); + float d = length(o); + float r = 0.3; + if (d < r) { + float a = atan2(o.y, o.x) + t * 0.6 * U[2]; + float sw = 0.5 + 0.5 * sin(a * 3.0 + d * 22.0 - t * 1.5 * U[2]); + vec3 inner = mix(hue(U[1] + d * 1.6 + 0.1 * sw), vec3(1.0), 0.25) * (0.75 + 0.35 * sw); + float edge = smoothstep(r * 0.65, r, d); + inner = mix(inner, vec3(0.75, 0.92, 1.0), edge * 0.6); + inner += smoothstep(0.1, 0.0, length(o - vec2(-0.1, -0.12))) * 0.9; + c = mix(c, inner, smoothstep(r, r - 0.006, d)); + } + c += vec3(1.0, 0.9, 0.7) * 0.12 * smoothstep(0.5, 0.0, length(uv - vec2(0.15, 0.1))); + // rounded corners (7% of the side) + vec2 hb = box_size * 0.5; float rr = box_size.x * 0.07; + vec2 qd = abs(p - hb) - hb + rr; + float sd = length(max(qd, 0.0)) + min(max(qd.x, qd.y), 0.0) - rr; + float alpha = clamp(0.5 - sd, 0.0, 1.0); + return vec4(c * alpha, alpha); +} +"; + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; background: #3d8ee6; user-select: none; + font-family: 'Segoe UI', Inter, system-ui, sans-serif; color: #fff; -webkit-font-smoothing: antialiased; } +.sky { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.app { position: absolute; width: 1200px; height: 776px; } +.txt { text-shadow: 0 1px 2px rgba(0,40,100,0.35); } + +/* glass: a translucent fill, frosted backdrop, a rim and a gloss band along the top */ +.glass { position: absolute; border-radius: 22px; + background: linear-gradient(180deg, rgba(255,255,255,0.26) 0%, rgba(255,255,255,0.08) 100%); + backdrop-filter: blur(20px) saturate(1.5); + box-shadow: 0 14px 40px rgba(8,50,120,0.28), 0 0 0 1px rgba(255,255,255,0.42), inset 0 1px 0 rgba(255,255,255,0.75); } +.gloss { position: absolute; left: 0; top: 0; width: 100%; height: 46%; border-radius: 22px 22px 0 0; + background: linear-gradient(180deg, rgba(255,255,255,0.28) 0%, rgba(255,255,255,0.0) 100%); } +.rise { animation: rise 520ms cubic-bezier(0.2, 0, 0, 1) backwards; } +@keyframes rise { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } } + +/* round glossy buttons */ +.btn { position: relative; display: flex; align-items: center; justify-content: center; cursor: pointer; + transition-property: transform, background-color; transition-duration: 140ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); } +.btn:active { transform: scale(0.96); } +.orb { border-radius: 50%; background: linear-gradient(180deg, rgba(255,255,255,0.55) 0%, rgba(255,255,255,0.18) 55%, rgba(255,255,255,0.3) 100%); + box-shadow: 0 4px 12px rgba(10,60,140,0.25), 0 0 0 1px rgba(255,255,255,0.6), inset 0 1px 0 #fff; } +.orb:hover { background-color: rgba(255,255,255,0.22); } +.go { border-radius: 50%; background: linear-gradient(180deg, #b8ff8a 0%, #4fd12f 48%, #2a9e18 52%, #4ec431 100%); + box-shadow: 0 6px 18px rgba(30,120,10,0.45), 0 0 0 1px rgba(255,255,255,0.7), inset 0 2px 1px rgba(255,255,255,0.8); } +.go:hover { background-color: #6fe04a; } +.pearl { border-radius: 50%; background: linear-gradient(180deg, #ffffff 0%, #e9f4ff 50%, #cfe3f7 52%, #f4f9ff 100%); + box-shadow: 0 4px 14px rgba(10,60,140,0.3), 0 0 0 1px rgba(255,255,255,0.9); } +.shine { position: absolute; left: 14%; top: 5%; width: 72%; height: 42%; border-radius: 50%; + background: linear-gradient(180deg, rgba(255,255,255,0.85) 0%, rgba(255,255,255,0.0) 100%); } +.ico { width: 20px; height: 20px; } +.swap { position: relative; width: 26px; height: 26px; } +.swap .ico { position: absolute; left: 0; top: 0; width: 26px; height: 26px; + transition-property: opacity, transform, filter; transition-duration: 220ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); } +.swap .off { opacity: 0; transform: scale(0.25); filter: blur(4px); } +.swap .on { opacity: 1; transform: scale(1); filter: blur(0px); } + +/* top bar */ +.logo { left: 18px; top: 14px; display: flex; align-items: center; gap: 10px; font-size: 22px; font-weight: 700; letter-spacing: -0.5px; } +.logo .mark { width: 34px; height: 34px; border-radius: 50%; position: relative; + background: linear-gradient(180deg, #a6ff7a 0%, #3cc522 55%, #1f8f12 100%); + box-shadow: 0 3px 10px rgba(20,110,10,0.45), 0 0 0 1px rgba(255,255,255,0.7); } +.search { left: 280px; top: 12px; width: 420px; height: 40px; border-radius: 20px; display: flex; align-items: center; gap: 10px; + padding: 0 16px; box-sizing: border-box; font-size: 14px; color: rgba(255,255,255,0.85); } +.pill { height: 40px; border-radius: 20px; display: flex; align-items: center; gap: 8px; padding: 0 16px; box-sizing: border-box; + font-size: 14px; font-weight: 600; } +.avatar { width: 30px; height: 30px; border-radius: 50%; background: linear-gradient(135deg, #ffd27a, #ff7aa8 55%, #7a8cff); + box-shadow: 0 0 0 1px rgba(255,255,255,0.8); } + +/* sidebar */ +.nav { margin: 10px; padding: 6px; border-radius: 16px; background: rgba(255,255,255,0.14); box-shadow: 0 0 0 1px rgba(255,255,255,0.3); } +.navi { display: flex; align-items: center; gap: 14px; height: 40px; padding: 0 12px; border-radius: 10px; font-size: 15px; font-weight: 600; cursor: pointer; + transition-property: background-color; transition-duration: 140ms; } +.navi:hover { background: rgba(255,255,255,0.16); } +.navi.sel { background: rgba(255,255,255,0.38); box-shadow: inset 0 1px 0 rgba(255,255,255,0.8); } +.plhead { display: flex; align-items: center; justify-content: space-between; padding: 8px 18px 6px; font-size: 13px; font-weight: 700; } +.plhead .tools { display: flex; gap: 6px; } +.pl { display: flex; align-items: center; gap: 12px; height: 56px; margin: 0 10px; padding: 0 8px; border-radius: 12px; cursor: pointer; + transition-property: background-color; transition-duration: 140ms; } +.pl:hover { background: rgba(255,255,255,0.16); } +.pl.sel { background: rgba(255,255,255,0.32); } +.pl .art { position: relative; width: 44px; height: 44px; border-radius: 8px; flex-shrink: 0; + box-shadow: 0 2px 6px rgba(0,40,100,0.25), 0 0 0 1px rgba(0,0,0,0.1); display: flex; align-items: center; justify-content: center; } +.pl .art .shine { left: 0; top: 0; width: 100%; height: 50%; border-radius: 8px 8px 0 0; background: linear-gradient(180deg, rgba(255,255,255,0.55), rgba(255,255,255,0)); } +.pl .name { font-size: 14px; font-weight: 600; } +.pl .meta { font-size: 11.5px; opacity: 0.8; margin-top: 1px; } + +/* album header */ +.cover { left: 24px; top: 24px; width: 176px; height: 176px; border-radius: 12px; + box-shadow: 0 12px 28px rgba(0,40,110,0.4), 0 0 0 1px rgba(0,0,0,0.1); } +.kind { left: 228px; top: 46px; font-size: 13px; font-weight: 600; } +.title { left: 224px; top: 62px; font-size: 64px; font-weight: 800; letter-spacing: -2px; line-height: 1.1; + text-shadow: 0 2px 12px rgba(0,40,100,0.35); } +.by { left: 228px; top: 146px; display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 700; } +.by .avatar { width: 24px; height: 24px; } +.meta2 { left: 228px; top: 178px; font-size: 13px; opacity: 0.9; } +.actions { left: 24px; top: 222px; display: flex; align-items: center; gap: 16px; } + +/* tracks */ +.thead { left: 16px; top: 296px; width: 872px; height: 30px; display: flex; align-items: center; font-size: 13px; font-weight: 600; opacity: 0.85; + border-bottom: 1px solid rgba(255,255,255,0.3); } +.list { left: 16px; top: 332px; width: 872px; height: 240px; overflow-y: auto; } +.row { display: flex; align-items: center; height: 46px; border-radius: 10px; cursor: pointer; font-size: 14px; + transition-property: background-color, box-shadow; transition-duration: 120ms; } +.row:hover { background: rgba(255,255,255,0.18); } +.row.on { background: rgba(255,255,255,0.3); box-shadow: inset 0 1px 0 rgba(255,255,255,0.7), 0 0 0 1px rgba(255,255,255,0.35); } +.c-n { width: 48px; text-align: center; font-variant-numeric: tabular-nums; opacity: 0.9; display: flex; justify-content: center; } +.c-t { flex: 1; } +.c-t .a { font-size: 12px; opacity: 0.8; margin-top: 1px; } +.c-p { width: 200px; font-variant-numeric: tabular-nums; opacity: 0.9; } +.c-l { width: 44px; display: flex; justify-content: center; } +.c-d { width: 60px; font-variant-numeric: tabular-nums; text-align: right; } +.c-m { width: 44px; display: flex; justify-content: center; opacity: 0; + transition-property: opacity; transition-duration: 120ms; } +.row:hover .c-m { opacity: 1; } +.eq { display: flex; align-items: flex-end; gap: 2px; height: 16px; } +.eq div { width: 3px; border-radius: 1.5px; background: #b9ff8f; } +.like { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; + border: 1.5px solid rgba(255,255,255,0.75); box-sizing: border-box; transition-property: transform; transition-duration: 120ms; } +.like:active { transform: scale(0.96); } +.like.yes { background: linear-gradient(180deg, #8af06a, #2fae1c); border-color: rgba(255,255,255,0.9); box-shadow: 0 1px 4px rgba(20,100,10,0.4); } +.pop { animation: pop 300ms cubic-bezier(0.2, 0, 0, 1); } +@keyframes pop { 0% { transform: scale(0.6); } 60% { transform: scale(1.15); } 100% { transform: scale(1); } } + +/* player bar */ +.now { left: 18px; top: 20px; display: flex; align-items: center; gap: 14px; } +.now .mini { width: 64px; height: 64px; border-radius: 10px; box-shadow: 0 6px 14px rgba(0,40,110,0.35), 0 0 0 1px rgba(0,0,0,0.1); } +.now .t { font-size: 15px; font-weight: 700; } +.now .a { font-size: 12.5px; opacity: 0.85; margin-top: 2px; } +.ctrl { left: 384px; top: 12px; width: 400px; display: flex; align-items: center; justify-content: center; gap: 22px; } +.tog { opacity: 0.75; transition-property: opacity; transition-duration: 140ms; } +.tog.lit { opacity: 1; } +.time { top: 70px; width: 44px; font-size: 12px; font-variant-numeric: tabular-nums; } +.bar { height: 24px; display: flex; align-items: center; cursor: pointer; } +.track { position: relative; width: 100%; height: 6px; border-radius: 3px; background: rgba(255,255,255,0.32); + box-shadow: inset 0 1px 2px rgba(0,40,100,0.3); } +.fill { position: absolute; left: 0; top: 0; height: 6px; border-radius: 3px; background: linear-gradient(180deg, #c6ff9e, #45c42a); } +.knob { position: absolute; top: -5px; width: 16px; height: 16px; margin-left: -8px; border-radius: 50%; + background: linear-gradient(180deg, #fff, #dbeaf7); box-shadow: 0 1px 4px rgba(0,40,100,0.4); + transform: scale(0.75); transition-property: transform; transition-duration: 140ms; } +.bar:hover .knob { transform: scale(1); } +.grab .knob { transform: scale(1.15); } +.right { left: 920px; top: 32px; display: flex; align-items: center; gap: 14px; } +/* last, so it wins over any class that positions relatively */ +.abs { position: absolute; } +"; + +/// Title, plays, length (seconds). +const TRACKS: [(&str, &str, u32); 8] = [ + ("Cloud Harbor", "21,734,620", 236), ("Dewfall", "12,664,330", 257), ("Sunlit Static", "8,725,384", 196), + ("Paper Planes", "11,264,330", 214), ("Greenhouse Heart", "9,345,124", 216), ("Bubble Tram", "6,102,775", 178), + ("Aquarium Sky", "4,918,203", 245), ("Fin", "3,377,941", 192), +]; +const ARTIST: &str = "Mira Solenne"; + +/// Name, meta, cover gradient. +const PLAYLISTS: [(&str, &str, &str); 7] = [ + ("Liked Songs", "Playlist · 1,338 songs", "linear-gradient(135deg, #5b4dff, #b9a9ff)"), + ("Morning Dew", "Playlist · Breeze", "linear-gradient(135deg, #ff9a8b, #ffd36e)"), + ("Chill Lagoon", "Playlist · oceanic", "linear-gradient(135deg, #00c6ff, #0062ff)"), + ("Run Club", "Playlist · oceanic", "linear-gradient(135deg, #3f9e1c, #b2ec6a)"), + ("2000s Gloss", "Playlist · Breeze", "linear-gradient(135deg, #ff6ec4, #7873f5)"), + ("Focus Garden", "Playlist · Breeze", "linear-gradient(135deg, #11998e, #38ef7d)"), + ("Summer Drive", "Playlist · oceanic", "linear-gradient(135deg, #f7971e, #ffd200)"), +]; + +const DESIGN: (f32, f32) = (1200.0, 776.0); +/// The player bar's corner, and the scrubber and the volume fader in it (x, y, width): a press +/// anywhere on one jumps there, so where they are is known up front. +const PLAYER: (f32, f32) = (16.0, 660.0); +const SCRUB: (f32, f32, f32) = (444.0, 66.0, 280.0); +const VOLUME: (f32, f32, f32) = (1036.0, 30.0, 110.0); + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +/// Icons, drawn with the painter on a 24-unit grid (one stroke weight: 1.8 units). +#[derive(Clone, Copy)] +enum Ico { + Home, + Search, + Library, + Plus, + Play, + Pause, + Prev, + Next, + Shuffle, + Repeat, + Heart, + Check, + Download, + More, + Back, + Forward, + Bell, + Volume, + Device, + Sparkle, + Chevron, + Clock, + Queue, +} + +fn ico(k: Ico, color: u32, size: f32) -> Div { + canvas(move |b, p| paint_ico(k, b, p, rgb(color))).class("ico").css("width", rem(size)).css("height", rem(size)) +} + +fn paint_ico(k: Ico, b: Bounds, p: &mut Painter, c: Rgba) { + let s = b.size.width.min(b.size.height) / 24.0; + let (ox, oy) = (b.origin.x + (b.size.width - 24.0 * s) / 2.0, b.origin.y + (b.size.height - 24.0 * s) / 2.0); + let at = |(x, y): (f32, f32)| (ox + x * s, oy + y * s); + let w = 1.8 * s; + let bx = |x: f32, y: f32, ww: f32, hh: f32| Bounds { origin: point(ox + x * s, oy + y * s), size: size(ww * s, hh * s) }; + macro_rules! line { + ($($pt:expr),+) => { p.line(&[$(at($pt)),+], c, w) }; + } + macro_rules! fill { + ($($pt:expr),+) => { p.polygon(&[$(at($pt)),+], c) }; + } + match k { + Ico::Home => { + line!((3.5, 11.0), (12.0, 3.8), (20.5, 11.0)); + line!((6.0, 9.5), (6.0, 20.0), (18.0, 20.0), (18.0, 9.5)); + } + Ico::Search => { + p.oval(bx(4.0, 4.0, 13.0, 13.0), Rgba::TRANSPARENT, c, w); + line!((15.0, 15.0), (20.5, 20.5)); + } + Ico::Library => { + line!((5.0, 4.0), (5.0, 20.0)); + line!((10.0, 4.0), (10.0, 20.0)); + line!((14.0, 5.0), (19.0, 19.5)); + } + Ico::Plus => { + line!((12.0, 5.0), (12.0, 19.0)); + line!((5.0, 12.0), (19.0, 12.0)); + } + // the triangle sits a unit right of the box centre: its visual centre is its centroid + Ico::Play => fill!((8.0, 4.5), (20.0, 12.0), (8.0, 19.5)), + Ico::Pause => { + p.quad(bx(6.0, 5.0, 4.2, 14.0), 1.2 * s, c, Rgba::TRANSPARENT, 0.0); + p.quad(bx(13.8, 5.0, 4.2, 14.0), 1.2 * s, c, Rgba::TRANSPARENT, 0.0); + } + Ico::Prev => { + fill!((19.0, 5.5), (8.5, 12.0), (19.0, 18.5)); + p.quad(bx(5.0, 5.5, 2.6, 13.0), 1.0 * s, c, Rgba::TRANSPARENT, 0.0); + } + Ico::Next => { + fill!((5.0, 5.5), (15.5, 12.0), (5.0, 18.5)); + p.quad(bx(16.4, 5.5, 2.6, 13.0), 1.0 * s, c, Rgba::TRANSPARENT, 0.0); + } + Ico::Shuffle => { + line!((3.5, 7.0), (8.0, 7.0), (15.0, 17.0), (19.0, 17.0)); + line!((3.5, 17.0), (8.0, 17.0), (15.0, 7.0), (19.0, 7.0)); + fill!((18.0, 4.0), (21.5, 7.0), (18.0, 10.0)); + fill!((18.0, 14.0), (21.5, 17.0), (18.0, 20.0)); + } + Ico::Repeat => { + line!((4.5, 13.0), (4.5, 8.0), (17.0, 8.0)); + line!((19.5, 11.0), (19.5, 16.0), (7.0, 16.0)); + fill!((16.0, 5.0), (19.5, 8.0), (16.0, 11.0)); + fill!((8.0, 13.0), (4.5, 16.0), (8.0, 19.0)); + } + Ico::Heart => { + let pts: [(f32, f32); 28] = std::array::from_fn(|i| { + let t = i as f32 / 28.0 * std::f32::consts::TAU; + let x = 16.0 * t.sin().powi(3); + let y = 13.0 * t.cos() - 5.0 * (2.0 * t).cos() - 2.0 * (3.0 * t).cos() - (4.0 * t).cos(); + at((12.0 + x * 0.5, 11.5 - y * 0.5)) + }); + p.polygon(&pts, c); + } + Ico::Check => line!((6.0, 12.5), (10.2, 16.5), (18.0, 7.5)), + Ico::Download => { + line!((12.0, 4.5), (12.0, 16.0)); + line!((7.0, 11.5), (12.0, 16.5), (17.0, 11.5)); + line!((5.0, 20.0), (19.0, 20.0)); + } + Ico::More => { + for x in [5.0, 12.0, 19.0] { + p.oval(bx(x - 1.7, 10.3, 3.4, 3.4), c, Rgba::TRANSPARENT, 0.0); + } + } + Ico::Back => line!((14.5, 5.5), (8.0, 12.0), (14.5, 18.5)), + Ico::Forward | Ico::Chevron => line!((9.5, 5.5), (16.0, 12.0), (9.5, 18.5)), + Ico::Bell => { + line!((5.0, 17.0), (6.5, 15.0), (6.5, 10.5), (8.0, 6.5), (12.0, 4.5), (16.0, 6.5), (17.5, 10.5), (17.5, 15.0), (19.0, 17.0), (5.0, 17.0)); + line!((10.0, 19.5), (14.0, 19.5)); + } + Ico::Volume => { + fill!((3.5, 9.0), (7.5, 9.0), (12.5, 4.8), (12.5, 19.2), (7.5, 15.0), (3.5, 15.0)); + line!((15.5, 9.0), (16.8, 12.0), (15.5, 15.0)); + line!((18.0, 6.0), (20.5, 12.0), (18.0, 18.0)); + } + Ico::Device => { + p.quad(bx(3.5, 5.0, 17.0, 11.5), 2.0 * s, Rgba::TRANSPARENT, c, w); + line!((8.0, 19.5), (16.0, 19.5)); + } + Ico::Sparkle => fill!((12.0, 3.0), (13.8, 10.2), (21.0, 12.0), (13.8, 13.8), (12.0, 21.0), (10.2, 13.8), (3.0, 12.0), (10.2, 10.2)), + Ico::Clock => { + p.oval(bx(3.5, 3.5, 17.0, 17.0), Rgba::TRANSPARENT, c, w); + line!((12.0, 7.0), (12.0, 12.0), (15.5, 14.0)); + } + Ico::Queue => { + line!((4.0, 6.0), (20.0, 6.0)); + line!((4.0, 12.0), (14.0, 12.0)); + line!((4.0, 18.0), (14.0, 18.0)); + fill!((16.5, 10.0), (21.0, 14.5), (16.5, 19.0)); + } + } +} + +/// A glossy round button: `class` picks the finish (`orb`, `go`, `pearl`). +fn round(id: &'static str, class: &str, d: f32, child: Div) -> Div { + div().id(id).class(format!("btn {class}")).css("width", rem(d)).css("height", rem(d)) + .child(div().class("shine")).child(child) +} + +/// Play and pause stacked; the one showing scales and un-blurs in as the other goes. +fn play_pause(playing: bool, color: u32, size: f32) -> Div { + let (a, b) = if playing { ("ico off", "ico on") } else { ("ico on", "ico off") }; + div().class("swap").css("width", rem(size)).css("height", rem(size)) + .child(ico(Ico::Play, color, size).class(a).css("position", "absolute")) + .child(ico(Ico::Pause, color, size).class(b).css("position", "absolute")) +} + +fn clock(secs: f32) -> String { + let s = secs.max(0.0) as u32; + format!("{}:{:02}", s / 60, s % 60) +} + +struct Aero { + sky: Fx, + cover: Fx, + playing: bool, + track: usize, + /// Seconds into the track. + pos: f32, + /// `now()` at the last frame. + last: f32, + seek: Dial, + volume: Dial, + liked: [bool; TRACKS.len()], + /// Likes so far: keys the pop, so it plays again. + likes: u32, + nav: usize, + playlist: usize, + shuffle: bool, + repeat: bool, + fit: Fit, + frames: u32, +} + +impl Aero { + const fn len(&self) -> f32 { + TRACKS[self.track].2 as f32 + } + + const fn play(&mut self, i: usize) { + if i == self.track { + self.playing = !self.playing; + } else { + self.track = i; + self.pos = 0.0; + self.playing = true; + } + } + + fn skip(&mut self, forward: bool) { + let n = TRACKS.len(); + // back within the first 3 s goes to the previous track, else to the start of this one + if !forward && self.pos > 3.0 { + self.pos = 0.0; + return; + } + let step = if self.shuffle { 3 } else { 1 }; + self.track = if forward { (self.track + step) % n } else { (self.track + n - step) % n }; + self.pos = 0.0; + } + + /// The time since the last frame: moves the playhead, the track ending into the next. + fn tick(&mut self) { + let t = now(); + let dt = (t - self.last).clamp(0.0, 0.25); + self.last = t; + if self.playing && !self.seek.dragging() { + self.pos += dt; + if self.pos >= self.len() { + if self.repeat { + self.pos = 0.0; + } else { + self.skip(true); + } + } + } + if !self.seek.dragging() { + self.seek.value = self.pos / self.len(); + } + } + + fn key(&mut self, key: &str) -> bool { + match key { + "space" => self.playing = !self.playing, + "Right" => self.pos = (self.pos + 5.0).min(self.len() - 0.1), + "Left" => self.pos = (self.pos - 5.0).max(0.0), + "Up" => return self.volume.set(self.volume.value + 0.05), + "Down" => return self.volume.set(self.volume.value - 0.05), + "n" | "N" => self.skip(true), + "p" | "P" => self.skip(false), + _ => return false, + } + true + } + + /// A window point in player-bar coordinates. + fn in_player(&self, p: Point) -> (f32, f32) { + let (x, y) = self.fit.design(p); + (x - PLAYER.0, y - PLAYER.1) + } + + fn top_bar() -> Div { + div().class("rise") + .child(div().class("abs logo txt").child(div().class("mark").child(div().class("shine"))).child("breeze")) + .child(round("back", "abs orb", 40.0, ico(Ico::Back, 0xffffff, 20.0)).css("left", rem(184.0)).css("top", rem(12.0))) + .child(round("fwd", "abs orb", 40.0, ico(Ico::Forward, 0xffffff, 20.0)).css("left", rem(230.0)).css("top", rem(12.0))) + .child(div().class("abs glass search").child(div().class("gloss")).child(ico(Ico::Search, 0xffffff, 18.0)) + .child(span().child("What do you want to play?"))) + .child(div().id("upgrade").class("abs glass pill btn").css("left", rem(760.0)).css("top", rem(12.0)) + .child(div().class("gloss")).child(ico(Ico::Sparkle, 0xfff3a8, 16.0)).child("Upgrade")) + .child(round("bell", "abs orb", 40.0, ico(Ico::Bell, 0xffffff, 18.0)).css("left", rem(898.0)).css("top", rem(12.0))) + .child(div().class("abs glass pill").css("left", rem(952.0)).css("top", rem(12.0)).css("width", rem(232.0)) + .child(div().class("gloss")).child(div().class("avatar")).child(div().css("flex", "1").child("oceanic")) + .child(ico(Ico::Chevron, 0xffffff, 14.0).css("transform", "rotate(90deg)"))) + } + + fn sidebar(&self, cx: &mut Context) -> Div { + let mut nav = div().class("nav"); + for (i, (name, icon)) in [("Home", Ico::Home), ("Search", Ico::Search), ("Your Library", Ico::Library)].into_iter().enumerate() { + nav = nav.child(div().id(format!("nav{i}")).class(if i == self.nav { "navi sel txt" } else { "navi txt" }) + .child(ico(icon, 0xffffff, 20.0)).child(name) + .on_click(cx.listener(move |this, _, _, cx| { + this.nav = i; + cx.notify(); + }))); + } + let mut side = div().class("glass rise").css("left", rem(16.0)).css("top", rem(64.0)).css("width", rem(252.0)) + .css("height", rem(584.0)).css("animation-delay", "60ms") + .child(div().class("gloss")).child(nav) + .child(div().class("plhead txt").child("Playlists") + .child(div().class("tools").child(ico(Ico::Plus, 0xffffff, 16.0)).child(ico(Ico::Chevron, 0xffffff, 16.0)))); + for (i, (name, meta, art)) in PLAYLISTS.iter().enumerate() { + let glyph = if i == 0 { ico(Ico::Heart, 0xffffff, 20.0) } else { div() }; + side = side.child(div().id(format!("pl{i}")).class(if i == self.playlist { "pl sel" } else { "pl" }) + .child(div().class("art").css("background", *art).child(div().class("shine")).child(glyph)) + .child(div().class("txt").child(div().class("name").child(*name)).child(div().class("meta").child(*meta))) + .on_click(cx.listener(move |this, _, _, cx| { + this.playlist = i; + cx.notify(); + }))); + } + side + } + + fn like(&self, i: usize, cx: &mut Context) -> Div { + let yes = self.liked[i]; + let mut d = div().id(format!("like{i}-{}", if yes { self.likes } else { 0 })) + .class(if yes { "like yes pop" } else { "like" }) + .child(ico(if yes { Ico::Check } else { Ico::Plus }, 0xffffff, 14.0)); + d = d.on_click(cx.listener(move |this, _, _, cx| { + this.liked[i] = !this.liked[i]; + this.likes += 1; + cx.stop_propagation(); + cx.notify(); + })); + d + } + + fn main_panel(&self, cx: &mut Context, t: f32) -> Div { + let playing = self.playing; + let cover = self.cover.canvas(move |_| [t, 0.55, if playing { 1.0 } else { 0.0 }]).class("abs cover"); + let total: u32 = TRACKS.iter().map(|t| t.2).sum(); + let big = round("play", "go", 60.0, play_pause(self.playing, 0xffffff, 26.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.playing = !this.playing; + cx.notify(); + })); + let mut list = div().class("abs list"); + for (i, (title, plays, secs)) in TRACKS.iter().enumerate() { + let on = i == self.track; + let n = if on { + // the equalizer: four bars, each on its own beat while it plays + let mut eq = div().class("eq"); + for k in 0..4 { + let f = k as f32; + let h = if self.playing { 0.25 + 0.75 * (t * (5.0 + f * 1.7) + f * 1.3).sin().abs() } else { 0.3 }; + eq = eq.child(div().css("height", rem(16.0 * h))); + } + eq + } else { + div().child(format!("{}", i + 1)) + }; + let row = div().id(format!("row{i}")).class(if on { "row on txt" } else { "row txt" }) + .child(div().class("c-n").child(n)) + .child(div().class("c-t").child(div().css("font-weight", "600").child(*title)).child(div().class("a").child(ARTIST))) + .child(div().class("c-p").child(*plays)) + .child(div().class("c-l").child(self.like(i, cx))) + .child(div().class("c-d").child(clock(*secs as f32))) + .child(div().class("c-m").child(ico(Ico::More, 0xffffff, 18.0))) + .on_click(cx.listener(move |this, _, _, cx| { + this.play(i); + cx.notify(); + })); + list = list.child(div().class("rise").css("animation-delay", format!("{}ms", 260 + i * 40)).child(row)); + } + div().class("glass rise").css("left", rem(280.0)).css("top", rem(64.0)).css("width", rem(904.0)).css("height", rem(584.0)) + .css("animation-delay", "120ms") + .child(div().class("gloss")).child(cover) + .child(div().class("abs kind txt").child("Album")) + .child(div().class("abs title").child("Glasswing")) + .child(div().class("abs by txt").child(div().class("avatar")).child(ARTIST)) + .child(div().class("abs meta2 txt").child(format!("2007 · {} songs, {} min {} sec", TRACKS.len(), total / 60, total % 60))) + .child(div().class("abs actions").child(big) + .child(round("add", "orb", 40.0, ico(Ico::Plus, 0xffffff, 20.0))) + .child(round("dl", "orb", 40.0, ico(Ico::Download, 0xffffff, 18.0))) + .child(round("more", "orb", 40.0, ico(Ico::More, 0xffffff, 18.0)))) + .child(div().class("abs thead txt").child(div().class("c-n").child("#")).child(div().class("c-t").child("Title")) + .child(div().class("c-p").child("Plays")).child(div().class("c-l")).child(div().class("c-d").child(ico(Ico::Clock, 0xffffff, 16.0).css("margin-left", "auto"))) + .child(div().class("c-m"))) + .child(list) + } + + fn player(&self, cx: &mut Context, t: f32) -> Div { + let playing = self.playing; + let mini = self.cover.canvas(move |_| [t, 0.55, if playing { 1.0 } else { 0.0 }]).class("mini"); + let scale = self.fit.scale; + let pp = round("pp", "pearl", 48.0, play_pause(self.playing, 0x1d4f8a, 22.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.playing = !this.playing; + cx.notify(); + })); + let tog = |id: &'static str, on: bool, k: Ico| div().id(id).class(if on { "btn tog lit" } else { "btn tog" }) + .css("width", rem(40.0)).css("height", rem(40.0)) + .child(ico(k, if on { 0xc6ff9e } else { 0xffffff }, 20.0)); + let ctrl = div().class("abs ctrl") + .child(tog("shuffle", self.shuffle, Ico::Shuffle).on_click(cx.listener(|this, _, _, cx| { + this.shuffle = !this.shuffle; + cx.notify(); + }))) + .child(div().id("prev").class("btn").css("width", rem(40.0)).css("height", rem(40.0)).child(ico(Ico::Prev, 0xffffff, 22.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.skip(false); + cx.notify(); + }))) + .child(pp) + .child(div().id("next").class("btn").css("width", rem(40.0)).css("height", rem(40.0)).child(ico(Ico::Next, 0xffffff, 22.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.skip(true); + cx.notify(); + }))) + .child(tog("repeat", self.repeat, Ico::Repeat).on_click(cx.listener(|this, _, _, cx| { + this.repeat = !this.repeat; + cx.notify(); + }))); + // the scrubber: press anywhere to jump there, then drag (the dial takes it from the jump) + let pct = format!("{}%", self.seek.value * 100.0); + let scrub = draggable(div().id("scrub").class(if self.seek.dragging() { "abs bar grab" } else { "abs bar" }), cx, Axis::Right, + SCRUB.2 * scale, |a: &mut Self| &mut a.seek, |a| a.pos = a.seek.value * a.len()) + .css("left", rem(SCRUB.0)).css("top", rem(SCRUB.1)).css("width", rem(SCRUB.2)) + .child(div().class("track").child(div().class("fill").css("width", pct.clone())).child(div().class("knob").css("left", pct))); + let vpct = format!("{}%", self.volume.value * 100.0); + let vol = draggable(div().id("vol").class(if self.volume.dragging() { "abs bar grab" } else { "abs bar" }), cx, Axis::Right, + VOLUME.2 * scale, |a: &mut Self| &mut a.volume, |_| {}) + .css("left", rem(VOLUME.0)).css("top", rem(VOLUME.1)).css("width", rem(VOLUME.2)) + .child(div().class("track").child(div().class("fill").css("width", vpct.clone())).child(div().class("knob").css("left", vpct))); + let (title, _, _) = TRACKS[self.track]; + div().class("glass rise").css("left", rem(PLAYER.0)).css("top", rem(PLAYER.1)).css("width", rem(1168.0)).css("height", rem(104.0)) + .css("animation-delay", "180ms") + .on_mouse_down_capture(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, _, _| { + let (x, y) = this.in_player(e.position); + let hit = |(bx, by, bw): (f32, f32, f32)| (bx - 8.0..bx + bw + 8.0).contains(&x) && (by..by + 24.0).contains(&y); + if hit(SCRUB) { + this.seek.set((x - SCRUB.0) / SCRUB.2); + this.pos = this.seek.value * this.len(); + } else if hit(VOLUME) { + this.volume.set((x - VOLUME.0) / VOLUME.2); + } + })) + .child(div().class("gloss")) + .child(div().class("abs now").child(mini) + .child(div().class("txt").child(div().class("t").child(title)).child(div().class("a").child(ARTIST))) + .child(self.like(self.track, cx)).child(ico(Ico::Plus, 0xffffff, 18.0))) + .child(ctrl) + .child(div().class("abs time txt").css("left", rem(SCRUB.0 - 54.0)).css("text-align", "right").child(clock(self.pos))) + .child(scrub) + .child(div().class("abs time txt").css("left", rem(SCRUB.0 + SCRUB.2 + 10.0)).child(clock(self.len()))) + .child(div().class("abs right").child(ico(Ico::Queue, 0xffffff, 20.0)).child(ico(Ico::Device, 0xffffff, 20.0)) + .child(ico(Ico::Volume, 0xffffff, 20.0))) + .child(vol) + } +} + +impl Render for Aero { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + // the sky always moves, so every frame renders + w.request_animation_frame(); + focus_root(w, &mut self.frames); + self.fit = Fit::new(w, DESIGN); + self.tick(); + let t = now(); + let energy = if self.playing { 0.5 + 0.5 * (t * 7.3).sin().abs() * self.volume.value } else { 0.0 }; + let sky = self.sky.canvas(move |_| [t, energy]).class("sky"); + let app = div().class("app").css("left", rem(self.fit.ox)).css("top", rem(self.fit.oy)) + .child(Self::top_bar()) + .child(self.sidebar(cx)) + .child(self.main_panel(cx, t)) + .child(self.player(cx, t)); + html().css("font-size", self.fit.root_font()) + .child(head().child(style().child(css()))) + .child(body().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| if this.key(&e.keystroke.key) { cx.notify() })) + .child(sky).child(app)) + } +} + +/// Every feature in turn: the entrance, a hover, a click to play, the icon morph, pause, a +/// scrub, the volume, a like, skipping, shuffle and the keys. +fn storyboard(dir: String) -> Script { + story(dir, move |s| { + s.play("00-enter", &[0, 120, 300, 600, 1000]); + s.hover("row2"); + s.play("01-hover", &[0, 200]); + s.click("row2"); + s.play("02-click-plays", &[0, 60, 120, 300, 1500]); + s.click("pp"); + s.play("03-pause", &[0, 60, 120, 300]); + s.click("play"); + s.play("04-play", &[0, 300]); + let b = s.cx.element_bounds(s.win, "scrub").expect("scrub"); + let y = b.origin.y + b.size.height / 2.0; + s.cx.simulate_drag(s.win, (b.origin.x + b.size.width * 0.2, y), (b.origin.x + b.size.width * 0.7, y)); + s.play("05-scrub", &[0, 300]); + let b = s.cx.element_bounds(s.win, "vol").expect("vol"); + let y = b.origin.y + b.size.height / 2.0; + s.cx.simulate_click(s.win, b.origin.x + b.size.width * 0.3, y); + s.play("06-volume", &[0]); + s.click("like3-0"); + s.play("07-like", &[0, 100, 300]); + s.click("shuffle"); + s.click("next"); + s.play("08-next", &[0, 300]); + s.click("pl3"); + s.click("nav1"); + s.cx.simulate_key(s.win, " ", "space"); + s.play("09-keys", &[0, 300]); + }) +} + +fn sky() -> Fx { + Fx::new("aero-sky", SKY, 2, [74, 150, 230]) +} + +fn cover() -> Fx { + Fx::new("aero-cover", COVER, 3, [90, 150, 220]) +} + +fn main() { + if let Some(dir) = arg("--frames") { + let (s, c) = (sky(), cover()); + if gpu_stills(&dir, 1200, 776, [("sky", [6.0f32, 0.0]), ("sky-later", [14.0, 0.8])], |g, f| g.draw(s.effect(), &[], f)).is_none() { + eprintln!("sky shader: {:?}", s.error()); + } + if gpu_stills(&dir, 352, 352, [("cover", [3.0f32, 0.55, 1.0])], |g, f| g.draw(c.effect(), &[], f)).is_none() { + eprintln!("cover shader: {:?}", c.error()); + } + return; + } + let make = || Aero { + sky: sky(), + cover: cover(), + playing: false, + track: 0, + pos: 42.0, + last: now(), + seek: Dial::new(0.0), + volume: Dial::new(0.72), + liked: [true, false, false, false, true, false, false, false], + likes: 0, + nav: 0, + playlist: 2, + shuffle: false, + repeat: false, + fit: Fit { scale: 1.0, w: DESIGN.0, h: DESIGN.1, ox: 0.0, oy: 0.0 }, + frames: 0, + }; + run_with(DESIGN.0, DESIGN.1, "Breeze", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/amp.rs b/demos/src/bin/amp.rs new file mode 100644 index 00000000..3ecd259c --- /dev/null +++ b/demos/src/bin/amp.rs @@ -0,0 +1,823 @@ +//! Lagoon: a skinned desktop MP3 player of the early 2000s, on BUI. Three docked windows in a +//! glossy aqua skin: the player (LCD clock, a live spectrum analyzer painted with BUI's `Painter`, +//! a character-stepped marquee, kbps / kHz, volume, balance, seek, transport), the equalizer +//! (ON / AUTO, a preamp and ten bands, the curve they make, presets) and the playlist. +//! +//! Everything works: Play runs the clock and the analyzer (its bars follow the EQ, the preamp and +//! the volume, peaks hold then fall); click the analyzer for the oscilloscope, the clock for the +//! time left. Drag (or wheel) any slider, click the seek bar to jump. PRESETS slides every band to +//! the next preset; AUTO picks one per track. Click a row to select it, double-click (or Enter) to +//! play it; +FILE adds a track, -FILE removes the selection, SHUF shuffles, SORT sorts, LOAD +//! resets the list. EQ / PL fold their windows away and the ones below slide up. Keys: Z X C V B +//! (prev, play, pause, stop, next), Space, ↑ / ↓ in the list, Enter. +//! +//! Motion: the windows drop in on first light (80 ms apart); folding a window is a 260 ms +//! transform + opacity transition; presets ease out over 420 ms; presses scale to 0.96. +//! +//! `cargo run --release --bin amp`, `-- --storyboard DIR` for headless frames. + +use std::sync::OnceLock; + +use blenderui::prelude::*; +use bui_demos::canvas::{rem, rem_css, Fit}; +use bui_demos::control::{draggable, Axis, Dial}; +use bui_demos::ease::{ease_out, lerp, progress}; +use bui_demos::{arg, focus_root, now, run_with, story::story, Script}; + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; user-select: none; + background: linear-gradient(160deg, #134b5f 0%, #0b2a3a 55%, #071822 100%); + font-family: Tahoma, 'Segoe UI', sans-serif; font-size: 11px; color: #0f5a63; -webkit-font-smoothing: antialiased; } +.abs { position: absolute; } +.app { position: absolute; width: 560px; height: 700px; } +.mono { font-family: Consolas, 'Courier New', monospace; } +.num { font-variant-numeric: tabular-nums; } + +/* docked windows: a slot moves (folding), the window inside drops in once */ +.slot { position: absolute; left: 20px; width: 520px; + transition-property: transform, opacity; transition-duration: 260ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); } +.slot.gone { opacity: 0; transform: translateY(-10px) scale(0.97); pointer-events: none; } +.win { position: relative; width: 520px; border-radius: 10px; + background: linear-gradient(180deg, #f0fdfd 0%, #c4ecef 40%, #98d8de 100%); + box-shadow: 0 18px 44px rgba(0,0,0,0.5), 0 0 0 1px #3d939b, inset 0 1px 0 #fff; + animation: drop 520ms cubic-bezier(0.2, 0, 0, 1) backwards; } +@keyframes drop { from { opacity: 0; transform: translateY(-18px); } to { opacity: 1; transform: translateY(0); } } +.tbar { position: absolute; left: 4px; top: 4px; width: 512px; height: 20px; border-radius: 6px; + background: linear-gradient(180deg, #8fe0e6 0%, #43b4be 50%, #2b9aa5 52%, #5cc6cf 100%); + box-shadow: inset 0 1px 0 rgba(255,255,255,0.7), 0 0 0 1px #2f8a93; + color: #fff; font-weight: 700; font-size: 10px; letter-spacing: 4px; text-align: center; line-height: 20px; } +.tbar .dots { position: absolute; right: 6px; top: 4px; display: flex; gap: 4px; } +.tbar .dots div { width: 12px; height: 12px; border-radius: 6px; background: linear-gradient(180deg, #e8fbfc, #7ccdd4); + box-shadow: 0 0 0 1px #2f8a93; } +.tbar .grip { position: absolute; left: 8px; top: 6px; width: 60px; height: 8px; + background: repeating-linear-gradient(180deg, rgba(255,255,255,0.6) 0px, rgba(255,255,255,0.6) 1px, transparent 1px, transparent 3px); } + +/* the LCD-ish panels */ +/* the LCD's glass clips what it shows: the analyzer, the curve, the scrolling marquee */ +.lcd { position: absolute; overflow: hidden; border-radius: 6px; background: linear-gradient(180deg, #f2feff 0%, #c7f0f4 100%); + box-shadow: inset 0 1px 3px rgba(0,60,70,0.35), 0 0 0 1px #6cb9c0; } +.clutter { position: absolute; left: 10px; top: 32px; width: 14px; display: flex; flex-direction: column; gap: 3px; + font-size: 9px; font-weight: 700; color: #2a8c95; text-align: center; } +.time { position: absolute; left: 34px; top: 0px; font-size: 40px; font-weight: 700; color: #0d4f58; letter-spacing: 1px; cursor: pointer; + text-shadow: 0 0 6px rgba(13,79,88,0.3); } +.state { position: absolute; left: 10px; top: 14px; width: 14px; height: 14px; background: #0d4f58; } +.st-play { clip-path: polygon(10% 0, 100% 50%, 10% 100%); background: #1c9b3a; } +.st-pause { clip-path: polygon(0 0, 38% 0, 38% 100%, 0 100%, 0 0, 62% 0, 100% 0, 100% 100%, 62% 100%, 62% 0); } +.st-stop { transform: scale(0.8); } +.marq { font-size: 13px; color: #0d4f58; line-height: 24px; padding-left: 8px; white-space: pre; } +.tag { font-size: 13px; font-weight: 700; color: #0d4f58; text-align: center; line-height: 20px; } +.lbl { position: absolute; font-size: 9px; font-weight: 700; color: #2a7d86; letter-spacing: 0.5px; } +.led { position: absolute; font-size: 9px; font-weight: 700; color: #8cc3c8; letter-spacing: 0.5px; + transition-property: color; transition-duration: 160ms; } +.led.lit { color: #0a7f8b; } + +/* buttons: glossy aqua keys */ +.key { position: absolute; display: flex; align-items: center; justify-content: center; flex-direction: column; border-radius: 6px; cursor: pointer; + background: linear-gradient(180deg, #ffffff 0%, #d4f3f5 48%, #a9e1e6 52%, #cdf0f2 100%); + box-shadow: 0 1px 2px rgba(0,50,60,0.35), 0 0 0 1px #5aaab2, inset 0 1px 0 #fff; + font-size: 9px; font-weight: 700; color: #11606a; letter-spacing: 0.5px; line-height: 1.15; + transition-property: transform, background-color, box-shadow; transition-duration: 120ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); } +.key:hover { background-color: #e9fbfc; } +.key:active { transform: scale(0.96); } +.key.lit { box-shadow: 0 1px 2px rgba(0,50,60,0.35), 0 0 0 1px #2b9aa5, inset 0 0 6px rgba(40,190,200,0.6); } +.key .dot { width: 6px; height: 6px; border-radius: 3px; background: #9cc9cd; margin-bottom: 2px; + transition-property: background-color, box-shadow; transition-duration: 160ms; } +.key.lit .dot { background: #31e05a; box-shadow: 0 0 5px #31e05a; } +.glyph { background: #11606a; } +.tri { width: 12px; height: 12px; clip-path: polygon(12% 0, 100% 50%, 12% 100%); } +.bars2 { width: 11px; height: 12px; clip-path: polygon(0 0, 36% 0, 36% 100%, 0 100%, 0 0, 64% 0, 100% 0, 100% 100%, 64% 100%, 64% 0); } +.sq { width: 11px; height: 11px; border-radius: 1px; } +.skip { display: flex; align-items: center; } +.skip .tri { width: 9px; height: 11px; } +.skip .bar { width: 3px; height: 11px; } +.eject { width: 12px; height: 8px; clip-path: polygon(50% 0, 100% 100%, 0 100%); } + +/* sliders */ +.hs { position: absolute; height: 20px; cursor: pointer; } +.groove { position: absolute; left: 0; top: 7px; width: 100%; height: 6px; border-radius: 3px; background: #7fbfc5; + box-shadow: inset 0 1px 2px rgba(0,50,60,0.5); } +.hs .fill { position: absolute; left: 0; top: 7px; height: 6px; border-radius: 3px; background: linear-gradient(180deg, #9ff0a8, #2fb64d); } +.thumb { position: absolute; top: 3px; width: 26px; height: 14px; margin-left: -13px; border-radius: 7px; + background: linear-gradient(180deg, #ffffff 0%, #c9eef1 50%, #8fd3d9 52%, #d7f4f6 100%); + box-shadow: 0 1px 3px rgba(0,50,60,0.5), 0 0 0 1px #4a9ea6; + transition-property: transform; transition-duration: 120ms; } +.hs:hover .thumb, .vs:hover .orb { transform: scale(1.08); } +.grab .thumb, .grab .orb { transform: scale(1.15); } + +.vs { position: absolute; width: 28px; height: 104px; cursor: pointer; } +.vs .groove { left: 11px; top: 4px; width: 6px; height: 96px; } +.vs .mid { position: absolute; left: 6px; top: 51px; width: 16px; height: 2px; background: rgba(15,90,99,0.35); } +.vs .lvl { position: absolute; left: 11px; width: 6px; border-radius: 3px; } +.orb { position: absolute; left: 3px; width: 22px; height: 22px; margin-top: -11px; border-radius: 11px; + background: linear-gradient(180deg, #e6fbff 0%, #6fd0f0 45%, #1f93c9 55%, #6fd6f2 100%); + box-shadow: 0 2px 4px rgba(0,40,70,0.5), 0 0 0 1px #1d7ea8, inset 0 1px 0 #fff; + transition-property: transform; transition-duration: 120ms; } +.db { position: absolute; left: -10px; width: 48px; text-align: center; font-size: 9px; font-weight: 700; color: #0d4f58; + opacity: 0; transition-property: opacity; transition-duration: 120ms; } +.grab .db { opacity: 1; } +.band { position: absolute; top: 192px; width: 40px; text-align: center; font-size: 9px; font-weight: 700; color: #2a7d86; } +.toast { position: absolute; right: 8px; top: 4px; font-size: 10px; font-weight: 700; color: #0d4f58; letter-spacing: 1px; } + +/* playlist */ +.list { left: 10px; top: 30px; width: 500px; height: 150px; overflow-y: auto; background: linear-gradient(180deg, #ffffff, #effcfd); } +.row { display: flex; height: 21px; line-height: 21px; padding: 0 8px; font-size: 12px; color: #1d6e78; cursor: pointer; + transition-property: background-color, color; transition-duration: 100ms; } +.row:hover { background: rgba(120,210,218,0.22); } +.row.sel { background: linear-gradient(180deg, #bdeef2, #8fd8de); color: #0b4a52; } +.row.cur { font-weight: 700; color: #0f4fb8; } +.row .t { flex: 1; white-space: nowrap; overflow: hidden; } +.row .d { width: 44px; text-align: right; } +.newrow { animation: rowin 300ms cubic-bezier(0.2, 0, 0, 1); } +@keyframes rowin { from { opacity: 0; transform: translateX(-12px); } to { opacity: 1; transform: translateX(0); } } +"; + +const DESIGN: (f32, f32) = (560.0, 700.0); +/// The three windows: top (design px) and height. +const MAIN: (f32, f32) = (16.0, 204.0); +const EQW: (f32, f32) = (226.0, 210.0); +const PLW: (f32, f32) = (442.0, 236.0); +/// Window x on the design canvas. +const WIN_X: f32 = 20.0; +/// A slider in the player window: its id, x, y, width, and whether it fills up to the thumb. +#[derive(Clone, Copy)] +struct Fader { + id: &'static str, + x: f32, + y: f32, + w: f32, + fill: bool, +} +const SEEK: Fader = Fader { id: "seek", x: 24.0, y: 130.0, w: 472.0, fill: true }; +const VOLUME: Fader = Fader { id: "volume", x: 232.0, y: 92.0, w: 150.0, fill: true }; +const BALANCE: Fader = Fader { id: "balance", x: 392.0, y: 92.0, w: 70.0, fill: false }; +/// Equalizer sliders: the preamp's x, the first band's, the step, the top, the travel. +const EQ_PRE_X: f32 = 22.0; +const EQ_BAND_X: f32 = 100.0; +const EQ_STEP: f32 = 41.0; +const EQ_TOP: f32 = 84.0; +const EQ_TRAVEL: f32 = 96.0; +const BANDS: [&str; 10] = ["60", "170", "310", "600", "1K", "3K", "6K", "12K", "14K", "16K"]; +/// Analyzer bars. +const BARS: usize = 24; + +/// Artist, title, seconds. +const LIBRARY: [(&str, &str, u32); 9] = [ + ("Dune Static", "Low Tide Signal", 240), ("Velvet Ohm", "Glass Arcade", 211), + ("Kiln & Koi", "Paper Lanterns (Short One)", 240), ("Northbound Tram", "Bad Signal", 225), + ("Mono Lisa", "Pastel Riot", 198), ("Halcyon Drive", "CRT Sunset", 252), + ("Saltwater Choir", "Dial-Up Hymn", 233), ("Neon Orchard", "Floppy Heart", 187), ("Quiet Arcade", "Insert Coin", 205), +]; +const START_LIST: [usize; 6] = [0, 1, 2, 3, 4, 5]; + +/// Name, then preamp and the ten bands (0..1, 0.5 flat). +const PRESETS: [(&str, [f32; 11]); 6] = [ + ("FLAT", [0.5; 11]), + ("ROCK", [0.55, 0.72, 0.64, 0.54, 0.42, 0.4, 0.5, 0.62, 0.7, 0.72, 0.72]), + ("POP", [0.52, 0.42, 0.55, 0.66, 0.7, 0.66, 0.52, 0.44, 0.42, 0.42, 0.44]), + ("BASS", [0.5, 0.86, 0.8, 0.7, 0.56, 0.46, 0.42, 0.4, 0.4, 0.4, 0.4]), + ("VOCAL", [0.5, 0.36, 0.42, 0.56, 0.7, 0.74, 0.68, 0.54, 0.46, 0.42, 0.4]), + ("DANCE", [0.56, 0.8, 0.7, 0.5, 0.44, 0.48, 0.6, 0.7, 0.66, 0.6, 0.58]), +]; +/// How long a preset takes to slide in (seconds). +const PRESET_SLIDE: f32 = 0.42; + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Play { + Stopped, + Playing, + Paused, +} + +/// The eleven equalizer dials (`band::<0>` is the preamp), as the function pointers `draggable` takes. +fn band(a: &mut Amp) -> &mut Dial { + &mut a.eq[I] +} +const BAND_DIALS: [fn(&mut Amp) -> &mut Dial; 11] = [ + band::<0>, band::<1>, band::<2>, band::<3>, band::<4>, band::<5>, band::<6>, band::<7>, band::<8>, band::<9>, band::<10>, +]; + +fn mmss(secs: u32) -> String { + format!("{:02}:{:02}", secs / 60, secs % 60) +} + +/// A cheap repeatable noise in 0..1. +fn hash(a: f32, b: f32) -> f32 { + ((a * 127.1 + b * 311.7).sin() * 43758.547).fract().abs() +} + +#[expect(clippy::struct_excessive_bools, reason = "each is one independent switch on the skin")] +struct Amp { + play: Play, + /// The library index playing, and seconds into it. + cur: usize, + pos: f32, + last: f32, + /// The playlist (library indices), the selected row, and rows added (keys their slide-in). + list: Vec, + sel: usize, + added: Option, + seek: Dial, + volume: Dial, + balance: Dial, + eq: [Dial; 11], + eq_on: bool, + auto: bool, + preset: usize, + /// A preset sliding in: when it began and where every band started. + slide: Option<(f32, [f32; 11])>, + show_eq: bool, + show_pl: bool, + remaining: bool, + scope: bool, + shuffle: bool, + repeat: bool, + /// The analyzer: bar levels and their peaks (with the time each peak still holds). + bars: [f32; BARS], + peaks: [f32; BARS], + hold: [f32; BARS], + fit: Fit, + frames: u32, +} + +impl Amp { + const fn len(&self) -> f32 { + LIBRARY[self.cur].2 as f32 + } + + fn start(&mut self, lib: usize) { + self.cur = lib; + self.pos = 0.0; + self.play = Play::Playing; + if self.auto { + self.apply_preset(1 + lib % (PRESETS.len() - 1)); + } + } + + /// The row of the playing track in the list, if it is in it. + fn cur_row(&self) -> Option { + self.list.iter().position(|&i| i == self.cur) + } + + fn skip(&mut self, forward: bool) { + if self.list.is_empty() { + return; + } + let n = self.list.len(); + let at = self.cur_row().unwrap_or(0); + let step = if self.shuffle { 1 + (self.pos as usize) % (n.max(2) - 1) } else { 1 }; + let row = if forward { (at + step) % n } else { (at + n - step % n) % n }; + let keep = self.play; + self.start(self.list[row]); + if keep != Play::Playing { + self.play = keep; + } + } + + fn apply_preset(&mut self, p: usize) { + self.preset = p; + self.slide = Some((now(), self.eq.map(|d| d.value))); + } + + fn eq_gain(&self, f: f32) -> f32 { + if !self.eq_on { + return 1.0; + } + let x = f * 9.0; + let (i, k) = (x.floor() as usize, x.fract()); + let v = lerp(self.eq[1 + i.min(9)].value, self.eq[1 + (i + 1).min(9)].value, k); + (1.0 + (v - 0.5) * 1.6) * (1.0 + (self.eq[0].value - 0.5) * 0.8) + } + + /// Advances the clock, a sliding preset and the analyzer by the time since the last frame. + fn tick(&mut self) { + let t = now(); + let dt = (t - self.last).clamp(0.0, 0.25); + self.last = t; + if self.play == Play::Playing && !self.seek.dragging() { + self.pos += dt; + if self.pos >= self.len() { + if self.repeat { self.pos = 0.0 } else { self.skip(true) } + } + } + if !self.seek.dragging() { + self.seek.value = self.pos / self.len(); + } + if let Some((at, from)) = self.slide { + let k = ease_out(progress(t, at, at + PRESET_SLIDE)); + let to = PRESETS[self.preset].1; + for (i, d) in self.eq.iter_mut().enumerate() { + d.value = lerp(from[i], to[i], k); + } + if k >= 1.0 { + self.slide = None; + } + } + let on = self.play == Play::Playing; + let kick = (-((t % 0.5) / 0.11)).exp(); + let snare = (-(((t + 0.25) % 1.0) / 0.09)).exp(); + for i in 0..BARS { + let f = i as f32 / (BARS - 1) as f32; + let jitter = hash((t * 18.0).floor(), i as f32); + let tone = 0.5 * (1.0 - 0.55 * f) * (0.55 + 0.45 * ((t * (2.0 + i as f32 * 0.37)).sin() * (t * 1.1 + i as f32).cos()).abs()); + let level = tone + kick * 0.55 * (1.0 - f).powi(2) + snare * 0.25 * (1.0 - (f - 0.45).abs() * 2.0).max(0.0) + jitter * 0.18 * f; + let target = if on { (level * self.eq_gain(f) * (0.35 + 0.8 * self.volume.value)).clamp(0.0, 1.0) } else { 0.0 }; + // bars jump up and fall at a steady rate; peaks hold, then fall slowly + self.bars[i] = target.max(self.bars[i] - dt * 2.4); + if self.bars[i] >= self.peaks[i] { + self.peaks[i] = self.bars[i]; + self.hold[i] = 0.35; + } else if self.hold[i] > 0.0 { + self.hold[i] -= dt; + } else { + self.peaks[i] = (self.peaks[i] - dt * 0.7).max(0.0); + } + } + } + + fn key(&mut self, key: &str) -> bool { + match key { + "z" | "Z" => self.skip(false), + "x" | "X" => self.press_play(), + "c" | "C" => self.pause(), + "v" | "V" => self.stop(), + "b" | "B" => self.skip(true), + "space" => { + if self.play == Play::Playing { self.pause() } else { self.press_play() } + } + "Up" => self.sel = self.sel.saturating_sub(1), + "Down" => self.sel = (self.sel + 1).min(self.list.len().saturating_sub(1)), + "Return" | "KP_Enter" => { + if let Some(&lib) = self.list.get(self.sel) { + self.start(lib); + } + } + _ => return false, + } + true + } + + fn press_play(&mut self) { + match self.play { + Play::Paused => self.play = Play::Playing, + Play::Playing => self.pos = 0.0, + Play::Stopped => { + let lib = self.list.get(self.sel).copied().unwrap_or(self.cur); + self.start(lib); + } + } + } + + const fn pause(&mut self) { + self.play = match self.play { + Play::Playing => Play::Paused, + Play::Paused => Play::Playing, + Play::Stopped => Play::Stopped, + }; + } + + const fn stop(&mut self) { + self.play = Play::Stopped; + self.pos = 0.0; + } + + /// A window point in the coordinates of the window whose top is `top`. + fn in_window(&self, p: Point, top: f32) -> (f32, f32) { + let (x, y) = self.fit.design(p); + (x - WIN_X, y - top) + } + + fn chrome(title: &'static str, h: f32) -> Div { + div().class("win").css("height", rem(h)) + .child(div().class("tbar").child(div().class("grip")).child(title) + .child(div().class("dots").child(div()).child(div()).child(div()))) + } + + fn key_btn(id: &'static str, (x, y, w, h): (f32, f32, f32, f32), lit: bool) -> Div { + div().id(id).class(if lit { "key lit" } else { "key" }) + .css("left", rem(x)).css("top", rem(y)).css("width", rem(w)).css("height", rem(h)) + } + + /// The slider `f` showing `d`, dragging the dial `dial` picks. + fn hslider(&self, cx: &mut Context, f: Fader, d: Dial, dial: fn(&mut Self) -> &mut Dial, changed: fn(&mut Self)) -> Div { + let pct = format!("{}%", d.value * 100.0); + let mut s = draggable(div().id(f.id).class(if d.dragging() { "hs grab" } else { "hs" }), cx, Axis::Right, + f.w * self.fit.scale, dial, changed) + .css("left", rem(f.x)).css("top", rem(f.y)).css("width", rem(f.w)) + .child(div().class("groove")); + if f.fill { + s = s.child(div().class("fill").css("width", pct.clone())); + } + s.child(div().class("thumb").css("left", pct)) + } + + fn main_win(&self, cx: &mut Context, t: f32) -> Div { + let shown = if self.remaining { format!("-{}", mmss((self.len() - self.pos).max(0.0) as u32)) } else { mmss(self.pos as u32) }; + let blink = self.play == Play::Paused && (t * 2.0).fract() > 0.5; + let state = match self.play { + Play::Playing => "state st-play", + Play::Paused => "state st-pause", + Play::Stopped => "state st-stop", + }; + let (bars, peaks, scope) = (self.bars, self.peaks, self.scope); + let level = bars.iter().sum::() / BARS as f32; + let analyzer = canvas(move |b, p| paint_analyzer(b, p, &bars, &peaks, scope, level, t)) + .id("viz").class("abs").css("left", rem(8.0)).css("top", rem(50.0)).css("width", rem(180.0)).css("height", rem(36.0)) + .on_click(cx.listener(|this, _, _, cx| { + this.scope = !this.scope; + cx.notify(); + })); + let lcd = div().class("lcd").css("left", rem(28.0)).css("top", rem(30.0)).css("width", rem(196.0)).css("height", rem(92.0)) + .child(div().class(state)) + .child(div().id("time").class("time mono num").css("opacity", if blink { "0.15" } else { "1" }).child(shown) + .on_click(cx.listener(|this, _, _, cx| { + this.remaining = !this.remaining; + cx.notify(); + }))) + .child(analyzer); + // the marquee steps a character at a time, as the bitmap fonts did + let (artist, title, secs) = LIBRARY[self.cur]; + let row = self.cur_row().map_or(0, |r| r + 1); + let text = format!("{row}. {artist} - {title} ({}) *** ", mmss(secs)); + let n = text.chars().count(); + let k = (t / 0.2) as usize % n; + let marquee: String = text.chars().cycle().skip(k).take(36).collect(); + let transport = [("prev", "skip rev"), ("play", "tri"), ("pause", "bars2"), ("stop", "sq"), ("next", "skip")]; + let mut win = Self::chrome("L A G O O N", MAIN.1) + .child(div().class("clutter").children(["O", "A", "I", "D", "V"].map(|c| div().child(c)))) + .child(lcd) + .child(div().class("lcd").css("left", rem(232.0)).css("top", rem(30.0)).css("width", rem(278.0)).css("height", rem(24.0)) + .child(div().class("marq mono").child(marquee))) + .child(div().class("lcd tag num").css("left", rem(232.0)).css("top", rem(62.0)).css("width", rem(36.0)).css("height", rem(20.0)).child("128")) + .child(div().class("lbl").css("left", rem(272.0)).css("top", rem(67.0)).child("kbps")) + .child(div().class("lcd tag num").css("left", rem(300.0)).css("top", rem(62.0)).css("width", rem(26.0)).css("height", rem(20.0)).child("44")) + .child(div().class("lbl").css("left", rem(330.0)).css("top", rem(67.0)).child("kHz")) + .child(div().class("led").css("left", rem(366.0)).css("top", rem(67.0)).child("mono")) + .child(div().class(if self.play == Play::Stopped { "led" } else { "led lit" }).css("left", rem(398.0)).css("top", rem(67.0)).child("stereo")) + .child(self.hslider(cx, VOLUME, self.volume, |a| &mut a.volume, |_| {})) + .child(self.hslider(cx, BALANCE, self.balance, |a| &mut a.balance, |a| { + // a detent at the centre + if (a.balance.value - 0.5).abs() < 0.05 { + a.balance.value = 0.5; + } + })) + .child(Self::key_btn("eqb", (470.0, 60.0, 40.0, 24.0), self.show_eq).child(div().class("dot")).child("EQ") + .on_click(cx.listener(|this, _, _, cx| { + this.show_eq = !this.show_eq; + cx.notify(); + }))) + .child(Self::key_btn("plb", (470.0, 88.0, 40.0, 24.0), self.show_pl).child(div().class("dot")).child("PL") + .on_click(cx.listener(|this, _, _, cx| { + this.show_pl = !this.show_pl; + cx.notify(); + }))) + .child(self.hslider(cx, SEEK, self.seek, |a| &mut a.seek, |a| a.pos = a.seek.value * a.len())); + for (i, (id, glyph)) in transport.into_iter().enumerate() { + let g = if id == "prev" || id == "next" { + let (tri, bar) = (div().class("glyph tri"), div().class("glyph bar")); + if id == "prev" { div().class("skip").child(bar).child(tri.css("transform", "scaleX(-1)")) } else { div().class("skip").child(tri).child(bar) } + } else { + div().class(format!("glyph {glyph}")) + }; + let lit = matches!((id, self.play), ("play", Play::Playing) | ("pause", Play::Paused) | ("stop", Play::Stopped)); + win = win.child(Self::key_btn(id, (10.0 + i as f32 * 46.0, 158.0, 44.0, 36.0), lit).child(g) + .on_click(cx.listener(move |this, _, _, cx| { + match id { + "prev" => this.skip(false), + "play" => this.press_play(), + "pause" => this.pause(), + "stop" => this.stop(), + _ => this.skip(true), + } + cx.notify(); + }))); + } + win.child(Self::key_btn("eject", (246.0, 158.0, 40.0, 36.0), false).child(div().class("glyph eject")) + .child(div().class("glyph").css("width", rem(12.0)).css("height", rem(2.0)).css("margin-top", rem(2.0))) + .on_click(cx.listener(|this, _, _, cx| { + this.show_pl = true; + this.added = None; + this.list = START_LIST.to_vec(); + cx.notify(); + }))) + .child(Self::key_btn("shuffle", (330.0, 160.0, 72.0, 32.0), self.shuffle).child(div().class("dot")).child("SHUFFLE") + .on_click(cx.listener(|this, _, _, cx| { + this.shuffle = !this.shuffle; + cx.notify(); + }))) + .child(Self::key_btn("repeat", (408.0, 160.0, 56.0, 32.0), self.repeat).child(div().class("dot")).child("REPEAT") + .on_click(cx.listener(|this, _, _, cx| { + this.repeat = !this.repeat; + cx.notify(); + }))) + .child(div().class("abs").css("left", rem(472.0)).css("top", rem(158.0)).css("width", rem(36.0)).css("height", rem(36.0)) + .css("border-radius", "50%").css("background", "linear-gradient(180deg, #e6fbff 0%, #6fd0f0 45%, #1f93c9 55%, #6fd6f2 100%)") + .css("box-shadow", "0 2px 4px rgba(0,40,70,0.5), 0 0 0 1px #1d7ea8, inset 0 1px 0 #fff")) + } + + fn eq_win(&self, cx: &mut Context) -> Div { + let vals = self.eq.map(|d| d.value); + let (on, preset_at) = (self.eq_on, self.slide.map(|s| s.0)); + let preset = PRESETS[self.preset].0; + let curve = canvas(move |b, p| paint_curve(b, p, &vals, on)) + .class("abs").css("left", rem(0.0)).css("top", rem(0.0)).css("width", rem(220.0)).css("height", rem(44.0)); + let fade = preset_at.map_or(0.0, |at| 1.0 - progress(now(), at + PRESET_SLIDE + 0.6, at + PRESET_SLIDE + 1.0)); + let mut win = Self::chrome("E Q U A L I Z E R", EQW.1) + .child(Self::key_btn("on", (10.0, 32.0, 56.0, 24.0), self.eq_on).child(div().class("dot")).child("ON") + .on_click(cx.listener(|this, _, _, cx| { + this.eq_on = !this.eq_on; + cx.notify(); + }))) + .child(Self::key_btn("auto", (72.0, 32.0, 62.0, 24.0), self.auto).child(div().class("dot")).child("AUTO") + .on_click(cx.listener(|this, _, _, cx| { + this.auto = !this.auto; + cx.notify(); + }))) + .child(div().class("lcd").css("left", rem(150.0)).css("top", rem(28.0)).css("width", rem(220.0)).css("height", rem(44.0)) + .child(curve).child(div().class("toast").css("opacity", format!("{fade}")).child(preset))) + .child(Self::key_btn("presets", (400.0, 32.0, 110.0, 24.0), false).child("PRESETS") + .on_click(cx.listener(|this, _, _, cx| { + this.apply_preset((this.preset + 1) % PRESETS.len()); + cx.notify(); + }))) + .child(div().class("lbl").css("left", rem(52.0)).css("top", rem(EQ_TOP)).child("+12 db")) + .child(div().class("lbl").css("left", rem(58.0)).css("top", rem(EQ_TOP + 46.0)).child("0 db")) + .child(div().class("lbl").css("left", rem(54.0)).css("top", rem(EQ_TOP + 92.0)).child("-12 db")); + for (i, dial) in BAND_DIALS.into_iter().enumerate() { + let d = self.eq[i]; + let x = if i == 0 { EQ_PRE_X } else { EQ_BAND_X + (i - 1) as f32 * EQ_STEP }; + // the level: from the 0 dB line to the thumb, green under, orange over + let y = 4.0 + (1.0 - d.value) * EQ_TRAVEL; + let (top, h) = if d.value >= 0.5 { (y, 52.0 - y) } else { (52.0, y - 52.0) }; + let colour = if d.value >= 0.5 { "linear-gradient(180deg, #ffb347, #9ff0a8)" } else { "linear-gradient(180deg, #9ff0a8, #2fb6c4)" }; + let db = (d.value - 0.5) * 24.0; + win = win.child(draggable(div().id(format!("band{i}")).class(if d.dragging() { "vs grab" } else { "vs" }), cx, Axis::Up, + EQ_TRAVEL * self.fit.scale, dial, |a| a.slide = None) + .css("left", rem(x)).css("top", rem(EQ_TOP)) + .child(div().class("groove")).child(div().class("mid")) + .child(div().class("lvl").css("top", rem(top)).css("height", rem(h.max(0.0))).css("background", colour)) + .child(div().class("orb").css("top", rem(y))) + .child(div().class("db num").css("top", rem(y - 26.0)).child(format!("{db:+.1}")))) + .child(div().class("band").css("left", rem(x - 6.0)).child(if i == 0 { "PRE" } else { BANDS[i - 1] })); + } + win + } + + fn pl_win(&self, cx: &mut Context) -> Div { + let mut list = div().class("abs lcd list"); + for (row, &lib) in self.list.iter().enumerate() { + let (artist, title, secs) = LIBRARY[lib]; + let mut class = String::from("row mono"); + if row == self.sel { + class.push_str(" sel"); + } + if lib == self.cur { + class.push_str(" cur"); + } + if self.added == Some(lib) { + class.push_str(" newrow"); + } + list = list.child(div().id(format!("r{lib}")).class(class) + .child(div().class("t").child(format!("{}. {artist} - {title}", row + 1))) + .child(div().class("d num").child(mmss(secs))) + .on_click(cx.listener(move |this, e: &ClickEvent, _, cx| { + this.sel = row; + if e.click_count() >= 2 { + this.start(lib); + } + cx.notify(); + }))); + } + let total: u32 = self.list.iter().map(|&i| LIBRARY[i].2).sum(); + let buttons: [(&'static str, &str, &str); 4] = [("add", "+", "FILE"), ("rem", "-", "FILE"), ("shuf", "SHUF", "LIST"), ("sort", "SORT", "A-Z")]; + let mut win = Self::chrome("P L A Y L I S T", PLW.1).child(list); + for (i, (id, a, b)) in buttons.into_iter().enumerate() { + win = win.child(Self::key_btn(id, (10.0 + i as f32 * 50.0, 188.0, 46.0, 40.0), false).child(a).child(b) + .on_click(cx.listener(move |this, _, _, cx| { + this.edit(id); + cx.notify(); + }))); + } + win.child(div().class("lcd tag mono num").css("left", rem(232.0)).css("top", rem(194.0)).css("width", rem(150.0)).css("height", rem(28.0)) + .css("line-height", rem(28.0)).child(format!("{}/{}", mmss(self.pos as u32), mmss(total)))) + .child(Self::key_btn("load", (430.0, 188.0, 80.0, 40.0), false).child("LOAD").child("LIST") + .on_click(cx.listener(|this, _, _, cx| { + this.edit("load"); + cx.notify(); + }))) + } + + /// The playlist buttons. The selection stays on its track through a shuffle or a sort. + fn edit(&mut self, what: &str) { + let selected = self.list.get(self.sel).copied(); + match what { + "add" => { + if let Some(lib) = (0..LIBRARY.len()).find(|i| !self.list.contains(i)) { + self.list.push(lib); + self.added = Some(lib); + self.sel = self.list.len() - 1; + } + } + "rem" => { + if self.sel < self.list.len() && self.list[self.sel] != self.cur { + self.list.remove(self.sel); + self.sel = self.sel.min(self.list.len().saturating_sub(1)); + } + } + "shuf" => { + let n = self.list.len(); + for i in (1..n).rev() { + let j = (hash(now(), i as f32) * (i + 1) as f32) as usize % (i + 1); + self.list.swap(i, j); + } + } + "sort" => self.list.sort_by_key(|&i| LIBRARY[i].1), + _ => { + self.list = START_LIST.to_vec(); + self.added = None; + } + } + if what != "add" && what != "rem" { + self.sel = selected.and_then(|lib| self.list.iter().position(|&i| i == lib)).unwrap_or(0); + } + } +} + +/// The analyzer's segments, bottom to top. +const SEGMENT_COLOURS: [u32; 4] = [0x18a0aa, 0x55cf7a, 0xe8d84a, 0xf08a2a]; + +/// The analyzer: bars in segments (teal to orange up the bar) with peak caps, or the scope. +fn paint_analyzer(b: Bounds, p: &mut Painter, bars: &[f32; BARS], peaks: &[f32; BARS], scope: bool, level: f32, t: f32) { + let (x0, y0, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); + // the dotted floor grid of the old skins + let mut gy = y0 + 3.0; + while gy < y0 + h { + let mut gx = x0; + while gx < x0 + w { + p.fill(Bounds { origin: point(gx, gy), size: size(1.0, 1.0) }, rgba(0x0f5a6330)); + gx += 4.0; + } + gy += 4.0; + } + if scope { + let pts: [(f32, f32); 72] = std::array::from_fn(|i| { + let u = i as f32 / 71.0; + let v = (u * 19.0 + t * 9.0).sin() * 0.6 + (u * 47.0 - t * 13.0).sin() * 0.3 + (u * 7.0 + t * 3.0).sin() * 0.3; + (x0 + u * w, y0 + h * 0.5 - v * level * h * 0.9) + }); + p.line(&pts, rgb(0x13a5b0), 1.6); + return; + } + let bw = w / BARS as f32; + let seg = 3.0; + let rows = (h / seg) as usize; + for i in 0..BARS { + let x = x0 + i as f32 * bw; + let lit = (bars[i] * rows as f32).round() as usize; + for r in 0..lit { + let c = SEGMENT_COLOURS[(r * SEGMENT_COLOURS.len() / rows.max(1)).min(SEGMENT_COLOURS.len() - 1)]; + p.fill(Bounds { origin: point(x + 0.5, y0 + h - (r + 1) as f32 * seg + 1.0), size: size(bw - 1.5, seg - 1.0) }, rgb(c)); + } + if peaks[i] > 0.02 { + p.fill(Bounds { origin: point(x + 0.5, y0 + h - peaks[i] * h - 1.0), size: size(bw - 1.5, 1.4) }, rgb(0x0d4f58)); + } + } +} + +/// The equalizer's curve: a Catmull-Rom spline through the ten bands, coloured by gain, over the +/// preamp's line. +fn paint_curve(b: Bounds, p: &mut Painter, vals: &[f32; 11], on: bool) { + let (x0, y0, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); + let pad = 6.0; + let y_of = |v: f32| y0 + pad + (1.0 - v) * (h - 2.0 * pad); + p.line(&[(x0 + pad, y_of(0.5)), (x0 + w - pad, y_of(0.5))], rgba(0x0f5a6340), 1.0); + p.line(&[(x0 + pad, y_of(vals[0])), (x0 + w - pad, y_of(vals[0]))], rgba(0x2fb6c470), 1.0); + let band = |i: isize| vals[1 + i.clamp(0, 9) as usize]; + let pts: [(f32, f32, f32); 46] = std::array::from_fn(|k| { + let u = k as f32 / 45.0 * 9.0; + let i = u.floor() as isize; + let f = u - i as f32; + let (a, bb, c, d) = (band(i - 1), band(i), band(i + 1), band(i + 2)); + // Catmull-Rom + let v = 0.5 * (2.0 * bb + (-a + c) * f + (2.0 * a - 5.0 * bb + 4.0 * c - d) * f * f + (-a + 3.0 * bb - 3.0 * c + d) * f * f * f); + (x0 + pad + u / 9.0 * (w - 2.0 * pad), y_of(v.clamp(0.0, 1.0)), v) + }); + for s in pts.windows(2) { + let v = f32::midpoint(s[0].2, s[1].2); + let c = if !on { 0x8cc3c8 } else if v > 0.62 { 0xf08a2a } else if v > 0.5 { 0xd8c83a } else if v > 0.4 { 0x3cbf6a } else { 0x18a0aa }; + p.line(&[(s[0].0, s[0].1), (s[1].0, s[1].1)], rgb(c), 2.0); + } +} + +impl Render for Amp { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + // the analyzer and the clock move while anything plays or settles + let peaks_settling = self.peaks.iter().any(|&p| p > 0.0); + if self.play != Play::Stopped || self.slide.is_some() || peaks_settling || self.frames < 90 { + w.request_animation_frame(); + } + focus_root(w, &mut self.frames); + self.fit = Fit::new(w, DESIGN); + self.tick(); + let t = now(); + let fold = if self.show_eq { 0.0 } else { EQW.1 + 6.0 }; + let app = div().class("app").css("left", rem(self.fit.ox)).css("top", rem(self.fit.oy)) + .on_mouse_down_capture(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, _, _| { + // a press on the seek bar jumps there; the drag carries on from it + let (x, y) = this.in_window(e.position, MAIN.0); + if (SEEK.x..SEEK.x + SEEK.w).contains(&x) && (SEEK.y..SEEK.y + 20.0).contains(&y) { + this.seek.set((x - SEEK.x) / SEEK.w); + this.pos = this.seek.value * this.len(); + } + })) + .child(div().class("slot").css("top", rem(MAIN.0)).child(self.main_win(cx, t))) + .child(div().class(if self.show_eq { "slot" } else { "slot gone" }).css("top", rem(EQW.0)) + .child(self.eq_win(cx).css("animation-delay", "80ms"))) + .child(div().class(if self.show_pl { "slot" } else { "slot gone" }).css("top", rem(PLW.0)) + .css("transform", format!("translateY(-{}rem)", fold / 16.0)) + .child(self.pl_win(cx).css("animation-delay", "160ms"))); + html().css("font-size", self.fit.root_font()) + .child(head().child(style().child(css()))) + .child(body().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| if this.key(&e.keystroke.key) { cx.notify() })) + .child(app)) + } +} + +/// Every control in turn. +fn storyboard(dir: String) -> Script { + story(dir, move |s| { + s.play("00-enter", &[0, 150, 300, 700]); + s.click("play"); + s.play("01-play", &[0, 500, 1500]); + s.click("presets"); + s.play("02-preset", &[0, 120, 250, 500, 1600]); + let b = s.cx.element_bounds(s.win, "band3").expect("band3"); + let x = b.origin.x + b.size.width / 2.0; + s.cx.simulate_drag(s.win, (x, b.origin.y + 50.0), (x, b.origin.y + 10.0)); + s.play("03-band-drag", &[0, 400]); + s.click("viz"); + s.play("04-scope", &[0, 300]); + s.click("viz"); + s.click("time"); + let b = s.cx.element_bounds(s.win, "seek").expect("seek"); + s.cx.simulate_click(s.win, b.origin.x + b.size.width * 0.6, b.origin.y + b.size.height / 2.0); + s.play("05-seek-remaining", &[0, 300]); + let b = s.cx.element_bounds(s.win, "volume").expect("volume"); + let y = b.origin.y + b.size.height / 2.0; + s.cx.simulate_drag(s.win, (b.origin.x + b.size.width * 0.7, y), (b.origin.x + b.size.width * 0.3, y)); + s.play("06-volume", &[0]); + s.click("r3"); + s.cx.simulate_click(s.win, x, y); + s.play("07-dblclick-row", &[0, 400]); + s.click("add"); + s.play("08-add", &[0, 100, 400]); + s.click("sort"); + s.play("09-sort", &[0]); + s.click("eqb"); + s.play("10-fold-eq", &[0, 100, 300]); + s.click("eqb"); + s.play("11-unfold-eq", &[0, 300]); + s.click("pause"); + s.play("12-pause", &[0, 300, 800]); + s.cx.simulate_key(s.win, "v", "v"); + s.play("13-stop", &[0, 600, 1500]); + }) +} + +fn main() { + let make = || Amp { + play: Play::Stopped, + cur: 2, + pos: 3.0, + last: now(), + list: START_LIST.to_vec(), + sel: 2, + added: None, + seek: Dial::new(0.0), + volume: Dial::new(0.75), + balance: Dial::new(0.5), + eq: PRESETS[3].1.map(Dial::new), + eq_on: true, + auto: false, + preset: 3, + slide: None, + show_eq: true, + show_pl: true, + remaining: false, + scope: false, + shuffle: false, + repeat: false, + bars: [0.0; BARS], + peaks: [0.0; BARS], + hold: [0.0; BARS], + fit: Fit { scale: 1.0, w: DESIGN.0, h: DESIGN.1, ox: 0.0, oy: 0.0 }, + frames: 0, + }; + run_with(DESIGN.0, DESIGN.1, "Lagoon", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/ascii.rs b/demos/src/bin/ascii.rs new file mode 100644 index 00000000..b664528b --- /dev/null +++ b/demos/src/bin/ascii.rs @@ -0,0 +1,381 @@ +//! ASCII Field: a dark engineer's portfolio over a background that answers the pointer, ported +//! from a portfolio site's hero (its WebGL "ice flow" pass and its canvas glyph field). +//! +//! The background is one GPU shader: a slow FBM scene (three layers drifting at their own speeds +//! and angles, cross-warped, vignetted, grained, in a near-black green) is sampled once per 13 px +//! cell and drawn as a 5 x 5 bitmap glyph picked by the cell's brightness. Near the pointer a halo +//! lifts the brightness, so the dim field turns into bright code around it (except in the middle, +//! where the headline sits); it eases in when the pointer arrives and out when it leaves the +//! window. Scanlines and a vignette finish it. +//! +//! Over it: cards that lift 4 px under the pointer with a 220 px green glow that follows it, and a +//! call-to-action band filled with a second, DOM-free glyph field (`Painter` text): random +//! characters that morph about once a second and brighten within 180 px of the pointer. +//! +//! Motion: the hero and the cards rise once on load (0.7 s, 90 ms apart); hover lift and glow are +//! 200 ms transitions; the glow halo follows at a frame-rate independent 0.12-per-30fps rate. +//! +//! `cargo run --release --bin ascii` +//! `-- --storyboard DIR` drives the pointer over it headlessly; `-- --frames DIR` renders the +//! background on the GPU with the pointer in a few places. + +use std::sync::OnceLock; + +use blenderui::prelude::*; +use bui_demos::canvas::{at, rem, rem_css, Fit}; +use bui_demos::ease::approach; +use bui_demos::{arg, gpu_stills, now, run_with, story::story, Fx, Script}; + +/// The glow of a card, the pointer at (`x`, `y`) in it (design px): only the card it is over draws one. +fn card_glow(x: f32, y: f32) -> Div { + let glow = div().class("glow"); + if (0.0..CARD_W).contains(&x) && (0.0..CARD_H).contains(&y) { + glow.css("background", format!("radial-gradient({} circle at {} {}, rgba(0,255,65,0.09), transparent 70%)", + rem(220.0), rem(x), rem(y))) + } else { + glow + } +} + +/// U[0] time, U[1..2] pointer (logical px in the box), U[3] glow 0..1, U[4] the box's logical width. +const FIELD: &str = r" +float hash21(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); } +float noise(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); + float a = hash21(i); float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); float d = hash21(i + vec2(1.0, 1.0)); + vec2 u = f * f * (3.0 - 2.0 * f); + return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y; +} +float fbm(vec2 p) { + float v = 0.0; float a = 0.5; + for (int i = 0; i < 5; i++) { v += a * noise(p); p *= 2.05; a *= 0.5; } + return v; +} +vec3 palette(float t) { + vec3 base = vec3(0.008, 0.016, 0.011); + vec3 mid = vec3(0.028, 0.082, 0.05); + vec3 peak = vec3(0.05, 0.14, 0.085); + float s = clamp(t, 0.0, 1.0); + return mix(base, mix(mid, peak, smoothstep(0.52, 1.0, s)), smoothstep(0.0, 0.68, s)); +} +// the scene at uv (0..1), pix (cell centre, logical px) for the grain +vec3 scene(vec2 uv, vec2 pix, float t) { + vec2 ar = vec2(box_size.x / box_size.y, 1.0); + vec2 p = (uv - 0.5) * ar; + float l1 = fbm(p * 1.7 + vec2(t * 0.032, t * 0.012)); + float l2 = fbm(p * 2.3 + vec2(-t * 0.018, t * 0.024) + vec2(3.7, 1.4)); + float warp = fbm(p * 1.4 + vec2(l1 * 1.8, l2 * 1.4) + t * 0.015); + float mixed = l1 * 0.42 + l2 * 0.32 + warp * 0.26; + mixed *= 1.0 - smoothstep(0.42, 0.92, length(p)); + mixed = clamp(mixed + (hash21(pix + vec2(t * 47.0)) - 0.5) * 0.022, 0.0, 1.0); + return palette(mixed); +} +// bit a of the 25-bit glyph n (exact in a float: n < 2^25 and even past 2^24) +float bit(float n, float a) { return mod(floor(n / exp2(a)), 2.0); } +float character(float n, vec2 p) { + p = floor(p * vec2(4.0, 4.0) + 2.5); + if (p.x < 0.0 || p.x > 4.0 || p.y < 0.0 || p.y > 4.0) return 0.0; + return bit(n, p.x + 5.0 * p.y); +} +vec4 effect(vec2 p) { + float s = box_size.x / max(U[4], 1.0); + float cell = 13.0 * s; + vec2 uv = p / box_size; + vec2 ar = vec2(box_size.x / box_size.y, 1.0); + vec2 centre = (floor(p / cell) + 0.5) * cell; + float gray = dot(scene(centre / box_size, centre / s, U[0]), vec3(0.299, 0.587, 0.114)); + float boost = 0.0; + if (U[3] > 0.001) { + vec2 m = vec2(U[1], U[2]) * s / box_size; + float halo = smoothstep(0.32, 0.0, length((uv - m) * ar)); + float fade = smoothstep(0.18, 0.42, length((uv - 0.5) * ar)); + boost = halo * U[3] * fade; + gray = clamp(gray + boost * 0.9, 0.0, 1.0); + } + float n = 0.0; + if (gray > 0.05) n = 4194304.0; + if (gray > 0.15) n = 131200.0; + if (gray > 0.25) n = 4329604.0; + if (gray > 0.35) n = 14815374.0; + if (gray > 0.45) n = 4357252.0; + if (gray > 0.55) n = 15255086.0; + if (gray > 0.65) n = 4532014.0; + if (gray > 0.75) n = 11512810.0; + if (gray > 0.85) n = 27141542.0; + float ch = character(n, mod(p, cell) / cell * 2.0 - 1.0); + vec3 green = vec3(0.180, 0.490, 0.310); + vec3 col = green * (0.55 + gray * 1.35) * ch * gray * 1.5; + col += green * boost * 0.45; + float scan = pow(sin(p.y / s * 3.14159 * 2.0) * 0.5 + 0.5, 1.5) * 0.07 * 0.15; + col -= scan; + col *= clamp(1.0 - length(uv - 0.5) * 0.28 * 1.2, 0.0, 1.0); + return vec4(max(col, vec3(0.0)), 1.0); +} +"; + +const DESIGN: (f32, f32) = (1280.0, 800.0); +/// The call-to-action band's glyph field: cells across and down, and the band (design px). +const COLS: usize = 56; +const ROWS: usize = 9; +const BAND: (f32, f32, f32, f32) = (80.0, 586.0, 1120.0, 180.0); +const GLYPHS: &[u8] = b" .:-=+*x?#@%/\\|<>{}[]()0123abcXYZ"; +/// The field's knobs, as the site's band sets them. +const DENSITY: f32 = 0.18; +const MORPH_HZ: f32 = 1.1; +const OPACITY: f32 = 0.35; +/// Within this many design px of the pointer a glyph brightens. +const REACH: f32 = 180.0; +/// The halo's follow rate: 0.12 of the way per frame at 30 fps. +const GLOW_RATE: f32 = 3.835; + +const CARDS: [(&str, &str, &str); 3] = [ + ("01", "Agent systems", "Tool-using agents with evals, tracing and a rollback plan, shipped to production instead of a demo day."), + ("02", "Realtime products", "Sync engines, presence and collaborative editing that stay under 50 ms on a bad hotel Wi-Fi."), + ("03", "Performance audits", "Two weeks, one report, a ranked list of fixes. Typical result: a 40% faster first load."), +]; +const CARD_Y: f32 = 352.0; +const CARD_W: f32 = 352.0; +const CARD_H: f32 = 190.0; +const CARD_GAP: f32 = 32.0; + +const CSS: &str = r" +html { height: 100%; background: #000; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; background: #000; color: #d7e4dc; user-select: none; + font-family: Inter, 'Segoe UI', system-ui, sans-serif; -webkit-font-smoothing: antialiased; } +.bg { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.abs { position: absolute; } +.mono { font-family: 'JetBrains Mono', Consolas, monospace; } + +.nav { left: 80px; top: 34px; width: 1120px; height: 44px; display: flex; align-items: center; justify-content: space-between; + animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.logo { font-size: 15px; font-weight: 700; letter-spacing: 0.5px; color: #e8f5ec; } +.logo b { color: #00ff41; font-weight: 700; } +.links { display: flex; gap: 6px; } +.link { height: 40px; padding: 0 14px; display: flex; align-items: center; font-size: 13px; color: #8da597; border-radius: 10px; + cursor: pointer; transition-property: color, background-color; transition-duration: 150ms; } +.link:hover { color: #e8f5ec; background: rgba(0,255,65,0.06); } + +.hero { left: 80px; top: 120px; width: 1120px; text-align: center; } +.eyebrow { font-size: 12px; letter-spacing: 2px; color: #00ff41; animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) 80ms backwards; } +.hero h1 { margin: 16px auto 0; width: 760px; font-size: 58px; line-height: 1.02; font-weight: 700; letter-spacing: -2px; color: #f2fbf5; + text-wrap: balance; animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) 160ms backwards; } +.hero p { margin: 18px auto 0; width: 560px; font-size: 16px; line-height: 1.5; color: #8da597; text-wrap: pretty; + animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) 240ms backwards; } + +.card { width: 352px; height: 190px; box-sizing: border-box; padding: 24px; border-radius: 18px; overflow: hidden; cursor: pointer; + background: rgba(10,14,12,0.78); backdrop-filter: blur(6px); + box-shadow: 0 0 0 1px rgba(255,255,255,0.08), 0 10px 30px rgba(0,0,0,0.45); + transition-property: transform, box-shadow; transition-duration: 200ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); + animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.card:hover { transform: translateY(-4px); box-shadow: 0 0 0 1px rgba(0,255,65,0.22), 0 20px 52px rgba(0,0,0,0.55); } +.card:active { transform: translateY(-4px) scale(0.96); } +/* the reference's `.hire__card:before`: a 220 px green circle at the pointer, fading out */ +.glow { position: absolute; left: 0; top: 0; width: 352px; height: 190px; opacity: 0; + transition-property: opacity; transition-duration: 200ms; } +.card:hover .glow { opacity: 1; } +.card .num { position: relative; font-size: 12px; color: #00ff41; letter-spacing: 1px; } +.card h3 { position: relative; margin: 14px 0 8px; font-size: 21px; font-weight: 650; color: #f2fbf5; letter-spacing: -0.4px; } +.card p { position: relative; margin: 0; font-size: 13.5px; line-height: 1.5; color: #8da597; text-wrap: pretty; } + +/* no overflow clip: the field keeps to its cells, and cutting its hundreds of glyphs at the rounded + corners every frame would double the page's cost */ +.band { left: 80px; top: 586px; width: 1120px; height: 180px; border-radius: 22px; background: #050806; + box-shadow: 0 0 0 1px rgba(0,255,65,0.14), 0 24px 60px rgba(0,0,0,0.6); + animation: rise 700ms cubic-bezier(0.2, 0, 0, 1) 420ms backwards; } +.field { position: absolute; left: 0; top: 0; width: 1120px; height: 180px; } +.cta { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: space-between; + padding: 0 48px; box-sizing: border-box; } +.cta h2 { margin: 0; font-size: 30px; font-weight: 700; letter-spacing: -0.8px; color: #f2fbf5; text-wrap: balance; } +.cta small { display: block; margin-top: 6px; font-size: 13px; color: #8da597; } +.btn { height: 48px; padding: 0 22px; border-radius: 12px; display: flex; align-items: center; gap: 10px; cursor: pointer; + background: #00ff41; color: #021006; font-size: 14px; font-weight: 700; + box-shadow: 0 0 0 1px rgba(0,255,65,0.5), 0 8px 30px rgba(0,255,65,0.25); + transition-property: transform, box-shadow; transition-duration: 150ms; } +.btn:hover { box-shadow: 0 0 0 1px rgba(0,255,65,0.8), 0 10px 40px rgba(0,255,65,0.45); } +.btn:active { transform: scale(0.96); } + +@keyframes rise { from { opacity: 0; transform: translateY(18px); } to { opacity: 1; transform: translateY(0); } } +"; + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +struct Ascii { + field: Fx, + /// The pointer in window px, and whether it is in the window (the halo's target). + pointer: (f32, f32), + inside: bool, + /// The halo, easing towards `inside`. + glow: f32, + last: f32, + /// The band's glyphs: an index into `GLYPHS`, or -1 for none. + glyphs: [i8; COLS * ROWS], + morphed: f32, + seed: u32, +} + +impl Ascii { + fn new() -> Self { + let mut a = Self { field: field(), pointer: (-1e4, -1e4), inside: false, glow: 0.0, last: now(), glyphs: [-1; COLS * ROWS], + morphed: now(), seed: 0x9e37_79b9 }; + for i in 0..a.glyphs.len() { + a.glyphs[i] = if a.rand() < DENSITY { a.pick() } else { -1 }; + } + a + } + + /// xorshift32: 0..1. + fn rand(&mut self) -> f32 { + let mut x = self.seed; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self.seed = x; + (x >> 8) as f32 / (1u32 << 24) as f32 + } + + fn pick(&mut self) -> i8 { + ((self.rand() * GLYPHS.len() as f32) as usize).min(GLYPHS.len() - 1) as i8 + } + + /// The field's morph: a few cells appear, change or go out (the glyph field step of the reference). + fn morph(&mut self) { + let n = ((self.glyphs.len() as f32 * 0.004) as usize).max(4); + for _ in 0..n { + let i = ((self.rand() * self.glyphs.len() as f32) as usize).min(self.glyphs.len() - 1); + self.glyphs[i] = if self.glyphs[i] < 0 { + if self.rand() < DENSITY { self.pick() } else { -1 } + } else if self.rand() < 0.18 { + -1 + } else { + self.pick() + }; + } + } +} + +/// The band's glyph field painted into `b`: each glyph's alpha rises near `pointer` (window px). +fn paint_field(b: Bounds, p: &mut Painter, glyphs: &[i8; COLS * ROWS], pointer: (f32, f32), reach: f32) { + let cell = b.size.width / COLS as f32; + let reach2 = reach * reach; + for (i, &g) in glyphs.iter().enumerate() { + if g < 0 { + continue; + } + let (col, row) = (i % COLS, i / COLS); + // clear of the copy and the button (the reference's exclusion ellipses), fading in past them + let e = clear_of_copy((col as f32 + 0.5) / COLS as f32, (row as f32 + 0.5) / ROWS as f32); + if e < 0.78 || ((col == 0 || col == COLS - 1) && (row == 0 || row == ROWS - 1)) { + continue; + } + let edge = ((e - 0.78) / 0.32).min(1.0); + let (x, y) = (b.origin.x + col as f32 * cell, b.origin.y + row as f32 * cell); + let (dx, dy) = (x + cell * 0.5 - pointer.0, y + cell * 0.5 - pointer.1); + let d2 = dx * dx + dy * dy; + let a = edge * if d2 < reach2 { (OPACITY + (1.0 - d2 / reach2) * 0.65).min(1.0) } else { OPACITY }; + let k = g as usize; + // SAFETY of the slice: GLYPHS is ASCII, so every byte is a char boundary + let s = std::str::from_utf8(&GLYPHS[k..=k]).unwrap_or(" "); + p.text(x, y, s, cell * 0.85, Rgba { r: 0.0, g: 1.0, b: 0.255, a }); + } +} + +/// How far (u, v) in the band (0..1) is outside the ellipses round its heading and its button: +/// below 1 inside one. +fn clear_of_copy(u: f32, v: f32) -> f32 { + let ellipse = |cx: f32, cy: f32, rx: f32, ry: f32| (((u - cx) / rx).powi(2) + ((v - cy) / ry).powi(2)).sqrt(); + ellipse(0.27, 0.5, 0.29, 0.5).min(ellipse(0.885, 0.5, 0.12, 0.42)) +} + +impl Render for Ascii { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + let fit = Fit::new(w, DESIGN); + let t = now(); + self.glow = approach(self.glow, if self.inside { 1.0 } else { 0.0 }, GLOW_RATE, (t - self.last).clamp(0.0, 0.1)); + self.last = t; + if t - self.morphed > 1.0 / MORPH_HZ { + self.morphed = t; + self.morph(); + } + + let (glow, pointer) = (self.glow, self.pointer); + let bg = self.field.canvas(move |b| { + [now(), pointer.0 - b.origin.x, pointer.1 - b.origin.y, glow, b.size.width] + }).class("bg"); + + // the pointer in design px, for the card glows + let (dx, dy) = (pointer.0 / fit.scale - fit.ox, pointer.1 / fit.scale - fit.oy); + let mut page = at(div(), fit.ox, fit.oy).css("width", rem(DESIGN.0)).css("height", rem(DESIGN.1)) + .child(at(div().class("nav"), 80.0, 34.0) + .child(div().class("logo mono").child("kai").child(b().child(".")).child("vance")) + .child(div().class("links") + .child(div().class("link").child("Work")).child(div().class("link").child("Writing")) + .child(div().class("link").child("Stack")).child(div().class("link").child("Contact")))) + .child(at(div().class("hero"), 80.0, 120.0) + .child(div().class("eyebrow mono").child("> AI FULLSTACK ENGINEER · PORTO · REMOTE")) + .child(h1().child("I build agent systems that actually ship.")) + .child(p().child("Twelve years of product engineering. Now: agents, realtime sync and the boring infrastructure that keeps both alive at 3 a.m."))); + for (i, (num, title, body)) in CARDS.iter().enumerate() { + let x = 80.0 + i as f32 * (CARD_W + CARD_GAP); + page = page.child(at(div().id(format!("card{i}")).class("card"), x, CARD_Y) + .css("animation-delay", format!("{}ms", 100 + i * 90)) + .child(card_glow(dx - x, dy - CARD_Y)) + .child(div().class("num mono").child(*num)) + .child(h3().child(*title)) + .child(p().child(*body))); + } + let glyphs = self.glyphs; + let reach = REACH * fit.scale; + page = page.child(at(div().id("band").class("band"), BAND.0, BAND.1) + .child(canvas(move |b, p| paint_field(b, p, &glyphs, pointer, reach)).class("field")) + .child(div().class("cta") + .child(div().child(h2().child("Have something hard? Let's build it.")).child(small().child("Two slots open for Q1 · replies within a day"))) + .child(div().id("cta").class("btn").child("Start a project").child(span().child("→"))))); + + html().css("font-size", fit.root_font()) + .child(head().child(style().child(css()))) + .child(body() + .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, _| { + this.pointer = (e.position.x.0, e.position.y.0); + this.inside = true; + })) + .on_mouse_leave(cx.listener(|this, _: &MouseMoveEvent, _, _| this.inside = false)) + .child(bg).child(page)) + } +} + +fn field() -> Fx { + Fx::new("ascii-field", FIELD, 5, [2, 6, 4]) +} + +/// The pointer over a card, across the band, then out of the window. +fn storyboard(dir: String) -> Script { + story(dir, move |s| { + s.play("00-enter", &[0, 200, 500, 1000]); + let (x, y) = s.centre("card1"); + s.cx.simulate_mouse_move(s.win, x - 60.0, y - 30.0); + s.play("01-card", &[0, 250]); + let (x, y) = s.centre("band"); + s.cx.simulate_mouse_move(s.win, x - 200.0, y); + s.play("02-band", &[0, 1200]); + s.hover("cta"); + s.play("03-cta", &[0, 200]); + }) +} + +fn main() { + if let Some(dir) = arg("--frames") { + let fx = field(); + let stills = [("rest", [6.0f32, 640.0, 400.0, 0.0, 1280.0]), ("glow-left", [6.0, 260.0, 300.0, 1.0, 1280.0]), + ("glow-right", [9.0, 1050.0, 620.0, 1.0, 1280.0]), ("glow-centre", [9.0, 640.0, 400.0, 1.0, 1280.0])]; + if gpu_stills(&dir, 1280, 800, stills, |g, f| g.draw(fx.effect(), &[], f)).is_none() { + eprintln!("field shader: {:?}", fx.error()); + } + return; + } + run_with(DESIGN.0, DESIGN.1, "BUI · ASCII Field", Ascii::new, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/bui_calendar.rs b/demos/src/bin/bui_calendar.rs new file mode 100644 index 00000000..02ad64f0 --- /dev/null +++ b/demos/src/bin/bui_calendar.rs @@ -0,0 +1,1314 @@ +//! BUI Calendar: a scheduling app made of Blender's UI. The window is a Blender screen: a Calendar +//! editor (week, day, month or agenda; a header with the view, navigation, search and time zone; a +//! toolbar region with a mini month and the calendars; an event editor in its sidebar) beside a +//! Day editor showing the selected day. Split, join or swap the areas as in Blender. +//! +//! Week and day views: drag on empty time to create an event, drag an event to move it (to another +//! day too), drag its bottom edge to resize it, click it to edit it in the sidebar. Overlapping +//! events share the column side by side. The month view: drag an event's chip onto another day, +//! double-click a day to add an event. The editor is Blender widgets: a title text field, a start +//! and a duration you drag or type math into (`1.5*60`), a calendar dropdown, an all-day and a +//! repeat-weekly checkbox with a count, notes in a text area. Calendars show and hide with their +//! checkboxes and recolor with Blender's color picker. Times follow the time-zone dropdown. A red +//! line marks now, moving by itself (a CSS animation: nothing renders while you wait). +//! +//! Keys: T today, ← / → previous / next, D W M A the views, Delete the selected event, Ctrl+D +//! duplicate, Ctrl+Z / Ctrl+Y undo / redo, Esc deselect. +//! +//! `cargo run --release --bin bui_calendar`, `-- --storyboard DIR` drives it headlessly. + +use std::fmt::Write as _; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use blenderui::prelude::*; +use blenderui::screen::{AreaRef, AreaSplit, Editor, Editors, Region, Screen}; +use bui_demos::story::story; +use bui_demos::{arg, focus_root, now, run_with, size_arg, Script}; +use bui_demos::color::hex; + +/// Pixels per hour in the time grid. +const HOUR_H: f32 = 44.0; +const SNAP: i64 = 15; +const DAY_MIN: i64 = 1440; +const GUTTER: f32 = 52.0; +const UNDO: usize = 200; + +// ------------------------------------------------------------------------------------------------ +// Dates: days since 1970-01-01 (Howard Hinnant's civil algorithms) + +const fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +const fn civil(z: i64) -> (i64, i64, i64) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// 0 Monday … 6 Sunday. +const fn weekday(z: i64) -> i64 { + (z + 3).rem_euclid(7) +} + +const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", + "October", "November", "December"]; +const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + +const fn month_start(z: i64) -> i64 { + let (y, m, _) = civil(z); + days_from_civil(y, m, 1) +} + +fn add_months(z: i64, n: i64) -> i64 { + let (y, m, d) = civil(z); + let k = y * 12 + (m - 1) + n; + let (ny, nm) = (k.div_euclid(12), k.rem_euclid(12) + 1); + let last = days_from_civil(ny + i64::from(nm == 12), if nm == 12 { 1 } else { nm + 1 }, 1) - days_from_civil(ny, nm, 1); + days_from_civil(ny, nm, d.min(last)) +} + +fn clock(min: i64) -> String { + let m = min.rem_euclid(DAY_MIN); + format!("{:02}:{:02}", m / 60, m % 60) +} + +fn date_label(z: i64) -> String { + let (_, m, d) = civil(z); + format!("{} {} {d}", DAYS[weekday(z) as usize], &MONTHS[(m - 1) as usize][..3]) +} + +/// Time zones: a name and the minutes from UTC. +const ZONES: [(&str, i64); 7] = [("UTC", 0), ("Los Angeles (UTC−8)", -480), ("New York (UTC−5)", -300), ("London (UTC+0)", 0), + ("Berlin (UTC+1)", 60), ("Delhi (UTC+5:30)", 330), ("Tokyo (UTC+9)", 540)]; + +// ------------------------------------------------------------------------------------------------ +// The data + +#[derive(Clone, PartialEq, Debug)] +struct Event { + id: u32, + cal: usize, + title: String, + notes: String, + /// Minutes since the epoch, UTC. + start: i64, + dur: i64, + all_day: bool, + /// Weekly occurrences in all (1: once). + repeat: u32, +} + +#[derive(Clone, PartialEq, Debug)] +struct Cal { + name: &'static str, + color: u32, + shown: bool, +} + +#[derive(Clone)] +struct Data { + events: Vec, + cals: Vec, + next_id: u32, +} + +/// One occurrence of an event, in the view's time zone: its local start and which repeat it is. +#[derive(Clone, Copy)] +struct Occ { + idx: usize, + start: i64, + dur: i64, + k: u32, +} + +impl Data { + fn find(&self, id: u32) -> Option { + self.events.iter().position(|e| e.id == id) + } + + /// The occurrences shown between local days `from` and `to` (exclusive), in zone `tz`. + fn occurrences(&self, from: i64, to: i64, tz: i64, filter: &str) -> Vec { + let lo = from * DAY_MIN; + let hi = to * DAY_MIN; + let q = filter.trim().to_lowercase(); + let mut out = Vec::new(); + for (idx, e) in self.events.iter().enumerate() { + if !self.cals.get(e.cal).is_some_and(|c| c.shown) { + continue; + } + if !q.is_empty() && !e.title.to_lowercase().contains(&q) && !e.notes.to_lowercase().contains(&q) { + continue; + } + for k in 0..e.repeat.max(1) { + let start = e.start + tz + i64::from(k) * 7 * DAY_MIN; + if start < hi && start + e.dur.max(1) > lo { + out.push(Occ { idx, start, dur: e.dur, k }); + } + } + } + out.sort_by_key(|o| (o.start, -o.dur)); + out + } +} + +/// Side-by-side columns for overlapping events: (column, columns in its cluster) per occurrence. +fn columns(occ: &[Occ]) -> Vec<(usize, usize)> { + let mut out = vec![(0, 1); occ.len()]; + let mut cluster: Vec = Vec::new(); + let mut ends: Vec = Vec::new(); + let mut cluster_end = i64::MIN; + let close = |cluster: &mut Vec, ends: &mut Vec, out: &mut Vec<(usize, usize)>| { + let n = ends.len().max(1); + for &i in cluster.iter() { + out[i].1 = n; + } + cluster.clear(); + ends.clear(); + }; + for (i, o) in occ.iter().enumerate() { + if o.start >= cluster_end && !cluster.is_empty() { + close(&mut cluster, &mut ends, &mut out); + } + let end = o.start + o.dur.max(SNAP); + let col = ends.iter().position(|&e| e <= o.start).unwrap_or(ends.len()); + if col == ends.len() { + ends.push(end); + } else { + ends[col] = end; + } + out[i].0 = col; + cluster.push(i); + cluster_end = cluster_end.max(end); + } + close(&mut cluster, &mut ends, &mut out); + out +} + +fn seed(today: i64) -> Data { + let cals = vec![ + Cal { name: "Work", color: 0x4772b3, shown: true }, + Cal { name: "Personal", color: 0x5aa85a, shown: true }, + Cal { name: "Renders", color: 0xe0913a, shown: true }, + Cal { name: "Holidays", color: 0x9b6bd1, shown: true }, + ]; + let monday = today - weekday(today); + let mut events = Vec::new(); + let mut id = 1; + let mut add = |cal: usize, title: &str, day: i64, h: f64, dur: i64, repeat: u32, notes: &str| { + events.push(Event { id, cal, title: title.into(), notes: notes.into(), start: day * DAY_MIN + (h * 60.0) as i64, + dur, all_day: false, repeat }); + id += 1; + }; + for d in 0..5 { + add(0, "Stand-up", monday + d, 9.5, 15, 3, if d == 0 { "Yesterday, today, blockers." } else { "" }); + } + add(0, "Layout review: shot 12", monday + 1, 11.0, 60, 1, "Bring the animatic."); + add(0, "Lighting pass", monday + 1, 11.5, 90, 1, "Overlaps the review: shows side by side."); + add(1, "Lunch with Ada", monday + 2, 12.5, 60, 1, "The ramen place."); + add(2, "Farm: final frames", monday + 2, 14.0, 240, 1, "Shots 10 to 14, 4K, 240 frames each."); + add(0, "Client call", monday + 3, 16.0, 45, 1, "Little Moth Studio, the teaser."); + add(1, "Climbing", monday + 1, 18.5, 90, 4, "Bring chalk."); + add(1, "Climbing", monday + 3, 18.5, 90, 4, ""); + add(0, "Sprint planning", monday + 4, 10.0, 120, 1, ""); + add(2, "Farm: lookdev batch", monday + 4, 13.0, 60, 1, ""); + add(1, "Market", monday + 5, 10.0, 90, 1, ""); + add(0, "Retro", monday + 11, 15.0, 60, 1, ""); + add(2, "Farm: trailer", monday + 9, 9.0, 300, 1, ""); + let mut data = Data { events, cals, next_id: id }; + let all_day = |data: &mut Data, cal: usize, title: &str, day: i64| { + let id = data.next_id; + data.next_id += 1; + data.events.push(Event { id, cal, title: title.into(), notes: String::new(), start: day * DAY_MIN, dur: DAY_MIN, + all_day: true, repeat: 1 }); + }; + all_day(&mut data, 3, "Studio offsite", monday + 4); + all_day(&mut data, 3, "Long weekend", monday + 12); + data +} + +// ------------------------------------------------------------------------------------------------ +// The app + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum View { + Day, + Week, + Month, + Agenda, +} + +const VIEWS: [(&str, View, &str); 4] = [("Day", View::Day, "D"), ("Week", View::Week, "W"), ("Month", View::Month, "M"), + ("Agenda", View::Agenda, "A")]; + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Drag { + /// On empty time: from and to (local minutes). + Create { from: i64, to: i64 }, + /// An event: where it was grabbed (minutes into it) and its local start now. + Move { id: u32, grab: i64, at: i64, moved: bool }, + Resize { id: u32, end: i64 }, + /// A month chip: the event and the day it is over. + Chip { id: u32, day: i64 }, +} + +#[derive(Clone)] +struct Ui { + view: View, + /// The selected day (local). + day: i64, + today: i64, + sel: Option, + drag: Option, + search: String, + tz: usize, + status: String, + /// Bumped by each new event: keys its pop-in. + born: u32, +} + +struct CalApp { + data: Arc, + ui: Ui, + undo: Vec>, + redo: Vec>, + frames: u32, + /// The wall clock's day minute when the app began (the now line runs on from it). + start_minute: i64, +} + +struct Snap { + data: Arc, + ui: Ui, + weak: WeakEntity, + now_min: i64, +} + +impl CalApp { + fn new() -> Self { + let wall = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs().cast_signed() / 60); + let today = wall.div_euclid(DAY_MIN); + Self { + data: Arc::new(seed(today)), + ui: Ui { view: View::Week, day: today, today, sel: None, drag: None, search: String::new(), tz: 0, + status: "Drag on empty time to add an event".into(), born: 0 }, + undo: Vec::new(), + redo: Vec::new(), + frames: 0, + start_minute: wall, + } + } + + const fn tz(&self) -> i64 { + ZONES[self.ui.tz].1 + } + + fn change(&mut self, what: &str, f: impl FnOnce(&mut Data)) { + self.undo.push(self.data.clone()); + if self.undo.len() > UNDO { + self.undo.remove(0); + } + self.redo.clear(); + f(Arc::make_mut(&mut self.data)); + self.ui.status = what.to_string(); + } + + fn undo(&mut self) -> bool { + let Some(prev) = self.undo.pop() else { return false }; + self.redo.push(std::mem::replace(&mut self.data, prev)); + self.ui.status = "Undo".into(); + self.fix_sel(); + true + } + + fn redo(&mut self) -> bool { + let Some(next) = self.redo.pop() else { return false }; + self.undo.push(std::mem::replace(&mut self.data, next)); + self.ui.status = "Redo".into(); + self.fix_sel(); + true + } + + fn fix_sel(&mut self) { + if self.ui.sel.is_some_and(|id| self.data.find(id).is_none()) { + self.ui.sel = None; + } + } + + fn edit(&mut self, what: &str, f: impl FnOnce(&mut Event)) { + let Some(i) = self.ui.sel.and_then(|id| self.data.find(id)) else { return }; + self.change(what, |d| f(&mut d.events[i])); + } + + /// A new event at local minute `start` for `dur`, selected. + fn create(&mut self, start: i64, dur: i64, all_day: bool) { + let id = self.data.next_id; + let tz = self.tz(); + let cal = self.ui.sel.and_then(|s| self.data.find(s)).map_or(0, |i| self.data.events[i].cal); + self.change("Event added", |d| { + d.next_id += 1; + d.events.push(Event { id, cal, title: "New event".into(), notes: String::new(), start: start - tz, dur: dur.max(SNAP), + all_day, repeat: 1 }); + }); + self.ui.sel = Some(id); + self.ui.born = id; + self.ui.day = start.div_euclid(DAY_MIN); + } + + fn delete(&mut self) -> bool { + let Some(id) = self.ui.sel else { return false }; + let Some(i) = self.data.find(id) else { return false }; + let title = self.data.events[i].title.clone(); + self.change(&format!("Deleted “{title}”"), |d| { + d.events.remove(i); + }); + self.ui.sel = None; + true + } + + fn duplicate(&mut self) -> bool { + let Some(i) = self.ui.sel.and_then(|id| self.data.find(id)) else { return false }; + let id = self.data.next_id; + self.change("Duplicated", |d| { + let mut e = d.events[i].clone(); + e.id = id; + e.start += 60; + d.next_id += 1; + d.events.push(e); + }); + self.ui.sel = Some(id); + self.ui.born = id; + true + } + + /// The days the main view's period moves by. + const fn period(&self) -> i64 { + match self.ui.view { + View::Day => 1, + View::Week | View::Agenda => 7, + View::Month => 0, + } + } + + fn step(&mut self, dir: i64) { + self.ui.day = if self.ui.view == View::Month { add_months(self.ui.day, dir) } else { self.ui.day + dir * self.period() }; + } + + fn key(&mut self, e: &KeyDownEvent) -> bool { + let k = &e.keystroke; + let ctrl = k.modifiers.control; + match (k.key.as_str(), ctrl) { + ("z" | "Z", true) => return self.undo(), + ("y" | "Y", true) => return self.redo(), + ("d" | "D", true) => return self.duplicate(), + ("t" | "T", false) => { + self.ui.day = self.ui.today; + self.ui.status = "Today".into(); + } + ("Left", _) => self.step(-1), + ("Right", _) => self.step(1), + ("Delete" | "BackSpace", _) => return self.delete(), + ("Escape", _) => { + self.ui.sel = None; + self.ui.drag = None; + } + (key, false) => match VIEWS.iter().find(|v| v.2.eq_ignore_ascii_case(key)) { + Some(v) => self.ui.view = v.1, + None => return false, + }, + _ => return false, + } + true + } + + /// A drag let go. + fn release(&mut self) -> bool { + let Some(d) = self.ui.drag.take() else { return false }; + let tz = self.tz(); + match d { + Drag::Create { from, to } => { + let (a, b) = (from.min(to), from.max(to)); + self.create(a, (b - a).max(30), false); + } + Drag::Move { id, at, moved, .. } => { + if moved && let Some(i) = self.data.find(id) { + let start = at - tz; + if self.data.events[i].start != start { + self.change(&format!("Moved to {} {}", date_label(at.div_euclid(DAY_MIN)), clock(at)), |d| d.events[i].start = start); + } + } + } + Drag::Resize { id, end } => { + if let Some(i) = self.data.find(id) { + let local_start = self.data.events[i].start + tz; + let dur = (end - local_start).max(SNAP); + if dur != self.data.events[i].dur { + self.change(&format!("Now {dur} min"), |d| d.events[i].dur = dur); + } + } + } + Drag::Chip { id, day } => { + if let Some(i) = self.data.find(id) { + let local = self.data.events[i].start + tz; + let start = day * DAY_MIN + local.rem_euclid(DAY_MIN) - tz; + if start != self.data.events[i].start { + self.change(&format!("Moved to {}", date_label(day)), |d| d.events[i].start = start); + } + } + } + } + true + } +} + +/// The local minute at window y in the time grid of day `day` whose top is `top`. +fn minute_at(day: i64, top: f32, y: f32) -> i64 { + let m = ((y - top) / HOUR_H * 60.0) as i64; + day * DAY_MIN + (m.div_euclid(SNAP) * SNAP).clamp(0, DAY_MIN - SNAP) +} + + +const CSS: &str = r" +.scr { width: 100vw; height: 100vh; } +bui-region { background: #303030; } +bui-region[region=sidebar] { background: #2b2b2b; border-left: 1px solid #1f1f1f; overflow-y: auto; } +bui-region[region=toolbar] { background: #2b2b2b; border-right: 1px solid #1f1f1f; overflow-y: auto; } +bui-region[region=footer] { background: #2e2e2e; border-top: 1px solid #1f1f1f; } +.hdr { display: flex; align-items: center; gap: 6px; height: 100%; padding: 0 8px; white-space: nowrap; } +.hdr .title { font-size: 15px; font-weight: 700; color: #ececec; min-width: 190px; margin: 0 6px; font-variant-numeric: tabular-nums; } +.hdr .sep { width: 1px; height: 16px; background: #4a4a4a; margin: 0 4px; } +.hdr .lbl { color: #9a9a9a; font-size: 11px; } +.foot { display: flex; align-items: center; height: 100%; padding: 0 10px; font-size: 12px; color: #a8a8a8; gap: 14px; } +.foot .st { color: #8cb4ff; } +.view { display: flex; flex-direction: column; height: 100%; background: #262626; user-select: none; } +.dayhead { display: flex; flex-shrink: 0; border-bottom: 1px solid #1d1d1d; background: #2e2e2e; } +.dayhead .gut { width: 52px; flex-shrink: 0; font-size: 10px; color: #8a8a8a; text-align: center; padding-top: 6px; } +.dh { flex: 1; padding: 5px 8px; font-size: 12px; color: #b6b6b6; cursor: pointer; border-left: 1px solid #222; + transition-property: background-color; transition-duration: 120ms; } +.dh:hover { background: #363636; } +.dh .n { font-size: 18px; font-weight: 700; color: #e6e6e6; font-variant-numeric: tabular-nums; } +.dh.today .n { color: #ff6a5e; } +.dh.sel { background: #34405a; } +.allday { display: flex; flex-shrink: 0; min-height: 26px; border-bottom: 1px solid #1d1d1d; background: #2a2a2a; } +.allday .gut { width: 52px; flex-shrink: 0; font-size: 10px; color: #8a8a8a; text-align: center; line-height: 26px; } +.ad { flex: 1; padding: 2px 3px; border-left: 1px solid #222; display: flex; flex-direction: column; gap: 2px; } +.body { flex: 1; overflow-y: scroll; position: relative; } +.tgrid { position: relative; display: flex; height: 1056px; } +.hours { width: 52px; flex-shrink: 0; position: relative; } +.hl { position: absolute; right: 6px; font-size: 10px; color: #8a8a8a; font-variant-numeric: tabular-nums; } +.line { position: absolute; left: 52px; right: 0px; height: 1px; background: #333333; } +.line.half { background: #2c2c2c; } +.col { flex: 1; position: relative; border-left: 1px solid #222; } +.col.today { background: rgba(255,106,94,0.035); } +.ev { position: absolute; border-radius: 5px; padding: 3px 6px; font-size: 11px; color: #ffffff; overflow: hidden; + box-sizing: border-box; cursor: grab; box-shadow: 0 1px 2px rgba(0,0,0,0.35); + transition-property: opacity, box-shadow; transition-duration: 120ms; } +.ev:hover { box-shadow: 0 2px 8px rgba(0,0,0,0.45); } +.ev .t { font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.ev .w { opacity: 0.85; font-variant-numeric: tabular-nums; white-space: nowrap; } +.ev.sel { box-shadow: 0 0 0 2px #ffffff, 0 4px 14px rgba(0,0,0,0.5); } +.ev.ghost { opacity: 0.55; } +.ev.born { animation: pop 260ms cubic-bezier(0.2, 0, 0, 1); } +.grip { position: absolute; left: 0px; right: 0px; bottom: 0px; height: 7px; cursor: ns-resize; } +.newbox { position: absolute; left: 2px; right: 2px; border-radius: 5px; background: rgba(140,180,255,0.35); + border: 1px dashed #9cc0ff; font-size: 11px; color: #ffffff; padding: 3px 6px; box-sizing: border-box; pointer-events: none; } +.now { position: absolute; left: 0px; right: 0px; height: 2px; background: #ff5a4e; pointer-events: none; } +.now::before { content: ''; position: absolute; left: -5px; top: -4px; width: 10px; height: 10px; border-radius: 5px; background: #ff5a4e; } +.chip { border-radius: 4px; padding: 1px 6px; font-size: 11px; color: #ffffff; white-space: nowrap; overflow: hidden; + text-overflow: ellipsis; cursor: grab; transition-property: opacity; transition-duration: 120ms; } +.chip.sel { box-shadow: 0 0 0 2px #ffffff; } +.chip.ghost { opacity: 0.45; } +.month { flex: 1; display: grid; grid-template-columns: repeat(7, 1fr); grid-template-rows: 28px repeat(6, 1fr); } +.mh { font-size: 11px; color: #8a8a8a; padding: 6px 8px; border-bottom: 1px solid #1d1d1d; } +.md { border-left: 1px solid #222; border-bottom: 1px solid #222; padding: 4px; display: flex; flex-direction: column; + gap: 2px; overflow: hidden; transition-property: background-color; transition-duration: 100ms; } +.md:hover { background: #2c2c2c; } +.md.out { color: #5e5e5e; } +.md.sel { background: #34405a; } +.md.drop { background: #3b4a63; } +.md .n { font-size: 12px; color: #c8c8c8; font-variant-numeric: tabular-nums; } +.md.out .n { color: #6a6a6a; } +.md.today .n { color: #ffffff; background: #ff5a4e; border-radius: 9px; padding: 0 6px; align-self: flex-start; } +.more { font-size: 10px; color: #9a9a9a; padding-left: 4px; } +.agenda { flex: 1; overflow-y: scroll; padding: 10px 14px; } +.ag-day { font-size: 12px; font-weight: 700; color: #8cb4ff; margin: 12px 0 4px; } +.ag { display: flex; align-items: center; gap: 10px; padding: 6px 8px; border-radius: 4px; font-size: 12px; cursor: pointer; + transition-property: background-color; transition-duration: 100ms; } +.ag:hover { background: #333333; } +.ag.sel { background: #34405a; } +.ag .dot { width: 9px; height: 9px; border-radius: 5px; flex-shrink: 0; } +.ag .tm { width: 96px; color: #a8a8a8; font-variant-numeric: tabular-nums; } +.ag .nt { color: #8a8a8a; margin-left: auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 40%; } +.empty { color: #8a8a8a; padding: 24px; text-align: center; } +.tools { padding: 8px; font-size: 12px; } +.mini { display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; margin: 6px 0 12px; } +.mini .h { font-size: 9px; color: #7a7a7a; text-align: center; } +.mini .d { font-size: 11px; text-align: center; line-height: 22px; border-radius: 11px; cursor: pointer; color: #c8c8c8; + font-variant-numeric: tabular-nums; transition-property: background-color; transition-duration: 100ms; } +.mini .d:hover { background: #3d3d3d; } +.mini .d.out { color: #5a5a5a; } +.mini .d.busy { font-weight: 700; color: #ffffff; } +.mini .d.sel { background: #4772b3; color: #ffffff; } +.mini .d.today { box-shadow: inset 0 0 0 1px #ff5a4e; } +.mhead { display: flex; align-items: center; justify-content: space-between; font-weight: 700; color: #dedede; } +.mhead .arrow { width: 26px; text-align: center; cursor: pointer; color: #aaaaaa; border-radius: 4px; line-height: 22px; } +.mhead .arrow:hover { background: #3d3d3d; } +.calrow { display: flex; align-items: center; gap: 6px; margin: 5px 0; } +.calrow .nm { flex: 1; } +.side { padding: 8px; font-size: 12px; } +.side details { margin-bottom: 6px; } +.row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 5px 0; } +.row .k { color: #9a9a9a; flex-shrink: 0; } +.hint { color: #8a8a8a; text-wrap: pretty; margin: 10px 2px; line-height: 1.45; } +.colorbar { height: 4px; border-radius: 2px; margin: 2px 0 8px; } +@keyframes pop { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } } +@keyframes fall { from { transform: translateY(0px); } to { transform: translateY(var(--fall)); } } +"; + +impl Snap { + const fn tz(&self) -> i64 { + ZONES[self.ui.tz].1 + } + + fn color_of(&self, e: &Event) -> u32 { + self.data.cals.get(e.cal).map_or(0x666666, |c| c.color) + } + + /// The days the main view shows in its time grid. + fn week_days(&self) -> Vec { + if self.ui.view == View::Day { + vec![self.ui.day] + } else { + let mon = self.ui.day - weekday(self.ui.day); + (mon..mon + 7).collect() + } + } + + fn title(&self) -> String { + let (y, m, d) = civil(self.ui.day); + match self.ui.view { + View::Day => format!("{} {d} {} {y}", DAYS[weekday(self.ui.day) as usize], MONTHS[(m - 1) as usize]), + View::Month => format!("{} {y}", MONTHS[(m - 1) as usize]), + View::Week | View::Agenda => { + let mon = self.ui.day - weekday(self.ui.day); + let (_, m1, d1) = civil(mon); + let (y2, m2, d2) = civil(mon + 6); + if m1 == m2 { + format!("{} {d1}–{d2}, {y2}", &MONTHS[(m1 - 1) as usize][..3]) + } else { + format!("{} {d1} – {} {d2}, {y2}", &MONTHS[(m1 - 1) as usize][..3], &MONTHS[(m2 - 1) as usize][..3]) + } + } + } + } + + /// A time grid of `days` (the week and day views), `tag` keeping its element ids its own. + fn time_grid(&self, days: &[i64], tag: &'static str) -> Div { + let w = self.weak; + let tz = self.tz(); + let (lo, hi) = (days[0], days[days.len() - 1] + 1); + let occ = self.data.occurrences(lo, hi, tz, &self.ui.search); + // the day heads + let mut head = div().class("dayhead").child(div().class("gut").child(ZONES[self.ui.tz].0.split(' ').next().unwrap_or(""))); + let mut allday = div().class("allday").child(div().class("gut").child("all day")); + for &d in days { + let (_, _, dn) = civil(d); + let mut cls = String::from("dh"); + if d == self.ui.today { + cls.push_str(" today"); + } + if d == self.ui.day && days.len() > 1 { + cls.push_str(" sel"); + } + head = head.child(div().id(format!("{tag}dh{d}")).class(cls).child(DAYS[weekday(d) as usize]) + .child(div().class("n").child(dn.to_string())) + .on_click(w.listener(move |this: &mut CalApp, ev: &ClickEvent, _, cx| { + this.ui.day = d; + if ev.click_count() > 1 { + this.ui.view = View::Day; + } + cx.notify(); + }))); + let mut cell = div().class("ad"); + for o in occ.iter().filter(|o| self.data.events[o.idx].all_day && o.start.div_euclid(DAY_MIN) == d) { + cell = cell.child(self.chip(o, tag)); + } + allday = allday.child(cell); + } + // the grid: hours, lines, the columns with their events + let mut hours = div().class("hours"); + let mut grid = div().id(format!("{tag}grid")).class("tgrid"); + for h in 0..24 { + let y = h as f32 * HOUR_H; + if h > 0 { + hours = hours.child(div().class("hl").css("top", format!("{}px", y - 7.0)).child(format!("{h:02}:00"))); + } + grid = grid.child(div().class("line").css("top", format!("{y}px"))) + .child(div().class("line half").css("top", format!("{}px", y + HOUR_H / 2.0))); + } + grid = grid.child(hours); + let now_local = self.now_min + tz; + for (ci, &d) in days.iter().enumerate() { + let col_id = format!("{tag}col{d}"); + let mut col = div().id(col_id.clone()).class(if d == self.ui.today { "col today" } else { "col" }); + let day_occ: Vec = occ.iter().copied() + .filter(|o| !self.data.events[o.idx].all_day && o.start.div_euclid(DAY_MIN) == d).collect(); + let cols = columns(&day_occ); + for (o, (c, n)) in day_occ.iter().zip(cols) { + col = col.child(self.block(*o, (c, n), tag, d)); + } + // the drag being made + if let Some(Drag::Create { from, to }) = self.ui.drag + && from.div_euclid(DAY_MIN) == d + { + let (a, b) = (from.min(to), from.max(to).max(from.min(to) + SNAP)); + let top = (a - d * DAY_MIN) as f32 / 60.0 * HOUR_H; + let h = (b - a) as f32 / 60.0 * HOUR_H; + col = col.child(div().class("newbox").css("top", format!("{top}px")).css("height", format!("{h}px")) + .child(format!("{} – {}", clock(a), clock(b)))); + } + // a moving event's ghost on the day it is over + if let Some(Drag::Move { id, at, moved: true, .. }) = self.ui.drag + && at.div_euclid(DAY_MIN) == d + && let Some(i) = self.data.find(id) + { + let e = &self.data.events[i]; + let top = (at - d * DAY_MIN) as f32 / 60.0 * HOUR_H; + col = col.child(div().class("ev ghost").css("left", "2px").css("right", "2px") + .css("top", format!("{top}px")).css("height", format!("{}px", (e.dur as f32 / 60.0 * HOUR_H).max(18.0))) + .css("background", hex(self.color_of(e))).child(div().class("t").child(e.title.clone())) + .child(div().class("w").child(format!("{} – {}", clock(at), clock(at + e.dur))))); + } + if d == now_local.div_euclid(DAY_MIN) { + // the now line falls on by itself until midnight: one CSS animation, no frames + let m = now_local.rem_euclid(DAY_MIN); + let top = m as f32 / 60.0 * HOUR_H; + let left = (DAY_MIN - m) as f32; + col = col.child(div().id(format!("{tag}now{m}")).class("now").css("top", format!("{top}px")) + .css("--fall", format!("{}px", left / 60.0 * HOUR_H)) + .css("animation", format!("fall {}s linear forwards", left * 60.0))); + } + let id_for_down = col_id.clone(); + let id_for_move = col_id; + col = col + .on_pointer_down(w.listener(move |this: &mut CalApp, e: &PointerEvent, win, cx| { + let Some(top) = win.bounds_of(&id_for_down).map(|b| b.origin.y) else { return }; + let m = minute_at(d, top, e.position.y.0); + this.ui.day = d; + this.ui.sel = None; + this.ui.drag = Some(Drag::Create { from: m, to: m + 60 }); + win.set_pointer_capture(cx); + cx.notify(); + })) + .on_pointer_move(w.listener(move |this: &mut CalApp, e: &PointerEvent, win, cx| { + if let Some(Drag::Create { from, .. }) = this.ui.drag + && let Some(top) = win.bounds_of(&id_for_move).map(|b| b.origin.y) + { + let m = minute_at(d, top, e.position.y.0) + SNAP; + this.ui.drag = Some(Drag::Create { from, to: m.max(from + SNAP) }); + cx.notify(); + } + })) + .on_pointer_up(w.listener(move |this: &mut CalApp, _: &PointerEvent, win, cx| { + win.release_pointer_capture(cx); + if this.release() { + cx.notify(); + } + })); + let _ = ci; + grid = grid.child(col); + } + div().class("view") + .child(head) + .child(allday) + .child(div().id(format!("{tag}body")).class("body").child(grid)) + } + + /// An event in a time grid: `(column, columns)` side by side with its overlaps. + fn block(&self, o: Occ, (c, n): (usize, usize), tag: &'static str, d: i64) -> Div { + let w = self.weak; + let e = &self.data.events[o.idx]; + let id = e.id; + let top = (o.start - d * DAY_MIN) as f32 / 60.0 * HOUR_H; + let h = (o.dur as f32 / 60.0 * HOUR_H).max(18.0); + let mut cls = String::from("ev"); + if self.ui.sel == Some(id) { + cls.push_str(" sel"); + } + if self.ui.born == id { + cls.push_str(" born"); + } + let moving = matches!(self.ui.drag, Some(Drag::Move { id: m, moved: true, .. }) if m == id); + if moving { + cls.push_str(" ghost"); + } + let end = match self.ui.drag { + Some(Drag::Resize { id: r, end }) if r == id => end, + _ => o.start + o.dur, + }; + let h = if end == o.start + o.dur { h } else { ((end - o.start) as f32 / 60.0 * HOUR_H).max(18.0) }; + let width = 100.0 / n as f32; + let block_id = format!("{tag}ev{id}_{}", o.k); + let grid_id = format!("{tag}grid"); + let grid_id2 = grid_id.clone(); + let days = self.week_days(); + let tz = self.tz(); + let start_utc = e.start; + let k = i64::from(o.k); + let mut b = div().id(block_id).class(cls) + .css("left", format!("calc({}% + 2px)", width * c as f32)).css("width", format!("calc({width}% - 4px)")) + .css("top", format!("{top}px")).css("height", format!("{h}px")).css("background", hex(self.color_of(e))) + .child(div().class("t").child(e.title.clone())); + if h > 30.0 { + b = b.child(div().class("w").child(format!("{} – {}", clock(o.start), clock(end)))); + } + b.child(div().id(format!("{tag}grip{id}_{}", o.k)).class("grip") + .on_pointer_down(w.listener(move |this: &mut CalApp, _: &PointerEvent, win, cx| { + this.ui.sel = Some(id); + this.ui.day = d; + this.ui.drag = Some(Drag::Resize { id, end: start_utc + tz + k * 7 * DAY_MIN + o.dur }); + win.set_pointer_capture(cx); + cx.stop_propagation(); + cx.notify(); + })) + .on_pointer_move(w.listener(move |this: &mut CalApp, e: &PointerEvent, win, cx| { + if let Some(Drag::Resize { id: r, .. }) = this.ui.drag + && r == id + && let Some(g) = win.bounds_of(&grid_id2) + { + let m = minute_at(d, g.origin.y, e.position.y.0) + SNAP; + this.ui.drag = Some(Drag::Resize { id, end: m.max(o.start + SNAP) }); + cx.notify(); + } + })) + .on_pointer_up(w.listener(|this: &mut CalApp, _: &PointerEvent, win, cx| { + win.release_pointer_capture(cx); + if this.release() { + cx.notify(); + } + }))) + .on_pointer_down(w.listener(move |this: &mut CalApp, e: &PointerEvent, win, cx| { + let Some(g) = win.bounds_of(&grid_id) else { return }; + let at = minute_at(d, g.origin.y, e.position.y.0); + this.ui.sel = Some(id); + this.ui.day = d; + this.ui.drag = Some(Drag::Move { id, grab: at - o.start, at: o.start, moved: false }); + win.set_pointer_capture(cx); + cx.stop_propagation(); + cx.notify(); + })) + .on_pointer_move(w.listener(move |this: &mut CalApp, e: &PointerEvent, win, cx| { + let Some(Drag::Move { id: m, grab, at, .. }) = this.ui.drag else { return }; + if m != id { + return; + } + let Some(g) = win.bounds_of(&format!("{tag}grid")) else { return }; + // which day column the pointer is over, and the time there + let col_w = (g.size.width - GUTTER) / days.len() as f32; + let ci = (((e.position.x.0 - g.origin.x - GUTTER) / col_w).floor() as i64).clamp(0, i64::try_from(days.len()).unwrap_or(1) - 1); + let day = days[ci as usize]; + let t = minute_at(day, g.origin.y, e.position.y.0) - grab; + let t = day * DAY_MIN + (t - day * DAY_MIN).clamp(0, DAY_MIN - SNAP); + if t != at { + this.ui.drag = Some(Drag::Move { id, grab, at: t, moved: true }); + cx.notify(); + } + })) + .on_pointer_up(w.listener(|this: &mut CalApp, _: &PointerEvent, win, cx| { + win.release_pointer_capture(cx); + if this.release() { + cx.notify(); + } + })) + } + + /// An all-day or month chip. + fn chip(&self, o: &Occ, tag: &'static str) -> Div { + let w = self.weak; + let e = &self.data.events[o.idx]; + let id = e.id; + let mut cls = String::from("chip"); + if self.ui.sel == Some(id) { + cls.push_str(" sel"); + } + if matches!(self.ui.drag, Some(Drag::Chip { id: m, .. }) if m == id) { + cls.push_str(" ghost"); + } + let label = if e.all_day { e.title.clone() } else { format!("{} {}", clock(o.start), e.title) }; + let day = o.start.div_euclid(DAY_MIN); + div().id(format!("{tag}chip{id}_{}", o.k)).class(cls).css("background", hex(self.color_of(e))).child(label) + .on_pointer_down(w.listener(move |this: &mut CalApp, _: &PointerEvent, _, cx| { + this.ui.sel = Some(id); + this.ui.day = day; + this.ui.drag = Some(Drag::Chip { id, day }); + cx.stop_propagation(); + cx.notify(); + })) + } + + fn month(&self) -> Div { + let w = self.weak; + let tz = self.tz(); + let first = month_start(self.ui.day); + let grid0 = first - weekday(first); + let occ = self.data.occurrences(grid0, grid0 + 42, tz, &self.ui.search); + let (_, m, _) = civil(self.ui.day); + let mut g = div().class("month"); + for d in DAYS { + g = g.child(div().class("mh").child(d)); + } + let drop_day = match self.ui.drag { + Some(Drag::Chip { day, .. }) => Some(day), + _ => None, + }; + for z in grid0..grid0 + 42 { + let (_, zm, zd) = civil(z); + let mut cls = String::from("md"); + if zm != m { + cls.push_str(" out"); + } + if z == self.ui.today { + cls.push_str(" today"); + } + if drop_day == Some(z) { + cls.push_str(" drop"); + } else if z == self.ui.day { + cls.push_str(" sel"); + } + let mut cell = div().id(format!("md{z}")).class(cls).child(div().class("n").child(zd.to_string())); + let mine: Vec<&Occ> = occ.iter().filter(|o| o.start.div_euclid(DAY_MIN) == z).collect(); + for o in mine.iter().take(3) { + cell = cell.child(self.chip(o, "m")); + } + if mine.len() > 3 { + cell = cell.child(div().class("more").child(format!("+{} more", mine.len() - 3))); + } + g = g.child(cell + .on_pointer_enter(w.listener(move |this: &mut CalApp, _: &PointerEvent, _, cx| { + if let Some(Drag::Chip { id, day }) = this.ui.drag + && day != z + { + this.ui.drag = Some(Drag::Chip { id, day: z }); + cx.notify(); + } + })) + .on_click(w.listener(move |this: &mut CalApp, e: &ClickEvent, _, cx| { + this.ui.day = z; + if e.click_count() > 1 { + this.create(z * DAY_MIN + 9 * 60, 60, false); + } + cx.notify(); + }))); + } + div().class("view").child(g) + } + + fn agenda(&self) -> Div { + let w = self.weak; + let tz = self.tz(); + let from = self.ui.day - weekday(self.ui.day); + let occ = self.data.occurrences(from, from + 21, tz, &self.ui.search); + let mut list = div().id("agenda").class("agenda"); + let mut last = i64::MIN; + for o in &occ { + let e = &self.data.events[o.idx]; + let day = o.start.div_euclid(DAY_MIN); + if day != last { + list = list.child(div().class("ag-day").child(if day == self.ui.today { format!("Today · {}", date_label(day)) } else { date_label(day) })); + last = day; + } + let id = e.id; + let when = if e.all_day { "all day".to_string() } else { format!("{} – {}", clock(o.start), clock(o.start + o.dur)) }; + list = list.child(div().id(format!("ag{id}_{}", o.k)).class(if self.ui.sel == Some(id) { "ag sel" } else { "ag" }) + .child(div().class("dot").css("background", hex(self.color_of(e)))) + .child(span().class("tm").child(when)) + .child(span().child(e.title.clone())) + .child(span().class("nt").child(e.notes.clone())) + .on_click(w.listener(move |this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.sel = Some(id); + this.ui.day = day; + cx.notify(); + }))); + } + if occ.is_empty() { + list = list.child(div().class("empty").child(if self.ui.search.is_empty() { "Nothing in these three weeks" } else { "Nothing matches the search" })); + } + div().class("view").child(list) + } + + fn header(&self) -> Div { + let w = self.weak; + let mut d = div().class("hdr") + .child(Button().id("today").child("Today").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day = this.ui.today; + cx.notify(); + }))) + .child(Button().id("prev").child("‹").css("width", "28px").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.step(-1); + cx.notify(); + }))) + .child(Button().id("next").child("›").css("width", "28px").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.step(1); + cx.notify(); + }))) + .child(span().class("title").child(self.title())) + .child(div().class("sep")); + for (label, v, _) in VIEWS { + d = d.child(Radio().id(format!("v{label}")).attr("name", "view").checked(self.ui.view == v) + .on_change(w.listener(move |this: &mut CalApp, e: &ChangeEvent, _, cx| { + if e.checked { + this.ui.view = v; + cx.notify(); + } + }))) + .child(span().class("lbl").child(label)); + } + let zones = ZONES.iter().fold(Dropdown().id("tz").css("width", "150px").value(ZONES[self.ui.tz].0), |d, z| d.child(option().child(z.0))); + d.child(div().class("sep")) + .child(TextField().id("search").attr("live", "").value(self.ui.search.clone()).placeholder("Search events") + .css("width", "170px") + .on_input(w.listener(|this: &mut CalApp, e: &ChangeEvent, _, cx| { + this.ui.search.clone_from(&e.value); + this.ui.status = if e.value.is_empty() { "Showing everything".into() } else { format!("Search: {}", e.value) }; + cx.notify(); + }))) + .child(span().class("lbl").child("Zone")) + .child(zones.on_change(w.listener(|this: &mut CalApp, e: &ChangeEvent, _, cx| { + this.ui.tz = (e.number as usize).min(ZONES.len() - 1); + this.ui.status = format!("Times in {}", ZONES[this.ui.tz].0); + cx.notify(); + }))) + } + + fn tools(&self) -> Div { + let w = self.weak; + let first = month_start(self.ui.day); + let grid0 = first - weekday(first); + let (y, m, _) = civil(self.ui.day); + let busy = self.data.occurrences(grid0, grid0 + 42, self.tz(), ""); + let mut mini = div().class("mini"); + for d in ["M", "T", "W", "T", "F", "S", "S"] { + mini = mini.child(div().class("h").child(d)); + } + for z in grid0..grid0 + 42 { + let (_, zm, zd) = civil(z); + let mut cls = String::from("d"); + if zm != m { + cls.push_str(" out"); + } + if busy.iter().any(|o| o.start.div_euclid(DAY_MIN) == z) { + cls.push_str(" busy"); + } + if z == self.ui.day { + cls.push_str(" sel"); + } + if z == self.ui.today { + cls.push_str(" today"); + } + mini = mini.child(div().id(format!("mini{z}")).class(cls).child(zd.to_string()) + .on_click(w.listener(move |this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day = z; + cx.notify(); + }))); + } + let mut t = div().class("tools") + .child(div().class("mhead") + .child(div().id("miniprev").class("arrow").child("‹").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day = add_months(this.ui.day, -1); + cx.notify(); + }))) + .child(span().child(format!("{} {y}", &MONTHS[(m - 1) as usize][..3]))) + .child(div().id("mininext").class("arrow").child("›").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day = add_months(this.ui.day, 1); + cx.notify(); + })))) + .child(mini) + .child(details().open(true).child(summary().child("Calendars"))); + for (i, c) in self.data.cals.iter().enumerate() { + let n = self.data.events.iter().filter(|e| e.cal == i).count(); + t = t.child(div().class("calrow") + .child(Checkbox().id(format!("cal{i}")).checked(c.shown) + .on_change(w.listener(move |this: &mut CalApp, e: &ChangeEvent, _, cx| { + let on = e.checked; + let name = this.data.cals[i].name; + this.change(if on { "Shown" } else { "Hidden" }, |d| d.cals[i].shown = on); + this.ui.status = format!("{name} {}", if on { "shown" } else { "hidden" }); + cx.notify(); + }))) + .child(span().class("nm").child(format!("{} ({n})", c.name))) + .child(ColorSwatch().id(format!("calcol{i}")).value(hex(c.color)).css("width", "34px") + .on_change(w.listener(move |this: &mut CalApp, e: &ChangeEvent, _, cx| { + if let Ok(col) = u32::from_str_radix(e.value.trim_start_matches('#'), 16) { + this.change("Recolored", |d| d.cals[i].color = col); + cx.notify(); + } + })))); + } + t.child(p().class("hint").child("Drag on empty time to add an event. Drag an event to move it, its bottom edge to resize it.")) + } + + /// The selected event's editor (the sidebar). + fn editor(&self) -> Div { + let w = self.weak; + let Some(e) = self.ui.sel.and_then(|id| self.data.find(id)).map(|i| &self.data.events[i]) else { + return div().class("side").child(details().open(true).child(summary().child("Event")) + .child(p().class("hint").child("No event selected. Click one, or drag on empty time in the week to make one."))); + }; + let tz = self.tz(); + let local = e.start + tz; + let row = |k: &str| div().class("row").child(span().class("k").child(k.to_string())); + let cal_dd = self.data.cals.iter().fold(Dropdown().id("ecal").css("width", "140px").value(self.data.cals[e.cal].name), + |d, c| d.child(option().child(c.name))); + let start_h = (local.rem_euclid(DAY_MIN)) as f64 / 60.0; + let id = e.id; + div().class("side") + .child(div().class("colorbar").css("background", hex(self.color_of(e)))) + .child(details().open(true).child(summary().child("Event")) + .child(row("Title").child(TextField().id("etitle").value(e.title.clone()).css("width", "170px") + .on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, win, cx| { + win.focus_id("root"); + let t = ev.value.trim().to_string(); + if !t.is_empty() { + this.edit("Renamed", |e| e.title = t); + } + cx.notify(); + })))) + .child(row("Calendar").child(cal_dd.on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let c = (ev.number as usize).min(this.data.cals.len() - 1); + this.edit("Calendar changed", |e| e.cal = c); + cx.notify(); + })))) + .child(row("Day").child(span().child(date_label(local.div_euclid(DAY_MIN))))) + .child(row("Starts (h)").child(NumberField().id("estart").min(0.0).max(23.75).step(0.25).precision(2) + .value(format!("{start_h:.2}")).css("width", "120px") + .on_change(w.listener(move |this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let m = ((ev.number.clamp(0.0, 23.75) * 60.0) as i64).div_euclid(SNAP) * SNAP; + let tz = this.tz(); + this.edit(&format!("Starts {}", clock(m)), |e| { + let day = (e.start + tz).div_euclid(DAY_MIN); + e.start = day * DAY_MIN + m - tz; + }); + cx.notify(); + })))) + .child(row("Minutes").child(NumberField().id("edur").min(15.0).max(1440.0).step(15.0).value(e.dur.to_string()) + .css("width", "120px") + .on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let d = (ev.number.round() as i64).clamp(SNAP, DAY_MIN); + this.edit(&format!("Lasts {d} min"), |e| e.dur = d); + cx.notify(); + })))) + .child(p().class("hint").child("Drag the numbers, or double-click and type math: 1.5*60")) + .child(row("All day").child(Checkbox().id("eallday").checked(e.all_day) + .on_change(w.listener(move |this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let on = ev.checked; + let tz = this.tz(); + this.edit(if on { "All day" } else { "Timed" }, |e| { + e.all_day = on; + if on { + e.start = (e.start + tz).div_euclid(DAY_MIN) * DAY_MIN - tz; + e.dur = DAY_MIN; + } else { + e.start += 9 * 60; + e.dur = 60; + } + }); + cx.notify(); + })))) + .child(row("Weekly").child(Checkbox().id("erepeat").checked(e.repeat > 1) + .on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let n = if ev.checked { 6 } else { 1 }; + this.edit(if ev.checked { "Repeats weekly" } else { "Once" }, |e| e.repeat = n); + cx.notify(); + })))) + .child(row("Times").child(NumberField().id("ecount").min(1.0).max(52.0).step(1.0).value(e.repeat.to_string()) + .disabled(e.repeat <= 1).css("width", "120px") + .on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let n = (ev.number.round() as u32).clamp(1, 52); + this.edit(&format!("{n} weeks"), |e| e.repeat = n); + cx.notify(); + }))))) + .child(details().open(true).child(summary().child("Notes")) + .child(TextArea().id("enotes").value(e.notes.clone()).attr("rows", "5").css("width", "100%") + .on_change(w.listener(|this: &mut CalApp, ev: &ChangeEvent, _, cx| { + let n = ev.value.clone(); + this.edit("Notes saved", |e| e.notes = n); + cx.notify(); + })))) + .child(div().class("row") + .child(Button().id("edup").child("Duplicate").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + if this.duplicate() { + cx.notify(); + } + }))) + .child(Button().id("edel").child("Delete").on_click(w.listener(move |this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.sel = Some(id); + if this.delete() { + cx.notify(); + } + })))) + } + + fn footer(&self) -> Div { + let tz = self.tz(); + let days = self.week_days(); + let occ = self.data.occurrences(days[0], days[days.len() - 1] + 1, tz, &self.ui.search); + let mins: i64 = occ.iter().filter(|o| !self.data.events[o.idx].all_day).map(|o| o.dur).sum(); + let mut f = div().class("foot") + .child(span().class("st").child(self.ui.status.clone())) + .child(span().child(format!("{} events · {}h {:02}m booked", occ.len(), mins / 60, mins % 60))); + let mut s = String::new(); + let _ = write!(s, "Now {}", clock(self.now_min + tz)); + f = f.child(span().css("margin-left", "auto").child(s)); + f + } + + fn main_editor(&self) -> Editor { + let body = match self.ui.view { + View::Week | View::Day => self.time_grid(&self.week_days(), "w"), + View::Month => self.month(), + View::Agenda => self.agenda(), + }; + Editor::new(body) + .header(self.header()) + .toolbar(Region::new(self.tools()).size(200).overlap(false)) + .sidebar(Region::new(self.editor()).size(290).overlap(false)) + .footer(Region::new(self.footer()).size(26).overlap(false)) + } + + fn day_editor(&self) -> Editor { + let w = self.weak; + Editor::new(self.time_grid(&[self.ui.day], "d")) + .header(div().class("hdr") + .child(Button().id("dprev").child("‹").css("width", "28px").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day -= 1; + cx.notify(); + }))) + .child(span().class("title").child(date_label(self.ui.day))) + .child(Button().id("dnext").child("›").css("width", "28px").on_click(w.listener(|this: &mut CalApp, _: &ClickEvent, _, cx| { + this.ui.day += 1; + cx.notify(); + })))) + } +} + +impl Render for CalApp { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + focus_root(w, &mut self.frames); + let now_min = self.start_minute + (now() / 60.0) as i64; + let snap = Arc::new(Snap { data: self.data.clone(), ui: self.ui.clone(), weak: cx.weak_entity(), now_min }); + let (s1, s2, s3) = (snap.clone(), snap.clone(), snap); + let editors = Editors::new() + .editor("Calendar", "TIME", move |_: &AreaRef| s1.main_editor()) + .editor("Day", "SEQUENCE", move |_: &AreaRef| s2.day_editor()) + .editor("Agenda", "TEXT", move |_: &AreaRef| Editor::new(s3.agenda())); + app().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, w, cx| { + // a key the calendar takes is not Blender's as well (Ctrl+Z would undo a field edit too) + if !w.text_field_focused() && this.key(e) { + cx.prevent_default(); + cx.notify(); + } + })) + .on_pointer_up(cx.listener(|this, _: &PointerEvent, _, cx| if this.release() { cx.notify() })) + .child(style().child(CSS)) + .child(Screen().editors(editors).class("scr").layout(AreaSplit::v(0.74, "Calendar", "Day"))) + } +} + +/// Every view, a drag to create, a move, a resize, the editor, the month drag, search, zones, undo. +fn storyboard(dir: String) -> Script { + story(dir, |s| { + s.play("00-week", &[0, 300]); + s.cx.simulate_mouse_move(s.win, 5.0, 5.0); + // scroll the week body to the working day + let body = s.bounds("wbody"); + let (bx, by) = (body.origin.x + 300.0, body.origin.y + 200.0); + s.cx.simulate_scroll(s.win, bx, by, -10); + s.play("01-scrolled", &[0]); + let app_days = { + let wall = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs().cast_signed() / 60); + let today = wall.div_euclid(DAY_MIN); + today - weekday(today) + }; + // drag on empty Thursday time to make an event + let col = s.bounds(&format!("wcol{}", app_days + 3)); + let x = col.origin.x + col.size.width / 2.0; + let y0 = col.origin.y + 13.0 * HOUR_H + 4.0; + s.cx.simulate_drag(s.win, (x, y0), (x, y0 + 1.5 * HOUR_H)); + s.play("02-created", &[0, 300]); + // rename it in the sidebar + s.click("etitle"); + s.tick(100); + s.cx.simulate_key_with(s.win, "a", "a", true, false); + s.type_text("Shot 14 review"); + s.key("Return"); + s.hover("wbody"); + s.play("03-renamed", &[0]); + // move the climbing session on Tuesday to Wednesday evening + let ev = s.bounds(&format!("wev{}_0", 11)); + let (ex, ey) = (ev.origin.x + ev.size.width / 2.0, ev.origin.y + 10.0); + s.cx.simulate_drag(s.win, (ex, ey), (ex + col.size.width, ey + HOUR_H)); + s.play("04-moved", &[0, 200]); + // resize the lunch by its bottom edge + let g = s.bounds(&format!("wgrip{}_0", 8)); + let (gx, gy) = (g.origin.x + g.size.width / 2.0, g.origin.y + g.size.height / 2.0); + s.cx.simulate_drag(s.win, (gx, gy), (gx, gy + HOUR_H)); + s.play("05-resized", &[0]); + // the month: drag the offsite chip to the next Monday + s.key("m"); + s.play("06-month", &[0, 200]); + let chip = format!("mchip{}_0", 18); + if let Some(c) = s.cx.element_bounds(s.win, &chip) { + let to = s.bounds(&format!("md{}", app_days + 7)); + s.cx.simulate_drag(s.win, (c.origin.x + 10.0, c.origin.y + 6.0), + (to.origin.x + to.size.width / 2.0, to.origin.y + to.size.height / 2.0)); + } + s.play("07-chip-moved", &[0, 200]); + // the agenda, searched + s.key("a"); + s.click("search"); + s.tick(100); + s.type_text("farm"); + s.key("Return"); + s.hover("agenda"); + s.play("08-agenda-search", &[0]); + s.click("search"); + s.tick(100); + s.cx.simulate_key_with(s.win, "a", "a", true, false); + s.key("BackSpace"); + s.key("Return"); + s.hover("agenda"); + // a calendar hidden, Tokyo time, the day view + s.key("w"); + s.click("cal1"); + s.play("09-personal-hidden", &[0, 200]); + s.click("cal1"); + s.key("d"); + s.play("10-day", &[0]); + s.key("w"); + s.key("Left"); + s.play("11-last-week", &[0]); + s.key("t"); + s.cx.simulate_key_with(s.win, "z", "z", true, false); + s.play("12-undo", &[0, 200]); + }) +} + +fn main() { + let (w, h) = size_arg((1500.0, 920.0)); + run_with(w, h, "BUI Calendar", CalApp::new, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/bui_chat.rs b/demos/src/bin/bui_chat.rs new file mode 100644 index 00000000..973eb7dd --- /dev/null +++ b/demos/src/bin/bui_chat.rs @@ -0,0 +1,1271 @@ +//! BUI Chat: a community chat app built from Blender's own interface. The window is a Blender +//! screen: the server rail is the Channels editor's toolbar region, your user panel its footer, +//! the composer the chat's footer, threads open in the chat's sidebar, and the members list is an +//! editor of its own. Split the chat area (its header's Split, or drag an area corner) and each +//! area keeps its own channel, so two channels sit side by side; Maximize gives one the window. +//! +//! What it does: four servers with unread pips and mention badges; text and voice channels in +//! categories (Blender panels you fold); messages grouped by author, with reactions you toggle, +//! replies that quote, and threads; a composer that sends on Enter (a Blender text field confirms +//! on Enter), after which someone starts typing and answers; mail-like background activity that +//! lights other channels; a voice channel with a live speaking meter drawn with BUI's `Painter`, a +//! volume slider per person, mute and deafen; and settings that act at once: your status (a +//! Blender menu), name color (Blender's color picker), accent (radio buttons), compact mode and +//! avatars (checkboxes), and a UI scale slider that resizes the whole app. +//! +//! Keys (with the pointer over a chat): Alt+Up / Alt+Down channels, Esc cancels a reply or closes a +//! thread, Ctrl+Z takes back your last message. +//! +//! `cargo run --release --bin bui_chat`, `-- --storyboard DIR` drives it headlessly. + +use std::rc::Rc; +use std::sync::OnceLock; + +use blenderui::prelude::*; +use blenderui::screen::{AreaRef, AreaSplit, Axis, Editor, Editors, Region, Screen}; +use bui_demos::story::story; +use bui_demos::{arg, focus_root, now, run_with, size_arg, Script}; +use bui_demos::area_id; + +// ========================================================================== +// The community + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Status { + Online, + Idle, + Busy, + Offline, +} + +impl Status { + const ALL: [Self; 4] = [Self::Online, Self::Idle, Self::Busy, Self::Offline]; + + const fn name(self) -> &'static str { + match self { + Self::Online => "Online", + Self::Idle => "Idle", + Self::Busy => "Do not disturb", + Self::Offline => "Offline", + } + } + + const fn color(self) -> &'static str { + match self { + Self::Online => "#43b581", + Self::Idle => "#faa61a", + Self::Busy => "#f04747", + Self::Offline => "#747f8d", + } + } +} + +struct Member { + name: String, + color: String, + status: Status, + role: &'static str, + /// Voice: their volume (0..2) and whether you muted them. + volume: f64, +} + +#[derive(Clone)] +struct Line { + id: u32, + author: usize, + text: String, + /// Minutes after midnight today (09:41 is now at the start). + at: u32, + reactions: Vec<(&'static str, u32, bool)>, + reply_to: Option, + thread: Vec, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Text, + Voice, +} + +struct Channel { + name: &'static str, + kind: Kind, + category: &'static str, + topic: &'static str, + lines: Vec, + unread: usize, + mentions: usize, + /// Voice: who is in it. + voice: Vec, +} + +struct Server { + name: &'static str, + glyph: &'static str, + color: &'static str, + channels: Vec, +} + +/// The members (0 is you). +const MEMBERS: [(&str, &str, Status, &str); 12] = [ + ("you", "#e3913c", Status::Online, "Lighting"), + ("Ana", "#5aa0e0", Status::Online, "Lighting"), + ("Jonas", "#43b581", Status::Online, "Pipeline"), + ("Kenji", "#b38fe0", Status::Idle, "Rigging"), + ("Priya", "#e06b8f", Status::Online, "Production"), + ("Tomas", "#e0c35a", Status::Busy, "FX"), + ("Yuki", "#5ae0c8", Status::Online, "Texturing"), + ("Omar", "#e07a5a", Status::Idle, "Color"), + ("Lena", "#8fb3e0", Status::Offline, "Guest"), + ("Sam", "#a0e05a", Status::Online, "Animation"), + ("Bot", "#9aa4b0", Status::Online, "Bot"), + ("Mo", "#e05a9e", Status::Offline, "Editorial"), +]; + +const EMOJI: [&str; 6] = ["👍", "🔥", "😂", "🎉", "👀", "✔"]; + +type SeedLine = (usize, &'static str, u32, &'static [(&'static str, u32)]); + +fn lines(seed: &[SeedLine], first: u32) -> Vec { + seed.iter().enumerate().map(|(i, &(author, text, at, reacts))| Line { + id: first + i as u32, + author, + text: text.into(), + at, + reactions: reacts.iter().map(|&(e, n)| (e, n, false)).collect(), + reply_to: None, + thread: Vec::new(), + }).collect() +} + +fn text(name: &'static str, category: &'static str, topic: &'static str, seed: &[SeedLine], first: u32) -> Channel { + Channel { name, kind: Kind::Text, category, topic, lines: lines(seed, first), unread: 0, mentions: 0, voice: Vec::new() } +} + +fn voice(name: &'static str, who: &[usize]) -> Channel { + Channel { name, kind: Kind::Voice, category: "Voice", topic: "", lines: Vec::new(), unread: 0, mentions: 0, voice: who.to_vec() } +} + +fn community() -> Vec { + let mut general = text("general", "Studio", "Everything Lumen. Be kind, post renders.", &[ + (2, "morning all ☕ farm is back online, queue is empty", 520, &[("👍", 4)]), + (1, "finally! I have 40 frames of shot 052 waiting", 523, &[]), + (1, "rendering now", 523, &[("🔥", 2)]), + (4, "reminder: dailies at 16:00 in screening room B", 540, &[("👀", 3)]), + (9, "is anyone else seeing the viewport stutter with the new driver?", 561, &[]), + (2, "yes, roll back to the previous one for now. I'll pin it in #pipeline", 563, &[("✔", 5)]), + (6, "new tileable concrete set is in the library, 8K", 570, &[("🎉", 6), ("🔥", 3)]), + (3, "the rig review moved to 11:00 btw", 575, &[]), + (1, "@you can you check the rim light on 052 when you're in?", 579, &[]), + ], 1); + general.lines[5].thread = lines(&[ + (9, "rolled back, smooth again. thanks!", 566, &[("👍", 1)]), + (5, "same here on the FX boxes", 568, &[]), + (2, "I'll update the install script", 569, &[]), + ], 900); + general.lines[4].thread = vec![]; + general.mentions = 1; + general.unread = 3; + let renders = text("renders", "Studio", "Post your frames. Critique welcome, be specific.", &[ + (6, "lookdev turntable for the lantern, v3", 480, &[("🔥", 5)]), + (7, "lovely. the glass reads a touch green under AgX", 486, &[]), + (6, "good eye, fixed the IOR tint", 501, &[("👍", 2)]), + (5, "first pass of the waterfall sim, 240 frames", 550, &[("🎉", 4), ("👀", 2)]), + ], 20); + let pipeline = text("pipeline", "Studio", "Tools, builds, the farm. Bot posts here.", &[ + (10, "✔ nightly #1842 passed in 14m 08s", 506, &[]), + (2, "pinned: driver 551.23 is the good one, avoid 560.x", 564, &[("✔", 7)]), + (10, "farm: 24/24 nodes online, queue 0", 571, &[]), + ], 40); + let random = text("random", "Off topic", "Cats, coffee, cameras.", &[ + (9, "my cat walked over the keyboard and keyed a whole animation", 512, &[("😂", 9)]), + (1, "honestly better timing than my last one", 513, &[("😂", 6)]), + (11, "lunch: thai downstairs?", 555, &[("👍", 3)]), + ], 60); + let jobs = text("jobs-board", "Off topic", "Who is hiring, who is available.", &[ + (4, "we're looking for a freelance compositor for 3 weeks in December", 400, &[("👀", 4)]), + ], 80); + let studio = Server { + name: "Lumen Studio", + glyph: "L", + color: "#e3913c", + channels: vec![general, renders, pipeline, random, jobs, voice("Lighting sync", &[1, 2, 9]), voice("Quiet room", &[])], + }; + let mut nodes = text("node-wrangling", "Learn", "Geometry and shader nodes: questions and tricks.", &[ + (3, "how do I scatter only on upward faces?", 300, &[]), + (6, "compare the face normal's Z with 0.7 and use that as the selection", 304, &[("✔", 3)]), + (3, "perfect, thank you", 306, &[("👍", 1)]), + ], 100); + nodes.unread = 2; + let blender_club = Server { + name: "Nodes Club", + glyph: "N", + color: "#5aa0e0", + channels: vec![nodes, text("showcase", "Learn", "Share what you made.", &[ + (9, "procedural brick wall, all nodes, no textures", 330, &[("🔥", 12)]), + ], 120), voice("Study hall", &[3, 6])], + }; + let mut lounge = text("lounge", "Hangout", "The couch.", &[ + (8, "anyone up for the film festival on the 14th?", 200, &[("🎉", 2)]), + (11, "I'm in!", 210, &[]), + ], 140); + lounge.unread = 5; + lounge.mentions = 2; + let friends = Server { name: "Weekend Crew", glyph: "W", color: "#43b581", channels: vec![lounge, voice("Couch", &[8])] }; + let bikes = Server { + name: "Spokes", + glyph: "S", + color: "#e06b8f", + channels: vec![text("saturday-ride", "Rides", "Routes, times, coffee stops.", &[ + (9, "62 km loop, meet at the bakery 8:00", 150, &[("👍", 6)]), + ], 160)], + }; + vec![studio, blender_club, friends, bikes] +} + +/// What others answer when you post (one after another). +const ANSWERS: [(usize, &str); 6] = [ + (1, "oh nice, on it"), + (2, "makes sense to me 👍"), + (9, "can you drop the file in the share?"), + (6, "looks great already"), + (4, "noted, I'll add it to the dailies list"), + (3, "ha, same thought"), +]; + +/// Chatter that arrives in other channels: (server, channel, author, text). +const CHATTER: [(usize, usize, usize, &str); 5] = [ + (0, 1, 5, "waterfall v2 with more spray, 240 frames"), + (1, 0, 6, "tip: use a Merge by Distance after the instance realize"), + (2, 0, 11, "@you festival tickets are on sale!"), + (0, 2, 10, "✔ nightly #1843 passed"), + (3, 0, 9, "rain tomorrow, ride moved to Sunday"), +]; + +// ========================================================================== +// State + +const ACCENTS: [(&str, &str); 4] = [("Blender blue", "#4772b3"), ("Orange", "#e3913c"), ("Green", "#43b581"), ("Purple", "#9a6ee0")]; + +struct Settings { + compact: bool, + avatars: bool, + show_ids: bool, + accent: usize, + scale: f64, +} + +#[allow(clippy::struct_excessive_bools)] +struct Chat { + servers: Vec, + members: Vec, + /// The server and channel of each chat area (by the area), and of the last one used. + areas: Vec<(AreaRef, (usize, usize))>, + active: (usize, usize), + /// The chat area keys and clicks act on last. + focus_area: Option, + replying: Option, + thread: Option, + /// The composer: sends so far (keys a fresh field after each, as a value pushed again would + /// not clear one the user typed in). + sent: u32, + my_last: Option<(usize, usize, u32)>, + typing: Option<(usize, f32, (usize, usize))>, + answered: usize, + chatter: usize, + next_chatter: f32, + next_id: u32, + settings: Settings, + in_voice: Option<(usize, usize)>, + muted: bool, + deafened: bool, + show_settings: bool, + /// The members list filter (a live Blender text field: each key filters). + member_filter: String, + picker: Option, + toast: Option<(String, f32)>, + frames: u32, +} + +impl Chat { + fn new() -> Self { + let mut chat = Self { + servers: community(), + members: MEMBERS.iter().map(|&(n, c, s, r)| Member { name: n.into(), color: c.into(), status: s, role: r, volume: 1.0 }).collect(), + areas: Vec::new(), + active: (0, 0), + focus_area: None, + replying: None, + thread: None, + sent: 0, + my_last: None, + typing: None, + answered: 0, + chatter: 0, + next_chatter: 12.0, + next_id: 1000, + settings: Settings { compact: false, avatars: true, show_ids: false, accent: 0, scale: 1.0 }, + in_voice: Some((0, 5)), + muted: false, + deafened: false, + show_settings: false, + member_filter: String::new(), + picker: None, + toast: None, + frames: 0, + }; + chat.open((0, 0)); + chat + } + + fn channel(&self, (s, c): (usize, usize)) -> &Channel { + &self.servers[s].channels[c] + } + + fn channel_mut(&mut self, (s, c): (usize, usize)) -> &mut Channel { + &mut self.servers[s].channels[c] + } + + /// The channel area `a` shows (an area not seen before shows the active one). + fn of(&self, a: Option) -> (usize, usize) { + a.and_then(|a| self.areas.iter().find(|(x, _)| *x == a).map(|(_, c)| *c)).unwrap_or(self.active) + } + + /// Opens `at` in the chat area used last (and makes it the active channel). + fn open(&mut self, at: (usize, usize)) { + self.active = at; + if let Some(a) = self.focus_area { + match self.areas.iter_mut().find(|(x, _)| *x == a) { + Some(e) => e.1 = at, + None => self.areas.push((a, at)), + } + } + let ch = self.channel_mut(at); + ch.unread = 0; + ch.mentions = 0; + if ch.kind == Kind::Voice { + self.in_voice = Some(at); + } + self.replying = None; + self.thread = None; + self.show_settings = false; + } + + /// Alt+Up / Alt+Down: the previous or next channel of the server. + fn step(&mut self, down: bool) { + let (s, c) = self.active; + let n = self.servers[s].channels.len(); + let next = if down { (c + 1) % n } else { (c + n - 1) % n }; + self.open((s, next)); + } + + fn line_mut(&mut self, at: (usize, usize), id: u32) -> Option<&mut Line> { + let ch = self.channel_mut(at); + for l in &mut ch.lines { + if l.id == id { + return Some(l); + } + if let Some(t) = l.thread.iter_mut().find(|t| t.id == id) { + return Some(t); + } + } + None + } + + fn react(&mut self, at: (usize, usize), id: u32, emoji: &'static str) { + if let Some(l) = self.line_mut(at, id) { + match l.reactions.iter_mut().position(|r| r.0 == emoji) { + Some(k) => { + let r = &mut l.reactions[k]; + r.2 = !r.2; + if r.2 { r.1 += 1 } else { r.1 -= 1 } + if r.1 == 0 { + l.reactions.remove(k); + } + } + None => l.reactions.push((emoji, 1, true)), + } + } + self.picker = None; + } + + /// Posts `text` as you in `at` (in the open thread when there is one), then someone answers. + fn post(&mut self, at: (usize, usize), text: &str) { + let text = text.trim().to_string(); + if text.is_empty() { + return; + } + let id = self.next_id; + self.next_id += 1; + let line = Line { id, author: 0, text, at: clock(), reactions: Vec::new(), reply_to: self.replying.take(), thread: Vec::new() }; + let thread = self.thread; + let ch = self.channel_mut(at); + match thread.and_then(|t| ch.lines.iter_mut().find(|l| l.id == t)) { + Some(parent) => parent.thread.push(line), + None => ch.lines.push(line), + } + self.my_last = Some((at.0, at.1, id)); + self.sent += 1; + if self.channel(at).kind == Kind::Text { + let who = ANSWERS[self.answered % ANSWERS.len()].0; + self.typing = Some((who, now() + 1.6, at)); + } + } + + /// Ctrl+Z: your last message taken back. + fn unsend(&mut self) { + let Some((s, c, id)) = self.my_last.take() else { return }; + let ch = self.channel_mut((s, c)); + ch.lines.retain(|l| l.id != id); + for l in &mut ch.lines { + l.thread.retain(|t| t.id != id); + } + self.toast = Some(("Message deleted".into(), now())); + } + + /// The clock moves on: answers arrive, other channels light up, toasts go. + fn tick(&mut self) -> bool { + let t = now(); + let mut busy = false; + if let Some((who, at, ch)) = self.typing { + busy = true; + if t >= at { + self.typing = None; + let text = ANSWERS[self.answered % ANSWERS.len()].1.to_string(); + self.answered += 1; + let id = self.next_id; + self.next_id += 1; + let thread = self.thread; + let c = self.channel_mut(ch); + let line = Line { id, author: who, text, at: clock(), reactions: Vec::new(), reply_to: None, thread: Vec::new() }; + match thread.and_then(|tid| c.lines.iter_mut().find(|l| l.id == tid)) { + Some(parent) => parent.thread.push(line), + None => c.lines.push(line), + } + } + } + if t >= self.next_chatter { + let (s, c, author, text) = CHATTER[self.chatter % CHATTER.len()]; + self.chatter += 1; + self.next_chatter = t + 12.0; + let id = self.next_id; + self.next_id += 1; + let shown = self.areas.iter().any(|(_, x)| *x == (s, c)) || self.active == (s, c); + let ch = self.channel_mut((s, c)); + ch.lines.push(Line { id, author, text: text.into(), at: clock(), reactions: Vec::new(), reply_to: None, thread: Vec::new() }); + if !shown { + ch.unread += 1; + if text.contains("@you") { + ch.mentions += 1; + } + } + } + if self.toast.as_ref().is_some_and(|(_, at)| t - at > 4.0) { + self.toast = None; + } + busy | self.toast.is_some() | self.in_voice.is_some() + } + + fn key(&mut self, e: &KeyDownEvent, w: &Window) -> bool { + let k = &e.keystroke; + // keys typed into the composer reach the page too (as in a browser): no shortcuts then + if w.text_field_focused() { + return false; + } + match (k.key.as_str(), k.modifiers.alt, k.modifiers.control) { + ("Up", true, _) => self.step(false), + ("Down", true, _) => self.step(true), + ("z", false, true) => self.unsend(), + ("Escape", _, _) => { + if self.replying.take().is_none() && self.thread.take().is_none() { + self.picker = None; + } + } + _ => return false, + } + true + } +} + +/// Minutes after midnight now: the demo's day starts at 09:41. +fn clock() -> u32 { + 9 * 60 + 41 + (now() / 60.0) as u32 +} + +fn hhmm(m: u32) -> String { + format!("{:02}:{:02}", m / 60 % 24, m % 60) +} + +// ========================================================================== +// What the areas draw + +struct Snap { + servers: Vec<(String, &'static str, &'static str, usize, usize)>, + channels: Vec, + server: usize, + active: (usize, usize), + /// Every chat area's channel, and each channel's lines (by `(server, channel)`). + views: Vec<((usize, usize), ChannelView)>, + areas: Vec<(AreaRef, (usize, usize))>, + members: Vec, + me: (String, String, Status), + replying: Option<(u32, String)>, + thread: Option, + sent: u32, + typing: Option<(String, (usize, usize))>, + settings: (bool, bool, bool, usize, f64), + in_voice: Option<(usize, usize)>, + muted: bool, + deafened: bool, + show_settings: bool, + picker: Option, + member_filter: String, +} + +/// A channel in the list: its index, name, kind, category, unread, mentions and who is in it. +type ChanRow = (usize, &'static str, Kind, &'static str, usize, usize, Vec); + +/// A member as drawn: name, color, status, role, voice volume. +type MemberRow = (String, String, Status, &'static str, f64); + +struct ChannelView { + name: &'static str, + kind: Kind, + topic: &'static str, + lines: Vec, + voice: Vec, +} + +impl Chat { + fn snap(&self) -> Snap { + let (server, _) = self.active; + let mut shown: Vec<(usize, usize)> = self.areas.iter().map(|(_, c)| *c).collect(); + shown.push(self.active); + shown.sort_unstable(); + shown.dedup(); + let views = shown.into_iter().map(|at| { + let ch = self.channel(at); + (at, ChannelView { name: ch.name, kind: ch.kind, topic: ch.topic, lines: ch.lines.clone(), voice: ch.voice.clone() }) + }).collect(); + let me = &self.members[0]; + Snap { + servers: self.servers.iter().map(|s| (s.name.to_string(), s.glyph, s.color, + s.channels.iter().map(|c| c.unread).sum(), s.channels.iter().map(|c| c.mentions).sum())) + .collect(), + channels: self.servers[server].channels.iter().enumerate() + .map(|(i, c)| (i, c.name, c.kind, c.category, c.unread, c.mentions, c.voice.clone())).collect(), + server, + active: self.active, + views, + areas: self.areas.clone(), + members: self.members.iter().map(|m| (m.name.clone(), m.color.clone(), m.status, m.role, m.volume)).collect(), + me: (me.name.clone(), me.color.clone(), me.status), + replying: self.replying.and_then(|id| { + self.channel(self.active).lines.iter().find(|l| l.id == id) + .map(|l| (id, self.members[l.author].name.clone())) + }), + thread: self.thread, + sent: self.sent, + typing: self.typing.map(|(who, _, at)| (self.members[who].name.clone(), at)), + settings: (self.settings.compact, self.settings.avatars, self.settings.show_ids, self.settings.accent, self.settings.scale), + in_voice: self.in_voice, + muted: self.muted, + deafened: self.deafened, + show_settings: self.show_settings, + picker: self.picker, + member_filter: self.member_filter.clone(), + } + } +} + +// ========================================================================== +// Look + +const CSS: &str = r" +body { color: #dcddde; -webkit-font-smoothing: antialiased; user-select: none; } +.shell { display: flex; flex-direction: column; height: 100vh; } +.screen { flex: 1; min-height: 0; } +.main { height: 100%; background: #303030; overflow-y: auto; } +.main.col { display: flex; flex-direction: column; overflow: hidden; } +.scroll { flex: 1; min-height: 0; overflow-y: auto; } +.hdr { display: flex; align-items: center; gap: 6px; height: 100%; padding: 0 8px; background: #3d3d3d; } +.hdr .hash { color: #8e9297; font-size: 1.15em; } +.hdr .name { font-weight: 700; color: #f0f0f0; } +.hdr .topic { color: #a0a0a0; font-size: 0.92em; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1; + padding-left: 8px; margin-left: 4px; border-left: 1px solid #555; } +.grow { flex: 1; } + +/* the server rail (the channels' toolbar) */ +.rail { height: 100%; background: #1f1f1f; display: flex; flex-direction: column; align-items: center; gap: 8px; padding-top: 8px; } +.srv { position: relative; width: 44px; height: 44px; border-radius: 22px; display: flex; align-items: center; justify-content: center; + font-weight: 800; font-size: 1.15em; color: #fff; background: #36393f; cursor: pointer; + transition-property: border-radius, background-color, transform; transition-duration: 180ms; + transition-timing-function: cubic-bezier(0.2, 0, 0, 1); } +.srv:hover { border-radius: 14px; } +.srv:active { transform: scale(0.96); } +.srv.on { border-radius: 14px; } +.pip { position: absolute; left: -9px; top: 18px; width: 4px; height: 8px; border-radius: 0 4px 4px 0; background: #fff; } +.srv.on .pip { top: 6px; height: 32px; } +.badge { position: absolute; right: -4px; bottom: -4px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; + background: #f04747; color: #fff; font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center; + box-shadow: 0 0 0 3px #1f1f1f; font-variant-numeric: tabular-nums; animation: pop 260ms cubic-bezier(0.2, 0, 0, 1); } + +/* channels */ +.srvname { padding: 12px 12px 8px; font-weight: 700; color: #f0f0f0; border-bottom: 1px solid #262626; } +.cat summary { font-size: 0.8em; text-transform: uppercase; letter-spacing: 0.5px; color: #8e9297; } +.chan { display: flex; align-items: center; gap: 6px; height: 30px; padding: 0 8px; margin: 1px 6px; border-radius: 4px; color: #8e9297; + cursor: pointer; transition-property: background-color, color; transition-duration: 120ms; } +.chan:hover { background: #3a3a3a; color: #dcddde; } +.chan.on { background: #45484d; color: #fff; } +.chan.unread { color: #fff; font-weight: 600; } +.chan .ic { width: 16px; text-align: center; } +.chan .men { margin-left: auto; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; background: #f04747; color: #fff; + font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center; } +.voiceppl { padding: 0 0 4px 34px; } +.voiceppl div { display: flex; align-items: center; gap: 6px; height: 22px; color: #a0a0a0; font-size: 0.92em; } + +/* your panel (the channels' footer) */ +.me { display: flex; align-items: center; gap: 8px; height: 52px; flex-shrink: 0; padding: 0 8px; background: #262626; } +.me .who { flex: 1; min-width: 0; } +.me .who b { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.me .who small { color: #a0a0a0; } + +/* avatars and status dots */ +.av { position: relative; width: 36px; height: 36px; border-radius: 18px; flex-shrink: 0; display: flex; align-items: center; + justify-content: center; font-weight: 700; color: #fff; } +.av.s { width: 28px; height: 28px; border-radius: 14px; font-size: 0.85em; } +.dot { position: absolute; right: -2px; bottom: -2px; width: 10px; height: 10px; border-radius: 5px; box-shadow: 0 0 0 3px #262626; } + +/* messages */ +.lines { padding: 12px 0 8px; } +.day { display: flex; align-items: center; gap: 8px; margin: 6px 16px 10px; color: #8e9297; font-size: 0.8em; font-weight: 600; } +.day::before, .day::after { content: ''; flex: 1; height: 1px; background: #3f4147; } +.grp { display: flex; gap: 12px; padding: 4px 16px 2px; margin-top: 10px; } +.grp.compact { margin-top: 2px; } +.ln { position: relative; padding: 2px 16px 2px 64px; transition-property: background-color; transition-duration: 100ms; } +.compact .ln, .ln.compact { padding-left: 16px; } +.ln:hover { background: #2a2a2a; } +.ln .acts { position: absolute; right: 16px; top: -12px; display: flex; gap: 2px; padding: 2px; border-radius: 4px; background: #3a3a3a; + box-shadow: 0 2px 8px rgba(0,0,0,0.35); opacity: 0; transition-property: opacity; transition-duration: 120ms; } +.ln:hover .acts { opacity: 1; } +.act { padding: 0 6px; border-radius: 3px; cursor: pointer; color: #b9bbbe; } +.act:hover { background: #4a4a4a; color: #fff; } +.author { font-weight: 600; margin-right: 6px; } +.ts { color: #72767d; font-size: 0.8em; font-variant-numeric: tabular-nums; } +.txt { color: #dcddde; line-height: 1.45; text-wrap: pretty; } +.txt .ment { background: rgba(250,166,26,0.18); color: #faa61a; padding: 0 2px; border-radius: 3px; } +.mine .txt { } +.quote { display: flex; gap: 6px; align-items: center; color: #b9bbbe; font-size: 0.85em; margin-bottom: 2px; } +.quote::before { content: ''; width: 20px; height: 8px; border-left: 2px solid #4f545c; border-top: 2px solid #4f545c; border-radius: 6px 0 0 0; margin-top: 6px; } +.reacts { display: flex; gap: 4px; margin: 4px 0 2px; flex-wrap: wrap; } +.re { display: flex; align-items: center; gap: 4px; padding: 0 6px; height: 22px; border-radius: 6px; background: #2f3136; cursor: pointer; + box-shadow: inset 0 0 0 1px #3f4147; font-size: 0.85em; font-variant-numeric: tabular-nums; + transition-property: background-color, box-shadow, transform; transition-duration: 120ms; } +.re:active { transform: scale(0.96); } +.re.mine { background: rgba(var(--acc-rgb), 0.25); box-shadow: inset 0 0 0 1px var(--acc); } +.picker { display: flex; gap: 2px; padding: 4px; border-radius: 6px; background: #3a3a3a; width: fit-content; margin: 4px 0; + animation: pop 200ms cubic-bezier(0.2, 0, 0, 1); } +.picker .act { font-size: 1.1em; } +.threadlink { color: var(--acc); font-size: 0.85em; font-weight: 600; cursor: pointer; margin-top: 2px; } +.typing { height: 22px; padding: 0 16px; color: #b9bbbe; font-size: 0.85em; display: flex; align-items: center; gap: 6px; } +.typing i { width: 6px; height: 6px; border-radius: 3px; background: #b9bbbe; animation: bob 900ms ease-in-out infinite; } +.typing i:nth-child(2) { animation-delay: 150ms; } +.typing i:nth-child(3) { animation-delay: 300ms; } +.idtag { color: #72767d; font-size: 0.75em; margin-left: 6px; font-variant-numeric: tabular-nums; } + +/* composer (the chat's footer) */ +.composer { display: flex; flex-direction: column; justify-content: center; gap: 4px; min-height: 52px; flex-shrink: 0; padding: 8px 12px; + background: #383838; } +.replybar { display: flex; align-items: center; gap: 8px; color: #b9bbbe; font-size: 0.85em; } +.replybar b { color: #fff; } + +/* thread (sidebar) */ +.thread { height: 100%; background: #2b2b2b; display: flex; flex-direction: column; } +.thread .th { padding: 10px 12px; font-weight: 700; border-bottom: 1px solid #222; display: flex; align-items: center; } + +/* members */ +.grouphd { padding: 14px 12px 4px; font-size: 0.8em; text-transform: uppercase; letter-spacing: 0.5px; color: #8e9297; } +.mem { display: flex; align-items: center; gap: 10px; padding: 4px 10px; margin: 0 6px; border-radius: 4px; } +.mem:hover { background: #3a3a3a; } +.mem.off { opacity: 0.4; } +.mem small { display: block; color: #8e9297; } + +/* voice */ +.voice { padding: 18px; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; } +.vcard { position: relative; height: 150px; border-radius: 10px; background: #232323; display: flex; flex-direction: column; + align-items: center; justify-content: center; gap: 8px; box-shadow: 0 0 0 2px transparent; + transition-property: box-shadow; transition-duration: 120ms; } +.vcard.speaking { box-shadow: 0 0 0 2px #43b581; } +.vcard .av { width: 56px; height: 56px; border-radius: 28px; font-size: 1.3em; } +.vcard .meter { width: 120px; height: 18px; } +.vctl { display: flex; align-items: center; gap: 8px; height: 44px; flex-shrink: 0; padding: 0 12px; background: #262626; } +.vctl .live { color: #43b581; font-weight: 600; } + +/* settings */ +.settings { padding: 18px 24px; max-width: 640px; } +.settings h2 { margin: 0 0 12px; font-size: 1.25em; text-wrap: balance; } +.srow { display: flex; align-items: center; gap: 10px; padding: 5px 0; } +.srow label { width: 150px; color: #b9bbbe; } +.toast { position: absolute; left: 50%; bottom: 74px; transform: translateX(-50%); padding: 6px 14px; border-radius: 6px; + background: #111; color: #fff; box-shadow: 0 8px 24px rgba(0,0,0,0.5); animation: rise 220ms cubic-bezier(0.2, 0, 0, 1); } +@keyframes pop { from { opacity: 0; transform: scale(0.6); } to { opacity: 1; transform: scale(1); } } +@keyframes rise { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } } +@keyframes bob { 0%, 100% { transform: translateY(0); opacity: 0.5; } 50% { transform: translateY(-3px); opacity: 1; } } +"; + +fn css() -> &'static str { + static S: OnceLock<&'static str> = OnceLock::new(); + S.get_or_init(|| CSS) +} + +type W = WeakEntity; + +fn avatar(name: &str, color: &str, status: Option, small: bool) -> Div { + let mut d = div().class(if small { "av s" } else { "av" }).css("background", color) + .child(name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default()); + if let Some(s) = status { + d = d.child(div().class("dot").css("background", s.color())); + } + d +} + +/// A message's text, an `@you` mention lit. +fn message_text(t: &str) -> Div { + let mut d = div().class("txt"); + let mut rest = t; + while let Some(at) = rest.find("@you") { + d = d.child(span().child(rest[..at].to_string())).child(span().class("ment").child("@you")); + rest = &rest[at + 4..]; + } + d.child(span().child(rest.to_string())) +} + +// ========================================================================== +// Areas + +fn channels_area(s: &Snap, weak: W, k: u32) -> Editor { + // the server rail: the editor's toolbar + let mut rail = div().class("rail"); + for (i, (name, glyph, color, unread, mentions)) in s.servers.iter().enumerate() { + let on = i == s.server; + let mut srv = div().id(area_id(&format!("srv{i}"), k)).class(if on { "srv on" } else { "srv" }) + .css("background", if on { (*color).to_string() } else { "#36393f".to_string() }) + .attr("aria-label", name.clone()) + .child(*glyph) + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + let first = this.servers[i].channels.iter().position(|c| c.kind == Kind::Text).unwrap_or(0); + this.open((i, first)); + cx.notify(); + })); + if on || *unread > 0 { + srv = srv.child(div().class("pip")); + } + if *mentions > 0 { + srv = srv.child(div().id(area_id(&format!("badge{i}-{mentions}"), k)).class("badge").child(mentions.to_string())); + } + rail = rail.child(srv); + } + let mut list = div().class("scroll").child(div().class("srvname").child(s.servers[s.server].0.clone())); + let mut cats: Vec<&str> = Vec::new(); + for c in &s.channels { + if !cats.contains(&c.3) { + cats.push(c.3); + } + } + for cat in cats { + let mut panel = details().id(area_id(&format!("cat-{}-{cat}", s.server), k)).open(true).class("cat").child(summary().child(cat)); + for (i, name, kind, _, unread, mentions, voice) in s.channels.iter().filter(|c| c.3 == cat) { + let at = (s.server, *i); + let on = at == s.active; + let cls = match (on, *unread > 0) { + (true, _) => "chan on", + (false, true) => "chan unread", + _ => "chan", + }; + let mut row = div().id(area_id(&format!("ch{}-{i}", s.server), k)).class(cls) + .child(div().class("ic").child(if *kind == Kind::Voice { "🔊" } else { "#" })) + .child(*name) + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + this.open(at); + cx.notify(); + })); + if *mentions > 0 { + row = row.child(div().class("men").child(mentions.to_string())); + } + panel = panel.child(row); + if *kind == Kind::Voice && !voice.is_empty() { + let mut ppl = div().class("voiceppl"); + for &m in voice { + let (n, c, ..) = &s.members[m]; + ppl = ppl.child(div().child(avatar(n, c, None, true).css("width", "18px").css("height", "18px").css("font-size", "10px")) + .child(n.clone())); + } + if s.in_voice == Some(at) { + ppl = ppl.child(div().child(avatar(&s.me.0, &s.me.1, None, true).css("width", "18px").css("height", "18px") + .css("font-size", "10px")).child(s.me.0.clone())); + } + panel = panel.child(ppl); + } + } + list = list.child(panel); + } + // you: the editor's footer + let me = div().class("me") + .child(avatar(&s.me.0, &s.me.1, Some(s.me.2), true)) + .child(div().class("who").child(b().css("color", s.me.1.clone()).child(s.me.0.clone())).child(small().child(s.me.2.name()))) + .child(Button().id(area_id("gear", k)).child("Settings").on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.show_settings = !this.show_settings; + cx.notify(); + }))); + // your panel sits under the list in the main view: a footer region is a header's height + Editor::new(div().class("main col").child(list).child(me)) + .toolbar(Region::new(rail).size(64).overlap(false)) +} + +fn chat_area(s: &Snap, weak: W, k: u32, area: AreaRef) -> Editor { + let at = s.areas.iter().find(|(a, _)| *a == area).map_or(s.active, |(_, c)| *c); + // a click anywhere in an area makes it the one keys and the channel list act on + let take = move |this: &mut Chat| { + this.focus_area = Some(area); + if !this.areas.iter().any(|(a, _)| *a == area) { + this.areas.push((area, at)); + } + this.active = this.of(Some(area)); + }; + let Some((_, view)) = s.views.iter().find(|(c, _)| *c == at) else { return Editor::new("") }; + if s.show_settings && k == 0 { + return settings_area(s, weak, k); + } + let header = div().class("hdr") + .child(div().class("hash").child(if view.kind == Kind::Voice { "🔊" } else { "#" })) + .child(div().class("name").child(view.name)) + .child(div().class("topic").child(view.topic)) + .child(Button().id(area_id("split", k)).child("Split").on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + // both halves keep this channel; the channel list goes on acting on this one + if let Some(new) = area.split(Axis::V, 0.5) { + for a in [area, new] { + match this.areas.iter_mut().find(|(x, _)| *x == a) { + Some(e) => e.1 = at, + None => this.areas.push((a, at)), + } + } + this.focus_area = Some(area); + } + cx.notify(); + }))) + .child(Button().id(area_id("max", k)).child("Maximize").on_click(move |_, _, _| area.maximize())); + if view.kind == Kind::Voice { + return voice_area(s, view, at, weak, k, header); + } + let (compact, avatars, show_ids, ..) = s.settings; + let mut lines = div().class("lines").child(div().class("day").child("Today")); + let mut last_author = usize::MAX; + let mut last_at = 0; + for l in &view.lines { + let (name, color, status, ..) = &s.members[l.author]; + let (name, color) = if l.author == 0 { (&s.me.0, &s.me.1) } else { (name, color) }; + let new_group = l.author != last_author || l.at > last_at + 5 || l.reply_to.is_some(); + last_author = l.author; + last_at = l.at; + let id = l.id; + let mut body = div(); + if let Some(r) = l.reply_to.and_then(|r| view.lines.iter().find(|x| x.id == r)) { + let (rn, rc, ..) = &s.members[r.author]; + body = body.child(div().class("quote").child(span().css("color", rc.clone()).child(format!("@{rn}"))) + .child(r.text.chars().take(60).collect::())); + } + if new_group || compact { + let mut head = div().child(span().class("author").css("color", color.clone()).child(name.clone())) + .child(span().class("ts").child(hhmm(l.at))); + if show_ids { + head = head.child(span().class("idtag").child(format!("#{id}"))); + } + body = body.child(head); + } + body = body.child(message_text(&l.text)); + if !l.reactions.is_empty() { + let mut re = div().class("reacts"); + for (j, &(e, n, mine)) in l.reactions.iter().enumerate() { + re = re.child(div().id(area_id(&format!("re{id}-{j}"), k)).class(if mine { "re mine" } else { "re" }) + .child(e).child(n.to_string()) + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.react(at, id, e); + cx.notify(); + }))); + } + body = body.child(re); + } + if s.picker == Some(id) { + let mut p = div().class("picker"); + for (j, e) in EMOJI.iter().enumerate() { + p = p.child(div().id(area_id(&format!("pick{id}-{j}"), k)).class("act").child(*e) + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.react(at, id, e); + cx.notify(); + }))); + } + body = body.child(p); + } + if !l.thread.is_empty() { + let n = l.thread.len(); + body = body.child(div().id(area_id(&format!("th{id}"), k)).class("threadlink") + .child(format!("{n} {} ›", if n == 1 { "reply" } else { "replies" })) + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.thread = Some(id); + cx.notify(); + }))); + } + let acts = div().class("acts") + .child(div().id(area_id(&format!("react{id}"), k)).class("act").child("☺+") + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.picker = if this.picker == Some(id) { None } else { Some(id) }; + cx.notify(); + }))) + .child(div().id(area_id(&format!("rep{id}"), k)).class("act").child("Reply") + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.replying = Some(id); + cx.notify(); + }))) + .child(div().id(area_id(&format!("thr{id}"), k)).class("act").child("Thread") + .on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + take(this); + this.thread = Some(id); + cx.notify(); + }))); + if new_group && !compact { + let av = if avatars { avatar(name, color, (l.author != 0).then_some(*status), false) } else { div().css("width", "36px") }; + lines = lines.child(div().class("grp").child(av).child(div().css("flex", "1").css("min-width", "0").css("position", "relative") + .child(div().id(area_id(&format!("l{id}"), k)).class("ln").css("padding-left", "0px").child(body).child(acts)))); + } else { + lines = lines.child(div().id(area_id(&format!("l{id}"), k)).class(if compact { "ln compact" } else { "ln" }).child(body).child(acts)); + } + } + let typing = s.typing.as_ref().filter(|(_, c)| *c == at); + let mut main = div().id(area_id("lines", k)).class("main col") + .on_mouse_down(MouseButton::Left, weak.listener(move |this: &mut Chat, _: &MouseDownEvent, _, _| take(this))) + .child(div().id(area_id(&format!("scroll{}-{}", at.0, at.1), k)).class("scroll").attr("data-stick", "always").child(lines)); + main = main.child(match typing { + Some((who, _)) => div().class("typing").child(i()).child(i()).child(i()).child(b().child(who.clone())).child(" is typing…"), + None => div().class("typing"), + }); + // the composer: the editor's footer (a Blender text field: Enter confirms, which sends) + let mut composer = div().class("composer"); + if let Some((_, who)) = s.replying.as_ref().filter(|_| s.active == at) { + composer = composer.child(div().class("replybar").child("Replying to").child(b().child(who.clone())) + .child(Button().id(area_id("cancel-reply", k)).child("✕").on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.replying = None; + cx.notify(); + })))); + } + composer = composer.child(TextField().id(area_id(&format!("compose{}", s.sent), k)) + .attr("placeholder", format!("Message #{} (Enter sends)", view.name)).css("width", "100%") + .on_change(weak.listener(move |this: &mut Chat, e: &ChangeEvent, _, cx| { + take(this); + this.post(at, &e.value); + cx.notify(); + }))); + let mut ed = Editor::new(main.child(composer)).header(Region::new(header).size(28)); + if let Some(t) = s.thread.and_then(|t| view.lines.iter().find(|l| l.id == t)) { + let (n, c, ..) = &s.members[t.author]; + let mut th = div().class("thread") + .child(div().class("th").child("Thread").child(div().class("grow")) + .child(Button().id(area_id("close-thread", k)).child("Close").on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.thread = None; + cx.notify(); + })))); + let mut body = div().css("flex", "1").css("overflow-y", "auto").child(div().class("grp") + .child(avatar(n, c, None, true)).child(div().child(span().class("author").css("color", c.clone()).child(n.clone())) + .child(message_text(&t.text)))); + for r in &t.thread { + let (rn, rc, ..) = &s.members[r.author]; + let (rn, rc) = if r.author == 0 { (&s.me.0, &s.me.1) } else { (rn, rc) }; + body = body.child(div().class("grp compact").child(avatar(rn, rc, None, true)) + .child(div().child(span().class("author").css("color", rc.clone()).child(rn.clone())) + .child(span().class("ts").child(hhmm(r.at))).child(message_text(&r.text)))); + } + th = th.child(body).child(div().css("padding", "8px").child(div().class("ts").child("Replies go in the thread while it is open."))); + ed = ed.sidebar(Region::new(th).size(300).overlap(false)); + } + ed +} + +fn voice_area(s: &Snap, view: &ChannelView, at: (usize, usize), weak: W, k: u32, header: Div) -> Editor { + let joined = s.in_voice == Some(at); + let t = now(); + let mut grid = div().class("voice"); + let mut people: Vec = view.voice.clone(); + if joined { + people.insert(0, 0); + } + if people.is_empty() { + grid = grid.child(div().css("color", "#8e9297").child("No one is here yet. Join to start talking.")); + } + for (slot, &m) in people.iter().enumerate() { + let (name, color, _, role, volume) = &s.members[m]; + let (name, color) = if m == 0 { (&s.me.0, &s.me.1) } else { (name, color) }; + // a voice level: speech-like bursts, each person their own rhythm; muted or deafened: none + let silent = (m == 0 && s.muted) || s.deafened; + let phase = m as f32 * 1.7; + let level = if silent { 0.0 } else { + ((t * 1.3 + phase).sin() * 0.5 + 0.5).powi(3) * (0.6 + 0.4 * (t * 9.0 + phase * 3.0).sin().abs()) + } * if m == 0 { 1.0 } else { *volume as f32 }; + let speaking = level > 0.25; + let meter = canvas(move |b, p| { + // twelve bars, the level spread across them with a little shimmer + let n = 12; + let w = b.size.width / n as f32; + for i in 0..n { + let x = b.origin.x + i as f32 * w; + let f = 1.0 - (i as f32 - n as f32 / 2.0).abs() / (n as f32 / 2.0); + let h = (level * f * 1.4 + 0.08).min(1.0) * b.size.height; + let col = if i as f32 / n as f32 > 0.8 && level > 0.8 { rgb(0xf04747) } else { rgb(0x43b581) }; + p.quad(Bounds { origin: point(x + 1.0, b.origin.y + (b.size.height - h) / 2.0), size: size(w - 2.0, h) }, + 1.5, col, Rgba::TRANSPARENT, 0.0); + } + }).class("meter"); + let mut card = div().id(area_id(&format!("v{m}"), k)).class(if speaking { "vcard speaking" } else { "vcard" }) + .child(avatar(name, color, None, false)).child(b().child(name.clone())).child(meter); + if m != 0 { + card = card.child(div().css("display", "flex").css("align-items", "center").css("gap", "6px") + .child(small().css("color", "#8e9297").child(*role)) + .child(NumberSlider().id(area_id(&format!("vol{m}"), k)).min(0.0).max(2.0).step(0.05).value(format!("{volume}")).w(px(100.0)) + .on_change(weak.listener(move |this: &mut Chat, e: &ChangeEvent, _, cx| { + this.members[m].volume = e.number.clamp(0.0, 2.0); + cx.notify(); + })))); + } + let _ = slot; + grid = grid.child(card); + } + let ctl = div().class("vctl") + .child(if joined { span().class("live").child("● Voice connected") } else { span().child("Not connected") }) + .child(div().class("grow")) + .child(Button().id(area_id("mute", k)).child(if s.muted { "Unmute" } else { "Mute" }).on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.muted = !this.muted; + cx.notify(); + }))) + .child(Button().id(area_id("deafen", k)).child(if s.deafened { "Undeafen" } else { "Deafen" }).on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.deafened = !this.deafened; + cx.notify(); + }))) + .child(Button().id(area_id("join", k)).child(if joined { "Leave" } else { "Join" }).on_click(weak.listener(move |this: &mut Chat, _: &ClickEvent, _, cx| { + this.in_voice = if this.in_voice == Some(at) { None } else { Some(at) }; + cx.notify(); + }))); + Editor::new(div().class("main col").child(div().class("scroll").child(grid)).child(ctl)).header(Region::new(header).size(28)) +} + +fn settings_area(s: &Snap, weak: W, k: u32) -> Editor { + let (compact, avatars, show_ids, accent, scale) = s.settings; + let check = |id: &str, label: &str, on: bool, f: fn(&mut Settings, bool)| { + div().class("srow").child(Checkbox().id(area_id(id, k)).checked(on) + .on_change(weak.listener(move |this: &mut Chat, e: &ChangeEvent, _, cx| { + f(&mut this.settings, e.checked); + cx.notify(); + }))).child(label.to_string()) + }; + let mut accents = div().class("srow").child(label().child("Accent")); + for (i, (name, _)) in ACCENTS.iter().enumerate() { + accents = accents.child(Radio().id(area_id(&format!("acc{i}"), k)).attr("name", area_id("accent", k)).checked(accent == i) + .on_change(weak.listener(move |this: &mut Chat, e: &ChangeEvent, _, cx| { + if e.checked { + this.settings.accent = i; + cx.notify(); + } + }))).child(*name); + } + let body = div().class("main").child(div().class("settings") + .child(h2().child("Settings")) + .child(details().id(area_id("set-profile", k)).open(true).child(summary().child("Profile")) + .child(div().class("srow").child(label().child("Display name")) + .child(TextField().id(area_id("name", k)).value(s.me.0.clone()).w(px(220.0)) + .on_change(weak.listener(|this: &mut Chat, e: &ChangeEvent, _, cx| { + let v = e.value.trim(); + if !v.is_empty() { + this.members[0].name = v.to_string(); + } + cx.notify(); + })))) + .child(div().class("srow").child(label().child("Name color")) + .child(ColorSwatch().id(area_id("namecolor", k)).value(s.me.1.clone()).w(px(80.0)) + .on_change(weak.listener(|this: &mut Chat, e: &ChangeEvent, _, cx| { + this.members[0].color.clone_from(&e.value); + cx.notify(); + })))) + .child(div().class("srow").child(label().child("Status")) + .child(Dropdown().id(area_id("status", k)).value(s.me.2.name()) + .children(Status::ALL.map(|st| option().child(st.name()))) + .on_change(weak.listener(|this: &mut Chat, e: &ChangeEvent, _, cx| { + if let Some(&st) = Status::ALL.get(e.number as usize) { + this.members[0].status = st; + } + cx.notify(); + }))))) + .child(details().id(area_id("set-look", k)).open(true).child(summary().child("Appearance")) + .child(accents) + .child(div().class("srow").child(label().child("UI scale")) + .child(NumberSlider().id(area_id("scale", k)).min(0.8).max(1.4).step(0.05).value(format!("{scale}")).w(px(220.0)) + .on_change(weak.listener(|this: &mut Chat, e: &ChangeEvent, _, cx| { + this.settings.scale = e.number.clamp(0.8, 1.4); + cx.notify(); + })))) + .child(check("compact", "Compact messages", compact, |st, v| st.compact = v)) + .child(check("avatars", "Show avatars", avatars, |st, v| st.avatars = v)) + .child(check("ids", "Developer mode (message ids)", show_ids, |st, v| st.show_ids = v))) + .child(div().class("srow").child(Button().id(area_id("done", k)).child("Done").on_click(weak.listener(|this: &mut Chat, _: &ClickEvent, _, cx| { + this.show_settings = false; + cx.notify(); + }))))); + Editor::new(body).header(Region::new(div().class("hdr").child(div().class("name").child("User settings"))).size(28)) +} + +fn members_area(s: &Snap, weak: W, k: u32) -> Editor { + let q = s.member_filter.to_lowercase(); + let mut list = div().class("main").child(div().css("padding", "8px 8px 0") + .child(TextField().id(area_id("member-filter", k)).attr("live", "").attr("placeholder", "Find a member") + .value(s.member_filter.clone()).css("width", "100%") + .on_input(weak.listener(|this: &mut Chat, e: &ChangeEvent, _, cx| { + this.member_filter.clone_from(&e.value); + cx.notify(); + })))); + let groups: [(&str, &[Status]); 2] = [("Online", &[Status::Online, Status::Idle, Status::Busy]), ("Offline", &[Status::Offline])]; + for (title, which) in groups { + let ms: Vec<(usize, &MemberRow)> = s.members.iter().enumerate() + .filter(|(i, m)| which.contains(&m.2) + && (q.is_empty() || (if *i == 0 { &s.me.0 } else { &m.0 }).to_lowercase().contains(&q) + || m.3.to_lowercase().contains(&q))) + .collect(); + list = list.child(div().class("grouphd").child(format!("{title} — {}", ms.len()))); + for (i, (name, color, status, role, _)) in ms { + let (name, color, status) = if i == 0 { (&s.me.0, &s.me.1, s.me.2) } else { (name, color, *status) }; + list = list.child(div().class(if status == Status::Offline { "mem off" } else { "mem" }) + .child(avatar(name, color, Some(status), true)) + .child(div().child(b().css("color", color.clone()).child(name.clone())).child(small().child(*role)))); + } + } + Editor::new(list).header(Region::new(div().class("hdr").child(div().class("name").child("Members"))).size(28)) +} + +// ========================================================================== +// The window + +impl Render for Chat { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + focus_root(w, &mut self.frames); + if self.tick() { + w.request_animation_frame(); + } + let weak = cx.weak_entity(); + let snap = Rc::new(self.snap()); + let editor = |make: fn(&Snap, W, u32, AreaRef) -> Editor| { + let snap = snap.clone(); + let n = std::cell::Cell::new(0u32); + move |area: &AreaRef| { + let k = n.get(); + n.set(k + 1); + make(&snap, weak, k, *area) + } + }; + let editors = Editors::new() + .editor("Channels", "OUTLINER", editor(|s, w, k, _| channels_area(s, w, k))) + .editor("Chat", "TEXT", editor(chat_area)) + .editor("Members", "USER", editor(|s, w, k, _| members_area(s, w, k))) + .editor("Settings", "PREFERENCES", editor(|s, w, k, _| settings_area(s, w, k))); + let screen = Screen().id("chat-screen").editors(editors).class("screen") + .layout(AreaSplit::v(0.22, "Channels", AreaSplit::v(0.78, "Chat", "Members"))); + let (accent_name, accent) = ACCENTS[self.settings.accent]; + let _ = accent_name; + let rgb_of = |h: &str| { + let v = u32::from_str_radix(h.trim_start_matches('#'), 16).unwrap_or(0x4772b3); + format!("{}, {}, {}", v >> 16 & 255, v >> 8 & 255, v & 255) + }; + let mut root = app().id("root").attr("tabindex", "0") + .css("font-size", format!("{}px", 14.0 * self.settings.scale)) + .css("--acc", accent).css("--acc-rgb", rgb_of(accent)) + .on_key_down(cx.listener(|this, e: &KeyDownEvent, w, cx| { + if this.key(e, w) { + // taken: Blender's own keys (a widget's undo, a hovered widget's shortcut) don't run too + cx.prevent_default(); + cx.stop_propagation(); + cx.notify(); + } + })) + .child(head().child(style().child(css()))) + .child(div().class("shell").child(screen)); + if let Some((t, _)) = &self.toast { + root = root.child(div().class("toast").child(t.clone())); + } + root + } +} + +/// Every feature in turn: channels, a reaction, the picker, a reply that is answered, a thread, a +/// second channel beside the first, servers, voice with a volume, settings that change the app. +fn storyboard(dir: String) -> Script { + story(dir, |s| { + s.play("00-open", &[0, 300]); + s.hover("lines"); + s.click("re1-0"); + s.play("01-react", &[0, 200]); + s.hover("l9"); + s.click("react9"); + s.play("02-picker", &[0, 200]); + s.click("pick9-3"); + s.play("03-picked", &[0, 200]); + s.hover("l9"); + s.click("rep9"); + s.play("04-replying", &[0, 200]); + s.click("compose0"); + s.type_text("on it, the rim is too hot on 052"); + s.key("Return"); + s.play("05-sent", &[0, 200, 1000, 2000]); + s.click("th6"); + s.play("06-thread", &[0, 300]); + s.click("compose1"); + s.type_text("rolled back here too"); + s.key("Return"); + s.play("07-thread-reply", &[0, 2000]); + s.click("close-thread"); + s.click("split"); + s.play("08-split", &[0, 300]); + s.click("ch0-1"); + s.play("09-second-channel", &[0, 300]); + s.click("srv2"); + s.play("10-server", &[0, 300]); + s.click("srv0"); + s.click("ch0-5"); + s.play("11-voice", &[0, 400, 900]); + let b = s.bounds("vol1"); + s.cx.simulate_drag(s.win, (b.origin.x + 40.0, b.origin.y + 8.0), (b.origin.x + 90.0, b.origin.y + 8.0)); + s.click("mute"); + s.play("12-voice-volume-mute", &[0, 400]); + s.click("gear"); + s.play("13-settings", &[0, 300]); + s.click("acc1"); + s.click("compact"); + let b = s.bounds("scale"); + s.cx.simulate_drag(s.win, (b.origin.x + 60.0, b.origin.y + 8.0), (b.origin.x + 150.0, b.origin.y + 8.0)); + s.play("14-settings-changed", &[0, 300]); + s.click("done"); + s.click("ch0-0"); + s.play("15-after-settings", &[0, 300]); + s.tick(12_000); + s.play("16-chatter", &[0, 300]); + s.click("member-filter"); + s.type_text("li"); + s.play("17-member-filter", &[0, 200]); + s.key("Return"); + s.cx.simulate_key_with(s.win, "z", "z", true, false); + s.play("18-unsend", &[0, 200]); + }) +} + +fn main() { + let (w, h) = size_arg((1440.0, 860.0)); + run_with(w, h, "BUI Chat", Chat::new, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/bui_files.rs b/demos/src/bin/bui_files.rs new file mode 100644 index 00000000..6ded3c15 --- /dev/null +++ b/demos/src/bin/bui_files.rs @@ -0,0 +1,1805 @@ +//! BUI Files: a file explorer built from Blender's own UI, on your real file system, which it +//! only reads. Everything that changes files (rename, new folder, delete, cut / copy / paste, drag +//! to move, duplicate, undo) works only inside its sandbox, a folder of sample files it makes in +//! the temp folder ("Sandbox" in Places); anywhere else those are refused, and the guard checks +//! every path before it touches the disk. +//! +//! Blender's screen holds three editors you can rearrange like Blender's (split, join, swap, +//! maximize, change an area's editor): Places (the sandbox, your folders, drives, bookmarks and a +//! folder tree), Files (a list or a thumbnail grid, a preview and properties sidebar on N) and +//! Operations (copies with progress bars, and the undo history). +//! +//! Mouse: click selects, Ctrl+click toggles, Shift+click a range, drag on empty space draws a +//! selection box, drag files onto a folder (in the list or Places) to move them, double-click +//! opens. Keys: arrows move (Shift extends), Enter opens, Backspace goes up, Alt+Left / Alt+Right +//! history, Ctrl+A all, typing jumps to a name, F2 renames, Delete trashes, Ctrl+C / X / V, +//! Ctrl+D duplicates, Ctrl+Shift+N a new folder, Ctrl+Z / Ctrl+Shift+Z undo / redo, Ctrl+L the +//! path, Ctrl+B bookmarks the folder, Ctrl+H hidden files, Ctrl+1 / Ctrl+2 list or grid. The +//! filter is Blender's own text field, live (it filters as you type). "Blender File Browser…" opens Blender's own File Browser in its window, to jump. +//! +//! `cargo run --release --bin bui_files`; `-- --storyboard DIR` drives it headlessly (in a fresh +//! sandbox). + +use std::collections::{BTreeSet, HashMap}; +use std::ffi::{c_char, c_int, CStr, CString}; +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use blenderui::prelude::*; +use blenderui::screen::{AreaRef, AreaSplit, Editor, Editors, Region, Screen}; +use bui_demos::story::{story, Story}; +use bui_demos::text::{edit, Edit}; +use bui_demos::{arg, focus_root, now, run_with, size_arg, Script}; +use bui_demos::act; + +const CSS: &str = r" +html, body { height: 100%; } +body { display: flex; flex-direction: column; font-size: 13px; color: #e6e6e6; -webkit-font-smoothing: antialiased; user-select: none; } +.top { height: 30px; flex-shrink: 0; display: flex; align-items: center; gap: 10px; padding: 0 10px; background: #232323; + border-bottom: 1px solid #161616; } +.brand { font-weight: 700; color: #f0f0f0; } +.sandbox-chip { padding: 2px 8px; border-radius: 9px; background: #3d4a2d; color: #cfe8a8; font-size: 11px; } +.ro-chip { padding: 2px 8px; border-radius: 9px; background: #3a3a3a; color: #b8b8b8; font-size: 11px; } +.spacer { flex: 1; } +.screen { flex: 1; min-height: 0; } +.status { height: 22px; flex-shrink: 0; display: flex; align-items: center; gap: 14px; padding: 0 10px; background: #232323; + border-top: 1px solid #161616; color: #9a9a9a; font-size: 11px; } +.status b { color: #d6d6d6; font-weight: 600; font-variant-numeric: tabular-nums; } +.msg { color: #e8c070; } +.msg.ok { color: #9ad27a; } + +/* regions */ +.hdr { height: 100%; display: flex; align-items: center; gap: 4px; padding: 0 6px; background: #2b2b2b; overflow: hidden; } +.hdr .sep { width: 1px; height: 16px; background: #444; margin: 0 3px; flex-shrink: 0; } +.hdr label { display: flex; align-items: center; gap: 4px; margin: 0 4px; white-space: nowrap; } +.side { height: 100%; overflow-y: auto; background: #2b2b2b; padding: 4px; box-sizing: border-box; } +.side details { margin-bottom: 4px; } +.prop { display: flex; gap: 8px; margin: 3px 6px; font-variant-numeric: tabular-nums; } +.prop span:first-child { width: 70px; flex-shrink: 0; color: #9a9a9a; } +.prop span + span { min-width: 0; overflow-wrap: anywhere; } +.preview { margin: 6px; border-radius: 4px; background: #1f1f1f; display: flex; align-items: center; justify-content: center; + min-height: 120px; overflow: hidden; } +.preview img { max-width: 100%; } +.preview pre { margin: 0; padding: 8px; width: 100%; box-sizing: border-box; font-size: 11px; color: #cfcfcf; white-space: pre-wrap; max-height: 260px; overflow: hidden; } +.footer { height: 100%; display: flex; align-items: center; gap: 12px; padding: 0 8px; background: #2b2b2b; color: #a8a8a8; font-size: 11px; + font-variant-numeric: tabular-nums; } + +/* fields of our own (keys go where we say: see `Field`) */ +.field { display: flex; align-items: center; height: 20px; padding: 0 6px; border-radius: 4px; background: #1d1d1d; color: #e6e6e6; + box-shadow: inset 0 0 0 1px #3d3d3d; cursor: text; min-width: 0; overflow: hidden; white-space: nowrap; } +.field.on { box-shadow: inset 0 0 0 1px var(--accent); background: #161616; } +.caret { width: 1px; height: 14px; background: #fff; margin-left: 1px; animation: blink 1s steps(1) infinite; } +/* the path takes the free room, so the controls after it never move (and the deepest folder shows) */ +.where { flex: 1; min-width: 0; display: flex; overflow: hidden; } +.crumbs { flex: 1; display: flex; align-items: center; justify-content: flex-end; min-width: 0; overflow: hidden; } +.crumb { padding: 2px 5px; border-radius: 3px; color: #cfcfcf; white-space: nowrap; cursor: pointer; + transition-property: background-color; transition-duration: 100ms; } +.crumb:hover { background: #3d3d3d; color: #fff; } +.crumb.drop { background: var(--accent); color: #fff; } +.slash { color: #666; } + +/* places */ +.places { height: 100%; overflow-y: auto; background: #303030; padding: 6px 4px; box-sizing: border-box; } +.place { display: flex; align-items: center; gap: 6px; padding: 3px 8px; border-radius: 4px; cursor: pointer; white-space: nowrap; + transition-property: background-color; transition-duration: 100ms; } +.place:hover { background: #3d3d3d; } +.place.on { background: #4a4a4a; } +.place.drop { background: var(--accent); } +.place .n { overflow: hidden; text-overflow: ellipsis; } +.tree-tw { width: 12px; flex-shrink: 0; color: #8a8a8a; text-align: center; } + +/* the file list */ +.list { height: 100%; overflow-y: auto; background: #303030; position: relative; box-sizing: border-box; } +table.rows { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } +.rows th { position: sticky; top: 0; z-index: 1; background: #2b2b2b; text-align: left; font-weight: 400; color: #a8a8a8; padding: 4px 8px; + cursor: pointer; white-space: nowrap; } +.rows th:hover { color: #fff; } +.rows th.num, .rows td.num { text-align: right; } +.rows td { padding: 3px 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 320px; } +.rows tr.it { transition-property: background-color; transition-duration: 80ms; } +.rows tr.it:hover { background: #3a3a3a; } +.rows tr.it:nth-child(even) { background: #333; } +.rows tr.it.sel, .rows tr.it.sel:hover { background: #33496b; } +.rows tr.it.cur td:first-child { border-left: 2px solid var(--accent); padding-left: 6px; } +.rows tr.it.drop { background: var(--accent); } +.rows tr.it.cut { opacity: 0.5; } +.name { display: flex; align-items: center; gap: 6px; } +.dim { color: #8a8a8a; } +.grid { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px; align-content: flex-start; } +.cell { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 6px; border-radius: 6px; box-sizing: border-box; + transition-property: background-color; transition-duration: 80ms; } +.cell:hover { background: #3a3a3a; } +.cell.sel, .cell.sel:hover { background: #33496b; } +.cell.cur { box-shadow: inset 0 0 0 1px var(--accent); } +.cell.drop { background: var(--accent); } +.cell.cut { opacity: 0.5; } +.cell .thumb { display: flex; align-items: center; justify-content: center; overflow: hidden; border-radius: 3px; } +.cell .thumb img { outline: 1px solid rgba(255,255,255,0.1); } +.cell .cap { width: 100%; text-align: center; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.empty { color: #8a8a8a; text-align: center; margin-top: 40px; } +.more { color: #8a8a8a; padding: 8px; text-align: center; } +.band { position: absolute; border: 1px solid var(--accent); background: rgba(71,114,179,0.18); pointer-events: none; } +.ghost { position: absolute; z-index: 10; padding: 3px 8px; border-radius: 4px; background: #222; box-shadow: 0 4px 14px rgba(0,0,0,0.5); + pointer-events: none; font-size: 11px; white-space: nowrap; } + +/* icons: drawn, a folder or a page with its kind's colour */ +.ic { position: relative; flex-shrink: 0; } +.ic.folder { border-radius: 2px 3px 3px 3px; background: #d6a64e; } +.ic.folder::before { content: ''; position: absolute; left: 0; top: -2px; width: 45%; height: 3px; border-radius: 2px 2px 0 0; background: #d6a64e; } +.ic.file { border-radius: 2px; background: #cfcfcf; } +.ic.file::after { content: ''; position: absolute; right: 0; top: 0; width: 30%; height: 30%; background: #8f8f8f; border-radius: 0 0 0 2px; } +.ic.k-image { background: #6fb3e0; } .ic.k-text { background: #dedede; } .ic.k-blend { background: #e87d0d; } +.ic.k-audio { background: #b07ee0; } .ic.k-archive { background: #b0a060; } .ic.k-data { background: #8ad08a; } + +/* operations */ +.ops { height: 100%; overflow-y: auto; background: #303030; padding: 8px; box-sizing: border-box; } +.job { margin-bottom: 8px; } +.job .what { display: flex; justify-content: space-between; font-variant-numeric: tabular-nums; margin-bottom: 3px; } +.job progress { width: 100%; } +.hist { display: flex; gap: 6px; padding: 2px 4px; font-variant-numeric: tabular-nums; } +.hist.undone { opacity: 0.45; text-decoration: line-through; } +.hist .k { color: #9a9a9a; width: 64px; flex-shrink: 0; } +.log { color: #a8a8a8; font-size: 11px; margin: 2px 4px; } +.log.bad { color: #e8a070; } +.log.fresh { animation: logIn 240ms cubic-bezier(0.2, 0, 0, 1); } +h4 { margin: 10px 4px 4px; color: #b8b8b8; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.6px; } + +@keyframes blink { 50% { opacity: 0; } } +@keyframes logIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } } +"; + +/// The most entries a folder is read to, and drawn (a narrower filter shows the rest). +const READ_MAX: usize = 20_000; +const DRAW_MAX: usize = 600; +/// Bytes a copy moves per frame: a big file's progress bar has something to show. +const COPY_STEP: usize = 192 * 1024; + +// --------------------------------------------------------------------------------------------- +// The sandbox: the one place this app writes + +fn sandbox_path() -> PathBuf { + std::env::temp_dir().join("bui_files_demo") +} + +/// A sample PNG: a procedural pattern `kind` (bricks, checker, noise, gradient, render). +fn sample_png(path: &Path, kind: u32, seed: u32) -> std::io::Result<()> { + let (w, h) = (192u32, 128u32); + let mut px = Vec::with_capacity((w * h * 3) as usize); + let hash = |x: u32, y: u32| ((x.wrapping_mul(374_761_393) ^ y.wrapping_mul(668_265_263) ^ seed.wrapping_mul(2_654_435_761)) >> 13) & 255; + for y in 0..h { + for x in 0..w { + let (r, g, b) = match kind { + 0 => { + let row = y / 16; + let off = if row % 2 == 0 { 0 } else { 16 }; + let mortar = y % 16 < 2 || (x + off) % 32 < 2; + if mortar { (200, 196, 186) } else { (150 + hash(x / 32, row) % 40, 70, 52) } + } + 1 => if (x / 16 + y / 16) % 2 == 0 { (230, 230, 230) } else { (40, 40, 40) }, + 2 => { + let v = hash(x / 3, y / 3); + (v, v, v) + } + 3 => (x * 255 / w, y * 255 / h, 200), + _ => { + // a "render": a lit sphere on a floor + let (cx, cy, r) = (96.0 + seed as f32 * 6.0, 58.0, 34.0); + let (dx, dy) = (x as f32 - cx, y as f32 - cy); + let d = (dx * dx + dy * dy).sqrt(); + if d < r { + let l = (1.0 - (dx + dy * 1.4) / (r * 2.6)).clamp(0.2, 1.0); + ((230.0 * l) as u32, (120.0 * l) as u32, (40.0 * l) as u32) + } else if y > 86 { + (60, 64, 72) + } else { + (28 + y / 4, 32 + y / 4, 44 + y / 3) + } + } + }; + px.extend_from_slice(&[r as u8, g as u8, b as u8]); + } + } + let file = fs::File::create(path)?; + let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w, h); + enc.set_color(png::ColorType::Rgb); + enc.set_depth(png::BitDepth::Eight); + enc.write_header().map_err(std::io::Error::other)?.write_image_data(&px).map_err(std::io::Error::other) +} + +/// Makes the sandbox and its sample files (`fresh`: from nothing, for a storyboard). +fn seed_sandbox(fresh: bool) -> std::io::Result { + let root = sandbox_path(); + if fresh && root.exists() && root == sandbox_path() { + fs::remove_dir_all(&root)?; + } + if root.exists() { + return Ok(root); + } + for d in ["Projects/Spaceship/renders", "Projects/Lighthouse", "Textures", "Documents", "Audio", ".trash"] { + fs::create_dir_all(root.join(d))?; + } + let text = |p: &str, s: &str| fs::write(root.join(p), s); + text("Documents/readme.txt", "This is the BUI Files sandbox.\n\nEverything here may be renamed, moved, copied or deleted:\nthe app writes nowhere else.\n")?; + text("Documents/todo.md", "# To do\n\n- [x] model the hull\n- [ ] UV the wings\n- [ ] bake the AO\n- [ ] render the turntable\n")?; + text("Documents/budget.csv", "item,cost\nrender farm,120\nHDRIs,35\ncoffee,48\n")?; + text("Projects/Spaceship/notes.md", "Spaceship\n=========\n\nScale: 1 unit = 1 m. Cycles, 256 samples, denoised.\n")?; + text("Projects/Lighthouse/scene.txt", "camera 35mm, f/2.8\nsun 4.5 W/m², 32° elevation\n")?; + text(".hidden_settings", "theme = dark\n")?; + fs::write(root.join("Projects/Spaceship/spaceship.blend"), b"BLENDER-v400 (a placeholder, not a real .blend)")?; + fs::write(root.join("Projects/Lighthouse/lighthouse.blend"), b"BLENDER-v400 (a placeholder)")?; + fs::write(root.join("Audio/hum.wav"), b"RIFF\0\0\0\0WAVE")?; + fs::write(root.join("Textures/textures.zip"), vec![0u8; 4096])?; + // a big one, so a copy has progress to show + fs::write(root.join("Projects/Spaceship/renders/cache.bin"), vec![7u8; 6 * 1024 * 1024])?; + for (name, kind) in [("bricks.png", 0), ("checker.png", 1), ("noise.png", 2), ("gradient.png", 3)] { + sample_png(&root.join("Textures").join(name), kind, 1)?; + } + for k in 1..=4u32 { + sample_png(&root.join(format!("Projects/Spaceship/renders/frame_{k:04}.png")), 4, k)?; + } + Ok(root) +} + +// --------------------------------------------------------------------------------------------- +// The model + +#[derive(Clone)] +struct Entry { + name: String, + path: PathBuf, + dir: bool, + size: u64, + modified: Option, + hidden: bool, +} + +impl Entry { + fn ext(&self) -> String { + if self.dir { String::new() } else { Path::new(&self.name).extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default() } + } + + fn kind(&self) -> &'static str { + if self.dir { + return "folder"; + } + match self.ext().as_str() { + "png" | "jpg" | "jpeg" | "webp" | "gif" | "bmp" | "tga" | "tif" | "tiff" | "hdr" | "exr" | "svg" => "image", + "txt" | "md" | "rs" | "py" | "toml" | "json" | "cfg" | "ini" | "log" | "c" | "h" | "js" | "ts" | "html" | "css" => "text", + "csv" | "tsv" => "data", + "blend" | "blend1" => "blend", + "wav" | "mp3" | "flac" | "ogg" | "m4a" => "audio", + "zip" | "7z" | "tar" | "gz" | "rar" => "archive", + _ => "file", + } + } + + fn is_image(&self) -> bool { + self.kind() == "image" && self.ext() != "exr" + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Sort { + Name, + Size, + Kind, + Modified, +} + +const SORTS: [(Sort, &str); 4] = [(Sort::Name, "Name"), (Sort::Size, "Size"), (Sort::Kind, "Type"), (Sort::Modified, "Modified")]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum View { + List, + Grid, +} + +/// One change on disk, with what undoes it. +#[derive(Clone)] +enum Op { + Rename { from: PathBuf, to: PathBuf }, + Mkdir(PathBuf), + /// Moved to the sandbox's trash (undo puts it back). + Trash { from: PathBuf, to: PathBuf }, + Move { from: PathBuf, to: PathBuf }, + /// A copy made (undo deletes it, to the trash). + Made(PathBuf), +} + +/// What the user did: one undo step of one or more ops. +#[derive(Clone)] +struct Step { + what: String, + ops: Vec, + undone: bool, +} + +/// A copy under way: files still to go, a frame's worth at a time. +struct Job { + label: String, + files: Vec<(PathBuf, PathBuf, u64)>, + total: u64, + done: u64, + open: Option<(fs::File, fs::File)>, + made: Vec, + /// Where a frame's bytes pass through (made once for the job). + buf: Box<[u8]>, +} + +#[derive(Clone, PartialEq, Eq)] +enum Field { + None, + Path, + Rename(PathBuf), +} + +#[derive(Clone, Copy)] +struct Band { + from: (f32, f32), + to: (f32, f32), + /// The selection before the box, which Ctrl adds to. + add: bool, +} + +#[derive(Clone)] +struct Drag { + paths: Vec, + from: (f32, f32), + at: (f32, f32), + live: bool, +} + +#[derive(Clone)] +struct Line { + text: String, + bad: bool, + at: f32, +} + +/// Something the pointer can land on, by its element id: an item of area `item`'s list, or +/// a folder (in the list or in Places) to drop on. +struct Target { + id: String, + path: PathBuf, + item: Option, + folder: bool, +} + +/// A [`Target`] where the last frame placed it. +struct Hit { + at: Bounds, + path: PathBuf, + item: Option, + folder: bool, +} + +struct Files { + root: PathBuf, + /// The sandbox as the file system resolves it: what every write is checked against. + canon: PathBuf, + dir: PathBuf, + entries: Vec, + error: Option, + back: Vec, + fwd: Vec, + sel: BTreeSet, + cursor: Option, + anchor: Option, + view: View, + /// How many times the view changed: the radios' ids (a clicked control keeps its own state + /// over `.checked()`, as an HTML input does, so a changed view makes them anew). + views: u32, + sort: Sort, + desc: bool, + hidden: bool, + thumb: f32, + filter: String, + field: Field, + draft: String, + bookmarks: Vec, + open_tree: BTreeSet, + tree_kids: HashMap>, + clip: Option<(Vec, bool)>, + steps: Vec, + job: Option, + log: Vec, + typed: (String, f32), + band: Option, + drag: Option, + /// The folder under a drag (a drop target), by its element id. + drop: Option, + /// A text file's first bytes, for the preview. + peek: Option<(PathBuf, String)>, + /// What the pointer can land on, by element id: this frame's items and folders. + targets: Vec, + /// The same, placed: where the last frame put them (a listener can't ask, so render reads it). + hits: Vec, + /// Columns of the grid at the last frame (arrow keys move by a row). + cols: usize, + headless: bool, + frames: u32, +} + +impl Files { + fn new(headless: bool) -> Self { + let root = seed_sandbox(headless).unwrap_or_else(|_| sandbox_path()); + let canon = root.canonicalize().unwrap_or_else(|_| root.clone()); + let mut f = Self { + root: root.clone(), + canon, + dir: root.clone(), + entries: Vec::new(), + error: None, + back: Vec::new(), + fwd: Vec::new(), + sel: BTreeSet::new(), + cursor: None, + anchor: None, + view: View::List, + views: 0, + sort: Sort::Name, + desc: false, + hidden: false, + thumb: 96.0, + filter: String::new(), + field: Field::None, + draft: String::new(), + bookmarks: vec![root.join("Textures")], + open_tree: BTreeSet::new(), + tree_kids: HashMap::new(), + clip: None, + steps: Vec::new(), + job: None, + log: Vec::new(), + typed: (String::new(), -10.0), + band: None, + drag: None, + drop: None, + peek: None, + targets: Vec::new(), + hits: Vec::new(), + cols: 6, + headless, + frames: 0, + }; + f.open_tree.insert(root); + f.read(); + f + } + + // -- reading -------------------------------------------------------------------------------- + + /// Reads the folder once (on arriving or after a change), never while drawing. + fn read(&mut self) { + self.entries.clear(); + self.error = None; + match fs::read_dir(&self.dir) { + Ok(rd) => { + for e in rd.flatten().take(READ_MAX) { + let name = e.file_name().to_string_lossy().into_owned(); + let meta = e.metadata().ok(); + let dir = meta.as_ref().is_some_and(fs::Metadata::is_dir); + let hidden = name.starts_with('.') || is_hidden_attr(meta.as_ref()); + self.entries.push(Entry { path: e.path(), dir, size: meta.as_ref().map_or(0, fs::Metadata::len), + modified: meta.as_ref().and_then(|m| m.modified().ok()), hidden, name }); + } + } + Err(e) => self.error = Some(e.to_string()), + } + self.sel.retain(|p| p.exists()); + self.tree_kids.remove(&self.dir); + } + + /// The entries shown: hidden ones only when asked, the filter, sorted (folders first). + fn visible(&self) -> Vec<&Entry> { + let f = self.filter.to_lowercase(); + let mut v: Vec<&Entry> = self.entries.iter() + .filter(|e| (self.hidden || !e.hidden) && (f.is_empty() || e.name.to_lowercase().contains(&f))) + .collect(); + v.sort_by(|a, b| { + let o = match self.sort { + Sort::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()), + Sort::Size => a.size.cmp(&b.size), + Sort::Kind => a.kind().cmp(b.kind()).then_with(|| a.ext().cmp(&b.ext())), + Sort::Modified => a.modified.cmp(&b.modified), + }; + b.dir.cmp(&a.dir).then(if self.desc { o.reverse() } else { o }) + }); + v + } + + fn tree_children(&mut self, dir: &Path) -> Vec { + if let Some(k) = self.tree_kids.get(dir) { + return k.clone(); + } + let mut kids: Vec = fs::read_dir(dir).map(|rd| rd.flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .filter(|e| self.hidden || !e.file_name().to_string_lossy().starts_with('.')) + .take(200).map(|e| e.path()).collect()).unwrap_or_default(); + kids.sort_by_key(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())); + self.tree_kids.insert(dir.to_path_buf(), kids.clone()); + kids + } + + // -- going places --------------------------------------------------------------------------- + + fn go(&mut self, dir: PathBuf) { + if dir == self.dir || !dir.is_dir() { + if !dir.is_dir() { + self.say(format!("Not a folder: {}", dir.display()), true); + } + return; + } + let from = std::mem::replace(&mut self.dir, dir); + self.back.push(from); + self.fwd.clear(); + self.arrive(); + } + + fn arrive(&mut self) { + self.typed.0.clear(); + self.sel.clear(); + self.cursor = None; + self.anchor = None; + self.filter.clear(); + self.read(); + // the tree shows the way here + let mut p = self.dir.clone(); + while let Some(parent) = p.parent().map(Path::to_path_buf) { + self.open_tree.insert(parent.clone()); + p = parent; + } + } + + fn history(&mut self, forward: bool) { + let (from, to) = if forward { (&mut self.fwd, &mut self.back) } else { (&mut self.back, &mut self.fwd) }; + if let Some(d) = from.pop() { + to.push(std::mem::replace(&mut self.dir, d)); + self.arrive(); + } + } + + fn up(&mut self) { + if let Some(p) = self.dir.parent().map(Path::to_path_buf) { + let here = self.dir.clone(); + self.go(p); + self.sel.insert(here.clone()); + self.cursor = Some(here); + } + } + + fn open(&mut self, path: &Path) { + if path.is_dir() { + self.go(path.to_path_buf()); + } else { + self.say(format!("{}: shown in the preview (opening files is up to you)", name_of(path)), false); + } + } + + // -- the guard ------------------------------------------------------------------------------ + + /// Whether `p` is inside the sandbox (what it would be, for a path that doesn't exist yet). + fn writable(&self, p: &Path) -> bool { + let real = p.canonicalize().ok().or_else(|| p.parent().and_then(|d| d.canonicalize().ok()).map(|d| d.join(p.file_name().unwrap_or_default()))); + real.is_some_and(|r| r.starts_with(&self.canon) && r != self.canon) + } + + /// Whether `p` is the sandbox itself (things go into it; it is never changed itself). + fn is_root(&self, p: &Path) -> bool { + p.canonicalize().is_ok_and(|c| c == self.canon) + } + + fn here_writable(&self) -> bool { + self.dir.canonicalize().is_ok_and(|d| d.starts_with(&self.canon)) + } + + fn refuse(&mut self) { + self.say(String::from("Read-only here: changes are made only in the Sandbox."), true); + } + + fn say(&mut self, text: String, bad: bool) { + self.log.push(Line { text, bad, at: now() }); + if self.log.len() > 60 { + self.log.remove(0); + } + } + + // -- changes (sandbox only) ----------------------------------------------------------------- + + /// Does `op` (forward) on the disk, both its paths checked first. + fn apply(&self, op: &Op) -> std::io::Result<()> { + let guard = |p: &Path| if self.writable(p) { Ok(()) } else { Err(std::io::Error::other("outside the sandbox")) }; + match op { + Op::Rename { from, to } | Op::Trash { from, to } | Op::Move { from, to } => { + guard(from)?; + guard(to)?; + if to.exists() { + return Err(std::io::Error::other(format!("{} exists", name_of(to)))); + } + fs::rename(from, to) + } + Op::Mkdir(p) => { + guard(p)?; + fs::create_dir(p) + } + Op::Made(_) => Ok(()), + } + } + + /// The op that undoes `op`. + fn inverse(&self, op: &Op) -> Op { + match op { + Op::Rename { from, to } => Op::Rename { from: to.clone(), to: from.clone() }, + Op::Move { from, to } => Op::Move { from: to.clone(), to: from.clone() }, + Op::Trash { from, to } => Op::Trash { from: to.clone(), to: from.clone() }, + Op::Mkdir(p) | Op::Made(p) => Op::Trash { from: p.clone(), to: self.trash_slot(p) }, + } + } + + fn trash_slot(&self, p: &Path) -> PathBuf { + let trash = self.root.join(".trash"); + let _ = fs::create_dir_all(&trash); + let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + trash.join(format!("{stamp}_{}", name_of(p))) + } + + /// Runs `ops` as one undo step named `what`; stops at the first refusal. + fn change(&mut self, what: String, ops: Vec) { + let mut done = Vec::new(); + for op in ops { + match self.apply(&op) { + Ok(()) => done.push(op), + Err(e) => { + self.say(format!("{what}: {e}"), true); + break; + } + } + } + if !done.is_empty() { + self.say(format!("{what} ({} item{})", done.len(), if done.len() == 1 { "" } else { "s" }), false); + self.steps.retain(|s| !s.undone); + self.steps.push(Step { what, ops: done, undone: false }); + } + self.read(); + } + + fn undo(&mut self, redo: bool) { + let Some(k) = (if redo { self.steps.iter().position(|s| s.undone) } else { self.steps.iter().rposition(|s| !s.undone) }) else { + self.say(String::from(if redo { "Nothing to redo" } else { "Nothing to undo" }), true); + return; + }; + let step = self.steps[k].clone(); + let ops: Vec = if redo { step.ops.clone() } else { step.ops.iter().rev().map(|o| self.inverse(o)).collect() }; + // a step redone after its copies were undone makes them again: copies are redone by copying + let mut ok = true; + for op in &ops { + if let Err(e) = self.apply(op) { + self.say(format!("{}: {e}", step.what), true); + ok = false; + break; + } + } + if ok { + if !redo { + // what the undo made (trash slots) is what a redo must take back + let fixed: Vec = step.ops.iter().zip(ops.iter().rev()).map(|(o, inv)| match (o, inv) { + (Op::Mkdir(_) | Op::Made(_), Op::Trash { from, to }) => Op::Trash { from: to.clone(), to: from.clone() }, + _ => o.clone(), + }).collect(); + self.steps[k].ops = fixed; + } + self.steps[k].undone = !redo; + self.say(format!("{} {}", if redo { "Redo" } else { "Undo" }, step.what), false); + } + self.read(); + } + + fn targets_or_refuse(&mut self) -> Option> { + if self.sel.is_empty() { + self.say(String::from("Nothing selected"), true); + return None; + } + if !self.sel.iter().all(|p| self.writable(p)) { + self.refuse(); + return None; + } + Some(self.sel.iter().cloned().collect()) + } + + fn trash(&mut self) { + let Some(paths) = self.targets_or_refuse() else { return }; + let ops = paths.iter().map(|p| Op::Trash { from: p.clone(), to: self.trash_slot(p) }).collect(); + self.change(String::from("Delete"), ops); + } + + fn new_folder(&mut self) { + if !self.here_writable() { + return self.refuse(); + } + let mut k = 1; + let mut p = self.dir.join("New Folder"); + while p.exists() { + k += 1; + p = self.dir.join(format!("New Folder {k}")); + } + self.change(String::from("New Folder"), vec![Op::Mkdir(p.clone())]); + self.sel = BTreeSet::from([p.clone()]); + self.cursor = Some(p.clone()); + self.begin_rename(p); + } + + fn begin_rename(&mut self, p: PathBuf) { + if !self.writable(&p) { + return self.refuse(); + } + self.draft = name_of(&p); + self.field = Field::Rename(p); + } + + fn finish_rename(&mut self, p: &Path) { + let name = self.draft.trim().to_owned(); + if name.is_empty() || name.contains(['/', '\\']) || name == name_of(p) { + return; + } + let to = p.with_file_name(&name); + self.change(String::from("Rename"), vec![Op::Rename { from: p.to_path_buf(), to: to.clone() }]); + self.sel = BTreeSet::from([to.clone()]); + self.cursor = Some(to); + } + + fn move_into(&mut self, paths: &[PathBuf], dir: &Path) { + if !self.writable(dir) && !self.is_root(dir) { + return self.refuse(); + } + let ops: Vec = paths.iter().filter(|p| p.parent() != Some(dir) && !dir.starts_with(p)) + .map(|p| Op::Move { from: p.clone(), to: dir.join(name_of(p)) }).collect(); + if ops.is_empty() { + return; + } + if !paths.iter().all(|p| self.writable(p)) { + return self.refuse(); + } + self.change(format!("Move to {}", name_of(dir)), ops); + } + + /// Copies `paths` into `dir`: a job a frame's worth at a time (names made unique). + fn copy_into(&mut self, paths: &[PathBuf], dir: &Path, label: &str) { + if !(self.writable(dir) || self.is_root(dir)) { + return self.refuse(); + } + let mut files = Vec::new(); + let mut made = Vec::new(); + for p in paths { + let mut to = dir.join(name_of(p)); + let mut k = 1; + while to.exists() { + k += 1; + let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let ext = p.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + to = dir.join(format!("{stem} {k}{ext}")); + } + made.push(to.clone()); + collect_copy(p, &to, &mut files); + } + // folders are made at once; files fill in over frames + for (_, to, size) in &files { + if *size == u64::MAX { + let _ = fs::create_dir_all(to); + } + } + files.retain(|f| f.2 != u64::MAX); + let total = files.iter().map(|f| f.2).sum(); + self.job = Some(Job { label: label.to_owned(), files, total, done: 0, open: None, made, buf: vec![0; 64 * 1024].into_boxed_slice() }); + } + + /// The copy moves on by one frame's worth. + fn step_job(&mut self) { + let Some(mut job) = self.job.take() else { return }; + let mut budget = COPY_STEP; + while budget > 0 { + if job.open.is_none() { + let Some((from, to, _)) = job.files.first() else { break }; + if !self.writable(to) { + job.files.clear(); + break; + } + if let (Ok(a), Ok(b)) = (fs::File::open(from), fs::File::create(to)) { + job.open = Some((a, b)); + } else { + job.files.remove(0); + continue; + } + } + let Some((src, dst)) = &mut job.open else { break }; + let want = budget.min(job.buf.len()); + match src.read(&mut job.buf[..want]) { + Ok(0) | Err(_) => { + job.open = None; + job.files.remove(0); + } + Ok(n) => { + let _ = dst.write_all(&job.buf[..n]); + job.done += n as u64; + budget = budget.saturating_sub(n); + } + } + } + if !job.files.is_empty() { + self.job = Some(job); + return; + } + let ops = job.made.iter().map(|p| Op::Made(p.clone())).collect(); + self.steps.retain(|s| !s.undone); + self.steps.push(Step { what: job.label.clone(), ops, undone: false }); + self.say(format!("{} ({} item{}, {})", job.label, job.made.len(), if job.made.len() == 1 { "" } else { "s" }, size_text(job.total)), false); + self.read(); + } + + fn paste(&mut self) { + let Some((paths, cut)) = self.clip.clone() else { + return self.say(String::from("The clipboard is empty"), true); + }; + let dir = self.dir.clone(); + if cut { + self.move_into(&paths, &dir); + self.clip = None; + } else { + self.copy_into(&paths, &dir, "Paste"); + } + } + + fn duplicate(&mut self) { + let Some(paths) = self.targets_or_refuse() else { return }; + let dir = self.dir.clone(); + self.copy_into(&paths, &dir, "Duplicate"); + } + + // -- selection ------------------------------------------------------------------------------ + + fn click(&mut self, path: &Path, ctrl: bool, shift: bool) { + let vis: Vec = self.visible().iter().map(|e| e.path.clone()).collect(); + if shift && let Some(a) = self.anchor.clone() { + let (i, j) = (vis.iter().position(|p| *p == a), vis.iter().position(|p| p == path)); + if let (Some(i), Some(j)) = (i, j) { + if !ctrl { + self.sel.clear(); + } + self.sel.extend(vis[i.min(j)..=i.max(j)].iter().cloned()); + } + } else if ctrl { + if !self.sel.remove(path) { + self.sel.insert(path.to_path_buf()); + } + self.anchor = Some(path.to_path_buf()); + } else { + self.sel = BTreeSet::from([path.to_path_buf()]); + self.anchor = Some(path.to_path_buf()); + } + self.cursor = Some(path.to_path_buf()); + self.peek_text(); + } + + fn set_view(&mut self, view: View) { + if self.view != view { + self.view = view; + self.views += 1; + } + } + + /// Arrow keys: by one, or by a row of the grid. + fn step(&mut self, by: isize, extend: bool) { + let p = { + let vis = self.visible(); + let Some(last) = vis.len().checked_sub(1) else { return }; + let at = self.cursor.as_ref().and_then(|c| vis.iter().position(|e| e.path == *c)); + vis[at.map_or(0, |i| i.saturating_add_signed(by).min(last))].path.clone() + }; + if extend { + self.click(&p, false, true); + self.cursor = Some(p); + } else { + self.click(&p, false, false); + } + } + + /// Typing jumps to the first name that starts with what was typed (within a second). + fn type_ahead(&mut self, ch: &str) { + let t = now(); + if t - self.typed.1 > 1.0 { + self.typed.0.clear(); + } + self.typed = (format!("{}{}", self.typed.0, ch.to_lowercase()), t); + let hit = self.visible().iter().find(|e| e.name.to_lowercase().starts_with(&self.typed.0)).map(|e| e.path.clone()); + if let Some(p) = hit { + self.click(&p, false, false); + } + } + + fn peek_text(&mut self) { + let Some(c) = self.cursor.clone() else { return }; + if self.peek.as_ref().is_some_and(|(p, _)| *p == c) { + return; + } + let entry = self.entries.iter().find(|e| e.path == c); + if entry.is_some_and(|e| matches!(e.kind(), "text" | "data")) { + let mut buf = vec![0u8; 4096]; + let n = fs::File::open(&c).and_then(|mut f| f.read(&mut buf)).unwrap_or(0); + self.peek = Some((c, String::from_utf8_lossy(&buf[..n]).into_owned())); + } else { + self.peek = None; + } + } + + // -- keys ----------------------------------------------------------------------------------- + + fn key(&mut self, e: &KeyDownEvent) -> bool { + let k = &e.keystroke; + let (ctrl, shift, alt) = (k.modifiers.control, k.modifiers.shift, k.modifiers.alt); + // our own fields take the keys while they are being typed in + if self.field != Field::None { + return match edit(&mut self.draft, k, 260) { + Edit::Typed => true, + Edit::Submit => { + match std::mem::replace(&mut self.field, Field::None) { + Field::Path => { + let p = PathBuf::from(self.draft.trim()); + self.go(p); + } + Field::Rename(p) => self.finish_rename(&p), + Field::None => {} + } + true + } + Edit::Leave => { + self.field = Field::None; + true + } + Edit::Ignored => false, + }; + } + let key = k.key.as_str(); + let grid = if self.view == View::Grid { self.cols.max(1).cast_signed() } else { 1 }; + match (key, ctrl, shift, alt) { + ("Left", _, _, true) => self.history(false), + ("Right", _, _, true) => self.history(true), + ("Up", false, s, _) => self.step(-grid, s), + ("Down", false, s, _) => self.step(grid, s), + ("Left", false, s, _) if self.view == View::Grid => self.step(-1, s), + ("Right", false, s, _) if self.view == View::Grid => self.step(1, s), + ("Return" | "KP_Enter", ..) => { + if let Some(c) = self.cursor.clone() { + self.open(&c); + } + } + ("BackSpace", false, ..) => self.up(), + ("F2", ..) => { + if let Some(c) = self.cursor.clone() { + self.begin_rename(c); + } + } + ("Delete", ..) => self.trash(), + ("Escape", ..) => { + self.sel.clear(); + self.clip = None; + } + ("a" | "A", true, ..) => self.sel = self.visible().iter().map(|e| e.path.clone()).collect(), + ("c" | "C", true, ..) => self.clip = (!self.sel.is_empty()).then(|| (self.sel.iter().cloned().collect(), false)), + ("x" | "X", true, ..) => { + if self.targets_or_refuse().is_some() { + self.clip = Some((self.sel.iter().cloned().collect(), true)); + } + } + ("v" | "V", true, ..) => self.paste(), + ("d" | "D", true, ..) => self.duplicate(), + ("n" | "N", true, true, _) => self.new_folder(), + ("z" | "Z", true, s, _) => self.undo(s), + ("y" | "Y", true, ..) => self.undo(true), + ("l" | "L", true, ..) => { + self.draft = self.dir.display().to_string(); + self.field = Field::Path; + } + ("b" | "B", true, ..) => self.bookmark(), + ("h" | "H", true, ..) => { + self.hidden = !self.hidden; + self.tree_kids.clear(); + } + ("1", true, ..) => self.set_view(View::List), + ("2", true, ..) => self.set_view(View::Grid), + _ => match &k.key_char { + Some(c) if !ctrl && !alt && c.chars().all(|ch| ch.is_alphanumeric() || ch == '.' || ch == '_') => self.type_ahead(c), + _ => return false, + }, + } + true + } + + fn bookmark(&mut self) { + if self.bookmarks.contains(&self.dir) { + self.bookmarks.retain(|b| *b != self.dir); + } else { + self.bookmarks.push(self.dir.clone()); + } + } + + // -- the pointer: boxes and drags ---------------------------------------------------------- + + /// The items of area `n` a selection box covers (as the last frame placed them). + fn band_select(&mut self, n: u32) { + let Some(b) = self.band else { return }; + let (x0, x1) = (b.from.0.min(b.to.0), b.from.0.max(b.to.0)); + let (y0, y1) = (b.from.1.min(b.to.1), b.from.1.max(b.to.1)); + if !b.add { + self.sel.clear(); + } + let r = |h: &Hit| (h.at.origin.x, h.at.origin.y, h.at.origin.x + h.at.size.width, h.at.origin.y + h.at.size.height); + self.sel.extend(self.hits.iter().filter(|h| h.item == Some(n)).filter(|h| { + let (l, t, rt, bt) = r(h); + l < x1 && rt > x0 && t < y1 && bt > y0 + }).map(|h| h.path.clone())); + } + + /// The folder under the pointer, if any. + fn target_at(&self, (x, y): (f32, f32)) -> Option { + self.hits.iter().filter(|h| h.folder).find(|h| { + let a = h.at; + x >= a.origin.x && x < a.origin.x + a.size.width && y >= a.origin.y && y < a.origin.y + a.size.height + }).map(|h| h.path.clone()) + } +} + +/// Every file under `from` (a file, or a folder's files) as (from, to, size); folders as +/// (from, to, `u64::MAX`) so they are made first. +fn collect_copy(from: &Path, to: &Path, out: &mut Vec<(PathBuf, PathBuf, u64)>) { + if from.is_dir() { + out.push((from.to_path_buf(), to.to_path_buf(), u64::MAX)); + if let Ok(rd) = fs::read_dir(from) { + for e in rd.flatten().take(5000) { + collect_copy(&e.path(), &to.join(e.file_name()), out); + } + } + } else { + out.push((from.to_path_buf(), to.to_path_buf(), fs::metadata(from).map_or(0, |m| m.len()))); + } +} + +#[cfg(windows)] +fn is_hidden_attr(meta: Option<&fs::Metadata>) -> bool { + use std::os::windows::fs::MetadataExt; + meta.is_some_and(|m| m.file_attributes() & 0x2 != 0) +} + +#[cfg(not(windows))] +const fn is_hidden_attr(_: Option<&fs::Metadata>) -> bool { + false +} + +fn name_of(p: &Path) -> String { + p.file_name().map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into_owned()) +} + +fn size_text(b: u64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + let mut v = b as f64; + let mut u = 0; + while v >= 1024.0 && u < UNITS.len() - 1 { + v /= 1024.0; + u += 1; + } + if u == 0 { format!("{b} B") } else { format!("{v:.1} {}", UNITS[u]) } +} + +/// `YYYY-MM-DD HH:MM` (UTC) of a file time: the civil date from the day count. +fn date_text(t: Option) -> String { + let Some(s) = t.and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs().cast_signed()) else { return String::from("—") }; + let (days, rem) = (s.div_euclid(86_400), s.rem_euclid(86_400)); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!("{y}-{m:02}-{d:02} {:02}:{:02}", rem / 3600, rem / 60 % 60) +} + +/// The places on this machine: the sandbox first, then the user's folders and the drives. +fn places(root: &Path) -> Vec<(String, PathBuf)> { + let mut out = vec![(String::from("Sandbox"), root.to_path_buf())]; + let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from); + if let Some(h) = home { + out.push((String::from("Home"), h.clone())); + for d in ["Desktop", "Documents", "Downloads", "Pictures", "Music", "Videos"] { + if h.join(d).is_dir() { + out.push((d.to_owned(), h.join(d))); + } + } + } + out.push((String::from("Temp"), std::env::temp_dir())); + if cfg!(windows) { + for l in b'C'..=b'Z' { + let p = PathBuf::from(format!("{}:\\", l as char)); + if p.is_dir() { + out.push((format!("Drive {}:", l as char), p)); + } + } + } else { + out.push((String::from("Root"), PathBuf::from("/"))); + } + out +} + +// --------------------------------------------------------------------------------------------- +// Blender's File Browser, the kit's (not in blenderui-sys: declared here) + +unsafe extern "C" { + fn BK_file_dialog(title: *const c_char, mode: c_int, dir: *const c_char, file: *const c_char, + filters: *const *const c_char, nfilters: c_int, multiple: c_int, r_paths: *mut *mut *mut c_char) -> c_int; + fn BK_file_dialog_free(paths: *mut *mut c_char); +} + +/// Blender's File Browser in its own window, picking a folder (`None`: cancelled, or no window host). +fn blender_pick_folder(start: &Path) -> Option { + let title = CString::new("Jump to Folder").ok()?; + let dir = CString::new(start.display().to_string()).ok()?; + let empty = CString::new("").ok()?; + let mut paths: *mut *mut c_char = std::ptr::null_mut(); + // SAFETY: NUL-terminated strings alive for the call, no filters; the kit fills `paths` + // (NULL-terminated) when it returns a count > 0, which we free with its own call. + let n = unsafe { BK_file_dialog(title.as_ptr(), 2, dir.as_ptr(), empty.as_ptr(), std::ptr::null(), 0, 0, &raw mut paths) }; + if n <= 0 || paths.is_null() { + return None; + } + // SAFETY: at least one entry, a NUL-terminated string the kit owns until freed below. + let first = unsafe { CStr::from_ptr(*paths) }.to_string_lossy().into_owned(); + // SAFETY: the array the call gave us, freed once. + unsafe { BK_file_dialog_free(paths) }; + Some(PathBuf::from(first)) +} + +// --------------------------------------------------------------------------------------------- +// Drawing + +type Weak = WeakEntity; + +fn icon(e: &Entry, size: f32) -> Div { + let (w, h) = if e.dir { (size, size * 0.74) } else { (size * 0.78, size) }; + let class = if e.dir { String::from("ic folder") } else { format!("ic file k-{}", e.kind()) }; + div().class(class).css("width", format!("{w}px")).css("height", format!("{h}px")) +} + +/// A field of ours (the path, a name being changed): the draft and a caret. +fn field(id: String, text: &str, width: &str) -> Div { + div().id(id).class("field on").css("width", width).child(span().child(text.to_owned())).child(div().class("caret")) +} + +/// What the editors need of the app, copied for their factories. +struct Snap { + dir: PathBuf, + root: PathBuf, + items: Vec, + shown: usize, + error: Option, + sel: BTreeSet, + cursor: Option, + view: View, + views: u32, + /// The column sorted by, and whether backwards. + order: (Sort, bool), + hidden: bool, + thumb: f32, + filter: String, + field: Field, + draft: String, + cut: BTreeSet, + /// How far back and forward the history goes. + back: usize, + fwd: usize, + writable: bool, + drop: Option, + places: Vec<(String, PathBuf)>, + bookmarks: Vec, + tree: Vec<(PathBuf, usize, bool, bool)>, + peek: Option<(PathBuf, String)>, + job: Option<(String, u64, u64, usize)>, + steps: Vec, + log: Vec, + headless: bool, +} + +/// Element ids for one area's editor: `{area}{n}-{name}`, so two copies of an editor (a split) +/// never share one. +fn ids(area: &'static str, n: u32) -> impl Fn(&str) -> String { + move |x| format!("{area}{n}-{x}") +} + +fn files_editor(s: &Snap, weak: Weak, n: u32) -> Editor { + let id = ids("fl", n); + // the header: history, the path (breadcrumbs, or our own field), the view, sort, filter + let mut crumbs = div().class("crumbs"); + let mut acc = PathBuf::new(); + for (k, comp) in s.dir.components().enumerate() { + acc.push(comp); + let label = comp.as_os_str().to_string_lossy().trim_end_matches(['\\', '/']).to_owned(); + if label.is_empty() { + continue; + } + if k > 0 { + crumbs = crumbs.child(span().class("slash").child("›")); + } + let to = acc.clone(); + crumbs = crumbs.child(div().id(id(&format!("cr{k}"))).class(if s.drop.as_ref() == Some(&to) { "crumb drop" } else { "crumb" }) + .child(label).on_click(act(weak, move |this, _: &ClickEvent| this.go(to.clone())))); + } + let path = if s.field == Field::Path { + field(id("path"), &s.draft, "100%") + } else { + crumbs.id(id("crumbs")) + }; + let mut sort = Dropdown().id(id("sort")).on_change(act(weak, |this, e: &ChangeEvent| { + this.sort = SORTS.get(e.number as usize).map_or(Sort::Name, |s| s.0); + })); + for (srt, name) in SORTS { + sort = sort.child(option().selected(srt == s.order.0).child(name)); + } + let vk = s.views; + let header = div().class("hdr") + .child(Button().id(id("back")).child("◀").disabled(s.back == 0).on_click(act(weak, |this, _: &ClickEvent| this.history(false)))) + .child(Button().id(id("fwd")).child("▶").disabled(s.fwd == 0).on_click(act(weak, |this, _: &ClickEvent| this.history(true)))) + .child(Button().id(id("up")).child("Up").on_click(act(weak, |this, _: &ClickEvent| this.up()))) + .child(div().class("sep")) + .child(div().class("where").child(path)) + .child(Button().id(id("edit")).child("Path…").on_click(act(weak, |this, _: &ClickEvent| { + this.draft = this.dir.display().to_string(); + this.field = Field::Path; + }))) + .child(label().child(Radio().id(id(&format!("vlist{vk}"))).attr("name", format!("view{n}{vk}")).checked(s.view == View::List) + .on_change(act(weak, |this, e: &ChangeEvent| if e.checked { this.set_view(View::List) }))).child("List")) + .child(label().child(Radio().id(id(&format!("vgrid{vk}"))).attr("name", format!("view{n}{vk}")).checked(s.view == View::Grid) + .on_change(act(weak, |this, e: &ChangeEvent| if e.checked { this.set_view(View::Grid) }))).child("Grid")) + .child(div().class("sep")) + .child(sort) + .child(label().child(Checkbox().id(id("desc")).checked(s.order.1).on_change(act(weak, |this, e: &ChangeEvent| this.desc = e.checked))).child("Desc")) + .child(label().child(Checkbox().id(id("hidden")).checked(s.hidden).on_change(act(weak, |this, e: &ChangeEvent| { + this.hidden = e.checked; + this.tree_kids.clear(); + }))).child("Hidden")) + .child(div().class("sep")) + // Blender's text field, live: it filters as you type (like Blender's own filter fields) + .child(TextField().id(id("filter")).attr("live", "").placeholder("Filter").value(s.filter.clone()).css("width", "130px") + .on_input(act(weak, |this, e: &ChangeEvent| this.filter.clone_from(&e.value)))); + + // the list or the grid + let mut list = div().id(id("list")).class("list") + .on_pointer_down(weak.listener(move |this: &mut Files, e: &PointerEvent, w, cx| { + // a press on empty space starts a box (the items stop theirs from getting here) + let p = (e.position.x.0, e.position.y.0); + this.band = Some(Band { from: p, to: p, add: e.modifiers.control || e.modifiers.shift }); + if !e.modifiers.control && !e.modifiers.shift { + this.sel.clear(); + } + this.field = Field::None; + w.set_pointer_capture(cx); + cx.notify(); + })) + .on_pointer_move(weak.listener(move |this: &mut Files, e: &PointerEvent, w, cx| { + let p = (e.position.x.0, e.position.y.0); + if let Some(b) = &mut this.band { + b.to = p; + this.band_select(n); + cx.notify(); + } else if let Some(d) = &mut this.drag { + d.at = p; + if !d.live && (p.0 - d.from.0).abs() + (p.1 - d.from.1).abs() > 6.0 { + // a drag now: the list holds the pointer, wherever it goes (Places too) + d.live = true; + w.set_pointer_capture(cx); + } + let at = this.target_at(p); + this.drop = at.filter(|t| !this.drag.as_ref().is_some_and(|d| d.paths.contains(t))); + cx.notify(); + } + })) + .on_pointer_up(weak.listener(move |this: &mut Files, _: &PointerEvent, w, cx| { + this.band = None; + if let Some(d) = this.drag.take() { + if d.live && let Some(t) = this.drop.take() { + this.move_into(&d.paths, &t); + } + this.drop = None; + } + w.release_pointer_capture(cx); + cx.notify(); + })); + let item_events = |d: Div, e: &Entry| { + let (p1, p2) = (e.path.clone(), e.path.clone()); + d.on_pointer_down(weak.listener(move |this: &mut Files, ev: &PointerEvent, w, cx| { + let m = ev.modifiers; + if !this.sel.contains(&p1) || m.control || m.shift { + this.click(&p1, m.control, m.shift); + } else { + this.cursor = Some(p1.clone()); + this.peek_text(); + } + this.field = Field::None; + // a drag of the selection (moves into a folder it is dropped on) + let at = (ev.position.x.0, ev.position.y.0); + this.drag = Some(Drag { paths: this.sel.iter().cloned().collect(), from: at, at, live: false }); + let _ = w; + cx.stop_propagation(); + cx.notify(); + })) + .on_double_click(act(weak, move |this, _: &ClickEvent| this.open(&p2))) + }; + let hidden_more = s.shown.saturating_sub(s.items.len()); + if s.view == View::List { + let head = |k: Sort, label: &'static str, class: &'static str| { + let arrow = if s.order.0 == k { if s.order.1 { " ▾" } else { " ▴" } } else { "" }; + th().id(id(&format!("h{label}"))).class(class).child(format!("{label}{arrow}")) + // a header is no empty space: a press here starts no box (which would take the click) + .on_pointer_down(weak.listener(|_: &mut Files, _: &PointerEvent, _, cx| cx.stop_propagation())) + .on_click(act(weak, move |this, _: &ClickEvent| { + if this.sort == k { this.desc = !this.desc } else { (this.sort, this.desc) = (k, false) } + })) + }; + let mut body = tbody(); + for (k, e) in s.items.iter().enumerate() { + let mut class = String::from("it"); + if s.sel.contains(&e.path) { class.push_str(" sel"); } + if s.cursor.as_ref() == Some(&e.path) { class.push_str(" cur"); } + if s.drop.as_ref() == Some(&e.path) { class.push_str(" drop"); } + if s.cut.contains(&e.path) { class.push_str(" cut"); } + let name_cell = if let Field::Rename(p) = &s.field && *p == e.path { + div().class("name").child(icon(e, 14.0)).child(field(id("rename"), &s.draft, "220px")) + } else { + div().class("name").child(icon(e, 14.0)).child(span().class(if e.hidden { "dim" } else { "" }).child(e.name.clone())) + }; + body = body.child(item_events(tr().id(id(&format!("it{k}"))).class(class) + .child(td().child(name_cell)) + .child(td().class("num").child(if e.dir { String::from("—") } else { size_text(e.size) })) + .child(td().class("dim").child(if e.dir { String::from("Folder") } else if e.ext().is_empty() { String::from("File") } else { format!("{} file", e.ext().to_uppercase()) })) + .child(td().class("dim").child(date_text(e.modified))), e)); + } + list = list.child(table().class("rows") + .child(thead().child(tr().child(head(Sort::Name, "Name", "")).child(head(Sort::Size, "Size", "num")) + .child(head(Sort::Kind, "Type", "")).child(head(Sort::Modified, "Modified", "")))) + .child(body)); + } else { + let mut grid = div().class("grid"); + let t = s.thumb; + for (k, e) in s.items.iter().enumerate() { + let mut class = String::from("cell"); + if s.sel.contains(&e.path) { class.push_str(" sel"); } + if s.cursor.as_ref() == Some(&e.path) { class.push_str(" cur"); } + if s.drop.as_ref() == Some(&e.path) { class.push_str(" drop"); } + if s.cut.contains(&e.path) { class.push_str(" cut"); } + let thumb = div().class("thumb").css("width", format!("{t}px")).css("height", format!("{}px", t * 0.75)); + let thumb = if e.is_image() { + thumb.child(img().src(e.path.display().to_string()).css("max-width", format!("{t}px")).css("max-height", format!("{}px", t * 0.75))) + } else { + thumb.child(icon(e, t * 0.5)) + }; + let cap = if let Field::Rename(p) = &s.field && *p == e.path { + field(id("rename"), &s.draft, &format!("{t}px")) + } else { + div().class("cap").child(e.name.clone()) + }; + grid = grid.child(item_events(div().id(id(&format!("it{k}"))).class(class).css("width", format!("{}px", t + 16.0)) + .child(thumb).child(cap), e)); + } + list = list.child(grid); + } + // under the column headers, so they stay put + if let Some(err) = &s.error { + list = list.child(div().class("empty").child(format!("Can't read this folder: {err}"))); + } else if s.items.is_empty() { + list = list.child(div().class("empty").child(if s.filter.is_empty() { "Empty folder" } else { "Nothing matches the filter" })); + } + if hidden_more > 0 { + list = list.child(div().class("more").child(format!("{hidden_more} more: narrow them down with the filter"))); + } + // the sidebar: preview and properties of the item under the cursor + let cur = s.cursor.as_ref().and_then(|c| s.items.iter().find(|e| e.path == *c)); + let side = match cur { + Some(e) => { + let preview = if e.is_image() { + div().class("preview").child(img().src(e.path.display().to_string()).css("max-width", "100%").css("max-height", "220px")) + } else if let Some((_, txt)) = s.peek.as_ref().filter(|(p, _)| *p == e.path) { + div().class("preview").child(pre().child(txt.clone())) + } else { + div().class("preview").child(icon(e, 64.0)) + }; + let prop = |k: &str, v: String| div().class("prop").child(span().child(k.to_owned())).child(span().child(v)); + div().class("side") + .child(details().open(true).child(summary().child("Preview")).child(preview)) + .child(details().open(true).child(summary().child("Properties")) + .child(prop("Name", e.name.clone())) + .child(prop("Kind", if e.dir { String::from("Folder") } else { e.kind().to_owned() })) + .child(prop("Size", if e.dir { String::from("—") } else { format!("{} ({} bytes)", size_text(e.size), e.size) })) + .child(prop("Modified", date_text(e.modified))) + .child(prop("Location", e.path.parent().map(|p| p.display().to_string()).unwrap_or_default())) + .child(prop("Writable", String::from(if e.path.starts_with(&s.root) { "Yes (sandbox)" } else { "No (read-only here)" })))) + } + None => div().class("side").child(div().class("preview").child(span().class("dim").child("Select a file to preview it"))), + }; + let total: u64 = s.items.iter().filter(|e| s.sel.contains(&e.path)).map(|e| e.size).sum(); + let footer = div().class("footer") + .child(span().child(format!("{} item{}", s.shown, if s.shown == 1 { "" } else { "s" }))) + .child(span().child(format!("{} selected ({})", s.sel.len(), size_text(total)))) + .child(div().class("spacer")) + .child(span().child("Thumbnails")) + .child(NumberSlider().id(id("thumb")).min(48.0).max(192.0).step(8.0).value(format!("{}", s.thumb)).css("width", "150px") + .on_change(act(weak, |this, e: &ChangeEvent| this.thumb = e.number as f32))) + .child(Button().id(id("newdir")).child("New Folder").disabled(!s.writable).on_click(act(weak, |this, _: &ClickEvent| this.new_folder()))) + .child(Button().id(id("browse")).child("Blender File Browser…").disabled(s.headless).on_click(act(weak, |this, _: &ClickEvent| { + if let Some(p) = blender_pick_folder(&this.dir) { + this.go(p); + } + }))); + Editor::new(list).header(header) + .sidebar(Region::new(side).size(260).overlap(false).hotkey("n")) + .footer(Region::new(footer).overlap(false)) +} + +fn places_editor(s: &Snap, weak: Weak, n: u32) -> Editor { + let id = ids("pl", n); + let mut col = div().class("places").child(h4().child("Places")); + let row = |rid: String, label: String, path: &PathBuf, depth: usize, twisty: Option<(bool, PathBuf)>, folder: bool| { + let on = s.dir == *path; + let drop = s.drop.as_ref() == Some(path); + let to = path.clone(); + let mut d = div().id(rid).class(if drop { "place drop" } else if on { "place on" } else { "place" }) + .css("padding-left", format!("{}px", 8 + depth * 12)); + if let Some((open, p)) = twisty { + d = d.child(div().class("tree-tw").child(if open { "▾" } else { "▸" }).on_click(act(weak, move |this, _: &ClickEvent| { + if !this.open_tree.remove(&p) { + this.open_tree.insert(p.clone()); + } + }))); + } + if folder { + d = d.child(div().class("ic folder").css("width", "13px").css("height", "10px")); + } + d.child(span().class("n").child(label)).on_click(act(weak, move |this, _: &ClickEvent| this.go(to.clone()))) + }; + for (k, (name, p)) in s.places.iter().enumerate() { + col = col.child(row(id(&format!("place{k}")), name.clone(), p, 0, None, true)); + } + col = col.child(h4().child("Bookmarks")); + if s.bookmarks.is_empty() { + col = col.child(div().class("log").child("Ctrl+B bookmarks the folder")); + } + for (k, b) in s.bookmarks.iter().enumerate() { + col = col.child(row(id(&format!("bm{k}")), name_of(b), b, 0, None, true)); + } + col = col.child(h4().child("Sandbox Tree")); + for (k, (p, depth, open, has_kids)) in s.tree.iter().enumerate() { + col = col.child(row(id(&format!("tree{k}")), name_of(p), p, *depth, has_kids.then(|| (*open, p.clone())), true)); + } + Editor::new(col).header(div().class("hdr").child(b().child("Places"))) +} + +fn ops_editor(s: &Snap, weak: Weak, n: u32) -> Editor { + let id = ids("op", n); + let mut col = div().class("ops"); + if let Some((label, done, total, left)) = &s.job { + col = col.child(div().class("job") + .child(div().class("what").child(span().child(format!("{label}: {left} file{} left", if *left == 1 { "" } else { "s" }))) + .child(span().child(format!("{} of {}", size_text(*done), size_text(*total))))) + .child(ProgressBar().id(id("job")).max(1.0).value(format!("{:.3}", if *total == 0 { 1.0 } else { *done as f64 / *total as f64 })))); + } + col = col.child(h4().child("History")); + if s.steps.is_empty() { + col = col.child(div().class("log").child("Nothing done yet. Changes work in the Sandbox, and Ctrl+Z undoes them.")); + } + for (k, st) in s.steps.iter().enumerate().rev() { + col = col.child(div().id(id(&format!("h{k}"))).class(if st.undone { "hist undone" } else { "hist" }) + .child(span().class("k").child(format!("#{}", k + 1))).child(span().child(format!("{} · {} item{}", st.what, st.ops.len(), if st.ops.len() == 1 { "" } else { "s" })))); + } + col = col.child(h4().child("Log")); + let t = now(); + for l in s.log.iter().rev().take(30) { + let mut class = String::from(if l.bad { "log bad" } else { "log" }); + if t - l.at < 0.3 { + class.push_str(" fresh"); + } + col = col.child(div().class(class).child(l.text.clone())); + } + let header = div().class("hdr").child(b().child("Operations")) + .child(div().class("spacer")) + .child(Button().id(id("undo")).child("Undo").disabled(!s.steps.iter().any(|x| !x.undone)).on_click(act(weak, |this, _: &ClickEvent| this.undo(false)))) + .child(Button().id(id("redo")).child("Redo").disabled(!s.steps.iter().any(|x| x.undone)).on_click(act(weak, |this, _: &ClickEvent| this.undo(true)))); + Editor::new(col).header(header) +} + +impl Files { + fn snap(&mut self) -> Snap { + self.peek_text(); + let vis: Vec = self.visible().into_iter().cloned().collect(); + let shown = vis.len(); + let items: Vec = vis.into_iter().take(DRAW_MAX).collect(); + // the sandbox's tree, as far as it is open + let mut tree = Vec::new(); + let mut stack = vec![(self.root.clone(), 0usize)]; + while let Some((p, depth)) = stack.pop() { + let kids = self.tree_children(&p); + let open = self.open_tree.contains(&p); + tree.push((p.clone(), depth, open, !kids.is_empty())); + if open && tree.len() < 400 { + for k in kids.into_iter().rev() { + stack.push((k, depth + 1)); + } + } + } + Snap { + dir: self.dir.clone(), + root: self.root.clone(), + items, + shown, + error: self.error.clone(), + sel: self.sel.clone(), + cursor: self.cursor.clone(), + view: self.view, + views: self.views, + order: (self.sort, self.desc), + hidden: self.hidden, + thumb: self.thumb, + filter: self.filter.clone(), + field: self.field.clone(), + draft: self.draft.clone(), + cut: self.clip.as_ref().filter(|c| c.1).map(|c| c.0.iter().cloned().collect()).unwrap_or_default(), + back: self.back.len(), + fwd: self.fwd.len(), + writable: self.here_writable(), + drop: self.drop.clone(), + places: places(&self.root), + bookmarks: self.bookmarks.clone(), + tree, + peek: self.peek.clone(), + job: self.job.as_ref().map(|j| (j.label.clone(), j.done, j.total, j.files.len())), + steps: self.steps.clone(), + log: self.log.clone(), + headless: self.headless, + } + } +} + +impl Render for Files { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + focus_root(w, &mut self.frames); + self.step_job(); + // frames only while something moves: a copy, a fresh log line, a caret (CSS blinks it) + if self.job.is_some() || self.log.last().is_some_and(|l| now() - l.at < 0.3) { + w.request_animation_frame(); + } + // the grid's columns, from the list's width at the last frame + if let Some(b) = w.bounds_of("fl0-list") { + self.cols = ((b.size.width - 16.0) / (self.thumb + 22.0)).floor().max(1.0) as usize; + } + let s = Rc::new(self.snap()); + // where the last frame's targets went (a listener can't ask: it only sees its own path) + self.hits.clear(); + for t in self.targets.drain(..) { + if let Some(at) = w.bounds_of(&t.id) { + self.hits.push(Hit { at, path: t.path, item: t.item, folder: t.folder }); + } + } + // this frame's, while a box or a drag is on: the items (box select, drops on folders) + // and Places' folders, by the ids the editors give them + let mut add = |id: String, path: &Path, item: Option, folder: bool| { + self.targets.push(Target { id, path: path.to_path_buf(), item, folder }); + }; + for n in (0..4).filter(|_| self.band.is_some() || self.drag.is_some()) { + for (k, e) in s.items.iter().enumerate() { + add(format!("fl{n}-it{k}"), &e.path, Some(n), e.dir); + } + for (k, p) in s.places.iter().enumerate() { + add(format!("pl{n}-place{k}"), &p.1, None, true); + } + for (k, p) in s.bookmarks.iter().enumerate() { + add(format!("pl{n}-bm{k}"), p, None, true); + } + for (k, p) in s.tree.iter().enumerate() { + add(format!("pl{n}-tree{k}"), &p.0, None, true); + } + } + let weak = cx.weak_entity(); + let counter = || std::cell::Cell::new(0u32); + let next = |c: &std::cell::Cell| { + let n = c.get(); + c.set(n + 1); + n + }; + let (s1, s2, s3) = (s.clone(), s.clone(), s.clone()); + let (n1, n2, n3) = (counter(), counter(), counter()); + let editors = Editors::new() + .editor("Files", "FILEBROWSER", move |_: &AreaRef| files_editor(&s1, weak, next(&n1))) + .editor("Places", "BOOKMARKS", move |_: &AreaRef| places_editor(&s2, weak, next(&n2))) + .editor("Operations", "INFO", move |_: &AreaRef| ops_editor(&s3, weak, next(&n3))); + + let writable = self.here_writable(); + let last = self.log.last().cloned(); + // the selection box and the dragged files, over everything (in window coordinates) + let overlay = { + let mut o = div().css("position", "absolute").css("left", "0").css("top", "0").css("width", "0").css("height", "0"); + if let Some(b) = self.band { + let (x0, y0) = (b.from.0.min(b.to.0), b.from.1.min(b.to.1)); + o = o.child(div().class("band").css("left", format!("{x0}px")).css("top", format!("{y0}px")) + .css("width", format!("{}px", (b.to.0 - b.from.0).abs())).css("height", format!("{}px", (b.to.1 - b.from.1).abs()))); + } + if let Some(d) = self.drag.as_ref().filter(|d| d.live) { + o = o.child(div().class("ghost").css("left", format!("{}px", d.at.0 + 14.0)).css("top", format!("{}px", d.at.1 + 10.0)) + .child(format!("{} item{}{}", d.paths.len(), if d.paths.len() == 1 { "" } else { "s" }, + self.drop.as_ref().map_or(String::new(), |t| format!(" → {}", name_of(t)))))); + } + o + }; + let top = div().class("top").child(span().class("brand").child("BUI Files")) + .child(span().class(if writable { "sandbox-chip" } else { "ro-chip" }).child(if writable { "Sandbox: changes allowed" } else { "Read-only here" })) + .child(div().class("spacer")) + .child(span().css("color", "#9a9a9a").child(self.dir.display().to_string())); + let status = div().class("status") + .child(span().child(kbd().child("F2")).child(" rename ").child(kbd().child("Del")).child(" delete ") + .child(kbd().child("Ctrl+C")).child(" copy ").child(kbd().child("Ctrl+V")).child(" paste ").child(kbd().child("Ctrl+Z")).child(" undo ") + .child(kbd().child("Ctrl+L")).child(" path ").child(kbd().child("N")).child(" sidebar")) + .child(div().class("spacer")) + .child(match last { + Some(l) => span().class(if l.bad { "msg" } else { "msg ok" }).child(l.text), + None => span(), + }); + let root = app().id("root").css("--accent", "#4772b3").css("position", "relative") + // keys typed into a Blender text field (the filter, a number typed into the slider) reach + // the page too: no shortcuts then + .on_key_down(cx.listener(|this, e: &KeyDownEvent, w, cx| { + // a key we act on is taken: Blender's own handling (Ctrl+Z over widget edits, a + // hovered field's Backspace) doesn't run as well + if !w.text_field_focused() && this.key(e) { + cx.prevent_default(); + cx.notify(); + } + })) + .child(style().child(CSS)) + .child(top) + .child(Screen().id("screen").class("screen").editors(editors) + .layout(AreaSplit::v(0.2, "Places", AreaSplit::h(0.74, "Files", "Operations")))) + .child(status); + root.child(overlay) + } +} + +/// Every feature, in the sandbox only: opening folders, the grid and its slider, selecting by +/// click, Ctrl, Shift, the box and Ctrl+A, the preview, renaming, a new folder, copy and paste +/// (with progress), a drag into a folder, delete, undo and redo, the filter, the path field, +/// sorting, hidden files, bookmarks, and a refusal outside the sandbox. +fn storyboard(s: &mut Story) { + let dbl = |s: &mut Story, id: &str| { + let (x, y) = s.centre(id); + s.cx.simulate_click(s.win, x, y); + s.cx.simulate_click(s.win, x, y); + }; + s.play("00-open", &[0, 300]); + s.cx.simulate_mouse_move(s.win, 600.0, 300.0); + // into Textures (sorted: Audio, Documents, Projects, Textures, then files), grid view + dbl(s, "fl0-it3"); + s.play("01-textures", &[0, 200]); + s.click("fl0-vgrid0"); + s.play("02-grid", &[0, 200]); + s.click("fl0-it0"); + s.play("03-preview-image", &[0, 200]); + // the thumbnail slider (Blender's: dragged) + let b = s.bounds("fl0-thumb"); + s.cx.simulate_drag(s.win, (b.origin.x + 20.0, b.origin.y + b.size.height / 2.0), (b.origin.x + b.size.width - 10.0, b.origin.y + b.size.height / 2.0)); + s.play("04-big-thumbs", &[0, 200]); + // the pointer stays on the slider: Backspace is the app's (taken), so the slider keeps its size + // back up, into Documents, list view, a text preview + s.key("BackSpace"); + s.click("fl0-vlist1"); + s.play("04b-list", &[0]); + dbl(s, "fl0-it1"); + s.play("05a-documents", &[0]); + s.click("fl0-it1"); + s.play("05-text-preview", &[0, 200]); + // rename todo.md (F2) to tasks.md + s.key("Down"); + s.key("F2"); + for _ in 0..7 { + s.key("BackSpace"); + } + s.type_text("tasks.md"); + s.play("06-renaming", &[0]); + s.key("Return"); + s.play("07-renamed", &[0, 300]); + // a new folder, named Exports + s.cx.simulate_key_with(s.win, "", "n", true, true); + for _ in 0..12 { + s.key("BackSpace"); + } + s.type_text("Exports"); + s.key("Return"); + s.play("08-new-folder", &[0, 300]); + // copy readme.txt, paste it into Exports + s.tick(1100); + s.type_text("readme"); + s.ctrl("c", false); + s.tick(1100); + s.type_text("exports"); + s.key("Return"); + s.ctrl("v", false); + s.play("09-pasted", &[0, 100, 400]); + s.key("BackSpace"); + // a big copy with progress: up to the sandbox, Projects/Spaceship/renders, cache.bin + s.key("BackSpace"); + s.tick(1100); + s.type_text("projects"); + s.key("Return"); + s.tick(1100); + s.type_text("spaceship"); + s.key("Return"); + s.tick(1100); + s.type_text("renders"); + s.key("Return"); + s.tick(1100); + s.type_text("cache"); + s.ctrl("d", false); + s.play("10-copying", &[0, 16, 48, 120, 400]); + // select frames 1..3 with Shift, then drag them onto the folder… there is none here: make one + s.click("fl0-it1"); + let (x, y) = s.centre("fl0-it3"); + s.cx.simulate_click_with(s.win, x, y, false, true); + s.play("11-shift", &[0]); + // a selection box: from the empty space under the rows, up over the last three + let z = s.bounds("fl0-it4"); + s.cx.simulate_drag(s.win, (z.origin.x + 300.0, z.origin.y + z.size.height + 40.0), + (z.origin.x + 120.0, z.origin.y - z.size.height * 1.5)); + s.play("12-box", &[0, 200]); + // Ctrl+A, then delete everything selected, then undo it + s.ctrl("a", false); + s.key("Delete"); + s.play("13-deleted", &[0, 300]); + // Ctrl+Z is the app's (taken): the slider dragged earlier keeps its size + s.ctrl("z", false); + s.play("14-undone", &[0, 300]); + // up to Spaceship, find notes.md by typing, and drag it into renders + s.key("BackSpace"); + s.tick(1100); + s.type_text("notes"); + let from = s.centre("fl0-it1"); + let to = s.centre("fl0-it0"); + s.cx.simulate_drag(s.win, from, to); + s.play("15-dragged", &[0, 300]); + // the filter (Blender's live text field) and the hidden files + s.click("fl0-filter"); + s.type_text("ren"); + s.play("16-filter", &[0, 200]); + s.key("Escape"); + s.click("pl0-place0"); + s.ctrl("h", false); + s.play("17-hidden", &[0, 200]); + // sort by size by its header, then go read-only (Temp) and try to delete there: refused + s.click("fl0-hSize"); + s.click("fl0-hSize"); + s.play("18-sorted", &[0, 200]); + s.ctrl("b", false); + s.ctrl("l", false); + for _ in 0..200 { + s.key("BackSpace"); + } + s.type_text(&std::env::temp_dir().display().to_string()); + s.key("Return"); + s.key("Down"); + s.key("Delete"); + s.play("19-refused", &[0, 300]); + s.click("pl0-place0"); + s.play("20-back-home", &[0, 300]); +} + +fn main() { + let (w, h) = size_arg((1360.0, 820.0)); + let board = arg("--storyboard").map(|dir| -> Script { story(dir, storyboard) }); + let headless = board.is_some(); + run_with(w, h, "BUI Files", move || Files::new(headless), board); +} diff --git a/demos/src/bin/bui_mail.rs b/demos/src/bin/bui_mail.rs new file mode 100644 index 00000000..8fc5e123 --- /dev/null +++ b/demos/src/bin/bui_mail.rs @@ -0,0 +1,1463 @@ +//! BUI Mail: an email client built from Blender's own interface. The window is a Blender screen: +//! folders, the message list and the reader are areas you can resize, split, join and maximize +//! (drag an area's corner, or the buttons in each header), each with Blender's header, toolbar and +//! sidebar regions. Every control is a real Blender widget: the account and sort menus are +//! Blender dropdowns, the checkboxes, number fields (drag to scrub, double-click to type `7*2`), +//! sliders, color swatches (Blender's color picker), text fields and the text editor. +//! +//! What it does: two accounts with their own mailboxes; folders with unread counts, and labels +//! whose colors you pick; live search; sort; Shift / Ctrl click multi-select (with a checkbox per +//! row); star and flag; conversations as Blender panels in the reader; reply, reply-all and forward +//! into a compose view (To / Cc / Subject fields, a body editor, a signature menu, attachments +//! that upload with a progress bar); a send that waits five seconds so you can undo it; drag a +//! message onto a folder or a label; rules (auto-archive older than N days, mark read on open, +//! snippets, density); every action undoable; and mail that keeps arriving. +//! +//! Keys (over the list or reader): J / K next / previous, Enter or O open, E archive, Del / # delete, +//! S star, U toggle read, R reply, A reply all, F forward, C compose, / search, Ctrl+A select all, +//! Esc clear, Ctrl+Z undo. +//! +//! `cargo run --release --bin bui_mail`, `-- --storyboard DIR` drives it headlessly. + +use std::rc::Rc; +use std::sync::OnceLock; + +use blenderui::prelude::*; +use blenderui::screen::{AreaRef, AreaSplit, Axis, Editor, Editors, Region, Screen}; +use bui_demos::story::story; +use bui_demos::{arg, focus_root, now, run_with, size_arg, Script}; +use bui_demos::area_id; + +// ========================================================================== +// The mailbox + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Folder { + Inbox, + Sent, + Drafts, + Archive, + Spam, + Trash, +} + +impl Folder { + const ALL: [Self; 6] = [Self::Inbox, Self::Sent, Self::Drafts, Self::Archive, Self::Spam, Self::Trash]; + + const fn name(self) -> &'static str { + match self { + Self::Inbox => "Inbox", + Self::Sent => "Sent", + Self::Drafts => "Drafts", + Self::Archive => "Archive", + Self::Spam => "Spam", + Self::Trash => "Trash", + } + } + + const fn glyph(self) -> &'static str { + match self { + Self::Inbox => "▤", + Self::Sent => "➤", + Self::Drafts => "✎", + Self::Archive => "▣", + Self::Spam => "⚠", + Self::Trash => "✕", + } + } +} + +/// What the list shows: a folder, a smart view, or a label. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum View { + Folder(Folder), + Starred, + Unread, + Label(usize), +} + +#[derive(Clone)] +struct Msg { + id: u32, + account: usize, + folder: Folder, + thread: u32, + from: &'static str, + addr: &'static str, + to: String, + subject: String, + body: String, + /// Minutes before "now" (the demo's clock starts at Tuesday 09:41). + age: u32, + unread: bool, + starred: bool, + flagged: bool, + /// Bit `k`: label `k`. + labels: u8, + /// 0 low, 1 normal, 2 high. + importance: u8, + attachments: Vec<(String, u32)>, +} + +struct Label { + name: &'static str, + color: String, +} + +const ACCOUNTS: [(&str, &str); 2] = [("Mira Okafor", "mira@lumen.studio"), ("Mira (personal)", "mira.ok@postbox.net")]; + +/// (account, folder, thread, from, address, subject, body, minutes ago, unread, starred, labels, attachment) +type Seed = (usize, Folder, u32, &'static str, &'static str, &'static str, &'static str, u32, bool, bool, u8, Option<(&'static str, u32)>); + +const SEEDS: &[Seed] = &[ + (0, Folder::Inbox, 1, "Jonas Weber", "jonas@lumen.studio", "Render farm is back online", "All 24 nodes report in again. The queue drained overnight; the shot 040 renders finished at 06:12. If you see a frame with fireflies, flag it and I'll re-queue it with more samples.", 14, true, false, 0b0001, None), + (0, Folder::Inbox, 2, "Ana Lima", "ana@lumen.studio", "Lighting notes for shot 052", "Rim light is too hot on the left shoulder. Try 0.6 of the current strength and warm it a little. Otherwise the mood is right. Attached the paintover.", 38, true, true, 0b0001, Some(("paintover_052.png", 2480))), + (0, Folder::Inbox, 3, "Build Bot", "bot@ci.lumen.studio", "✔ nightly #1842 passed", "All 312 tests passed in 14m 08s. Artifacts: addon-1.9.4.zip, docs.tar.gz.", 55, false, false, 0b0100, None), + (0, Folder::Inbox, 4, "Priya Shah", "priya@orbitfilms.co", "Contract draft v3", "Hi Mira, here is v3 with the changes from Friday. Section 4 now caps revisions at three rounds. Let me know if legal has comments by Thursday.", 92, true, false, 0b0001, Some(("contract_v3.pdf", 412))), + (0, Folder::Inbox, 4, "Mira Okafor", "mira@lumen.studio", "Re: Contract draft v3", "Thanks Priya. Forwarding to legal now; one question on the payment schedule in 6.2 — is net 30 from delivery or from approval?", 80, false, false, 0b0001, None), + (0, Folder::Inbox, 4, "Priya Shah", "priya@orbitfilms.co", "Re: Contract draft v3", "From approval. I'll make that explicit in v4.", 61, true, false, 0b0001, None), + (0, Folder::Inbox, 5, "Tomas Reyes", "tomas@lumen.studio", "Geometry nodes setup for the forest", "I rebuilt the scatter with a density mask from the path. Viewport is at 40 fps now with instances. Can you check it on your machine?", 130, false, false, 0b0001, None), + (0, Folder::Inbox, 6, "Asset Shelf", "noreply@assetshelf.io", "Your weekly asset digest", "12 new materials, 4 HDRIs and a pack of foliage were added to libraries you follow.", 240, false, false, 0, None), + (0, Folder::Inbox, 7, "Ana Lima", "ana@lumen.studio", "Lunch?", "Thai place downstairs at 12:30?", 300, false, false, 0, None), + (0, Folder::Inbox, 8, "Kenji Mori", "kenji@hollowpine.jp", "Rigging review tomorrow", "Agenda: the face rig controls, the shoulder twist and the IK/FK switch. 30 minutes should do.", 420, true, false, 0b0001, None), + (0, Folder::Inbox, 9, "Finance", "finance@lumen.studio", "Expense report approved", "Your October expenses (4 items, 1,284.00) were approved and will be paid on Friday.", 600, false, false, 0b0010, None), + (0, Folder::Inbox, 10, "Build Bot", "bot@ci.lumen.studio", "✘ nightly #1841 failed", "2 tests failed: test_uv_unwrap_islands, test_bake_normals. See the log for details.", 1500, false, true, 0b0100, Some(("log_1841.txt", 88))), + (0, Folder::Inbox, 10, "Jonas Weber", "jonas@lumen.studio", "Re: ✘ nightly #1841 failed", "The bake test is flaky on the old GPU node. I pinned it to the new pool.", 1440, false, false, 0b0100, None), + (0, Folder::Inbox, 11, "Lena Fischer", "lena@pixelpost.de", "Interview for the studio feature", "We'd love to feature Lumen in our December issue. Do you have 45 minutes next week for a call?", 1700, true, false, 0, None), + (0, Folder::Inbox, 12, "Travel Desk", "trips@lumen.studio", "Your trip to the festival is booked", "Flight LS 214 on the 14th, 08:20. Hotel near the venue for three nights. Your badge is waiting at registration.", 2900, false, true, 0b1000, Some(("itinerary.pdf", 156))), + (0, Folder::Inbox, 13, "Omar Haddad", "omar@lumen.studio", "Color pipeline: ACES or AgX?", "For the new show I'd move us to AgX for viewing. It handles the saturated neons far better. Thoughts before Monday?", 3100, false, false, 0b0001, None), + (0, Folder::Inbox, 13, "Ana Lima", "ana@lumen.studio", "Re: Color pipeline: ACES or AgX?", "+1 for AgX. Let's test it on shot 052 first.", 3000, false, false, 0b0001, None), + (0, Folder::Inbox, 14, "Calendar", "calendar@lumen.studio", "Reminder: dailies at 16:00", "Screening room B. Bring the latest renders of sequence 4.", 3500, false, false, 0, None), + (0, Folder::Inbox, 15, "Yuki Tanaka", "yuki@lumen.studio", "Texture bake times", "Baking 8K textures takes 6 min per asset on my machine. Is there a farm profile for bakes?", 4400, false, false, 0b0001, None), + (0, Folder::Inbox, 16, "Store", "receipts@gridmarket.com", "Your receipt for Studio Lights Pack", "Thanks for your purchase. Total 39.00. Download your files from your library.", 5800, false, false, 0b0010, None), + (0, Folder::Inbox, 17, "Dev Weekly", "news@devweekly.io", "Issue 211: Shaders without tears", "This week: writing a toon shader, a look at node-based compositing, and a dozen add-ons worth trying.", 7200, false, false, 0, None), + (0, Folder::Inbox, 18, "Sam Carter", "sam@lumen.studio", "Hand-off for shot 061", "Animation is final on 061. Cache is on the share under /shots/061/cache. Ping me if the cloth sim needs another pass.", 8600, false, false, 0b0001, None), + (0, Folder::Archive, 19, "Priya Shah", "priya@orbitfilms.co", "Kick-off notes", "Thanks for a great kick-off. Notes attached: milestones, contacts, delivery specs.", 21000, false, false, 0b0001, Some(("kickoff_notes.pdf", 220))), + (0, Folder::Archive, 20, "Jonas Weber", "jonas@lumen.studio", "New workstation specs", "Ordered: 2 x 24 GB GPUs, 128 GB RAM, the quiet case.", 26000, false, false, 0, None), + (0, Folder::Archive, 21, "Finance", "finance@lumen.studio", "Q3 budget closed", "Q3 is closed. Thanks everyone for getting receipts in on time.", 40000, false, false, 0b0010, None), + (0, Folder::Sent, 22, "Mira Okafor", "mira@lumen.studio", "Shot list for sequence 4", "Hi all, attached is the shot list for sequence 4 with owners and due dates.", 4000, false, false, 0b0001, Some(("seq4_shots.csv", 12))), + (0, Folder::Sent, 23, "Mira Okafor", "mira@lumen.studio", "Re: Lunch?", "Yes! See you there.", 290, false, false, 0, None), + (0, Folder::Drafts, 24, "Mira Okafor", "mira@lumen.studio", "Studio feature answers", "1. How did Lumen start? We were three friends with one render node and a lot of coffee…", 900, false, false, 0, None), + (0, Folder::Spam, 25, "Prize Center", "win@lucky-prizes.biz", "You have WON a free GPU!!!", "Click here to claim your prize before midnight.", 700, true, false, 0, None), + (0, Folder::Spam, 26, "Crypto Daily", "alpha@coin-moon.xyz", "This one coin will 1000x", "Don't miss out.", 2000, true, false, 0, None), + (0, Folder::Trash, 27, "Asset Shelf", "noreply@assetshelf.io", "Last week's asset digest", "8 new materials were added.", 10500, false, false, 0, None), + (1, Folder::Inbox, 30, "Dad", "papa.okafor@postbox.net", "Sunday dinner", "Are you coming Sunday? Your aunt is making jollof. Bring the camera, the garden looks great.", 45, true, false, 0b0000, Some(("garden.jpg", 3100))), + (1, Folder::Inbox, 31, "Bike Club", "rides@spokesclub.org", "Saturday ride: 62 km loop", "Meet at the bakery at 8:00. Route and elevation attached. Coffee stop at km 34.", 210, false, false, 0, Some(("route.gpx", 44))), + (1, Folder::Inbox, 32, "Lena", "lena.k@postbox.net", "Photos from the hike", "Uploaded the photos from the ridge. The one with the fog is my favourite.", 620, true, true, 0, None), + (1, Folder::Inbox, 32, "Mira (personal)", "mira.ok@postbox.net", "Re: Photos from the hike", "They're gorgeous. Can I print the fog one?", 600, false, false, 0, None), + (1, Folder::Inbox, 33, "Library", "notices@citylibrary.org", "Your books are due Friday", "3 items are due on Friday. Renew online or at the desk.", 1300, false, false, 0, None), + (1, Folder::Inbox, 34, "Airline", "booking@skyhopper.travel", "Check-in is open", "Check in now for your flight on the 14th. Seat 14A is reserved.", 2600, false, false, 0b1000, None), + (1, Folder::Inbox, 35, "Bank", "alerts@harborbank.com", "Your statement is ready", "Your November statement is available in online banking.", 5100, false, false, 0b0010, None), + (1, Folder::Inbox, 36, "Plant Shop", "hello@leafandpot.com", "Your monstera has shipped", "Tracking: LP-42-7781. Expected Thursday.", 6300, false, false, 0b0010, None), + (1, Folder::Inbox, 37, "Mum", "mama.okafor@postbox.net", "Recipe you asked for", "Here it is, with my notes in the margin. Don't skip the smoked paprika.", 9000, false, true, 0, Some(("recipe.jpg", 1900))), + (1, Folder::Archive, 38, "Bike Club", "rides@spokesclub.org", "Membership renewed", "Thanks for renewing! Your new jersey is on its way.", 30000, false, false, 0, None), + (1, Folder::Sent, 39, "Mira (personal)", "mira.ok@postbox.net", "Re: Sunday dinner", "I'll be there by 6, with the camera!", 30, false, false, 0, None), + (1, Folder::Spam, 40, "Pharmacy", "deals@cheap-meds.biz", "Limited offer", "Act now.", 3300, true, false, 0, None), +]; + +/// What arrives later, one every half minute (account 0). +const ARRIVALS: &[(&str, &str, &str, &str)] = &[ + ("Ana Lima", "ana@lumen.studio", "Paintover v2", "Updated the paintover with the warmer rim. Much better, I think."), + ("Build Bot", "bot@ci.lumen.studio", "✔ nightly #1843 passed", "All 312 tests passed in 13m 51s."), + ("Kenji Mori", "kenji@hollowpine.jp", "Moved the review to 11:00", "Sorry for the shuffle, the client call moved."), + ("Jonas Weber", "jonas@lumen.studio", "Disk space on the share", "We're at 91%. I'll archive season 1 caches to cold storage tonight."), +]; + +const SIGNATURES: [(&str, &str); 3] = [ + ("None", ""), + ("Studio", "\n\n— Mira Okafor\nLighting Lead, Lumen Studio"), + ("Short", "\n\nMira"), +]; + +const SORTS: [&str; 5] = ["Newest first", "Oldest first", "Sender", "Subject", "Unread first"]; + +// ========================================================================== +// State + +/// A reply, forward or new message being written. +#[derive(Clone)] +struct Draft { + kind: &'static str, + to: String, + cc: String, + subject: String, + body: String, + signature: usize, + /// (file name, size KB, upload progress 0..1, when it started) + files: Vec<(String, u32, f32)>, + /// Bumped to push a new body into the editor (values go to a widget only when they change). + rev: u32, +} + +/// An action that can be undone: each message it touched and how that message was. +struct Undo { + what: String, + before: Vec, +} + +/// A message on its way: sent at `at` unless undone. +struct Outgoing { + msg: Msg, + at: f32, +} + +#[allow(clippy::struct_excessive_bools)] +struct Rules { + archive_days: f64, + auto_archive: bool, + read_on_open: bool, + snippets: bool, + threads: bool, + density: f64, +} + +struct Mail { + msgs: Vec, + next_id: u32, + labels: Vec