Skip to main content

Context

Struct Context 

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

Source

pub fn entity_id(&self) -> EntityId

Returns the id of the entity this context works on.

Source

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.

Source

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.

Source

pub fn observe<W>( &mut self, entity: &Entity<W>, on_notify: impl FnMut(&mut T, Entity<W>, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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();
});

See ownership and data flow.

Source

pub fn observe_self( &mut self, on_event: impl FnMut(&mut T, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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.

Source

pub fn subscribe<T2, Evt>( &mut self, entity: &Entity<T2>, on_event: impl FnMut(&mut T, Entity<T2>, &Evt, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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 });
});
Source

pub fn subscribe_self<Evt>( &mut self, on_event: impl FnMut(&mut T, &Evt, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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.

Source

pub fn on_release( &self, on_release: impl FnOnce(&mut T, &mut App) + 'static, ) -> Subscription
where 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.

Source

pub fn observe_release<T2>( &self, entity: &Entity<T2>, on_release: impl FnOnce(&mut T, &mut T2, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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.

Source

pub fn observe_global<G: 'static>( &mut self, f: impl FnMut(&mut T, &mut Context<'_, T>) + 'static, ) -> Subscription
where 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.

Source

pub fn on_app_restart( &self, on_restart: impl FnMut(&mut T, &mut App) + 'static, ) -> Subscription
where 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.

Source

pub fn on_app_quit<Fut>( &self, on_quit: impl FnMut(&mut T, &mut Context<'_, T>) -> Fut + 'static, ) -> Subscription
where Fut: 'static + Future<Output = ()>, T: 'static,

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.

Source

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();
    }
}

See ownership and data flow.

Source

pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> ⓘ
where T: 'static, AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncApp) -> R + 'static, R: 'static,

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.

Source

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);

See ownership and data flow.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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, ) -> Subscription
where 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.

Source

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, ) -> Subscription
where 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.

Source

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.

Source

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, ) -> Subscription
where 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.

Source

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.

Source

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.

Source

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).

Source

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.

Source

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.

Source

pub fn observe_button_layout_changed( &self, window: &mut Window, callback: impl FnMut(&mut T, &mut Window, &mut Context<'_, T>) + 'static, ) -> Subscription

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn spawn_in<AsyncFn, R>(&self, window: &Window, f: AsyncFn) -> Task<R> ⓘ
where R: 'static, AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,

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.

Source

pub fn spawn_in_with_priority<AsyncFn, R>( &self, priority: Priority, window: &Window, f: AsyncFn, ) -> Task<R> ⓘ
where R: 'static, AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,

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.

Source

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.

Source

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.

Source

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>

Source

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 });
});

See ownership and data flow.

Methods from Deref<Target = App>§

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper>

Returns the keyboard mapper for the active layout.

Source

pub fn on_keyboard_layout_change<F>(&self, callback: F) -> Subscription
where F: 'static + FnMut(&mut App),

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.

Source

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.

Source

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.

Source

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.

Source

pub fn cursor_hide_mode(&self) -> CursorHideMode

Returns the policy that decides when GPUI hides the cursor while typing.

Defaults to CursorHideMode::OnTypingAndAction.

Source

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.

Source

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.

See App::set_cursor_hide_mode.

Source

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.

Source

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.

Source

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.

Source

pub fn observe<W>( &mut self, entity: &Entity<W>, on_notify: impl FnMut(Entity<W>, &mut App) + 'static, ) -> Subscription
where 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);

See ownership and data flow.

Source

pub fn subscribe<T, Event>( &mut self, entity: &Entity<T>, on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static, ) -> Subscription
where 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);
Source

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.

Source

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.

Source

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

Source

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.

Source

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.

Source

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));
Source

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.

Source

pub fn hide(&self)

Hides the app, the same as choosing Hide from the app menu.

Source

pub fn hide_other_apps(&self)

Hides all other applications.

Source

pub fn unhide_other_apps(&self)

Shows the applications hidden by App::hide_other_apps.

