r3bl_tui 0.3.6

TUI library inspired by Redux, Redux, Flexbox, CSS, editor components, etc
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
/*
 *   Copyright (c) 2022 R3BL LLC
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

use std::fmt::Debug;

use r3bl_rs_utils_core::*;

use crate::*;

#[derive(Debug)]
pub enum DialogEngineApplyResponse {
    UpdateEditorBuffer(EditorBuffer),
    DialogChoice(DialogChoice),
    SelectScrollResultsPanel,
    Noop,
}

/// Things you can do with a [DialogEngine].
pub struct DialogEngineApi;

impl DialogEngineApi {
    pub async fn render_engine<S, A>(
        args: DialogEngineArgs<'_, S, A>,
    ) -> CommonResult<RenderPipeline>
    where
        S: HasDialogBuffers + Default + Clone + PartialEq + Debug + Sync + Send,
        A: Debug + Default + Clone + Sync + Send,
    {
        let mode = args.dialog_engine.dialog_options.mode;
        let overlay_flex_box: PartialFlexBox = {
            match &args.dialog_engine.maybe_flex_box {
                // No need to calculate new flex box if:
                // 1) there's an existing one & 2) the window size hasn't changed.
                Some((saved_size, saved_mode, saved_box))
                    if saved_size == args.window_size && saved_mode == &mode =>
                {
                    *saved_box
                }
                // Otherwise, calculate a new flex box & save it.
                _ => {
                    let it = internal_impl::make_flex_box_for_dialog(
                        &args.self_id,
                        &args.dialog_engine.dialog_options,
                        args.window_size,
                        args.dialog_engine.maybe_surface_bounds,
                    )?;
                    args.dialog_engine.maybe_flex_box.replace((
                        *args.window_size,
                        mode,
                        it,
                    ));
                    it
                }
            }
        };

        let (origin_pos, bounds_size) =
            overlay_flex_box.get_style_adjusted_position_and_size();

        let pipeline = {
            let mut it = render_pipeline!();

            it.push(
                ZOrder::Glass,
                internal_impl::render_border(
                    &origin_pos,
                    &bounds_size,
                    args.dialog_engine,
                ),
            );

            it.push(
                ZOrder::Glass,
                internal_impl::render_title(
                    &origin_pos,
                    &bounds_size,
                    &args.dialog_buffer.title,
                    args.dialog_engine,
                ),
            );

            // Call render_results_panel() if mode is autocomplete.
            if matches!(
                args.dialog_engine.dialog_options.mode,
                DialogEngineMode::ModalAutocomplete
            ) {
                let results_panel_ops = internal_impl::render_results_panel(
                    &origin_pos,
                    &bounds_size,
                    args.dialog_engine,
                    args.self_id,
                    args.state,
                )?;
                if !results_panel_ops.is_empty() {
                    it.push(ZOrder::Glass, results_panel_ops);
                }
            }

            it += internal_impl::render_editor(&origin_pos, &bounds_size, args).await?;

            it
        };

        Ok(pipeline)
    }

    /// Event based interface for the editor. This executes the [InputEvent] and returns one of the
    /// following:
    /// - [DialogEngineApplyResponse::DialogChoice] => <kbd>Enter</kbd> or <kbd>Esc</kbd> was
    ///   pressed.
    /// - [DialogEngineApplyResponse::UpdateEditorBuffer] => the editor buffer was updated.
    /// - [DialogEngineApplyResponse::Noop] => otherwise.
    pub async fn apply_event<S, A>(
        args: DialogEngineArgs<'_, S, A>,
        input_event: &InputEvent,
    ) -> CommonResult<DialogEngineApplyResponse>
    where
        S: HasDialogBuffers + Default + Clone + PartialEq + Debug + Sync + Send,
        A: Debug + Default + Clone + Sync + Send,
    {
        let DialogEngineArgs {
            self_id,
            component_registry,
            shared_store,
            shared_global_data,
            state,
            dialog_buffer,
            dialog_engine,
            ..
        } = args;

        // Was a dialog choice made?
        if let Some(choice) = internal_impl::try_handle_dialog_choice(
            input_event,
            dialog_buffer,
            dialog_engine,
        ) {
            dialog_engine.reset();
            return Ok(DialogEngineApplyResponse::DialogChoice(choice));
        }

        // Was up / down pressed to select autocomplete results & vert scroll the results panel?
        if let EventPropagation::ConsumedRender =
            internal_impl::try_handle_up_down(input_event, dialog_buffer, dialog_engine)
        {
            return Ok(DialogEngineApplyResponse::SelectScrollResultsPanel);
        }

        // Otherwise, pass the event to the editor engine.
        let editor_engine_args = EditorEngineArgs {
            component_registry,
            shared_global_data,
            self_id,
            editor_buffer: &dialog_buffer.editor_buffer,
            editor_engine: &mut dialog_engine.editor_engine,
            shared_store,
            state,
        };

        // If the editor engine applied the event, return the new editor buffer.
        if let EditorEngineApplyEventResult::Applied(new_editor_buffer) =
            EditorEngineApi::apply_event(editor_engine_args, input_event).await?
        {
            return Ok(DialogEngineApplyResponse::UpdateEditorBuffer(
                new_editor_buffer,
            ));
        }

        // Otherwise, return noop.
        Ok(DialogEngineApplyResponse::Noop)
    }
}

#[repr(u16)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DisplayConstants {
    DialogComponentBorderWidthPercent = 90,
    /// border-top, title, input, border-bottom.
    SimpleModalRowCount = 4,
    EmptyLine = 1,
    DefaultResultsPanelRowCount = 5,
}

mod internal_impl {
    use super::*;

    /// Return the [FlexBox] for the dialog to be rendered in.
    ///
    /// - In non-modal contexts (which this is not), this is determined by the layout engine.
    /// - In the modal case (which this is), things are different because the dialog escapes the
    ///   boundaries of the layout engine and really just paints itself on top of everything. It can
    ///   reach any corner of the screen.
    ///   - In autocomplete mode it sizes itself differently than in normal mode.
    /// - However, it is still constrained by the bounds of the [Surface] itself and does not take
    ///   into account the full window size (in case these are different). This only applies if a
    ///   [Surface] is passed in as an argument.
    ///
    /// ```text
    /// EditorEngineFlexBox {
    ///   id: ..,
    ///   style_adjusted_origin_pos: ..,
    ///   style_adjusted_bounds_size: ..,
    ///   maybe_computed_style: None,
    /// }
    /// ```
    pub fn make_flex_box_for_dialog(
        dialog_id: &FlexBoxId,
        dialog_options: &DialogEngineConfigOptions,
        window_size: &Size,
        maybe_surface_bounds: Option<SurfaceBounds>,
    ) -> CommonResult<PartialFlexBox> {
        let surface_size = if let Some(surface_bounds) = maybe_surface_bounds {
            surface_bounds.box_size
        } else {
            *window_size
        };

        let surface_origin_pos = if let Some(surface_bounds) = maybe_surface_bounds {
            surface_bounds.origin_pos
        } else {
            position!(col_index: 0, row_index: 0)
        };

        // Check to ensure that the dialog box has enough space to be displayed.
        if window_size.col_count < ch!(MinSize::Col as u8)
            || window_size.row_count < ch!(MinSize::Row as u8)
        {
            return CommonError::new(
                CommonErrorType::DisplaySizeTooSmall,
                &format!(
                    "Window size is too small. Min size is {} cols x {} rows",
                    MinSize::Col as u8,
                    MinSize::Row as u8
                ),
            );
        }

        let (origin_pos, bounds_size) = match dialog_options.mode {
            DialogEngineMode::ModalSimple => {
                let simple_dialog_size = {
                    // Calc dialog bounds size based on window size.
                    let col_count = {
                        let percent = percent!(
                            DisplayConstants::DialogComponentBorderWidthPercent as u16
                        )?;
                        percent.calc_percentage(surface_size.col_count)
                    };
                    let row_count = ch!(DisplayConstants::SimpleModalRowCount as u16);
                    let size = size! { col_count: col_count, row_count: row_count };
                    assert!(size.row_count < ch!(MinSize::Row as u8));
                    size
                };

                let origin_pos = {
                    // Calc origin position based on window size & dialog size.
                    let origin_col =
                        surface_size.col_count / 2 - simple_dialog_size.col_count / 2;
                    let origin_row =
                        surface_size.row_count / 2 - simple_dialog_size.row_count / 2;
                    let mut it = position!(col_index: origin_col, row_index: origin_row);
                    it += surface_origin_pos;
                    it
                };

                (origin_pos, simple_dialog_size)
            }
            DialogEngineMode::ModalAutocomplete => {
                let autocomplete_dialog_size = {
                    // Calc dialog bounds size based on window size.
                    let row_count = ch!(DisplayConstants::SimpleModalRowCount as u16)
                        + ch!(DisplayConstants::EmptyLine as u16)
                        + dialog_options.result_panel_display_row_count;
                    let col_count = {
                        let percent = percent!(
                            DisplayConstants::DialogComponentBorderWidthPercent as u16
                        )?;
                        percent.calc_percentage(surface_size.col_count)
                    };
                    let size = size!(col_count: col_count, row_count: row_count);
                    assert!(size.row_count < ch!(MinSize::Row as u8));
                    size
                };

                let origin_pos = {
                    // Calc origin position based on window size & dialog size.
                    let origin_col = surface_size.col_count / 2
                        - autocomplete_dialog_size.col_count / 2;
                    let origin_row = surface_size.row_count / 2
                        - autocomplete_dialog_size.row_count / 2;
                    let mut it = position!(col_index: origin_col, row_index: origin_row);
                    it += surface_origin_pos;
                    it
                };

                (origin_pos, autocomplete_dialog_size)
            }
        };

        throws_with_return!({
            PartialFlexBox {
                id: *dialog_id,
                style_adjusted_origin_pos: origin_pos,
                style_adjusted_bounds_size: bounds_size,
                maybe_computed_style: None,
            }
        })
    }

    pub async fn render_editor<S, A>(
        origin_pos: &Position,
        bounds_size: &Size,
        args: DialogEngineArgs<'_, S, A>,
    ) -> CommonResult<RenderPipeline>
    where
        S: Debug + Default + Clone + PartialEq + Sync + Send,
        A: Debug + Default + Clone + Sync + Send,
    {
        let maybe_style = args.dialog_engine.dialog_options.maybe_style_editor;

        let flex_box: FlexBox = PartialFlexBox {
            id: args.self_id,
            style_adjusted_origin_pos: position! {col_index: origin_pos.col_index + 1, row_index: origin_pos.row_index + 2},
            style_adjusted_bounds_size: size! {col_count: bounds_size.col_count - 2, row_count: 1},
            maybe_computed_style: maybe_style,
        }
        .into();

        let editor_engine_args = EditorEngineArgs {
            component_registry: args.component_registry,
            shared_global_data: args.shared_global_data,
            self_id: args.self_id,
            editor_buffer: &args.dialog_buffer.editor_buffer,
            editor_engine: &mut args.dialog_engine.editor_engine,
            shared_store: args.shared_store,
            state: args.state,
        };

        let mut pipeline =
            EditorEngineApi::render_engine(editor_engine_args, &flex_box).await?;
        pipeline.hoist(ZOrder::Normal, ZOrder::Glass);

        // Paint hint.
        if args.dialog_buffer.editor_buffer.is_empty()
            || args.dialog_buffer.editor_buffer.get_as_string() == ""
        {
            let mut ops = render_ops!();
            let msg = "Press <Esc> to close, or <Enter> to accept".to_string();

            ops.push(RenderOp::ResetColor);
            ops.push(RenderOp::MoveCursorPositionAbs(
                flex_box.style_adjusted_origin_pos,
            ));

            ops.push(RenderOp::PaintTextWithAttributes(
                msg,
                Some(if let Some(style) = maybe_style {
                    Style { dim: true, ..style }
                } else {
                    Style {
                        dim: true,
                        ..Default::default()
                    }
                }),
            ));

            pipeline.push(ZOrder::Glass, ops);
        };

        Ok(pipeline)
    }

    pub fn render_results_panel<S>(
        origin_pos: &Position,
        bounds_size: &Size,
        dialog_engine: &DialogEngine,
        self_id: FlexBoxId,
        state: &S,
    ) -> CommonResult<RenderOps>
    where
        S: HasDialogBuffers + Default + Clone + PartialEq + Debug + Sync + Send,
    {
        let mut it = render_ops!();

        if let Some(dialog_buffer) = state.get_dialog_buffer(self_id) {
            if let Some(results) = dialog_buffer.maybe_results.as_ref() {
                if !results.is_empty() {
                    paint_results(
                        &mut it,
                        origin_pos,
                        bounds_size,
                        results,
                        dialog_engine,
                    );
                };
            }
        };

        return Ok(it);

        pub fn paint_results(
            ops: &mut RenderOps,
            origin_pos: &Position,
            bounds_size: &Size,
            results: &[String],
            dialog_engine: &DialogEngine,
        ) {
            let col_start_index = ch!(1);
            let row_start_index =
                ch!(DisplayConstants::SimpleModalRowCount as u16) - ch!(1);

            let mut rel_insertion_pos =
                position!(col_index: col_start_index, row_index: row_start_index);

            let scroll_offset_row_index = dialog_engine.scroll_offset_row_index;
            let selected_row_index = dialog_engine.selected_row_index;

            // Print results panel.
            for (row_index, item) in results.iter().enumerate() {
                let row_index = ch!(row_index);

                // Skip rows that are above the scroll offset.
                if row_index < scroll_offset_row_index {
                    continue;
                }

                rel_insertion_pos.add_row(1);

                let text = UnicodeString::from(item.as_str());
                let max_display_col_count = bounds_size.col_count - 2;
                let clipped_text = if text.display_width > max_display_col_count {
                    let snip_len = ch!(2); /* `..` */
                    let postfix_len = ch!(5); /* last 5 characters */

                    let lhs_start_index = ch!(0);
                    let lhs_end_index = max_display_col_count - postfix_len - snip_len;
                    let lhs = text.clip_to_width(lhs_start_index, lhs_end_index);

                    let rhs_start_index = text.display_width - postfix_len;
                    let rhs_end_index = text.display_width;
                    let rhs = text.clip_to_width(rhs_start_index, rhs_end_index);

                    format!("{lhs}..{rhs}")
                } else {
                    text.string
                };

                let max_display_row_count =
                    /* Viewport height: */ dialog_engine.dialog_options.result_panel_display_row_count +
                    /* Scroll offset: */ scroll_offset_row_index;
                if row_index >= max_display_row_count {
                    break;
                }

                ops.push(RenderOp::ResetColor);
                ops.push(RenderOp::MoveCursorPositionRelTo(
                    *origin_pos,
                    rel_insertion_pos,
                ));

                // Set style to underline if selected row & paint.
                match selected_row_index.eq(&row_index) {
                    // This is the selected row.
                    true => {
                        let my_selected_style = match dialog_engine
                            .dialog_options
                            .maybe_style_results_panel
                        {
                            // Update existing style.
                            Some(style) => Style {
                                underline: true,
                                ..style
                            },
                            // No existing style, so create a new style w/ only underline.
                            _ => Style {
                                underline: true,
                                ..Default::default()
                            },
                        }
                        .into();
                        // Paint the text for the row.
                        ops.push(RenderOp::ApplyColors(my_selected_style));
                        ops.push(RenderOp::PaintTextWithAttributes(
                            clipped_text,
                            my_selected_style,
                        ));
                    }
                    // Regular row, not selected.
                    false => {
                        // Paint the text for the row.
                        ops.push(RenderOp::ApplyColors(
                            dialog_engine.dialog_options.maybe_style_results_panel,
                        ));
                        ops.push(RenderOp::PaintTextWithAttributes(
                            clipped_text,
                            dialog_engine.dialog_options.maybe_style_results_panel,
                        ));
                    }
                }
            }
        }
    }

    pub fn render_title(
        origin_pos: &Position,
        bounds_size: &Size,
        title: &str,
        dialog_engine: &mut DialogEngine,
    ) -> RenderOps {
        let mut ops = render_ops!();

        let row_pos = position!(col_index: origin_pos.col_index + 1, row_index: origin_pos.row_index + 1);

        let title_us = UnicodeString::from(title);
        let text_content = title_us.truncate_to_fit_size(size! {
          col_count: bounds_size.col_count - 2, row_count: bounds_size.row_count
        });

        ops.push(RenderOp::ResetColor);
        ops.push(RenderOp::MoveCursorPositionAbs(row_pos));
        ops.push(RenderOp::ApplyColors(
            dialog_engine.dialog_options.maybe_style_title,
        ));

        // Apply lolcat override (if enabled) to the fg_color of text_content.
        lolcat_from_style(
            &mut ops,
            &mut dialog_engine.color_wheel,
            &dialog_engine.dialog_options.maybe_style_title,
            text_content,
        );

        ops
    }

    /// Only Colorizes text in-place if [Style]'s `lolcat` field is true. Otherwise leaves `text`
    /// alone.
    fn lolcat_from_style(
        ops: &mut RenderOps,
        color_wheel: &mut ColorWheel,
        maybe_style: &Option<Style>,
        text: &str,
    ) {
        // If lolcat is enabled, then colorize the text.
        if let Some(style) = maybe_style {
            if style.lolcat {
                color_wheel
                    .colorize_into_styled_texts(
                        &UnicodeString::from(text),
                        GradientGenerationPolicy::ReuseExistingGradientAndResetIndex,
                        TextColorizationPolicy::ColorEachCharacter(*maybe_style),
                    )
                    .render_into(ops);
                return;
            }
        }

        // Otherwise, just paint the text as-is.
        ops.push(RenderOp::PaintTextWithAttributes(text.into(), *maybe_style));
    }

    pub fn render_border(
        origin_pos: &Position,
        bounds_size: &Size,
        dialog_engine: &mut DialogEngine,
    ) -> RenderOps {
        let mut ops = render_ops!();
        let inner_spaces = SPACER.repeat(ch!(@to_usize bounds_size.col_count - 2));
        let maybe_style = dialog_engine.dialog_options.maybe_style_border;

        for row_idx in 0..*bounds_size.row_count {
            let row_pos = position!(col_index: origin_pos.col_index, row_index: origin_pos.row_index + row_idx);

            let is_first_line = row_idx == 0;
            let is_last_line = row_idx == (*bounds_size.row_count - 1);

            ops.push(RenderOp::ResetColor);
            ops.push(RenderOp::MoveCursorPositionAbs(row_pos));
            ops.push(RenderOp::ApplyColors(maybe_style));

            match (is_first_line, is_last_line) {
                // First line.
                (true, false) => {
                    let text_content = format!(
                        "{}{}{}",
                        BorderGlyphCharacter::TopLeft.as_ref(),
                        BorderGlyphCharacter::Horizontal
                            .as_ref()
                            .repeat(ch!(@to_usize bounds_size.col_count - 2)),
                        BorderGlyphCharacter::TopRight.as_ref()
                    );

                    // Apply lolcat override (if enabled) to the fg_color of text_content.
                    lolcat_from_style(
                        &mut ops,
                        &mut dialog_engine.color_wheel,
                        &maybe_style,
                        &text_content,
                    );
                }

                // Middle line.
                (false, false) => {
                    let text_content = format!(
                        "{}{}{}",
                        BorderGlyphCharacter::Vertical.as_ref(),
                        inner_spaces,
                        BorderGlyphCharacter::Vertical.as_ref()
                    );
                    // Apply lolcat override (if enabled) to the fg_color of text_content.
                    lolcat_from_style(
                        &mut ops,
                        &mut dialog_engine.color_wheel,
                        &maybe_style,
                        &text_content,
                    );
                }

                // Last line.
                (false, true) => {
                    // Paint bottom border.
                    let text_content = format!(
                        "{}{}{}",
                        BorderGlyphCharacter::BottomLeft.as_ref(),
                        BorderGlyphCharacter::Horizontal
                            .as_ref()
                            .repeat(ch!(@to_usize bounds_size.col_count - 2)),
                        BorderGlyphCharacter::BottomRight.as_ref(),
                    );
                    // Apply lolcat override (if enabled) to the fg_color of text_content.
                    lolcat_from_style(
                        &mut ops,
                        &mut dialog_engine.color_wheel,
                        &maybe_style,
                        &text_content,
                    );
                }
                _ => {}
            };

            // Paint separator for results panel if in autocomplete mode.
            match dialog_engine.dialog_options.mode {
                DialogEngineMode::ModalSimple => {}
                DialogEngineMode::ModalAutocomplete => {
                    let inner_line = BorderGlyphCharacter::Horizontal
                        .as_ref()
                        .repeat(ch!(@to_usize bounds_size.col_count - 2))
                        .to_string();

                    let text_content = format!(
                        "{}{}{}",
                        BorderGlyphCharacter::LineUpDownRight.as_ref(),
                        inner_line,
                        BorderGlyphCharacter::LineUpDownLeft.as_ref()
                    );

                    let col_start_index = ch!(0);
                    let row_start_index =
                        ch!(DisplayConstants::SimpleModalRowCount as u16) - ch!(1);
                    let rel_insertion_pos =
                        position!(col_index: col_start_index, row_index: row_start_index);

                    ops.push(RenderOp::ResetColor);
                    ops.push(RenderOp::MoveCursorPositionRelTo(
                        *origin_pos,
                        rel_insertion_pos,
                    ));

                    // Apply lolcat override (if enabled) to the fg_color of text_content.
                    lolcat_from_style(
                        &mut ops,
                        &mut dialog_engine.color_wheel,
                        &maybe_style,
                        &text_content,
                    );
                }
            }
        }

        ops
    }

    pub fn try_handle_dialog_choice(
        input_event: &InputEvent,
        dialog_buffer: &DialogBuffer,
        dialog_engine: &DialogEngine,
    ) -> Option<DialogChoice> {
        match DialogEvent::from(input_event) {
            // Handle Enter.
            DialogEvent::EnterPressed => match dialog_engine.dialog_options.mode {
                DialogEngineMode::ModalSimple => {
                    let text = dialog_buffer.editor_buffer.get_as_string();
                    return Some(DialogChoice::Yes(text));
                }

                DialogEngineMode::ModalAutocomplete => {
                    let selected_index = ch!(@to_usize dialog_engine.selected_row_index);
                    if let Some(results) = &dialog_buffer.maybe_results {
                        if let Some(selected_result) = results.get(selected_index) {
                            return Some(DialogChoice::Yes(selected_result.clone()));
                        }
                    }
                    return Some(DialogChoice::No);
                }
            },

            // Handle Esc.
            DialogEvent::EscPressed => {
                return Some(DialogChoice::No);
            }
            _ => {}
        }
        None
    }

    pub fn try_handle_up_down(
        input_event: &InputEvent,
        dialog_buffer: &DialogBuffer,
        dialog_engine: &mut DialogEngine,
    ) -> EventPropagation {
        // Handle up arrow?
        if input_event.matches(&[InputEvent::Keyboard(KeyPress::Plain {
            key: Key::SpecialKey(SpecialKey::Up),
        })]) {
            if dialog_engine.selected_row_index > ch!(0) {
                dialog_engine.selected_row_index -= 1;
            }

            if dialog_engine.selected_row_index < dialog_engine.scroll_offset_row_index {
                dialog_engine.scroll_offset_row_index -= 1;
            }

            return EventPropagation::ConsumedRender;
        }

        // Handle down arrow?
        if input_event.matches(&[InputEvent::Keyboard(KeyPress::Plain {
            key: Key::SpecialKey(SpecialKey::Down),
        })]) {
            let max_abs_row_index = dialog_buffer.get_results_count() - ch!(1);

            let results_panel_viewport_height_row_count =
                dialog_engine.dialog_options.result_panel_display_row_count;

            if dialog_engine.selected_row_index < max_abs_row_index {
                dialog_engine.selected_row_index += 1;
            }

            if dialog_engine.selected_row_index
                >= dialog_engine.scroll_offset_row_index
                    + results_panel_viewport_height_row_count
            {
                dialog_engine.scroll_offset_row_index += 1;
            }

            return EventPropagation::ConsumedRender;
        }

        EventPropagation::Propagate
    }
}

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

    use super::*;
    use crate::test_dialog::mock_real_objects_for_dialog;

    #[tokio::test]
    async fn render_engine() {
        let self_id: FlexBoxId = FlexBoxId::from(0);
        let window_size = &size!( col_count: 70, row_count: 15 );
        let dialog_buffer = &mut DialogBuffer::new_empty();
        let dialog_engine = &mut mock_real_objects_for_dialog::make_dialog_engine();
        let shared_store = &mock_real_objects_for_dialog::create_store();
        let shared_global_data =
            &test_editor::mock_real_objects_for_editor::make_shared_global_data(
                (*window_size).into(),
            );
        let component_registry =
            &mut test_editor::mock_real_objects_for_editor::make_component_registry();
        let state = &shared_store.read().await.state.clone();
        let args = DialogEngineArgs {
            shared_global_data,
            shared_store,
            state,
            component_registry,
            window_size,
            self_id,
            dialog_buffer,
            dialog_engine,
        };

        let pipeline = dbg!(DialogEngineApi::render_engine(args).await.unwrap());
        assert_eq2!(pipeline.len(), 1);
        let render_ops = pipeline.get(&ZOrder::Glass).unwrap();
        assert!(!render_ops.is_empty());
    }
}

