Last active
May 26, 2020 01:03
-
-
Save covercash2/0ef3185cf25635900363da5b71e4e268 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use druid::{AppLauncher, PlatformError, Widget, WidgetExt, WindowDesc}; | |
use druid::{ | |
widget::{Flex, Label, Painter, TextBox}, | |
Color, Data, Lens, RenderContext, | |
}; | |
/// state data. | |
/// `string` is updated via the `TextBox` | |
#[derive(Clone, Debug, Data, Lens)] | |
pub struct State { | |
string: String, | |
} | |
impl State { | |
fn good(&self) -> bool { | |
is_even(self.string.len()) | |
} | |
} | |
/// builds a widget to show path information. | |
pub fn path_widget() -> impl Widget<State> { | |
let painter = Painter::new(|ctx, state: &State, _env| { | |
let bounds = ctx.size().to_rect(); | |
let color = if state.good() { | |
Color::rgb(0, 1, 0) | |
} else { | |
Color::rgb(1, 0, 1) | |
}; | |
// draw the border | |
ctx.stroke(bounds.inset(-0.5), &color, 2.0); | |
}); | |
let textbox = TextBox::new() | |
.with_placeholder("./directory") | |
.expand_width() | |
.lens(State::string) | |
.padding(4.0) | |
.background(painter); | |
// a dummy label that triggers the expected draw | |
let state_label = Label::dynamic(|state: &State, _| { | |
if state.good() { | |
String::from("good state!") | |
} else { | |
String::from("not good :(") | |
} | |
}); | |
Flex::column().with_flex_child(textbox, 1.0) | |
// uncomment this line to fix the drawing! | |
//.with_flex_child(state_label, 1.0) | |
} | |
fn main() -> Result<(), PlatformError> { | |
simple_logger::init().expect("unable to initialize logger"); | |
let ui_builder = path_widget; | |
// new state at root | |
let state = State::from("/"); | |
AppLauncher::with_window(WindowDesc::new(ui_builder)).launch(state)?; | |
Ok(()) | |
} | |
// details | |
// ------------------------------------------------- | |
fn is_even(n: usize) -> bool { | |
n & 1 == 0 | |
} | |
impl<S: Into<String>> From<S> for State { | |
fn from(s: S) -> State { | |
let string = s.into(); | |
State { string } | |
} | |
} | |
impl Default for State { | |
fn default() -> State { | |
State::from("starting string") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment