mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-24 17:40:47 +01:00
d0400aaf033a703a037f8fe5400bbc896db985da
3524 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d0400aaf03 |
gpui: Match keystrokes before context predicates (#66634)
## Summary `Keymap::resolve_bindings_for_input` now matches keystrokes before evaluating context predicates. Keystroke matching is cheaper and rejects most bindings. Both checks are just pure filters so lookup results are identical. Avg time per `Keymap::bindings_for_input` call over 48 common keystrokes in editor context. Windows 11 Ryzen 7 9800X3D. | Keymap | Before | After | |---|---|---| | Linux | 15.5 µs | 1.26 µs | | Linux + vim (normal mode) | 41.4 µs | 3.05 µs | | Windows | 14.6 µs | 1.20 µs | | Windows + vim (normal mode) | 41.5 µs | 2.97 µs | ## Testing Windows 11, with and without vim mode: typing, `ctrl-s`, `ctrl-shift-p` hints, `ctrl-k ctrl-c`, `ctrl-k z`, buffer search `enter` and `escape`, and vim `i`, `escape`, `dd`, `gg`, `G`, `ciw`, `v d`. No issues found. - `cargo test -p gpui --features test-support`: pass. - `cargo test -p vim -p which_key`: pass. - `cargo test -p zed -- keymap emacs keybinding`: pass. - Lookup results match before and after for every bound keystroke sequence and prefix, across 13 context stacks and the Linux, Windows, and macOS keymaps, with and without vim. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - N/A - [GPUI] Improved keybinding lookup performance. |
||
|
|
f0fa51bb51 |
gpui: Fix unused import warning with bench-support (#66905)
## Summary
Building gpui with `bench-support` alone without `test-support`, as
`cargo check -p gpui --features bench-support` and
script/gpui-bench-compare do, warns:
warning: unused import: `DisplayId`
--> crates/gpui/src/platform/test/platform.rs:7:32
Fix gates the import on `test-support`, like the neighboring imports
that are only used by `test-support` code.
#63039 added `bench-support` as a test dependency, and then #65059 added
the `DisplayId` imports without the same `#[cfg(...)]` its users have.
## Testing
Before
# cargo check -p gpui --features bench-support
[...]
warning: unused import: `DisplayId`
--> crates/gpui/src/platform/test/platform.rs:7:32
|
7 | CursorStyle, DevicePixels, DisplayId, DummyKeyboardMapper,
ForegroundExecutor, Keymap,
| ^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by
default
warning: `gpui` (lib) generated 1 warning (run `cargo fix --lib -p gpui`
to apply 1 suggestion)
After
# cargo check -p gpui --features bench-support
Checking gpui v0.2.2 (/home/josh/Source/zed/crates/gpui)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.14s
## Self-review
- [x] I've reviewed my diff for quality, security, reliability, and
performance.
- [x] UI changes follow the
[checklist](https://zed.dev/docs/development/ui-checklist).
- [x] Tests cover the new or changed behavior.
Release Notes:
- [GPUI] N/A
|
||
|
|
dc93abce2f |
gpui: Keep macOS notification service calls off the UI thread (#66934)
## Problem macOS notification APIs can synchronously wait for the notification service, even when they expose completion handlers. A captured main-thread stack showed notification dismissal blocked in `removePendingNotificationRequestsWithIdentifiers:` → `__NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__`. GPUI called that API on the UI thread while holding its platform-state mutex, freezing the interface until macOS replied. ## Changes - Lazily start one dedicated notification thread that owns the notification center, delegate, authorization state, and registered categories. - Queue posting and dismissal in FIFO order so a delayed dismissal cannot overtake a replacement notification. Initialization and native calls happen on the worker; notification responses still return through the foreground executor. - Return a `Task<()>` from `dismiss_system_notification`, allowing callers to await completion without blocking the UI. Completion means the platform calls returned, not that asynchronous OS work finished. Dropping the task does not cancel dismissal. Update the other platform implementations, example, and tests for the return type. - Keep the unbundled-binary guard and use autorelease pools around native work. A stalled notification service can still delay later notification commands, but no longer stalls the UI. ## Verification Ran on macOS: ```sh corgi test -p gpui -p gpui_macos --lib 'system_notification' ``` All five tests passed. The new regression test submits show/dismiss/show commands without advancing a consumer, checks their order, and verifies completion remains pending until acknowledgement. The source published here is identical to that tested revision; the subsequent commit only records the human removal of the README review marker. No live macOS-service stall was induced, and Linux/Windows/browser workflows were not run. Release Notes: - [GPUI] Fixed macOS system notification operations blocking the UI thread while waiting for the notification service. --------- Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com> Co-authored-by: Anthony Eid <hello@anthonyeid.me> |
||
|
|
aff99ecc32 |
gpui: Animate SVG transformations without re-rendering views (#66896)
## Summary Ref #21146, #23479, #51597 One common problem that I've been working towards fixing by adding a retained mode is Zed's high battery usage, caused by invalidating clean entities because a single ancestor is dirty. While looking closer into this problem I realized that a ton of the invalidations we run into are due to animations, which can be fixed separately from retained mode. My solution is adding a `TimedTransformation` struct and a new animation API that uses it. ```rust // A spinner: one full turn every two seconds. svg() .path("icons/load_circle.svg") .with_timed_transformation(TimedTransformation::rotation( Duration::from_secs(2), Transformation::default(), )) // A pulsing ring: grows to 1.5x while fading out, each value with its own easing. svg() .path("icons/ring.svg") .with_timed_transformation( TimedTransformation::new(Duration::from_millis(1750)) .from(Transformation::alpha(0.6)) .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) .with_scale_easing(Easing::EaseOutQuint), ) ``` Because most of our animations are an SVG sprite with simple matrix operations applied to it, such as rotation, alpha changes and size changes, that change based on elapsed time, we can avoid invalidating the view by extracting the before and after transformations and deriving a function that takes elapsed time and computes what the animated sprite should look like. The extracted function lives in a table on the scene, and each animated sprite points at its entry. This lets GPUI advance animations right before presenting a frame, without dirtying the view or recomputing the scene from scratch. This should save a lot of CPU usage and battery life for end users of GPUI apps that use animations. `Icon` and `Vector` in `ui` now use this for `with_rotate_animation`, so Zed's existing spinners get it with no call site changes. With reduced motion on, the SVG is drawn at its starting transformation and nothing animates. ### Results Main-thread CPU instructions for one animated frame, from a headless benchmark on macOS with the Metal renderer (not included in this PR): | | 200 animated SVGs | 60 rows of text + 5 spinners | |---|---|---| | Re-render with `with_animation` | 6.07 M | 7.34 M | | `with_timed_transformation` | 162 K | 100 K | | Improvement | 37x | 73x | The `svg_animation` example (`cargo run --release -p gpui --example svg_animation`, 200 animated SVGs in a window, Apple M4 Max), as reported by `top`: | | CPU | Energy impact | |---|---|---| | Re-render with `with_animation` | 21% | 21.5 | | `with_timed_transformation` | 6% | 7.5 | | `with_timed_transformation`, capped at 15 fps | 1.9% | 3.0 | That is about 3.5x less CPU and 3x less energy impact uncapped, and about 11x less CPU and 7x less energy impact with the cap. ### Follow ups - Allow animating more primitives, such as glyphs, instead of only SVG sprites - Lower the fixed cost of presenting a frame, which is most of what remains after this change - Retained layers, so a whole subtree can be moved or faded without re-rendering Release Notes: - Improved battery life by animating spinners without re-rendering the views that contain them - [GPUI] Added `TimedTransformation` and `Svg::with_timed_transformation` to animate SVGs without re-rendering a view |
||
|
|
4fd48c02ac |
Miscellaneous improvements to prepare for Rust 1.100 (#66901)
## Summary Fixes rustc and clippy warnings for a potential upcoming Rust 1.100 version bump. All changes are backwards compatible and Rust is **not** bumped in this PR. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - N/A - [GPUI] N/A --------- Co-authored-by: Finn Evers <finn.evers@outlook.de> |
||
|
|
d3fc053d5b |
gpui: Speed up sorting scene primitives (#66898)
`Scene::finish` sorts each primitive array by draw order. It used `sort_by_key` on the primitives themselves, so every move in the sort copied a whole instance struct. This sorts small `(key, index)` pairs instead, then permutes the primitives in place by following the permutation's cycles, so each primitive is copied once. Details: - The insertion index is part of each key, so ties keep insertion order, the same as the stable `sort_by_key` did. That also makes `sort_unstable` safe to use, and it measured about 20% faster than the stable sort here. - Arrays that are already sorted return early without allocating. - One key buffer, local to `finish`, is shared by all primitive kinds. - Paths and surfaces keep `sort_by_key`: they aren't `Copy` and there are few of them. ## Benchmarks This adds a `Primitives/finish` group to the `primitives` bench. It inserts the primitives during untimed setup and times only `Scene::finish`. Measured on an Apple Silicon Mac, two seeds per size: | Case | `main` | This PR | Change | |---|---|---|---| | random-256 | 6.0 / 7.2 µs | 4.0 / 4.4 µs | −33% / −40% | | random-1024 | 46.0 / 40.7 µs | 22.9 / 18.4 µs | −50% / −55% | | random-4096 | 270 / 264 µs | 121 / 117 µs | −55% / −55% | The already-sorted patterns (grid, stripes, overlay and so on) take 0.1–4 µs and are the same or faster, apart from run-to-run noise in the 4096-primitive cases. `finish` is about 5% of building a scene in `Primitives/scene/random-4096` (about 5.5 ms per build), so the whole scene build gets roughly 2.5–3% faster. Draw-order assignment during insertion is the rest. Release Notes: - [GPUI] Improved the speed of sorting scene primitives in `Scene::finish` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> |
||
|
|
78a8526196 |
Update merman to 0.9.3 (#66874)
Closes #66582 Closes #62410 Closes #62913 Closes https://github.com/zed-industries/zed/pull/65192 * Label measurement merman 0.9 no longer ships font metrics, and sizes label boxes from a font-agnostic estimate. `SvgRenderer::measure_text_width` lays out a line with the renderer's own `usvg` options, and merman's width callback uses it, so layout and painting share font matching, fallback and shaping. This also fixes labels overflowing their nodes with a wide UI font. * Font data `fontdb` reopens and maps a file-backed font on every glyph lookup, which made each measurement with a system font cost 1 to 5ms. The SVG renderer now reads each font file selected for text once, within a 64MiB total budget, and serves later lookups from memory. A 36-character measurement with Menlo went from 2.8ms to 0.06ms. * Configuration merman 0.9 follows Mermaid 12 defaults: the `neo` look, 120px wrapping and a 120px minimum node width. Zed keeps the classic look, 200px wrapping and no minimum width, as before. merman also stopped restricting `themeVariables` in diagram directives; Zed restricts it again, together with `fontSize`. * Styling merman now defines label text once in `<defs>` and references it with `<use>`, so descendant selectors and position lookups no longer reach it. Node accents, mindmap section colors and edge label backgrounds are adapted to that structure. Label typography comes from merman instead of a forced 16px, and label viewports are not clipped. * Limits * Text measurement has a per-render work budget, so a label of zero-width characters fails the render instead of measuring ever longer prefixes. * merman 0.9.3 has a hard-coded limit on CSS matching work in its label fallback. Flowcharts above about 310 nodes and class diagrams above about 375 members fail with `svg_fallback_selector_index exceeded`. `main` renders 500 nodes and 400 members. * Behavior changes * ER relationship labels are 14px, merman's size; they were forced to 16px. * A `gantt.fontSize` directive is ignored, because `fontSize` is restricted at any depth. * A per-node `font-size` style is now painted; before, only the node box grew. * A single label line above roughly 90KB fails to render. ### Known regression Release Notes: - Fixed Mermaid state descriptions overlapping in the Markdown preview. - Fixed Mermaid sequence diagram titles being cut off. - Fixed Mermaid labels overflowing their nodes with wide fonts. - [GPUI] Added `SvgRenderer::measure_text_width`, and made SVG text rendering keep used font files in memory. |
||
|
|
be07e43ea0 |
gpui: Reduce overdraw using the depth buffer (#66811)
GPUI paints a frame by recording primitives (quads, shadows, paths, underlines, glyph sprites, surfaces) into a `Scene`. The renderer then draws the scene's primitives back to front, so that later primitives paint over earlier ones. This means every pixel of every primitive is shaded, even where a later primitive completely covers it. In heavily nested UI, this adds up to a lot of overdraw. Inspired by WebRender, we reduce overdraw with a depth buffer and two passes: - The opaque pass draws quads that we know cover their whole area with an opaque color. They're drawn front to back, with depth testing and depth writes enabled. In practice, we can only make this guarantee for quads with a solid, fully opaque fill and no rounded corners. - The blended pass draws everything else back to front, with depth testing enabled but depth writes disabled. This is essentially the existing render loop with a depth test added. Any fragment 'behind' an opaque quad fails the depth test and is never shaded. To get more of each frame into the opaque pass, `paint_quad` now splits any quad with rounded corners into a rectangular interior and the four edge strips around it. The interior is a plain rectangle, so if its fill is solid and opaque, it's drawn in the opaque pass, and only the strips need the border and corner shading. Measured on an Intel HD 4600: Scene | Before | After | Change | Pixel shader invocations | |---|---|---|---|---| | Editor | 3,941µs | 1,689µs | −57% | 3.71M → 1.65M (−55%) | | Command palette | 7,658µs | 2,275µs | −70% | 5.33M → 1.80M (−66%) | | Git Graph | 3,589µs | 1,889µs | −47% | 3.13M → 1.65M (−47%) | Fixes https://github.com/zed-industries/zed/issues/8043 Release Notes: - Reduced GPU usage - [GPUI] Improved rendering performance by skipping pixels hidden behind opaque quads |
||
|
|
1d8eda94bd |
gpui: Improve primitive batching (#66810)
GPUI groups primitives into GPU batches by draw order. Each primitive is inserted into an R-tree of the bounds painted so far, which assigns it a draw order one above the highest order it overlaps. The renderer then draws primitives in batches grouped by draw order, then by primitive kind. We fix two limitations that split batches unnecessarily: - Previously, a primitive that overlapped anything was assigned a new draw order. However, GPUs draw instances in submission order, and within a draw order we draw kinds in a fixed order. So, a primitive can share the draw order of an overlapping primitive, as long as its kind doesn't sort before the overlapped primitive's kind. (Sprites are exempted, since sprites are also sorted by their atlas texture within a draw order.) - Note that adjacent batches of the same kind were already merged on `main`, but any primitive of another kind drawn in between kept them apart. Now, we reuse the draw order whenever it's safe. - Previously, `window.paint_layer` created a new draw order from the provided bounds as soon as the layer was opened. Now, the layer is inserted into the R-tree once it's closed, using the union of the bounds of the primitives painted inside the layer. It reuses a draw order by the same rule, if every primitive in the layer could. - Since `paint_layer` now computes its bounds from the primitives it paints, the `bounds` argument is no longer needed and was removed. Despite this, scene construction is still faster than it is on `main`. In Zed, this cuts batches per frame from 20 to 4 at startup, and from 22 to 6 with a selection. On an Intel HD 4600, GPU time drops by 2.5–4.5%. Release Notes: - Reduced GPU usage - [GPUI] Improved draw call batching. `Window::paint_layer` no longer takes a `bounds` argument |
||
|
|
ffe0fa29e4 |
gpui: Improve path rendering (#66809)
GPUI currently implements paths in two ways: - A remnant of a Loop-Blinn shader (which doesn't quite work because the winding accumulation is missing). - Tessellating paths on the CPU with `lyon` and uploading the triangles to the GPU. Tessellated triangles have no curve coordinates, so Loop-Blinn's analytic antialiasing doesn't help them. To antialias them, we used 4x MSAA instead. This was particularly problematic: - MSAA has an enormous bandwidth and memory cost relative to the quality of the result (5 coverage levels). - Many lower-end GPUs can't afford MSAA on the main render target. So, paths rendered into a separate MSAA target, which was resolved into an intermediate texture and then drawn onto the main target. These textures cost extra memory. - The MSAA draw and resolve happened per path batch. We didn't use a single path atlas, because in principle its memory use is unbounded. This dramatically magnifies the bandwidth cost of path rendering, especially on tile-based GPUs, since every batch switches render passes mid-frame. We present a new path renderer that computes analytic coverage per pixel from the winding number. Coverage is computed as in Eric Lengyel's Slug: we cast rays leftward and upward from the pixel and count crossings with the path's curves. Crossings within the pixel contribute partial winding. GPUI paths can be larger and more complex than glyphs. But since they're built at a fixed scale in screen space, we can do some of the spatial work on the CPU: - `PathBuilder` turns each contour into closed chains of monotone quadratic curves. - The curves are binned into square cells, where each cell lists only the curves near it. Cell size is picked per path to balance binning cost against shading cost. - For each cell, the CPU computes a *backdrop* value that encodes the winding contribution of all the curves it doesn't list. - Neighboring cells with the same curve list and backdrop merge into rectangular tiles. A large rectangle becomes nine tiles: four corners, four edges, and a solid interior with no listed curves. - Each tile is one GPU instance, and the shader loops only over that tile's curves. Tiles are drawn in the main render pass alongside every other primitive. There's no MSAA, no intermediate textures, no extra render passes or resolves, and no tessellation. --- Binning has a different cost profile from tessellation: - The tessellator's work happened almost entirely in `PathBuilder::build()`. Binning depends on the display scale, so it happens in `paint_path`. Code that caches and reuses `Path`s pays binning cost on every paint. However, this doesn't seem to be a common pattern, so mitigations are deferred. - In general, fills are about as fast as before or slightly faster, while strokes are 2–8× slower. `lyon` has a dedicated stroke tessellator that emits triangles directly along the stroke. We convert the stroke to an outline with `tiny-skia`, then bin it like any other fill. Long, sprawling strokes are the worst case (a 1,000-point scribble takes about 1.5ms now vs 0.2ms before). GPU time is, generally, reduced dramatically. Measured on an Intel HD 4600: | Scene | Before | After | Change | Pixel shader invocations | |---|---|---|---|---| | `painting` example | 9,257µs | 1,928µs | −79% | 1.81M → 1.50M (−17%) | | Git Graph | 19,669µs | 3,828µs | −81% | 3.21M → 3.13M (−2%) | --- Some breaking changes were made to the API: - `Path` is no longer generic and can only be built with `PathBuilder`. Use `PathBuilder`'s equivalents of `Path`'s builder methods. - `PathBuilder` can still be populated from `lyon` path builders, but the places where `lyon`'s tessellator leaked into the API were removed. `StrokeOptions` and `FillOptions` are now GPUI types with fewer options, and `PathBuilder::build_path` is gone. - Since paths now render with analytic antialiasing, you may see conflation artifacts where MSAA didn't have any. Release Notes: - Reduced GPU usage - [GPUI] Improved path rendering performance. `Path` is no longer generic and must be built with `PathBuilder` --------- Co-authored-by: Anthony Eid <hello@anthonyeid.me> |
||
|
|
3d42ca7c09 |
cli: Add debug state command (#66852)
This PR adds a debug state command to the CLI and a `cx.debug_state` API to GPUI's `App`, so users can better understand where things went wrong in their GPUI apps when they run into a bug. `zed --debug-state` prints the running instance's snapshot as JSON. Release Notes: - Added a `zed --debug-state` CLI flag that prints the running app's window, display, and platform state as JSON for debugging - [GPUI] Added `cx.debug_state` API to output the current GPUI state |
||
|
|
ba06cc5191 |
Add setting to show/hide title bar (#65671)
## Summary Restores `title_bar.show` from #37428 with `always`, `never`, and `hide_in_full_screen`. - On macOS the whole native titlebar is hidden, so fullscreen no longer reveals an empty bar at the top edge. - The Threads Sidebar and thread history headers drop their window controls together with the title bar. - With client-side decorations, the window frame is square at corners where no title bar, status bar or sidebar rounds the content. - Leaving the Threads Sidebar falls back to the workspace when the previously focused element is gone. Includes macOS window-control handling adapted from #42540. Related discussion: #55183. ## Testing Tests and clippy for the touched crates pass on macOS and Linux. Not run on Windows or under a real Linux compositor. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover visibility changes and focus restoration. Release Notes: - Added a setting to hide the title bar always or only in fullscreen. - [GPUI] Added `Window::set_native_titlebar_visibility` on macOS and `FocusHandle::is_rendered`. - [GPUI] Fixed fullscreen changes not notifying window bounds observers on Wayland and X11. - [GPUI] Fixed the macOS titlebar staying opaque after a failed fullscreen entry. --------- Co-authored-by: Kirill Bulatov <mail4score@gmail.com> |
||
|
|
64ef8026c7 |
gpui: Resolve window placement from active window (#61459)
Closes #33314 ### Objective On multi-monitor setups, opening a new window placed it on the primary display instead of the display I'm currently on. ### Solution GPUI now retains the active window bounds and display ID while it is on the update stack. New windows use this for placement, falling back to the primary display when no active display is available. ### Testing - Tested it on macOS 26 ### Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [ ] Unsafe blocks (if any) have justifying comments - [x] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Fixed new windows always opening on the primary display - [GPUI] Added `App::active_display`; `WindowBounds::centered` now takes a `display_id` |
||
|
|
415d310e52 |
gpui: Avoid copying and comparing the bytes of shared text (#66728)
Two small changes that avoid touching the bytes of text that hasn't
changed:
- `SharedString` equality checks whether both sides point at the same
bytes before comparing them. `SmolStr` compares heap-allocated and
static strings byte by byte even when both are clones of the same
allocation, which is common when a view clones the same label into its
elements every frame. Strings of up to 23 bytes are stored inline and
still use `SmolStr`'s comparison. `Hash` is now implemented by hand
(clippy rejects deriving it alongside a manual `PartialEq`) and hashes
exactly as before.
- A `&'static str` text child (e.g. `div().child("Some label")`) is
wrapped with `SharedString::new_static` instead of copied every frame,
which allocated for strings longer than 23 bytes. Its comparisons now
hit the pointer check above.
Release Notes:
- N/A
- [GPUI] Avoid allocating for a SharedString in `imp Element for
&'static str`
|
||
|
|
0929d569fa |
client: Report Linux desktop environment and connected display server in telemetry (#66772)
Telemetry now reports the display server Zed actually connected to instead of guessing from environment variables, so `os_name` is correct when Wayland falls back to X11. It also sends the connected session's desktop environment (`XDG_CURRENT_DESKTOP`), so we can split Linux hang and frame data by desktop. Release Notes: - [GPUI] Added `GraphicalEnvironment::desktop_environment()` for reading the connected session's desktop environment - N/A |
||
|
|
39467cf4b1 |
gpui: Remove hand-written IntoElement impls for elements (#64864)
Custom elements previously had to hand-write an `IntoElement` impl that just returned `self`. Replace that boilerplate with a blanket `impl<T: Element> IntoElement for T`, and relax the `Element` supertrait bound from `IntoElement` to `Sized`. Any type implementing `Element` is now usable as a child element without extra code. `AnyElement` overrides `into_any` to return `self`, so converting one does not nest a boxed element inside another. To make that easy to notice, the private `AnyElement::new` is renamed to `new_please_call_into_any_to_avoid_double_box`. Remove the now-redundant `IntoElement` impls across gpui and its consumers. ## Testing Manually test your changes; report results, mention platforms if relevant. How can reviewers test this easily? Include setup and steps. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [ ] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [ ] Tests cover the new or changed behavior. Release Notes: - [GPUI] (breaking) Added blanket impl for `IntoElement` trait with `ElementType = Self` when `Self` implements `Element`. --------- Co-authored-by: Amp <amp@ampcode.com> |
||
|
|
ddb90e5e89 |
gpui: Don't copy the text of every shaped line (#66682)
## Summary `WindowTextSystem::layout_line` converted its `&str` to a `SharedString` before cache lookup. For text longer than 23 bytes (`SmolStr`'s inline limit) that's one heap allocation + copy on every call, even on cache hits. `shape_line` went through the same path, copying a `SharedString` it already owned. `LineLayoutCache::layout_line` is already generic over the text type and only converts on a miss, so the text is now passed straight through. A hit no longer allocates, and a miss from `shape_line` shares its `SharedString` with the cache key instead of copying it. This is hit by editor row shaping, terminal text batches, and cursor motion via `DisplaySnapshot::layout_row`. Cache hits, release build, `NoopTextSystem`, 64-byte lines (measured with a local probe, not included): | | Allocations per call | Time per call | |---|---|---| | `shape_line` | 1 → 0 | 276 → 178 ns | | `layout_line` | 1 → 0 | 155 → 87 ns | ## Testing - Added `shape_line_shares_its_text_with_the_layout_cache` which fails on `main` and passes with this change. - `cargo test -p gpui` passes. `cargo clippy -p gpui` is clean with the CI pipeline's flags. - Tested manually on Windows 11 against a `main` build: scrolling and typing in a large file and in the terminal. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - N/A - [GPUI] Improved text shaping performance: `WindowTextSystem::layout_line` now accepts any text convertible to `SharedString`, and `shape_line` and `layout_line` no longer copy the text on a line layout cache hit. --------- Co-authored-by: Anthony Eid <hello@anthonyeid.me> |
||
|
|
22580c6e69 |
gpui: Trim per-line and per-glyph work in the text system (#66722)
## Summary Skips painting line backgrounds when no run has a background color, stops allocating a `SharedString` and reserving ~3 KB of decoration runs for every laid-out line, checks subpixel support before reading the window's background appearance (which locks the window on macOS, once per glyph), and shares one empty `FontFeatures` list instead of allocating one for every default `TextStyle`, which `Window::text_style` builds on every call. ## Benchmarks Change vs. the commit before this PR, `script/gpui-bench-compare` core suite, macOS (Apple Silicon), 3 runs per case: | Workload | Instructions | Allocations | Bytes allocated | |---|---:|---:|---:| | Text panels | −4.4% to −4.6% | −15.9% to −16.1% | −15% to −30% | | Scrolling | −3.2% to −8.1% | −12.7% to −12.9% | −37% to −40% | | Closed inspector panel | −2.4% | −7.7% | −24% | | Path-free full refresh | −0.1% to −1.8% | −1.3% to −3.7% | −13% to −19% | | Full refresh with paths | −0.3% to −2.8% | −0.5% to −1.3% | −1% to −15% | | Mixed, with and without cached views | −1.1% to −1.3% | −0.6% to −0.7% | +3.5% to +3.6% | | Primitives, closed inspector grid | ~0% | ~0% | ~0% | Release Notes: - N/A - [GPUI] Improved text rendering performance by skipping line backgrounds when no run has one and sharing one empty `FontFeatures` list |
||
|
|
4023e3c88e |
gpui: Only take a line wrapper when truncating text (#66720)
## Summary Every text measurement took a `LineWrapper` from the pool, which locks it twice, resolves the font and moves its ~1 KB character width cache in and out, even though only truncation uses it. This takes one only when truncating. Stacked on #66719. ## Benchmarks Change vs `main`, `randomized_element_tree`, macOS (Apple Silicon), 2 alternating runs: | Workload | Instructions | Allocations | |---|---:|---:| | Scrolling | −7.1% to −9.3% | 0% | | Text panels, two updates | −3.8% to −5.7% | 0% | | Path-free full refresh | −1.3% to −2.5% | 0% | Release Notes: - N/A - [GPUI] Only take line wrapper lock when truncating text, instead of every text run |
||
|
|
62682ebde9 |
gpui: Compute tab stop order only when moving focus (#66721)
## Summary `TabStopMap` inserted every focusable element into a `SumTree` on every frame, but the order is only read when focus moves with tab. This records nodes in a `Vec` and sorts on demand. Stacked on #66719. ## Benchmarks Change vs `main`, `randomized_element_tree`, macOS (Apple Silicon), 2 alternating runs: | Workload | Instructions | Allocations | Bytes allocated | |---|---:|---:|---:| | Path-free full refresh, wide | −12.4% to −19.9% | −7.8% to −12.1% | −43% to −57% | | Path-free full refresh, dense / mixed | −2.1% to −11.0% | −1.9% to −7.9% | −13% to −45% | | Full refresh with paths | −0.3% to −4.2% | −0.1% to −1.9% | −0.5% to −4.4% | | Text, scrolling | ~0% | 0% | 0% | Release Notes: - N/A - [GPUI] Change tab stop internal data structure from a SumTree to a Vector for performance and memory savings |
||
|
|
4ce4b7b567 |
gpui: Move a Div's Interactivity out of line (#66719)
## Summary Tessellating vector paths dominates the randomized element tree's frames, hiding layout and the rest of the frame. This adds a `with_paths(false)` option (the canvas stays, so layout is unchanged), `PathlessTree/full refresh` and `PathlessTree/element style` benchmark groups, and adds the path-free full refresh to `script/gpui-bench-compare`'s core suite. It also adds a random text mutation to the randomized element tree, so its tests cover text whose measured size changes (including text that wraps and text that's removed). Generated trees are unchanged, but the extra mutation kind changes which mutations each seed applies. These PRs are stacked on this one and use its path-free groups for their benchmark numbers: - #66723 gpui: Move a Div's Interactivity out of line (merged into this branch) - #66720 gpui: Only take a line wrapper when truncating text - #66721 gpui: Compute tab stop order only when moving focus - #66722 gpui: Trim per-line and per-glyph work in the text system Release Notes: - N/A - [GPUI] Improve randomize element tree test |
||
|
|
78fde14d12 |
gpui: Fix ignored horizontal padding on the list() element (#64056)
# Objective This PR fixes a small bug in the `list()` element which reads padding on both axes (X & Y) but only applies the values set for the Y axis while the X axis values end up being ignored. Right now Zed works around this bug by manually setting the horizontal padding to `8` on a `div` inside of the `list` (here's an example: https://github.com/zed-industries/zed/blob/main/crates/settings_ui/src/settings_ui.rs#L3616). P.S.: ths PR is a new PR for the same change/fix as [this closed PR](https://github.com/zed-industries/zed/pull/63784). I cleaned up my branch and this time I'm the one writing the description not Claude 😓 ## Solution I simply subtract the left & right padding from the width the `list()` element gives its items, and offset the items by the left padding. ## Testing - Did you test these changes? If so, how? - I ran `cargo test -p gpui` to make sure my changes didn't break any existing test. - Are there any parts that need more testing? - I don't think so. - How can other people (reviewers) test your changes? Is there anything specific they need to know? - You can set the horizontal padding of the settings UI in Zed to the `list()` element itself or simply spin up a basic GPUI app with a `list()` element in it. - If relevant, what platforms did you test these changes on, and are there any important ones you can't test? - Web, Linux and macOS. I haven't tested on Windows. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments - [x] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable ## Showcase <details> <summary>Before</summary> <img width="480" height="392" alt="image" src="https://github.com/user-attachments/assets/1d394636-e407-42e2-a6da-98359af315cb" /> </details> <details> <summary>After</summary> <img width="480" height="392" alt="image" src="https://github.com/user-attachments/assets/70629183-a733-4f53-95fe-177fd332ed9d" /> </details> --- Release Notes: - N/A - [GPUI] Fixed horizontal padding on the `list()` element. ## AI Disclosure: Claude Fable 5.1 was used to write the changes in this PR. --------- Co-authored-by: Finn Evers <finn@zed.dev> |
||
|
|
7bb5656e63 |
gpui: Implement Along for Edges (#66614)
Release Notes: - [GPUI] Implemented `Along` for `Edges` |
||
|
|
635026fabc |
gpui: Support animated WebP in Image::to_image_data (#66459)
## Summary When opening an animated `.webp` file in Zed's image viewer, only the first frame was rendered statically. `ImageAssetLoader` in `crates/gpui/src/elements/img.rs` already supported animated WebP via `WebPDecoder`, but `Image::to_image_data` in `crates/gpui/src/platform.rs` (which is used when opening image files in a project tab or loading clipboard images) still called `decode_static_image` for `ImageFormat::Webp`. This PR updates `Image::to_image_data` to decode animated WebP frames and moves the GIF and WebP decoding logic into shared `decode_gif_image` and `decode_webp_image` helpers in `platform.rs` so both paths stay in sync. ## Testing - Added a unit test (`test_animated_webp_image_to_image_data_decodes_frames`) in `crates/gpui/src/platform.rs`. - Tested manually on Linux by opening both static and animated `.webp` files in Zed. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - Fixed animated WebP files only displaying their first frame when opened in the image viewer. - [GPUI] Added animated WebP decoding support to `Image::to_image_data`. |
||
|
|
c7bea34383 |
gpui: Fix cursor reverting when a drag starts (#66540)
## Summary Dragging an element with a cursor style, such as a narrow resize handle, could briefly show the wrong cursor as the drag began. **The problem.** GPUI starts a drag once the pointer moves more than 2 px from the press. On a narrow handle, that same move can take the pointer off the handle. `dispatch_mouse_event` then: 1. Re-ran the hit test, saw the pointer had left the handle, and picked the cursor from the last painted frame, which gave whatever was underneath. 2. Ran the mouse listeners, where `on_drag` started the drag and requested a repaint. 3. Only applied the drag's cursor at the end of the next draw. So the drag was running under the wrong cursor until that paint. A native X11 trace measured this at about 51 ms. On macOS, 3 of 4 drags sampled at drag start read `Arrow` in a real app on an older GPUI revision. **The fix.** - `dispatch_mouse_event` updates the cursor after the listeners run, so a drag started by the current event takes effect in that event. - `reset_cursor_style` checks the active drag's cursor before the painted frame, because that frame predates the drag. **Behavior to review.** - An active drag's cursor now beats `set_window_cursor_style`, which previously won if painted last. The other callers (pane dividers, scrollbars, the editor scrollbar and minimap) only use it during their own custom drags, so I don't expect a conflict. - The cursor is now resolved on every mouse event rather than only when the hit test changes. See the benchmark below. **Not fixed by this PR.** - Pressing near a handle's edge and moving 1 px off it leaves the pointer outside the handle but under the drag threshold, so the underlying cursor shows until the drag starts. This comes from reading the code; I haven't reproduced it. - The drag's cursor can linger until the next paint after release, as it does today. - On macOS, cursor updates are skipped while the window is inactive, so a drag started by the click that focuses the window is unaffected. ## Benchmark Cost of the added per-event cursor update, in a release build on an M4 Max with a real AppKit window, averaged over 20,000 calls per run: | Cursor requests | Pointer over nothing | Worst case: 30 nested hitboxes, match scanned last | Worst case: mouse-move dispatch total, including the update | |---|---|---|---| | 100 | 0.06 µs | 1.1–1.3 µs | 5.6–5.8 µs | | 1,000 | 0.2 µs | 11.5–13.3 µs | 47–52 µs | | 10,000 | 2.3 µs | about 118 µs (one run) | about 486 µs (one run) | - The platform call is about 40 ns on macOS. Nearly all the time is the scan of the frame's cursor requests. - Compared with the old behavior on moves within the same hitboxes, this adds about 1.5% per mouse-move dispatch with the pointer over nothing and about 30% in the worst case, both at 1,000 requests. - At 1,000 requests, the worst case is about 0.16% of a core at 120 events/s and 1.3% at 1,000 events/s. Limits of these numbers: - The layout is a synthetic grid, and I don't know how many cursor requests a real window has. - The machine was busy (load average 60–90), so the numbers likely overstate the cost a little. - These are averages, not worst-case individual calls. - The 10,000 row has one run because the benchmark stopped when its window lost focus. ## Testing - `test_drag_cursor_applies_before_next_paint` fails without the fix (`IBeam` instead of `ResizeColumn`) and passes with it. - `gpui` lib tests pass on macOS (496), rebased on current `main`. - `./script/clippy -p gpui` and rustfmt were clean on macOS before the rebase. Not tested: - A before/after of this final version in a real window on any platform. An earlier version of the fix was checked natively on X11. - Windows and Wayland. To try it, drag any element that has `.cursor_*()` and `on_drag`, moving off the element as the drag starts. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [ ] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). (N/A: no visual UI changes.) - [x] Tests cover the new or changed behavior. Release Notes: - [GPUI] Fixed the cursor briefly reverting when a drag starts, before the next paint Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ce6c5413f1 |
ui: Open submenus and popovers on the side that has room (#66496)
Follow up of https://github.com/zed-industries/zed/pull/66482 Wide submenus could open on top of their own menu, and popovers near the window bottom got pushed up over their button. The side was picked while rendering, before the menu's real size was known, so submenus guessed 200px wide and popovers never switched sides at all. This adds `Anchored::attach(target, corner)` to GPUI, which picks the side during layout using the real size and moves the element to the other side of the target when it doesn't fit. Submenus and `PopoverMenu` use it. `DropdownMenu` now opens left-aligned under its button, and settings row dropdowns opt into right alignment. Left out on purpose: - Pickers can switch between above and below as the list shrinks while you type. Using the side that fits seems better than a stale one. Before: <img width="300" src="https://github.com/user-attachments/assets/9a45aba2-6149-4835-8aa5-c2e8ae49c9b2" /> After: <img width="300" src="https://github.com/user-attachments/assets/148e205d-dd6b-4c59-9ed4-5ad37054725e" /> <img width="300" src="https://github.com/user-attachments/assets/88a24ac6-e1c5-4e92-b9be-26f813b1b576" /> Release Notes: - Fixed wide submenus and popovers covering the menu or button they open from. - [GPUI] Added `Anchored::attach` to place an element next to a target and flip it to the other side when it doesn't fit. |
||
|
|
decd2399b1 |
gpui: Keep subscriptions for entities read by reused cached views (#65952)
When a cached view was reused, entities it read outside its recorded scope lost their subscriptions, so notifying them no longer redrew the window. Two cases: - **Deferred draws.** `deferred(...)` elements are prepainted and painted at window level after the element tree, outside the cached view's recorded reads. Each deferred draw now records its own reads alongside its reusable ranges and restores them when it's replayed. - **Paint-phase reads.** A cached view recorded the entities read during render, layout and prepaint, but not during paint, so a model read only in a paint callback (for example a `canvas`) was dropped on reuse. Paint reads are now added to the view's recorded set. In both cases one set covers every phase and is restored when the prepaint is reused, since the window only consumes it at the end of the draw. It also changes how scoped reads are recorded. `detect_accessed_entities` used to clone every entity read so far in the frame and diff against it afterwards, which cost O(frame reads) per cached view (and now per deferred draw), and dropped entities that something earlier in the frame had already read. Reads are now recorded in a stack of scopes: each read goes into the innermost scope, and a scope's reads are added to its parent when it ends. Each scope now gets exactly its own reads, at a cost proportional to those reads. Restoring a recorded set now skips entities released since it was recorded. Previously the window subscribed to them again after `App` had removed their subscriptions, leaking those entries for as long as the cache kept being reused. Tests cover a canvas paint read under a reused cached panel, with and without a deferred draw around it, and with the panel itself deferred. Each fix's case fails without it. A unit test covers nested scopes, entities read before a scope began, and released entities. A unit test covers nested scopes recording entities read before them. Known limitation (unchanged): notifying a non-view entity read by a cached view redraws the window but doesn't mark that view dirty, because `mark_view_dirty` only resolves views through the dispatch tree. Release Notes: - [GPUI] Fixed entity notifications failing to redraw windows when the entity was read by a deferred draw or a paint callback inside a reused cached view. --------- Co-authored-by: Lukas Wirth <lukas@zed.dev> |
||
|
|
26abd1c959 |
gpui_platform: Extend benchmarks and add a two-revision comparison script (#66316)
Extends the GPUI benchmarks in `gpui_platform` and adds `script/gpui-bench-compare` for quick before/after comparisons. No runtime behavior changes. The only new GPUI APIs are `bench-support`-only: `Window::rendered_scene()` and `BenchWindowContext::simulate_resize`. ## Benchmarks - **`RandomizedTree/mixed` and `CachedTree/mixed`:** the general benchmark. Each iteration applies a fixed, seeded sequence of changes to a freshly built tree, one per frame: restyles, resizes, structural edits, reorders, pointer moves, scroll events, focus moves and window resizes, while some entities animate. Every iteration does exactly the same work. - **Single-change groups:** element style, leaf bounds, root layout, insert/remove, reorder and hover. They explain where a difference in the mixed workload comes from. - **`CachedTree`:** the same workloads with entities wrapped in `.cached()`. - **`TextPanels`, `Scroll` and `LayoutChurn`:** text updates and first frames, three scrolling workloads, and entity/ID/text churn. `LayoutChurn` also prints a heap check before timing. - **`Primitives`:** seeded random quads, shadows, underlines, paths and text, plus fixed overlap patterns, painted through a window and directly on `Scene`. - **The randomized tree fixture:** now draws paths, shadows, scroll containers, text, hover styles and optional animations. The benchmarks don't check their output; that's left to the fixture's tests. On macOS and Linux, frames include GPU submission through the headless renderer. Text benchmarks are skipped on Windows and on macOS without `font-kit`, because neither has a real headless text system. ## Comparison script `script/gpui-bench-compare BASE NEW` builds both revisions once and alternates short runs of 25 core cases. It reports foreground instructions per frame, wall time and run-to-run spread, in about 3 minutes. It also accepts `--filter`, `--full`, `--repetitions` and `--slow`. Both revisions must include this PR. ## Validation - A/A runs: within ±0.15% on the mixed cases and ±0.34% or better on the core suite. - All 193 `--test` cases pass (`SEED=0 ITERATIONS=1`, `bench-support,font-kit,inspector`). - The fixture's tests and `./script/clippy` pass. - A full `cargo bench` takes about 13 minutes on an M-series Mac. I haven't run it on Linux. ## Follow-ups - Add hiding the root to `CachedTree/mixed` once the `.cached()` visibility bug is fixed. - Add text edits, keyboard input, scale changes, overlays, virtual lists, images and drag and drop to the mixed workload. - Add images and SVG icons to the `Primitives` random case. - Measure GPU time, memory and upload bandwidth next to CPU instructions. - Cover hover and animation in the fixture's render-equivalence test. - Bring the window-painted `Primitives` random case into the core suite once GPU noise is separated out. Release Notes: - [GPUI] Added a mixed-workload benchmark, plus cached-view, hover, text, scrolling, layout-churn and primitive benchmarks, and `script/gpui-bench-compare` for quick instruction-count comparisons between two revisions |
||
|
|
c408f8efc4 |
gpui: Improve borrow and window error diagnostics (#66358)
## Summary - Preserve the attempted borrow location and existing App borrow origin in fallible borrow errors, using a compact anyhow result without a redundant standard borrow error. - Propagate caller locations through window-update wrappers and share diagnostic formatting between returned errors and panics. - Add operation and window context to all 34 log_err sites in window.rs. Context formatting runs only on failure. ## Validation - cargo nextest run -p gpui app::test:: — all 5 existing tests passed. - Formatting checks passed for the changed Rust files. - No test changes are included in this PR. - The original Delta reentrancy trigger was not reproduced; this improves diagnostics, not the underlying reentrancy behavior. Release Notes: - [GPUI] Improved App borrow and window-operation errors with caller locations, borrow origins, and operation context. |
||
|
|
14b7b0ef37 |
gpui_linux: Replace kde-blur protocol with ext-background-effect protocol (#53746)
Replaces the `kde-blur` protocol (which is now deprecated and being [removed from kde](https://invent.kde.org/plasma/kwin/-/commit/7f9e0aa1cd2c2ab4fea1097800893b6f780089eb)) with the new [ext-background-effect](https://gitlab.freedesktop.org/wayland/wayland-protocols/-/blob/main/staging/ext-background-effect/ext-background-effect-v1.xml) protocol (which is supported by niri, new KDE releases, and more compositors over time) # Current questions - Currently, the PR completely removes the old KDE blur and replaces it. Should we keep the old kde-blur implementation and use it as a fallback? - Since the protocol technically supports adding new capabilities and types of background effects, should zed track if the compositor supports the protocol, and only try blurring then? The protocol seems to imply that you can still use [set_blur_region](https://wayland.app/protocols/ext-background-effect-v1#ext_background_effect_surface_v1:request:set_blur_region), but the compositor will do nothing - Since the protocol is generic, should it be checked when resizing to see if the window should be blurred before updating the blur region? Currently it doesn't do it, since it's implied (a note has been added to the code) - I wonder if this could be expanded to where popovers (such as diagnostic popovers) can become their own wayland surfaces, and thus also be blurred (so a transparent warning popover/diagnostic can properly blur the text underneath for readability, rather than it having to be opaque). That sounds like a major refactor/out of scope though, not even sure if it's possible (I'd love to work on it though, if the team has any pointers on how to get started) I'm keeping this PR as a draft until those points are figured out/commented on Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments - [x] The content is consistent with the [UI/UX checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) - [/] Tests cover the new/changed behavior - I do not know how to test this, and the old implementation wasn't tested - [/] Performance impact has been considered and is acceptable - I don't see how this would affect performance Release Notes: - [GPUI] wayland: deprecate kde-blur protocol, implement and default to ext-background-effect --------- Co-authored-by: Alexander Bachmann <a.t.bachmann@gmail.com> Co-authored-by: Tom Houlé <tom@tomhoule.com> |
||
|
|
99e70ee4a0 |
gpui: Time animations with the executor clock (#66317)
Animations and springs measured elapsed time with `Instant::now()`, which tests can't control, so tests that advance the fake clock between frames stepped them by however much real time passed. This made `test_spring_animation_preserves_velocity_when_retargeted` fail intermittently. They now use the executor's clock, as synced animations already do: the platform's monotonic clock in production, and the test clock in tests. Release Notes: - [GPUI] Fixed animations measuring time with the wall clock instead of the executor's clock, which made animation tests nondeterministic. |
||
|
|
8fa085e397 |
gpui: Repaint cached views when inherited opacity changes (#65951)
A clean `cached()` view under a parent whose opacity changes kept painting with the old opacity, because the cached view's reuse key didn't include inherited opacity. This adds inherited opacity to the reuse key, and passes a div's opacity down during prepaint as well as paint, since the reuse decision happens in prepaint. Children's prepaint now sees the inherited opacity; the cache key is the only thing that reads it there. Prepaint can only predict the opacity paint will apply: an ancestor's hover or drag-over style depends on the frame's hit test, which isn't known until paint. So the key records the opacity that was actually painted, and if reused output ends up painted under a different opacity, the view redraws on the next frame. Opacities are compared by bits, so a NaN opacity doesn't disable the cache. Tests cover a wrapper's opacity changing (fails on main), hover opacity on mouse enter and leave, and a hover that starts without a mouse move because the wrapper grew under the pointer. While an ancestor's opacity animates, cached views under it re-render every frame. Applying the alpha at replay instead could avoid that and is left as a follow-up. Release Notes: - [GPUI] Fixed cached views retaining stale paint opacity when an ancestor's opacity changes. |
||
|
|
2529740084 |
gpui: Wrap arena in an Rc to prevent UB (#66293)
Attempting to repro an unrelated bug with miri discovered UB in the way we handle the arenas. Previously, the `App` struct had a `RefCell<Arena>` field. A `*const` to this refcell was stored in a thread-local, which, when allocating elements, is then converted to a `&RefCell<Arena>`, and then `.borrow_mut()`-ed and `Deref`-ed into a `&mut Arena`. However, at the same time, we produced a `&mut App` reference, which claims unique write access to the fields of `App`, including the `RefCell<Arena>` (and therefore the `Arena` itself). Since we were producing a `&mut App`, at the same time as a `&mut <field of that App>`, and that second reference was derived from a thread local, it's UB (miri reports it in both stacked-borrows and tree-borrows modes). Wrapping it in an `Rc` breaks this "exclusive claim", since the `&mut App` only implies exclusive access to the `Rc` itself (i.e. the `RcInner` pointer), but not the `RefCell<T>` itself. Release Notes: - [GPUI]: n/a |
||
|
|
bc7041c600 |
Fix standalone modifier sequences not being flushed after timeout (#55800)
### Summary
Standalone modifier keys were not timing out, causing them to linger in
pending state and incorrectly form multi-stroke sequences (e.g.
triggering `shift shift` after IME switching).
### Details
Standalone modifier keystrokes (e.g. `shift`) were not participating in
the key sequence timeout lifecycle, causing them to remain in the
pending input state indefinitely.
In Chinese IME, `shift` is commonly used to toggle between EN and ZH
modes.
A typical workflow is:
1. Tap `shift` to switch to Chinese input
2. Type some Chinese text
3. Tap `shift` again to switch back to English
However, due to the missing timeout behavior, the first `shift` remains
in the pending sequence.
As a result, the second `shift` is interpreted as `shift shift`, which
incorrectly triggers the command palette.
### Reproduction
1. Use the following keymap, or enable the JetBrains keymap:
```json
[
{
"bindings": {
"shift shift": "command_palette::Toggle",
},
}
]
```
2. Press the `shift` key twice with an interval greater than the timeout
(1 second)
3. The command palette is toggled (unexpected; it should not be
triggered)
### Fix
If the pending input sequence contains only a standalone modifier, mark
it as requiring a timeout, so it is flushed after the timeout.
### Test
Tests are added to cover:
- timeout flushing of standalone modifiers
- successful dispatch when the sequence completes before timeout
---
Self-Review Checklist:
- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable
~~Closes #ISSUE~~
Release Notes:
- [GPUI] Fixed standalone modifier keys no longer lingering in the
pending input state indefinitely. This prevents them from incorrectly
forming multi-stroke shortcuts after long intervals
|
||
|
|
7c8dbadcb5 |
gpui: Make power and thermal frame intervals configurable (#66281)
## Summary Expose `low_power_frame_interval` and `thermal_frame_interval` on `WindowOptions`, alongside the existing `inactive_frame_interval`. Defaults remain approximately 30 fps in Low Power Mode and 60 fps under serious or critical thermal pressure. Each option accepts `None` to disable that particular limit. When multiple limits apply, the longest interval wins; mandatory platform presentations continue to bypass throttling. Profiler skip reasons identify the effective limit. Applications can now choose their own limits without changing GPUI internals. This does not add application settings UI. Release Notes: - [GPUI] Added configurable Low Power Mode and thermal-pressure frame intervals to `WindowOptions`, with the most restrictive enabled limit taking precedence. |
||
|
|
2c2f737ab2 |
gpui: Add sendable foreground execution for web HTTP clients (#66165)
## Summary This cleans up the gpui_platform code a bit, and in combination the way we set up the http client for the web. This does introduce a `ForegroundExecutor` variant that it itself is Send-able, allowing to dispatch foreground futures from background workers (by requiring the future to be Send, unlike `ForegroundExecutor`), which is a requirement for web fetch. a31c7b54c60738b82524e4e4c12aec2f6caf101d fixes a bunch of warnings with our binary names Release Notes: - [gpui] N/A |
||
|
|
f0210f1621 |
gpui: Use UAX #14 line breaking for text wrapping (#64624)
Replaces the `is_word_char` list with Unicode line breaking ([UAX #<!-- -->14](https://www.unicode.org/reports/tr14/)) using the `icu_segmenter` crate. `is_word_char` can't express line breaks that depend on both neighboring characters, so currently wrapped lines sometimes start with `/` or `?`, and some emojis like 👍🏽, 🇯🇵, and 👩💻 get incorrectly split across lines: https://github.com/user-attachments/assets/2a8a9eee-11c9-4143-b56c-3a2b4621af9a This generalizes the tweaks from #11296, #17590, #35724, #37019, #37024, #45160, #51659, #51973, #54546, #59775, and #62743, and supersedes #62345 and #63983. Important to note: - This allows hyphenated words to break after the hyphen which is a behavior change. I believe UAX #<!-- -->14 does permit tweaking this in case we want to keep the current behavior, by filtering those out of the `break_indices` return value. - Obviously this isn't quite as performant as `is_word_char`, but it seems to still be plenty fast enough, as I wasn't able to come up with a contrived case where this causes noticeable performance issues. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments - [x] The content adheres to Zed's UI standards ([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist) and [icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md) guidelines) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Improved text wrapping to follow Unicode line breaking rules. - [GPUI] Improved text wrapping to follow Unicode line breaking rules. --------- Co-authored-by: Noritada Kobayashi <noritada.kobayashi@gmail.com> Co-authored-by: Lukas Wirth <lukas@zed.dev> |
||
|
|
2580a00264 |
gpui: Apply frame limits consistently and stabilize pacing (#66237)
## Summary Apply GPUI frame limits consistently to input-driven redraws, animation callbacks, forced renders, and retained presentation requests. Previously dirty-only redraws bypassed the limiter, so the effective cadence depended on the source of frame demand. Explicit mandatory platform presentations still bypass the limits. Release Notes: - [GPUI] Improved frame pacing under frame-rate limits by applying limits consistently to redraws and animations and bounding timing corrections after delayed frames. |
||
|
|
e4a3732b94 |
gpui: Fix text system reference cycle through pooled line wrappers (#66206)
`TextSystem` pooled whole `LineWrapper`s, and each wrapper owns an `Arc<TextSystem>`, so once any text was wrapped the pool kept its own text system (and font caches) alive forever. This leaked one text system per app for tests and embedders that create and drop apps. The pool now keeps only each wrapper's per-font character width caches (`CharWidthCache`), so the cache reuse is preserved without the cycle. A regression test checks that a `TextSystem` is released after wrapping a line and dropping all handles. Release Notes: - [GPUI] Fixed a memory leak where a `TextSystem` was never freed after wrapping text, due to a reference cycle through its line wrapper pool |
||
|
|
fdcb198110 |
gpui: Smooth frame pacing in macOS Low Power Mode (#63477)
# Objective On macOS, Low Power Mode reduces the CPU and GPU performance available to applications. GPUI continued requesting animation frames at the normal cadence, so work that no longer fit inside every refresh produced irregular frame drops instead of a deliberate lower frame rate. Frame throttling could also reject a display-link callback that arrived a fraction of a millisecond before the mathematically exact target interval. On a 120 Hz display, for example, a measured 16.666 ms interval missed a 16.667 ms threshold and delayed the frame until roughly 25 ms, intermittently turning a 60 fps cap into 40 fps. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments - [x] The content adheres to Zed's UI standards - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - [GPUI] Improved animation smoothness on macOS when Low Power Mode is enabled. --------- Co-authored-by: Anthony Eid <hello@anthonyeid.me> |
||
|
|
dde76a1dca |
gpui: Some gpui cleanups (#66156)
## Summary Some general reshuffling cleanups, more notable are the SubscriberSet changes: - Add a concrete `SingleSubscriberSet` for single-emitter observers, removing the unnecessary outer map and emitter-key arguments. - Keep `SubscriberSet` for observers grouped by entity or type. - Replace separate activation and cancellation flags with one shared `Pending | Active | Dropped` state, saving one `Rc` allocation per subscription. - Make `insert` immediately active and add `insert_pending` for deferred activation, simplifying callers while preserving existing activation timing. - Preserve registration order and cancellation behavior when callbacks add or drop subscriptions during dispatch. Merge retained subscriptions with `BTreeMap::appen`d, avoiding rebuilding the tree when the destination is empty. Best reviewed commit by commit. The first commit [1740a07](https://github.com/zed-industries/zed/pull/66156/commits/1740a0718faddf57feb8cb0946a286585548ad3f) re-orders the import / mod prelude a bit and gets rid of the lint allows by fixing their offenses. Release Notes: - [GPUI] N/A |
||
|
|
370591f3d1 |
gpui: Defer native window close cleanup to avoid reentrant app borrow (#66181)
Defer the shared native window-close callback to a foreground task so Windows destruction messages can arrive while GPUI is borrowed without panicking or skipping cleanup. The task removes the window if still present, then removes its system tab; a regression test delivers the close notification while the app is borrowed and verifies cleanup after tasks drain. Opus 5.5 review passed, and the focused test passed after rebasing onto main (using Cargo after a Corgi Metal-toolchain failure); the Wasm check passed before rebasing. Native Windows behavior has not been exercised. Fixes [FR-531](https://linear.app/zed-industries/issue/FR-531/zed-ck4-refcell-already-borrowed), tracking [ZED-CK4](https://zed-dev.sentry.io/issues/7796580884/). Release Notes: - [GPUI] Fixed a panic when native window destruction re-entered GPUI while the app was borrowed, including on Windows. |
||
|
|
2a74c8dff6 |
gpui: Remove unused hash-based text layout cache (#66152)
The hash-based text layout interface was introduced for an earlier Delta editor prototype, but neither Zed nor Delta has any remaining callers. Let's remove it and re-introduce it proper when needed. Release Notes: - [GPUI] Removed an unused hash-based text layout cache interface. |
||
|
|
772a8a9100 |
gpui: Remove synchronization from window text layout (#66147)
## Summary There isn't really any reason for us to use synchronization here at this layer. `WindowTextSystem` gains little from being `Send`, allowing us to simplify this a bit. Release Notes: - [GPUI] Improved per-window text layout performance by removing unnecessary synchronization. |
||
|
|
79fe6a645f |
gpui: Add a way to write credentials only if none exist (#66062)
Apps that keep a shared secret in the system keychain, such as an encryption key, create it on first use. With only `read_credentials` and `write_credentials`, two processes can both find no secret, and the second write then replaces the first. Data encrypted with the replaced secret can no longer be read. Add `write_credentials_if_not_exists`, which returns `true` if it wrote the credentials and `false` if they already existed. It never replaces an existing secret. On macOS this is a single atomic `SecItemAdd`: an existing item with the same URL and username makes it return `false`. Other platforms and providers get a default that reads and then writes. That default never overwrites credentials it can see, but two concurrent callers can still race. A failed read, including a cancelled Keychain prompt, never writes. `write_credentials` keeps its update behavior. Release Notes: - [GPUI] Added `write_credentials_if_not_exists`, which never replaces existing credentials and is atomic on macOS |
||
|
|
389c22e1c7 |
gpui: Make Modifiers::secondary web platform aware (#65970)
This introduces a new PlatformInfo abstraction that allows querying a gpui app's platform from runtime facts. This is necessary for correctness when dealing with web applications, as their host platform there is a runtime fact, not a compile time fact. Release Notes: - [GPUI] Fixed platform-dependent modifiers and keybinding parsing and formatting in web applications by querying the host operating system at runtime. |
||
|
|
b7d50b95e8 |
Warn only for explicitly requested fonts (#65968)
Follow-up to https://github.com/zed-industries/zed/pull/65852 Release Notes: - [GPUI] N/A |
||
|
|
3389d87577 |
Cache resolved fonts (#65852)
Closes https://github.com/zed-industries/zed/issues/65777 Release Notes: - [GPUI] Fixed font lookup causing performance issues |
||
|
|
b488c4e814 |
gpui: Update Taffy 0.13 to 0.15 (#65950)
Updates Taffy from 0.13 to 0.15. Upstream reports roughly 60% faster grid layout and 15% faster flexbox layout, alongside layout caching improvements and fixes to sizing, alignment, and absolute positioning. This adapts GPUI to the updated measurement and alignment APIs while retaining its explicit relative-positioning default; performance improvements have not been benchmarked in Zed. Validation: All 469 existing GPUI library tests passed with `corgi test -p gpui --lib -F gpui_platform/runtime_shaders`; formatting and diff checks passed. Runtime shaders were enabled to bypass a local Metal compiler failure. Release Notes: - [Gpui] Update taffy version |
||
|
|
f41ac64812 |
agent: Parse thread markdown lazily, on first render (#65470)
## Summary Opening an agent thread previously materialized parsed Markdown for message and tool-output blocks before those blocks were laid out, including blocks far off-screen. Parsed Markdown can retain events, per-code-block syntax highlights, and rasterized Mermaid diagrams. The original debug-build profiling with two large threads open attributed approximately 295 MiB to `markdown`, with individual assistant or tool blocks accounting for tens of MiB. The profiling figures below are from the original measurements and were not rerun during the final review. The thread view uses a virtualized `gpui::list` (`ListState`), but layout also includes overdraw and can include focused off-screen rows. Previously, parsing started at entity creation in `acp_thread`, independently of list layout. With `MarkdownOptions::defer_parsing`, `Markdown` records the source without parsing until one of these occurs: - `MarkdownElement::request_layout` lays out the block. - `Markdown::ensure_parsed(cx)` is called explicitly. While deferred, source updates through `append` and `reset` do not start parsing. Once parsing starts, later source updates parse normally, including when the block is off-screen. This is one-time lazy activation, not eviction of previously parsed blocks. `acp_thread` enables deferral for message content created through `ContentBlock::create_markdown`, including assistant and tool messages and compaction summaries, and for tool-call raw input and output. Tool-call labels and error text remain eager. The numbered `read_file` output bypasses `MarkdownElement` to draw its own gutter. Its `RenderOnce` component now calls `ensure_parsed` before reading the code-block language for highlighting. Raw source remains available before parsing for search, copy/export, and content-visibility checks. Restoring a thread applies its saved scroll position before deferred Markdown has finished measuring. `ListState::set_item_measurement_readiness` lets the thread report pending Markdown parsing and Mermaid rendering, including compaction summaries and errors. The list preserves scroll intent while measurements remain provisional. Leading overdraw stops at the first unready preceding row rather than traversing the entire zero-height prefix. Search autoscroll also waits for parsing and Mermaid rendering to finish. ## Original memory measurements The original before/after heap profiles used uncapped dumps of the same view: two large threads and one expanded tool card. | | Before | After | | ---------------------------------------- | --------: | --------: | | `markdown` category | 273.7 MiB | 109.5 MiB | | Parsed events (`start_background_parse`) | 213.0 MiB | 11.0 MiB | Deferred blocks that have not been laid out or explicitly activated do not retain a parsed representation. Raw source remains available, and blocks that have already been parsed are not evicted merely because they leave the viewport. Companion PR: #65444. ## Testing - Agent UI library suite: 519 passed. - Three scroll-restoration regressions across 20 scheduler seeds each: 60 successful runs. - GPUI list tests: 36 passed. - Focused Markdown/Mermaid tests: 21 passed. - ACP compaction regression: passed. - Five regression assertions fail with the corresponding fixes removed. - Two adapted controls fail on main with production code unchanged. - Scoped `rustfmt` and `git diff --check` passed. Validation used isolated Cargo build artifacts and `INPUTRC=/dev/null` for the agent-UI suite. Interactive visual behavior was not manually validated during this review. Release Notes: - Improved agent panel memory usage by parsing thread message Markdown on first layout instead of at thread load. - [GPUI] Added `ListState::set_item_measurement_readiness` to preserve scroll intent while asynchronously measured list items settle. --------- Co-authored-by: Kirill Bulatov <kirill@zed.dev> Co-authored-by: Kirill Bulatov <mail4score@gmail.com> |