#[cfg(test)]
mod test_dialog_api_make_flex_box_for_dialog {
    use std::error::Error;

    use r3bl_rs_utils_core::*;

    use crate::{dialog_engine_api::internal_impl, *};

    /// More info on `is` and downcasting:
    /// - https://stackoverflow.com/questions/71409337/rust-how-to-match-against-any
    /// - https://ysantos.com/blog/downcast-rust
    #[test]
    fn make_flex_box_for_dialog_simple_display_size_too_small() {
        let surface = Surface::default();
        let window_size = Size::default();
        let dialog_id: FlexBoxId = FlexBoxId::from(0);

        // The window size is too small and will result in this error.
        // Err(
        //   CommonError {
        //       err_type: DisplaySizeTooSmall,
        //       err_msg: Some(
        //           "Window size is too small. Min size is 65 cols x 10 rows",
        //       ),
        //   },
        let result_flex_box = dbg!(internal_impl::make_flex_box_for_dialog(
            &dialog_id,
            &DialogEngineConfigOptions {
                mode: DialogEngineMode::ModalSimple,
                ..Default::default()
            },
            &window_size,
            Some(SurfaceBounds::from(&surface)),
        ));

        // Assert that a general `CommonError` is returned.
        let my_err: Box<dyn Error + Send + Sync> = result_flex_box.err().unwrap();
        assert_eq2!(my_err.is::<CommonError>(), true);

        // Assert that this specific error is returned.
        let result = matches!(
            my_err.downcast_ref::<CommonError>(),
            Some(CommonError {
                err_type: CommonErrorType::DisplaySizeTooSmall,
                err_msg: _,
            })
        );

        assert_eq2!(result, true);
    }

