Typed window update errors

This commit is contained in:
Lukas Wirth 2026-05-12 10:11:50 +02:00
parent 7d3989602d
commit 740af9f156
9 changed files with 97 additions and 48 deletions

View file

@ -126,6 +126,29 @@ impl Drop for AppRef<'_> {
#[derive(Deref, DerefMut)]
pub struct AppRefMut<'a>(RefMut<'a, App>);
/// An error returned when updating a window fails.
#[derive(Debug, thiserror::Error)]
pub enum UpdateWindowError {
/// The application was released before the window update could run.
#[error("app was released")]
AppReleased,
/// The application is already mutably borrowed.
#[error("app is already borrowed")]
AppAlreadyBorrowed,
/// The application is quitting and cannot update windows.
#[error("app is quitting")]
AppQuitting,
/// The window was not found.
#[error("window not found")]
WindowNotFound,
/// The window is already being updated.
#[error("window is already being updated")]
WindowAlreadyUpdating,
}
/// The result type for updating a window.
pub type UpdateWindowResult<T> = std::result::Result<T, UpdateWindowError>;
impl Drop for AppRefMut<'_> {
fn drop(&mut self) {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
@ -1072,8 +1095,8 @@ impl App {
(
TypeId::of::<Evt>(),
Box::new(move |event, cx| {
let event: &Evt = event.downcast_ref().expect("invalid event type");
if let Some(entity) = handle.upgrade() {
let event: &Evt = event.downcast_ref().expect("invalid event type");
on_event(entity, event, cx)
} else {
false
@ -1621,18 +1644,28 @@ impl App {
.or_insert(window);
}
pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
pub(crate) fn update_window_id<T, F>(
&mut self,
id: WindowId,
update: F,
) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
self.update(|cx| {
let mut window = cx.windows.get_mut(id)?.take()?;
let window_slot = cx
.windows
.get_mut(id)
.ok_or(UpdateWindowError::WindowNotFound)?;
let mut window = window_slot
.take()
.ok_or(UpdateWindowError::WindowAlreadyUpdating)?;
let root_view = window.root.clone().unwrap();
cx.window_update_stack.push(window.handle.id);
let result = update(root_view, &mut window, cx);
fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
fn trail(id: WindowId, window: Box<Window>, cx: &mut App) -> UpdateWindowResult<()> {
cx.window_update_stack.pop();
if window.removed {
@ -1666,15 +1699,17 @@ impl App {
cx.quit();
}
} else {
cx.windows.get_mut(id)?.replace(window);
cx.windows
.get_mut(id)
.ok_or(UpdateWindowError::WindowNotFound)?
.replace(window);
}
Some(())
Ok(())
}
trail(id, window, cx)?;
Some(result)
Ok(result)
})
.context("window not found")
}
/// Creates an `AsyncApp`, which can be cloned and has a static lifetime
@ -2210,6 +2245,7 @@ impl App {
.update(self, |_, window, cx| {
window.dispatch_action(action.boxed_clone(), cx)
})
.context("Failed to dispatch action to active window")
.log_err();
} else {
self.dispatch_global_action(action);
@ -2515,7 +2551,7 @@ impl AppContext for App {
read(entity, self)
}
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{

View file

@ -1,8 +1,8 @@
use crate::{
AnyView, AnyWindowHandle, App, AppCell, AppContext, BackgroundExecutor, BorrowAppContext,
Entity, EntityId, EventEmitter, Focusable, ForegroundExecutor, Global, GpuiBorrow,
PromptButton, PromptLevel, Render, Reservation, Result, Subscription, Task, VisualContext,
Window, WindowHandle,
PromptButton, PromptLevel, Render, Reservation, Result, Subscription, Task, UpdateWindowError,
UpdateWindowResult, VisualContext, Window, WindowHandle,
};
use anyhow::{Context as _, bail};
use derive_more::{Deref, DerefMut};
@ -82,14 +82,16 @@ impl AppContext for AsyncApp {
lock.read_entity(handle, callback)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
let app = self.app.upgrade().context("app was released")?;
let mut lock = app.try_borrow_mut()?;
let app = self.app.upgrade().ok_or(UpdateWindowError::AppReleased)?;
let mut lock = app
.try_borrow_mut()
.map_err(|_| UpdateWindowError::AppAlreadyBorrowed)?;
if lock.quitting {
bail!("app is quitting");
return Err(UpdateWindowError::AppQuitting);
}
lock.update_window(window, f)
}
@ -297,8 +299,9 @@ impl AsyncWindowContext {
/// A convenience method for [`App::update_window`].
pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
self.app
.update_window(self.window, |_, window, cx| update(window, cx))
Ok(self
.app
.update_window(self.window, |_, window, cx| update(window, cx))?)
}
/// A convenience method for [`App::update_window`].
@ -306,7 +309,7 @@ impl AsyncWindowContext {
&mut self,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R> {
self.app.update_window(self.window, update)
Ok(self.app.update_window(self.window, update)?)
}
/// A convenience method for [`Window::on_next_frame`].
@ -321,8 +324,9 @@ impl AsyncWindowContext {
&mut self,
read: impl FnOnce(&G, &Window, &App) -> R,
) -> Result<R> {
self.app
.update_window(self.window, |_, window, cx| read(cx.global(), window, cx))
Ok(self
.app
.update_window(self.window, |_, window, cx| read(cx.global(), window, cx))?)
}
/// A convenience method for [`App::update_global`](BorrowAppContext::update_global).
@ -334,9 +338,9 @@ impl AsyncWindowContext {
where
G: Global,
{
self.app.update_window(self.window, |_, window, cx| {
Ok(self.app.update_window(self.window, |_, window, cx| {
cx.update_global(|global, cx| update(global, window, cx))
})
})?)
}
/// Schedule a future to be executed on the main thread. This is used for collecting
@ -424,7 +428,7 @@ impl AppContext for AsyncWindowContext {
self.app.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
@ -477,9 +481,9 @@ impl VisualContext for AsyncWindowContext {
&mut self,
build_entity: impl FnOnce(&mut Window, &mut Context<T>) -> T,
) -> Result<Entity<T>> {
self.app.update_window(self.window, |_, window, cx| {
Ok(self.app.update_window(self.window, |_, window, cx| {
cx.new(|cx| build_entity(window, cx))
})
})?)
}
fn update_window_entity<T: 'static, R>(
@ -502,17 +506,17 @@ impl VisualContext for AsyncWindowContext {
where
V: 'static + Render,
{
self.app.update_window(self.window, |_, window, cx| {
Ok(self.app.update_window(self.window, |_, window, cx| {
window.replace_root(cx, build_view)
})
})?)
}
fn focus<V>(&mut self, view: &Entity<V>) -> Result<()>
where
V: Focusable,
{
self.app.update_window(self.window, |_, window, cx| {
Ok(self.app.update_window(self.window, |_, window, cx| {
view.read(cx).focus_handle(cx).focus(window, cx);
})
})?)
}
}

View file

@ -1,7 +1,8 @@
use crate::{
AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,
FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
SubscriberSet, Subscription, Task, UpdateWindowResult, WeakEntity, WeakFocusHandle, Window,
WindowHandle,
};
use anyhow::Result;
use futures::FutureExt;
@ -825,7 +826,7 @@ impl<T> AppContext for Context<'_, T> {
}
#[inline]
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> UpdateWindowResult<R>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> R,
{

View file

@ -12,7 +12,7 @@ use crate::{
AnyView, AnyWindowHandle, App, AppCell, AppContext, AssetSource, BackgroundExecutor, Bounds,
Context, Entity, EntityId, ForegroundExecutor, Global, Pixels, PlatformHeadlessRenderer,
PlatformTextSystem, Render, Reservation, Size, Task, TestDispatcher, TestPlatform, TextSystem,
Window, WindowBounds, WindowHandle, WindowOptions,
UpdateWindowResult, Window, WindowBounds, WindowHandle, WindowOptions,
app::{GpuiBorrow, GpuiMode},
};
use anyhow::Result;
@ -156,7 +156,7 @@ impl HeadlessAppContext {
&mut self,
window: AnyWindowHandle,
f: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R> {
) -> UpdateWindowResult<R> {
let mut app = self.app.borrow_mut();
app.update_window(window, f)
}
@ -238,7 +238,7 @@ impl AppContext for HeadlessAppContext {
app.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{

View file

@ -4,8 +4,8 @@ use crate::{
Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global, InputEvent, Keystroke,
Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
Pixels, Platform, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform,
TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds,
WindowHandle, WindowOptions, app::GpuiMode, window::ElementArenaScope,
TestScreenCaptureSource, TestWindow, TextSystem, UpdateWindowResult, VisualContext, Window,
WindowBounds, WindowHandle, WindowOptions, app::GpuiMode, window::ElementArenaScope,
};
use anyhow::{anyhow, bail};
use futures::{Stream, StreamExt, channel::oneshot};
@ -76,7 +76,7 @@ impl AppContext for TestAppContext {
app.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
@ -989,7 +989,7 @@ impl AppContext for VisualTestContext {
self.cx.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{

View file

@ -2,8 +2,8 @@ use crate::{
Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AssetSource, BackgroundExecutor,
Bounds, ClipboardItem, Context, Entity, EntityId, ForegroundExecutor, Global, InputEvent,
Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
Platform, Point, Render, Result, Size, Task, TestDispatcher, TextSystem, VisualTestPlatform,
Window, WindowBounds, WindowHandle, WindowOptions, app::GpuiMode,
Platform, Point, Render, Result, Size, Task, TestDispatcher, TextSystem, UpdateWindowResult,
VisualTestPlatform, Window, WindowBounds, WindowHandle, WindowOptions, app::GpuiMode,
};
use anyhow::anyhow;
use image::RgbaImage;
@ -173,7 +173,7 @@ impl VisualTestAppContext {
}
/// Updates a window.
pub fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
pub fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
@ -438,7 +438,7 @@ impl AppContext for VisualTestAppContext {
app.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{

View file

@ -167,7 +167,7 @@ pub trait AppContext {
T: 'static;
/// Update a window for the given handle.
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> UpdateWindowResult<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T;

View file

@ -16,9 +16,9 @@ use crate::{
StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, px, rems, size,
transparent_black,
UpdateWindowResult, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls,
WindowDecorations, WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, px, rems,
size, transparent_black,
};
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
@ -1345,6 +1345,7 @@ impl Window {
move |request_frame_options| {
let thermal_state = handle
.update(&mut cx, |_, _, cx| cx.thermal_state())
.context("Failed to get thermal state")
.log_err();
// Throttle frame rate based on conditions:
@ -1374,6 +1375,7 @@ impl Window {
// `complete_frame`) or the compositor won't send another callback.
handle
.update(&mut cx, |_, window, _| window.complete_frame())
.context("Failed to complete frame")
.log_err();
return;
}
@ -1388,6 +1390,7 @@ impl Window {
callback(window, cx);
}
})
.context("Failed to execute next frame callbacks")
.log_err();
}
@ -1411,11 +1414,13 @@ impl Window {
window.present();
arena_clear_needed.clear();
})
.context("Failed to draw and present frame")
.log_err();
})
} else if needs_present {
handle
.update(&mut cx, |_, window, _| window.present())
.context("Failed to present frame")
.log_err();
}
@ -1423,6 +1428,7 @@ impl Window {
.update(&mut cx, |_, window, _| {
window.complete_frame();
})
.context("Failed to complete frame")
.log_err();
}
}));
@ -1886,6 +1892,7 @@ impl Window {
let node_id = window.focus_node_id_in_rendered_frame(focus_id);
window.dispatch_action_on_node(node_id, action.as_ref(), cx);
})
.context("Failed to dispatch action on window")
.log_err();
})
}
@ -4555,6 +4562,7 @@ impl Window {
window.pending_input_changed(cx);
window.replay_pending_input(to_replay, cx)
})
.context("Failed to replay pending input")
.log_err();
}));
} else {
@ -5623,7 +5631,7 @@ impl AnyWindowHandle {
self,
cx: &mut C,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R>
) -> UpdateWindowResult<R>
where
C: AppContext,
{

View file

@ -72,7 +72,7 @@ pub fn derive_app_context(input: TokenStream) -> TokenStream {
self.#app_variable.read_entity(handle, read)
}
fn update_window<T, F>(&mut self, window: gpui::AnyWindowHandle, f: F) -> gpui::Result<T>
fn update_window<T, F>(&mut self, window: gpui::AnyWindowHandle, f: F) -> gpui::UpdateWindowResult<T>
where
F: FnOnce(gpui::AnyView, &mut gpui::Window, &mut gpui::App) -> T,
{