Crate druid

source ·
Expand description

Simple data-oriented GUI.

Druid lets you build simple interactive graphical applications that can be deployed on Windows, macOS, Linux, OpenBSD, FreeBSD 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 certain 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

Utility 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 backend instead of GTK.
  • wayland - Work-in-progress Wayland backend, very experimental.
  • serde - Serde support for some internal types (most Kurbo primitives).

Image format features:

  • png
  • jpeg
  • jpeg_rayon
  • gif
  • bmp
  • ico
  • tiff
  • webp
  • pnm
  • dds
  • tga
  • farbfeld
  • dxt
  • hdr

You can enable all these formats with image-all.

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

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

Note for Windows apps

By default, Windows will open a console with your application’s window. If you don’t want the console to be shown, use #![windows_subsystem = "windows"] at the beginning of your crate.

Re-exports

  • pub use shell::image;
  • pub use shell::keyboard_types;

Modules

  • Commands with special meaning, defined by Druid.
  • A data structure for representing widget trees.
  • An environment which is passed downward into the widget tree.
  • Immutable Data Structures for Rust
  • 2D geometry, with a focus on curves.
  • Implementations of Lens, a way of focusing on subfields of data.
  • Window, application, and context menus
  • A piet backend appropriate for the current platform.
  • Pre-configured, platform appropriate menus and menu items.
  • A component for embedding in another widget to provide consistent and extendable scrolling behavior
  • Additional unit tests that cross file or module boundaries.
  • Editing and displaying text.
  • Theme keys and initial values.
  • Common widgets.

Macros

  • Construct a lens accessing a type’s field
  • A macro to help implementation of WidgetWrapper for a direct wrapper. Use it in the body of the impl.
  • A macro to help implementation of WidgetWrapper for a wrapper of a typed pod. Use it in the body of the impl.

Structs

  • A 2D affine transform.
  • Handles initial setup of an application, and starts the runloop.
  • The top level application object.
  • Constraints for layout.
  • A handle to the system clipboard.
  • Data coupled with a type identifier.
  • An arbitrary command.
  • A platform-independent description of a custom cursor.
  • A context passed in to AppDelegate functions.
  • The struct implements the druid-shell WinHandler trait.
  • An environment passed down through all widget traversals.
  • A mutable context provided to event handling methods of widgets.
  • An error that occurs if an external event cannot be submitted. This probably means that the application has gone away.
  • A thing that can move into other threads and be used to submit commands back to the running application.
  • Options for file dialogs.
  • Information about the path to be opened or saved.
  • A description of a filetype, for specifying allowed types in a file dialog.
  • A description of a keyboard shortcut.
  • An in-memory pixel buffer.
  • Insets from the edges of a rectangle.
  • A typed Env key.
  • Information about a keyboard event.
  • A context provided to layout-handling methods of widgets.
  • A mutable context provided to the lifecycle method on widgets.
  • A description of a linear gradient in the unit rect, which can be resolved to a fixed gradient.
  • A string that can be localized based on the current locale.
  • A menu.
  • An item in a menu.
  • The modifiers.
  • Monitor struct containing data about a monitor on the system
  • A set of MouseButtons.
  • The state of the mouse for a click, mouse-up, move, or wheel event.
  • A message passed up the tree from a Widget to its ancestors.
  • A context passed to paint methods of widgets.
  • A 2D point.
  • A description of a radial gradient in the unit rect, which can be resolved to a fixed gradient.
  • A rectangle.
  • A union of rectangles, useful for describing an area that needs to be repainted.
  • Radii for each corner of a rounded rectangle.
  • Coordinate scaling between pixels and display points.
  • A specific area scaling state.
  • Information about the screen and monitors
  • An identifier for a particular command.
  • A wrapper type for Command payloads that should only be used once.
  • A 2D size.
  • A token that uniquely identifies a running timer.
  • A representation of a point relative to a unit rectangle.
  • A mutable context provided to data update methods of widgets.
  • The error type for environment access.
  • A 2D vector.
  • Information about the widget’s surroundings.
  • A unique identifier for a single Widget.
  • A container for one widget in the hierarchy.
  • Generic state for all widgets in the hierarchy.
  • Per-window state not owned by user code.
  • Window configuration that can be applied to a WindowBuilder, or to an existing WindowHandle. It does not include anything related to app data.
  • A description of a window to be instantiated.
  • A handle to a platform window object.
  • A unique identifier for a window.

Enums

  • Code is the physical position of a key.
  • A datatype representing color.
  • Mouse cursors.
  • An event, propagated downwards during event flow.
  • An enum for specifying whether an event was handled.
  • Internal events used by Druid inside WidgetPod.
  • Internal lifecycle events used by Druid inside WidgetPod.
  • Either a concrete T or a Key<T> that can be resolved in the Env.
  • Application life cycle events.
  • The location attribute contains an indication of the logical location of the key on the device.
  • An indicator of which mouse button was pressed.
  • Shell errors.
  • A representation of the active modifier keys.
  • An enum to simply combine the different possible raw window handle variants.
  • A platform-agnostic representation of keyboard modifiers, for command handling.
  • The target of a Command.
  • A dynamic type representing all values that can be stored in an environment.
  • Levels in the window system - Z order for display purposes. Describes the purpose of a window and should be mapped appropriately to match platform conventions.
  • Defines how a windows size should be determined
  • Contains the different states a Window can be in.

Traits

  • A type that provides hooks for handling and modifying top-level events.
  • A trait used to represent value types.
  • Window that wraps around a raw window handle.
  • A lens is a datatype that gives access to a part of a larger data structure.
  • Helpers for manipulating Lenses
  • The main trait for rendering graphics.
  • The Scalable trait describes how coordinates should be translated from display points into pixels and vice versa using a Scale.
  • Values which can be stored in an environment.
  • The trait implemented by all widgets.
  • A trait that provides extra methods for combining Widgets.

Type Definitions

  • A type identifier for the system clipboard.
  • The meaning (mapped value) of a keypress.

Derive Macros

  • Generates implementations of the Data trait.
  • Generates lenses to access the fields of a struct.