flux-tui 0.5.0

Fast and lightweight Terminal UI drawing library
Documentation
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::*;
use crate::canvas::Canvas;

use std::num::NonZero;
use std::rc::Rc;
use std::time::{Duration, Instant};

use crossterm::event::KeyCode;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::*;


pub type TextChangedCallback = dyn Fn(&mut Textbox);
pub type TextboxKeyHandler = fn(&mut Textbox, event: &mut WindowEvent);

/// Single-line text input method
/// Allows navigating through the string, removing (using Backspace) and adding characters at the '_' sign
/// The cursor will hide the grapheme behind it
///
/// Design (including Border):
/// ```text
/// ┌─────┐
/// │Tex_1│
/// └─────┘
/// ```
pub struct Textbox {
	text: String,
	grapheme_count: usize,
	cursor: usize,
	offset: usize,
	has_focus: bool,
	// Actual current size of the component
	width: usize,
	max_length: usize,
	base: WidgetBase,
	readonly: bool,

	focus_color: Option<Color>,
	fat_cursor: bool,

	last_change: Instant,
	delay: Duration,
	callback: Rc<TextChangedCallback>,
	key_handler: TextboxKeyHandler,
}

impl Default for Textbox {
	fn default() -> Self {
		let mut s = Self {
			text: String::new(),
			width: usize::MIN,
			max_length: 128,
			base: WidgetBase::default(),
			has_focus: false,
			cursor: usize::MIN,
			offset: usize::MIN,
			grapheme_count: usize::MIN,
			readonly: false,

			focus_color: None,
			fat_cursor: true,

			last_change: Instant::now(),
			delay: Self::DELAY_DEFAULT,
			callback: Rc::new(Self::default_callback),
			key_handler: Self::default_key_handler,
		};
		s.base.constraints.y.min = NonZero::<TSize>::MIN;
		s.base.constraints.y.max = Size::Fixed(NonZero::<TSize>::MIN);
		s
	}
}

impl Textbox {
	pub const DELAY_DEFAULT: Duration = Duration::from_millis(250);
	pub const CURSOR: Grapheme = Grapheme::new_unchecked("_", GlyphWidth::Half);
	pub const CURSOR_WIDE: Grapheme = Grapheme::new_unchecked("_", GlyphWidth::Half);

	pub fn default_callback(_: &mut Self) {}

	pub fn default_key_handler(&mut self, event: &mut WindowEvent) {
		if let Event::Key(k) = event.raw() {
			match k.code {
				KeyCode::Left => {
					self.move_cursor_left();
					event.handled = true;
				}
				KeyCode::Right => {
					self.move_cursor_right();
					event.handled = true;
				}
				KeyCode::Backspace => {
					if !self.readonly {
						self.remove_glyph_before_cursor();
					}
					event.handled = true;
				}
				KeyCode::Char(ch) => {
					if !self.readonly {
						self.insert_char_at_cursor(ch);
					}
					event.handled = true;
				}
				_ => {}
			}
		}
	}

