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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::io::{BufWriter, Stdout};
use std::num::NonZero;

use arrayvec::ArrayString;
use bitflags::bitflags;
use crossterm::QueueableCommand;
use crossterm::style::{self, Attribute};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use vector2d::Vector2D;

pub use arrayvec_const as arrayvec;
pub use as_any;
pub use crossterm;
pub use vector2d;

pub use crossterm::event::Event;
pub use crossterm::style::Color;

/// Terminal size limitation
pub type TSize = u16;
/// Point/Coordinate inside a terminal
pub type TPoint = Vector2D<TSize>;

/// Direction of characters being drawn
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CharDirection {
	/// Left to Right
	LeftRight,
	/// Right to Left
	RightLeft,
}

/// Generic over the concept of vertical/horizontal
/// Lower/Higher are relative terms in relation to the screen coordinates
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Alignment {
	LowerBound,
	Center,
	HigherBound,
}

impl From<Alignment> for HorizontalAlignment {
	fn from(value: Alignment) -> Self {
		match value {
			Alignment::LowerBound => Self::Left,
			Alignment::Center => Self::Center,
			Alignment::HigherBound => Self::Right,
		}
	}
}

impl From<Alignment> for VerticalAlignment {
	fn from(value: Alignment) -> Self {
		match value {
			Alignment::LowerBound => Self::Top,
			Alignment::Center => Self::Center,
			Alignment::HigherBound => Self::Bottom,
		}
	}
}

/// Alignment on the x-axis
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum HorizontalAlignment {
	Left,
	#[default]
	Center,
	Right,
}

impl From<HorizontalAlignment> for Alignment {
	fn from(value: HorizontalAlignment) -> Self {
		match value {
			HorizontalAlignment::Left => Self::HigherBound,
			HorizontalAlignment::Center => Self::Center,
			HorizontalAlignment::Right => Self::HigherBound,
		}
	}
}

/// Alignment on the y-axis
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum VerticalAlignment {
	Top,
	#[default]
	Center,
	Bottom,
}

impl From<VerticalAlignment> for Alignment {
	fn from(value: VerticalAlignment) -> Self {
		match value {
			VerticalAlignment::Top => Self::HigherBound,
			VerticalAlignment::Center => Self::Center,
			VerticalAlignment::Bottom => Self::HigherBound,
		}
	}
}

/// Orientation of a component (e.g. StackPanel or ScrollViewer)
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(usize)]
pub enum Orientation {
	Horizontal = 0,
	Vertical,
}

impl Orientation {
	const INV_MAP: [Orientation; 2] = [Self::Vertical, Self::Horizontal];

	pub fn invert(&self) -> Self {
		Self::INV_MAP[*self as usize]
	}
}

#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Line2D<T> {
	pub a: Vector2D<T>,
	pub b: Vector2D<T>,
}

impl Line2D<TSize> {
	pub const fn new(x1: TSize, y1: TSize, x2: TSize, y2: TSize) -> Self {
		Self {
			a: Vector2D::new(x1, y1),
			b: Vector2D::new(x2, y2),
		}
	}

	pub const fn from(p1: TPoint, p2: TPoint) -> Self {
		Self { a: p1, b: p2 }
	}

	pub const fn is_vertical(&self) -> bool {
		self.a.x == self.b.x
	}

	pub const fn is_horizontal(&self) -> bool {
		self.a.y == self.b.y
	}

	pub const fn is_ascending(&self) -> bool {
		self.a.y < self.b.y
	}

	pub const fn is_descending(&self) -> bool {
		self.a.y > self.b.y
	}

	pub const fn is_constant(&self) -> bool {
		self.a.y == self.b.y
	}

	/// Interval = 1
	pub const fn iter_points(&self) -> PointIterator<Line2D<TSize>> {
		PointIterator::<Line2D<TSize>>::new(*self)
	}
}

pub struct PointIterator<T: Sized> {
	line: T,
	cursor: TSize,
}

impl Iterator for PointIterator<Line2D<TSize>> {
	type Item = TPoint;

