Commit Graph

29 Commits

Author SHA1 Message Date
Anthony Eid 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
2026-11-13 16:33:49 +00:00
Eric Holk 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>
2026-11-12 20:28:32 +00:00
John Tur 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
2026-11-12 08:19:31 +00:00
John Tur 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>
2026-11-12 08:19:30 +00:00
Anthony Eid 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
2026-11-09 04:15:58 +00:00
Anthony Eid 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
2026-11-02 02:46:28 +00:00
Lukas Wirth 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
2026-10-29 09:12:10 +00:00
richerfu 484bcbfea6 feat(gpui): Allow building gpui against ohos (#64579)
# Objective

This PR will allow to develop and use gpui ohos platform's crate.We need
to use ohos instead of linux logic.

## Solution

- Avoid linux logic when target is ohos.
- Add gesture for ohos.

## Testing

I've already test it in HarmonyOS emulator and physical HarmonyOS
device.

## 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

I made a gpui backend crate for OpenHarmony
[gpui-ohos](https://github.com/ohos-rs/gpui-ohos) and Using it to
develop an application which already publish into Huawei store for a
long time.

Here is [source code](https://github.com/richerfu/nearsend/pull/14)

Here is a video to show it.



https://github.com/user-attachments/assets/26efe4f7-d5ef-473f-8dbd-e30ab14ec186


---

Release Notes:

- [GPUI] N/A
2026-10-26 15:29:14 +00:00
Kirill Bulatov 1808df02c0 Remove block dependency from the tree (#65942)
Closes https://github.com/zed-industries/zed/issues/22408

See also
https://github.com/zed-industries/scap/commit/b5c86ec58dd4b6b7732bf6ac8be03d6b1f190a82
that makes all macOS dependencies optional: we do not use these in Zed
anyway, and have `default-features = false` that allow to remove all
transitive `block` dependencies from the tree.

Adjust the test to ensure no such dependencies can appear later.

Release Notes:

- [GPUI] Removed `block` dependecy from the tree
2026-10-26 11:20:06 +00:00
Kirill Bulatov e463c5ab74 Fix focus cleanup stalls during conversation restoration (#65177)
Noticed hangs when opening certain agent threads, hang sample: [Sample
of Zed
Nightly.txt](https://github.com/user-attachments/files/33056833/Sample.of.Zed.Nightly.txt)

Focus cleanup scanned the entire handle registry before each app effect,
amplifying work while restoring large conversations. Queue final handle
drops instead and process only those IDs at the existing cleanup
boundary, preserving blur and pending-input behavior.

Recheck subagent registration after loading to avoid duplicate views and
subscriptions from concurrent loads.

Add targeted regression coverage and a focus-cleanup benchmark.

Release Notes:

- Fixed threads with subagents restoration causing hangs
- [GPUI] Improved focus cleanup performance when many focus handles are
retained or released
2026-10-14 17:42:31 +00:00
Anthony Eid a47f721832 gpui_ios: Add iOS platform backend (#63068)
This adds an experimental `gpui_ios` backend so GPUI applications can
run on iPhone and iPad. It uses typed objc2 UIKit subclasses with
Rust-owned application and scene delegates, and it builds on the
`gpui_apple` services and Metal rendering already on `main`. UIKit
touches go through GPUI's portable touch and gesture handling, and
safe-area and keyboard geometry are exposed as window insets. Native
text input goes through a focused `UITextInput` bridge. Each field gets
its own text-input session, so offsets from one field can't edit
another, and GPUI focus is kept when the keyboard is dismissed. The
backend is registered with `gpui_platform`, and the PR includes a small
standalone Rust example that can be built and run in the iOS simulator.

This is initial support, not full desktop or mobile feature parity.
Native edit menus and networking/TLS workarounds are deferred to
follow-ups, and the Return key and hardware-keyboard shortcuts are not
yet delivered as GPUI key events. The backend's unit tests and a native
UIKit text-input test pass on the iPhone and iPad simulators, the
example runs in the simulator, and it links for physical iOS devices.

Release Notes:

- [GPUI] Added an experimental iOS platform backend with a standalone
Rust example.

---------

Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-10-14 17:01:58 +00:00
Hernán Fernández a2a92fe7c4 gpui_platform: Forward gpui_webs multithreaded feature instead of forcing it (#65289)
## Summary

I'm building a single-threaded web app on `gpui_web`, served as static
files, and I can't build it on stable Rust. `gpui_web`'s default feature
`multithreaded` pulls in `wasm_thread`, which needs the unstable
`stdarch_wasm_atomic_wait` feature gate. With `default-features = false`
the crate checks clean on stable, but `gpui_platform` depends on
`gpui_web` with defaults, so using the platform helper on wasm,
including its `single_threaded_web()`, brings the feature and nightly
back. Threads in a browser also need COOP/COEP headers and `build-std`,
so for a static site the single-threaded platform is the normal case.

This declares `gpui_web` without default features in the workspace and
has `gpui_platform` forward `multithreaded`, on by default. Nothing
changes unless a consumer opts out with `default-features = false`.
`hello_web` keeps its threads since it takes the helper's defaults.

## Testing

In this workspace, on stable: `cargo check -p gpui_platform --target
wasm32-unknown-unknown --no-default-features`. On nightly, the same with
defaults, which is the status quo path. `cargo check -p gpui_platform`
on the host, since `gpui_web` is only a wasm dependency and the feature
reference must still be accepted there. And `cargo tree -p gpui_platform
-e features --target wasm32-unknown-unknown` with and without
`--no-default-features`, showing `wasm_thread` present and then absent.

## 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). (No UI
change.)
- [ ] Tests cover the new or changed behavior. (A manifest change, the
tree and check commands above are the test.)

I used an AI assistant, which helped me trace where the feature gets
switched on. I've reviewed the changes and verified the checks above
pass on my machine.

Release Notes:

- N/A
- [GPUI] The multithreaded feature for `gpui_web` can now be forwarded

Co-authored-by: Lukas Wirth <lukas@zed.dev>
2026-10-09 08:23:20 +00:00
Cameron Mcloughlin f37989fbdf gpui: Cross-platform headless windowing API and linux impl (#64969)
Adds a cross-platform API for GPUI apps to switch between windowed and
headless modes.

Release Notes:

- N/A
- [GPUI]: N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
2026-10-02 16:04:33 +00:00
Anthony Eid 3135cdf8dc gpui: Add randomized element tree benchmarks and fix Linux benchmark leaks (#64842)
Adds a seeded, randomized element tree for benchmarking GPUI rendering,
and a Criterion suite that measures what one frame costs under each
class of change. Running it on Linux exposed thread leaks in the
benchmark harness and in the Linux dispatcher that made every
`#[gpui::bench]` binary slow down as it ran; those are fixed here too.

## Randomized element tree (`gpui::randomized_element_tree`, behind
`bench-support`)

A tree of elements and entities generated from a `StdRng`, with wide,
deep, mixed and narrow topologies, entity-backed elements, and
interaction handlers. It supports the mutations a UI goes through (child
color and bounds, root bounds, insert, leaf removal, reorder, recoloring
a share of the tree either localized to one entity subtree or spread
out) and counts what re-rendered, so benchmarks can assert the renderer
did the work. `RandomizedElementTreeBounds` describes a family of trees
(topologies, element-count and density ranges) and `sample(&mut rng)`
draws one.

## Benchmarks (`gpui_platform/benches/randomized_element_tree.rs`)

Groups, each measuring frames in which exactly one thing happens: full
refresh (`Window::refresh`), unchanged (a notified root), leaf style,
leaf bounds, root layout, insert-remove, reorder, and a changing-share
grid (0/1/5/25/100% localized, 5/25% spread).

- **Families:** `any`, `wide`, `tall`, `mixed` and `dense-entities`,
each with at least 5% entities. Each family is a `#[gpui::bench]` input
seeded through the `StdRng` support from #64843, so ids read
`RandomizedTree/<group>/tree/<family>/seed-<n>` and `SEED`/`ITERATIONS`
choose trees as they choose `#[gpui::test]` seeds. The family name is
mixed into the RNG so overlapping families don't draw the same tree at
the same seed.
- **Reports:** each tree is described once with the heap its window
holds after the first frame. The bench report adds instructions,
allocations and frame timings from `bench_metrics`, and a final summary
prints each group and family's geometric mean of time and allocations
per iteration across seeds.
- **Run time:** two seeds per family (one for the changing-share grid)
and a 0.5 s warm-up with a 1 s measurement: 105 benchmarks in about 4.5
minutes on Linux. `ITERATIONS=6`, `--warm-up-time` and
`--measurement-time` give a longer run.
- **Checks:** every measured loop asserts that the tree actually
re-rendered, so a faster frame that skipped the changed element fails
rather than passing as an improvement.

```
cargo bench -p gpui_platform --features bench-support --bench randomized_element_tree [-- FILTER]
```

## Linux fixes for `#[gpui::bench]` and the dispatcher

On Linux the full suite reached thousands of threads and took about 40
minutes, each benchmark slower than the last. Measured frame times are
unchanged by these fixes.

- **A platform per routine call.** `#[gpui::bench]` builds a context for
every Criterion routine call, and each built a whole
`gpui_platform::current_platform(true)` just to take its text system.
`gpui_platform::bench_text_system()` now builds it once per thread.
- **A GPU device per window.** `WgpuHeadlessRenderer::new` created a new
wgpu device each time, about 65 ms per call. `WgpuContext::new_headless`
now shares one device per process, held in a static that is never
dropped (wgpu's queue reads its own thread-locals on drop, so a
thread-local cache aborted on thread exit), and creates a new one if it
is lost. Device errors are tracked per device, so a renderer joining a
shared device observes only errors raised from then on.
- **Dispatcher threads outlived their platform.** Dropping a Linux
platform left all 21 threads running. Workers block in
`PriorityQueueReceiver::recv`, which checked for dropped senders only
before waiting, and dropping the last sender never signalled the
condition variable. It now wakes every waiter (acquiring the queue lock
first so no receiver misses the wake-up), `recv` re-checks after each
wake, and the timer thread's event loop stops when its channel closes. A
regression test fails on the old code and passes with the fix. The
editor builds one platform per process, so it isn't affected in
practice; benchmarks, visual tests, and
`gpui_platform::background_executor()` are.

## Validation

On Linux:
- Full suite: 105 benchmarks in 262 s, none failing, with the thread
count flat (about 63 to 68) and live heap between routine calls flat (6
to 8 MB). Before the fixes: about 40 minutes, 2,315 threads 20 s into a
group.
- One frame per iteration: window draws equal iterations exactly, and
each iteration renders the root once and every element once.
- `gpui` (437, run on one thread, since 4 profiler and `bench_context`
tests share global state and also fail in parallel on `main`) and
`gpui_linux` (42) tests pass; clippy and fmt are clean.

On `main`, every class of change costs about the same as a full refresh,
and the changing-share grid is flat from 1% to 100%, because any notify
re-renders the whole tree. That's the curve retained rendering should
bend.

Release Notes:

- [GPUI] Added randomized element tree benchmarks, and fixed Linux
platform threads not exiting when the platform is dropped and
`#[gpui::bench]` creating a platform and GPU device for every iteration

---------

Co-authored-by: Mikayla Maki <mikayla.c.maki@gmail.com>
2026-09-28 16:17:17 +00:00
Anthony Eid e91b82c106 gpui_wgpu: Add Linux headless rendering (#64718)
## Summary

Add Linux WGPU headless rendering for GPUI tests and benchmarks without
creating a display surface or window.

- Extract a concrete `WgpuRendererCore` shared by the windowed and
headless wrappers, retaining production pipelines, atlas handling, and
frame encoding.
- Reuse an offscreen render target between same-size frames. Normal
rendering submits GPU work without screenshot readback; image capture
performs aligned readback and returns RGBA pixels.
- Reuse adapter ranking, including the `ZED_DEVICE_ID` preference.
Reject software adapters by default, with an explicit software-allowed
constructor for functional tests.
- Wire Linux platform selection through separate `bench-support` and
`test-support` features. Propagate initialization failures rather than
silently running a benchmark without a renderer.
- Preserve upstream atlas bind-group caching and window lifecycle
behavior.

This is a fresh implementation following discussion of #62341, not a
continuation of that PR. It does not include a Criterion upgrade,
hardware counters, benchmark CI, or GPU timing queries.

## Validation

After merging `origin/main` at `baee1ca6de`:

- `cargo test -p gpui_wgpu` — 38 tests passed.
- `cargo test -p gpui_wgpu --features test-support` — passed.
- `env -u DISPLAY -u WAYLAND_DISPLAY cargo test -p gpui_wgpu
headless_renderer` — passed.
- `cargo check -p gpui_platform --features bench-support` — passed.
- `cargo check -p gpui_platform --features 'test-support,wayland,x11'` —
passed.
- `cargo check -p gpui_wgpu --target wasm32-unknown-unknown` — passed.
- Formatting and diff checks passed.
- Verified the `gpui_wgpu` benchmark feature graph does not enable
`test-support`.

Windowed rendering and device recovery have compile coverage but have
not been manually exercised after the refactor. Headless timings
represent CPU rendering/submission, not display latency or
GPU-completion time.

## Suggested .rules additions

For `gpui_wgpu`: Tests requiring GPUI test contexts must be gated on
`test-support`, rather than enabling that feature unconditionally in a
dev dependency. Cargo unifies dev-dependency features into this crate's
benchmark targets.

Release Notes:

- [GPUI] Added headless renderer support for WGPU on Linux for
benchmarks and testing.
2026-09-25 17:49:48 +00:00
Finn Evers aec7395e30 Fix cargo shear warnings (#64340)
Also updates CI to always run this - that way we ensure that disabling
or enabling tests does not become stale at some point and thus can
safely add this.

Release Notes:

- N/A
- [GPUI] N/A
2026-09-17 08:49:31 +00:00
Kirill Bulatov b0f53ad23b Optimize GPUI inspector's runtime cost by an order of magnitude (#64309)
Prerequisite to https://github.com/zed-industries/zed/pull/64257

* gpui: build inspector IDs only when the window's inspector exists,
drop the inspector maps on close, skip inspector state lookups for
absent or non-selected IDs
* gpui: create inspector element renderers per inspector instance
instead of at registration
* inspector_ui: create the project and editors lazily per inspector
session, keep the init task and subscriptions cancellable, hold the
inspector weakly from the completion provider
* lsp: bound the shutdown output drain by the same timeout as the
shutdown request
* gpui_platform: add an `inspector_render` benchmark that builds with
the inspector in or out

Mean time per rendered frame with the inspector closed; overhead is
relative to the inspector compiled out.

| Benchmark | Frame, compiled out | Frame, `main` | Frame, this PR |
Overhead on `main` | Overhead on this PR |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1,000 bare divs, never opened | 3.352 ms | 3.505 ms | 3.362 ms | +153
µs (+4.57%) | +10 µs (+0.29%) |
| 1,000 bare divs, opened and closed twice | 3.349 ms | 3.508 ms | 3.364
ms | +159 µs (+4.76%) | +15 µs (+0.46%) |
| 100 bare divs, opened and closed twice | 317.0 µs | 336.3 µs | 317.6
µs | +19 µs (+6.10%) | +1 µs (+0.18%) |
| 10,000 bare divs, never opened | 56.617 ms | 58.925 ms | 56.472 ms |
+2.31 ms (+4.08%) | -145 µs (-0.26%) |
| 500 panel rows with text, hover, click, never opened | 4.173 ms |
4.451 ms | 4.179 ms | +278 µs (+6.67%) | +7 µs (+0.16%) |
| 500 panel rows with text, hover, click, opened and closed twice |
4.197 ms | 4.448 ms | 4.159 ms | +252 µs (+6.00%) | -37 µs (-0.89%) |
| 50 panel rows with text, hover, click, never opened | 523.4 µs | 543.3
µs | 522.3 µs | +20 µs (+3.80%) | -1 µs (-0.21%) |
| 500 panel rows with text, hover, click, opened and closed twice,
another window inspected | 4.191 ms | 4.469 ms | 4.176 ms | +278 µs
(+6.64%) | -15 µs (-0.35%) |
| editor, cursor moves (`crates/benchmarks`, `release-fast`) | 940.9 µs
| 943.0 µs | 942.5 µs | +2 µs (+0.23%) | +2 µs (+0.17%) |




Release Notes:

- N/A
- [GPUI] Optimize GPUI inspector's runtime cost by an order of magnitude
2026-09-16 16:02:58 +00:00
Anthony Eid fecc3273ed gpui_platform: Expose headless renderer through bench support (#63244)
GPUI's `bench-support` feature provides the benchmark context and
headless-renderer interface without enabling `test-support`, but the
platform implementation remained available only through
`gpui_platform/test-support`. As a result, consumers could not use
`#[gpui::bench]` with a fully isolated feature graph because the
generated benchmark harness calls
`gpui_platform::current_headless_renderer()`.

This threads `bench-support` through `gpui_platform`, `gpui_macos`, and
`gpui_apple`, exposing the existing Metal headless renderer without
widening unrelated test window or prompt APIs. The existing benchmark
package now requests the platform's canonical `bench-support` feature.
Its other test-backed fixtures are intentionally unchanged and remain
outside this focused dependency fix.

Validation:

- Confirmed `gpui_apple/bench-support`, `gpui_macos/bench-support`, and
`gpui_platform/bench-support` resolve no `test-support` feature with
`cargo tree --locked --no-default-features --features bench-support -e
no-dev,features`.
- Ran `cargo check --locked -p benchmarks --benches` to compile every
existing `#[gpui::bench]` target against the real platform headless
renderer.
- Ran `cargo nextest run --locked -p gpui_apple -p gpui_macos -p
gpui_platform`.
- Ran `./script/clippy` for each changed platform package with
`--no-default-features --features bench-support`.
- Ran `cargo fmt --check`.

Release Notes:

- N/A
2026-08-26 11:00:10 +00:00
JKN 74490daced gpui_windows: Implement render_to_image for headless window capture (#63012)
# Objective

`gpui_macos` implements `PlatformWindow::render_to_image` — the
MetalRenderer samples an offscreen target, so a **hidden** window can be
captured. `gpui_windows` does not implement it, so the method falls
through to the trait default and returns `Err("render_to_image not
implemented for this platform")`.

That leaves Windows consumers (tests, headless screenshot harnesses) on
`PrintWindow`-style workarounds, which require the window to actually be
on screen: a DirectComposition swap chain that never presents has no
frame to read, so you get a visible flash — or an off-screen parking
trick — for every capture.

This closes the macOS/Windows gap. Linux (`gpui_linux`) still returns
the trait default; a Blade/wgpu readback is the obvious follow-up but is
not in this PR.

## Solution

The DirectX analogue of the Metal path:

- `DirectXRenderer::draw`'s clear, scene upload and batch encoding are
factored into a shared `render(scene, background_appearance)`. `draw` is
now `render` + `present`; `render_to_image` is `render` + readback.
Nothing about how a frame is produced is duplicated between them, so the
two cannot drift.
- `render_to_image` renders into the **existing** render target —
created at window construction, so no window need ever be shown — then
copies it into a `D3D11_USAGE_STAGING` texture, `Map`s it, and converts
BGRA → RGBA. `RowPitch` padding is honoured per row; the copy loop
carries a safety comment.
- It refuses to run while `skip_draws` is set. That flag marks a pending
device-lost recovery, where the atlas still holds tile references from
the previous device — drawing before the forced re-render rebuilds them
panics in `DirectXAtlasState::texture` (the case
`WindowState::force_render_pending` documents). Returning an error beats
panicking in a capture harness.
- Gated on `cfg(any(test, feature = "test-support"))` to match the trait
method. `gpui_platform`'s `test-support` now forwards to
`gpui_windows/test-support`, the way it already does for `gpui_macos`.

No behaviour change outside `test-support`/`cfg(test)` builds beyond the
`render` factoring, which is a pure code move.

## Testing

- **Windows, functional:** an earlier revision of this patch has been in
production use since June in the `--screenshot` harness of a GPUI app I
ship ([Ferail](https://github.com/jonx/Ferail)), capturing a hidden
window (`show: false`) with no flash. BGRA→RGBA output was verified
against the on-screen rendering.
- **This exact revision** has been cross-checked from macOS only: `cargo
clippy -p gpui_windows --no-default-features --features test-support
--target x86_64-pc-windows-msvc -- -D warnings` is clean, both with and
without `test-support` (clang-cl + `xwin`; `--no-default-features` skips
only the `windows-manifest` embed-resource step, which is irrelevant
here). I'm relying on CI for a native Windows build of this revision —
happy to report back from a Windows host if that's a blocker for review.
- **Not covered by an automated test.** The behaviour needs a live D3D11
device, so it can only be exercised by a Windows-hosted test. Happy to
add one under `gpui_windows` if you'd like it — say the word and I'll
push it rather than guess at the shape you want.
- **Reviewers:** the interesting part is the staging-texture readback in
`directx_renderer.rs`. Worth a second pair of eyes on the `skip_draws`
guard and on premultiplied alpha (the swap chain is
`DXGI_ALPHA_MODE_PREMULTIPLIED`, so non-opaque captures come back
premultiplied — same as the macOS path, but it does mean
semi-transparent regions are not straight-alpha).

## 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) — n/a, no UI surface
- [ ] Tests cover the new/changed behavior — see Testing; needs a
Windows host, happy to add
- [x] Performance impact has been considered and is acceptable — the
readback path is `test-support`-only; `draw` is unchanged apart from the
`render` factoring

## Showcase

<!-- TODO: drop in the headless Windows capture (and the macOS one
beside it) -->

---

Release Notes:

- N/A

Co-authored-by: Lukas Wirth <lukas@zed.dev>
2026-08-26 08:17:09 +00:00
Cameron Mcloughlin 4601ead416 gpui: Webgl backend (#62165)
Currently gpui only supports webgpu as a backend when compiling for the
web. However, webgpu support on Linux browsers is spotty (without
setting experimental flags):
- chromium has is enabled for nvidia and recent intel chips
- firefox does not enable it

This PR adds a WebGL backend, which is much more widely supported

---

Release Notes:

- N/A or Added/Fixed/Improved ...

---------

Co-authored-by: Lukas Wirth <me@lukaswirth.dev>
2026-08-04 15:53:09 +00:00
Gaauwe Rombouts b2131e9df8 gpui_web: Support Fetch requests from background workers (#61782)
Browser Fetch APIs must run on the main thread, while GPUI image loading
can invoke its HTTP client from background WASM workers. This routes
`FetchHttpClient` requests through the web dispatcher's main-thread
mailbox, installs the client by default for web applications, and
removes thread-affine browser state from the safely movable dispatcher.

Release Notes:
- N/A
2026-07-28 13:32:52 +00:00
Lukas Wirth c97b7c0ea4 gpui_web: Fix some bugs (#61707)
Release Notes:

- N/A or Added/Fixed/Improved ...
2026-07-28 06:22:31 +00:00
Lukas Wirth 7c185202f5 agent: Fix cargo test -p agent on windows (#52311)
Release Notes:

- N/A or Added/Fixed/Improved ...
2026-03-24 11:05:12 +00:00
Conrad Irwin b32067d248 GPUI updates (#51415)
- **Fix race condition in test_collaborating_with_completion**
- **WIP: Integrate scheduler crate into GPUI TestDispatcher**
- **WIP: scheduler integration debugging**
- **Fix formatting**
- **Unify RunnableMeta and add execution tracking to TestScheduler**
- **Remove unused execution tracking from TestScheduler and
TestDispatcher**
- **Add is_ready() to GPUI Task for API parity with scheduler**
- **Eliminate RunnableVariant::Compat - all runnables now have source
location metadata**
- **Update integration plans to reflect completed phases**
- **Simplify RunnableVariant to type alias**
- **Delegate TestDispatcher task queues to TestScheduler (Phase 2b)**
- **Remove waiting_hint/waiting_backtrace and debug logging from
TestDispatcher**
- **Remove wrapper methods from TestDispatcher - access scheduler()
directly**
- **Update integration plan with complete state and instructions for
full scheduler migration**
- **Use scheduler's native timer() and simplify TestDispatcher**
- **Fix rng() usage to lock mutex, update plan with SharedRng wrapper**
- **Add SharedRng wrapper for ergonomic random number generation**
- **Update plan: mark Phase 1 (SharedRng) as complete**
- **Update scheduler integration plan with Phase 2 investigation notes**
- **Phase 3: Delegate simulate_random_delay to
scheduler.yield_random()**
- **Phase 4: Remove TaskLabel**
- **Phase 5 (WIP): Simplify block_internal and remove unparkers**
- **Phase 5 Complete: Scheduler integration finished**
- **Update integration plan with code review findings**
- **Phase 6 & 7: Restore realtime priority support and delete dead
code**
- **Add TestApp and TestAppWindow for cleaner GPUI testing**
- **Fix formatting across the branch**
- **Fix Linux build: add explicit type annotation and rename
probability() to weight()**
- **Add TestApp and TestAppWindow for cleaner GPUI testing**
- **Rename TestAppWindow to TestWindow, internal TestWindow to
TestPlatformWindow**
- **Remove unused RunnableVariant imports on Linux**
- **Add STATUS.md for next agent**
- **Run cargo fmt**
- **Use per-app element arena only and scope test draws**
- **Fix collab tests for scheduler timing and ordering**
- **Store element arena on App and route element allocations through
draw scope**
- **Fix TestScheduler lock ordering between rng and state**
- **Fix inlay hints test by explicitly triggering refresh after viewport
setup**
- **Add scheduler integration regression risk analysis doc**
- **Fix tests: avoid caching Entity in global OnceLock for Codestral API
key**
- **Document learned weak point: global cached Entity handles break
across App contexts**
- **Add scheduler regression test for block_with_timeout continuation
and explicit time advancement**
- **Document TestScheduler timeout tick budget behavior and explicit
time advancement guidance**
- **Add test asserting realtime priority spawns panic under
TestDispatcher**
- **Document realtime priority determinism contract in tests**
- **Remove realtime priority until we have a concrete use case (cc
@localcc)**
- **Update STATUS for scheduler integration decisions and realtime
priority removal**
- **Fix prettier docs and clippy in scheduler tests**
- **Remove unused imports from Windows dispatcher**
- **WIP: scheduler integration debugging + agent terminal diagnostics**
- **Update scheduler integration status**
- **Remove temporary planning docs, consolidate into scheduler
integration doc**
- **Remove unrelated changes from scheduler integration**
- **Fix clippy errors**
- **Add STATUS.md with debugging instructions for Linux/Windows hang**
- **WIP: local changes needed by ex**
- **Add pointer capture API for stable drag handling**
- **Add pointer capture API for stable drag handling**
- **chore: update generated cargo manifests**
- **gpui: Expose ShapedLine::width() for pen advancement**
- **Remove git2 usage from util test.rs**
- **Store DiagnosticQuad bounds in logical Pixels**
- **WIP: executor and test_app changes for scheduler integration**
- **Expose font APIs publicly**
- **gpui: add typed diagnostics and record_diagnostic API**
- **WIP: gpui test window diagnostics changes**
- **Add LineCacheKey trait and shape_line_cached API for
content-addressable shaping**
- **Fix RenderGlyphParams field additions for Ex compatibility**
- **Add doc comment for recommended_rendering_mode, fix formatting**
- **Add scheduler_executor() method for Ex compatibility**
- **Fix TestWindow -> TestPlatformWindow in test_context.rs**
- **Add headless metal renderer and window focus improvements**
- **Fix double borrow in TestWindow::simulate_resize**
- **Fix cbindgen panic: remove default type parameter from
Diagnostic<T>**
- **Implement AppContext for HeadlessMetalAppContext**
- **Missing trait impls**
- **Add ShapedLine::split_at and eliminate re-shaping in soft wraps**
- **Add handoff doc for platform-neutral-tests merge**
- **Remove ex-only test infrastructure before merging main**
- **Add cross-platform HeadlessAppContext with pluggable text system**
- **Export platform_text_system() from gpui_windows for cross-platform
tests**
- **Restore TestApp/TestAppWindow with pluggable text system support**
- **Add TestApp::open_window_sized for tests that need specific window
dimensions**
- **Fix some warnings**
- **Fixes**
- **Add a platform-neutral headless renderer interface**
- **Synchronize Managed texture before CPU readback on discrete GPUs**
- **Allow creating TestDispatcher with custom scheduler**

Release Notes:

- N/A

---------

Co-authored-by: Nathan Sobo <nathan@zed.dev>
Co-authored-by: John Tur <john-tur@outlook.com>
Co-authored-by: Agus Zubiaga <agus@zed.dev>
Co-authored-by: Antonio Scandurra <me@as-cii.com>
2026-03-12 22:15:12 +00:00
Lukas Wirth e30720a781 gpui_web: Implement fetch based HTTP client (#50463)
Can only be used in single threaded environments for now due to js
futures being non-send.

Release Notes:

- N/A *or* Added/Fixed/Improved ...
2026-03-02 16:18:01 +01:00
Lukas Wirth 14f37ed502 GPUI on the web (#50228)
Implements a basic web platform for the wasm32-unknown-unknown target
for gpui

Release Notes:

- N/A *or* Added/Fixed/Improved ...

---------

Co-authored-by: John Tur <john-tur@outlook.com>
2026-02-26 18:36:50 +01:00
claire 90d8c26796 Fix visual test screenshot functionality (#49649)
After #49277 was merged, all visual tests failed to run with the error
"FAILED - render_to_image not implemented for this platform".

Release Notes:

- N/A
2026-02-19 22:48:33 +01:00
Piotr Osiewicz 6a9d259fec gpui_linux: Fix headless build (#49652)
Closes #ISSUE

Before you mark this PR as ready for review, make sure that you have:
- [ ] Added a solid test coverage and/or screenshots from doing manual
testing
- [ ] Done a self-review taking into account security and performance
aspects
- [ ] Aligned any UI changes with the [UI
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)

Release Notes:

- N/A
2026-02-19 20:38:40 +00:00
Piotr Osiewicz bc31ad4a8c gpui: Extract gpui_platform out of gpui (#49277)
#2874 on steroids

Before you mark this PR as ready for review, make sure that you have:
- [ ] Added a solid test coverage and/or screenshots from doing manual
testing
- [ ] Done a self-review taking into account security and performance
aspects
- [ ] Aligned any UI changes with the [UI
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)

Release Notes:

- N/A

---------

Co-authored-by: Eric Holk <eric@zed.dev>
2026-02-19 18:57:49 +01:00