Skip to main content

Crate gpui

Crate gpui 

Source
Expand description

GPUI is a Rust framework for building interfaces on macOS, Windows, Linux, and the web. It lays out element trees on the CPU and paints them with a GPU renderer. You keep application state in entities, build the interface from that state, and notify GPUI after changes that should appear on screen.

GPUI was built by Zed Industries to make the Zed editor. This crate is GPUI Community Edition (GPUI-CE), a fork maintained for standalone applications. It is published as gpui-ce and imported as gpui.

This program opens a window containing a counter. The click handler increments the count and calls notify; the next render puts the new count in the button:

use gpui::{App, Context, Window, WindowOptions, div, prelude::*, rgb};

struct Counter {
    count: usize,
}

impl Render for Counter {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        div()
            .size_full()
            .flex()
            .items_center()
            .justify_center()
            .bg(rgb(0xf5f5f4))
            .child(
                div()
                    .id("button")
                    .px_4()
                    .py_2()
                    .rounded_md()
                    .bg(rgb(0x2563eb))
                    .text_color(rgb(0xffffff))
                    .cursor_pointer()
                    .child(format!("Clicked {} times", self.count))
                    .on_click(cx.listener(|counter, _event, _window, cx| {
                        counter.count += 1;
                        cx.notify();
                    })),
            )
    }
}

fn main() {
    gpui_platform::application().run(|cx: &mut App| {
        cx.open_window(WindowOptions::default(), |_window, cx| {
            cx.new(|_cx| Counter { count: 0 })
        })
        .unwrap();
        cx.activate(true);
    });
}

The counter also runs without a display. TestApp sends two clicks to a headless window, and the assertion checks the resulting state:

use gpui::{MouseButton, TestApp, point, px};

let mut app = TestApp::new();
let mut window = app.open_window(|_window, _cx| Counter { count: 0 });

window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);
window.simulate_click(point(px(10.), px(10.)), MouseButton::Left);

assert_eq!(window.read(|counter, _cx| counter.count), 2);

§Overview

The counter uses three parts of GPUI: an entity to hold the count, a view to read it, and elements to display it and receive clicks. Their lifetimes differ: the entity survives between frames, while each render builds a new element tree.

  • App owns entity state. App::new stores a value and returns an Entity<T>: a cloneable handle for reading and updating it through a context. Entities connect shared state to observers and dependent views; ownership explains their lifetimes.
  • A view is an entity that can Render. When a view renders, it builds a fresh tree of elements. A view keeps its state between frames; the elements it returns are thrown away after they’re drawn.
  • Elements describe the interface. div is the workhorse: a box with children, styles and event handlers. Text, img, svg, uniform_list and canvas cover the rest, and you can write your own by implementing Element. Style them with Styled methods named after Tailwind CSS classes, such as .flex(), .p_4() and .rounded_md(), and GPUI lays them out with flexbox and grid.
  • Contexts give you access. Callbacks receive the access they need: App for application-wide services, Context<T> while you work on one entity, and Window for the window being drawn or handling input.
  • Changes need notification. Mutating an entity’s fields alone doesn’t schedule a redraw. Context::notify informs observers and marks dependent windows for redraw. The frame cycle connects this notification to layout and painting.
  • Input follows hit testing and focus. Mouse dispatch uses element hitboxes; keyboard dispatch follows the path to the focused element. Key bindings map keystrokes to typed actions. Input dispatch explains capture, bubbling, and propagation.

The concepts section explains each of these ideas in depth.

§Getting started

Add GPUI and its platform crate to Cargo.toml. The platform crate picks the right windowing and rendering backends for the target you build for:

[dependencies]
gpui = { package = "gpui-ce", version = "0.2" }
gpui_platform = { package = "gpui_ce_platform", version = "0.1" }

Then follow the tutorial, which builds a todo app one idea at a time. Start a project covers system requirements for each platform.

The rest of this page is a map of GPUI:

§How do I…

These snippets cover common tasks. Each links to a guide with setup and related behavior.

§Respond to a click

Give the element an id so GPUI can track it between frames, then register a handler. Context::listener gives the handler mutable access to your view:

div()
    .id("increment")
    .child("Add one")
    .on_click(cx.listener(|counter, _event, _window, cx| {
        counter.count += 1;
        cx.notify();
    }))

See mouse and touch input.

§Bind a keyboard shortcut

Declare an action, bind a keystroke to it, and handle it on an element that has focus or contains the focused element:

use gpui::{App, KeyBinding, actions};

actions!(editor, [Save]);

fn bind_keys(cx: &mut App) {
    cx.bind_keys([KeyBinding::new("cmd-s", Save, Some("Editor"))]);
}
div()
    .key_context("Editor")
    .track_focus(&self.focus_handle)
    .on_action(cx.listener(Editor::save))

See keyboard input.

§Run work without freezing the window

Context::spawn runs async code on the main thread, where it can update entities. Move expensive work to a thread pool with background_spawn and await the result:

impl Report {
    fn refresh(&mut self, text: String, cx: &mut Context<Self>) {
        self.task = Some(cx.spawn(async move |this, cx| {
            let summary = cx.background_spawn(async move { summarize(&text) }).await;
            this.update(cx, |report, cx| {
                report.summary = Some(summary);
                cx.notify();
            })
            .ok();
        }));
    }
}

Dropping a Task cancels it, so storing it in the view ties the work’s lifetime to the view’s. See async work.

§Show a list of ten thousand rows

uniform_list builds rows for the viewport and a small buffer. This limits element construction even when the data contains thousands of rows:

uniform_list(
    "log",
    self.lines.len(),
    cx.processor(|log, range: std::ops::Range<usize>, _window, _cx| {
        range
            .map(|index| div().h(px(20.)).child(log.lines[index].clone()))
            .collect::<Vec<_>>()
    }),
)
.h_full()

See lists and scrolling.

§Animate a change

Wrap any element with with_animation. The closure receives the eased progress, from 0.0 to 1.0, and returns the element as it should look at that point:

use gpui::{Animation, AnimationExt, ease_in_out, millis};

div()
    .child("Saved")
    .with_animation(
        "fade-in",
        Animation::new(millis(300)).with_easing(ease_in_out),
        |element, progress| element.opacity(progress),
    )

See animation.

§Draw a custom shape

canvas gives you a callback with the element’s bounds and direct access to the window’s paint methods:

canvas(
    |_bounds, _window, _cx| {},
    |bounds, _state, window, _cx| {
        window.paint_quad(fill(bounds, rgb(0x2563eb)));
    },
)
.size(px(64.))

See custom drawing.

§The API at a glance

Most application-facing items are exported from the crate root. These tables group the main types and functions by purpose.

Applications and windows

ItemPurpose
ApplicationStarts the event loop. Get one from gpui_platform::application().
AppThe application context: windows, globals, key bindings, platform services.
Window, WindowOptionsOne window: its size, focus, input and drawing.
WindowHandle, AnyWindowHandleRefer to a window from outside it.

State

ItemPurpose
Entity, WeakEntityHandles to state owned by the app.
ContextAccess to one entity while you update it.
AppContextThe operations every context supports: create, read and update entities.
EventEmitter, SubscriptionTyped events between entities.
GlobalApplication-wide singletons such as settings.

Views and elements

ItemPurpose
RenderA stateful view: an entity that renders elements.
RenderOnce, IntoElementA stateless component, built and consumed in one frame.
div, DivThe general-purpose container element.
StyledText, img, svg, canvasText runs, images, vector icons, custom painting.
uniform_list, listVirtualized lists of equal or varying row heights.
anchored, deferredPopovers and overlays that escape their parent.
Element, AnyElementThe low-level element protocol, for custom layout and painting.

Style and layout

ItemPurpose
StyledTailwind-style builder methods for layout, color, borders, shadows and text.
Style, StyleRefinementThe full style, and a partial one that overrides it.
px, rems, relativeLengths in logical pixels, root ems and fractions.
Hsla, Rgba, rgb, hslaColors.
Bounds, Point, Size, PixelsGeometry.

Input

ItemPurpose
InteractiveElement, StatefulInteractiveElementMouse, keyboard, focus, hover and drag handlers on elements.
FocusHandle, FocusableKeyboard focus.
Action, actions!, KeyBindingKeystrokes mapped to typed commands.
ClickEvent, MouseDownEvent, KeyDownEvent, …The events your handlers receive.

Motion

ItemPurpose
Animation, AnimationExtAnimate an element over time.
StyleTransitionsAnimate style changes such as hover colors.
Transition, SpringConfigAnimate values toward a moving target.

Async and time

ItemPurpose
TaskA handle to running async work; dropping it cancels the work.
AsyncApp, AsyncWindowContextContexts you can hold across .await.
BackgroundExecutor, ForegroundExecutorSpawn work on a thread pool or the main thread.

Testing

ItemPurpose
TestAppA headless app for driving views with simulated input.
TestAppContext, #[gpui::test]Async tests with a deterministic scheduler.

§Crate features

FeatureDefaultEffect
wayland, x11yesInclude the Wayland and X11 code paths on Linux and FreeBSD.
font-kityesLegacy dependency feature retained for compatibility. The macOS backend discovers fonts through its shared Parley font database.
windows-manifestyesEmbed an application manifest in Windows executables.
test-supportnoTestApp, TestAppContext and other testing tools.
inspectornoThe element inspector, for debugging layout in a running app.
profilernoFrame, input-latency and task profiling, with an on-screen overlay.
hot-patchingnoPatch render code into a running app with Dioxus’ dx. See hot reload.
embedded-assetsnoEmbed an asset directory in the binary with rust-embed.
leak-detectionnoReport entity handles that outlive their app, with backtraces.
screen-capturenoCapture screen contents as a surface on Windows.
custom-gpunoExposes custom GPU drawing APIs. The renderer also needs device-sharing support; see platform features.
wgpu-surfacesnoCompatibility marker for Windows surface imports in gpui_wgpu. Enable the renderer’s feature of the same name to compile that integration.
stackernoGrow the stack on demand for very deep element trees.
bench-supportnoHelpers for Criterion benchmarks of GPUI code.
benchnoCompatibility alias for bench-support.

Cargo combines features requested by all dependencies. For example, turning off default features on one dependency does not remove a backend that another dependency enables. Platform selection and renderer features belong to their respective crates; the platforms page explains those relationships.

§Documentation

  • The tutorial builds a complete app.
  • The guides solve specific problems.
  • The concepts explain how GPUI works.
  • The examples are complete programs you can run, many of them live in your browser.
  • Design explains why GPUI is the way it is, comparison weighs it against other Rust toolkits, platforms describes what runs where, and upstream lists the differences from Zed’s GPUI.

Re-exports§

pub use test::TestScreenCaptureSource;
pub use test::TestScreenCaptureStream;
pub use proptest;
pub use accesskit;
pub use profiler::*;
pub use test::*;

Modules§

_documentation
Tutorials, guides and background reading for GPUI applications.
colors
The default colors used by GPUI.
http_client
HTTP client abstraction for making requests.
inspector_reflection
Runtime descriptions of trait methods, generated by #[derive_inspector_reflection].
layer_shell
popup
Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
prelude
The GPUI prelude is a collection of traits and types that are widely used throughout the library. It is recommended to import this prelude into your application to avoid having to import each trait individually.
profiler
Profiling utilities for task, frame, and thread performance tracking. Timing for tasks, actions and window frames.
queue
A queue with three priority levels. A sender can be shared by reference across threads, while cloning a receiver adds another consumer of the same queue.
styled_reflection
Implements function reflection
test
Support for the #[gpui::test] macro, and streams for observing entities in tests.

Macros§

actions
Declares unit structs that are actions, and registers them with the app.
bench_group
Defines a Criterion benchmark group for benchmarks annotated with gpui::bench.
bench_main
Defines the entry point for GPUI Criterion benchmark groups.
border_style_methods
Generates the border methods for Styled, such as border_1 and border_color.
box_shadow_style_methods
Generates the box-shadow and corner methods for Styled.
cursor_style_methods
Generates the cursor methods for Styled, such as cursor_pointer.
margin_style_methods
Generates the margin methods for Styled, such as m_4 and mx_auto.
overflow_style_methods
Generates the overflow methods for Styled, such as overflow_hidden.
padding_style_methods
Generates the padding methods for Styled, such as p_4 and px_2.
position_style_methods
Generates the position methods for Styled, such as relative and absolute.
register_action
Registers a type that implements gpui::Action by hand.
text
Creates a Text element that has an ID, so that screen readers can read it.
visibility_style_methods
Generates the visible and invisible methods for Styled.

Structs§