Source

pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>

Returns the connected displays.

Source

pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>

Returns the primary display, or None if the platform reports none.

Source

pub fn is_screen_capture_supported(&self) -> bool

Returns whether App::screen_capture_sources can return sources on this platform.

Source

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.

Source

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.

Source

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.

Source

pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> ⓘ

Prevents idle sleep while the returned guard is held.

Source

pub fn on_thermal_state_change<F>(&self, callback: F) -> Subscription
where F: 'static + FnMut(&mut App),

Calls callback when the system’s thermal state changes.

The subscription stays active while you hold it.

Source

pub fn on_system_sleep<F>(&self, callback: F) -> Subscription
where F: 'static + FnMut(&mut App),

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.

Source

pub fn observe_displays<F>(&self, callback: F) -> Subscription
where F: 'static + FnMut(DisplayEvent, &mut App),

Invokes a handler when a display is connected, disconnected, or its properties change.

Source

pub fn on_system_wake<F>(&self, callback: F) -> Subscription
where F: 'static + FnMut(&mut App),

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn supports_haptic_feedback(&self) -> bool

Returns whether App::play_haptic_feedback does anything on this platform.

Source

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.

Source

pub fn button_layout(&self) -> Option<WindowButtonLayout>

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.

Source

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.

Source

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.

Source

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.

Source

pub fn text_rendering_mode(&self) -> TextRenderingMode

Returns how text is currently rasterized. See App::set_text_rendering_mode.

Source

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"));
});
Source

pub fn read_from_primary(&self) -> Option<ClipboardItem>

Reads data from the primary selection buffer. Only available on Linux and FreeBSD.

Source

pub fn write_to_primary(&self, item: ClipboardItem)

Writes data to the primary selection buffer. Only available on Linux and FreeBSD.

Source

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.

Source

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.

Source

pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> ⓘ

Removes the credentials stored for url from the platform keychain.

Source

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.

Source

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.

Source

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.

Source

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).

Source

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.

Source

pub fn on_system_notification_response<F>(&self, callback: F)
where F: 'static + FnMut(SystemNotificationResponse, &mut App),

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.

Source

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.

Source

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.

Source

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.

See Application::path_for_auxiliary_executable.

Source

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.

Source

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.

Source

pub fn reveal_path(&self, path: &Path)

Shows path in the platform’s file manager, such as Finder on macOS.

Source

pub fn open_with_system(&self, path: &Path)

Opens path with the system’s default application for its file type.

Source

pub fn should_auto_hide_scrollbars(&self) -> bool

Returns whether the user has configured scrollbars to auto-hide at the platform level.

Source

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.

Source

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.

Source

pub fn http_client(&self) -> Arc<dyn HttpClient> ⓘ

Returns the app’s HTTP client. See Application::with_http_client.

Source

pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>)

Replaces the HTTP client that App::http_client returns.

Source

pub fn set_quit_mode(&mut self, mode: QuitMode)

Sets when the app quits on its own. See QuitMode.

Defaults to QuitMode::Default.

Source

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.

Source

pub fn svg_renderer(&self) -> SvgRenderer

Returns the SVG renderer that draws the app’s SVG assets.

Source

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.

Source

pub fn to_async(&self) -> AsyncApp

Returns an AsyncApp that can be held across await points.

The AsyncApp holds the app weakly, so it does not keep the app alive. Use it in tasks that outlive the current update.

Source

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.

Source

pub fn is_test(&self) -> bool

Whether this app runs on the deterministic test scheduler. See BackgroundExecutor::is_test.

Source

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).

Source

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.

Source

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.

Source

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));
Source

pub fn assets(&self) -> &Arc<AssetRegistry> ⓘ

Returns the asset registry that the app loads assets from. See Application::with_assets.

Source

pub fn text_system(&self) -> &Arc<TextSystem> ⓘ

Returns the app’s TextSystem, which shapes and rasterizes text.

Source

pub fn has_global<G: Global>(&self) -> bool

Returns whether a global of type G has been set.

