Skip to main content

App

Struct App 

Source
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

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 AppContext for App

Source§

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

Builds an entity that is owned by the application.

The given function will be invoked with a Context and must return an object representing the entity. An Entity handle will be returned, which can be used to access the entity in a context.

Source§

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>

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

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

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

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

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

fn read_entity<T, R>( &self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R, ) -> R
where T: '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<T, F>( &mut self, handle: AnyWindowHandle, update: F, ) -> Result<T>
where F: FnOnce(AnyView, &mut Window, &mut App) -> T,

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<T, R>( &self, window: &WindowHandle<T>, read: impl FnOnce(Entity<T>, &App) -> R, ) -> Result<R>
where T: '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<T: 'static>(&mut self, entity: Entity<T>)

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

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

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

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

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 DefaultColors for App

Source§

fn default_colors(&self) -> &Arc<Colors> ⓘ

Returns the app-wide 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 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<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