tuigui 0.23.0

An easy-to-use, highly extensible, and speedy TUI 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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
macro_rules! include {
    ($module: ident) => {
        mod $module;
        pub use $module::*;
    };
}

include!(backend);
include!(widget);
include!(animation);
include!(shader);
include!(content_processor);
include!(style);

mod type_aliases;
use type_aliases::*;

pub mod preludes;
pub mod backends;
pub mod content_processors;
pub mod widgets;
pub mod animations;
pub mod shaders;
pub mod event;

use std::io;

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Simple enum that dictates what is at a specific location
pub enum Content {
    /// Styled character
    Styled(char, Style),
    /// Nothing (clear terminal area)
    Clear,
}

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Context configuration, this contains config options for different
/// things regarding the context
pub struct ContextConfig {
    /// Delay between each frame draw (doesn't block logic loop).
    /// This option doesn't block, because it is simply a condition
    /// on whether or not the context should draw, there is no thread
    /// sleeping going on here
    pub frame_delay: Option<std::time::Duration>,
    /// Clear the content buffer before every frame draw
    pub clear_buffer: bool,
    /// Specify a custom size for the context to use as the screen size
    pub custom_size: Option<Size>,
    /// If true, don't print at absolute values like (0, 0).
    /// Instead, print relative to where the cursor started
    pub relative_printing: bool,
    /// Use damaged area calculation to limit how much of the terminal is re-drawn
    /// (only re-draw what actually changed) (recommended to always keep this set to 'true')
    pub damaged_only: bool,
    /// Clear any pasted text from the event state after a draw call
    pub clear_paste: bool,
    /// Allow screen tearing (why would you do this!?)
    pub allow_screen_tearing: bool,
}

