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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
mod button;
pub use button::*;

mod stackpanel;
pub use stackpanel::*;

mod textbox;
pub use textbox::*;

mod label;
pub use label::*;

mod scrollviewer;
pub use scrollviewer::*;

mod checkbox;
pub use checkbox::*;

mod combobox;
pub use combobox::*;

mod tabview;
pub use tabview::*;

mod numeric;
pub use numeric::*;

mod datagrid;
pub use datagrid::*;

mod dockpanel;
pub use dockpanel::*;

mod textblock;
pub use textblock::*;

use arrayvec::ArrayVec;
use vector2d::Vector2D;

use crate::{common::*, window::*};
use std::num::NonZero;

/// Defines setter functions to the corresponding [Window] functions
pub trait Widget: WindowLayout + Default {
	fn set_alignment(&mut self, horizontal: HorizontalAlignment, vertical: VerticalAlignment);

	fn set_visibility(&mut self, visibility: bool);

	fn set_width(&mut self, width: Size);

	fn set_height(&mut self, height: Size);

	fn set_width_constraint(&mut self, width: SizeConstraint);

	fn set_height_constraint(&mut self, height: SizeConstraint);

	fn set_margin(&mut self, margin: Thickness);

	fn set_border(&mut self, border: BorderStyle);

	/// Changing the IsEnabled state usually changes the highlight color
	fn set_enabled_state(&mut self, is_enabled: bool);
}

pub trait WidgetColors: Widget {
	fn set_disabled_color(&mut self, color: Option<Color>);

	fn set_base_fg_color(&mut self, color: Option<Color>);

	fn set_base_bg_color(&mut self, color: Option<Color>);
}


/// Exposes an interface for widgets containing an underlying collection
pub trait ItemCollection<T>: Widget {
	/// Type used to index the underlying collection
	type Index: Copy;

	/// Adds an item to the underlying collection
	fn add_item(&mut self, item: T);

	/// Removes an item from the underlying collection
	fn remove_item(&mut self, item: &T);

	/// Removes an item at the given index from the underlying collection
	/// Might panic if index is invalid
	fn remove_at(&mut self, index: Self::Index) -> T;

	/// Returns an item from the collection by its index
	fn get_item(&mut self, index: Self::Index) -> Option<&T>;

	/// Clears all items in the underlying collection
	fn clear_items(&mut self);

	/// Returns the number of items in the underlying collection
	fn items(&self) -> Self::Index;
}

#[derive(Default)]
pub struct ColorBase {
	pub disabled: Option<Color>,
	pub base_bg: Option<Color>,
	pub base_fg: Option<Color>,
}

impl ColorBase {}

/// Base struct usable for implementations of [Widget]
pub struct WidgetBase {
	pub colors: ColorBase,
	pub visibility: bool,
	pub size: Vector2D<Size>,
	pub constraints: Vector2D<SizeConstraint>,
	pub margin: Thickness,
	pub border: BorderStyle,
	pub alignment: (HorizontalAlignment, VerticalAlignment),
	pub enabled: bool,
	pub uid: WindowUID,
}

impl Default for WidgetBase {
	fn default() -> Self {
		Self {
			colors: ColorBase::default(),
			visibility: true,
			enabled: true,
			uid: WindowUID::new(),
			size: Vector2D::new(Size::default(), Size::default()),
			constraints: Default::default(),
			margin: Thickness::default(),
			border: BorderStyle::default(),
			alignment: (HorizontalAlignment::default(), VerticalAlignment::default()),
		}
	}
}

impl WidgetBase {
	/// Returns the color associated to the state
	pub const fn state_color(&self, is_enabled: bool) -> Option<Color> {
		match is_enabled {
			true => None,
			false => self.colors.disabled,
		}
	}

	pub fn desired_size(&self, available_size: TPoint) -> TPoint {
		Vector2D::new(
			Self::get_size(available_size.x, self.constraints.x, self.size.x),
			Self::get_size(available_size.y, self.constraints.y, self.size.y),
		)
	}

	fn get_size(available_size: TSize, constraint: SizeConstraint, size: Size) -> TSize {
		if available_size >= constraint.min.get() as TSize {
			match size {
				Size::Relative(Percent::DEFAULT) => constraint.max.get_size(available_size),
				v => v.get_size(available_size),
			}
		}
		else {
			TSize::MIN
		}
	}
}


#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Size {
	Fixed(NonZero<TSize>),
	Relative(Percent),
}

impl Default for Size {
	fn default() -> Self {
		Self::Relative(Percent::default())
	}
}

