Skip to content

Widget adaptor for string parsing #346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would explicitly document that this works with the FromStr trait, and that T has to be a type that implements FromStr.

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