    /// More info on `is` and downcasting:
    /// - https://stackoverflow.com/questions/71409337/rust-how-to-match-against-any
    /// - https://ysantos.com/blog/downcast-rust
    #[test]
    fn make_flex_box_for_dialog_autocomplete_display_size_too_small() {
        let surface = Surface::default();
        let window_size = Size::default();
        let dialog_id: FlexBoxId = FlexBoxId::from(0);

        // The window size is too small and will result in this error.
        // Err(
        //   CommonError {
        //       err_type: DisplaySizeTooSmall,
        //       err_msg: Some(
        //           "Window size is too small. Min size is 65 cols x 10 rows",
        //       ),
        //   },
        let result_flex_box = dbg!(internal_impl::make_flex_box_for_dialog(
            &dialog_id,
            &DialogEngineConfigOptions {
                mode: DialogEngineMode::ModalAutocomplete,
                ..Default::default()
            },
            &window_size,
            Some(SurfaceBounds::from(&surface)),
        ));

        // Assert that a general `CommonError` is returned.
        let my_err: Box<dyn Error + Send + Sync> = result_flex_box.err().unwrap();
        assert_eq2!(my_err.is::<CommonError>(), true);

        // Assert that this specific error is returned.
        let result = matches!(
            my_err.downcast_ref::<CommonError>(),
            Some(CommonError {
                err_type: CommonErrorType::DisplaySizeTooSmall,
                err_msg: _,
            })
        );

        assert_eq2!(result, true);
    }

