65 Commits
Author SHA1 Message Date
Vlad GaevskyandChris Biscardi 55387ea4b7 gpui_windows: Keep DirectWrite's default ligatures when no font features are set (#62338)
On Windows, ligatures are off by default: they only show up if
`buffer_font_features` is set to something non-empty.

`generate_font_features` always creates an `IDWriteTypography` and
passes it to `apply_font_features` (`direct_write.rs:446-452`), and the
layout code calls `SetTypography` with it unconditionally (`:567`,
`:605`). `apply_font_features` returned early when no features were
configured, so an empty typography object reached DirectWrite.
`SetTypography` replaces the default feature set with exactly what the
typography contains, so `liga`, `clig` and `calt` ended up disabled.

Dropping the early return lets the rest of the function run, which adds
`liga`, `clig` and `calt` at 1. Users who configure features explicitly
are unaffected: that path already ran before this change, and an
explicit `liga: 0` still resolves to 0 through the same loop.

I went with this rather than guarding the two `SetTypography` calls,
because the function already owns the knowledge of which features
DirectWrite enables by default for the non-empty case, and guarding the
call sites would duplicate it in two places.

Other platforms are not affected: `generate_feature_array` on macOS
(`gpui_macos/src/open_type.rs:77`) appends one dictionary per configured
tag and does not replace the default feature set when the list is empty.

No test here: `apply_font_features` takes a live `IDWriteTypography`
from `CreateTypography()`, so covering it needs a real DirectWrite
factory and cannot run off Windows. I can extract the tag resolution
into a pure function and unit test that separately if you would prefer
it.

Checked on a Windows build with no `buffer_font_features` set: ligatures
render with this change and are absent without it.

Release Notes:

- Fixed ligatures being disabled on Windows unless
`buffer_font_features` was set
- [GPUI] N/A