Source

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.

Source

pub fn try_global<G: Global>(&self) -> Option<&G>

Returns the global of type G, or None if it has not been set.

Source

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.

Source

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.

Source

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"));
Source

pub fn clear_globals(&mut self)

Clear all stored globals. Does not notify global observers.

Source

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.

Source

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);
Source

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.

Source

pub fn observe_release<T>( &self, handle: &Entity<T>, on_release: impl FnOnce(&mut T, &mut App) + 'static, ) -> Subscription
where 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.

Source

pub fn observe_release_in<T>( &self, handle: &Entity<T>, window: &Window, on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static, ) -> Subscription
where 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.

Source

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.

Source

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.

Source

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.

Source

pub fn clear_key_bindings(&mut self)

Removes every key binding from the app’s keymap.

Source

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.

Source

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);
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn action_deprecation_messages( &self, ) -> &HashMap<&'static str, &'static str>

Returns a map from each deprecated action name to its deprecation message.

Source

pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str>

Returns a map from each action name to its documentation string.

Source

pub fn on_app_quit<Fut>( &self, on_quit: impl FnMut(&mut App) -> Fut + 'static, ) -> Subscription
where Fut: 'static + Future<Output = ()>,

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.

Source

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.

Source

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.

Source

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.

Source

pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>)

Replaces the app’s menu bar with menus.

Menu items that name an action show the key bindings from the keymap.

Source

pub fn get_menus(&self) -> Option<Vec<OwnedMenu>>

Returns the menu bar most recently set with App::set_menus, or None if none was set.

Source

pub fn set_dock_menu(&self, menus: Vec<MenuItem>)

Sets the menu that appears when the user right-clicks the app’s Dock icon.

Source

pub fn perform_dock_menu_action(&self, action: usize)

Runs the dock menu item at index action, as set with App::set_dock_menu.

Only Windows uses this path.

Source

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.

Source

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.

Source

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.

Source

pub fn has_active_drag(&self) -> bool

Returns whether a drag is in progress.

Source

pub fn active_drag(&self) -> Option<&AnyDrag>

Returns the payload of the drag in progress, if any.

Source

pub fn active_drag_cursor_style(&self) -> Option<CursorStyle>

Returns the cursor style of the drag in progress, if it set one.

Source

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.

Source

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.

Source

pub fn stop_active_drag(&mut self, window: &mut Window) -> bool

Stops active drag and clears any related effects.

Source

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.

Source

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.

Source

pub fn reset_prompt_builder(&mut self)

Reset the prompt builder to the default implementation.

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn set_inspector_renderer(&mut self, f: InspectorRenderer)

Sets the renderer for the inspector.

Source

pub fn register_inspector_element<T: 'static, R: IntoElement, F>( &mut self, factory: impl 'static + Fn(&mut Window, &mut App) -> F, )
where F: 'static + FnMut(InspectorElementId, &T, &mut Window, &mut App) -> R,

Registers a renderer specific to an inspector state.

Source

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>

Source§

fn new<U: 'static>( &mut self, build_entity: impl FnOnce(&mut Context<'_, U>) -> U, ) -> Entity<U>

Creates an entity from build_entity, and returns a handle to it. Read more
Source§

fn reserve_entity<U: 'static>(&mut self) -> Reservation<U>

Reserves an entity slot, and returns a Reservation for it. Read more
Source§

fn insert_entity<U: 'static>( &mut self, reservation: Reservation<U>, build_entity: impl FnOnce(&mut Context<'_, U>) -> U, ) -> Entity<U>

Creates the entity for a Reservation from AppContext::reserve_entity. Read more
Source§

fn update_entity<U: 'static, R>( &mut self, handle: &Entity<U>, update: impl FnOnce(&mut U, &mut Context<'_, U>) -> R, ) -> R

Runs update with the entity and a Context for it, and returns the result. Read more
Source§

fn as_mut<'a, E>(&'a mut self, handle: &Entity<E>) -> GpuiBorrow<'a, E>
where E: 'static,

