-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit_box.rs
346 lines (293 loc) · 10.6 KB
/
edit_box.rs
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use log::{debug, warn};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::config::theme::Theme;
use crate::cursor::cursor_set::CursorSet;
use crate::experiments::clipboard::ClipboardRef;
use crate::experiments::screenspace::Screenspace;
use crate::io::input_event::InputEvent;
use crate::io::input_event::InputEvent::KeyInput;
use crate::io::keys::Keycode;
use crate::io::output::Output;
use crate::primitives::common_edit_msgs::{key_to_edit_msg, CommonEditMsg};
use crate::primitives::helpers;
use crate::primitives::xy::XY;
use crate::text::buffer_state::BufferState;
use crate::text::text_buffer::TextBuffer;
use crate::widget::any_msg::AnyMsg;
use crate::widget::fill_policy::SizePolicy;
use crate::widget::widget::{get_new_widget_id, Widget, WidgetAction, WID};
use crate::{unpack_or_e, unpack_unit_e};
//TODO filter out the newlines on paste
//TODO add layout tests (min size, max size etc)
pub struct EditBoxWidget {
id: WID,
enabled: bool,
// hit is basically pressing enter.
on_hit: Option<WidgetAction<EditBoxWidget>>,
on_change: Option<WidgetAction<EditBoxWidget>>,
// miss is trying to make illegal move. Like backspace on empty, left on leftmost etc.
on_miss: Option<WidgetAction<EditBoxWidget>>,
buffer: BufferState,
min_width_op: Option<u16>,
max_width_op: Option<u16>,
clipboard_op: Option<ClipboardRef>,
last_size_x: Option<u16>,
size_policy: SizePolicy,
}
impl EditBoxWidget {
const MIN_WIDTH: u16 = 2;
pub const TYPENAME: &'static str = "edit_box";
pub fn new() -> Self {
let widget_id = get_new_widget_id();
let mut buffer = BufferState::simplified_single_line();
buffer.initialize_for_widget(widget_id, None);
let mut res = EditBoxWidget {
id: widget_id,
enabled: true,
buffer,
on_hit: None,
on_change: None,
on_miss: None,
max_width_op: None,
clipboard_op: None,
last_size_x: None,
min_width_op: None,
size_policy: SizePolicy::SELF_DETERMINED,
};
res
}
pub fn with_size_policy(self, size_policy: SizePolicy) -> Self {
Self { size_policy, ..self }
}
pub fn with_clipboard(self, clipboard: ClipboardRef) -> Self {
Self {
clipboard_op: Some(clipboard),
..self
}
}
pub fn with_max_width(self, max_width: u16) -> Self {
EditBoxWidget {
max_width_op: Some(max_width),
..self
}
}
pub fn with_min_width(self, min_width: u16) -> Self {
EditBoxWidget {
min_width_op: Some(min_width),
..self
}
}
pub fn with_on_hit(self, on_hit: WidgetAction<EditBoxWidget>) -> Self {
EditBoxWidget {
on_hit: Some(on_hit),
..self
}
}
pub fn with_on_change(self, on_change: WidgetAction<EditBoxWidget>) -> Self {
EditBoxWidget {
on_change: Some(on_change),
..self
}
}
pub fn with_on_miss(self, on_miss: WidgetAction<EditBoxWidget>) -> Self {
EditBoxWidget {
on_miss: Some(on_miss),
..self
}
}
pub fn with_enabled(self, enabled: bool) -> Self {
EditBoxWidget { enabled, ..self }
}
pub fn with_text<'a, T: AsRef<str>>(self, text: T) -> Self {
let mut res = EditBoxWidget {
buffer: BufferState::simplified_single_line().with_text(text),
..self
};
res.buffer.initialize_for_widget(self.id, None);
res
}
pub fn get_buffer(&self) -> &BufferState {
&self.buffer
}
pub fn get_text(&self) -> String {
self.buffer.text().to_string()
}
pub fn is_empty(&self) -> bool {
self.buffer.len_bytes() == 0 //TODO
}
pub fn set_text<'a, T: AsRef<str>>(&mut self, text: T) {
self.buffer = BufferState::simplified_single_line().with_text(text);
self.buffer.initialize_for_widget(self.id, None);
}
pub fn set_cursor_end(&mut self) {
let mut cursor_set = CursorSet::single();
cursor_set.move_end(&self.buffer, false);
self.buffer.text_mut().set_cursor_set(self.id, cursor_set);
}
pub fn clear(&mut self) {
self.buffer = BufferState::simplified_single_line();
self.buffer.initialize_for_widget(self.id, None);
}
fn event_changed(&self) -> Option<Box<dyn AnyMsg>> {
if self.on_change.is_some() {
self.on_change.as_ref().unwrap()(self)
} else {
None
}
}
fn event_miss(&self) -> Option<Box<dyn AnyMsg>> {
if self.on_miss.is_some() {
self.on_miss.as_ref().unwrap()(self)
} else {
None
}
}
fn event_hit(&self) -> Option<Box<dyn AnyMsg>> {
if self.on_hit.is_some() {
self.on_hit.as_ref().unwrap()(self)
} else {
None
}
}
}
impl Widget for EditBoxWidget {
fn id(&self) -> WID {
self.id
}
fn static_typename() -> &'static str
where
Self: Sized,
{
Self::TYPENAME
}
fn typename(&self) -> &'static str {
Self::TYPENAME
}
fn full_size(&self) -> XY {
XY::new(self.min_width_op.unwrap_or(Self::MIN_WIDTH), 1)
}
fn size_policy(&self) -> SizePolicy {
self.size_policy
}
fn layout(&mut self, screenspace: Screenspace) {
self.last_size_x = Some(screenspace.output_size().x);
}
fn on_input(&self, input_event: InputEvent) -> Option<Box<dyn AnyMsg>> {
debug_assert!(self.enabled, "EditBoxWidgetMsg: received input to disabled component!");
let cursor_set_copy = unpack_or_e!(self.buffer.text().get_cursor_set(self.id), None, "failed to get cursor_set").clone();
return match input_event {
KeyInput(key_event) => {
if key_event.keycode == Keycode::Enter {
Some(Box::new(EditBoxWidgetMsg::Hit))
} else {
match key_to_edit_msg(key_event) {
Some(cem) => match cem {
// the 4 cases below are designed to NOT consume the event in case it cannot be used.
CommonEditMsg::CursorUp { selecting: _ } | CommonEditMsg::CursorDown { selecting: _ } => None,
CommonEditMsg::CursorLeft { selecting: _ }
if cursor_set_copy.as_single().map(|c| c.a == 0).unwrap_or(false) =>
{
None
}
CommonEditMsg::CursorRight { selecting: _ }
if cursor_set_copy.as_single().map(|c| c.a > self.buffer.len_chars()).unwrap_or(false) =>
{
None
}
_ => Some(Box::new(EditBoxWidgetMsg::CommonEditMsg(cem))),
},
None => None,
}
}
}
_ => None,
};
}
fn update(&mut self, msg: Box<dyn AnyMsg>) -> Option<Box<dyn AnyMsg>> {
let our_msg = msg.as_msg::<EditBoxWidgetMsg>();
if our_msg.is_none() {
warn!("expecetd EditBoxWidgetMsg, got {:?}", msg);
return None;
}
debug!("EditBox got {:?}", msg);
return match our_msg.unwrap() {
EditBoxWidgetMsg::Hit => self.event_hit(),
EditBoxWidgetMsg::CommonEditMsg(cem) => {
if self
.buffer
.apply_common_edit_message(cem.clone(), self.id, 1, self.clipboard_op.as_ref())
{
self.event_changed()
} else {
None
}
}
};
}
fn render(&self, theme: &Theme, focused: bool, output: &mut dyn Output) {
let size = XY::new(unpack_unit_e!(self.last_size_x, "render before layout",), 1);
#[cfg(test)]
output.emit_metadata(crate::io::output::Metadata {
id: self.id(),
typename: self.typename().to_string(),
rect: crate::primitives::rect::Rect::from_zero(size),
focused,
});
let primary_style = theme.highlighted(focused);
helpers::fill_output(primary_style.background, output);
let cursor_set_copy = unpack_unit_e!(self.buffer.text().get_cursor_set(self.id), "failed to get cursor_set",).clone();
let mut x: usize = 0;
for (char_idx, g) in self.buffer.to_string().graphemes(true).enumerate() {
if x + g.width() > size.x as usize {
// not drawing beyond x
break;
}
let style = match theme.cursor_background(cursor_set_copy.get_cursor_status_for_char(char_idx)) {
Some(bg) => primary_style.with_background(if focused { bg } else { bg.half() }),
None => primary_style,
};
output.print_at(
XY::new(x as u16, 0), //TODO
style,
g,
);
x += g.width();
}
// one character after, but only if it fits.
if x < size.x as usize {
let style = match theme.cursor_background(cursor_set_copy.get_cursor_status_for_char(self.buffer.len_chars())) {
Some(bg) => primary_style.with_background(if focused { bg } else { bg.half() }),
None => primary_style,
};
output.print_at(XY::new(x as u16, 0), style, " ");
}
// if cursor is after the text, we need to add an offset, so the background does not
// overwrite cursor style.
let cursor_offset: u16 = cursor_set_copy.max_cursor_pos() as u16 + 1; //TODO
let text_width = self.buffer.to_string().width() as u16; //TODO
let end_of_text = cursor_offset.max(text_width);
// background after the text
if size.x > end_of_text {
let background_length = size.x - end_of_text;
for i in 0..background_length {
let pos = XY::new(end_of_text + i as u16, 0);
output.print_at(pos, primary_style, " ");
}
}
}
fn kite(&self) -> XY {
XY::ZERO
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum EditBoxWidgetMsg {
Hit,
CommonEditMsg(CommonEditMsg),
}
impl AnyMsg for EditBoxWidgetMsg {}
impl Default for EditBoxWidget {
fn default() -> Self {
EditBoxWidget::new()
}
}