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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
mod cell;
mod rect;
mod size;
mod state;
use core::fmt::Debug;
use self::cell::CellSize;
use self::rect::RectangleExt;
use self::size::SizeExt;
use self::state::State;
use embedded_graphics::draw_target::{DrawTarget, DrawTargetExt};
use embedded_graphics::geometry::{AnchorX, Point};
use embedded_graphics::iterator::raw::RawDataSlice;
use embedded_graphics::pixelcolor::raw::BigEndian;
use embedded_graphics::pixelcolor::{PixelColor, Rgb888};
use embedded_graphics::primitives::Rectangle;
use embedded_graphics::text::renderer::TextRenderer;
use embedded_graphics::text::{Baseline, DecorationColor};
use embedded_graphics::transform::Transform;
use mplusfonts::BitmapFont;
use mplusfonts::color::{Invert, Screen, WeightedAvg};
use mplusfonts::style::BitmapFontStyle;
use ratatui_core::backend::{Backend, ClearType, WindowSize};
use ratatui_core::buffer::Cell;
use ratatui_core::layout::{Position, Size};
use ratatui_core::style::Modifier;
use crate::color::{MapWith, Palette, Palettes};
use crate::cursor::{Colors, Extent, Symbol};
use crate::error::{Error, MeasureError, SetCursorError};
pub use crate::wrapper::Wrapper;
#[cfg(feature = "alloc")]
pub use crate::wrapper::blink::{BlinkWrapper, ConfigureBlinkWrapper};
#[cfg(feature = "alloc")]
pub use crate::wrapper::cursor::{ConfigureCursorWrapper, CursorWrapper};
pub use crate::wrapper::flush::FlushWrapper;
/// Backend for Ratatui that renders to a display with the [`embedded-graphics`](embedded_graphics)
/// crate, using fixed-width bitmap fonts from the [`mplusfonts`] crate.
#[non_exhaustive]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DumoBackend<'a, 'b, 'c, 'd, D, C>
where
C: PixelColor + From<C::Raw>,
D: DrawTarget,
D::Color: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
D::Error: Debug,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
BitmapFontStyle<'a, 'b, D::Color, C, 1>: TextRenderer<Color = D::Color>,
{
/// The draw target.
pub target: &'d mut D,
/// The bitmap font to use in general.
pub font: &'b BitmapFont<'a, C, 1>,
/// The bitmap font for when text should be bold. Defaults to the regular font.
pub font_bold: Option<&'b BitmapFont<'a, C, 1>>,
/// The foreground color to use in case no specific color is set. Defaults to white or enabled.
pub fg_reset: Option<D::Color>,
/// The background color to use in case no specific color is set. Defaults to black or disabled.
pub bg_reset: Option<D::Color>,
/// The color palette for looking up ANSI colors by index, including the 16 named ones.
pub palette: Palette<'c, D::Color>,
/// The sides of cells that should be aligned in case the set of glyph images that represent a
/// given character or character cluster span a different number of cells than expected in the
/// Unicode standard and Ratatui. For example, `â–²` and `â–¼` have graphics that require cropping,
/// and the _x_-axis anchor point determines which sections to draw.
pub anchor_x: AnchorX,
/// The values to carry across calls to different methods for a given frame, and across frames.
state: State,
}
/// Backend with a reference to a draw target.
///
/// A backend or backend wrapper that implements this trait is able to call functions that expect a
/// reference with exclusive access to a draw target as an argument, and it offers extended drawing
/// capabilities that are required by wrappers in order to perform their tasks.
pub trait DrawTargetBackend<D: DrawTarget>: Backend {
/// Invokes the specified function item, which gets to access the draw target in the scope of a
/// function call.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{DrawTargetBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.call(|display| {
/// // ...
///
/// Ok(())
/// });
/// ```
fn call(&mut self, f: impl FnMut(&mut D) -> Result<(), D::Error>) -> Result<(), D::Error>;
/// Draws the specified content as if [`HIDDEN`](ratatui_core::style::Modifier::HIDDEN) was set
/// on all of the items, which is equivalent to using the background colors — or the foreground
/// colors if [`REVERSED`](ratatui_core::style::Modifier::REVERSED) is set — to clear the cells
/// that each of the characters or character clusters spans.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{DrawTargetBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
/// use ratatui::buffer::Cell;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.draw_hidden(core::iter::once((0, 0, &Cell::new("A"))));
/// ```
fn draw_hidden<'z, I>(&mut self, content: I) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'z Cell)>;
/// Draws the specified content using another set of colors and cropped to the specified extent
/// with the [`Symbol::UnderCursor`] parameter; otherwise, the characters or character clusters
/// from the [`Symbol::Custom`] parameter are drawn instead.
///
/// If the content is reversed, then the set of colors for the cursor are also reversed, and if
/// the content has text decorations, then those are also applied if [`Symbol::UnderCursor`] is
/// drawn, as is whether text should be bold or hidden, including having _blinked_.
///
/// [`Symbol::Custom`] only respects the content's modifier to have the set of colors reversed.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::cursor::{Colors, Extent, Symbol};
/// use dumo::fonts::*;
/// use dumo::{DrawTargetBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
/// use ratatui::buffer::Cell;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.draw_cursor(
/// core::iter::once((0, 0, &Cell::new("A"))),
/// Colors::ReversedReset,
/// Extent::FullBlock,
/// Symbol::UnderCursor,
/// );
/// ```
fn draw_cursor<'z, I>(
&mut self,
content: I,
colors: Colors,
extent: Extent,
symbol: Symbol,
) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'z Cell)>;
/// Advances the blinking animation associated with the backend or backend wrapper if there are
/// such features, calling [`advance_blink_by`](DrawTargetBackend::advance_blink_by) afterwards
/// so that inner layers can do the same. The `ticks` are added to their internal frame counts.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "alloc", feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::blink::{Blink, ControlBlinking};
/// use dumo::fonts::*;
/// use dumo::{DrawTargetBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS)
/// .with_blink(Blink::with_period(16), Blink::with_period(8));
///
/// backend.stop_blinking();
///
/// for _ in 0..100 {
/// backend.advance_blink_by(1);
/// }
/// ```
fn advance_blink_by(&mut self, ticks: usize) -> Result<(), Self::Error>;
/// Takes the unit from the backend or backend wrapper, indicating, when [`Some`], that an area
/// of the draw target with the cursor has been redrawn without the cursor being drawn over it.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "alloc", feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::blink::Blink;
/// use dumo::cursor::Cursor;
/// use dumo::error::Error;
/// use dumo::fonts::*;
/// use dumo::{DrawTargetBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS)
/// .with_blink(Blink::with_period(16), Blink::with_period(8))
/// .with_cursor(Cursor::default());
///
/// let cursor_is_dirty = backend.take_dirty_cursor()?.is_some();
///
/// Ok::<(), Error<_>>(())
/// ```
fn take_dirty_cursor(&mut self) -> Result<Option<()>, Self::Error>;
}
/// Backend configuration retrieval and modification.
///
/// A backend or backend wrapper that implements this trait allows its fields that are configurable
/// to have their values read or have new values assigned.
pub trait ConfigureBackend<'a, 'b, 'c, T, C>
where
C: PixelColor + From<C::Raw>,
T: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
{
/// Returns the bitmap font to use in general.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// let bitmap_font = backend.font();
/// ```
fn font(&self) -> &'b BitmapFont<'a, C, 1>;
/// Sets the bitmap font to use in general.
///
/// This bitmap font is used to render text that either has no modifiers set, is set to italic,
/// and also text that is set to bold, when the bitmap font for when text should be bold is not
/// set to a value.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-12x36", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.set_font(&FONT_12X36_4_BITS);
/// ```
fn set_font(&mut self, font: &'b BitmapFont<'a, C, 1>);
/// Returns the optional bitmap font for when text should be bold.
///
/// When not set to a value, the backend renders all texts, including text that should be bold,
/// using the regular font.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(
/// # feature = "font-8x24",
/// # feature = "font-8x24-bold",
/// # feature = "font-4-bits",
/// # )))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_font_bold(Some(&FONT_8X24_BOLD_4_BITS));
///
/// let bitmap_font_bold = backend.font_bold();
/// ```
fn font_bold(&self) -> Option<&'b BitmapFont<'a, C, 1>>;
/// Sets the optional bitmap font for when text should be bold.
///
/// When not set to a value, the backend renders all texts, including text that should be bold,
/// using the regular font.
///
/// This bitmap font and the regular one should have the same cell size; otherwise, the backend
/// will introduce clipping or padding with the background color in character cells, the reason
/// being that the cell size is always calculated using the regular font.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(
/// # feature = "font-8x24",
/// # feature = "font-12x36",
/// # feature = "font-12x36-bold",
/// # feature = "font-4-bits"
/// # )))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_font(&FONT_12X36_4_BITS);
///
/// backend.set_font_bold(Some(&FONT_12X36_BOLD_4_BITS));
/// ```
fn set_font_bold(&mut self, font_bold: Option<&'b BitmapFont<'a, C, 1>>);
/// Returns the optional foreground color to use in case no specific color is set.
///
/// When not set to a value, the backend uses the inverse of the default value for type `T`.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_fg_reset(Some(Rgb565::new(30, 60, 30)));
///
/// let text_color = backend.fg_reset();
/// ```
fn fg_reset(&self) -> Option<T>;
/// Sets the optional foreground color to use in case no specific color is set.
///
/// When not set to a value, the backend uses the inverse of the default value for type `T`.
///
/// This color is used as the default foreground color, when the text color is reset.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.set_fg_reset(Some(Rgb565::new(30, 60, 30)));
/// ```
fn set_fg_reset(&mut self, fg_reset: Option<T>);
/// Returns the optional background color to use in case no specific color is set.
///
/// When not set to a value, the backend uses the default value for type `T`.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_bg_reset(Some(Rgb565::new(5, 10, 5)));
///
/// let background_color = backend.bg_reset();
/// ```
fn bg_reset(&self) -> Option<T>;
/// Sets the optional background color to use in case no specific color is set.
///
/// When not set to a value, the backend uses the default value for type `T`.
///
/// This color is used as the default background color, when the text background color is reset.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.set_bg_reset(Some(Rgb565::new(5, 10, 5)));
/// ```
fn set_bg_reset(&mut self, bg_reset: Option<T>);
/// Returns the color palette for looking up ANSI colors by index, including the 16 named ones.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::color::Palettes;
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_palette(Rgb565::WEB_256);
///
/// let web_color_palette = backend.palette();
/// ```
fn palette(&self) -> Palette<'c, T>;
/// Sets the color palette for looking up ANSI colors by index, including the 16 named ones.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::color::Palettes;
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.set_palette(Rgb565::WEB_256);
/// ```
fn set_palette(&mut self, palette: Palette<'c, T>);
/// Returns the _x_-axis anchor point for which sides of cells to align in case of disagreement.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::geometry::AnchorX;
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// backend.set_anchor_x(AnchorX::Center);
///
/// let center_anchor_x = backend.anchor_x();
/// ```
fn anchor_x(&self) -> AnchorX;
/// Sets the _x_-axis anchor point for which sides of cells to align in case of disagreement.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::fonts::*;
/// use dumo::{ConfigureBackend, DumoBackend};
/// # use embedded_graphics::geometry::AnchorX;
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let mut backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
///
/// backend.set_anchor_x(AnchorX::Center);
/// ```
fn set_anchor_x(&mut self, anchor_x: AnchorX);
}
impl<'a, 'b, 'c, 'd, D, C> DumoBackend<'a, 'b, 'c, 'd, D, C>
where
C: PixelColor + From<C::Raw>,
D: DrawTarget,
D::Color: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
D::Error: Debug,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
BitmapFontStyle<'a, 'b, D::Color, C, 1>: TextRenderer<Color = D::Color>,
{
/// Creates a new backend with exclusive access to the specified draw target, configuring it to
/// use the specified bitmap font for text rendering.
///
/// # Examples
///
/// ```
/// # #[cfg(not(all(feature = "font-8x24", feature = "font-4-bits")))]
/// # {
/// # compile_error!("doc-test is missing required features");
/// # }
/// #
/// use dumo::DumoBackend;
/// use dumo::fonts::*;
/// # use embedded_graphics::mock_display::MockDisplay;
/// # use embedded_graphics::pixelcolor::Rgb565;
///
/// # let mut display: MockDisplay<Rgb565> = MockDisplay::new();
/// let backend = DumoBackend::new(&mut display, &FONT_8X24_4_BITS);
/// ```
pub const fn new(target: &'d mut D, font: &'b BitmapFont<'a, C, 1>) -> Self
where
D::Color: Palettes<'c>,
{
Self {
target,
font,
font_bold: None,
fg_reset: None,
bg_reset: None,
palette: D::Color::XTERM_256,
anchor_x: AnchorX::Left,
state: State::new(),
}
}
}
impl<'a, 'b, 'c, D, C> Backend for DumoBackend<'a, 'b, 'c, '_, D, C>
where
C: PixelColor + From<C::Raw>,
D: DrawTarget,
D::Color: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
D::Error: Debug,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
BitmapFontStyle<'a, 'b, D::Color, C, 1>: TextRenderer<Color = D::Color>,
{
type Error = Error<D::Error>;
fn draw<'z, I>(&mut self, content: I) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'z Cell)>,
{
use MeasureError::*;
use embedded_graphics::geometry::Size;
use unicode_width::UnicodeWidthStr;
const ORIGIN: Point = Point::zero();
const BASELINE: Baseline = Baseline::Top;
let cell_size = self.font.cell_size();
for (x, y, cell) in content {
let text_color = cell.fg.map_with(self.palette).or(self.fg_reset);
let text_color = text_color.unwrap_or(D::Color::default().invert());
let background_color = cell.bg.map_with(self.palette).or(self.bg_reset);
let background_color = background_color.unwrap_or_default();
let is_dim = cell.modifier.intersects(Modifier::DIM);
let text_color = if is_dim {
text_color.weighted_avg(
background_color,
background_color,
text_color,
text_color,
background_color,
)
} else {
text_color
};
let is_reversed = cell.modifier.intersects(Modifier::REVERSED);
let [text_color, background_color] = if is_reversed {
[background_color, text_color]
} else {
[text_color, background_color]
};
let is_underlined = cell.modifier.intersects(Modifier::UNDERLINED);
let underline_color = if is_underlined {
cell.underline_color
.map_with(self.palette)
.map(DecorationColor::Custom)
.unwrap_or(DecorationColor::TextColor)
} else {
DecorationColor::None
};
let is_crossed_out = cell.modifier.intersects(Modifier::CROSSED_OUT);
let strikethrough_color = if is_crossed_out {
DecorationColor::TextColor
} else {
DecorationColor::None
};
let mut renderer = BitmapFontStyle::new(self.font, text_color);
renderer.background_color = Some(background_color);
renderer.underline_color = underline_color;
renderer.strikethrough_color = strikethrough_color;
let text = cell.symbol();
let columns_rows = [x, y].map(Into::into).into();
let pixels = cell_size.checked_component_mul(columns_rows);
let [x_offset, y_offset] = pixels.ok_or(InvalidSize)?.into();
let top_left = Point {
x: ORIGIN.x.saturating_add_unsigned(x_offset),
y: ORIGIN.y.saturating_add_unsigned(y_offset),
};
let columns = text.width().try_into().unwrap_or(u32::MAX);
let pixels = cell_size.width.checked_mul(columns);
let explicit_width = pixels.ok_or(InvalidSize)?;
let size = Size::new(explicit_width, renderer.line_height());
let clip_area = Rectangle { top_left, size };
let mut adapter = self.target.clipped(&clip_area);
let is_hidden = cell.modifier.intersects(Modifier::HIDDEN);
if is_hidden {
self.target
.fill_solid(&clip_area, background_color)
.map_err(Error::Draw)?;
} else if text.chars().all(|char| char::is_ascii_whitespace(&char)) {
renderer
.draw_whitespace(explicit_width, top_left, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
} else {
let metrics = renderer.measure_string(text, top_left, BASELINE);
let pixels = metrics.next_position.x.saturating_sub(top_left.x);
let inherent_width = pixels.try_into().unwrap_or_default();
let crop_area = clip_area.resized_width(inherent_width, self.anchor_x);
let mut adapter = adapter.translated(crop_area.top_left);
let is_bold = cell.modifier.intersects(Modifier::BOLD);
if is_bold && let Some(font_bold) = self.font_bold {
renderer.font = font_bold;
let width = explicit_width.saturating_sub(inherent_width);
let next_position = renderer
.draw_string(text, Point::zero(), BASELINE, &mut adapter)
.map_err(Error::Draw)?;
renderer
.draw_whitespace(width, next_position, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
let metrics = renderer.measure_string(text, crop_area.top_left, BASELINE);
let below = clip_area.below(&metrics.bounding_box);
let wide = clip_area.above(&below);
let left = wide.left_of(&metrics.bounding_box);
let right = metrics.next_position.x.saturating_add_unsigned(width);
let right = wide.indent_to(right);
for area in [left, right, below] {
self.target
.fill_solid(&area, background_color)
.map_err(Error::Draw)?;
}
} else {
let width = explicit_width.saturating_sub(inherent_width);
let next_position = renderer
.draw_string(text, Point::zero(), BASELINE, &mut adapter)
.map_err(Error::Draw)?;
renderer
.draw_whitespace(width, next_position, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
self.target
.fill_solid(&clip_area.left_of(&crop_area), background_color)
.map_err(Error::Draw)?;
}
}
}
Ok(())
}
fn hide_cursor(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn show_cursor(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn get_cursor_position(&mut self) -> Result<Position, Self::Error> {
let columns_rows = self.state.cursor_position;
Ok(columns_rows)
}
fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> Result<(), Self::Error> {
use SetCursorError::*;
let position = position.into();
let columns_rows = self.size()?;
let [columns, rows] = [columns_rows.width, columns_rows.height];
self.state.cursor_position = (position.x < columns && position.y < rows)
.then_some(position)
.ok_or(InvalidPosition)?;
Ok(())
}
fn clear(&mut self) -> Result<(), Self::Error> {
let background_color = self.bg_reset.unwrap_or_default();
self.target.clear(background_color).map_err(Error::Clear)?;
self.state.cursor_coverage = None;
Ok(())
}
fn clear_region(&mut self, clear_type: ClearType) -> Result<(), Self::Error> {
use MeasureError::*;
const ORIGIN: Point = Point::zero();
let background_color = self.bg_reset.unwrap_or_default();
let cursor_coverage = if let Some(cursor_coverage) = self.state.cursor_coverage {
cursor_coverage
} else {
let cell_size = self.font.cell_size();
let Position { x, y } = self.state.cursor_position;
let columns_rows = [x, y].map(Into::into).into();
let pixels = cell_size.checked_component_mul(columns_rows);
let [x_offset, y_offset] = pixels.ok_or(InvalidSize)?.into();
let top_left = Point {
x: ORIGIN.x.saturating_add_unsigned(x_offset),
y: ORIGIN.y.saturating_add_unsigned(y_offset),
};
Rectangle {
top_left,
size: cell_size,
}
};
let top = cursor_coverage.top_left.y;
let bottom = top.saturating_add_unsigned(cursor_coverage.size.height);
let all_pixels = self.target.bounding_box();
let current_line = all_pixels.y_reduce(top, bottom);
let region_areas = match clear_type {
ClearType::All => &[all_pixels][..],
ClearType::AfterCursor => {
let below = all_pixels.below(¤t_line);
let right = current_line.right_of(&cursor_coverage);
&[cursor_coverage, right, below]
}
ClearType::BeforeCursor => {
let above = all_pixels.above(¤t_line);
let left = current_line.left_of(&cursor_coverage);
&[cursor_coverage, left, above]
}
ClearType::CurrentLine => &[current_line],
ClearType::UntilNewLine => {
let right = current_line.right_of(&cursor_coverage);
&[cursor_coverage, right]
}
};
for area in region_areas {
self.target
.fill_solid(area, background_color)
.map_err(Error::Clear)?;
}
self.state.cursor_coverage = None;
Ok(())
}
fn size(&self) -> Result<Size, Self::Error> {
use MeasureError::*;
let target_size = self.target.bounding_box().size;
let cell_size = self.font.cell_size();
let columns_rows = target_size.checked_component_div_ceil(cell_size);
let [columns, rows] = columns_rows.ok_or(InvalidSize)?.into();
let [columns, rows] = [columns, rows].map(|count| count.try_into().map_err(TryFromSize));
let columns_rows = Size::new(columns?, rows?);
Ok(columns_rows)
}
fn window_size(&mut self) -> Result<WindowSize, Self::Error> {
use MeasureError::*;
let target_size = self.target.bounding_box().size;
let cell_size = self.font.cell_size();
let columns_rows = target_size.checked_component_div_ceil(cell_size);
let [columns, rows] = columns_rows.ok_or(InvalidSize)?.into();
let [columns, rows] = [columns, rows].map(|count| count.try_into().map_err(TryFromSize));
let width_height = target_size.checked_component_next_multiple_of(cell_size);
let [width, height] = width_height.ok_or(InvalidSize)?.into();
let [width, height] = [width, height].map(|value| value.try_into().map_err(TryFromSize));
let window_size = WindowSize {
columns_rows: Size::new(columns?, rows?),
pixels: Size::new(width?, height?),
};
Ok(window_size)
}
fn flush(&mut self) -> Result<(), Self::Error> {
Ok(())
}
}
impl<'a, 'b, 'c, D, C> DrawTargetBackend<D> for DumoBackend<'a, 'b, 'c, '_, D, C>
where
C: PixelColor + From<C::Raw>,
D: DrawTarget,
D::Color: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
D::Error: Debug,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
BitmapFontStyle<'a, 'b, D::Color, C, 1>: TextRenderer<Color = D::Color>,
{
fn call(&mut self, mut f: impl FnMut(&mut D) -> Result<(), D::Error>) -> Result<(), D::Error> {
f(self.target)
}
fn draw_hidden<'z, I>(&mut self, content: I) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'z Cell)>,
{
use MeasureError::*;
use embedded_graphics::geometry::Size;
use unicode_width::UnicodeWidthStr;
const ORIGIN: Point = Point::zero();
let cell_size = self.font.cell_size();
for (x, y, cell) in content {
let text_color = cell.fg.map_with(self.palette).or(self.fg_reset);
let text_color = text_color.unwrap_or(D::Color::default().invert());
let background_color = cell.bg.map_with(self.palette).or(self.bg_reset);
let background_color = background_color.unwrap_or_default();
let is_dim = cell.modifier.intersects(Modifier::DIM);
let text_color = if is_dim {
text_color.weighted_avg(
background_color,
background_color,
text_color,
text_color,
background_color,
)
} else {
text_color
};
let is_reversed = cell.modifier.intersects(Modifier::REVERSED);
let background_color = if is_reversed {
text_color
} else {
background_color
};
let text = cell.symbol();
let columns_rows = [x, y].map(Into::into).into();
let pixels = cell_size.checked_component_mul(columns_rows);
let [x_offset, y_offset] = pixels.ok_or(InvalidSize)?.into();
let top_left = Point {
x: ORIGIN.x.saturating_add_unsigned(x_offset),
y: ORIGIN.y.saturating_add_unsigned(y_offset),
};
let columns = text.width().try_into().unwrap_or(u32::MAX);
let pixels = cell_size.width.checked_mul(columns);
let explicit_width = pixels.ok_or(InvalidSize)?;
let size = Size::new(explicit_width, self.font.metrics.line_height());
let fill_area = Rectangle { top_left, size };
self.target
.fill_solid(&fill_area, background_color)
.map_err(Error::Draw)?;
}
Ok(())
}
fn draw_cursor<'z, I>(
&mut self,
content: I,
colors: Colors,
extent: Extent,
symbol: Symbol,
) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'z Cell)>,
{
use MeasureError::*;
use embedded_graphics::geometry::Size;
use unicode_width::UnicodeWidthStr;
const ORIGIN: Point = Point::zero();
const BASELINE: Baseline = Baseline::Top;
let cell_size = self.font.cell_size();
for (x, y, cell) in content {
let [text_color, background_color] = match colors {
Colors::ReversedReset => {
let text_color = self.fg_reset.unwrap_or(D::Color::default().invert());
let background_color = self.bg_reset.unwrap_or_default();
[background_color, text_color]
}
Colors::InvertedReset => {
let text_color = self.fg_reset.unwrap_or(D::Color::default().invert());
let text_color = text_color.invert();
let background_color = self.bg_reset.unwrap_or_default();
let background_color = background_color.invert();
[text_color, background_color]
}
Colors::Custom { fg, bg } => {
let text_color = fg.map_with(self.palette).or(self.fg_reset);
let text_color = text_color.unwrap_or(D::Color::default().invert());
let background_color = bg.map_with(self.palette).or(self.bg_reset);
let background_color = background_color.unwrap_or_default();
[text_color, background_color]
}
};
let is_reversed = cell.modifier.intersects(Modifier::REVERSED);
let [text_color, background_color] = if is_reversed {
[background_color, text_color]
} else {
[text_color, background_color]
};
let is_underlined = cell.modifier.intersects(Modifier::UNDERLINED);
let underline_color = if is_underlined && symbol == Symbol::UnderCursor {
cell.underline_color
.map_with(self.palette)
.map(DecorationColor::Custom)
.unwrap_or(DecorationColor::TextColor)
} else {
DecorationColor::None
};
let is_crossed_out = cell.modifier.intersects(Modifier::CROSSED_OUT);
let strikethrough_color = if is_crossed_out && symbol == Symbol::UnderCursor {
DecorationColor::TextColor
} else {
DecorationColor::None
};
let mut renderer = BitmapFontStyle::new(self.font, text_color);
renderer.background_color = Some(background_color);
renderer.underline_color = underline_color;
renderer.strikethrough_color = strikethrough_color;
let text = cell.symbol();
let columns_rows = [x, y].map(Into::into).into();
let pixels = cell_size.checked_component_mul(columns_rows);
let [x_offset, y_offset] = pixels.ok_or(InvalidSize)?.into();
let top_left = Point {
x: ORIGIN.x.saturating_add_unsigned(x_offset),
y: ORIGIN.y.saturating_add_unsigned(y_offset),
};
let columns = text.width().try_into().unwrap_or(u32::MAX);
let pixels = cell_size.width.checked_mul(columns);
let explicit_width = pixels.ok_or(InvalidSize)?;
let size = Size::new(explicit_width, renderer.line_height());
let text_area = Rectangle { top_left, size };
let clip_area = match extent {
Extent::FullBlock => text_area,
Extent::VerticalBar { width } => {
let explicit_width = explicit_width.min(width);
text_area.resized_width(explicit_width, AnchorX::Left)
}
Extent::Underline { height } => {
let top = renderer.font.metrics.y_offset(Baseline::Top);
let top = top.saturating_sub(renderer.font.underline.y_offset());
let top = top.saturating_add(top_left.y);
let bottom = top.saturating_add_unsigned(height);
text_area.y_reduce(top, bottom)
}
Extent::Custom(area) => {
let area = area.translate(top_left);
text_area.intersection(&area)
}
};
let mut adapter = self.target.clipped(&clip_area);
let text = match symbol {
Symbol::UnderCursor => text,
Symbol::Custom(text) => text,
};
let is_hidden = cell.modifier.intersects(Modifier::HIDDEN);
if is_hidden && symbol == Symbol::UnderCursor {
self.target
.fill_solid(&clip_area, background_color)
.map_err(Error::Draw)?;
} else if text.chars().all(|char| char::is_ascii_whitespace(&char)) {
renderer
.draw_whitespace(explicit_width, top_left, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
} else {
let metrics = renderer.measure_string(text, top_left, BASELINE);
let pixels = metrics.next_position.x.saturating_sub(top_left.x);
let inherent_width = pixels.try_into().unwrap_or_default();
let crop_area = text_area.resized_width(inherent_width, self.anchor_x);
let mut adapter = adapter.translated(crop_area.top_left);
let is_bold = cell.modifier.intersects(Modifier::BOLD);
if is_bold
&& let Some(font_bold) = self.font_bold
&& symbol == Symbol::UnderCursor
{
renderer.font = font_bold;
let width = explicit_width.saturating_sub(inherent_width);
let next_position = renderer
.draw_string(text, Point::zero(), BASELINE, &mut adapter)
.map_err(Error::Draw)?;
renderer
.draw_whitespace(width, next_position, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
let metrics = renderer.measure_string(text, crop_area.top_left, BASELINE);
let below = clip_area.below(&metrics.bounding_box);
let wide = clip_area.above(&below);
let left = wide.left_of(&metrics.bounding_box);
let right = metrics.next_position.x.saturating_add_unsigned(width);
let right = wide.indent_to(right);
for area in [left, right, below] {
self.target
.fill_solid(&area, background_color)
.map_err(Error::Draw)?;
}
} else {
let width = explicit_width.saturating_sub(inherent_width);
let next_position = renderer
.draw_string(text, Point::zero(), BASELINE, &mut adapter)
.map_err(Error::Draw)?;
renderer
.draw_whitespace(width, next_position, BASELINE, &mut adapter)
.map_err(Error::Draw)?;
self.target
.fill_solid(&clip_area.left_of(&crop_area), background_color)
.map_err(Error::Draw)?;
}
}
self.state.cursor_coverage = Some(text_area);
}
Ok(())
}
fn advance_blink_by(&mut self, _: usize) -> Result<(), Self::Error> {
Ok(())
}
fn take_dirty_cursor(&mut self) -> Result<Option<()>, Self::Error> {
Ok(None)
}
}
impl<'a, 'b, 'c, D, C> ConfigureBackend<'a, 'b, 'c, D::Color, C>
for DumoBackend<'a, 'b, 'c, '_, D, C>
where
C: PixelColor + From<C::Raw>,
D: DrawTarget,
D::Color: PixelColor + Default + Invert + Screen + WeightedAvg + From<Rgb888>,
D::Error: Debug,
RawDataSlice<'a, C::Raw, BigEndian>: IntoIterator<Item = C::Raw>,
BitmapFontStyle<'a, 'b, D::Color, C, 1>: TextRenderer<Color = D::Color>,
{
fn font(&self) -> &'b BitmapFont<'a, C, 1> {
self.font
}
fn set_font(&mut self, font: &'b BitmapFont<'a, C, 1>) {
self.font = font;
}
fn font_bold(&self) -> Option<&'b BitmapFont<'a, C, 1>> {
self.font_bold
}
fn set_font_bold(&mut self, font_bold: Option<&'b BitmapFont<'a, C, 1>>) {
self.font_bold = font_bold;
}
fn fg_reset(&self) -> Option<D::Color> {
self.fg_reset
}
fn set_fg_reset(&mut self, fg_reset: Option<D::Color>) {
self.fg_reset = fg_reset;
}
fn bg_reset(&self) -> Option<D::Color> {
self.bg_reset
}
fn set_bg_reset(&mut self, bg_reset: Option<D::Color>) {
self.bg_reset = bg_reset;
}
fn palette(&self) -> Palette<'c, D::Color> {
self.palette
}
fn set_palette(&mut self, palette: Palette<'c, D::Color>) {
self.palette = palette;
}
fn anchor_x(&self) -> AnchorX {
self.anchor_x
}
fn set_anchor_x(&mut self, anchor_x: AnchorX) {
self.anchor_x = anchor_x;
}
}