Co-authored-by: Chris Biscardi <chris@christopherbiscardi.com>
2026-09-17 16:37:56 +00:00
Minh VuandChris Biscardi 836c68bb20 gpui_windows: Fix reversed linear/sRGB transfer functions in shader (#57543)
## Summary
- swap the Windows HLSL exponents for `linear_to_srgb` and
`srgb_to_linear`
- align the Windows Oklab gradient path with the existing Metal and WGSL
implementations

## Testing
- not run (shader-only change)

Fixes #57542

Release Notes:

- [GPUI] Fix reversed linear/sRGB transfer functions

Co-authored-by: Chris Biscardi <chris@christopherbiscardi.com>
2026-09-17 16:09:12 +00:00
Finn Evers 20d55798db Fix cargo shear warnings (#64340)
Also updates CI to always run this - that way we ensure that disabling
or enabling tests does not become stale at some point and thus can
safely add this.

Release Notes:

- N/A
- [GPUI] N/A
2026-09-17 08:49:31 +00:00
Finn Evers 26fb9817c4 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
2026-09-17 08:24:25 +00:00
Kirill Bulatov a5be476362 Fix Windows build of remote-server (#64270)
Fixes a warning from
https://github.com/zed-industries/zed/actions/runs/35018526372/job/104551077687

Release Notes:

- N/A
- [GPUI] N/A
2026-09-16 06:30:27 +00:00
Anthony Eid eb655653f2 Move Windows dialogs and credential I/O off the foreground thread (#64250)
## Summary

Move Windows file-open, file-save, and native message dialogs off the
foreground executor so time spent waiting for a user does not appear as
a long foreground task poll. Move Windows Credential Manager reads,
writes, and deletes to the background executor as well.

The caller-facing receiver/task APIs remain unchanged. No hang-journal
suppression or new public GPUI task-spawn API is introduced.

## Implementation

- Run synchronous native dialogs on dedicated threads with COM STA
initialization and cleanup on the same thread.
- Keep the native owner relationship when a window exists; support
ownerless file/save dialogs by passing a null owner HWND.
- Serialize dialogs per owner using one mutex, also used to wait for
active native work before destroying the owner HWND. Closing the GPUI
window sets a shared cancellation flag and hides the native window;
queued requests see that flag and cannot launch. No pending counter,
lifetime lease, cancellation registry, or idle-notification channels are
needed.
- Use a worker-thread timer to request native cancellation when the
caller drops its receiver or the owner closes.
- Preserve message prompts without a Cancel option by vetoing user
cancellation unless an internal cancellation was requested.
- Distinguish actual file-dialog failures from user cancellation.

Sleep/wake and frame-visibility telemetry are intentionally deferred.

## Validation

- `corgi fmt -p gpui_windows -- --check` and scoped `git diff --check`
passed.
- Minimal scratch Windows-target harnesses type-checked the dialog
module and native API wiring against real Windows 0.62 bindings. These
are not full integration builds.
- Six extracted native-independent state/policy tests passed, covering
owner shutdown, queued-request cancellation state, per-request
cancellation isolation, per-owner serialization, ownerless cancellation,
and 12 message-prompt cancellation-policy combinations. These do not
execute native dialogs or the complete coordinator/worker handoff.
- Before the shutdown simplification, Cameron built and launched Zed
successfully on Windows using a shorter `CARGO_TARGET_DIR`, and reported
running the manual prompt checks. The captured output contains no
foreground/action hang or saved task-trace messages, but exact
prompt-by-prompt coverage and timing have not been established.
- The committed Windows test suite has not yet been run natively.

## Open review items

This PR remains a draft. The dialog helper has been simplified to
approximately 245 production lines, retaining native ownership and using
the existing per-owner mutex for shutdown instead of separate lifetime
bookkeeping. Independent static review found no concrete lifetime
regression. Native cancellation still uses the existing worker-thread
timer/window-enumeration mechanism; Windows runtime validation of the
revised shutdown path is outstanding.

Before merging, verify ownerless prompts, focus/Alt+Tab behavior,
overlapping requests for the same owner, cancellation while
queued/shown, owner closure, and nested overwrite confirmations on
Windows. Absence of hang logs alone does not establish those behaviors.

The required review-confirmation marker in README.md must be removed
manually by the human author after review.

Release Notes:

- N/A
- [GPUI] Move window dialogs and credential I/O off foreground thread
2026-09-15 18:59:14 +00:00
Anthony Eid 6736a09abe 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
2026-09-12 03:25:52 +00:00
whitecat1331 d223a49235 gpui_windows: Fix use-after-free in power request reason string (#64001)
## Summary

`PowerRequest::prevent_idle_sleep` passed `PowerCreateRequest` a reason
string whose UTF-16 buffer was dropped when the function returned.
`PowerCreateRequest` documents that the reason pointer must remain valid
for the lifetime of the handle, so the OS was left holding a pointer
into freed memory.

This is a use-after-free (CWE-416), a memory-safety vulnerability. The
reason string is a fixed literal rather than attacker-controlled input,
so the practical exploitability is limited; but it is a genuine
memory-safety defect and should be fixed.

Keep the UTF-16 buffer alive alongside the handle.

## The bug

The reason string is encoded into a local `Vec<u16>`, and a raw pointer
to its heap buffer is handed to `PowerCreateRequest`:

```rust
let mut reason = reason.encode_utf16().chain([0]).collect::<Vec<_>>();
let context = REASON_CONTEXT {
    // ...
    Reason: REASON_CONTEXT_0 {
        SimpleReasonString: PWSTR(reason.as_mut_ptr()),
    },
};
let handle = unsafe { PowerCreateRequest(&context) }?;
// ...
Ok(Self { handle }) // `reason` dropped here, freeing the buffer the handle points into
```

The pointer crosses an `unsafe` FFI boundary, so the borrow checker
cannot see that Windows retains it. When `prevent_idle_sleep` returns,
`reason` is dropped and its buffer freed while the handle still refers
to it.

## The fix

Move the UTF-16 buffer into the struct so it lives as long as the
handle:

```rust
struct PowerRequest {
    handle: HANDLE,
    _reason: Vec<u16>,
}
// ...
Ok(Self { handle, _reason: reason })
```

`Drop` closes the handle before fields are dropped, so the buffer is
freed only after the OS stops referencing it.

Release Notes:

- Fixed a use-after-free in Windows idle-sleep prevention that could
read freed memory.
2026-09-11 21:17:45 +00:00
Xiaobo LiuandKirill Bulatov 3d0649186f 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>
2026-09-09 13:49:13 +00:00
Kirill Bulatov b80f016f89 Bump more dependencies (#63379)
* 1st commit fixes bumps `quinn-proto` and `serde_with` to fix the
dependabot alerts

* 2nd commit deduplicates more dependencies

`cargo tree -d` listing: 194 -> 187 top-level entries on the host
target, 298 -> 287 unique duplicated crate-versions across all targets.

<details>
<summary>Deduplicated list</summary>

```
accesskit_consumer (v0.35.0, v0.37.0 -> v0.38.0)
bindgen (v0.71.1, v0.72.1 -> v0.72.1)
nix (v0.28.0, v0.29.0, v0.30.1 -> v0.28.0, v0.30.1)
ordered-float (v2.10.1, v4.6.0 -> v5.5.0)
quick-xml (v0.30.0, v0.37.5, v0.38.3, v0.39.3, v0.41.0 -> v0.30.0, v0.37.5, v0.39.3, v0.41.0)
sysinfo (v0.31.4, v0.37.2 -> v0.31.4, v0.39.6)
wasm-encoder (v0.252.0, v0.254.0 -> v0.254.0)
wasmparser (v0.252.0, v0.254.0 -> v0.254.0)
windows-registry (v0.4.0, v0.5.3, v0.6.1 -> v0.4.0, v0.6.1)
```

`ordered-float v4.6.0` remains in the lockfile only as an inactive
optional dependency of `sea-query`; the compiled graph is fully
deduplicated to v5.5.0.

</details>

Release Notes:

- N/A
2026-09-02 18:21:25 +00:00
John Tur 2ada348466 Improve Windows shell discovery (#63339)
- Simplify PowerShell discovery, and add support for .NET global tool
installations.
- Fix Git Bash discovery in the case where Zed was launched from within
Git Bash. Git Bash prepends its internal `mingw64\bin` directory to
`PATH`, so `which git` returns a different `bash` executable that causes
the relative path lookup to fail.

Release Notes:

- N/A
2026-08-28 03:21:39 +00:00
69bfd0c0ef gpui_windows: Fix window placement on secondary monitor with different DPI scaling (#62859)
# Objective

Fixes #48927. On Windows, when monitors have different DPI scaling
factors, a new window opened on a secondary monitor can be positioned
partially off-screen, with the title bar unreachable.

## Solution

`WindowsWindow::new` calls `CreateWindowExW` with `CW_USEDEFAULT` for
the window's initial position, so Windows picks a starting spot
(typically based on where the previous window was, which is often the
primary monitor) before the window is explicitly moved to its intended
monitor via `SetWindowPlacement`.

`WindowsWindowState::new` immediately reads the window's scale factor
via `GetDpiForWindow(hwnd)` at that point — i.e. the DPI of wherever
Windows initially placed it, not necessarily the target monitor.
`retrieve_window_placement` then used that scale factor to convert the
target monitor's logical bounds into physical pixels. When the two
monitors have different scaling (e.g. 150% vs 100%, as in the linked
issue), this produces the wrong physical rect, leaving the window
off-screen.

The target `WindowsDisplay` already computes its own correct
`scale_factor` from the actual monitor (`get_scale_factor_for_monitor`)
— this is also what `check_given_bounds` already uses. This PR exposes
that value via `WindowsDisplay::scale_factor()` and uses it in
`retrieve_window_placement` instead of the transient window's scale
factor, since the bounds being converted are expressed in logical pixels
for that target display.

## Testing

- Verified the logic by tracing through `WindowsWindowState::new` →
`retrieve_window_placement` → `calculate_window_rect` and confirming the
target monitor's own DPI (not the temporarily-assigned window DPI) is
now used to compute the physical placement rect, matching the approach
`WindowsDisplay::check_given_bounds` already uses for the same
target/temporary-monitor mismatch.
- I wasn't able to build/run Zed locally in this environment (missing
Windows SDK components in the local toolchain, unrelated to this change)
to reproduce the original multi-monitor/mixed-DPI repro steps
first-hand. I'd appreciate a maintainer or anyone who can reproduce
#48927 double-checking on real mixed-DPI hardware.
- Platforms: Windows only (`gpui_windows` crate); no other platform code
touched.

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments (no new unsafe
blocks added)
- [ ] The content adheres to Zed's UI standards (N/A, no UI change)
- [ ] Tests cover the new/changed behavior (no existing test harness for
Windows-specific placement logic; happy to add one if pointed at the
right pattern)
- [x] Performance impact has been considered and is acceptable (no
measurable impact; same number of DPI queries, just reading from the
already-computed `WindowsDisplay` instead of the window)

Release Notes:

- Fixed: new windows on Windows could open partially off-screen when
placed on a secondary monitor with a different DPI scaling factor than
the monitor Windows initially placed them on.

---------

Co-authored-by: Lukas Wirth <lukas@zed.dev>
Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-08-26 08:42:18 +00:00
JKNandLukas Wirth eae9f3eed0 gpui_windows: Implement render_to_image for headless window capture (#63012)
# Objective

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

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

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

## Solution

The DirectX analogue of the Metal path:

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

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

## Testing

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

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines) — n/a, no UI surface
- [ ] Tests cover the new/changed behavior — see Testing; needs a
Windows host, happy to add
- [x] Performance impact has been considered and is acceptable — the
readback path is `test-support`-only; `draw` is unchanged apart from the
`render` factoring

## Showcase

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

---

Release Notes:

- N/A

Co-authored-by: Lukas Wirth <lukas@zed.dev>
2026-08-26 08:17:09 +00:00
Ali 5a05eb346a gpui_windows: Clear render target before compositing COLR emoji (#63225)
… layers

# Objective

olor emoji (COLR glyphs) are rasterized on the GPU by compositing each
glyph layer into a D3D11 render target that is created with
`pInitialData: None` and, until now, never cleared. The texture contents
are undefined: texels not covered by any layer quad retained garbage
(typically leftovers from previous rasterizations via the DXGI
allocation pool).

## Solution

- Clear the render target with `[0, 0, 0, 0]` (premultiplied
transparent) immediately after binding it and before drawing the layers.

## Testing

add test to test this specifically 


## Showcase

before : 
<img width="1634" height="754" alt="ezgif-1a339c7dea79f905"
src="https://github.com/user-attachments/assets/6e282c46-d2a4-4043-9c1c-7f4ee9232fcc"
/>


after : 

<img width="1677" height="690" alt="Screenshot 2026-08-26 015248"
src="https://github.com/user-attachments/assets/c922909e-c70b-49f0-88fd-5a0c7cbe574b"
/>

---

Release Notes:

- Windows: Fixed artifacts around color emoji glyphs
2026-08-26 07:49:12 +00:00
John Tur 8a6aaa73ef 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
2026-08-24 02:59:15 +00:00
Neel 255880598d Switch from cargo-machete to cargo-shear (#62643)
This results in ~110 crates being removed, and some orphaned files also.

---

Release Notes:

- N/A

Signed-off-by: Neel <neel@zed.dev>
2026-08-20 10:08:48 +00:00
Kevin BravoandTom Houlé d7f85eed4e 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>
2026-08-19 14:32:19 +00:00
John Tur ec5ddcf55e Tweak renderer resource management (#62069)
Factoring some changes out of
https://github.com/zed-industries/zed/pull/61461:
- On Metal and wgpu, bulk-upload instance buffers at the start of the
frame rather than uploading chunks as we draw them. The depth buffer
patch needs this architecture since all opaque quads in the scene are
painted before anything else. This also lets us get rid of the awkward
retry loop when the GPU buffer is too small for the scene.
- On Windows, use a constant buffer for the instance offset rather than
creating SRVs with different `FirstElement`s. `FirstElement` is buggy on
some vendors' drivers, and reusing the SRV object should reduce D3D
runtime overhead.
- Misc. refactoring: remove redundant parameters, deduplicate code,
create fewer bind groups on wgpu, etc.

Fixes https://github.com/zed-industries/zed/issues/49588
Fixes https://github.com/zed-industries/zed/issues/59192

Release Notes:

- Fixed an issue where UI elements would flicker on some Windows
devices.
2026-08-03 14:37:21 +00:00
roboinandJohn Tur 94cb83400b gpui_windows: Align inactive GPUI popup behavior on Windows with other platforms (#61411)
*As an LLM was used to translate the PR message, the original text is
included alongside the translation in accordance with the contributing
guidelines.

# Objective

> On Windows, GPUI accepted `WindowKind::PopUp` and `focus: false`, but
the window creation path ignored both options. This caused two problems
with the notification popup shown when an agent finished its work:
> 
> * When another window had focus, the popup could appear behind it.
> * When Zed had focus, the popup could steal focus.
> 
> This pull request applies `WindowKind::PopUp` and `focus: false` to
windows on Windows, bringing popup behavior in line with other operating
systems.

Windows版GPUIでは、`WindowKind::PopUp`と`focus:
false`を指定しても、それらのオプションが実際のウィンドウ生成処理では無視されていました。そのため、エージェントの作業が完了したときに表示される通知で次のような問題が発生していました。

- ほかのウィンドウにフォーカスがある場合にポップアップがほかのウィンドウの背後に隠れてしまう
- Zedにフォーカスがある場合はポップアップがフォーカスを奪ってしまう

このプルリクエストでは、Windows上でも`WindowKind::PopUp`と`focus:
false`をウィンドウに反映させるようにし、ポップアップの挙動をほかのOSと一致させます。

## Solution

> This PR updates popup creation in GPUI on Windows to match the
behavior on other platforms. When you specify `WindowKind::PopUp` and
`focus: false`, GPUI now keeps the popup above other windows without
stealing focus.
> 
> Keeping a `focus: false` popup above other windows caused the IME to
commit text under composition when the popup appeared. This PR also
fixes that issue.


Windows版GPUIのポップアップの生成処理をほかのプラットフォームの挙動と一致するように変更しました。このPRでは、`WindowKind::PopUp`と`focus:
false`を指定したときにポップアップウィンドウを最前面に表示し、フォーカスを奪わないようにしました。

また、`focus:
false`のポップアップが最前面に表示されるようにしたことで、ポップアップが表示されたときにIMEで入力中のテキストが意図せず確定されるようになってしまったため、それに対する修正も含まれています。

## Testing

> I built Zed on Windows and displayed a test agent notification to
verify the following:
> 
> * The popup stays above other windows when another window has focus.
> * When Zed has focus, a popup with `focus: false` does not steal focus
or interrupt IME input.
> * The buttons in the popup remain clickable.

Windows上でZedをビルドし、テスト用のエージェント通知を表示して次の項目をテストしました。

- ほかのウィンドウにフォーカスがある場合でもポップアップが最前面に表示される
- Zedにフォーカスがある場合に`focus: false`のポップアップがフォーカスを奪わず、IMEを使った入力も阻害しない
- ポップアップ内のボタンをクリックできる

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

## Showcase

> Note: I added a button to display an agent notification for testing in
this video, but this PR does not include that button.

※この動画ではテスト目的でエージェント通知を表示するボタンを追加していますが、このPRの変更には含まれていません。

### Before

The popup window is hidden when another window has focus:


https://github.com/user-attachments/assets/5312729b-1409-4c81-a169-dd031099059b

A popup with `focus: false` steals focus:


https://github.com/user-attachments/assets/dd1ac2a2-d5e8-4f8f-bc47-6cc659a10951

### After

The popup window stays on top even when another window has focus:


https://github.com/user-attachments/assets/af058921-14fc-4ca5-9698-758202c4c888

A popup with `focus: false` does not steal focus or interrupt text
input:


https://github.com/user-attachments/assets/9bc487c6-ae68-4ec0-9073-1257b91e06a9

---

Release Notes:

- Fixed Windows agent notifications appearing behind other windows,
stealing input focus, or committing active IME composition.

---------

Co-authored-by: John Tur <john-tur@outlook.com>
2026-07-25 20:38:42 +00:00
John Tur 907dd1f442 gpui_windows: Only flash the window once on request_attention (#61611)
The current behavior bothers me.

Release Notes:

- N/A
2026-07-24 21:44:30 +00:00
Richard Feldman 396cdc37c1 gpui: Defer element arena clears while an enclosing draw is in progress (#60295)
GPUI allocates every element for a draw in a single per-App bump arena,
and `Arena::clear()` assumed no draw was in progress. But draws can
nest: on Windows, the window procedure re-enters whenever the main
thread pumps messages mid-draw (cross-thread `SendMessage` dispatch,
modal message loops entered by COM/OLE calls such as clipboard reads),
and on any platform a draw can be triggered from within another draw
(e.g. `open_window`). When a nested draw finished, its arena clear freed
and rewound memory the outer draw was still using. The `ArenaBox`
validity flag only guards new derefs, so `&mut` references already held
by the outer draw silently pointed into reused memory. That
use-after-free corrupted element-state keys
(`GlobalElementId`/`SharedString` Arcs) and heap metadata, crashing
later in innocent-looking frames — seen in the wild as
`EXCEPTION_ACCESS_VIOLATION_READ / 0xffffffffffffffff` in
`Frame::finish` and element allocation
([ZED-9QN](https://zed-dev.sentry.io/issues/7577818040/),
[ZED-7JC](https://sentry.io/organizations/zed-dev/issues/7465778926/),
[ZED-7C6](https://zed-dev.sentry.io/issues/7460258444/)), plus
occasional "attempted to dereference an ArenaRef after its Arena was
cleared" panics (ZED-96P, ZED-8XN), Windows-dominant and spanning
versions 1.1.7–1.8.2.

The fix makes the arena sound under nesting: `ElementArenaScope` tracks
a scope depth on the arena, and `Arena::clear()` is deferred while any
scope is active — the outermost draw's clear drops both draws'
allocations. Since arena chunks are stable heap blocks and allocation
only appends, nested allocation was already safe; the mid-draw clear was
the only destructive operation. Scopes are ended via a consuming
`exit(arena)` call that asserts arena identity (by pointer comparison,
never dereferencing), and `ArenaClearNeeded::clear(cx)` reaches the
arena through the App, so this bookkeeping contains no unsafe code
beyond what existed before. A panic that unwinds a draw balances the
scope depth in the guard's `Drop`, so later clears still run; only the
unwound draw's own clear token is never produced, leaving the arena
populated until the next draw's clear — a one-frame leak at worst, never
a use-after-free.

Additionally, draws are no longer run re-entrantly: GPUI's
`on_request_frame` callback skips requests that arrive while a draw is
already on the thread's stack (remembering `force_render` for the next
frame), and on Windows a `DrawCoordinator` owned by the platform and
shared with every window additionally guards the wider `draw_window`
span (presentation, IME updates). Deferred windows validate their update
region (so nested message pumps don't busy-loop on WM_PAINT) and are
repainted at most one vsync later by the vsync thread's existing
per-tick invalidation.

An integration test opens a window from within an element's paint;
without the deferred clear it reproduces the exact "ArenaRef after its
Arena was cleared" panic seen in the wild. Deferrals are logged so the
diagnosis can be confirmed from user logs.

Closes FR-110

Closes FR-114

Release Notes:

- Fixed a crash on Windows caused by re-entrant window drawing
corrupting UI element memory.
2026-07-22 15:25:22 +00:00
tidely 484ae39d7c zed: Unify dependencies (#61381)
# Objective

Unify dependencies inside of the root `Cargo.toml` to prevent versions
from going out of sync and creating copies of dependencies.

## Testing

- All tests pass, nothing touches the `Cargo.lock`

## Review

Review is easiest by going through commit by commit.

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-07-21 07:58:16 +00:00
John Tur 4feae499a6 Reduce overdraw for border-only quads (#61274)
Restore an optimization that I mistakenly removed in
https://github.com/zed-industries/zed/pull/54728.

Drawing a quad with a border but no fill color will run the quad
fragment shader for every transparent interior pixel, which is
especially costly when the quad is large. Instead, split these quads
into four non-overlapping strips that cover the regions where borders
are painted. The side strips own the straight left and right edges,
while the top and bottom strips own the horizontal edges and the rounded
corners.

Previously, this optimization only applied to borders drawn by the Taffy
layout. I've decided to reinstate the logic directly in `paint_quad` so
that the optimization can be applied more generally... though if this
feels like too much policy, we can move it back.

This reduces the GPU time spent painting a representative Zed scene by
about 20% or so.

Release Notes:

- N/A
2026-07-19 06:52:53 +00:00
John Tur 2e405c7c7a gpui: Remove ExitProcess shutdown workaround (#61219)
The issue with aws-lc that necessitated this workaround has been fixed
upstream: https://github.com/aws/aws-lc/issues/3197.

Release Notes:

- N/A
2026-07-17 19:16:49 +00:00
Lukas WirthandJohn Tur cd91c84675 gpui: Add system notification platform APIs (#61189)
Release Notes:

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

---------

Co-authored-by: John Tur <john-tur@outlook.com>
2026-07-17 18:52:23 +00:00
tidely 9948409b40 gpui: Unify raw-window-handle dependency (#61193)
Just something I noticed while skimming through dependencies

Release Notes:

- N/A or Added/Fixed/Improved ...
2026-07-17 13:41:05 +00:00
John Tur dd5f651227 Use more efficient thread pool API on Windows (#60917)
This interface uses fewer syscalls and has less internal synchronization
(since the `TP_WORK` object is not exposed).

Release Notes:

- N/A
2026-07-14 16:40:22 +00:00
Lukas Wirthandzed-zippy[bot] a932df5550 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>
2026-07-13 11:03:51 +00:00
Richard Feldman 5e66b2a57c gpui_windows: Harden DirectWrite and DirectX text rendering (#60124)
This hardens the Windows text rendering path in gpui_windows against
undefined behavior and out-of-bounds access. DirectWrite hands back
glyph-run arrays (glyph indices, advances, offsets) and cluster maps as
raw pointers that may be null; these are now interpreted through a
shared `slice_from_nullable` helper that treats a null pointer with zero
length as an empty slice and returns `E_INVALIDARG` when a null pointer
arrives with a nonzero length, instead of constructing a slice from a
null pointer. It also fixes a provenance bug: the renderer context
passed to `IDWriteTextLayout::Draw` was derived via `&raw const` from a
non-mut binding, but the `DrawGlyphRun` callback recovers that pointer
and writes through it, which is undefined behavior under Stacked/Tree
Borrows; the binding is now `mut` and the pointer is derived from `&raw
mut` so its provenance matches the write (codegen is unchanged).

On the DirectX side, the atlas upload is now bounded by the source slice
length so a mismatched destination region cannot read past the end of
the source, and the color-glyph staging texture is unmapped after
readback so the mapping is no longer leaked and the resource pinned. The
color-glyph rasterizer drives the shared, non-thread-safe D3D11
immediate context that `DirectXRenderer` and `DirectXAtlas` also use, so
it must stay on the main UI thread — which it always is today; a comment
documents that invariant.

Since gpui_windows is a Windows-only crate, it cannot be compiled on
non-Windows hosts, so Windows CI is the compile gate for these changes.

Release Notes:

- N/A
2026-07-13 09:54:38 +00:00
John Tur 756116c2b0 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
2026-07-09 18:06:00 +00:00
Richard Feldman 711e286c7f gpui: Store GPU-facing bools as PaddedBool32 to avoid uninitialized padding (#60482)
`PolychromeSprite` in `crates/gpui/src/scene.rs` is `#[repr(C)]` and had
a `grayscale: bool` field followed by 3 compiler-inserted padding bytes
that were never written. The wgpu renderer's `instance_bytes`
reinterprets `&[PolychromeSprite]` as `&[u8]` via
`slice::from_raw_parts` and passes it to `queue.write_buffer`, so those
uninitialized padding bytes were exposed behind a shared `&[u8]` on
every frame that draws an image or emoji, which is undefined behavior.

Rather than widening the field to a raw `u32` (which would suggest
values other than 0 and 1 are meaningful), this introduces
`PaddedBool32`: a `#[repr(transparent)]` wrapper around `u32` whose only
public constructor is `From<bool>`, so the 0-or-1 invariant is enforced
by the type while the layout has no padding. `Underline.wavy`, which was
already a raw `u32` for the same reason, is converted too.

cbindgen emits the wrapper as `typedef uint32_t PaddedBool32;`, so the
generated Metal header and shaders are unchanged. The WGSL and HLSL
shaders already declared these fields as `u32`/`uint`; their `& 0xFFu`
masks, which existed to ignore the garbage padding bytes, are now
simplified to plain comparisons.

Release Notes:

- N/A
2026-07-09 05:37:35 +00:00
Richard Feldman ae61c133f1 gpui_windows: Check composition attribute lookup (#60122)
Checks that SetWindowCompositionAttribute was found before transmuting
and calling the function pointer, making the composition setup a no-op
when the undocumented export is unavailable.

Release Notes:

- N/A
2026-07-08 19:27:01 +00:00
Philipp Schaffrath 636e764737 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
2026-07-08 19:22:23 +00:00
迷渡 0514cad371 Fix disabled Windows window controls (#60440)
## Summary

- Store Windows window minimizable and resizable capabilities on
`WindowsWindowInner`.
- Prevent custom titlebar hit testing from returning minimize/maximize
button hit targets when the corresponding capability is disabled.
- Swallow disabled native non-client minimize/maximize button mouse
events so they cannot fall through to the default window procedure or
GPUI's manual `ShowWindowAsync` handling.

Fixes #52067.

## Validation

- `cargo fmt --package gpui_windows`
- `cargo check -p gpui_windows`
- `git diff --check`

Release Notes:

- Fixed disabled minimize and maximize window controls still activating
on Windows.
2026-07-07 09:01:58 +00:00
ArtinandSmit Barmase 03d11509fa Reduce OAuth scope to avoid Windows credential size limit (#58541)
I encountered an issue where I couldn't sign in to ChatGPT Subscription
on Windows:

```
ChatGPT subscription sign-in failed to persist credentials: 
Failed to write credentials to Windows Credential Manager: 
占位程序接收到错误数据。 (0x800706F7)
```

Interestingly, only one of my three ChatGPT accounts had this problem —
the other two signed in successfully.

## What I Found

After investigating, I noticed that the OAuth scope in
`openai_subscribed.rs` requests 6 permissions:

```
openid profile email offline_access api.connectors.read api.connectors.invoke
```

I wrote a test script to measure token sizes and found that:
- With 6 scopes: my problematic account's token was **2578 bytes**
- With 4 scopes (removing `api.connectors.read` and
`api.connectors.invoke`): the same token was **2516 bytes**

Since Windows Credential Manager has a 2560-byte limit
(`CRED_MAX_CREDENTIAL_BLOB_SIZE`), this could explain why some accounts
fail while others succeed — it depends on the base token size.

## My Hypothesis

The issue seems to be that:
- Error code `0x800706F7` = `RPC_X_BAD_STUB_DATA` (size limit, not
format)
- Accounts with larger base tokens exceed the limit when the extra 48
chars are added
- Accounts with smaller base tokens still fit, which is why this isn't
universally reproducible

I'm not 100% certain this is the root cause, but the evidence seems to
point in this direction.

## Proposed Fix

I removed `api.connectors.read` and `api.connectors.invoke` from the
OAuth scope, since:
- These scopes don't appear to be used by Zed's current ChatGPT
integration
- OpenCode (another tool using the same OAuth provider) successfully
uses only 4 scopes
- This fix allowed my problematic account to sign in

However, I'd like to ask the maintainers:
- Are there plans to use OpenAI Connectors API in the future?
- Are there security or compliance reasons for requesting these extra
scopes?

If the answer is yes to either, we'd need a different approach (e.g.,
splitting credentials, using encrypted file storage, or checking token
size before storage).

## Testing

- [x] Verified my problematic account now signs in successfully
- [x] Verified my other accounts still work
- [x] Ran `cargo check -p language_models` (compilation successful)
- [ ] Would appreciate help testing on macOS/Linux

## Questions

1. Does this analysis make sense?
2. Are there any other considerations I'm missing?
3. Would it be helpful to add a size check with a clearer error message
for future cases?

I'm happy to adjust this approach based on your feedback.

Release Notes:

- Fixed ChatGPT Subscription sign-in failing on Windows for some
accounts by removing unused OAuth scopes (`api.connectors.read`,
`api.connectors.invoke`) that pushed JWT tokens over Windows Credential
Manager's limit.

---------

Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
2026-07-03 19:38:42 +00:00
Agus Zubiaga e85a546880 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
2026-06-24 19:59:34 +00:00
Lukas Wirth 2428be3d1f gpui_windows: Fix immovable windows skipping hit testing entirely (#59816)
Prior to this, marking a window as immovable would prevent the title bar
buttons working on windows.

Release Notes:

- N/A
2026-06-24 16:31:35 +00:00
Cole Miller 8aca6b1eda Remove gpui's dependency on async-process (#59358)
This removes gpui's dependency on the `util` crate, which depends on
async process. It now depends on `gpui_util` only, and uses
`std::process::Command` for the two cases where it was previously using
an async `Command`. This lifts the requirement of non-Zed consumers of
gpui to depend on our forked async-process (see #59156).

Release Notes:

- N/A
2026-06-16 13:47:55 +00:00
Konstantinos St ba93284c6a Fix miscellaneous typos (#58979)
Some typos I found while reading the code

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Release Notes:

- N/A
2026-06-09 22:46:22 +00:00
Anthony Eid cc84a7bdd6 gpui: Free atlas tile space when removing tiles (#58874)
Partially addresses #54659

`PlatformAtlas::remove` removed the tile from `tiles_by_key` and
decremented the texture's refcount, but never returned the tile's
rectangle to the etagere allocator. Removed tiles' space could only be
reclaimed if the entire texture was dropped, which doesn't happen if
glyph/emoji share the texture. Because we don't have correct glyph/emoji
removal

I added regression tests on all three platforms to prevent this from
occurring as well.

Note: this doesn't fix glyph eviction or the nil-texture panic from
#54659; those are follow ups.

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

Closes #ISSUE

Release Notes:

- gpui: Fix GPUI memory growing unboundedly when images are repeatedly
loaded and released
2026-06-08 23:09:47 +00:00
Yara 🏳️‍⚧️ a0d71a483a Log worst hanging tasks and actions (#57835)
We have a lot of long blocking tasks on both the foreground and
background, this is a start of getting some insight into those.

We will now log tasks running longer then 100ms on the foreground or
background. Hanging actions will also be logged including their name. We
simultaneously collect statistics on task and action performance and
send those to telemetry. This includes quantiles and averages for each
hanging task.

Finally this adds tree dev actions: 
- hang action
- hang foreground
- hang background

These cause a hang to check if hang reporting is working and in the
future telemetry.

Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

Closes #ISSUE

Release Notes:

- Added logging and telemetry of tasks and actions with performance
issues
2026-06-02 12:03:05 +00:00
761fda75cd gpui: Accesskit support (#56065)
GPUI AccessKit integration

This PR is replacing #51097 , and is much more limited in scope. This PR
*ONLY* adds AccessKit support to GPUI, and doesn't touch Zed. Once this
lands, we can start adding aria attributes to Zed's components.

This PR is the first step to addressing #41138 .

Release Notes:

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

---------

Co-authored-by: John Tur <john-tur@outlook.com>
Co-authored-by: Zed Zippy <234243425+zed-zippy[bot]@users.noreply.github.com>
Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
Co-authored-by: Agus Zubiaga <agus@zed.dev>
2026-05-27 18:17:59 +00:00
Danilo LealandAgus Zubiaga d7b27f9ead gpui: Add support for inset shadow (#57685)
This PR adds support for inset shadows in the box shadow through the
`inset: true` field. It includes support for both the macOS as well WGSL
shaders. For now, there is no immediate application of it in Zed, so
nothing should change in the app.

<img width="600" alt="Screenshot 2026-05-25 at 8  46@2x"
src="https://github.com/user-attachments/assets/db564a6b-8af5-491a-a573-17c060a3647c"
/>

Run the example above with `cargo run --example shadow -p gpui`.

Release Notes:

- N/A

---------

Co-authored-by: Agus Zubiaga <agus@zed.dev>
2026-05-26 14:32:45 +00:00
Lukas WirthandZed Zippy c0390c1ca0 gpui_windows: Avoid process-wide priority elevation (#56050)
We were incorrectly calling this with a thread handle, additionally
changing the process priority here doesn't make sense, so just drop
this.

Release Notes:

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

---------

Co-authored-by: Zed Zippy <234243425+zed-zippy[bot]@users.noreply.github.com>
2026-05-07 14:09:39 +00:00
Ben Brandt d4d6abd439 Fix DirectX atlas panic after GPU device recovery (#55878)
## Problem

A Sentry-reported crash on Windows (Intel Iris Xe Graphics, v1.0.1):

```
index out of bounds: the len is 1 but the index is 1
```

panicking at `DirectXAtlasState::texture` in

[`crates/gpui_windows/src/directx_atlas.rs`](https://github.com/zed-industries/zed/blob/main/crates/gpui_windows/src/directx_atlas.rs):

```rust
AtlasTextureKind::Subpixel => {
    &self.subpixel_textures[id.index as usize].as_ref().unwrap()
}
```

## Root cause

After a GPU device-lost recovery, GPUI's view cache replays stale
`AtlasTile`
references from the previous frame's `paint_operations` via
`Scene::replay`.

1. **Atlas grows past one texture.** A long enough session pushes
`subpixel_textures.textures.len() ≥ 2` (easy on Iris Xe at the default
1024×1024 atlas size). Top-level views in Zed use `cached(...)`, so
their
`AnyViewState.paint_range` records into
`rendered_frame.scene.paint_operations`,
   referencing both index `0` and index `1`.
2. **Device lost.** `handle_device_lost` clears every `AtlasTextureList`
(`textures.len() == 0`)
   and `tiles_by_key`, then sets `skip_draws = true`.
3. **`WM_GPUI_FORCE_UPDATE_WINDOW` arrives.** `mark_drawable()` flips
`skip_draws` back to `false` and `request_frame` runs with
`force_render: true`.
4. **The cache hit.** Inside `Window::draw`, `AnyView::prepaint`'s cache
check (`!dirty_views.contains(...) && !window.refreshing`) succeeds for
every cached view because the recovery doesn't touch invalidator state
and
`force_render` doesn't propagate into `Window`. `AnyView::paint` calls
`window.reuse_paint` → `Scene::replay` → `primitive.clone()`, which
(since
   `SubpixelSprite`/`AtlasTile` are `Copy`) verbatim copies a
`Primitive::SubpixelSprite { tile: { texture_id: { index: 1, ... }, ...
} }`
   into `next_frame.scene`.
5. **Atlas regrows to one.** Dirty/uncached parts of the same frame
   (caret, animations, anything that called `cx.notify`) fall through to
   `paint_glyph` → `get_or_insert_with` → `push_texture`, growing
`subpixel_textures.textures` from `0` to **`1`** with index `0` valid.
6. **Panic.** After `mem::swap`, `rendered_frame.scene` contains a mix
of
   fresh `index = 0` and replayed `index = 1` sprites. `Scene::batches`
emits separate batches per `texture_id`; the `index = 1` batch reaches
   `atlas.get_texture_view` → `subpixel_textures[1]` → panic with
   `len = 1, index = 1`.

The two earlier related fixes do not catch this:

- **#52389 / c8f20c78** (`if force_render { mark_drawable }`) protects
the
200 ms recovery sleep — pending `WM_PAINT`s carry `force_render = false`
  and so do not clear `skip_draws`. But `WM_GPUI_FORCE_UPDATE_WINDOW`
  carries `force_render = true`, so `mark_drawable` runs, then
  `Window::draw`'s `reuse_paint` still reproduces stale tiles.
- The unmerged Windows draft `2e5d890e37`
(`force_render_after_recovery`)
  similarly only forces the forced-render branch — it doesn't bypass the
  view cache.

## Fix

Two parts:

**1. Bypass the view cache on a forced draw (cross-platform).**

In the platform-agnostic `request_frame` closure in `Window::new`, call
`window.refresh()` whenever `RequestFrameOptions::force_render` is
`true`.
`Window::refresh` is the documented escape hatch for cached views (per
the
`AnyView::cached` docs: *"The one exception is when [Window::refresh] is
called, in which case caching is ignored."*). With `refreshing = true`
every `AnyView::prepaint` cache check fails, every cached view fully
repaints, and `paint_glyph` allocates fresh tiles for every glyph, so
`rendered_frame.scene` ends up free of stale `AtlasTile`s.

**2. Add the `force_render_after_recovery` flag on Windows.**

Mirror the Linux fix from #52389: a per-window `Cell<bool>` set after
`WindowsWindowInner::handle_device_lost` succeeds and consumed at the
top
of `draw_window`. Together with the GPUI change above, the first frame
after recovery (whether a stray `WM_PAINT` during the 200 ms recovery
sleep or the explicit `WM_GPUI_FORCE_UPDATE_WINDOW`) is treated as a
forced render that both clears `skip_draws` and bypasses the view cache.

## Testing

- `script/clippy -p gpui` is clean.
- I do not have a Windows toolchain available locally, so I have not
  cross-compiled `gpui_windows`. Reviewers with Windows access — please
  smoke-test on a machine where the device-lost path can be exercised
  (Intel iGPU, suspend/resume, or running a TDR-inducing test on a GPU
  driver).

## Related

- Sentry issue ID 7457971403 (DirectX subpixel atlas crash, Intel Iris
Xe).
- Builds on / fixes the residual gap in #52389 (`gpui_linux: Force scene
  rebuild after GPU device recovery"). The GPUI change here also hardens
  the corresponding Linux path against the same `reuse_paint` mechanism.

Release Notes:

- Fixed a crash on Windows when the GPU device is lost and recovered
during use (typically driver crash, suspend/resume, or display
reconfiguration, most commonly on Intel iGPUs)
2026-05-07 10:22:52 +00:00
Lukas WirthandJohn Tur 156a47d0d0 gpui(windows): Fix unwrap panic when monitor goes missing (#55630)
Fixes ZED-5K1

Release Notes:

- Fixed a panic on windows when a monitor disappears from windows
monitor enumeration

---------

Co-authored-by: John Tur <john-tur@outlook.com>
2026-05-06 07:35:40 +00:00
Agus Zubiaga ba6d258b0f Handle hiding cursor on keyboard input at GPUI level (#55664)
Instead of manually handing hiding the cursor on keyboard input at the
editor level, GPUI will now take care of it.

This makes it significantly easier to handle the edge cases, and allows
delegating the cursor restoration to the platform itself in the macOS
case. On Linux and Windows, we still have to restore the cursor on
movement ourselves, but this now happens at the platform-specific level.

Bugs fixed by this change:
- No cursor when "Unsaved edits" prompt appears
- Cursor disappears when clicking a panel button if it contains a search
bar (e.g. collab panel)

### Setting rename

The `hide_mouse` setting value `"on_typing_and_movement"` has been
renamed to `"on_typing_and_action"` to better reflect what it actually
does — it hides the cursor when a keystroke resolves to an action (e.g.
cursor movement, deletion). Existing settings are migrated
automatically.

### Tested platforms
- [x] macOS
- [x] Wayland
- [x] X11
- [x] Windows
- [x] Web

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
- [x] Performance impact has been considered and is acceptable

Release Notes:

- Renamed the `hide_mouse` setting value `on_typing_and_movement` to
`on_typing_and_action` to better describe its behavior (existing
settings are auto-migrated)
- Fixed a few situations where the mouse cursor would be incorrectly
hidden
2026-05-04 22:51:56 +00:00
John Tur f01d6816cb Support BGR subpixel layout (#55174)
Release Notes:

- Added text rendering support for BGR subpixel layouts.
2026-04-29 12:26:19 +00:00
John Tur 55adf85aa7 Fix process teardown deadlock on Windows (#55065)
AWS-LC registers an `atexit` handler that intentionally acquires a lock
without releasing it. AWS-LC also has `thread_local` objects which
acquire this lock in their destructor. Destructors for `thread_local`s
run under the loader lock. So, there is a race condition where, if a
thread exits after `atexit` handlers have run, the TLS destructors will
block indefinitely on this lock while holding the loader lock. Since
`ExitProcess` also requires the loader lock, process teardown will
deadlock.


Closes #54856

Release Notes:

- Fixed an issue where the Zed process wouldn't exit after closing all
windows
2026-04-28 08:19:03 +00:00
John Tur 18a1c1c36a Fix broken is_maximized check on Windows (#54436)
Bad change from https://github.com/zed-industries/zed/pull/54321

Fixes https://github.com/zed-industries/zed/issues/54418

Release Notes:

- N/A
2026-04-21 13:35:13 -04:00