	pub fn set_text_changed_callback<F: Fn(&mut Self) + 'static>(&mut self, callback: F) {
		self.callback = Rc::new(callback);
	}

	pub fn set_callback_delay(&mut self, duration: Duration) {
		self.delay = duration;
	}

	pub fn set_key_handler(&mut self, f: TextboxKeyHandler) {
		self.key_handler = f;
	}

	/// `fat_cursor`: `true` will just highlight the current position, `false` will use _ instead
	/// as cursor
	pub fn set_cursor_type(&mut self, fat_cursor: bool) {
		self.fat_cursor = fat_cursor;
	}

	/// Foreground color when the textbox has focus
	pub fn set_focus_color(&mut self, focus_color: Option<Color>) {
		self.focus_color = focus_color;
	}

	pub fn is_readonly(&self) -> bool {
		self.readonly
	}

	pub fn set_readonly(&mut self, readonly: bool) {
		self.readonly = readonly;
	}

	/// Returns the maximum length of the inner text
	pub fn get_max_length(&self) -> usize {
		self.max_length
	}

	/// Sets the maximum length of the inner text (number of graphemes)
	pub fn set_max_length(&mut self, length: usize) {
		self.max_length = length;
	}

	/// Returns the inner text
	pub fn get_text(&self) -> &str {
		&self.text
	}

	/// Updates the inner text
	pub fn set_text(&mut self, text: &str) {
		self.text.clear();
		self.text.push_str(text);
		self.grapheme_count = self.text.graphemes(true).count();

		self.cursor = self.grapheme_count % self.width;
		self.offset = self.grapheme_count - self.cursor;

		self.text_changed();
	}

	/// Clears the inner text
	pub fn clear(&mut self) {
		self.text.clear();
		self.grapheme_count = usize::MIN;
		self.cursor = usize::MIN;
		self.offset = usize::MIN;
		self.text_changed();
	}

	pub fn move_cursor_left(&mut self) {
		if self.actual_cursor_pos() > usize::MIN {
			self.decrease_cursor();
		}
	}

	pub fn move_cursor_right(&mut self) {
		if self.actual_cursor_pos() < self.grapheme_count {
			self.increase_cursor();
			self.check_cursor();
		}
	}

	pub fn remove_glyph_before_cursor(&mut self) {
		let cursor = self.actual_cursor_pos();
		if cursor > usize::MIN {
			let mut iter = self.text.grapheme_indices(true).skip(cursor - 1);
			if let Some((idx, str)) = iter.next() {
				(0..str.chars().count()).for_each(|_| {
					self.text.remove(idx);
				});
				self.decrease_cursor();
			}
			self.grapheme_count = self.text.graphemes(true).count();
		}
	}

	pub fn insert_char_at_cursor(&mut self, ch: char) {
		let cursor = self.actual_cursor_pos();
		// Do nothing if its a control character
		let ch_width = match ch.width() {
			Some(w) => w,
			None => return,
		};

		if self.grapheme_count < self.max_length {
			if cursor == self.grapheme_count {
				if self.get_current_visible_width() == self.width - ch_width {
					self.cursor -= 1;
					self.offset += 1;
				}
				self.cursor += 1;
			}
			else {
				self.increase_cursor();
			}

			let mut iter = self.text.grapheme_indices(true).skip(cursor);
			match iter.next().map(|(idx, _)| idx) {
				Some(idx) => self.text.insert(idx, ch),
				None => self.text.push(ch),
			}
			self.grapheme_count = self.text.graphemes(true).count();
			self.check_cursor();
			self.text_changed();
		}
	}

	fn check_cursor(&mut self) {
		// Prevent issues with grapheme clusters
		let len = self.text.width();
		if self.actual_cursor_pos() > len {
			let diff = self.actual_cursor_pos() - len;
			self.cursor -= diff;
		}
	}

	fn actual_cursor_pos(&self) -> usize {
		self.cursor + self.offset
	}

	fn get_current_visible_width(&self) -> usize {
		let mut iter = self.text.grapheme_indices(true).skip(self.offset);
		let start = iter.next().map(|x| x.0).unwrap_or(usize::MIN);
		let mut iter = self
			.text
			.grapheme_indices(true)
			.skip(self.offset + self.cursor + 1);
		let end = iter.next().map(|x| x.0).unwrap_or(self.text.len());
		self.text[start..end].width()
	}

	fn is_cursor_at_max_width(&self) -> bool {
		self.get_current_visible_width() == self.width
	}

	fn increase_cursor(&mut self) {
		if self.is_cursor_at_max_width() {
			self.offset += 1;
		}
		else {
			self.cursor += 1;
		}
	}

	fn decrease_cursor(&mut self) {
		if self.offset > usize::MIN && self.cursor == usize::MIN {
			self.offset -= 1;
		}
		else {
			self.cursor -= 1;
		}
	}

	fn text_changed(&mut self) {
		if self.last_change.elapsed() > self.delay {
			let cb = self.callback.clone();
			cb(self);
		}

		self.last_change = Instant::now();
	}
}

