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 lens::Lens;
pub use lens::LensExt;
pub use widget::Widget;
pub use widget::WidgetExt;
pub use widget::WidgetId;
pub use shell::image;
pub use shell::keyboard_types;

Modules§

commands
Commands with special meaning, defined by Druid.
debug_state
A data structure for representing widget trees.
env
An environment which is passed downward into the widget tree.
im
Immutable Data Structures for Rust
kurbo
2D geometry, with a focus on curves.
lens
Implementations of Lens, a way of focusing on subfields of data.
menu
Window, application, and context menus
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
tests
Additional unit tests that cross file or module boundaries.
text
Editing and displaying text.
theme
Theme keys and initial values.
widget
Common widgets.

Macros§

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

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.
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 specifying allowed types in a file dialog.
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.
Menu
A menu.
MenuItem
An item in a menu.
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.
RoundedRectRadii
Radii for each corner of a rounded rectangle.
Scale
Coordinate scaling between pixels and display points.
ScaledArea
A specific area scaling state.
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.
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.
ValueTypeError
The error type for environment access.
Vec2
A 2D vector.
ViewContext
Information about the widget’s surroundings.
WidgetPod
A container for one widget in the hierarchy.
WidgetState
Generic state for all widgets 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.
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.
RawWindowHandle
A window handle for a particular windowing system.
SysMods
A platform-agnostic representation of keyboard modifiers, for command handling.
Target
The target of a Command.
Value
A dynamic type representing all values that can be stored in an environment.
WindowLevel
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.
WindowSizePolicy
Defines how a windows size should be determined
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.
HasRawWindowHandle
Window that wraps around a raw window handle.
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.

Type Aliases§

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

Derive Macros§

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