    #[test]
    fn make_flex_box_for_dialog_simple() {
        // 1. The surface and window_size are not the same width and height.
        // 2. The surface is also not starting from the top left corner of the window.
        let surface = Surface {
            origin_pos: position! { col_index: 2, row_index: 2 },
            box_size: size!( col_count: 65, row_count: 10 ),
            ..Default::default()
        };
        let window_size = size!( col_count: 70, row_count: 15 );
        let self_id: FlexBoxId = FlexBoxId::from(0);

        // The dialog box should be centered inside the surface.
        let result_flex_box = dbg!(internal_impl::make_flex_box_for_dialog(
            &self_id,
            &DialogEngineConfigOptions {
                mode: DialogEngineMode::ModalSimple,
                ..Default::default()
            },
            &window_size,
            Some(SurfaceBounds::from(&surface)),
        ));

        assert_eq2!(result_flex_box.is_ok(), true);

        let flex_box = result_flex_box.unwrap();
        assert_eq2!(flex_box.id, self_id);
        assert_eq2!(
            flex_box.style_adjusted_bounds_size,
            size!( col_count: 58, row_count: 4 )
        );
        assert_eq2!(
            flex_box.style_adjusted_origin_pos,
            position!( col_index: 5, row_index: 5 )
        );
    }

