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
//! Stateful terminal lifecycle and double-buffering.
use crate::backend::{Backend, Output};
use crate::event::Event;
use crate::grid::{Grid, Rect, Size};
use crate::surface::Surface;
use core::time::Duration;
/// A double-buffered terminal generic over a [`Backend`].
///
/// Owns the current and previous frame grids and the backend's lifecycle (resize, present,
/// events). Drawing itself goes entirely through [`Surface`]: see [`draw`](Self::draw) for the
/// common case (draw a frame, then present it) and [`surface`](Self::surface) for manual control
/// over presenting.
///
/// # Out-of-bounds drawing
///
/// [`Surface`] clips any write that falls outside its own area rather than panicking; see
/// [`Surface`]'s own "out-of-bounds drawing" documentation.
///
/// # Examples
///
/// ```
/// use retroglyph_core::backend::Headless;
/// use retroglyph_core::{Color, Terminal};
///
/// let mut term = Terminal::new(Headless::new(20, 5));
/// term.draw(|surface| {
/// surface.put((2, 1), '@', retroglyph_core::Style::new().fg(Color::GREEN));
/// })
/// .unwrap();
/// ```
pub struct Terminal<B: Backend> {
current: Grid,
previous: Grid,
/// Single-layer scratch buffers used only when the backend does not
/// composite layers itself. `present` flattens `current` into
/// `flattened_current`, diffs it against `flattened_previous`, and sends the
/// result. Unused (but allocated) for compositing backends.
flattened_current: Grid,
flattened_previous: Grid,
backend: B,
queued_event: Option<Event>,
/// `true` when the flatten buffers no longer reflect the last frame sent to
/// the backend (because the single-layer fast path bypassed them). The next
/// multi-layer present clears `flattened_previous` first so it does a full
/// redraw instead of diffing against stale data.
flattened_stale: bool,
/// Incremented every time [`present`](Self::present) is called.
///
/// Lets embedding drivers detect whether application code already presented during a frame,
/// so they can skip a redundant driver-side present.
present_count: u64,
}
impl<B: Backend> Terminal<B> {
/// Create a terminal with the given backend.
/// Grid dimensions are queried from the backend.
#[must_use]
pub fn new(backend: B) -> Self {
let size = backend.size();
let current = Grid::new(size.width(), size.height());
let previous = Grid::new(size.width(), size.height());
let flattened_current = Grid::new(size.width(), size.height());
let flattened_previous = Grid::new(size.width(), size.height());
Self {
current,
previous,
flattened_current,
flattened_previous,
backend,
queued_event: None,
flattened_stale: false,
present_count: 0,
}
}
/// Draws one frame: `f` gets a [`Surface`] scoped to the whole terminal on layer 0, then the
/// frame is presented (see [`present`](Self::present)) once `f` returns.
///
/// This is the common entry point for drawing: a caller that draws every frame regardless of
/// whether anything changed calls this once per frame. A caller that only wants to redraw
/// when its own state changed should gate the call to `draw` itself (e.g. `if
/// state.changed() { term.draw(|s| render(s, &state))?; }`) rather than rely on `draw`/
/// [`present`](Self::present) to no-op. Unlike some earlier revisions of this API, presenting
/// is unconditional here.
///
/// # Errors
///
/// Propagates errors from [`present`](Self::present).
pub fn draw(&mut self, f: impl FnOnce(&mut Surface<'_>)) -> Result<(), <B as Output>::Error> {
let area = self.area();
let mut surface = Surface::new(&mut self.current, area, 0);
f(&mut surface);
self.present()
}
/// A [`Surface`] scoped to the whole terminal on layer 0, for manual control over presenting
/// (e.g. partial updates spread across several calls, or conditionally skipping a present).
/// Most callers want [`draw`](Self::draw) instead.
pub const fn surface(&mut self) -> Surface<'_> {
let area = self.area();
Surface::new(&mut self.current, area, 0)
}
/// Returns the current grid dimensions.
#[must_use]
pub const fn size(&self) -> Size {
Size::new(self.current.width(), self.current.height())
}
/// Returns the full drawing surface as a [`Rect`] at the origin.
///
/// Equivalent to `Rect::new(0, 0, width, height)`. Handy for passing the
/// whole terminal to layout helpers or region-based drawing.
#[must_use]
pub const fn area(&self) -> Rect {
Rect::new(0, 0, self.current.width(), self.current.height())
}
/// Resize both grids to `width` × `height` cells.
///
/// Content within the overlapping region is preserved in the current grid.
/// The previous grid is cleared so the next [`present`](Self::present) redraws
/// the entire new surface rather than diffing stale data.
pub fn resize(&mut self, width: u16, height: u16) {
self.current.resize(width, height);
self.previous.resize(width, height);
self.flattened_current.resize(width, height);
self.flattened_previous.resize(width, height);
// Clearing previous forces a full redraw next present(), ensuring no
// stale cells bleed into the resized layout.
self.previous.clear_all();
self.flattened_previous.clear_all();
self.backend.resize(Size::new(width, height));
}
/// Returns a reference to the current grid.
#[must_use]
pub const fn grid(&self) -> &Grid {
&self.current
}
/// Returns a mutable reference to the current grid, with no clipping or layer scoping.
///
/// Escape hatch for whole-grid operations that don't fit [`Surface`]'s clipped,
/// single-layer model (e.g. [`Grid::blit`]). Most drawing should go through
/// [`draw`](Self::draw)/[`surface`](Self::surface) instead.
pub const fn grid_mut(&mut self) -> &mut Grid {
&mut self.current
}
/// Returns a reference to the backend.
#[must_use]
pub const fn backend(&self) -> &B {
&self.backend
}
/// Returns a mutable reference to the backend.
pub const fn backend_mut(&mut self) -> &mut B {
&mut self.backend
}
/// Number of times [`present`](Self::present) has been called so far.
///
/// Wraps on overflow; intended for detecting whether `present` was called *at all* between two
/// points in time (compare a saved count against the current one), not as a precise total.
/// Embedding drivers (e.g. `retroglyph-window`'s windowed drivers) use this to decide whether
/// application code already presented during a frame, so they can skip a redundant
/// driver-side present.
#[must_use]
pub const fn present_count(&self) -> u64 {
self.present_count
}
/// Present the current frame: computes the diff against the previous frame, sends changed
/// cells to the backend, flushes, then swaps buffers. Always presents unconditionally, even
/// if nothing was drawn since the last call; most callers want [`draw`](Self::draw) instead
/// of calling this directly.
///
/// When the backend requires a full frame (see
/// [`crate::Output::needs_full_frame`]), all cells from every allocated layer are
/// sent rather than just the diff, so pixel-based backends can clear and
/// redraw to avoid orphaned pixels from sub-cell offsets.
///
/// After a present, the new current buffer is cleared so the next frame starts empty.
/// Callers should not draw into a frame and skip presenting it: the next [`draw`](Self::draw)
/// call starts from an empty grid regardless.
///
/// # Immediate mode
///
/// This is an immediate-mode API (the same trade [ratatui] makes): the
/// current buffer is wiped after every present, so each frame must redraw
/// its entire scene from scratch. Cells are **not** retained between
/// frames. The diff only bounds what is sent to the backend (terminal or
/// pixel I/O); it does not bound the CPU cost of your redraw.
///
/// [ratatui]: https://docs.rs/ratatui
///
/// # Errors
///
/// Propagates errors from the backend's [`draw_layers`](crate::Output::draw_layers) or
/// [`flush`](crate::Output::flush) operations. Either failure returns before the
/// current/previous buffers are swapped, so the cells from the failed frame stay marked
/// dirty and are resent the next time `present` succeeds; the caller doesn't need to
/// redraw anything to recover, just call `draw`/`present` again.
pub fn present(&mut self) -> Result<(), <B as Output>::Error> {
self.present_count = self.present_count.wrapping_add(1);
if self.backend.composites_layers() {
// Pixel/GPU backends composite the raw layered stream themselves.
if self.backend.needs_full_frame() {
let all = self.current.layers();
self.backend.draw_layers(all)?;
} else {
let diff = self.current.diff(&self.previous);
self.backend.draw_layers(diff)?;
}
} else if self.current.max_layer() == 0 && self.previous.max_layer() == 0 {
// Fast path: only layer 0 is in play, so flattening would be an exact
// copy of `current`. Diff the real grids directly and skip the
// flatten buffers entirely.
let diff = self.current.diff(&self.previous);
self.backend.draw_layers(diff)?;
self.flattened_stale = true;
} else {
// Cell backends receive a pre-flattened, single-layer diff so layers
// 1+ appear everywhere, not just on pixel backends.
if self.flattened_stale {
// The previous frame used the fast path, so `flattened_previous`
// is stale. Clear it to force a full redraw this frame.
self.flattened_previous.clear_all();
self.flattened_stale = false;
}
self.current.flatten_into(&mut self.flattened_current);
let diff = self.flattened_current.diff(&self.flattened_previous);
self.backend.draw_layers(diff)?;
core::mem::swap(&mut self.flattened_current, &mut self.flattened_previous);
}
self.backend.flush()?;
core::mem::swap(&mut self.current, &mut self.previous);
self.current.clear_all();
Ok(())
}
/// Polls for an input event, waiting up to `timeout`.
///
/// If an event was previously buffered by [`has_input`](Self::has_input), it is
/// returned immediately. Otherwise, the backend is polled for a new event.
///
/// [`Event::Resize`] events are automatically applied: both grids are resized
/// before the event is returned to the caller, so the game loop can immediately
/// redraw at the new size.
pub fn poll(&mut self, timeout: Duration) -> Option<Event> {
let event = self
.queued_event
.take()
.or_else(|| self.backend.poll_event(timeout))?;
if let Event::Resize(w, h) = event {
self.resize(w, h);
}
Some(event)
}
/// Reads an input event, blocking indefinitely until one is available.
///
/// Only call this on backends that genuinely block (e.g. crossterm, window). Backends
/// that never block (e.g. [`Headless`](crate::backend::Headless), which returns
/// immediately regardless of timeout) will panic here once their event queue is
/// empty; use [`poll`](Self::poll) or [`drain_events`](Self::drain_events) instead if
/// that is a possibility.
///
/// # Panics
///
/// Panics if the backend's [`poll_event`](crate::Input::poll_event) returns
/// `None` even with an unbounded timeout.
pub fn read_blocking(&mut self) -> Event {
self.poll(Duration::MAX)
.expect("read_blocking() called but no events available")
}
/// Drains all available events without blocking.
///
/// Returns an iterator that yields every pending event — the internal queued event
/// followed by all events buffered in the backend. The iterator polls the backend
/// with zero timeout repeatedly until `None` is returned.
///
/// This is needed for frame-based game loops (e.g. software backend + WASM, where
/// frames are gated by `requestAnimationFrame`). Multiple keypresses can arrive
/// between frames; draining all of them ensures accumulated input doesn't replay in
/// slow motion.
///
/// Crossterm and headless backends can also use this, but the single-event `poll`
/// pattern works for them because their loops aren't frame-capped.
pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + use<'_, B> {
struct DrainEvents<'a, B: Backend> {
terminal: &'a mut Terminal<B>,
}
impl<B: Backend> Iterator for DrainEvents<'_, B> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
self.terminal.poll(Duration::ZERO)
}
}
impl<B: Backend> core::iter::FusedIterator for DrainEvents<'_, B> {}
DrainEvents { terminal: self }
}
/// Checks if a pending input event is available without blocking.
///
/// If an event is already buffered, returns `true`. Otherwise, polls the backend
/// with zero timeout. If the backend returns an event, it is stored in the internal
/// buffer and `true` is returned; otherwise, returns `false`.
pub fn has_input(&mut self) -> bool {
if self.queued_event.is_some() {
true
} else if let Some(event) = self.backend.poll_event(Duration::ZERO) {
self.queued_event = Some(event);
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::Headless;
use crate::color::Color;
use crate::grid::Pos;
use crate::style::Style;
use crate::tile::Tile;
#[test]
fn test_terminal_grid_mut() {
let backend = Headless::new(10, 10);
let mut terminal = Terminal::new(backend);
assert_eq!(terminal.grid()[Pos::new(0, 0)].glyph(), ' ');
terminal
.grid_mut()
.put_tile(0, (0, 0), Tile::new('X', Style::default()));
assert_eq!(terminal.grid()[Pos::new(0, 0)].glyph(), 'X');
}
#[test]
fn test_terminal_poll_and_read() {
let backend = Headless::new(10, 10);
let mut terminal = Terminal::new(backend);
assert_eq!(terminal.poll(Duration::ZERO), None);
terminal.backend_mut().push_event(Event::Close);
assert_eq!(terminal.poll(Duration::ZERO), Some(Event::Close));
terminal.backend_mut().push_event(Event::Resize(80, 25));
assert_eq!(terminal.read_blocking(), Event::Resize(80, 25));
}
#[test]
fn test_terminal_has_input() {
let backend = Headless::new(10, 10);
let mut terminal = Terminal::new(backend);
assert!(!terminal.has_input());
terminal.backend_mut().push_event(Event::Close);
assert!(terminal.has_input());
assert!(terminal.has_input()); // Repeated calls should still be true
// Read/Poll should retrieve the buffered event
assert_eq!(terminal.poll(Duration::ZERO), Some(Event::Close));
// After taking, it should be false again
assert!(!terminal.has_input());
}
#[test]
#[should_panic(expected = "read_blocking() called but no events available")]
fn test_terminal_read_panic() {
let backend = Headless::new(10, 10);
let mut terminal = Terminal::new(backend);
let _ = terminal.read_blocking();
}
#[test]
fn test_draw_composites_layers_for_cell_backend() {
// A cell backend (Headless) must see layers 1+ composited, not
// dropped. Terrain on layer 0, entity on layer 1.
let mut term = Terminal::new(Headless::new(3, 1));
term.draw(|s| {
s.put((0, 0), '.', Style::default());
s.put((1, 0), '.', Style::default());
s.on_layer(1).put((1, 0), '@', Style::default());
})
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), '.');
// Layer 1's glyph wins at (1, 0).
assert_eq!(term.backend().grid()[Pos::new(1, 0)].glyph(), '@');
}
#[test]
fn test_draw_explicit_space_on_higher_layer_erases_and_sets_bg() {
// An explicit space on a higher layer is opaque: it overwrites the
// glyph beneath (erase) and applies its background. This is the
// deliberate consequence of the explicit-EMPTY transparency model.
let mut term = Terminal::new(Headless::new(2, 1));
term.draw(|s| {
s.put((0, 0), 'x', Style::default());
s.on_layer(1).put((0, 0), ' ', Style::new().bg(Color::RED));
})
.expect("draw failed");
let cell = term.backend().grid()[Pos::new(0, 0)];
assert_eq!(cell.glyph(), ' ');
assert_eq!(cell.style().background(), Color::RED);
}
#[test]
fn test_draw_single_layer_fast_path_matches_backend() {
// Only layer 0 is ever touched: the fast path must still deliver the
// correct cells to a cell backend across multiple frames.
let mut term = Terminal::new(Headless::new(3, 1));
term.draw(|s| s.put((0, 0), 'a', Style::default()))
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), 'a');
// Immediate mode: redraw 'a' and add 'c'.
term.draw(|s| {
s.put((0, 0), 'a', Style::default());
s.put((2, 0), 'c', Style::default());
})
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), 'a');
assert_eq!(term.backend().grid()[Pos::new(2, 0)].glyph(), 'c');
// A cell that is not redrawn is erased (immediate mode).
term.draw(|s| s.put((0, 0), 'a', Style::default()))
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), 'a');
assert_eq!(term.backend().grid()[Pos::new(2, 0)].glyph(), ' ');
}
#[test]
fn test_present_transition_single_to_multi_layer() {
// Start single-layer (fast path), then introduce layer 1. The frame
// that adds the layer must composite correctly despite the fast path
// having bypassed the flatten buffers.
let mut term = Terminal::new(Headless::new(2, 1));
term.draw(|s| {
s.put((0, 0), '.', Style::default());
s.put((1, 0), '.', Style::default());
})
.expect("draw failed");
term.draw(|s| {
s.put((0, 0), '.', Style::default());
s.put((1, 0), '.', Style::default());
s.on_layer(1).put((1, 0), '@', Style::default());
})
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), '.');
assert_eq!(term.backend().grid()[Pos::new(1, 0)].glyph(), '@');
}
#[test]
fn test_present_untouched_higher_layer_is_transparent() {
// A higher layer that was allocated but not written at this cell must
// not disturb the lower layer's glyph or background.
let mut term = Terminal::new(Headless::new(2, 1));
term.draw(|s| {
s.put((0, 0), 'x', Style::default());
// Allocate layer 1 by writing elsewhere, leaving (0, 0) empty.
s.on_layer(1).put((1, 0), 'y', Style::default());
})
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), 'x');
}
#[test]
fn test_terminal_size() {
let term = Terminal::new(Headless::new(40, 20));
assert_eq!(term.size(), Size::new(40, 20));
}
#[test]
fn test_terminal_area() {
let term = Terminal::new(Headless::new(40, 20));
assert_eq!(term.area(), Rect::new(0, 0, 40, 20));
}
#[test]
fn test_terminal_resize_changes_dimensions() {
let mut term = Terminal::new(Headless::new(10, 10));
term.resize(30, 15);
assert_eq!(term.size(), Size::new(30, 15));
assert_eq!(term.grid().width(), 30);
assert_eq!(term.grid().height(), 15);
}
#[test]
fn test_terminal_resize_preserves_current_content() {
// Writes through `surface()` rather than `draw()`, so `current` is inspected before any
// `present()` clears it: `draw()` always presents, which would swap this content out to
// `previous` and clear the new `current` before the assertions below could see it.
let mut term = Terminal::new(Headless::new(10, 10));
term.surface().put((2, 2), 'X', Style::default());
term.resize(20, 20);
assert_eq!(term.grid()[Pos::new(2, 2)].glyph(), 'X');
assert_eq!(term.grid()[Pos::new(15, 15)].glyph(), ' ');
}
#[test]
fn test_terminal_resize_event_auto_applies() {
let mut term = Terminal::new(Headless::new(10, 10));
term.backend_mut().push_event(Event::Resize(80, 25));
let event = term.poll(Duration::ZERO);
assert_eq!(event, Some(Event::Resize(80, 25)));
assert_eq!(term.size(), Size::new(80, 25));
}
#[test]
fn test_terminal_resize_new_cells_accessible() {
// Resize to a larger area, then draw into the newly created region.
let mut term = Terminal::new(Headless::new(3, 3));
term.draw(|s| s.put((0, 0), 'A', Style::default()))
.expect("draw failed");
term.resize(5, 5);
// Draw into the expanded region and verify it reaches the backend.
term.draw(|s| s.put((4, 4), 'B', Style::default()))
.expect("draw failed");
assert_eq!(term.backend().grid()[Pos::new(4, 4)].glyph(), 'B');
// (0,0) was not redrawn this frame; backend retains 'A' from before resize.
assert_eq!(term.backend().grid()[Pos::new(0, 0)].glyph(), 'A');
}
// --- unicode width ---
#[test]
fn test_put_wide_char_sets_continuation() {
let mut term = Terminal::new(Headless::new(10, 3));
term.surface().put((0, 0), '\u{4e2d}', Style::default()); // 'ä¸', width 2
assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
// With egc: spacer uses WIDE_CHAR_SPACER flag, glyph is space.
// Without egc: spacer is '\0'.
#[cfg(feature = "egc")]
{
use crate::tile::TileFlags;
assert!(
term.grid()[Pos::new(1, 0)]
.flags()
.contains(TileFlags::WIDE_CHAR_SPACER)
);
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), ' ');
}
#[cfg(not(feature = "egc"))]
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), '\0');
assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), ' '); // untouched
}
#[test]
fn test_print_advances_by_char_width() {
let mut term = Terminal::new(Headless::new(10, 3));
term.surface().print((0, 0), "\u{4e2d}x", Style::default()); // 'ä¸' (2) then 'x' at col 2
assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
#[cfg(feature = "egc")]
{
use crate::tile::TileFlags;
assert!(
term.grid()[Pos::new(1, 0)]
.flags()
.contains(TileFlags::WIDE_CHAR_SPACER)
);
}
#[cfg(not(feature = "egc"))]
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), '\0');
assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'x');
}
#[test]
fn test_put_accepts_a_pos_or_a_tuple() {
// `put` takes `impl Into<Pos>`, so a `Pos` and an equivalent `(u16, u16)` tuple must
// write the same cell.
let mut term = Terminal::new(Headless::new(10, 3));
let mut s = term.surface();
s.put(Pos::new(2, 1), 'X', Style::default());
s.put((3, 1), 'Y', Style::default());
assert_eq!(term.grid()[Pos::new(2, 1)].glyph(), 'X');
assert_eq!(term.grid()[Pos::new(3, 1)].glyph(), 'Y');
}
#[test]
fn test_put_offset_accepts_pos_and_offset_tuples() {
// `put_offset` takes `impl Into<Pos>` and `impl Into<Offset>`, so `Pos`/`Offset` values
// and equivalent tuples must produce the same tile.
let mut term = Terminal::new(Headless::new(4, 1));
let mut s = term.surface();
s.put_offset(
Pos::new(1, 0),
crate::grid::Offset::new(3, -2),
'X',
Style::default(),
);
s.put_offset((2, 0), (-1, 4), 'Y', Style::default());
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), 'X');
assert_eq!(term.grid()[Pos::new(1, 0)].dx(), 3);
assert_eq!(term.grid()[Pos::new(1, 0)].dy(), -2);
assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'Y');
assert_eq!(term.grid()[Pos::new(2, 0)].dx(), -1);
assert_eq!(term.grid()[Pos::new(2, 0)].dy(), 4);
}
#[test]
fn test_put_wide_char_at_last_column_does_not_overflow() {
// Wide char placed at the last column: can't place a spacer.
// write_grapheme silently refuses rather than leaving an orphan.
let mut term = Terminal::new(Headless::new(4, 1));
term.surface().put((3, 0), '\u{4e2d}', Style::default()); // col 3 is last; need col 4 for spacer
assert_eq!(term.grid()[Pos::new(3, 0)].glyph(), ' '); // nothing written
}
// --- styled spans ---
#[test]
fn test_print_styled_basic() {
use crate::text::{Line, Span};
let mut term = Terminal::new(Headless::new(20, 3));
let line = Line::from(vec![
Span::raw("HP: "),
Span::styled("100", Style::new().fg(Color::GREEN)),
]);
term.surface().print_line((0, 0), &line);
assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), 'H');
assert_eq!(term.grid()[Pos::new(3, 0)].glyph(), ' ');
assert_eq!(term.grid()[Pos::new(4, 0)].glyph(), '1');
assert_eq!(term.grid()[Pos::new(4, 0)].style.fg, Color::GREEN);
assert_eq!(term.grid()[Pos::new(6, 0)].glyph(), '0');
}
#[test]
fn test_print_styled_wide_chars() {
use crate::text::Line;
let mut term = Terminal::new(Headless::new(10, 3));
let line = Line::from(vec![crate::text::Span::raw("\u{4e2d}x")]);
term.surface().print_line((0, 0), &line);
assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), '\u{4e2d}');
#[cfg(feature = "egc")]
{
use crate::tile::TileFlags;
assert!(
term.grid()[Pos::new(1, 0)]
.flags()
.contains(TileFlags::WIDE_CHAR_SPACER)
);
}
#[cfg(not(feature = "egc"))]
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), '\0');
assert_eq!(term.grid()[Pos::new(2, 0)].glyph(), 'x');
}
#[test]
fn test_print_str_styled_applies_style_to_every_cell() {
let mut term = Terminal::new(Headless::new(20, 3));
term.surface()
.print((0, 0), "HP", Style::new().fg(Color::GREEN));
assert_eq!(term.grid()[Pos::new(0, 0)].glyph(), 'H');
assert_eq!(term.grid()[Pos::new(0, 0)].style.fg, Color::GREEN);
assert_eq!(term.grid()[Pos::new(1, 0)].glyph(), 'P');
assert_eq!(term.grid()[Pos::new(1, 0)].style.fg, Color::GREEN);
}
}