pub struct Context<'a, T> { /* private fields */ }Expand description
A mutable handle to the App that also knows which entity T you are working on.
GPUI passes a Context<T> to every callback that works on an entity. Entity::update
and WeakEntity::update pass one to their closure, and render methods receive one as
their last argument. Because Context<T> dereferences to App, you can use any App
method through it. The methods on Context<T> itself need the entity: Context::notify,
Context::emit, Context::observe, Context::subscribe, Context::listener and
Context::spawn.
Use the context of the entity you’re changing for anything about that entity, and use
&mut App for work that spans the application. See
contexts for when you get each kind of context.
§Examples
struct Clock {
ticks: u64,
}
impl Clock {
fn tick(&mut self, cx: &mut Context<Self>) {
self.ticks += 1;
cx.notify();
}
}
let clock = cx.new(|_cx| Clock { ticks: 0 });
clock.update(cx, |clock, cx| clock.tick(cx));
assert_eq!(clock.read(cx).ticks, 1);Implementations§
Source§impl<'a, T: 'static> Context<'a, T>
impl<'a, T: 'static> Context<'a, T>
Sourcepub fn entity(&self) -> Entity<T>
pub fn entity(&self) -> Entity<T>
Returns a strong handle to the entity this context works on.
The handle keeps the entity alive. Use Context::weak_entity when a callback should not
keep it alive.
Sourcepub fn weak_entity(&self) -> WeakEntity<T>
pub fn weak_entity(&self) -> WeakEntity<T>
Returns a weak handle to the entity this context works on.
Store the weak handle in callbacks and tasks that can outlive the current update. Upgrade it when you need the entity, and handle the case where it has been released.
Sourcepub fn observe<W>(
&mut self,
entity: &Entity<W>,
on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
W: 'static,
pub fn observe<W>(
&mut self,
entity: &Entity<W>,
on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
W: 'static,
Calls on_notify whenever entity calls Context::notify.
Use this to keep one entity in step with another. When entity changes, your callback can
read it and update your own state. The callback receives this entity mutably, a handle to the
observed entity, and a context for this entity. It runs after the update that called notify
finishes. Several notifications before that point deliver the callback once.
The callback stays registered while the returned Subscription is alive. Keep it in a field
so the callback lasts as long as your entity, or call Subscription::detach to keep it for as
long as both entities exist. Once this entity is released, the callback is never called again.
§Examples
struct Counter {
count: usize,
}
struct Label {
text: String,
}
let counter = cx.new(|_cx| Counter { count: 0 });
let label = cx.new(|cx: &mut Context<Label>| {
cx.observe(&counter, |label, counter, cx| {
label.text = counter.read(cx).count.to_string();
})
.detach();
Label { text: String::new() }
});
(counter, label)
counter.update(cx, |counter, cx| {
counter.count = 21;
cx.notify();
});Sourcepub fn observe_self(
&mut self,
on_event: impl FnMut(&mut T, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn observe_self(
&mut self,
on_event: impl FnMut(&mut T, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls on_event whenever this entity calls Context::notify.
It runs after the update that called notify finishes. Keep the returned
Subscription alive for as long as you want the callback to run.
Sourcepub fn subscribe<T2, Evt>(
&mut self,
entity: &Entity<T2>,
on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
T2: 'static + EventEmitter<Evt>,
Evt: 'static,
pub fn subscribe<T2, Evt>(
&mut self,
entity: &Entity<T2>,
on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
T2: 'static + EventEmitter<Evt>,
Evt: 'static,
Calls on_event whenever entity emits an event of type Evt.
The emitting entity must implement EventEmitter<Evt>. Events are
delivered after the update that emitted them finishes, in the order they were emitted. Each event
type needs its own subscription. The callback receives this entity mutably, a handle to the
emitting entity, the event, and a context for this entity.
Keep the returned Subscription in a field, or call Subscription::detach to keep the
callback for as long as both entities exist.
§Examples
struct Downloader;
enum DownloadEvent {
Finished { bytes: usize },
}
impl EventEmitter<DownloadEvent> for Downloader {}
struct StatusBar {
message: String,
}
let downloader = cx.new(|_cx| Downloader);
let status = cx.new(|cx: &mut Context<StatusBar>| {
cx.subscribe(&downloader, |status, _downloader, event: &DownloadEvent, _cx| match event {
DownloadEvent::Finished { bytes } => {
status.message = format!("Downloaded {bytes} bytes");
}
})
.detach();
StatusBar { message: String::new() }
});
(downloader, status)
downloader.update(cx, |_downloader, cx| {
cx.emit(DownloadEvent::Finished { bytes: 512 });
});Sourcepub fn subscribe_self<Evt>(
&mut self,
on_event: impl FnMut(&mut T, &Evt, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static + EventEmitter<Evt>,
Evt: 'static,
pub fn subscribe_self<Evt>(
&mut self,
on_event: impl FnMut(&mut T, &Evt, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static + EventEmitter<Evt>,
Evt: 'static,
Calls on_event whenever this entity emits an event of type Evt.
This is Context::subscribe for events that this entity emits itself. Keep the returned
Subscription alive for as long as you want the callback to run.
Sourcepub fn on_release(
&self,
on_release: impl FnOnce(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn on_release(
&self,
on_release: impl FnOnce(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls on_release when GPUI releases this entity.
GPUI releases an entity at the end of the update in which its last strong handle was dropped. The callback runs then, while the value still exists, and receives it mutably together with the app. Use it to tear down resources the entity holds outside GPUI.
The callback stays registered while the returned Subscription is alive. Dropping the
subscription cancels the callback. Call Subscription::detach to keep it until the entity is
released.
Sourcepub fn observe_release<T2>(
&self,
entity: &Entity<T2>,
on_release: impl FnOnce(&mut T, &mut T2, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: Any,
T2: 'static,
pub fn observe_release<T2>(
&self,
entity: &Entity<T2>,
on_release: impl FnOnce(&mut T, &mut T2, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: Any,
T2: 'static,
Calls on_release when entity is released.
The callback receives this entity mutably and the released value. It doesn’t run if this entity
has been released too. The callback stays registered while the returned Subscription is
alive.
Sourcepub fn observe_global<G: 'static>(
&mut self,
f: impl FnMut(&mut T, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn observe_global<G: 'static>(
&mut self,
f: impl FnMut(&mut T, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls f whenever the global of type G is set or updated.
f runs after the update that changed the global finishes. It doesn’t receive the value, so
read it with App::global. Keep the returned Subscription alive for as long as you want
the callback to run. To also receive a window, use Context::observe_global_in.
Sourcepub fn on_app_restart(
&self,
on_restart: impl FnMut(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn on_app_restart(
&self,
on_restart: impl FnMut(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls on_restart when the application is about to restart.
The callback doesn’t run if this entity has been released. Keep the returned Subscription
alive for as long as you want the callback to run.
Sourcepub fn on_app_quit<Fut>(
&self,
on_quit: impl FnMut(&mut T, &mut Context<'_, T>) -> Fut + 'static,
) -> Subscription
pub fn on_app_quit<Fut>( &self, on_quit: impl FnMut(&mut T, &mut Context<'_, T>) -> Fut + 'static, ) -> Subscription
Calls on_quit when the application quits, and waits for the future it returns.
GPUI polls the returned future for up to SHUTDOWN_TIMEOUT while the
app quits. Use this to save state before the process exits. The callback doesn’t run if this
entity has been released.
Sourcepub fn notify(&mut self)
pub fn notify(&mut self)
Marks this entity as changed, so that the windows showing it are redrawn and its observers are called.
GPUI doesn’t watch your fields: call notify after changing state that affects rendering or that
observers registered with Context::observe care about. The effects run when the current
update finishes, not during this call, and several notifications in one update are delivered
once.
§Examples
struct Counter {
count: usize,
}
impl Counter {
fn increment(&mut self, cx: &mut Context<Self>) {
self.count += 1;
cx.notify();
}
}
Sourcepub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> ⓘ
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> ⓘ
Runs the future returned by f on the main thread, with a weak handle to this entity.
f receives a WeakEntity<T> for this entity and an AsyncApp. Use the weak handle to
reach the entity after an .await. Its update returns an error if the entity has been released
in the meantime. Use the AsyncApp to reach the rest of the app.
The returned Task cancels the future when it’s dropped. Keep it in a field to cancel the work
when this entity changes, or call Task::detach to let it continue after the local handle
is gone. Detaching does not guarantee completion during shutdown. For work that needs a
window, use Context::spawn_in. Use AppContext::background_spawn inside the future
for work on the background executor; see BackgroundExecutor
for platform differences.
§Examples
struct Search {
results: Vec<String>,
}
impl Search {
fn run(&mut self, query: String, cx: &mut Context<Self>) {
cx.spawn(async move |search, cx| {
// A real app would await a network request here.
let results = vec![format!("result for {query}")];
search
.update(cx, |search, cx| {
search.results = results;
cx.notify();
})
.ok();
})
.detach();
}
}
app.update(|cx| {
search.update(cx, |search, cx| search.run("gpui".to_string(), cx));
});
// `TestApp::update` runs the task before it returns.
app.read(|cx| assert_eq!(search.read(cx).results[0], "result for gpui"));See async work.
Sourcepub fn listener<E: ?Sized>(
&self,
listener: impl Fn(&mut T, &E, &mut Window, &mut Context<'_, T>) + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static
pub fn listener<E: ?Sized>( &self, listener: impl Fn(&mut T, &E, &mut Window, &mut Context<'_, T>) + 'static, ) -> impl Fn(&E, &mut Window, &mut App) + 'static
Wraps f in an event handler that receives this entity mutably.
Element event handlers receive the event, a Window and an App, but not your entity.
listener returns a handler that calls f with the entity, the event, the window and a context
for the entity. Pass the result to an element’s handler method, such as on_click.
The handler holds a weak handle to the entity, so an element that is still registered doesn’t
keep its view alive. If the entity has been released, the handler does nothing. Call
Context::notify inside f to redraw the window after you change state.
§Examples
use gpui::{Context, MouseButton, TestApp, Window, div, point, prelude::*, px};
struct Counter {
count: usize,
}
impl Render for Counter {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("button")
.size_full()
.on_click(cx.listener(|counter, _event, _window, cx| {
counter.count += 1;
cx.notify();
}))
}
}
let mut app = TestApp::new();
let mut window = app.open_window(|_window, _cx| Counter { count: 0 });
window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);
window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);
assert_eq!(window.read(|counter, _cx| counter.count), 2);Sourcepub fn processor<E, R>(
&self,
f: impl Fn(&mut T, E, &mut Window, &mut Context<'_, T>) -> R + 'static,
) -> impl Fn(E, &mut Window, &mut App) -> R + 'static
pub fn processor<E, R>( &self, f: impl Fn(&mut T, E, &mut Window, &mut Context<'_, T>) -> R + 'static, ) -> impl Fn(E, &mut Window, &mut App) -> R + 'static
Wraps f in a closure that receives this entity mutably and returns a value.
Use this when the caller needs the handler’s return value. For event handlers, prefer
Context::listener. The returned closure holds a strong handle to this entity, so it
keeps the entity alive for as long as the closure exists.
Sourcepub fn on_drop(
&self,
f: impl FnOnce(&mut T, &mut Context<'_, T>) + 'static,
) -> Deferred<impl FnOnce()>
pub fn on_drop( &self, f: impl FnOnce(&mut T, &mut Context<'_, T>) + 'static, ) -> Deferred<impl FnOnce()>
Returns a guard that calls f with this entity when the guard is dropped.
The guard is returned as a Deferred. Call abort on it to cancel the callback. If the entity
has been released by the time the guard is dropped, f doesn’t run.
§Panics
Panics if the guard is dropped while the app is already borrowed, for example inside another update of the same app, and the entity is still alive. Drop the guard from a later update instead.
Sourcepub fn focus_view<W: Focusable>(
&mut self,
view: &Entity<W>,
window: &mut Window,
)
pub fn focus_view<W: Focusable>( &mut self, view: &Entity<W>, window: &mut Window, )
Focuses view in window.
W must implement Focusable. The focus change uses the focus handle that view returns.
Sourcepub fn on_next_frame(
&self,
window: &mut Window,
f: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
)where
T: 'static,
pub fn on_next_frame(
&self,
window: &mut Window,
f: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
)where
T: 'static,
Runs f with this entity and window on the next frame of window.
The callback runs once, during the next frame. It doesn’t run if this entity has been released.
Sourcepub fn defer_in(
&mut self,
window: &Window,
f: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
)
pub fn defer_in( &mut self, window: &Window, f: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) + 'static, )
Runs f with this entity and window at the end of the current effect cycle.
Use it to change this entity from code that is still on the stack, such as a method called from inside this entity’s own update. The callback runs after the outermost update finishes, when the entity is no longer borrowed. It doesn’t run if this entity has been released.
Sourcepub fn observe_in<V2>(
&mut self,
observed: &Entity<V2>,
window: &mut Window,
on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
V2: 'static,
T: 'static,
pub fn observe_in<V2>(
&mut self,
observed: &Entity<V2>,
window: &mut Window,
on_notify: impl FnMut(&mut T, Entity<V2>, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
V2: 'static,
T: 'static,
Calls on_notify when observed calls Context::notify, and passes it the window.
Pass the window that displays this entity. If that window has been closed, the callback does not run.
Sourcepub fn subscribe_in<Emitter, Evt>(
&mut self,
emitter: &Entity<Emitter>,
window: &Window,
on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
Emitter: EventEmitter<Evt>,
Evt: 'static,
pub fn subscribe_in<Emitter, Evt>(
&mut self,
emitter: &Entity<Emitter>,
window: &Window,
on_event: impl FnMut(&mut T, &Entity<Emitter>, &Evt, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
Emitter: EventEmitter<Evt>,
Evt: 'static,
Calls on_event when emitter emits an event of type Evt, and passes it the window.
Pass the window that displays this entity. If that window has been closed, the callback does not run.
Sourcepub fn on_release_in(
&mut self,
window: &Window,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscription
pub fn on_release_in( &mut self, window: &Window, on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static, ) -> Subscription
Calls on_release with the window when this entity is released.
The callback doesn’t run if the window was closed before this entity was released.
Sourcepub fn observe_release_in<T2>(
&self,
observed: &Entity<T2>,
window: &Window,
on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
T2: 'static,
pub fn observe_release_in<T2>(
&self,
observed: &Entity<T2>,
window: &Window,
on_release: impl FnMut(&mut T, &mut T2, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscriptionwhere
T: 'static,
T2: 'static,
Calls on_release when observed is released, and passes it the window.
The callback does not run if window has been closed, or if this entity has been released.
Sourcepub fn observe_window_bounds(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_window_bounds( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls callback when the bounds of window change.
Keep the returned Subscription alive for as long as you want the callback to run. The callback
stops once this entity is released.
Sourcepub fn observe_window_activation(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_window_activation( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls callback when window becomes active or inactive.
Keep the returned Subscription alive for as long as you want the callback to run. The callback
stops once this entity is released.
Sourcepub fn observe_window_visibility(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_window_visibility( &self, window: &mut Window, callback: impl FnMut(&mut T, WindowVisibility, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Registers a callback to be invoked when the window’s visibility changes
(see WindowVisibility).
Sourcepub fn observe_window_appearance(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_window_appearance( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls callback when the system appearance changes between light and dark.
Keep the returned Subscription alive for as long as you want the callback to run. The callback
stops once this entity is released.
Sourcepub fn observe_window_display(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_window_display( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Registers a callback invoked when the window moves to another display
or its display’s refresh interval changes. See
Window::observe_window_display.
Calls callback when the window’s titlebar button layout changes.
Keep the returned Subscription alive for as long as you want the callback to run. The callback
stops once this entity is released.
Sourcepub fn observe_keystrokes(
&mut self,
f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_keystrokes( &mut self, f: impl FnMut(&mut T, &KeystrokeEvent, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls f with this entity for each keystroke that App::observe_keystrokes observes.
The keystroke’s action is set when a key binding handled it. Keep the returned
Subscription alive for as long as you want the callback to run.
Sourcepub fn observe_pending_input(
&self,
window: &mut Window,
callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_pending_input( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls callback when the pending input of window changes.
Pending input is a partly typed key sequence, such as the first key of a multi-key binding. The
callback runs when the sequence starts, grows, or is cleared. Keep the returned Subscription
alive for as long as you want the callback to run.
Sourcepub fn on_focus(
&mut self,
handle: &FocusHandle,
window: &mut Window,
listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn on_focus( &mut self, handle: &FocusHandle, window: &mut Window, listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls listener when handle becomes the focused element.
The listener doesn’t run when focus moves into a descendant of handle. Use Context::on_focus_in
to hear about that as well. Keep the returned Subscription alive for as long as you want the
listener to run.
Sourcepub fn on_focus_in(
&mut self,
handle: &FocusHandle,
window: &mut Window,
listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn on_focus_in( &mut self, handle: &FocusHandle, window: &mut Window, listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls listener when focus moves into handle or one of its descendants.
The listener doesn’t run when focus was already inside handle and moves to another descendant.
Keep the returned Subscription alive for as long as you want the listener to run.
Sourcepub fn on_blur(
&mut self,
handle: &FocusHandle,
window: &mut Window,
listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn on_blur( &mut self, handle: &FocusHandle, window: &mut Window, listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls listener when handle stops being the focused element.
The listener also runs when focus moves from handle to one of its descendants, since handle
is no longer the focused element. Use Context::on_focus_out to hear only about focus leaving
handle and its descendants. Keep the returned Subscription alive for as long as you want the
listener to run.
Sourcepub fn on_focus_lost(
&mut self,
window: &mut Window,
listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn on_focus_lost( &mut self, window: &mut Window, listener: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls listener when no element in window has focus.
This happens when the focused element is removed from the tree. Use it to move focus to a sensible
default. Keep the returned Subscription alive for as long as you want the listener to run.
Sourcepub fn on_focus_out(
&mut self,
handle: &FocusHandle,
window: &mut Window,
listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn on_focus_out( &mut self, handle: &FocusHandle, window: &mut Window, listener: impl FnMut(&mut T, FocusOutEvent, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls listener when focus leaves handle or one of its descendants.
The listener receives a FocusOutEvent that says which element lost focus. Keep the returned
Subscription alive for as long as you want the listener to run.
Sourcepub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R> ⓘ
pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R> ⓘ
Runs the future returned by f on the main thread, with a weak handle to this entity and a window
context.
f receives an AsyncWindowContext for window, so the future can reach it after an
.await. Window operations through the context return errors once the window has closed.
The returned Task cancels the future when it’s dropped. Call Task::detach to let the future
run to completion.
Sourcepub fn spawn_in_with_priority<AsyncFn, R>(
&self,
priority: Priority,
window: &Window,
f: AsyncFn,
) -> Task<R> ⓘ
pub fn spawn_in_with_priority<AsyncFn, R>( &self, priority: Priority, window: &Window, f: AsyncFn, ) -> Task<R> ⓘ
Runs the future returned by f on the main thread at priority, with a weak handle to this entity
and a window context.
The returned Task cancels the future when it is dropped.
Sourcepub fn observe_global_in<G: Global>(
&mut self,
window: &Window,
f: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static,
) -> Subscription
pub fn observe_global_in<G: Global>( &mut self, window: &Window, f: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription
Calls f with the window whenever the global of type G is set or updated.
Pass the window this entity is shown in. If that window is unavailable, for example during a nested update of it, the callback is skipped for that change and stays registered. The callback stops once this entity is released.
Sourcepub fn on_action(
&mut self,
action_type: TypeId,
window: &mut Window,
listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<'_, T>) + 'static,
)
pub fn on_action( &mut self, action_type: TypeId, window: &mut Window, listener: impl Fn(&mut T, &dyn Any, DispatchPhase, &mut Window, &mut Context<'_, T>) + 'static, )
Calls listener when an action of type action_type is dispatched to window.
Pass TypeId::of::<A>() for the action type A. The listener receives the action as &dyn Any
together with the DispatchPhase, so it can tell capture from bubble. It also gets the window and
a context for this entity.
Like Window::on_action, the listener is registered for the next frame only. Call this during
paint, on every frame that should handle the action.
Sourcepub fn focus_self(&mut self, window: &mut Window)where
T: Focusable,
pub fn focus_self(&mut self, window: &mut Window)where
T: Focusable,
Focuses this entity’s focus handle in window.
This entity must implement Focusable. The focus change happens at the end of the current effect
cycle.
Source§impl<T> Context<'_, T>
impl<T> Context<'_, T>
Sourcepub fn emit<Evt>(&mut self, event: Evt)where
T: EventEmitter<Evt>,
Evt: 'static,
pub fn emit<Evt>(&mut self, event: Evt)where
T: EventEmitter<Evt>,
Evt: 'static,
Emits event from this entity to its subscribers.
Subscribers registered with Context::subscribe or App::subscribe for this event type
receive it after the current update finishes, in the order the events were emitted. Emitting an
event that nobody subscribed to does nothing. This entity must implement EventEmitter<Evt>.
§Examples
struct Button;
struct Clicked {
times: usize,
}
impl EventEmitter<Clicked> for Button {}
struct Tally {
clicks: usize,
}
let button = cx.new(|_cx| Button);
let tally = cx.new(|cx: &mut Context<Tally>| {
cx.subscribe(&button, |tally, _button, event: &Clicked, _cx| {
tally.clicks += event.times;
})
.detach();
Tally { clicks: 0 }
});
(button, tally)
button.update(cx, |_button, cx| {
cx.emit(Clicked { times: 2 });
cx.emit(Clicked { times: 1 });
});Methods from Deref<Target = App>§
Sourcepub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot
Captures a snapshot of all entities that currently have alive handles.
The returned LeakDetectorSnapshot can later be passed to
assert_no_new_leaks to verify that no
entities created after the snapshot are still alive.
Sourcepub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot)
pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot)
Asserts that no entities created after snapshot still have alive handles.
Entities that were already tracked at the time of the snapshot are ignored,
even if they still have handles. Only new entities (those whose
EntityId was not present in the snapshot) are considered leaks.
§Panics
Panics if any new entity handles exist. The panic message lists every
leaked entity with its type name, and includes allocation-site backtraces
when LEAK_BACKTRACE is set.
Sourcepub fn shutdown(&mut self)
pub fn shutdown(&mut self)
Runs the quit handlers, closes every window and flushes pending effects.
The platform calls this when the app quits. Handlers registered with
Context::on_app_quit run first. Native apps wait up to SHUTDOWN_TIMEOUT
for them to finish and log an error if they don’t. On the web the handlers run
asynchronously as best-effort cleanup, because the event loop cannot block.
To quit from your own code, call App::quit instead.
Sourcepub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout
pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout
Returns the keyboard layout that is active now.
Use it to translate between keystrokes and the characters they produce. The
value is updated when the layout changes, which App::on_keyboard_layout_change
reports.
Sourcepub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper>
pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper>
Returns the keyboard mapper for the active layout.
Sourcepub fn on_keyboard_layout_change<F>(&self, callback: F) -> Subscription
pub fn on_keyboard_layout_change<F>(&self, callback: F) -> Subscription
Calls callback each time the user switches the keyboard layout.
The subscription stays active while you hold it. Drop it to stop receiving
calls. By the time the callback runs, App::keyboard_layout already returns
the new layout.
Sourcepub fn quit(&self)
pub fn quit(&self)
Asks the platform to quit the app, the same as choosing Quit from the app menu.
The quit happens later, not inside this call. The platform then calls
App::shutdown, which runs the Context::on_app_quit handlers and closes
the windows. Use this to quit from your own code. QuitMode controls quits
that happen when the last window closes.
Sourcepub fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> ⓘ
pub fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> ⓘ
Switches the platform between headless and windowed modes.
On Linux, headless means no display server: windows opened afterwards lay out and handle
input but draw nothing. Windowed, the platform connects to the display server the
environment names. On macOS, the modes set the ActivationPolicy: headless is
Accessory (no Dock icon or menu bar) and windowed is Regular. Switching to windowed
doesn’t activate the app: call App::activate for that.
The returned task resolves once the switch has been applied. It fails if the platform is already in the requested mode (switching to another display server means going headless first), if the platform doesn’t allow the mode or can’t switch at all, if any window is open (a window belongs to the display server that opened it), or if the display server can’t be reached.
Sourcepub fn graphical_environment(&self) -> Option<GraphicalEnvironment>
pub fn graphical_environment(&self) -> Option<GraphicalEnvironment>
The environment of the display server the platform is connected to, or None while
headless. Its activation token is always unset, since the connection has used it.
Programs an app launches inherit this process’s environment, which may name another
graphical session, or none if the app started headless. Pass them this one with
GraphicalEnvironment::apply_to.
On macOS, the environment carries nothing, and this is None while the activation
policy is Accessory. Always None on platforms that can’t switch windowing modes.
Sourcepub fn cursor_hide_mode(&self) -> CursorHideMode
pub fn cursor_hide_mode(&self) -> CursorHideMode
Returns the policy that decides when GPUI hides the cursor while typing.
Defaults to CursorHideMode::OnTypingAndAction.
Sourcepub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode)
pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode)
Sets the policy that decides when GPUI hides the cursor while typing.
Takes effect for the next keystroke. The cursor reappears when the mouse moves.
Sourcepub fn is_cursor_visible(&self) -> bool
pub fn is_cursor_visible(&self) -> bool
Returns whether the cursor is currently visible according to the
platform. This will report false after a keyboard input has hidden
the cursor and the user has not yet moved the mouse to restore it.
Sourcepub fn reduce_motion(&self) -> bool
pub fn reduce_motion(&self) -> bool
Returns whether non-essential animations should render in a static state.
Check this before you start a decorative animation, such as a spinner that only
looks busy. The app sets it, and it defaults to false.
Sourcepub fn set_reduce_motion(&mut self, reduce_motion: bool)
pub fn set_reduce_motion(&mut self, reduce_motion: bool)
Sets whether non-essential animations should render in a static state.
Setting a different value redraws all windows. Animations that are needed to show state, such as a progress bar, should keep running.
Sourcepub fn refresh_windows(&mut self)
pub fn refresh_windows(&mut self)
Redraws every window once the current update finishes.
Calling it several times in one update still causes a single redraw per window.
Use Context::notify on the entity that changed instead when you can. Use this
when state outside any entity changes what is drawn.
Sourcepub fn observe<W>(
&mut self,
entity: &Entity<W>,
on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
) -> Subscriptionwhere
W: 'static,
pub fn observe<W>(
&mut self,
entity: &Entity<W>,
on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
) -> Subscriptionwhere
W: 'static,
Calls on_notify each time entity calls Context::notify.
The callback receives the entity and the App. It runs when the update that
called notify finishes, not during that call. Keep the returned Subscription
alive, because dropping it ends the observation.
§Examples
let seen = Rc::new(Cell::new(0));
let counter = app.update(|cx| cx.new(|_| 0));
let _subscription = app.update(|cx| {
cx.observe(&counter, {
let seen = seen.clone();
move |counter, cx| seen.set(*counter.read(cx))
})
});
app.update(|cx| {
counter.update(cx, |count, cx| {
*count = 2;
cx.notify();
})
});
assert_eq!(seen.get(), 2);Sourcepub fn subscribe<T, Event>(
&mut self,
entity: &Entity<T>,
on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static + EventEmitter<Event>,
Event: 'static,
pub fn subscribe<T, Event>(
&mut self,
entity: &Entity<T>,
on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static + EventEmitter<Event>,
Event: 'static,
Calls on_event each time entity emits an event of type Event.
The callback receives the entity, a reference to the event and the App. The
entity emits with Context::emit. Callbacks run when the update that emitted
the event finishes. Keep the returned Subscription alive, because dropping it
ends the subscription. Use App::observe when the entity only calls
Context::notify and doesn’t send a payload.
§Examples
struct Counter;
struct Incremented(usize);
impl EventEmitter<Incremented> for Counter {}
let counter = app.update(|cx| cx.new(|_| Counter));
let total = Rc::new(Cell::new(0));
let _subscription = app.update(|cx| {
cx.subscribe(&counter, {
let total = total.clone();
move |_, event: &Incremented, _| total.set(total.get() + event.0)
})
});
app.update(|cx| counter.update(cx, |_, cx| cx.emit(Incremented(3))));
assert_eq!(total.get(), 3);Sourcepub fn windows(&self) -> Vec<AnyWindowHandle>
pub fn windows(&self) -> Vec<AnyWindowHandle>
Returns handles to every open window.
Each handle is untyped. AnyWindowHandle::downcast checks the root type recorded in
the handle. If the root may have been replaced, use AnyWindowHandle::update to
inspect the live root; the recorded type does not change with it.
Sourcepub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>
pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>
Returns the window handles ordered by their appearance on screen, front to back.
The first window in the returned list is the active/topmost window of the application.
This method returns None if the platform doesn’t implement the method yet.
Sourcepub fn set_gpu_requirements(&self, requirements: Box<dyn Any>)
pub fn set_gpu_requirements(&self, requirements: Box<dyn Any>)
Sets the GPU device requirements (extra features and limits) for the renderer. Only macOS uses them.
Call this before opening any window. The argument must be a
gpui_wgpu::WgpuDeviceRequirements boxed as Box<dyn Any>.
Sourcepub fn set_keyring_label(&self, label: impl Into<SharedString>)
pub fn set_keyring_label(&self, label: impl Into<SharedString>)
Sets the label applied to credentials stored in the system keyring. Call before writing credentials. Only Linux/FreeBSD apply the label.
Sourcepub fn active_window(&self) -> Option<AnyWindowHandle>
pub fn active_window(&self) -> Option<AnyWindowHandle>
Returns the handle of the window that the platform reports as active, if any.
Returns None when no window of this app has focus, for example when another
application is in front.
Sourcepub fn open_window<V: 'static + Render>(
&mut self,
options: WindowOptions,
build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
) -> Result<WindowHandle<V>>
pub fn open_window<V: 'static + Render>( &mut self, options: WindowOptions, build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>, ) -> Result<WindowHandle<V>>
Opens a window and builds its root view.
build_root_view runs once, with the new Window and the App, and returns
the root entity. The window is drawn once before this method returns. Use the
returned WindowHandle to update or read the root view later.
In tests, TestApp::open_window opens a window without a display.
§Errors
Returns an error if the platform cannot create the window. In that case
build_root_view is not called.
§Examples
struct Hello;
impl Render for Hello {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().child("Hello")
}
}
let window = app.update(|cx| {
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Hello))
.unwrap()
});
app.read(|cx| assert_eq!(cx.windows().len(), 1));Sourcepub fn activate(&self, ignoring_other_apps: bool)
pub fn activate(&self, ignoring_other_apps: bool)
Brings the app to the front.
Pass ignoring_other_apps: true to activate the app even when another app is in front.
Use it sparingly, because it moves the user’s focus.
Sourcepub fn hide_other_apps(&self)
pub fn hide_other_apps(&self)
Hides all other applications.
Sourcepub fn unhide_other_apps(&self)
pub fn unhide_other_apps(&self)
Shows the applications hidden by App::hide_other_apps.
Sourcepub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>
pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>
Returns the connected displays.
Sourcepub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>
pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>
Returns the primary display, or None if the platform reports none.
Sourcepub fn is_screen_capture_supported(&self) -> bool
pub fn is_screen_capture_supported(&self) -> bool
Returns whether App::screen_capture_sources can return sources on this platform.
Sourcepub fn screen_capture_sources(
&self,
) -> Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> ⓘ
pub fn screen_capture_sources( &self, ) -> Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> ⓘ
Asks the platform for the screens and windows that can be captured.
The list arrives on the returned channel, so the call doesn’t block. The channel
yields an error if the platform can’t list sources. Check
App::is_screen_capture_supported first.
Sourcepub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>
pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>
Returns the display with the given DisplayId, or None if it is not connected.
Sourcepub fn thermal_state(&self) -> ThermalState
pub fn thermal_state(&self) -> ThermalState
Returns the system’s current ThermalState.
Check it before heavy work, such as a long animation or a background computation, and reduce the work when the system is hot.
Sourcepub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> ⓘ
pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> ⓘ
Prevents idle sleep while the returned guard is held.
Sourcepub fn on_thermal_state_change<F>(&self, callback: F) -> Subscription
pub fn on_thermal_state_change<F>(&self, callback: F) -> Subscription
Calls callback when the system’s thermal state changes.
The subscription stays active while you hold it.
Sourcepub fn on_system_sleep<F>(&self, callback: F) -> Subscription
pub fn on_system_sleep<F>(&self, callback: F) -> Subscription
Invokes a handler when the system is about to sleep.
The platform gives the process only a short time before suspending, so handlers should record state or cancel work rather than start it.
Sourcepub fn observe_displays<F>(&self, callback: F) -> Subscription
pub fn observe_displays<F>(&self, callback: F) -> Subscription
Invokes a handler when a display is connected, disconnected, or its properties change.
Sourcepub fn on_system_wake<F>(&self, callback: F) -> Subscription
pub fn on_system_wake<F>(&self, callback: F) -> Subscription
Calls callback when the system wakes from sleep.
Use it to reconnect to network services or refresh data that went stale while the machine slept. The subscription stays active while you hold it.
Sourcepub fn on_app_lifecycle(
&self,
callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
) -> Subscription
pub fn on_app_lifecycle( &self, callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static, ) -> Subscription
Observes mobile application lifecycle changes. Desktop platforms do not emit these events. On iOS these currently describe the single connected scene, not individual windows.
Save important changes incrementally: neither disconnection nor quit is guaranteed before the system terminates a backgrounded application. Dropping the returned subscription removes the observer.
Sourcepub fn on_memory_warning(
&self,
callback: impl FnMut(&mut App) + 'static,
) -> Subscription
pub fn on_memory_warning( &self, callback: impl FnMut(&mut App) + 'static, ) -> Subscription
Observes mobile memory-pressure warnings so applications can release expendable caches. Dropping the subscription removes the observer.
Sourcepub fn window_appearance(&self) -> WindowAppearance
pub fn window_appearance(&self) -> WindowAppearance
Returns whether the windows use the light or dark appearance.
This is the system setting unless App::set_window_appearance overrides it.
Sourcepub fn set_window_appearance(&self, appearance: Option<WindowAppearance>)
pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>)
Overrides the appearance (light/dark) applied to the app’s windows, independent of
the OS-wide setting. Pass None to clear the override and follow the system again.
The current value is reported by App::window_appearance.
On macOS this sets the underlying NSApplication.appearance, which controls the
native window chrome (the window border and titlebar) of every window. Use this
when the app uses a dark theme while the system is in light mode (or vice versa)
so the window edges render to match the theme. While an appearance is forced,
windows stop tracking system light/dark changes; pass None to resume following
the system. On other platforms this is a no-op.
Sourcepub fn supports_haptic_feedback(&self) -> bool
pub fn supports_haptic_feedback(&self) -> bool
Returns whether App::play_haptic_feedback does anything on this platform.
Sourcepub fn play_haptic_feedback(&self, style: HapticFeedbackStyle)
pub fn play_haptic_feedback(&self, style: HapticFeedbackStyle)
Plays a haptic feedback pulse of the given style.
Call it from the main thread, for example in response to a click or a drop that
the user should feel. It does nothing on platforms without haptics. Check
App::supports_haptic_feedback to decide whether to show a haptic option.
Styles correspond to
NSHapticFeedbackPattern
values on macOS.
Returns the window button layout (the position of close, minimize and maximize), if the platform reports one.
Returns None when the platform has no custom layout. Use it to draw your own
window controls in the same place as the native ones.
Sourcepub fn read_from_clipboard(&self) -> Option<ClipboardItem>
pub fn read_from_clipboard(&self) -> Option<ClipboardItem>
Reads the current contents of the system clipboard.
Returns None if the clipboard is empty or holds nothing GPUI can read. On
the web, use App::read_from_clipboard_async instead, because this method
cannot wait for permission.
Sourcepub fn read_from_clipboard_async(
&self,
) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> ⓘ
pub fn read_from_clipboard_async( &self, ) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> ⓘ
Reads the system clipboard and resolves once the contents are available.
Prefer this over App::read_from_clipboard in code that can await. On
platforms where clipboard access is asynchronous and permission-gated (such as
the web), the synchronous read always returns None while this method performs
a real read. The task resolves to an error if the read fails.
Sourcepub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode)
pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode)
Sets how text is rasterized for every window in the app.
The default is TextRenderingMode::PlatformDefault. The new mode applies to
text drawn after this call.
Sourcepub fn text_rendering_mode(&self) -> TextRenderingMode
pub fn text_rendering_mode(&self) -> TextRenderingMode
Returns how text is currently rasterized. See App::set_text_rendering_mode.
Sourcepub fn write_to_clipboard(&self, item: ClipboardItem)
pub fn write_to_clipboard(&self, item: ClipboardItem)
Replaces the contents of the system clipboard with item.
§Examples
app.update(|cx| cx.write_to_clipboard(ClipboardItem::new_string("copied".into())));
app.read(|cx| {
let item = cx.read_from_clipboard().unwrap();
assert_eq!(item.text().as_deref(), Some("copied"));
});Sourcepub fn read_from_primary(&self) -> Option<ClipboardItem>
pub fn read_from_primary(&self) -> Option<ClipboardItem>
Reads data from the primary selection buffer. Only available on Linux and FreeBSD.
Sourcepub fn write_to_primary(&self, item: ClipboardItem)
pub fn write_to_primary(&self, item: ClipboardItem)
Writes data to the primary selection buffer. Only available on Linux and FreeBSD.
Sourcepub fn write_credentials(
&self,
url: &str,
username: &str,
password: &[u8],
) -> Task<Result<()>> ⓘ
pub fn write_credentials( &self, url: &str, username: &str, password: &[u8], ) -> Task<Result<()>> ⓘ
Stores a username and password for url in the platform keychain.
The task resolves once the store finishes, or to an error if it fails. Await it
from a task spawned with App::spawn.
Sourcepub fn read_credentials(
&self,
url: &str,
) -> Task<Result<Option<(String, Vec<u8>)>>> ⓘ
pub fn read_credentials( &self, url: &str, ) -> Task<Result<Option<(String, Vec<u8>)>>> ⓘ
Reads the username and password stored for url.
The task resolves to None when nothing is stored for url. Use the same url
that you passed to App::write_credentials.
Sourcepub fn delete_credentials(&self, url: &str) -> Task<Result<()>> ⓘ
pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> ⓘ
Removes the credentials stored for url from the platform keychain.
Sourcepub fn open_url(&self, url: &str)
pub fn open_url(&self, url: &str)
Opens url in the platform’s default browser or handler.
The call returns immediately. In tests, TestApp::opened_url reports the last
URL passed here.
Sourcepub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> ⓘ
pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> ⓘ
Registers scheme (for example zed for zed:// links) so that links with it open this app.
Use Application::on_open_urls to receive the links. On some platforms you
declare schemes when you package the app. This method registers them at runtime.
Sourcepub fn set_app_identity(&self, identifier: &str, name: &str)
pub fn set_app_identity(&self, identifier: &str, name: &str)
Sets the app’s identifier and user-visible name for the operating system.
The identifier is used for platform identity mechanisms such as the Windows AppUserModelID. The name is shown wherever the operating system presents the app.
Sourcepub fn show_system_notification(&self, notification: SystemNotification)
pub fn show_system_notification(&self, notification: SystemNotification)
Posts a notification to the operating system’s notification center.
Posting a notification whose SystemNotification::tag matches an
earlier one replaces that notification where the platform supports it.
No-op on platforms without notification support, or when delivery is
unavailable (e.g. authorization was denied).
Sourcepub fn dismiss_system_notification(&self, tag: &str)
pub fn dismiss_system_notification(&self, tag: &str)
Removes the delivered or pending notification with this tag.
Best-effort: some platforms cannot retract a notification once shown, in which case it ages out of the notification center on its own.
Sourcepub fn on_system_notification_response<F>(&self, callback: F)
pub fn on_system_notification_response<F>(&self, callback: F)
Registers the handler invoked when the user activates a system notification, either by clicking its body or one of its action buttons. Subsequent registrations replace the handler.
Sourcepub fn app_path(&self) -> Result<PathBuf>
pub fn app_path(&self) -> Result<PathBuf>
Returns the full pathname of the current app bundle.
Returns an error if the app is not being run from a bundle.
Sourcepub fn compositor_name(&self) -> &'static str
pub fn compositor_name(&self) -> &'static str
On Linux, returns the name of the compositor in use. On the web, returns "Web".
Returns an empty string on other platforms.
Sourcepub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>
Returns the path to a helper executable named name that ships with the app.
Sourcepub fn prompt_for_paths(
&self,
options: PathPromptOptions,
) -> Receiver<Result<Option<Vec<PathBuf>>>> ⓘ
pub fn prompt_for_paths( &self, options: PathPromptOptions, ) -> Receiver<Result<Option<Vec<PathBuf>>>> ⓘ
Shows the platform’s file or folder picker and returns the user’s choice.
The result arrives on the returned channel once the user picks paths or cancels.
Cancelling yields Ok(None). The picker is shown without blocking the caller.
On Linux the channel yields an error if the picker can’t be opened.
Sourcepub fn prompt_for_new_path(
&self,
directory: &Path,
suggested_name: Option<&str>,
) -> Receiver<Result<Option<PathBuf>>> ⓘ
pub fn prompt_for_new_path( &self, directory: &Path, suggested_name: Option<&str>, ) -> Receiver<Result<Option<PathBuf>>> ⓘ
Shows the platform’s save dialog and returns the path the user chose.
directory is the folder the dialog opens in, and suggested_name pre-fills the
file name. The result arrives on the returned channel. Cancelling yields
Ok(None). On Linux the channel yields an error if the dialog can’t be opened.
Sourcepub fn reveal_path(&self, path: &Path)
pub fn reveal_path(&self, path: &Path)
Shows path in the platform’s file manager, such as Finder on macOS.
Sourcepub fn open_with_system(&self, path: &Path)
pub fn open_with_system(&self, path: &Path)
Opens path with the system’s default application for its file type.
Sourcepub fn should_auto_hide_scrollbars(&self) -> bool
pub fn should_auto_hide_scrollbars(&self) -> bool
Returns whether the user has configured scrollbars to auto-hide at the platform level.
Sourcepub fn restart(&mut self)
pub fn restart(&mut self)
Restarts the app. Runs the handlers from App::on_app_restart, then asks the
platform to relaunch it.
The relaunch uses the path from App::set_restart_path and the arguments from
Application::with_restart_arguments.
Sourcepub fn set_restart_path(&mut self, path: PathBuf)
pub fn set_restart_path(&mut self, path: PathBuf)
Sets the executable path that App::restart launches. The path is used once, by the next restart.
Sourcepub fn http_client(&self) -> Arc<dyn HttpClient> ⓘ
pub fn http_client(&self) -> Arc<dyn HttpClient> ⓘ
Returns the app’s HTTP client. See Application::with_http_client.
Sourcepub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>)
pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>)
Replaces the HTTP client that App::http_client returns.
Sourcepub fn set_quit_mode(&mut self, mode: QuitMode)
pub fn set_quit_mode(&mut self, mode: QuitMode)
Sets when the app quits on its own. See QuitMode.
Defaults to QuitMode::Default.
Sourcepub fn set_activation_policy(&mut self, policy: ActivationPolicy)
pub fn set_activation_policy(&mut self, policy: ActivationPolicy)
Sets whether the application participates in the system’s foreground UI.
Only has an effect on macOS, where Self::request_windowing normally sets it. Use this
for an accessory app that shows windows, such as a menu bar utility. It overrides the
policy until the next Self::request_windowing, and the app counts as headless while
Accessory. After switching to ActivationPolicy::Regular, activate the app yourself
with Self::activate; otherwise its menu bar may not appear until the app is
reactivated.
Sourcepub fn svg_renderer(&self) -> SvgRenderer
pub fn svg_renderer(&self) -> SvgRenderer
Returns the SVG renderer that draws the app’s SVG assets.
Sourcepub fn with_window<R>(
&mut self,
entity_id: EntityId,
f: impl FnOnce(&mut Window, &mut App) -> R,
) -> Option<R>
pub fn with_window<R>( &mut self, entity_id: EntityId, f: impl FnOnce(&mut Window, &mut App) -> R, ) -> Option<R>
Runs f with the window that most recently drew the entity entity_id.
If the entity has not been drawn yet, the window it was created in is used. The
callback receives the Window and the App. Returns None if the entity has
no current window, if that window has closed, or if the window is already being
updated higher up the call stack.
Sourcepub fn background_executor(&self) -> &BackgroundExecutor
pub fn background_executor(&self) -> &BackgroundExecutor
Returns the BackgroundExecutor for Send futures.
Native backends use worker threads; single-threaded web builds use the main thread.
Sourcepub fn is_test(&self) -> bool
pub fn is_test(&self) -> bool
Whether this app runs on the deterministic test scheduler. See
BackgroundExecutor::is_test.
Sourcepub fn foreground_executor(&self) -> &ForegroundExecutor
pub fn foreground_executor(&self) -> &ForegroundExecutor
Returns the ForegroundExecutor, which runs futures on the main thread.
§Panics
Panics if called after the quit handlers have started running (from
App::on_app_quit).
Sourcepub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> ⓘwhere
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> ⓘwhere
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
Runs an async block on the main thread, with an AsyncApp for access to app state.
The closure receives &mut AsyncApp. Use it to update entities and windows after
an await. The future doesn’t need to be Send, because it stays on the main
thread. Dropping the returned Task cancels it, so store it or call
Task::detach to let it run to completion in the background.
Use App::background_executor for CPU-heavy or blocking work, and send the
result back to the main thread with a spawn task.
§Panics
In debug builds this panics if called after the quit handlers have started running. Release builds log a debug message and continue.
§Examples
let ran = Rc::new(Cell::new(false));
app.update(|cx| {
let ran = ran.clone();
cx.spawn(async move |_cx| ran.set(true)).detach();
});
app.read(|_| assert!(ran.get()));See async work for the executors and how to share state across tasks.
Sourcepub fn spawn_with_priority<AsyncFn, R>(
&self,
priority: Priority,
f: AsyncFn,
) -> Task<R> ⓘwhere
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
pub fn spawn_with_priority<AsyncFn, R>(
&self,
priority: Priority,
f: AsyncFn,
) -> Task<R> ⓘwhere
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
Like App::spawn, but schedules the task with the given Priority.
Sourcepub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static)
pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static)
Runs f after the current effect cycle finishes, with the App.
Use it to act on state that is borrowed right now. For example, you can change
an entity from inside its own update, which would otherwise be a double borrow.
The callback runs once the outermost update returns.
let mut app = TestApp::new();
let count = app.update(|cx| cx.new(|_| 0));
app.update(|cx| {
let count = count.clone();
cx.defer(move |cx| {
count.update(cx, |count, _| *count += 1);
});
});
app.read(|cx| assert_eq!(*count.read(cx), 1));Sourcepub fn assets(&self) -> &Arc<AssetRegistry> ⓘ
pub fn assets(&self) -> &Arc<AssetRegistry> ⓘ
Returns the asset registry that the app loads assets from. See Application::with_assets.
Sourcepub fn text_system(&self) -> &Arc<TextSystem> ⓘ
pub fn text_system(&self) -> &Arc<TextSystem> ⓘ
Returns the app’s TextSystem, which shapes and rasterizes text.
Sourcepub fn has_global<G: Global>(&self) -> bool
pub fn has_global<G: Global>(&self) -> bool
Returns whether a global of type G has been set.
Sourcepub fn global<G: Global>(&self) -> &G
pub fn global<G: Global>(&self) -> &G
Returns the global of type G.
§Panics
Panics if no global of type G has been set. Use App::try_global when the
global may be missing.
Sourcepub fn try_global<G: Global>(&self) -> Option<&G>
pub fn try_global<G: Global>(&self) -> Option<&G>
Returns the global of type G, or None if it has not been set.
Sourcepub fn global_mut<G: Global>(&mut self) -> &mut G
pub fn global_mut<G: Global>(&mut self) -> &mut G
Returns the global of type G for mutation, and notifies global observers.
Observers registered with App::observe_global run when the current update
finishes. The notification happens on every call, even if you don’t change the
value.
§Panics
Panics if no global of type G has been set. Use App::default_global to
create one on first use.
Sourcepub fn default_global<G: Global + Default>(&mut self) -> &mut G
pub fn default_global<G: Global + Default>(&mut self) -> &mut G
Returns the global of type G for mutation, first setting G::default() if it is missing.
Like App::global_mut, this notifies global observers.
Sourcepub fn set_global<G: Global>(&mut self, global: G)
pub fn set_global<G: Global>(&mut self, global: G)
Sets the global of type G to global, replacing any previous value.
Notifies global observers when the current update finishes.
§Examples
struct Theme {
name: &'static str,
}
impl Global for Theme {}
app.update(|cx| cx.set_global(Theme { name: "dark" }));
app.read(|cx| assert_eq!(cx.global::<Theme>().name, "dark"));Sourcepub fn clear_globals(&mut self)
pub fn clear_globals(&mut self)
Clear all stored globals. Does not notify global observers.
Sourcepub fn remove_global<G: Global>(&mut self) -> G
pub fn remove_global<G: Global>(&mut self) -> G
Removes the global of type G and returns it.
Notifies global observers when the current update finishes.
§Panics
Panics if no global of type G has been set.
Sourcepub fn observe_global<G: Global>(
&mut self,
f: impl FnMut(&mut Self) + 'static,
) -> Subscription
pub fn observe_global<G: Global>( &mut self, f: impl FnMut(&mut Self) + 'static, ) -> Subscription
Calls f each time the global of type G is set, changed or removed.
The observer is active once the current update finishes. Keep the returned
Subscription alive, because dropping it stops the observer.
§Examples
struct Count(usize);
impl Global for Count {}
let calls = Rc::new(Cell::new(0));
let _subscription = app.update(|cx| {
cx.set_global(Count(0));
cx.observe_global::<Count>({
let calls = calls.clone();
move |_| calls.set(calls.get() + 1)
})
});
app.update(|cx| cx.global_mut::<Count>().0 += 1);
assert_eq!(calls.get(), 1);Sourcepub fn observe_new<T: 'static>(
&self,
on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<'_, T>),
) -> Subscription
pub fn observe_new<T: 'static>( &self, on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<'_, T>), ) -> Subscription
Calls on_new each time an entity of type T is created.
The callback receives the new state, the Window if the entity was created with
one, and a Context for it. Use it to set up behavior for every instance of a
type, such as registering an observer. Keep the returned Subscription alive
for the callback to keep running.
Sourcepub fn observe_release<T>(
&self,
handle: &Entity<T>,
on_release: impl FnOnce(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn observe_release<T>(
&self,
handle: &Entity<T>,
on_release: impl FnOnce(&mut T, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls on_release when the entity behind handle is released.
The callback runs after the entity’s last strong handle is dropped, and before the
entity’s state is dropped. It receives the state as &mut T. Keep the returned
Subscription alive for the callback to run.
Sourcepub fn observe_release_in<T>(
&self,
handle: &Entity<T>,
window: &Window,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
pub fn observe_release_in<T>(
&self,
handle: &Entity<T>,
window: &Window,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscriptionwhere
T: 'static,
Calls on_release when the entity behind handle is released, inside window.
Like App::observe_release, but the callback also receives window. The
callback doesn’t run if window has already closed when the entity is released.
Sourcepub fn observe_keystrokes(
&mut self,
f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
) -> Subscription
pub fn observe_keystrokes( &mut self, f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static, ) -> Subscription
Calls f for every keystroke that reaches any window of the app.
The callback runs after action and event handling has finished, and the event
names the action that handled the keystroke, if any. Keystrokes consumed by an
interceptor or a raw keyboard event handler are not observed, and a modifier
pressed on its own is observed when it is released. Use
App::intercept_keystrokes to see keystrokes before they are dispatched. Keep
the returned Subscription alive.
Sourcepub fn intercept_keystrokes(
&mut self,
f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
) -> Subscription
pub fn intercept_keystrokes( &mut self, f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static, ) -> Subscription
Calls f for every key-down that reaches any window, before it is dispatched.
Unlike App::observe_keystrokes, which runs after handling, the interceptor runs
first. Calling App::stop_propagation inside it stops the keystroke from reaching
action dispatch. Keep the returned Subscription alive.
Sourcepub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>)
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>)
Adds key bindings to the app’s keymap and redraws the windows.
A binding maps a keystroke, optionally limited to a KeyContext, to an action.
Bindings are matched during key dispatch. Calling this again adds to the existing
bindings, and App::clear_key_bindings removes them all.
§Examples
use gpui::{AppContext, KeyBinding, Keystroke, TestApp, actions};
actions!(app_bind_keys, [Save]);
let mut app = TestApp::new();
app.update(|cx| cx.bind_keys([KeyBinding::new("ctrl-s", Save, None)]));
app.read(|cx| {
let bindings = cx.all_bindings_for_input(&[Keystroke::parse("ctrl-s").unwrap()]);
assert_eq!(bindings.len(), 1);
assert_eq!(bindings[0].action().name(), "app_bind_keys::Save");
});See keyboard for context rules and input dispatch for how a keystroke picks an action.
Sourcepub fn clear_key_bindings(&mut self)
pub fn clear_key_bindings(&mut self)
Removes every key binding from the app’s keymap.
Sourcepub fn key_bindings(&self) -> Rc<RefCell<Keymap>>
pub fn key_bindings(&self) -> Rc<RefCell<Keymap>>
Returns the app’s keymap, shared with the app.
Borrow it to inspect bindings. Don’t hold the borrow across a call that changes
bindings, such as App::bind_keys, because the borrow panics.
Sourcepub fn on_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut Self) + 'static,
) -> &mut Self
pub fn on_action<A: Action>( &mut self, listener: impl Fn(&A, &mut Self) + 'static, ) -> &mut Self
Registers a handler that runs when an action is dispatched. Global handlers run in
the bubble phase, after the handlers in the element tree, and only if no earlier
handler stopped the propagation. Use it for app-wide
commands such as Quit, which should work with no window focused. Dispatch an action
with App::dispatch_action.
§Examples
use gpui::{AppContext, TestApp, actions};
use std::{cell::Cell, rc::Rc};
actions!(app_on_action, [Ping]);
let mut app = TestApp::new();
let pings = Rc::new(Cell::new(0));
app.update(|cx| {
let pings = pings.clone();
cx.on_action(move |_: &Ping, _| pings.set(pings.get() + 1));
});
app.update(|cx| cx.dispatch_action(&Ping));
assert_eq!(pings.get(), 1);Sourcepub fn stop_propagation(&mut self)
pub fn stop_propagation(&mut self)
Stops the current event or action from reaching later handlers.
Handlers for mouse events further down the z-order, and keyboard handlers higher
in the tree, don’t run after this. Call App::propagate to undo it before the
effects are flushed.
Sourcepub fn propagate(&mut self)
pub fn propagate(&mut self)
Lets the current event or action continue to later handlers.
Use it in a handler to pass the event on to the next handler, for example an
action listener on a parent element or a global handler from App::on_action.
It cancels an earlier App::stop_propagation in the same dispatch.
Sourcepub fn build_action(
&self,
name: &str,
data: Option<Value>,
) -> Result<Box<dyn Action>, ActionBuildError>
pub fn build_action( &self, name: &str, data: Option<Value>, ) -> Result<Box<dyn Action>, ActionBuildError>
Builds an action by its registered name, from JSON data such as a keymap entry.
data is the action’s parameters, or None for an action with no parameters.
Returns an ActionBuildError if the name is unknown or the data doesn’t match
the action’s type. Use it to load actions from a keymap file.
Sourcepub fn all_action_names(&self) -> &[&'static str]
pub fn all_action_names(&self) -> &[&'static str]
Returns the names of every action type that has been registered.
Registration makes an action buildable by name with App::build_action. It
does not bind the action to a key or a handler. For that, use App::bind_keys
and App::on_action.
Sourcepub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding>
pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding>
Returns the bindings that match input, ignoring key context.
The bindings come back in the order they were added. When you show one to the user, use the last one, because it takes precedence.
Sourcepub fn action_schemas(
&self,
generator: &mut SchemaGenerator,
) -> Vec<(&'static str, Option<Schema>)>
pub fn action_schemas( &self, generator: &mut SchemaGenerator, ) -> Vec<(&'static str, Option<Schema>)>
Returns each registered action name with its JSON schema, if it has one.
Use it to generate editor completions or to validate keymap files.
Sourcepub fn action_schema_by_name(
&self,
name: &str,
generator: &mut SchemaGenerator,
) -> Option<Option<Schema>>
pub fn action_schema_by_name( &self, name: &str, generator: &mut SchemaGenerator, ) -> Option<Option<Schema>>
Returns the JSON schema for the action named name.
Returns None if no action has that name. Returns Some(None) if the action
exists but has no schema, and Some(Some(schema)) if it has one.
Sourcepub fn deprecated_actions_to_preferred_actions(
&self,
) -> &HashMap<&'static str, &'static str>
pub fn deprecated_actions_to_preferred_actions( &self, ) -> &HashMap<&'static str, &'static str>
Returns a map from each deprecated action name to the name that replaces it.
Sourcepub fn action_deprecation_messages(
&self,
) -> &HashMap<&'static str, &'static str>
pub fn action_deprecation_messages( &self, ) -> &HashMap<&'static str, &'static str>
Returns a map from each deprecated action name to its deprecation message.
Sourcepub fn action_documentation(&self) -> &HashMap<&'static str, &'static str>
pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str>
Returns a map from each action name to its documentation string.
Sourcepub fn on_app_quit<Fut>(
&self,
on_quit: impl FnMut(&mut App) -> Fut + 'static,
) -> Subscription
pub fn on_app_quit<Fut>( &self, on_quit: impl FnMut(&mut App) -> Fut + 'static, ) -> Subscription
Calls on_quit when the app is about to quit, and waits for the returned future.
Use it to flush data to disk or close connections. The quit can’t be cancelled
at this point. Native apps wait up to SHUTDOWN_TIMEOUT for the futures, so
keep the work short. Keep the returned Subscription alive for the callback to
run.
Sourcepub fn on_app_restart(
&self,
on_restart: impl 'static + FnMut(&mut App),
) -> Subscription
pub fn on_app_restart( &self, on_restart: impl 'static + FnMut(&mut App), ) -> Subscription
Calls on_restart when the app is about to restart, before any App::on_app_quit handlers run.
Keep the returned Subscription alive for the callback to run.
Sourcepub fn on_window_closed(
&self,
on_closed: impl FnMut(&mut App, WindowId) + 'static,
) -> Subscription
pub fn on_window_closed( &self, on_closed: impl FnMut(&mut App, WindowId) + 'static, ) -> Subscription
Calls on_closed with the WindowId each time a window closes.
The window is no longer accessible when the callback runs. Keep the returned
Subscription alive for the callback to run.
Sourcepub fn is_action_available(&mut self, action: &dyn Action) -> bool
pub fn is_action_available(&mut self, action: &dyn Action) -> bool
Returns whether action would be handled if it were dispatched now.
Checks the active window’s focus path and its bindings, then the global listeners
from App::on_action. Use it to enable or disable menu items.
Replaces the app’s menu bar with menus.
Menu items that name an action show the key bindings from the keymap.
Returns the menu bar most recently set with App::set_menus, or None if none was set.
Sets the menu that appears when the user right-clicks the app’s Dock icon.
Runs the dock menu item at index action, as set with App::set_dock_menu.
Only Windows uses this path.
Sourcepub fn add_recent_document(&self, path: &Path)
pub fn add_recent_document(&self, path: &Path)
On macOS, adds path to the recent documents list, which the Dock menu shows.
Other platforms do nothing.
Call this when the user opens a document, so it appears in the recent list next time.
Sourcepub fn update_jump_list(
&self,
menus: Vec<MenuItem>,
entries: Vec<SmallVec<[PathBuf; 2]>>,
) -> Task<Vec<SmallVec<[PathBuf; 2]>>> ⓘ
pub fn update_jump_list( &self, menus: Vec<MenuItem>, entries: Vec<SmallVec<[PathBuf; 2]>>, ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> ⓘ
Replaces the Windows jump list with menus and the recent entries.
Only Windows uses this. It also sets the dock menu.
Sourcepub fn dispatch_action(&mut self, action: &dyn Action)
pub fn dispatch_action(&mut self, action: &dyn Action)
Dispatches action to the active window, or to the global listeners if no window is active.
In a window, the action follows the focus path, as a keystroke bound to it would.
Without an active window, it goes to the listeners from App::on_action. See
crate::Action for how actions work.
Sourcepub fn has_active_drag(&self) -> bool
pub fn has_active_drag(&self) -> bool
Returns whether a drag is in progress.
Sourcepub fn active_drag(&self) -> Option<&AnyDrag>
pub fn active_drag(&self) -> Option<&AnyDrag>
Returns the payload of the drag in progress, if any.
Sourcepub fn active_drag_cursor_style(&self) -> Option<CursorStyle>
pub fn active_drag_cursor_style(&self) -> Option<CursorStyle>
Returns the cursor style of the drag in progress, if it set one.
Sourcepub fn start_drag(&mut self, drag: AnyDrag)
pub fn start_drag(&mut self, drag: AnyDrag)
Starts a drag with drag as its payload. Refresh the windows after calling this, so the drag shows.
§Panics
Debug builds panic if a drag is already in progress.
Sourcepub fn stop_drag(&mut self, window: &Window) -> Option<Arc<dyn Any>>
pub fn stop_drag(&mut self, window: &Window) -> Option<Arc<dyn Any>>
Ends the drag in progress and returns its payload, if there was one.
Refresh the windows after calling this.
Sourcepub fn stop_active_drag(&mut self, window: &mut Window) -> bool
pub fn stop_active_drag(&mut self, window: &mut Window) -> bool
Stops active drag and clears any related effects.
Sourcepub fn set_active_drag_cursor_style(
&mut self,
cursor_style: CursorStyle,
window: &mut Window,
) -> bool
pub fn set_active_drag_cursor_style( &mut self, cursor_style: CursorStyle, window: &mut Window, ) -> bool
Sets the cursor shown during the active drag. Returns false if no drag is in progress.
Sourcepub fn set_prompt_builder(
&mut self,
renderer: impl Fn(PromptLevel, &str, Option<&str>, &[PromptButton], PromptHandle, &mut Window, &mut App) -> RenderablePromptHandle + 'static,
)
pub fn set_prompt_builder( &mut self, renderer: impl Fn(PromptLevel, &str, Option<&str>, &[PromptButton], PromptHandle, &mut Window, &mut App) -> RenderablePromptHandle + 'static, )
Replaces the default and platform prompts with renderer.
The renderer is called for each prompt the app shows. It receives the prompt’s
level, message, detail and buttons, and returns the handle that the window renders.
Use App::reset_prompt_builder to go back to the default prompts.
Sourcepub fn reset_prompt_builder(&mut self)
pub fn reset_prompt_builder(&mut self)
Reset the prompt builder to the default implementation.
Sourcepub fn remove_asset<A: Asset>(&mut self, source: &A::Source)
pub fn remove_asset<A: Asset>(&mut self, source: &A::Source)
Removes the cached result for source, so the next App::fetch_asset loads it again.
Sourcepub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool
pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool
Returns whether source is cached for asset type A, either loading or loaded.
This doesn’t start a load. Only available in tests and with the test-support feature.
Sourcepub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output>
pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output>
Starts loading an uncached asset and returns its result once available.
Pending loads and completed results are cached until Self::remove_asset.
This method does not subscribe a view to completion notifications.
Sourcepub fn focus_handle(&self) -> FocusHandle
pub fn focus_handle(&self) -> FocusHandle
Creates a new FocusHandle for tracking keyboard focus.
Attach the handle to an element with track_focus, and move focus to it with
Window::focus.
Sourcepub fn get_name(&self) -> Option<&'static str>
pub fn get_name(&self) -> Option<&'static str>
Returns the debugging name of this app, if one was set.
Only available in tests, with the test-support feature, or in debug builds.
Sourcepub fn can_select_mixed_files_and_dirs(&self) -> bool
pub fn can_select_mixed_files_and_dirs(&self) -> bool
Returns true if the platform file picker supports selecting a mix of files and directories.
Sourcepub fn drop_image(
&mut self,
image: Arc<RenderImage>,
current_window: Option<&mut Window>,
)
pub fn drop_image( &mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>, )
Removes an image from the sprite atlas on all windows.
A window that is being updated is not in App.windows, so pass it as current_window to
remove the image from it too.
This is a no-op if the image is not in the sprite atlas.
Sourcepub fn set_inspector_renderer(&mut self, f: InspectorRenderer)
pub fn set_inspector_renderer(&mut self, f: InspectorRenderer)
Sets the renderer for the inspector.
Sourcepub fn register_inspector_element<T: 'static, R: IntoElement, F>(
&mut self,
factory: impl 'static + Fn(&mut Window, &mut App) -> F,
)
pub fn register_inspector_element<T: 'static, R: IntoElement, F>( &mut self, factory: impl 'static + Fn(&mut Window, &mut App) -> F, )
Registers a renderer specific to an inspector state.
Sourcepub fn init_colors(&mut self)
pub fn init_colors(&mut self)
Sets the default Colors global, which cx.default_colors() returns.
Trait Implementations§
Source§impl<T> AppContext for Context<'_, T>
impl<T> AppContext for Context<'_, T>
Source§fn new<U: 'static>(
&mut self,
build_entity: impl FnOnce(&mut Context<'_, U>) -> U,
) -> Entity<U>
fn new<U: 'static>( &mut self, build_entity: impl FnOnce(&mut Context<'_, U>) -> U, ) -> Entity<U>
build_entity, and returns a handle to it. Read moreSource§fn reserve_entity<U: 'static>(&mut self) -> Reservation<U>
fn reserve_entity<U: 'static>(&mut self) -> Reservation<U>
Reservation for it. Read moreSource§fn insert_entity<U: 'static>(
&mut self,
reservation: Reservation<U>,
build_entity: impl FnOnce(&mut Context<'_, U>) -> U,
) -> Entity<U>
fn insert_entity<U: 'static>( &mut self, reservation: Reservation<U>, build_entity: impl FnOnce(&mut Context<'_, U>) -> U, ) -> Entity<U>
Source§fn update_entity<U: 'static, R>(
&mut self,
handle: &Entity<U>,
update: impl FnOnce(&mut U, &mut Context<'_, U>) -> R,
) -> R
fn update_entity<U: 'static, R>( &mut self, handle: &Entity<U>, update: impl FnOnce(&mut U, &mut Context<'_, U>) -> R, ) -> R
Source§fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> GpuiBorrow<'a, E>where
E: 'static,
fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> GpuiBorrow<'a, E>where
E: 'static,
Source§fn read_entity<U, R>(
&self,
handle: &Entity<U>,
read: impl FnOnce(&U, &App) -> R,
) -> Rwhere
U: 'static,
fn read_entity<U, R>(
&self,
handle: &Entity<U>,
read: impl FnOnce(&U, &App) -> R,
) -> Rwhere
U: 'static,
read. Read moreSource§fn notify(&mut self, entity_id: EntityId)
fn notify(&mut self, entity_id: EntityId)
entity_id changed. Its observers run and windows
that show it redraw. Read moreSource§fn emit<EntityType, EventType>(
&mut self,
entity: &Entity<EntityType>,
event: EventType,
)where
EntityType: EventEmitter<EventType>,
EventType: 'static,
fn emit<EntityType, EventType>(
&mut self,
entity: &Entity<EntityType>,
event: EventType,
)where
EntityType: EventEmitter<EventType>,
EventType: 'static,
Source§fn update_window<R, F>(
&mut self,
window: AnyWindowHandle,
update: F,
) -> Result<R>
fn update_window<R, F>( &mut self, window: AnyWindowHandle, update: F, ) -> Result<R>
f with the window’s root view, the window and the app, and returns the
result. Read moreSource§fn with_window<R>(
&mut self,
entity_id: EntityId,
f: impl FnOnce(&mut Window, &mut App) -> R,
) -> Option<R>
fn with_window<R>( &mut self, entity_id: EntityId, f: impl FnOnce(&mut Window, &mut App) -> R, ) -> Option<R>
f with the window that most recently rendered the entity entity_id, and
returns the result. Read moreSource§fn read_window<U, R>(
&self,
window: &WindowHandle<U>,
read: impl FnOnce(Entity<U>, &App) -> R,
) -> Result<R>where
U: 'static,
fn read_window<U, R>(
&self,
window: &WindowHandle<U>,
read: impl FnOnce(Entity<U>, &App) -> R,
) -> Result<R>where
U: 'static,
window with the app, and returns the result. Read moreSource§fn background_spawn<R>(
&self,
future: impl Future<Output = R> + Send + 'static,
) -> Task<R> ⓘwhere
R: Send + 'static,
fn background_spawn<R>(
&self,
future: impl Future<Output = R> + Send + 'static,
) -> Task<R> ⓘwhere
R: Send + 'static,
future on the background executor and returns a task for its result. Read moreSource§fn insert_global_entity<E: 'static>(&mut self, entity: Entity<E>)
fn insert_global_entity<E: 'static>(&mut self, entity: Entity<E>)
entity alive without a handle to it. Read moreSource§fn remove_global_entity<E: 'static>(&mut self, entity: &Entity<E>)
fn remove_global_entity<E: 'static>(&mut self, entity: &Entity<E>)
entity alive. It’s dropped once no other handle refers to it.Source§fn global_entities<E: 'static>(&self) -> impl Iterator<Item = Entity<E>>
fn global_entities<E: 'static>(&self) -> impl Iterator<Item = Entity<E>>
AppContext::insert_global_entity whose type is
T.Source§impl<T> BorrowMut<App> for Context<'_, T>
impl<T> BorrowMut<App> for Context<'_, T>
Source§fn borrow_mut(&mut self) -> &mut App
fn borrow_mut(&mut self) -> &mut App
Auto Trait Implementations§
impl<'a, T> !RefUnwindSafe for Context<'a, T>
impl<'a, T> !Send for Context<'a, T>
impl<'a, T> !Sync for Context<'a, T>
impl<'a, T> !UnwindSafe for Context<'a, T>
impl<'a, T> Freeze for Context<'a, T>where
WeakEntity<T>: Freeze,
impl<'a, T> Unpin for Context<'a, T>where
WeakEntity<T>: Unpin,
impl<'a, T> UnsafeUnpin for Context<'a, T>where
WeakEntity<T>: UnsafeUnpin,
Blanket Implementations§
Source§impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for Swhere
T: Real + Zero + Arithmetics + Clone,
Swp: WhitePoint<T>,
Dwp: WhitePoint<T>,
D: AdaptFrom<S, Swp, Dwp, T>,
impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for Swhere
T: Real + Zero + Arithmetics + Clone,
Swp: WhitePoint<T>,
Dwp: WhitePoint<T>,
D: AdaptFrom<S, Swp, Dwp, T>,
Source§fn adapt_into_using<M>(self, method: M) -> Dwhere
M: TransformMatrix<T>,
fn adapt_into_using<M>(self, method: M) -> Dwhere
M: TransformMatrix<T>,
replaced by palette::chromatic_adaptation::AdaptIntoUnclamped
Source§fn adapt_into(self) -> D
fn adapt_into(self) -> D
replaced by palette::chromatic_adaptation::AdaptIntoUnclamped
Source§impl<T, C> AdaptIntoUnclamped<T> for Cwhere
T: AdaptFromUnclamped<C>,
impl<T, C> AdaptIntoUnclamped<T> for Cwhere
T: AdaptFromUnclamped<C>,
Source§type Scalar = <T as AdaptFromUnclamped<C>>::Scalar
type Scalar = <T as AdaptFromUnclamped<C>>::Scalar
Source§fn adapt_into_unclamped_with<M>(self) -> Twhere
M: LmsToXyz<<C as AdaptIntoUnclamped<T>>::Scalar> + XyzToLms<<C as AdaptIntoUnclamped<T>>::Scalar>,
fn adapt_into_unclamped_with<M>(self) -> Twhere
M: LmsToXyz<<C as AdaptIntoUnclamped<T>>::Scalar> + XyzToLms<<C as AdaptIntoUnclamped<T>>::Scalar>,
Source§impl<T, C> ArraysFrom<C> for Twhere
C: IntoArrays<T>,
impl<T, C> ArraysFrom<C> for Twhere
C: IntoArrays<T>,
Source§fn arrays_from(colors: C) -> T
fn arrays_from(colors: C) -> T
Source§impl<T, C> ArraysInto<C> for Twhere
C: FromArrays<T>,
impl<T, C> ArraysInto<C> for Twhere
C: FromArrays<T>,
Source§fn arrays_into(self) -> C
fn arrays_into(self) -> C
Source§impl<C> BorrowAppContext for C
impl<C> BorrowAppContext for C
Source§fn set_global<G>(&mut self, global: G)where
G: Global,
fn set_global<G>(&mut self, global: G)where
G: Global,
T to global, replacing any previous value. Observers of
the global are notified when the current update finishes.Source§fn update_default_global<G, R>(
&mut self,
f: impl FnOnce(&mut G, &mut C) -> R,
) -> R
fn update_default_global<G, R>( &mut self, f: impl FnOnce(&mut G, &mut C) -> R, ) -> R
BorrowAppContext::update_global, but first sets G::default() if no
global of type G has been set.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for Uwhere
T: FromCam16Unclamped<WpParam, U>,
impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for Uwhere
T: FromCam16Unclamped<WpParam, U>,
Source§type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar
type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar
parameters when converting.Source§fn cam16_into_unclamped(
self,
parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>,
) -> T
fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T
self into C, using the provided parameters.impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T, C> ComponentsFrom<C> for Twhere
C: IntoComponents<T>,
impl<T, C> ComponentsFrom<C> for Twhere
C: IntoComponents<T>,
Source§fn components_from(colors: C) -> T
fn components_from(colors: C) -> T
Source§impl<T, C> ComponentsInto<C> for T
impl<T, C> ComponentsInto<C> for T
Source§fn components_into(self) -> C
fn components_into(self) -> C
Source§impl<T> FromAngle<T> for T
impl<T> FromAngle<T> for T
Source§fn from_angle(angle: T) -> T
fn from_angle(angle: T) -> T
angle.Source§impl<T, U> FromStimulus<U> for Twhere
U: IntoStimulus<T>,
impl<T, U> FromStimulus<U> for Twhere
U: IntoStimulus<T>,
Source§fn from_stimulus(other: U) -> T
fn from_stimulus(other: U) -> T
other into Self, while performing the appropriate scaling,
rounding and clamping.Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T, U> IntoAngle<U> for Twhere
U: FromAngle<T>,
impl<T, U> IntoAngle<U> for Twhere
U: FromAngle<T>,
Source§fn into_angle(self) -> U
fn into_angle(self) -> U
T.Source§impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for Uwhere
T: Cam16FromUnclamped<WpParam, U>,
impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for Uwhere
T: Cam16FromUnclamped<WpParam, U>,
Source§type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar
type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar
parameters when converting.Source§fn into_cam16_unclamped(
self,
parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>,
) -> T
fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T
self into C, using the provided parameters.Source§impl<T, U> IntoColor<U> for Twhere
U: FromColor<T>,
impl<T, U> IntoColor<U> for Twhere
U: FromColor<T>,
Source§fn into_color(self) -> U
fn into_color(self) -> U
Source§impl<T, U> IntoColorUnclamped<U> for Twhere
U: FromColorUnclamped<T>,
impl<T, U> IntoColorUnclamped<U> for Twhere
U: FromColorUnclamped<T>,
Source§fn into_color_unclamped(self) -> U
fn into_color_unclamped(self) -> U
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoStimulus<T> for T
impl<T> IntoStimulus<T> for T
Source§fn into_stimulus(self) -> T
fn into_stimulus(self) -> T
self into T, while performing the appropriate scaling,
rounding and clamping.Source§impl<T> Pointable for T
impl<T> Pointable for T
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T, C> TryComponentsInto<C> for Twhere
C: TryFromComponents<T>,
impl<T, C> TryComponentsInto<C> for Twhere
C: TryFromComponents<T>,
Source§type Error = <C as TryFromComponents<T>>::Error
type Error = <C as TryFromComponents<T>>::Error
try_into_colors fails to cast.Source§fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>
fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>
Source§impl<T, U> TryIntoColor<U> for Twhere
U: TryFromColor<T>,
impl<T, U> TryIntoColor<U> for Twhere
U: TryFromColor<T>,
Source§fn try_into_color(self) -> Result<U, OutOfBounds<U>>
fn try_into_color(self) -> Result<U, OutOfBounds<U>>
OutOfBounds error is returned which contains
the unclamped color. Read more