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
484
485
486
487
488
489
490
491
492
493
494
495
use std::{
	cell::RefCell,
	rc::{Rc, Weak},
};

use super::*;
use crate::canvas::GlyphArray;

/// [Window] which is scrollable
pub trait Scrollable: Window {
	/// Can current [Scrollable] be scrolled horizontally / vertically
	fn is_scrollable(&self, axis: Orientation) -> bool;

	/// Scrolls page/line-wise (see [ScrollKind]) in the given direction
	fn scroll(&mut self, direction: Direction, kind: ScrollKind);

	/// Sets the horizontal / vertical offset
	fn set_offset(&mut self, direction: Orientation, offset: usize);

	/// Horizontal / Vertical offset of the scrolled content
	fn offset(&self, axis: Orientation) -> usize;

	/// Horizontal / Vertical size of the viewport for current [Scrollable]
	fn viewport(&self, axis: Orientation) -> usize;

	/// Should only be called by the [ScrollViewer] itself
	fn set_scroll_viewer(&mut self, scroll_viewer: Weak<RefCell<ScrollViewer>>);
}

/// Base struct for storing different information required for the [Scrollable] trait
/// Has all fns of [Scrollable] but doesn't implement the trait
#[derive(Clone, Debug, Default)]
pub struct ScrollBase {
	/// Offset of the base 0,0 coordinate (as in rendering)
	pub offset: Vector2D<usize>,
	/// Viewport for the whole content to be rendered
	pub viewport: Vector2D<usize>,
	/// Actual size rendered
	pub render_size: TPoint,
	/// Weak reference to the owning scroll viewer
	pub scroll_viewer: Weak<RefCell<ScrollViewer>>,
}

impl ScrollBase {
	pub fn is_scrollable(&self, axis: Orientation) -> bool {
		let idx = axis as usize;
		self.scroll_viewer.strong_count() > usize::MIN
			&& ((self.offset[idx] == usize::MIN
				&& self.viewport[idx] > self.render_size[idx] as usize)
				|| self.offset[idx] > usize::MIN)
	}

	pub fn scroll(&mut self, direction: Direction, kind: ScrollKind) {
		let delta = match kind {
			ScrollKind::Line => 1,
			ScrollKind::Page => match direction {
				Direction::Up | Direction::Down => self.render_size.y as usize,
				Direction::Left | Direction::Right => self.render_size.x as usize,
			},
		};
		match direction {
			Direction::Up => {
				if let Some(offset) = self.offset.y.checked_sub(delta) {
					self.offset.y = offset;
				}
				else {
					self.offset.y = usize::MIN;
				}
			}
			Direction::Down => {
				let offset = self.offset.y + delta;
				if offset <= self.viewport.y - delta {
					self.offset.y += delta;
				}
				else {
					self.offset.y = self.viewport.y - delta;
				}
			}
			Direction::Left => {
				if let Some(offset) = self.offset.x.checked_sub(delta) {
					self.offset.x -= offset;
				}
				else {
					self.offset.x = usize::MIN
				}
			}
			Direction::Right => {
				let offset = self.offset.x + delta;
				if offset <= self.viewport.x - delta {
					self.offset.x += delta;
				}
				else {
					self.offset.x = self.viewport.x - delta;
				}
			}
		}
	}

	pub fn set_offset(&mut self, direction: Orientation, offset: usize) {
		match direction {
			Orientation::Horizontal => {
				if offset < self.viewport.x {
					self.offset.x = offset;
				}
				else {
					self.offset.x = self.viewport.x.checked_sub(1).unwrap_or_default();
				}
			}
			Orientation::Vertical => {
				if offset < self.viewport.y {
					self.offset.y = offset;
				}
				else {
					self.offset.y = self.viewport.y.checked_sub(1).unwrap_or_default();
				}
			}
		}
	}

	pub fn offset(&self, axis: Orientation) -> usize {
		match axis {
			Orientation::Horizontal => self.offset.x,
			Orientation::Vertical => self.offset.y,
		}
	}

	pub fn viewport(&self, axis: Orientation) -> usize {
		match axis {
			Orientation::Horizontal => self.viewport.x,
			Orientation::Vertical => self.viewport.y,
		}
	}

	pub fn set_scroll_viewer(&mut self, scroll_viewer: Weak<RefCell<ScrollViewer>>) {
		self.scroll_viewer = scroll_viewer;
	}
}

