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
pub(crate) mod event_queue;
pub(crate) mod handler;
pub(crate) mod helper;

use as_any::AsAny;
use singlevec::SingleVec;
use uid::IdU64;
use vector2d::Vector2D;

use crate::canvas::{BorderCanvas, Canvas};
use crate::common::*;
use std::cell::RefCell;
use std::rc::*;

pub use event_queue::*;
pub use handler::WindowHandler;
pub use helper::*;


/// Defines border decoration
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum BorderKind {
	#[default]
	Solid,
	Thick,
	Dashed,
}

impl BorderKind {
	/// Top Left, Top Right, Bottom Left, Bottom Right
	pub const fn corner_style(&self) -> [Grapheme; 4] {
		match self {
			BorderKind::Solid => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Dashed => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Thick => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
		}
	}

	/// Default cross
	pub const fn cross_style(&self) -> Grapheme {
		match self {
			BorderKind::Solid => Grapheme::new_unchecked("", GlyphWidth::Half),
			BorderKind::Dashed => Grapheme::new_unchecked("", GlyphWidth::Half),
			BorderKind::Thick => Grapheme::new_unchecked("", GlyphWidth::Half),
		}
	}

	/// Non-connected side: Left, Right, Top, Bottom
	pub const fn connector_style(&self) -> [Grapheme; 4] {
		match self {
			BorderKind::Solid => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Dashed => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Thick => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
		}
	}

	/// Horizontal line, Vertical line
	pub const fn line_style(&self) -> [Grapheme; 2] {
		match self {
			BorderKind::Solid => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Dashed => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
			BorderKind::Thick => [
				Grapheme::new_unchecked("", GlyphWidth::Half),
				Grapheme::new_unchecked("", GlyphWidth::Half),
			],
		}
	}
}

/// The given [Window] is the instance which returned BorderStyle
pub type CustomStyleFn = fn(&dyn Window, BorderCanvas);

#[derive(Copy, Clone, Debug, Default)]
pub enum BorderStyle {
	#[default]
	None,
	Preset {
		kind: BorderKind,
		bg: Option<Color>,
		fg: Option<Color>,
	},
	Custom(CustomStyleFn, Thickness),
}

impl PartialEq for BorderStyle {
	fn eq(&self, other: &Self) -> bool {
		match self {
			Self::None => matches!(other, Self::None),
			Self::Preset {
				kind: kind0,
				bg: bg0,
				fg: fg0,
			} => match other {
				Self::Preset { kind, bg, fg } => kind0 == kind && bg0 == bg && fg0 == fg,
				_ => false,
			},
			Self::Custom(_, _) => false,
		}
	}
}

impl BorderStyle {
	pub const fn new(kind: BorderKind, bg: Option<Color>, fg: Option<Color>) -> Self {
		Self::Preset { kind, bg, fg }
	}

	/// Use a custom callback to render the border
	pub const fn custom(f: CustomStyleFn, thickness: Thickness) -> Self {
		Self::Custom(f, thickness)
	}

	pub const fn thickness(&self) -> Thickness {
		match *self {
			BorderStyle::None => Thickness::from(0),
			BorderStyle::Custom(_, tn) => tn,
			_ => Thickness::from(1),
		}
	}

	pub const fn get_borderkind(&self) -> Option<BorderKind> {
		match self {
			BorderStyle::Preset { kind, .. } => Some(*kind),
			_ => None,
		}
	}
}

#[derive(Default, Clone, Copy, Debug, PartialEq)]
pub struct Thickness {
	pub top: TSize,
	pub left: TSize,
	pub right: TSize,
	pub bottom: TSize,
}

impl Thickness {
	pub const fn from(size: TSize) -> Self {
		Self {
			top: size,
			left: size,
			right: size,
			bottom: size,
		}
	}

	pub const fn new(top: TSize, left: TSize, right: TSize, bottom: TSize) -> Self {
		Self {
			top,
			left,
			right,
			bottom,
		}
	}

	pub const fn width(&self) -> TSize {
		self.left + self.right
	}

	pub const fn height(&self) -> TSize {
		self.top + self.bottom
	}
}

impl From<CustomStyleFn> for BorderStyle {
	fn from(value: CustomStyleFn) -> Self {
		Self::Custom(value, Thickness::from(1))
	}
}

impl From<BorderKind> for BorderStyle {
	fn from(value: BorderKind) -> Self {
		Self::Preset {
			kind: value,
			bg: None,
			fg: None,
		}
	}
}

#[derive(Copy, Clone, Debug, Default)]
pub struct RectsOverlapping {}

pub struct SubWindowBuilder {
	base_rect: Rect,
	children: SingleVec<WindowRef>,
	rects: SingleVec<Rect>,
	overlapping: bool,
}

impl SubWindowBuilder {
	pub(crate) fn from(base_rect: Rect) -> Self {
		Self {
			base_rect,
			children: SingleVec::new(),
			rects: SingleVec::new(),
			overlapping: true,
		}
	}

	/// Allows overlapping sub-windows
	/// Enabled by default
	pub fn enable_overlapping(&mut self) {
		self.overlapping = true;
	}

	/// Disallows overlapping sub-windows
	pub fn disable_overlapping(&mut self) {
		self.overlapping = false;
	}