impl Window for Textbox {
	fn render(&self, canvas: &mut Canvas) {
		let mut row = canvas.get_row_variable_width(TSize::MIN).unwrap();
		let mut graphemes = self.text.graphemes(true).skip(self.offset);
		let mut counter = usize::MIN;
		while row.cursor() < row.width() {
			let gr = graphemes.next();
			let str;
			let mut style = Style::None;
			let mut fg = None;

			if !self.base.enabled {
				fg = self.base.colors.disabled;
			}
			else if self.has_focus {
				fg = self.focus_color;
			}

			fg = fg.or(self.base.colors.base_fg);

			if self.has_focus && counter == self.cursor {
				if self.fat_cursor {
					str = gr
						.map(|v| Grapheme::from(v).unwrap())
						.unwrap_or(Grapheme::PLACEHOLDER);
					style = Style::Reverse | Style::ResetAfter;
				}
				else {
					let width = gr.map(|x| x.width()).unwrap_or(usize::MIN);
					str = match width {
						2 => Self::CURSOR_WIDE,
						_ => Self::CURSOR,
					};
				}
			}
			else {
				str = gr
					.map(|v| Grapheme::from(v).unwrap())
					.unwrap_or(Grapheme::PLACEHOLDER);
			}
			row.add_grapheme(str, fg, self.base.colors.base_bg, style)
				.ok();
			counter += 1;
		}
	}

	fn handle_event(&mut self, event: &mut WindowEvent) {
		match event.raw() {
			Event::Resize(w, _) => self.width = *w as usize,
			Event::FocusGained => self.has_focus = true,
			Event::FocusLost => self.has_focus = false,
			_ => (self.key_handler)(self, event),
		}
	}

	fn is_enabled(&self) -> bool {
		self.base.enabled
	}
}

impl WindowLayout for Textbox {
	fn desired_size(&self, available_size: TPoint) -> TPoint {
		self.base.desired_size(available_size)
	}

	fn alignment(&self) -> (HorizontalAlignment, VerticalAlignment) {
		self.base.alignment
	}

	fn margin(&self) -> Thickness {
		self.base.margin
	}

	fn border(&self) -> BorderStyle {
		self.base.border
	}

	fn is_visible(&self) -> bool {
		self.base.visibility
	}
}

impl HasWindowUID for Textbox {
	fn uid(&self) -> WindowUID {
		self.base.uid
	}
}

impl Widget for Textbox {
	fn set_alignment(&mut self, horizontal: HorizontalAlignment, vertical: VerticalAlignment) {
		self.base.alignment = (horizontal, vertical);
		self.provoke_changed_property(WindowProperty::Alignment);
	}

	fn set_visibility(&mut self, visibility: bool) {
		self.base.visibility = visibility;
		self.provoke_changed_property(WindowProperty::IsVisible);
	}

	fn set_width(&mut self, width: Size) {
		self.base.size.x = width;
		self.provoke_changed_property(WindowProperty::Size);
	}

	fn set_height(&mut self, _: Size) {}

	fn set_margin(&mut self, margin: Thickness) {
		self.base.margin = margin;
		self.provoke_changed_property(WindowProperty::Margin);
	}

	fn set_border(&mut self, border: BorderStyle) {
		self.base.border = border;
		self.provoke_changed_property(WindowProperty::Border);
	}

	fn set_enabled_state(&mut self, is_enabled: bool) {
		self.base.enabled = is_enabled;
	}

	fn set_width_constraint(&mut self, width: SizeConstraint) {
		self.base.constraints.x = width;
		self.provoke_changed_property(WindowProperty::Size);
	}

	fn set_height_constraint(&mut self, _: SizeConstraint) {}
}

impl WidgetColors for Textbox {
	fn set_disabled_color(&mut self, color: Option<Color>) {
		self.base.colors.disabled = color;
	}

	fn set_base_fg_color(&mut self, color: Option<Color>) {
		self.base.colors.base_fg = color;
	}

	fn set_base_bg_color(&mut self, color: Option<Color>) {
		self.base.colors.base_bg = color;
	}
}