#[derive(Clone, Copy, Debug)]
pub enum Direction {
	Up,
	Down,
	Left,
	Right,
}

#[derive(Copy, Clone, Debug)]
pub enum ScrollKind {
	Line,
	Page,
}

/// Scrolling container which manages the internal content's scrolling
///
/// Design (optional Border):
///  ```text
/// ┌─────────┐
/// │Child1  ▲│
/// │Child2  ┃│
/// │Child3   │
/// │Child4   │
/// │Child5  ▼│
/// │◀━     ▶ │
/// └─────────┘
/// ```
#[derive(Default)]
pub struct ScrollViewer {
	base: WidgetBase,
	draw_bars: Vector2D<bool>,
	content: Option<Rc<RefCell<dyn Scrollable>>>,
	show_scrollbar: bool,
	size: Vector2D<TSize>,
}

impl ScrollViewer {
	pub const ARROW_UP: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_UP_DISABLED: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const BAR_MARKER_V: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_DOWN: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_DOWN_DISABLED: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);

	pub const ARROW_LEFT: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_LEFT_DISABLED: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const BAR_MARKER_H: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_RIGHT: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);
	pub const ARROW_RIGHT_DISABLED: Grapheme = Grapheme::new_unchecked("", GlyphWidth::Half);

	pub fn set_content(rc: &Rc<RefCell<Self>>, mut content: Option<&Rc<RefCell<dyn Scrollable>>>) {
		if let Some(old) = rc.borrow_mut().content.as_mut() {
			old.borrow_mut().set_scroll_viewer(Weak::new());
		}

		if let Some(cnt) = content.as_mut() {
			cnt.borrow_mut().set_scroll_viewer(Rc::downgrade(rc));
		}
		let brw = &mut rc.borrow_mut();
		brw.content = content.cloned();
		brw.provoke_changed_property(WindowProperty::Children);
	}

	pub fn set_scrollbar_visibility(&mut self, show: bool) {
		self.show_scrollbar = show;
		self.reevaluate_showbars();
	}

	fn reevaluate_showbars(&mut self) {
		if let Some(cnt) = self.content.as_ref() {
			let brw = cnt.borrow();
			let old = self.draw_bars;
			self.draw_bars = Vector2D::new(
				self.size.x > 2 && brw.is_scrollable(Orientation::Vertical) && self.show_scrollbar,
				self.size.y > 2
					&& brw.is_scrollable(Orientation::Horizontal)
					&& self.show_scrollbar,
			);
			if old != self.draw_bars {
				self.provoke_changed_property(WindowProperty::Children);
			}
		}
	}

	fn render_scroller(
		&self,
		array: &mut dyn GlyphArray,
		size: TPoint,
		content: &dyn Scrollable,
		orientation: Orientation,
		other_bar: bool,
	) {
		let (arrow_prev, arrow_next, bar_marker);
		let (arrow_prev_dis, arrow_next_dis);
		let max_size;

		match orientation {
			Orientation::Horizontal => {
				arrow_prev = Self::ARROW_LEFT;
				arrow_prev_dis = Self::ARROW_LEFT_DISABLED;
				arrow_next = Self::ARROW_RIGHT;
				arrow_next_dis = Self::ARROW_RIGHT_DISABLED;
				bar_marker = Self::BAR_MARKER_H;
				max_size = size.x;
			}
			Orientation::Vertical => {
				arrow_prev = Self::ARROW_UP;
				arrow_prev_dis = Self::ARROW_UP_DISABLED;
				arrow_next = Self::ARROW_DOWN;
				arrow_next_dis = Self::ARROW_DOWN_DISABLED;
				bar_marker = Self::BAR_MARKER_V;
				max_size = size.y;
			}
		}

		if max_size > 2 && content.is_scrollable(orientation) {
			let offset = content.offset(orientation);
			let viewport = content.viewport(orientation);

			let mut arrow_up = array.get(TSize::MIN).unwrap();
			if !self.base.enabled || offset == usize::MIN {
				arrow_up.set_grapheme(arrow_prev_dis).ok();
				if let Some(color) = self.base.colors.disabled {
					arrow_up.set_fg(color);
				}
			}
			else {
				arrow_up.set_grapheme(arrow_prev).ok();
			}
			std::mem::drop(arrow_up);

			let render_size = max_size - other_bar as TSize;
			if max_size >= 2 {
				let length = size[orientation as usize] - 2 - other_bar as TSize;
				let start = (offset * length as usize + 1).div_ceil(viewport) as TSize;
				let end = if offset + render_size as usize > viewport {
					length + 1
				}
				else {
					((offset + render_size as usize + 1) * length as usize).div_ceil(viewport)
						as TSize
				};

				for idx in start..end + (start == end) as TSize {
					let mut g = array.get(idx).unwrap();
					g.set_grapheme(bar_marker).ok();
					if let Some(color) = self.base.colors.disabled
						&& !self.base.enabled
					{
						g.set_fg(color);
					}
				}
			}

			let mut arrow_down = array.get(max_size - 1 - other_bar as TSize).unwrap();
			if !self.base.enabled || offset + render_size as usize >= viewport {
				arrow_down.set_grapheme(arrow_next_dis).ok();
				if let Some(color) = self.base.colors.disabled {
					arrow_down.set_fg(color);
				}
			}
			else {
				arrow_down.set_grapheme(arrow_next).ok();
			}
		}
	}


	/// Can current [Scrollable] be scrolled horizontally / vertically
	pub fn is_scrollable(&self, axis: Orientation) -> bool {
		match self.content.as_ref() {
			Some(sc) => sc.borrow().is_scrollable(axis),
			None => false,
		}
	}

	/// Scrolls page/line-wise (see [ScrollKind]) in the given direction
	pub fn scroll(&mut self, direction: Direction, kind: ScrollKind) {
		if let Some(sc) = self.content.as_ref() {
			sc.borrow_mut().scroll(direction, kind);
		}
	}

	/// Sets the horizontal / vertical offset
	pub fn set_offset(&mut self, direction: Orientation, offset: usize) {
		if let Some(sc) = self.content.as_ref() {
			sc.borrow_mut().set_offset(direction, offset);
		}
	}

	/// Horizontal / Vertical offset of the scrolled content
	pub fn offset(&self, axis: Orientation) -> usize {
		match self.content.as_ref() {
			Some(sc) => sc.borrow().offset(axis),
			None => usize::MIN,
		}
	}

	/// Horizontal / Vertical size of the viewport for current [Scrollable]
	pub fn viewport(&self, axis: Orientation) -> usize {
		match self.content.as_ref() {
			Some(sc) => sc.borrow().viewport(axis),
			None => usize::MIN,
		}
	}
}