	fn next(&mut self) -> Option<Self::Item> {
		let mut ret = None;
		if self.line.is_vertical() {
			if self.cursor < self.line.b.y {
				ret = Some(Vector2D::new(self.line.a.y, self.cursor));
				self.cursor += 1;
			}
		}
		else if self.cursor < self.line.b.x {
			let div = self.line.b.x - self.line.a.x;
			let mut m = TSize::MIN;
			if div != TSize::MIN {
				m = (self.line.b.y - self.line.a.y) / div;
			}
			let b = self.line.a.y - self.line.a.x * m;
			ret = Some(Vector2D::new(self.cursor, m * self.cursor + b));

			self.cursor += 1;
		}
		ret
	}
}

impl PointIterator<Line2D<TSize>> {
	const fn new(line: Line2D<TSize>) -> Self {
		if line.is_vertical() {
			Self {
				line,
				cursor: line.a.y,
			}
		}
		else {
			Self {
				line,
				cursor: line.a.x,
			}
		}
	}
}


/// Wraps a percentage value
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Percent(NonZero<u8>);

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

impl Percent {
	pub const MIN: Self = Self(NonZero::<u8>::MIN);
	pub const MAX: Self = Self(NonZero::new(100).unwrap());
	pub const DEFAULT: Self = Self::MAX;

	/// The value must be between 1 and 100, otherwise it will get coerced into the range
	pub const fn from_int(u: u8) -> Self {
		if u == 0 {
			Self::MIN
		}
		else if u >= 100 {
			Self::MAX
		}
		else {
			Self(NonZero::new(u).unwrap())
		}
	}

	/// The value must be between 0.01 and 1., otherwise it will get coerced into the range
	pub const fn from_float(f: f32) -> Self {
		if !f.is_normal() {
			return Self::DEFAULT;
		}
		let u = (f * 100.) as u8;
		if u == 0 {
			Self::MIN
		}
		else if u >= 100 {
			Self::MAX
		}
		else {
			Self(NonZero::new(u).unwrap())
		}
	}

	/// Multiplies the percentage value with an TSize
	pub const fn multiply(self, u: TSize) -> TSize {
		(u * self.0.get() as TSize) / 100
	}

	/// Inner percentage value as u8
	pub const fn value(self) -> u8 {
		self.0.get()
	}
}


/// Defines the width of a single [Grapheme] - see <https://unicode.org/reports/tr11/>
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(usize)]
pub enum GlyphWidth {
	Half = 1,
	Full = 2,
}

impl TryFrom<usize> for GlyphWidth {
	type Error = GraphemeError;

	fn try_from(value: usize) -> Result<Self, GraphemeError> {
		match value {
			1 => Ok(GlyphWidth::Half),
			2 => Ok(GlyphWidth::Full),
			_ => Err(GraphemeError::ConversionError),
		}
	}
}

impl Default for GlyphWidth {
	fn default() -> Self {
		Self::Half
	}
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// Grapheme with calculated width and safety checks
pub struct Grapheme {
	inner: ArrayString<{ Self::MAX_SIZE }>,
	width: GlyphWidth,
}

impl Default for Grapheme {
	fn default() -> Self {
		Self::PLACEHOLDER
	}
}

impl Grapheme {
	pub const MAX_SIZE: usize = 16;
	pub const PLACEHOLDER: Self = Self::new_unchecked(" ", GlyphWidth::Half);
	pub const REPLACEMENT: Self = Self::new_unchecked("\u{FFFD}", GlyphWidth::Half);

	//TODO: In case arrayvec_const will get merged, switch back to arrayvec
	/// This will create a grapheme from a static [str] with a predefined width
	/// Which will only do the most necessary checks on the grapheme
	pub(crate) const fn new_unchecked(grapheme: &'static str, width: GlyphWidth) -> Self {
		if grapheme.len() > Self::MAX_SIZE {
			panic!(stringify!(GraphemeError::GraphemeTooBig));
		}
		if grapheme.as_bytes()[0] < 32 {
			panic!(stringify!(GraphemeError::InvalidGlyphWidth));
		}
		//TODO: Result::unwrap is currently not const
		match ArrayString::from(grapheme) {
			Ok(v) => Self { width, inner: v },
			Err(_) => panic!("Error creating ArrayString"),
		}
	}

