1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#![allow(deprecated)]
use std::fmt::Display;
use std::mem;
use std::str::FromStr;
use tracing::instrument;
use crate::debug_state::DebugState;
use crate::widget::prelude::*;
use crate::Data;
#[doc(hidden)]
#[deprecated(since = "0.7.0", note = "Use the Formatter trait instead")]
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> {
#[instrument(name = "Parse", level = "trace", skip(self, ctx, event, data, 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();
}
#[instrument(name = "Parse", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(
&mut self,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &Option<T>,
env: &Env,
) {
if let LifeCycle::WidgetAdded = event {
if let Some(data) = data {
self.state = data.to_string();
}
}
self.widget.lifecycle(ctx, event, &self.state, env)
}
#[instrument(name = "Parse", level = "trace", skip(self, ctx, _old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &Option<T>, data: &Option<T>, env: &Env) {
let old = match *data {
None => return, Some(ref x) => {
match self.state.parse() {
Err(_) => Some(mem::replace(&mut self.state, x.to_string())),
Ok(v) => {
if !Data::same(&v, x) {
Some(mem::replace(&mut self.state, x.to_string()))
} else {
None
}
}
}
}
};
let old_data = old.as_ref().unwrap_or(&self.state);
self.widget.update(ctx, old_data, &self.state, env)
}
#[instrument(name = "Parse", level = "trace", skip(self, ctx, bc, _data, env))]
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &Option<T>,
env: &Env,
) -> Size {
self.widget.layout(ctx, bc, &self.state, env)
}
#[instrument(name = "Parse", level = "trace", skip(self, ctx, _data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, _data: &Option<T>, env: &Env) {
self.widget.paint(ctx, &self.state, env)
}
fn id(&self) -> Option<WidgetId> {
self.widget.id()
}
fn debug_state(&self, _data: &Option<T>) -> DebugState {
DebugState {
display_name: "Parse".to_string(),
main_value: self.state.clone(),
..Default::default()
}
}
}