impl Size {
	/// This will return size relative to the given size
	/// If its a percentage it will just get multiplied
	/// If its a fixed size it will be equal or less than 'relative_to'
	pub fn get_size(&self, relative_to: TSize) -> TSize {
		match *self {
			Size::Fixed(u) => {
				let size = u.get();
				if relative_to >= size {
					size
				}
				else {
					relative_to
				}
			}
			Size::Relative(p) => p.multiply(relative_to),
		}
	}
}

impl From<Percent> for Size {
	fn from(value: Percent) -> Self {
		Size::Relative(value)
	}
}


/// When setting the Layout together there's a strict order on which size is determined over the other.
/// Min size > Max size > (Preferred) size
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct SizeConstraint {
	pub min: NonZero<TSize>,
	pub max: Size,
}

impl Default for SizeConstraint {
	fn default() -> Self {
		Self {
			min: NonZero::<TSize>::MIN,
			max: Size::Relative(Percent::default()),
		}
	}
}

pub struct DisplayValue<T: PartialEq> {
	value: T,
	display: String,
}

impl<T: PartialEq> Default for DisplayValue<T>
where T: Default
{
	fn default() -> Self {
		Self {
			value: T::default(),
			display: String::default(),
		}
	}
}

impl<T: PartialEq> DisplayValue<T> {
	pub fn new<S: ToString>(value: T, display: S) -> Self {
		Self {
			value,
			display: display.to_string(),
		}
	}

	pub fn from(value: T, display: String) -> Self {
		Self { value, display }
	}

	// Returns the stored value of the pair
	pub fn value(&self) -> &T {
		&self.value
	}

	// Returns the display value of the pair
	pub fn display(&self) -> &str {
		&self.display
	}
}

#[repr(usize)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Radix {
	Binary = 2,
	Octal = 8,
	#[default]
	Decimal = 10,
	Hexadecimal = 16,
}

impl Radix {
	pub const LITERALS: [Grapheme; 16] = [
		Grapheme::new_unchecked("0", GlyphWidth::Half),
		Grapheme::new_unchecked("1", GlyphWidth::Half),
		Grapheme::new_unchecked("2", GlyphWidth::Half),
		Grapheme::new_unchecked("3", GlyphWidth::Half),
		Grapheme::new_unchecked("4", GlyphWidth::Half),
		Grapheme::new_unchecked("5", GlyphWidth::Half),
		Grapheme::new_unchecked("6", GlyphWidth::Half),
		Grapheme::new_unchecked("7", GlyphWidth::Half),
		Grapheme::new_unchecked("8", GlyphWidth::Half),
		Grapheme::new_unchecked("9", GlyphWidth::Half),
		Grapheme::new_unchecked("A", GlyphWidth::Half),
		Grapheme::new_unchecked("B", GlyphWidth::Half),
		Grapheme::new_unchecked("C", GlyphWidth::Half),
		Grapheme::new_unchecked("D", GlyphWidth::Half),
		Grapheme::new_unchecked("E", GlyphWidth::Half),
		Grapheme::new_unchecked("F", GlyphWidth::Half),
	];
	pub const NEGATIVE_INDICATOR: Grapheme = Grapheme::new_unchecked("-", GlyphWidth::Half);
	pub const PREFIX_BINARY: [Grapheme; 2] = [
		Grapheme::new_unchecked("0", GlyphWidth::Half),
		Grapheme::new_unchecked("b", GlyphWidth::Half),
	];
	pub const PREFIX_OCTAL: [Grapheme; 2] = [
		Grapheme::new_unchecked("0", GlyphWidth::Half),
		Grapheme::new_unchecked("o", GlyphWidth::Half),
	];
	pub const PREFIX_HEX: [Grapheme; 2] = [
		Grapheme::new_unchecked("0", GlyphWidth::Half),
		Grapheme::new_unchecked("x", GlyphWidth::Half),
	];

	pub fn iter_float(&self, number: f32) -> RenderFloatIterator {
		RenderFloatIterator::new(*self, number)
	}

	pub fn iter_integer(&self, number: i32) -> RenderIntegerIterator {
		RenderIntegerIterator::new(*self, number)
	}

	pub fn first_literal(&self, number: usize) -> Grapheme {
		Self::LITERALS[number % *self as usize]
	}

	pub const fn prefix_glyphs(&self) -> &[Grapheme] {
		match *self {
			Self::Binary => &Self::PREFIX_BINARY,
			Self::Octal => &Self::PREFIX_OCTAL,
			Self::Decimal => &[],
			Self::Hexadecimal => &Self::PREFIX_HEX,
		}
	}
}