	/// Creates a new [Grapheme] from a [str].
	/// Checks that `grapheme` fulfills all checks:
	/// - Length does not exceed [Self::MAX_SIZE]
	/// - Contains exactly one grapheme
	/// - Is not a control char
	/// - Width is not zero
	pub fn from(grapheme: &str) -> Result<Self, GraphemeError> {
		if grapheme.len() > Self::MAX_SIZE {
			return Err(GraphemeError::GraphemeTooBig);
		}

		let mut graphemes = grapheme.graphemes(true);
		let _ = graphemes.next();
		let g2 = graphemes.next();

		if g2.is_some() {
			return Err(GraphemeError::TooManyGraphemes);
		}

		let width = grapheme.width();
		if grapheme.as_bytes()[0] < 32 || width == 0 {
			return Err(GraphemeError::InvalidGlyphWidth);
		}

		Ok(Self {
			inner: ArrayString::from(grapheme).unwrap(),
			width: GlyphWidth::try_from(width).unwrap(),
		})
	}

	#[inline(always)]
	pub(crate) fn get_string(&self) -> ArrayString<{ Self::MAX_SIZE }> {
		self.inner
	}

	#[inline(always)]
	pub fn as_str(&self) -> &str {
		&self.inner
	}

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

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum GraphemeError {
	GraphemeTooBig,
	TooManyGraphemes,
	InvalidGlyphWidth,
	ConversionError,
}

impl Display for GraphemeError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.write_fmt(format_args!("{self:?}"))
	}
}

impl Error for GraphemeError {}

bitflags! {
	/// Styles which just contain the best supported attributed by most terminals
	/// Used as bitflags seperately
	#[derive(Debug, Copy, Clone, PartialEq, Default, PartialOrd, Hash)]
	pub struct Style: u8{

	/// No styles at all, the default
	const None = 0b0000_0000;
	/// Resets all styles before drawing the current glyph
	const ResetBefore = 0b0000_0001;
	/// Resets all styles after drawing the current glyph
	/// The only attribute applied after the current glyph
	const ResetAfter = 0b0000_0010;
	/// Makes the text bold
	const Bold = 0b0000_0100;
	/// Removes bold effect
	const NoBold = 0b0000_1000;
	/// Makes the text underlined
	const Underline = 0b0001_0000;
	/// Removes underlined effect
	const NoUnderline = 0b0010_0000;
	/// Reverse fore- and background color
	const Reverse = 0b0100_0000;
	/// Removes underlined effect
	const NoReverse = 0b1000_0000;
	}
}

impl Style {
	const ATTRIBUTES: [Attribute; 8] = [
		// ResetBefore
		Attribute::Reset,
		// ResetAfter
		Attribute::Reset,
		Attribute::Bold,
		Attribute::NoBold,
		Attribute::Underlined,
		Attribute::NoUnderline,
		Attribute::Reverse,
		Attribute::NoReverse,
	];

	#[inline(always)]
	pub(crate) fn apply_pre_styles(
		stdout: &mut BufWriter<Stdout>,
		flags: Style,
	) -> Result<(), std::io::Error> {
		for idx in [0, 2, 3, 4, 5, 6, 7] {
			if flags.bits() & (1 << idx) != 0 {
				stdout.queue(style::SetAttribute(Self::ATTRIBUTES[idx]))?;
			}
		}
		Ok(())
	}

	#[inline(always)]
	pub(crate) fn apply_post_styles(
		stdout: &mut BufWriter<Stdout>,
		flags: Style,
	) -> Result<(), std::io::Error> {
		const INDEX: u8 = Style::ResetAfter.flag_index();
		if flags.bits() & (1 << INDEX) != 0 {
			stdout.queue(style::SetAttribute(Self::ATTRIBUTES[INDEX as usize]))?;
		}
		Ok(())
	}

	#[inline(always)]
	const fn flag_index(self) -> u8 {
		let mut n = u8::MIN;
		while (self.bits() >> (n + 1)) != 0 {
			n += 1;
		}
		n
	}