Borrows the entity mutably, without a closure. Read more
Source§

fn read_entity<U, R>( &self, handle: &Entity<U>, read: impl FnOnce(&U, &App) -> R, ) -> R
where U: 'static,

Reads the entity with a shared borrow, and returns the result of read. Read more
Source§

fn notify(&mut self, entity_id: EntityId)

Tells GPUI that the entity with entity_id changed. Its observers run and windows that show it redraw. Read more
Source§

fn emit<EntityType, EventType>( &mut self, entity: &Entity<EntityType>, event: EventType, )
where EntityType: EventEmitter<EventType>, EventType: 'static,

Emits event from entity. Read more
Source§

fn update_window<R, F>( &mut self, window: AnyWindowHandle, update: F, ) -> Result<R>
where F: FnOnce(AnyView, &mut Window, &mut App) -> R,

Runs f with the window’s root view, the window and the app, and returns the result. Read more
Source§

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 rendered the entity entity_id, and returns the result. Read more
Source§

fn read_window<U, R>( &self, window: &WindowHandle<U>, read: impl FnOnce(Entity<U>, &App) -> R, ) -> Result<R>
where U: 'static,

Reads the root view of window with the app, and returns the result. Read more
Source§

fn background_spawn<R>( &self, future: impl Future<Output = R> + Send + 'static, ) -> Task<R> ⓘ
where R: Send + 'static,

Runs future on the background executor and returns a task for its result. Read more
Source§

fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
where G: Global,

Calls callback with the global of type G and the app, and returns the result. Read more
Source§

fn insert_global_entity<E: 'static>(&mut self, entity: Entity<E>)

Keeps entity alive without a handle to it. Read more
Source§

fn remove_global_entity<E: 'static>(&mut self, entity: &Entity<E>)

Stops keeping entity alive. It’s dropped once no other handle refers to it.
Source§

fn global_entities<E: 'static>(&self) -> impl Iterator<Item = Entity<E>>

Returns the entities stored with AppContext::insert_global_entity whose type is T.
Source§

impl<T> Borrow<App> for Context<'_, T>

Source§

fn borrow(&self) -> &App

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<App> for Context<'_, T>

Source§

fn borrow_mut(&mut self) -> &mut App

Mutably borrows from an owned value. Read more
Source§

impl<'a, T> Deref for Context<'a, T>

Source§

type Target = App

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<'a, T> DerefMut for Context<'a, T>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

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>

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where 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) -> D
where M: TransformMatrix<T>,

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

👎Deprecated since 0.7.7:

replaced by palette::chromatic_adaptation::AdaptIntoUnclamped

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T, C> AdaptIntoUnclamped<T> for C
where T: AdaptFromUnclamped<C>,

Source§

type Scalar = <T as AdaptFromUnclamped<C>>::Scalar

The number type that’s used as the color’s components.
Source§

fn adapt_into_unclamped_with<M>(self) -> T

Adapt a color of type Self into a color of type T, using the custom matrix M. Read more
Source§

fn adapt_into_unclamped(self) -> T
where Bradford: LmsToXyz<Self::Scalar> + XyzToLms<Self::Scalar>,

Adapt a color of type Self into a color of type T, using the Bradford matrix. Read more
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<C> BorrowAppContext for C
where C: BorrowMut<App>,

Source§

fn set_global<G>(&mut self, global: G)
where G: Global,

Sets the global of type T to global, replacing any previous value. Observers of the global are notified when the current update finishes.
Source§

fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut C) -> R) -> R
where G: Global,

Updates the global of type G with f, and returns the result of f. Read more
Source§

fn update_default_global<G, R>( &mut self, f: impl FnOnce(&mut G, &mut C) -> R, ) -> R
where G: Global + Default,

Like BorrowAppContext::update_global, but first sets G::default() if no global of type G has been set.
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<T, C> ComponentsInto<C> for T

Source§

fn components_into(self) -> C

Cast this collection of color components into a collection of colors. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more