pub struct RenderFloatIterator {
	dot: bool,
	fract: f32,
	nums: ArrayVec<u8, { f32::MANTISSA_DIGITS as usize }>,
	f: f32,
	r: Radix,
	cnt: u8,
}

impl RenderFloatIterator {
	const F_NAN: [Grapheme; 3] = [
		Grapheme::new_unchecked("N", GlyphWidth::Half),
		Grapheme::new_unchecked("a", GlyphWidth::Half),
		Grapheme::new_unchecked("N", GlyphWidth::Half),
	];
	const F_INF: Grapheme = Grapheme::new_unchecked("∞", GlyphWidth::Half);
	const F_DOT: Grapheme = Grapheme::new_unchecked(".", GlyphWidth::Half);

	fn new(r: Radix, number: f32) -> Self {
		let mut n = number.abs().trunc() as i32;
		let mut vec = ArrayVec::new();
		while n != 0 {
			vec.push((n % r as i32) as u8);
			n /= r as i32;
		}
		Self {
			dot: false,
			fract: number.fract(),
			nums: vec,
			f: number,
			r,
			cnt: 0,
		}
	}
}

impl Iterator for RenderFloatIterator {
	type Item = Grapheme;

	fn next(&mut self) -> Option<Self::Item> {
		if self.f.is_nan() {
			if self.cnt as usize > Self::F_NAN.len() - 1 {
				None
			}
			else {
				let v = Self::F_NAN[self.cnt as usize];
				self.cnt += 1;
				Some(v)
			}
		}
		else if self.f.is_sign_negative() && self.f != 0.0 {
			self.f = self.f.abs();
			Some(Radix::NEGATIVE_INDICATOR)
		}
		else if self.f.is_infinite() {
			if self.cnt != 0 {
				None
			}
			else {
				self.cnt = 1;
				Some(Self::F_INF)
			}
		}
		else if self.r != Radix::Decimal && (self.cnt as usize) < self.r.prefix_glyphs().len() {
			let v = self.r.prefix_glyphs()[self.cnt as usize];
			self.cnt += 1;
			Some(v)
		}
		else {
			if !self.nums.is_empty() {
				self.nums.pop().map(|v| Radix::LITERALS[v as usize])
			}
			else if !self.dot {
				self.dot = true;
				Some(Self::F_DOT)
			}
			else if self.fract != 0.0 {
				let rem = self.fract * self.r as usize as f32;
				let v = Radix::LITERALS[rem.trunc() as usize];
				self.fract = rem.fract();
				Some(v)
			}
			else {
				None
			}
		}
	}
}

pub struct RenderIntegerIterator {
	i: i32,
	nums: ArrayVec<u8, { i32::BITS as usize }>,
	r: Radix,
	cnt: u8,
}

impl RenderIntegerIterator {
	fn new(r: Radix, number: i32) -> Self {
		let mut n = number.abs();
		let mut vec = ArrayVec::new();
		while n != 0 {
			vec.push((n % r as i32) as u8);
			n /= r as i32;
		}
		Self {
			i: number,
			r,
			cnt: 0,
			nums: vec,
		}
	}
}

impl Iterator for RenderIntegerIterator {
	type Item = Grapheme;

	fn next(&mut self) -> Option<Self::Item> {
		if self.i.is_negative() {
			self.i = self.i.abs();
			Some(Radix::NEGATIVE_INDICATOR)
		}
		else if self.r != Radix::Decimal && (self.cnt as usize) < self.r.prefix_glyphs().len() {
			let v = self.r.prefix_glyphs()[self.cnt as usize];
			self.cnt += 1;
			Some(v)
		}
		else {
			self.nums.pop().map(|v| Radix::LITERALS[v as usize])
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn size_fixed() {
		let value = NonZero::new(20).unwrap();
		let fixed = Size::Fixed(value);

		assert_eq!(fixed.get_size(25), value.get());
		assert_eq!(fixed.get_size(value.get()), value.get());
		assert_eq!(fixed.get_size(12), 12);
	}

	#[test]
	fn size_relative() {
		let value = 25;
		let rel = Size::Relative(Percent::from_int(25));

		assert_eq!(rel.get_size(100), value);
		assert_eq!(rel.get_size(200), value * 2);
		assert_eq!(rel.get_size(50), value / 2);
		assert_eq!(rel.get_size(0), 0);
	}
}