	/// Returns self if condition is met otherwise [Self::None]
	#[inline(always)]
	pub fn when(self, when: bool) -> Self {
		Self::from_bits_retain(self.bits() * when as u8)
	}
}

// Visual glyph, which consists of a unicode grapheme, its fore- and background color
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) struct Glyph {
	pub style: Style,
	pub bg: Option<Color>,
	pub fg: Option<Color>,
	pub grapheme: ArrayString<{ Grapheme::MAX_SIZE }>,
}

impl Default for Glyph {
	fn default() -> Self {
		Self {
			style: Style::default(),
			bg: None,
			fg: None,
			grapheme: ArrayString::from(Grapheme::PLACEHOLDER.as_str()).unwrap(),
		}
	}
}

impl Glyph {
	pub const NULL: &'static str = "\0";

	pub fn nullify(&mut self) {
		self.grapheme.clear();
		self.grapheme.push_str(Self::NULL);
	}

	pub fn is_null(&self) -> bool {
		self.grapheme.as_str() == Self::NULL
	}
}


pub enum RectError {
	HorizontalBorderExceeds(Rect, Rect),
	VerticalBorderExceeds(Rect, Rect),
}

impl Debug for RectError {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::HorizontalBorderExceeds(rect, base) => write!(
				f,
				"Rect ({rect:?}) exceeds the base rect's ({base:?}) right border."
			),
			Self::VerticalBorderExceeds(rect, base) => write!(
				f,
				"Rect ({rect:?}) exceeds the base rect's ({base:?}) right border."
			),
		}
	}
}

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

/// Rectangle defining an area
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Rect {
	pub(crate) start: TPoint,
	pub(crate) size: TPoint,
}

impl Rect {
	/// Creates a new rect which is relative to the base coordinates of {0, 0}
	/// This will be relative to the base and check their bounds
	pub const fn subrect(
		&self,
		x: TSize,
		y: TSize,
		width: TSize,
		height: TSize,
	) -> Result<Rect, RectError> {
		let abs = Rect {
			start: Vector2D::new(self.start.x + x, self.start.y + y),
			size: Vector2D::new(width, height),
		};
		let base_end = self.end();
		let end = abs.end();
		if end.x > base_end.x {
			return Err(RectError::HorizontalBorderExceeds(*self, abs));
		}
		if end.y > base_end.y {
			return Err(RectError::VerticalBorderExceeds(*self, abs));
		}

		Ok(abs)
	}

	/// Same as [Self::subrect] but with [Vector2D]s as arguments
	pub fn subrect2(&self, offset: TPoint, size: TPoint) -> Result<Rect, RectError> {
		let abs = Rect {
			start: self.start + offset,
			size,
		};
		let base_end = self.end();
		let end = abs.end();
		if end.x > base_end.x {
			return Err(RectError::HorizontalBorderExceeds(*self, abs));
		}
		if end.y > base_end.y {
			return Err(RectError::VerticalBorderExceeds(*self, abs));
		}

		Ok(abs)
	}

	/// Creates a new Rect with start x and y being 0
	pub(crate) fn from(width: TSize, height: TSize) -> Self {
		Self {
			start: Vector2D::new(TSize::MIN, TSize::MIN),
			size: Vector2D::new(width, height),
		}
	}

	/// Start coordinates
	pub const fn start(&self) -> TPoint {
		self.start
	}

	/// Size of the rectangle
	pub const fn size(&self) -> TPoint {
		self.size
	}

	/// End coordinates (start + end)
	pub const fn end(&self) -> TPoint {
		Vector2D::new(self.start.x + self.size.x, self.start.y + self.size.y)
	}

	/// Checks if the two rects overlap
	pub fn overlaps(&self, other: &Self) -> bool {
		let end1 = self.end();
		let end2 = other.end();
		let x_overlap = self.start.x < end2.x
			&& end1.x > other.start.x
			&& self.start.y < end2.y
			&& end1.y > other.start.y;
		let y_overlap = self.start.x < end2.x
			&& end1.x > other.start.x
			&& self.start.y > end2.y
			&& end1.y < other.start.y;
		x_overlap || y_overlap
	}