	/// Adds only a new children into the buffer
	pub fn add_child(&mut self, child: WindowRef) {
		self.children.push(child);
	}

	/// Returns [Err] when rects overlap (if overlapping is disabled)
	pub fn add_rect(&mut self, rect: Rect) -> Result<(), RectsOverlapping> {
		if self.check_overlapping(rect) {
			return Err(RectsOverlapping::default());
		}
		self.rects.push(rect);
		Ok(())
	}

	/// If `rect` is None then [Self::base_rect] will be used
	/// Returns [Err] when rects overlap (if overlapping is disabled)
	pub fn add_pair(
		&mut self,
		child: WindowRef,
		rect: Option<Rect>,
	) -> Result<(), RectsOverlapping> {
		let rect = rect.unwrap_or(self.base_rect);
		if self.check_overlapping(rect) {
			return Err(RectsOverlapping::default());
		}

		self.children.push(child);
		self.rects.push(rect);
		Ok(())
	}

	#[inline(always)]
	pub fn base_rect(&self) -> Rect {
		self.base_rect
	}

	/// Builds children and their corresponding rects together
	/// Children and their rects have to be in the same order
	/// Returns `None` when the children and rects length are unequal
	pub fn build(self) -> Option<SubWindows> {
		if self.children.len() != self.rects.len() {
			return None;
		}

		Some(SubWindows {
			children: self.children,
			rects: self.rects,
		})
	}

	fn check_overlapping(&self, rect: Rect) -> bool {
		if !self.overlapping {
			for rt in self.rects.iter() {
				if rt.overlaps(&rect) {
					return true;
				}
			}
		}
		false
	}
}

//Instead SingleVec<SubWindow>
#[derive(Default)]
pub struct SubWindows {
	children: SingleVec<WindowRef>,
	rects: SingleVec<Rect>,
}

impl SubWindows {
	/// Returns the children/sub-windows of the current window
	pub fn children(&self) -> &[WindowRef] {
		&self.children
	}

	/// This returns the childrens associated rectangles
	/// The rectangles define the inner area for rendering
	pub fn rects(&self) -> &[Rect] {
		&self.rects
	}
}

pub type WindowRef = Rc<RefCell<dyn Window>>;
pub type WindowWeakRef = Weak<RefCell<dyn Window>>;

/// Main trait for any window
pub trait Window: WindowLayout + HasWindowUID + AsAny {
	/// The events are forwarded from [crossterm] with the only exception of Resize
	/// which will have the same dimensions as the resulting canvas
	/// If a event's handled attributed is set to true it will stop bubbling
	/// otherwise it will keep bubbling until another Window marks it as handled
	/// Except for:
	/// - [Event::FocusGained] and [Event::FocusLost] indicate focus for the specific Window
	/// - [Event::Resize] is broadcasted
	fn handle_event(&mut self, event: &mut WindowEvent) {
		let _ = event;
	}

	/// Returns all children windows (and layouting [Rect]s)
	/// Note: When changing the children make sure to also adjust the focus
	fn children(&mut self, builder: SubWindowBuilder) -> SubWindows {
		let _ = builder;
		SubWindows::default()
	}

	/// Allows [self] to draw into its own [Canvas]
	/// The canvas size depends on other properties set and the terminal size itself
	/// It is guarenteed that the size of the [Canvas] is atleast 1x1
	fn render(&self, canvas: &mut Canvas);


	/// Which child of the window has focus
	/// Is there is None, then ´self´ has focus
	fn focus(&self) -> Option<WindowRef> {
		None
	}

	/// Is [self] enabled?
	/// Indicated whether or not to handle input and if its focusable
	/// When `false`, [Window] is still eligible to receive events
	fn is_enabled(&self) -> bool {
		true
	}
}


/// Properties which define how the window is drawn
pub trait WindowLayout {
	/// Aligns [self] within its parent [Window]
	fn alignment(&self) -> (HorizontalAlignment, VerticalAlignment) {
		(HorizontalAlignment::default(), VerticalAlignment::default())
	}

	/// This is similar to desired_size but will not return anything and can mutably change [self]
	/// This is executed *before* [WindowLayout::desired_size]
	/// Only implement if actually necessary
	fn desired_size_pre_hook(&mut self, available_size: TPoint) {
		_ = available_size;
	}

	/// Parents call this to get the desired size of the child
	/// This must not exceed `available_size` on any axis
	/// When the result's product is equal to 0, this window wont be drawn
	fn desired_size(&self, available_size: TPoint) -> TPoint {
		available_size
	}

	fn margin(&self) -> Thickness {
		Thickness::default()
	}

	fn border(&self) -> BorderStyle {
		BorderStyle::default()
	}

	fn is_visible(&self) -> bool {
		true
	}
}


pub trait HasWindowUID {
	/// Must be static and unique for each object implementing [Window].
	/// Generate once per instance using [WindowUID::new].
	fn uid(&self) -> WindowUID;
}

/// Helper struct for generating the UID
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WindowUID(u64);

impl std::fmt::Display for WindowUID {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.0)
	}
}

impl Default for WindowUID {
	fn default() -> Self {
		Self::new()
	}
}

impl WindowUID {
	/// Generates a new [Window]'s UID
	pub fn new() -> Self {
		Self(IdU64::<Self>::new().get())
	}
}