mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
Keep the triangles of a path in an Arc with an identity. A change gives the triangles a new identity. The process never gives an identity twice. Paint a path without a copy of its vertices. The scene path shares the triangles and keeps the scale factor and the paint transformation. The vertex shaders scale and transform the vertices in the order of operations of the CPU code. The Metal shader turns off fast-math contraction and reassociation for this. A GPU can fuse a multiply and an add into one rounding. For a rotation or a skew, the renderer thus keeps screen positions that the CPU placed. The GPU still scales the vertices for the local clip. Keep the triangles of each identity in a pool on the GPU. Append only the triangles that no earlier frame drew. Replace the pool when it is full or when the frame uses less than one eighth of it. Never write to a part of the pool that a frame can read. After a failed upload, forget the pool. Draw each path with one 144-byte instance record. Use this design for storage buffers, the WebGL2 texture transport, and Metal. Write WebGL2 instance data and pool data in blocks of whole rows. Each array needs a maximum of four texture writes. Remove the frame paths of wgpu and Metal that no caller can reach.
9.0 KiB
9.0 KiB
Working in packages/ui/ (for agents)
packages/ui/ holds the zero-dependency token crate (packages/ui/tokens), the domain-neutral GPU UI library (packages/ui/ui), and the cross-platform component kit (packages/ui/kit).
This directory belongs to the client Cargo workspace rooted at packages/frontend/Cargo.toml.
Active Invariants (enforced now)
Workspace boundaries
packages/ui/tokens(ui-tokens): Zero-dependency crate (#![forbid(unsafe_code)]) exposing generatedtokens(tokens.rs),icons(icons.rs), and the five tracked repository font slices viabundled_font_bytes(), while keepingextract-tokens.mjs --checkand standalonerustc --edition 2024 --testgates intact.packages/ui/ui: Single fused internal GPU UI library (vendored once without upstream sync hooks, zero internalproc-macro = truecrates, zero external UI-kit dependencies). It knows nothing about BlockSuite or AFFiNE (packages/frontend/scripts/check-invariants.shrejectsblocksuiteandaffineinsidepackages/ui/ui) and embeds zero fonts (fonts are registered by the application viacx.text_system().add_fonts(...)).packages/ui/kit(ui-kit): Domain-neutral cross-platform component library (#![forbid(unsafe_code)]) depending only onuiandui-tokens. ProvidesLogicalEdges,LogicalStyled,SafeArea,VirtualList, andSwipeDialog(Sheet).packages/frontend/scripts/check-invariants.shrejects BlockSuite/AFFiNE terms and physical left/right layout helpers insidepackages/ui/kit/src.
Platform matrix
packages/ui/ui compiles cleanly across four targets from one crate:
- macOS (
target_os = "macos"): AppKit + Metal + CoreText, including windowlessMetalHeadlessRendererreadback, full mip-0MetalAtlaszero-init, and offscreenMacWindowframe/scale fallbacks. - iOS (
target_os = "ios"): Metal, CoreText, and GCD shared fromplatform::apple, withplatform::ios(IosPlatform,IosDisplay,IosWindow) checked onaarch64-apple-iosandaarch64-apple-ios-sim. - Linux Headless (
target_os = "linux"):wgpu+cosmic-textviaWgpuHeadlessRendereron Mesalavapipefor deterministic software rasterization in CI. - Web (
target_family = "wasm"): Single-threadedwasm32-unknown-unknown+ WebGPU/WebGL2 +CanvasFontFallback+ block-scopedImeMirror(nowasm_thread, nohttp_client), verified in headless Chromium viapackages/frontend/scripts/web-smoke.mjs(--queryloads the page with a query string such as a live room,--min-title-inkwaits for that much page ink before capturing; without a query it also drives composition across blocks and composition and paste in the toolbar's link field through the hidden textarea).
Determinism, single clock, and zero tester branches
- Single UI execution path: Headless shell rendering (
bs-harness render), desktop (main.rs), and Web (wasm_main) all instantiate and render the exact same shippingPlaygroundViewthroughApplication::with_platform(...)andWindow::draw().HeadlessPlatform::new_with_text_systemis strictly for deterministic tests and harness customPlatformTextSysteminjection, never an application entry point. - No wall clock outside
packages/ui/ui/src/platform/:Instant::now()andSystemTime::now()are forbidden anywhere outsidepackages/ui/ui/src/platform/(packages/frontend/scripts/check-invariants.sh). Host thread-park deadlines read monotonic time inpackages/ui/ui/src/platform/clock.rs; animations and transitions read the scheduler clock (cx.background_executor().now(), backed byTestSchedulerin headless/test runs and the platform scheduler in desktop/web). - Motion is pure data: Transitions are declared once as
(from, to, curve, start_ms, duration_ms)and evaluated as a pure function of scheduler time. Never write frame-by-frame recurrence loops orsleepwaits. - Zero tester branches: Application and layout logic never inspect
is_headlessor inline#[cfg(any(test, feature = "harness"))]to alter behavior (packages/frontend/scripts/check-invariants.sh). - Four-rate replay invariance: Stepped
PlaygroundViewtransitions (the mode switch, the slash menu and the formatting toolbar opening and closing) must progress monotonically with in-flight frames and produce byte-identical terminalFrameSnapshotJSON at60,120,24, and7fps (bs-harness fps-check). - Callsite tracing: Under the
harnessfeature,InteractiveElement::snapshot(...)records post-layout bounds,content_mask, interactivity, focus, and#[track_caller]file:lineorigins intoWindow::frame_snapshot()forsources_at(x, y)andbs-harness audit. The snapshot schema and the audit rules are the repository'stools/frame-audit(aserde-only path dependency ofpackages/ui/ui, re-exported fromui::harness). Change them there and keep both workspaces' tests green. Non-harness release builds compile to no-op stubs.packages/ui/ui/src/harness.rs(normalize_callsite_path) mapspackages/ui/ui/tocrates/ui/and out-of-treecrates/paths tocrates/soFrameSnapshotJSON stays byte-identical across hosts and checkout roots. - Locked builds & rustflags isolation:
Cargo.lockis committed and CI runs with--lockedandCARGO_ENCODED_RUSTFLAGS=""(packages/frontend/scripts/check-invariants.shverifies freshcargo rustc --print link-argscontains zero leaked root NAPI flags).
Edgeless rendering and GPU transforms
- End-to-end GPU transforms and local clip masks:
Window::with_paint_transformationcomposes 2D affine transforms (TransformationMatrix) on a stack andWindow::with_local_paint_maskintersects pre-transform local clip rects (ContentMask<Pixels>). All GPU primitives (Quad,Shadow,Underline,MonochromeSprite,SubpixelSprite,PolychromeSprite, andPathInstance) are 16-byte aligned (size_of % 16 == 0, verified by compile-time assertions) for WebGL2RGBA32Uinstance-texture decoding. Both Metal (shaders.metal) and wgpu/WebGL2 (shaders.wgsl,shaders_webgl.wgsl,shaders_subpixel.wgsl) transform vertices on the GPU, reserve bit 31 ofquad_id(0x80000000u) invs_quad/quad_vertexfor the solid-quad fast path, evaluate SDFs in local space scaled bytransform_scalefor 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-spacecontent_maskand pre-transformlocal_content_mask. - Resident path triangles: A
Pathshares its triangles (PathVertices, behind anArc) under aPathGeometryIdthat every change replaces and that is never given twice.Window::paint_pathcopies no vertex: the scene'sScenePathshares the triangles, and the GPU scales them by the scale factor and maps them through the paint transformation in the CPU's order of operations. A GPU can fusea * x + b * yinto one rounding, so for a rotation or skew the renderer keeps screen positions that the CPU placed (ScenePath::needs_cpu_placement), and the GPU only scales the vertices for the local clip. The Metal path vertex shader turns off fast-math contraction and reassociation (#pragma clang fp) so that it rounds as the CPU does. Each renderer (wgpu storage buffer, WebGL2Rgba32Uinttexture, Metal buffer) keeps them in a pool (fast/resident_paths.rs) that a frame appends to only for identities no earlier frame drew, and replaces, never overwrites, when it fills or is used under an eighth, and forgets after a failed upload. Each path is one draw with a 144-bytePathInstance. WebGL2 texture writes span whole rows (platform/wgpu/fast/texels.rs, at most fourwrite_texturecalls an array). - Quarter-octave glyph zoom bucketing: Under non-unit paint scales,
Window::paint_glyphandWindow::paint_glyph_in_runquantize rasterization scale to quarter-octave buckets (2^(round(4*log2(s))/4)clamped to[0.25, 8.0]), rasterizing atlas tiles atfont_size * bucketwhile scaling local quad bounds by1 / bucketso cached1.0xRichParagraph/BlockFlowlayouts render crisply at0.1x..6.0xwithout re-shaping or relayouting during pan/zoom. - Procedural dot-grid (
BackgroundTag::DotGrid = 4): Renders the Edgeless background grid in a single fullscreenQuaddraw call with 1-device-pixel anti-aliased dots centered in each tile with screen offset(0.5 * gap - pan * zoom).rem_euclid(gap)per axis and spacing matching BlockSuite'sgetBgGridGap(zoom).
Design tokens and style oracle
packages/ui/tokens/(extract-tokens.mjs,tokens.rs,icons.rs,fonts.lock) &blocksuite/crates/oracle/(extract-style-oracle.spec.ts,style-oracle.json):extract-tokens.mjsdeterministically generates Rust-Ord-sortedtokens.rs,icons.rs(preserving inherited<svg fill>and stroke attributes), andfonts.lock(SHA-256 font asset manifest +CommunityCanvasTextFontsdescriptors), with--checkandrustc --edition 2024 --testenforced on every push in CI.style-oracle.jsonis regenerated via Vitest Browser (extract-style-oracle.spec.ts,isolate: falsereusable iframe) whenever BlockSuite styles or themes change (until its browser CI job lands).