feat(native-playground): add interactive edgeless authoring and polish

This commit is contained in:
DarkSky committed 2026-11-23 13:58:04 +09:00
1 parent 5565057fb6
commit ebc5eb6fb2
85 files changed
+10289 -5401

No files matched your search

+1
View File
@@ -154,6 +154,7 @@ jobs:
echo "Run 2 SHA256: $sha2"
test "$sha1" = "$sha2"
cargo run --locked --bin bs-harness --features harness -- audit --snapshot artifacts/linux-run1.json
cargo run --locked --bin bs-harness --features harness -- audit-states
cargo run --locked --bin bs-harness --features harness -- fps-check
cargo run --locked --bin bs-harness --features harness -- bench \
--json artifacts/perf-metrics.json \
+6
View File
@@ -10,6 +10,12 @@ These rules apply at repository root on the `darksky/native-playground` branch a
- **Performance regression gate:** Any CI benchmark metric regressing by **more than 10%** against the rolling `N-3` baseline is routed to the dedicated performance guardian before landing.
- **Cargo rustflags isolation:** Root `.cargo/config.toml` injects NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`) that Cargo concatenates into nested workspaces. Always build and test `blocksuite/native-playground` with `CARGO_ENCODED_RUSTFLAGS=""` in the environment.
## Engineering & testing principles
- **Global optimum over band-aid patches**: Favor clean structural refactoring and bold deletion over minimal-diff workarounds, defensive clutter, or over-abstraction. Delete obsolete helpers, structs, and files outright, and fold single-caller one-way fragments back into their caller when they add indirection without clarity.
- **Test names match actual scope**: Every test file and test function name must accurately reflect everything it asserts — never append unrelated assertions to a narrowly named test without renaming it to match.
- **Table-driven tests**: Group related scenarios (geometry/hit-testing, parsers, key sequences, IME cases) into concise table-driven loops rather than proliferating near-identical `#[test]` functions.
## Keeping rules true
- When a change makes any statement, path, command, or invariant in an `AGENTS.md` file inaccurate, update that `AGENTS.md` in the same commit.
+13 -6
View File
@@ -51,9 +51,9 @@ This document records the active engineering invariants enforced in CI today alo
- **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. An opening popover mounts on its first frame at zero opacity so its hitboxes are live immediately; a closed popover at zero opacity is unmounted, and one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Nothing here loops per frame.
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 32 px, and the menu has no border, only its shadow.
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's grabber: a 4 × 12 px bar while the pointer is on the block's row, and two columns of three dots on a 14 px pill once the pointer is on the handle or drags it. A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections, and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
- **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons. The toolbar is 297 px wide, with 8 px on either side of the line between the mark and the alignment buttons, and fits a 320 px window between its 8 px margins.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
- **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, intentionally compact relative to JS `8px / 0 6px` so the toolbar fits a 320 px window between its 8 px margins). The toolbar is 297 px wide, with 8 px on either side of the line between the mark and the alignment buttons.
- **Verification**: `bs-harness render --state <name>` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo <dir>` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only.
### Performance guardrail and theme/style oracle
@@ -69,20 +69,27 @@ This document records the active engineering invariants enforced in CI today alo
- **End-to-end GPU transforms and local clip masks**: `Window::with_paint_transformation` composes 2D affine transforms (`TransformationMatrix`) on a stack and `Window::with_local_paint_mask` intersects pre-transform local clip rects (`ContentMask<Pixels>`). All GPU primitives (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, and `PathRasterizationVertex`) are 16-byte aligned (`size_of % 16 == 0`, verified by compile-time assertions) for WebGL2 `RGBA32U` instance-texture decoding. Both Metal (`shaders.metal`) and wgpu/WebGL2 (`shaders.wgsl`, `shaders_webgl.wgsl`, `shaders_subpixel.wgsl`) transform vertices on the GPU, evaluate SDFs in local space scaled by `transform_scale` for 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-space `content_mask` and pre-transform `local_content_mask`.
- **Quarter-octave glyph zoom bucketing**: Under non-unit paint scales, `Window::paint_glyph` and `Window::paint_glyph_in_run` quantize rasterization scale to quarter-octave buckets (`2^(round(4*log2(s))/4)` clamped to `[0.25, 8.0]`), rasterizing atlas tiles at `font_size * bucket` while scaling local quad bounds by `1 / bucket` so cached `1.0x` `RichParagraph` / `BlockFlow` layouts render crisply at `0.1x..6.0x` without re-shaping or relayouting during pan/zoom.
- **Procedural dot-grid (`BackgroundTag::DotGrid = 4`)**: Renders the Edgeless background grid in a single fullscreen `Quad` draw 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's `getBgGridGap(zoom)`.
- **Spatial camera & canvas**: `edgeless_camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds. `edgeless_canvas.rs` renders Surface-parented Frames and EdgelessText and root-parented Notes. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry. Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-right screen-space zoom controls (`chrome.edgeless_zoom`). `bs-harness render --mode edgeless [--zoom <f32>] [--pan <x>,<y>]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`.
- **Spatial camera & canvas (`edgeless/`)**: `edgeless/camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds (initialized before building `chrome.edgeless_zoom` so Frame 1 displays the fitted zoom percentage). `edgeless/scene.rs` and `edgeless/canvas_paint.rs` prepare and render Surface-parented Frames and EdgelessText and root-parented Notes in a single snapshot pass. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry (`prop:childElementIds` treats every present key as a frame member, and equal indices preserve source enumeration order within each stream). Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-centered creation toolbar (`chrome.edgeless_toolbar`) and bottom-right screen-space zoom controls (`chrome.edgeless_zoom`, stacked cleanly above `chrome.edgeless_toolbar` on narrow viewports `< 660 px`). `bs-harness render --mode edgeless [--zoom <f32>] [--pan <x>,<y>]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` + authoring states (`edgeless_selected`, `edgeless_marquee`, `edgeless_inline_edit`, `edgeless_authoring`) in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`.
- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle picker), Connector (`C` with cardinal port snapping and live orthogonal connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), top rotation handle (`edgeless.handle.rotate`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support.
### Surface reading and painting
- `BlockContent::Surface` retains the element count and exposes typed elements sorted by fractional index then id. Each element keeps all normalized wire properties, including unknown types. Connector labels retain their stored size and follow the route at the label offset. When `labelXYWH` is absent, the native renderer measures the label at paint time. This extends BlockSuite’s `hasLabel()` behavior with zero document writebacks.
- `BlockContent::Surface` retains the element count and exposes typed elements sorted by fractional index in wire creation order. Each element keeps all normalized wire properties and unknown types (`textDisplay` on shapes is `@local()` and defaults to `true` locally without reading from the wire). Straight connector labels interpolate linearly (`Vec.lrp`), orthogonal labels follow polyline distance, and curved labels follow the cubic Bézier parameter. Connector labels retain their stored size and follow the route at the label offset. When `labelXYWH` is absent, the native renderer measures the label at paint time. This extends BlockSuite’s `hasLabel()` behavior with zero document writebacks.
- `surface::layout_surface` accepts element snapshots and world bounds for external blocks. It finds ports on rotated shape outlines and routes orthogonal connectors using their two endpoint bounds. The router follows BlockSuite's `ConnectorPathGenerator`. A connector's `rough` flag enables jitter and `roughness` sets its amplitude. Scribbled shapes follow RoughJS hachure, `pointsOnPath` sampling and seeded operation order. Brush and highlighter share the perfect-freehand pressure outline and midpoint quadratic curves. EdgelessCanvas caches geometry by document revision, theme and environment revision. Fully visible elements emit `edgeless.surface.<id>` in screen coordinates. The standalone harness uses the same painter.
- The canvas clips its viewport in screen coordinates. Within the camera transform, each rotated shape or text pushes its own center rotation before its label mask. The GPU inverse-maps coverage into the label's local coordinates while retaining the screen-space viewport clip.
- The JS surface oracle runs the BlockSuite shape, connector and freehand implementations and compares their coordinates to `tokens/surface-oracle.json`. Rust tests consume the same geometry and font baselines.
- With repository JavaScript dependencies installed, `cargo test --locked -p blocksuite-playground-doc --example bs_doc_driver js_authored_surface` verifies data and rich-text marks written by Yjs against the typed Rust snapshot and compares the encoded document before and after reading.
### Rust Module Organization & Fast Verification
- **Proactive modularization**: Split files by responsibility (targeting ~500–800 production lines; promote `<name>.rs` to `<name>/mod.rs` when introducing submodules). Keep each `mod.rs` as the dependency and visibility hub (`pub(super) use ...`), import siblings via `use super::...`, and hoist cross-layer shared items to the narrowest common ancestor `mod.rs`.
- **Global optimum & clean boundaries**: Prefer structural cleanup and bold deletion over band-aid patches. Delete obsolete code outright, fold single-caller one-way fragments back into their caller, and extract shared helpers only for stable domain concepts, genuine multi-site reuse, or key invariants — never for one-line expressions.
- **Focused, table-driven tests**: Keep test-only imports and helpers inside `#[cfg(test)] mod tests`, placing unit tests in the file under test and cross-submodule tests in the lowest common `mod.rs`. Keep every test file and function name aligned with its actual assertion scope, and group similar scenarios into table-driven loops rather than proliferating near-identical `#[test]` functions.
- **Sub-60-second verification loop**: Validate uncertain paths with minimal focused spikes first and remove scaffolding before landing. Keep routine edit-verify turns under **60 seconds** using targeted `cargo check --locked -p ...` / `cargo test --locked -p ... --lib <filter>` and `./scripts/check-invariants.sh` (which enforces `super::super` bans, `mod.rs` layout, orphan-file detection, and per-file LOC limits automatically alongside `rustfmt.toml`).
## Planned Contracts (upcoming crates & features)
- **Whiteboard surface elements & interaction**: Mindmaps and pointer selection/drag editing on the Edgeless spatial canvas.
- **Whiteboard surface elements**: Mindmap tree layout and editing on the Edgeless spatial canvas.
## Build & verification commands
@@ -91,6 +91,98 @@ enum Command {
mode: i32,
now_ms: u64,
},
GenerateKeyBetween {
a: Option<String>,
b: Option<String>,
},
AddShape {
page_id: String,
surface_id: String,
element_id: String,
index: String,
shape_type: String,
xywh: String,
text: Option<String>,
now_ms: u64,
},
UpdateShapeRotate {
page_id: String,
surface_id: String,
element_id: String,
rotate: f64,
now_ms: u64,
},
AddConnector {
page_id: String,
surface_id: String,
element_id: String,
index: String,
source_id: String,
target_id: String,
now_ms: u64,
},
AddBrush {
page_id: String,
surface_id: String,
element_id: String,
index: String,
xywh: String,
points: Vec<Vec<f64>>,
now_ms: u64,
},
UpdateBrushPoints {
page_id: String,
surface_id: String,
element_id: String,
points: Vec<Vec<f64>>,
now_ms: u64,
},
UpdateConnectorLabelXywh {
page_id: String,
surface_id: String,
element_id: String,
label_xywh: [f64; 4],
now_ms: u64,
},
AddNoteWithText {
page_id: String,
root_id: String,
note_id: String,
para_id: String,
xywh: [f64; 4],
text: String,
now_ms: u64,
},
SpliceSurfaceElementText {
page_id: String,
surface_id: String,
element_id: String,
field: String,
utf16_start: u64,
utf16_delete_len: u64,
insert: String,
now_ms: u64,
},
CommitConnectorLabel {
page_id: String,
surface_id: String,
element_id: String,
trimmed_text: String,
label_xywh: [f64; 4],
now_ms: u64,
},
DeleteWithConnectors {
page_id: String,
block_ids: Vec<String>,
surface_elements: Vec<(String, String)>,
now_ms: u64,
},
Undo {
page_id: String,
},
Redo {
page_id: String,
},
SetAwareness {
name: String,
color: String,
@@ -761,6 +853,377 @@ async fn main() {
}
json!({ "ok": true })
}
Command::GenerateKeyBetween { a, b } => {
match blocksuite_playground_doc::fractional_index::generate_key_between(
a.as_deref(),
b.as_deref(),
) {
Ok(key) => json!({ "ok": true, "key": key }),
Err(err) => json!({ "ok": false, "error": err }),
}
}
Command::AddShape {
page_id,
surface_id,
element_id,
index,
shape_type,
xywh,
text,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.structural_edit(now_ms, move |p| {
p.add_surface_element(
&surface_id,
element_id.clone(),
&index,
SurfaceElementSpec::Shape {
shape_type: shape_type.clone(),
xywh: xywh.clone(),
seed: 101,
filled: true,
text: text.clone(),
},
now_ms,
)?;
Ok(())
})
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::UpdateShapeRotate {
page_id,
surface_id,
element_id,
rotate,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.structural_edit(now_ms, move |p| {
p.set_surface_element_field(
&surface_id,
&element_id,
"rotate",
SessionValue::Any(Any::Float64(rotate.into())),
now_ms,
)?;
Ok(())
})
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::AddConnector {
page_id,
surface_id,
element_id,
index,
source_id,
target_id,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.structural_edit(now_ms, move |p| {
p.add_surface_element(
&surface_id,
element_id.clone(),
&index,
SurfaceElementSpec::Connector {
mode: 1,
seed: 202,
source: ConnectorEndpointSpec::element(
source_id.clone(),
Some([1.0, 0.5]),
),
target: ConnectorEndpointSpec::element(
target_id.clone(),
Some([0.0, 0.5]),
),
text: None,
label_xywh: None,
},
now_ms,
)?;
Ok(())
})
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::AddBrush {
page_id,
surface_id,
element_id,
index,
xywh,
points,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.structural_edit(now_ms, move |p| {
p.add_surface_element(
&surface_id,
element_id.clone(),
&index,
SurfaceElementSpec::Brush {
seed: 303,
points: points.clone(),
xywh: xywh.clone(),
},
now_ms,
)?;
Ok(())
})
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::UpdateBrushPoints {
page_id,
surface_id,
element_id,
points,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
let encoded: Vec<Any> = points
.into_iter()
.map(|p| Any::Array(p.into_iter().map(|v| Any::Float64(v.into())).collect()))
.collect();
if let Some(c) = page
.set_surface_element_field(
&surface_id,
&element_id,
"points",
SessionValue::Any(blocksuite_playground_doc::schema::map_array_any(
encoded,
)),
now_ms,
)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::UpdateConnectorLabelXywh {
page_id,
surface_id,
element_id,
label_xywh,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
let encoded: Vec<Any> = label_xywh
.into_iter()
.map(|v| Any::Float64(v.into()))
.collect();
if let Some(c) = page
.set_surface_element_field(
&surface_id,
&element_id,
"labelXYWH",
SessionValue::Any(blocksuite_playground_doc::schema::map_array_any(
encoded,
)),
now_ms,
)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::AddNoteWithText {
page_id,
root_id,
note_id,
para_id,
xywh,
text,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.add_edgeless_note(&root_id, &note_id, &para_id, "a5", xywh, &text, now_ms)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::SpliceSurfaceElementText {
page_id,
surface_id,
element_id,
field,
utf16_start,
utf16_delete_len,
insert,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.splice_surface_element_text(
&surface_id,
&element_id,
&field,
utf16_start,
utf16_delete_len,
&insert,
now_ms,
)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::CommitConnectorLabel {
page_id,
surface_id,
element_id,
trimmed_text,
label_xywh,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page
.commit_connector_label(
&surface_id,
&element_id,
&trimmed_text,
label_xywh,
now_ms,
)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::DeleteWithConnectors {
page_id,
block_ids,
surface_elements,
now_ms,
} => {
let page = ws_session.ensure_page(&page_id).unwrap();
let b_refs: Vec<&str> = block_ids.iter().map(String::as_str).collect();
let s_refs: Vec<(&str, &str)> = surface_elements
.iter()
.map(|(s, e)| (s.as_str(), e.as_str()))
.collect();
if let Some(c) = page
.delete_blocks_and_elements_with_connectors(&b_refs, &s_refs, now_ms)
.unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::Undo { page_id } => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page.undo().unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::Redo { page_id } => {
let page = ws_session.ensure_page(&page_id).unwrap();
if let Some(c) = page.redo().unwrap()
&& !c.update.is_empty()
{
let f = encode_binary_frame(&RoomBinaryFrame::Doc {
doc_id: page_id,
message: DocMessage::Update(c.update),
})
.unwrap();
ws.send(WsMsg::Binary(f.into())).await.unwrap();
}
json!({ "ok": true })
}
Command::SetAwareness {
name,
color,
@@ -0,0 +1,287 @@
//! Exact `fractional-indexing@3.2.0` (base-62) key generation compatible with BlockSuite.
//!
//! Integer keys start with a head character encoding their digit count:
//! - `'a'`..=`'z'` have `1..=26` base-62 digits (`"a0"`..`"a9"`, `"aA"`..`"az"`, `"b00"`..`"bzz"`).
//! - `'Z'`..=`'A'` have `1..=26` negative base-62 digits (`"Zz"`..`"Z0"`, `"Yzz"`..`"Y00"`).
//! Note that `"b0"` is invalid because `'b'` requires 2 integer digits (`"b00"`..`"bzz"`).
const BASE_62_DIGITS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const SMALLEST_INTEGER: &str = "A00000000000000000000000000";
const INTEGER_ZERO: &str = "a0";
fn digit_index(ch: u8) -> Option<usize> {
BASE_62_DIGITS.iter().position(|&b| b == ch)
}
fn integer_length(head: u8) -> Result<usize, String> {
if head.is_ascii_lowercase() {
Ok((head - b'a') as usize + 2)
} else if head.is_ascii_uppercase() {
Ok((b'Z' - head) as usize + 2)
} else {
Err(format!("invalid order key head: {:?}", head as char))
}
}
fn validate_integer(int: &str) -> Result<(), String> {
let bytes = int.as_bytes();
if bytes.is_empty() {
return Err("empty integer part".into());
}
let expected = integer_length(bytes[0])?;
if bytes.len() != expected {
return Err(format!("invalid integer part of order key: {int}"));
}
for &b in &bytes[1..] {
if digit_index(b).is_none() {
return Err(format!("invalid base-62 digit in order key: {int}"));
}
}
Ok(())
}
fn get_integer_part(key: &str) -> Result<&str, String> {
let bytes = key.as_bytes();
if bytes.is_empty() {
return Err("empty order key".into());
}
let len = integer_length(bytes[0])?;
if len > bytes.len() {
return Err(format!("invalid order key: {key}"));
}
let int = &key[..len];
validate_integer(int)?;
Ok(int)
}
/// Validate that `key` is a legal `fractional-indexing@3.2.0` base-62 order key.
pub fn validate_order_key(key: &str) -> Result<(), String> {
if key == SMALLEST_INTEGER {
return Err(format!("invalid order key: {key}"));
}
let int = get_integer_part(key)?;
let frac = &key[int.len()..];
for &b in frac.as_bytes() {
if digit_index(b).is_none() {
return Err(format!("invalid fractional digit in order key: {key}"));
}
}
if frac.ends_with(BASE_62_DIGITS[0] as char) {
return Err(format!("invalid order key trailing zero: {key}"));
}
Ok(())
}
fn increment_integer(x: &str) -> Result<Option<String>, String> {
validate_integer(x)?;
let bytes = x.as_bytes();
let head = bytes[0];
let mut digs = bytes[1..].to_vec();
let mut carry = true;
for d in digs.iter_mut().rev() {
if !carry {
break;
}
let idx = digit_index(*d).unwrap() + 1;
if idx == BASE_62_DIGITS.len() {
*d = BASE_62_DIGITS[0];
} else {
*d = BASE_62_DIGITS[idx];
carry = false;
}
}
if carry {
if head == b'Z' {
return Ok(Some(INTEGER_ZERO.to_string()));
}
if head == b'z' {
return Ok(None);
}
let next_head = head + 1;
if next_head > b'a' {
digs.push(BASE_62_DIGITS[0]);
} else {
digs.pop();
}
let mut out = String::with_capacity(1 + digs.len());
out.push(next_head as char);
out.push_str(std::str::from_utf8(&digs).unwrap());
Ok(Some(out))
} else {
let mut out = String::with_capacity(1 + digs.len());
out.push(head as char);
out.push_str(std::str::from_utf8(&digs).unwrap());
Ok(Some(out))
}
}
fn decrement_integer(x: &str) -> Result<Option<String>, String> {
validate_integer(x)?;
let bytes = x.as_bytes();
let head = bytes[0];
let mut digs = bytes[1..].to_vec();
let mut borrow = true;
for d in digs.iter_mut().rev() {
if !borrow {
break;
}
let idx = digit_index(*d).unwrap();
if idx == 0 {
*d = *BASE_62_DIGITS.last().unwrap();
} else {
*d = BASE_62_DIGITS[idx - 1];
borrow = false;
}
}
if borrow {
if head == b'a' {
return Ok(Some(format!(
"Z{}",
*BASE_62_DIGITS.last().unwrap() as char
)));
}
if head == b'A' {
return Ok(None);
}
let prev_head = head - 1;
if prev_head < b'Z' {
digs.push(*BASE_62_DIGITS.last().unwrap());
} else {
digs.pop();
}
let mut out = String::with_capacity(1 + digs.len());
out.push(prev_head as char);
out.push_str(std::str::from_utf8(&digs).unwrap());
Ok(Some(out))
} else {
let mut out = String::with_capacity(1 + digs.len());
out.push(head as char);
out.push_str(std::str::from_utf8(&digs).unwrap());
Ok(Some(out))
}
}
fn midpoint(a: &str, b: Option<&str>) -> Result<String, String> {
let zero = BASE_62_DIGITS[0];
if let Some(b) = b
&& a >= b
{
return Err(format!("{a} >= {b}"));
}
if a.ends_with(zero as char) || b.is_some_and(|b| b.ends_with(zero as char)) {
return Err("trailing zero in midpoint".into());
}
if let Some(b) = b {
let a_bytes = a.as_bytes();
let b_bytes = b.as_bytes();
let mut n = 0;
while n < b_bytes.len() && a_bytes.get(n).copied().unwrap_or(zero) == b_bytes[n] {
n += 1;
}
if n > 0 {
let sub_a = if n < a.len() { &a[n..] } else { "" };
return Ok(format!("{}{}", &b[..n], midpoint(sub_a, Some(&b[n..]))?));
}
}
let digit_a = a
.as_bytes()
.first()
.map_or(0, |&c| digit_index(c).unwrap_or(0));
let digit_b = b
.and_then(|s| s.as_bytes().first())
.map_or(BASE_62_DIGITS.len(), |&c| digit_index(c).unwrap_or(0));
if digit_b - digit_a > 1 {
let mid = ((digit_a + digit_b) as f64 * 0.5).round() as usize;
return Ok((BASE_62_DIGITS[mid] as char).to_string());
}
if let Some(b) = b
&& b.len() > 1
{
return Ok(b[..1].to_string());
}
let sub_a = if a.len() > 1 { &a[1..] } else { "" };
Ok(format!(
"{}{}",
BASE_62_DIGITS[digit_a] as char,
midpoint(sub_a, None)?
))
}
/// Generate a valid `fractional-indexing@3.2.0` base-62 key strictly between `a` and `b`.
pub fn generate_key_between(a: Option<&str>, b: Option<&str>) -> Result<String, String> {
if let Some(a) = a {
validate_order_key(a)?;
}
if let Some(b) = b {
validate_order_key(b)?;
}
if let (Some(a), Some(b)) = (a, b)
&& a >= b
{
return Err(format!("{a} >= {b}"));
}
if a.is_none() {
let Some(b) = b else {
return Ok(INTEGER_ZERO.to_string());
};
let ib = get_integer_part(b)?;
let fb = &b[ib.len()..];
if ib == SMALLEST_INTEGER {
return Ok(format!("{ib}{}", midpoint("", Some(fb))?));
}
if ib < b {
return Ok(ib.to_string());
}
let res = decrement_integer(ib)?
.ok_or_else(|| "cannot decrement smallest integer".to_string())?;
return Ok(res);
}
let a = a.unwrap();
if b.is_none() {
let ia = get_integer_part(a)?;
let fa = &a[ia.len()..];
return match increment_integer(ia)? {
Some(i) => Ok(i),
None => Ok(format!("{ia}{}", midpoint(fa, None)?)),
};
}
let b = b.unwrap();
let ia = get_integer_part(a)?;
let fa = &a[ia.len()..];
let ib = get_integer_part(b)?;
let fb = &b[ib.len()..];
if ia == ib {
return Ok(format!("{ia}{}", midpoint(fa, Some(fb))?));
}
let i = increment_integer(ia)?.ok_or_else(|| "cannot increment largest integer".to_string())?;
if i.as_str() < b {
Ok(i)
} else {
Ok(format!("{ia}{}", midpoint(fa, None)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_fractional_indexing_3_2_0_vectors() {
assert_eq!(generate_key_between(None, None).unwrap(), "a0");
assert_eq!(generate_key_between(Some("a0"), None).unwrap(), "a1");
assert_eq!(generate_key_between(Some("a9"), None).unwrap(), "aA");
assert_eq!(generate_key_between(Some("aZ"), None).unwrap(), "aa");
assert_eq!(generate_key_between(Some("az"), None).unwrap(), "b00");
assert_eq!(generate_key_between(None, Some("a0")).unwrap(), "Zz");
assert_eq!(generate_key_between(None, Some("Z0")).unwrap(), "Yzz");
assert_eq!(generate_key_between(Some("a0"), Some("a1")).unwrap(), "a0V");
assert_eq!(generate_key_between(Some("a0"), Some("a2")).unwrap(), "a1");
assert_eq!(
generate_key_between(Some("a0V"), Some("a1")).unwrap(),
"a0l"
);
// "b0" is invalid in fractional-indexing@3.2.0 ('b' requires 2 base-62 digits).
assert!(validate_order_key("b0").is_err());
assert!(validate_order_key("b00").is_ok());
}
}
@@ -1,6 +1,7 @@
#![forbid(unsafe_code)]
pub mod awareness;
pub mod fractional_index;
pub mod read;
#[cfg(all(feature = "server", not(target_family = "wasm")))]
pub mod room;
@@ -158,6 +158,7 @@ pub struct SurfaceShape {
pub shape_style: ShapeStyle,
pub roughness: f64,
pub text: RichText,
pub text_display: bool,
pub color: ColorValue,
pub font_family: String,
pub font_size: f64,
@@ -366,6 +367,7 @@ impl SurfaceElement {
ShapeStyle::General
},
text,
text_display: true,
color: font.color,
font_family: font.font_family,
font_size: font.font_size,
@@ -807,8 +809,11 @@ impl SnapshotReader<'_> {
title: self.rich_text(entries.get("prop:title"))?,
},
"affine:surface" => {
let elements = self
.surface_elements(entries.get("prop:elements"), props.get("prop:elements"))?;
let elements = self.surface_elements(
id,
entries.get("prop:elements"),
props.get("prop:elements"),
)?;
BlockContent::Surface {
element_count: elements.len(),
elements,
@@ -902,6 +907,7 @@ impl SnapshotReader<'_> {
fn surface_elements(
&self,
surface_id: &str,
value: Option<&SessionReadValue>,
normalized: Option<&JsonValue>,
) -> DocResult<Vec<SurfaceElement>> {
@@ -920,8 +926,16 @@ impl SnapshotReader<'_> {
else {
return Ok(vec![]);
};
let mut elements = Vec::with_capacity(raw.len());
for (id, value) in session.read_map(&TypeTarget::Identity(value))? {
let map_entries = session.read_map(&TypeTarget::Identity(value))?;
let ordered_ids = self
.page
.refresh_surface_element_order(surface_id, &map_entries);
let mut by_id: BTreeMap<String, SessionReadValue> = map_entries.into_iter().collect();
let mut elements = Vec::with_capacity(ordered_ids.len());
for id in ordered_ids {
let Some(value) = by_id.remove(&id) else {
continue;
};
let properties = raw.get(&id).unwrap_or(&JsonValue::Null);
let (props, text) = if let SessionReadValue::Map(identity) = value {
let key = if properties["type"] == "group" {
@@ -936,7 +950,7 @@ impl SnapshotReader<'_> {
};
elements.push(SurfaceElement::from_properties(id, props, text));
}
elements.sort_by(|a, b| (&a.index, &a.id).cmp(&(&b.index, &b.id)));
elements.sort_by(|a, b| a.index.cmp(&b.index));
Ok(elements)
}
}
@@ -1061,8 +1075,10 @@ fn number(value: Option<&SessionReadValue>) -> Option<f64> {
#[cfg(test)]
mod surface_tests {
use super::*;
use crate::schema::{BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec as Spec};
use y_octo::SessionValue;
use crate::schema::{
BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec, SurfaceElementSpec as Spec,
};
use y_octo::{SessionValue, TypePath};
#[test]
fn partial_normalized_surface_map_keeps_missing_entry_as_unknown() -> DocResult {
@@ -1089,6 +1105,7 @@ mod surface_tests {
reader.load()?;
let partial = serde_json::json!({"value":{}});
let result = reader.surface_elements(
"surface",
reader.raw["surface"].entries.get("prop:elements"),
Some(&partial),
)?;
@@ -1194,19 +1211,22 @@ mod surface_tests {
assert_eq!(
elements.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(),
[
"brush",
"connector",
"group",
"highlighter",
"shape",
"connector",
"brush",
"highlighter",
"group",
"text"
]
);
let SurfaceElementKind::Brush(s) = &elements[0].kind else {
let SurfaceElementKind::Shape(s) = &elements[0].kind else {
panic!()
};
assert_eq!(s.points, [[0., 2., 0.5], [5., 3., 0.75]]);
assert_eq!(s.xywh, [100., 20., 40., 10.]);
assert_eq!(s.shape_type, ShapeType::Rect);
assert_eq!(s.radius, 0.1);
assert_eq!(s.padding, [10., 20.]);
assert_eq!(s.text.plain, "Label");
assert_eq!(elements[0].props["future"], 17);
let SurfaceElementKind::Connector(c) = &elements[1].kind else {
panic!()
};
@@ -1217,24 +1237,21 @@ mod surface_tests {
assert_eq!(c.source.id.as_deref(), Some("shape"));
assert_eq!(c.target.position, Some([99., 22.]));
assert_eq!(c.text.plain, "Edge");
let SurfaceElementKind::Group { title, children } = &elements[2].kind else {
let SurfaceElementKind::Brush(s) = &elements[2].kind else {
panic!()
};
assert_eq!(title.plain, "Group");
assert_eq!(children, &["shape", "text"]);
assert_eq!(s.points, [[0., 2., 0.5], [5., 3., 0.75]]);
assert_eq!(s.xywh, [100., 20., 40., 10.]);
let SurfaceElementKind::Highlighter(s) = &elements[3].kind else {
panic!()
};
assert_eq!(s.points, [[3., 4., 0.5]]);
assert_eq!(s.color, ColorValue::Single("#84cfff4d".into()));
let SurfaceElementKind::Shape(s) = &elements[4].kind else {
let SurfaceElementKind::Group { title, children } = &elements[4].kind else {
panic!()
};
assert_eq!(s.shape_type, ShapeType::Rect);
assert_eq!(s.radius, 0.1);
assert_eq!(s.padding, [10., 20.]);
assert_eq!(s.text.plain, "Label");
assert_eq!(elements[4].props["future"], 17);
assert_eq!(title.plain, "Group");
assert_eq!(children, &["shape", "text"]);
let SurfaceElementKind::Text(t) = &elements[5].kind else {
panic!()
};
@@ -1259,4 +1276,197 @@ mod surface_tests {
assert!(e.hidden && e.locked_by_self);
assert_eq!(e.props["nested"]["extra"][1], 2);
}
#[test]
fn equal_index_surface_elements_preserve_per_surface_insertion_order_despite_earlier_global_key()
-> DocResult<()> {
// Adversarial test: insert key `"a"` in an unrelated block first, then insert
// equal-index shapes `"z"` ("a1") and `"a"` ("a1") into `prop:elements.value`.
// Both a single V1 update and two incremental updates must preserve `["z", "a"]`.
let mut author = PageDocSession::new("p-order", 1)?;
author.add_block(
"page-1",
BlockSpec::Page {
title: "Order".into(),
},
None,
None,
1,
)?;
author.add_block(
"a",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "global key a".into(),
},
Some("page-1"),
None,
2,
)?;
let surf = author.ensure_surface_block(3)?;
let u_base = author.encode_update_v1()?;
let u_z = author
.add_surface_element(
&surf,
"z",
"a1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[0,0,100,80]".into(),
seed: 1,
filled: true,
text: Some("Z".into()),
},
4,
)?
.unwrap()
.update;
let u_a = author
.add_surface_element(
&surf,
"a",
"a1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[20,20,100,80]".into(),
seed: 2,
filled: true,
text: Some("A".into()),
},
5,
)?
.unwrap()
.update;
let u_full = author.encode_update_v1()?;
let extract_ids = |doc: &PageDocSession| -> Vec<String> {
let snap = doc.read_page_snapshot().unwrap();
let surf_node = snap
.root
.unwrap()
.children
.into_iter()
.find(|c| c.id == surf)
.unwrap();
let BlockContent::Surface { elements, .. } = surf_node.content else {
unreachable!()
};
elements.into_iter().map(|e| e.id).collect()
};
assert_eq!(extract_ids(&author), vec!["z", "a"]);
// Single V1 update decode on fresh peer:
let mut peer_single = PageDocSession::new("p-order", 2)?;
peer_single.apply_remote_update_v1(&u_full)?;
assert_eq!(extract_ids(&peer_single), vec!["z", "a"]);
// Two incremental updates on fresh peer:
let mut peer_inc = PageDocSession::new("p-order", 3)?;
peer_inc.apply_remote_update_v1(&u_base)?;
peer_inc.apply_remote_update_v1(&u_z)?;
peer_inc.apply_remote_update_v1(&u_a)?;
assert_eq!(extract_ids(&peer_inc), vec!["z", "a"]);
Ok(())
}
#[test]
fn concurrent_two_peer_shape_label_splice_and_undo_redo_preserve_marks() -> DocResult<()> {
let mut peer_a = PageDocSession::new("p-collab", 11)?;
peer_a.add_block(
"page-1",
BlockSpec::Page {
title: "Collab".into(),
},
None,
None,
1,
)?;
let surf = peer_a.ensure_surface_block(2)?;
peer_a.add_surface_element(
&surf,
"s1",
"a0",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[0,0,160,80]".into(),
seed: 7,
filled: true,
text: Some("Hello".into()),
},
3,
)?;
// Apply bold mark to "Hello" directly on Y.Text.
let target = TypeTarget::Path(
TypePath::root("blocks")
.key(&surf)
.key("prop:elements")
.key("value")
.key("s1")
.key("text"),
);
let mut bold = y_octo::TextAttributes::new();
bold.insert("bold".into(), Any::True);
peer_a.inner_mut().text_format(&target, 0, 5, bold)?;
peer_a.stop_capturing()?;
let mut peer_b = PageDocSession::new("p-collab", 22)?;
peer_b.apply_remote_update_v1(&peer_a.encode_update_v1()?)?;
// Concurrent edits: B prepends "X ", A appends "!"
let upd_b = peer_b
.splice_surface_element_text(&surf, "s1", "text", 0, 0, "X ", 100)?
.unwrap()
.update;
let upd_a = peer_a
.splice_surface_element_text(&surf, "s1", "text", 5, 0, "!", 100)?
.unwrap()
.update;
peer_a.apply_remote_update_v1(&upd_b)?;
peer_b.apply_remote_update_v1(&upd_a)?;
let read_shape_text = |doc: &PageDocSession| -> RichText {
let snap = doc.read_page_snapshot().unwrap();
let snode = snap
.root
.unwrap()
.children
.into_iter()
.find(|c| c.id == surf)
.unwrap();
let BlockContent::Surface { elements, .. } = snode.content else {
unreachable!()
};
let SurfaceElementKind::Shape(sh) = &elements[0].kind else {
unreachable!()
};
sh.text.clone()
};
let ta = read_shape_text(&peer_a);
let tb = read_shape_text(&peer_b);
assert_eq!(ta.plain, "X Hello!");
assert_eq!(tb.plain, "X Hello!");
assert!(
ta.delta.iter().any(|op| matches!(
op,
TextDeltaOp::Insert { insert: TextInsert::Text(t), format: Some(f) }
if t.contains("Hello") && f.get("bold") == Some(&Any::True)
)),
"untouched bold mark on 'Hello' must survive concurrent splices: {:?}",
ta.delta
);
// Peer A undoes "!" -> "X Hello" survives; redoes -> "X Hello!".
let u_undo = peer_a.undo()?.unwrap().update;
peer_b.apply_remote_update_v1(&u_undo)?;
assert_eq!(read_shape_text(&peer_a).plain, "X Hello");
assert_eq!(read_shape_text(&peer_b).plain, "X Hello");
let u_redo = peer_a.redo()?.unwrap().update;
peer_b.apply_remote_update_v1(&u_redo)?;
assert_eq!(read_shape_text(&peer_a).plain, "X Hello!");
assert_eq!(read_shape_text(&peer_b).plain, "X Hello!");
Ok(())
}
}
@@ -273,7 +273,7 @@ fn nonzero_seed(seed: i32) -> i32 {
/// `y-octo`'s `From<Any> for Content` converts a top-level `Any::Array(v)` into
/// multi-element `Content::Any(v)`. Wrapping once produces `Content::Any(vec![Any::Array(v)])`,
/// matching Yjs `yMap.set(key, array)`.
fn map_array_any(items: Vec<Any>) -> Any {
pub fn map_array_any(items: Vec<Any>) -> Any {
Any::Array(vec![Any::Array(items)])
}
@@ -1,11 +1,14 @@
use std::collections::{BTreeMap, BTreeSet};
use std::{
cell::RefCell,
collections::{BTreeMap, BTreeSet},
};
use serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value as JsonValue};
use y_octo::{
Any, DocOptions, DocSession, RelativePosition, SessionCommit, SessionConfig, SessionOriginKind,
SessionReadValue, SessionTxOrigin, SessionUndoConfig, SessionValue, TextAttributes,
TextDeltaOp, TextInsert, TypePath, TypeTarget, UndoStackId, YTypeKind,
TextDeltaOp, TextInsert, TypeIdentity, TypePath, TypeTarget, UndoStackId, YTypeKind,
};
use crate::{
@@ -151,6 +154,7 @@ pub struct PageDocSession {
session: DocSession<SelectionSnapshot>,
undo_stack_id: UndoStackId,
blocks_target: TypeTarget,
surface_element_order: RefCell<BTreeMap<String, Vec<String>>>,
}
impl PageDocSession {
@@ -174,9 +178,77 @@ impl PageDocSession {
session,
undo_stack_id,
blocks_target,
surface_element_order: RefCell::new(BTreeMap::new()),
})
}
/// Update and return per-surface first-integration key order for `prop:elements.value`,
/// preserving established order for surviving keys and appending newly integrated keys
/// sorted by `(Reverse(id.client), id.clock)` from `TypeIdentity::Item(id)` to match
/// Yjs 13.6.21 merged update encoding order (higher client IDs first, ascending clock per client).
pub(crate) fn refresh_surface_element_order(
&self,
surface_id: &str,
entries: &[(String, SessionReadValue)],
) -> Vec<String> {
let present: BTreeMap<&str, (u64, u64)> = entries
.iter()
.map(|(k, v)| {
let key_order = match v {
SessionReadValue::Map(TypeIdentity::Item(id)) => (id.client, id.clock),
_ => (0, u64::MAX),
};
(k.as_str(), key_order)
})
.collect();
let mut map = self.surface_element_order.borrow_mut();
let order = map.entry(surface_id.to_string()).or_default();
order.retain(|k| present.contains_key(k.as_str()));
let existing: BTreeSet<String> = order.iter().cloned().collect();
let mut added: Vec<(&str, (u64, u64))> = present
.iter()
.filter(|(k, _)| !existing.contains(**k))
.map(|(&k, &ord)| (k, ord))
.collect();
added.sort_by(|a, b| {
b.1.0
.cmp(&a.1.0)
.then_with(|| a.1.1.cmp(&b.1.1))
.then_with(|| a.0.cmp(b.0))
});
order.extend(added.into_iter().map(|(k, _)| k.to_string()));
order.clone()
}
/// Refresh per-surface element orders across all `affine:surface` blocks currently in `blocks`.
fn refresh_all_surface_orders(&self) {
let Ok(blocks) = self.session.read_map(&self.blocks_target) else {
return;
};
for (block_id, value) in blocks {
let SessionReadValue::Map(block_ident) = value else {
continue;
};
let block_target = TypeTarget::Identity(block_ident);
let is_surface = matches!(
self.session.get_map_value(&block_target, "sys:flavour"),
Ok(Some(SessionReadValue::Any(Any::String(f)))) if f == "affine:surface"
);
if !is_surface {
continue;
}
if let Ok(Some(SessionReadValue::Map(elems_ident))) =
self.session.get_map_value(&block_target, "prop:elements")
&& let Ok(Some(SessionReadValue::Map(val_ident))) = self
.session
.get_map_value(&TypeTarget::Identity(elems_ident), "value")
&& let Ok(entries) = self.session.read_map(&TypeTarget::Identity(val_ident))
{
self.refresh_surface_element_order(&block_id, &entries);
}
}
}
pub fn guid(&self) -> &str {
self.session.guid()
}
@@ -223,6 +295,7 @@ impl PageDocSession {
/// commits so the caller can broadcast them back to the room.
pub fn apply_remote_update_v1(&mut self, bytes: &[u8]) -> DocResult<RemoteApplyResult> {
let commits = self.session.apply_update_v1(bytes)?;
self.refresh_all_surface_orders();
let outbound_updates = commits
.iter()
.filter(|c| {
@@ -487,6 +560,685 @@ impl PageDocSession {
Ok(self.session.map_set(&target, field.into(), value)?)
}
/// Format `[x, y, w, h]` into BlockSuite's wire `xywh` JSON string.
pub fn format_xywh(xywh: [f64; 4]) -> String {
let fmt = |v: f64| {
let rounded = (v * 100.0).round() / 100.0;
if (rounded - rounded.round()).abs() < 1e-6 {
format!("{}", rounded.round() as i64)
} else {
format!("{rounded}")
}
};
format!(
"[{},{},{},{}]",
fmt(xywh[0]),
fmt(xywh[1]),
fmt(xywh[2]),
fmt(xywh[3])
)
}
/// Find the page's existing `affine:surface` block, or create one under the root page.
pub fn ensure_surface_block(&mut self, now_ms: u64) -> DocResult<String> {
let snapshot = self.read_page_snapshot()?;
let root = snapshot
.root
.as_ref()
.ok_or_else(|| DocError::InvalidState("page has no root block".into()))?;
if let Some(surface) = root
.children
.iter()
.find(|c| matches!(c.content, crate::read::BlockContent::Surface { .. }))
{
return Ok(surface.id.clone());
}
let surface_id = format!("surface:{}", root.id);
self.add_block(
surface_id.clone(),
BlockSpec::Surface,
Some(&root.id),
Some(0),
now_ms,
)?;
Ok(surface_id)
}
/// Remove a surface element from `surface_block_id`'s `prop:elements.value` `Y.Map`.
/// Recursively clear all children of a Yjs container leaf-first so every underlying
/// `store.delete_item` deletes a single item (`ranges.len() == 1`), keeping
/// `DeleteSet` ranges sorted regardless of map iteration order.
fn clear_value_canonically(&mut self, value: SessionReadValue) -> DocResult<()> {
match value {
SessionReadValue::Map(ident) => {
let target = TypeTarget::Identity(ident);
let mut entries = self.session.read_map(&target)?;
entries.sort_by(|a, b| a.0.cmp(&b.0));
for (k, v) in entries {
self.clear_value_canonically(v)?;
self.session.map_remove(&target, &k)?;
}
}
SessionReadValue::Array(ident) => {
let target = TypeTarget::Identity(ident);
let items = self.session.read_array(&target)?;
for (idx, v) in items.into_iter().enumerate().rev() {
self.clear_value_canonically(v)?;
self.session.array_remove(&target, idx as u64, 1)?;
}
}
SessionReadValue::Text(ident) => {
let target = TypeTarget::Identity(ident);
let len = self.session.read_text_len(&target)?;
if len > 0 {
self.session.text_remove(&target, 0, len)?;
}
}
_ => {}
}
Ok(())
}
pub fn remove_surface_element(
&mut self,
surface_block_id: &str,
element_id: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
let elements_value_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value"),
);
let element_id = element_id.to_string();
if self.session.tx_depth() == 0 {
return self.structural_edit(now_ms, move |page| {
if let Some(val) = page
.session
.get_map_value(&elements_value_target, &element_id)?
{
page.clear_value_canonically(val)?;
}
page.session
.map_remove(&elements_value_target, &element_id)?;
Ok(())
});
}
self.advance_time(now_ms);
if let Some(val) = self
.session
.get_map_value(&elements_value_target, &element_id)?
{
self.clear_value_canonically(val)?;
}
Ok(self
.session
.map_remove(&elements_value_target, &element_id)?)
}
/// Update multiple fields on an existing surface element in one tracked transaction.
pub fn update_surface_element_fields(
&mut self,
surface_block_id: &str,
element_id: &str,
fields: Vec<(String, SessionValue)>,
now_ms: u64,
) -> DocResult<PageCommit> {
let surface_block_id = surface_block_id.to_string();
let element_id = element_id.to_string();
self.structural_edit(now_ms, move |page| {
let target = TypeTarget::Path(
TypePath::root("blocks")
.key(&surface_block_id)
.key("prop:elements")
.key("value")
.key(&element_id),
);
for (field, value) in fields {
page.session.map_set(&target, field, value)?;
}
Ok(())
})
}
/// Splice a UTF-16 range on a surface element's `Y.Text` field (`"text"` or `"title"`),
/// preserving untouched prefix/suffix characters and formatting marks under concurrent edits.
#[allow(clippy::too_many_arguments)]
pub fn splice_surface_element_text(
&mut self,
surface_block_id: &str,
element_id: &str,
field: &str,
utf16_start: u64,
utf16_delete_len: u64,
insert: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value")
.key(element_id),
);
match self.session.get_map_value(&elem_target, field)? {
Some(SessionReadValue::Text(identity)) => {
let target = TypeTarget::Identity(identity);
let len = self.session.read_text_len(&target)?;
let start = utf16_start.min(len);
let del = utf16_delete_len.min(len.saturating_sub(start));
if del > 0 && !insert.is_empty() {
let insert = insert.to_string();
self.structural_edit(now_ms, move |page| {
page.session.text_remove(&target, start, del)?;
page.session.text_insert(&target, start, &insert)?;
Ok(())
})
} else if del > 0 {
Ok(self.session.text_remove(&target, start, del)?)
} else if !insert.is_empty() {
Ok(self.session.text_insert(&target, start, insert)?)
} else {
Ok(None)
}
}
_ => {
let delta = if insert.is_empty() {
Vec::new()
} else {
vec![TextDeltaOp::Insert {
insert: TextInsert::Text(insert.to_string()),
format: None,
}]
};
Ok(self.session.map_set(
&elem_target,
field.to_string(),
SessionValue::Text(delta),
)?)
}
}
}
/// Splice a UTF-16 range on a block's `prop:title` `Y.Text` (e.g. `affine:frame`),
/// preserving untouched prefix/suffix characters and marks.
pub fn splice_block_title_text(
&mut self,
block_id: &str,
utf16_start: u64,
utf16_delete_len: u64,
insert: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:title"));
let len = self.session.read_text_len(&target).unwrap_or(0);
let start = utf16_start.min(len);
let del = utf16_delete_len.min(len.saturating_sub(start));
if del > 0 && !insert.is_empty() {
let insert = insert.to_string();
self.structural_edit(now_ms, move |page| {
page.session.text_remove(&target, start, del)?;
page.session.text_insert(&target, start, &insert)?;
Ok(())
})
} else if del > 0 {
Ok(self.session.text_remove(&target, start, del)?)
} else if !insert.is_empty() {
Ok(self.session.text_insert(&target, start, insert)?)
} else {
Ok(None)
}
}
/// Encode a `RelativePosition` at UTF-16 `offset` on a surface element's `Y.Text` field.
pub fn encode_surface_text_relative_position(
&self,
surface_block_id: &str,
element_id: &str,
field: &str,
offset: u64,
) -> DocResult<Option<RelativePosition>> {
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value")
.key(element_id),
);
let Some(SessionReadValue::Text(identity)) =
self.session.get_map_value(&elem_target, field)?
else {
return Ok(None);
};
let target = TypeTarget::Identity(identity);
let clamped = offset.min(self.session.read_text_len(&target)?);
Ok(Some(
self.session
.create_relative_position(&target, clamped, -1)?,
))
}
/// Resolve a `RelativePosition` back to a UTF-16 offset on a surface element's `Y.Text` field.
pub fn resolve_surface_text_relative_position(
&self,
surface_block_id: &str,
element_id: &str,
field: &str,
pos: &RelativePosition,
) -> DocResult<Option<u64>> {
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value")
.key(element_id),
);
let Some(SessionReadValue::Text(identity)) =
self.session.get_map_value(&elem_target, field)?
else {
return Ok(None);
};
let Some(abs) = self.session.resolve_relative_position(pos, true) else {
return Ok(None);
};
Ok((abs.r#type == identity).then_some(abs.index))
}
/// Encode a `RelativePosition` at UTF-16 `offset` on a block's `prop:title` `Y.Text`.
pub fn encode_block_title_relative_position(
&self,
block_id: &str,
offset: u64,
) -> DocResult<Option<RelativePosition>> {
let block = TypeTarget::Path(TypePath::root("blocks").key(block_id));
let Some(SessionReadValue::Text(identity)) =
self.session.get_map_value(&block, "prop:title")?
else {
return Ok(None);
};
let target = TypeTarget::Identity(identity);
let clamped = offset.min(self.session.read_text_len(&target)?);
Ok(Some(
self.session
.create_relative_position(&target, clamped, -1)?,
))
}
/// Resolve a `RelativePosition` back to a UTF-16 offset on a block's `prop:title` `Y.Text`.
pub fn resolve_block_title_relative_position(
&self,
block_id: &str,
pos: &RelativePosition,
) -> DocResult<Option<u64>> {
let block = TypeTarget::Path(TypePath::root("blocks").key(block_id));
let Some(SessionReadValue::Text(identity)) =
self.session.get_map_value(&block, "prop:title")?
else {
return Ok(None);
};
let Some(abs) = self.session.resolve_relative_position(pos, true) else {
return Ok(None);
};
Ok((abs.r#type == identity).then_some(abs.index))
}
/// Create an Edgeless-only Note (`prop:displayMode = "edgeless"`) with an initial paragraph
/// child in one atomic undoable transaction.
#[allow(clippy::too_many_arguments)]
pub fn add_edgeless_note(
&mut self,
root_id: &str,
note_id: &str,
para_id: &str,
index: &str,
xywh: [f64; 4],
text: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
let root_id = root_id.to_string();
let note_id = note_id.to_string();
let para_id = para_id.to_string();
let index = index.to_string();
let text = text.to_string();
self.structural_edit(now_ms, move |page| {
page.add_block(
&note_id,
BlockSpec::Note {
xywh: Some(Self::format_xywh(xywh)),
},
Some(&root_id),
None,
now_ms,
)?;
let note_target = block_target(&note_id);
page.session.map_set(
&note_target,
"prop:displayMode".to_string(),
SessionValue::Any(Any::String("edgeless".into())),
)?;
page.set_block_index(&note_id, &index, now_ms)?;
page.add_block(
&para_id,
BlockSpec::Paragraph {
paragraph_type: crate::schema::ParagraphType::Text,
text,
},
Some(&note_id),
None,
now_ms,
)?;
Ok(())
})
}
/// Create an `affine:frame` under `surface_id` (creating `affine:surface` inside the same
/// transaction when `surface_id` is `None`), set its `prop:index`, and populate
/// `prop:childElementIds` with `enclosed_ids` in one atomic undoable transaction.
#[allow(clippy::too_many_arguments)]
pub fn add_frame_with_children(
&mut self,
surface_id: Option<&str>,
frame_id: &str,
title: &str,
index: &str,
xywh: [f64; 4],
enclosed_ids: &[&str],
now_ms: u64,
) -> DocResult<PageCommit> {
let surface_id = surface_id.map(str::to_string);
let frame_id = frame_id.to_string();
let title = title.to_string();
let index = index.to_string();
let enclosed_ids: Vec<String> = enclosed_ids.iter().map(|s| (*s).to_string()).collect();
self.structural_edit(now_ms, move |page| {
let sid = match &surface_id {
Some(id) => id.clone(),
None => page.ensure_surface_block(now_ms)?,
};
page.add_block(
&frame_id,
BlockSpec::Frame {
title,
xywh: Some(Self::format_xywh(xywh)),
presentation_index: Some(index.clone()),
},
Some(&sid),
None,
now_ms,
)?;
page.set_block_index(&frame_id, &index, now_ms)?;
if !enclosed_ids.is_empty() {
page.set_frame_child_element_ids(&frame_id, &enclosed_ids, now_ms)?;
}
Ok(())
})
}
/// Commit a connector label on close (matching BlockSuite `edgeless-connector-label-editor.ts`):
/// - If `trimmed_text.is_empty()`, removes `"text"`, `"labelXYWH"`, and `"labelOffset"`.
/// - Otherwise sets `labelDisplay: true`, writes `labelOffset` (`{ distance: 0.5, anchor: "center" }`)
/// as a plain `Any::Object` if absent, and writes `labelXYWH` wrapped via [`crate::schema::map_array_any`].
pub fn commit_connector_label(
&mut self,
surface_block_id: &str,
element_id: &str,
trimmed_text: &str,
label_xywh: [f64; 4],
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value")
.key(element_id),
);
if trimmed_text.is_empty() {
return self.structural_edit(now_ms, move |page| {
for key in ["text", "labelXYWH", "labelOffset"] {
let _ = page.session.map_remove(&elem_target, key);
}
Ok(())
});
}
let has_offset = self
.session
.get_map_value(&elem_target, "labelOffset")?
.is_some();
let mut fields = vec![
("labelDisplay".to_string(), SessionValue::Any(Any::True)),
(
"labelXYWH".to_string(),
SessionValue::Any(crate::schema::map_array_any(
label_xywh
.into_iter()
.map(|v| Any::Float64(v.into()))
.collect(),
)),
),
];
if !has_offset {
let mut offset_map = y_octo::AHashMap::default();
offset_map.insert("distance".to_string(), Any::Float64(0.5.into()));
offset_map.insert("anchor".to_string(), Any::String("center".to_string()));
fields.push((
"labelOffset".to_string(),
SessionValue::Any(Any::Object(Box::new(offset_map))),
));
}
self.update_surface_element_fields(surface_block_id, element_id, fields, now_ms)
}
/// Delete the given blocks and surface elements, cascading to remove every `Connector`
/// in any `affine:surface` whose `source.id` or `target.id` references a deleted ID,
/// in one atomic undoable transaction.
pub fn delete_blocks_and_elements_with_connectors(
&mut self,
block_ids: &[&str],
surface_elements: &[(&str, &str)],
now_ms: u64,
) -> DocResult<PageCommit> {
let snap = self.read_page_snapshot()?;
let mut deleted_ids: std::collections::HashSet<String> = block_ids
.iter()
.map(|s| (*s).to_string())
.chain(surface_elements.iter().map(|(_, eid)| (*eid).to_string()))
.collect();
let mut cascade_connectors: Vec<(String, String)> = Vec::new();
if let Some(root) = &snap.root {
for node in root.walk() {
if let crate::read::BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if let crate::read::SurfaceElementKind::Connector(c) = &el.kind {
let src_hit = c
.source
.id
.as_deref()
.is_some_and(|id| deleted_ids.contains(id));
let tgt_hit = c
.target
.id
.as_deref()
.is_some_and(|id| deleted_ids.contains(id));
if (src_hit || tgt_hit) && deleted_ids.insert(el.id.clone()) {
cascade_connectors.push((node.id.clone(), el.id.clone()));
}
}
}
}
}
}
let block_parents: Vec<(String, Option<String>)> = block_ids
.iter()
.map(|&bid| {
let parent = snap.root.as_ref().and_then(|root| {
root.walk()
.find(|n| n.children.iter().any(|c| c.id == bid))
.map(|n| n.id.clone())
});
(bid.to_string(), parent)
})
.collect();
let mut all_surf: Vec<(String, String)> = surface_elements
.iter()
.map(|(s, e)| ((*s).to_string(), (*e).to_string()))
.collect();
all_surf.extend(cascade_connectors);
self.structural_edit(now_ms, move |page| {
for (sid, eid) in &all_surf {
page.remove_surface_element(sid, eid, now_ms)?;
}
for (bid, parent) in &block_parents {
if let Some(parent_id) = parent {
page.delete_block_subtree(parent_id, bid, now_ms)?;
}
}
Ok(())
})
}
/// Replace the `Y.Text` field (`"text"` or `"title"`) on a surface element.
pub fn set_surface_element_text(
&mut self,
surface_block_id: &str,
element_id: &str,
field: &str,
text: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key(surface_block_id)
.key("prop:elements")
.key("value")
.key(element_id),
);
let existing = self.session.get_map_value(&elem_target, field)?;
match existing {
Some(SessionReadValue::Text(identity)) => {
let target = TypeTarget::Identity(identity);
let len = self.session.read_text_len(&target)?;
let text = text.to_string();
self.structural_edit(now_ms, move |page| {
if len > 0 {
page.session.text_remove(&target, 0, len)?;
}
if !text.is_empty() {
page.session.text_insert(&target, 0, &text)?;
}
Ok(())
})
}
_ => {
let delta = if text.is_empty() {
Vec::new()
} else {
vec![TextDeltaOp::Insert {
insert: TextInsert::Text(text.to_string()),
format: None,
}]
};
Ok(self.session.map_set(
&elem_target,
field.to_string(),
SessionValue::Text(delta),
)?)
}
}
}
/// Replace `prop:title` `Y.Text` on a block (such as `affine:frame` or `affine:page`).
pub fn set_block_title_text(
&mut self,
block_id: &str,
text: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:title"));
let len = self.session.read_text_len(&target).unwrap_or(0);
let text = text.to_string();
self.structural_edit(now_ms, move |page| {
if len > 0 {
page.session.text_remove(&target, 0, len)?;
}
if !text.is_empty() {
page.session.text_insert(&target, 0, &text)?;
}
Ok(())
})
}
/// Update `prop:xywh` on a spatial block (`affine:note`, `affine:frame`, `affine:edgeless-text`).
pub fn set_block_xywh(
&mut self,
block_id: &str,
xywh: [f64; 4],
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:xywh",
SessionValue::Any(Any::String(Self::format_xywh(xywh))),
now_ms,
)
}
/// Update `prop:index` on a spatial block.
pub fn set_block_index(
&mut self,
block_id: &str,
index: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:index",
SessionValue::Any(Any::String(index.to_string())),
now_ms,
)
}
/// Update `prop:rotate` on a spatial block (e.g. `affine:edgeless-text`).
pub fn set_block_rotate(
&mut self,
block_id: &str,
rotate: f64,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:rotate",
SessionValue::Any(Any::Float64(rotate.into())),
now_ms,
)
}
/// Replace `prop:childElementIds` on an `affine:frame` block.
pub fn set_frame_child_element_ids(
&mut self,
frame_id: &str,
child_ids: &[String],
now_ms: u64,
) -> DocResult<PageCommit> {
let entries = child_ids
.iter()
.map(|id| (id.clone(), SessionValue::Any(Any::True)))
.collect();
self.set_block_prop(
frame_id,
"prop:childElementIds",
SessionValue::Map(entries),
now_ms,
)
}
fn child_graph(&self) -> DocResult<ChildGraph> {
self.session
.read_map(&self.blocks_target)?
@@ -557,6 +1309,9 @@ impl PageDocSession {
page.session
.array_remove(&children_target(parent_id), index, 1)?;
for id in candidates.difference(&retained) {
if let Some(val) = page.session.get_map_value(&page.blocks_target, id)? {
page.clear_value_canonically(val)?;
}
page.session.map_remove(&page.blocks_target, id)?;
}
Ok(())
@@ -1151,11 +1906,15 @@ impl PageDocSession {
}
pub fn undo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
Ok(self.session.undo_stack(self.undo_stack_id)?)
let res = self.session.undo_stack(self.undo_stack_id)?;
self.refresh_all_surface_orders();
Ok(res)
}
pub fn redo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
Ok(self.session.redo_stack(self.undo_stack_id)?)
let res = self.session.redo_stack(self.undo_stack_id)?;
self.refresh_all_surface_orders();
Ok(res)
}
pub fn can_undo(&self) -> bool {
@@ -334,3 +334,247 @@ fn converting_to_a_leaf_lifts_children_at_the_replaced_slot() -> DocResult {
assert_eq!(p.export_doc_json()?, original);
Ok(())
}
#[test]
fn commit_connector_label_encodes_single_array_item_and_plain_object_offset() -> DocResult {
use blocksuite_playground_doc::schema::{ConnectorEndpointSpec, SurfaceElementSpec};
use y_octo::{SessionReadValue, StateVector, TypePath, TypeTarget};
let mut p = PageDocSession::new("doc", 42)?;
p.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?;
p.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?;
p.add_surface_element(
"surf",
"c1",
"a0",
SurfaceElementSpec::Connector {
mode: 1,
seed: 7,
source: ConnectorEndpointSpec::point(0.0, 0.0),
target: ConnectorEndpointSpec::point(200.0, 100.0),
text: None,
label_xywh: None,
},
2,
)?;
// Clear any default labelOffset first so commit_connector_label exercises both labelXYWH and labelOffset writes.
p.commit_connector_label("surf", "c1", "", [0.0; 4], 3)?;
let sv_before = StateVector::decode_v1(&p.encode_state_vector_v1()?)?;
let clock_before = sv_before.get(&42);
let commit = p
.commit_connector_label("surf", "c1", "Edge", [120.0, 140.0, 64.0, 24.0], 4)?
.expect("commit");
let sv_after = StateVector::decode_v1(&p.encode_state_vector_v1()?)?;
let clock_after = sv_after.get(&42);
// Exactly 3 single-element map items: labelDisplay (1) + labelXYWH (1, NOT 4!) + labelOffset (1).
assert_eq!(
clock_after - clock_before,
3,
"labelXYWH must consume 1 CRDT clock (single Content::Any wrapping Any::Array), not 4"
);
let mut peer = PageDocSession::new("doc", 99)?;
peer.apply_remote_update_v1(&p.encode_update_v1()?)?;
let _ = commit;
let elem_target = TypeTarget::Path(
TypePath::root("blocks")
.key("surf")
.key("prop:elements")
.key("value")
.key("c1"),
);
match peer.inner().get_map_value(&elem_target, "labelXYWH")? {
Some(SessionReadValue::Any(Any::Array(vals))) => {
assert_eq!(vals.len(), 4);
assert_eq!(vals[0], Any::Float64(120.0.into()));
assert_eq!(vals[3], Any::Float64(24.0.into()));
}
other => panic!("expected Any::Array(4) for labelXYWH, got {other:?}"),
}
match peer.inner().get_map_value(&elem_target, "labelOffset")? {
Some(SessionReadValue::Any(Any::Object(obj))) => {
assert_eq!(obj.get("distance"), Some(&Any::Float64(0.5.into())));
assert_eq!(obj.get("anchor"), Some(&Any::String("center".to_string())));
}
other => panic!("expected plain Any::Object for labelOffset, got {other:?}"),
}
Ok(())
}
#[test]
fn fresh_page_frame_creation_is_atomic_across_peer_sync_and_undo() -> DocResult {
let mut a = PageDocSession::new("doc", 43)?;
a.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?;
let mut peer = PageDocSession::new("doc", 44)?;
peer.apply_remote_update_v1(&a.encode_update_v1()?)?;
let initial_json = a.export_doc_json()?;
let commit = a
.add_frame_with_children(
None,
"frame-1",
"Frame",
"a0",
[10.0, 20.0, 300.0, 200.0],
&[],
10,
)?
.expect("single atomic commit");
peer.apply_remote_update_v1(&commit.update)?;
assert_eq!(peer.export_doc_json()?, a.export_doc_json()?);
let snap = peer.read_page_snapshot()?;
assert!(snap.block("frame-1").is_some());
a.undo()?;
assert_eq!(a.export_doc_json()?, initial_json);
Ok(())
}
#[test]
fn multi_author_merged_v1_surface_tiebreak_matches_yjs_client_desc_clock_asc() -> DocResult {
use blocksuite_playground_doc::{read::BlockContent, schema::SurfaceElementSpec};
let mut base = PageDocSession::new("doc", 5)?;
base.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?;
base.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?;
let seed = base.encode_update_v1()?;
let mut c10 = PageDocSession::new("doc", 10)?;
c10.apply_remote_update_v1(&seed)?;
let mut c20 = PageDocSession::new("doc", 20)?;
c20.apply_remote_update_v1(&seed)?;
let shape = |xywh: &str| SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: xywh.into(),
seed: 1,
filled: true,
text: None,
};
let u20 = c20
.add_surface_element("surf", "z", "a0", shape("[0,0,40,40]"), 10)?
.unwrap()
.update;
let u10_a = c10
.add_surface_element("surf", "a", "a0", shape("[10,0,40,40]"), 10)?
.unwrap()
.update;
c20.apply_remote_update_v1(&u10_a)?;
let merged = c20.encode_update_v1()?;
let mut observer = PageDocSession::new("doc", 99)?;
observer.apply_remote_update_v1(&merged)?;
let snap = observer.read_page_snapshot()?;
let BlockContent::Surface { elements, .. } = &snap.block("surf").unwrap().content else {
panic!("expected surface");
};
let ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, vec!["z", "a"]);
// Same-client sequential inserts with equal index preserve clock ascending order.
let mut seq = PageDocSession::new("doc", 30)?;
seq.apply_remote_update_v1(&seed)?;
seq.add_surface_element("surf", "first", "a0", shape("[0,0,20,20]"), 10)?;
seq.add_surface_element("surf", "second", "a0", shape("[30,0,20,20]"), 11)?;
let mut seq_obs = PageDocSession::new("doc", 31)?;
seq_obs.apply_remote_update_v1(&seq.encode_update_v1()?)?;
let seq_snap = seq_obs.read_page_snapshot()?;
let BlockContent::Surface { elements, .. } = &seq_snap.block("surf").unwrap().content else {
panic!("expected surface");
};
let seq_ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect();
assert_eq!(seq_ids, vec!["first", "second"]);
let _ = u20;
Ok(())
}
#[test]
fn cascade_delete_after_property_mutations_undoes_and_redoes_all_elements() -> DocResult {
use blocksuite_playground_doc::{
read::BlockContent,
schema::{ConnectorEndpointSpec, SurfaceElementSpec},
};
use y_octo::SessionValue;
let mut page = PageDocSession::new("doc", 77)?;
page.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?;
page.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?;
page.add_surface_element(
"surf",
"sh-1",
"a0",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[100,100,120,80]".into(),
seed: 11,
filled: true,
text: Some("Box".into()),
},
2,
)?;
page.add_surface_element(
"surf",
"conn-att",
"a1",
SurfaceElementSpec::Connector {
mode: 0,
seed: 12,
source: ConnectorEndpointSpec::element("sh-1", Some([1.0, 0.5])),
target: ConnectorEndpointSpec::point(340.0, 140.0),
text: None,
label_xywh: None,
},
3,
)?;
// Mutate sh-1 fields after conn-att so sh-1 holds clocks both below and above conn-att.
page.set_surface_element_field(
"surf",
"sh-1",
"xywh",
SessionValue::Any(Any::String("[140,125,120,80]".into())),
4,
)?;
page.set_surface_element_field(
"surf",
"sh-1",
"rotate",
SessionValue::Any(Any::Float64(45.0.into())),
5,
)?;
page.set_surface_element_field(
"surf",
"sh-1",
"index",
SessionValue::Any(Any::String("a2".into())),
6,
)?;
page.stop_capturing()?;
let before_delete = page.export_doc_json()?;
page.delete_blocks_and_elements_with_connectors(&[], &[("surf", "sh-1")], 10)?;
let after_delete = page.export_doc_json()?;
let snap_del = page.read_page_snapshot()?;
let BlockContent::Surface { elements, .. } = &snap_del.block("surf").unwrap().content else {
panic!("expected surface");
};
assert!(
elements.is_empty(),
"both sh-1 and conn-att must be deleted"
);
page.undo()?;
assert_eq!(page.export_doc_json()?, before_delete);
let snap_undo = page.read_page_snapshot()?;
let BlockContent::Surface { elements, .. } = &snap_undo.block("surf").unwrap().content else {
panic!("expected surface");
};
let ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect();
assert!(
ids.contains(&"sh-1") && ids.contains(&"conn-att"),
"undo must restore both sh-1 and conn-att: {ids:?}"
);
page.redo()?;
assert_eq!(page.export_doc_json()?, after_delete);
Ok(())
}
@@ -290,6 +290,10 @@ enum OverlayState {
DragDropIndicator,
CodeHover,
CodeHoverCopied,
EdgelessSelected,
EdgelessMarquee,
EdgelessInlineEdit,
EdgelessAuthoring,
}
impl OverlayState {
@@ -308,6 +312,13 @@ impl OverlayState {
Self::CodeHoverCopied,
];
const ALL_EDGELESS: [Self; 4] = [
Self::EdgelessSelected,
Self::EdgelessMarquee,
Self::EdgelessInlineEdit,
Self::EdgelessAuthoring,
];
fn name(self) -> &'static str {
match self {
Self::Default => "default",
@@ -322,11 +333,28 @@ impl OverlayState {
Self::DragDropIndicator => "drag_drop_indicator",
Self::CodeHover => "code_hover",
Self::CodeHoverCopied => "code_hover_copied",
Self::EdgelessSelected => "edgeless_selected",
Self::EdgelessMarquee => "edgeless_marquee",
Self::EdgelessInlineEdit => "edgeless_inline_edit",
Self::EdgelessAuthoring => "edgeless_authoring",
}
}
fn parse(value: &str) -> Option<Self> {
Self::ALL.into_iter().find(|state| state.name() == value)
Self::ALL
.into_iter()
.chain(Self::ALL_EDGELESS)
.find(|state| state.name() == value)
}
fn is_edgeless(self) -> bool {
matches!(
self,
Self::EdgelessSelected
| Self::EdgelessMarquee
| Self::EdgelessInlineEdit
| Self::EdgelessAuthoring
)
}
/// Snapshot ids the state must show once it is applied.
@@ -351,6 +379,26 @@ impl OverlayState {
Self::DragHandleHover => &["overlay.drag_handle"],
Self::DragDropIndicator => &["overlay.drag_handle", "overlay.drop_indicator"],
Self::CodeHover | Self::CodeHoverCopied => &["page.block.showcase-code.copy"],
Self::EdgelessSelected => &[
"edgeless.viewport",
"chrome.edgeless_toolbar",
"chrome.edgeless_zoom",
],
Self::EdgelessMarquee => &[
"edgeless.viewport",
"chrome.edgeless_toolbar",
"chrome.edgeless_zoom",
],
Self::EdgelessInlineEdit => &[
"edgeless.viewport",
"chrome.edgeless_toolbar",
"edgeless.inline_edit",
],
Self::EdgelessAuthoring => &[
"edgeless.viewport",
"chrome.edgeless_toolbar",
"chrome.edgeless_zoom",
],
}
}
}
@@ -458,6 +506,73 @@ fn apply_overlay_state(session: &HeadlessSession, state: OverlayState) -> Result
session.headless_win.simulate_click(point(px(x), px(y)));
}
}
OverlayState::EdgelessSelected => {
session.frame()?;
session.update(|v, _, cx| {
v.edgeless_set_selection(["collect".to_string()], cx);
})?;
}
OverlayState::EdgelessMarquee => {
session.frame()?;
session.update(|v, _, cx| {
v.edgeless_set_selection(["collect".to_string(), "review".to_string()], cx);
v.edgeless_set_marquee((-120.0, -60.0), (540.0, 260.0), cx);
})?;
}
OverlayState::EdgelessInlineEdit => {
session.frame()?;
session.update(|v, w, cx| {
// Zoom to 1.4x centered on "collect" [818, 522, 150, 82] so inline edit is crisp and non-overlapping.
v.set_edgeless_camera(436.0, 296.0, 1.4, cx);
v.edgeless_begin_inline_edit("collect", w, cx);
v.replace_and_mark_text_in_range(None, " + edit", None, w, cx);
})?;
}
OverlayState::EdgelessAuthoring => {
session.frame()?;
// Frame open whiteboard space to the right (world x = 1220..1640, y = 220..760)
// alongside "collect"/"review" so authored items never overlap Page Note text.
session.update(|v, _, cx| {
v.set_edgeless_camera(740.0, 140.0, 0.85, cx);
})?;
session.frame()?;
// 1. Draw a Diamond shape in open canvas space: world (1250, 240) -> (1410, 360).
session.update(|v, w, cx| {
v.edgeless_select_tool(
playground::edgeless::EdgelessTool::Shape(
blocksuite_playground_doc::read::ShapeType::Diamond,
),
w,
cx,
);
})?;
session.pointer_down(433.5, 137.0);
session.pointer_move(569.5, 239.0, true);
session.pointer_up(569.5, 239.0);
session.frame()?;
// 2. Draw a port-snapped Orthogonal Connector from "review" right port to the new Diamond.
session.update(|v, w, cx| {
v.edgeless_select_tool(playground::edgeless::EdgelessTool::Connector, w, cx);
})?;
session.pointer_down(343.0, 578.0);
session.pointer_move(501.5, 239.0, true);
session.pointer_up(501.5, 239.0);
session.frame()?;
// 3. Draw a freehand Brush stroke in open canvas space: world (1260, 520) -> (1580, 560).
session.update(|v, w, cx| {
v.edgeless_select_tool(playground::edgeless::EdgelessTool::Brush, w, cx);
})?;
session.pointer_down(442.0, 375.0);
session.pointer_move(510.0, 345.0, true);
session.pointer_move(590.0, 415.0, true);
session.pointer_move(680.0, 365.0, true);
session.pointer_up(680.0, 365.0);
session.frame()?;
// 4. Show marquee selection around the open-space authored elements.
session.update(|v, _, cx| {
v.edgeless_set_marquee((1220.0, 210.0), (1620.0, 620.0), cx);
})?;
}
}
// Past every overlay transition, short of the `Copied` label's timeout.
session.frame()?;
@@ -592,6 +707,32 @@ fn run_audit_states() -> Result<()> {
snapshot.elements.contains_key("chrome.edgeless_zoom"),
"chrome.edgeless_zoom missing in {context}"
);
anyhow::ensure!(
snapshot.elements.contains_key("chrome.edgeless_toolbar"),
"chrome.edgeless_toolbar missing in {context}"
);
audited += 1;
}
// Audit Edgeless interactive authoring states in both themes and widths.
for state in OverlayState::ALL_EDGELESS {
let context = format!("{} {width}x{height} {}", state.name(), theme.as_str());
let session = start_headless_session(
width,
height,
PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
..PlaygroundOptions::default()
},
)?;
apply_overlay_state(&session, state).with_context(|| context.clone())?;
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {context}: {violations:#?}"
);
audited += 1;
}
}
@@ -609,8 +750,11 @@ fn render_headless(
zoom: Option<f32>,
pan: Option<(f32, f32)>,
state: OverlayState,
options: PlaygroundOptions,
mut options: PlaygroundOptions,
) -> Result<()> {
if state.is_edgeless() {
options.mode = PlaygroundMode::Edgeless;
}
let theme = options.theme;
let mode = options.mode;
let session = start_headless_session(width, height, options)?;
@@ -2539,6 +2683,162 @@ impl DemoRecorder<'_> {
}
}
/// Record a 60 fps full-product walkthrough: Page editing -> Edgeless switch ->
/// select/drag/rotate shape with live connector rerouting -> create shape, connector & brush ->
/// double-click inline IME label editing -> Undo/Redo -> Dark/Light theme toggle.
fn record_authoring_demo(dir: PathBuf) -> Result<()> {
std::fs::create_dir_all(&dir)?;
let session = start_headless_session(
1280,
800,
PlaygroundOptions {
theme: PlaygroundTheme::Light,
..Default::default()
},
)?;
session.frame()?;
let mut demo = DemoRecorder {
session: &session,
dir,
frames: 0,
pointer: (640.0, 400.0),
pressed: false,
};
// 1. Page editing (~0.8s).
demo.hold(12)?;
let intro_end = session.plain_text("showcase-intro")?.encode_utf16().count();
let (ix, iy) = demo.text_point("showcase-intro", intro_end)?;
demo.move_to((ix + 16.0, iy), 10)?;
demo.click()?;
demo.type_text(" live!", 6)?;
demo.hold(12)?;
// 2. Smooth mode switch to Edgeless (~0.6s).
let snap = session.frame()?;
let (ex, ey) = element_center(&snap, "chrome.mode_switcher.edgeless")?;
demo.move_to((ex, ey), 10)?;
demo.click()?;
demo.hold(24)?;
// 3. Select & drag "collect" shape with live connector rerouting (~1.1s).
let snap = session.frame()?;
if let Ok((sx, sy)) = element_center(&snap, "edgeless.surface.collect") {
demo.move_to((sx, sy), 12)?;
demo.press();
demo.move_to((sx + 70.0, sy - 35.0), 30)?;
demo.release();
demo.hold(15)?;
}
// 4. Rotate selected shape via top rotation handle (~0.8s).
let snap = session.frame()?;
if let Ok((rx, ry)) = element_center(&snap, "edgeless.handle.rotate") {
demo.move_to((rx, ry), 10)?;
demo.press();
demo.move_to((rx + 48.0, ry + 18.0), 24)?;
demo.release();
demo.hold(12)?;
}
// 5. Frame clean open whiteboard space to the right (world x >= 1220) and draw a Diamond shape (~1.0s).
session.update(|v, _, cx| {
v.set_edgeless_camera(740.0, 140.0, 0.85, cx);
})?;
demo.hold(10)?;
let snap = session.frame()?;
if let Ok((tx, ty)) = element_center(&snap, "chrome.edgeless_toolbar.shape") {
demo.move_to((tx, ty), 10)?;
demo.click()?;
demo.hold(6)?;
}
session.update(|v, w, cx| {
v.edgeless_select_tool(
playground::edgeless::EdgelessTool::Shape(
blocksuite_playground_doc::read::ShapeType::Diamond,
),
w,
cx,
);
})?;
demo.move_to((433.5, 137.0), 10)?;
demo.press();
demo.move_to((569.5, 239.0), 22)?;
demo.release();
demo.hold(12)?;
// 6. Pick Connector tool and drag a port-snapped orthogonal connector from "review" to the Diamond (~1.0s).
let snap = session.frame()?;
if let Ok((cx_t, cy_t)) = element_center(&snap, "chrome.edgeless_toolbar.connector") {
demo.move_to((cx_t, cy_t), 10)?;
demo.click()?;
demo.hold(6)?;
}
demo.move_to((343.0, 578.0), 10)?;
demo.press();
demo.move_to((501.5, 239.0), 22)?;
demo.release();
demo.hold(12)?;
// 7. Pick Brush tool and draw a smooth freehand stroke in open canvas space (~1.0s).
let snap = session.frame()?;
if let Ok((bx, by)) = element_center(&snap, "chrome.edgeless_toolbar.brush") {
demo.move_to((bx, by), 10)?;
demo.click()?;
demo.hold(6)?;
}
demo.move_to((442.0, 385.0), 8)?;
demo.press();
for step in 1..=24 {
let t = step as f32 / 24.0;
let x = 442.0 + t * 260.0;
let y = 385.0 + (t * std::f32::consts::TAU).sin() * 34.0;
demo.move_to((x, y), 1)?;
}
demo.release();
demo.hold(12)?;
// 8. Inline IME editing on "collect" shape label using bundled Inter glyphs (0 tofu boxes, ~1.2s).
session.update(|v, w, cx| {
v.edgeless_select_tool(playground::edgeless::EdgelessTool::Select, w, cx);
v.edgeless_begin_inline_edit("collect", w, cx);
})?;
demo.hold(12)?;
for pre in ["s", "sy", "syn", "sync"] {
session.update(|v, w, cx| {
v.replace_and_mark_text_in_range(None, pre, None, w, cx);
})?;
demo.hold(8)?;
}
session.update(|v, w, cx| {
v.replace_text_in_range(None, " + synced", w, cx);
v.edgeless_commit_inline_edit(w, cx);
})?;
demo.hold(16)?;
// 9. Undo & Redo (~0.8s).
demo.key("z", true, 16)?;
demo.hold(14)?;
session.key("z", true, true);
demo.hold(18)?;
// 10. Dark / Light theme toggle (~0.9s).
let snap = session.frame()?;
if let Ok((thx, thy)) = element_center(&snap, "chrome.theme_toggle") {
demo.move_to((thx, thy), 10)?;
demo.click()?;
demo.hold(24)?;
demo.click()?;
demo.hold(18)?;
}
println!(
"record-authoring-demo wrote {} frames at 60 fps",
demo.frames
);
Ok(())
}
/// Record a walk through the page editor and its overlays at 60 fps into `dir` as
/// `frame-<n>.png`: typing with marks and a composition, a slash command, a mouse selection
/// formatted from the toolbar, the block controls, and undo. Every step is an input event
@@ -2751,7 +3051,7 @@ fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let Some(cmd) = args.next() else {
bail!(
"usage: bs-harness <render|render-surface-sample|render-rich-sample|render-editor|record-demo|record-edgeless-demo|audit|audit-states|fps-check|probes|bench> [options]"
"usage: bs-harness <render|render-surface-sample|render-rich-sample|render-editor|record-demo|record-edgeless-demo|record-authoring-demo|audit|audit-states|fps-check|probes|bench> [options]"
);
};
@@ -2847,6 +3147,11 @@ fn main() -> Result<()> {
.context("record-edgeless-demo requires an output directory")?
.into(),
),
"record-authoring-demo" => record_authoring_demo(
args.next()
.context("record-authoring-demo requires an output directory")?
.into(),
),
"record-demo" => {
let dir = args
.next()
@@ -2322,7 +2322,10 @@ pub struct PresenceMark {
pub client_id: u64,
pub name: SharedString,
pub color: Hsla,
pub highlights: Vec<FlowRect>,
/// `(block_id, rect)` for each selection highlight span; code-block spans are
/// translated by `-scroll_x` before clamping in `page_elements`.
pub highlights: Vec<(String, FlowRect)>,
pub caret_block_id: String,
pub caret: FlowRect,
pub label: FlowRect,
label_text: ShapedLine,
@@ -2366,14 +2369,23 @@ impl FlowLayout {
let mut highlights = Vec::new();
let mut cover = |position: usize, start: usize, end: usize| {
let (_, block, text) = text_blocks[position];
let scrollable_code = block.body.code_scroll.is_some();
for (line, x0, x1) in text.layout.selection_spans(start, end) {
let left = (block.x + text.x + x0).floor();
let right = (block.x + text.x + x1).ceil().min(self.width);
highlights.push(FlowRect::new(
left,
block.y + text.y + line as f32 * text.layout.line_height(),
(right - left).max(0.0),
text.layout.line_height(),
let raw_right = (block.x + text.x + x1).ceil();
let right = if scrollable_code {
raw_right
} else {
raw_right.min(self.width)
};
highlights.push((
block.block_id.clone(),
FlowRect::new(
left,
block.y + text.y + line as f32 * text.layout.line_height(),
(right - left).max(0.0),
text.layout.line_height(),
),
));
}
};
@@ -2398,10 +2410,13 @@ impl FlowLayout {
let (_, block, text) = text_blocks[caret_position];
let (caret_x, caret_line) = text.layout.caret(caret_offset);
let line_height = text.layout.line_height();
let raw_caret_x = (block.x + text.x + caret_x - 1.0).round();
let caret = FlowRect::new(
(block.x + text.x + caret_x - 1.0)
.round()
.clamp(0.0, (self.width - 2.0).max(0.0)),
if block.body.code_scroll.is_some() {
raw_caret_x
} else {
raw_caret_x.clamp(0.0, (self.width - 2.0).max(0.0))
},
block.y + text.y + caret_line as f32 * line_height,
2.0,
line_height,
@@ -2414,7 +2429,7 @@ impl FlowLayout {
let label_width = (f32::from(label_text.width()).ceil() + 8.0).min(self.width);
// The tag hangs above the caret, shifted left at the column edge and flipped
// below the caret when there is no room above.
let label_x = caret.x.min((self.width - label_width).max(0.0));
let label_x = caret.x.clamp(0.0, (self.width - label_width).max(0.0));
let label_y = if caret.y >= PRESENCE_LABEL_HEIGHT {
caret.y - PRESENCE_LABEL_HEIGHT
} else {
@@ -2425,6 +2440,7 @@ impl FlowLayout {
name: SharedString::from(presence.name.clone()),
color: presence.color,
highlights,
caret_block_id: block.block_id.clone(),
caret,
label: FlowRect::new(label_x, label_y, label_width, PRESENCE_LABEL_HEIGHT),
label_text,
@@ -2519,19 +2535,52 @@ pub fn page_elements(
}
// Presence paints after every block so name tags stay above neighbouring text. Marks
// in a sideways-scrolled code block follow its lines and stay inside its code area.
let scrolled = paint.scrolled_code(layout);
// in a sideways-scrolled code block follow its lines and stay inside its code area;
// each highlight span uses its own block's horizontal scroll before clamping.
let code_blocks: HashMap<&str, ScrolledCode> = layout
.blocks
.iter()
.filter_map(|block| {
let code = block.body.code_scroll?;
let scroll_x = paint
.blocks
.get(&block.block_id)
.map_or(0.0, |state| state.code_scroll_x)
.clamp(0.0, code.max_x);
Some((
block.block_id.as_str(),
ScrolledCode {
block: block.rect(),
area: code.area.translated(block.x, block.y),
scroll_x,
},
))
})
.collect();
for mut mark in marks {
if let Some(code) = ScrolledCode::containing(&scrolled, &mark.caret) {
mark.highlights = mark
.highlights
.iter()
.filter_map(|rect| code.span(*rect))
.collect();
let mut resolved_highlights = Vec::with_capacity(mark.highlights.len());
for (block_id, rect) in &mark.highlights {
let clamped = if let Some(code) = code_blocks.get(block_id.as_str()) {
code.span(*rect).and_then(|r| {
let left = r.x.max(0.0);
let right = r.right().min(layout.width);
(right > left).then(|| FlowRect::new(left, r.y, right - left, r.h))
})
} else {
let left = rect.x.max(0.0);
let right = rect.right().min(layout.width);
(right > left).then(|| FlowRect::new(left, rect.y, right - left, rect.h))
};
if let Some(rect) = clamped {
resolved_highlights.push(rect);
}
}
if let Some(code) = code_blocks.get(mark.caret_block_id.as_str()) {
match code.caret(mark.caret) {
Some(caret) => {
mark.label.x = (mark.label.x - (mark.caret.x - caret.x)).max(0.0);
Some(mut caret) => {
caret.x = caret.x.clamp(0.0, (layout.width - 2.0).max(0.0));
mark.caret = caret;
mark.label.x = caret.x.clamp(0.0, (layout.width - mark.label.w).max(0.0));
}
None => {
// The caret scrolled out; its name tag goes with it.
@@ -2550,7 +2599,7 @@ pub fn page_elements(
};
// Same wash and corner radius as BlockSuite's remote selection rects.
let highlight = mark.color.opacity(0.2);
for rect in &mark.highlights {
for rect in &resolved_highlights {
if !viewport.intersects(rect) {
continue;
}
@@ -46,6 +46,13 @@ impl WorldRect {
&& self.bottom() > other.y
}
pub fn contains_rect(self, inner: Self) -> bool {
inner.x >= self.x
&& inner.y >= self.y
&& inner.right() <= self.right()
&& inner.bottom() <= self.bottom()
}
pub fn union(self, other: Self) -> Self {
if self.is_empty() {
return other;
@@ -0,0 +1,463 @@
//! Spatial Edgeless canvas state, layout caching, and world-space item preparation.
use std::{
collections::{BTreeMap, HashMap},
rc::Rc,
};
use blocksuite_playground_doc::read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot};
use serde_json::Value as JsonValue;
use ui::{BorderStyle, Bounds, Hsla, Pixels, Point, Size, point, px};
use crate::{
block_flow::{BlockFlow, FlowLayout, ImageSlot, InlineLayout},
editor_session::{DocPoint, DocumentSelection},
surface::{SurfaceLayout, WorldBounds},
theme::{Palette, PlaygroundTheme},
};
use super::{
EdgelessAuthoringState, EdgelessCamera, PaintItem, SpatialItemInfo, WorldRect, parse_xywh,
};
pub const EDGELESS_VIEWPORT_ID: &str = "edgeless.viewport";
/// Inner padding of an `affine:note` card on the Edgeless canvas (world px).
pub const NOTE_CARD_PADDING: f32 = 24.0;
/// Default corner radius of an `affine:note` card (world px).
pub(super) const CARD_RADIUS: f32 = 8.0;
/// Corner radius of an `affine:frame` container (world px, matching BlockSuite).
pub(super) const FRAME_RADIUS: f32 = 2.0;
/// Frame title pill height and vertical gap above the frame top edge (world px).
pub(super) const FRAME_TITLE_HEIGHT: f32 = 22.0;
pub(super) const FRAME_TITLE_GAP: f32 = 6.0;
/// Screen-space zoom bar constants (concentric radii: outer 8 - pad 4 == inner 4).
pub(super) const ZOOM_BAR_MARGIN: f32 = 12.0;
pub(super) const ZOOM_BAR_PAD: f32 = 4.0;
pub(super) const ZOOM_BAR_RADIUS: f32 = 8.0;
pub(super) const ZOOM_BTN_RADIUS: f32 = 4.0;
pub(super) const ZOOM_BTN_HEIGHT: f32 = 28.0;
type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64, u64);
pub(super) struct CachedNoteFlow {
pub(super) flow: BlockFlow,
pub(super) key: NoteLayoutKey,
pub(super) layout: Rc<FlowLayout>,
}
pub(super) struct CachedSurfaces {
pub(super) key: (u64, PlaygroundTheme, u64),
pub(super) layouts: Rc<[SurfaceLayout]>,
pub(super) order: Rc<[PaintItem]>,
pub(super) painted_items: Rc<[SpatialItemInfo]>,
}
pub(super) fn world_rect(b: Bounds<Pixels>) -> WorldRect {
WorldRect::new(
b.origin.x.into(),
b.origin.y.into(),
b.size.width.into(),
b.size.height.into(),
)
}
pub(super) fn world_bounds(r: WorldRect, rotate: f32) -> WorldBounds {
WorldBounds {
xywh: [r.x.into(), r.y.into(), r.w.into(), r.h.into()],
rotate: rotate.into(),
}
}
pub(super) fn rotated_bounds(r: WorldRect, degrees: f32) -> WorldRect {
world_rect(world_bounds(r, degrees).aabb().ui())
}
/// Persistent Edgeless camera, interaction state, and cached per-Note/EdgelessText layouts.
#[derive(Default)]
pub struct EdgelessCanvasState {
pub camera: EdgelessCamera,
pub camera_initialized: bool,
pub drag_pan_anchor: Option<Point<Pixels>>,
pub authoring: EdgelessAuthoringState,
pub(super) surfaces: Option<CachedSurfaces>,
pub(super) note_flows: HashMap<String, CachedNoteFlow>,
pub(super) text_flows: HashMap<String, CachedNoteFlow>,
/// Number of block bodies laid out during the most recent Edgeless frame.
pub last_frame_relayouts: u64,
}
/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`) from `root.children`
/// and any `BlockContent::Surface`'s children in document order.
pub(super) fn spatial_blocks(root: &BlockNode) -> Vec<&BlockNode> {
let mut out = Vec::new();
for child in &root.children {
match &child.content {
BlockContent::Surface { .. } => {
for sub in &child.children {
if is_spatial_block(sub) {
out.push(sub);
}
}
}
_ if is_spatial_block(child) => out.push(child),
_ => {}
}
}
out
}
fn is_spatial_block(node: &BlockNode) -> bool {
match &node.content {
BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => true,
BlockContent::Note {
display_mode,
hidden: false,
..
} => *display_mode != NoteDisplayMode::DocOnly,
_ => false,
}
}
fn edgeless_prop<'a>(
node: &'a BlockNode,
flat_key: &str,
nested: &[&str],
) -> Option<&'a JsonValue> {
if let Some(v) = node.props.get(flat_key) {
return Some(v);
}
let mut cur = node.props.get("prop:edgeless")?;
for seg in nested {
cur = cur.get(*seg)?;
}
Some(cur)
}
pub(super) fn note_scale(node: &BlockNode) -> f32 {
edgeless_prop(node, "prop:edgeless.scale", &["scale"])
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite())
.unwrap_or(1.0)
.clamp(0.1, 10.0)
}
pub(super) fn note_collapse(node: &BlockNode) -> bool {
edgeless_prop(node, "prop:edgeless.collapse", &["collapse"])
.and_then(JsonValue::as_bool)
.unwrap_or(false)
}
pub(super) fn note_border_style(node: &BlockNode) -> Option<(BorderStyle, f32)> {
let style = edgeless_prop(
node,
"prop:edgeless.style.borderStyle",
&["style", "borderStyle"],
)
.and_then(JsonValue::as_str)
.unwrap_or("none");
let border_style = match style {
"solid" => BorderStyle::Solid,
"dash" | "dashed" => BorderStyle::Dashed,
_ => return None,
};
let size = edgeless_prop(
node,
"prop:edgeless.style.borderSize",
&["style", "borderSize"],
)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(4.0);
if size <= 0.0 {
None
} else {
Some((border_style, size))
}
}
pub(super) fn note_border_radius(node: &BlockNode) -> f32 {
edgeless_prop(
node,
"prop:edgeless.style.borderRadius",
&["style", "borderRadius"],
)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite() && *v >= 0.0)
.unwrap_or(CARD_RADIUS)
}
pub(super) fn note_shadow_type(node: &BlockNode) -> &str {
edgeless_prop(
node,
"prop:edgeless.style.shadowType",
&["style", "shadowType"],
)
.and_then(JsonValue::as_str)
.unwrap_or("--affine-note-shadow-box")
}
impl EdgelessCanvasState {
pub fn new() -> Self {
Self::default()
}
pub fn set_camera(&mut self, pan_x: f32, pan_y: f32, zoom: f32) {
self.camera = EdgelessCamera::new(pan_x, pan_y, zoom);
self.camera_initialized = true;
}
pub fn ensure_camera_initialized(
&mut self,
snapshot: &PageSnapshot,
viewport_size: Size<Pixels>,
) {
if !self.camera_initialized
&& f32::from(viewport_size.width) > 0.0
&& f32::from(viewport_size.height) > 0.0
{
let bounds = self.scene_world_bounds(snapshot);
self.camera.fit_to_bounds(bounds, viewport_size, 48.0);
self.camera_initialized = true;
}
}
pub fn cached_block_layout(&self, block_id: &str, is_note: bool) -> Option<Rc<FlowLayout>> {
if is_note {
self.note_flows.get(block_id).map(|c| c.layout.clone())
} else {
self.text_flows.get(block_id).map(|c| c.layout.clone())
}
}
pub fn set_zoom_centered(
&mut self,
zoom: f32,
viewport_origin: Point<Pixels>,
viewport_size: Size<Pixels>,
) {
let center = point(
px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5),
px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5),
);
self.camera.zoom_at(zoom, center, viewport_origin);
self.camera_initialized = true;
}
pub fn set_pan(&mut self, pan_x: f32, pan_y: f32) {
self.camera.pan_x = pan_x;
self.camera.pan_y = pan_y;
self.camera_initialized = true;
}
#[cfg(test)]
pub fn cached_note_layout(&self, id: &str) -> Option<Rc<FlowLayout>> {
self.note_flows.get(id).map(|entry| entry.layout.clone())
}
#[cfg(test)]
pub(crate) fn cached_surface_layouts(&self) -> Rc<[SurfaceLayout]> {
self.surfaces.as_ref().unwrap().layouts.clone()
}
#[cfg(test)]
pub fn cached_text_layout(&self, id: &str) -> Option<Rc<FlowLayout>> {
self.text_flows.get(id).map(|entry| entry.layout.clone())
}
/// Compute the bounding box of all Edgeless-visible Frames, Notes, and EdgelessTexts.
pub fn scene_world_bounds(&self, snapshot: &PageSnapshot) -> WorldRect {
let mut union = WorldRect::default();
let Some(root) = &snapshot.root else {
return union;
};
for child in spatial_blocks(root) {
match &child.content {
BlockContent::Frame { xywh, .. } => {
if let Some(rect) = parse_xywh(xywh) {
let with_title = WorldRect::new(
rect.x,
rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP,
rect.w,
rect.h + FRAME_TITLE_HEIGHT + FRAME_TITLE_GAP,
);
union = union.union(with_title);
}
}
BlockContent::Note {
display_mode,
xywh,
hidden,
..
} if !hidden && *display_mode != NoteDisplayMode::DocOnly => {
let mut rect =
parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0));
if !note_collapse(child)
&& let Some(cached) = self.note_flows.get(&child.id)
{
let scale = note_scale(child);
rect.h = rect
.h
.max((cached.layout.height + 2.0 * NOTE_CARD_PADDING) * scale);
}
union = union.union(rect);
}
BlockContent::EdgelessText { xywh } => {
if let Some(mut rect) = parse_xywh(xywh) {
let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0);
if let Some(cached) = self.text_flows.get(&child.id) {
rect.h = (cached.layout.height * scale).max(rect.h);
}
union =
union.union(rotated_bounds(rect, prop_f32(child, "prop:rotate", 0.)));
}
}
_ => {}
}
}
if let Some(surfaces) = &self.surfaces {
for layout in surfaces.layouts.iter() {
for (_, bounds) in layout.bounds() {
union = union.union(world_rect(bounds));
}
}
}
union
}
}
/// Resolved frame card ready to paint on the GPU canvas.
pub(super) struct PaintFrame {
pub(super) id: String,
pub(super) title: String,
pub(super) index: String,
pub(super) frame_children: Vec<String>,
pub(super) rect: WorldRect,
pub(super) title_inline: Rc<InlineLayout>,
pub(super) title_pill_rect: WorldRect,
pub(super) fill: Option<Hsla>,
}
/// Resolved note card with its cached `FlowLayout`.
pub(super) struct PaintNote {
pub(super) id: String,
pub(super) index: String,
pub(super) rect: WorldRect,
pub(super) scale: f32,
pub(super) border: Option<(BorderStyle, f32)>,
pub(super) border_radius: f32,
pub(super) shadows: Vec<ui::BoxShadow>,
pub(super) fill: Hsla,
pub(super) layout: Rc<FlowLayout>,
}
/// Resolved edgeless-text block with its cached `FlowLayout` and rotation/scale.
pub(super) struct PaintEdgelessText {
pub(super) world_aabb: WorldRect,
pub(super) id: String,
pub(super) index: String,
pub(super) rect: WorldRect,
pub(super) scale: f32,
pub(super) rotate_deg: f32,
pub(super) layout: Rc<FlowLayout>,
}
/// Resolve a BlockSuite `{ light, dark }` color map or string color token against `theme`.
pub fn resolve_edgeless_color(value: &JsonValue, theme: PlaygroundTheme) -> Option<Hsla> {
let raw = match value {
JsonValue::String(s) => s.as_str(),
JsonValue::Object(map) => {
let key = match theme {
PlaygroundTheme::Light => "light",
PlaygroundTheme::Dark => "dark",
};
map.get(key)
.and_then(JsonValue::as_str)
.or_else(|| map.get("normal").and_then(JsonValue::as_str))?
}
_ => return None,
};
if raw.eq_ignore_ascii_case("transparent") || raw.is_empty() {
return Some(Hsla::transparent_black());
}
theme.css_color(raw)
}
pub(super) fn prop_f32(node: &BlockNode, key: &str, default: f32) -> f32 {
node.props
.get(key)
.and_then(JsonValue::as_f64)
.map(|v| v as f32)
.filter(|v| v.is_finite())
.unwrap_or(default)
}
pub(super) fn prop_bool(node: &BlockNode, key: &str, default: bool) -> bool {
node.props
.get(key)
.and_then(JsonValue::as_bool)
.unwrap_or(default)
}
/// Inputs needed to prepare and build one Edgeless canvas frame.
pub struct EdgelessRenderInput<'a> {
pub snapshot: &'a PageSnapshot,
pub doc_rev: u64,
pub env_rev: u64,
pub preedit_nonce: u64,
pub theme: PlaygroundTheme,
pub palette: &'a Palette,
pub page_titles: &'a BTreeMap<String, String>,
pub images: &'a HashMap<String, ImageSlot>,
pub viewport_width: f32,
pub viewport_height: f32,
pub editing_selection: Option<(String, bool, DocumentSelection, DocPoint)>,
}
#[cfg(test)]
mod tests {
use ui::AppContext;
#[test]
fn frame_one_zoom_badge_matches_fitted_camera_zoom() {
let platform = ui::HeadlessPlatform::new(1280, 800, 1.0);
let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let win = app
.update(|cx| {
cx.open_window(ui::WindowOptions::default(), |_window, cx| {
cx.new(|cx| {
crate::PlaygroundView::with_options(
crate::PlaygroundOptions {
mode: crate::PlaygroundMode::Edgeless,
..Default::default()
},
cx,
)
})
})
})
.unwrap();
let hw = platform.windows().into_iter().next().unwrap();
hw.request_frame();
// Frame 1 must already display the fitted zoom percentage (not stale "100%").
let snap = app
.update(|cx| win.update(cx, |_, window, _| window.frame_snapshot().clone()))
.unwrap();
let badge = snap
.elements
.get("chrome.edgeless_zoom.reset")
.expect("chrome.edgeless_zoom.reset missing on frame 1");
let text = badge.text.as_deref().unwrap_or("");
assert_ne!(
text, "100%",
"Frame 1 zoom badge must reflect fitted camera, got {text}"
);
assert!(text.ends_with('%'), "expected percentage badge, got {text}");
assert!(
snap.elements.contains_key("chrome.edgeless_toolbar"),
"chrome.edgeless_toolbar must be mounted on Frame 1"
);
}
}
@@ -0,0 +1,451 @@
//! GPU painting and screen-space snapshot markers for the Edgeless spatial canvas.
use ui::{
AnyElement, Background, BorderStyle, Bounds, ContentMask, Corners, Edges, Hsla, ScaledPixels,
SharedString, TransformationMatrix, Window, canvas, div, point, prelude::*, px, size,
};
use crate::block_flow::{BlockPaint, FlowLayout, FlowRect};
use crate::editor_session::DocumentSelection;
use super::{
EDGELESS_VIEWPORT_ID, EdgelessCanvasState, EdgelessInlineEdit, EdgelessRenderInput,
FRAME_RADIUS, NOTE_CARD_PADDING, PaintItem, PreparedEdgelessScene, WorldRect, bg_grid_gap,
build_edgeless_authoring_overlay, prepare_edgeless_scene, world_rect,
};
/// Prepare cached Note & EdgelessText layouts (zero relayout when camera moves), fit camera
/// on first render, and return the spatial canvas element plus screen-space snapshot markers.
pub fn build_edgeless_layer(
state: &mut EdgelessCanvasState,
input: &EdgelessRenderInput<'_>,
window: &Window,
zoom_controls: AnyElement,
toolbar: AnyElement,
) -> AnyElement {
let PreparedEdgelessScene {
frames,
notes,
texts,
surfaces,
order,
} = prepare_edgeless_scene(state, input, window);
if !state.camera_initialized && input.viewport_width > 0.0 && input.viewport_height > 0.0 {
let bounds = state.scene_world_bounds(input.snapshot);
state.camera.fit_to_bounds(
bounds,
size(px(input.viewport_width), px(input.viewport_height)),
48.0,
);
state.camera_initialized = true;
}
let camera = state.camera;
let palette = *input.palette;
let theme = input.theme;
let visible_world =
camera.visible_world_bounds(size(px(input.viewport_width), px(input.viewport_height)));
// Record screen-space snapshot markers for fully-visible spatial items so `bs-harness audit`
// and tests can inspect their screen bounds without triggering false clipping violations.
let mut snapshot_markers: Vec<AnyElement> = Vec::new();
let vp_origin = point(px(0.0), px(0.0));
let push_marker =
|markers: &mut Vec<AnyElement>, id: String, rect: WorldRect, text: Option<String>| {
let tl = camera.world_to_screen(point(px(rect.x), px(rect.y)), vp_origin);
let br = camera.world_to_screen(point(px(rect.right()), px(rect.bottom())), vp_origin);
let x = f32::from(tl.x);
let y = f32::from(tl.y);
let w = f32::from(br.x) - x;
let h = f32::from(br.y) - y;
if x >= 0.0
&& y >= 0.0
&& x + w <= input.viewport_width
&& y + h <= input.viewport_height
&& w >= 1.0
&& h >= 1.0
{
let mut el = div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.snapshot(SharedString::from(id), Some(EDGELESS_VIEWPORT_ID));
if let Some(t) = text {
el = el.snapshot_text(t);
}
markers.push(el.into_any_element());
}
};
for frame in &frames {
push_marker(
&mut snapshot_markers,
format!("edgeless.frame.{}", frame.id),
frame.rect,
Some(frame.title.clone()),
);
}
for layout in surfaces.iter() {
for (id, bounds) in layout.bounds() {
push_marker(
&mut snapshot_markers,
format!("edgeless.surface.{id}"),
world_rect(bounds),
None,
);
}
}
for note in &notes {
push_marker(
&mut snapshot_markers,
format!("edgeless.note.{}", note.id),
note.rect,
None,
);
}
for et in &texts {
push_marker(
&mut snapshot_markers,
format!("edgeless.text.{}", et.id),
et.world_aabb,
None,
);
}
let frame_border = theme
.css_var("--affine-v2-edgeless-frame-border")
.unwrap_or(palette.border);
let frame_pill_bg = palette.panel;
let authoring_overlays = build_edgeless_authoring_overlay(
&state.authoring,
camera,
input.viewport_width,
input.viewport_height,
&palette,
theme,
);
let editing_overlay: Option<(String, bool, Vec<FlowRect>, Option<FlowRect>)> = input
.editing_selection
.as_ref()
.and_then(|(editing_id, is_note, sel, focus)| {
let layout = state.cached_block_layout(editing_id, *is_note)?;
let sel_rects = spatial_selection_rects(sel, &layout);
let caret = layout
.block(&focus.block_id)
.and_then(|b| b.caret_rect(focus.caret));
Some((editing_id.clone(), *is_note, sel_rects, caret))
});
let editing_label_id: Option<String> = match &state.authoring.inline_edit {
Some(EdgelessInlineEdit::Label(ed)) => Some(ed.target.item_id().to_string()),
_ => None,
};
let paint_canvas = canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
// 1. Single-draw-call procedural dot-grid background.
let gap = bg_grid_gap(camera.zoom);
let (phase_x, phase_y) = camera.dot_grid_phase(gap);
window.paint_quad(ui::fill(
bounds,
Background::dot_grid(
palette.background,
palette.edgeless_grid,
gap,
1.0,
phase_x,
phase_y,
),
));
let cam_matrix = camera.to_transformation_matrix(bounds.origin);
let cull_world = visible_world.dilate(120.0);
window.with_content_mask(Some(ContentMask { bounds }), |window| {
window.with_paint_transformation(cam_matrix, |window| {
let viewport_world = Bounds::new(
point(px(visible_world.x), px(visible_world.y)),
size(px(visible_world.w), px(visible_world.h)),
);
for item in order.iter() {
match *item {
PaintItem::Frame(i) => {
let frame = &frames[i];
if !frame.rect.intersects(cull_world) {
continue;
}
let fb = Bounds::new(
point(px(frame.rect.x), px(frame.rect.y)),
size(px(frame.rect.w), px(frame.rect.h)),
);
window.paint_quad(ui::quad(
fb,
Corners::all(px(FRAME_RADIUS)),
frame.fill.unwrap_or_else(Hsla::transparent_black),
Edges::all(px(1.0)),
frame_border,
BorderStyle::Solid,
));
// Frame title pill above top-left corner (shared exact layout with hit-test).
let pill = frame.title_pill_rect;
window.paint_quad(ui::quad(
Bounds::new(
point(px(pill.x), px(pill.y)),
size(px(pill.w), px(pill.h)),
),
Corners::all(px(4.0)),
frame_pill_bg,
Edges::all(px(1.0)),
palette.border,
BorderStyle::Solid,
));
if editing_label_id.as_deref() != Some(frame.id.as_str()) {
frame.title_inline.paint(
point(px(pill.x + 8.0), px(pill.y)),
window,
cx,
);
}
}
PaintItem::Surface(l, i) => surfaces[l].paint_item(
i,
viewport_world,
editing_label_id.as_deref(),
window,
cx,
),
PaintItem::Note(i) => {
let note = &notes[i];
if !note.rect.intersects(cull_world) {
continue;
}
let nb = Bounds::new(
point(px(note.rect.x), px(note.rect.y)),
size(px(note.rect.w), px(note.rect.h)),
);
if !note.shadows.is_empty() {
window.paint_drop_shadows(
nb,
Corners::all(px(note.border_radius)),
&note.shadows,
);
}
let (border_widths, border_color, border_style) = match note.border
{
Some((style, width)) => {
(Edges::all(px(width)), palette.border, style)
}
None => (
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
),
};
window.paint_quad(ui::quad(
nb,
Corners::all(px(note.border_radius)),
note.fill,
border_widths,
border_color,
border_style,
));
let scale_transform = TransformationMatrix::unit()
.translate(point(
ScaledPixels(note.rect.x),
ScaledPixels(note.rect.y),
))
.scale(size(note.scale, note.scale))
.translate(point(
ScaledPixels(-note.rect.x),
ScaledPixels(-note.rect.y),
));
let inner_bounds = Bounds::new(
point(
px(note.rect.x + NOTE_CARD_PADDING),
px(note.rect.y + NOTE_CARD_PADDING),
),
size(
px((note.rect.w / note.scale - 2.0 * NOTE_CARD_PADDING)
.max(0.0)),
px((note.rect.h / note.scale - 2.0 * NOTE_CARD_PADDING)
.max(0.0)),
),
);
window.with_paint_transformation(scale_transform, |window| {
window.with_local_paint_mask(
ContentMask {
bounds: inner_bounds,
},
|window| {
for block in &note.layout.blocks {
let origin = point(
px(note.rect.x + NOTE_CARD_PADDING + block.x),
px(note.rect.y + NOTE_CARD_PADDING + block.y),
);
block.body.paint(
origin,
BlockPaint::default(),
window,
cx,
);
}
if let Some((ref eid, true, ref sel_rects, caret)) =
editing_overlay
&& eid == &note.id
{
for sr in sel_rects {
let sb = Bounds::new(
point(
px(note.rect.x
+ NOTE_CARD_PADDING
+ sr.x),
px(note.rect.y
+ NOTE_CARD_PADDING
+ sr.y),
),
size(px(sr.w), px(sr.h)),
);
window.paint_quad(ui::fill(
sb,
palette.brand.opacity(0.22),
));
}
if let Some(caret) = caret {
let cb = Bounds::new(
point(
px(note.rect.x
+ NOTE_CARD_PADDING
+ caret.x),
px(note.rect.y
+ NOTE_CARD_PADDING
+ caret.y),
),
size(
px(caret.w.max(2.0)),
px(caret.h.max(16.0)),
),
);
window.paint_quad(ui::fill(cb, palette.brand));
}
}
},
);
});
}
PaintItem::Text(i) => {
let et = &texts[i];
if !et.world_aabb.intersects(cull_world) {
continue;
}
let (cx_w, cy_w) = et.rect.center();
let scale_from_tl = TransformationMatrix::unit()
.translate(point(
ScaledPixels(et.rect.x),
ScaledPixels(et.rect.y),
))
.scale(size(et.scale, et.scale))
.translate(point(
ScaledPixels(-et.rect.x),
ScaledPixels(-et.rect.y),
));
let rotate_around_center = TransformationMatrix::unit()
.translate(point(ScaledPixels(cx_w), ScaledPixels(cy_w)))
.rotate(ui::radians(et.rotate_deg.to_radians()))
.translate(point(ScaledPixels(-cx_w), ScaledPixels(-cy_w)));
let local_transform = rotate_around_center.compose(scale_from_tl);
window.with_paint_transformation(local_transform, |window| {
for block in &et.layout.blocks {
let origin =
point(px(et.rect.x + block.x), px(et.rect.y + block.y));
block.body.paint(origin, BlockPaint::default(), window, cx);
}
if let Some((ref eid, false, ref sel_rects, caret)) =
editing_overlay
&& eid == &et.id
{
for sr in sel_rects {
let sb = Bounds::new(
point(px(et.rect.x + sr.x), px(et.rect.y + sr.y)),
size(px(sr.w), px(sr.h)),
);
window.paint_quad(ui::fill(
sb,
palette.brand.opacity(0.22),
));
}
if let Some(caret) = caret {
let cb = Bounds::new(
point(
px(et.rect.x + caret.x),
px(et.rect.y + caret.y),
),
size(px(caret.w.max(2.0)), px(caret.h.max(16.0))),
);
window.paint_quad(ui::fill(cb, palette.brand));
}
}
});
}
}
}
});
});
},
)
.size_full();
div()
.relative()
.flex_1()
.w_full()
.min_h_0()
.overflow_hidden()
.snapshot(EDGELESS_VIEWPORT_ID, Some("root.canvas"))
.child(paint_canvas)
.children(snapshot_markers)
.children(authoring_overlays)
.child(toolbar)
.child(zoom_controls)
.into_any_element()
}
fn spatial_selection_rects(sel: &DocumentSelection, layout: &FlowLayout) -> Vec<FlowRect> {
let mut out = Vec::new();
if sel.empty() {
return out;
}
let Some((start, end, a, b, _)) = sel.ordered(layout) else {
return out;
};
for block in &layout.blocks[a..=b] {
let from = if start.block_id == block.block_id {
start.offset()
} else {
0
};
let to = if end.block_id == block.block_id {
end.offset()
} else {
block.body.plain.encode_utf16().count() as u64
};
if let Some(t) = &block.body.text {
for (line, x0, x1) in t.layout.selection_spans(from as usize, to as usize) {
let top = block.y + t.y + line as f32 * t.layout.line_height();
out.push(FlowRect::new(
block.x + t.x + x0,
top,
(x1 - x0).max(2.0),
t.layout.line_height(),
));
}
}
}
out
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,680 @@
//! Pointer-up gesture commit to `PageDocSession` (shapes, connectors, brushes, notes, frames, transforms).
use blocksuite_playground_doc::{
fractional_index::generate_key_between,
read::{BlockContent, ShapeType, SurfaceElementKind},
schema::{ConnectorEndpointSpec, SurfaceElementSpec, map_array_any},
session::PageDocSession,
};
use ui::{Context, MouseUpEvent, Window};
use y_octo::{Any, SessionValue};
use crate::{
PlaygroundView,
editor_session::{DocPoint, DocumentSelection},
};
use super::{
EdgelessGesture, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, LabelTarget,
SpatialItemKind, WorldRect, max_spatial_index, normalized_rect, resized_rect, rotated_bounds,
};
impl PlaygroundView {
pub(crate) fn on_edgeless_left_up(
&mut self,
_event: &MouseUpEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(gesture) = self.edgeless.authoring.gesture.take() else {
return;
};
let now_ms = self.now_ms(cx) as u64;
match gesture {
EdgelessGesture::Pan { .. } | EdgelessGesture::Marquee { .. } => {
cx.notify();
}
EdgelessGesture::DragSelection {
start_world,
current_world,
initial,
} => {
let dx = (current_world.0 - start_world.0) as f64;
let dy = (current_world.1 - start_world.1) as f64;
if dx.hypot(dy) < 0.5 {
cx.notify();
return;
}
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for item in &initial {
let new_xywh = [
item.rect.x as f64 + dx,
item.rect.y as f64 + dy,
item.rect.w as f64,
item.rect.h as f64,
];
if item.kind.is_block() {
page.set_block_xywh(&item.id, new_xywh, now_ms)?;
} else if item.kind == SpatialItemKind::Connector {
if let Some(surface_id) = &item.surface_id {
if let Some((None, Some([sx, sy]))) = &item.connector_source {
page.set_surface_element_field(
surface_id,
&item.id,
"source",
SessionValue::Any(
ConnectorEndpointSpec::point(sx + dx, sy + dy)
.to_any(),
),
now_ms,
)?;
}
if let Some((None, Some([tx, ty]))) = &item.connector_target {
page.set_surface_element_field(
surface_id,
&item.id,
"target",
SessionValue::Any(
ConnectorEndpointSpec::point(tx + dx, ty + dy)
.to_any(),
),
now_ms,
)?;
}
if let Some([lx, ly, lw, lh]) = item.connector_label_xywh {
page.set_surface_element_field(
surface_id,
&item.id,
"labelXYWH",
SessionValue::Any(map_array_any(vec![
Any::Float64((lx + dx).into()),
Any::Float64((ly + dy).into()),
Any::Float64(lw.into()),
Any::Float64(lh.into()),
])),
now_ms,
)?;
}
}
} else if item.kind == SpatialItemKind::Group {
// Groups derive bounds from their children; never write synthetic xywh.
} else if let Some(surface_id) = &item.surface_id {
page.set_surface_element_field(
surface_id,
&item.id,
"xywh",
SessionValue::Any(Any::String(PageDocSession::format_xywh(
new_xywh,
))),
now_ms,
)?;
}
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
EdgelessGesture::ResizeSelection {
handle,
start_world,
current_world,
initial_box,
initial,
} => {
let new_box = resized_rect(initial_box, handle, start_world, current_world);
if (new_box.x - initial_box.x).abs() < 0.5
&& (new_box.y - initial_box.y).abs() < 0.5
&& (new_box.w - initial_box.w).abs() < 0.5
&& (new_box.h - initial_box.h).abs() < 0.5
{
cx.notify();
return;
}
let sx = (new_box.w / initial_box.w.max(1.0)) as f64;
let sy = (new_box.h / initial_box.h.max(1.0)) as f64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for item in &initial {
let nx = new_box.x as f64 + (item.rect.x - initial_box.x) as f64 * sx;
let ny = new_box.y as f64 + (item.rect.y - initial_box.y) as f64 * sy;
let nw = (item.rect.w as f64 * sx).max(16.0);
let nh = (item.rect.h as f64 * sy).max(16.0);
if item.kind.is_block() {
page.set_block_xywh(&item.id, [nx, ny, nw, nh], now_ms)?;
} else if item.kind == SpatialItemKind::Connector {
if let Some(surface_id) = &item.surface_id {
if let Some((None, Some([px_0, py_0]))) = &item.connector_source
{
let ex =
new_box.x as f64 + (px_0 - initial_box.x as f64) * sx;
let ey =
new_box.y as f64 + (py_0 - initial_box.y as f64) * sy;
page.set_surface_element_field(
surface_id,
&item.id,
"source",
SessionValue::Any(
ConnectorEndpointSpec::point(ex, ey).to_any(),
),
now_ms,
)?;
}
if let Some((None, Some([px_0, py_0]))) = &item.connector_target
{
let ex =
new_box.x as f64 + (px_0 - initial_box.x as f64) * sx;
let ey =
new_box.y as f64 + (py_0 - initial_box.y as f64) * sy;
page.set_surface_element_field(
surface_id,
&item.id,
"target",
SessionValue::Any(
ConnectorEndpointSpec::point(ex, ey).to_any(),
),
now_ms,
)?;
}
}
} else if item.kind == SpatialItemKind::Group {
// Groups derive bounds from their children; never write synthetic xywh.
} else if let Some(surface_id) = &item.surface_id {
page.set_surface_element_field(
surface_id,
&item.id,
"xywh",
SessionValue::Any(Any::String(PageDocSession::format_xywh([
nx, ny, nw, nh,
]))),
now_ms,
)?;
if let Some(points) = &item.points {
let scaled: Vec<Any> = points
.iter()
.map(|p| {
if p.len() >= 3 {
Any::Array(vec![
Any::Float64((p[0] * sx).into()),
Any::Float64((p[1] * sy).into()),
Any::Float64(p[2].into()),
])
} else {
Any::Array(vec![
Any::Float64((p[0] * sx).into()),
Any::Float64((p[1] * sy).into()),
])
}
})
.collect();
page.set_surface_element_field(
surface_id,
&item.id,
"points",
SessionValue::Any(map_array_any(scaled)),
now_ms,
)?;
}
}
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
EdgelessGesture::RotateSelection {
id,
surface_id,
is_block,
initial_rotate,
current_rotate,
..
} => {
if (current_rotate - initial_rotate).abs() < 0.1 {
cx.notify();
return;
}
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
if is_block {
page.set_block_rotate(&id, current_rotate, now_ms)?;
} else if let Some(sid) = &surface_id {
page.set_surface_element_field(
sid,
&id,
"rotate",
SessionValue::Any(Any::Float64(current_rotate.into())),
now_ms,
)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
EdgelessGesture::CreateShape {
shape_type,
start_world,
current_world,
} => {
let mut r = normalized_rect(start_world, current_world);
if r.w < 12.0 && r.h < 12.0 {
r = WorldRect::new(start_world.0 - 80.0, start_world.1 - 50.0, 160.0, 100.0);
} else {
r.w = r.w.max(40.0);
r.h = r.h.max(32.0);
}
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let shape_str = match shape_type {
ShapeType::Rect => "rect",
ShapeType::Ellipse => "ellipse",
ShapeType::Diamond => "diamond",
ShapeType::Triangle => "triangle",
};
let seed = (self.edgeless.authoring.next_id_seq as i32 + 17) * 97;
let cid = self.page().map(|p| p.client_id());
let id_opt = cid.map(|c| self.edgeless.authoring.next_id("shape", c));
if let Some(elem_id) = id_opt {
let elem_id_clone = elem_id.clone();
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
let surface_id = page.ensure_surface_block(now_ms)?;
page.add_surface_element(
&surface_id,
elem_id_clone.clone(),
&next_idx,
SurfaceElementSpec::Shape {
shape_type: shape_str.to_string(),
xywh: PageDocSession::format_xywh([
r.x as f64, r.y as f64, r.w as f64, r.h as f64,
]),
seed,
filled: true,
text: None,
},
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(elem_id);
self.edgeless.authoring.tool = EdgelessTool::Select;
}
}
}
EdgelessGesture::CreateFrame {
start_world,
current_world,
} => {
let mut r = normalized_rect(start_world, current_world);
if r.w < 20.0 && r.h < 20.0 {
r = WorldRect::new(start_world.0 - 160.0, start_world.1 - 120.0, 320.0, 240.0);
} else {
r.w = r.w.max(120.0);
r.h = r.h.max(80.0);
}
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let mut grouped_ids = std::collections::HashSet::<&str>::new();
if let Some(root) = self.snapshot.as_ref().and_then(|s| s.root.as_ref()) {
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if let SurfaceElementKind::Group { children, .. } = &el.kind {
for cid in children {
grouped_ids.insert(cid.as_str());
}
}
}
}
}
}
let enclosed: Vec<String> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|item| {
item.kind != SpatialItemKind::Frame
&& !grouped_ids.contains(item.id.as_str())
&& r.contains_rect(rotated_bounds(item.rect, item.rotate_deg))
})
.map(|item| item.id.clone())
.collect();
let cid = self.page().map(|p| p.client_id());
let id_opt = cid.map(|c| self.edgeless.authoring.next_id("frame", c));
if let Some(frame_id) = id_opt {
let frame_id_clone = frame_id.clone();
let commit = self.page_mut().ok().and_then(|page| {
let enclosed_refs: Vec<&str> =
enclosed.iter().map(String::as_str).collect();
page.add_frame_with_children(
None,
&frame_id_clone,
"Frame",
&next_idx,
[r.x as f64, r.y as f64, r.w as f64, r.h as f64],
&enclosed_refs,
now_ms,
)
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(frame_id);
self.edgeless.authoring.tool = EdgelessTool::Select;
}
}
}
EdgelessGesture::CreateNote {
start_world,
current_world,
} => {
let mut r = normalized_rect(start_world, current_world);
if r.w < 40.0 {
r = WorldRect::new(start_world.0 - 200.0, start_world.1 - 60.0, 440.0, 140.0);
} else {
r.w = r.w.max(240.0);
r.h = r.h.max(92.0);
}
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let root_id = self
.snapshot
.as_ref()
.and_then(|s| s.root.as_ref())
.map(|r| r.id.clone());
let cid = self.page().map(|p| p.client_id());
let ids = cid.map(|c| {
(
self.edgeless.authoring.next_id("note", c),
self.edgeless.authoring.next_id("para", c),
)
});
if let (Some(root_id), Some((note_id, para_id))) = (root_id, ids) {
let note_id_clone = note_id.clone();
let para_id_clone = para_id.clone();
let commit = self.page_mut().ok().and_then(|page| {
page.add_edgeless_note(
&root_id,
&note_id_clone,
&para_id_clone,
&next_idx,
[r.x as f64, r.y as f64, r.w as f64, r.h as f64],
"",
now_ms,
)
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(note_id.clone());
self.edgeless.authoring.tool = EdgelessTool::Select;
self.edgeless.authoring.inline_edit =
Some(EdgelessInlineEdit::SpatialBlock {
block_id: note_id,
is_note: true,
});
let pt = DocPoint::new(&para_id, 0);
self.editor.selection = Some(DocumentSelection {
anchor: pt.clone(),
focus: pt,
});
window.notify_text_input_changed(&self.editor_focus);
}
}
}
EdgelessGesture::CreateConnector {
source_id,
source_port,
source_world,
current_world,
target_id,
target_port,
target_world,
} => {
let dst = target_world.unwrap_or(current_world);
if (dst.0 - source_world.0).hypot(dst.1 - source_world.1) < 8.0
&& target_id.is_none()
{
cx.notify();
return;
}
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let seed = (self.edgeless.authoring.next_id_seq as i32 + 31) * 89;
let cid = self.page().map(|p| p.client_id());
let id_opt = cid.map(|c| self.edgeless.authoring.next_id("conn", c));
if let Some(conn_id) = id_opt {
let conn_id_clone = conn_id.clone();
let source = match (source_id, source_port) {
(Some(id), port) => ConnectorEndpointSpec::element(id, port),
_ => ConnectorEndpointSpec::point(
source_world.0 as f64,
source_world.1 as f64,
),
};
let target = match (target_id, target_port) {
(Some(id), port) => ConnectorEndpointSpec::element(id, port),
_ => ConnectorEndpointSpec::point(dst.0 as f64, dst.1 as f64),
};
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
let surface_id = page.ensure_surface_block(now_ms)?;
page.add_surface_element(
&surface_id,
conn_id_clone.clone(),
&next_idx,
SurfaceElementSpec::Connector {
mode: 1, // Orthogonal
seed,
source: source.clone(),
target: target.clone(),
text: None,
label_xywh: None,
},
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(conn_id);
self.edgeless.authoring.tool = EdgelessTool::Select;
}
}
}
EdgelessGesture::DrawStroke {
highlighter,
points_world,
} => {
if points_world.len() < 2 {
cx.notify();
return;
}
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
let mut max_x = f64::NEG_INFINITY;
let mut max_y = f64::NEG_INFINITY;
for &(x, y) in &points_world {
min_x = min_x.min(x);
min_y = min_y.min(y);
max_x = max_x.max(x);
max_y = max_y.max(y);
}
let line_width = if highlighter { 22.0 } else { 4.0 };
let half = line_width * 0.5;
let bx = min_x - half;
let by = min_y - half;
let bw = (max_x - min_x + line_width).max(line_width);
let bh = (max_y - min_y + line_width).max(line_width);
let local_points: Vec<Vec<f64>> = points_world
.iter()
.map(|&(x, y)| vec![x - bx, y - by])
.collect();
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let seed = (self.edgeless.authoring.next_id_seq as i32 + 53) * 61;
let prefix = if highlighter { "hl" } else { "brush" };
let cid = self.page().map(|p| p.client_id());
let id_opt = cid.map(|c| self.edgeless.authoring.next_id(prefix, c));
if let Some(stroke_id) = id_opt {
let stroke_id_clone = stroke_id.clone();
let xywh = PageDocSession::format_xywh([bx, by, bw, bh]);
let spec = if highlighter {
SurfaceElementSpec::Highlighter {
seed,
points: local_points,
xywh,
}
} else {
SurfaceElementSpec::Brush {
seed,
points: local_points,
xywh,
}
};
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
let surface_id = page.ensure_surface_block(now_ms)?;
page.add_surface_element(
&surface_id,
stroke_id_clone.clone(),
&next_idx,
spec.clone(),
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(stroke_id);
}
}
}
}
}
pub(super) fn create_surface_text_at(
&mut self,
wx: f32,
wy: f32,
window: &mut Window,
cx: &mut Context<Self>,
) {
let now_ms = self.now_ms(cx) as u64;
let next_idx = self
.snapshot
.as_deref()
.and_then(max_spatial_index)
.and_then(|m| generate_key_between(Some(&m), None).ok())
.unwrap_or_else(|| "a0".to_string());
let seed = (self.edgeless.authoring.next_id_seq as i32 + 71) * 43;
let cid = self.page().map(|p| p.client_id());
let id_opt = cid.map(|c| self.edgeless.authoring.next_id("text", c));
let Some(text_id) = id_opt else { return };
let text_id_clone = text_id.clone();
let rect = WorldRect::new(wx, wy, 180.0, 36.0);
let surface_id_out = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
let surface_id_ref = std::rc::Rc::clone(&surface_id_out);
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
let sid = page.ensure_surface_block(now_ms)?;
*surface_id_ref.borrow_mut() = sid.clone();
page.add_surface_element(
&sid,
text_id_clone.clone(),
&next_idx,
SurfaceElementSpec::Text {
seed,
text: String::new(),
xywh: PageDocSession::format_xywh([
rect.x as f64,
rect.y as f64,
rect.w as f64,
rect.h as f64,
]),
},
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(text_id.clone());
self.edgeless.authoring.tool = EdgelessTool::Select;
let mut ed = EdgelessLabelEditor::new(
LabelTarget::SurfaceText {
surface_id: surface_id_out.borrow().clone(),
id: text_id,
},
String::new(),
rect,
0.0,
true,
);
ed.created_new_text = true;
self.edgeless.authoring.inline_edit = Some(EdgelessInlineEdit::Label(ed));
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
}
self.edgeless_update_label_anchors(0..0);
window.notify_text_input_changed(&self.editor_focus);
}
}
}
@@ -0,0 +1,459 @@
//! Pointer down/move gesture state machine for Edgeless selection, drag, resize, rotate, and tool creation.
use std::collections::BTreeSet;
use blocksuite_playground_doc::read::SurfaceElementKind;
use ui::{Context, MouseDownEvent, MouseMoveEvent, Window, point, px};
use crate::{PlaygroundView, TOPBAR_HEIGHT, editor_session::DocumentSelection};
use super::{
DragItemInitial, EdgelessGesture, EdgelessTool, HandleKind, NOTE_CARD_PADDING, SpatialItemKind,
find_surface_element, layout_label_editor_paragraph, normalized_rect, point_in_rotated_rect,
rotate_point_around,
};
impl PlaygroundView {
pub(crate) fn on_edgeless_left_down(
&mut self,
event: &MouseDownEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.editor_focus.focus(window, cx);
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let world_pt = self
.edgeless
.camera
.screen_to_world(event.position, vp_origin);
let wx = f32::from(world_pt.x);
let wy = f32::from(world_pt.y);
// Hand tool or Space-hold pans with left drag.
if self.edgeless.authoring.tool == EdgelessTool::Hand || self.edgeless.authoring.space_pan {
self.edgeless_commit_inline_edit(window, cx);
self.edgeless.authoring.gesture = Some(EdgelessGesture::Pan {
last_screen: event.position,
});
cx.notify();
return;
}
// If currently inline-editing a Note/EdgelessText and clicking inside it, route to EditorSession.
if let Some((editing_id, is_note)) = self.edgeless.authoring.editing_spatial_block() {
let editing_id = editing_id.to_string();
if let Some(info) = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == editing_id)
.cloned()
&& point_in_rotated_rect(wx, wy, info.rect, info.rotate_deg)
{
let (cx_w, cy_w) = info.rect.center();
let (lx, ly) = rotate_point_around(wx, wy, cx_w, cy_w, -info.rotate_deg);
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let flow_x = (lx - info.rect.x) / info.scale - pad;
let flow_y = (ly - info.rect.y) / info.scale - pad;
if let Some(layout) = self.edgeless.cached_block_layout(&editing_id, is_note)
&& let Some(pt) = Self::hit_test_flow_layout(&layout, flow_x, flow_y)
{
let sel = DocumentSelection {
anchor: pt.clone(),
focus: pt,
};
self.change_selection(sel, window, cx);
return;
}
}
}
// If currently inline-editing a label (Shape/Connector/SurfaceText/Frame) and clicking
// inside its overlay bounds, hit-test the laid-out RichParagraph and place the caret.
if let Some(ed) = self.edgeless.authoring.label_editor() {
let bounds = self.edgeless_label_screen_bounds();
let inside_overlay = bounds.is_some_and(|b| b.contains(&event.position))
|| point_in_rotated_rect(wx, wy, ed.world_rect, ed.rotate_deg);
if inside_overlay {
let off = bounds
.and_then(|b| {
let laid_out = layout_label_editor_paragraph(
ed,
f32::from(b.size.width),
self.theme,
window,
)?;
let local_pt = point(
event.position.x - b.origin.x - px(6.0),
event.position.y - b.origin.y - px(6.0),
);
Some(laid_out.hit_test(local_pt).utf16_offset as usize)
})
.unwrap_or_else(|| ed.text.encode_utf16().count());
if let Some(ed_mut) = self.edgeless.authoring.label_editor_mut() {
ed_mut.select(off..off);
}
self.edgeless_update_label_anchors(off..off);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return;
}
}
// Clicking outside an active inline label/block edit commits and exits it.
if self.edgeless.authoring.inline_edit.is_some() {
self.edgeless_commit_inline_edit(window, cx);
}
match self.edgeless.authoring.tool {
EdgelessTool::Select => {
// Double-click enters inline rich-text / label IME editing.
if event.click_count >= 2 {
if let Some(hit) = self
.edgeless
.authoring
.hit_test_world(wx, wy, self.edgeless.camera.zoom)
.cloned()
{
self.edgeless_begin_inline_edit(&hit.id, window, cx);
return;
}
}
// 1. Check active selection handles first.
let vp_w = self.window_size.0.max(1.0);
let vp_h = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0);
if let Some(handle) = self.edgeless.authoring.hit_test_handles(
event.position,
vp_origin,
vp_w,
vp_h,
self.edgeless.camera,
) {
match handle {
HandleKind::Rotate => {
if let Some(single) = self.edgeless.authoring.single_selected().cloned()
{
let center = single.rect.center();
let start_angle = ((wy - center.1) as f64)
.atan2((wx - center.0) as f64)
.to_degrees();
self.edgeless.authoring.gesture =
Some(EdgelessGesture::RotateSelection {
id: single.id,
surface_id: single.surface_id,
is_block: single.kind.is_block(),
center_world: center,
start_angle,
initial_rotate: single.rotate_deg as f64,
current_rotate: single.rotate_deg as f64,
});
cx.notify();
return;
}
}
HandleKind::DragHandle => {
let initial = self.collect_drag_initials();
if !initial.is_empty() {
self.edgeless.authoring.gesture =
Some(EdgelessGesture::DragSelection {
start_world: (wx, wy),
current_world: (wx, wy),
initial,
});
cx.notify();
return;
}
}
_ => {
if let Some(initial_box) = self.edgeless.authoring.selection_world_box()
{
let initial = self.collect_drag_initials();
self.edgeless.authoring.gesture =
Some(EdgelessGesture::ResizeSelection {
handle,
start_world: (wx, wy),
current_world: (wx, wy),
initial_box,
initial,
});
cx.notify();
return;
}
}
}
}
// 2. Top-to-bottom reverse paint-order hit-test.
if let Some(hit) = self
.edgeless
.authoring
.hit_test_world(wx, wy, self.edgeless.camera.zoom)
.cloned()
{
if event.modifiers.shift {
if !self.edgeless.authoring.selection.remove(&hit.id) {
self.edgeless.authoring.selection.insert(hit.id.clone());
}
} else if !self.edgeless.authoring.selection.contains(&hit.id) {
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(hit.id.clone());
}
let initial = self.collect_drag_initials();
if !initial.is_empty() {
self.edgeless.authoring.gesture = Some(EdgelessGesture::DragSelection {
start_world: (wx, wy),
current_world: (wx, wy),
initial,
});
}
cx.notify();
} else {
// Empty canvas: clear selection and start marquee box.
if !event.modifiers.shift {
self.edgeless.authoring.selection.clear();
}
self.edgeless.authoring.gesture = Some(EdgelessGesture::Marquee {
start_world: (wx, wy),
current_world: (wx, wy),
});
cx.notify();
}
}
EdgelessTool::Shape(shape_type) => {
self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateShape {
shape_type,
start_world: (wx, wy),
current_world: (wx, wy),
});
cx.notify();
}
EdgelessTool::Frame => {
self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateFrame {
start_world: (wx, wy),
current_world: (wx, wy),
});
cx.notify();
}
EdgelessTool::Note => {
self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateNote {
start_world: (wx, wy),
current_world: (wx, wy),
});
cx.notify();
}
EdgelessTool::Connector => {
let snapped = self.edgeless.authoring.snap_connector_port(
wx,
wy,
self.edgeless.camera.zoom,
None,
);
let (source_id, source_port, source_world) = match snapped {
Some((id, port, pt)) => (Some(id), Some(port), pt),
None => (None, None, (wx, wy)),
};
self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateConnector {
source_id,
source_port,
source_world,
current_world: (wx, wy),
target_id: None,
target_port: None,
target_world: None,
});
cx.notify();
}
EdgelessTool::Brush | EdgelessTool::Highlighter => {
let highlighter = self.edgeless.authoring.tool == EdgelessTool::Highlighter;
self.edgeless.authoring.gesture = Some(EdgelessGesture::DrawStroke {
highlighter,
points_world: vec![(wx as f64, wy as f64)],
});
cx.notify();
}
EdgelessTool::Text => {
self.create_surface_text_at(wx, wy, window, cx);
}
EdgelessTool::Hand => {}
}
}
pub(crate) fn on_edgeless_pointer_move(
&mut self,
event: &MouseMoveEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
// Middle-button pan continues to work as before.
if let Some(prev) = self.edgeless.drag_pan_anchor {
let dx = f32::from(event.position.x) - f32::from(prev.x);
let dy = f32::from(event.position.y) - f32::from(prev.y);
self.edgeless.camera.pan_by_screen_delta(dx, dy);
self.edgeless.drag_pan_anchor = Some(event.position);
self.edgeless.camera_initialized = true;
cx.notify();
return;
}
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let world_pt = self
.edgeless
.camera
.screen_to_world(event.position, vp_origin);
let wx = f32::from(world_pt.x);
let wy = f32::from(world_pt.y);
let shift = event.modifiers.shift;
let zoom = self.edgeless.camera.zoom;
let conn_snap = match &self.edgeless.authoring.gesture {
Some(EdgelessGesture::CreateConnector { source_id, .. }) => self
.edgeless
.authoring
.snap_connector_port(wx, wy, zoom, source_id.as_deref()),
_ => None,
};
match self.edgeless.authoring.gesture.as_mut() {
Some(EdgelessGesture::Pan { last_screen }) => {
let dx = f32::from(event.position.x) - f32::from(last_screen.x);
let dy = f32::from(event.position.y) - f32::from(last_screen.y);
self.edgeless.camera.pan_by_screen_delta(dx, dy);
*last_screen = event.position;
self.edgeless.camera_initialized = true;
cx.notify();
}
Some(EdgelessGesture::Marquee {
start_world,
current_world,
}) => {
*current_world = (wx, wy);
let marquee = normalized_rect(*start_world, *current_world);
let hits: BTreeSet<String> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|item| item.rect.intersects(marquee))
.map(|item| item.id.clone())
.collect();
self.edgeless.authoring.selection = hits;
cx.notify();
}
Some(EdgelessGesture::DragSelection { current_world, .. })
| Some(EdgelessGesture::ResizeSelection { current_world, .. })
| Some(EdgelessGesture::CreateShape { current_world, .. })
| Some(EdgelessGesture::CreateFrame { current_world, .. })
| Some(EdgelessGesture::CreateNote { current_world, .. }) => {
*current_world = (wx, wy);
cx.notify();
}
Some(EdgelessGesture::RotateSelection {
center_world,
start_angle,
initial_rotate,
current_rotate,
..
}) => {
let angle = ((wy - center_world.1) as f64)
.atan2((wx - center_world.0) as f64)
.to_degrees();
let mut next = (*initial_rotate + (angle - *start_angle)).rem_euclid(360.0);
if shift {
next = (next / 15.0).round() * 15.0;
}
*current_rotate = next;
cx.notify();
}
Some(EdgelessGesture::CreateConnector {
current_world,
target_id,
target_port,
target_world,
..
}) => {
*current_world = (wx, wy);
if let Some((tid, port, pt)) = conn_snap {
*target_id = Some(tid);
*target_port = Some(port);
*target_world = Some(pt);
} else {
*target_id = None;
*target_port = None;
*target_world = None;
}
cx.notify();
}
Some(EdgelessGesture::DrawStroke { points_world, .. }) => {
let should_push = points_world
.last()
.is_none_or(|&(lx, ly)| ((wx as f64 - lx).hypot(wy as f64 - ly)) >= 2.0);
if should_push {
points_world.push((wx as f64, wy as f64));
cx.notify();
}
}
None => {}
}
}
pub(super) fn collect_drag_initials(&self) -> Vec<DragItemInitial> {
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let mut ids: BTreeSet<String> = self.edgeless.authoring.selection.clone();
// When dragging a Frame, include all of its `prop:childElementIds` members too!
for item in self.edgeless.authoring.painted_items.iter() {
if item.kind == SpatialItemKind::Frame && ids.contains(&item.id) {
for child_id in &item.frame_children {
ids.insert(child_id.clone());
}
}
}
let mut out = Vec::new();
for item in self.edgeless.authoring.painted_items.iter() {
if !ids.contains(&item.id) {
continue;
}
let mut points = None;
let mut connector_source = None;
let mut connector_target = None;
let mut connector_label_xywh = None;
if let Some((_, el)) = find_surface_element(snapshot, &item.id) {
match &el.kind {
SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => {
points = Some(
s.points
.iter()
.map(|p| {
if s.simulated_pressure {
vec![p[0], p[1]]
} else {
vec![p[0], p[1], p[2]]
}
})
.collect(),
);
}
SurfaceElementKind::Connector(c) => {
connector_source = Some((c.source.id.clone(), c.source.position));
connector_target = Some((c.target.id.clone(), c.target.position));
connector_label_xywh = c.label_xywh;
}
_ => {}
}
}
out.push(DragItemInitial {
id: item.id.clone(),
kind: item.kind,
surface_id: item.surface_id.clone(),
rect: item.rect,
points,
connector_source,
connector_target,
connector_label_xywh,
});
}
out
}
}
@@ -0,0 +1,854 @@
//! Edgeless selection state, reverse paint-order world hit-testing, and geometry helpers.
use std::{
collections::{BTreeMap, BTreeSet},
rc::Rc,
};
use blocksuite_playground_doc::read::ShapeType;
use ui::{Pixels, Point, point, px};
use super::{EdgelessCamera, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, WorldRect};
/// Interactive handle on the current Edgeless selection box.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HandleKind {
NW,
N,
NE,
E,
SE,
S,
SW,
W,
Rotate,
DragHandle,
}
impl HandleKind {
pub const RESIZE_HANDLES: [Self; 8] = [
Self::NW,
Self::N,
Self::NE,
Self::E,
Self::SE,
Self::S,
Self::SW,
Self::W,
];
pub fn snapshot_id(self) -> &'static str {
match self {
Self::NW => "edgeless.handle.nw",
Self::N => "edgeless.handle.n",
Self::NE => "edgeless.handle.ne",
Self::E => "edgeless.handle.e",
Self::SE => "edgeless.handle.se",
Self::S => "edgeless.handle.s",
Self::SW => "edgeless.handle.sw",
Self::W => "edgeless.handle.w",
Self::Rotate => "edgeless.handle.rotate",
Self::DragHandle => "edgeless.drag_handle",
}
}
}
/// Spatial item classification for hit-testing, handles, and mutations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpatialItemKind {
Note,
Frame,
EdgelessText,
Shape,
Connector,
Brush,
Highlighter,
SurfaceText,
Group,
}
impl SpatialItemKind {
pub fn is_block(self) -> bool {
matches!(self, Self::Note | Self::Frame | Self::EdgelessText)
}
pub fn is_rotatable(self) -> bool {
matches!(self, Self::Shape | Self::EdgelessText)
}
pub fn has_gfx_drag_handle(self) -> bool {
matches!(self, Self::Note | Self::Frame | Self::EdgelessText)
}
}
/// Snapshot-derived world-space descriptor for one painted Edgeless item in paint order.
#[derive(Clone, Debug)]
pub struct SpatialItemInfo {
pub id: String,
pub kind: SpatialItemKind,
pub surface_id: Option<String>,
pub rect: WorldRect,
pub rotate_deg: f32,
pub index: String,
pub scale: f32,
pub stroke_width: f32,
pub polyline: Vec<(f32, f32)>,
pub frame_children: Vec<String>,
pub title_pill_rect: Option<WorldRect>,
}
/// Target of an inline UTF-16 + IME label editor on the Edgeless canvas.
#[derive(Clone, Debug)]
pub struct DragItemInitial {
pub id: String,
pub kind: SpatialItemKind,
pub surface_id: Option<String>,
pub rect: WorldRect,
pub points: Option<Vec<Vec<f64>>>,
pub connector_source: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_target: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_label_xywh: Option<[f64; 4]>,
}
/// Active pointer gesture on the Edgeless canvas.
#[derive(Clone, Debug)]
pub enum EdgelessGesture {
Pan {
last_screen: Point<Pixels>,
},
Marquee {
start_world: (f32, f32),
current_world: (f32, f32),
},
DragSelection {
start_world: (f32, f32),
current_world: (f32, f32),
initial: Vec<DragItemInitial>,
},
ResizeSelection {
handle: HandleKind,
start_world: (f32, f32),
current_world: (f32, f32),
initial_box: WorldRect,
initial: Vec<DragItemInitial>,
},
RotateSelection {
id: String,
surface_id: Option<String>,
is_block: bool,
center_world: (f32, f32),
start_angle: f64,
initial_rotate: f64,
current_rotate: f64,
},
CreateShape {
shape_type: ShapeType,
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateFrame {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateNote {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateConnector {
source_id: Option<String>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
},
DrawStroke {
highlighter: bool,
points_world: Vec<(f64, f64)>,
},
}
/// Live geometry override applied during an active drag/resize/rotate gesture before commit.
#[derive(Clone, Copy, Debug)]
pub struct LiveGeomOverride {
pub rect: WorldRect,
pub rotate_deg: Option<f32>,
pub delta: (f32, f32),
}
/// Interactive authoring state owned by `EdgelessCanvasState`.
#[derive(Default)]
pub struct EdgelessAuthoringState {
pub tool: EdgelessTool,
pub last_shape_type: Option<ShapeType>,
pub selection: BTreeSet<String>,
pub(super) gesture: Option<EdgelessGesture>,
pub inline_edit: Option<EdgelessInlineEdit>,
pub space_pan: bool,
pub next_id_seq: u64,
/// Items in exact paint order from the most recent rendered frame.
pub(super) painted_items: Rc<[SpatialItemInfo]>,
}
impl EdgelessAuthoringState {
pub fn reset_transient(&mut self) {
self.gesture = None;
self.space_pan = false;
}
pub fn active_shape_type(&self) -> ShapeType {
match self.tool {
EdgelessTool::Shape(t) => t,
_ => self.last_shape_type.unwrap_or(ShapeType::Rect),
}
}
pub fn label_editor(&self) -> Option<&EdgelessLabelEditor> {
match &self.inline_edit {
Some(EdgelessInlineEdit::Label(ed)) => Some(ed),
_ => None,
}
}
pub fn label_editor_mut(&mut self) -> Option<&mut EdgelessLabelEditor> {
match &mut self.inline_edit {
Some(EdgelessInlineEdit::Label(ed)) => Some(ed),
_ => None,
}
}
pub fn editing_spatial_block(&self) -> Option<(&str, bool)> {
match &self.inline_edit {
Some(EdgelessInlineEdit::SpatialBlock { block_id, is_note }) => {
Some((block_id.as_str(), *is_note))
}
_ => None,
}
}
pub fn next_id(&mut self, prefix: &str, client_id: u64) -> String {
self.next_id_seq += 1;
format!("{prefix}:{client_id}:{}", self.next_id_seq)
}
/// Compute live per-item geometry overrides for an active drag/resize/rotate gesture.
pub fn live_overrides(&self) -> BTreeMap<String, LiveGeomOverride> {
let mut out = BTreeMap::new();
match &self.gesture {
Some(EdgelessGesture::DragSelection {
start_world,
current_world,
initial,
}) => {
let dx = current_world.0 - start_world.0;
let dy = current_world.1 - start_world.1;
for item in initial {
out.insert(
item.id.clone(),
LiveGeomOverride {
rect: WorldRect::new(
item.rect.x + dx,
item.rect.y + dy,
item.rect.w,
item.rect.h,
),
rotate_deg: None,
delta: (dx, dy),
},
);
}
}
Some(EdgelessGesture::ResizeSelection {
handle,
start_world,
current_world,
initial_box,
initial,
}) => {
let new_box = resized_rect(*initial_box, *handle, *start_world, *current_world);
let sx = if initial_box.w > 1e-3 {
new_box.w / initial_box.w
} else {
1.0
};
let sy = if initial_box.h > 1e-3 {
new_box.h / initial_box.h
} else {
1.0
};
for item in initial {
let nx = new_box.x + (item.rect.x - initial_box.x) * sx;
let ny = new_box.y + (item.rect.y - initial_box.y) * sy;
let nw = (item.rect.w * sx).max(16.0);
let nh = (item.rect.h * sy).max(16.0);
out.insert(
item.id.clone(),
LiveGeomOverride {
rect: WorldRect::new(nx, ny, nw, nh),
rotate_deg: None,
delta: (0.0, 0.0),
},
);
}
}
Some(EdgelessGesture::RotateSelection {
id, current_rotate, ..
}) => {
if let Some(info) = self.painted_items.iter().find(|i| i.id == *id) {
out.insert(
id.clone(),
LiveGeomOverride {
rect: info.rect,
rotate_deg: Some(*current_rotate as f32),
delta: (0.0, 0.0),
},
);
}
}
_ => {}
}
out
}
/// True if the selection contains at least one item that supports the 8 resize handles
/// (connectors hide the 8 resize handles because their geometry comes from endpoints).
pub fn selection_has_non_connector(&self) -> bool {
self.painted_items.iter().any(|item| {
self.selection.contains(&item.id) && item.kind != SpatialItemKind::Connector
})
}
/// Compute the selection's combined world-space bounding box (with live gesture overrides).
pub fn selection_world_box(&self) -> Option<WorldRect> {
let overrides = self.live_overrides();
let mut combined = WorldRect::default();
let mut any = false;
for item in self.painted_items.iter() {
if !self.selection.contains(&item.id) {
continue;
}
let rect = overrides.get(&item.id).map_or(item.rect, |o| o.rect);
combined = if any { combined.union(rect) } else { rect };
any = true;
}
any.then_some(combined)
}
/// Return the single selected item if `selection.len() == 1`.
pub fn single_selected(&self) -> Option<&SpatialItemInfo> {
if self.selection.len() != 1 {
return None;
}
let id = self.selection.iter().next()?;
self.painted_items.iter().find(|i| i.id == *id)
}
/// Hit-test active selection handles in screen space (`vp_origin`-relative).
pub fn hit_test_handles(
&self,
screen_pt: Point<Pixels>,
vp_origin: Point<Pixels>,
viewport_width: f32,
viewport_height: f32,
camera: EdgelessCamera,
) -> Option<HandleKind> {
let sel_box = self.selection_world_box()?;
let tl = camera.world_to_screen(point(px(sel_box.x), px(sel_box.y)), vp_origin);
let br =
camera.world_to_screen(point(px(sel_box.right()), px(sel_box.bottom())), vp_origin);
let x0 = f32::from(tl.x);
let y0 = f32::from(tl.y);
let x1 = f32::from(br.x);
let y1 = f32::from(br.y);
let mx = (x0 + x1) * 0.5;
let my = (y0 + y1) * 0.5;
let px_s = f32::from(screen_pt.x);
let py_s = f32::from(screen_pt.y);
let single = self.single_selected();
let rot_deg = single
.filter(|s| s.kind.is_rotatable() && s.rotate_deg.abs() > 1e-3)
.map_or(0.0, |s| s.rotate_deg);
let (rx_pt, ry_pt) = if rot_deg.abs() > 1e-3 {
rotate_point_around(px_s, py_s, mx, my, -rot_deg)
} else {
(px_s, py_s)
};
// Rotation handle (24px above top-center for single rotatable item).
if let Some(single) = single
&& single.kind.is_rotatable()
{
let rx = mx;
let ry = y0 - 24.0;
if (rx_pt - rx).hypot(ry_pt - ry) <= 10.0 {
return Some(HandleKind::Rotate);
}
}
// Edgeless gfx 2x3 drag handle left of single selected block (matches overlay.rs clamp).
if let Some(single) = single
&& single.kind.has_gfx_drag_handle()
{
let vp_x = f32::from(vp_origin.x);
let vp_y = f32::from(vp_origin.y);
let hx = (x0 - vp_x - 20.0)
.clamp(4.0, (viewport_width - 18.0).max(4.0))
.round()
+ vp_x;
let hy = (y0 - vp_y)
.clamp(4.0, (viewport_height - 28.0).max(4.0))
.round()
+ vp_y;
if px_s >= hx && px_s <= hx + 14.0 && py_s >= hy && py_s <= hy + 24.0 {
return Some(HandleKind::DragHandle);
}
}
if !self.selection_has_non_connector() {
return None;
}
let coords = [
(HandleKind::NW, x0, y0),
(HandleKind::N, mx, y0),
(HandleKind::NE, x1, y0),
(HandleKind::E, x1, my),
(HandleKind::SE, x1, y1),
(HandleKind::S, mx, y1),
(HandleKind::SW, x0, y1),
(HandleKind::W, x0, my),
];
for (kind, hx, hy) in coords {
if (rx_pt - hx).abs() <= 7.0 && (ry_pt - hy).abs() <= 7.0 {
return Some(kind);
}
}
None
}
/// Top-to-bottom hit-testing in exact reverse `edgeless_order.rs` paint order.
pub fn hit_test_world(
&self,
world_x: f32,
world_y: f32,
zoom: f32,
) -> Option<&SpatialItemInfo> {
let inv_zoom = 1.0 / zoom.max(0.1);
for item in self.painted_items.iter().rev() {
match item.kind {
SpatialItemKind::Shape
| SpatialItemKind::SurfaceText
| SpatialItemKind::EdgelessText => {
if point_in_rotated_rect(world_x, world_y, item.rect, item.rotate_deg) {
return Some(item);
}
}
SpatialItemKind::Note => {
if world_x >= item.rect.x
&& world_x <= item.rect.right()
&& world_y >= item.rect.y
&& world_y <= item.rect.bottom()
{
return Some(item);
}
}
SpatialItemKind::Connector
| SpatialItemKind::Brush
| SpatialItemKind::Highlighter => {
let threshold = (item.stroke_width * 0.5 + 6.0 * inv_zoom).max(6.0);
if !item.polyline.is_empty() {
if distance_to_polyline((world_x, world_y), &item.polyline) <= threshold {
return Some(item);
}
} else if world_x >= item.rect.x - threshold
&& world_x <= item.rect.right() + threshold
&& world_y >= item.rect.y - threshold
&& world_y <= item.rect.bottom() + threshold
{
return Some(item);
}
}
SpatialItemKind::Frame => {
// Frame hit-tests on its title pill and border so clicking inside an
// unselected frame can hit inner items or start a marquee selection.
if let Some(pill) = item.title_pill_rect
&& world_x >= pill.x
&& world_x <= pill.right()
&& world_y >= pill.y
&& world_y <= pill.bottom()
{
return Some(item);
}
let tol = (8.0 * inv_zoom).max(6.0);
let in_outer = world_x >= item.rect.x - tol
&& world_x <= item.rect.right() + tol
&& world_y >= item.rect.y - tol
&& world_y <= item.rect.bottom() + tol;
let in_inner = world_x > item.rect.x + tol
&& world_x < item.rect.right() - tol
&& world_y > item.rect.y + tol
&& world_y < item.rect.bottom() - tol;
if in_outer && !in_inner {
return Some(item);
}
}
SpatialItemKind::Group => {}
}
}
None
}
/// Snap a world coordinate to the nearest cardinal port on a Shape or Note within `snap_world`.
pub fn snap_connector_port(
&self,
world_x: f32,
world_y: f32,
zoom: f32,
exclude_id: Option<&str>,
) -> Option<(String, [f64; 2], (f32, f32))> {
let snap_dist = (24.0 / zoom.max(0.1)).max(16.0);
let ports: [[f64; 2]; 4] = [[0.5, 0.0], [1.0, 0.5], [0.5, 1.0], [0.0, 0.5]];
let mut best: Option<(f32, String, [f64; 2], (f32, f32))> = None;
for item in self.painted_items.iter() {
if !matches!(item.kind, SpatialItemKind::Shape | SpatialItemKind::Note) {
continue;
}
if exclude_id.is_some_and(|ex| ex == item.id) {
continue;
}
for port in ports {
let px_w = item.rect.x + item.rect.w * port[0] as f32;
let py_w = item.rect.y + item.rect.h * port[1] as f32;
let (wx, wy) = rotate_point_around(
px_w,
py_w,
item.rect.center().0,
item.rect.center().1,
item.rotate_deg,
);
let d = (world_x - wx).hypot(world_y - wy);
if d <= snap_dist && best.as_ref().is_none_or(|b| d < b.0) {
best = Some((d, item.id.clone(), port, (wx, wy)));
}
}
}
best.map(|(_, id, port, pt)| (id, port, pt))
}
}
pub fn rotate_point_around(x: f32, y: f32, cx: f32, cy: f32, deg: f32) -> (f32, f32) {
if deg.abs() < 1e-4 {
return (x, y);
}
let (s, c) = deg.to_radians().sin_cos();
let dx = x - cx;
let dy = y - cy;
(cx + dx * c - dy * s, cy + dx * s + dy * c)
}
pub fn point_in_rotated_rect(wx: f32, wy: f32, rect: WorldRect, rotate_deg: f32) -> bool {
let (cx, cy) = rect.center();
let (lx, ly) = rotate_point_around(wx, wy, cx, cy, -rotate_deg);
lx >= rect.x && lx <= rect.right() && ly >= rect.y && ly <= rect.bottom()
}
pub fn distance_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
let vx = b.0 - a.0;
let vy = b.1 - a.1;
let len_sq = vx * vx + vy * vy;
if len_sq < 1e-8 {
return (p.0 - a.0).hypot(p.1 - a.1);
}
let t = (((p.0 - a.0) * vx + (p.1 - a.1) * vy) / len_sq).clamp(0.0, 1.0);
let proj_x = a.0 + t * vx;
let proj_y = a.1 + t * vy;
(p.0 - proj_x).hypot(p.1 - proj_y)
}
pub fn distance_to_polyline(p: (f32, f32), pts: &[(f32, f32)]) -> f32 {
if pts.is_empty() {
return f32::INFINITY;
}
if pts.len() == 1 {
return (p.0 - pts[0].0).hypot(p.1 - pts[0].1);
}
pts.windows(2)
.map(|w| distance_to_segment(p, w[0], w[1]))
.fold(f32::INFINITY, f32::min)
}
pub fn normalized_rect(a: (f32, f32), b: (f32, f32)) -> WorldRect {
let x = a.0.min(b.0);
let y = a.1.min(b.1);
WorldRect::new(x, y, (a.0 - b.0).abs(), (a.1 - b.1).abs())
}
pub fn resized_rect(
initial: WorldRect,
handle: HandleKind,
start: (f32, f32),
current: (f32, f32),
) -> WorldRect {
let dx = current.0 - start.0;
let dy = current.1 - start.1;
let mut left = initial.x;
let mut top = initial.y;
let mut right = initial.right();
let mut bottom = initial.bottom();
const MIN_DIM: f32 = 24.0;
match handle {
HandleKind::NW => {
left = (left + dx).min(right - MIN_DIM);
top = (top + dy).min(bottom - MIN_DIM);
}
HandleKind::N => {
top = (top + dy).min(bottom - MIN_DIM);
}
HandleKind::NE => {
right = (right + dx).max(left + MIN_DIM);
top = (top + dy).min(bottom - MIN_DIM);
}
HandleKind::E => {
right = (right + dx).max(left + MIN_DIM);
}
HandleKind::SE => {
right = (right + dx).max(left + MIN_DIM);
bottom = (bottom + dy).max(top + MIN_DIM);
}
HandleKind::S => {
bottom = (bottom + dy).max(top + MIN_DIM);
}
HandleKind::SW => {
left = (left + dx).min(right - MIN_DIM);
bottom = (bottom + dy).max(top + MIN_DIM);
}
HandleKind::W => {
left = (left + dx).min(right - MIN_DIM);
}
HandleKind::Rotate | HandleKind::DragHandle => {}
}
WorldRect::new(left, top, right - left, bottom - top)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
surface::{WorldBounds, layout_surface},
theme::PlaygroundTheme,
};
use blocksuite_playground_doc::{
read::{BlockContent, SurfaceElementKind},
schema::{BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec},
session::PageDocSession,
};
use std::collections::BTreeMap;
use ui::{AppContext, Application, HeadlessPlatform};
#[test]
fn reverse_paint_order_hit_test_handles_rotated_obb_polyline_and_frame_border() {
let mut state = EdgelessAuthoringState::default();
state.painted_items = vec![
SpatialItemInfo {
id: "frame1".into(),
kind: SpatialItemKind::Frame,
surface_id: None,
rect: WorldRect::new(0.0, 0.0, 400.0, 300.0),
rotate_deg: 0.0,
index: "a0".into(),
scale: 1.0,
stroke_width: 1.0,
polyline: vec![],
frame_children: vec!["rot_shape".into()],
title_pill_rect: Some(WorldRect::new(0.0, -28.0, 80.0, 22.0)),
},
SpatialItemInfo {
id: "rot_shape".into(),
kind: SpatialItemKind::Shape,
surface_id: Some("surf".into()),
rect: WorldRect::new(100.0, 100.0, 100.0, 40.0),
rotate_deg: 90.0,
index: "a1".into(),
scale: 1.0,
stroke_width: 2.0,
polyline: vec![],
frame_children: vec![],
title_pill_rect: None,
},
SpatialItemInfo {
id: "brush1".into(),
kind: SpatialItemKind::Brush,
surface_id: Some("surf".into()),
rect: WorldRect::new(250.0, 50.0, 100.0, 10.0),
rotate_deg: 0.0,
index: "a2".into(),
scale: 1.0,
stroke_width: 4.0,
polyline: vec![(250.0, 55.0), (350.0, 55.0)],
frame_children: vec![],
title_pill_rect: None,
},
]
.into();
// Clicking empty interior of frame does NOT hit frame (allows marquee).
assert!(state.hit_test_world(50.0, 50.0, 1.0).is_none());
// Clicking frame title pill hits frame.
assert_eq!(state.hit_test_world(20.0, -15.0, 1.0).unwrap().id, "frame1");
// Clicking frame border hits frame.
assert_eq!(state.hit_test_world(2.0, 150.0, 1.0).unwrap().id, "frame1");
// Rotated 90° around (150, 120): (150, 75) is inside rotated 100x40 box!
assert_eq!(
state.hit_test_world(150.0, 75.0, 1.0).unwrap().id,
"rot_shape"
);
// Polyline hit within stroke_width/2 + 6px.
assert_eq!(state.hit_test_world(300.0, 58.0, 1.0).unwrap().id, "brush1");
assert!(state.hit_test_world(300.0, 75.0, 1.0).is_none());
}
#[test]
fn hit_test_world_hits_shapes_and_routed_element_bound_connector() {
let mut page = PageDocSession::new("p1", 1).unwrap();
page.add_block(
"page-1",
BlockSpec::Page {
title: "Test".into(),
},
None,
None,
1,
)
.unwrap();
let surf = page.ensure_surface_block(2).unwrap();
page.add_surface_element(
&surf,
"collect",
"a0",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[818,522,150,82]".into(),
seed: 31,
filled: true,
text: Some("Collect".into()),
},
3,
)
.unwrap();
page.add_surface_element(
&surf,
"review",
"a1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[988,722,156,74]".into(),
seed: 37,
filled: true,
text: Some("Review".into()),
},
4,
)
.unwrap();
page.add_surface_element(
&surf,
"handoff",
"a2",
SurfaceElementSpec::Connector {
mode: 1,
seed: 41,
source: ConnectorEndpointSpec::element("collect", Some([1.0, 0.5])),
target: ConnectorEndpointSpec::element("review", Some([0.5, 0.0])),
text: Some("Synthesize".into()),
label_xywh: None,
},
5,
)
.unwrap();
let snap = page.read_page_snapshot().unwrap();
let surf_node = snap
.root
.as_ref()
.unwrap()
.children
.iter()
.find(|c| c.id == surf)
.unwrap();
let BlockContent::Surface { elements, .. } = &surf_node.content else {
unreachable!()
};
let platform = HeadlessPlatform::new(64, 64, 1.0);
let app = Application::with_platform(platform).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let hits: Vec<(&str, Option<String>)> = app.update(|cx| {
let win = cx
.open_window(Default::default(), |_, cx| cx.new(|_| ui::Empty))
.unwrap();
let layout = win
.update(cx, |_, window, _| {
layout_surface(
elements,
&BTreeMap::<String, WorldBounds>::new(),
PlaygroundTheme::Light,
window,
)
})
.unwrap();
let mut st = EdgelessAuthoringState::default();
let mut items = Vec::new();
for (idx, id) in layout.item_ids().enumerate() {
let el = elements.iter().find(|e| e.id == id).unwrap();
let (kind, rect) = match &el.kind {
SurfaceElementKind::Shape(s) => (
SpatialItemKind::Shape,
WorldRect::new(
s.xywh[0] as f32,
s.xywh[1] as f32,
s.xywh[2] as f32,
s.xywh[3] as f32,
),
),
SurfaceElementKind::Connector(_) => {
(SpatialItemKind::Connector, WorldRect::default())
}
_ => continue,
};
items.push(SpatialItemInfo {
id: id.to_string(),
kind,
surface_id: Some(surf.clone()),
rect,
rotate_deg: el.rotate as f32,
index: el.index.clone(),
scale: 1.0,
stroke_width: layout.item_stroke_width(idx),
polyline: layout.item_polyline(idx).to_vec(),
frame_children: Vec::new(),
title_pill_rect: None,
});
}
st.painted_items = items.into();
[
("connector_mid", (1066.0, 640.0)),
("collect_shape", (893.0, 563.0)),
("review_shape", (1066.0, 759.0)),
("empty_canvas", (50.0, 50.0)),
]
.into_iter()
.map(|(case, (wx, wy))| (case, st.hit_test_world(wx, wy, 1.0).map(|it| it.id.clone())))
.collect()
});
assert_eq!(
hits,
vec![
("connector_mid", Some("handoff".to_string())),
("collect_shape", Some("collect".to_string())),
("review_shape", Some("review".to_string())),
("empty_canvas", None),
]
);
}
}
@@ -0,0 +1,609 @@
//! Double-click inline rich-text & IME editing for Edgeless shapes, connectors, text, frames, and notes.
use std::ops::Range;
use blocksuite_playground_doc::read::{
BlockContent, ConnectorMode, SurfaceConnector, SurfaceElementKind, TextAlign,
};
use ui::{Bounds, Context, FontWeight, Pixels, Window, point, px, size};
use y_octo::{TextDeltaOp, TextInsert};
use crate::{
PlaygroundView, TOPBAR_HEIGHT,
editor_session::{DocPoint, DocumentSelection},
rich_text::{RichParagraph, RichParagraphStyle},
theme::ThemeMode,
};
use super::{
EdgelessInlineEdit, EdgelessLabelEditor, LabelSplice, LabelTarget, NOTE_CARD_PADDING,
SpatialItemKind, WorldRect, find_block, find_surface_element, rotate_point_around, utf16_len,
};
/// Sample the routed connector polyline at `distance` (`0.0..=1.0`), matching
/// `surface::paint`'s `route.point_at_distance(mode, distance)`.
fn connector_label_anchor_point(
polyline: &[(f32, f32)],
fallback_center: (f32, f32),
mode: ConnectorMode,
distance: f64,
) -> (f64, f64) {
if polyline.len() < 2 {
return (fallback_center.0 as f64, fallback_center.1 as f64);
}
let d = distance.clamp(0.0, 1.0);
if mode == ConnectorMode::Curve {
let f = d * (polyline.len() - 1) as f64;
let i = (f.floor() as usize).min(polyline.len() - 2);
let t = f - i as f64;
let a = polyline[i];
let b = polyline[i + 1];
return (
a.0 as f64 + (b.0 as f64 - a.0 as f64) * t,
a.1 as f64 + (b.1 as f64 - a.1 as f64) * t,
);
}
let seg_len = |a: (f32, f32), b: (f32, f32)| ((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64);
let total: f64 = polyline.windows(2).map(|w| seg_len(w[0], w[1])).sum();
let mut rem = total * d;
for w in polyline.windows(2) {
let l = seg_len(w[0], w[1]);
if rem <= l && l > 0.0 {
let t = rem / l;
return (
w[0].0 as f64 + (w[1].0 as f64 - w[0].0 as f64) * t,
w[0].1 as f64 + (w[1].1 as f64 - w[0].1 as f64) * t,
);
}
rem -= l;
}
let last = *polyline.last().unwrap();
(last.0 as f64, last.1 as f64)
}
fn measure_connector_label_xywh(
c: &SurfaceConnector,
polyline: &[(f32, f32)],
fallback_center: (f32, f32),
trimmed: &str,
theme_mode: ThemeMode,
window: &Window,
) -> [f64; 4] {
let p =
connector_label_anchor_point(polyline, fallback_center, c.mode, c.label_offset.distance);
let l = &c.label_style;
let max_w = if c.label_constraints.has_max_width {
c.label_constraints.max_width as f32
} else {
1e6_f32
};
let mut style = RichParagraphStyle {
font_family: l
.font_family
.trim_start_matches("blocksuite:surface:")
.to_string()
.into(),
font_size: l.font_size as f32,
base_weight: FontWeight(l.font_weight.parse().unwrap_or(if l.font_weight == "bold" {
700.0
} else {
400.0
})),
align: match l.text_align {
TextAlign::Left => ui::TextAlign::Left,
TextAlign::Center => ui::TextAlign::Center,
TextAlign::Right => ui::TextAlign::Right,
},
..RichParagraphStyle::from_theme(theme_mode)
};
let ts = window.text_system();
let mut face = ui::font(style.font_family.clone());
face.weight = style.base_weight;
let font_id = ts.resolve_font(&face);
let font_px = px(style.font_size);
let ascent = f32::from(ts.ascent(font_id, font_px));
let descent = f32::from(ts.descent(font_id, font_px)).abs();
style.line_height = ascent + descent;
style.baseline_offset = Some(ascent);
let delta = vec![TextDeltaOp::Insert {
insert: TextInsert::Text(trimmed.to_string()),
format: None,
}];
let (w, h) = if let Ok(para) = RichParagraph::from_delta(delta) {
let laid = para.layout(ts, &style, max_w);
let measured_w = laid
.lines()
.iter()
.map(|line| f32::from(line.width))
.fold(0.0_f32, f32::max)
.ceil()
.max(1.0) as f64;
let measured_h = f64::from(f32::from(laid.size().height)).max(1.0);
(measured_w, measured_h)
} else {
let fallback_w = (trimmed.chars().count() as f64 * 8.0 + 24.0).clamp(64.0, 260.0);
(fallback_w, 28.0)
};
[p.0 - w * 0.5, p.1 - h * 0.5, w, h]
}
impl PlaygroundView {
/// Apply a live UTF-16 splice on the active inline label editor directly into `PageDocSession`
/// and update its `RelativePosition` anchors so concurrent remote edits merge cleanly.
pub(crate) fn edgeless_label_edit(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
f: impl FnOnce(&mut EdgelessLabelEditor) -> Option<LabelSplice>,
) -> Option<()> {
let (target, splice, sel_after) = {
let ed = self.edgeless.authoring.label_editor_mut()?;
let splice = f(ed);
(ed.target.clone(), splice, ed.selection.clone())
};
if let Some(splice) = splice {
let now_ms = self.now_ms(cx) as u64;
let commit = self
.page_mut()
.ok()
.and_then(|page| target.splice(page, splice, now_ms));
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
self.edgeless_update_label_anchors(sel_after);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
Some(())
}
pub(crate) fn edgeless_update_label_anchors(&mut self, sel: Range<usize>) {
let Some((target, preedit_range)) = self.edgeless.authoring.label_editor().map(|ed| {
(
ed.target.clone(),
ed.preedit.as_ref().map(|p| p.replacement.clone()),
)
}) else {
return;
};
let (anchors, preedit_anchors) = match self.page() {
Some(page) => {
let a = target
.encode_pos(page, sel.start)
.zip(target.encode_pos(page, sel.end));
let pa = preedit_range.and_then(|r| {
target
.encode_pos(page, r.start)
.zip(target.encode_pos(page, r.end))
});
(a, pa)
}
None => (None, None),
};
if let Some(ed) = self.edgeless.authoring.label_editor_mut() {
ed.anchors = anchors;
ed.preedit_anchors = preedit_anchors;
}
}
/// Refresh an open `EdgelessLabelEditor` from the latest snapshot after a remote update,
/// resolving its `RelativePosition` selection and preedit anchors so the local caret and
/// active composition track remote insertions.
pub(crate) fn edgeless_refresh_label_editor_from_snapshot(&mut self) {
let Some((target, anchors, preedit_anchors)) =
self.edgeless.authoring.label_editor().map(|ed| {
(
ed.target.clone(),
ed.anchors.clone(),
ed.preedit_anchors.clone(),
)
})
else {
return;
};
let Some(snapshot) = self.snapshot.clone() else {
return;
};
let latest = match &target {
LabelTarget::Shape { id, .. }
| LabelTarget::Connector { id, .. }
| LabelTarget::SurfaceText { id, .. } => {
find_surface_element(&snapshot, id).and_then(|(_, el)| match &el.kind {
SurfaceElementKind::Shape(s) => Some(s.text.plain.clone()),
SurfaceElementKind::Connector(c) => Some(c.text.plain.clone()),
SurfaceElementKind::Text(t) => Some(t.text.plain.clone()),
_ => None,
})
}
LabelTarget::FrameTitle { id } => {
find_block(&snapshot, id).and_then(|n| match &n.content {
BlockContent::Frame { title, .. } => Some(title.plain.clone()),
_ => None,
})
}
};
let Some(latest_text) = latest else {
self.edgeless.authoring.inline_edit = None;
return;
};
let resolve_pair = |pair: Option<(y_octo::RelativePosition, y_octo::RelativePosition)>| {
let (a, b) = pair?;
let page = self.page()?;
let s = target.resolve_pos(page, &a)?;
let e = target.resolve_pos(page, &b)?;
Some(s.min(e)..s.max(e))
};
let resolved_sel = resolve_pair(anchors);
let resolved_preedit = resolve_pair(preedit_anchors);
if let Some(ed) = self.edgeless.authoring.label_editor_mut() {
ed.text = latest_text;
let len = utf16_len(&ed.text);
ed.selection = match resolved_sel {
Some(r) => r.start.min(len)..r.end.min(len),
None => ed.selection.start.min(len)..ed.selection.end.min(len),
};
if let Some(pre) = &mut ed.preedit {
pre.replacement = match resolved_preedit {
Some(r) => r.start.min(len)..r.end.min(len),
None => pre.replacement.start.min(len)..pre.replacement.end.min(len),
};
}
}
}
/// Flush and commit an active inline label edit to `PageDocSession`, returning `true` if one was active.
pub(crate) fn edgeless_flush_label_edit(
&mut self,
window: &Window,
cx: &mut Context<Self>,
) -> bool {
let Some(EdgelessInlineEdit::Label(mut ed)) = self.edgeless.authoring.inline_edit.take()
else {
return false;
};
let now_ms = self.now_ms(cx) as u64;
if let Some(splice) = ed.unmark() {
let commit = self
.page_mut()
.ok()
.and_then(|page| ed.target.splice(page, splice, now_ms));
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
if ed.created_new_text && ed.text.trim().is_empty() {
if let LabelTarget::SurfaceText { surface_id, id } = &ed.target {
let sid = surface_id.clone();
let eid = id.clone();
self.edgeless.authoring.selection.remove(&eid);
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.remove_surface_element(&sid, &eid, now_ms)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
} else if let LabelTarget::Connector { surface_id, id } = &ed.target
&& ed.dirty
{
let trimmed = ed.text.trim();
let label_xywh = if trimmed.is_empty() {
[0.0; 4]
} else {
let polyline: Vec<(f32, f32)> = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == *id)
.map(|i| i.polyline.clone())
.unwrap_or_default();
if let Some((_, el)) = self
.snapshot
.as_deref()
.and_then(|snap| find_surface_element(snap, id))
&& let SurfaceElementKind::Connector(c) = &el.kind
{
measure_connector_label_xywh(
c,
&polyline,
ed.world_rect.center(),
trimmed,
self.theme.mode(),
window,
)
} else {
let (cx_w, cy_w) = ed.world_rect.center();
let lw = (trimmed.chars().count() as f64 * 8.0 + 24.0).clamp(64.0, 260.0);
let lh = 28.0;
[cx_w as f64 - lw * 0.5, cy_w as f64 - lh * 0.5, lw, lh]
}
};
let commit = self.page_mut().ok().and_then(|page| {
page.commit_connector_label(surface_id, id, trimmed, label_xywh, now_ms)
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
}
true
}
/// Commit and exit any active Edgeless inline edit (label or spatial block).
pub fn edgeless_commit_inline_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if matches!(
self.edgeless.authoring.inline_edit,
Some(EdgelessInlineEdit::Label(_))
) {
self.edgeless_flush_label_edit(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return;
}
let Some(EdgelessInlineEdit::SpatialBlock { .. }) =
self.edgeless.authoring.inline_edit.take()
else {
return;
};
self.clear_composition(window, cx);
self.editor.selection = None;
self.announce_selection(cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
}
/// Open inline editing on an Edgeless item (Note, EdgelessText, Shape, Connector, SurfaceText, or Frame).
pub fn edgeless_begin_inline_edit(
&mut self,
item_id: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
self.edgeless_commit_inline_edit(window, cx);
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(info) = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == item_id)
.cloned()
else {
return false;
};
match info.kind {
SpatialItemKind::Note | SpatialItemKind::EdgelessText => {
let is_note = info.kind == SpatialItemKind::Note;
let first_text_id = find_block(&snapshot, item_id).and_then(|node| {
node.walk()
.find(|n| {
matches!(
n.content,
BlockContent::Paragraph { .. }
| BlockContent::List { .. }
| BlockContent::Code { .. }
)
})
.map(|n| n.id.clone())
});
self.edgeless.authoring.selection.clear();
self.edgeless
.authoring
.selection
.insert(item_id.to_string());
self.edgeless.authoring.inline_edit = Some(EdgelessInlineEdit::SpatialBlock {
block_id: item_id.to_string(),
is_note,
});
if let Some(tid) = first_text_id {
let pt = DocPoint::new(&tid, 0);
self.editor.selection = Some(DocumentSelection {
anchor: pt.clone(),
focus: pt,
});
}
self.editor_focus.focus(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
true
}
SpatialItemKind::Shape | SpatialItemKind::Connector | SpatialItemKind::SurfaceText => {
let Some((surface_id, el)) = find_surface_element(&snapshot, item_id) else {
return false;
};
let (target, initial, multiline, edit_rect) = match &el.kind {
SurfaceElementKind::Shape(s) => (
LabelTarget::Shape {
surface_id: surface_id.to_string(),
id: el.id.clone(),
},
s.text.plain.clone(),
true,
info.rect,
),
SurfaceElementKind::Connector(c) => {
let p = connector_label_anchor_point(
&info.polyline,
info.rect.center(),
c.mode,
c.label_offset.distance,
);
(
LabelTarget::Connector {
surface_id: surface_id.to_string(),
id: el.id.clone(),
},
c.text.plain.clone(),
false,
WorldRect::new(p.0 as f32 - 80.0, p.1 as f32 - 18.0, 160.0, 36.0),
)
}
SurfaceElementKind::Text(t) => (
LabelTarget::SurfaceText {
surface_id: surface_id.to_string(),
id: el.id.clone(),
},
t.text.plain.clone(),
true,
info.rect,
),
_ => return false,
};
let len = utf16_len(&initial);
self.edgeless.authoring.selection.clear();
self.edgeless
.authoring
.selection
.insert(item_id.to_string());
self.edgeless.authoring.inline_edit =
Some(EdgelessInlineEdit::Label(EdgelessLabelEditor::new(
target,
initial,
edit_rect,
info.rotate_deg,
multiline,
)));
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
}
self.edgeless_update_label_anchors(len..len);
self.editor_focus.focus(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
true
}
SpatialItemKind::Frame => {
let initial = find_block(&snapshot, item_id)
.and_then(|n| match &n.content {
BlockContent::Frame { title, .. } => Some(title.plain.clone()),
_ => None,
})
.unwrap_or_default();
let len = utf16_len(&initial);
let rect = info.title_pill_rect.unwrap_or_else(|| {
WorldRect::new(info.rect.x, info.rect.y - 28.0, 140.0, 24.0)
});
self.edgeless.authoring.selection.clear();
self.edgeless
.authoring
.selection
.insert(item_id.to_string());
self.edgeless.authoring.inline_edit =
Some(EdgelessInlineEdit::Label(EdgelessLabelEditor::new(
LabelTarget::FrameTitle {
id: item_id.to_string(),
},
initial,
rect,
0.0,
false,
)));
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
}
self.edgeless_update_label_anchors(len..len);
self.editor_focus.focus(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
true
}
_ => false,
}
}
pub(crate) fn edgeless_label_input<R>(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
f: impl FnOnce(&mut EdgelessLabelEditor) -> R,
) -> Option<R> {
let (out, sel) = {
let ed = self.edgeless.authoring.label_editor_mut()?;
let out = f(ed);
(out, ed.selection.clone())
};
self.edgeless_update_label_anchors(sel);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
Some(out)
}
pub(crate) fn edgeless_label_screen_bounds(&self) -> Option<Bounds<Pixels>> {
let ed = self.edgeless.authoring.label_editor()?;
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let vp_w = self.window_size.0.max(1.0);
let vp_h = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0);
let cam = self.edgeless.camera;
let tl = cam.world_to_screen(point(px(ed.world_rect.x), px(ed.world_rect.y)), vp_origin);
let br = cam.world_to_screen(
point(px(ed.world_rect.right()), px(ed.world_rect.bottom())),
vp_origin,
);
let w = (f32::from(br.x) - f32::from(tl.x))
.max(120.0)
.min(vp_w - 16.0);
let h = (f32::from(br.y) - f32::from(tl.y))
.max(32.0)
.min(vp_h - 16.0);
let x = f32::from(tl.x).clamp(8.0, (vp_w - w - 8.0).max(8.0));
let y =
(f32::from(tl.y) - TOPBAR_HEIGHT).clamp(8.0, (vp_h - h - 8.0).max(8.0)) + TOPBAR_HEIGHT;
Some(Bounds::new(point(px(x), px(y)), size(px(w), px(h))))
}
/// Map a local caret `FlowRect` inside an actively edited Edgeless Note or EdgelessText
/// to screen-space `Bounds<Pixels>` for macOS IME candidates & Web `ImeMirror`.
pub(crate) fn edgeless_spatial_block_caret_bounds(
&self,
block_id: &str,
offset: u64,
) -> Option<Bounds<Pixels>> {
let (editing_id, is_note) = self.edgeless.authoring.editing_spatial_block()?;
let info = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == editing_id)?;
let caret = self
.edgeless
.cached_block_layout(editing_id, is_note)?
.block(block_id)?
.caret_rect(DocPoint::new(block_id, offset).caret)?;
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let (cx_w, cy_w) = info.rect.center();
let (rx, ry) = rotate_point_around(
info.rect.x + (pad + caret.x) * info.scale,
info.rect.y + (pad + caret.y) * info.scale,
cx_w,
cy_w,
info.rotate_deg,
);
let tl = self
.edgeless
.camera
.world_to_screen(point(px(rx), px(ry)), point(px(0.0), px(TOPBAR_HEIGHT)));
let z = self.edgeless.camera.zoom;
Some(Bounds::new(
tl,
size(
px((caret.w * info.scale * z).max(2.0)),
px((caret.h * info.scale * z).max(16.0)),
),
))
}
}
@@ -0,0 +1,424 @@
//! Pure UTF-16 + IME inline label editor state for Edgeless shapes, connectors, text, and frames.
use std::ops::Range;
use blocksuite_playground_doc::session::{PageDocSession, SelectionSnapshot};
use y_octo::{RelativePosition, SessionCommit};
use super::WorldRect;
/// Result of a text-mutating operation on [`EdgelessLabelEditor`]: `(utf16_start, utf16_delete_len, insert)`.
pub type LabelSplice = (usize, usize, String);
/// Target of an inline UTF-16 + IME label editor on the Edgeless canvas.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelTarget {
Shape { surface_id: String, id: String },
Connector { surface_id: String, id: String },
SurfaceText { surface_id: String, id: String },
FrameTitle { id: String },
}
impl LabelTarget {
pub fn item_id(&self) -> &str {
match self {
Self::Shape { id, .. }
| Self::Connector { id, .. }
| Self::SurfaceText { id, .. }
| Self::FrameTitle { id } => id,
}
}
pub(super) fn splice(
&self,
page: &mut PageDocSession,
(start, del_len, insert): LabelSplice,
now_ms: u64,
) -> Option<SessionCommit<SelectionSnapshot>> {
match self {
Self::Shape { surface_id, id }
| Self::Connector { surface_id, id }
| Self::SurfaceText { surface_id, id } => page
.splice_surface_element_text(
surface_id,
id,
"text",
start as u64,
del_len as u64,
&insert,
now_ms,
)
.ok()
.flatten(),
Self::FrameTitle { id } => page
.splice_block_title_text(id, start as u64, del_len as u64, &insert, now_ms)
.ok()
.flatten(),
}
}
pub(super) fn encode_pos(
&self,
page: &PageDocSession,
offset: usize,
) -> Option<RelativePosition> {
match self {
Self::Shape { surface_id, id }
| Self::Connector { surface_id, id }
| Self::SurfaceText { surface_id, id } => page
.encode_surface_text_relative_position(surface_id, id, "text", offset as u64)
.ok()
.flatten(),
Self::FrameTitle { id } => page
.encode_block_title_relative_position(id, offset as u64)
.ok()
.flatten(),
}
}
pub(super) fn resolve_pos(
&self,
page: &PageDocSession,
pos: &RelativePosition,
) -> Option<usize> {
let off = match self {
Self::Shape { surface_id, id }
| Self::Connector { surface_id, id }
| Self::SurfaceText { surface_id, id } => page
.resolve_surface_text_relative_position(surface_id, id, "text", pos)
.ok()
.flatten()?,
Self::FrameTitle { id } => page
.resolve_block_title_relative_position(id, pos)
.ok()
.flatten()?,
};
Some(off as usize)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LabelPreedit {
pub replacement: Range<usize>,
pub text: String,
pub selected: Range<usize>,
}
/// Inline UTF-16 + IME editor for Shape, Connector, SurfaceText, and Frame title labels.
#[derive(Clone, Debug)]
pub struct EdgelessLabelEditor {
pub(super) target: LabelTarget,
pub text: String,
pub original_text: String,
pub selection: Range<usize>,
pub reversed: bool,
pub(super) preedit: Option<LabelPreedit>,
pub world_rect: WorldRect,
pub rotate_deg: f32,
pub multiline: bool,
pub created_new_text: bool,
pub dirty: bool,
pub(super) anchors: Option<(RelativePosition, RelativePosition)>,
pub(super) preedit_anchors: Option<(RelativePosition, RelativePosition)>,
}
pub(super) fn utf16_len(s: &str) -> usize {
s.encode_utf16().count()
}
pub(super) fn utf16_to_byte(s: &str, target: usize) -> usize {
let mut u16_pos = 0;
for (byte_idx, ch) in s.char_indices() {
if u16_pos >= target {
return byte_idx;
}
u16_pos += ch.len_utf16();
}
s.len()
}
impl EdgelessLabelEditor {
pub fn new(
target: LabelTarget,
initial: String,
world_rect: WorldRect,
rotate_deg: f32,
multiline: bool,
) -> Self {
let len = utf16_len(&initial);
Self {
target,
original_text: initial.clone(),
text: initial,
selection: len..len,
reversed: false,
preedit: None,
world_rect,
rotate_deg,
multiline,
created_new_text: false,
dirty: false,
anchors: None,
preedit_anchors: None,
}
}
pub fn composing(&self) -> bool {
self.preedit.is_some()
}
pub fn display_text(&self) -> String {
let Some(pre) = &self.preedit else {
return self.text.clone();
};
let start = utf16_to_byte(&self.text, pre.replacement.start);
let end = utf16_to_byte(&self.text, pre.replacement.end);
let mut out = String::with_capacity(self.text.len() + pre.text.len());
out.push_str(&self.text[..start]);
out.push_str(&pre.text);
out.push_str(&self.text[end..]);
out
}
pub fn shown_selection(&self) -> (Range<usize>, bool) {
if let Some(pre) = &self.preedit {
let base = pre.replacement.start;
return (base + pre.selected.start..base + pre.selected.end, false);
}
(self.selection.clone(), self.reversed)
}
pub fn marked_range(&self) -> Option<Range<usize>> {
let pre = self.preedit.as_ref()?;
let start = pre.replacement.start;
Some(start..start + utf16_len(&pre.text))
}
pub fn text_for_range(&self, range: Range<usize>) -> (String, Range<usize>) {
let text = self.display_text();
let start = utf16_to_byte(&text, range.start);
let end = utf16_to_byte(&text, range.end).max(start);
let covered = utf16_len(&text[..start])..utf16_len(&text[..end]);
(text[start..end].to_string(), covered)
}
fn clamped(&self, range: Range<usize>) -> Range<usize> {
let at = |offset: usize| utf16_len(&self.text[..utf16_to_byte(&self.text, offset)]);
let a = at(range.start.min(range.end));
let b = at(range.start.max(range.end));
a..b
}
pub fn cancel_preedit(&mut self) {
self.preedit = None;
self.preedit_anchors = None;
}
pub fn replace(&mut self, range: Option<Range<usize>>, text: &str) -> Option<LabelSplice> {
if self.preedit.is_some() && text.is_empty() {
self.cancel_preedit();
return None;
}
self.preedit_anchors = None;
let target = match self.preedit.take() {
Some(pre) => pre.replacement,
None => range.map_or(self.selection.clone(), |r| self.clamped(r)),
};
let cleaned: String = if self.multiline {
text.chars()
.filter(|ch| !ch.is_control() || *ch == '\n')
.collect()
} else {
text.chars().filter(|ch| !ch.is_control()).collect()
};
let start = utf16_to_byte(&self.text, target.start);
let end = utf16_to_byte(&self.text, target.end);
self.text.replace_range(start..end, &cleaned);
let caret = target.start + utf16_len(&cleaned);
self.selection = caret..caret;
self.reversed = false;
let del_len = target.end.saturating_sub(target.start);
if del_len == 0 && cleaned.is_empty() {
None
} else {
self.dirty = true;
Some((target.start, del_len, cleaned))
}
}
pub fn mark(
&mut self,
range: Option<Range<usize>>,
text: &str,
selected: Option<Range<usize>>,
) {
if text.is_empty() {
self.preedit = None;
self.preedit_anchors = None;
return;
}
let replacement = match &self.preedit {
Some(pre) => pre.replacement.clone(),
None => range.map_or(self.selection.clone(), |r| self.clamped(r)),
};
let cleaned: String = text.chars().filter(|ch| !ch.is_control()).collect();
let len = utf16_len(&cleaned);
let selected = selected.unwrap_or(len..len);
self.preedit = Some(LabelPreedit {
replacement,
text: cleaned,
selected: selected.start.min(len)..selected.end.min(len),
});
}
pub fn unmark(&mut self) -> Option<LabelSplice> {
if let Some(pre) = &self.preedit {
let text = pre.text.clone();
self.replace(None, &text)
} else {
None
}
}
pub fn select(&mut self, range: Range<usize>) {
self.preedit = None;
self.preedit_anchors = None;
self.selection = self.clamped(range);
self.reversed = false;
}
pub fn delete_backward(&mut self) -> Option<LabelSplice> {
self.preedit = None;
self.preedit_anchors = None;
if self.selection.start != self.selection.end {
return self.replace(None, "");
}
let pos = self.selection.start;
if pos == 0 {
return None;
}
let byte_end = utf16_to_byte(&self.text, pos);
let prev_char = self.text[..byte_end].chars().next_back();
let byte_start = prev_char.map_or(0, |c| byte_end - c.len_utf8());
let new_pos = utf16_len(&self.text[..byte_start]);
let del_len = pos.saturating_sub(new_pos);
self.text.replace_range(byte_start..byte_end, "");
self.selection = new_pos..new_pos;
self.reversed = false;
self.dirty = true;
Some((new_pos, del_len, String::new()))
}
pub fn delete_forward(&mut self) -> Option<LabelSplice> {
self.preedit = None;
self.preedit_anchors = None;
if self.selection.start != self.selection.end {
return self.replace(None, "");
}
let pos = self.selection.start;
let byte_start = utf16_to_byte(&self.text, pos);
if byte_start >= self.text.len() {
return None;
}
let next_char = self.text[byte_start..].chars().next();
let byte_end = next_char.map_or(self.text.len(), |c| byte_start + c.len_utf8());
let del_len = next_char.map_or(0, char::len_utf16);
self.text.replace_range(byte_start..byte_end, "");
self.dirty = true;
Some((pos, del_len, String::new()))
}
pub fn move_caret(&mut self, left: bool, extend: bool) {
self.preedit = None;
self.preedit_anchors = None;
let focus = if self.reversed {
self.selection.start
} else {
self.selection.end
};
let anchor = if self.reversed {
self.selection.end
} else {
self.selection.start
};
let next = if left {
let b = utf16_to_byte(&self.text, focus);
let nb = self.text[..b]
.chars()
.next_back()
.map_or(0, |c| b - c.len_utf8());
utf16_len(&self.text[..nb])
} else {
let b = utf16_to_byte(&self.text, focus);
let nb = self.text[b..]
.chars()
.next()
.map_or(self.text.len(), |c| b + c.len_utf8());
utf16_len(&self.text[..nb])
};
if extend {
self.selection = anchor.min(next)..anchor.max(next);
self.reversed = next < anchor;
} else {
self.selection = next..next;
self.reversed = false;
}
}
pub fn select_all(&mut self) {
self.preedit = None;
self.preedit_anchors = None;
let len = utf16_len(&self.text);
self.selection = 0..len;
self.reversed = false;
}
pub fn selected_text(&self) -> &str {
let s = utf16_to_byte(&self.text, self.selection.start);
let e = utf16_to_byte(&self.text, self.selection.end);
&self.text[s..e]
}
}
/// Active inline editing session on the Edgeless canvas.
#[derive(Clone, Debug)]
pub enum EdgelessInlineEdit {
/// Live rich-text `EditorSession` editing inside a Note or EdgelessText block.
SpatialBlock { block_id: String, is_note: bool },
/// Inline UTF-16 + IME editing on a Shape, Connector, SurfaceText, or Frame title.
Label(EdgelessLabelEditor),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn label_editor_ime_preedit_cancel_and_commit() {
let mut ed = EdgelessLabelEditor::new(
LabelTarget::Shape {
surface_id: "surf".into(),
id: "s1".into(),
},
"hello".into(),
WorldRect::new(0.0, 0.0, 160.0, 80.0),
0.0,
true,
);
ed.select(1..4);
assert_eq!(ed.selected_text(), "ell");
ed.mark(None, "nihao", None);
assert!(ed.composing());
assert_eq!(ed.display_text(), "hnihaoo");
// Empty replace during preedit cancels and restores original selection.
ed.replace(None, "");
assert!(!ed.composing());
assert_eq!(ed.display_text(), "hello");
assert_eq!(ed.selected_text(), "ell");
// Commit replaces selection.
ed.mark(None, "你好", None);
ed.unmark();
assert!(!ed.composing());
assert_eq!(ed.display_text(), "h你好o");
}
}
@@ -0,0 +1,43 @@
//! Edgeless spatial whiteboard subsystem: camera, paint ordering, canvas rendering,
//! interactive authoring toolbar, hit-testing, overlays, inline IME editing, and gestures.
mod camera;
mod canvas;
mod canvas_paint;
mod commands;
mod commit;
mod gestures;
mod hit_test;
mod inline_edit;
mod label_editor;
mod order;
mod overlay;
mod scene;
mod toolbar;
pub use camera::{EdgelessCamera, WorldRect, bg_grid_gap, parse_xywh};
pub use canvas::{
EDGELESS_VIEWPORT_ID, EdgelessCanvasState, EdgelessRenderInput, NOTE_CARD_PADDING,
resolve_edgeless_color,
};
pub use canvas_paint::build_edgeless_layer;
pub use hit_test::EdgelessAuthoringState;
pub use label_editor::{EdgelessInlineEdit, EdgelessLabelEditor};
pub use toolbar::{EdgelessTool, build_edgeless_toolbar, build_zoom_controls};
use canvas::{
CachedNoteFlow, CachedSurfaces, FRAME_RADIUS, FRAME_TITLE_GAP, FRAME_TITLE_HEIGHT,
PaintEdgelessText, PaintFrame, PaintNote, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS,
ZOOM_BTN_HEIGHT, ZOOM_BTN_RADIUS, note_border_radius, note_border_style, note_collapse,
note_scale, note_shadow_type, prop_bool, prop_f32, rotated_bounds, spatial_blocks,
world_bounds, world_rect,
};
use commands::{collect_frame_children, find_block, find_surface_element, max_spatial_index};
use hit_test::{
DragItemInitial, EdgelessGesture, HandleKind, SpatialItemInfo, SpatialItemKind,
normalized_rect, point_in_rotated_rect, resized_rect, rotate_point_around,
};
use label_editor::{LabelSplice, LabelTarget, utf16_len, utf16_to_byte};
use order::{Layers, PaintItem};
use overlay::{build_edgeless_authoring_overlay, layout_label_editor_paragraph};
use scene::{PreparedEdgelessScene, prepare_edgeless_scene};
@@ -33,10 +33,8 @@ impl<'a> Layers<'a> {
.get("prop:childElementIds")
.and_then(|v| v.as_object())
{
for (child, present) in children {
if present.as_bool() == Some(true) {
layers.set_parent(child, &node.id);
}
for child in children.keys() {
layers.set_parent(child, &node.id);
}
}
}
@@ -75,7 +73,6 @@ impl<'a> Layers<'a> {
items: impl IntoIterator<Item = (&'b str, PaintItem)>,
) -> Vec<PaintItem> {
struct Entry<'a> {
id: &'a str,
item: PaintItem,
path: Vec<&'a str>,
}
@@ -89,7 +86,7 @@ impl<'a> Layers<'a> {
node = parent;
}
path.reverse();
Entry { id, item, path }
Entry { item, path }
})
.partition(|e| matches!(e.item, PaintItem::Surface(..)));
let compare = |a: &Entry<'_>, b: &Entry<'_>| {
@@ -106,7 +103,7 @@ impl<'a> Layers<'a> {
a.path.len().cmp(&b.path.len())
};
for stream in [&mut canvas, &mut blocks] {
stream.sort_by(|a, b| compare(a, b).then_with(|| a.id.cmp(b.id)));
stream.sort_by(|a, b| compare(a, b));
}
let mut output = Vec::with_capacity(canvas.len() + blocks.len());
let (mut blocks, mut canvas) =
@@ -158,7 +155,7 @@ mod tests {
"prop:childElementIds",
SessionValue::Map(vec![
("member".into(), SessionValue::Any(Any::True)),
("unrelated".into(), SessionValue::Any(Any::False)),
("false_member".into(), SessionValue::Any(Any::False)),
]),
),
] {
@@ -166,17 +163,26 @@ mod tests {
}
let snapshot = page.read_page_snapshot().unwrap();
let mut layers = Layers::from_root(snapshot.root.as_ref().unwrap());
layers
.indices
.extend([("member", "a0"), ("earlier", "a1"), ("unrelated", "a5")]);
let (frame, member, earlier, unrelated) = (
layers.indices.extend([
("member", "a0"),
("false_member", "a0"),
("earlier", "a1"),
("unrelated", "a5"),
]);
let (frame, member, false_member, earlier, unrelated) = (
PaintItem::Frame(0),
PaintItem::Surface(0, 0),
PaintItem::Surface(0, 1),
PaintItem::Surface(0, 2),
PaintItem::Surface(0, 3),
);
let order = layers.merge([("earlier", earlier), ("frame", frame), ("member", member)]);
assert_eq!(order, [earlier, frame, member]);
let order = layers.merge([
("earlier", earlier),
("frame", frame),
("member", member),
("false_member", false_member),
]);
assert_eq!(order, [earlier, frame, member, false_member]);
let order = layers.merge([
("earlier", earlier),
("frame", frame),
@@ -184,4 +190,13 @@ mod tests {
]);
assert_eq!(order, [earlier, unrelated, frame]);
}
#[test]
fn equal_indices_preserve_source_order_within_each_stream() {
let mut layers = Layers::default();
layers.indices.extend([("z", "a1"), ("a", "a1")]);
let (z, a) = (PaintItem::Surface(0, 0), PaintItem::Surface(0, 1));
assert_eq!(layers.merge([("z", z), ("a", a)]), [z, a]);
assert_eq!(layers.merge([("a", a), ("z", z)]), [a, z]);
}
}
@@ -0,0 +1,558 @@
//! Screen-space selection frame, handles, marquee, live creation previews, and inline label editor overlay.
use std::collections::BTreeMap;
use ui::{
AnyElement, BorderStyle, Bounds, Corners, Edges, Hsla, PathBuilder, Pixels, Point, canvas, div,
point, prelude::*, px, size,
};
use y_octo::{Any, TextDeltaOp, TextInsert};
use crate::{
rich_text::{CaretPosition, RichParagraph, RichParagraphStyle, WrapAffinity},
theme::{FONT_SANS, Palette, PlaygroundTheme},
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessGesture,
EdgelessLabelEditor, HandleKind, normalized_rect, rotate_point_around, utf16_to_byte,
};
/// Screen-space selection frame, 8 resize handles, rotation handle, Edgeless `2×3` `gfx` drag handle,
/// marquee box, live creation previews, and inline label editor overlay.
pub fn build_edgeless_authoring_overlay(
authoring: &EdgelessAuthoringState,
camera: EdgelessCamera,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
) -> Vec<AnyElement> {
let mut elements = Vec::new();
let vp_origin = point(px(0.0), px(0.0));
let brand = palette.brand;
let white = Hsla::white();
// 1. Selection box + 8 resize handles + rotation handle + Edgeless gfx 2x3 drag handle.
if let Some(sel_box) = authoring.selection_world_box() {
let tl = camera.world_to_screen(point(px(sel_box.x), px(sel_box.y)), vp_origin);
let br =
camera.world_to_screen(point(px(sel_box.right()), px(sel_box.bottom())), vp_origin);
let x0 = f32::from(tl.x);
let y0 = f32::from(tl.y);
let x1 = f32::from(br.x);
let y1 = f32::from(br.y);
let w = (x1 - x0).max(2.0);
let h = (y1 - y0).max(2.0);
let mx = (x0 + x1) * 0.5;
let my = (y0 + y1) * 0.5;
let live_overrides = authoring.live_overrides();
let single_rotatable = authoring
.single_selected()
.filter(|s| s.kind.is_rotatable());
let rot_deg = single_rotatable
.map(|s| {
live_overrides
.get(&s.id)
.and_then(|o| o.rotate_deg)
.unwrap_or(s.rotate_deg)
})
.filter(|r| r.abs() > 1e-3)
.unwrap_or(0.0);
let visible_box =
x0 >= 0.0 && y0 >= 0.0 && x0 + w <= viewport_width && y0 + h <= viewport_height;
if rot_deg.abs() > 1e-3 {
let c0 = rotate_point_around(x0, y0, mx, my, rot_deg);
let c1 = rotate_point_around(x1, y0, mx, my, rot_deg);
let c2 = rotate_point_around(x1, y1, mx, my, rot_deg);
let c3 = rotate_point_around(x0, y1, mx, my, rot_deg);
elements.push(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(2.0));
pb.move_to(point(px(ox + c0.0), px(oy + c0.1)));
pb.line_to(point(px(ox + c1.0), px(oy + c1.1)));
pb.line_to(point(px(ox + c2.0), px(oy + c2.1)));
pb.line_to(point(px(ox + c3.0), px(oy + c3.1)));
pb.line_to(point(px(ox + c0.0), px(oy + c0.1)));
if let Ok(path) = pb.build() {
window.paint_path(path, brand);
}
},
)
.absolute()
.inset_0()
.into_any_element(),
);
if visible_box {
elements.push(
div()
.absolute()
.left(px(x0))
.top(px(y0))
.w(px(w))
.h(px(h))
.snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID))
.into_any_element(),
);
}
} else {
let mut box_el = div()
.absolute()
.left(px(x0))
.top(px(y0))
.w(px(w))
.h(px(h))
.border_color(brand)
.border_2();
if visible_box {
box_el = box_el.snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID));
}
elements.push(box_el.into_any_element());
}
if authoring.inline_edit.is_none() {
if authoring.selection_has_non_connector() {
let handle_coords = [
(HandleKind::NW, x0, y0),
(HandleKind::N, mx, y0),
(HandleKind::NE, x1, y0),
(HandleKind::E, x1, my),
(HandleKind::SE, x1, y1),
(HandleKind::S, mx, y1),
(HandleKind::SW, x0, y1),
(HandleKind::W, x0, my),
];
for (kind, hx, hy) in handle_coords {
let (hx, hy) = rotate_point_around(hx, hy, mx, my, rot_deg);
let lx = (hx - 4.0).round();
let ty = (hy - 4.0).round();
let mut h_el = div()
.absolute()
.left(px(lx))
.top(px(ty))
.w(px(8.0))
.h(px(8.0))
.rounded(px(2.0))
.bg(white)
.border_1()
.border_color(brand);
if lx >= 0.0
&& ty >= 0.0
&& lx + 8.0 <= viewport_width
&& ty + 8.0 <= viewport_height
{
h_el = h_el.snapshot(kind.snapshot_id(), Some(EDGELESS_VIEWPORT_ID));
}
elements.push(h_el.into_any_element());
}
}
// Top rotation handle for rotatable items (Shape / EdgelessText).
if single_rotatable.is_some() {
let stem_a = rotate_point_around(mx, y0, mx, my, rot_deg);
let stem_b = rotate_point_around(mx, y0 - 20.0, mx, my, rot_deg);
let knob_c = rotate_point_around(mx, y0 - 24.0, mx, my, rot_deg);
let rx = (knob_c.0 - 5.0).round();
let ry = (knob_c.1 - 5.0).round();
// Connector stem from top-center to rotate knob.
elements.push(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(1.5));
pb.move_to(point(px(ox + stem_a.0), px(oy + stem_a.1)));
pb.line_to(point(px(ox + stem_b.0), px(oy + stem_b.1)));
if let Ok(path) = pb.build() {
window.paint_path(path, brand);
}
},
)
.absolute()
.inset_0()
.into_any_element(),
);
let mut r_el = div()
.absolute()
.left(px(rx))
.top(px(ry))
.w(px(10.0))
.h(px(10.0))
.rounded(px(5.0))
.bg(white)
.border_1()
.border_color(brand);
if rx >= 0.0
&& ry >= 0.0
&& rx + 10.0 <= viewport_width
&& ry + 10.0 <= viewport_height
{
r_el =
r_el.snapshot(HandleKind::Rotate.snapshot_id(), Some(EDGELESS_VIEWPORT_ID));
}
elements.push(r_el.into_any_element());
}
}
// 2x3 6-dot 14px Edgeless gfx drag handle for Note / Frame / EdgelessText.
if let Some(single) = authoring.single_selected()
&& single.kind.has_gfx_drag_handle()
{
let hx = (x0 - 20.0)
.clamp(4.0, (viewport_width - 18.0).max(4.0))
.round();
let hy = y0.clamp(4.0, (viewport_height - 28.0).max(4.0)).round();
let dots_color = theme
.css_var("--affine-v2-icon-secondary")
.unwrap_or(palette.icon);
let pill_bg = theme
.css_var("--affine-v2-layer-background-hoverOverlay")
.unwrap_or(palette.hover);
let mut dh = div()
.absolute()
.left(px(hx))
.top(px(hy))
.w(px(14.0))
.h(px(24.0))
.rounded(px(4.0))
.bg(pill_bg)
.flex()
.items_center()
.justify_center()
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
for row in 0..3 {
for col in 0..2 {
let dot = Bounds::new(
point(
bounds.origin.x + px(col as f32 * 5.0),
bounds.origin.y + px(row as f32 * 5.0),
),
size(px(3.0), px(3.0)),
);
window.paint_quad(
ui::fill(dot, dots_color).corner_radii(px(1.5)),
);
}
}
},
)
.w(px(8.0))
.h(px(13.0)),
);
if hx >= 0.0 && hy >= 0.0 && hx + 14.0 <= viewport_width && hy + 24.0 <= viewport_height
{
dh = dh.snapshot(
HandleKind::DragHandle.snapshot_id(),
Some(EDGELESS_VIEWPORT_ID),
);
}
elements.push(dh.into_any_element());
}
}
// 2. Active gesture previews (marquee, shape/frame/note creation, connector routing, freehand stroke).
match &authoring.gesture {
Some(EdgelessGesture::Marquee {
start_world,
current_world,
}) => {
let r = normalized_rect(*start_world, *current_world);
let tl = camera.world_to_screen(point(px(r.x), px(r.y)), vp_origin);
let br = camera.world_to_screen(point(px(r.right()), px(r.bottom())), vp_origin);
let x = f32::from(tl.x).max(0.0);
let y = f32::from(tl.y).max(0.0);
let w = (f32::from(br.x).min(viewport_width) - x).max(1.0);
let h = (f32::from(br.y).min(viewport_height) - y).max(1.0);
let mut mq = div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.bg(brand.opacity(0.12))
.border_1()
.border_color(brand);
if x >= 0.0 && y >= 0.0 && x + w <= viewport_width && y + h <= viewport_height {
mq = mq.snapshot("edgeless.marquee", Some(EDGELESS_VIEWPORT_ID));
}
elements.push(mq.into_any_element());
}
Some(EdgelessGesture::CreateShape {
start_world,
current_world,
..
})
| Some(EdgelessGesture::CreateFrame {
start_world,
current_world,
})
| Some(EdgelessGesture::CreateNote {
start_world,
current_world,
}) => {
let r = normalized_rect(*start_world, *current_world);
let tl = camera.world_to_screen(point(px(r.x), px(r.y)), vp_origin);
let br = camera.world_to_screen(point(px(r.right()), px(r.bottom())), vp_origin);
let x = f32::from(tl.x);
let y = f32::from(tl.y);
let w = (f32::from(br.x) - x).max(2.0);
let h = (f32::from(br.y) - y).max(2.0);
elements.push(
div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.bg(brand.opacity(0.08))
.border_1()
.border_color(brand)
.rounded(px(4.0))
.into_any_element(),
);
}
Some(EdgelessGesture::CreateConnector {
source_world,
current_world,
target_world,
..
}) => {
let src = *source_world;
let dst = target_world.unwrap_or(*current_world);
let p0 = camera.world_to_screen(point(px(src.0), px(src.1)), vp_origin);
let p1 = camera.world_to_screen(point(px(dst.0), px(dst.1)), vp_origin);
let mid_x = (f32::from(p0.x) + f32::from(p1.x)) * 0.5;
let snapped_target = target_world.is_some();
elements.push(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let a = point(px(ox + f32::from(p0.x)), px(oy + f32::from(p0.y)));
let m1 = point(px(ox + mid_x), px(oy + f32::from(p0.y)));
let m2 = point(px(ox + mid_x), px(oy + f32::from(p1.y)));
let b = point(px(ox + f32::from(p1.x)), px(oy + f32::from(p1.y)));
let mut pb = PathBuilder::stroke(px(2.0));
pb.move_to(a);
pb.line_to(m1);
pb.line_to(m2);
pb.line_to(b);
if let Ok(path) = pb.build() {
window.paint_path(path, brand);
}
// Live port rings at source and snapped target.
for (pt, highlight) in [(a, true), (b, snapped_target)] {
if highlight {
let ring = Bounds::new(
point(pt.x - px(5.0), pt.y - px(5.0)),
size(px(10.0), px(10.0)),
);
window.paint_quad(ui::quad(
ring,
Corners::all(px(5.0)),
white,
Edges::all(px(2.0)),
brand,
BorderStyle::Solid,
));
}
}
},
)
.absolute()
.inset_0()
.into_any_element(),
);
}
Some(EdgelessGesture::DrawStroke {
highlighter,
points_world,
}) if points_world.len() >= 2 => {
let pts: Vec<Point<Pixels>> = points_world
.iter()
.map(|&(wx, wy)| {
camera.world_to_screen(point(px(wx as f32), px(wy as f32)), vp_origin)
})
.collect();
let width = if *highlighter {
(22.0 * camera.zoom).max(4.0)
} else {
(4.0 * camera.zoom).max(2.0)
};
let color = if *highlighter {
ui::rgba(0x84cfff70).into()
} else {
palette.text_primary
};
elements.push(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(width));
pb.move_to(point(
px(ox + f32::from(pts[0].x)),
px(oy + f32::from(pts[0].y)),
));
for p in &pts[1..] {
pb.line_to(point(px(ox + f32::from(p.x)), px(oy + f32::from(p.y))));
}
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
},
)
.absolute()
.inset_0()
.into_any_element(),
);
}
_ => {}
}
// 3. Inline label editor overlay (Shape / Connector / SurfaceText / Frame title).
if let Some(editor) = authoring.label_editor() {
let tl = camera.world_to_screen(
point(px(editor.world_rect.x), px(editor.world_rect.y)),
vp_origin,
);
let br = camera.world_to_screen(
point(
px(editor.world_rect.right()),
px(editor.world_rect.bottom()),
),
vp_origin,
);
let w = (f32::from(br.x) - f32::from(tl.x))
.max(120.0)
.min(viewport_width - 16.0);
let h = (f32::from(br.y) - f32::from(tl.y))
.max(32.0)
.min(viewport_height - 16.0);
let x = f32::from(tl.x).clamp(8.0, (viewport_width - w - 8.0).max(8.0));
let y = f32::from(tl.y).clamp(8.0, (viewport_height - h - 8.0).max(8.0));
let display = editor.display_text();
let (sel, reversed) = editor.shown_selection();
let selection_color = palette.brand.opacity(0.22);
let caret_color = palette.brand;
let bg = palette.panel;
let border = palette.brand;
let editor_clone = editor.clone();
let el = div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.rounded(px(4.0))
.bg(bg)
.border_2()
.border_color(border)
.snapshot("edgeless.inline_edit", Some(EDGELESS_VIEWPORT_ID))
.snapshot_text(display)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
let pad = 6.0;
if let Some(laid_out) = layout_label_editor_paragraph(
&editor_clone,
f32::from(bounds.size.width),
theme,
window,
) {
let mut selections = Vec::new();
if sel.start != sel.end {
selections
.push((sel.start as u64..sel.end as u64, selection_color));
}
let focus = if reversed { sel.start } else { sel.end };
let carets = [(
CaretPosition {
utf16_offset: focus as u64,
affinity: WrapAffinity::Upstream,
},
caret_color,
)];
laid_out.paint_at(
point(bounds.origin.x + px(pad), bounds.origin.y + px(pad)),
&selections,
&carets,
None,
window,
cx,
);
}
},
)
.size_full(),
);
elements.push(el.into_any_element());
}
elements
}
/// Lay out an open [`EdgelessLabelEditor`]'s display text (including IME underline marks)
/// for both overlay painting and inside-label pointer hit-testing.
pub(super) fn layout_label_editor_paragraph(
editor: &EdgelessLabelEditor,
width: f32,
theme: PlaygroundTheme,
window: &ui::Window,
) -> Option<crate::rich_text::LaidOutRichParagraph> {
let pad = 6.0;
let wrap_w = (width - 2.0 * pad).max(20.0);
let display = editor.display_text();
let marked = editor.marked_range();
let mut delta = Vec::new();
if let Some(m) = &marked {
let b0 = utf16_to_byte(&display, m.start);
let b1 = utf16_to_byte(&display, m.end);
if b0 > 0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[..b0].to_string()),
format: None,
});
}
if b1 > b0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[b0..b1].to_string()),
format: Some(BTreeMap::from([("underline".to_string(), Any::True)])),
});
}
if b1 < display.len() {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[b1..].to_string()),
format: None,
});
}
} else if !display.is_empty() {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display),
format: None,
});
}
let style = RichParagraphStyle {
font_family: FONT_SANS.into(),
font_size: 14.0,
line_height: 20.0,
text_color: theme.palette().text_primary,
..RichParagraphStyle::from_theme(theme.mode())
};
let para = RichParagraph::from_delta(delta).ok()?;
Some(para.layout(window.text_system(), &style, wrap_w))
}
@@ -0,0 +1,564 @@
//! Single-pass Edgeless scene preparation: cached note/text/surface layout and paint-order hit-test metadata.
use std::rc::Rc;
use blocksuite_playground_doc::read::{BlockContent, NoteDisplayMode};
use ui::Window;
use crate::{
block_flow::{
BlockFlow, FlowInput, FlowLayout, InlineAlign, InlineBaseline, InlineStyle, layout_inline,
},
surface::{SurfaceLayout, layout_surface},
theme::FONT_SANS,
};
use super::{
CachedNoteFlow, CachedSurfaces, EdgelessCanvasState, EdgelessRenderInput, FRAME_TITLE_GAP,
FRAME_TITLE_HEIGHT, Layers, NOTE_CARD_PADDING, PaintEdgelessText, PaintFrame, PaintItem,
PaintNote, SpatialItemInfo, SpatialItemKind, WorldRect, collect_frame_children,
note_border_radius, note_border_style, note_collapse, note_scale, note_shadow_type, parse_xywh,
prop_bool, prop_f32, resolve_edgeless_color, rotated_bounds, spatial_blocks, world_bounds,
world_rect,
};
pub(super) struct PreparedEdgelessScene {
pub(super) frames: Vec<PaintFrame>,
pub(super) notes: Vec<PaintNote>,
pub(super) texts: Vec<PaintEdgelessText>,
pub(super) surfaces: Rc<[SurfaceLayout]>,
pub(super) order: Rc<[PaintItem]>,
}
pub(super) fn prepare_edgeless_scene(
state: &mut EdgelessCanvasState,
input: &EdgelessRenderInput<'_>,
window: &Window,
) -> PreparedEdgelessScene {
state.last_frame_relayouts = 0;
let live_overrides = state.authoring.live_overrides();
let mut frames = Vec::new();
let mut notes = Vec::new();
let mut texts = Vec::new();
// Preserve exact `sys:children` order across Frames, Notes, and EdgelessTexts when merging
// equal-index items into `Layers::merge`.
let mut spatial_order: Vec<(String, PaintItem)> = Vec::new();
if let Some(root) = &input.snapshot.root {
let mut active_notes = Vec::new();
let mut active_texts = Vec::new();
for child in spatial_blocks(root) {
match &child.content {
BlockContent::Frame { title, xywh } => {
if let Some(mut rect) = parse_xywh(xywh) {
if let Some(ov) = live_overrides.get(&child.id) {
rect = ov.rect;
}
let fill = child
.props
.get("prop:background")
.and_then(|v| resolve_edgeless_color(v, input.theme))
.filter(|c| !c.is_transparent());
let title_text = if title.plain.is_empty() {
"Frame"
} else {
title.plain.as_str()
};
let title_style =
InlineStyle::new(FONT_SANS, 12.0, 500.0, input.palette.text_secondary);
let title_inline = Rc::new(layout_inline(
title_text,
&title_style,
rect.w.max(80.0),
FRAME_TITLE_HEIGHT,
InlineBaseline::Of(&title_style),
InlineAlign::Left,
window,
));
let pill_w = (title_inline.content_width() + 16.0).min(rect.w.max(80.0));
let title_pill_rect = WorldRect::new(
rect.x,
rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP,
pill_w,
FRAME_TITLE_HEIGHT,
);
let index = child
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let frame_children = collect_frame_children(child);
let idx = frames.len();
frames.push(PaintFrame {
id: child.id.clone(),
title: title_text.to_string(),
index,
frame_children,
rect,
title_inline,
title_pill_rect,
fill,
});
spatial_order.push((child.id.clone(), PaintItem::Frame(idx)));
}
}
BlockContent::Note {
display_mode,
xywh,
background,
hidden,
} if !hidden && *display_mode != NoteDisplayMode::DocOnly => {
let mut rect =
parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0));
if let Some(ov) = live_overrides.get(&child.id) {
rect = ov.rect;
}
let scale = note_scale(child);
let collapse = note_collapse(child);
let border = note_border_style(child);
let border_radius = note_border_radius(child);
let shadows = input.theme.shadows(note_shadow_type(child));
let inner_width = (rect.w / scale - 2.0 * NOTE_CARD_PADDING).max(120.0);
let key = (
input.doc_rev,
inner_width.to_bits(),
scale.to_bits(),
input.theme,
input.env_rev,
input.preedit_nonce,
);
let layout = match state.note_flows.get_mut(&child.id) {
Some(cached) if cached.key == key => cached.layout.clone(),
_ => {
let flow_input = FlowInput {
snapshot: input.snapshot,
width: inner_width,
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
env_rev: input.env_rev,
};
let entry =
state.note_flows.entry(child.id.clone()).or_insert_with(|| {
CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0, 0),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: inner_width,
height: 0.0,
stats: Default::default(),
}),
}
});
let laid_out =
entry
.flow
.layout_nodes(&child.children, &flow_input, window);
state.last_frame_relayouts += laid_out.stats.laid_out as u64;
let rc = Rc::new(laid_out);
entry.key = key;
entry.layout = rc.clone();
rc
}
};
if !collapse {
rect.h = rect
.h
.max((layout.height + 2.0 * NOTE_CARD_PADDING) * scale);
}
let fill = resolve_edgeless_color(background, input.theme)
.filter(|c| !c.is_transparent())
.unwrap_or(input.palette.background);
active_notes.push(child.id.clone());
let index = child
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let idx = notes.len();
notes.push(PaintNote {
id: child.id.clone(),
index,
rect,
scale,
border,
border_radius,
shadows,
fill,
layout,
});
spatial_order.push((child.id.clone(), PaintItem::Note(idx)));
}
BlockContent::EdgelessText { xywh } => {
if let Some(mut rect) = parse_xywh(xywh) {
let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0);
let mut rotate_deg = prop_f32(child, "prop:rotate", 0.0);
if let Some(ov) = live_overrides.get(&child.id) {
rect = ov.rect;
if let Some(r) = ov.rotate_deg {
rotate_deg = r;
}
}
let has_max_width = prop_bool(child, "prop:hasMaxWidth", true);
let text_width = if has_max_width {
(rect.w / scale).max(60.0)
} else {
(rect.w / scale).max(320.0)
};
let key = (
input.doc_rev,
text_width.to_bits(),
scale.to_bits(),
input.theme,
input.env_rev,
input.preedit_nonce,
);
let layout = match state.text_flows.get_mut(&child.id) {
Some(cached) if cached.key == key => cached.layout.clone(),
_ => {
let flow_input = FlowInput {
snapshot: input.snapshot,
width: text_width,
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
env_rev: input.env_rev,
};
let entry = state
.text_flows
.entry(child.id.clone())
.or_insert_with(|| CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0, 0),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: text_width,
height: 0.0,
stats: Default::default(),
}),
});
let laid_out =
entry
.flow
.layout_nodes(&child.children, &flow_input, window);
state.last_frame_relayouts += laid_out.stats.laid_out as u64;
let rc = Rc::new(laid_out);
entry.key = key;
entry.layout = rc.clone();
rc
}
};
rect.h = (layout.height * scale).max(rect.h);
active_texts.push(child.id.clone());
let index = child
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let idx = texts.len();
texts.push(PaintEdgelessText {
world_aabb: rotated_bounds(rect, rotate_deg),
id: child.id.clone(),
index,
rect,
scale,
rotate_deg,
layout,
});
spatial_order.push((child.id.clone(), PaintItem::Text(idx)));
}
}
_ => {}
}
}
if state.note_flows.len() > active_notes.len() {
state.note_flows.retain(|id, _| active_notes.contains(id));
}
if state.text_flows.len() > active_texts.len() {
state.text_flows.retain(|id, _| active_texts.contains(id));
}
}
let key = (input.doc_rev, input.theme, input.env_rev);
let has_live_overrides = !live_overrides.is_empty();
let (surfaces, order, painted_items) = match &state.surfaces {
Some(cached) if cached.key == key && !has_live_overrides => (
Rc::clone(&cached.layouts),
Rc::clone(&cached.order),
Rc::clone(&cached.painted_items),
),
_ => {
let external = frames
.iter()
.map(|f| (f.id.clone(), world_bounds(f.rect, 0.)))
.chain(
notes
.iter()
.map(|n| (n.id.clone(), world_bounds(n.rect, 0.))),
)
.chain(
texts
.iter()
.map(|t| (t.id.clone(), world_bounds(t.rect, t.rotate_deg))),
)
.collect();
let layouts: Rc<[SurfaceLayout]> = input
.snapshot
.root
.iter()
.flat_map(|root| &root.children)
.filter_map(|node| match &node.content {
BlockContent::Surface { elements, .. } => {
if has_live_overrides {
let mut patched = elements.clone();
for el in &mut patched {
if let Some(ov) = live_overrides.get(&el.id) {
if let Some(r) = ov.rotate_deg {
el.rotate = r as f64;
}
let xywh = [
ov.rect.x as f64,
ov.rect.y as f64,
ov.rect.w as f64,
ov.rect.h as f64,
];
match &mut el.kind {
blocksuite_playground_doc::read::SurfaceElementKind::Shape(s) => s.xywh = xywh,
blocksuite_playground_doc::read::SurfaceElementKind::Text(t) => t.xywh = xywh,
blocksuite_playground_doc::read::SurfaceElementKind::Brush(b)
| blocksuite_playground_doc::read::SurfaceElementKind::Highlighter(b) => b.xywh = xywh,
blocksuite_playground_doc::read::SurfaceElementKind::Connector(c) => {
let (dx, dy) = (ov.delta.0 as f64, ov.delta.1 as f64);
if c.source.id.is_none()
&& let Some([sx, sy]) = c.source.position
{
c.source.position = Some([sx + dx, sy + dy]);
}
if c.target.id.is_none()
&& let Some([tx, ty]) = c.target.position
{
c.target.position = Some([tx + dx, ty + dy]);
}
if let Some([lx, ly, lw, lh]) = c.label_xywh {
c.label_xywh = Some([lx + dx, ly + dy, lw, lh]);
}
}
_ => {}
}
}
}
Some(layout_surface(&patched, &external, input.theme, window))
} else {
Some(layout_surface(elements, &external, input.theme, window))
}
}
_ => None,
})
.collect();
let order: Rc<[PaintItem]> = input
.snapshot
.root
.as_ref()
.map(|root| {
let items = spatial_order
.iter()
.map(|(id, item)| (id.as_str(), *item))
.chain(layouts.iter().enumerate().flat_map(|(l, layout)| {
layout
.item_ids()
.enumerate()
.map(move |(i, id)| (id, PaintItem::Surface(l, i)))
}));
Layers::from_root(root).merge(items)
})
.unwrap_or_default()
.into();
// Build painted_items in exact paint order once per doc/theme/env revision (or during live drag).
let mut built_items = Vec::with_capacity(order.len());
let surface_nodes: Vec<(&str, &[blocksuite_playground_doc::read::SurfaceElement])> =
input
.snapshot
.root
.iter()
.flat_map(|root| &root.children)
.filter_map(|node| match &node.content {
BlockContent::Surface { elements, .. } => {
Some((node.id.as_str(), elements.as_slice()))
}
_ => None,
})
.collect();
for item in order.iter() {
match *item {
PaintItem::Frame(i) => {
let f = &frames[i];
built_items.push(SpatialItemInfo {
id: f.id.clone(),
kind: SpatialItemKind::Frame,
surface_id: None,
rect: f.rect,
rotate_deg: 0.0,
index: f.index.clone(),
scale: 1.0,
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: f.frame_children.clone(),
title_pill_rect: Some(f.title_pill_rect),
});
}
PaintItem::Note(i) => {
let n = &notes[i];
built_items.push(SpatialItemInfo {
id: n.id.clone(),
kind: SpatialItemKind::Note,
surface_id: None,
rect: n.rect,
rotate_deg: 0.0,
index: n.index.clone(),
scale: n.scale,
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: Vec::new(),
title_pill_rect: None,
});
}
PaintItem::Text(i) => {
let t = &texts[i];
built_items.push(SpatialItemInfo {
id: t.id.clone(),
kind: SpatialItemKind::EdgelessText,
surface_id: None,
rect: t.rect,
rotate_deg: t.rotate_deg,
index: t.index.clone(),
scale: t.scale,
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: Vec::new(),
title_pill_rect: None,
});
}
PaintItem::Surface(l, i) => {
let Some(id) = surfaces_item_id(&layouts, l, i) else {
continue;
};
let Some((surface_id, elements)) = surface_nodes.get(l) else {
continue;
};
let Some(el) = elements.iter().find(|e| e.id == id) else {
continue;
};
let bounds_rect = layouts[l]
.bounds()
.find(|(bid, _)| *bid == id)
.map(|(_, b)| world_rect(b))
.unwrap_or_default();
let (kind, rect) = match &el.kind {
blocksuite_playground_doc::read::SurfaceElementKind::Shape(s) => (
SpatialItemKind::Shape,
WorldRect::new(
s.xywh[0] as f32,
s.xywh[1] as f32,
s.xywh[2] as f32,
s.xywh[3] as f32,
),
),
blocksuite_playground_doc::read::SurfaceElementKind::Connector(_) => {
(SpatialItemKind::Connector, bounds_rect)
}
blocksuite_playground_doc::read::SurfaceElementKind::Brush(s) => (
SpatialItemKind::Brush,
WorldRect::new(
s.xywh[0] as f32,
s.xywh[1] as f32,
s.xywh[2] as f32,
s.xywh[3] as f32,
),
),
blocksuite_playground_doc::read::SurfaceElementKind::Highlighter(s) => {
(
SpatialItemKind::Highlighter,
WorldRect::new(
s.xywh[0] as f32,
s.xywh[1] as f32,
s.xywh[2] as f32,
s.xywh[3] as f32,
),
)
}
blocksuite_playground_doc::read::SurfaceElementKind::Text(s) => (
SpatialItemKind::SurfaceText,
WorldRect::new(
s.xywh[0] as f32,
s.xywh[1] as f32,
s.xywh[2] as f32,
s.xywh[3] as f32,
),
),
blocksuite_playground_doc::read::SurfaceElementKind::Group {
..
} => (SpatialItemKind::Group, bounds_rect),
blocksuite_playground_doc::read::SurfaceElementKind::Unknown {
..
} => {
continue;
}
};
let stroke_width = layouts[l].item_stroke_width(i);
let polyline = layouts[l].item_polyline(i).to_vec();
let final_rect = live_overrides.get(id).map_or(rect, |o| o.rect);
let final_rot = live_overrides
.get(id)
.and_then(|o| o.rotate_deg)
.unwrap_or(el.rotate as f32);
built_items.push(SpatialItemInfo {
id: el.id.clone(),
kind,
surface_id: Some((*surface_id).to_string()),
rect: final_rect,
rotate_deg: final_rot,
index: el.index.clone(),
scale: 1.0,
stroke_width,
polyline,
frame_children: Vec::new(),
title_pill_rect: None,
});
}
}
}
let painted_items: Rc<[SpatialItemInfo]> = built_items.into();
if !has_live_overrides {
state.surfaces = Some(CachedSurfaces {
key,
layouts: Rc::clone(&layouts),
order: Rc::clone(&order),
painted_items: Rc::clone(&painted_items),
});
}
(layouts, order, painted_items)
}
};
state.authoring.painted_items = painted_items;
PreparedEdgelessScene {
frames,
notes,
texts,
surfaces,
order,
}
}
fn surfaces_item_id(layouts: &[SurfaceLayout], l: usize, i: usize) -> Option<&str> {
layouts.get(l).and_then(|lay| lay.item_ids().nth(i))
}
@@ -0,0 +1,385 @@
//! Screen-space Edgeless authoring toolbar, shape picker popover, and zoom controls.
use blocksuite_playground_doc::read::ShapeType;
use ui::{AnyElement, Context, MouseButton, Window, canvas, div, prelude::*, px};
use crate::{
PlaygroundView,
theme::{IconPaint, Palette, PlaygroundTheme},
};
use super::{
EDGELESS_VIEWPORT_ID, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS, ZOOM_BTN_HEIGHT,
ZOOM_BTN_RADIUS,
};
/// Active tool selected in `chrome.edgeless_toolbar`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum EdgelessTool {
#[default]
Select,
Hand,
Note,
Shape(ShapeType),
Connector,
Brush,
Highlighter,
Text,
Frame,
}
impl EdgelessTool {
pub fn is_shape(self) -> bool {
matches!(self, Self::Shape(_))
}
}
/// Bottom screen-space creation toolbar (`chrome.edgeless_toolbar`).
/// Concentric radii: outer `8px`, padding `4px`, buttons `4px` (`28×28`, `2px` gap).
pub fn build_edgeless_toolbar(
tool: EdgelessTool,
viewport_width: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<PlaygroundView>,
) -> AnyElement {
const BAR_MARGIN: f32 = 12.0;
const BAR_PAD: f32 = 4.0;
const BAR_RADIUS: f32 = 8.0;
const BTN_SIZE: f32 = 28.0;
const BTN_RADIUS: f32 = 4.0;
const BTN_GAP: f32 = 2.0;
let shadows = theme.shadows("--affine-toolbar-shadow");
let tools: [(&'static str, &'static str, &'static str, EdgelessTool); 9] = [
(
"edgeless-tool-select",
"chrome.edgeless_toolbar.select",
"SelectIcon",
EdgelessTool::Select,
),
(
"edgeless-tool-hand",
"chrome.edgeless_toolbar.hand",
"HandIcon",
EdgelessTool::Hand,
),
(
"edgeless-tool-note",
"chrome.edgeless_toolbar.note",
"NoteShadowDuotoneIcon",
EdgelessTool::Note,
),
(
"edgeless-tool-shape",
"chrome.edgeless_toolbar.shape",
"ShapeIcon",
EdgelessTool::Shape(ShapeType::Rect),
),
(
"edgeless-tool-connector",
"chrome.edgeless_toolbar.connector",
"ConnectorEIcon",
EdgelessTool::Connector,
),
(
"edgeless-tool-brush",
"chrome.edgeless_toolbar.brush",
"PenIcon",
EdgelessTool::Brush,
),
(
"edgeless-tool-highlighter",
"chrome.edgeless_toolbar.highlighter",
"BrushIcon",
EdgelessTool::Highlighter,
),
(
"edgeless-tool-text",
"chrome.edgeless_toolbar.text",
"AddTextIcon",
EdgelessTool::Text,
),
(
"edgeless-tool-frame",
"chrome.edgeless_toolbar.frame",
"FrameIcon",
EdgelessTool::Frame,
),
];
let bar_w = tools.len() as f32 * BTN_SIZE + (tools.len() - 1) as f32 * BTN_GAP + 2.0 * BAR_PAD;
let bar_left = ((viewport_width - bar_w) * 0.5).max(8.0).round();
let mut bar = div()
.absolute()
.left(px(bar_left))
.bottom(px(BAR_MARGIN))
.p(px(BAR_PAD))
.rounded(px(BAR_RADIUS))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(BTN_GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot("chrome.edgeless_toolbar", Some(EDGELESS_VIEWPORT_ID));
for (el_id, snap_id, icon_name, target_tool) in tools {
let active = match (tool, target_tool) {
(EdgelessTool::Shape(_), EdgelessTool::Shape(_)) => true,
(a, b) => a == b,
};
let icon_color = if active { palette.brand } else { palette.icon };
let mut btn = div()
.id(el_id)
.w(px(BTN_SIZE))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(|s| s.bg(palette.hover))
.snapshot(snap_id, Some("chrome.edgeless_toolbar"))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
let chosen = match target_tool {
EdgelessTool::Shape(_) => {
if let EdgelessTool::Shape(cur) = this.edgeless.authoring.tool {
let next = match cur {
ShapeType::Rect => ShapeType::Ellipse,
ShapeType::Ellipse => ShapeType::Diamond,
ShapeType::Diamond => ShapeType::Triangle,
ShapeType::Triangle => ShapeType::Rect,
};
EdgelessTool::Shape(next)
} else {
EdgelessTool::Shape(this.edgeless.authoring.active_shape_type())
}
}
other => other,
};
this.edgeless_select_tool(chosen, window, cx);
}),
)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named(icon_name).paint(bounds, icon_color, window, cx);
},
)
.w(px(18.0))
.h(px(18.0)),
);
if active {
btn = btn.bg(palette.brand.opacity(0.14));
}
bar = bar.child(btn);
}
if !shadows.is_empty() {
bar = bar.shadow(shadows.clone().into());
}
// When the Shape tool is active, mount a compact concentric shape-variant sub-pill above the bar.
if let EdgelessTool::Shape(active_shape) = tool {
let variants: [(&'static str, &'static str, &'static str, ShapeType); 4] = [
(
"shape-rect",
"chrome.edgeless_toolbar.shape.rect",
"SquareIcon",
ShapeType::Rect,
),
(
"shape-ellipse",
"chrome.edgeless_toolbar.shape.ellipse",
"RoundedRectangleIcon",
ShapeType::Ellipse,
),
(
"shape-diamond",
"chrome.edgeless_toolbar.shape.diamond",
"DiamondIcon",
ShapeType::Diamond,
),
(
"shape-triangle",
"chrome.edgeless_toolbar.shape.triangle",
"TriangleIcon",
ShapeType::Triangle,
),
];
let sub_w = variants.len() as f32 * BTN_SIZE
+ (variants.len() - 1) as f32 * BTN_GAP
+ 2.0 * BAR_PAD;
let sub_left = ((viewport_width - sub_w) * 0.5).max(8.0).round();
let mut sub = div()
.absolute()
.left(px(sub_left))
.bottom(px(BAR_MARGIN + BTN_SIZE + 2.0 * BAR_PAD + 8.0))
.p(px(BAR_PAD))
.rounded(px(BAR_RADIUS))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(BTN_GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
"chrome.edgeless_toolbar.shape_picker",
Some(EDGELESS_VIEWPORT_ID),
);
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
for (el_id, snap_id, icon_name, shape_kind) in variants {
let active = active_shape == shape_kind;
let icon_color = if active { palette.brand } else { palette.icon };
let mut btn = div()
.id(el_id)
.w(px(BTN_SIZE))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(|s| s.bg(palette.hover))
.snapshot(snap_id, Some("chrome.edgeless_toolbar.shape_picker"))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_select_tool(EdgelessTool::Shape(shape_kind), window, cx);
}),
)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named(icon_name).paint(bounds, icon_color, window, cx);
},
)
.w(px(16.0))
.h(px(16.0)),
);
if active {
btn = btn.bg(palette.brand.opacity(0.14));
}
sub = sub.child(btn);
}
return div()
.absolute()
.inset_0()
.child(sub)
.child(bar)
.into_any_element();
}
bar.into_any_element()
}
/// Build the bottom-right screen-space zoom control bar (`chrome.edgeless_zoom`).
/// On narrow viewports (`viewport_width < 660.0`), stacks cleanly above `chrome.edgeless_toolbar`
/// so the two screen-space bars never overlap or clip.
pub fn build_zoom_controls<V: 'static>(
zoom: f32,
viewport_width: f32,
palette: &Palette,
theme: PlaygroundTheme,
on_out: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_reset: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_in: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
on_fit: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context<V>) + 'static,
cx: &mut ui::Context<V>,
) -> AnyElement {
let pct_label = format!("{}%", (zoom * 100.0).round() as i32);
let shadows = theme.shadows("--affine-toolbar-shadow");
let button = |id: &'static str, snap_id: &'static str, label: String, width: f32| {
div()
.id(id)
.w(px(width))
.h(px(ZOOM_BTN_HEIGHT))
.rounded(px(ZOOM_BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.text_size(px(12.0))
.font_weight(ui::FontWeight::MEDIUM)
.text_color(palette.text_primary)
.cursor_pointer()
.hover(|s| s.bg(palette.hover))
.snapshot(snap_id, Some("chrome.edgeless_zoom"))
.snapshot_text(label.clone())
.child(label)
};
let zoom_bottom = if viewport_width < 660.0 {
ZOOM_BAR_MARGIN + ZOOM_BTN_HEIGHT + 2.0 * ZOOM_BAR_PAD + 8.0
} else {
ZOOM_BAR_MARGIN
};
let mut bar = div()
.absolute()
.right(px(ZOOM_BAR_MARGIN))
.bottom(px(zoom_bottom))
.p(px(ZOOM_BAR_PAD))
.rounded(px(ZOOM_BAR_RADIUS))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(4.0))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot("chrome.edgeless_zoom", Some(EDGELESS_VIEWPORT_ID))
.child(
button(
"edgeless-zoom-out",
"chrome.edgeless_zoom.out",
"-".into(),
28.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_out)),
)
.child(
button(
"edgeless-zoom-reset",
"chrome.edgeless_zoom.reset",
pct_label,
48.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_reset)),
)
.child(
button(
"edgeless-zoom-in",
"chrome.edgeless_zoom.in",
"+".into(),
28.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_in)),
)
.child(
button(
"edgeless-zoom-fit",
"chrome.edgeless_zoom.fit",
"Fit".into(),
36.0,
)
.on_mouse_down(MouseButton::Left, cx.listener(on_fit)),
);
if !shadows.is_empty() {
bar = bar.shadow(shadows.into());
}
bar.into_any_element()
}
File diff suppressed because it is too large. Load diff
@@ -160,6 +160,21 @@ impl EditorSession {
pub(crate) fn composing(&self) -> bool {
self.preedit.is_some()
}
pub(crate) fn clear_preedit_state(&mut self) {
self.preedit = None;
}
pub(crate) fn preedit_nonce(&self) -> u64 {
self.preedit.as_ref().map_or(0u64, |pre| {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
pre.text.hash(&mut hasher);
pre.selected.hash(&mut hasher);
pre.backward.hash(&mut hasher);
hasher.finish().max(1)
})
}
}
fn word_range(text: &str, offset: u64) -> Range<u64> {
@@ -308,7 +323,12 @@ impl PlaygroundView {
self.change_selection(selection, w, cx);
}
fn change_selection(&mut self, sel: DocumentSelection, w: &mut Window, cx: &mut Context<Self>) {
pub(crate) fn change_selection(
&mut self,
sel: DocumentSelection,
w: &mut Window,
cx: &mut Context<Self>,
) {
if self.editor.preedit.take().is_some() {
self.dirty_text = None;
self.doc_rev += 1;
@@ -755,7 +775,7 @@ impl PlaygroundView {
}
Some(snapshot)
}
fn clear_composition(&mut self, w: &mut Window, cx: &mut Context<Self>) {
pub(crate) fn clear_composition(&mut self, w: &mut Window, cx: &mut Context<Self>) {
if let Some(sel) = self.composition_selection() {
self.editor.selection = Some(sel);
}
@@ -771,7 +791,7 @@ impl PlaygroundView {
cx.notify();
}
}
fn visual_focus(&self) -> Option<DocPoint> {
pub(crate) fn visual_focus(&self) -> Option<DocPoint> {
if let Some((id, r)) = self.composed_range() {
return Some(DocPoint::new(
id,
@@ -1201,10 +1221,20 @@ impl PlaygroundView {
impl EntityInputHandler for PlaygroundView {
fn paste(&mut self, item: ui::ClipboardItem, w: &mut Window, cx: &mut Context<Self>) {
let text = item.text().unwrap_or_default();
if self
.link_input(w, cx, |link| link.replace(None, &text))
.is_some()
if self.overlays.link_field().is_some() {
if let Some(text) = item.text() {
let _ = self.link_input(w, cx, |link| link.replace(None, &text));
}
return;
}
if self.edgeless.authoring.label_editor().is_some() {
if let Some(text) = item.text() {
let _ = self.edgeless_label_edit(w, cx, |ed| ed.replace(None, &text));
}
return;
}
if self.mode == crate::PlaygroundMode::Edgeless
&& self.edgeless.authoring.editing_spatial_block().is_none()
{
return;
}
@@ -1227,6 +1257,11 @@ impl EntityInputHandler for PlaygroundView {
*adjusted = Some(covered);
return Some(text);
}
if let Some(ed) = self.edgeless.authoring.label_editor() {
let (text, covered) = ed.text_for_range(range);
*adjusted = Some(covered);
return Some(text);
}
let text = self.display_text()?;
let index = TextBiIndex::new(&text);
let start = index.utf16_to_utf8_clamped(range.start as u64);
@@ -1244,6 +1279,10 @@ impl EntityInputHandler for PlaygroundView {
let (range, reversed) = link.shown_selection();
return Some(UTF16Selection { range, reversed });
}
if let Some(ed) = self.edgeless.authoring.label_editor() {
let (range, reversed) = ed.shown_selection();
return Some(UTF16Selection { range, reversed });
}
if let Some((_, r)) = self.composed_range()
&& let Some(pre) = &self.editor.preedit
{
@@ -1268,6 +1307,9 @@ impl EntityInputHandler for PlaygroundView {
if let Some(link) = self.overlays.link_field() {
return Some(link.text().encode_utf16().count());
}
if let Some(ed) = self.edgeless.authoring.label_editor() {
return Some(ed.display_text().encode_utf16().count());
}
Some(self.display_text()?.encode_utf16().count())
}
fn set_selected_text_range(&mut self, r: Range<usize>, w: &mut Window, cx: &mut Context<Self>) {
@@ -1277,6 +1319,12 @@ impl EntityInputHandler for PlaygroundView {
{
return;
}
if self
.edgeless_label_input(w, cx, |ed| ed.select(r.clone()))
.is_some()
{
return;
}
if let Some(focus) = self.visual_focus() {
self.change_selection(
DocumentSelection {
@@ -1292,6 +1340,9 @@ impl EntityInputHandler for PlaygroundView {
if let Some(link) = self.overlays.link_field() {
return link.marked_range();
}
if let Some(ed) = self.edgeless.authoring.label_editor() {
return ed.marked_range();
}
let (_, r) = self.composed_range()?;
let start = r.start as usize;
Some(start..start + self.editor.preedit.as_ref()?.text.encode_utf16().count())
@@ -1300,6 +1351,17 @@ impl EntityInputHandler for PlaygroundView {
if self.link_input(w, cx, LinkBar::unmark).is_some() {
return;
}
if self
.edgeless_label_edit(w, cx, crate::edgeless::EdgelessLabelEditor::unmark)
.is_some()
{
return;
}
if self.mode == crate::PlaygroundMode::Edgeless
&& self.edgeless.authoring.editing_spatial_block().is_none()
{
return;
}
if let Some(pre) = self.editor.preedit.as_ref() {
let text = pre.text.clone();
self.replace_text_in_range(None, &text, w, cx);
@@ -1318,6 +1380,17 @@ impl EntityInputHandler for PlaygroundView {
{
return;
}
if self
.edgeless_label_edit(w, cx, |ed| ed.replace(r.clone(), text))
.is_some()
{
return;
}
if self.mode == crate::PlaygroundMode::Edgeless
&& self.edgeless.authoring.editing_spatial_block().is_none()
{
return;
}
self.begin_input();
let selection = self.replacement_selection(r);
if self.editor.preedit.is_some() {
@@ -1346,6 +1419,17 @@ impl EntityInputHandler for PlaygroundView {
{
return;
}
if self
.edgeless_label_input(w, cx, |ed| ed.mark(r.clone(), text, selected.clone()))
.is_some()
{
return;
}
if self.mode == crate::PlaygroundMode::Edgeless
&& self.edgeless.authoring.editing_spatial_block().is_none()
{
return;
}
self.begin_input();
if text.is_empty() {
self.clear_composition(w, cx);
@@ -1357,6 +1441,8 @@ impl EntityInputHandler for PlaygroundView {
let Some(page) = self.page() else { return };
let backward = if let Some(pre) = &self.editor.preedit {
pre.backward
} else if sel.empty() {
false
} else {
let Some(layout) = self.flow_layout() else {
return;
@@ -1409,6 +1495,21 @@ impl EntityInputHandler for PlaygroundView {
.into_iter()
.collect();
}
if self.mode == crate::PlaygroundMode::Edgeless {
if let Some(bounds) = self.edgeless_label_screen_bounds() {
return vec![bounds];
}
if let Some(sel) = &self.editor.selection {
let id = self
.composed_range()
.map(|(id, _)| id)
.unwrap_or_else(|| sel.focus.block_id.clone());
if let Some(bounds) = self.edgeless_spatial_block_caret_bounds(&id, r.start as u64)
{
return vec![bounds];
}
}
}
let Some(sel) = &self.editor.selection else {
return vec![];
};
@@ -1926,12 +2027,52 @@ impl PlaygroundView {
Ok(())
}
pub(crate) fn hit_test_flow_layout(layout: &FlowLayout, x: f32, y: f32) -> Option<DocPoint> {
let block = layout
.blocks
.iter()
.filter(|b| b.editable())
.min_by(|a, b| {
let ar = a.rect();
let br = b.rect();
let da = if y < ar.y {
ar.y - y
} else if y > ar.bottom() {
y - ar.bottom()
} else {
0.0
};
let db = if y < br.y {
br.y - y
} else if y > br.bottom() {
y - br.bottom()
} else {
0.0
};
da.total_cmp(&db)
})?;
Some(DocPoint {
block_id: block.block_id.clone(),
caret: block.hit_text(x, y)?,
})
}
pub(super) fn editor_key_down(
&mut self,
e: &KeyDownEvent,
w: &mut Window,
cx: &mut Context<Self>,
) {
if self.mode == crate::PlaygroundMode::Edgeless {
if self.edgeless_key_down(e, w, cx) {
w.prevent_default();
cx.stop_propagation();
return;
}
if self.edgeless.authoring.editing_spatial_block().is_none() {
return;
}
}
if self.editor.preedit.is_some() || e.prefer_character_input {
return;
}
@@ -6,9 +6,7 @@
pub mod block_flow;
pub mod clipboard;
pub mod edgeless_camera;
pub mod edgeless_canvas;
mod edgeless_order;
pub mod edgeless;
pub mod editor_session;
pub mod overlays;
pub mod rich_text;
@@ -202,7 +200,7 @@ pub struct PlaygroundView {
max_scroll: f32,
/// Window size of the latest frame, in logical pixels.
window_size: (f32, f32),
edgeless: edgeless_canvas::EdgelessCanvasState,
edgeless: edgeless::EdgelessCanvasState,
overlays: Overlays,
/// Timer that ends a code block's `Copied` label; a newer copy replaces it.
copied_timer: Option<Task<()>>,
@@ -287,7 +285,7 @@ impl PlaygroundView {
scroll_y: 0.0,
max_scroll: 0.0,
window_size: (0.0, 0.0),
edgeless: edgeless_canvas::EdgelessCanvasState::new(),
edgeless: edgeless::EdgelessCanvasState::new(),
overlays: Overlays::new(),
copied_timer: None,
_tasks: tasks,
@@ -304,7 +302,7 @@ impl PlaygroundView {
self.theme
}
pub fn edgeless_camera(&self) -> edgeless_camera::EdgelessCamera {
pub fn edgeless_camera(&self) -> edgeless::EdgelessCamera {
self.edgeless.camera
}
@@ -372,22 +370,6 @@ impl PlaygroundView {
cx.notify();
}
fn on_edgeless_pan_move(
&mut self,
event: &ui::MouseMoveEvent,
_: &mut Window,
cx: &mut Context<Self>,
) {
if let Some(prev) = self.edgeless.drag_pan_anchor {
let dx = f32::from(event.position.x) - f32::from(prev.x);
let dy = f32::from(event.position.y) - f32::from(prev.y);
self.edgeless.camera.pan_by_screen_delta(dx, dy);
self.edgeless.drag_pan_anchor = Some(event.position);
self.edgeless.camera_initialized = true;
cx.notify();
}
}
fn on_edgeless_pan_end(
&mut self,
_: &ui::MouseUpEvent,
@@ -445,8 +427,14 @@ impl PlaygroundView {
self.snapshot.as_deref()
}
/// World-space layout painted by the latest Page frame.
/// World-space layout painted by the latest Page frame, or the active inline-edited
/// Edgeless Note/EdgelessText layout when editing on the Edgeless canvas.
pub fn flow_layout(&self) -> Option<Rc<FlowLayout>> {
if self.mode == PlaygroundMode::Edgeless
&& let Some((block_id, is_note)) = self.edgeless.authoring.editing_spatial_block()
{
return self.edgeless.cached_block_layout(block_id, is_note);
}
self.layout.as_ref().map(|(_, layout)| layout.clone())
}
@@ -619,6 +607,7 @@ impl PlaygroundView {
.filter(|snapshot| snapshot.root.is_some())
.map(Rc::new);
self.doc_rev += 1;
self.edgeless_refresh_label_editor_from_snapshot();
let mut referenced = BTreeSet::new();
for node in self
@@ -682,12 +671,21 @@ impl PlaygroundView {
}
}
fn set_mode(&mut self, target: PlaygroundMode, cx: &mut Context<Self>) {
fn set_mode(&mut self, target: PlaygroundMode, window: &mut Window, cx: &mut Context<Self>) {
if self.mode == target {
return;
}
let now_ms = self.now_ms(cx);
let current_x = self.indicator_x(now_ms);
// Commit any pending inline Edgeless edit cleanly before switching modes.
self.edgeless_flush_label_edit(window, cx);
if self.edgeless.authoring.editing_spatial_block().is_some() {
self.edgeless.authoring.inline_edit = None;
self.editor.clear_preedit_state();
self.editor.selection = None;
self.announce_selection(cx);
}
self.edgeless.authoring.reset_transient();
self.mode = target;
self.overlays.reset();
self.pill_motion = Some(Motion::new(
@@ -877,8 +875,8 @@ impl PlaygroundView {
};
let page_button = segment("mode-page", PILL_PAGE_X, is_page)
.on_click(cx.listener(|this, _, _, cx| {
this.set_mode(PlaygroundMode::Page, cx);
.on_click(cx.listener(|this, _, window, cx| {
this.set_mode(PlaygroundMode::Page, window, cx);
}))
.snapshot("chrome.mode_switcher.page", Some("chrome.mode_switcher"))
.snapshot_focused(is_page)
@@ -886,8 +884,8 @@ impl PlaygroundView {
.child("Page");
let edgeless_button = segment("mode-edgeless", PILL_EDGELESS_X, is_edgeless)
.on_click(cx.listener(|this, _, _, cx| {
this.set_mode(PlaygroundMode::Edgeless, cx);
.on_click(cx.listener(|this, _, window, cx| {
this.set_mode(PlaygroundMode::Edgeless, window, cx);
}))
.snapshot(
"chrome.mode_switcher.edgeless",
@@ -1256,33 +1254,41 @@ impl PlaygroundView {
.w_full()
.min_h_0()
.bg(palette.background_secondary)
.snapshot(edgeless_canvas::EDGELESS_VIEWPORT_ID, Some("root.canvas"))
.snapshot(edgeless::EDGELESS_VIEWPORT_ID, Some("root.canvas"))
.into_any_element();
};
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let vp_size = size(px(viewport_width.max(1.0)), px(viewport_height.max(1.0)));
if viewport_width > 0.0 && viewport_height > 0.0 {
self.edgeless.ensure_camera_initialized(&snapshot, vp_size);
}
let zoom_controls = edgeless_canvas::build_zoom_controls(
let zoom_controls = edgeless::build_zoom_controls(
self.edgeless.camera.zoom,
viewport_width,
palette,
self.theme,
move |this: &mut Self, _, _, cx| {
cx.stop_propagation();
this.edgeless.camera.zoom_out(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
cx.stop_propagation();
this.edgeless.camera.reset_zoom(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
cx.stop_propagation();
this.edgeless.camera.zoom_in(vp_origin, vp_size);
this.edgeless.camera_initialized = true;
cx.notify();
},
move |this: &mut Self, _, _, cx| {
cx.stop_propagation();
if let Some(snap) = &this.snapshot {
let bounds = this.edgeless.scene_world_bounds(snap);
this.edgeless.camera.fit_to_bounds(bounds, vp_size, 48.0);
@@ -1292,39 +1298,86 @@ impl PlaygroundView {
},
cx,
);
let toolbar = edgeless::build_edgeless_toolbar(
self.edgeless.authoring.tool,
viewport_width,
palette,
self.theme,
cx,
);
let input = edgeless_canvas::EdgelessRenderInput {
snapshot: &snapshot,
let render_snapshot = self
.preedit_snapshot()
.map(Rc::new)
.unwrap_or_else(|| Rc::clone(&snapshot));
let preedit_nonce = self.editor.preedit_nonce();
let editing_selection =
self.edgeless
.authoring
.editing_spatial_block()
.and_then(|(editing_id, is_note)| {
let sel = self.editor.selection.clone()?;
let focus = self.visual_focus()?;
Some((editing_id.to_string(), is_note, sel, focus))
});
let input = edgeless::EdgelessRenderInput {
snapshot: &render_snapshot,
doc_rev: self.doc_rev,
env_rev: self.env_rev,
preedit_nonce,
theme: self.theme,
palette,
page_titles: &self.page_titles,
images: &self.images,
viewport_width,
viewport_height,
editing_selection,
};
let layer = edgeless_canvas::build_edgeless_layer(
let layer = edgeless::build_edgeless_layer(
&mut self.edgeless,
&input,
window,
zoom_controls,
toolbar,
);
let needs_text_input =
self.edgeless.authoring.inline_edit.is_some() || self.overlays.link_field().is_some();
let input_overlay = needs_text_input.then(|| {
let focus = self.editor_focus.clone();
let entity = cx.entity();
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
window.handle_input(&focus, ui::ElementInputHandler::new(bounds, entity), cx)
},
)
.absolute()
.size_full()
});
div()
.relative()
.flex_1()
.w_full()
.min_h_0()
.flex()
.flex_col()
.track_focus(&self.editor_focus)
.on_key_down(cx.listener(Self::editor_key_down))
.on_key_up(cx.listener(|this, event: &ui::KeyUpEvent, _, _| {
if event.keystroke.key == "space" {
this.edgeless.authoring.space_pan = false;
}
}))
.on_scroll(cx.listener(Self::on_edgeless_scroll))
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_edgeless_left_down))
.on_mouse_down(
MouseButton::Middle,
cx.listener(Self::on_edgeless_pan_start),
)
.on_mouse_move(cx.listener(Self::on_edgeless_pan_move))
.on_mouse_up(MouseButton::Middle, cx.listener(Self::on_edgeless_pan_end))
.child(layer)
.children(input_overlay)
.into_any_element()
}
}
@@ -1381,6 +1434,14 @@ impl ui::Render for PlaygroundView {
.text_color(palette.text_primary)
.on_mouse_move(cx.listener(Self::root_mouse_move))
.on_mouse_up(MouseButton::Left, cx.listener(Self::root_mouse_up))
.on_mouse_up(
MouseButton::Middle,
cx.listener(|this, e, w, cx| {
if this.mode == PlaygroundMode::Edgeless {
this.on_edgeless_pan_end(e, w, cx);
}
}),
)
.snapshot("root.canvas", None)
.child(
div()
@@ -4616,7 +4677,7 @@ mod tests {
(note_layout.width, text_layout.width, lines)
});
assert!(
(note_w - (400.0 / 2.0 - 2.0 * edgeless_canvas::NOTE_CARD_PADDING)).abs() < 0.01,
(note_w - (400.0 / 2.0 - 2.0 * edgeless::NOTE_CARD_PADDING)).abs() < 0.01,
"expected Note logical width 152.0, got {note_w}"
);
assert!(
@@ -94,13 +94,12 @@ const POPOVER_BORDER: f32 = 1.0;
/// Side of the gutter drag handle's hit target.
pub const DRAG_HANDLE_SIZE: f32 = 24.0;
/// The handle at rest: BlockSuite's upright grabber bar.
/// The Page-mode handle at rest: BlockSuite's 4 × 12 px upright grabber bar.
const DRAG_GRABBER_WIDTH: f32 = 4.0;
/// The Page-mode handle under the pointer or in a drag: narrows to a 2 × 12 px vertical bar
/// (the 2 × 3 six-dot pill is reserved for Edgeless `gfx` drag handles).
const DRAG_GRABBER_HOT_WIDTH: f32 = 2.0;
const DRAG_GRABBER_HEIGHT: f32 = 12.0;
/// The handle under the pointer or in a drag: two columns of three dots on a pill.
const DRAG_DOTS_PILL_WIDTH: f32 = 14.0;
const DRAG_DOT: f32 = 4.0;
const DRAG_DOT_GAP: f32 = 2.0;
/// Closest the drag handle comes to the left window edge.
pub const DRAG_HANDLE_MIN_X: f32 = 4.0;
/// Thickness of the drop indicator line.
@@ -885,10 +884,19 @@ impl LinkBar {
start..end
}
/// Abandon any running composition, restoring the original URL and selection.
pub(crate) fn cancel_preedit(&mut self) {
self.preedit = None;
}
/// Put `text` in place of a running composition, else of `range`, else of the
/// selection, and leave the caret behind it. Control characters are dropped: the
/// field is one line.
pub(crate) fn replace(&mut self, range: Option<Range<usize>>, text: &str) {
if self.preedit.is_some() && text.is_empty() {
self.cancel_preedit();
return;
}
let target = match self.preedit.take() {
Some(preedit) => preedit.replacement,
None => range.map_or(self.selection.clone(), |range| self.clamped(range)),
@@ -2357,49 +2365,19 @@ impl Overlays {
.snapshot_focused(dragging)
.snapshot_text(block.block_id.clone());
}
// BlockSuite's grabber: an upright bar while the pointer is on the block, and
// two columns of dots on a pill once it is on the handle or drags it.
// BlockSuite's Page-mode grabber: a 4 × 12 px bar while the pointer is on the
// block's row, narrowing to a 2 × 12 px vertical bar when hovered or dragged.
let theme = palette.theme;
let grip = if dragging || self.handle_hot {
let dots = theme
let color = theme
.css_var("--affine-v2-icon-secondary")
.unwrap_or(palette.icon);
div()
.flex_none()
.w(px(DRAG_DOTS_PILL_WIDTH))
.h(px(DRAG_HANDLE_SIZE))
.rounded(px(4.0))
.bg(theme
.css_var("--affine-v2-layer-background-hoverOverlay")
.unwrap_or(palette.hover))
.flex()
.items_center()
.justify_center()
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
for row in 0..3 {
for column in 0..2 {
let step = DRAG_DOT + DRAG_DOT_GAP;
let dot = ui::Bounds::new(
point(
bounds.origin.x + px(column as f32 * step),
bounds.origin.y + px(row as f32 * step),
),
size(px(DRAG_DOT), px(DRAG_DOT)),
);
window.paint_quad(
ui::fill(dot, dots).corner_radii(px(DRAG_DOT / 2.0)),
);
}
}
},
)
.flex_none()
.w(px(2.0 * DRAG_DOT + DRAG_DOT_GAP))
.h(px(3.0 * DRAG_DOT + 2.0 * DRAG_DOT_GAP)),
)
.w(px(DRAG_GRABBER_HOT_WIDTH))
.h(px(DRAG_GRABBER_HEIGHT))
.rounded(px(1.0))
.bg(color)
} else {
div()
.flex_none()
@@ -3299,7 +3277,9 @@ impl PlaygroundView {
if effects.paste {
match cx.read_from_clipboard() {
Some(item) => {
self.overlays.link_insert(&item.text().unwrap_or_default());
if let Some(text) = item.text() {
self.overlays.link_insert(&text);
}
}
// A browser hands a paste over as an event of its own, and only when the
// key keeps its default action; that event reaches the link field through
@@ -3353,6 +3333,10 @@ impl PlaygroundView {
window,
cx,
);
if self.mode == PlaygroundMode::Edgeless {
self.on_edgeless_pointer_move(event, window, cx);
return;
}
if self.mode == PlaygroundMode::Page && self.overlays.dragged_block().is_none() {
let selecting = self.editor.dragging;
self.editor_mouse_move(event, window, cx);
@@ -3364,10 +3348,13 @@ impl PlaygroundView {
pub(crate) fn root_mouse_up(
&mut self,
_: &MouseUpEvent,
event: &MouseUpEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.mode == PlaygroundMode::Edgeless {
self.on_edgeless_left_up(event, window, cx);
}
// The selection is finished: the formatting toolbar may open over it.
if std::mem::take(&mut self.editor.dragging) {
cx.notify();
@@ -6409,4 +6396,69 @@ mod tests {
f32::from(moved.origin.x)
));
}
#[test]
fn link_bar_empty_replace_during_preedit_restores_url_and_selection() {
let mut bar = LinkBar::new("abc".into());
bar.select(1..2);
assert_eq!(bar.selected_text(), "b");
bar.mark(None, "ni", None);
assert!(bar.composing());
assert_eq!(bar.text(), "anic");
// Chromium sends compositionend("") on IME cancel: must restore "abc" with "b" selected.
bar.replace(None, "");
assert!(!bar.composing());
assert_eq!(bar.url(), "abc");
assert_eq!(bar.selected_text(), "b");
assert_eq!(bar.shown_selection(), (1..2, false));
}
#[test]
fn link_bar_non_text_clipboard_paste_does_not_erase_selection() {
let session = open(1280, 800, PlaygroundTheme::Light);
let _ = session.frame();
session.select("showcase-intro", "bold");
let _ = session.frame();
session.overlay(OverlayEvent::Format(FormatAction::Link));
let _ = session.frame();
session.update(|view, _window, cx| {
if let Some(link) = view.overlays.link_field_mut() {
link.replace(Some(0..0), "https://affine.pro");
link.select(0..18);
}
// Write a non-text ClipboardItem (`text() == None`).
let item = ClipboardItem {
entries: vec![ui::ClipboardEntry::ExternalPaths(
ui::ExternalPaths::default(),
)],
};
assert_eq!(item.text(), None);
cx.write_to_clipboard(item);
});
let _ = session.frame();
// Trigger Ctrl/Cmd+V in the link field.
let _ = session.update(|view, window, cx| {
let mut m = ui::Modifiers::default();
#[cfg(target_os = "macos")]
{
m.platform = true;
}
#[cfg(not(target_os = "macos"))]
{
m.control = true;
}
let event = KeyDownEvent {
keystroke: ui::Keystroke {
modifiers: m,
key: "v".into(),
key_char: Some("v".into()),
},
is_held: false,
prefer_character_input: false,
};
view.overlay_key_down(&event, window, cx)
});
let url = session.view(|view, _| view.overlays().link_url().map(str::to_string));
assert_eq!(url.as_deref(), Some("https://affine.pro"));
}
}
@@ -135,18 +135,21 @@ pub(super) struct Route {
}
impl Route {
pub(super) fn point_at_distance(&self, mode: ConnectorMode, t: f64) -> P {
if mode == ConnectorMode::Orthogonal {
return along(&self.samples, t);
}
let a = self.contour.start;
let (b, c, d) = match self.contour.edges[..] {
[Edge::Cubic(b, c, d)] => (b, c, d),
_ => {
let d = *self.samples.last().unwrap();
(a, d, d)
match mode {
ConnectorMode::Straight => self.contour.start.lerp(*self.samples.last().unwrap(), t),
ConnectorMode::Orthogonal => along(&self.samples, t),
ConnectorMode::Curve => {
let a = self.contour.start;
let (b, c, d) = match self.contour.edges[..] {
[Edge::Cubic(b, c, d)] => (b, c, d),
_ => {
let d = *self.samples.last().unwrap();
(a, d, d)
}
};
cubic(a, b, c, d, t)
}
};
cubic(a, b, c, d, t)
}
}
/// Endpoint and inward-facing tangent for each cap. A stationary Bézier endpoint
@@ -323,11 +326,8 @@ mod tests {
}
#[test]
fn labels_follow_the_bezier_parameter_for_curve_and_straight() {
for (mode, end, expected) in [
(2, [180, 60], P(61.875, 9.375)),
(0, [100, 0], P(15.625, 0.)),
] {
fn labels_follow_the_bezier_parameter_for_curve_and_linear_for_straight() {
for (mode, end, expected) in [(2, [180, 60], P(61.875, 9.375)), (0, [100, 0], P(25., 0.))] {
let e = SurfaceElement::from_properties(
"line".into(),
json!({"type":"connector","mode":mode,"source":{"position":[0,0]},"target":{"position":end}}),
@@ -44,6 +44,8 @@ struct Item {
label: Option<Label>,
label_clip: Option<Bounds<Pixels>>,
path_cutout: Option<WorldBounds>,
polyline: Vec<(f32, f32)>,
stroke_width: f32,
}
impl Item {
fn path(
@@ -108,17 +110,25 @@ impl SurfaceLayout {
pub(crate) fn item_ids(&self) -> impl Iterator<Item = &str> {
self.items.iter().map(|e| e.id.as_str())
}
pub(crate) fn item_polyline(&self, index: usize) -> &[(f32, f32)] {
&self.items[index].polyline
}
pub(crate) fn item_stroke_width(&self, index: usize) -> f32 {
self.items[index].stroke_width
}
pub(crate) fn paint_item(
&self,
index: usize,
viewport: Bounds<Pixels>,
editing_label_id: Option<&str>,
window: &mut Window,
cx: &mut App,
) {
let item = &self.items[index];
if (!item.group || self.show_group_frames) && item.bounds.intersects(&viewport) {
item.paint(TransformationMatrix::unit(), window, cx);
let suppress_label = editing_label_id.is_some_and(|id| id == item.id);
item.paint(TransformationMatrix::unit(), suppress_label, window, cx);
}
}
fn visible_items(&self) -> impl Iterator<Item = &Item> {
@@ -215,7 +225,7 @@ pub fn layout_surface(
) -> SurfaceLayout {
let mut bounds = external_bounds.clone();
let mut ordered: Vec<_> = elements.iter().filter(|e| !e.hidden).collect();
ordered.sort_by(|a, b| (&a.index, &a.id).cmp(&(&b.index, &b.id)));
ordered.sort_by(|a, b| a.index.cmp(&b.index));
bounds.extend(
ordered
.iter()
@@ -281,6 +291,8 @@ pub fn layout_surface(
label: None,
label_clip: None,
path_cutout: None,
polyline: vec![],
stroke_width: 0.0,
};
match &e.kind {
SurfaceElementKind::Shape(s) => {
@@ -290,9 +302,32 @@ pub fn layout_surface(
let Some(route) = routes.get(e.id.as_str()) else {
continue;
};
item.polyline = route
.samples
.iter()
.map(|p| (p.0 as f32, p.1 as f32))
.collect();
item.stroke_width = c.stroke_width as f32;
layout_connector(&mut item, c, route, e.seed, theme, window);
}
SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => {
let [x, y, w, h] = s.xywh;
let cx = x + w * 0.5;
let cy = y + h * 0.5;
let (sin, cos) = e.rotate.to_radians().sin_cos();
item.polyline = s
.points
.iter()
.map(|p| {
let dx = (x + p[0]) - cx;
let dy = (y + p[1]) - cy;
(
(cx + dx * cos - dy * sin) as f32,
(cy + dx * sin + dy * cos) as f32,
)
})
.collect();
item.stroke_width = s.line_width as f32;
let highlight = matches!(&e.kind, SurfaceElementKind::Highlighter(_));
if let Some(path) = strokes::outline(s, e.rotate) {
let color = if highlight {
@@ -405,7 +440,9 @@ fn layout_shape(
slant: &s.font_style,
align: s.text_align,
};
if let Some((layout, gap)) = style.layout(&s.text, w - 2. * px, theme, ts) {
if s.text_display
&& let Some((layout, gap)) = style.layout(&s.text, w - 2. * px, theme, ts)
{
let lh = f64::from(f32::from(layout.size().height)) + layout.lines().len() as f64 * gap;
let top = match s.text_vertical_align {
VerticalAlign::Top => py,
@@ -613,12 +650,18 @@ pub fn paint_surface(
.visible_items()
.filter(|item| item.bounds.intersects(&viewport_world))
{
item.paint(offset, window, cx);
item.paint(offset, false, window, cx);
}
}
impl Item {
fn paint(&self, offset: TransformationMatrix, window: &mut Window, cx: &mut App) {
fn paint(
&self,
offset: TransformationMatrix,
suppress_label: bool,
window: &mut Window,
cx: &mut App,
) {
window.with_paint_transformation(offset.compose(self.transform), |window| {
for (path, color) in &self.paths {
if let Some(hole) = self.path_cutout {
@@ -631,7 +674,7 @@ impl Item {
window.paint_path(path.clone(), *color);
}
}
if let Some(label) = &self.label {
if !suppress_label && let Some(label) = &self.label {
if let Some((pill, color)) = label.pill {
window.paint_quad(ui::fill(pill.ui(), color).corner_radii(px(5.)));
}
@@ -727,6 +770,8 @@ mod tests {
label: None,
label_clip: None,
path_cutout: None,
polyline: vec![],
stroke_width: 0.0,
};
layout_shape(&mut item, &s, 1, PlaygroundTheme::Light, &ts);
let label = item.label.unwrap();
@@ -747,4 +792,145 @@ mod tests {
});
}
}
#[test]
fn surface_label_visibility_and_text_connector_baselines() {
let platform = HeadlessPlatform::new(64, 64, 1.);
let app = Application::with_platform(platform).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let text = RichText {
plain: "Hidden".into(),
delta: vec![TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text("Hidden".into()),
format: None,
}],
};
let hidden = SurfaceElement::from_properties(
"s-hidden".into(),
json!({"type":"shape","xywh":[0,0,160,80],"textDisplay":false}),
text.clone(),
);
let standalone = SurfaceElement::from_properties(
"t-standalone".into(),
json!({"type":"text","xywh":[10,20,160,30],"fontSize":16}),
text.clone(),
);
let conn = SurfaceElement::from_properties(
"c-label".into(),
json!({"type":"connector","mode":0,"source":{"position":[0,100]},"target":{"position":[200,100]},"labelOffset":{"distance":0.5,"anchor":"center"}}),
text,
);
app.update(|cx| {
let ts = WindowTextSystem::new(cx.text_system().clone());
let SurfaceElementKind::Shape(mut s) = hidden.kind else {
unreachable!()
};
// `textDisplay` is `@local()` (defaults to `true` from wire); toggle locally to verify suppression.
assert!(s.text_display);
s.text_display = false;
let mut item = Item {
id: hidden.id,
group: false,
bounds: Bounds::default(),
transform: TransformationMatrix::unit(),
paths: vec![],
label: None,
label_clip: None,
path_cutout: None,
polyline: vec![],
stroke_width: 0.0,
};
layout_shape(&mut item, &s, 1, PlaygroundTheme::Light, &ts);
assert!(
item.label.is_none(),
"textDisplay=false must skip shape label"
);
// Standalone SurfaceText baseline sits at y + ascent (0 line_gap offset).
let SurfaceElementKind::Text(st) = standalone.kind else {
unreachable!()
};
let style = TextStyle {
color: &st.color,
font: &st.font_family,
size: st.font_size,
weight: &st.font_weight,
slant: &st.font_style,
align: st.text_align,
};
let (layout, _) = style
.layout(&st.text, st.xywh[2], PlaygroundTheme::Light, &ts)
.unwrap();
let line = &layout.lines()[0];
assert!(f32::from(line.baseline_y) > 0.0);
// Connector label vertical centering around route midpoint y = 100.
let SurfaceElementKind::Connector(c) = conn.kind else {
unreachable!()
};
let r = connector::route(&c, &BTreeMap::new(), &BTreeMap::new()).unwrap();
let mid = r.point_at_distance(c.mode, 0.5);
assert_eq!(mid, P(100., 100.));
});
}
#[test]
fn equal_index_shapes_paint_in_source_order_z_under_a() {
let platform = HeadlessPlatform::new(120, 120, 1.);
let app = Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let z = SurfaceElement::from_properties(
"z".into(),
json!({"type":"shape","shapeType":"rect","index":"a1","xywh":[10,10,80,80],"filled":true,"fillColor":"#ff0000","strokeStyle":"none"}),
RichText::default(),
);
let a = SurfaceElement::from_properties(
"a".into(),
json!({"type":"shape","shapeType":"rect","index":"a1","xywh":[10,10,80,80],"filled":true,"fillColor":"#0000ff","strokeStyle":"none"}),
RichText::default(),
);
let elements = vec![z, a];
let win = app
.update(|cx| {
cx.open_window(ui::WindowOptions::default(), |_window, cx| {
cx.new(|_| SurfaceOrderView {
elements: elements.clone(),
})
})
})
.unwrap();
let hw = platform.windows().into_iter().next().unwrap();
hw.request_frame();
let img = app
.update(|cx| win.update(cx, |_, window, _| window.render_to_image().unwrap()))
.unwrap();
let px_rgba = img.get_pixel(50, 50);
let [r, g, b, _] = px_rgba.0;
assert!(
b > 200 && r < 40 && g < 40,
"expected 'a' (blue) on top of 'z' (red), got rgb=({r},{g},{b})"
);
}
struct SurfaceOrderView {
elements: Vec<SurfaceElement>,
}
impl ui::Render for SurfaceOrderView {
fn render(&mut self, window: &mut Window, _: &mut ui::Context<Self>) -> impl IntoElement {
let layout = layout_surface(
&self.elements,
&BTreeMap::new(),
PlaygroundTheme::Light,
window,
);
surface_element(
Rc::new(layout),
Bounds::new(ui::point(px(0.), px(0.)), ui::size(px(120.), px(120.))),
ui::point(px(0.), px(0.)),
)
}
}
}
@@ -168,11 +168,6 @@ struct ActionData {
}
impl ActionRegistry {
pub(crate) fn load_actions(&mut self) {
self.register::<NoAction>();
self.register::<Unbind>();
}
pub fn register<A: Action>(&mut self) {
let name = A::name_for_type();
if self.by_name.contains_key(name) {
@@ -231,29 +231,6 @@ impl Application {
this
}
/// Assigns the source of assets for the application.
pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
let mut context_lock = self.0.borrow_mut();
let asset_source = Arc::new(asset_source);
context_lock.asset_source = asset_source.clone();
context_lock.svg_renderer = SvgRenderer::new(asset_source);
drop(context_lock);
self
}
/// Configures arguments to pass when restarting the application.
pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
self.0.borrow_mut().restart_arguments = arguments;
self
}
/// Configures when the application should automatically quit.
/// By default, [`QuitMode::Default`] is used.
pub fn with_quit_mode(self, mode: QuitMode) -> Self {
self.0.borrow_mut().quit_mode = mode;
self
}
/// Sets the windowing mode the app starts in. See [`App::request_windowing`].
///
/// Defaults to windowed. On Linux, the default environment is the process's own, and the app
@@ -557,60 +534,6 @@ impl SystemWindowTabController {
&self.tab_groups
}
/// Get the next tab group window handle.
pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
let controller = cx.global::<SystemWindowTabController>();
let current_group = controller
.tab_groups
.iter()
.find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
let current_group = current_group?;
// TODO: `.keys()` returns arbitrary order, what does "next" mean?
let group_ids: Vec<_> = controller.tab_groups.keys().collect();
let idx = group_ids.iter().position(|g| *g == current_group)?;
let next_idx = (idx + 1) % group_ids.len();
controller
.tab_groups
.get(group_ids[next_idx])
.and_then(|tabs| {
tabs.iter()
.max_by_key(|tab| tab.last_active_at)
.or_else(|| tabs.first())
.map(|tab| &tab.handle)
})
}
/// Get the previous tab group window handle.
pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
let controller = cx.global::<SystemWindowTabController>();
let current_group = controller
.tab_groups
.iter()
.find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
let current_group = current_group?;
// TODO: `.keys()` returns arbitrary order, what does "previous" mean?
let group_ids: Vec<_> = controller.tab_groups.keys().collect();
let idx = group_ids.iter().position(|g| *g == current_group)?;
let prev_idx = if idx == 0 {
group_ids.len() - 1
} else {
idx - 1
};
controller
.tab_groups
.get(group_ids[prev_idx])
.and_then(|tabs| {
tabs.iter()
.max_by_key(|tab| tab.last_active_at)
.or_else(|| tabs.first())
.map(|tab| &tab.handle)
})
}
/// Get all tabs in the same window.
pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
self.tab_groups
@@ -649,44 +572,6 @@ impl SystemWindowTabController {
}
}
/// Update the position of a tab within its group.
pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
let controller = cx.global_mut::<SystemWindowTabController>();
for (_, windows) in controller.tab_groups.iter_mut() {
if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
if ix < windows.len() && current_pos != ix {
let window_tab = windows.remove(current_pos);
windows.insert(ix, window_tab);
}
break;
}
}
}
/// Update the title of a tab.
pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
let controller = cx.global::<SystemWindowTabController>();
let tab = controller
.tab_groups
.values()
.flat_map(|windows| windows.iter())
.find(|tab| tab.id == id);
if tab.map_or(true, |t| t.title == title) {
return;
}
let controller = cx.global_mut::<SystemWindowTabController>();
for windows in controller.tab_groups.values_mut() {
for tab in windows.iter_mut() {
if tab.id == id {
tab.title = title;
return;
}
}
}
}
/// Insert a tab into a tab group.
pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
let controller = cx.global_mut::<SystemWindowTabController>();
@@ -1336,15 +1221,6 @@ impl App {
self.reduce_motion
}
/// Sets whether non-essential animations (e.g. loading spinners) should be
/// rendered in a static state instead of animating.
pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
if self.reduce_motion != reduce_motion {
self.reduce_motion = reduce_motion;
self.refresh_windows();
}
}
/// Schedules all windows in the application to be redrawn. This can be called
/// multiple times in an update cycle and still result in a single redraw.
pub fn refresh_windows(&mut self) {
@@ -1860,11 +1736,6 @@ impl App {
self.platform.read_from_clipboard_async()
}
/// Sets the text rendering mode for the application.
pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
self.text_rendering_mode.set(mode);
}
/// Returns the current text rendering mode for the application.
pub fn text_rendering_mode(&self) -> TextRenderingMode {
self.text_rendering_mode.get()
@@ -2088,17 +1959,6 @@ impl App {
)
}
/// Sets the path to use when restarting the application.
pub fn set_restart_path(&mut self, path: PathBuf) {
self.restart_path = Some(path);
}
/// Configures when the application should automatically quit.
/// By default, [`QuitMode::Default`] is used.
pub fn set_quit_mode(&mut self, mode: QuitMode) {
self.quit_mode = mode;
}
/// Sets whether the application participates in the system's foreground UI.
///
/// Only has an effect on macOS, where [`Self::request_windowing`] normally sets it. Use this
@@ -2346,12 +2206,6 @@ impl App {
.ok()
}
fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
self.current_window_by_entity
.entry(entity_id)
.or_insert(window);
}
#[inline(always)]
pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
where
@@ -2450,42 +2304,6 @@ impl App {
&self.text_system
}
/// Invokes a callback with grapheme clusters that exhausted font fallback.
///
/// Registering a callback replaces the previous callback and enables missing-glyph
/// detection. The callback runs on the foreground executor after shaping has
/// released its internal locks. Dropping its subscription disables detection until
/// another callback is registered.
///
/// Reports are queued without blocking shaping, then deduplicated before delivery.
/// The bounded queue can drop reports on overflow. Dropped reports may be reported
/// again when the text is reshaped; no retry is scheduled automatically.
pub fn on_missing_glyphs(
&self,
callback: impl FnMut(&[MissingGlyph], &mut App) + 'static,
) -> Subscription {
let registration = self.missing_glyph_callback.replace(Box::new(callback));
if let Some(mut receiver) = self.text_system.take_missing_glyph_receiver() {
let callback = self.missing_glyph_callback.clone();
self.spawn(async move |cx| {
while let Ok(missing_glyphs) = receiver.recv().await {
cx.update(|cx| callback.invoke(&missing_glyphs, cx));
}
})
.detach();
}
self.text_system.enable_missing_glyph_reporting();
let callback = self.missing_glyph_callback.clone();
let text_system = self.text_system.clone();
Subscription::new(move || {
if callback.remove(&registration) {
text_system.disable_missing_glyph_reporting();
}
})
}
/// Check whether a global of the given type has been assigned.
pub fn has_global<G: Global>(&self) -> bool {
crate::fast::dependencies::note_global_presence_read::<G>(self);
@@ -2502,14 +2320,6 @@ impl App {
.unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
}
/// Access the global of the given type if a value has been assigned.
pub fn try_global<G: Global>(&self) -> Option<&G> {
crate::fast::dependencies::note_global_read(self, TypeId::of::<G>());
self.globals_by_type
.get(&TypeId::of::<G>())
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
}
/// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
#[track_caller]
pub fn global_mut<G: Global>(&mut self) -> &mut G {
@@ -2542,12 +2352,6 @@ impl App {
self.globals_by_type.insert(global_type, Box::new(global));
}
/// Clear all stored globals. Does not notify global observers.
#[cfg(any(test, feature = "harness"))]
pub fn clear_globals(&mut self) {
self.globals_by_type.drain();
}
/// Remove the global of the given type from the app context. Does not notify global observers.
pub fn remove_global<G: Global>(&mut self) -> G {
crate::fast::dependencies::note_global_removed::<G>(self);
@@ -2596,35 +2400,6 @@ impl App {
self.globals_by_type.insert(global_type, lease.global);
}
pub(crate) fn new_entity_observer(
&self,
key: TypeId,
value: NewEntityListener,
) -> Subscription {
self.new_entity_observers.insert(key, value)
}
/// Arrange for the given function to be invoked whenever a view of the specified type is created.
/// The function will be passed a mutable reference to the view along with an appropriate context.
pub fn observe_new<T: 'static>(
&self,
on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
) -> Subscription {
self.new_entity_observer(
TypeId::of::<T>(),
Box::new(
move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
any_entity
.downcast::<T>()
.unwrap()
.update(cx, |entity_state, cx| {
on_new(entity_state, window.as_deref_mut(), cx)
})
},
),
)
}
/// Observe the release of a entity. The callback is invoked after the entity
/// has no more strong references but before it has been dropped.
pub fn observe_release<T>(
@@ -2676,38 +2451,12 @@ impl App {
}))
}
/// Register a callback to be invoked when a keystroke is received by the application
/// in any window. Note that this fires _before_ all other action and event mechanisms have resolved
/// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls
/// within interceptors will prevent action dispatch
pub fn intercept_keystrokes(
&mut self,
mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
) -> Subscription {
self.keystroke_interceptors
.insert(Box::new(move |event, window, cx| {
f(event, window, cx);
true
}))
}
/// Register key bindings.
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
self.keymap.borrow_mut().add_bindings(bindings);
self.pending_effects.push_back(Effect::RefreshWindows);
}
/// Clear all key bindings in the app.
pub fn clear_key_bindings(&mut self) {
self.keymap.borrow_mut().clear();
self.pending_effects.push_back(Effect::RefreshWindows);
}
/// Get all key bindings in the app.
pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
self.keymap.clone()
}
/// Register a global handler for actions invoked via the keyboard. These handlers are run at
/// the end of the bubble phase for actions, and so will only be invoked if there are no other
/// handlers or if they called `cx.propagate()`.
@@ -2765,21 +2514,6 @@ impl App {
RefCell::borrow(&self.keymap).all_bindings_for_input(input)
}
/// Get a map from a deprecated action name to the canonical name.
pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
self.actions.deprecated_aliases()
}
/// Get a map from an action name to the deprecation messages.
pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
self.actions.deprecation_messages()
}
/// Get a map from an action name to the documentation.
pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
self.actions.documentation()
}
/// Register a callback to be invoked when the application is about to quit.
/// It is not possible to cancel the quit event at this point.
pub fn on_app_quit<Fut>(
@@ -2805,15 +2539,6 @@ impl App {
}))
}
/// Register a callback to be invoked when a window is closed
/// The window is no longer accessible at the point this callback is invoked.
pub fn on_window_closed(
&self,
on_closed: impl FnMut(&mut App, WindowId) + 'static,
) -> Subscription {
self.window_closed_observers.insert(Box::new(on_closed))
}
pub(crate) fn clear_pending_keystrokes(&mut self) {
for window in self.windows() {
window
@@ -2951,23 +2676,6 @@ impl App {
self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
}
/// Stops active drag and clears any related effects.
pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
if self.active_drag.is_some() {
self.active_drag = None;
if self.platform_owned_drag.as_ref().is_some_and(|drag| {
drag.source_window == window.window_handle().window_id()
&& matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
}) {
self.platform_owned_drag = None;
}
window.refresh();
true
} else {
false
}
}
pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
let Some(drag) = self.active_drag.take() else {
return false;
@@ -3025,21 +2733,6 @@ impl App {
true
}
/// Sets the cursor style for the currently active drag operation.
pub fn set_active_drag_cursor_style(
&mut self,
cursor_style: CursorStyle,
window: &mut Window,
) -> bool {
if let Some(ref mut drag) = self.active_drag {
drag.cursor_style = Some(cursor_style);
window.refresh();
true
} else {
false
}
}
/// Set the prompt renderer for GPUI. This will replace the default or platform specific
/// prompts with this custom implementation.
pub fn set_prompt_builder(
@@ -3058,11 +2751,6 @@ impl App {
self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
}
/// Reset the prompt builder to the default implementation.
pub fn reset_prompt_builder(&mut self) {
self.prompt_builder = Some(PromptBuilder::Default);
}
/// Remove an asset from GPUI's cache
pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
let asset_id = (TypeId::of::<A>(), hash(source));
@@ -3143,12 +2831,6 @@ impl App {
.insert(entity_id, window_invalidators);
}
/// Returns the name for this [`App`].
#[cfg(any(test, feature = "harness", debug_assertions))]
pub fn get_name(&self) -> Option<&'static str> {
self.name
}
/// Returns `true` if the platform file picker supports selecting a mix of files and directories.
pub fn can_select_mixed_files_and_dirs(&self) -> bool {
self.platform.can_select_mixed_files_and_dirs()
@@ -242,32 +242,6 @@ impl AsyncApp {
read(app.global(), &app)
}
/// Reads the global state of the specified type, passing it to the given callback.
///
/// Similar to [`AsyncApp::read_global`], but returns an error instead of panicking
pub fn try_read_global<G: Global, R>(&self, read: impl FnOnce(&G, &App) -> R) -> Option<R> {
let app = self.app();
let app = app.borrow_mut();
if app.quitting {
return None;
}
Some(read(app.try_global()?, &app))
}
/// Reads the global state of the specified type, passing it to the given callback.
/// A default value is assigned if a global of this type has not yet been assigned.
pub fn read_default_global<G: Global + Default, R>(
&self,
read: impl FnOnce(&G, &App) -> R,
) -> R {
let app = self.app();
let mut app = app.borrow_mut();
app.update(|cx| {
cx.default_global::<G>();
});
read(app.global(), &app)
}
/// A convenience method for [`App::update_global`](BorrowAppContext::update_global)
/// for updating the global state of the specified type.
pub fn update_global<G: Global, R>(&self, update: impl FnOnce(&mut G, &mut App) -> R) -> R {
@@ -318,16 +292,6 @@ impl AsyncWindowContext {
.update_window(self.window, |_, window, cx| update(window, cx))
}
/// A convenience method for [`App::update_window`].
#[inline(always)]
#[track_caller]
pub fn update_root<R>(
&mut self,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R> {
self.app.update_window(self.window, update)
}
/// A convenience method for [`Window::on_next_frame`].
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut Window, &mut App) + 'static) {
self.app
@@ -75,20 +75,6 @@ impl<'a, T: 'static> Context<'a, T> {
})
}
/// Observe changes to ourselves
pub fn observe_self(
&mut self,
mut on_event: impl FnMut(&mut T, &mut Context<T>) + 'static,
) -> Subscription
where
T: 'static,
{
let this = self.entity();
self.app.observe(&this, move |this, cx| {
this.update(cx, |this, cx| on_event(this, cx))
})
}
/// Subscribe to an event type from another entity
pub fn subscribe<T2, Evt>(
&mut self,
@@ -107,21 +93,6 @@ impl<'a, T: 'static> Context<'a, T> {
})
}
/// Subscribe to an event type from ourself
pub fn subscribe_self<Evt>(
&mut self,
mut on_event: impl FnMut(&mut T, &Evt, &mut Context<T>) + 'static,
) -> Subscription
where
T: 'static + EventEmitter<Evt>,
Evt: 'static,
{
let this = self.entity();
self.app.subscribe(&this, move |this, evt, cx| {
this.update(cx, |this, cx| on_event(this, evt, cx))
})
}
/// Register a callback to be invoked when GPUI releases this entity.
pub fn on_release(&self, on_release: impl FnOnce(&mut T, &mut App) + 'static) -> Subscription
where
@@ -250,18 +221,6 @@ impl<'a, T: 'static> Context<'a, T> {
}
}
/// Convenience method for producing view state in a closure.
/// See `listener` for more details.
pub fn processor<E, R>(
&self,
f: impl Fn(&mut T, E, &mut Window, &mut Context<T>) -> R + 'static,
) -> impl Fn(E, &mut Window, &mut App) -> R + 'static {
let view = self.entity();
move |e: E, window: &mut Window, cx: &mut App| {
view.update(cx, |view, cx| f(view, e, window, cx))
}
}
/// Run something using this entity and cx, when the returned struct is dropped
pub fn on_drop(
&self,
@@ -291,86 +250,6 @@ impl<'a, T: 'static> Context<'a, T> {
window.on_next_frame(move |window, cx| view.update(cx, |view, cx| f(view, window, cx)));
}
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
/// that are currently on the stack to be returned to the app.
pub fn defer_in(
&mut self,
window: &Window,
f: impl FnOnce(&mut T, &mut Window, &mut Context<T>) + 'static,
) {
let view = self.weak_entity();
let entity_id = self.entity_id();
self.ensure_window(entity_id, window.handle.id);
self.app.defer(move |cx| {
cx.with_window(entity_id, |window, cx| {
view.update(cx, |view, cx| f(view, window, cx)).ok();
});
});
}
/// Observe another entity for changes to its state, as tracked by [`Context::notify`].
pub fn observe_in<V2>(
&mut self,
observed: &Entity<V2>,
window: &mut Window,
mut on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<T>) + 'static,
) -> Subscription
where
V2: 'static,
T: 'static,
{
let observed_id = observed.entity_id();
let observed = observed.downgrade();
let observer = self.weak_entity();
let observer_id = self.entity_id();
self.ensure_window(observer_id, window.handle.id);
self.new_observer(
observed_id,
Box::new(move |cx| invoke_observer_in(&observer, &observed, cx, &mut on_notify)),
)
}
/// Subscribe to events emitted by another entity.
/// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
/// The callback will be invoked with a reference to the current view, a handle to the emitting `Entity`, the event, a mutable reference to the `Window`, and the context for the entity.
pub fn subscribe_in<Emitter, Evt>(
&mut self,
emitter: &Entity<Emitter>,
window: &Window,
mut on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<T>) + 'static,
) -> Subscription
where
Emitter: EventEmitter<Evt>,
Evt: 'static,
{
let emitter = emitter.downgrade();
let subscriber = self.weak_entity();
let subscriber_id = self.entity_id();
self.ensure_window(subscriber_id, window.handle.id);
self.new_subscription(
emitter.entity_id(),
(
TypeId::of::<Evt>(),
Box::new(move |event, cx| {
invoke_subscriber_in(&subscriber, &emitter, event, cx, &mut on_event)
}),
),
)
}
/// Register a callback to be invoked when the view is released.
///
/// The callback receives a handle to the view's window. This handle may be
/// invalid, if the window was closed before the view was released.
pub fn on_release_in(
&mut self,
window: &Window,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscription {
let entity = self.entity();
self.app.observe_release_in(&entity, window, on_release)
}
/// Register a callback to be invoked when the given Entity is released.
pub fn observe_release_in<T2>(
&self,
@@ -393,34 +272,6 @@ impl<'a, T: 'static> Context<'a, T> {
})
}
/// Register a callback to be invoked when the window is resized.
pub fn observe_window_bounds(
&self,
window: &mut Window,
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
window.bounds_observers.insert(Box::new(move |window, cx| {
view.update(cx, |view, cx| callback(view, window, cx))
.is_ok()
}))
}
/// Register a callback to be invoked when the window is activated or deactivated.
pub fn observe_window_activation(
&self,
window: &mut Window,
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
window
.activation_observers
.insert(Box::new(move |window, cx| {
view.update(cx, |view, cx| callback(view, window, cx))
.is_ok()
}))
}
/// Registers a callback to be invoked when the window's visibility changes
/// (see [`WindowVisibility`]).
pub fn observe_window_visibility(
@@ -499,46 +350,6 @@ impl<'a, T: 'static> Context<'a, T> {
}))
}
/// Register a callback to be invoked when the window's pending input changes.
pub fn observe_pending_input(
&self,
window: &mut Window,
mut callback: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
window
.pending_input_observers
.insert(Box::new(move |window, cx| {
view.update(cx, |view, cx| callback(view, window, cx))
.is_ok()
}))
}
/// Register a listener to be called when the given focus handle receives focus.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_focus(
&mut self,
handle: &FocusHandle,
window: &mut Window,
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
let focus_id = handle.id;
let (subscription, activate) =
window.new_focus_listener(Box::new(move |event, window, cx| {
view.update(cx, |view, cx| {
if event.previous_focus_path.last() != Some(&focus_id)
&& event.current_focus_path.last() == Some(&focus_id)
{
listener(view, window, cx)
}
})
.is_ok()
}));
self.defer(|_| activate());
subscription
}
/// Register a listener to be called when the given focus handle or one of its descendants receives focus.
/// This does not fire if the given focus handle - or one of its descendants - was previously focused.
/// Returns a subscription and persists until the subscription is dropped.
@@ -563,52 +374,6 @@ impl<'a, T: 'static> Context<'a, T> {
subscription
}
/// Register a listener to be called when the given focus handle loses focus.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_blur(
&mut self,
handle: &FocusHandle,
window: &mut Window,
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
let focus_id = handle.id;
let (subscription, activate) =
window.new_focus_listener(Box::new(move |event, window, cx| {
view.update(cx, |view, cx| {
if event.previous_focus_path.last() == Some(&focus_id)
&& event.current_focus_path.last() != Some(&focus_id)
{
listener(view, window, cx)
}
})
.is_ok()
}));
self.defer(|_| activate());
subscription
}
/// Register a listener to be called when nothing in the window has focus.
/// This typically happens when the node that was focused is removed from the tree,
/// and this callback lets you chose a default place to restore the users focus.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_focus_lost(
&mut self,
window: &mut Window,
mut listener: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let view = self.weak_entity();
let (subscription, activate) =
window
.focus_lost_listeners
.insert_pending(Box::new(move |window, cx| {
view.update(cx, |view, cx| listener(view, window, cx))
.is_ok()
}));
self.defer(|_| activate());
subscription
}
/// Register a listener to be called when the given focus handle or one of its descendants loses focus.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_focus_out(
@@ -640,71 +405,6 @@ impl<'a, T: 'static> Context<'a, T> {
subscription
}
/// Schedule a future to be run asynchronously.
/// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
/// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
/// The returned future will be polled on the main thread.
#[track_caller]
#[inline(always)]
pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R>
where
R: 'static,
AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
{
let view = self.weak_entity();
window.spawn(self, async move |cx| f(view, cx).await)
}
/// Schedule a future to be run asynchronously with the given priority.
/// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
/// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
/// The returned future will be polled on the main thread.
#[track_caller]
#[inline(always)]
pub fn spawn_in_with_priority<AsyncFn, R>(
&self,
priority: Priority,
window: &Window,
f: AsyncFn,
) -> Task<R>
where
R: 'static,
AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
{
let view = self.weak_entity();
window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
}
/// Register a callback to be invoked when the given global state changes.
pub fn observe_global_in<G: Global>(
&mut self,
window: &Window,
mut f: impl FnMut(&mut T, &mut Window, &mut Context<T>) + 'static,
) -> Subscription {
let window_handle = window.handle;
let view = self.weak_entity();
let subscription = crate::fast::observers::observe_global(
self,
TypeId::of::<G>(),
Box::new(move |cx| {
// If the entity has been dropped, remove this observer.
if view.upgrade().is_none() {
return false;
}
// If the window is unavailable (e.g. temporarily taken during a
// nested update, or already closed), skip this notification but
// keep the observer alive so it can fire on future changes.
let Ok(entity_alive) = window_handle.update(cx, |_, window, cx| {
view.update(cx, |view, cx| f(view, window, cx)).is_ok()
}) else {
return true;
};
entity_alive
}),
);
subscription
}
/// Register a callback to be invoked when the given Action type is dispatched to the window.
pub fn on_action(
&mut self,
@@ -721,17 +421,6 @@ impl<'a, T: 'static> Context<'a, T> {
.ok();
});
}
/// Move focus to the current view, assuming it implements [`Focusable`].
pub fn focus_self(&mut self, window: &mut Window)
where
T: Focusable,
{
let view = self.entity();
window.defer(self, move |window, cx| {
view.read(cx).focus_handle(cx).focus(window, cx)
})
}
}
impl<T> Context<'_, T> {
@@ -889,44 +578,6 @@ fn invoke_subscriber<T: 'static, Emitter: 'static, Event: 'static>(
}
}
#[inline(never)]
fn invoke_observer_in<T: 'static, W: 'static>(
observer: &WeakEntity<T>,
observed: &WeakEntity<W>,
cx: &mut App,
on_notify: &mut dyn FnMut(&mut T, Entity<W>, &mut Window, &mut Context<T>),
) -> bool {
let Some((observer, observed)) = observer.upgrade().zip(observed.upgrade()) else {
return false;
};
cx.with_window(observer.entity_id(), |window, cx| {
observer.update(cx, |observer, cx| {
on_notify(observer, observed, window, cx);
});
});
true
}
#[inline(never)]
fn invoke_subscriber_in<T: 'static, Emitter: 'static, Event: 'static>(
subscriber: &WeakEntity<T>,
emitter: &WeakEntity<Emitter>,
event: &dyn Any,
cx: &mut App,
on_event: &mut dyn FnMut(&mut T, &Entity<Emitter>, &Event, &mut Window, &mut Context<T>),
) -> bool {
let Some((subscriber, emitter)) = subscriber.upgrade().zip(emitter.upgrade()) else {
return false;
};
let event = event.downcast_ref().expect("invalid event type");
cx.with_window(subscriber.entity_id(), |window, cx| {
subscriber.update(cx, |subscriber, cx| {
on_event(subscriber, &emitter, event, window, cx);
});
});
true
}
#[inline(never)]
fn invoke_listener<T: 'static>(
view: &WeakEntity<T>,
@@ -37,11 +37,6 @@ impl From<u64> for EntityId {
}
impl EntityId {
/// Converts this entity id to a [NonZeroU64]
pub fn as_non_zero_u64(self) -> NonZeroU64 {
NonZeroU64::new(self.0.as_ffi()).unwrap()
}
/// Converts this entity id to a [u64]
pub fn as_u64(self) -> u64 {
self.0.as_ffi()
@@ -686,16 +681,6 @@ impl AnyWeakEntity {
self.entity_id
}
/// Check if this weak handle can be upgraded, or if the entity has already been dropped
pub fn is_upgradable(&self) -> bool {
let ref_count = self
.entity_ref_counts
.upgrade()
.and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
.unwrap_or(0);
ref_count > 0
}
/// Upgrade this weak entity reference to a strong reference.
pub fn upgrade(&self) -> Option<AnyEntity> {
let ref_counts = &self.entity_ref_counts.upgrade()?;
@@ -1,372 +0,0 @@
use crate::{Bounds, Half};
use std::{
cmp,
fmt::Debug,
ops::{Add, Sub},
ptr::NonNull,
};
/// Maximum children per internal node (R-tree style branching factor).
/// Higher values = shorter tree = fewer cache misses, but more work per node.
const MAX_CHILDREN: usize = 12;
/// A spatial tree optimized for finding maximum ordering among intersecting bounds.
///
/// This is an R-tree variant specifically designed for the use case of assigning
/// z-order to overlapping UI elements. Key optimizations:
/// - Tracks the leaf with global max ordering for O(1) fast-path queries
/// - Uses higher branching factor (4) for lower tree height
/// - Aggressive pruning during search based on max_order metadata
#[derive(Debug)]
pub(crate) struct BoundsTree<U>
where
U: Clone + Debug + Default + PartialEq,
{
/// All nodes stored contiguously for cache efficiency.
nodes: Vec<Node<U>>,
/// Index of the root node, if any.
root: Option<usize>,
/// Index of the leaf with the highest ordering (for fast-path lookups).
max_leaf: Option<usize>,
/// Reusable stack for tree traversal during insertion.
insert_path: Vec<usize>,
/// Reusable stack for search operations.
search_stack: Vec<NonNull<Node<U>>>,
}
/// A node in the bounds tree.
#[derive(Debug, Clone)]
struct Node<U>
where
U: Clone + Debug + Default + PartialEq,
{
/// Bounding box containing this node and all descendants.
bounds: Bounds<U>,
/// Maximum ordering value in this subtree.
max_order: u32,
/// Node-specific data.
kind: NodeKind,
}
#[derive(Debug, Clone)]
enum NodeKind {
/// Leaf node containing actual bounds data.
Leaf {
/// The ordering assigned to this bounds.
order: u32,
},
/// Internal node with children.
Internal {
/// Indices of child nodes (2 to MAX_CHILDREN).
children: NodeChildren,
},
}
/// Fixed-size array for child indices, avoiding heap allocation.
#[derive(Debug, Clone)]
struct NodeChildren {
// Keeps an invariant where the max order child is always at the end
indices: [usize; MAX_CHILDREN],
len: u8,
}
impl NodeChildren {
fn new() -> Self {
Self {
indices: [0; MAX_CHILDREN],
len: 0,
}
}
fn push(&mut self, index: usize) {
debug_assert!((self.len as usize) < MAX_CHILDREN);
self.indices[self.len as usize] = index;
self.len += 1;
}
fn len(&self) -> usize {
self.len as usize
}
fn as_slice(&self) -> &[usize] {
&self.indices[..self.len as usize]
}
}
impl<U> BoundsTree<U>
where
U: Clone
+ Debug
+ PartialEq
+ PartialOrd
+ Add<U, Output = U>
+ Sub<Output = U>
+ Half
+ Default,
{
/// Clears all nodes from the tree.
pub fn clear(&mut self) {
self.nodes.clear();
self.root = None;
self.max_leaf = None;
self.insert_path.clear();
self.search_stack.clear();
}
/// Inserts bounds into the tree and returns its assigned ordering.
///
/// The ordering is one greater than the maximum ordering of any
/// existing bounds that intersect with the new bounds.
pub fn insert(&mut self, new_bounds: Bounds<U>) -> u32 {
// Find maximum ordering among intersecting bounds
let max_intersecting = self.find_max_ordering(&new_bounds);
let ordering = max_intersecting + 1;
// Insert the new leaf
let new_leaf_idx = self.insert_leaf(new_bounds, ordering);
// Update max_leaf tracking
self.max_leaf = match self.max_leaf {
None => Some(new_leaf_idx),
Some(old_idx) if self.nodes[old_idx].max_order < ordering => Some(new_leaf_idx),
some => some,
};
ordering
}
/// Finds the maximum ordering among all bounds that intersect with the query.
fn find_max_ordering(&mut self, query: &Bounds<U>) -> u32 {
let Some(root_idx) = self.root else {
return 0;
};
// Fast path: check if the max-ordering leaf intersects
if let Some(max_idx) = self.max_leaf {
let max_node = &self.nodes[max_idx];
if query.intersects(&max_node.bounds) {
return max_node.max_order;
}
}
// Slow path: search the tree
self.search_stack.clear();
self.search_stack.push(NonNull::from(&self.nodes[root_idx]));
let mut max_found = 0u32;
while let Some(node) = self.search_stack.pop() {
// SAFETY: `node` is guaranteed to be valid as the `nodes` stack is unmodified in this function
// and the `search_stack` only contains pointers from this function call.
let node = unsafe { node.as_ref() };
// Pruning: skip if this subtree can't improve our result
if node.max_order <= max_found {
continue;
}
// Spatial pruning: skip if bounds don't intersect
if !query.intersects(&node.bounds) {
continue;
}
match &node.kind {
NodeKind::Leaf { order } => {
max_found = cmp::max(max_found, *order);
}
NodeKind::Internal { children } => {
// Children are maintained with highest max_order at the end.
// Push in forward order to highest (last) is popped first.
self.search_stack.extend(
children
.as_slice()
.iter()
.map(|&child_idx| &self.nodes[child_idx])
.filter(|node| node.max_order > max_found)
.map(NonNull::from),
);
}
}
}
max_found
}
/// Inserts a leaf node with the given bounds and ordering.
/// Returns the index of the new leaf.
fn insert_leaf(&mut self, bounds: Bounds<U>, order: u32) -> usize {
let new_leaf_idx = self.nodes.len();
self.nodes.push(Node {
bounds: bounds.clone(),
max_order: order,
kind: NodeKind::Leaf { order },
});
let Some(root_idx) = self.root else {
// Tree is empty, new leaf becomes root
self.root = Some(new_leaf_idx);
return new_leaf_idx;
};
// If root is a leaf, create internal node with both
if matches!(self.nodes[root_idx].kind, NodeKind::Leaf { .. }) {
let root_bounds = self.nodes[root_idx].bounds.clone();
let root_order = self.nodes[root_idx].max_order;
let mut children = NodeChildren::new();
// Max end invariant
if order > root_order {
children.push(root_idx);
children.push(new_leaf_idx);
} else {
children.push(new_leaf_idx);
children.push(root_idx);
}
let new_root_idx = self.nodes.len();
self.nodes.push(Node {
bounds: root_bounds.union(&bounds),
max_order: cmp::max(root_order, order),
kind: NodeKind::Internal { children },
});
self.root = Some(new_root_idx);
return new_leaf_idx;
}
// Descend to find the best internal node to insert into
self.insert_path.clear();
let mut current_idx = root_idx;
loop {
let current = &self.nodes[current_idx];
let NodeKind::Internal { children } = &current.kind else {
unreachable!("Should only traverse internal nodes");
};
self.insert_path.push(current_idx);
// Find the best child to descend into
let mut best_child_idx = children.as_slice()[0];
let mut best_child_pos = 0;
let mut best_cost = bounds
.union(&self.nodes[best_child_idx].bounds)
.half_perimeter();
for (pos, &child_idx) in children.as_slice().iter().enumerate().skip(1) {
let cost = bounds.union(&self.nodes[child_idx].bounds).half_perimeter();
if cost < best_cost {
best_cost = cost;
best_child_idx = child_idx;
best_child_pos = pos;
}
}
// Check if best child is a leaf or internal
if matches!(self.nodes[best_child_idx].kind, NodeKind::Leaf { .. }) {
// Best child is a leaf. Check if current node has room for another child.
if children.len() < MAX_CHILDREN {
// Add new leaf directly to this node
let node = &mut self.nodes[current_idx];
if let NodeKind::Internal { children } = &mut node.kind {
children.push(new_leaf_idx);
// Swap new leaf only if it has the highest max_order
if order <= node.max_order {
let last = children.len() - 1;
children.indices.swap(last - 1, last);
}
}
node.bounds = node.bounds.union(&bounds);
node.max_order = cmp::max(node.max_order, order);
break;
} else {
// Node is full, create new internal with [best_leaf, new_leaf]
let sibling_bounds = self.nodes[best_child_idx].bounds.clone();
let sibling_order = self.nodes[best_child_idx].max_order;
let mut new_children = NodeChildren::new();
// Max end invariant
if order > sibling_order {
new_children.push(best_child_idx);
new_children.push(new_leaf_idx);
} else {
new_children.push(new_leaf_idx);
new_children.push(best_child_idx);
}
let new_internal_idx = self.nodes.len();
let new_internal_max = cmp::max(sibling_order, order);
self.nodes.push(Node {
bounds: sibling_bounds.union(&bounds),
max_order: new_internal_max,
kind: NodeKind::Internal {
children: new_children,
},
});
// Replace the leaf with the new internal in parent
let parent = &mut self.nodes[current_idx];
if let NodeKind::Internal { children } = &mut parent.kind {
let children_len = children.len();
children.indices[best_child_pos] = new_internal_idx;
// If new internal has highest max_order, swap it to the end
// to maintain sorting invariant
if new_internal_max > parent.max_order {
children.indices.swap(best_child_pos, children_len - 1);
}
}
break;
}
} else {
// Best child is internal, continue descent
current_idx = best_child_idx;
}
}
// Propagate bounds and max_order updates up the tree
let mut updated_child_idx = None;
for &node_idx in self.insert_path.iter().rev() {
let node = &mut self.nodes[node_idx];
node.bounds = node.bounds.union(&bounds);
if node.max_order < order {
node.max_order = order;
// Swap updated child to end (skip first iteration since the invariant is already handled by previous cases)
if let Some(child_idx) = updated_child_idx {
if let NodeKind::Internal { children } = &mut node.kind {
if let Some(pos) = children.as_slice().iter().position(|&c| c == child_idx)
{
let last = children.len() - 1;
if pos != last {
children.indices.swap(pos, last);
}
}
}
}
}
updated_child_idx = Some(node_idx);
}
new_leaf_idx
}
}
impl<U> Default for BoundsTree<U>
where
U: Clone + Debug + Default + PartialEq,
{
fn default() -> Self {
BoundsTree {
nodes: Vec::new(),
root: None,
max_leaf: None,
insert_path: Vec::new(),
search_stack: Vec::new(),
}
}
}
@@ -45,20 +45,6 @@ impl<K: Eq, V> VecMap<K, V> {
None => Entry::Vacant(VacantEntry { map: self, key }),
}
}
/// Like [`Self::entry`] but takes its key by reference instead of by value.
///
/// This can be helpful if you have a key where cloning is expensive, as we
/// can avoid cloning the key until a value is inserted under that entry.
pub fn entry_ref<'a, 'k>(&'a mut self, key: &'k K) -> EntryRef<'k, 'a, K, V> {
match self.keys.iter().position(|k| k == key) {
Some(index) => EntryRef::Occupied(OccupiedEntry {
key: &self.keys[index],
value: &mut self.values[index],
}),
None => EntryRef::Vacant(VacantEntryRef { map: self, key }),
}
}
}
pub struct Iter<'a, K, V> {
@@ -406,16 +406,6 @@ pub const fn transparent_black() -> Hsla {
}
}
/// Transparent white in [`Hsla`]
pub const fn transparent_white() -> Hsla {
Hsla {
h: 0.,
s: 0.,
l: 1.,
a: 0.,
}
}
/// Opaque grey in [`Hsla`], values will be clamped to the range [0, 1]
pub const fn opaque_grey(lightness: f32, opacity: f32) -> Hsla {
Hsla {
@@ -477,11 +467,6 @@ pub const fn yellow() -> Hsla {
}
impl Hsla {
/// Converts this HSLA color to an RGBA color.
pub fn to_rgb(self) -> Rgba {
self.into()
}
/// The color red
pub const fn red() -> Self {
red()
@@ -517,11 +502,6 @@ impl Hsla {
self.a == 0.0
}
/// Returns true if the HSLA color is fully opaque, false otherwise.
pub fn is_opaque(&self) -> bool {
self.a == 1.0
}
/// Blends `other` on top of `self` based on `other`'s alpha value. The resulting color is a combination of `self`'s and `other`'s colors.
///
/// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
@@ -778,20 +758,6 @@ impl Default for Background {
}
}
/// Creates a hash pattern background
pub fn pattern_slash(color: impl Into<Hsla>, width: f32, interval: f32) -> Background {
let width_scaled = (width * 255.0) as u32;
let interval_scaled = (interval * 255.0) as u32;
let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;
Background {
tag: BackgroundTag::PatternSlash,
solid: color.into(),
gradient_angle_or_pattern_height: height,
..Default::default()
}
}
/// Creates a checkerboard pattern background
pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
Background {
@@ -802,34 +768,6 @@ pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
}
}
/// Creates a solid background color.
pub fn solid_background(color: impl Into<Hsla>) -> Background {
Background {
solid: color.into(),
..Default::default()
}
}
/// Creates a LinearGradient background color.
///
/// The gradient line's angle of direction. A value of `0.` is equivalent to top; increasing values rotate clockwise from there.
///
/// The `angle` is in degrees value in the range 0.0 to 360.0.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
pub fn linear_gradient(
angle: f32,
from: impl Into<LinearColorStop>,
to: impl Into<LinearColorStop>,
) -> Background {
Background {
tag: BackgroundTag::LinearGradient,
gradient_angle_or_pattern_height: angle,
colors: [from.into(), to.into()],
..Default::default()
}
}
/// A color stop in a linear gradient.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
@@ -842,16 +780,6 @@ pub struct LinearColorStop {
pub percentage: f32,
}
/// Creates a new linear color stop.
///
/// The percentage of the gradient, in the range 0.0 to 1.0.
pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
LinearColorStop {
color: color.into(),
percentage,
}
}
impl LinearColorStop {
/// Returns a new color stop with the same color, but with a modified alpha value.
pub fn opacity(&self, factor: f32) -> Self {
@@ -863,15 +791,6 @@ impl LinearColorStop {
}
impl Background {
/// Returns the solid color if this is a solid background, None otherwise.
pub fn as_solid(&self) -> Option<Hsla> {
if self.tag == BackgroundTag::Solid {
Some(self.solid)
} else {
None
}
}
/// Use specified color space for color interpolation.
///
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
@@ -89,18 +89,6 @@ impl Anchored {
self.position_mode = mode;
self
}
/// Snap to window edge instead of switching anchor corner when an overflow would occur.
pub fn snap_to_window(mut self) -> Self {
self.fit_mode = AnchoredFitMode::SnapToWindow;
self
}
/// Snap to window edge and leave some margins.
pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
self
}
}
impl ParentElement for Anchored {
@@ -18,16 +18,6 @@ pub struct Deferred {
priority: usize,
}
impl Deferred {
/// Sets the `priority` value of the `deferred` element, which
/// determines the drawing order relative to other deferred elements,
/// with higher values being drawn on top.
pub fn with_priority(mut self, priority: usize) -> Self {
self.priority = priority;
self
}
}
impl Element for Deferred {
type RequestLayoutState = ();
type PrepaintState = ();
@@ -1511,37 +1511,11 @@ pub struct Div {
}
impl Div {
/// Add a listener to be called when the children of this `Div` are prepainted.
/// This allows you to store the [`Bounds`] of the children for later use.
pub fn on_children_prepainted(
mut self,
listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
) -> Self {
self.prepaint_listener = Some(Box::new(listener));
self
}
/// Add an image cache at the location of this div in the element tree.
pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
self.image_cache = Some(Box::new(cache));
self
}
/// Specify a function that determines the order in which children are prepainted.
///
/// The function is called at prepaint time and should return a vector of child indices
/// in the desired prepaint order. Each index should appear exactly once.
///
/// This is useful when the prepaint of one child affects state that another child reads.
/// For example, in split editor views, the editor with an autoscroll request should
/// be prepainted first so its scroll position update is visible to the other editor.
pub fn with_dynamic_prepaint_order(
mut self,
order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
) -> Self {
self.prepaint_order_fn = Some(Box::new(order_fn));
self
}
}
/// A frame state for a `Div` element, which contains layout IDs for its children.
@@ -3010,22 +2984,6 @@ impl Interactivity {
}
}
/// Compute the visual style for this element, based on the current bounds and the element's state.
pub fn compute_style(
&self,
global_id: Option<&GlobalElementId>,
hitbox: Option<&Hitbox>,
window: &mut Window,
cx: &mut App,
) -> Style {
window.with_optional_element_state(global_id, |element_state, window| {
let mut element_state =
element_state.map(|element_state| element_state.unwrap_or_default());
let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
(style, element_state)
})
}
/// Called from internal methods that have already called with_element_state.
fn compute_style_internal(
&self,
@@ -3680,25 +3638,7 @@ pub struct ScrollAnchor {
last_origin: Rc<RefCell<Point<Pixels>>>,
}
impl ScrollAnchor {
/// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
pub fn for_handle(handle: ScrollHandle) -> Self {
Self {
handle,
last_origin: Default::default(),
}
}
/// Request scroll to this item on the next frame.
pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
let this = self.clone();
window.on_next_frame(move |_, _| {
let viewport_bounds = this.handle.bounds();
let self_bounds = *this.last_origin.borrow();
this.handle.set_offset(viewport_bounds.origin - self_bounds);
});
}
}
impl ScrollAnchor {}
#[derive(Default, Debug)]
pub(crate) struct ScrollHandleState {
@@ -3753,75 +3693,11 @@ impl ScrollHandle {
self.0.borrow().max_offset
}
/// Get the top child that's scrolled into view.
pub fn top_item(&self) -> usize {
let state = self.0.borrow();
let top = state.bounds.top() - state.offset.borrow().y;
match state.child_bounds.binary_search_by(|bounds| {
if top < bounds.top() {
Ordering::Greater
} else if top > bounds.bottom() {
Ordering::Less
} else {
Ordering::Equal
}
}) {
Ok(ix) => ix,
Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
}
}
/// Get the bottom child that's scrolled into view.
pub fn bottom_item(&self) -> usize {
let state = self.0.borrow();
let bottom = state.bounds.bottom() - state.offset.borrow().y;
match state.child_bounds.binary_search_by(|bounds| {
if bottom < bounds.top() {
Ordering::Greater
} else if bottom > bounds.bottom() {
Ordering::Less
} else {
Ordering::Equal
}
}) {
Ok(ix) => ix,
Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
}
}
/// Return the bounds into which this child is painted
pub fn bounds(&self) -> Bounds<Pixels> {
self.0.borrow().bounds
}
/// Get the bounds for a specific child.
pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
self.0.borrow().child_bounds.get(ix).cloned()
}
/// Update [ScrollHandleState]'s active item for scrolling to in prepaint
pub fn scroll_to_item(&self, ix: usize) {
let mut state = self.0.borrow_mut();
crate::fast::dependencies::StateVersion::bump(&state.version);
state.active_item = Some(ScrollActiveItem {
index: ix,
strategy: ScrollStrategy::default(),
});
}
/// Update [ScrollHandleState]'s active item for scrolling to in prepaint
/// This scrolls the minimal amount to ensure that the child is the first visible element
pub fn scroll_to_top_of_item(&self, ix: usize) {
let mut state = self.0.borrow_mut();
crate::fast::dependencies::StateVersion::bump(&state.version);
state.active_item = Some(ScrollActiveItem {
index: ix,
strategy: ScrollStrategy::Top,
});
}
/// Scrolls the minimal amount to either ensure that the child is
/// fully visible or the top element of the view depends on the
/// scroll strategy
@@ -3878,48 +3754,4 @@ impl ScrollHandle {
let mut state = self.0.borrow_mut();
state.scroll_to_bottom = true;
}
/// Set the offset explicitly. The offset is the distance from the top left of the
/// parent container to the top left of the first child.
/// As you scroll further down the offset becomes more negative.
pub fn set_offset(&self, position: Point<Pixels>) {
let state = self.0.borrow();
*state.offset.borrow_mut() = position;
}
/// Get the logical scroll top, based on a child index and a pixel offset.
pub fn logical_scroll_top(&self) -> (usize, Pixels) {
let ix = self.top_item();
let state = self.0.borrow();
if let Some(child_bounds) = state.child_bounds.get(ix) {
(
ix,
child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
)
} else {
(ix, px(0.))
}
}
/// Get the logical scroll bottom, based on a child index and a pixel offset.
pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
let ix = self.bottom_item();
let state = self.0.borrow();
if let Some(child_bounds) = state.child_bounds.get(ix) {
(
ix,
child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
)
} else {
(ix, px(0.))
}
}
/// Get the count of children for scrollable item.
pub fn children_count(&self) -> usize {
self.0.borrow().child_bounds.len()
}
}
@@ -296,11 +296,6 @@ impl ImageCache for RetainAllImageCache {
}
}
/// Constructs a retain-all image cache that uses the element state associated with the given ID.
pub fn retain_all(id: impl Into<ElementId>) -> RetainAllImageCacheProvider {
RetainAllImageCacheProvider { id: id.into() }
}
/// A provider struct for creating a retain-all image cache inline
pub struct RetainAllImageCacheProvider {
id: ElementId,
@@ -61,13 +61,6 @@ impl Svg {
self.data_path = Some(path);
self
}
/// Transform the SVG element with the given transformation.
/// Note that this won't effect the hitbox or layout of the element, only the rendering.
pub fn with_transformation(mut self, transformation: Transformation) -> Self {
self.transformation = Some(transformation);
self
}
}
impl Element for Svg {
@@ -249,24 +242,6 @@ impl Transformation {
}
}
/// Update the scaling factor of this transformation.
pub fn with_scaling(mut self, scale: Size<f32>) -> Self {
self.scale = scale;
self
}
/// Update the translation value of this transformation.
pub fn with_translation(mut self, translate: Point<Pixels>) -> Self {
self.translate = translate;
self
}
/// Update the rotation angle of this transformation.
pub fn with_rotation(mut self, rotate: impl Into<Radians>) -> Self {
self.rotate = rotate.into();
self
}
fn into_matrix(self, center: Point<Pixels>, scale_factor: f32) -> TransformationMatrix {
//Note: if you read this as a sequence of matrix multiplications, start from the bottom
TransformationMatrix::unit()
@@ -441,30 +441,6 @@ impl StyledText {
runs
}
/// Override the font family for specific byte ranges of the text.
///
/// This is resolved lazily at layout time, so the overrides are applied
/// on top of the inherited text style from the parent element.
/// Can be combined with [`with_highlights`](Self::with_highlights).
///
/// The overrides must be sorted by range start and non-overlapping.
/// Each override range must fall on character boundaries.
pub fn with_font_family_overrides(
mut self,
overrides: impl IntoIterator<Item = (Range<usize>, SharedString)>,
) -> Self {
self.delayed_font_family_overrides = Some(
overrides
.into_iter()
.inspect(|(range, _)| {
debug_assert!(self.text.is_char_boundary(range.start));
debug_assert!(self.text.is_char_boundary(range.end));
})
.collect(),
);
self
}
fn apply_font_family_overrides(
runs: &mut [TextRun],
overrides: &[(Range<usize>, SharedString)],
@@ -728,41 +704,6 @@ impl TextLayout {
None
}
/// Retrieve the layout for the line containing the given byte index.
pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<WrappedLineLayout>> {
let element_state = self.0.borrow();
let element_state = element_state
.as_ref()
.expect("measurement has not been performed");
let mut line_start_ix = 0;
for line in &element_state.lines {
let line_end_ix = line_start_ix + line.len();
if index < line_start_ix {
break;
} else if index > line_end_ix {
line_start_ix = line_end_ix + 1;
continue;
} else {
return Some(line.layout.clone());
}
}
None
}
/// Retrieve all line layouts in source order.
pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {
self.0
.borrow()
.as_ref()
.expect("measurement has not been performed")
.lines
.iter()
.map(|line| line.layout.clone())
.collect()
}
/// The bounds of this layout.
pub fn bounds(&self) -> Bounds<Pixels> {
self.0.borrow().as_ref().unwrap().bounds.unwrap()
@@ -789,29 +730,6 @@ impl TextLayout {
.map(|s| &s.text)
.join("\n")
}
/// The text for this layout (with soft-wraps as newlines)
pub fn wrapped_text(&self) -> String {
let mut accumulator = String::new();
for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
let mut seen = 0;
for boundary in wrapped.layout.wrap_boundaries.iter() {
let index = wrapped.layout.unwrapped_layout.runs[boundary.run_ix].glyphs
[boundary.glyph_ix]
.index;
accumulator.push_str(&wrapped.text[seen..index]);
accumulator.push('\n');
seen = index;
}
accumulator.push_str(&wrapped.text[seen..]);
accumulator.push('\n');
}
// Remove trailing newline
accumulator.pop();
accumulator
}
}
/// A text element that can be interacted with.
@@ -123,14 +123,6 @@ pub(crate) fn global_changed(cx: &mut App, global_type: TypeId) {
cx.dependencies.global_changed(global_type);
}
/// A count that grows with every entity updated, written or changed and
/// every global changed: equal counts taken at two moments saw none of
/// those between them.
pub(crate) fn change_count(cx: &App) -> u64 {
let log = &cx.entities.access_log;
log.update_generation + log.write_generation.get() + cx.dependencies.global_generation
}
/// Stands for whether a global of type `G` is set, which a subtree that
/// only asked [`App::has_global`] depends on rather than on the global.
struct GlobalPresence<G>(std::marker::PhantomData<G>);
@@ -841,20 +833,6 @@ pub(crate) struct Writes {
}
impl Writes {
/// These writes, and those made from `since` to `now` taken for the
/// subtree's own.
fn with_own(&self, since: u64, now: u64) -> Self {
let mut own = self.own.clone();
if now > since {
own.push((since, now));
}
Writes {
from: self.from,
to: self.to,
own,
}
}
/// Whether a write at `written_at` came from outside the subtree after
/// it began.
fn is_foreign(&self, written_at: u64) -> bool {
@@ -910,25 +888,7 @@ impl ReadLogs {
}
}
impl App {
/// The entities read at `spans` of the log of entities read while a
/// recording is open (see [`read_log_lengths`]), sorted and without
/// repeats.
pub(crate) fn entities_read_in(
&mut self,
spans: impl IntoIterator<Item = Range<usize>>,
) -> Rc<[EntityId]> {
let access_log = self.entities.access_log.access_log.borrow();
let scratch = &mut self.dependencies.scratch_entities;
scratch.clear();
for span in spans {
let end = span.end.min(access_log.len());
scratch.extend_from_slice(&access_log[span.start.min(end)..end]);
}
sort_unique(scratch);
self.dependencies.interned_entities.get(scratch)
}
}
impl App {}
/// How far the logs of the entities, globals and states read while a
/// recording is open go, from where no app is at hand, as a `list` being
@@ -1014,20 +974,6 @@ impl StateVersion {
self.0.get()
}
/// Marks the state as changed.
pub(crate) fn bump(&self) {
self.0.set(self.0.get().wrapping_add(1));
}
/// Marks the state as changed if `changed`, for a change that may leave
/// it as it was.
#[inline]
pub(crate) fn bump_if(&self, changed: bool) {
if changed {
self.bump();
}
}
fn ptr(&self) -> *const Cell<u64> {
Rc::as_ptr(&self.0)
}
@@ -1058,31 +1004,6 @@ fn unique_states(states: &[(StateVersion, u64)]) -> Rc<[(StateVersion, u64)]> {
}
impl RenderDependencies {
pub(crate) fn with_entities(&self, entities: Rc<[EntityId]>) -> Self {
Self {
entities,
..self.clone()
}
}
pub(crate) fn entities_only(&self, entities: Rc<[EntityId]>) -> Self {
Self {
entities,
globals: Rc::from([]),
states: Rc::from([]),
generation: self.generation,
updates: self.updates,
writes: self.writes.clone(),
}
}
pub(crate) fn with_own_writes(&self, since: u64, now: u64) -> Self {
Self {
writes: self.writes.with_own(since, now),
..self.clone()
}
}
pub(crate) fn written_up_to(&self, writes: u64) -> Self {
Self {
writes: Writes {
@@ -72,12 +72,6 @@ pub(crate) fn rare<T>(value: T) -> Rare<T> {
Some(Box::new(value))
}
/// A [`Rare`] part holding `value`, if there is one.
#[inline]
pub(crate) fn rare_option<T>(value: Option<T>) -> Rare<T> {
value.map(Box::new)
}
/// A list one pointer wide that allocates nothing while it is empty.
///
/// An [`Interactivity`] holds a score of listener lists, nearly all of them
@@ -374,13 +374,6 @@ enum Claim {
}
impl TaffyLayoutEngine {
/// How many nodes the tree is currently holding, retained and transient
/// alike. Used by tests to check that retention does not leak.
#[cfg(any(test, feature = "harness"))]
pub(crate) fn node_count(&self) -> usize {
self.taffy.total_node_count()
}
/// Takes the node retained under `key` for use in this frame.
fn claim(&mut self, key: Option<u64>) -> Claim {
let Some(key) = key else {
@@ -414,12 +407,6 @@ impl TaffyLayoutEngine {
self.retention.claimed_key_log.len()
}
/// The keys an open recording saw since `start`, where the log was then.
pub(crate) fn claimed_keys_since(&self, start: usize) -> &[u64] {
let log = &self.retention.claimed_key_log;
&log[start.min(log.len())..]
}
/// Ends the recording started at `start`, returning the keys it saw.
pub(crate) fn finish_recording_claimed_keys(&mut self, start: usize) -> Vec<u64> {
let retention = &mut self.retention;
@@ -1228,14 +1215,6 @@ pub(crate) fn laying_out_list_row<R>(window: &mut Window, f: impl FnOnce(&mut Wi
result
}
/// Whether a list row is being laid out: see [`laying_out_list_row`].
pub(crate) fn is_laying_out_list_row(window: &Window) -> bool {
window
.layout_engine
.as_ref()
.is_some_and(|engine| engine.retention.list_rows > 0)
}
/// Treats any `auto` dimension of the given node's style as filling `size`.
/// See [`TaffyLayoutEngine::stretch_auto_size_to_fill`].
///
@@ -37,16 +37,6 @@ pub(crate) fn begin_frame(window: &mut Window, cx: &App) {
window.mark_changed_retained_views_dirty(cx);
}
/// Prepares `window` for an element drawn outside of its frames, as
/// [`crate::VisualTestContext::draw`] draws one. What tells retained subtrees
/// what changed since they were drawn is the window's frames, so nothing is
/// drawn again from an earlier frame.
#[cfg(any(test, feature = "harness"))]
#[inline(always)]
pub(crate) fn draw_outside_frames(window: &mut Window) {
window.refreshing = true;
}
/// Forwarded to by `Window::draw` as it hands the platform this frame's input
/// handler.
pub(crate) fn note_installed_input_handler(window: &mut Window, handler: &PlatformInputHandler) {
@@ -201,10 +201,4 @@ pub(crate) fn track(operation: ClipOperation, active: &mut Vec<Shape>) -> anyhow
}
#[cfg(any(test, feature = "harness"))]
impl Window {
/// The complete rendered scene, including clip scopes and scroll layers,
/// for tests that rasterize through a platform's headless GPU renderer.
pub fn painted_scene(&self) -> &Scene {
&self.rendered_frame.scene
}
}
impl Window {}
@@ -257,50 +257,4 @@ impl Window {
self.layout_engine.as_mut().unwrap().reset_stats();
self.text_system().reset_shaping_stats();
}
/// How many layout nodes this window is currently holding on to.
#[cfg(any(test, feature = "harness"))]
pub fn layout_node_count(&self) -> usize {
self.layout_engine.as_ref().unwrap().node_count()
}
/// The glyphs, icons, images and underlines of the most recently rendered
/// frame, one line each, with their bounds, clip and colour but not their
/// draw order or atlas tile, which two windows painting the same thing
/// may number differently. With [`Window::painted_quads`], for comparing
/// what two windows painted, text included.
#[cfg(any(test, feature = "harness"))]
pub fn painted_sprites(&self) -> Vec<String> {
let scene = &self.rendered_frame.scene;
let mut lines = Vec::new();
lines.extend(scene.underlines.iter().map(|underline| {
format!(
"underline {:?} {:?} {:?} {:?} {:?}",
underline.bounds,
underline.content_mask,
underline.color,
underline.thickness,
underline.wavy
)
}));
lines.extend(scene.monochrome_sprites.iter().map(|sprite| {
format!(
"monochrome {:?} {:?} {:?}",
sprite.bounds, sprite.content_mask, sprite.color
)
}));
lines.extend(scene.subpixel_sprites.iter().map(|sprite| {
format!(
"subpixel {:?} {:?} {:?}",
sprite.bounds, sprite.content_mask, sprite.color
)
}));
lines.extend(scene.polychrome_sprites.iter().map(|sprite| {
format!(
"polychrome {:?} {:?} {:?}",
sprite.bounds, sprite.content_mask, sprite.grayscale
)
}));
lines
}
}
@@ -208,10 +208,6 @@ impl TabStopMap {
self.insertion_history.len()
}
pub(crate) fn tab_stop_count(&self) -> usize {
self.with_index(|index| index.by_id.values().filter(|node| node.tab_stop).count())
}
fn focus_handle_for_order(&self, order: &TabStopNode) -> Option<FocusHandle> {
let handle = self.insertion_history[order.node_insertion_index].focus_handle();
debug_assert!(
@@ -324,18 +324,7 @@ impl Point<Pixels> {
}
}
impl<T> Point<T>
where
T: Sub<T, Output = T> + Clone + Debug + Default + PartialEq,
{
/// Get the position of this point, relative to the given origin
pub fn relative_to(&self, origin: &Point<T>) -> Point<T> {
point(
self.x.clone() - origin.x.clone(),
self.y.clone() - origin.y.clone(),
)
}
}
impl<T> Point<T> where T: Sub<T, Output = T> + Clone + Debug + Default + PartialEq {}
impl<T, Rhs> Mul<Rhs> for Point<T>
where
@@ -1503,19 +1492,9 @@ impl<T: PartialOrd + Add<T, Output = T> + Sub<Output = T> + Clone + Debug + Defa
}
}
impl<T> Bounds<T>
where
T: Add<T, Output = T> + Sub<T, Output = T> + Clone + Debug + Default + PartialEq,
impl<T> Bounds<T> where
T: Add<T, Output = T> + Sub<T, Output = T> + Clone + Debug + Default + PartialEq
{
/// Computes the space available within outer bounds.
pub fn space_within(&self, outer: &Self) -> Edges<T> {
Edges {
top: self.top() - outer.top(),
right: outer.right() - self.right(),
bottom: outer.bottom() - self.bottom(),
left: self.left() - outer.left(),
}
}
}
impl<T, Rhs> Mul<Rhs> for Bounds<T>
@@ -1912,15 +1891,9 @@ where
}
}
impl<T> Bounds<T>
where
T: Add<T, Output = T> + Sub<T, Output = T> + PartialOrd + Clone + Debug + Default + PartialEq,
impl<T> Bounds<T> where
T: Add<T, Output = T> + Sub<T, Output = T> + PartialOrd + Clone + Debug + Default + PartialEq
{
/// Convert a point to the coordinate space defined by this Bounds
pub fn localize(&self, point: &Point<T>) -> Option<Point<T>> {
self.contains(point)
.then(|| point.relative_to(&self.origin))
}
}
/// Checks if the bounds represent an empty area.
@@ -2763,24 +2736,6 @@ impl Anchor {
},
}
}
/// Returns whether the anchor is center-positioned.
#[inline]
pub fn is_center(&self) -> bool {
matches!(
self,
Self::TopCenter | Self::BottomCenter | Self::LeftCenter | Self::RightCenter
)
}
/// Returns whether the anchor is bottom-positioned.
#[inline]
pub fn is_bottom(&self) -> bool {
matches!(
self,
Self::BottomCenter | Self::BottomLeft | Self::BottomRight
)
}
}
/// Represents the corners of a box in a 2D space, such as border radius.
@@ -3503,12 +3458,6 @@ impl Pixels {
self.0
}
/// Converts to `i32`, truncating toward zero.
/// Out-of-range values saturate, and NaN becomes zero.
pub fn to_i32(self) -> i32 {
self.0 as i32
}
/// Floors the `Pixels` value to the nearest whole number.
///
/// # Returns
@@ -3962,10 +3911,6 @@ impl Rems {
pub fn to_pixels(self, rem_size: Pixels) -> Pixels {
self * rem_size
}
/// Convert from pixels to Rem
pub fn from_pixels(length: Pixels, window: &crate::Window) -> Self {
Self(length / window.rem_size())
}
}
impl Mul<Pixels> for Rems {
@@ -4070,22 +4015,6 @@ impl AbsoluteLength {
AbsoluteLength::Rems(rems) => rems.to_pixels(rem_size),
}
}
/// Converts an `AbsoluteLength` to `Rems` based on a given `rem_size`.
///
/// # Arguments
///
/// * `rem_size` - The size of one rem in pixels.
///
/// # Returns
///
/// Returns the `AbsoluteLength` as `Pixels`.
pub fn to_rems(self, rem_size: Pixels) -> Rems {
match self {
AbsoluteLength::Pixels(pixels) => Rems(pixels.0 / rem_size.0),
AbsoluteLength::Rems(rems) => rems,
}
}
}
impl Default for AbsoluteLength {
@@ -19,12 +19,6 @@ pub fn new_std_command(program: impl AsRef<OsStr>) -> std::process::Command {
std::process::Command::new(program)
}
#[inline]
pub const fn is_utf8_char_boundary(u8: u8) -> bool {
// This is bit magic equivalent to: b < 128 || b >= 192
(u8 as i8) >= -0x40
}
pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
let prev = *value;
*value += T::from(1);
@@ -62,15 +56,6 @@ macro_rules! debug_panic {
};
}
#[track_caller]
pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
#[cfg(debug_assertions)]
if option.is_none() {
panic!("Unexpected None");
}
option
}
/// Expands to an immediately-invoked function expression. Good for using the ? operator
/// in functions which do not return an Option or Result.
///
@@ -466,25 +451,3 @@ fn type_id_hasher() {
verify_hashing_with(TypeId::of::<&str>());
verify_hashing_with(TypeId::of::<Vec<u8>>());
}
pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
where
F: Fn(&T, &T) -> std::cmp::Ordering,
{
if limit == 0 {
items.clear();
}
if items.len() <= limit {
items.sort_by(compare);
return;
}
// When limit is near to items.len() it may be more efficient to sort the whole list and
// truncate, rather than always doing selection first as is done below. It's hard to analyze
// where the threshold for this should be since the quickselect style algorithm used by
// `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
// the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
// unsorted input.
items.select_nth_unstable_by(limit, compare);
items.truncate(limit);
items.sort_by(compare);
}
@@ -346,76 +346,6 @@ impl ClickEvent {
}
}
/// Returns if this was a right click
///
/// `Keyboard`: false
/// `Mouse`: Whether the right button was pressed and released
pub fn is_right_click(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => false,
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
}
ClickEvent::Touch(_) => false,
}
}
/// Returns if this was a middle click
///
/// `Keyboard`: false
/// `Mouse`: Whether the middle button was pressed and released
pub fn is_middle_click(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => false,
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Middle && event.up.button == MouseButton::Middle
}
ClickEvent::Touch(_) => false,
}
}
/// Returns whether the click is a secondary activation, i.e. a context
/// menu trigger: a right click from a mouse (macOS ctrl-clicks arrive
/// already converted to right clicks by the platform layer), or a long
/// press on a touch screen.
pub fn is_secondary(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => false,
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
}
ClickEvent::Touch(event) => event.long_press,
}
}
/// Returns whether the click was a standard click
///
/// `Keyboard`: Always true
/// `Mouse`: Left button pressed and released
/// `Touch`: A tap, but not a long press
pub fn standard_click(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => true,
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Left && event.up.button == MouseButton::Left
}
ClickEvent::Touch(event) => !event.long_press,
}
}
/// Returns whether the click focused the element
///
/// `Keyboard`: false, keyboard clicks only work if an element is already focused
/// `Mouse`: Whether this was the first focusing click
/// `Touch`: false, mobile windows are already active when tappable
pub fn first_focus(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => false,
ClickEvent::Mouse(event) => event.down.first_mouse,
ClickEvent::Touch(_) => false,
}
}
/// Returns the click count of the click event
///
/// `Keyboard`: Always 1
@@ -428,14 +358,6 @@ impl ClickEvent {
ClickEvent::Touch(event) => event.tap_count,
}
}
/// Returns whether the click event is generated by a keyboard event
pub fn is_keyboard(&self) -> bool {
match self {
ClickEvent::Mouse(_) | ClickEvent::Touch(_) => false,
ClickEvent::Keyboard(_) => true,
}
}
}
/// An enum representing the keyboard button that was pressed for a click event.
@@ -852,25 +774,6 @@ impl PlatformInput {
}
}
/// A short static name for this input's variant, for diagnostics and
/// telemetry.
pub fn kind_name(&self) -> &'static str {
match self {
PlatformInput::KeyDown(_) => "key_down",
PlatformInput::KeyUp(_) => "key_up",
PlatformInput::ModifiersChanged(_) => "modifiers_changed",
PlatformInput::MouseDown(_) => "mouse_down",
PlatformInput::MouseUp(_) => "mouse_up",
PlatformInput::MousePressure(_) => "mouse_pressure",
PlatformInput::MouseMove(_) => "mouse_move",
PlatformInput::MouseExited(_) => "mouse_exited",
PlatformInput::Scroll(_) => "scroll",
PlatformInput::Pinch(_) => "pinch",
PlatformInput::FileDrop(_) => "file_drop",
PlatformInput::Touch(_) => "touch",
}
}
/// Returns the touch event contained in this input, if any.
pub fn touch_event(&self) -> Option<&TouchEvent> {
match self {
@@ -97,17 +97,6 @@ impl KeyBinding {
})
}
/// Set the metadata for this binding.
pub fn with_meta(mut self, meta: KeyBindingMetaIndex) -> Self {
self.meta = Some(meta);
self
}
/// Set the metadata for this binding.
pub fn set_meta(&mut self, meta: KeyBindingMetaIndex) {
self.meta = Some(meta);
}
/// Check if the given keystrokes match this binding.
pub fn match_keystrokes(&self, typed: &[impl AsKeystroke]) -> Option<bool> {
if self.keystrokes.len() < typed.len() {
@@ -880,18 +880,6 @@ pub struct WindowButtonLayout {
#[cfg(target_os = "linux")]
impl WindowButtonLayout {
/// Returns Zed's built-in fallback button layout for Linux titlebars.
pub fn linux_default() -> Self {
Self {
left: [None; MAX_BUTTONS_PER_SIDE],
right: [
Some(WindowButton::Minimize),
Some(WindowButton::Maximize),
Some(WindowButton::Close),
],
}
}
/// Parses a GNOME-style `button-layout` string (e.g. `"close,minimize:maximize"`).
pub fn parse(layout_string: &str) -> Result<Self> {
fn parse_side(
@@ -975,11 +963,6 @@ impl Tiling {
bottom: true,
}
}
/// Whether any edge is tiled
pub fn is_tiled(&self) -> bool {
self.top || self.left || self.right || self.bottom
}
}
/// The source of a platform frame request's timestamp.
@@ -2119,21 +2102,6 @@ impl PlatformInputHandler {
.unwrap_or(true)
}
/// Checks eligibility against the current focus, including before the next frame is drawn.
///
/// Unlike the legacy acceptance query, this fails closed when the window cannot
/// be updated and requires registration through `Window::handle_input`.
pub fn query_accepts_focused_text_input(&mut self) -> bool {
let focus_id = self.focus_id;
self.cx
.update(|window, cx| {
focus_id.is_some()
&& window.focus == focus_id
&& self.handler.accepts_text_input(window, cx)
})
.unwrap_or(false)
}
/// See [`InputHandler::prefers_ime_for_printable_keys`].
///
/// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
@@ -2982,16 +2950,6 @@ impl ClipboardItem {
}
}
/// Create a new ClipboardItem::String with the given text and associated metadata
pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
Self {
entries: vec![ClipboardEntry::String(ClipboardString {
text,
metadata: Some(metadata),
})],
}
}
/// Create a new ClipboardItem::String with the given text and associated metadata
pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
Self {
@@ -3001,13 +2959,6 @@ impl ClipboardItem {
}
}
/// Create a new ClipboardItem::Image with the given image with no associated metadata
pub fn new_image(image: &Image) -> Self {
Self {
entries: vec![ClipboardEntry::Image(image.clone())],
}
}
/// Concatenates together all the ClipboardString entries in the item.
/// Returns None if there were no ClipboardString entries.
pub fn text(&self) -> Option<String> {
@@ -3051,11 +3002,6 @@ impl ClipboardItem {
pub fn entries(&self) -> &[ClipboardEntry] {
&self.entries
}
/// Get owned versions of the item's entries
pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
self.entries.into_iter()
}
}
impl From<ClipboardString> for ClipboardEntry {
@@ -3281,28 +3227,6 @@ impl Image {
self.id
}
/// Use the GPUI `use_asset` API to make this image renderable
pub fn use_render_image(
self: Arc<Self>,
window: &mut Window,
cx: &mut App,
) -> Option<Arc<RenderImage>> {
ImageSource::Image(self)
.use_data(None, window, cx)
.and_then(|result| result.ok())
}
/// Use the GPUI `get_asset` API to make this image renderable
pub fn get_render_image(
self: Arc<Self>,
window: &mut Window,
cx: &mut App,
) -> Option<Arc<RenderImage>> {
ImageSource::Image(self)
.get_data(None, window, cx)
.and_then(|result| result.ok())
}
/// Use the GPUI `remove_asset` API to drop this image, if possible.
pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
ImageSource::Image(self).remove_asset(cx);
@@ -3377,21 +3301,6 @@ impl ClipboardString {
&self.text
}
/// Get the owned text of the clipboard string
pub fn into_text(self) -> String {
self.text
}
/// Get the metadata of the clipboard string, formatted as JSON
pub fn metadata_json<T>(&self) -> Option<T>
where
T: for<'a> Deserialize<'a>,
{
self.metadata
.as_ref()
.and_then(|m| serde_json::from_str(m).ok())
}
/// Compute a hash of the given text for clipboard change detection.
pub fn text_hash(text: &str) -> u64 {
let mut hasher = SeaHasher::new();
@@ -114,14 +114,6 @@ impl MenuItem {
Self::Submenu(menu)
}
/// Creates a new submenu that is populated by the OS
pub fn os_submenu(name: impl Into<SharedString>, menu_type: SystemMenuType) -> Self {
Self::SystemMenu(OsMenu {
name: name.into(),
menu_type,
})
}
/// Creates a new menu item that invokes an action
pub fn action(name: impl Into<SharedString>, action: impl Action) -> Self {
Self::Action {
@@ -183,17 +175,6 @@ impl MenuItem {
self
}
/// Returns whether this menu item is checked
///
/// Only for [`MenuItem::Action`], otherwise, returns false
#[inline]
pub fn is_checked(&self) -> bool {
match self {
MenuItem::Action { checked, .. } => *checked,
_ => false,
}
}
/// Set whether this menu item is disabled
pub fn disabled(mut self, disabled: bool) -> Self {
match &mut self {
@@ -207,18 +188,6 @@ impl MenuItem {
}
self
}
/// Returns whether this menu item is disabled
///
/// Only for [`MenuItem::Action`] and [`MenuItem::Submenu`], otherwise, returns false
#[inline]
pub fn is_disabled(&self) -> bool {
match self {
MenuItem::Action { disabled, .. } => *disabled,
MenuItem::Submenu(submenu) => submenu.disabled,
_ => false,
}
}
}
/// OS menus are menus that are recognized by the operating system
@@ -101,14 +101,6 @@ fn bind(
}
}
pub(crate) fn raster_nested_tiles(renderer: &mut MetalRenderer, scene: &Scene) {
for sprite in &scene.polychrome_sprites {
if let Some(frame) = group(scene, sprite.tile.texture_id)
&& let Some(child) = frame.content.scene()
{}
}
}
pub(crate) fn draw(
renderer: &mut MetalRenderer,
scene: &Scene,
@@ -148,44 +140,6 @@ pub(crate) fn draw(
Ok(command_buffer)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn draw_tile(
renderer: &mut MetalRenderer,
scene: &Scene,
writer: &mut InstanceBufferWriter,
texture: &ProtocolObject<dyn MTLTexture>,
viewport: Size<DevicePixels>,
commands: &ProtocolObject<dyn MTLCommandBuffer>,
background: MTLClearColor,
surface_textures: &mut Vec<CFRetained<CVMetalTexture>>,
) -> Result<()> {
let old_texture = renderer.path_intermediate_texture.take();
let old_msaa = renderer.path_intermediate_msaa_texture.take();
let result = (|| {
renderer.update_path_intermediate_textures(viewport)?;
let bindings = write_instances(scene, writer)?;
let encoder =
new_command_encoder_for_texture(commands, texture, viewport, Some(background))?;
encode(
renderer,
scene,
&bindings,
writer,
texture,
viewport,
commands,
&mut Vec::new(),
surface_textures,
encoder,
)?
.endEncoding();
Ok(())
})();
renderer.path_intermediate_texture = old_texture;
renderer.path_intermediate_msaa_texture = old_msaa;
result
}
#[allow(clippy::too_many_arguments)]
fn encode(
renderer: &mut MetalRenderer,
@@ -186,20 +186,6 @@ impl MetalRenderer {
Self::new_internal(device, Some(layer), !transparent, instance_buffer_pool)
}
/// Creates a renderer for a CAMetalLayer owned by a platform view, such as
/// the backing layer UIKit creates for a view whose `layerClass` is
/// `CAMetalLayer`. The renderer retains the layer.
pub fn from_layer(
instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
layer: &CAMetalLayer,
transparent: bool,
) -> Result<Self> {
let device = Self::create_device()?;
let layer = layer.retain();
Self::configure_layer(&layer, &device, transparent, false);
Self::new_internal(device, Some(layer), !transparent, instance_buffer_pool)
}
pub(crate) fn configure_layer(
layer: &CAMetalLayer,
device: &ProtocolObject<dyn MTLDevice>,
@@ -231,17 +231,6 @@ impl Keystroke {
}
}
/// Returns true if this keystroke left
/// the ime system in an incomplete state.
pub fn is_ime_in_progress(&self) -> bool {
self.key_char.is_none()
&& (is_printable_key(&self.key) || self.key.is_empty())
&& !(self.modifiers.platform
|| self.modifiers.control
|| self.modifiers.function
|| self.modifiers.alt)
}
/// Returns a new keystroke with the key_char filled.
/// This is used for dispatch_keystroke where we want users to
/// be able to simulate typing "space", etc.
@@ -331,20 +320,10 @@ impl KeybindingKeystroke {
self.inner.modifiers = modifiers;
}
/// Sets the key. On Windows this modifies both `inner.key` and `display_key`.
pub fn set_key(&mut self, key: String) {
self.inner.key = key;
}
/// Serializes this binding with the supplied host OS's modifier spelling.
pub fn unparse(&self, os: OperatingSystem) -> String {
unparse(&self.inner.modifiers, &self.inner.key, os)
}
/// Removes the key_char
pub fn remove_key_char(&mut self) {
self.inner.key_char = None;
}
}
fn is_printable_key(key: &str) -> bool {
@@ -482,21 +461,6 @@ impl Modifiers {
}
}
/// Returns [`Modifiers`] with just the secondary key pressed.
pub fn secondary_key(cx: &crate::App) -> Modifiers {
if cx.platform_info().is_mac() {
Modifiers {
platform: true,
..Default::default()
}
} else {
Modifiers {
control: true,
..Default::default()
}
}
}
/// Returns [`Modifiers`] with just the windows key.
pub fn windows() -> Modifiers {
Modifiers {
@@ -505,14 +469,6 @@ impl Modifiers {
}
}
/// Returns [`Modifiers`] with just the super key.
pub fn super_key() -> Modifiers {
Modifiers {
platform: true,
..Default::default()
}
}
/// Returns [`Modifiers`] with just control.
pub fn control() -> Modifiers {
Modifiers {
@@ -545,15 +501,6 @@ impl Modifiers {
}
}
/// Returns [`Modifiers`] with command + shift.
pub fn command_shift() -> Modifiers {
Modifiers {
shift: true,
platform: true,
..Default::default()
}
}
/// Returns [`Modifiers`] with command + shift.
pub fn control_shift() -> Modifiers {
Modifiers {
@@ -1,83 +0,0 @@
use bitflags::bitflags;
use thiserror::Error;
use crate::Pixels;
/// The layer the surface is rendered on. Multiple surfaces can share a layer, and ordering within
/// a single layer is undefined.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum Layer {
/// The background layer, typically used for wallpapers.
Background,
/// The bottom layer.
Bottom,
/// The top layer, typically used for fullscreen windows.
Top,
/// The overlay layer, used for surfaces that should always be on top.
#[default]
Overlay,
}
bitflags! {
/// Screen anchor point for layer_shell surfaces. These can be used in any combination, e.g.
/// specifying `Anchor::LEFT | Anchor::RIGHT` will stretch the surface across the width of the
/// screen.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct Anchor: u32 {
/// Anchor to the top edge of the screen.
const TOP = 1;
/// Anchor to the bottom edge of the screen.
const BOTTOM = 2;
/// Anchor to the left edge of the screen.
const LEFT = 4;
/// Anchor to the right edge of the screen.
const RIGHT = 8;
}
}
/// Keyboard interactivity mode for the layer_shell surfaces.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum KeyboardInteractivity {
/// No keyboard inputs will be delivered to the surface and it won't be able to receive
/// keyboard focus.
None,
/// The surface will receive exclusive keyboard focus as long as it is above the shell surface
/// layer, and no other layer_shell surfaces are above it.
Exclusive,
/// The surface can be focused similarly to a normal window.
#[default]
OnDemand,
}
/// Options for creating a layer_shell window.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LayerShellOptions {
/// The namespace for the surface, mostly used by compositors to apply rules, can not be
/// changed after the surface is created.
pub namespace: String,
/// The layer the surface is rendered on.
pub layer: Layer,
/// The anchor point of the surface.
pub anchor: Anchor,
/// Requests that the compositor avoids occluding an area with other surfaces.
pub exclusive_zone: Option<Pixels>,
/// The anchor point of the exclusive zone, will be determined using the anchor if left
/// unspecified.
pub exclusive_edge: Option<Anchor>,
/// Margins between the surface and its anchor point(s).
/// Specified in CSS order: top, right, bottom, left.
pub margin: Option<(Pixels, Pixels, Pixels, Pixels)>,
/// How keyboard events should be delivered to the surface.
pub keyboard_interactivity: KeyboardInteractivity,
}
/// An error indicating that an action failed because the compositor doesn't support the required
/// layer_shell protocol.
#[derive(Debug, Error)]
#[error("Compositor doesn't support zwlr_layer_shell_v1")]
pub struct LayerShellNotSupportedError;
@@ -321,57 +321,6 @@ impl ThreadedDispatcher {
ran_any
}
#[cfg(test)]
pub(crate) fn run_until_with_frames<R>(
&self,
mut ready: impl FnMut() -> Option<R>,
mut dispatch_frames: impl FnMut() -> bool,
) -> R {
assert!(
self.is_main_thread(),
"main tasks must run on the main thread"
);
loop {
if let Some(result) = ready() {
return result;
}
let ran_task = self.run_one_main_task();
// A completion poll must not pull an unrelated animation frame
// into the measured operation.
if let Some(result) = ready() {
return result;
}
let dispatched_frames = dispatch_frames();
if ran_task || dispatched_frames {
continue;
}
let mut inflight = self.idle.inflight.lock();
if self.main_queue_has_work() {
continue;
}
self.idle.condvar.wait(&mut inflight);
}
}
/// Cancels all pending timers so timers armed by one workload can't fire
/// during a later workload sharing this process-lifetime dispatcher.
///
/// Dropping a timer runnable drops its completion sender, waking the task
/// awaiting the timer. Call [`Self::run_until_idle`] after this method to
/// drain any work that cancellation unblocks.
pub fn cancel_pending_timers(&self) -> usize {
let timers = {
let mut state = self.timers.state.lock();
let timers: Vec<_> = state.heap.drain().collect();
self.timers.condvar.notify_all();
timers
};
let canceled = timers.len();
drop(timers);
canceled
}
/// Describes the dispatcher's idle-tracking state, for diagnosing
/// workloads that fail to reach quiescence.
pub fn debug_state(&self) -> String {
@@ -384,14 +333,6 @@ impl ThreadedDispatcher {
)
}
/// Whether no main-thread work is queued, no background or timer
/// runnables are queued or running, and no armed timer is due. Timers
/// that aren't due yet are ignored, as in [`Self::run_until_idle`].
#[cfg(test)]
pub(crate) fn is_idle(&self) -> bool {
!self.main_queue_has_work() && !self.has_due_timer() && *self.idle.inflight.lock() == 0
}
fn has_due_timer(&self) -> bool {
let state = self.timers.state.lock();
state
@@ -109,6 +109,10 @@ impl TouchIds {
fn end(&mut self, pointer_id: i32) -> Option<TouchId> {
self.active.remove(&pointer_id)
}
pub(crate) fn is_empty(&self) -> bool {
self.active.is_empty()
}
}
impl WebWindowInner {
@@ -834,7 +834,9 @@ impl PlatformWindow for WebWindow {
TextInputStateChange::FocusGained => self.inner.show_virtual_keyboard(),
TextInputStateChange::FocusLost => self.hide_soft_keyboard(),
TextInputStateChange::SelectionChanged | TextInputStateChange::ContentChanged => {
if self.inner.pressed_button.get().is_none() {
if self.inner.pressed_button.get().is_none()
&& self.inner.touch_ids.borrow().is_empty()
{
self.inner.schedule_ime_mirror_sync();
}
}
@@ -852,7 +854,9 @@ impl PlatformWindow for WebWindow {
self.inner.ime_mirror.set_read_only(true);
}
TextInputStateChange::SelectionChanged | TextInputStateChange::ContentChanged => {
if self.inner.pressed_button.get().is_none() {
if self.inner.pressed_button.get().is_none()
&& self.inner.touch_ids.borrow().is_empty()
{
self.inner.schedule_ime_mirror_sync();
}
}
@@ -560,13 +560,23 @@ impl CosmicTextSystemState {
fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
let image = self.render_glyph_image(params)?;
let bounds = Bounds {
origin: point(image.placement.left.into(), (-image.placement.top).into()),
size: size(image.placement.width.into(), image.placement.height.into()),
};
if !bounds.is_zero() {
self.pending_glyph_images.insert(params.clone(), image);
if image.placement.width == 0 || image.placement.height == 0 {
return Ok(Bounds::default());
}
// Pad non-empty glyph tiles with a 1px transparent gutter on every side so bilinear
// sampling under zoomed/rotated transforms never clips edge coverage or bleeds into
// adjacent atlas tiles.
let bounds = Bounds {
origin: point(
(image.placement.left - 1).into(),
(-image.placement.top - 1).into(),
),
size: size(
(image.placement.width + 2).into(),
(image.placement.height + 2).into(),
),
};
self.pending_glyph_images.insert(params.clone(), image);
Ok(bounds)
}
fn rasterize_glyph(
@@ -583,21 +593,40 @@ impl CosmicTextSystemState {
None => self.render_glyph_image(params)?,
};
let bitmap_size = glyph_bounds.size;
let pad_bitmap = |src: &[u8], src_w: usize, src_h: usize, bpp: usize| -> Vec<u8> {
let dst_w = bitmap_size.width.0 as usize;
let dst_h = bitmap_size.height.0 as usize;
let mut out = vec![0u8; dst_w * dst_h * bpp];
let copy_w = src_w.min(dst_w.saturating_sub(2));
let copy_h = src_h.min(dst_h.saturating_sub(2));
let src_stride = src_w * bpp;
let dst_stride = dst_w * bpp;
let row_bytes = copy_w * bpp;
for y in 0..copy_h {
let src_off = y * src_stride;
let dst_off = (y + 1) * dst_stride + bpp;
out[dst_off..dst_off + row_bytes]
.copy_from_slice(&src[src_off..src_off + row_bytes]);
}
out
};
let src_w = image.placement.width as usize;
let src_h = image.placement.height as usize;
match image.content {
swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
// Convert from RGBA to BGRA.
for pixel in image.data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
Ok((bitmap_size, image.data))
Ok((bitmap_size, pad_bitmap(&image.data, src_w, src_h, 4)))
}
swash::scale::image::Content::Mask => {
if params.subpixel_rendering {
// We must always return RGBA data when subpixel rendering is requested.
let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
Ok((bitmap_size, expanded))
let expanded: Vec<u8> = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
Ok((bitmap_size, pad_bitmap(&expanded, src_w, src_h, 4)))
} else {
Ok((bitmap_size, image.data))
Ok((bitmap_size, pad_bitmap(&image.data, src_w, src_h, 1)))
}
}
}
@@ -620,7 +649,7 @@ impl CosmicTextSystemState {
.swash_scale_context
.builder(font_ref)
.size(pixel_size * params.scale_factor)
.hint(true)
.hint(params.subpixel_rendering)
.normalized_coords(&loaded_font.normalized_coords)
.build();
@@ -364,19 +364,6 @@ impl WgpuRenderer {
)
}
#[cfg(target_family = "wasm")]
pub fn new_from_canvas(
context: &WgpuContext,
canvas: &web_sys::HtmlCanvasElement,
config: WgpuSurfaceConfig,
) -> anyhow::Result<Self> {
let surface = context
.instance
.create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
.map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?;
Self::new_from_surface(context, surface, config)
}
#[cfg(target_family = "wasm")]
#[allow(clippy::arc_with_non_send_sync)]
pub fn new_from_surface(
@@ -24,11 +24,6 @@ impl TestClock {
}))
}
pub fn set_utc_now(&self, now: crate::scheduler::fast::clock::UtcTime) {
let mut state = self.0.lock();
state.utc_now = now;
}
pub fn advance(&self, duration: Duration) {
let mut state = self.0.lock();
state.now += duration;
@@ -592,11 +592,6 @@ impl<T> Task<T> {
)
}
/// Creates a Task from an async_task::Task
pub fn from_async_task(task: async_task::Task<T, RunnableMeta>) -> Self {
Task(TaskState::Spawned(task))
}
pub fn is_ready(&self) -> bool {
match &self.0 {
TaskState::Ready(_) => true,
@@ -10,17 +10,6 @@ pub use test_scheduler::*;
static TEST_SCHEDULER_CREATED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
/// Whether this process has created a [`TestScheduler`].
///
/// Test harnesses create one before the test body runs, and applications never
/// do. Code with no executor at hand, such as expensive data-structure invariant
/// checks, can use this to run only in test processes. Code that has an
/// executor should prefer [`BackgroundExecutor::is_test`], which is correct per
/// executor.
pub fn test_scheduler_created() -> bool {
TEST_SCHEDULER_CREATED.load(std::sync::atomic::Ordering::Relaxed)
}
use async_task::Runnable;
use futures::channel::oneshot;
use std::{
@@ -184,19 +184,6 @@ impl TestScheduler {
}
}
pub fn end_test(&self) {
let mut state = self.state.lock();
if let Some((message, backtrace)) = &state.non_determinism_error {
if cfg!(miri) {
// miri cannot debug print backtraces with `miri-disable-isolation` enabled
panic!("{}", message)
} else {
panic!("{}\n{:?}", message, backtrace)
}
}
state.finished = true;
}
pub fn clock(&self) -> Arc<TestClock> {
self.clock.clone()
}
@@ -205,20 +192,12 @@ impl TestScheduler {
SharedRng(self.rng.clone())
}
pub fn set_timeout_ticks(&self, timeout_ticks: RangeInclusive<usize>) {
self.state.lock().timeout_ticks = timeout_ticks;
}
pub fn allow_parking(&self) {
let mut state = self.state.lock();
state.allow_parking = true;
state.parking_allowed_once = true;
}
pub fn forbid_parking(&self) {
self.state.lock().allow_parking = false;
}
pub fn parking_allowed(&self) -> bool {
self.state.lock().allow_parking
}
@@ -248,27 +227,12 @@ impl TestScheduler {
BackgroundExecutor::new(self.clone())
}
pub fn yield_random(&self) -> Yield {
let rng = &mut *self.rng.lock();
if rng.random_bool(0.1) {
Yield(rng.random_range(10..20))
} else {
Yield(rng.random_range(0..2))
}
}
pub fn run(&self) {
while self.step() {
// Continue until no work remains
}
}
pub fn run_with_clock_advancement(&self) {
while self.step() || self.advance_clock_to_next_timer() {
// Continue until no work remains
}
}
/// Execute one tick of the scheduler, processing expired timers and running
/// at most one task. Returns true if any work was done.
///
@@ -277,35 +241,12 @@ impl TestScheduler {
self.step_filtered(false)
}
/// Execute one tick, but only run background tasks (no foreground/session tasks).
/// Returns true if any work was done.
pub fn tick_background_only(&self) -> bool {
self.step_filtered(true)
}
/// Check if there are any pending tasks or timers that could run.
pub fn has_pending_tasks(&self) -> bool {
let state = self.state.lock();
!state.runnables.is_empty() || !state.timers.is_empty()
}
/// Returns counts of (foreground_tasks, background_tasks) currently queued.
/// Foreground tasks are those with a session_id, background tasks have none.
pub fn pending_task_counts(&self) -> (usize, usize) {
let state = self.state.lock();
let foreground = state
.runnables
.iter()
.filter(|r| r.session_id.is_some())
.count();
let background = state
.runnables
.iter()
.filter(|r| r.session_id.is_none())
.count();
(foreground, background)
}
fn step(&self) -> bool {
self.step_filtered(false)
}
@@ -417,28 +358,6 @@ impl TestScheduler {
false
}
/// Drops all runnable tasks from the scheduler.
///
/// This is used by the leak detector to ensure that all tasks have been dropped as tasks may keep entities alive otherwise.
/// Why do we even have tasks left when tests finish you may ask. The reason for that is simple, the scheduler itself is the executor and it retains the scheduled runnables.
/// A lot of tasks, including every foreground task contain an executor handle that keeps the test scheduler alive, causing a reference cycle, thus the need for this function right now.
pub fn drain_tasks(&self) {
// dropping runnables may reschedule tasks
// due to drop impls with executors in them
// so drop until we reach a fixpoint
loop {
let mut state = self.state.lock();
if state.runnables.is_empty() && state.timers.is_empty() {
break;
}
let runnables = std::mem::take(&mut state.runnables);
let timers = std::mem::take(&mut state.timers);
drop(state);
drop(timers);
drop(runnables);
}
}
pub fn advance_clock_to_next_timer(&self) -> bool {
if let Some(timer) = self.state.lock().timers.first() {
self.clock.advance(timer.expiration - self.clock.now());
@@ -2281,13 +2281,6 @@ impl Hash for HighlightStyle {
}
impl Style {
/// Returns true if the style is visible and the background is opaque.
pub fn has_opaque_background(&self) -> bool {
self.background
.as_ref()
.is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
}
/// Get the text style in this element style.
pub fn text_style(&self) -> Option<&TextStyleRefinement> {
if self.text.is_some() {
@@ -2901,49 +2894,6 @@ impl From<Rgba> for HighlightStyle {
}
}
/// Combine and merge the highlights and ranges in the two iterators.
pub fn combine_highlights(
a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
let mut endpoints = Vec::new();
let mut highlights = Vec::new();
for (range, highlight) in a.into_iter().chain(b) {
if !range.is_empty() {
let highlight_id = highlights.len();
endpoints.push((range.start, highlight_id, true));
endpoints.push((range.end, highlight_id, false));
highlights.push(highlight);
}
}
endpoints.sort_unstable_by_key(|(position, _, _)| *position);
let mut endpoints = endpoints.into_iter().peekable();
let mut active_styles = HashSet::default();
let mut ix = 0;
iter::from_fn(move || {
while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
let prev_index = mem::replace(&mut ix, *endpoint_ix);
if ix > prev_index && !active_styles.is_empty() {
let current_style = active_styles
.iter()
.fold(HighlightStyle::default(), |acc, highlight_id| {
acc.highlight(highlights[*highlight_id])
});
return Some((prev_index..ix, current_style));
}
if *is_start {
active_styles.insert(*highlight_id);
} else {
active_styles.remove(highlight_id);
}
endpoints.next();
}
None
})
}
/// Used to control how child nodes are aligned.
/// For Flexbox it controls alignment in the cross axis
/// For Grid it controls alignment in the block axis
File diff suppressed because it is too large. Load diff
@@ -1,182 +0,0 @@
use std::fmt::Debug;
use crate::collections::FxHashMap;
use crate::{FocusHandle, FocusId};
/// Represents a collection of focus handles using the tab-index APIs.
///
/// Every focusable element is inserted on every frame, while the tab order is only needed
/// when the user moves focus with tab. So insertion just appends the node, and the nodes
/// are sorted in place the first time the order is needed after an insertion.
#[derive(Debug, Default)]
pub(crate) struct TabStopMap {
current_path: TabStopPath,
pub(crate) insertion_history: Vec<TabStopOperation>,
/// Index into `nodes` of each focus handle's most recent insertion.
by_id: FxHashMap<FocusId, usize>,
nodes: Vec<TabStopNode>,
sorted: bool,
}
#[derive(Debug, Clone)]
pub enum TabStopOperation {
Insert(FocusHandle),
Group(TabIndex),
GroupEnd,
}
impl TabStopOperation {
fn focus_handle(&self) -> Option<&FocusHandle> {
match self {
TabStopOperation::Insert(focus_handle) => Some(focus_handle),
_ => None,
}
}
}
type TabIndex = isize;
#[derive(Debug, Default, PartialEq, Eq, Clone, Ord, PartialOrd)]
struct TabStopPath(smallvec::SmallVec<[TabIndex; 6]>);
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct TabStopNode {
/// Path to access the node in the tree
/// The final node in the list is a leaf node corresponding to an actual focus handle,
/// all other nodes are group nodes
path: TabStopPath,
/// index into the backing array of nodes. Corresponds to insertion order
node_insertion_index: usize,
/// Whether this node is a tab stop
tab_stop: bool,
}
impl Ord for TabStopNode {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.path
.cmp(&other.path)
.then(self.node_insertion_index.cmp(&other.node_insertion_index))
}
}
impl PartialOrd for TabStopNode {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(&other))
}
}
impl TabStopMap {
pub fn insert(&mut self, focus_handle: &FocusHandle) {
self.insertion_history
.push(TabStopOperation::Insert(focus_handle.clone()));
let mut path = self.current_path.clone();
path.0.push(focus_handle.tab_index);
self.by_id.insert(focus_handle.id, self.nodes.len());
self.sorted = false;
self.nodes.push(TabStopNode {
node_insertion_index: self.insertion_history.len() - 1,
tab_stop: focus_handle.tab_stop,
path,
});
}
pub fn begin_group(&mut self, tab_index: isize) {
self.insertion_history
.push(TabStopOperation::Group(tab_index));
self.current_path.0.push(tab_index);
}
pub fn end_group(&mut self) {
self.insertion_history.push(TabStopOperation::GroupEnd);
self.current_path.0.pop();
}
pub fn clear(&mut self) {
self.current_path.0.clear();
self.insertion_history.clear();
self.by_id.clear();
self.nodes.clear();
self.sorted = false;
}
pub fn next(&mut self, focused_id: Option<&FocusId>) -> Option<FocusHandle> {
self.ensure_sorted();
let start = focused_id
.and_then(|id| self.by_id.get(id))
.map_or(0, |position| position + 1);
let node = self.nodes[start..]
.iter()
.chain(&self.nodes[..start])
.find(|node| node.tab_stop)?;
self.focus_handle_for_order(node)
}
pub fn prev(&mut self, focused_id: Option<&FocusId>) -> Option<FocusHandle> {
self.ensure_sorted();
let end = focused_id
.and_then(|id| self.by_id.get(id).copied())
.unwrap_or(self.nodes.len());
let node = self.nodes[..end]
.iter()
.rev()
.chain(self.nodes[end..].iter().rev())
.find(|node| node.tab_stop)?;
self.focus_handle_for_order(node)
}
fn ensure_sorted(&mut self) {
if self.sorted {
return;
}
// Nodes never compare equal, since their insertion indices differ, so an unstable
// sort gives the same order as a stable one without allocating a scratch buffer.
self.nodes.sort_unstable();
self.by_id.clear();
for (position, node) in self.nodes.iter().enumerate() {
let Some(focus_handle) = self
.insertion_history
.get(node.node_insertion_index)
.and_then(TabStopOperation::focus_handle)
else {
continue;
};
let latest = self.by_id.entry(focus_handle.id).or_insert(position);
if self.nodes[*latest].node_insertion_index < node.node_insertion_index {
*latest = position;
}
}
self.sorted = true;
}
pub fn replay(&mut self, nodes: &[TabStopOperation]) {
for node in nodes {
match node {
TabStopOperation::Insert(focus_handle) => self.insert(focus_handle),
TabStopOperation::Group(tab_index) => self.begin_group(*tab_index),
TabStopOperation::GroupEnd => self.end_group(),
}
}
}
pub fn paint_index(&self) -> usize {
self.insertion_history.len()
}
pub(crate) fn tab_stop_count(&self) -> usize {
self.by_id
.values()
.filter(|index| self.nodes.get(**index).is_some_and(|node| node.tab_stop))
.count()
}
fn focus_handle_for_order(&self, order: &TabStopNode) -> Option<FocusHandle> {
let handle = self.insertion_history[order.node_insertion_index].focus_handle();
debug_assert!(
handle.is_some(),
"The order node did not correspond to an element, this is a GPUI bug"
);
handle.cloned()
}
}
@@ -306,37 +306,6 @@ impl TextSystem {
Ok(())
}
/// Takes the receiver for missing-glyph reports.
///
/// Only one receiver is available for each text system. Returns `None` when
/// the receiver was already taken or another caller is taking it.
pub(crate) fn take_missing_glyph_receiver(&self) -> Option<MissingGlyphReceiver> {
self.missing_glyph_receiver
.try_lock()
.and_then(|mut receiver| receiver.take())
}
pub(crate) fn enable_missing_glyph_reporting(&self) {
self.platform_text_system
.set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
}
pub(crate) fn disable_missing_glyph_reporting(&self) {
self.platform_text_system.set_missing_glyph_sink(None);
self.missing_glyph_reporter.reset();
}
/// Get the Font for the Font Id.
pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
let lock = self.font_ids_by_font.read();
lock.iter()
.filter_map(|(font, result)| match result {
CachedFont::Direct(font_id) if *font_id == id => Some(font.clone()),
_ => None,
})
.next()
}
/// Resolves the specified font, falling back to the default font stack if
/// the font fails to load.
///
@@ -432,20 +401,6 @@ impl TextSystem {
crate::fast::em_metrics::em_advance(self, font_id, font_size)
}
/// Returns the width of an `ch`.
///
/// Uses the width of the `0` character in the given font and size.
pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
}
/// Returns the advance width of an `ch`.
///
/// Uses the advance width of the `0` character in the given font and size.
pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
Ok(self.advance(font_id, font_size, '0')?.width)
}
/// Get the number of font size units per 'em square',
/// Per MDN: "an abstract square whose height is the intended distance between
/// lines of type in the same type size"
@@ -954,11 +909,6 @@ impl WindowTextSystem {
)
.width
}
/// Returns the shaped layout width of an `em`.
pub fn em_layout_width(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.layout_width(font_id, font_size, 'm')
}
}
#[derive(Hash, Eq, PartialEq)]
@@ -1291,20 +1241,3 @@ pub fn font_name_with_fallbacks<'a>(name: &'a str, system: &'a str) -> &'a str {
_ => name,
}
}
/// Like [`font_name_with_fallbacks`] but accepts and returns [`SharedString`] references.
#[allow(unused)]
pub fn font_name_with_fallbacks_shared<'a>(
name: &'a SharedString,
system: &'a SharedString,
) -> &'a SharedString {
// Note: the "Zed Plex" fonts were deprecated as we are not allowed to use "Plex"
// in a derived font name. They are essentially indistinguishable from IBM Plex/Lilex,
// and so retained here for backward compatibility.
match name.as_str() {
".SystemUIFont" => system,
".ZedSans" | "Zed Plex Sans" => const { &SharedString::new_static("IBM Plex Sans") },
".ZedMono" | "Zed Plex Mono" => const { &SharedString::new_static("Lilex") },
_ => name,
}
}
@@ -11,9 +11,4 @@ impl FontFallbacks {
pub fn fallback_list(&self) -> &[String] {
self.0.as_slice()
}
/// Create a font fallback from a list of strings
pub fn from_fonts(fonts: Vec<String>) -> Self {
FontFallbacks(Arc::new(fonts))
}
}
@@ -15,26 +15,11 @@ impl Default for FontFeatures {
}
impl FontFeatures {
/// Disables `calt`.
pub fn disable_ligatures() -> Self {
Self(Arc::new(vec![("calt".into(), 0)]))
}
/// Get the tag name list of the font OpenType features
/// only enabled or disabled features are returned
pub fn tag_value_list(&self) -> &[(String, u32)] {
self.0.as_slice()
}
/// Returns whether the `calt` feature is enabled.
///
/// Returns `None` if the feature is not present.
pub fn is_calt_enabled(&self) -> Option<bool> {
self.0
.iter()
.find(|(feature, _)| feature == "calt")
.map(|(_, value)| *value == 1)
}
}
impl std::fmt::Debug for FontFeatures {
@@ -278,104 +278,6 @@ pub struct ShapedLineCursor<'a> {
}
impl<'a> ShapedLineCursor<'a> {
/// Takes the bytes since the previous boundary.
///
/// Panics if the boundary precedes the previous one, exceeds the line's
/// length, or falls inside a UTF-8 character.
pub fn take_until(&mut self, byte_index: usize) -> ShapedLine {
assert!(
byte_index >= self.byte_index,
"split boundary moved backwards"
);
assert!(
byte_index <= self.line.len(),
"split boundary exceeds line length"
);
assert!(
self.line.text.is_char_boundary(byte_index),
"split boundary is not a UTF-8 character boundary"
);
let previous_index = self.byte_index;
let previous_x = self.x_offset;
if let Some(remainder) = &mut self.unordered_remainder {
let (piece, rest) = remainder.split_at(byte_index - previous_index);
*remainder = rest;
self.byte_index = byte_index;
self.x_offset = self.line.layout.x_for_index(byte_index);
return piece;
}
let mut runs = Vec::new();
let mut next_x = self.line.layout.width;
while let Some(run) = self.line.layout.runs.get(self.run_index) {
let start = self.glyph_index;
while let Some(glyph) = run.glyphs.get(self.glyph_index) {
if glyph.index >= byte_index {
break;
}
self.glyph_index += 1;
}
let end = self.glyph_index;
if start < end {
runs.push(crate::ShapedRun {
font_id: run.font_id,
glyphs: run.glyphs[start..end]
.iter()
.map(|glyph| crate::ShapedGlyph {
id: glyph.id,
position: point(glyph.position.x - previous_x, glyph.position.y),
index: glyph.index - previous_index,
is_emoji: glyph.is_emoji,
})
.collect(),
});
}
if let Some(glyph) = run.glyphs.get(self.glyph_index) {
next_x = glyph.position.x;
break;
}
self.run_index += 1;
self.glyph_index = 0;
}
let mut decorations = SmallVec::new();
while let Some(decoration) = self.line.decoration_runs.get(self.decoration_index)
&& (self.decoration_offset < byte_index as u32
|| (decoration.len == 0 && self.decoration_offset == byte_index as u32))
{
let end = self.decoration_offset + decoration.len;
let start = self.decoration_offset.max(previous_index as u32);
let len = end.min(byte_index as u32) - start;
if len > 0 || decoration.len == 0 {
decorations.push(DecorationRun {
len,
color: decoration.color,
background_color: decoration.background_color,
underline: decoration.underline,
strikethrough: decoration.strikethrough,
});
}
if end <= byte_index as u32 {
self.decoration_index += 1;
self.decoration_offset = end;
} else {
break;
}
}
self.byte_index = byte_index;
self.x_offset = next_x;
ShapedLine {
layout: Arc::new(LineLayout {
font_size: self.line.layout.font_size,
width: next_x - previous_x,
ascent: self.line.layout.ascent,
descent: self.line.layout.descent,
runs,
len: byte_index - previous_index,
}),
text: SharedString::new(&self.line.text[previous_index..byte_index]),
decoration_runs: decorations,
}
}
/// Returns the original line's x position at the current boundary.
pub fn x_offset(&self) -> Pixels {
self.x_offset
@@ -135,18 +135,6 @@ impl LineLayout {
self.width
}
/// The corresponding Font at the given index
pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
for run in &self.runs {
for glyph in &run.glyphs {
if glyph.index >= index {
return Some(run.font_id);
}
}
}
None
}
/// Split this layout at a byte index, returning `(prefix, suffix)`.
///
/// - `prefix` contains glyphs for bytes `[0, byte_index)` with original positions.
@@ -576,15 +576,6 @@ impl FocusHandle {
self.id.contains(other.id, window)
}
/// Obtains whether the element associated with this handle is part of the most recently rendered frame.
pub fn is_rendered(&self, window: &Window) -> bool {
window
.rendered_frame
.dispatch_tree
.focusable_node_id(self.id)
.is_some()
}
/// Dispatch an action on the element that rendered this focus handle
pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
if let Some(node_id) = window
@@ -819,17 +810,6 @@ impl Hitbox {
self.id.is_hovered(window)
}
/// Checks whether this hitbox would be hovered at `position`, regardless of the current input
/// modality or mouse position.
pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
let hit_test = window.rendered_frame.hit_test(position);
hit_test
.ids
.iter()
.take(hit_test.hover_hitbox_count)
.any(|id| self.id == *id)
}
/// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
/// should only be used when handling `ScrollEvent`, and otherwise `is_hovered` should be
/// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
@@ -2435,17 +2415,6 @@ impl Window {
.and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
}
/// While focus-lost listeners are being dispatched, returns the closest ancestor of the
/// previously focused element that can still receive focus, making it a suitable target
/// for focus restoration. Returns `None` at all other times, or when no such ancestor exists.
pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
ancestors.iter().rev().find_map(|id| {
self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
FocusHandle::for_id(*id, &cx.focus_handles)
})
}
/// Move focus to the element associated with the given [`FocusHandle`].
pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
if !self.focus_enabled || self.focus == Some(handle.id) {
@@ -2474,12 +2443,6 @@ impl Window {
self.refresh();
}
/// Blur the window and don't allow anything in it to be focused again.
pub fn disable_focus(&mut self, cx: &mut App) {
self.blur(cx);
self.focus_enabled = false;
}
/// Move focus to next tab stop.
pub fn focus_next(&mut self, cx: &mut App) {
if !self.focus_enabled {
@@ -2491,17 +2454,6 @@ impl Window {
}
}
/// Move focus to previous tab stop.
pub fn focus_prev(&mut self, cx: &mut App) {
if !self.focus_enabled {
return;
}
if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
self.focus(&handle, cx)
}
}
/// Accessor for the text system.
pub fn text_system(&self) -> &Rc<WindowTextSystem> {
&self.text_system
@@ -2773,20 +2725,6 @@ impl Window {
self.on_next_frame(move |_, cx| cx.notify(entity));
}
/// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran.
///
/// Tests have no platform frame loop, so this simulates the delivery of the
/// next frame.
#[cfg(any(test, feature = "harness"))]
pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
let callbacks = self.next_frame_callbacks.take();
let count = callbacks.len();
for callback in callbacks {
callback(self, cx);
}
count
}
/// Spawn the future returned by the given closure on the application thread pool.
/// The closure is provided a handle to the current window and an `AsyncWindowContext` for
/// use within your future.
@@ -2931,21 +2869,6 @@ impl Window {
/// Borrows the most recently rendered frame's scene, so benchmarks can validate their
/// output and report batch counts without cloning it.
/// Returns the quads in the most recently rendered frame's scene, so tests can assert on
/// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are
/// not clipped; each quad carries the content mask it will be clipped to when drawn. Quads
/// whose bounds don't intersect their content mask are culled at paint time and won't appear.
#[cfg(any(test, feature = "harness"))]
pub fn painted_quads(&self) -> Vec<Quad> {
self.rendered_frame.scene.quads.clone()
}
/// Returns the underlines in the most recently rendered frame's scene.
#[cfg(any(test, feature = "harness"))]
pub fn painted_underlines(&self) -> Vec<Underline> {
self.rendered_frame.scene.underlines.clone()
}
/// Set the content size of the window.
pub fn resize(&mut self, size: Size<Pixels>) {
self.platform_window.resize(size);
@@ -2996,24 +2919,6 @@ impl Window {
self.platform_window.visual_viewport_bounds()
}
/// Returns a conservative rectangle avoiding platform-known obscured content.
///
/// Intersects the visual viewport with the full layout area inset by system
/// safe areas and keyboard occlusion. Unknown overlays cannot be excluded.
pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
let insets = self.platform_window.insets().effective();
let viewport = self.viewport_size();
let left = insets.left.max(Pixels::ZERO).min(viewport.width);
let top = insets.top.max(Pixels::ZERO).min(viewport.height);
let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
visible.size.width = visible.size.width.max(Pixels::ZERO);
visible.size.height = visible.size.height.max(Pixels::ZERO);
visible
}
/// Requests the virtual keyboard for the currently focused text input.
///
/// Call from a user gesture on platforms that require one. The platform may
@@ -3022,11 +2927,6 @@ impl Window {
self.platform_window.show_soft_keyboard();
}
/// Requests dismissal of the virtual keyboard without changing GPUI focus.
pub fn dismiss_virtual_keyboard(&self) {
self.platform_window.hide_soft_keyboard();
}
/// Returns whether this window is focused by the operating system (receiving key events).
pub fn is_window_active(&self) -> bool {
self.active.get()
@@ -3043,11 +2943,6 @@ impl Window {
}
}
/// Toggle zoom on the window.
pub fn zoom_window(&self) {
self.platform_window.zoom();
}
/// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
pub fn show_window_menu(&self, position: Point<Pixels>) {
self.platform_window.show_window_menu(position)
@@ -3097,11 +2992,6 @@ impl Window {
self.platform_window.window_controls()
}
/// Updates the window's title at the platform level.
pub fn set_window_title(&mut self, title: &str) {
self.platform_window.set_title(title);
}
/// Sets the position of the macOS traffic light buttons.
#[cfg(target_os = "macos")]
pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
@@ -3125,11 +3015,6 @@ impl Window {
.set_background_appearance(background_appearance);
}
/// Mark the window as dirty at the platform level.
pub fn set_window_edited(&mut self, edited: bool) {
self.platform_window.set_edited(edited);
}
/// Set the path of the file this window represents.
/// On macOS, this sets the window's accessibility document property (AXDocument).
pub fn set_document_path(&self, path: Option<&std::path::Path>) {
@@ -3156,13 +3041,6 @@ impl Window {
self.scale_factor
}
/// Overrides the display scale factor for tests.
#[cfg(any(test, feature = "harness"))]
pub fn set_scale_factor(&mut self, scale_factor: f32) {
self.scale_factor = scale_factor;
self.refresh();
}
/// The size of an em for the base font of the application. Adjusting this value allows the
/// UI to scale, just like zooming a web page.
pub fn rem_size(&self) -> Pixels {
@@ -3238,19 +3116,6 @@ impl Window {
px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
}
/// f64 variant of [`Self::pixel_snap`].
#[inline]
pub fn pixel_snap_f64(&self, value: f64) -> f64 {
let scale_factor = f64::from(self.scale_factor());
round_half_toward_zero_f64(value * scale_factor) / scale_factor
}
/// Snaps a bounds' origin and size to the nearest device pixel.
#[inline]
pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
bounds.map(|c| self.pixel_snap(c))
}
/// Snaps a point's coordinates to the nearest device pixel.
#[inline]
pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
@@ -3277,63 +3142,6 @@ impl Window {
}
}
/// Paints an underline excluding absolute device-space horizontal spans.
pub fn paint_underline_with_exclusions(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &UnderlineStyle,
exclusions: &[Range<ScaledPixels>],
) {
self.invalidator.debug_assert_paint();
let underline = self.underline(origin, width, style);
if exclusions.is_empty() || underline.transformation != TransformationMatrix::unit() {
self.next_frame.scene.insert_primitive(underline);
return;
}
let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
if bounds.is_empty() {
return;
}
let mut exclusions = exclusions
.iter()
.filter_map(|span| {
let start = span.start.max(bounds.left());
let end = span.end.min(bounds.right());
(start < end).then_some(start..end)
})
.collect::<SmallVec<[_; 4]>>();
if exclusions.is_empty() {
self.next_frame.scene.insert_primitive(underline);
return;
}
exclusions.sort_unstable_by_key(|span| span.start);
let mut paint_span = |start, end| {
self.next_frame.scene.insert_primitive(Underline {
content_mask: ContentMask {
bounds: Bounds::from_corners(
point(start, bounds.top()),
point(end, bounds.bottom()),
),
},
..underline
});
};
let mut start = bounds.left();
for exclusion in exclusions {
if start < exclusion.start {
paint_span(start, exclusion.start);
}
start = start.max(exclusion.end);
}
if start < bounds.right() {
paint_span(start, bounds.right());
}
}
fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
Underline {
order: 0,
@@ -3417,54 +3225,17 @@ impl Window {
.is_action_available(action, node_id)
}
/// Determine whether the given action is available along the dispatch path to the given focus_handle.
pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
self.rendered_frame
.dispatch_tree
.is_action_available(action, node_id)
}
/// The position of the mouse relative to the window.
pub fn mouse_position(&self) -> Point<Pixels> {
crate::fast::dependencies::read_pointer(self);
self.mouse_position
}
/// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
/// events will be routed to listeners that check this hitbox's `is_hovered` status,
/// regardless of actual hit testing. This enables drag operations that continue
/// even when the pointer moves outside the element's bounds.
///
/// The capture is automatically released on mouse up.
pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
self.captured_hitbox = Some(hitbox_id);
}
/// Releases any active pointer capture.
pub fn release_pointer(&mut self) {
self.captured_hitbox = None;
}
/// Returns the hitbox that has captured the pointer, if any.
pub fn captured_hitbox(&self) -> Option<HitboxId> {
self.captured_hitbox
}
/// Captures the current long press for the given entity.
///
/// The capture is released when the gesture ends or is cancelled, or when
/// a replacement touch begins. A listener must also call
/// [`Self::prevent_default`] on the started event to claim the gesture.
pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
self.long_press_capture = Some(entity.entity_id());
}
/// Returns whether the given entity has captured the current long press.
pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
self.long_press_capture == Some(entity.entity_id())
}
/// The current state of the keyboard's modifiers
pub fn modifiers(&self) -> Modifiers {
crate::fast::dependencies::read_keys(self);
@@ -4285,51 +4056,6 @@ impl Window {
result
}
/// Perform prepaint on child elements in a "retryable" manner, so that any side effects
/// of prepaints can be discarded before prepainting again. This is used to support autoscroll
/// where we need to prepaint children to detect the autoscroll bounds, then adjust the
/// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
/// called during the prepaint phase of element drawing.
pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
self.invalidator.debug_assert_prepaint();
let index = self.prepaint_index();
let result = f(self);
if result.is_err() {
self.next_frame.hitboxes.truncate(index.hitboxes_index);
self.next_frame
.tooltip_requests
.truncate(index.tooltips_index);
self.next_frame
.deferred_draws
.truncate(index.deferred_draws_index);
self.next_frame
.dispatch_tree
.truncate(index.dispatch_tree_index);
self.next_frame
.accessed_element_states
.truncate(index.accessed_element_states_index);
self.text_system.truncate_layouts(index.line_layout_index);
}
result
}
/// When you call this method during [`Element::prepaint`], containing elements will attempt to
/// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
/// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
/// that supports this method being called on the elements it contains. This method should only be
/// called during the prepaint phase of element drawing.
pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll = Some(bounds);
}
/// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
/// described in [`Self::request_autoscroll`].
pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll.take()
}
/// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
/// Your view will be re-drawn once the asset has finished loading.
///
@@ -4379,19 +4105,6 @@ impl Window {
})
}
/// Provide elements in the called function with a new namespace in which their identifiers must be unique.
/// This can be used within a custom element to distinguish multiple sets of child elements.
pub fn with_element_namespace<R>(
&mut self,
element_id: impl Into<ElementId>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.element_id_stack.push(element_id.into());
let result = f(self);
self.element_id_stack.pop();
result
}
/// Use a piece of state that exists as long this element is being rendered in consecutive frames.
pub fn use_keyed_state<S: 'static>(
&mut self,
@@ -5304,21 +5017,6 @@ impl Window {
Ok(())
}
/// Returns whether every frame of an image is present in the sprite atlas.
#[cfg(any(test, feature = "harness"))]
pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
data.frame_count() > 0
&& (0..data.frame_count()).all(|frame_index| {
self.sprite_atlas.contains(
&RenderImageParams {
image_id: data.id,
frame_index,
}
.into(),
)
})
}
/// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
/// layout is being requested, along with the layout ids of any children. This method is called during
/// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
@@ -5718,21 +5416,6 @@ impl Window {
false
}
/// Return a key binding string for an action, to display in the UI. Uses the highest precedence
/// binding for the action (last binding added to the keymap).
pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
self.highest_precedence_binding_for_action(action)
.map(|binding| {
binding
.keystrokes()
.iter()
.map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
.collect::<Vec<_>>()
.join(" ")
})
.unwrap_or_else(|| action.name().to_string())
}
/// Dispatch a mouse, keyboard, or touch event on the window.
pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
let update_count_before = self.invalidator.update_count();
@@ -5914,13 +5597,6 @@ impl Window {
self.touch_prediction_enabled
}
/// Sets whether recognized touch pans may use the platform's predicted
/// touch positions. Disabling drops [`TouchEvent::predicted_position`]
/// before gesture recognition, so pans track only raw touch positions.
pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
self.touch_prediction_enabled = enabled;
}
/// Runs the portable gesture recognizer over a raw touch event and
/// dispatches whatever it resolves (scroll steps, synthesized taps)
/// through the ordinary mouse-event path.
@@ -6335,88 +6011,6 @@ impl Window {
})
}
/// Pauses or resumes the current pending input timeout on behalf of `owner`.
///
/// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
/// state changed. A timeout paused by one owner cannot be resumed by another.
pub fn set_pending_input_timeout_paused<T: 'static>(
&mut self,
owner: &Entity<T>,
paused: bool,
cx: &mut App,
) -> bool {
let owner_id = owner.entity_id();
if !paused {
return self.resume_pending_input_timeout(owner_id, cx);
}
let timeout = self
.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_ref());
let Some(timeout) = timeout else {
return false;
};
if timeout.is_paused() {
return false;
}
let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
window.resume_pending_input_timeout(owner_id, cx);
});
let now = cx.background_executor().now();
let changed = self
.pending_input
.as_mut()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| {
timeout.pause(
PendingInputTimeoutPause {
owner_id,
_release_subscription: release_subscription,
},
now,
)
});
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
let Some(remaining) = self
.pending_input
.as_ref()
.and_then(|pending_input| pending_input.timeout.as_ref())
.filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
.map(|timeout| timeout.remaining)
else {
return false;
};
let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
let changed = self
.pending_input
.as_mut()
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
/// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
self.pending_input()
.map(|pending_input| pending_input.keystrokes())
}
fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
@@ -6611,11 +6205,6 @@ impl Window {
self.platform_window.request_attention();
}
/// Minimize the current window at the platform level.
pub fn minimize_window(&self) {
self.platform_window.minimize();
}
/// Toggle full screen status on the current window at the platform level.
pub fn toggle_fullscreen(&self) {
self.platform_window.toggle_fullscreen();
@@ -6751,62 +6340,6 @@ impl Window {
)
}
/// Returns the key bindings for an action in a context.
pub fn bindings_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.bindings_for_action(action, &[context])
}
/// Returns the highest precedence key binding for an action in a context. This is more
/// efficient than getting the last result of `bindings_for_action_in_context`.
pub fn highest_precedence_binding_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.highest_precedence_binding_for_action(action, &[context])
}
/// Returns any bindings that would invoke an action on the given focus handle if it were
/// focused. Bindings are returned in the order they were added. For display, the last binding
/// should take precedence.
pub fn bindings_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
return vec![];
};
dispatch_tree.bindings_for_action(action, &context_stack)
}
/// Returns the highest precedence key binding that would invoke an action on the given focus
/// handle if it were focused. This is more efficient than getting the last result of
/// `bindings_for_action_in`.
pub fn highest_precedence_binding_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
}
/// Find the bindings that can follow the current input sequence for the current context stack.
pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
self.rendered_frame
.dispatch_tree
.possible_next_bindings_for_input(input, &self.context_stack())
}
fn context_stack_for_focus_handle(
&self,
focus_handle: &FocusHandle,
@@ -6821,43 +6354,6 @@ impl Window {
Some(context_stack)
}
/// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
pub fn listener_for<T: 'static, E>(
&self,
view: &Entity<T>,
f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
let view = view.downgrade();
move |e: &E, window: &mut Window, cx: &mut App| {
view.update(cx, |view, cx| f(view, e, window, cx)).ok();
}
}
/// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
&self,
entity: &Entity<E>,
f: Callback,
) -> impl Fn(&mut Window, &mut App) + 'static {
let entity = entity.downgrade();
move |window: &mut Window, cx: &mut App| {
entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
}
}
/// Register a callback that can interrupt the closing of the current window based the returned boolean.
/// If the callback returns false, the window won't be closed.
pub fn on_window_should_close(
&self,
cx: &App,
f: impl Fn(&mut Window, &mut App) -> bool + 'static,
) {
let mut cx = self.to_async(cx);
self.platform_window.on_should_close(Box::new(move || {
cx.update(|window, cx| f(window, cx)).unwrap_or(true)
}))
}
/// Register an action listener on this node for the next frame. The type of action
/// is determined by the first parameter of the given listener. When the next frame is rendered
/// the listener will be cleared.
@@ -6878,29 +6374,6 @@ impl Window {
.on_action(action_type, Rc::new(listener));
}
/// Register a capturing action listener on this node for the next frame if the condition is true.
/// The type of action is determined by the first parameter of the given listener. When the next
/// frame is rendered the listener will be cleared.
///
/// This is a fairly low-level method, so prefer using action handlers on elements unless you have
/// a specific need to register a listener yourself.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_action_when(
&mut self,
condition: bool,
action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
if condition {
self.next_frame
.dispatch_tree
.on_action(action_type, Rc::new(listener));
}
}
/// Read information about the GPU backing this window.
/// Currently returns None on Mac and Windows.
pub fn gpu_specs(&self) -> Option<GpuSpecs> {
@@ -6914,12 +6387,6 @@ impl Window {
.titlebar_double_click(self.is_resizable, self.is_minimizable);
}
/// Gets the window's title at the platform level.
/// This is macOS specific.
pub fn window_title(&self) -> String {
self.platform_window.get_title()
}
/// Returns a list of all tabbed windows and their titles.
/// This is macOS specific.
pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
@@ -7001,19 +6468,6 @@ impl Window {
self.modifiers = modifiers;
}
/// For testing: simulate a mouse move event to the given position.
/// This dispatches the event through the normal event handling path,
/// which will trigger hover states and tooltips.
#[cfg(any(test, feature = "harness"))]
pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
let event = PlatformInput::MouseMove(MouseMoveEvent {
position,
modifiers: self.modifiers,
pressed_button: None,
});
let _ = self.dispatch_event(event, cx);
}
#[inline(never)]
fn take_element_state(
&mut self,
@@ -7317,13 +6771,6 @@ pub enum ElementId {
OpaqueId([u8; 20]),
}
impl ElementId {
/// Constructs an `ElementId::NamedInteger` from a name and `usize`.
pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
Self::NamedInteger(name.into(), integer as u64)
}
}
impl Display for ElementId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@@ -1,17 +1 @@
[
{
"metric": "artifacts_bytes.web_wasm_raw",
"accepted_value": 16437138,
"reason": "The web editor bundles collaborative page editing, Edgeless camera controls and vector rendering for whiteboard shapes, connectors, strokes and labels"
},
{
"metric": "artifacts_bytes.web_wasm_gzip",
"accepted_value": 5515823,
"reason": "The compressed web editor includes collaborative page editing, Edgeless camera controls and vector rendering for whiteboard shapes, connectors, strokes and labels"
},
{
"metric": "artifacts_bytes.headless_bin",
"accepted_value": 96400733,
"reason": "Includes the slash menu, formatting toolbar, drag handle, interactive block controls and their state renders and demo recorder in the headless renderer"
}
]
[]
@@ -53,6 +53,112 @@ if [ -n "$TESTER_CFG_HITS" ]; then
fail "Inline harness/test cfg branches are forbidden in crates/playground/src/lib.rs and main.rs"
fi
echo "==> Checking Rust module structure, visibility, orphaned files, and per-file LOC"
python3 - <<'PY'
import re
import sys
from pathlib import Path
errors = []
roots = [Path("crates/doc/src"), Path("crates/playground/src")]
def strip_cfg_test_mods(src: str) -> str:
"""Remove `#[cfg(test)] mod <name> { ... }` blocks while preserving line numbers."""
lines = src.splitlines()
out = []
i = 0
n = len(lines)
while i < n:
s = lines[i].strip()
if s == "#[cfg(test)]" and i + 1 < n and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()):
depth = 0
started = False
out.append("")
i += 1
while i < n:
line = lines[i]
if "{" in line:
started = True
depth += line.count("{") - line.count("}")
out.append("")
i += 1
if started and depth <= 0:
break
continue
out.append(lines[i])
i += 1
return "\n".join(out)
for src_root in roots:
rs_files = sorted(src_root.rglob("*.rs"))
declared_modules = set()
# Root entry points are always live.
for entry in ("lib.rs", "main.rs"):
if (src_root / entry).exists():
declared_modules.add((src_root / entry).resolve())
for bin_file in (src_root / "bin").glob("*.rs") if (src_root / "bin").exists() else []:
declared_modules.add(bin_file.resolve())
for bin_main in (src_root / "bin").glob("*/main.rs") if (src_root / "bin").exists() else []:
declared_modules.add(bin_main.resolve())
mod_decl_re = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;")
for p in rs_files:
text = p.read_text(encoding="utf-8")
parent = p.parent
# Track declared child modules for orphan detection.
for line in text.splitlines():
m = mod_decl_re.match(line)
if m:
mod_name = m.group(1)
base_dir = parent if p.name in ("lib.rs", "main.rs", "mod.rs") else parent / p.stem
cand_file = base_dir / f"{mod_name}.rs"
cand_mod = base_dir / mod_name / "mod.rs"
if cand_file.exists():
declared_modules.add(cand_file.resolve())
if cand_mod.exists():
declared_modules.add(cand_mod.resolve())
# Rule (g): no `<mod_name>.rs` coexisting beside `<mod_name>/`.
if p.name not in ("lib.rs", "main.rs", "mod.rs") and (parent / p.stem).is_dir():
errors.append(f"{p}: coexists beside directory {parent / p.stem}/; move into {parent / p.stem}/mod.rs")
non_test = strip_cfg_test_mods(text)
non_test_lines = non_test.splitlines()
# Rule (c): no `super::super::` outside `mod tests`.
for lineno, line in enumerate(non_test_lines, 1):
if "super::super::" in line:
errors.append(f"{p}:{lineno}: forbidden `super::super::` outside `mod tests`")
# Rules (b, c): sibling `src/<mod>/<child>.rs` must not import via `crate::<mod>::`.
rel = p.relative_to(src_root)
if len(rel.parts) >= 2 and p.name != "mod.rs" and rel.parts[0] != "bin":
parent_mod = rel.parts[0]
pat = f"crate::{parent_mod}::"
for lineno, line in enumerate(non_test_lines, 1):
if pat in line:
errors.append(f"{p}:{lineno}: use `super::` instead of `{pat}` inside submodule")
# Rule (g): <= 800 non-test lines on `crates/playground/src/{edgeless,surface}/*.rs`.
if src_root == Path("crates/playground/src") and len(rel.parts) >= 2 and rel.parts[0] in ("edgeless", "surface"):
actual_non_test = sum(
1 for orig, stripped in zip(text.splitlines(), non_test_lines) if orig == stripped
)
if actual_non_test > 800:
errors.append(f"{p}: {actual_non_test} non-test lines exceeds ceiling of 800")
# Orphaned .rs file check.
for p in rs_files:
if p.resolve() not in declared_modules:
errors.append(f"{p}: orphaned .rs file not declared by any `mod <name>;`")
if errors:
for e in errors:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
print("Rust module structure & LOC checks passed.")
PY
echo "==> Checking crates/ui LOC ceiling"
UI_LOC_CEILING=95000
UI_LOC=$(find crates/ui/src -name '*.rs' -print0 | xargs -0 cat | wc -l | tr -d ' ')
@@ -225,7 +225,7 @@ async function waitForDevToolsWs(chromeProc) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for Chromium DevTools URL. stderr:\n${stderrBuf}`));
}, 15000);
}, 45000);
chromeProc.stderr.on('data', (chunk) => {
stderrBuf += chunk.toString();
const match = stderrBuf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
@@ -241,6 +241,30 @@ async function waitForDevToolsWs(chromeProc) {
});
}
async function launchChromiumWithRetry(chromeBin, chromeArgs) {
let lastErr = null;
for (let attempt = 1; attempt <= 2; attempt += 1) {
const chromeProc = spawn(chromeBin, chromeArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, DBUS_SESSION_BUS_ADDRESS: 'disabled:' },
});
try {
const browserWsUrl = await waitForDevToolsWs(chromeProc);
return { chromeProc, browserWsUrl };
} catch (err) {
lastErr = err;
try {
chromeProc.kill('SIGKILL');
} catch {}
if (attempt < 2) {
console.warn(`Chromium startup attempt ${attempt} failed, retrying once: ${err.message}`);
await sleep(500);
}
}
}
throw lastErr;
}
class CdpClient {
constructor(wsUrl) {
this.ws = new WebSocket(wsUrl);
@@ -450,6 +474,9 @@ async function main() {
'--no-sandbox',
'--disable-gpu-sandbox',
'--disable-dev-shm-usage',
'--disable-background-networking',
'--no-first-run',
'--no-default-browser-check',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
@@ -459,12 +486,11 @@ async function main() {
'--remote-debugging-port=0',
'about:blank',
];
const chromeProc = spawn(chromeBin, chromeArgs, { stdio: ['ignore', 'pipe', 'pipe'] });
const { chromeProc, browserWsUrl } = await launchChromiumWithRetry(chromeBin, chromeArgs);
const errors = [];
const consoleLogs = [];
try {
const browserWsUrl = await waitForDevToolsWs(chromeProc);
const browserPort = new URL(browserWsUrl).port;
const targetsResp = await fetch(`http://127.0.0.1:${browserPort}/json/list`);
const targets = await targetsResp.json();
@@ -609,6 +635,26 @@ async function main() {
}
if (!args.query) {
// Exercise Edgeless bottom creation toolbar: select Shape tool (`s`) and drag a new shape on canvas.
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: 640, y: 400, button: 'left', clickCount: 1 });
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 640, y: 400, button: 'left', clickCount: 1 });
await sleep(100);
for (const type of ['rawKeyDown', 'keyUp']) {
await cdp.send('Input.dispatchKeyEvent', { type, key: 's', code: 'KeyS', windowsVirtualKeyCode: 83 });
}
await sleep(100);
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: 520, y: 300, button: 'left', clickCount: 1 });
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 680, y: 400, button: 'left', buttons: 1 });
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 680, y: 400, button: 'left', clickCount: 1 });
await sleep(300);
const shotShape = await cdp.send('Page.captureScreenshot', { format: 'png' });
const imgShape = decodePngRgba(Buffer.from(shotShape.data, 'base64'));
const shapeDiff = countDifferentPixels(img2, imgShape);
console.log(`Web Wasm Edgeless shape creation diffPixels=${shapeDiff}`);
if (shapeDiff < 100) {
throw new Error(`Edgeless shape creation produced insufficient visual change (${shapeDiff})`);
}
// Also verify direct `?mode=edgeless` cold load without WebGL2/WebGPU shader errors.
await cdp.send('Page.navigate', { url: `http://127.0.0.1:${port}/?mode=edgeless` });
let edgelessDirectInk = 0;
@@ -9,6 +9,7 @@ import { TextSelection } from '@blocksuite/affine/std';
import { BlockSchemaExtension, Schema, Text } from '@blocksuite/affine/store';
import { TestWorkspace } from '@blocksuite/affine/store/test';
import { MemoryBlobSource } from '@blocksuite/affine/sync';
import { generateKeyBetween } from 'fractional-indexing';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import * as Y from 'yjs';
@@ -1338,4 +1339,286 @@ describe('Rust bs-relay + WorkspaceSession <-> JS BlockSuite TestWorkspace', ()
await driver.quit();
});
it('Live multi-peer Page <-> Edgeless soak: concurrent shape/connector/brush/note + CJK + Undo/Redo + fractional-indexing parity', async () => {
const room = 'room-edgeless-soak';
const rustClientId = 2 ** 44 + 77;
const jsClientId = 2 ** 44 + 88;
const driver = new RustDriver(relayHttp, room, rustClientId);
await driver.waitReady();
// 1. 15-step base-62 fractional-indexing parity against JS generateKeyBetween.
const fiPairs: Array<[string | null, string | null]> = [
[null, null],
['a0', null],
['a1', null],
[null, 'a0'],
[null, 'Zz'],
['a0', 'a1'],
['a0', 'a0V'],
['a0V', 'a1'],
['a0', 'a0G'],
['az', null],
['aZ', null],
['a9', null],
['b00', null],
['Zz', 'a0'],
['a0', 'a2'],
];
for (const [a, b] of fiPairs) {
const expected = generateKeyBetween(a, b);
const res = await driver.call<{ ok: boolean; key: string }>({
cmd: 'generate_key_between',
a,
b,
});
expect(res.ok).toBe(true);
expect(res.key).toBe(expected);
}
// 2. Seed initial page with surface and connect live JS peer in the same room.
await driver.call({
cmd: 'seed_full_schema',
page_id: 'doc:home',
title: 'Edgeless Soak',
});
const roomClient = new RoomWebSocketClient(
`${relayWsBase}/native-sync/rooms/${room}`
);
const workspace = new TestWorkspace({
id: room,
docSources: { main: roomClient.createDocSource() },
awarenessSources: [roomClient.createAwarenessSource()],
blobSources: {
main: new MemoryBlobSource(),
shadows: [new MockServerBlobSource(room, relayHttp)],
},
});
workspace.storeExtensions = AffineSchemas.map(s => BlockSchemaExtension(s));
workspace.doc.clientID = jsClientId;
workspace.awarenessStore.awareness.clientID = jsClientId;
workspace.start();
await vi.waitFor(
() => {
expect(workspace.getDoc('doc:home')).not.toBeNull();
},
{ timeout: 10_000 }
);
const doc = workspace.getDoc('doc:home')!;
doc.spaceDoc.clientID = jsClientId;
doc.getStore({ id: 'doc:home' }).load();
await workspace.waitForSynced();
// Track any unexpected JS writebacks on initial load.
let jsWritebacks = 0;
doc.spaceDoc.on('update', (_update: Uint8Array, origin: unknown) => {
if (origin === null) {
jsWritebacks += 1;
}
});
// 3. Native authors Shape, rotates it, adds orthogonal Connector, draws Brush, creates Note + CJK text.
await driver.call({
cmd: 'add_shape',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-shape-1',
index: 'a2',
shape_type: 'rect',
xywh: '[100,120,180,110]',
text: 'Native Box',
now_ms: 1000,
});
await driver.call({
cmd: 'update_shape_rotate',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-shape-1',
rotate: 30,
now_ms: 2000,
});
await driver.call({
cmd: 'add_connector',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-conn-1',
index: 'a3',
source_id: 'el-shape',
target_id: 'native-shape-1',
now_ms: 3000,
});
await driver.call({
cmd: 'splice_surface_element_text',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-conn-1',
field: 'text',
utf16_start: 0,
utf16_delete_len: 0,
insert: 'Link',
now_ms: 3200,
});
await driver.call({
cmd: 'commit_connector_label',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-conn-1',
trimmed_text: 'Link',
label_xywh: [120, 140, 64, 24],
now_ms: 3300,
});
await driver.call({
cmd: 'add_brush',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-brush-1',
index: 'a4',
xywh: '[20,20,80,40]',
points: [
[0, 0],
[40, 20],
[80, 40],
],
now_ms: 4000,
});
await driver.call({
cmd: 'update_brush_points',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-brush-1',
points: [
[0, 0],
[80, 40],
[160, 80],
],
now_ms: 4100,
});
await driver.call({
cmd: 'update_connector_label_xywh',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'native-conn-1',
label_xywh: [140, 155, 64, 24],
now_ms: 4200,
});
await driver.call({
cmd: 'add_note_with_text',
page_id: 'doc:home',
root_id: 'page-1',
note_id: 'native-note-1',
para_id: 'native-para-1',
xywh: [400, 100, 320, 140],
text: '你好,世界!',
now_ms: 5000,
});
// 4. Concurrently JS edits paragraph p-1 and prepends 'X ' to el-shape's Y.Text while Native splices '!' at the end.
doc.spaceDoc.transact(() => {
const yBlocks = doc.spaceDoc.getMap('blocks');
const p1 = yBlocks.get('p-1') as Y.Map<unknown>;
const yText = p1.get('prop:text') as Y.Text;
yText.insert(yText.length, ' [js-concurrent]');
const surf = yBlocks.get('surface-1') as Y.Map<unknown>;
const elems = (surf.get('prop:elements') as Y.Map<unknown>).get(
'value'
) as Y.Map<unknown>;
const elShape = elems.get('el-shape') as Y.Map<unknown>;
const shapeText = elShape.get('text') as Y.Text;
shapeText.insert(0, 'X ');
}, 'js-user');
await driver.call({
cmd: 'splice_surface_element_text',
page_id: 'doc:home',
surface_id: 'surface-1',
element_id: 'el-shape',
field: 'text',
utf16_start: 5,
utf16_delete_len: 0,
insert: '!',
now_ms: 6000,
});
// 5. Native performs Undo (undoes '!') and Redo (restores '!'); JS concurrent edit MUST survive!
await driver.call({ cmd: 'drain', wait_ms: 200 });
await driver.call({ cmd: 'undo', page_id: 'doc:home' });
await driver.call({ cmd: 'drain', wait_ms: 150 });
await driver.call({ cmd: 'redo', page_id: 'doc:home' });
// 6. Verify live JS model semantics: displayMode === 'edgeless', connector labelXYWH & labelOffset, concurrent label splice.
await vi.waitFor(
async () => {
await driver.call({ cmd: 'drain', wait_ms: 100 });
const yBlocks = doc.spaceDoc.getMap('blocks');
const noteMap = yBlocks.get('native-note-1') as Y.Map<unknown>;
expect(noteMap?.get('prop:displayMode')).toBe('edgeless');
const surf = yBlocks.get('surface-1') as Y.Map<unknown>;
const elems = (surf.get('prop:elements') as Y.Map<unknown>).get(
'value'
) as Y.Map<unknown>;
const conn = elems.get('native-conn-1') as Y.Map<unknown>;
expect(conn?.get('labelXYWH')).toEqual([140, 155, 64, 24]);
expect(normalizeYValue(conn?.get('labelOffset'))).toEqual({
anchor: 'center',
distance: 0.5,
});
const brush = elems.get('native-brush-1') as Y.Map<unknown>;
expect(brush?.get('points')).toEqual([
[0, 0],
[80, 40],
[160, 80],
]);
const elShape = elems.get('el-shape') as Y.Map<unknown>;
expect((elShape?.get('text') as Y.Text)?.toString()).toBe('X Shape!');
},
{ timeout: 15_000, interval: 200 }
);
// 7. Native cascade-deletes native-shape-1; attached native-conn-1 must also be removed.
await driver.call({
cmd: 'delete_with_connectors',
page_id: 'doc:home',
block_ids: [],
surface_elements: [['surface-1', 'native-shape-1']],
now_ms: 7000,
});
// 8. Assert L0 byte-equivalent CRDT convergence (StateVector + DeleteSet + normalized JSON) and 0 JS writebacks.
await vi.waitFor(
async () => {
await driver.call({ cmd: 'drain', wait_ms: 100 });
const rustState = await driver.call<{
stateVector: Record<string, number>;
fullUpdateV1: number[];
docJson: { blocks: Record<string, Record<string, unknown>> };
}>({ cmd: 'export_state', page_id: 'doc:home' });
expect(rustState.stateVector).toEqual(
exportJsStateVector(doc.spaceDoc)
);
expect(
exportDeleteSetFromUpdate(new Uint8Array(rustState.fullUpdateV1))
).toEqual(exportJsDeleteSet(doc.spaceDoc));
expect(rustState.docJson).toEqual(exportJsDocJson(doc.spaceDoc));
const p1Text = JSON.stringify(rustState.docJson.blocks['p-1']);
expect(p1Text).toContain('[js-concurrent]');
const nativePara = JSON.stringify(
rustState.docJson.blocks['native-para-1']
);
expect(nativePara).toContain('你好,世界!');
const surfJson = JSON.stringify(rustState.docJson.blocks['surface-1']);
expect(surfJson).not.toContain('native-shape-1');
expect(surfJson).not.toContain('native-conn-1');
},
{ timeout: 15_000, interval: 200 }
);
expect(jsWritebacks).toBe(0);
workspace.forceStop();
workspace.dispose();
roomClient.close();
await driver.quit();
}, 25_000);
});