### Run Hello Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Introduces the basics of Druid, suitable for starting applications with text boxes and labels. ```bash cargo run --example hello ``` -------------------------------- ### Build Hello Web Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Builds the 'hello_web' example for web deployment using wasm-pack. See the example's README for prerequisites. ```bash cd druid/examples/hello_web wasm-pack build --out-dir pkg --out-name hello_web ``` -------------------------------- ### Build Web Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Builds the 'web' example for web deployment using wasm-pack. See the example's README for prerequisites. ```bash cd druid/examples/web wasm-pack build --out-dir pkg --out-name web ``` -------------------------------- ### Run Multiple Windows Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates the basic setup required for creating and managing multiple windows within a Druid application. ```bash cargo run --example multiwin ``` -------------------------------- ### Run Layout Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md An example demonstrating basic widget composition using only built-in widgets. ```bash cargo run --example layout ``` -------------------------------- ### Run Panels Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Similar to the layout example, this demonstrates splitting the screen into two segments. ```bash cargo run --example panels ``` -------------------------------- ### Run Markdown Preview Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md An example featuring a split view with markdown preview on the left and editable text on the right. ```bash cargo run --example markdown_preview ``` -------------------------------- ### Run Calc Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md A simple calculator application example. ```bash cargo run --example calc ``` -------------------------------- ### Run Transparency Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates how to make the application window transparent, allowing the desktop background to show through. ```bash cargo run --example transparency ``` -------------------------------- ### Run Sub Window Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Illustrates how to create a completely new window with shared state. Note: This example may not be fully functional. ```bash cargo run --example sub_window ``` -------------------------------- ### Run Flex Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates the capabilities of flex elements, allowing real-time interaction and modification of settings. ```bash cargo run --example flex ``` -------------------------------- ### Run TextBox Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates various configuration options available for the TextBox widget. ```bash cargo run --example textbox ``` -------------------------------- ### Run Scroll Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md An example demonstrating how to implement scrolling to display content that exceeds the visible screen area. ```bash cargo run --example scroll ``` -------------------------------- ### Run Open Save Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to implement cross-platform file opening and saving functionality, crucial for many applications. ```bash cargo run --example open_save ``` -------------------------------- ### Install GTK-3 on OpenBSD Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Install the GTK-3 package on OpenBSD. This is a prerequisite for using Druid on OpenBSD. ```sh > pkg_add gtk+3 ``` -------------------------------- ### Install GTK-3 development kit on Ubuntu Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Install the GTK-3 development kit on Ubuntu. This is a prerequisite for using Druid on Linux. ```sh > sudo apt-get install libgtk-3-dev ``` -------------------------------- ### Run Cursor Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates setting the cursor icon and using custom cursors. Requires the 'image' and 'png' features. ```bash cargo run --example cursor --features="image png" ``` -------------------------------- ### Run View Switcher Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates a view switcher that allows dynamic switching of widgets, offering more control than tabs. ```bash cargo run --example view_switcher ``` -------------------------------- ### Install mdBook Source: https://github.com/linebender/druid/blob/master/docs/README.md Install the mdBook tool from crates.io using cargo. This is required for editing and previewing documentation. ```bash cargo install mdbook ``` -------------------------------- ### Run Text Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Illustrates the effects of TextAlignment and LineBreaker types on text rendering. ```bash cargo run --example text ``` -------------------------------- ### Run SVG Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates how to display an SVG as a widget. Requires the 'svg' feature to be enabled. ```bash cargo run --example svg --features="svg" ``` -------------------------------- ### Shell: Install GTK+3 on OpenBSD Source: https://github.com/linebender/druid/blob/master/druid/README.md Command to install the GTK+3 development libraries on OpenBSD using the `pkg_add` utility, a requirement for Druid on Linux and OpenBSD. ```sh pkg_add gtk+3 ``` -------------------------------- ### Run List Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to add and delete items from lists dynamically. Requires the 'im' feature. ```bash cargo run --example list --features="im" ``` -------------------------------- ### Run Anim Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates how to create a simple animation using `Event::AnimFrame`. ```bash cargo run --example anim ``` -------------------------------- ### Run Tabs Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates how to use tabs to separate different portions of the UI. Requires the 'im' feature. ```bash cargo run --example tabs --features="im" ``` -------------------------------- ### Run Timer Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to use timers to send events to widgets at specific future points in time. ```bash cargo run --example timer ``` -------------------------------- ### Run Split Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates the split widget, which allows placing multiple widgets next to or on top of each other and resizing them. ```bash cargo run --example split_demo ``` -------------------------------- ### Serve Directory with http Source: https://github.com/linebender/druid/blob/master/druid/examples/hello_web/README.md Run this command to start a simple HTTP server in the current directory. This is used to serve the generated web application files. ```bash > http ``` -------------------------------- ### Install GTK-3 development kit on Fedora Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Install the GTK-3 development kit and GLib development files on Fedora. This is a prerequisite for using Druid on Linux. ```sh > sudo dnf install gtk3-devel glib2-devel ``` -------------------------------- ### Run Image Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Showcases various options for handling images, including real-time adjustments. Requires 'image' and 'png' features. ```bash cargo run --example image --features "image png" ``` -------------------------------- ### Run Input Region Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates window features like input regions, always-on-top, and titlebar visibility. Includes interactive elements for testing these features. ```bash cargo run --example input_region ``` -------------------------------- ### Run Lens Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates the use of lenses in Druid for navigating and manipulating parts of the application state. ```bash cargo run --example lens ``` -------------------------------- ### Install GTK+3 Development Files on Ubuntu Source: https://github.com/linebender/druid/blob/master/README.md This command installs the necessary GTK+3 development files on Ubuntu-based systems, which are required for Druid on Linux. ```bash sudo apt-get install libgtk-3-dev ``` -------------------------------- ### Run Event Viewer Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md A debugging tool that prints mouse and keyboard events as they are received by Druid. ```bash cargo run --example event_viewer ``` -------------------------------- ### Run Custom Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to utilize all methods on `PaintCtx` for drawing on a canvas, including text, images, and curves. ```bash cargo run --example custom_widget ``` -------------------------------- ### Run Widget Gallery Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Presents a gallery of simple widgets with their default styling. These widgets are interactive but their styling cannot be modified. Requires 'svg', 'im', 'image', and 'png' features. ```bash cargo run --example widget_gallery --features="svg im image png" ``` -------------------------------- ### Run Invalidation Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to use debug invalidation regions within widgets, including examples with built-in widgets. Requires the 'im' feature. ```bash cargo run --example invalidation --features="im" ``` -------------------------------- ### Run Identity Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Illustrates using identity to send commands to specific widgets, such as colorwells and buttons, rather than broadcasting them. ```bash cargo run --example identity ``` -------------------------------- ### Launch a Druid Application with a Counter Example Source: https://context7.com/linebender/druid/llms.txt This snippet demonstrates how to bootstrap a Druid application using AppLauncher. It includes a simple counter UI and configures the environment by setting a window background color. ```rust use druid::widget::{Flex, Label}; use druid::{AppLauncher, Data, Env, Lens, LocalizedString, PlatformError, Widget, WidgetExt, WindowDesc}; #[derive(Clone, Data, Lens)] struct AppState { count: u32, } fn build_ui() -> impl Widget { let label = Label::new(|state: &AppState, _env: &Env| format!("Count: {}", state.count)) .padding(10.0) .center(); let button = Button::new("Increment") .on_click(|_ctx, state: &mut AppState, _env| state.count += 1) .padding(5.0); Flex::column().with_child(label).with_child(button) } fn main() -> Result<(), PlatformError> { let window = WindowDesc::new(build_ui()) .title(LocalizedString::new("Counter App")) .window_size((400.0, 300.0)); AppLauncher::with_window(window) .configure_env(|env, _state| { // Override theme keys before the app starts env.set(druid::theme::WINDOW_BACKGROUND_COLOR, druid::Color::grey8(240)); }) .log_to_console() .launch(AppState { count: 0 }) } ``` -------------------------------- ### Run Styled Text Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Showcases various styling options for text in Druid, such as color, size, and monospace. ```bash cargo run --example styled_text ``` -------------------------------- ### Run Slider and RangeSlider Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows the settings for Slider and RangeSlider widgets, enabling users to pick a value within a specified range. ```bash cargo run --example slider ``` -------------------------------- ### Complete Druid Application Code Example Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md This snippet shows a complete `main.rs` file integrating all previously shown widgets and data structures for a functional todo list application. ```rust use druid::widget::{Button, Container, Flex, Label, List, TextBox}; use druid::{AppLauncher, Data, Lens, LocalizedString, Widget, WidgetExt, WindowDesc}; use std::collections::VecDeque; #[derive(Clone, Data, Lens)] pub struct TodoList { pub items: VecDeque, pub next_item: String, } fn build_ui() -> impl Widget { let list = List::new(|| { Label::new(|data: &String, _env: &_| data.clone()) }).lens(TodoList::items); let input = TextBox::new() .lens(TodoList::next_item) .with_placeholder("New item..."); let button = Button::new("Add Item") .on_click(|_ctx, data: &mut TodoList, _env| { if !data.next_item.is_empty() { data.items.push(data.next_item.clone()); data.next_item.clear(); } }); Flex::row() .with_child(Container::new(list).width(200.0)) .with_child(input) .with_child(button) } fn main() { let main_window = WindowDesc::new(build_ui()); let data = TodoList { items: VecDeque::new(), next_item: String::new(), }; AppLauncher::with_window(main_window) .launch(data) .expect("Failed to launch application"); } ``` -------------------------------- ### Run Value Formatting Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to parse and validate text input for numeric values, as Druid does not have specific numeric textboxes. ```bash cargo run ``` -------------------------------- ### Run Either Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates the `Either` widget, which displays one of two children based on a predicate. Useful for loading screens or error messages. ```bash cargo run --example either ``` -------------------------------- ### Rust: Simple Counter Example App Source: https://github.com/linebender/druid/blob/master/druid/README.md Demonstrates a basic counter application using Druid widgets like Label, Button, and Flex. Requires `druid` dependency. The UI is built dynamically. ```rust use druid::widget::{Button, Flex, Label}; use druid::{AppLauncher, LocalizedString, PlatformError, Widget, WidgetExt, WindowDesc}; fn main() -> Result<(), PlatformError> { let main_window = WindowDesc::new(ui_builder()); let data = 0_u32; AppLauncher::with_window(main_window) .log_to_console() .launch(data) } fn ui_builder() -> impl Widget { // The label text will be computed dynamically based on the current locale and count let text = LocalizedString::new("hello-counter").with_arg("count", |data: &u32, _env| (*data).into()); let label = Label::new(text).padding(5.0).center(); let button = Button::new("increment") .on_click(|_ctx, data, _env| *data += 1) .padding(5.0); Flex::column().with_child(label).with_child(button) } ``` -------------------------------- ### Run Async Event Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Shows how to receive data from an external source and update the UI asynchronously. This is suitable for long-running, independent data sources. ```bash cargo run --example async_event ``` -------------------------------- ### Run Disabled Widget Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Showcases widgets that support a disabled state, useful for preventing user input. ```bash cargo run --example disabled ``` -------------------------------- ### Run Game of Life Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md A simple implementation of Conway's Game of Life, featuring adjustable evolution speed and pause functionality. ```bash cargo run --example game_of_life ``` -------------------------------- ### Run Switches Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Showcases the use of Druid's built-in switches, including on/off toggles and up/down controls for incrementing numeric values. ```bash cargo run --example switches ``` -------------------------------- ### Run Scroll Colors Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Demonstrates scrolling through a gradient square divided into smaller colored squares. Offers alternative methods to achieve similar effects. ```bash cargo run --example scroll_colors ``` -------------------------------- ### Druid Key Declaration Examples Source: https://github.com/linebender/druid/blob/master/docs/src/06_env.md Demonstrates how to declare `Key`s for use with the `Env`. It highlights the convention of using `const` with unique, namespaced identifiers for custom keys. ```rust const BAD_NAME: Key = Key::new("height"); const GOOD_NAME: Key = Key::new("com.example.my-app.main-view-height"); ``` -------------------------------- ### Identical Implementation Snippet Source: https://github.com/linebender/druid/blob/master/docs/src/05_lens.md This snippet is identical to a previous example and serves as a placeholder or continuation. No specific usage notes are provided for this exact block. ```rust // .. identical to previous example } ``` -------------------------------- ### Using LensWrap with Lenses Source: https://github.com/linebender/druid/blob/master/docs/src/03_data.md Example of using `LensWrap` to compose widgets that operate on different subsets of data using lenses. `Foobar::foo` and `Foobar::bar` are generated lenses. ```rust fn build_foobar() -> impl Widget { Flex::column() .with_child( LensWrap::new(build_foo(), Foobar::foo), ) .with_child( LensWrap::new(build_bar(), Foobar::bar), ) } ``` -------------------------------- ### Run Blocking Function Example Source: https://github.com/linebender/druid/blob/master/druid/examples/readme.md Illustrates fetching data from disk or network without blocking the UI thread. Tasks are run in a separate thread and data is sent back as it arrives. ```bash cargo run --example blocking_function ``` -------------------------------- ### Install cargo-edit Source: https://github.com/linebender/druid/blob/master/CONTRIBUTING.md Installs the cargo-edit tool, which is used for managing Rust project dependencies. ```sh cargo install cargo-edit ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/linebender/druid/blob/master/docs/README.md Serve the documentation locally to preview changes. Navigate to the 'docs/' directory and run the command. The documentation will be available at http://localhost:3000. ```bash mdbook serve ``` -------------------------------- ### Build Documentation Source: https://github.com/linebender/druid/blob/master/docs/README.md Build the documentation into static HTML files from the project root. The output will be placed in the 'docs/book' folder. ```bash mdbook build docs ``` -------------------------------- ### Describe a Druid Window with Custom Properties Source: https://context7.com/linebender/druid/llms.txt This snippet shows how to define a window using WindowDesc, customizing its title, size, resizability, and title bar visibility. It also demonstrates launching multiple windows. ```rust use druid::{WindowDesc, WindowSizePolicy, LocalizedString, Data, Lens}; use druid::widget::Label; #[derive(Clone, Data, Lens)] struct MyState { name: String } let window = WindowDesc::new(Label::new(|s: &MyState, _| s.name.clone())) .title(LocalizedString::new("my-app")) .window_size((800.0, 600.0)) .resizable(true) .show_titlebar(true) .transparent(false); // Multiple windows can be opened at launch: use druid::AppLauncher; AppLauncher::with_window(window) // .with_window(second_window) // add more windows here .launch(MyState { name: "World".into() }) .expect("launch failed"); ``` -------------------------------- ### Implement Button Callback in Druid Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Add a callback to a Druid button to mutate application data when clicked. This example shows how to add an item to a list. ```rust fn build_ui() -> impl Widget { // ... Button::new("Add Item") .on_click(|_ctx, data: &mut TodoList, _env| { data.items.push("New Item".to_string()); }), // ... } ``` -------------------------------- ### Create a new Druid project and add dependency Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Create a new Rust binary crate for your Druid application and add the `druid` crate as a dependency using cargo. ```sh > cargo new my-druid-app Created binary (application) `my-druid-app` package > cd my-druid-app > cargo add druid ``` -------------------------------- ### Using WidgetExt for Widget Customization in Druid Source: https://context7.com/linebender/druid/llms.txt Demonstrates common builder methods from `WidgetExt` for styling and behavior customization. Includes padding, sizing, alignment, disabling widgets based on state, and applying background/border styles. ```rust use druid::widget::{Label, Slider, Flex}; use druid::{Color, WidgetExt, Data, Lens}; #[derive(Clone, Data, Lens)] struct State { volume: f64, muted: bool } fn build_controls() -> impl druid::Widget { let label = Label::new("Volume") .padding(8.0) .center() .fix_width(100.0); let slider = Slider::new() .with_range(0.0, 1.0) .lens(State::volume) .disabled_if(|state: &State, _env| state.muted) // grey out when muted .expand_width() .padding(5.0); let styled = Label::new("Warning!") .background(Color::rgb8(255, 200, 0)) .border(Color::RED, 2.0) .rounded(4.0) .padding(10.0); Flex::row() .with_child(label) .with_flex_child(slider, 1.0) .with_child(styled) } ``` -------------------------------- ### Create a dynamic UI for a todo list using List and Label::dynamic Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Build a UI that dynamically displays a list of strings using the `List` widget and `Label::dynamic`. The `List` widget iterates over the `TodoList` data, and `Label::dynamic` creates a label for each item. ```rust use druid::widget::{Label, List}; use druid::im::Vector; use druid::Widget; fn build_ui() -> impl Widget { List::new(|| Label::new(|data: &String, _env| data.to_string())) } ``` -------------------------------- ### Implementing a Custom Widget in Druid Source: https://context7.com/linebender/druid/llms.txt Example of implementing the `Widget` trait to create a custom widget. This widget paints a colored square and changes its color when clicked. Requires implementing `event`, `lifecycle`, `update`, `layout`, and `paint` methods. ```rust use druid::widget::prelude::*; use druid::{Color, Point, Rect}; // A widget that paints a colored square and changes color on click struct ColorSquare { color: Color, hot_color: Color, } impl Widget<()> for ColorSquare { fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut (), _env: &Env) { match event { Event::MouseDown(_) => { std::mem::swap(&mut self.color, &mut self.hot_color); ctx.request_paint(); } _ => {} } } fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &(), _env: &Env) {} fn update(&mut self, ctx: &mut UpdateCtx, _old: &(), _new: &(), _env: &Env) { ctx.request_paint(); } fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &(), _env: &Env) -> Size { bc.constrain(Size::new(100.0, 100.0)) } fn paint(&mut self, ctx: &mut PaintCtx, _data: &(), _env: &Env) { let rect = ctx.size().to_rect(); ctx.fill(rect, &self.color); } } // Use it: let widget = ColorSquare { color: Color::BLUE, hot_color: Color::RED, }; ``` -------------------------------- ### Drawing with Bezier Paths and Rectangles in Druid Source: https://github.com/linebender/druid/blob/master/druid/README.md Demonstrates how to create and draw bezier paths and rectangles using Druid's Piet integration. Requires importing BezPath, Point, Rect from druid::kurbo and Color from druid::piet. ```rust use druid::kurbo::{BezPath, Point, Rect}; use druid::piet::Color; // Create an arbitrary bezier path // (ctx.size() returns the size of the layout rect we're painting in) let mut path = BezPath::new(); path.move_to(Point::ORIGIN); path.quad_to( (80.0, 90.0), (ctx.size().width, ctx.size().height), ); // Create a color let stroke_color = Color::rgb8(0x00, 0x80, 0x00); // Stroke the path with thickness 1.0 ctx.stroke(path, &stroke_color, 1.0); // Rectangles: the path for practical people let rect = Rect::from_origin_size((10., 10.), (100., 100.)); // Note the Color:rgba8 which includes an alpha channel (7F in this case) let fill_color = Color::rgba8(0x00, 0x00, 0x00, 0x7F); ctx.fill(rect, &fill_color); ``` -------------------------------- ### Build a UI with multiple widgets using container widgets Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Construct a UI with multiple widgets, including nested containers like `Split`, `Flex`, and `Container`, to create a two-column layout for a todo-list application. ```rust use druid::widget::{Container, Flex, Label, Split, Button}; use druid::{Color, UnitPoint, Widget, WindowDesc}; fn build_ui() -> impl Widget<()> { Split::columns( Flex::row() .with_child(Label::new("List")) .with_child(Container::new(Label::new("Placeholder for button")) .background(Color::rgb8(0, 0, 255)) .padding(5.0)) .padding(10.0), Container::new(Label::new("Another column")) .background(Color::rgb8(0, 255, 0)) .padding(5.0) ) .split_point(0.5) .bar_size(1.0) .border(Color::BLACK, 1.0) .padding(10.0) } ``` -------------------------------- ### Create a Stack of Labels using Flex Builder Source: https://github.com/linebender/druid/blob/master/docs/src/04_widget.md Demonstrates how to create a vertical stack of three labels using the `flex_row` or `flex_column` builder methods on container widgets. ```rust Flex::column() .with_child(Label::new("First"), 0.0) .with_child(Label::new("Second"), 1.0) .with_child(Label::new("Third"), 0.0) ``` -------------------------------- ### Define and Use Themed Environment Keys with Env and Key Source: https://context7.com/linebender/druid/llms.txt Define typed keys for theme parameters like colors and fonts. Use EnvScope to override environment settings for specific subtrees. ```rust use druid::{Key, Color, Env, Data, Lens, Widget, WidgetExt, AppLauncher, WindowDesc}; use druid::widget::{Label, Flex, EnvScope}; // Define typed keys as constants const BRAND_COLOR: Key = Key::new("com.myapp.brand-color"); const FONT_SIZE: Key = Key::new("com.myapp.font-size"); #[derive(Clone, Data)] struct State; fn build_ui() -> impl Widget { let branded_label = Label::new("Hello!") .with_text_color(BRAND_COLOR) .with_text_size(FONT_SIZE); // Override env for a subtree only let dark_section = EnvScope::new( |env, _data| { env.set(druid::theme::BACKGROUND_LIGHT, Color::grey8(30)); env.set(druid::theme::LABEL_COLOR, Color::WHITE); }, Label::new("Dark section"), ); Flex::column() .with_child(branded_label) .with_child(dark_section) } fn main() { AppLauncher::with_window(WindowDesc::new(build_ui())) .configure_env(|env, _state| { env.set(BRAND_COLOR, Color::rgb8(0, 120, 215)); env.set(FONT_SIZE, 18.0); }) .launch(State) .expect("launch failed"); } ``` -------------------------------- ### Display a minimal window with a label in Druid Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md A minimal Druid application that displays a window with a single label. It uses `AppLauncher` to create and launch the window. ```rust use druid::widget::{Label}; use druid::{AppLauncher, WindowDesc}; fn main() { AppLauncher::default() .configure_web() .launch(window()) .expect("Failed to launch application"); } fn window() -> WindowDesc<'static> { WindowDesc::new .title("my-druid-app") .window_size((100.0, 300.0)) .build_ui(|_| { Label::new("Hello World!") }) } ``` -------------------------------- ### Wrap Widget with LensWrap using lens! Macro Source: https://github.com/linebender/druid/blob/master/druid/README.md Shows how to construct lenses on-demand using the `lens!` macro, which is particularly useful for types defined in other crates or for more complex lens compositions. ```rust LensWrap::new(WidgetThatExpectsf64::new(), lens!(AppState, value)); ``` -------------------------------- ### Construct a Stepper Widget with Builder Methods Source: https://github.com/linebender/druid/blob/master/docs/src/04_widget.md Illustrates the use of builder-style methods for constructing a Stepper widget. These methods are directly available on the widget type. ```rust Stepper::new(Rangef::new(0.0, 100.0)) ``` -------------------------------- ### Launch Druid application with hardcoded todo list data Source: https://github.com/linebender/druid/blob/master/docs/src/02_getting_started.md Launch a Druid application with a hardcoded `TodoList` data. This demonstrates how to provide initial data to the UI for testing purposes. ```rust use druid::widget::{Container, Flex, Label, Split, Button}; use druid::{Color, UnitPoint, Widget, WindowDesc, AppLauncher}; use druid::im::Vector; type TodoList = Vector; fn main() { let data = TodoList::from(vec![ "Write code".to_string(), "Ship it".to_string(), ]); AppLauncher::default() .configure_web() .launch(window(data)) .expect("Failed to launch application"); } fn window(data: TodoList) -> WindowDesc<'static> { WindowDesc::new .title("my-druid-app") .window_size((100.0, 300.0)) .build_ui(move |cx| { Split::columns( Flex::row() .with_child(Label::new("List")) .with_child(Container::new(Label::new("Placeholder for button")) .background(Color::rgb8(0, 0, 255)) .padding(5.0)) .padding(10.0), Container::new(Label::new("Another column")) .background(Color::rgb8(0, 255, 0)) .padding(5.0) ) .split_point(0.5) .bar_size(1.0) .border(Color::BLACK, 1.0) .padding(10.0) }) .log_requests() .with_initial_data(data) } ``` -------------------------------- ### Druid Container Widgets: Scroll, Split, Tabs Source: https://context7.com/linebender/druid/llms.txt Demonstrates the usage of Scroll for making widgets scrollable, Split for creating resizable panes, and Tabs for organizing content into labeled pages. Requires importing relevant widgets from druid::widget. ```rust use druid::widget::{Flex, Label, Scroll, Split, Tabs, TabInfo}; use druid::{Data, Widget, WidgetExt}; #[derive(Clone, Data)] struct State; fn build_layout() -> impl Widget { // Scroll: make a widget scrollable let scrollable_content = Scroll::new( Flex::column().with_child(Label::new("Line 1")) .with_child(Label::new("Line 2")) // ... many more children ).vertical(); // Split: resizable split pane let split_view = Split::columns( Label::new("Left panel").center(), Label::new("Right panel").center(), ) .split_point(0.3) // 30% / 70% .draggable(true) .solid_bar(true) .min_size(100.0, 100.0); // Tabs: tabbed navigation let tabbed = Tabs::new() .with_tab("Overview", Label::new("Overview content").center()) .with_tab("Settings", Label::new("Settings content").center()) .with_tab("About", Label::new("About content").center()); // Combine them all Flex::column() .with_flex_child(tabbed, 1.0) .with_child(split_view.fix_height(200.0)) } ``` -------------------------------- ### Run Pre-Push Checks with Git Hook Source: https://github.com/linebender/druid/blob/master/CONTRIBUTING.md This script should be placed in `druid/.git/hooks/pre-push` to automate checks before pushing code. It runs cargo fmt, clippy, and tests for various Druid components. ```sh #!/bin/sh set -e echo "cargo fmt" cargo fmt --all -- --check echo "cargo clippy druid-shell" cargo clippy --manifest-path=druid-shell/Cargo.toml --all-targets --features=raw-win-handle -- -D warnings echo "cargo clippy druid" cargo clippy --manifest-path=druid/Cargo.toml --all-targets --features=svg,image,im,raw-win-handle -- -D warnings echo "cargo clippy druid (wasm)" cargo clippy --manifest-path=druid/Cargo.toml --all-targets --features=image,im --target wasm32-unknown-unknown -- -D warnings echo "cargo clippy druid-derive" cargo clippy --manifest-path=druid-derive/Cargo.toml --all-targets -- -D warnings echo "cargo clippy book examples" cargo clippy --manifest-path=docs/book_examples/Cargo.toml --all-targets -- -D warnings echo "cargo test druid-shell" cargo test --manifest-path=druid-shell/Cargo.toml echo "cargo test druid" cargo test --manifest-path=druid/Cargo.toml --features=svg,image,im echo "cargo test druid-derive" cargo test --manifest-path=druid-derive/Cargo.toml echo "cargo test book examples" cargo test --manifest-path=docs/book_examples/Cargo.toml ``` -------------------------------- ### Enable Git Symbolic Links on Windows Source: https://github.com/linebender/druid/blob/master/CONTRIBUTING.md Commands to test and enable symbolic link support for Git on Windows. Requires administrative privileges for system configuration. ```sh echo "Hello" > original.txt mklink link.txt original.txt type link.txt ``` ```sh git config --system core.symlinks true ``` ```sh git config --local core.symlinks true git reset --hard ``` -------------------------------- ### Build WebAssembly Module with wasm-pack Source: https://github.com/linebender/druid/blob/master/druid/examples/hello_web/README.md Use this command to build the Rust code into a JavaScript module for web deployment. The --target web flag specifies the output format, and --dev enables development mode. ```bash > wasm-pack build --target web --dev ``` -------------------------------- ### Build a Widget with Composed Buttons Source: https://github.com/linebender/druid/blob/master/druid/README.md Demonstrates composing multiple Button widgets within a Flex column and wrapping them in a Scroll widget. This is a common pattern for creating scrollable lists of interactive elements. ```rust fn build_widget() -> impl Widget { let mut col = Flex::column(); for i in 0..30 { let button = Button::new(format!("Button {}", i).padding(5.0); col.add_child(button); } Scroll::new(col) } ``` -------------------------------- ### Sized Painter for Color Swatch Source: https://github.com/linebender/druid/blob/master/docs/src/08_widgets_in_depth.md To give a `Painter` a specific size, wrap it in a `SizedBox` and provide explicit constraints. ```rust SizedBox::new(Painter::new(|ctx| { let size = ctx.size(); let color = Color::RED; let rect = size.to_rect().to_rounded_rect(5.0); ctx.fill(rect, &color); })) .width(50.0) .height(50.0) ``` -------------------------------- ### Druid LensExt Combinators for Data Transformation Source: https://context7.com/linebender/druid/llms.txt Shows how to use LensExt combinators like .then(), .deref(), .index(), .in_arc(), and .not() to compose and transform lenses for complex data projections. Requires Data, Lens, and LensExt traits from druid. ```rust use druid::{Data, Lens, LensExt}; use druid::lens; use std::sync::Arc; #[derive(Clone, Data, Lens)] struct Outer { inner: Inner } #[derive(Clone, Data, Lens)] struct Inner { values: Arc> } // Compose: Outer → Inner → values let to_values = Outer::inner.then(Inner::values); // Deref Arc> to Vec let derefed = Outer::inner.then(Inner::values).deref(); // Index: pick element 2 of a Vec (via slice ref) let elem2 = lens::Identity.as_ref().index(2usize); // in_arc: COW semantics on Arc let cow = lens::Identity.index(0usize).in_arc(); let mut data = Arc::new(vec![1.0f64, 2.0, 3.0]); let original = data.clone(); cow.put(&mut data, 1.0); // no clone — same value assert!(Arc::ptr_eq(&original, &data)); cow.put(&mut data, 99.0); // clones only now assert_eq!(data[0], 99.0); // not: negate a boolean field #[derive(Lens)] struct Flags { enabled: bool } let disabled_lens = Flags::enabled.not(); // map: synthesize a derived value let halved = lens!(Outer, inner).then(Inner::values) .map(|_v: &Arc>| 0.0f64, |_v, _new| {}); // example shape ``` -------------------------------- ### Composing and Mapping Lenses in Druid Source: https://context7.com/linebender/druid/llms.txt Demonstrates composing lenses using `.then()` and mapping lenses with custom closures to adapt data ranges or transformations. The `lens!` macro provides a concise way to create lenses for struct fields or tuple indices. ```rust // Compose two lenses: Outer::inner.then(Inner::field) #[derive(Clone, Data, Lens)] struct Outer { inner: Inner } #[derive(Clone, Data, Lens)] struct Inner { value: f64 } let composed = Outer::inner.then(Inner::value); // Map a lens — adapt f64 range 0..2 to 0..1 for a Slider use druid::widget::Slider; let scaled = druid::lens::Identity.map(|x: &f64| x / 2.0, |x, y| *x = y * 2.0); // lens! macro for struct fields or tuple indices let tuple_lens = druid::lens!((bool, f64), 1); // accesses the f64 in a tuple ``` -------------------------------- ### Wrap Widget with LensWrap using Associated Constant Source: https://github.com/linebender/druid/blob/master/druid/README.md Illustrates how to use `LensWrap` to connect a widget to a specific field of a data structure using the field's associated constant name. ```rust LensWrap::new(WidgetThatExpectsf64::new(), AppState::value); ```