pub struct App { /* private fields */ }Expand description
The state of a running application: its entities, windows, globals and key bindings.
You get a &mut App from the callback passed to Application::run, from
TestApp::update, and from any Context, which derefs to App. Read an
entity with Entity::read, and create one with AppContext::new. Callbacks that
run after an await can’t hold the App, so they use an AsyncApp instead.
App is not Clone. Keep one per app, and use the references you are given. It
is not Send, so it only runs on the main thread.
§Examples
let mut app = TestApp::new();
let count = app.update(|cx| cx.new(|_| 1));
app.read(|cx| assert_eq!(*count.read(cx), 1));See contexts for how App relates to the
other context types.
Implementations§
Source§impl App
impl 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 AppContext for App
impl AppContext for App
Source§fn new<T: 'static>(
&mut self,
build_entity: impl FnOnce(&mut Context<'_, T>) -> T,
) -> Entity<T>
fn new<T: 'static>( &mut self, build_entity: impl FnOnce(&mut Context<'_, T>) -> T, ) -> Entity<T>
Source§fn update_entity<T: 'static, R>(
&mut self,
handle: &Entity<T>,
update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
) -> R
fn update_entity<T: 'static, R>( &mut self, handle: &Entity<T>, update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R, ) -> R
Updates the entity referenced by the given handle. The function is passed a mutable reference to the
entity along with a Context for the entity.
Source§fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T>
Reservation for it. Read moreSource§fn insert_entity<T: 'static>(
&mut self,
reservation: Reservation<T>,
build_entity: impl FnOnce(&mut Context<'_, T>) -> T,
) -> Entity<T>
fn insert_entity<T: 'static>( &mut self, reservation: Reservation<T>, build_entity: impl FnOnce(&mut Context<'_, T>) -> T, ) -> Entity<T>
Source§fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>where
T: 'static,
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>where
T: 'static,
Source§fn read_entity<T, R>(
&self,
handle: &Entity<T>,
read: impl FnOnce(&T, &App) -> R,
) -> Rwhere
T: 'static,
fn read_entity<T, R>(
&self,
handle: &Entity<T>,
read: impl FnOnce(&T, &App) -> R,
) -> Rwhere
T: '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<T, F>(
&mut self,
handle: AnyWindowHandle,
update: F,
) -> Result<T>
fn update_window<T, F>( &mut self, handle: AnyWindowHandle, update: F, ) -> Result<T>
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<T, R>(
&self,
window: &WindowHandle<T>,
read: impl FnOnce(Entity<T>, &App) -> R,
) -> Result<R>where
T: 'static,
fn read_window<T, R>(
&self,
window: &WindowHandle<T>,
read: impl FnOnce(Entity<T>, &App) -> R,
) -> Result<R>where
T: '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<T: 'static>(&mut self, entity: Entity<T>)
fn insert_global_entity<T: 'static>(&mut self, entity: Entity<T>)
entity alive without a handle to it. Read moreSource§fn remove_global_entity<T: 'static>(&mut self, entity: &Entity<T>)
fn remove_global_entity<T: 'static>(&mut self, entity: &Entity<T>)
entity alive. It’s dropped once no other handle refers to it.Source§fn global_entities<T: 'static>(&self) -> impl Iterator<Item = Entity<T>>
fn global_entities<T: 'static>(&self) -> impl Iterator<Item = Entity<T>>
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
Source§impl DefaultColors for App
impl DefaultColors for App
Source§fn default_colors(&self) -> &Arc<Colors> ⓘ
fn default_colors(&self) -> &Arc<Colors> ⓘ
Colors that App::init_colors set.Auto Trait Implementations§
impl !Freeze for App
impl !RefUnwindSafe for App
impl !Send for App
impl !Sync for App
impl !UnwindSafe for App
impl Unpin for App
impl UnsafeUnpin for App
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