Skip to content

Commit

Permalink
Widget adaptor for string parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Ralith committed Dec 8, 2019
1 parent 44a8fbf commit 96c8cad
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 1 deletion.
37 changes: 37 additions & 0 deletions druid/examples/parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2019 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use druid::widget::{Align, DynLabel, Flex, Padding, Parse, TextBox};
use druid::{AppLauncher, Widget, WindowDesc};

fn main() {
let main_window = WindowDesc::new(ui_builder);
let data = Some(0);
AppLauncher::with_window(main_window)
.use_simple_logger()
.launch(data)
.expect("launch failed");
}

fn ui_builder() -> impl Widget<Option<u32>> {
let label = DynLabel::new(|data: &Option<u32>, _env| {
data.map_or_else(|| "Invalid input".into(), |x| x.to_string())
});
let input = Parse::new(TextBox::new());

let mut col = Flex::column();
col.add_child(Align::centered(Padding::new(5.0, label)), 1.0);
col.add_child(Padding::new(5.0, input), 1.0);
col
}
3 changes: 3 additions & 0 deletions druid/src/widget/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,6 @@ pub use widget_ext::WidgetExt;

mod list;
pub use crate::widget::list::{List, ListIter};

mod parse;
pub use crate::widget::parse::Parse;
65 changes: 65 additions & 0 deletions druid/src/widget/parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::fmt::Display;
use std::mem;
use std::str::FromStr;

use crate::kurbo::Size;
use crate::{
BaseState, BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, UpdateCtx, Widget,
};

/// Converts a `Widget<String>` to a `Widget<Option<T>>`, mapping parse errors to None
pub struct Parse<T> {
widget: T,
state: String,
}

impl<T> Parse<T> {
pub fn new(widget: T) -> Self {
Self {
widget,
state: String::new(),
}
}
}

impl<T: FromStr + Display + Data, W: Widget<String>> Widget<Option<T>> for Parse<W> {
fn update(
&mut self,
ctx: &mut UpdateCtx,
old_data: Option<&Option<T>>,
data: &Option<T>,
env: &Env,
) {
let old = match *data {
None => return, // Don't clobber the input
Some(ref x) => mem::replace(&mut self.state, x.to_string()),
};
let old = old_data.map(|_| old);
self.widget.update(ctx, old.as_ref(), &self.state, env)
}

fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut Option<T>, env: &Env) {
self.widget.event(ctx, event, &mut self.state, env);
*data = self.state.parse().ok();
}

fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &Option<T>,
env: &Env,
) -> Size {
self.widget.layout(ctx, bc, &self.state, env)
}

fn paint(
&mut self,
paint: &mut PaintCtx,
base_state: &BaseState,
_data: &Option<T>,
env: &Env,
) {
self.widget.paint(paint, base_state, &self.state, env)
}
}
10 changes: 9 additions & 1 deletion druid/src/widget/widget_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use crate::kurbo::Insets;
use crate::piet::{PaintBrush, UnitPoint};

use super::{Align, Container, EnvScope, Padding, SizedBox};
use super::{Align, Container, EnvScope, Padding, Parse, SizedBox};
use crate::{Data, Env, Lens, LensWrap, Widget};

/// A trait that provides extra methods for combining `Widget`s.
Expand Down Expand Up @@ -116,6 +116,14 @@ pub trait WidgetExt<T: Data>: Widget<T> + Sized + 'static {
fn lens<S: Data, L: Lens<S, T>>(self, lens: L) -> LensWrap<T, L, Self> {
LensWrap::new(self, lens)
}

/// Parse a `Widget<String>`'s contents
fn parse(self) -> Parse<Self>
where
Self: Widget<String>,
{
Parse::new(self)
}
}

impl<T: Data + 'static, W: Widget<T> + 'static> WidgetExt<T> for W {}
Expand Down

0 comments on commit 96c8cad

Please sign in to comment.