A11yCallbacks
The callbacks an accessibility adapter uses to talk to the application.
A11ySubtreeBuilder
Adds accessibility nodes for things an element draws but doesn’t model as elements.
ActionBindingCollection
A set of actions and the keystrokes that trigger each one, to be bound together in one key context.
ActivityGuard
Keeps an operating system activity, such as an idle sleep inhibitor, alive until dropped.
Anchored
An element that places its children at an anchor point, and keeps them inside the window.
AnchoredState
The layout state of an Anchored element: the layout ids of its children.
Animated
A value that animates toward a target, and keeps the state it needs to change course.
AnimatedSample
A value sampled from an Animated, together with its activity and progress.
Animation
A timed change to an element, applied with AnimationExt::with_animation.
AnimationElement
The element returned by AnimationExt::with_animation and AnimationExt::with_animations.
AnimationPhase
An animation coordinate that can go past zero and one.
AnyDrag
The state of a drag in progress, started by dragging an element in a window.
AnyElement
An element with its concrete type erased, so that elements of different types can share one type.
AnyEntity
A handle to an entity whose type is erased.
AnyImageCache
A type-erased ImageCache, so one img can hold any cache type.
AnyTooltip
The state of a tooltip that is currently shown.
AnyView
A type-erased handle to a view.
AnyWeakEntity
A type-erased handle to an entity that doesn’t keep it alive.
AnyWeakView
A weak, type-erased handle to a view.
AnyWindowHandle
A handle to an open window whose root view type isn’t known at compile time.
App
The state of a running application: its entities, windows, globals and key bindings.
Application
The entry point for a GPUI application. Configure it, then call Application::run.
ApplicationHandle
A strong handle to an Application started with Application::run_embedded.
ArenaClearNeeded
Returned when the element arena has been used and so must be cleared before the next draw.
AssetRegistry
The named assets that the app loads by path, such as images, SVGs and fonts.
AsyncApp
A handle to the app that you can hold across .await points.
AsyncWindowContext
A handle to the app and one window, for use across .await points.
AtlasTextureId
Identifies one texture in an atlas.
AtlasTile
Where a glyph, SVG or image sits in an atlas texture.
BackdropFilter
A filter applied to the content already painted behind bounds, composited into a rounded rectangle. A blur gives the frosted-glass effect.
Background
A fill for a shape: a solid color, a linear gradient, or a pattern.
BackgroundExecutor
Runs Send futures on GPUI’s background executor.
BindingIndex
The position of a binding in a Keymap, counted in the order bindings were added.
Bounds
A rectangle, defined by its top left corner and its size.
BoundsRefinement
A refinable version of [#ident]. See that type’s documentation for details.
BoxShadow
The values accepted by an element’s box-shadow style.
Canvas
An element that runs custom drawing code, created with canvas.
Capslock
The state of the caps lock key at some point in time.
CaretMovement
The destination of a caret movement, and the column to keep across vertical moves.
CaretPosition
A position between characters, given as a UTF-8 byte index plus the side it attaches to.
CaretSelection
A text selection with an anchor and a caret, each with its own affinity.
Cascade
A cascade of refinements that can be merged in priority order.
CascadeSlot
A handle to a specific slot in a cascade.
ClipboardItem
Something to put on the clipboard, or something read from it.
ClipboardString
A string on the clipboard, with optional metadata.
ContainerQuery
A container query element, created with container_query.
ContentMask
The visible region of the window, which clips what is painted and hit-tested.
Context
A mutable handle to the App that also knows which entity T you are working on.
ContextEntry
One identifier or key-value pair in a KeyContext.
Corners
The values at the four corners of a box, such as a border radius.
CornersRefinement
A refinable version of [#ident]. See that type’s documentation for details.
DebugBelow
Lets a custom element read the debug_below setting in debug builds.
DedicatedExecutor
A handle to one long-lived session. Every future spawned on it runs on that session’s single thread, never on the background pool.
Deferred
An element that draws its child after the rest of the tree, in priority order.
DeferredScrollToItem
A scroll request that waits for the next prepaint.
DevicePixels
A whole number of physical pixels on the display.
DismissEvent
The event a ManagedView emits to ask its owner to close it.
DispatchEventResult
The outcome of Window::dispatch_event.
DisplayChanges
The properties of a display that a DisplayEvent::Changed reports.
DisplayId
An identifier for a display that is valid for the current session.
Div
The all-in-one element for building most user interfaces. Create one with div.
DivFrameState
The layout state a Div keeps between its layout and prepaint phases.
DivInspectorState
The interactivity state of an element, as shown and edited by the inspector.
DragMoveEvent
A pointer move during a drag of type T, passed to InteractiveElement::on_drag_move listeners.
Drawable
An Element together with the state GPUI keeps while drawing it in one frame.
DropListener
Handles drags of a single type over an element: whether they can be dropped, how the element looks while they are over it, and what happens when they are released.
DummyKeyboardMapper
A PlatformKeyboardMapper that changes nothing.
DuplicateAssetPath
Returned when a path is already registered in an AssetRegistry. It holds the duplicated path.
DurationDescription
The timing of a duration-based Motion: its passes, delay and playback.
Easing
An easing function that maps linear pass time to eased progress.
Edges
The sizes of the four sides of a box, such as its padding or margin.
EdgesRefinement
A refinable version of [#ident]. See that type’s documentation for details.
ElementClickedState
Whether an element, or a group that contains it, is pressed by the mouse.
ElementHoverState
Whether an element, or a group that contains it, is hovered.
ElementInputHandler
Connects an EntityInputHandler view to the platform’s text input.
Empty
An element that draws nothing and takes up no space.
EmptyView
A view that renders nothing.
Entity
A handle to state owned by the App.
EntityId
Identifies an entity within the app.
ExternalPaths
The file paths carried by a file drop.
FallbackPromptRenderer
The view that fallback_prompt_renderer shows inside the window.
FallibleTask
A Task that resolves to Option<T>, and to None instead of panicking when the task is cancelled.
FileDragPaths
The files for a native file drag, each paired with whether it is a directory.
FillOptions
Parameters for the fill tessellator.
FilterBoundary
The start or end marker of a content-filter or opacity isolation group.
FilterTargetIndex
The index of an offscreen target in the renderer’s content-filter target pool.
FocusHandle
A handle that makes an element focusable and tracks whether it has focus.
FocusId
A key that identifies one focusable element within the focus map of a window.
FocusOutEvent
The event passed to listeners registered with Context::on_focus_out.
Font
The face to use for text: a font family plus its weight, width, style, features, and fallbacks.
FontFallbacks
Font families to try, in order, when a Font lacks a glyph.
FontFeatures
OpenType feature settings applied while shaping a Font.
FontId
An opaque identifier for a font face that the TextSystem has resolved.
FontMetrics
The measurements of a typeface, in font units.
FontWeight
The weight of a font, from FontWeight::THIN (100) to FontWeight::BLACK (900).
FontWidth
The requested width of a font face, as a percentage of its normal width.
ForegroundExecutor
Runs futures on the main thread, interleaved with event handling and drawing.
GestureKinds
The gestures a platform recognizes on its own.
GestureTuning
The timing, distance and feel constants that touch gesture recognition uses.
GlobalElementId
A globally unique identifier for an element, used to track state across frames.
GlyphAtlasEntry
A cached glyph’s GPU tile and the placement metadata for its uploaded pixels.
GlyphId
An identifier for a specific glyph, as returned by WindowTextSystem::layout_line.
GpuSpecs
Describes the GPU that GPUI renders with.
GpuiBorrow
A mutable borrow of an entity’s state, taken out of GPUI while the borrow is alive.
GraphicalEnvironment
The graphical session to connect to: the variables that locate its display server, as some process sees them.
GridLocation
The rows and columns that a grid item occupies.
GridTemplate
The portion of a grid template that describes track sizes.
GridTemplateRefinement
A refinable version of [#ident]. See that type’s documentation for details.
GroupStyle
A style that applies to an element while a named group of elements is hovered, pressed or receives a drag.
HeadlessAppContext
A headless app for tests that need real text layout, without a window on screen.
HeadlessAtlas
A sprite atlas for windows without a GPU. It hands out uniquely identified tiles without uploading any pixels, so glyph, SVG, and image painting can run to completion in tests and headless platforms.
HighlightStyle
A highlight style to apply, similar to a TextStyle except for a single font, uniformly sized and spaced text.
HitTest
The hitboxes under the mouse, from front to back, as of the last frame.
HitTestEntry
An entry in a HitTest which represents a Hitbox. Contains some metadata about the hitbox in the frame the HitTest was evaluated on.
Hitbox
A region that receives mouse input for the frame it was inserted in.
HitboxId
Identifies a Hitbox in the frame that inserted it.
Image
Encoded image data and the format it is encoded in.
ImageCacheElement
The element that image_cache returns. It installs the cache for its children during layout and paint, and lays out like a div.
ImageCacheItem
Owns an image load and its cached result.
ImageFormatIter
An iterator over the variants of ImageFormat
ImageId
Identifies a RenderImage. RenderImage::new gives each image a new ID, so two images never share one. The wrapped usize is the counter value that identifies the image.
ImageStyle
The settings that the StyledImage methods set on an image element.
Img
An image element, made by img.
ImgLayoutState
The per-frame state that an Img passes from layout to paint.
InlineBoxRequest
An atomic element inserted at a UTF-8 boundary in an inline document.
InlineLayout
Text and atomic boxes laid out together, following inline paragraph flow.
InlineLayoutRequest
Complete input for a document containing text and element boxes.
InlineRangeGeometry
The area that a text range covers on one visual line.
InlineTextMetrics
Font metrics that set the vertical extent of an inline line.
InlineTextStyle
Resolved font size and line height for part of an inline document.
InlineVisualLine
One row of an inline layout, positioned relative to the layout’s origin.
Inspector
Tracks the element selected or hovered in the inspector, and whether picking is active.
InspectorElementId
Identifies one element so the inspector can select it and describe its state.
InspectorElementPath
A GlobalElementId plus the source location where the element was built.
InteractiveElementState
The state that an element with an ElementId keeps between frames, such as its focus handle and scroll offset.
InteractiveText
A StyledText that reports clicks, hovers, and tooltips for character ranges.
Interactivity
The interactivity state of an element: its listeners, styles, focus and scroll state.
InteractivityPrepaint
The bounds and content size of an element, as passed to Interactivity::on_prepaint.
InvalidKeystrokeError
Error returned by Keystroke::parse when a string isn’t a valid keystroke.
ItemSize
The sizes of a UniformList’s viewport and of all its rows, from the last prepaint.
KeyBinding
A keybinding: a keystroke sequence, the action it runs, and the key context it applies in.
KeyBindingMetaIndex
An index into your own store of metadata about where a binding came from, such as the keymap file or the built-in defaults. Lower indexes are stronger sources.
KeyContext
The names and values that describe one element, for matching key bindings.
KeyDownEvent
A key press, sent when the platform reports that a key went down.
KeyUpEvent
A key release, sent when the platform reports that a key went up.
KeybindingKeystroke
A keystroke as it appears in a keybinding, ready to display to the user.
KeyboardClickEvent
A click triggered from the keyboard: Enter or Space on a focused element.
Keymap
The set of key bindings for the application, and the rules for choosing among them.
KeymapVersion
An identifier for one state of a Keymap.
Keystroke
A key press, with the modifier keys that were held when it happened.
KeystrokeEvent
A keystroke that reached the app, with the action it resolved to, if any.
LayoutId
An id for a node in the layout tree.
LeakDetectorSnapshot
A snapshot of the entities that had alive handles at one point in time.
LineLayout
The shaped and laid-out form of a string of text, ready to measure and paint.
LinearColorStop
A color stop in a linear gradient.
List
The element returned by list. Style it, then return it from render.
ListOffset
A position in a list: a row index and a pixel offset into that row.
ListPrepaintState
The hitbox and laid-out rows that a List carries from prepaint to paint. You don’t construct it.
ListScrollEvent
The state of a ListState after a wheel or trackpad scroll.
ListState
The state of a list. Store it on your view and pass a clone to list each frame.
LongPressEvent
A touch held still long enough to count as a long press.
Menu
A menu in the application’s menu bar, or a submenu inside another menu.
Modifiers
The modifier keys held at some point in time.
ModifiersChangedEvent
A change to the modifier keys (Shift, Control, Alt, Platform, Function) or Caps Lock, sent without a key press.
MonochromeSprite
A single-color sprite: an alpha mask from the sprite atlas, tinted with color.
Motion
A deterministic, time-sampled motion from a start value to a target.
MotionPass
One directional pass of a Motion: a duration together with its easing curve.
MotionSample
The state of a Motion at one moment, returned by Motion::sample.
MouseClickEvent
A completed mouse click: the press and the release of one button on one element.
MouseDownEvent
A mouse button press, sent to InteractiveElement::on_mouse_down listeners.
MouseExitEvent
The pointer left the window.
MouseMoveEvent
The pointer moved over the window, with or without a button held.
MousePressureEvent
A pressure update from a force-sensitive trackpad, sent as the user presses harder or eases off. Only macOS trackpads report it today.
MouseUpEvent
A mouse button release, sent to InteractiveElement::on_mouse_up listeners.
NoAction
Disables the lower-precedence bindings for the same keystrokes.
NullPlatformGestures
A PlatformGestures with the default tuning and no native recognizers.
OngoingScroll
Keeps a scroll gesture on one axis, so a mostly vertical swipe does not drift sideways.
OsMenu
A submenu that the operating system fills in, such as the Services menu on macOS.
OwnedMenu
A Menu in the form that App::get_menus returns.
OwnedOsMenu
An OsMenu in the form that App::get_menus returns.
PaintFragment
A run of glyphs that share one font and one style, positioned on a visual line.
PaintQuad
A rectangle with a background and optional border, ready for Window::paint_quad.
PaintStyle
The paint properties of one run of text: color, background, underline, and strikethrough.
PaintSurface
A surface produced outside GPUI, such as a video frame, drawn as a rectangle.
ParsedSvg
A parsed SVG document that can be rasterized at any scale.
Path
A filled shape, stored as a triangle mesh.
PathBuilder
Builds a Path from lines and curves, and tessellates it into triangles.
PathId
Identifies a Path by the index it had in Scene::paths when the path was inserted. The scene assigns it at that point, and Scene::finish may sort the paths afterwards.
PathPromptOptions
Options for Platform::prompt_for_paths, which shows a file or folder picker.
PathVertex
A vertex of a Path triangle.
PendingInputStatus
Pending input for a potential multi-stroke key binding.
PendingInputTimeoutStatus
The timeout state for pending input.
Percentage
A fraction of a full turn, from 0.0 to 1.0.
PinchEvent
A pinch-to-zoom gesture, typically from a trackpad.
Pixels
A length in logical pixels, GPUI’s unit for layout, painting and input.
PlatformFrameSignal
Preserves the first platform frame request time across coalesced notifications.
PlatformInputHandler
Connects the platform’s input method (IME) to the focused InputHandler.
Playback
The iteration count and configured direction of a run.
Point
A position or offset in two-dimensional space.
PointRefinement
A refinable version of [#ident]. See that type’s documentation for details.
PolychromeSprite
A sprite whose colors come from the atlas as they are, such as an image or a color emoji.
PositionedInlineBox
An atomic box from an inline layout, with the position the layout gave it.
PreparedRasterStyle
The cache-relevant raster settings chosen by a platform rasterizer.
Progress
A motion’s presentation progress, normally between zero and one.
PromptHandle
A handle that a prompt builder uses to show a prompt and report the user’s answer.
PromptResponse
The event a prompt emits when the user chooses one of its buttons.
Quad
A filled rectangle with an optional border and rounded corners, in scaled pixels.
Radians
An angle in radians.
RasterStyleRequest
A scene request before a platform rasterizer normalizes its cache-relevant settings.
RasterizedGlyph
A glyph raster produced by a platform rasterizer.
Relative
A length given as a fraction of a reference length.
Rems
A length in rems, a unit based on the font size of the window.
RenderGlyphParams
Parameters for rendering a glyph, used as cache keys for glyph atlas entries.
RenderImage
A decoded image: one or more frames of BGRA pixels, ready to draw.
RenderImageParams
RenderSvgParams
RenderablePromptHandle
A prompt that a window can render, as returned by a prompt builder.
RequestFrameOptions
Options for a frame the platform asks GPUI to draw. The platform passes them to the callback registered with PlatformWindow::on_request_frame.
Reservation
A slot for an entity that doesn’t exist yet.
ResizeRegion
Resize handles around a rectangle.
RetainAllImageCache
An ImageCache that keeps every image it loads until you clear it, remove a source, or drop the cache.
RetainAllImageCacheProvider
The ImageCacheProvider that retain_all returns.
RingStyle
A ring around or inside an element.
RingStyleRefinement
A refinable version of [#ident]. See that type’s documentation for details.
RunnableMeta
Metadata attached to runnables for debugging and profiling.
ScaledPixels
A logical length multiplied by the display’s scale factor.
Scene
The primitives painted for one frame, ready for a renderer to consume.
SceneHsla
Internal representation of palette::Hsla with the layout provided to the renderer.
ScenePlan
A compiled scene command stream, built by Scene::finish and shared by every renderer.
ScenePlanRequirements
Allocation and draw totals collected while compiling one ScenePlan.
SchedulerLocalExecutor
An executor for one session, for futures that are not Send.
Scope
A set of futures that run together and are awaited together.
ScreenCaptureFrame
One frame of captured video.
ScrollAnchor
A reference to an element that a ScrollHandle can scroll to, even if it is not a direct child of the scrolling element.
ScrollHandle
A handle to the scroll state of an element, used to read the scroll position and to scroll it.
ScrollWheelEvent
A scroll from a mouse wheel, a trackpad, or a touch pan.
Shadow
A blurred shadow of a rounded rectangle. It is drawn outside the element, or inside it when Shadow::inset is set.
ShapedGlyph
One glyph in a shaped line, ready to paint.
ShapedLine
A shaped line that is ready to measure and paint.
ShapedText
Shaped text that may contain hard breaks and soft-wrapped lines.
ShapedTextLayout
Shaped text with its wrap width, which is how a layout is measured and queried.
SharedString
A shared string is an immutable string that can be cheaply cloned in GPUI tasks. Essentially an abstraction over an Arc<str> and &'static str, currently backed by a SmolStr.
SharedUri
A URI held in a SharedString, so cloning the handle does not copy its text.
Size
A width and height, such as the size of a window or an element.
SizeRefinement
A refinable version of [#ident]. See that type’s documentation for details.
SourceMetadata
Describes a screen or window that can be captured.
SpringAnimation
A spring animation for an element: a SpringConfig, a target and a starting value.
SpringAnimationElement
The element returned by AnimationExt::with_spring.
SpringConfig
The physical parameters of a damped spring that moves a scalar toward a target.
SpringDescription
The timing of a spring-driven Motion: its physical parameters and settling tolerance.
SpringState
The position and velocity of a spring at one instant.
Stateful
An element with an ElementId, which lets it keep state between frames.
StrikethroughStyle
The properties that can be applied to a strikethrough.
StrikethroughStyleRefinement
A refinable version of [#ident]. See that type’s documentation for details.
StrokeOptions
Parameters for the tessellator.
Style
The resolved styling of an element, which GPUI uses to lay out and paint it.
StyleRefinement
A refinable version of [#ident]. See that type’s documentation for details.
StyleTransitions
Selects style properties to transition and configures their motion.
StyledText
Text that is laid out and painted with a different style for each run.
SubpixelSprite
A glyph drawn with subpixel anti-aliasing, tinted with color.
Subscription
A handle to a callback that GPUI calls until the handle is dropped.
Surface
An element that shows a platform video or capture frame, such as a camera feed.
Svg
An element that draws an SVG as a single-color mask, filled with the text color.
SvgRenderer
Parses and rasterizes SVG documents, resolving their fonts from the app’s crate::AssetRegistry.
SystemNotification
A notification for the operating system’s notification center, rather than in-app UI.
SystemNotificationAction
A button on a SystemNotification.
SystemNotificationResponse
The user’s response to a SystemNotification.
SystemWindowTabController
A global that tracks which windows are grouped into native window tabs.
Task
A handle to a future that runs in the background, and to its output.
TestApp
A headless app for tests.
TestAppContext
The test version of App, passed to #[gpui::test] functions.
TestAppWindow
A window opened by TestApp::open_window.
TestScreenCaptureSource
A fake screen capture source for tests. It reports a 1x1 resolution and sends no frames.
TestScreenCaptureStream
A fake screen capture stream for tests. It reports the metadata of TestScreenCaptureSource.
TestTextSystem
Text
An Element that lays out and paints one text string.
TextInputConfiguration
Platform text-assistance preferences for the focused text region.
TextLayout
The laid-out state of a text element, for mapping between byte indices and pixels.
TextLayoutRequest
Complete input for one backend-owned text document layout.
TextLayoutTruncation
How a text element should truncate its text to fit, computed during layout.
TextMovement
A caret movement described by a direction and a unit, such as “to the end of the word”.
TextRun
A stretch of text that shares one font and style.
TextStyle
The text properties of an element: font, size, color and spacing.
TextStyleRefinement
A refinable version of [#ident]. See that type’s documentation for details.
TextSystem
The platform-independent font database and metrics cache, shared by all windows.
ThreadedDispatcher
A [PlatformDispatcher] that runs background work on real threads, for tests and benchmarks.
TileId
Identifies a tile within its atlas texture.
Tiling
Which edges of a window are tiled against the screen edge.
Timeout
The error returned when a future given to FutureExt::with_timeout doesn’t finish in time.
TitlebarOptions
Options for a window’s titlebar.
TooltipId
Identifies a tooltip set during prepaint with Window::set_tooltip.
TouchClickEvent
A tap, or a long press, recognized on a touch screen.
TouchDragEvent
A touch drag that a listener can claim before the touch becomes a tap, long press or scroll.
TouchEvent
A raw touch sample from a touch screen, before gesture recognition.
TouchId
Identifies one touch (finger or stylus contact) from its TouchPhase::Started event through its TouchPhase::Ended or TouchPhase::Cancelled event.
Transformation
A rotation, scale and translation applied to an Svg when it is drawn.
TransformationMatrix
A 2D affine transform in scaled pixels: a 2x2 linear part and a translation.
Transition
A value that moves toward a goal over time and changes course when that goal changes.
UTF16Selection
A struct representing a selection in a text buffer, in UTF16 characters. This is different from a range because the head may be before the tail.
Unbind
Removes a lower-precedence binding for the same keystrokes that runs the named action.
Underline
A horizontal line under or through text, which can be wavy.
UnderlineStyle
The properties that can be applied to an underline.
UnderlineStyleRefinement
A refinable version of [#ident]. See that type’s documentation for details.
UniformList
The element returned by uniform_list. Configure it with the builder methods, then return it from render. To read or set the scroll position, pass a UniformListScrollHandle to UniformList::track_scroll.
UniformListFrameState
The rows and decorations that a UniformList lays out for one frame. You don’t construct it.
UniformListScrollHandle
A handle that reads and sets the scroll position of a UniformList.
UniformListScrollState
The state that a UniformListScrollHandle shares with its UniformList.
ValidatedRasterizedGlyph
A glyph raster whose placement and pixel buffer have passed validation.
VisualLine
One row of text produced by shaping and line breaking.
VisualTestContext
A TestAppContext bound to one window, the test equivalent of a Window and App.
WeakEntity
A handle to an entity that doesn’t keep it alive.
WeakFocusHandle
A focus handle that doesn’t keep its element focusable.
Window
The state of one platform window: its focus, input, bounds, frame and drawing.
WindowButtonLayout
Which WindowButtons appear on each side of the titlebar, in order.
WindowControls
The window controls a platform supports.
WindowHandle
A handle to an open window whose root view has type V.
WindowId
Identifies an open window. A stale id from a closed window never matches a newer one.
WindowInsets
Regions of a window that are obscured or reserved by the system.
WindowOptions
Options for creating a window, passed to App::open_window.
WindowParams
The variables that can be configured when creating a new window The platform-level options for one window, passed to Platform::open_window.
WindowTextSystem
The text layout subsystem for one window, with a cache of shaped lines.
WindowingModes
The windowing modes a platform may start in or switch to.

Enums§

AbsoluteLength
A length that doesn’t depend on the parent: pixels or rems.
AccessibleAction
An action to be taken on an accessibility node.
ActionBuildError
Error returned by App::build_action when an action can’t be built by name.
ActivationPolicy
Controls whether the application participates in the system’s foreground UI.
AlignContent
Distributes free space between flex lines or grid tracks along the cross axis.
AlignItems
Aligns children along the cross axis in flexbox and the block axis in grid.
Anchor
A point on the edge or corner of a box, used to align a position to that box.
AnchoredFitMode
How an Anchored element keeps its children inside the window.
AnchoredPositionMode
The coordinate space of an Anchored element’s anchor position.
AnyMotion
A duration or spring Motion behind one type, so that an API can accept either.
AppLifecyclePhase
The application’s lifecycle phase, as owned and reported by a mobile OS.
ArcCow
AssetEntry
One asset in the AssetRegistry: its bytes, or a loader that produces them on request.
AssetLogger
Wraps an Asset whose output is a Result, and logs each error as it loads.
AtlasKey
Identifies one entry in a PlatformAtlas: a glyph, an SVG or a raster image.
AtlasTextureKind
The kind of pixels a texture in an atlas stores.
Autocapitalize
Automatic capitalization applied by software keyboards.
AvailableSpace
How much space an element is given along one axis when it is laid out.
Axis
An axis of two-dimensional space.
BackgroundKind
What a Background paints, decoded from its packed representation.
BackgroundTag
The storage-buffer discriminant for a Background.
BorderStyle
The style of a Quad border.
CaretAffinity
Determines which logical neighbor owns a caret at a shared text boundary.
ClickEvent
A completed click from the mouse, keyboard or touch.
ClipboardEntry
One part of a ClipboardItem: a string, an image or a list of file paths.
ClipboardReadError
An error from Platform::read_from_clipboard_async. Each variant calls for different guidance to the user.
ColorSpace
A color space for color interpolation.
CursorHideMode
Controls when GPUI hides the mouse cursor in response to keyboard input.
CursorStyle
The shape of the mouse cursor. Each variant names the CSS cursor it maps to on the web.
Decorations
The decorations a window is currently using.
DeferredPriority
How the draw priority of a Deferred element is chosen.
DefiniteLength
A length with a value: an absolute length, or a fraction of the parent.
Direction
The configured direction of a motion’s iterations.
DispatchPhase
The two passes an event makes through the element tree.
Display
Selects the layout algorithm used for this element’s children.
DisplayEvent
A change to the connected displays, reported through App::observe_displays.
ElementId
Identifies an element across frames, so that its element state survives re-renders.
ExternalDragPayload
The content of a drag that leaves the window and becomes a native drag session handed to the operating system.
FileDropEvent
A stage of a file drag from the operating system into the window.
Fill
The kinds of fill that can be applied to a shape.
FillRule
The fill rule defines how to determine what is inside and what is outside of the shape.
Filter
A graphical filter that can be applied either to an element’s own content (via Styled::filter, like CSS filter) or to the content rendered behind it (via Styled::backdrop_filter, like CSS backdrop-filter).
FilterRenderTarget
Where the contents of a filter group are rendered.
FlexDirection
The direction of a flex container’s main axis.
FlexWrap
Controls whether flex items stay on one line or wrap onto multiple lines.
FollowMode
Whether a ListState keeps the end of the list in view as rows are added.
FontStyle
Selects an italic or oblique face when the font family has one.
ForegroundDependency
Describes which foreground channels can change rasterized color artwork.
FrameRequestSource
The source of a platform frame request’s timestamp.
GlyphRenderMode
The kind of glyph image requested from a rasterizer.
GridPlacement
Where a grid item starts or ends along one axis of a grid.
GridTemplateMinSize
The minimum size of a grid column or row.
HapticFeedbackStyle
A kind of haptic feedback to play with App::play_haptic_feedback.
HitboxBehavior
How a hitbox affects the hitboxes behind it.
HoverListenerMode
Controls how StatefulInteractiveElement::on_hover responds to key presses while the mouse is stationary.
ImageAssetLoader
Loads and decodes a Resource into a RenderImage. img uses it, through ImgResourceLoader, for URLs, file paths and registry entries.
ImageCacheError
Why an image failed to load or decode.
ImageFormat
An image format GPUI recognizes in clipboard data and in Image.
ImageSource
Where an img element gets its pixels.
InputPreference
Whether a keystroke should prefer character input or key bindings.
Iterations
How many iterations a Motion plays before it completes.
KeyBindingContextPredicate
A condition on the key context stack that decides whether a binding applies.
KeyboardButton
The key that triggered a keyboard click: Enter or Space.
LayoutDirection
The inline direction established by an element.
Length
A length that can be a definite value or auto.
LinuxWindowBackground
The background appearance of a Linux window, set through WindowOptions::linux_window_background. Whether blurring is honored depends on the compositor; X11 treats it as plain transparency.
ListAlignment
Where a ListState starts: at its first row, or at its last row.
ListHorizontalSizingBehavior
Whether the rows of a crate::UniformList can be wider than the list.
ListMeasuringBehavior
Whether a ListState measures every row or only the rows it renders.
ListSizingBehavior
How a list or crate::UniformList sizes itself during layout.
MenuItem
An entry in a Menu: a separator, a submenu, a system menu, or an action.
MotionExtent
The total length of a motion, including its delay.
MotionPhase
Where a sampled motion is in its lifecycle.
MouseButton
A mouse button.
NavigationDirection
The direction of a navigation button, the side buttons on some mice.
ObjectFit
How an image is sized and positioned inside an element’s bounds.
Orientation
OsAction
A standard command that the operating system knows about, such as Copy or Undo.
Overflow
How overflow affects layout and the scroll region.
OwnedMenuItem
A MenuItem in the form that App::get_menus returns.
PassDirection
The direction of the pass that a sample falls in.
PathStyle
How a crate::PathBuilder tessellates its path: as an outline, or as a filled shape.
PlatformInput
Any input event the platform sends to a window.
Position
The positioning strategy for this item.
PressureStage
How hard a force-sensitive trackpad is pressed.
Primitive
Any primitive that Scene::insert_primitive accepts.
PrimitiveBatch
A contiguous run of one primitive type that the renderer draws in one call.
Priority
Task priority for background tasks.
PromptButton
A button on a prompt shown with PlatformWindow::prompt.
PromptLevel
How serious a prompt is. The platform uses it to choose the alert’s icon or style.
QuitMode
Controls whether the app quits on its own when its last window closes.
RasterColorEffect
The part of the requested color, if any, which changes rasterized pixels.
RasterizedGlyphFormat
The byte layout supplied by a glyph rasterizer.
RenderCommand
Backend-neutral rendering work derived from a Scene.
ResizeEdge
The edge or corner of a window that a user drags to resize it.
Resource
Where an image or other asset is loaded from: a URL, a file path, or a name in the registry.
RingColor
A ring’s color or gradient.
Role
The type of an accessibility node.
ScaledFilter
The scene-space (device-pixel) form of a Filter, carried on the scene primitives that the renderers consume. Produced by Filter::scale; pixel magnitudes are in ScaledPixels.
ScrollDelta
The amount a scroll event moves the content.
ScrollPhysics
How a fling slows down after the finger lifts.
ScrollStrategy
Where a scroll request places the target row in the viewport.
ShaderBool
A bool stored as a four-byte integer, so its layout matches the GPU’s view of it.
SpringPlayback
How a spring advances, and where it rests, when its animation changes state.
SurfaceSource
The frame that a Surface shows.
SvgSize
The size at which SvgRenderer::render_parsed rasterizes an SVG.
SystemMenuType
The kinds of menu that the operating system fills in.
TextAlign
How text is aligned within the element.
TextBoundary
The unit that a semantic text movement stops at.
TextDirection
The direction of a semantic text movement, such as an arrow key or a Home key.
TextInputAction
The action a software keyboard advertises on its confirm (“enter”) key.
TextInputStateChange
A change in the state of the focused text input.
TextOverflow
How text is truncated when it exceeds the element’s width.
TextRenderingMode
The text rendering mode for glyphs.
TextSelectionKind
The unit selected by a double or triple click at a point.
TextTransform
Case mapping applied at layout time while keeping UTF-8 byte lengths unchanged.
ThermalState
The device’s thermal pressure, from least to most constrained.
Toggled
TouchPhase
The lifecycle stage of a touch, scroll or pinch event.
TruncateFrom
The part of an overflowing line that is removed and replaced by the affix.
UnicodeBidi
Controls the Unicode bidirectional scope established by an element.
VerticalAlign
Controls the vertical position of an element box in an inline formatting context.
Visibility
Whether an element is painted while it remains in layout.
VisualDirection
A direction in visual order, which is left and right on screen, regardless of text direction.
WhiteSpace
How text handles whitespace and line wrapping.
WindowAppearance
The light or dark appearance of a window, as the operating system defines it.
WindowBackgroundAppearance
How a window’s background is drawn when there is no content or the content is transparent.
WindowBounds
The state a window opens in, with the bounds it uses for that state.
WindowButton
A window control button, used in WindowButtonLayout.
WindowControlArea
A region of a custom title bar that the operating system treats as a window control.
WindowDecorations
Whether a window draws its own titlebar and borders, or the window server does.
WindowKind
The kind of window to create, set with WindowOptions::kind.
WindowVisibility
Whether the platform is presenting a window’s frames.
WindowingRequest
A display mode for App::request_windowing to switch to.

Constants§

DEFAULT_ADDITIONAL_WINDOW_SIZE
A 6:5 minimum window size in logical pixels, for secondary windows such as settings or document-library windows.
DEFAULT_WINDOW_SIZE
The size, in logical pixels, of a window whose bounds were not set.
KEYSTROKE_PARSE_EXPECTED_MESSAGE
The sentence that InvalidKeystrokeError appends to its message. It describes the syntax Keystroke::parse expects.
LOADING_DELAY
How long an image may take to load before the StyledImage::with_loading placeholder appears.
MAX_BUTTONS_PER_SIDE
The largest number of WindowButtons on one side of the titlebar.
MAX_FILTER_GROUP_DEPTH
Inline capacity of renderer isolation stacks. Deeper groups allocate additional targets.
SHUTDOWN_TIMEOUT
The duration for which native applications wait for futures returned from Context::on_app_quit before fully quitting.
SMOOTH_SVG_SCALE_FACTOR
The multiplier used when SvgRenderer::render_parsed rasterizes a scale-factor request.
SUBPIXEL_VARIANTS_X
The number of horizontal subpixel positions each glyph is rasterized at.
SUBPIXEL_VARIANTS_Y
The number of vertical subpixel positions each glyph is rasterized at.

Traits§

Action
An action is a named command that the app can run, such as saving or moving the cursor up.
Along
Reads and updates the value along one Axis.
AnimationExt
Adds animation methods to every element and component.
AppContext
Operations shared by GPUI’s app, entity and async contexts.
AsKeystroke
A type that can be viewed as a Keystroke.
Asset
A value that GPUI loads in the background and shares between callers, such as an image.
AssetSource
A read-only source of files that the app can load by path, such as a directory or a bundle.
BorrowAppContext
Helpers for changing globals from any context that can reach the App.
ColorExt
Helpers for changing the alpha of a color.
DurationWithEasing
The former name of MotionDurationExt. Adds motion constructors to Duration, including duration.with_easing(...).
Element
A part of a window’s element tree that lays itself out and paints itself.
EntityInputHandler
Text input for a view: the methods the platform calls for typed text, IME composition, paste and selection.
EventEmitter
Declares that an entity type emits events of type E.
Focusable
A view that owns a FocusHandle and can be focused as a whole.
FutureExt
Adds timeout combinators to futures.
GestureEvent
A gesture event recognized from touch input, such as PinchEvent, LongPressEvent or TouchDragEvent.
Global
Marks a type whose value is stored once per app.
Half
Returns half of a value, for centering and midpoints.
ImageCache
A store of decoded images that img elements read from.
ImageCacheProvider
Creates the AnyImageCache for an image_cache element.
InputEvent
A platform input event that GPUI can dispatch to a window.
InputHandler
Receives text from the platform’s input method (IME) on behalf of a focused element.
InteractiveElement
An element that can respond to the mouse and keyboard, style itself on state, and take focus.
Interpolate
A value that AnimationPhase can interpolate.
IntoElement
A type that can be converted into an Element, so it can be a child of another element.
IsEmpty
IsZero
Checks whether a length or geometry value is zero.
KeyEvent
An input event from the keyboard: KeyDownEvent, KeyUpEvent or ModifiersChangedEvent.
Lerp
A type whose values can be interpolated between two endpoints.
ManagedView
A view whose lifetime is controlled by a parent view, such as a modal, popover or menu.
MotionDurationExt
The former name of MotionDurationExt. Adds motion constructors to Duration, including duration.with_easing(...).
MouseEvent
An input event from a pointer or touch: mouse buttons, movement, scrolling, pinch, pressure, file drops and the gesture events.
ParentElement
An element that can hold any number of children of any type.
ParentElementTyped
A parent element whose children all have one concrete type.
Platform
The operating system or browser that GPUI runs on, as seen by the App.
PlatformAtlas
A texture atlas that packs glyphs, SVGs and images into shared GPU textures.
PlatformDisplay
A display, such as a monitor or a laptop screen, as the platform reports it.
PlatformGestures
Gesture settings that a platform supplies to GPUI.
PlatformHeadlessRenderer
Renders scenes offscreen for windows that have no display, such as in tests and benchmarks.
PlatformKeyboardLayout
The keyboard layout that is currently active on a platform.
PlatformKeyboardMapper
Maps keystrokes in keybindings to the keys the platform reports.
PlatformTextLayout
The text interaction model that a backend provides for one laid-out string.
PlatformTextSystem
Loads fonts and lays out text for one platform. Each backend implements this trait.
PlatformWindow
The native window that GPUI draws into, implemented by each backend.
Prompt
A view that can be shown as a prompt in a window.
RasterColorExt
Converts a scene color to the bytes used by a raster cache key.
ReadGlobal
Reads the global of the implementing type from an App, as in Theme::global(cx).
Refineable
A trait for types that can be refined with partial updates.
Render
A view: an entity that GPUI draws in a window.
RenderOnce
A component: a value that describes a pattern of elements and renders it once.
ScreenCaptureSource
A screen or window that can be captured.
ScreenCaptureStream
A running capture of a ScreenCaptureSource.
SpringTarget
A value that a one-dimensional spring can target.
StatefulInteractiveElement
An element with an id, which can also be clicked, scrolled, dragged, given a tooltip, and read by accessibility tools.
Styled
Sets an element’s layout, paint and text properties.
StyledImage
Styling methods for image elements, implemented by Img and Stateful<Img>.
TaskExt
Extension methods for tasks that produce a Result.
TextRangeExt
UTF-8 text range containment checks.
UniformListDecoration
An element drawn over the rows of a UniformList, such as indent guides.
UpdateGlobal
Changes or sets the global of the implementing type through a context.
View
A value that renders into elements and may carry an entity identity.
VisualContext
Operations that need a window.

Functions§

align_inline_boxes
Applies CSS-like vertical alignment to boxes after a text backend assigns them to lines.
anchored
Creates an Anchored element that keeps its children inside the window.
auto
Returns Length::Auto, which lets layout choose the size from the context.
black
Opaque black in Hsla.
block_on
Block the thread until the future is ready.
blue
Opaque blue in Hsla, at hue 240 degrees.
bounce
Runs easing forward over the first half, then backward over the second half.
bounds
Creates Bounds from an origin and a size.
canvas
Creates a Canvas that draws with the painting methods on Window.
checkerboard
Creates a checkerboard of squares in color, alternating with transparency.
combine_highlights
Combine and merge the highlights and ranges in the two iterators.
container_query
Creates a ContainerQuery whose contents depend on the size it is given.
deferred
Creates a Deferred element that draws child after the rest of the tree.
div
Creates an empty Div element, which you style and fill with children.
ease_in_out
Starts and ends slowly, and moves fastest at the midpoint.
ease_out_quint
Starts quickly and decelerates to a stop.
fallback_prompt_renderer
Shows a prompt drawn inside the window, rather than a platform dialog.
fillDeprecated
Returns a filled quad with no border and no corner radius.
font
Returns a Font for family, with normal weight, width, and style.
generate_list_of_all_registered_actions
Generate a list of all the registered actions. Useful for transforming the list of available actions into a format suited for static analysis such as in validating keymaps, or generating documentation.
get_gamma_correction_ratios
Returns the gamma correction ratios for subpixel text at gamma.
green
A dark, opaque green in Hsla, at hue 120 degrees and lightness 0.25.
guess_compositor
Return which compositor we’re guessing we’ll use. Does not attempt to connect to the given compositor.
hash
Hashes data with a fast, non-cryptographic hash, for use as a cache key within one process.
hsla
Creates an Hsla color from hue, saturation, lightness and alpha.
hsla_schemar
Generates the JsonSchema for palette::Hsla
hsla_to_rgba
Converts an Hsla color to sRGB Rgba, keeping the alpha.
image_cache
Scopes an image cache to the img elements below it.
img
Creates an image element that draws source.
is_no_action
Returns whether action is a NoAction.
is_paragraph_separator
Returns whether character separates Unicode text paragraphs.
is_unbind
Returns whether action is an Unbind.
linear
Returns delta unchanged. This is the default easing.
linear_color_stop
Creates a color stop of color at percentage along a gradient line.
linear_gradient
Creates a linear gradient between two color stops.
list
Creates a list element that renders rows of any height, using the state in state.
millis
Creates a Duration from whole milliseconds.
oklcha
Creates an Oklcha color from lightness, chroma, hue and alpha.
opaque_grey
A grey in Hsla with the given lightness and opacity.
outlineDeprecated
Returns a transparent quad with a 1px border and the given border style.
pattern_slash
Creates a background of diagonal stripes in color, over transparency.
percentage
Creates a Percentage of a full turn.
phi
Returns the golden ratio, about 1.618, as a Relative length.
point
Creates a Point from its x and y coordinates.
pulsating_between
Breathes between min and max, for idle indicators.
px
Creates a Pixels length, the usual way to write a fixed size in logical pixels.
quadDeprecated
Returns a quad with bounds, radii, background, border widths, border color and border style.
quadratic
Accelerates from rest. Returns delta * delta.
radians
Creates a Radians angle from a value in radians.
red
Opaque red in Hsla, at hue 0.0.
refresh_interval_from_hz
Converts a refresh rate in hertz to the time between refreshes, rejecting the zero, negative, and non-finite rates platforms use to mean “unknown”.
relative
Creates a Relative length, a fraction of the reference length.
rems
Creates a Rems length.
retain_all
Returns a provider for an image_cache element that keeps one RetainAllImageCache in the element state under id.
rgb
Creates an opaque Rgba color from a 0xRRGGBB hex number.
rgb_to_hsla
Converts an sRGB Rgba color to Hsla, keeping the alpha.
rgba
Creates an Rgba color from a 0xRRGGBBAA hex number.
rgba_schemar
Generates the JsonSchema for palette::Rgba
sampled_easing
Returns the time a spring takes to settle from rest, and an easing that samples it over that time.
secs
Creates a Duration from whole seconds.
size
Creates a Size from its width and height.
solid_background
Creates a solid background of color.
spring
Creates a SpringConfig from stiffness, damping and mass.
surface
Creates a Surface that shows source.
svg
Creates an Svg element with no source yet.
swap_rgba_pa_to_bgra
Converts one premultiplied RGBA pixel to straight-alpha BGRA, in place.
transparent_black
Black with zero alpha in Hsla.
transparent_white
White with zero alpha in Hsla.
uniform_list
Creates a list of rows that all have the same height, and renders only the rows in view.
utf8_to_utf16_offset
Converts a UTF-8 byte offset into a UTF-16 code-unit offset.
utf16_to_utf8_offset
Converts a UTF-16 code-unit offset into a UTF-8 byte offset.
white
Opaque white in Hsla.
yellow
Opaque yellow in Hsla, at hue 60 degrees.

Type Aliases§

AlignSelf
Aligns one child along the cross axis in flexbox or the block axis in grid.
AssetData
The bytes of one asset. Cow::Borrowed for data compiled into the binary, and Cow::Owned for data read at runtime.
CanDropListenerFn
Function type for DropListener::can_drop, which checks if a typed payload can be dropped on an element’s hitbox.
CaretSelectionMovement
The result of moving a selection: the new anchor and caret, and the column to keep.
DrawOrder
The order in which primitives are drawn. Lower values are drawn first.
ExternalDragPayloadSource
A closure that builds the payload for a drag that leaves the window.
FnAssetLoader
A callback that produces an asset’s bytes when the asset is requested, or None if it can’t.
Hsla
Linear HSL with an alpha component. See the Hsla implementation in Alpha.
ImgResourceLoader
The asset loader that img uses for ImageSource::Resource sources: URLs, file paths and crate::AssetRegistry entries.
InspectorRenderer
The function that builds the inspector panel. Install it with App::set_inspector_renderer.
JustifyContent
Distributes free space between flex items or grid tracks along the main or inline axis.
JustifyItems
Aligns grid children along the inline axis.
JustifySelf
Aligns one grid child along the inline axis.
MacActivationPolicyDeprecated
The activation policy for a macOS application.
MotionInfoDeprecated
The former name of Motion.
OnDragOverFn
Function type for DropListener::on_drag_over.
OnDropFn
Function type for DropListener::on_drop.
PathVertex_ScaledPixels
A PathVertex in scaled pixels.
Result
Result<T, Error>
Rgba
Generic RGB with an alpha component. See the Rgba implementation in Alpha.
Rgba8
Eight-bit sRGB color stored in a raster cache key when a native raster path needs it.
RunnableVariant
Type alias for runnables with metadata. Previously an enum with a single variant, now simplified to a direct type alias.
TimerResolutionGuard
Transform
Alias for euclid::default::Transform2D<f32>
TransitionState
The state behind a Transition: an Animated that reads the clock from Instant.

Attribute Macros§

bench
Turns a function into a Criterion benchmark that runs with GPUI support.
property_test
A variant of #[gpui::test] that runs a test with many generated inputs.
test
Marks a function as a GPUI test. The generated function is a #[test], so it runs under cargo test or cargo nextest.

Derive Macros§

Action
Derives gpui::Action for a type and registers it with the runtime.
AppContext
Derives gpui::AppContext for a struct that holds a &mut gpui::App.
InteractiveElement
Derives gpui::InteractiveElement for a struct with an #[interactivity] field.
IntoElement
Derives gpui::IntoElement for a type that implements gpui::RenderOnce.
ParentElement
Derives gpui::ParentElement for a struct with a #[children] field.
Refineable
StatefulInteractiveElement
Derives gpui::StatefulInteractiveElement, which adds methods such as role.
Styled
Derives gpui::Styled for a struct with a #[style] field.
VisualContext
Derives gpui::VisualContext for a struct that holds a &mut gpui::App and a &mut gpui::Window.