    #[test]

    fn make_flex_box_for_dialog_autocomplete() {
        // 1. The surface and window_size are not the same width and height.
        // 2. The surface is also not starting from the top left corner of the window.
        let surface = Surface {
            origin_pos: position! { col_index: 2, row_index: 2 },
            box_size: size!( col_count: 65, row_count: 10 ),
            ..Default::default()
        };
        let window_size = size!( col_count: 70, row_count: 15 );
        let self_id: FlexBoxId = FlexBoxId::from(0);

        // The dialog box should be centered inside the surface.
        let result_flex_box = dbg!(internal_impl::make_flex_box_for_dialog(
            &self_id,
            &DialogEngineConfigOptions {
                mode: DialogEngineMode::ModalAutocomplete,
                ..Default::default()
            },
            &window_size,
            Some(SurfaceBounds::from(&surface)),
        ));

        assert_eq2!(result_flex_box.is_ok(), true);

        let flex_box = result_flex_box.unwrap();
        assert_eq2!(flex_box.id, self_id);
        assert_eq2!(
            flex_box.style_adjusted_bounds_size,
            size!( col_count: 58, row_count: 10 )
        );
        assert_eq2!(
            flex_box.style_adjusted_origin_pos,
            position!( col_index: 5, row_index: 2 )
        );
    }
}

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

    use super::*;
    use crate::test_dialog::mock_real_objects_for_dialog;

    #[tokio::test]
    async fn apply_event_esc() {
        let self_id: FlexBoxId = FlexBoxId::from(0);
        let window_size = &size!( col_count: 70, row_count: 15 );
        let dialog_buffer = &mut DialogBuffer::new_empty();
        let dialog_engine = &mut mock_real_objects_for_dialog::make_dialog_engine();
        let shared_store = &mock_real_objects_for_dialog::create_store();
        let shared_global_data =
            &test_editor::mock_real_objects_for_editor::make_shared_global_data(
                (*window_size).into(),
            );
        let component_registry =
            &mut test_editor::mock_real_objects_for_editor::make_component_registry();
        let state = &shared_store.read().await.state.clone();
        let args = DialogEngineArgs {
            shared_global_data,
            shared_store,
            state,
            component_registry,
            window_size,
            self_id,
            dialog_buffer,
            dialog_engine,
        };

        let input_event = InputEvent::Keyboard(keypress!(@special SpecialKey::Esc));
        let response = dbg!(DialogEngineApi::apply_event(args, &input_event)
            .await
            .unwrap());
        assert!(matches!(
            response,
            DialogEngineApplyResponse::DialogChoice(DialogChoice::No)
        ));
    }

    #[tokio::test]
    async fn apply_event_enter() {
        let self_id: FlexBoxId = FlexBoxId::from(0);
        let window_size = &size!( col_count: 70, row_count: 15 );
        let dialog_buffer = &mut DialogBuffer::new_empty();
        let dialog_engine = &mut mock_real_objects_for_dialog::make_dialog_engine();
        let shared_store = &mock_real_objects_for_dialog::create_store();
        let shared_global_data =
            &test_editor::mock_real_objects_for_editor::make_shared_global_data(
                (*window_size).into(),
            );
        let component_registry =
            &mut test_editor::mock_real_objects_for_editor::make_component_registry();
        let state = &shared_store.read().await.state.clone();
        let args = DialogEngineArgs {
            shared_global_data,
            shared_store,
            state,
            component_registry,
            window_size,
            self_id,
            dialog_buffer,
            dialog_engine,
        };

        let input_event = InputEvent::Keyboard(keypress!(@special SpecialKey::Enter));
        let response = dbg!(DialogEngineApi::apply_event(args, &input_event)
            .await
            .unwrap());
        if let DialogEngineApplyResponse::DialogChoice(DialogChoice::Yes(value)) =
            &response
        {
            assert_eq2!(value, "");
        }
        assert!(matches!(
            response,
            DialogEngineApplyResponse::DialogChoice(DialogChoice::Yes(_))
        ));
    }

    #[tokio::test]
    async fn apply_event_other_key() {
        let self_id: FlexBoxId = FlexBoxId::from(0);
        let window_size = &size!( col_count: 70, row_count: 15 );
        let dialog_buffer = &mut DialogBuffer::new_empty();
        let dialog_engine = &mut mock_real_objects_for_dialog::make_dialog_engine();
        let shared_store = &mock_real_objects_for_dialog::create_store();
        let shared_global_data =
            &test_editor::mock_real_objects_for_editor::make_shared_global_data(
                (*window_size).into(),
            );
        let component_registry =
            &mut test_editor::mock_real_objects_for_editor::make_component_registry();
        let state = &shared_store.read().await.state.clone();
        let args = DialogEngineArgs {
            shared_global_data,
            shared_store,
            state,
            component_registry,
            window_size,
            self_id,
            dialog_buffer,
            dialog_engine,
        };

        let input_event = InputEvent::Keyboard(keypress!(@char 'a'));
        let response = dbg!(DialogEngineApi::apply_event(args, &input_event)
            .await
            .unwrap());
        if let DialogEngineApplyResponse::UpdateEditorBuffer(editor_buffer) = &response {
            assert_eq2!(editor_buffer.get_as_string(), "a");
        }
    }
}