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
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
//! [`Surface`]: an area-clipped, single-layer view over a [`Grid`].
//!
//! `Surface` is the workspace's one grid-drawing primitive. [`Terminal`](crate::Terminal)'s
//! [`draw`](crate::Terminal::draw)/[`surface`](crate::Terminal::surface) hand out a `Surface`
//! scoped to the whole grid, and `retroglyph-widgets` renders every widget into a `Surface`
//! scoped to a sub-[`Rect`]: there is no separate stateful drawing API on `Terminal` itself.
use crate::color::Color;
use crate::grid::{Grid, Offset, Pos, Rect, Size};
use crate::style::Style;
use crate::text::Line;
use crate::tile::Tile;
use crate::tint::Tint;
#[cfg(not(feature = "egc"))]
use unicode_width::UnicodeWidthChar;
/// The render target for every drawing call in the workspace: a mutable reference to a
/// [`Grid`] plus a fixed `layer`, scoped to one area.
///
/// A `Surface` is typically created once per frame, scoped to the whole drawing surface (e.g.
/// via [`Terminal::draw`](crate::Terminal::draw)), and handed to every subsystem/widget in turn;
/// each caller's own `area: Rect` (a sub-rect of the surface's own area, e.g. one produced by a
/// layout split) is in the same coordinate space as [`Surface::area`] itself.
/// [`Surface::put`]/[`Surface::print`]/... take coordinates in that same space and silently clip
/// any write that falls outside [`Surface::area`], matching the rest of the workspace's
/// clip-on-draw policy for out-of-bounds drawing.
///
/// [`Surface::clip`] turns a sub-rect into a surface of its own, so a subsystem that should not
/// draw outside one is bounded by the type rather than trusted to respect an `area` handed to it
/// alongside a wider surface. The clip is intersected, never substituted, so narrowing only ever
/// tightens.
///
/// A caller that genuinely needs more than one layer at once (e.g. a modal dimming layer 0 while
/// drawing its own content on layer 1) switches layers with [`Surface::on_layer`] rather than
/// being restricted to the layer it was constructed with.
pub struct Surface<'a> {
grid: &'a mut Grid,
area: Rect,
layer: u8,
tint: Tint,
origin_offset: (i32, i32),
}
impl<'a> Surface<'a> {
/// A surface over `grid`, scoped to `area` on `layer`, tinting nothing.
pub const fn new(grid: &'a mut Grid, area: Rect, layer: u8) -> Self {
Self {
grid,
area,
layer,
tint: Tint::None,
origin_offset: (0, 0),
}
}
/// The area this surface clips writes to.
#[must_use]
pub const fn area(&self) -> Rect {
self.area
}
/// The width of this surface's area, in columns.
#[must_use]
pub const fn width(&self) -> u16 {
self.area.width()
}
/// The height of this surface's area, in rows.
#[must_use]
pub const fn height(&self) -> u16 {
self.area.height()
}
/// The grid layer this surface writes to.
#[must_use]
pub const fn layer(&self) -> u8 {
self.layer
}
/// A new surface over the same grid and area, but writing to `layer` instead.
#[must_use]
pub const fn on_layer(&mut self, layer: u8) -> Surface<'_> {
Surface {
grid: self.grid,
area: self.area,
layer,
tint: self.tint,
origin_offset: self.origin_offset,
}
}
/// The tint every sprite drawn through this surface is recoloured by.
#[must_use]
pub const fn tint(&self) -> Tint {
self.tint
}
/// A new surface over the same grid, area, and layer, recolouring every sprite it draws by
/// `tint`.
///
/// Substituted rather than combined: unlike [`clip`](Self::clip), which can only narrow,
/// a tint replaces whatever the parent surface carried. Two tints do not compose into a
/// third meaningful one, and silently multiplying an inherited shadow into a caller's damage
/// flash would be harder to predict than replacing it.
///
/// Applies to sprites only. A cell backend has no sprite to recolour and draws the cell's
/// glyph in its own [`Style`], tinted or not, so this is invisible there. See [`Tint`].
///
/// This tint composes with the sheet's own colour treatment; see
/// `retroglyph_window::tileset::SheetColor` and `retroglyph_window::sprite_cache::SpriteTint`
/// for the two-stage resolution (retroglyph-core has no dependency on retroglyph-window, so
/// these are plain names, not intra-doc links).
///
/// For a multi-cell span the tint lands on the anchor cell, which is where a pixel backend
/// draws the sprite from.
///
/// # Examples
///
/// ```
/// # fn main() {
/// # fn run() -> Option<()> {
/// use retroglyph_core::{Grid, Rect, Style, Surface, Tint};
///
/// let mut grid = Grid::new(8, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 4), 0);
///
/// // One grass sprite, drawn twice: once as itself, once dimmed into shadow.
/// let grass = '\u{E000}';
/// surface.put_span_uniform((0, 0), (2, 1), grass, ' ', Style::default())?;
/// surface
/// .with_tint(Tint::multiply(128, 128, 128))
/// .put_span_uniform((2, 0), (2, 1), grass, ' ', Style::default())?;
///
/// assert_eq!(grid.tint(0, 0, 0), Tint::None);
/// assert_eq!(grid.tint(0, 2, 0), Tint::multiply(128, 128, 128));
/// # Some(())
/// # }
/// # run().unwrap();
/// # }
/// ```
#[must_use]
pub const fn with_tint(&mut self, tint: Tint) -> Surface<'_> {
Surface {
grid: self.grid,
area: self.area,
layer: self.layer,
tint,
origin_offset: self.origin_offset,
}
}
/// A new surface over the same grid and layer, clipped to `area` intersected with this
/// surface's own area.
///
/// Coordinates are unchanged: the sub-surface addresses the same space this one does, so a
/// sub-rect computed against [`Surface::area`] (e.g. by a [`layout`](crate::layout) split)
/// can be passed straight in. Because `area` is intersected rather than substituted,
/// narrowing is monotonic: handing a surface down a layout tree can only ever tighten what a
/// callee is able to touch.
///
/// Clipping is also how the area-sensitive calls are told what they are drawing into:
///
/// - [`print`](Self::print) wraps overflow onto the next row. Clipped to a one-row bar, the
/// wrapped remainder falls outside the area and is dropped, which is what a single-line
/// bar wants.
/// - [`put_span`](Self::put_span) and [`put_span_uniform`](Self::put_span_uniform) refuse a
/// footprint that leaves the area. Clipped to a content rect, "fits" stops meaning "fits
/// the screen" and starts meaning "does not reserve cells in the status bar below".
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(6, 2);
/// let mut screen = Surface::new(&mut grid, Rect::new(0, 0, 6, 2), 0);
///
/// // A title too long for the one-row bar at the top: the remainder wraps out of the
/// // clip instead of onto the map below.
/// screen
/// .clip(Rect::new(0, 0, 6, 1))
/// .print((0, 0), "retroglyph", Style::default());
///
/// assert_eq!(grid[Pos::new(0, 0)].glyph(), 'r');
/// assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
/// ```
#[must_use]
pub fn clip(&mut self, area: Rect) -> Surface<'_> {
Surface {
area: self.area.intersect(area),
grid: self.grid,
layer: self.layer,
tint: self.tint,
origin_offset: self.origin_offset,
}
}
/// A view whose `(0, 0)` sits at `origin` relative to this surface's own coordinate space, so
/// a caller can draw in a shifted (e.g. world/camera) coordinate space and let the surface do
/// the clipping, rather than subtracting `origin` from every coordinate by hand.
///
/// Every coordinate-taking method on the returned surface -- [`put`](Self::put),
/// [`put_signed`](Self::put_signed), [`print`](Self::print), [`print_line`](Self::print_line),
/// [`fill_rect`](Self::fill_rect), [`put_offset`](Self::put_offset),
/// [`put_span`](Self::put_span), [`put_span_uniform`](Self::put_span_uniform), and
/// [`clear_region`](Self::clear_region) -- subtracts `origin` (composed with any outstanding
/// translate) from the coordinate it is given before applying its usual bounds check. Only
/// [`clear`](Self::clear), which takes no coordinate and always clears this surface's whole
/// area, is unaffected.
///
/// This does not touch [`area`](Self::area), so [`area`](Self::area), [`width`](Self::width),
/// and [`height`](Self::height) keep reporting the same thing before and after translating:
/// only the coordinate a caller must pass to land a write shifts, never what the surface
/// itself covers. This composes with [`clip`](Self::clip) the same order it is called in:
/// `clip(...).translate(...)` first narrows the area, then shifts the coordinate space that
/// still-narrowed area is addressed in, so a coordinate that goes negative after the shift can
/// land inside the pre-narrowed area.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(10, 10);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 10, 10), 0);
///
/// // Narrow to a 4x4 viewport, then shift its coordinate space by (-5, -5): translating
/// // does not move or resize the viewport itself.
/// let mut clipped = surface.clip(Rect::new(5, 5, 4, 4));
/// let mut view = clipped.translate((-5, -5));
/// assert_eq!(view.area(), Rect::new(5, 5, 4, 4));
///
/// // (-5, -5) minus the translate offset (-5, -5) is (0, 0): the viewport's own local
/// // origin, which lands at the viewport's top-left grid cell (5, 5).
/// view.put_signed((-5, -5), 'X', Style::default());
///
/// assert_eq!(grid[Pos::new(5, 5)].glyph(), 'X');
/// ```
#[must_use]
pub const fn translate(&mut self, origin: (i32, i32)) -> Surface<'_> {
Surface {
grid: self.grid,
area: self.area,
layer: self.layer,
tint: self.tint,
origin_offset: (
self.origin_offset.0.saturating_add(origin.0),
self.origin_offset.1.saturating_add(origin.1),
),
}
}
/// A styled view over this surface: same area and layer, but every draw call uses `style`
/// without needing to pass it each time. Handy for a run of same-styled writes (e.g. filling
/// in a wall glyph over many cells) without repeating the [`Style`] at every call site.
pub const fn with_style(&mut self, style: Style) -> StyledSurface<'_, 'a> {
StyledSurface {
surface: self,
style,
}
}
/// Borrows the underlying [`Grid`] directly, with no clipping.
///
/// Escape hatch for multi-layer or whole-grid operations (e.g. [`Grid::blit`]) that don't fit
/// this surface's clipped, single-layer model. Drawing into a sub-rect is not one of those:
/// [`clip`](Self::clip) narrows a surface without handing out the unclipped grid to do it.
pub const fn grid_mut(&mut self) -> &mut Grid {
self.grid
}
/// Read-only counterpart of [`grid_mut`](Self::grid_mut).
#[must_use]
pub const fn grid(&self) -> &Grid {
self.grid
}
/// The tile at `pos` on this surface's layer, if any.
///
/// Respects this surface's layer but not its area clip, mirroring [`grid_mut`](Self::grid_mut)
/// in that sense: a caller wanting an area-clipped read should check
/// [`self.area().contains(...)`](Rect::contains) first.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
/// surface.put((1, 1), 'X', Style::default());
///
/// assert_eq!(surface.tile((1, 1)).map(|t| t.glyph()), Some('X'));
/// assert_eq!(surface.tile((0, 0)).map(|t| t.glyph()), Some(' '));
/// ```
#[must_use]
pub fn tile(&self, pos: impl Into<Pos>) -> Option<&Tile> {
self.grid.tile(self.layer, pos.into())
}
/// The background colour at `pos` on this surface's layer, or `None` if there's no tile
/// there.
///
/// A read-only read of a cell's own background lets a caller blend a new draw with what's
/// already there (e.g. `surface.background(pos).unwrap_or(default)`) without the mutable
/// borrow [`grid_mut`](Self::grid_mut) would otherwise force.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Color, Grid, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
/// surface.put((1, 1), 'X', Style::new().bg(Color::RED));
///
/// assert_eq!(surface.background((1, 1)), Some(Color::RED));
/// // Out of the grid entirely: no tile there to read a background from.
/// assert_eq!(surface.background((10, 10)), None);
/// ```
#[must_use]
pub fn background(&self, pos: impl Into<Pos>) -> Option<Color> {
self.tile(pos).map(|t| t.style().background())
}
/// Shifts `(x, y)` by this surface's translate offset (see [`translate`](Self::translate)),
/// returning the coordinate to actually write at if the shift still lands inside this
/// surface's own area, or `None` otherwise.
fn shift(&self, x: u16, y: u16) -> Option<(u16, u16)> {
let sx = i32::from(x).checked_sub(self.origin_offset.0)?;
let sy = i32::from(y).checked_sub(self.origin_offset.1)?;
let sx = u16::try_from(sx).ok()?;
let sy = u16::try_from(sy).ok()?;
self.area.contains(sx, sy).then_some((sx, sy))
}
/// Applies this surface's tint to the cell just written at `(x, y)`.
///
/// Called after a write rather than as part of one, because a glyph write drops whatever
/// tint the cell held (see [`Grid::set_tint`]); doing it in the other order would erase the
/// tint being applied. Untinted surfaces skip the call entirely, so the ordinary text path
/// never touches the side table.
fn apply_tint(&mut self, x: u16, y: u16) {
if self.tint != Tint::None {
self.grid.set_tint(self.layer, x, y, self.tint);
}
}
/// Writes `grapheme` (already a single extended grapheme cluster) at `(x, y)`. A no-op if
/// out of this surface's area.
#[cfg(feature = "egc")]
fn put_grapheme(&mut self, x: u16, y: u16, grapheme: &str, style: Style) {
let Some((x, y)) = self.shift(x, y) else {
return;
};
self.grid.write_grapheme(self.layer, x, y, grapheme, style);
self.apply_tint(x, y);
}
/// Place `ch` at `pos` in `style`. A no-op if `pos` is outside this surface's area.
///
/// If a pixel backend resolves `ch` to a sprite, that sprite is composited from its own
/// pixels: [`style.fg`](Style::fg) does not tint it, and `style.bg` shows through only where
/// the sprite is transparent. See [`put_span`](Self::put_span).
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
///
/// surface.put((1, 1), 'X', Style::default());
/// // Outside the surface's area: silently dropped, not a panic.
/// surface.put((10, 10), 'X', Style::default());
///
/// assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
/// ```
pub fn put(&mut self, pos: impl Into<Pos>, ch: char, style: Style) {
let pos = pos.into();
#[cfg(feature = "egc")]
{
let mut buf = [0u8; 4];
let s = ch.encode_utf8(&mut buf);
self.put_grapheme(pos.x, pos.y, s, style);
}
#[cfg(not(feature = "egc"))]
{
let Some((x, y)) = self.shift(pos.x, pos.y) else {
return;
};
let tile = Tile::new(ch, style);
self.grid.put_tile(self.layer, (x, y), tile);
self.apply_tint(x, y);
}
}
/// [`put`](Self::put), in coordinates relative to this surface's own area origin, where a
/// negative coordinate is expressible and simply falls outside (a no-op, matching `put`'s
/// out-of-bounds behavior).
///
/// Scrolling/camera code (e.g. a viewport over a wider world) computes positions in a
/// coordinate space that can go negative relative to the viewport, which [`Pos`] (backed by
/// `u16`) cannot even express. `put_signed` takes that arithmetic directly, so a caller no
/// longer clip-tests by hand before calling `put`.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
///
/// // Negative in either axis: outside this surface's area, silently dropped.
/// surface.put_signed((-1, 1), 'X', Style::default());
/// // Non-negative and within bounds: lands like `put`.
/// surface.put_signed((1, 1), 'X', Style::default());
///
/// assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
/// assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
/// ```
pub fn put_signed(&mut self, pos: (i32, i32), ch: char, style: Style) {
let (x, y) = pos;
let x = x.saturating_sub(self.origin_offset.0);
let y = y.saturating_sub(self.origin_offset.1);
if x < 0 || y < 0 {
return;
}
let Ok(x) = u16::try_from(x) else {
return;
};
let Ok(y) = u16::try_from(y) else {
return;
};
if x >= self.width() || y >= self.height() {
return;
}
let abs_x = self.area.left() + x;
let abs_y = self.area.top() + y;
let tile = Tile::new(ch, style);
self.grid.put_tile(self.layer, (abs_x, abs_y), tile);
self.apply_tint(abs_x, abs_y);
}
/// Print `text` starting at `pos` in `style`.
///
/// `\n` advances to the next row at the original column. Text that would extend beyond this
/// surface's area wraps to the next row at the original column; cells outside the area
/// (either axis) are clipped. When the `egc` feature is enabled, `text` is split into
/// extended grapheme clusters (so combining marks and ZWJ sequences write as one cell each);
/// otherwise it is split by `char`.
///
/// # Examples
///
/// ```
/// use retroglyph_core::backend::Headless;
/// use retroglyph_core::{Style, Terminal};
///
/// let mut term = Terminal::new(Headless::new(6, 3));
/// term.draw(|s| s.print((0, 0), "hello wrapped world", Style::default()))
/// .unwrap();
///
/// // Wraps back to column 0 every 6 cells; the surface is only 3 rows tall, so
/// // the remainder past row 2 is clipped rather than growing the grid.
/// assert_eq!(
/// term.backend().format_view(),
/// "hello·\nwrappe\nd·worl\n",
/// );
/// ```
pub fn print(&mut self, pos: impl Into<Pos>, text: &str, style: Style) {
let pos = pos.into();
#[cfg(feature = "egc")]
self.print_egc(pos, text, style);
#[cfg(not(feature = "egc"))]
self.print_chars(pos, text, style);
}
/// [`print`](Self::print) implementation used when `egc` is enabled: splits on extended
/// grapheme clusters rather than `char`.
#[cfg(feature = "egc")]
fn print_egc(&mut self, pos: Pos, text: &str, style: Style) {
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
let right = self.area.right();
let mut cx = pos.x;
let mut cy = pos.y;
for grapheme in text.graphemes(true) {
if grapheme == "\n" {
cx = pos.x;
cy = cy.saturating_add(1);
continue;
}
// A single grapheme's display width is 0, 1, or 2 per `unicode-width` (see
// `Tile::width`'s doc comment), never anywhere near `u16::MAX`.
#[allow(clippy::cast_possible_truncation)]
let w = grapheme.width() as u16;
if w == 0 {
continue;
}
self.put_grapheme(cx, cy, grapheme, style);
cx = cx.saturating_add(w);
if cx >= right {
cx = pos.x;
cy = cy.saturating_add(1);
}
}
}
/// [`print`](Self::print) implementation used when `egc` is disabled: splits on `char`.
#[cfg(not(feature = "egc"))]
fn print_chars(&mut self, pos: Pos, text: &str, style: Style) {
let right = self.area.right();
let mut cx = pos.x;
let mut cy = pos.y;
for ch in text.chars() {
if ch == '\n' {
cx = pos.x;
cy = cy.saturating_add(1);
continue;
}
// A single char's display width is 0, 1, or 2 per `unicode-width` (see `Tile::width`'s
// doc comment), never anywhere near `u16::MAX`.
#[allow(clippy::cast_possible_truncation)]
let w = UnicodeWidthChar::width(ch).unwrap_or(1) as u16;
if w == 0 {
continue;
}
self.put((cx, cy), ch, style);
cx = cx.saturating_add(w);
if cx >= right {
cx = pos.x;
cy = cy.saturating_add(1);
}
}
}
/// Print `line`'s styled spans starting at `pos`, one row, each span in its own style.
/// Stops once a span would start past this surface's area.
///
/// # Examples
///
/// ```
/// use retroglyph_core::backend::Headless;
/// use retroglyph_core::text::{Line, Span};
/// use retroglyph_core::Terminal;
///
/// let mut term = Terminal::new(Headless::new(5, 2));
/// let line = Line::from(vec![Span::raw("hello"), Span::raw("world")]);
/// term.draw(|s| s.print_line((0, 0), &line)).unwrap();
///
/// // The first span exactly fills the one-row area. The second span would start at
/// // column 5, past the area, so it is skipped entirely rather than wrapped onto the
/// // next row the way `print` would wrap.
/// assert_eq!(term.backend().format_view(), "hello\n·····\n");
/// ```
pub fn print_line(&mut self, pos: impl Into<Pos>, line: &Line) {
use unicode_width::UnicodeWidthStr;
let pos = pos.into();
let right = self.area.right();
let mut cx = pos.x;
for span in &line.spans {
if cx >= right {
break;
}
self.print((cx, pos.y), &span.content, span.style);
// A single span wider than `u16::MAX` columns would already be unaddressable in this
// crate's `u16` coordinate space; `cx` still saturates rather than overflowing even if
// this cast wraps.
#[allow(clippy::cast_possible_truncation)]
let w = UnicodeWidthStr::width(span.content.as_str()) as u16;
cx = cx.saturating_add(w);
}
}
/// [`print`](Self::print), horizontally aligned within `rect` (clipped to this surface's own
/// area) and measured in display columns (via `unicode_width`), not bytes.
///
/// Wants a per-frame redrawn UI label (a status line, a centred title bar) that should not
/// allocate: unlike [`TextLayout`](crate::layout::TextLayout), which only accepts a
/// [`Line`] (forcing an allocation to build one for every call), this
/// takes `&str` directly.
///
/// The starting column is computed with saturating arithmetic, so `text` wider than `rect`
/// does not panic or underflow: it simply left-aligns and lets [`print`](Self::print) clip
/// the overflow, for every [`HAlign`](crate::layout::HAlign) (matching how
/// [`HAlign::Center`](crate::layout::HAlign::Center) itself saturates in
/// [`TextLayout`](crate::layout::TextLayout)).
///
/// # Examples
///
/// ```
/// use retroglyph_core::backend::Headless;
/// use retroglyph_core::layout::HAlign;
/// use retroglyph_core::{Rect, Style, Terminal};
///
/// let mut term = Terminal::new(Headless::new(6, 1));
/// term.draw(|s| {
/// s.print_aligned(Rect::new(0, 0, 6, 1), "hi", HAlign::Center, Style::default())
/// })
/// .unwrap();
///
/// // "hi" is 2 columns wide in a 6-column rect: (6 - 2) / 2 == 2 columns of left padding.
/// assert_eq!(term.backend().format_view(), "··hi··\n");
/// ```
#[cfg(feature = "egc")]
pub fn print_aligned(
&mut self,
rect: Rect,
text: &str,
align: crate::layout::HAlign,
style: Style,
) {
use crate::layout::HAlign;
use unicode_width::UnicodeWidthStr;
// A single line's display width is never anywhere near `u16::MAX` (see `print_line`'s
// own use of this same cast for a single span).
#[allow(clippy::cast_possible_truncation)]
let text_width = UnicodeWidthStr::width(text) as u16;
let x_offset = match align {
HAlign::Left => 0,
HAlign::Center => rect.width().saturating_sub(text_width) / 2,
HAlign::Right => rect.width().saturating_sub(text_width),
};
let pos = (rect.left().saturating_add(x_offset), rect.top());
self.clip(rect).print(pos, text, style);
}
/// Fill `rect` (clipped to this surface's own area) with `ch` in `style`.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
///
/// // `rect` extends well past the grid on both axes; only the cells inside the
/// // surface's own area are touched, the rest is silently clipped.
/// surface.fill_rect(Rect::new(2, 2, 10, 10), '#', Style::default());
///
/// assert_eq!(grid[Pos::new(3, 3)].glyph(), '#');
/// assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
/// ```
pub fn fill_rect(&mut self, rect: Rect, ch: char, style: Style) {
for y in rect.top()..rect.bottom() {
for x in rect.left()..rect.right() {
self.put((x, y), ch, style);
}
}
}
/// Writes a multi-cell span at `pos` on this surface's layer in `style`: one piece of
/// artwork occupying a block of cells rather than one, the [`Surface`] twin of
/// [`Grid::write_span`].
///
/// `rows` holds one string per row of the footprint. Its first character is the **anchor**
/// glyph, which a pixel backend looks up in its sprite cache; the rest are the span's **text
/// fallback**, printed by cell backends and skipped by pixel backends. Any `AsRef<str>` row
/// works, so a literal footprint (`&["[==]", "|__|"]`) and a computed one (`&Vec<String>`)
/// both pass without a borrowing pass over the rows; for the uniform case, see
/// [`put_span_uniform`](Self::put_span_uniform).
///
/// See [`Grid::write_span`] for the full write semantics, and [`Grid::span_owner`] to
/// hit-test the whole footprint.
///
/// # `style` applies to the text fallback, not to the sprite
///
/// A sprite is composited from its own pixels. [`style.fg`](Style::fg) does not tint it;
/// `style.bg` is still painted behind it, so it shows through wherever the sprite is
/// transparent. Recoloring a shared sprite per cell is therefore not possible: draw a
/// variant of the artwork instead, which is the usual tileset idiom.
///
/// `style` is not dead on such a cell, because the same span drawn by a *cell* backend
/// renders the text fallback in it. The consequence is that `fg` reads very differently
/// depending on the backend, and that a glyph missing from the sprite cache silently falls
/// back to a font glyph that *is* `fg`-colored, which looks a lot like a tint working.
///
/// # Returns
///
/// `Some(())` once the whole span is written, or `None` having written nothing at all when
/// `rows` is empty or ragged, either axis exceeds 255 cells, or the footprint does not fit
/// entirely within this surface's own area (not just the grid) at `pos`. The surface has
/// strictly more ways to refuse a span than [`Grid::write_span`] does, so a sprite that did
/// not draw is answered here rather than in the backend.
pub fn put_span<S: AsRef<str>>(
&mut self,
pos: impl Into<Pos>,
rows: &[S],
style: Style,
) -> Option<()> {
let pos = pos.into();
let (x, y) = self.shift(pos.x, pos.y)?;
let cols = rows.first()?.as_ref().chars().count();
let w = u16::try_from(cols).ok()?;
let h = u16::try_from(rows.len()).ok()?;
if !self.span_fits(Pos::new(x, y), w, h) {
return None;
}
self.grid.write_span(self.layer, x, y, rows, style)?;
// The anchor only: a pixel backend draws the whole footprint from that one cell, so the
// covered cells have no sprite of their own to recolour.
self.apply_tint(x, y);
Some(())
}
/// Writes a `size` multi-cell span at `pos` on this surface's layer in `style`: `anchor` in
/// the anchor cell, `fill` in every other cell of the footprint, the [`Surface`] twin of
/// [`Grid::write_span_uniform`].
///
/// The uniform case of [`put_span`](Self::put_span), and what a sheet-driven renderer usually
/// wants: one sprite, chosen at runtime, with the cells it covers blanked so nothing shows
/// through its transparent pixels. `fill` is the text fallback a *cell* backend prints for
/// those covered cells, so `' '` blanks them and a visible character keeps the footprint
/// legible in a terminal.
///
/// `style` reads exactly as it does for [`put_span`](Self::put_span): it applies to the text
/// fallback, never to the sprite.
///
/// # Returns
///
/// `Some(())` once the whole span is written, or `None` having written nothing at all when
/// either axis of `size` is `0` or exceeds 255 cells, or the footprint does not fit entirely
/// within this surface's own area at `pos`.
///
/// # Examples
///
/// ```
/// # fn main() {
/// # fn run() -> Option<()> {
/// use retroglyph_core::{Grid, Rect, Style, Surface};
///
/// let mut grid = Grid::new(8, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 8, 4), 0);
///
/// // A 16x16 sprite over a 2x1 block of 8x16 cells, anchored at a runtime glyph.
/// let anchor = '\u{E000}';
/// surface.put_span_uniform((1, 1), (2, 1), anchor, ' ', Style::default())?;
/// # Some(())
/// # }
/// # run().unwrap();
/// # }
/// ```
pub fn put_span_uniform(
&mut self,
pos: impl Into<Pos>,
size: impl Into<Size>,
anchor: char,
fill: char,
style: Style,
) -> Option<()> {
let pos = pos.into();
let (x, y) = self.shift(pos.x, pos.y)?;
let pos = Pos::new(x, y);
let size = size.into();
if !self.span_fits(pos, size.width(), size.height()) {
return None;
}
self.grid
.write_span_uniform(self.layer, pos, size, anchor, fill, style)?;
self.apply_tint(pos.x, pos.y);
Some(())
}
/// `true` if a `w` x `h` footprint at `pos` lies entirely within this surface's area.
///
/// A span is all-or-nothing rather than clipped like the per-cell writes, because a
/// footprint half outside the area would reserve cells the caller does not own.
fn span_fits(&self, pos: Pos, w: u16, h: u16) -> bool {
pos.x >= self.area.left()
&& pos.y >= self.area.top()
&& pos.x.saturating_add(w) <= self.area.right()
&& pos.y.saturating_add(h) <= self.area.bottom()
}
/// Place `ch` at `pos` with a sub-cell pixel `offset`, in `style`.
///
/// Sub-cell offsets are visual only: they do not affect grid logic or hit-testing.
/// Backends that cannot represent pixel offsets (e.g. `CrosstermBackend`) ignore them. A
/// no-op if `pos` is outside this surface's area.
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Offset, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
///
/// // A large offset still lands the glyph in cell (1, 1): the offset is a pixel nudge
/// // for a pixel backend, never a coordinate shift.
/// surface.put_offset((1, 1), Offset::new(12, -12), 'X', Style::default());
/// // Outside the surface's area: silently dropped, matching `put`.
/// surface.put_offset((10, 10), Offset::default(), 'X', Style::default());
///
/// assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
/// ```
pub fn put_offset(
&mut self,
pos: impl Into<Pos>,
offset: impl Into<Offset>,
ch: char,
style: Style,
) {
let pos = pos.into();
let Some((x, y)) = self.shift(pos.x, pos.y) else {
return;
};
let offset = offset.into();
let tile = Tile::new(ch, style).with_offset(offset.dx, offset.dy);
self.grid.put_tile(self.layer, (x, y), tile);
}
/// Clears this surface's entire area (on its own layer) back to [`Tile::default`].
pub fn clear(&mut self) {
let area = self.area;
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
self.grid.put_tile(self.layer, (x, y), Tile::default());
}
}
}
/// Clears `rect` (clipped to this surface's own area, on its own layer) back to
/// [`Tile::default`].
///
/// # Examples
///
/// ```
/// use retroglyph_core::{Grid, Pos, Rect, Style, Surface};
///
/// let mut grid = Grid::new(4, 4);
/// let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
/// surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
///
/// // `rect` extends past the surface's own area; only the overlap is cleared.
/// surface.clear_region(Rect::new(2, 2, 10, 10));
///
/// assert_eq!(grid[Pos::new(2, 2)].glyph(), ' ');
/// assert_eq!(grid[Pos::new(1, 1)].glyph(), '#');
/// ```
pub fn clear_region(&mut self, rect: Rect) {
for y in rect.top()..rect.bottom() {
for x in rect.left()..rect.right() {
if let Some((x, y)) = self.shift(x, y) {
self.grid.put_tile(self.layer, (x, y), Tile::default());
}
}
}
}
}
/// A [`Surface`] with a [`Style`] bound in, returned by [`Surface::with_style`].
///
/// Every draw call omits the `style` argument the underlying [`Surface`] method would otherwise
/// need, using the bound style instead. Reach back to the underlying surface (e.g. to call
/// [`Surface::print_line`], whose per-span styles make a bound style meaningless) via
/// [`StyledSurface::surface`].
pub struct StyledSurface<'s, 'a> {
surface: &'s mut Surface<'a>,
style: Style,
}
impl<'a> StyledSurface<'_, 'a> {
/// The style every draw call on this view uses.
#[must_use]
pub const fn style(&self) -> Style {
self.style
}
/// Borrows the underlying [`Surface`] directly, for calls that need an explicit style (e.g.
/// [`Surface::print_line`]) or a capability [`StyledSurface`] doesn't expose.
pub const fn surface(&mut self) -> &mut Surface<'a> {
self.surface
}
/// [`Surface::put`] using this view's bound style.
pub fn put(&mut self, pos: impl Into<Pos>, ch: char) {
self.surface.put(pos, ch, self.style);
}
/// [`Surface::print`] using this view's bound style.
pub fn print(&mut self, pos: impl Into<Pos>, text: &str) {
self.surface.print(pos, text, self.style);
}
/// [`Surface::fill_rect`] using this view's bound style.
pub fn fill_rect(&mut self, rect: Rect, ch: char) {
self.surface.fill_rect(rect, ch, self.style);
}
/// [`Surface::put_span`] using this view's bound style.
pub fn put_span<S: AsRef<str>>(&mut self, pos: impl Into<Pos>, rows: &[S]) -> Option<()> {
self.surface.put_span(pos, rows, self.style)
}
/// [`Surface::put_span_uniform`] using this view's bound style.
pub fn put_span_uniform(
&mut self,
pos: impl Into<Pos>,
size: impl Into<Size>,
anchor: char,
fill: char,
) -> Option<()> {
self.surface
.put_span_uniform(pos, size, anchor, fill, self.style)
}
/// [`Surface::put_offset`] using this view's bound style.
pub fn put_offset(&mut self, pos: impl Into<Pos>, offset: impl Into<Offset>, ch: char) {
self.surface.put_offset(pos, offset, ch, self.style);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn screen(grid: &mut Grid) -> Surface<'_> {
let area = Rect::new(0, 0, grid.width(), grid.height());
Surface::new(grid, area, 0)
}
#[test]
fn put_span_takes_any_as_ref_str_row() {
let mut grid = Grid::new(4, 4);
// A footprint computed at runtime: owned rows, no borrowing pass over them.
let rows: Vec<String> = (0..2)
.map(|row| {
(0..2)
.map(|col| if (row, col) == (0, 0) { 'C' } else { ' ' })
.collect()
})
.collect();
assert_eq!(
screen(&mut grid).put_span((0, 0), &rows, Style::default()),
Some(())
);
assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
}
#[test]
fn put_span_reports_why_a_span_did_not_draw() {
let mut grid = Grid::new(4, 4);
let area = Rect::new(0, 0, 2, 2);
let mut surface = Surface::new(&mut grid, area, 0);
let style = Style::default();
assert_eq!(surface.put_span((0, 0), &[] as &[&str], style), None);
assert_eq!(surface.put_span((0, 0), &[""], style), None);
// Ragged rows are refused by the grid, and that answer is passed through.
assert_eq!(surface.put_span((0, 0), &["ab", "c"], style), None);
// Fits the grid, but leaves the surface's own area.
assert_eq!(surface.put_span((1, 1), &["ab"], style), None);
assert_eq!(surface.put_span((0, 0), &["ab"], style), Some(()));
}
#[test]
fn put_span_uniform_writes_the_anchor_once_and_fills_the_rest() {
let mut grid = Grid::new(4, 4);
assert_eq!(
screen(&mut grid).put_span_uniform((1, 1), (2, 2), 'C', '.', Style::default()),
Some(())
);
assert_eq!(grid[Pos::new(1, 1)].glyph(), 'C');
assert_eq!(grid[Pos::new(1, 1)].span(), (2, 2));
assert_eq!(grid[Pos::new(2, 2)].glyph(), '.');
assert_eq!(grid.span_owner(0, 2, 2), Some(Pos::new(1, 1)));
}
#[test]
fn put_span_uniform_writes_to_this_surfaces_layer() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
surface
.on_layer(2)
.put_span_uniform((0, 0), (2, 1), 'C', ' ', Style::default())
.expect("span write");
}
assert_eq!(grid.span_owner(2, 1, 0), Some(Pos::new(0, 0)));
assert_eq!(grid.span_owner(0, 1, 0), None);
}
#[test]
fn put_span_uniform_refuses_a_footprint_that_leaves_the_surfaces_area() {
let mut grid = Grid::new(4, 4);
let area = Rect::new(0, 0, 2, 2);
let mut surface = Surface::new(&mut grid, area, 0);
let style = Style::default();
// Both fit the grid; neither fits the area.
assert_eq!(
surface.put_span_uniform((1, 0), (2, 1), 'C', ' ', style),
None
);
assert_eq!(
surface.put_span_uniform((0, 1), (1, 2), 'C', ' ', style),
None
);
assert_eq!(
surface.put_span_uniform((0, 0), (0, 1), 'C', ' ', style),
None
);
assert_eq!(
surface.put_span_uniform((0, 0), (2, 2), 'C', ' ', style),
Some(())
);
}
#[test]
fn styled_surface_forwards_both_span_calls() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
let mut styled = surface.with_style(Style::new().fg(Color::RED));
styled.put_span((0, 0), &["ab"]).expect("span write");
styled
.put_span_uniform((0, 1), (2, 1), 'C', ' ')
.expect("span write");
}
assert_eq!(grid[Pos::new(0, 0)].style().foreground(), Color::RED);
assert_eq!(grid[Pos::new(0, 1)].style().foreground(), Color::RED);
assert_eq!(grid[Pos::new(0, 1)].span(), (2, 1));
}
#[test]
fn with_tint_applies_to_the_cell_it_writes() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
surface
.with_tint(Tint::multiply(128, 64, 32))
.put((1, 1), '@', Style::default());
}
assert_eq!(grid[Pos::new(1, 1)].glyph(), '@');
assert_eq!(grid.tint(0, 1, 1), Tint::multiply(128, 64, 32));
}
#[test]
fn an_untinted_surface_leaves_the_side_table_alone() {
let mut grid = Grid::new(4, 4);
screen(&mut grid).put((1, 1), '@', Style::default());
assert_eq!(grid.tint(0, 1, 1), Tint::None);
}
#[test]
fn with_tint_lands_on_the_span_anchor_only() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
surface
.with_tint(Tint::multiply(200, 200, 200))
.put_span((0, 0), &["ab", "cd"], Style::default())
.expect("span write");
}
// A pixel backend draws the whole footprint from the anchor, so that is the only cell
// with a sprite to recolour.
assert_eq!(grid.tint(0, 0, 0), Tint::multiply(200, 200, 200));
assert_eq!(grid.tint(0, 1, 0), Tint::None);
assert_eq!(grid.tint(0, 1, 1), Tint::None);
}
#[test]
fn with_tint_applies_to_a_uniform_span_anchor() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
surface
.with_tint(Tint::mix(255, 0, 0, 128))
.put_span_uniform((1, 1), (2, 2), 'C', '.', Style::default())
.expect("span write");
}
assert_eq!(grid.tint(0, 1, 1), Tint::mix(255, 0, 0, 128));
assert_eq!(grid.tint(0, 2, 2), Tint::None);
}
#[test]
fn with_tint_is_not_applied_to_a_refused_span() {
let mut grid = Grid::new(4, 4);
let area = Rect::new(0, 0, 2, 2);
{
let mut surface = Surface::new(&mut grid, area, 0);
// Fits the grid, leaves the area: nothing is written, so nothing is tinted.
assert_eq!(
surface.with_tint(Tint::multiply(1, 2, 3)).put_span(
(1, 1),
&["ab"],
Style::default()
),
None
);
}
assert_eq!(grid.tint(0, 1, 1), Tint::None);
}
#[test]
fn with_tint_survives_clip_and_on_layer() {
let mut grid = Grid::new(8, 4);
{
let mut surface = screen(&mut grid);
let mut tinted = surface.with_tint(Tint::multiply(9, 9, 9));
assert_eq!(tinted.tint(), Tint::multiply(9, 9, 9));
assert_eq!(
tinted.clip(Rect::new(0, 0, 4, 4)).tint(),
Tint::multiply(9, 9, 9)
);
assert_eq!(tinted.on_layer(2).tint(), Tint::multiply(9, 9, 9));
tinted.on_layer(2).put((1, 1), '@', Style::default());
}
assert_eq!(grid.tint(2, 1, 1), Tint::multiply(9, 9, 9));
}
#[test]
fn with_tint_replaces_rather_than_composes() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
let mut outer = surface.with_tint(Tint::multiply(128, 128, 128));
// Unlike `clip`, a nested tint substitutes: two tints have no meaningful product.
outer
.with_tint(Tint::mix(255, 0, 0, 64))
.put((0, 0), '@', Style::default());
}
assert_eq!(grid.tint(0, 0, 0), Tint::mix(255, 0, 0, 64));
}
#[test]
fn clip_narrows_the_area_and_keeps_the_coordinate_space() {
let mut grid = Grid::new(8, 4);
let mut surface = screen(&mut grid);
let sub = surface.clip(Rect::new(2, 1, 4, 2));
assert_eq!(sub.area(), Rect::new(2, 1, 4, 2));
assert_eq!(sub.width(), 4);
assert_eq!(sub.height(), 2);
}
#[test]
fn clip_keeps_the_layer() {
let mut grid = Grid::new(4, 4);
let mut surface = screen(&mut grid);
let mut layer1 = surface.on_layer(1);
assert_eq!(layer1.clip(Rect::new(0, 0, 2, 2)).layer(), 1);
}
#[test]
fn clip_intersects_rather_than_replaces_so_it_cannot_widen() {
let mut grid = Grid::new(8, 4);
let area = Rect::new(2, 1, 4, 2);
let mut surface = Surface::new(&mut grid, area, 0);
// A rect reaching outside the surface's own area only ever tightens it.
assert_eq!(surface.clip(Rect::new(0, 0, 8, 4)).area(), area);
assert_eq!(
surface.clip(Rect::new(0, 0, 4, 4)).area(),
Rect::new(2, 1, 2, 2)
);
}
#[test]
fn clip_writes_outside_the_sub_rect_are_dropped() {
let mut grid = Grid::new(4, 2);
{
let mut surface = screen(&mut grid);
let mut top = surface.clip(Rect::new(0, 0, 4, 1));
top.put((1, 0), 'a', Style::default());
// Inside the surface's own area, outside the clip.
top.put((1, 1), 'b', Style::default());
}
assert_eq!(grid[Pos::new(1, 0)].glyph(), 'a');
assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
}
#[test]
fn clip_to_one_row_drops_print_overflow_instead_of_wrapping_it() {
let mut grid = Grid::new(4, 2);
{
let mut surface = screen(&mut grid);
surface
.clip(Rect::new(0, 0, 4, 1))
.print((0, 0), "abcdef", Style::default());
}
assert_eq!(grid[Pos::new(3, 0)].glyph(), 'd');
// "ef" wrapped onto row 1, which the clip excludes.
assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
}
#[test]
fn clip_makes_put_span_measure_its_footprint_against_the_sub_rect() {
let mut grid = Grid::new(4, 3);
{
let mut surface = screen(&mut grid);
// Fits the grid, but reserves a cell on the bottom row the clip excludes.
surface
.clip(Rect::new(0, 0, 4, 2))
.put_span((0, 1), &["ab", "cd"], Style::default());
}
assert_eq!(grid[Pos::new(0, 1)].glyph(), ' ');
let mut surface = screen(&mut grid);
surface
.clip(Rect::new(0, 0, 4, 2))
.put_span((0, 0), &["ab", "cd"], Style::default());
assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
}
#[test]
fn clip_makes_put_span_uniform_measure_its_footprint_against_the_sub_rect() {
let mut grid = Grid::new(4, 3);
let style = Style::default();
{
let mut surface = screen(&mut grid);
let mut content = surface.clip(Rect::new(0, 0, 4, 2));
// Fits the grid, but reserves a cell on the bottom row the clip excludes.
assert_eq!(
content.put_span_uniform((0, 1), (2, 2), 'C', '.', style),
None
);
assert_eq!(
content.put_span_uniform((0, 0), (2, 2), 'C', '.', style),
Some(())
);
}
assert_eq!(grid[Pos::new(0, 0)].span(), (2, 2));
assert_eq!(grid[Pos::new(0, 2)].glyph(), ' ');
}
#[test]
fn clip_to_a_disjoint_rect_is_empty_and_drops_every_write() {
let mut grid = Grid::new(8, 4);
{
let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 4, 4), 0);
let mut sub = surface.clip(Rect::new(4, 0, 4, 4));
assert_eq!(sub.area(), Rect::EMPTY);
sub.print((0, 0), "abc", Style::default());
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}
#[test]
fn put_signed_drops_a_negative_coordinate() {
let mut grid = Grid::new(4, 4);
let mut surface = screen(&mut grid);
surface.put_signed((-1, 0), 'X', Style::default());
surface.put_signed((0, -1), 'X', Style::default());
assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
}
#[test]
fn put_signed_lands_a_valid_coordinate_at_the_area_origin() {
let mut grid = Grid::new(4, 4);
let area = Rect::new(1, 1, 2, 2);
let mut surface = Surface::new(&mut grid, area, 0);
// (0, 0) relative to the area's own origin is grid position (1, 1).
surface.put_signed((0, 0), 'X', Style::default());
assert_eq!(grid[Pos::new(1, 1)].glyph(), 'X');
}
#[test]
fn put_signed_drops_a_coordinate_past_this_surfaces_width_or_height() {
let mut grid = Grid::new(4, 4);
let area = Rect::new(0, 0, 2, 2);
let mut surface = Surface::new(&mut grid, area, 0);
// Fits the grid, but not this surface's own (relative) width/height.
surface.put_signed((2, 0), 'X', Style::default());
surface.put_signed((0, 2), 'X', Style::default());
assert_eq!(grid[Pos::new(2, 0)].glyph(), ' ');
assert_eq!(grid[Pos::new(0, 2)].glyph(), ' ');
}
#[test]
fn translate_does_not_change_area_width_or_height() {
let mut grid = Grid::new(10, 10);
let mut surface = screen(&mut grid);
let mut clipped = surface.clip(Rect::new(5, 5, 4, 4));
let view = clipped.translate((-5, -5));
assert_eq!(view.area(), Rect::new(5, 5, 4, 4));
assert_eq!(view.width(), 4);
assert_eq!(view.height(), 4);
}
#[test]
fn translate_shifts_put_by_subtracting_the_origin() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
let mut view = surface.translate((3, 3));
// (3, 3) minus the translate origin (3, 3) is (0, 0).
view.put((3, 3), 'A', Style::default());
// (2, 3) minus (3, 3) is negative on the x axis: out of bounds, dropped.
view.put((2, 3), 'B', Style::default());
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
assert_eq!(grid[Pos::new(0, 3)].glyph(), ' ');
}
#[test]
fn translate_composes_with_clip_and_lets_a_negative_signed_coordinate_land() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
let mut clipped = surface.clip(Rect::new(5, 5, 4, 4));
let mut view = clipped.translate((-5, -5));
// -5 minus the translate origin (-5) is 0: the viewport's own local origin, landing
// at the clipped area's top-left grid cell.
view.put_signed((-5, -5), 'X', Style::default());
// -6 minus -5 is still -1: still negative, so still out of bounds.
view.put_signed((-6, -6), 'Y', Style::default());
}
assert_eq!(grid[Pos::new(5, 5)].glyph(), 'X');
assert_eq!(grid[Pos::new(4, 4)].glyph(), ' ');
}
#[test]
fn translate_composes_additively_across_two_calls() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
let mut once = surface.translate((2, 0));
let mut twice = once.translate((1, 0));
// Composed origin is (3, 0): (3, 0) minus (3, 0) is (0, 0).
twice.put((3, 0), 'A', Style::default());
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), 'A');
}
#[test]
fn translate_shifts_fill_rect_print_and_clear_region_via_put() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
let mut view = surface.translate((5, 5));
view.fill_rect(Rect::new(5, 5, 2, 2), '#', Style::default());
view.print((5, 6), "a", Style::default());
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), '#');
assert_eq!(grid[Pos::new(1, 1)].glyph(), '#');
assert_eq!(grid[Pos::new(0, 1)].glyph(), 'a');
}
#[test]
fn translate_shifts_clear_region() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
let mut view = surface.translate((2, 2));
// Clears grid (0..2, 0..2) once shifted by the translate origin.
view.clear_region(Rect::new(2, 2, 2, 2));
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
assert_eq!(grid[Pos::new(1, 1)].glyph(), ' ');
assert_eq!(grid[Pos::new(2, 2)].glyph(), '#');
}
#[test]
fn translate_shifts_put_span_and_put_span_uniform() {
let mut grid = Grid::new(10, 10);
{
let mut surface = screen(&mut grid);
let mut view = surface.translate((4, 4));
assert_eq!(view.put_span((4, 4), &["ab"], Style::default()), Some(()));
assert_eq!(
view.put_span_uniform((6, 4), (2, 1), 'C', ' ', Style::default()),
Some(())
);
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), 'a');
assert_eq!(grid[Pos::new(2, 0)].glyph(), 'C');
}
#[test]
fn clear_is_unaffected_by_translate() {
let mut grid = Grid::new(4, 4);
{
let mut surface = screen(&mut grid);
surface.fill_rect(Rect::new(0, 0, 4, 4), '#', Style::default());
let mut view = surface.translate((100, 100));
// `clear` takes no coordinate, so the translate offset does not apply to it: it
// always clears this surface's own area.
view.clear();
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
assert_eq!(grid[Pos::new(3, 3)].glyph(), ' ');
}
#[test]
fn grid_is_the_read_only_counterpart_of_grid_mut() {
let mut grid = Grid::new(4, 4);
let mut surface = screen(&mut grid);
surface.put((1, 1), 'X', Style::default());
assert_eq!(surface.grid()[Pos::new(1, 1)].glyph(), 'X');
}
#[test]
fn tile_reads_a_written_cell_without_a_mutable_borrow() {
let mut grid = Grid::new(4, 4);
let mut surface = screen(&mut grid);
surface.put((1, 1), 'X', Style::default());
assert_eq!(surface.tile((1, 1)).map(Tile::glyph), Some('X'));
assert_eq!(surface.tile((0, 0)).map(Tile::glyph), Some(' '));
assert_eq!(surface.tile((10, 10)), None);
}
#[test]
fn background_reads_the_styles_background_colour() {
let mut grid = Grid::new(4, 4);
let mut surface = screen(&mut grid);
surface.put((1, 1), 'X', Style::new().bg(Color::RED));
assert_eq!(surface.background((1, 1)), Some(Color::RED));
assert_eq!(surface.background((10, 10)), None);
}
#[test]
#[cfg(feature = "egc")]
fn print_aligned_left_aligns_by_default() {
let mut grid = Grid::new(8, 1);
{
let mut surface = screen(&mut grid);
surface.print_aligned(
Rect::new(0, 0, 8, 1),
"hi",
crate::layout::HAlign::Left,
Style::default(),
);
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), 'h');
assert_eq!(grid[Pos::new(1, 0)].glyph(), 'i');
assert_eq!(grid[Pos::new(2, 0)].glyph(), ' ');
}
#[test]
#[cfg(feature = "egc")]
fn print_aligned_centers_matching_text_layouts_own_saturating_formula() {
let mut grid = Grid::new(6, 1);
{
let mut surface = screen(&mut grid);
surface.print_aligned(
Rect::new(0, 0, 6, 1),
"hi",
crate::layout::HAlign::Center,
Style::default(),
);
}
// (6 - 2) / 2 == 2 columns of left padding, matching `HAlign::Center` in `layout.rs`.
assert_eq!(grid[Pos::new(2, 0)].glyph(), 'h');
assert_eq!(grid[Pos::new(3, 0)].glyph(), 'i');
}
#[test]
#[cfg(feature = "egc")]
fn print_aligned_right_aligns_flush_to_the_rects_right_edge() {
let mut grid = Grid::new(6, 1);
{
let mut surface = screen(&mut grid);
surface.print_aligned(
Rect::new(0, 0, 6, 1),
"hi",
crate::layout::HAlign::Right,
Style::default(),
);
}
assert_eq!(grid[Pos::new(4, 0)].glyph(), 'h');
assert_eq!(grid[Pos::new(5, 0)].glyph(), 'i');
}
#[test]
#[cfg(feature = "egc")]
fn print_aligned_does_not_panic_or_underflow_on_text_wider_than_the_rect() {
let mut grid = Grid::new(4, 1);
{
let mut surface = screen(&mut grid);
// "hello" is wider than the 4-column rect on every alignment: this must not panic
// (a plain `rect.width() - text_width` would underflow) and instead left-aligns and
// lets `print` clip the overflow.
surface.print_aligned(
Rect::new(0, 0, 4, 1),
"hello",
crate::layout::HAlign::Center,
Style::default(),
);
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), 'h');
assert_eq!(grid[Pos::new(3, 0)].glyph(), 'l');
}
#[test]
#[cfg(feature = "egc")]
fn print_aligned_clips_to_this_surfaces_own_area_as_well_as_rect() {
let mut grid = Grid::new(4, 1);
{
let mut surface = Surface::new(&mut grid, Rect::new(0, 0, 2, 1), 0);
// `rect` extends past this surface's own area; the write is still clipped to it.
surface.print_aligned(
Rect::new(0, 0, 4, 1),
"hi",
crate::layout::HAlign::Right,
Style::default(),
);
}
assert_eq!(grid[Pos::new(0, 0)].glyph(), ' ');
assert_eq!(grid[Pos::new(1, 0)].glyph(), ' ');
}
#[test]
fn clip_nests_monotonically() {
let mut grid = Grid::new(8, 4);
let mut surface = screen(&mut grid);
let mut outer = surface.clip(Rect::new(1, 1, 4, 2));
let inner = outer.clip(Rect::new(0, 0, 8, 4));
assert_eq!(inner.area(), Rect::new(1, 1, 4, 2));
}
}