	/// Splits the rect into two seperate rects at the given `orientation`'s line
	/// `ratio` determines the size of the first rect, the other rect will occupy the remaining
	/// size
	/// 'padding' might be adjusted towards 0 in case one of the rect's area would be 0 => Thus
	/// this method will always produce rects with a width/height of 1
	pub fn split(
		&self,
		orientation: Orientation,
		ratio: Percent,
		mut padding: TSize,
	) -> Result<SplitRect, RectError> {
		let min_base_base = self.size[orientation.invert() as usize].saturating_sub(2);
		if padding >= min_base_base {
			padding = min_base_base;
		}
		eprintln!("padding: {padding}");

		match orientation {
			Orientation::Horizontal => {
				let y = self.size().y - padding;
				let subsize = (ratio.value() as TSize * y).div_ceil(100);
				let padding_area = match padding {
					0 => None,
					v => Some(self.subrect(0, subsize, self.size().x, v)?),
				};

				Ok(SplitRect {
					rects: (
						self.subrect(0, 0, self.size().x, subsize)?,
						self.subrect(0, subsize + padding, self.size().x, y - subsize)?,
					),
					padding_area,
				})
			}
			Orientation::Vertical => {
				let x = self.size().x - padding;
				let subsize = (ratio.value() as TSize * x).div_ceil(100);
				let padding_area = match padding {
					0 => None,
					v => Some(self.subrect(subsize, 0, v, self.size().y)?),
				};
				Ok(SplitRect {
					rects: (
						self.subrect(0, 0, subsize, self.size().y)?,
						self.subrect(subsize + padding, 0, x - subsize, self.size().y)?,
					),
					padding_area,
				})
			}
		}
	}


	/// Returns the inner area
	pub const fn area(&self) -> TSize {
		self.size.x * self.size.y
	}
}

