[][src]Crate druid

Simple data-oriented GUI.

Druid lets you build simple interactive graphical applications that can be deployed on Windows, macOS, Linux, and the web.

Druid is built on top of druid-shell, which implements all of the lower-level, platform-specific code, providing a common abstraction for things like key and mouse events, creating windows, and launching an application. Below druid-shell is piet, which is a cross-platform 2D graphics library, providing a simple and familiar drawing API that can be implemented for various platforms.

Druid is a data-driven, declarative framework. You describe your application model in terms of the Data trait, and then you build up a tree of widget s that can display and modify your data.

Your widgets handle Events, such as mouse movement, and can modify the data; these changes are then delivered to relevant widgets, which can update their state and redraw.

As your application grows, you can use Lenses to expose only certain subsets of your data model to certains subsets of your widget tree.

For more information you should read the druid book.

Examples

For many more examples, see druid/examples.

use druid::widget::{Align, Flex, Label, TextBox};
use druid::{AppLauncher, Data, Env, Lens, LocalizedString, Widget, WindowDesc, WidgetExt};

const VERTICAL_WIDGET_SPACING: f64 = 20.0;
const TEXT_BOX_WIDTH: f64 = 200.0;
const WINDOW_TITLE: LocalizedString<HelloState> = LocalizedString::new("Hello World!");

#[derive(Clone, Data, Lens)]
struct HelloState {
    name: String,
}

fn main() {
    // describe the main window
    let main_window = WindowDesc::new(build_root_widget)
        .title(WINDOW_TITLE)
        .window_size((400.0, 400.0));

    // create the initial app state
    let initial_state = HelloState {
        name: "World".into(),
    };

    // start the application
    AppLauncher::with_window(main_window)
        .launch(initial_state)
        .expect("Failed to launch application");
}

fn build_root_widget() -> impl Widget<HelloState> {
    // a label that will determine its text based on the current app data.
    let label = Label::new(|data: &HelloState, _env: &Env| format!("Hello {}!", data.name));
    // a textbox that modifies `name`.
    let textbox = TextBox::new()
        .with_placeholder("Who are we greeting?")
        .fix_width(TEXT_BOX_WIDTH)
        .lens(HelloState::name);

    // arrange the two widgets vertically, with some padding
    let layout = Flex::column()
        .with_child(label)
        .with_spacer(VERTICAL_WIDGET_SPACING)
        .with_child(textbox);

    // center the two widgets in the available space
    Align::centered(layout)
}

Optional Features

  • im - Efficient immutable data structures using the im crate, which is made available via the im module.
  • svg - Scalable Vector Graphics for icons and other scalable images using the usvg crate.
  • image - Bitmap image support using the image crate.
  • x11 - Work-in-progress X11 Linux backend instead of GTK.

Features can be added with cargo. For example, in your Cargo.toml:

[dependencies.druid]
version = "0.6.0"
features = ["im", "svg", "image"]

Re-exports

pub use shell::keyboard_types;

Modules

commands

Commands with special meaning, defined by druid.

im

Immutable Data Structures for Rust

kurbo

2D geometry, with a focus on curves.

lens

Support for lenses, a way of focusing on subfields of data.

piet

A piet backend appropriate for the current platform.

platform_menus

Pre-configured, platform appropriate menus and menu items.

scroll_component

A component for embedding in another widget to provide consistent and extendable scrolling behavior

text

Text editing utilities.

theme

Theme keys and initial values.

widget

Common widgets.

Macros

lens

Construct a lens accessing a type's field

Structs

Affine

A 2D affine transform.

AppLauncher

Handles initial setup of an application, and starts the runloop.

Application

The top level application object.

BoxConstraints

Constraints for layout.

Clipboard

A handle to the system clipboard.

ClipboardFormat

Data coupled with a type identifier.

Command

An arbitrary command.

ContextMenu

A menu displayed as a pop-over.

CursorDesc

A platform-independent description of a custom cursor.

DelegateCtx

A context passed in to AppDelegate functions.

DruidHandler

The struct implements the druid-shell WinHandler trait.

Env

An environment passed down through all widget traversals.

EventCtx

A mutable context provided to event handling methods of widgets.

ExtEventError

An error that occurs if an external event cannot be submitted. This probably means that the application has gone away.

ExtEventSink

A thing that can move into other threads and be used to submit commands back to the running application.

