mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 15:10:34 +01:00
d0400aaf033a703a037f8fe5400bbc896db985da
104 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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> |
||
|
|
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` |
||
|
|
bfcd5949ff |
gpui_linux: Time Wayland frame callbacks from receipt (#66774)
Wayland frame callbacks backdated the frame signal using the `wl_callback.done` timestamp. The protocol leaves that timestamp's clock and meaning unspecified, so the conversion assumed `CLOCK_MONOTONIC` (true for Mutter and Sway) which caused problems for compositors that used the timestamp to mean something else in our hang telemetry. Changing this to `std::time::Instant::now()` to be inline with MacOS, (with the MetalLayer) Windows Release Notes: - N/A - [GPUI] Change Wayland frame time profiler to use `std::time::Instant` type to signify the start of a frame signal |
||
|
|
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> |
||
|
|
4d847859f5 |
gpui_linux: Fix Wayland activation requests (#64058)
Closes #59397 Wayland activation requests previously shared a single pending-action slot. Concurrent requests could overwrite that slot, leaving an issued token unused and Mutter's global launch indicator active until its timeout. Each activation token now carries its own pending window, URI, or path action. This prevents requests from overwriting one another and removes the resulting unpaired-token error. Track the latest eligible keyboard or pointer press together with the surface that received it. Window activation uses that context when available; without it, it still requests a token for the target surface so the compositor can indicate that the window wants attention. URI/path opens use the input context when available and otherwise retain the tokenless fallback. Launcher-provided startup token handling remains unchanged. The approach builds on the investigation and prototype attached to #59397, but does not combine serials from unrelated Wayland protocols. Test results: - `cargo fmt --all -- --check`: passed after formatting the follow-up changes. - `cargo test -p gpui_linux --lib`: 50 passed. - `cargo build -p zed`: passed. - `./script/clippy -p gpui_linux`: passed (release, all targets/features, warnings denied). The wrapper skipped its later optional checks because `cargo-shear` is not installed. - Current-head (`412dc7f6f6`) cold-start smoke test under isolated headless Mutter 51.0 with `WAYLAND_DEBUG=client`: two startup activation requests, two returned tokens, both tokens passed to `activate`, and 37 surface buffer attachments. No unpaired-token error appeared. Startup intentionally issues activation requests now. - Earlier manual GNOME testing covered the original implementation, before the attention-preserving follow-up. A visual GNOME busy-cursor check, launcher-provided-token launch, new-window shortcut, and URL-opening retest of the current head remain outstanding; the headless startup trace does not cover those interactions. Release Notes: - Fixed the global busy cursor lingering after Zed opens on GNOME Wayland. - [GPUI] Fixed concurrent Wayland activation requests losing their pending actions and improved keyboard-triggered activation context tracking. --------- Co-authored-by: Anthony <hello@anthonyeid.me> |
||
|
|
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> |
||
|
|
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. |
||
|
|
e39fb7c2e0 |
gpui: Rename ScrollWheelEvent to ScrollEvent and add trackpad scrolling on iOS (#65805)
Scrolling in GPUI comes from mouse wheels and trackpads reported by the OS, and from touch pans that GPUI recognizes itself. All of them arrived as `ScrollWheelEvent`, and handlers had no way to tell a finger pan from anything else. ## API change - `ScrollWheelEvent` → `ScrollEvent`, with a new `source: ScrollSource` field. - `ScrollSource` has two variants: - `Pointer` (the default): a scroll the platform reported from a mouse wheel or trackpad. `ScrollDelta::precise()` still tells continuous devices apart from wheel notches. - `Touch`: a finger pan recognized by GPUI, including its synthesized momentum. - `on_scroll_wheel` → `on_scroll`. - `PlatformInput::ScrollWheel` → `PlatformInput::Scroll`. ### Compatibility Existing app code keeps compiling: `ScrollWheelEvent` and `on_scroll_wheel` remain as deprecated aliases. Two things still need changes: - Platform backends must switch to `PlatformInput::Scroll`. Rust can't alias an enum variant. - `ScrollEvent` literals that list every field must add `source`. Literals using `..Default::default()` get `ScrollSource::Pointer`. ## Trackpad and mouse-wheel scrolling on iOS `gpui_ios` previously handled only raw touches, so trackpads and mice on iPad couldn't scroll. The backend now adds a `UIPanGestureRecognizer` to the Metal view that accepts all scroll types and sends each step as a `ScrollEvent` with the pointer position and modifiers. The recognizer has an empty `allowedTouchTypes` and `cancelsTouchesInView = false`. That way it never claims finger touches, which keep going to `touchesBegan` and GPUI's touch recognizer. UIKit ends these gestures when the fingers lift and leaves momentum to the app. So for now a trackpad scroll on iOS stops when the fingers lift, without the post-release glide that native views have. ## Verification Done on Linux: - `cargo test -p gpui --features test-support --lib -- gestures list:: scroll`: 72 passed. - `./script/clippy -p gpui -p gpui_linux`: clean. - `cargo clippy` for `gpui_ios` (`aarch64-apple-ios`) and `gpui_macos` (`aarch64-apple-darwin`): clean. - `cargo check -p gpui_web` (`wasm32-unknown-unknown`): clean. - A temporary downstream-style test confirmed that code using `ScrollWheelEvent` and `.on_scroll_wheel(...)` still compiles and receives scrolls. Not verified: - **Windows:** wasn't type-checked locally, because `gpui`'s build script needs the Windows resource compiler. CI covers it. - **iOS behavior:** trackpad and wheel scrolling on an iPad hasn't been tried. Specifically unconfirmed: scroll direction under natural scrolling, and that finger pans don't also trigger the scroll recognizer. Release Notes: - [GPUI] Renamed `ScrollWheelEvent` to `ScrollEvent` and `on_scroll_wheel` to `on_scroll` (old names remain as deprecated aliases), added `ScrollEvent::source` to distinguish pointer scrolling from GPUI-recognized touch pans, and added trackpad and mouse-wheel scrolling on iOS --------- Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com> |
||
|
|
f495dd0f77 |
gpui: Track connected displays and each window's display (#65059)
GPUI now tracks connected displays and the display each window is on.
`App` caches every display's bounds and refresh interval, rereading them
whenever a platform reports that displays may have changed, and reports
`Added`, `Removed`, and `Changed { id, changes }` through
`App::observe_displays`. Windows report only moves between displays;
`Window::refresh_interval(cx)` reads App's cache, and
`Window`/`Context::observe_window_display` fire when a window moves or
its display changes, with App updated first. This is implemented on
macOS, Windows (whose platform window is now a hidden top-level window
so it receives `WM_DISPLAYCHANGE` and `WM_ENDSESSION` with no windows
open), and Wayland, and was exercised at runtime on all three by
switching refresh rates; X11 and web report no refresh interval, and
headless Linux now reports no displays. Planned consumers are
refresh-rate-aware frame telemetry and the screen-share display picker.
Release Notes:
- [GPUI] Added `App::observe_displays`, `Window::refresh_interval`, and
`observe_window_display` for tracking connected displays, their refresh
rates, and each window's display
|
||
|
|
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> |
||
|
|
cd4fc8de4c |
gpui: Journal platform frame requests and skipped frames (#64958)
## Summary Pass captured platform frame request timing to `on_request_frame` and emit foreground journal records. This PR provides timing data; it does not classify platform waits or change latency histogram/reporting policy. `RequestFrameOptions` carries an optional captured time and a native-callback/local-schedule source. A per-window atomic preserves the earliest coalesced request timestamp and its matching source until main-thread delivery. Journal records include window identity, captured time when available, foreground handling time, and source. No request IDs or second journal stream are introduced. ## Completed frame skips (retained for review) Keep completed GPUI decisions not to render as sealing boundaries, with no-render-needed, inactive-throttle, and thermal-throttle reasons. They seal at foreground completion without satisfying or clearing pending demand. Hang serialization uses `sealed_by: "frame_skipped"`. Platform frame requests do not seal or count as foreground work. Reentrant deferrals remain non-sealing raw diagnostic records with their own window/time payload; they cannot be represented as completed skip reasons or sealing skip boundaries. Raw point diagnostics are not copied into snapshots. Hang qualification still uses foreground execution durations and occupancy; infinite foreground hang detection remains follow-up work. The skip-sealing portion is intentionally retained for review and can be split out if requested. The signal-to-present histogram, refresh estimation, platform-wait filtering, and Frame Duration Report changes are deferred. The complete prior checkpoint is preserved on `platform-frame-latency-followup`; it is not a second PR yet. ## Platform sources - **macOS:** CoreVideo’s supplied current host timestamp is converted to an `Instant` using paired host-clock/local-clock samples, with receipt-time fallback for invalid timestamps. Capture happens before registry locking/coalescing; synchronous `displayLayer` and key-window draws use call time. `WindowFrameSource::stop()` clears stale signals after detaching the subscription. - **Windows:** VSyncProvider time immediately after waiting, before redraw invalidation. Compositor-paced waits are tagged `NativeCallback`; failed or short waits followed by the existing fallback sleep are tagged `LocalSchedule`. Coalescing retains the earliest timestamp and its matching source together; hidden/minimized slots are cleared. Wait and redraw behavior are unchanged. - **Wayland:** compositor milliseconds converted against CLOCK_MONOTONIC with wrapping subtraction and a 60-second plausibility bound; receipt-time fallback. Demand pings retain enqueue time; retries retain scheduled deadlines. - **X11:** scheduled calloop refresh deadline; expose requests have no captured time. - **Web:** no captured timestamp yet, but requests are still journaled with foreground handling time. Captured-time option fields remain available regardless of the profiler feature so independently featured backends share one API shape. Built-in backends collect timestamps only with `gpui/profiler`: disabled capture does not evaluate clock/conversion closures, the accumulator has no timestamp storage or atomic operations, and callback delivery and actual scheduling clocks remain unchanged. Wayland's protocol does not guarantee the clock epoch. Windows fully covered-window behavior and X11 compositor gating beyond the timer remain limitations of these sources. Live compositor/display-off/lock workflows remain unverified. Skip-boundary changes touch `journal.rs` and `hang.rs`. This PR will merge before the parallel hang-watchdog work; that follow-up PR will resolve its conflicts against these changes. ## Verification Latest feature-gating checks: the profiler-disabled capture regression passed; enabled coalescing and window integration tests passed; macOS and GPUI/Web Wasm compiled with profiling both disabled and enabled. An optimized probe built from the shared implementation confirmed disabled capture/accumulator paths contain no calls or atomic instructions. Clippy, formatting, and whitespace checks passed. Latest-head CI passed Linux, Windows, and macOS tests and Clippy, along with Wasm and style checks. Latest type/guard cleanup: seven focused journal, hang, and window tests passed, along with the profiler-disabled GPUI library check, Clippy, formatting, and whitespace checks. The consecutive profiler guards are grouped without shortening the foreground-turn guard lifetime. - Previous extracted checkpoint: `cargo test -p gpui --features profiler --lib -- --test-threads=1`: **431 passed**. - Focused TestPlatform tests exercise request/source emission and pending demand surviving throttling, observing callback execution and draw counts. No wall-clock sleeps are used by the new window tests. - `corgi check -p gpui_macos --lib`: passed. - `./script/clippy -p gpui -p gpui_macos -p input_latency_ui`: passed, including repository hygiene checks. - GPUI + Web Wasm check with profiler and repository CI build-std/atomics flags: passed. - Formatting and `git diff --check`: passed. Corgi's parallel suite passed 436 of 437 tests but encountered the previously observed hang-monitor shutdown channel timing failure. That test passed in the serial Cargo suite and was not changed or disabled. The preceding checkpoint passed Linux, Windows, macOS, and Wasm CI. CI also passed on the current head, `3641f14ab0`. Local cross-target checks remain constrained by missing Linux system libraries and Windows SDK tooling on the macOS host. ## Suggested .rules additions When manually driving platform frame requests in GPUI tests, account for test-mode automatic draws during effect flushing. For throttle-routing tests, configure a comfortably long throttle interval instead of relying on wall-clock sleeps or short scheduling deadlines. Release Notes: - [GPUI] Added captured platform frame request timing and foreground journal records, including sealing boundaries for completed decisions not to render. |
||
|
|
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> |
||
|
|
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. |
||
|
|
f25434f3c5 |
gpui_linux: Force a full render on X11 Expose after GPU recovery (#64570)
# Objective Zed on X11 could crash with `index out of bounds: the len is 0 but the index is 0` in `WgpuAtlas::get_texture_info` right after recovering from a lost GPU device (Sentry ZED-BVQ, Linear FR-488). ## Solution When the device is lost, `X11Window::draw` recreates the renderer, which clears the sprite atlas, and sets `force_render_after_recovery` so the next frame rebuilds the scene instead of replaying the cached one. Only the periodic refresh timer consumed that flag though. An `Expose` event handled in the same event loop turn (a compositor repainting after the same GPU reset, for example) requested a presentation-only frame with `force_render: false`, so GPUI presented the previously rendered scene, whose sprites still pointed at atlas textures that no longer exist. We now consume the flag in `X11WindowStatePtr::refresh`, so every frame request, Expose or timer, forces a full render after recovery. The field is private now so a caller can't bypass it again. ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed a crash on Linux (X11) that could occur when a window was redrawn immediately after recovering from a lost GPU device. - [GPUI] Fixed a crash on Linux (X11) when an `Expose` event presented a cached frame immediately after GPU device recovery. |
||
|
|
0ef92145ff |
gpui: Improve PlatformAtlas::get_or_insert_with (#64331)
Stumbled across this during a recent review: At all of the call sites in prod code, we would clone, then into, then pass by ref, and then immediately clone again in `get_or_insert_with` when the texture was not found. Instead, changed the API to now take an owned `AtlasKey` to make better use of the cloning. As a second step, went ahead and added a generic `AtlasState`, as I noticed all atlases shared some similar logic around keeping track of the tiles. With this restructing, we reuse some code across different backends, but more importantly, get rid of an additional hashmap lookup by instead using the `Entry` API. Release Notes: - N/A - [GPUI] N/A |
||
|
|
87a1ea30e8 |
gpui_linux: Discard stale Wayland file drag reads (#64122)
## Objective
Prevent canceled external file drags on Linux Wayland from becoming
active again after the native drag session has already left the Zed
window.
This is a rare timing-sensitive race. When it occurs, the stale external
drag remains active inside GPUI. Ordinary mouse movement then behaves
like drag movement throughout Zed, and a later unrelated click can drop
or copy the previously dragged file into the project panel.
The issue was observed on Fedora 44 with GNOME Wayland, with the drag
originating in GNOME Files.
## Cause
The Wayland destination path reads the drag's `text/uri-list` payload
asynchronously.
Before this change, `state.drag.window` and `state.drag.data_offer` were
installed only after that asynchronous read completed. If
`wl_data_device::Event::Leave` arrived first, it found no installed
destination and returned. The detached read could then complete and
dispatch a stale `FileDropEvent::Entered` after the native drag had
already ended.
Rapidly entering and leaving Zed could also create multiple overlapping
URI reads whose stale completions replaced one another.
With a temporary delay added to make the timing deterministic, the
failing sequence was:
```text
entered: offer=81
left: active_offer=None, had_window=false
paths ready: offer=81
installing destination: offer=81, previous_offer=None
```
Two overlapping stale completions produced:
```text
installing destination: offer=80,
previous_offer=Some(offer=81),
had_window=true
```
The temporary delay and diagnostics are not included in this PR.
## Solution
Associate each asynchronous drag URI read with a monotonically
increasing generation.
- A new `Enter` begins a new generation and invalidates an older pending
read.
- `Leave` invalidates the current pending read.
- `Drop` invalidates the current pending read.
- Before installing the destination and dispatching
`FileDropEvent::Entered`, the asynchronous task verifies that its
generation is still current.
- Stale completions destroy their data offer and return without creating
an active GPUI drag.
Normal drags whose URI reads complete before a terminal event continue
through the existing path unchanged.
## Testing
- Added a unit test covering:
- A newer drag invalidating an older URI read.
- A terminal drag event invalidating the current URI read.
- Reproduced the race deterministically with a temporary two-second
delay before destination installation.
- Verified that stale completions are discarded with the fix and no
longer cause ordinary mouse movement or clicks to act on the old file.
- Ran:
```text
cargo test -p gpui_linux invalidates_stale_drag_uri_reads
cargo check -p gpui_linux
cargo build -p zed
git diff --check
```
Release Notes:
- Fixed canceled external file drags on Linux Wayland sometimes
remaining active and causing later clicks to copy the dragged file.
|
||
|
|
a7c7219d5b |
gpui_linux: Avoid local XKB files for server keymaps (#64113)
# Objective Avoid requiring local XKB keyboard-definition directories when using the resolved keymap supplied by Wayland or X11. If libxkbcommon cannot find any usable default include directory, context creation can fail even though the client already has everything needed to use the server's keyboard map. Wayland can then panic on missing keyboard state when a modifier event arrives. Closes DELTA-9B ## Solution Create the shared XKB context with `XKB_CONTEXT_NO_DEFAULT_INCLUDES`. The [libxkbcommon documentation](https://xkbcommon.org/doc/current/group__context.html) explicitly identifies clients retrieving their keymaps from Wayland or X11 as a use case for this flag. [Qt's X11 backend](https://github.com/qt/qtbase/blob/6.8/src/plugins/platforms/xcb/qxcbkeyboard.cpp#L342-L358) uses the same approach. Keep default include paths in the X11 test fixtures, which compile named layouts from local definitions instead of receiving resolved maps from a server. No fallback layout, platform-error callback API, or changes to other keymap failure handling are included. ## Testing - Passed `corgi fmt --check -p gpui_linux` and `git diff origin/main...HEAD --check`. - Reviewed the complete diff: two source files. The author has removed the README review marker. - Linux build/test execution remains unverified. Earlier `corgi` and `cargo` cross-build attempts on macOS were blocked by missing Linux native dependencies/toolchain (`x86_64-linux-musl-gcc`); no Linux runtime or running Docker daemon is available here. - No subprocess/environment-manipulating regression test is included. Manual verification is pending: - On ordinary Linux, check typing, modifiers/shortcuts, layout switching, and compose/dead keys under both Wayland and X11. - Reproduce startup with inaccessible XKB configuration paths in the old build, then verify keyboard input works in the patched build under the same conditions, ideally on the affected NixOS setup. - Run the existing `gpui_linux` X11 keyboard tests on Linux to verify the fixture adjustment. Draft pending Linux validation. Release Notes: - Fixed a Linux startup crash when local XKB keyboard-definition files are unavailable. |
||
|
|
3db02c2c77 |
gpui: Add is_visible and on_visibility_changed API on Window (#64107)
Adds a `WindowVisibility` API to GPUI: `Window::visibility()` / `Window::is_visible()`, `Window::observe_window_visibility`, and `Context::observe_window_visibility`, backed by one platform signal per backend — `NSWindow.occlusionState` on macOS, `WS_VISIBLE` plus the minimized state on Windows, the xdg-shell v6 `suspended` toplevel state on Wayland, mapped state plus `VisibilityNotify` on X11, and the Page Visibility API on web. Only transitions are reported, the initial value is read from the platform when the window is created, and the two `PlatformWindow` methods have no default so a backend cannot silently opt out. The per-platform limits (Windows can't see a fully covered window, pre-v6 Wayland compositors never report `Hidden`) are documented on the type. It also adds `Platform::on_system_sleep` / `App::on_system_sleep`, mirroring the existing wake hook, on macOS (`NSWorkspaceWillSleepNotification`), Windows (`PBT_APMSUSPEND`), and Linux (logind `PrepareForSleep(true)`, which the listener previously discarded). Nothing in Zed subscribes to either yet; the hang-telemetry journal will use visibility to stop measuring frames that could not have been presented, and the sleep/wake pair to bracket time the process was not running. Release Notes: - N/A |
||
|
|
450775244f |
gpui: Prevent idle sleep during AI response streaming (#53130)
Release Notes: - Added button tu prevent idle sleep during AI response streaming **Context / Motivation:** When an AI agent takes a long time to generate a response, the operating system might enter an idle sleep (or display sleep) state if there is no user interaction (mouse or keyboard). This can interrupt the workflow. This PR aims to prevent the system from sleeping during an active AI turn by invoking native OS APIs, and provides a UI toggle for users to control this behavior. **Key Changes:** 1. **Cross-Platform Idle Sleep Prevention in GPUI (`gpui`, `gpui_*`)** - Added a new `prevent_idle_sleep` method to the `Platform` trait. It returns a RAII-based `PreventIdleSleepToken`, which automatically restores the original sleep policy when dropped. - **macOS**: Utilizes `NSProcessInfo`'s `beginActivityWithOptions` with `NSActivityIdleDisplaySleepDisabled`. - **Windows**: Uses `SetThreadExecutionState` to prevent display and system sleep, incorporating a reference counter to handle concurrent requests safely. - **Linux**: Uses `ashpd` to request `org.freedesktop.portal.Inhibit` (inhibiting `Idle` and `Suspend` states) via D-Bus. 2. **AI Agent State Integration (`crates/acp_thread`)** - Introduced idle sleep prevention logic in `AcpThread`: Acquires the token at the beginning of `run_turn`, and automatically releases it when the turn completes normally, errors out, or is explicitly canceled by the user. - Added comprehensive unit tests to ensure the token is correctly acquired and released under various cancellation and concurrency scenarios. 3. **Settings and UI (`crates/agent_settings`, `crates/agent_ui`)** - Added `AgentOutputIdleSleepControl` to global state. - Added a new toggle button (screen icon) to the toolbar at the bottom of the `ThreadView` (AI conversation panel). Users can hover to view the tooltip and click to toggle the feature on or off. <img width="419" height="132" alt="截屏2026-04-04 16 09 08" src="https://github.com/user-attachments/assets/619da9ff-10f7-46e0-b959-d7c74b16b918" /> --------- Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com> Co-authored-by: Kirill Bulatov <kirill@zed.dev> |
||
|
|
4a217d5316 |
gpui_linux: Disable IME in project panel when no input handler on Wayland (#63776)
# Objective Fixes #63774 ## Solution On Wayland, the IME remained enabled when the focused control did not register a text input handler. This allowed IME to intercept ABC...Z character shortcuts in non-text UI, including the Project Panel outside filename editing. However Windows 11 doesn't have this problem. Fixed it by treating a missing input handler as not accepting text input. ## Testing I've tested on both Vim/Helix mode and normal mode with Vim/Helix keybinds. All clear now. ## Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable ## Showcase [after.webm](https://github.com/user-attachments/assets/91743d71-05c5-49d2-b032-4aebc8e91496) ABC...Z character shortcuts are not going to be intercepted by IME unexpectedly in project panel now. --- Release Notes: - Fixed IME remains enabled in project panel without a focused text input in Wayland #63774 |
||
|
|
5dd0666dfb |
Fix missing NUL terminator in X11 WM_CLASS (#62848)
## Objective GPUI's X11 `WM_CLASS` property omits its final NUL terminator, so any window manager that relies on the terminator reads the class one byte short. `WM_CLASS` is specified by [ICCCM §4.1.2.5](https://tronche.com/gui/x/icccm/sec-4.html#s-4.1.2.5) as two consecutive NUL-**terminated** strings, `instance\0class\0`. `set_app_id` writes the separator but not the final terminator: ```rust let mut data = Vec::with_capacity(app_id.len() * 2 + 1); data.extend(app_id.bytes()); // instance data.push(b'\0'); data.extend(app_id.bytes()); // class <- no trailing NUL ``` This affects Zed itself. `ReleaseChannel::app_id()` returns `dev.zed.Zed` on stable, so under X11 and XWayland the class is read as `dev.zed.Ze`. The shipped desktop file is `dev.zed.Zed.desktop`, so the association it depends on is exactly the string being truncated, and window-manager rules or taskbar grouping matching `dev.zed.Zed` silently fail to apply. Wayland is unaffected, since the app id is set through `xdg_toplevel` rather than an X11 property. ## Solution Append the missing terminator after the class string, and size the `Vec` capacity to match (`* 2 + 2` rather than `* 2 + 1`). ## Testing Tested manually on Arch Linux with Hyprland v0.56.2 (wlroots) via XWayland. **Reproducing the bug** — Zed 1.14.2, before the fix: ``` $ env -u WAYLAND_DISPLAY zeditor some-dir $ hyprctl clients -j | jq '.[] | select(.xwayland) | .class' "dev.zed.Zed\u0000dev.zed.Ze" ``` The same window read with `xprop`, which does not require the terminator, shows the intended value — confirming the property itself is malformed rather than the compositor misreading it: ``` $ xprop -id 0x800001 WM_CLASS WM_CLASS(STRING) = "dev.zed.Zed", "dev.zed.Zed" ``` **Control** — on the same compositor and the same XWayland path, Alacritty (winit, which writes the trailing NUL) reports its class intact: ``` $ hyprctl clients -j | jq '.[] | select(.xwayland) | .class' "Alacritty" ``` The same truncation was reproduced independently with a third-party GPUI application using `app_id: Some("sprite")`, which reports `sprite\u0000sprit`. **Platforms:** verified on Linux/XWayland only. Wayland does not use this code path. macOS and Windows have their own `set_app_id` implementations and are unaffected by this change. **Needs more testing:** confirmation on a bare X11 session (not XWayland) and on a non-wlroots window manager such as i3, KWin, or Mutter would be welcome — the malformed property is compositor-independent, but which readers visibly truncate it is not. ## Self-Review Checklist - [x] I've reviewed my own diff for quality, security, and reliability - [x] Unsafe blocks (if any) have justifying comments — *none added* - [x] The content adheres to Zed's UI standards — *N/A, no UI change* - [ ] Tests cover the new/changed behavior — *see note below* - [x] Performance impact has been considered and is acceptable — *one additional byte in a property set once per window* "No automated test: asserting the property bytes requires a live X server. Happy to add one if there's an existing pattern for X11 window tests I've missed." Co-authored-by: Lukas Wirth <lukas@zed.dev> |
||
|
|
7f2a2c3c3e |
gpui: Support Windows Restart Manager shutdown (#62987)
Handle the `WM_QUERYENDSESSION` and `WM_ENDSESSION` messages, which are used by Windows when shutting down an application. For example, Restart Manager uses this mechanism to gracefully close applications (e.g. when installing an update to the application). Release Notes: - N/A |
||
|
|
d9ad6aff67 |
gpui_linux: Release X11 client state before close callback (#63089)
Release Notes: - Fixed double-lease panic on X11 when reacting to WM_DELETE_WINDOW event. |
||
|
|
eb354c8d50 |
gpui: Make the Wayland render loop demand-driven (#60690)
Closes #55345. Wayland is the only platform whose frame ticks are conditional: a wl_surface frame callback only arrives after a commit the compositor goes on to repaint. GPUI assumed unconditional ticks (any previously our Wayland backend faked them), so an idle fullscreen window stopped receiving callbacks and froze until external damage arrived. This PR makes the Wayland render loop demand-driven, instead parking when there's nothing to draw, and stops Zed committing empty frames on every tick as the artificial heartbeat from the compositor. --- Release Notes: - Fixed the UI freezing in fullscreen on some Wayland compositors - Fixed idle windows waking at the display's refresh rate on Wayland --------- Co-authored-by: Philipp Schaffrath <philipp.schaffrath@gmail.com> Co-authored-by: Daan De Meyer <daan@amutable.com> Co-authored-by: Christopher Biscardi <chris@christopherbiscardi.com> |
||
|
|
f4178619ac |
gpui_linux: Drain buffered X11 events after foreground work (#62081)
# Objective Closes #52429 Closes #56735 Closes #62495 Closes #62878 Reverts #13071 This PR fixes Zed windows sometimes remaining blank when first opened on X11. The issue remained very inconsistent across WMs and conditions to reproduce and was finally consistently reproducable on my dwm build with no compositor and on i3 with no compositor after removing the workaround earlier added, which made it occur in i3 but not on my dwm build because it was more aggressive with it's EWMH policy. It happened only on opening a newer repo not opened the last time. While running foreground work, a synchronous X11 request can read events from the socket and place them in x11rb's internal event queue, calloop monitors the underlying socket rather than this internal queue, so if the socket is empty when the foreground work finishes, these events may remain unprocessed until unrelated X11 activity occurs. window is mapped -> events are buffered by x11rb -> X11 socket is no longer readable -> calloop does not wake -> MapNotify is not processed -> refresh loop does not start -> window remains blank This explains why the problem was inconsistent and differed between window managers. Later focus, scrolling (on any window), exposure, or other X11 activity could make the connection readable again and incidentally process the older events. My earlier PR #61162 fixed the related case where an already processed `Expose` event could wait indefinitely for a stopped refresh loop. It did not fix this initial-window case because the relevant events had not reached Zed's event handler yet, which was again not perfectly reproducable and lead me to assume was fixed. ## Solution Process any X11 events buffered by x11rb after each foreground runnable completes: foreground work completes -> buffered X11 events are processed -> MapNotify starts the refresh loop -> initial window contents are displayed This also removes the unconditional [`SetInputFocus`](https://tronche.com/gui/x/xlib/input/XSetInputFocus.html) added in #13071. That call frequently masked the issue by generating additional X11 activity, but also bypassed the window manager's focus policy despite Zed already sending the standard `_NET_ACTIVE_WINDOW` request. With the event queue handled correctly, Zed no longer needs to force focus to make the initial frame appear. ## Testing Repeatedly opened fresh and existing workspaces under dwm while another application retained focus with a new-project being opened everytime (at least not the previous one). Before this change, fresh windows could remain blank until later X11 activity occurred. After this change, they render immediately without focusing, scrolling, resizing, or switching workspaces. Also verified that window activation is left to the window manager through `_NET_ACTIVE_WINDOW`. ## 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) * [ ] Tests cover the new/changed behavior * [x] Performance impact has been considered and is acceptable Release Notes: * Fixed Zed windows sometimes remaining blank when first opened on X11 * Fixed Zed overriding window-manager focus policies when activating windows |
||
|
|
4d1935b8d0 |
gpui_linux: Clear X11 urgency hint when the window becomes active (#61619)
# Objective
On X11, GPUI raises the ICCCM `WM_HINTS` urgency flag to ask for
attention, but
it never clears it. The window stays urgent for the rest of its life.
`request_attention` was the only thing touching the bit. There was no
code
anywhere to clear it.
Docks and taskbars latch on the rising edge, so they show the attention
state
once and then sit there with a permanent urgent indicator, no further
notifications.
## Solution
Clear the flag when the window becomes active.
The read/modify/write moves out of `request_attention` into a helper,
`set_wm_hints_urgency(xcb, x_window, urgent)`. The raise and clear sites
are on
different self types (`X11Window` vs `X11WindowStatePtr`), so it takes
the
connection and window id.
The clear goes in `set_wm_properties`, where `state.active` gets set
from
`_NET_WM_STATE_FOCUSED`. That's the same field `request_attention`
already checks
in its `if self.is_active() { return; }` guard.
Two implementation notes:
* The clear is edge triggered (`state.active && !was_active`).
`set_wm_properties` recomputes everything on every `_NET_WM_STATE`
change, so a
level triggered check would do a blocking `WmHints::get` round trip on
every
maximize, fullscreen, hide and workspace switch while focused. Edge
triggering
is safe here because `request_attention` early returns when active, so
urgency
only ever gets raised while inactive, and the false to true transition
always
follows a raise.
* Clearing reads the hints first and skips the write if the bit isn't
set.
Otherwise focusing a window that never asked for attention would create
a
`WM_HINTS` property just to say "not urgent".
The raise path behaves exactly as before. The skip can't fire when
`urgent` is
true, so repeat raises still write every time.
Focusing clears the flag even if a second thread is still waiting.
That's already
how it works, since `request_attention` early returns when the window is
active.
## Testing
Tested on X11, Cinnamon with Muffin.
On an unpatched build the window had `_NET_WM_STATE_FOCUSED` and the
urgency bit
set at the same time.
W=$(xdotool search --class "dev.zed.Zed" | head -1)
xprop -id $W WM_HINTS
xprop -spy -id $W WM_HINTS
1. Fresh window says `WM_HINTS: not found`, and still does after
focusing it.
2. With focus on another window, the urgency bit shows up when attention
is
requested. `request_attention` early returns when active, so the window
has to
be unfocused for this to fire.
3. Focusing Zed clears the bit.
4. Repeating 2 and 3 re-arms it every cycle, not just once.
5. No `WM_HINTS` writes during normal use (resize, maximize, workspace
switch).
No automated test. It's an X11 round trip on a real window and there's
no X11
test harness in the tree.
## Self-Review Checklist:
- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments (none added)
- [x] The content adheres to Zed's UI standards (no UI change)
- [x] Tests cover the new/changed behavior (see Testing)
- [x] Performance impact has been considered and is acceptable
Note this was manually tested, there wasn't a good way to test it
through the current harness.
---
Release Notes:
- Fixed the X11 urgency hint never being cleared, which left Zed showing
a permanent attention indicator in taskbars and docks after the first
notification
|
||
|
|
7150765979 |
Preserve --user-data-dir across restarts (#62022)
# Objective Fixes #57701. When Zed is launched with `--user-data-dir`, a Zed-initiated restart—such as `workspace: clear trusted worktrees` or Restart to Update—can relaunch Zed without that argument. The restarted process then uses the default data directory instead of the directory selected by the user. ## Solution - Store the resolved custom data directory as GPUI restart arguments alongside the existing optional restart executable path. - Forward those arguments when relaunching on Linux, macOS, and Windows. - Preserve argument boundaries and native `OsString` values, including paths containing spaces. - On Windows updates, carry the arguments through `auto_update_helper.exe` when it launches the updated `Zed.exe`. Normal launches without `--user-data-dir` continue to restart without additional arguments. This does not attempt to preserve unrelated CLI arguments or general launch state. ## Testing - `cargo fmt --all -- --check` - `cargo test -p gpui` - `cargo test -p auto_update --features workspace/test-support` - `cargo check -p auto_update_helper --tests --target x86_64-pc-windows-msvc` - `./script/clippy -p gpui -p gpui_macos -p auto_update -p zed` - `./script/clippy -p auto_update_helper --target x86_64-pc-windows-msvc` The regression tests cover simultaneous restart executable and argument forwarding, Windows paths containing spaces and trailing backslashes, updater-helper argument parsing, and the final `Zed.exe` command. Compilation and unit tests were run on macOS. Linux and Windows runtime behavior was reviewed but not run locally. A full `gpui_windows` cross-target check was attempted, but its `psm` dependency requires the MSVC `lib.exe` tool, which is not available on this macOS host; the standalone Windows updater helper and its tests compile successfully for the Windows target. ## 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 (no UI changes) - [x] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed Zed forgetting an explicitly passed `--user-data-dir` argument after restarting (e.g. clicking "Restart to Update") --------- Co-authored-by: Tom Houlé <tom@tomhoule.com> |
||
|
|
c43e2d9734 |
gpui_linux: Handle XKB context initialization failure (#62868)
Release Notes: - Added check for XKB context initialization failure |
||
|
|
655ed1385b |
Prevent inactive windows from updating the IME position on linux/Wayland (#62086)
# Objective Fixes #62084 Fix the Wayland IME candidate window flickering between two positions when an inactive Zed window has a terminal producing continuous output. Terminal wakeup events in the inactive window can trigger IME position updates, causing its cursor bounds to alternate with those from the active window. https://github.com/zed-industries/zed/blob/90d024b88abc91264d9a0ad260eb4f365fa695c3/crates/terminal_view/src/terminal_view.rs#L1130-L1136 https://github.com/zed-industries/zed/blob/90d024b88abc91264d9a0ad260eb4f365fa695c3/crates/gpui/src/window.rs#L5617-L5627 ## Solution Ignore IME position updates from inactive Wayland windows. This ensures that only the active window can update the cursor rectangle of the shared Wayland text-input object. ## Testing To test manually on Linux with Wayland and Fcitx5: 1. Open two Zed windows. 2. Start continuous terminal output in the first window. 3. Use the Chinese IME in an editor in the second window. 4. Verify that the IME candidate window remains at a stable position. ## 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#uxui-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 ## Showcase after fix: [2026-08-02 22-43-35.webm](https://github.com/user-attachments/assets/ff2e3bc7-7772-481e-82f8-92e6e3fa7275) --- Release Notes: - Fixed the IME candidate window flickering when another Zed window has continuous terminal output |
||
|
|
c7aea6cbbd |
gpui_linux: Add wl_data_source support for outbound drags on Wayland (#61947)
# Objective - Enable drag'n'drop from Zed in Wayland. - Partially addresses #13186 - Related to #58161, #61940 ## Solution - Implement wl_data_source support for outbound drags on Wayland ## Testing Tested on KDE Wayland, kwin 6.7.3 I dragged files to Firefox, to other Zed windows and into Dolphin. ## 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 Can try to record if requested Release Notes: - Added support for dragging files from the Project Panel to external Linux Wayland apps. |
||
|
|
ae99a867d7 |
x11: Request repaint after exposure instead of within blocked loop (#61162)
# Objective Closes #61054 This PR fixes Zed window not repainting after they are uncovered on X11. When an X11 window becomes visible after being covered, X11 sends an `Expose` event to tell the application that the window contents need to be presented again. Previously, Zed stored this event and waited for the periodic refresh loop to request a presentation but, the refresh loop is stopped while a window is fully hidden to avoid unnecessary rendering. This meant there might be no refresh tick to handle the pending exposure. window is fully hidden -> periodic refresh loop stops window is uncovered -> expose event -> waits for refresh loop -> window may remain blank This change requests one presentation directly after processing the pending X11 events. Multiple `Expose` events for the same window are coalesced, and unmapped windows are ignored. ## Solution window is uncovered -> expose event -> presentation is requested -> window contents are displayed Required presentations are also excluded from inactive-window frame throttling, so the request is not dropped when Zed is unfocused. Regular rendering for unfocused or fully obscured windows remains throttled. ## Testing Check the issue being closed on steps to reproduction. ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - Fixed Zed windows sometimes not repainting after being uncovered on X11 |
||
|
|
dc2a339d5d |
gpui_linux: Fix Wayland serial token tracking (#61454)
Closes #58651 Closes FR-123 https://github.com/zed-industries/zed/pull/50406/ while fixing one issue regressed serial tracking in Wayland. What happens is we conflated unrelated serials into a common value which is wrong. For example, `InputMethod` serial does not come from the same source as `MousePress` or `KeyPress`, and if Zed is running for a while and the user performs lots of IME commits (`zwp_text_input_v3.commit`), `InputMethod` will overtake other serial values and will be incorrectly used for clipboard authorisation/selection by the compositor such as Mutter or kWin. This will effectively poison the clipboard making Zed the indefinite owner until we kill Zed. More concretely, we use `get_latest()` on the serial tracker to extract *the largest serial REGARDLESS of kind* which is wrong since not every serial kind comes from the same pool. Release Notes: - Fixed copy-paste behaviour in Wayland. |
||
|
|
de827bce2f |
gpui: Add system notification platform APIs (#61189)
Release Notes: - N/A or Added/Fixed/Improved ... --------- Co-authored-by: John Tur <john-tur@outlook.com> |
||
|
|
5079b33d65 |
gpui_linux: Fix unbounded memory growth when composing text with Fcitx5 under KWin/Wayland (#61079)
# Objective Close #61034. Fix unbounded memory growth when composing text with Fcitx5 under KWin/Wayland. While a non-empty preedit is cached, KWin resends it whenever it receives a text-input-v3 `commit()` ([relevant KWin code](https://github.com/KDE/kwin/blob/0e473e87a64d5d404c2fecf5516a9a5c3cf17d91/src/wayland/textinput_v3.cpp#L444-L504)). Zed handles the replayed preedit as a buffer edit. This invalidates the IME character coordinates, causing Zed to submit the same cursor rectangle and call `commit()` on the next frame. That commit makes KWin replay the cached preedit again, forming an infinite feedback loop. The observed memory growth is caused by retained CRDT state accumulating indefinitely. ## Solution Following [SDL's solution to the same problem](https://github.com/libsdl-org/SDL/commit/81479d8784d0e1a61eafb3a444dd3865ad762fb2), cache the last submitted cursor rectangle and compare it with the new rectangle before calling `set_cursor_rectangle()`. If the rectangles are equal, skip both the rectangle update and its associated `commit()`. The initial cursor rectangle and actual rectangle changes during an active composition are still submitted, preserving the candidate-window positioning behavior introduced by #59911. ## Testing Manually tested on KDE Plasma with `fcitx5-chinese-addons`. Before the fix, memory usage grew continuously while preedit text was present, with `WAYLAND_DEBUG=client` showing text-input events repeating indefinitely. After the fix, the repeated events stopped and memory usage remained stable. No automated test was added because reproducing the feedback loop requires compositor-specific KWin text-input-v3 behavior. ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed excessive memory usage when composing text with Fcitx5 on KDE Wayland. --------- Co-authored-by: Tom Houlé <tom@tomhoule.com> |
||
|
|
166f044fd0 |
gpui: Linux wayland set exclusive zone and edge (#60163)
# Objective The exclusive zone and exclusive edge of a wlr-layer-shell surface could only be set once, at creation, through `LayerShellOptions`. This adds runtime setters so a live layer-shell window such as a panel can update them without being recreated. ## Solution Add two methods on `Window`: - `set_exclusive_zone` updates how much screen space the surface reserves. A positive value reserves that distance from the anchored edge, 0 lets the surface be moved out of others' exclusive zones, and -1 ignores reserved space and may extend under other surfaces. - `set_exclusive_edge` chooses which anchored edge the exclusive zone applies to, which is needed to disambiguate a corner-anchored surface. Setting an exclusive edge the surface is not anchored to is a fatal protocol error, so the edge is validated (it must be a single edge that the surface anchor contains) and an invalid edge is logged and ignored. The same validation now also guards the creation path. Both setters only commit the surface when a change actually applies, and are no-ops on non-layer-shell windows and on other platforms. This is where these 2 are documented: https://wayland.app/protocols/wlr-layer-shell-unstable-v1#zwlr_layer_surface_v1:request:set_exclusive_zone https://wayland.app/protocols/wlr-layer-shell-unstable-v1#zwlr_layer_surface_v1:request:set_exclusive_edge ## Testing - Verified with a small local layer-shell window (a top bar anchored TOP, LEFT, RIGHT) with buttons that call the setters at runtime - No automated test was added, since this calls through to the compositor. - Reviewers without a layer-shell capable compositor (for example GNOME/Mutter) cannot exercise this, as `zwlr_layer_shell_v1` is unavailable there, I tested this on the [Smithay](https://github.com/Smithay/smithay/) based compositor [niri](https://github.com/niri-wm/niri) ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
905e955a70 |
gpui: Implement window attention (#58779)
Release Notes: - On agent notifications, the corresponding zed window will now mark itself for OS level attention --------- Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com> |
||
|
|
2c4e44704c |
Fix "Task polled after completion" panic (#60693)
Dropping a scheduled runnable cancels its task and makes the next poll of any awaiter panic with "Task polled after completion." The only paths where we drop these runnables seem to be during shutdown or extreme resource exhaustion, so, let's leak the runnables instead of crashing. On Windows, we also moved to calling the Win32 thread pool API directly, because 1) WinRT thread pool API is just a wrapper that adds overhead we don't need, and 2) the closure we pass to the `WorkItemHandler` object takes ownership of the runnable object, so if the WinRT thread pool releases the delegate, it can free the runnable without our control. Release Notes: - N/A |
||
|
|
664b7ecb40 |
gpui: Fix hover state not clearing when mouse leaves window (#60275)
# Objective Fix two gaps in element hover tracking at window boundaries. Hover was only re-evaluated on `MouseMove`, so when the pointer left the window no event fired `on_hover(false)` and the element stayed hovered. Symmetrically on Wayland, no `Motion` follows `Enter` until the pointer moves again, so hover was not established at the entry pixel. Both cases are easy to miss since most hover-styled elements don't sit flush against the window edge, but they surfaced while implementing layer_shell popups with input_regions, which should close when stop hovering. ## Solution The hover compare-and-fire logic in `div` is refactored into a shared `update_hover` closure, and a second listener on `MouseExitEvent` clears hover when the pointer leaves the window. It clears unconditionally because `MouseExited` doesn't update the tracked mouse position, so a hit test during that dispatch would still report the element as hovered. On Wayland, a `MouseMove` is synthesized at the entry position on `wl_pointer.enter`, mirroring the `MouseExited` already dispatched on `Leave`. ## Testing Tested manually on Wayland/Linux: hover on a window-edge element clears when the pointer leaves the window, and hover is established immediately when the pointer enters a surface with an element under the entry pixel. Not tested on other platforms. The `div` change relies on each platform's existing `MouseExited` dispatch: macOS and X11 emit it, so they get the exit fix too. Windows never dispatches `MouseExited` (`WM_MOUSELEAVE` only flips the window-level hover flag), so the stuck-hover case might remain there, unchanged from before. Before: https://github.com/user-attachments/assets/6af83bb3-de9d-40e2-a64c-bdefc98fc96d After: https://github.com/user-attachments/assets/721a9b5c-108a-499f-867e-da111836a34a Here is an example application to test this: ```rs #![cfg_attr(target_family = "wasm", no_main)] use gpui::{ App, Bounds, Context, Window, WindowBounds, WindowOptions, div, prelude::*, px, rgb, size, }; use gpui_platform::application; struct HoverExit { hovered: bool, } impl Render for HoverExit { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { // Fills the whole window so its edge is the window edge: moving the mouse // out of the window is what exercises the MouseExited path. div() .id("hover-exit") .size_full() .flex() .justify_center() .items_center() .text_xl() .text_color(rgb(0xffffff)) .bg(if self.hovered { rgb(0x585f58) } else { rgb(0x505050) }) .child(if self.hovered { "HOVERED" } else { "not hovered" }) .on_hover(cx.listener(|this, hovered, _, cx| { this.hovered = *hovered; cx.notify(); })) } } fn run_example() { application().run(|cx: &mut App| { let bounds = Bounds::centered(None, size(px(240.), px(160.0)), cx); cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), app_id: Some("gpui-hover-exit".to_string()), ..Default::default() }, |_, cx| cx.new(|_| HoverExit { hovered: false }), ) .unwrap(); cx.activate(true); }); } #[cfg(not(target_family = "wasm"))] fn main() { run_example(); } #[cfg(target_family = "wasm")] #[wasm_bindgen::prelude::wasm_bindgen(start)] pub fn start() { gpui_platform::web_init(); run_example(); } ``` ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - Fixed element hover state not clearing when the mouse leaves the window |
||
|
|
546a16d64f |
gpui: Add parent-anchored native popup windows (with wayland xdg_popup implementation only so far) (#60232)
# Objective gpui can't show UI that extends past the window it belongs to. Menus, dropdowns and tooltips are drawn as elements inside the window, so they clip at its edges. This PR adds a window kind for platform-native popups anchored to a parent window, as groundwork for real native menus, dropdowns and tooltips. ## Solution `WindowKind::AnchoredPopup(PopupOptions)` opens a popup positioned relative to a parent window. Instead of giving the popup an absolute position, you describe where it should go and the platform figures out the rest: - `parent`: the window to anchor to - `anchor_rect`: a rectangle in the parent, e.g. the button that opened the menu - `anchor` and `gravity`: which point of that rect to attach to, and which direction to grow - `constraint_adjustment`: what the platform may do if the popup would leave the screen (slide, flip, resize) - `grab`: menu behavior, the popup takes focus and is dismissed when clicking outside the app The popup's size comes from `WindowOptions::window_bounds`. This model mirrors Wayland's `xdg_positioner`, where the compositor owns positioning and the client can only describe intent. Since that's the most restrictive case, the other platforms can implement the same description later with simple math against screen bounds. Only Wayland is implemented so far, via `xdg_popup` on top of the existing surface implementation. Popups can be parented to toplevels, layer-shell surfaces (a menu opened from a panel) and other popups (nested menus). macOS, Windows, X11 and web reject the kind with `PopupNotSupportedError`, so callers can detect that and fall back to in-window popovers. Some Wayland details that might help during review: - Anchor rects are translated from gpui coordinates into the parent's window geometry space and clamped to it. A rect outside the geometry, or with zero size, is a fatal protocol error - Resizing a mapped popup goes through `xdg_popup.reposition` - Mouse press serials are now recorded on press only, not release. Compositors decline grabs and interactive moves that reference a release serial ## Testing Tested manually on Wayland with an example app: the menu opens anchored below its button, extends past the parent window, flips above the button near the bottom of the screen, and a grabbing popup is dismissed when clicking into another application. Nested menus were tested in one of my projects (ignore that they are ugly, that's just a prototype 😛): https://github.com/user-attachments/assets/2cd3e2e9-87f7-4b02-986f-48e5633e205c I also have a complete runnable example demonstrating it. I did not add it to the PR, because this might give the impression that `WindowKind::AnchoredPopup` are a complete implementation, despite only working on wayland so far: <details> <summary>Click to view example</summary> ```rust //! Example and manual test for platform-native popups (`WindowKind::AnchoredPopup`). //! //! A native popup is a real, parent-anchored window that can extend beyond its parent onto the //! screen, unlike gpui's in-window popovers. Run it, open the menu, and confirm the points listed //! in the window. On a platform without an implementation the button reports that popups are not //! supported instead of opening anything. //! //! Run with: cargo run -p gpui --example popup #![cfg_attr(target_family = "wasm", no_main)] use gpui::{ AnyWindowHandle, App, Bounds, Context, MouseButton, SharedString, Window, WindowBounds, WindowHandle, WindowKind, WindowOptions, div, point, popup::*, prelude::*, px, rgb, size, }; use gpui_platform::application; /// The trigger button, at a fixed position so the popup can anchor to a known rectangle. Real code /// would anchor to the measured bounds of whatever element opens the popup. const BUTTON_BOUNDS: Bounds<gpui::Pixels> = Bounds { origin: point(px(24.), px(24.)), size: size(px(200.), px(32.)), }; const POPUP_SIZE: gpui::Size<gpui::Pixels> = size(px(260.), px(320.)); struct Menu; impl Render for Menu { fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { let item = |label: &str| { div() .id(label.to_string()) .px_3() .py_1() .rounded_sm() .hover(|this| this.bg(rgb(0x3a3a3a))) .cursor_pointer() .child(label.to_string()) .on_click(|_, window, _| window.remove_window()) }; div() .id("menu-root") .size_full() .p_1() .flex() .flex_col() .gap_0p5() .bg(rgb(0x2a2a2a)) .text_color(gpui::white()) .rounded_md() .border_1() .border_color(rgb(0x454545)) .child(item("Foo")) .child(item("Bar")) .child(item("Baz")) .child(item("Qux")) .child(item("Alice")) .child(item("Bob")) } } struct PopupExample { menu: Option<WindowHandle<Menu>>, status: SharedString, } impl Default for PopupExample { fn default() -> Self { Self { menu: None, status: "Click \"Open menu\" to open a native popup.".into(), } } } impl PopupExample { /// Closes the menu if it is open. Returns true if a menu was actually open. fn close_menu(&mut self, cx: &mut App) -> bool { match self.menu.take() { Some(menu) => menu .update(cx, |_, window, _| window.remove_window()) .is_ok(), None => false, } } fn toggle_menu(&mut self, parent: AnyWindowHandle, cx: &mut App) { if self.close_menu(cx) { return; } match open_menu(parent, cx) { Ok(menu) => { self.menu = Some(menu); self.status = "Menu open. Dismiss it by selecting an item, clicking elsewhere in \ this window, or clicking another application." .into(); } // A real application would fall back to an in-window popover here. Err(error) => { self.status = format!("Failed to open a native popup: {error}").into(); log::error!("failed to open popup: {error}"); } } } } impl Render for PopupExample { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let bullet = |text: &str| div().child(format!("• {text}")); div() .id("root") .size_full() .bg(rgb(0xf7f7f7)) .text_color(rgb(0x222222)) // Same-app clicks don't auto-dismiss a grabbing popup (see `PopupOptions::grab`). .on_mouse_down( MouseButton::Left, cx.listener(|this, _, _window, cx| { this.close_menu(cx); }), ) .child( div() .size_full() .p_5() .pt(px(76.)) .flex() .flex_col() .gap_3() .child(div().text_xl().child("Native popup test")) .child(div().text_sm().child( "WindowKind::AnchoredPopup opens a real, parent-anchored window that can \ extend past this window onto the screen. Only some platforms implement \ it so far.", )) .child( div() .flex() .flex_col() .gap_1() .text_sm() .text_color(rgb(0x555555)) .child(div().child("Verify:")) .child(bullet("The menu opens anchored below the button.")) .child(bullet( "The menu extends past the bottom edge of this window.", )) .child(bullet( "Near the bottom of the screen, the menu flips above the button.", )) .child(bullet("Clicking another application dismisses the menu.")) .child(bullet( "Selecting an item or clicking in this window dismisses it.", )), ) .child( div() .text_sm() .text_color(rgb(0x333333)) .child(self.status.clone()), ), ) .child( div() .absolute() .left(BUTTON_BOUNDS.origin.x) .top(BUTTON_BOUNDS.origin.y) .w(BUTTON_BOUNDS.size.width) .h(BUTTON_BOUNDS.size.height) .flex() .items_center() .justify_center() .bg(rgb(0xffffff)) .border_1() .border_color(rgb(0xd0d0d0)) .rounded_md() .cursor_pointer() .id("open-menu") .active(|this| this.bg(rgb(0xeeeeee))) .child("Open menu ▾") // Open on mouse-down, not on click, so the grab is taken while the button is still held. .on_mouse_down( MouseButton::Left, cx.listener(|this, _, window, cx| { // Don't let the window handler above close the menu we are opening. cx.stop_propagation(); this.toggle_menu(window.window_handle(), cx); }), ), ) } } fn open_menu(parent: AnyWindowHandle, cx: &mut App) -> anyhow::Result<WindowHandle<Menu>> { cx.open_window( WindowOptions { titlebar: None, // Sizes the popup. The platform decides the position, so the origin is ignored. window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.), px(0.)), size: POPUP_SIZE, })), kind: WindowKind::AnchoredPopup(PopupOptions { parent, anchor_rect: BUTTON_BOUNDS, // Anchor to the button's bottom-left and grow down-right so the menu drops beneath it. anchor: PopupAnchor::BottomLeft, gravity: PopupGravity::BottomRight, // Slide horizontally and flip vertically if the menu would leave the screen. constraint_adjustment: PopupConstraintAdjustment::SLIDE_X | PopupConstraintAdjustment::FLIP_Y, offset: point(px(0.), px(4.)), // Grab input so the compositor dismisses the popup on clicks into other applications. grab: true, }), ..Default::default() }, |_, cx| cx.new(|_| Menu), ) } fn run_example() { application().run(|cx: &mut App| { cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(100.), px(100.)), size: size(px(420.), px(300.)), })), ..Default::default() }, |_, cx| cx.new(|_| PopupExample::default()), ) .unwrap(); cx.activate(true); }); } #[cfg(not(target_family = "wasm"))] fn main() { run_example(); } #[cfg(target_family = "wasm")] #[wasm_bindgen::prelude::wasm_bindgen(start)] pub fn start() { gpui_platform::web_init(); run_example(); } ``` </details> ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
961f4f2024 |
gpui: Refresh mouse position after bounds changes (#60421)
## Summary - Refresh GPUI's cached mouse position when window bounds change so hover hit-testing uses the current cursor position after live resize. - Return X11 mouse positions in window-relative logical pixels to keep `PlatformWindow::mouse_position()` consistent with other backends. Fixes #57354 ## Testing - `cargo fmt -p gpui -p gpui_linux` - `cargo check -p gpui_linux` - `cargo check -p gpui` ## Suggested .rules additions - In GPUI platform backends, `PlatformWindow::mouse_position()` should return window-relative logical pixels; use separate APIs or fields for global/device-pixel coordinates. Release Notes: - Fixed incorrect hover state while resizing GPUI windows. |
||
|
|
a29c0d41f4 |
gpui: Add input region support for Wayland windows (#60161)
# Objective Wayland windows have no way to restrict which parts of the surface accept pointer and touch input. This adds support for setting an input region, so events outside it pass through to whatever is below the window. This is useful for shaped or partially click-through windows. Clicks in green area can pass through the window, clicks in red area do not: <img width="1057" height="395" alt="image" src="https://github.com/user-attachments/assets/2039af62-e43b-4834-b877-edad2a8f5ccf" /> ## Solution Add `Window::set_input_region`, which takes `Option<&[Bounds<Pixels>]>`: - `Some(rects)` restricts pointer and touch input to the union of the rectangles, in window coordinates. - `Some(&[])` is an empty region, so the window receives no input at all and is fully click-through. - `None` resets the region to the default, so the whole window receives input again. On Wayland this maps to `wl_surface.set_input_region`, building a `wl_region` from the rectangles or clearing it for `None`, and commits so the change applies immediately rather than waiting for the next frame. The method is a no-op on other platforms. ## Testing Tested on Linux with Wayland. - Tested in my own GPUI application, which uses a fullscreen layer for overlays while allowing clicks outside of the rendered elements to be passed through to the underlying windows. - No automated test was added, since this calls through to the compositor and is checked by observing input routing. ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable --- Release Notes: - N/A |
||
|
|
c56646ffdf |
terminal: Fix IME candidate window not following cursor in TUI apps (#59911)
# Objective Fix IME candidate window not following cursor position in the integrated terminal when running fullscreen TUI applications like opencode. When using IME (Input Method Editor) in Zed's terminal with fullscreen TUI applications (e.g., opencode), the candidate window does not follow the cursor position. This issue does not occur in normal terminal usage (e.g., bash shell). # Solution The root cause was three-layer blocking preventing IME position updates in ALT_SCREEN mode: 1. **ALT_SCREEN blocking**: `selected_text_range()` returned `None` in ALT_SCREEN mode, causing `selected_bounds()` to return `None` 2. **Missing trigger**: `Event::Wakeup` did not call `invalidate_character_coordinates()`, so cursor movement did not trigger IME position updates 3. **Composition blocking**: `update_ime_position()` skipped updates when `state.composing` was true Fixes: - Remove ALT_SCREEN check in `selected_text_range()` so IME position updates work in fullscreen TUI apps - Add `window.invalidate_character_coordinates()` in `Event::Wakeup` to trigger IME position updates when terminal cursor moves - Remove `state.composing` check in `update_ime_position()` to allow IME position updates during text-input-v3 composition - Remove unused `terminal` field from `TerminalInputHandler` struct # Testing **Did you test these changes? If so, how?** - Yes, tested on Linux GNOME Wayland with iBus input method - Verified IME candidate window correctly follows cursor in opencode - Verified normal terminal usage with IME still works correctly **Are there any parts that need more testing?** - Other IMEs (fcitx, etc.) may need testing **How can other people (reviewers) test your changes?** 1. Open Zed's integrated terminal 2. Run a fullscreen TUI application like `opencode` 3. Activate IME (e.g., iBus with Chinese input) 4. Type text and observe the IME candidate window follows the cursor **What platforms did you test these changes on?** - Linux (GNOME Wayland) - tested - macOS - not tested (may have different IME behavior) - Windows - not tested (different code path) # Self-Review Checklist: - [x] I've reviewed my own diff for quality, security, and reliability - [ ] Unsafe blocks (if any) have justifying comments - [ ] The content adheres to Zed's UI standards (UX/UI and icon guidelines) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable # Showcase <details> <summary>Before</summary> <video src="https://github.com/user-attachments/assets/ee2fac4e-801b-49af-a57e-32ce25e01db5" width="320" height="180" /> </details> <details> <summary>After</summary> <video src="https://github.com/user-attachments/assets/c669ea99-2ffc-4179-b587-a47873e33e70" width="320" height="180" /> </details> --- Release Notes: - Fixed IME candidate window not following cursor in terminal TUI apps |
||
|
|
f4364d870e |
gpui_linux: Add support for open_window in headless client (#60359)
This actually makes it possible for Linux headless client to have working windows for computation (well, we are in headless mode after all). This also matches macOS headless client behaviour. Release Notes: - N/A |
||
|
|
7c3160b7bf |
gpui_linux: Consume Wayland startup activation token (#59995)
When opening Zed from GNOME on Wayland, the cursor can stay stuck in the launch spinner state for several seconds because GPUI never tells the compositor that the launched app's first window has loaded. Desktop launchers pass this information through `XDG_ACTIVATION_TOKEN`, which Wayland clients are expected to consume once their first toplevel surface is ready. This PR fixes that by reading and removing `XDG_ACTIVATION_TOKEN` during Wayland client startup, storing it on the client state, and consuming it on the first XDG toplevel surface via the existing `xdg_activation_v1.activate(token, surface)` plumbing. Anthony manually verified this on GNOME Wayland. docs ref: https://wayland.app/protocols/xdg-activation-v1 Release Notes: - Fixed Linux Wayland cursor being stuck as a spinner for a couple of seconds. |
||
|
|
441de84a77 |
gpui_linux: Suppress dead code warning on wake_sender (#60090)
This PR adds a conditional `allow(dead_code)` to the `wake_sender` field
to fix this error when building Collab:
```
error: field `wake_sender` is never read
--> crates/gpui_linux/src/linux/platform.rs:126:5
|
116 | pub(crate) struct LinuxCommon {
| ----------- field in this struct
...
126 | wake_sender: Sender<()>,
| ^^^^^^^^^^^
|
= note: `-D dead-code` implied by `-D warnings`
= help: to override `-D warnings` add `#[expect(dead_code)]` or `#[allow(dead_code)]`
error: could not compile `gpui_linux` (lib) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
```
https://github.com/zed-industries/zed/actions/runs/28374439219/job/84060893437
Release Notes:
- N/A
|
||
|
|
35eaeb94a7 |
gpui: Fix xdg_toplevel app_id set to None at first commit on Wayland (#55583)
This PR fixes the default behaviour of setting `app_id` to `None` which breaks the rules based management by KWin as the first commit doesn't have the actual `app_id` and apply initially setting stops checking for the window by when it updates. 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 #53962 Release Notes: - Fixed KWin not respecting Zed's rules due to mismatch of toplevel app_id at startup |
||
|
|
dae3e574e4 |
gpui_linux: Improve error message when X11 and Wayland feature flags are missing (#58685)
Improves `gpui_linux` error messages for missing feature flags. Currently, you'd need to look at the source & Rust backtrace to diagnose the error shown when the feature flags are missing. 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 Release Notes: - Improve `gpui_linux` error messages for missing feature flags --------- Co-authored-by: Tom Houlé <tom@tomhoule.com> |
||
|
|
ee571d3c69 |
gpui: Add system wake callback (#59831)
# Objective GPUI apps currently don't have a cross-platform way to react when the system wakes from sleep. ## Solution Add `Application::on_system_wake`, backed by platform hooks for macOS, Windows, and Linux. The platform listeners are registered lazily once an app installs a wake callback. ## Testing - N/A ## 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) - [ ] Tests cover the new/changed behavior - [x] Performance impact has been considered and is acceptable Release Notes: - N/A |