#[derive(Debug)]
pub struct SplitRect {
	pub rects: (Rect, Rect),
	/// None if padding is 0
	pub padding_area: Option<Rect>,
}

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

	#[test]
	fn grapheme_invalid_chars() {
		for c in 0..32 {
			assert_eq!(
				Grapheme::from(&char::from_u32(c).unwrap().to_string()),
				Err(GraphemeError::InvalidGlyphWidth)
			);
		}
	}

	#[test]
	fn grapheme_check_count() {
		assert_eq!(Grapheme::from("abc"), Err(GraphemeError::TooManyGraphemes));
		assert_eq!(Grapheme::from("ʤĵ"), Err(GraphemeError::TooManyGraphemes));
	}

	#[test]
	fn grapheme_check_size() {
		assert_eq!(Grapheme::from("🤦🏻‍♂️"), Err(GraphemeError::GraphemeTooBig));
	}

	#[test]
	fn percent_int() {
		assert_eq!(Percent::from_int(0), Percent::from_int(1));
		assert_eq!(Percent::from_int(101), Percent::from_int(100));
		for v in 1..=100 {
			assert_eq!(Percent::from_int(v).value(), v);
		}
	}

	#[test]
	fn percent_float() {
		assert_eq!(Percent::from_float(0.001), Percent::from_int(1));
		assert_eq!(Percent::from_float(1.1), Percent::from_int(100));
		assert_eq!(Percent::from_float(f32::INFINITY), Percent::from_int(100));
		let mut v = 0.01;
		while v <= 1. {
			assert_eq!(Percent::from_float(v).value(), (v * 100.) as u8);
			v += 0.01;
		}
	}

	mod line {
		use super::*;

		#[test]
		fn check_ctor() {
			assert_eq!(
				Line2D::from(Vector2D::new(0, 4), Vector2D::new(2, 1)),
				Line2D::new(0, 4, 2, 1)
			);
		}

		#[test]
		fn check_iter() {
			let f1 = |x: TSize| 2 * x + 4;
			let l1 = Line2D::new(0, 4, 16, 4);
			let l2 = Line2D::new(2, 4, 2, 20);
			let l3 = Line2D::new(0, f1(0), 12, f1(12));

			for (v, exp) in l1.iter_points().zip(0..16) {
				assert_eq!(v.x, exp);
			}

			for (v, exp) in l2.iter_points().zip(4..20) {
				assert_eq!(v.y, exp);
			}

			for v in l3.iter_points() {
				assert_eq!(v.y, f1(v.x));
			}
		}

		#[test]
		fn check_linear_properties() {
			let l1 = Line2D::new(0, 4, 2, 1);
			let l2 = Line2D::new(2, 1, 4, 5);
			assert!(l1.is_descending());
			assert!(l2.is_ascending());
			assert!(!l1.is_vertical());
			assert!(!l2.is_horizontal());

			let l3 = Line2D::new(2, 4, 2, 12);
			let l4 = Line2D::new(1, 2, 12, 2);
			assert!(l3.is_vertical());
			assert!(l4.is_horizontal());
			assert!(l4.is_constant());
		}
	}

	#[test]
	fn rect_check() {
		let rect = Rect::from(100, 100);
		let subrect = rect.subrect(20, 20, 50, 50).unwrap();
		assert_ne!(rect.start(), subrect.start());
		assert_ne!(rect.end(), subrect.end());
		assert_ne!(rect.area(), subrect.area());
		assert!(subrect.overlaps(&rect));
		assert!(!subrect.overlaps(&Rect::from(20, 20)));
		assert!(subrect.overlaps(&Rect::from(21, 21)));
		assert!(!subrect.overlaps(&Rect::from(20, 21)));
		assert!(!subrect.overlaps(&Rect::from(21, 20)));
		assert!(!subrect.overlaps(&rect.subrect(70, 70, 20, 20).unwrap()));
		assert!(subrect.overlaps(&rect.subrect(69, 69, 20, 20).unwrap()));
		assert!(!subrect.overlaps(&rect.subrect(70, 69, 20, 20).unwrap()));
		assert!(!subrect.overlaps(&rect.subrect(69, 70, 20, 20).unwrap()));
		let subsubrect = subrect.subrect(10, 10, 20, 20).unwrap();
		assert_eq!(subsubrect.start(), subrect.start() + Vector2D::new(10, 10));
		assert!(
			subrect
				.subrect(0, 0, subrect.size().x + 1, subrect.size().y + 1)
				.is_err()
		);
	}

	#[test]
	fn rect_split_check() {
		let rect = Rect::from(64, 64);
		let p = Percent::from_int(20);
		let split = rect.split(Orientation::Horizontal, p, 2).unwrap();
		let expected_rect_0 = Rect {
			start: Vector2D::new(0, 0),
			size: Vector2D::new(64, 13),
		};
		let expected_rect_1 = Rect {
			start: Vector2D::new(0, 15),
			size: Vector2D::new(64, 49),
		};
		assert_eq!(split.rects, (expected_rect_0, expected_rect_1));

		let p = Percent::from_int(40);
		let split = rect.split(Orientation::Vertical, p, 3).unwrap();
		let expected_rect_0 = Rect {
			start: Vector2D::new(0, 0),
			size: Vector2D::new(25, 64),
		};
		let expected_rect_1 = Rect {
			start: Vector2D::new(28, 0),
			size: Vector2D::new(36, 64),
		};
		assert_eq!(split.rects, (expected_rect_0, expected_rect_1));


		let small_rect = Rect::from(4, 4);
		let p = Percent::from_int(20);
		let split = small_rect.split(Orientation::Horizontal, p, 2).unwrap();
		let expected_rect_0 = Rect {
			start: Vector2D::new(0, 0),
			size: Vector2D::new(4, 1),
		};
		let expected_rect_1 = Rect {
			start: Vector2D::new(0, 3),
			size: Vector2D::new(4, 1),
		};
		assert_eq!(split.rects, (expected_rect_0, expected_rect_1));

		let split = small_rect.split(Orientation::Horizontal, p, 4).unwrap();
		assert_eq!(split.rects, (expected_rect_0, expected_rect_1));
	}
}