FileDialogOptions

Options for file dialogs.

FileInfo

Information about the path to be opened or saved.

FileSpec

A description of a filetype, for specifiying allowed types in a file dialog.

FontDescriptor

A collection of attributes that describe a font.

FontFamily

A reference to a font family.

FontWeight

A font weight, represented as a value in the range 1..=1000.

HotKey

A description of a keyboard shortcut.

ImageBuf

An in-memory pixel buffer.

Insets

Insets from the edges of a rectangle.

Key

A typed Env key.

KeyEvent

Information about a keyboard event.

LayoutCtx

A context provided to layout handling methods of widgets.

LifeCycleCtx

A mutable context provided to the lifecycle method on widgets.

LinearGradient

A description of a linear gradient in the unit rect, which can be resolved to a fixed gradient.

LocalizedString

A string that can be localized based on the current locale.

MenuDesc

A platform-agnostic description of an application, window, or context menu.

MenuItem

A normal menu item.

Modifiers

The modifiers.

Monitor

Monitor struct containing data about a monitor on the system

MouseButtons

A set of MouseButtons.

MouseEvent

The state of the mouse for a click, mouse-up, move, or wheel event.

Notification

A message passed up the tree from a Widget to its ancestors.

PaintCtx

A context passed to paint methods of widgets.

Point

A 2D point.

RadialGradient

A description of a radial gradient in the unit rect, which can be resolved to a fixed gradient.

Rect

A rectangle.

Region

A union of rectangles, useful for describing an area that needs to be repainted.

Scale

Coordinate scaling between pixels and display points.

Screen

Information about the screen and monitors

Selector

An identifier for a particular command.

SingleUse

A wrapper type for Command payloads that should only be used once.

Size

A 2D size.

TextLayout

A component for displaying text on screen.

TimerToken

A token that uniquely identifies a running timer.

UnitPoint

A representation of a point relative to a unit rectangle.

UpdateCtx

A mutable context provided to data update methods of widgets.

Vec2

A 2D vector.

WidgetId

A unique identifier for a single Widget.

WidgetPod

A container for one widget in the hierarchy.

Window

Per-window state not owned by user code.

WindowConfig

Window configuration that can be applied to a WindowBuilder, or to an existing WindowHandle. It does not include anything related to app data.

WindowDesc

A description of a window to be instantiated.

WindowHandle

A handle to a platform window object.

WindowId

A unique identifier for a window.

Enums

Code

Code is the physical position of a key.

Color

A datatype representing color.

Cursor

Mouse cursors.

Event

An event, propagated downwards during event flow.

FontStyle

A font style, which may be italic or regular.

Handled

An enum for specifying whether an event was handled.

InternalEvent

Internal events used by druid inside WidgetPod.

InternalLifeCycle

Internal lifecycle events used by druid inside WidgetPod.

KeyOrValue

Either a concrete T or a Key<T> that can be resolved in the Env.

LifeCycle

Application life cycle events.

Location

The location attribute contains an indication of the logical location of the key on the device.

MouseButton

An indicator of which mouse button was pressed.

PlatformError

Shell errors.

RawMods

A representation of the active modifier keys.

SysMods

A platform-agnostic representation of keyboard modifiers, for command handling.

Target

The target of a Command.

TextAlignment

The alignment of text in a TextLayout.

Value

A dynamic type representing all values that can be stored in an environment.

WindowState

Contains the different states a Window can be in.

Traits

AppDelegate

A type that provides hooks for handling and modifying top-level events.

Data

A trait used to represent value types.

Lens

A lens is a datatype that gives access to a part of a larger data structure.

LensExt

Helpers for manipulating Lenses

RenderContext

The main trait for rendering graphics.

Scalable

The Scalable trait describes how coordinates should be translated from display points into pixels and vice versa using a Scale.

ValueType

Values which can be stored in an environment.

Widget

The trait implemented by all widgets.

WidgetExt

A trait that provides extra methods for combining Widgets.

Type Definitions

ArcStr

A reference counted string slice.

FormatId

A type identifer for the system clipboard.

KbKey

The meaning (mapped value) of a keypress.

KeyCodeDeprecated

The meaning (mapped value) of a keypress.

KeyModifiersDeprecated

See Modifiers.

Derive Macros

Data

Generates implementations of the Data trait.

Lens

Generates lenses to access the fields of a struct.