impl Default for ContextConfig {
    fn default() -> Self {
        Self {
            frame_delay: None,
            clear_buffer: true,
            custom_size: None,
            relative_printing: false,
            damaged_only: true,
            clear_paste: true,
            allow_screen_tearing: false,
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// These are things that should be set and then never touched again.
/// These things relate to setting up and restoring the terminal environment.
pub struct ContextSetupConfig {
    /// Enable raw mode
    pub raw_mode: bool,
    /// Use alternate screen
    pub alt_screen: bool,
    /// Hide the cursor
    pub hide_cursor: bool,
    /// Capture the mouse
    pub capture_mouse: bool,
}

impl Default for ContextSetupConfig {
    fn default() -> Self {
        Self {
            raw_mode: true,
            alt_screen: true,
            hide_cursor: true,
            capture_mouse: false,
        }
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct DrawSummary {
    /// The amount of time taken to draw the frame
    pub duration: std::time::Duration,
    /// Number of terminal characters altered/printed
    pub count: usize,
    /// Index of the drawn buffer
    pub drawn_buffer: usize,
}

#[derive(Debug, Clone)]
/// The context, this handles everything.
/// It handles drawing the frames, it stores the root
/// widget, it calls backend commands, etc...
pub struct Context<CT: ContentProcessorOutput, B: Backend<CT>, C: ContentProcessor<CT>, R: Widget> {
    pub config: ContextConfig,
    pub backend: B,
    pub content_processor: C,
    pub root: R,
    pub event_state: event::EventState,
    last_event_state: Option<event::EventState>,
    filler: Content,
    refresh_all: bool,
    setup_config: ContextSetupConfig,
    has_drawn_before: bool,
    last_draw: Option<std::time::Instant>,
    last_size: Option<Size>,
    buffers: [Buffer; 2],
    front_buffer: usize,
    _phantom: std::marker::PhantomData<CT>,
}

impl<CT: ContentProcessorOutput, B: Backend<CT>, C: ContentProcessor<CT>, R: Widget> Context<CT, B, C, R> {
    /// Create a new context
    pub fn new(config: ContextConfig, setup_config: ContextSetupConfig, backend: B, content_processor: C, root: R) -> Self {
        Self {
            config,
            backend,
            content_processor,
            root,
            setup_config,
            has_drawn_before: false,
            last_draw: None,
            last_size: None,
            buffers: [
                Buffer::new(),
                Buffer::new(),
            ],
            front_buffer: 0,
            filler: Content::Clear,
            refresh_all: true,
            event_state: event::EventState::new(),
            last_event_state: None,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set up the context (call before logic loop)
    pub fn setup(&mut self) -> Result<(), io::Error> {
        self.set_state(true)?;

        Ok(())
    }

    /// Set up the context (call after logic loop)
    pub fn cleanup(&mut self) -> Result<(), io::Error> {
        self.set_state(false)?;

        if self.setup_config.alt_screen == false {
            self.backend.clear(ClearType::FromCursorDown)?;
        }

        Ok(())
    }

    fn set_state(&mut self, enable: bool) -> Result<(), io::Error> {
        if self.setup_config.capture_mouse {
            self.backend.capture_mouse(enable)?;
        }

        if self.setup_config.alt_screen {
            self.backend.alt_screen(enable)?;
        }

        if self.setup_config.raw_mode {
            self.backend.raw_mode(enable)?;
        }

        if self.setup_config.hide_cursor {
            self.backend.show_cursor(!enable)?;
        }

        Ok(())
    }

    /// Obtain the terminal's previous size
    pub fn last_size(&self) -> Option<Size> {
        return self.last_size;
    }

    /// Obtain the time that the context's previous draw happened
    pub fn last_draw(&self) -> Option<std::time::Instant> {
        return self.last_draw;
    }

    /// The duration since the last frame draw
    pub fn duration_since_last_draw(&self) -> Option<std::time::Duration> {
        match self.last_draw() {
            Some(s) => Some(std::time::Instant::now() - s),
            None => None,
        }
    }

    #[inline(always)]
    fn should_draw(&self) -> bool {
        let mut should_draw = true;

        if let Some(frame_delay) = self.config.frame_delay {
            match self.duration_since_last_draw() {
                Some(s) => {
                    if s < frame_delay {
                        should_draw = false;
                    }
                },
                None => (),
            };
        }

        return should_draw;
    }

    #[inline(always)]
    fn front_buffer_index(&self) -> usize {
        return self.front_buffer;
    }

    #[inline(always)]
    fn back_buffer_index(&self) -> usize {
        return match self.front_buffer_index() {
            0 => 1,
            1 => 0,
            _ => unreachable!(),
        }
    }

    #[inline(always)]
    fn swap_buffers(&mut self) {
        self.front_buffer = self.back_buffer_index();
    }

    /// Draw the context (this should be called after every update)
    ///
    /// This function returns a summary if the draw actually took place
    /// sometimes drawing a frame is skipped
    /// (that is how non-blocking frame delay is implemented)
    pub fn draw(&mut self) -> Result<Option<DrawSummary>, io::Error> {
        let draw_start_time = std::time::Instant::now();

        let mut draw_count: usize = 0;

        if self.should_draw() == false {
            return Ok(None);
        }

        self.swap_buffers();

        let front_index = self.front_buffer_index();
        let back_index = self.back_buffer_index();

        if self.config.clear_buffer {
            self.buffers[front_index].clear();
        }

        let offset = match self.config.relative_printing {
            true => self.backend.cursor_position()?,
            false => Position::new(0, 0),
        };

        let size = match self.config.custom_size {
            Some(s) => s,
            None => self.backend.terminal_size()?,
        } - Size::new(offset.col as u16, offset.row as u16);

        let mut canvas = Canvas::new(
            Transform::new(
                Position::zero(),
                size,
            ),
            0,
            &mut self.buffers[front_index],
            self.filler.clone(),
        );

        canvas.transform.size = self.root.widget_info().size_info.correct_size(canvas.transform.size);

        self.root.draw(&mut canvas, Some(&self.event_state_frame()));

        if size != self.last_size.unwrap_or(size) {
            self.refresh_all = true;
        }

        if self.config.allow_screen_tearing == false {
            self.backend.begin_sync_update()?;
        }

        for row in 0..size.rows {
            for col in 0..size.cols {
                let position = Position::new(col as i16, row as i16);
                let draw_position = position + offset;

                let back_content = self.buffers[back_index].get(position);
                let front_content = self.buffers[front_index].get(position);

                let should_draw: bool = self.refresh_all
                    || self.config.damaged_only == false
                    || front_content != back_content;

                if should_draw {
                    self.backend.set_cursor_pos(draw_position)?;

                    let content: Content = match self.buffers[front_index].get(position) {
                        Some(s) => s.clone(),
                        None => self.filler.clone(),
                    };

                    self.print(&content, &mut draw_count)?;
                }
            }
        }

        if self.config.allow_screen_tearing == false {
            self.backend.end_sync_update()?;
        }

        self.backend.set_cursor_pos(offset)?;

        self.backend.flush()?;

        // Set all the prev stuff.
        self.last_draw = Some(std::time::Instant::now());
        self.last_size = Some(size);
        self.last_event_state = Some(self.event_state.clone());

        // Untick stuff.
        self.refresh_all = false;

        if self.config.clear_paste {
            self.event_state.terminal.paste = None;
        }

        // Very last stuff.
        self.has_drawn_before = true;
        let draw_duration = std::time::Instant::now() - draw_start_time;
        Ok(Some(DrawSummary {
            duration: draw_duration,
            count: draw_count,
            drawn_buffer: front_index,
        }))
    }

    #[inline(always)]
    pub fn event_state_frame(&self) -> event::EventStateFrame {
        return self.event_state.calculate_frame(self.last_event_state.clone().unwrap_or(self.event_state.clone()));
    }

    #[inline(always)]
    pub fn get_last_event_state(&self) -> Option<event::EventState> {
        return self.last_event_state.clone();
    }

    #[inline(always)]
    fn print(&mut self, content: &Content, draw_count: &mut usize) -> Result<(), io::Error> {
        self.backend.print(match content {
            Content::Clear => CT::clear_output(),
            Content::Styled(character, style) => {
                self.content_processor.process(*character, style)
            },
        })?;

        *draw_count += 1;

        Ok(())
    }

    #[inline(always)]
    /// This is the content that will be used in place
    /// of empty spots not drawn over by a canvas
    /// (the background content essentially)
    pub fn set_filler(&mut self, content: Content) {
        if self.filler != content {
            self.refresh_all = true;
        }

        self.filler = content;
    }

    #[inline(always)]
    pub fn get_filler(&self) -> &Content {
        return &self.filler;
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
struct Buffer {
    map: HashMap<Position, Content>,
}

impl Buffer {
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    #[inline(always)]
    pub fn set(&mut self, position: Position, content: Option<Content>) {
        match content {
            Some(s) => self.map.insert(position, s),
            None => self.map.remove(&position),
        };
    }

    #[inline(always)]
    pub fn get(&self, position: Position) -> Option<&Content> {
        return self.map.get(&position);
    }

    #[inline(always)]
    pub fn clear(&mut self) {
        self.map = HashMap::new(); // This is faster than .clear() for some reason.
    }
}

/// A canvas is how a widget displays contents
/// you can create a mutable canvas with a certain size and position
/// relative to the parent, and then tell a widget to draw to that canvas
/// via a mutable reference
pub struct Canvas {
    /// Transform with modifications
    pub transform: Transform,
    /// Pointer to the buffer
    buffer_pointer: *mut Buffer,
    /// All the positions of the content that were set by this canvas
    set_by_canvas: HashMap<Position, ()>,
    /// Transform without modifications
    transform_original: Transform,
    /// Canvas hierarchy depth (0 == root)
    depth: u32,
    /// Filler content
    filler: Content,
}

impl Canvas {
    /// Create a new canvas
    fn new(
        transform: Transform,
        depth: u32,
        buffer_pointer: *mut Buffer,
        filler: Content,
    ) -> Self {
        return Self {
            transform,
            buffer_pointer,
            set_by_canvas: HashMap::new(),
            transform_original: transform,
            depth,
            filler,
        };
    }

    #[inline(always)]
    /// Create new child canvas (transform argument is offset)
    pub fn new_child(&self, transform: Transform) -> Self {
        return Self::new(
            transform.offset_by(self.transform.position),
            self.depth + 1,
            self.buffer_pointer,
            self.filler.clone(),
        );
    }

    #[inline(always)]
    /// Create new child canvas with the same transform as the parent
    pub fn new_copy_child(&self) -> Self {
        return self.new_child(Transform::new(Position::zero(), self.transform.size));
    }

    #[inline(always)]
    /// Get canvas hierarchy depth (root == 0)
    pub fn depth(&self) -> u32 {
        return self.depth;
    }

    #[inline(always)]
    /// Returns 'true' if the canvas is the root canvas (hierarchy depth of 0)
    pub fn is_root(&self) -> bool {
        return self.depth == 0;
    }

    #[inline(always)]
    /// Animate canvas
    pub fn animate<A: Animation>(
        &mut self,
        animation: &mut A,
        animation_data: &AnimationData,
        custom_original: Option<Transform>,
    ) {
        self.animate_with_offset(animation, animation_data, custom_original, 0.0);
    }

    #[inline(always)]
    /// Animate canvas (with extra offset option)
    pub fn animate_with_offset<A: Animation>(
        &mut self,
        animation: &mut A,
        animation_data: &AnimationData,
        custom_original: Option<Transform>,
        offset: f64,
    ) {
        let original = custom_original.unwrap_or(self.original_transform());

        self.transform = animate(animation, animation_data, original, offset);
    }

    #[inline(always)]
    /// Original transform (canvas transform without modifications)
    pub fn original_transform(&self) -> Transform {
        return self.transform_original;
    }

    #[inline(always)]
    /// Returns 'true' if the canvas is actually visible,
    /// the canvas is not visible when either the rows or columns
    /// in the canvas size are 0
    pub fn is_visible(&self) -> bool {
        if self.transform.size.cols == 0 || self.transform.size.rows == 0 {
            return false;
        }

        return true;
    }

    #[inline(always)]
    /// Returns 'true' if the content at that position relative
    /// to the canvas has been changed by the canvas
    pub fn changed_at(&self, position: Position) -> bool {
        return !(self.set_by_canvas.get(&position) == None);
    }

    #[inline(always)]
    /// Get content at a specified position on the canvas
    pub fn get(&self, position: Position) -> Option<&Content> {
        if self.transform.zero_position().contains_point(position) == false {
            return None;
        }

        let real_position = self.transform.position + position;

        let buffer = unsafe { &*self.buffer_pointer };

        return buffer.get(real_position);
    }

    #[inline(always)]
    /// Set content at a specified position on the canvas
    pub fn set(&mut self, position: Position, content: Option<Content>) {
        if self.transform.zero_position().contains_point(position) == false {
            return;
        }

        let real_position = self.transform.position + position;
        let mut content = content;

        let buffer = unsafe { &mut *self.buffer_pointer };

        if let Some(Content::Styled(_, ref mut style)) = content {
            let behind_content = buffer.get(real_position).unwrap_or(&self.filler);

            *style = overlay_transparent(style, Some(behind_content), Some(&self.filler));
        }

        buffer.set(real_position, content);
        self.set_by_canvas.insert(position, ());
    }
}

#[inline(always)]
fn overlay_transparent(front: &Style, back: Option<&Content>, filler: Option<&Content>) -> Style {
    let mut style = front.clone();

    macro_rules! style_apply {
        ($fg_bg: ident, $opposite_fg_bg: ident, $pull_layer: expr, $back: ident) => {
            if let Some(content) = $back {
                match content {
                    Content::Styled(_, b_style) => {
                        style.$fg_bg = match $pull_layer {
                            StylePullLayer::Foreground => b_style.fg,
                            StylePullLayer::Background => b_style.bg,
                            StylePullLayer::Same => b_style.$fg_bg,
                            StylePullLayer::Any | StylePullLayer::AnyColor => {
                                let color_only = $pull_layer == StylePullLayer::AnyColor;

                                if (b_style.$fg_bg.is_final() && color_only == false)
                                || (b_style.$fg_bg.is_color() && color_only) {
                                    b_style.$fg_bg
                                } else {
                                    if (b_style.$opposite_fg_bg.is_final() && color_only == false)
                                    || (b_style.$opposite_fg_bg.is_color() && color_only) {
                                        b_style.$opposite_fg_bg
                                    } else {
                                        b_style.$fg_bg
                                    }
                                }
                            },
                        };
                    },
                    Content::Clear => style.$fg_bg = StyleGround::Clear,
                };
            }
        };
    }

    macro_rules! apply {
        ($fg_bg: ident, $opposite_fg_bg: ident) => {
            if style.$fg_bg.is_final() == false {
                if let StyleGround::Filler(pull_layer) = style.$fg_bg {
                    style_apply!($fg_bg, $opposite_fg_bg, pull_layer, filler);
                }

                else if let StyleGround::Transparent(pull_layer) = style.$fg_bg {
                    style_apply!($fg_bg, $opposite_fg_bg, pull_layer, back);
                }
            }
        };
    }

    apply!(fg, bg);
    apply!(bg, fg);

    return style;
}

pub fn compute_refresh_area(
    damaged: Option<Transform>,
    prev_damaged: Option<Transform>,
    has_drawn_before: bool,
    full_size: Size,
) -> Option<Transform> {
    let last_damaged: Option<Transform> = match (prev_damaged, has_drawn_before) {
        (None, false) => Some(Transform::new(Position::zero(), full_size)),
        (l_d, _) => l_d,
    };

    return match (damaged, last_damaged) {
        (Some(damaged), Some(last_damaged)) => Some(damaged.combined_area(last_damaged)),
        (Some(damaged), None) => Some(damaged),
        (None, Some(last_damaged)) => Some(last_damaged),
        (None, None) => None,
    };
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Terminal transform for an area
pub struct Transform {
    pub position: Position,
    pub size: Size,
}

impl Transform {
    pub fn new(position: Position, size: Size) -> Self {
        Self {
            position,
            size,
        }
    }

    #[inline(always)]
    pub fn zero() -> Self {
        Self::new(Position::zero(), Size::zero())
    }

    #[inline(always)]
    /// Return a copy of the transform with the position set to (0, 0)
    pub fn zero_position(&self) -> Self {
        return Self::new(Position::zero(), self.size);
    }

    #[inline(always)]
    /// Return a copy of the transform with the position offset by the specified position
    pub fn offset_by(&self, offset: Position) -> Self {
        return Self::new(self.position + offset, self.size);
    }

    #[inline(always)]
    /// Returns 'true' if the given position lies somewhere inside the transform as an area
    ///
    /// # Examples:
    /// ```rust
    /// use tuigui::{ Transform, Position, Size };
    ///
    /// fn main() {
    ///     let area = Transform::new(Position::new(12, 8), Size::new(10, 6));
    ///     let points = [ // (position, inside)
    ///         (Position::new(12, 8), true),
    ///         (Position::new(21, 13), true),
    ///         (Position::new(22, 13), false),
    ///         (Position::new(15, 10), true),
    ///     ];
    ///
    ///     for i in points {
    ///         assert_eq!(area.contains_point(i.0), i.1);
    ///     }
    /// }
    /// ```
    pub fn contains_point(&self, position: Position) -> bool {
        if position.col >= self.position.col
        && position.row >= self.position.row {
            if position.col < self.size.cols as i16 + self.position.col
            && position.row < self.size.rows as i16 + self.position.row {
                return true;
            }
        }

        return false;
    }

    #[inline(always)]
    /// Same as combining for total area, but treating the position
    /// as a transform of size (1, 1)
    ///
    /// # Examples:
    /// ```rust
    /// use tuigui::{ Transform, Position, Size };
    ///
    /// fn main() {
    ///     let area = Transform::new(Position::new(12, 8), Size::new(10, 6));
    ///     let expanded = area.expand_to_position(Position::new(4, 5));
    ///
    ///     assert_eq!(expanded, Transform::new(Position::new(4, 5), Size::new(18, 9)));
    /// }
    /// ```
    pub fn expand_to_position(&self, position: Position) -> Self {
        return self.combined_area(Self::new(position, Size::new(1, 1)));
    }

    #[inline(always)]
    /// Return the total rectangular area of 2 transforms
    ///
    /// # Examples:
    /// ```rust
    /// use tuigui::{ Transform, Position, Size };
    ///
    /// fn main() {
    ///     let area_1 = Transform::new(Position::new(2, 4), Size::new(7, 5));
    ///     let area_2 = Transform::new(Position::new(10, 11), Size::new(2, 3));
    ///
    ///     let total_area = area_1.combined_area(area_2);
    ///
    ///     assert_eq!(total_area, Transform::new(Position::new(2, 4), Size::new(10, 10)));
    /// }
    /// ```
    pub fn combined_area(&self, other: Self) -> Self {
        let mut total = *self;

        if other.position.row < total.position.row {
            total.size.rows += (total.position.row - other.position.row) as u16;
            total.position.row = other.position.row;
        }

        if other.position.col < total.position.col {
            total.size.cols += (total.position.col - other.position.col) as u16;
            total.position.col = other.position.col;
        }

        if other.size.rows as i16 + other.position.row >= total.size.rows as i16 + total.position.row {
            total.size.rows = ((other.size.rows as i16 + other.position.row) - total.position.row) as u16;
        }

        if other.size.cols as i16 + other.position.col >= total.size.cols as i16 + total.position.col {
            total.size.cols = ((other.size.cols as i16 + other.position.col) - total.position.col) as u16;
        }

        return total;
    }

    #[inline(always)]
    pub fn apply_lerp(&self, b: Self, t: f64, f: fn(f64, f64, f64) -> f64) -> Self {
        return Self::new(
            Position {
                col: f(self.position.col as f64, b.position.col as f64, t) as i16,
                row: f(self.position.row as f64, b.position.row as f64, t) as i16,
            },
            Size {
                cols: f(self.size.cols as f64, b.size.cols as f64, t) as u16,
                rows: f(self.size.rows as f64, b.size.rows as f64, t) as u16,
            },
        );
    }

    #[inline(always)]
    pub fn apply_quadratic_bezier(&self, control: Self, b: Self, t: f64, f: fn(f64, f64, f64, f64) -> f64) -> Self {
        return Self::new(
            Position {
                col: f(self.position.col as f64, control.position.col as f64, b.position.col as f64, t) as i16,
                row: f(self.position.row as f64, control.position.row as f64, b.position.row as f64, t) as i16,
            },
            Size {
                cols: f(self.size.cols as f64, control.size.cols as f64, b.size.cols as f64, t) as u16,
                rows: f(self.size.rows as f64, control.size.rows as f64, b.size.rows as f64, t) as u16,
            },
        );
    }

    #[inline(always)]
    pub fn apply_cubic_bezier(&self, a_control: Self, b: Self, b_control: Self, t: f64, f: fn(f64, f64, f64, f64, f64) -> f64) -> Self {
        return Self::new(
            Position {
                col: f(self.position.col as f64, a_control.position.col as f64, b.position.col as f64, b_control.position.col as f64, t) as i16,
                row: f(self.position.row as f64, a_control.position.row as f64, b.position.row as f64, b_control.position.row as f64, t) as i16,
            },
            Size {
                cols: f(self.size.cols as f64, a_control.size.cols as f64, b.size.cols as f64, b_control.size.cols as f64, t) as u16,
                rows: f(self.size.rows as f64, a_control.size.rows as f64, b.size.rows as f64, b_control.size.rows as f64, t) as u16,
            },
        );
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Size of an area in the terminal
pub struct Size {
    pub cols: u16,
    pub rows: u16,
}

impl Size {
    pub fn new(cols: u16, rows: u16) -> Self {
        Self {
            cols,
            rows,
        }
    }

    #[inline(always)]
    pub fn zero() -> Self {
        Self::new(0, 0)
    }

    #[inline(always)]
    pub fn same(cols_rows: u16) -> Self {
        Self::new(cols_rows, cols_rows)
    }

    #[inline(always)]
    /// Get the total area of a size (cols * rows)
    pub fn area(&self) -> u32 {
        return (self.cols as u32) * (self.rows as u32);
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Position in the terminal where (col: 0, row: 0) is the top left
pub struct Position {
    pub col: i16,
    pub row: i16,
}

impl Position {
    pub fn new(col: i16, row: i16) -> Self {
        Self {
            col,
            row,
        }
    }

    #[inline(always)]
    pub fn zero() -> Self {
        Self::new(0, 0)
    }

    #[inline(always)]
    pub fn same(col_row: i16) -> Self {
        Self::new(col_row, col_row)
    }
}

macro_rules! op_impl_core {
    ($op: ident, $func: ident, $subfunc: ident) => {
        impl std::ops::$op for Size {
            type Output = Self;

            fn $func(self, rhs: Self) -> Self::Output {
                Self {
                    cols: self.cols.$subfunc(rhs.cols),
                    rows: self.rows.$subfunc(rhs.rows),
                }
            }
        }

        impl std::ops::$op for Position {
            type Output = Self;

            fn $func(self, rhs: Self) -> Self::Output {
                Self {
                    col: self.col.$subfunc(rhs.col),
                    row: self.row.$subfunc(rhs.row),
                }
            }
        }

        impl std::ops::$op for Transform {
            type Output = Self;

            fn $func(self, rhs: Self) -> Self::Output {
                Self {
                    position: self.position.$func(rhs.position),
                    size: self.size.$func(rhs.size),
                }
            }
        }
    };
}

macro_rules! op_impl {
    ($op: ident, $func: ident) => {
        op_impl_core!($op, $func, $func);
    };
    ($op: ident, $func: ident, $subfunc: ident) => {
        op_impl_core!($op, $func, $subfunc);
    };
}

op_impl!(Add, add, saturating_add);
op_impl!(Sub, sub, saturating_sub);
op_impl!(Mul, mul, saturating_mul);
op_impl!(Div, div, saturating_div);
op_impl!(Rem, rem);
op_impl!(Shl, shl);
op_impl!(Shr, shr);