impl Window for ScrollViewer {
	fn render(&self, canvas: &mut crate::canvas::Canvas) {
		if let Some(content) = self.content.as_ref() {
			let brw = content.borrow();
			let size = canvas.size();
			if self.draw_bars.x {
				self.render_scroller(
					&mut canvas.get_column(size.x - 1, GlyphWidth::Half).unwrap(),
					size,
					&*brw,
					Orientation::Vertical,
					self.draw_bars.y,
				);
			}
			if self.draw_bars.y {
				self.render_scroller(
					&mut canvas.get_row(size.y - 1, GlyphWidth::Half).unwrap(),
					size,
					&*brw,
					Orientation::Horizontal,
					self.draw_bars.x,
				);
			}
		}
	}

	fn handle_event(&mut self, event: &mut WindowEvent) {
		if let Event::Resize(w, h) = event.raw() {
			self.size = Vector2D::new(*w, *h);
			self.reevaluate_showbars();
		}
	}

	fn children(&mut self, mut builder: SubWindowBuilder) -> super::SubWindows {
		if let Some(ch) = self.content.clone() {
			let rect = builder.base_rect();
			builder
				.add_pair(
					ch,
					Some(
						rect.subrect(
							0,
							0,
							rect.size.x - self.draw_bars.x as TSize,
							rect.size.y - self.draw_bars.y as TSize,
						)
						.unwrap(),
					),
				)
				.unwrap();
		}
		builder.build().unwrap()
	}

	fn focus(&self) -> Option<WindowRef> {
		self.content.clone().map(|x| x as Rc<RefCell<dyn Window>>)
	}

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

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

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

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

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

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

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

impl Widget for ScrollViewer {
	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, height: Size) {
		self.base.size.y = height;
		self.provoke_changed_property(WindowProperty::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_alignment(&mut self, horizontal: HorizontalAlignment, vertical: VerticalAlignment) {
		self.base.alignment = (horizontal, vertical);
		self.provoke_changed_property(WindowProperty::Alignment);
	}

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

	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, height: SizeConstraint) {
		self.base.constraints.y = height;
		self.provoke_changed_property(WindowProperty::Size);
	}
}

impl WidgetColors for ScrollViewer {
	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;
	}
}