hello/
hello.rs

1// Copyright 2019 The Druid Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This is a very small example of how to setup a Druid application.
16//! It does the almost bare minimum while still being useful.
17
18// On Windows platform, don't show a console when opening the app.
19#![windows_subsystem = "windows"]
20
21use druid::widget::prelude::*;
22use druid::widget::{Flex, Label, TextBox};
23use druid::{AppLauncher, Data, Lens, UnitPoint, WidgetExt, WindowDesc};
24
25const VERTICAL_WIDGET_SPACING: f64 = 20.0;
26const TEXT_BOX_WIDTH: f64 = 200.0;
27
28#[derive(Clone, Data, Lens)]
29struct HelloState {
30    name: String,
31}
32
33pub fn main() {
34    // describe the main window
35    let main_window = WindowDesc::new(build_root_widget())
36        .title("Hello World!")
37        .window_size((400.0, 400.0));
38
39    // create the initial app state
40    let initial_state: HelloState = HelloState {
41        name: "World".into(),
42    };
43
44    // start the application. Here we pass in the application state.
45    AppLauncher::with_window(main_window)
46        .log_to_console()
47        .launch(initial_state)
48        .expect("Failed to launch application");
49}
50
51fn build_root_widget() -> impl Widget<HelloState> {
52    // a label that will determine its text based on the current app data.
53    let label = Label::new(|data: &HelloState, _env: &Env| {
54        if data.name.is_empty() {
55            "Hello anybody!?".to_string()
56        } else {
57            format!("Hello {}!", data.name)
58        }
59    })
60    .with_text_size(32.0);
61
62    // a textbox that modifies `name`.
63    let textbox = TextBox::new()
64        .with_placeholder("Who are we greeting?")
65        .with_text_size(18.0)
66        .fix_width(TEXT_BOX_WIDTH)
67        .lens(HelloState::name);
68
69    // arrange the two widgets vertically, with some padding
70    Flex::column()
71        .with_child(label)
72        .with_spacer(VERTICAL_WIDGET_SPACING)
73        .with_child(textbox)
74        .align_vertical(UnitPoint::CENTER)
75}