Skip to main content

uncurses/buffer/
surface.rs

1//! Cell-grid surface traits.
2//!
3//! Buffer-like types ([`Buffer`](super::Buffer), [`Window`](super::Window),
4//! [`View`](super::View), [`TextBuffer`](super::TextBuffer), and
5//! [`Screen`](crate::screen::Screen)) all expose a rectangular region of
6//! [`Cell`]s. This module defines the traits that let drawing code use
7//! those regions without depending on a concrete storage type.
8//!
9//! ## Trait layers
10//!
11//! | trait          | adds                            | required methods                         |
12//! |----------------|---------------------------------|------------------------------------------|
13//! | [`Bounded`]    | rectangular extent              | [`bounds`](Bounded::bounds)              |
14//! | [`Surface`]    | read-only cell access           | [`cell`](Surface::cell)                  |
15//! | [`SurfaceMut`] | writes and terminal operations  | [`set_cell`](SurfaceMut::set_cell), [`cell_mut`](SurfaceMut::cell_mut) |
16//!
17//! [`Surface`] extends [`Bounded`], and [`SurfaceMut`] extends
18//! [`Surface`]. Default methods supply common behavior such as
19//! [`Surface::draw`], [`SurfaceMut::fill_rect`],
20//! [`SurfaceMut::insert_lines`], and [`SurfaceMut::delete_cells`].
21//! Implementations may override defaults for storage-specific fast paths
22//! as long as they preserve the same visible semantics.
23//!
24//! ## Coordinates and bounds
25//!
26//! Coordinates are terminal-cell coordinates in the implementer's own
27//! coordinate space. A surface reports the rectangle where reads and writes
28//! are meaningful through [`Bounded::bounds`]; attempts outside that region
29//! should either return `None` or have no effect, as documented by each
30//! method.
31//!
32//! ```text
33//! Rect::new(2, 1, 4, 2)
34//!
35//! y=1      x=2 x=3 x=4 x=5
36//!        ┌───┬───┬───┬───┐
37//!        │   │   │   │   │
38//! y=2    ├───┼───┼───┼───┤
39//!        │   │   │   │   │
40//!        └───┴───┴───┴───┘
41//! ```
42//!
43//! ## Wide-cell invariants
44//!
45//! A wide grapheme occupies a primary cell plus a continuation placeholder
46//! in the following column. Methods that copy or fill cells step by the
47//! primary cell's display width and substitute blanks when a wide grapheme
48//! would be split by a source slice, a destination edge, or a fill region.
49
50use crate::cell::Cell;
51use crate::layout::{Position, Rect, overruns};
52
53/// A value with a rectangular extent in terminal-cell coordinates.
54///
55/// `Bounded` is the base trait for readable and writable surfaces. It does
56/// not imply that cells can be inspected or modified; it only describes the
57/// region where a value exists in its own coordinate space.
58///
59/// Implement this trait for types that can answer "what rectangle do I
60/// cover?" and then add [`Surface`] or [`SurfaceMut`] when cell access is
61/// available.
62pub trait Bounded {
63    /// Return the valid region in this value's own coordinate space.
64    ///
65    /// # Returns
66    ///
67    /// A [`Rect`] whose `x`/`y` form the top-left coordinate and whose
68    /// `width`/`height` form the extent in terminal cells.
69    ///
70    /// # Panics
71    ///
72    /// Implementations should not panic.
73    ///
74    /// # Usage notes
75    ///
76    /// For most storage-backed surfaces the origin is `(0, 0)`. Clipping
77    /// adaptors may report non-zero origins when they expose a sub-rectangle
78    /// in the wrapped surface's coordinate space.
79    fn bounds(&self) -> Rect;
80
81    /// Return the width of [`Self::bounds`] in terminal cell columns.
82    ///
83    /// # Returns
84    ///
85    /// `self.bounds().width`.
86    ///
87    /// # Panics
88    ///
89    /// Never panics unless [`Self::bounds`] panics.
90    ///
91    /// # Usage notes
92    ///
93    /// This is a convenience method; override only if computing full bounds
94    /// is meaningfully more expensive than returning the width.
95    fn width(&self) -> u16 {
96        self.bounds().width
97    }
98
99    /// Return the height of [`Self::bounds`] in terminal cell rows.
100    ///
101    /// # Returns
102    ///
103    /// `self.bounds().height`.
104    ///
105    /// # Panics
106    ///
107    /// Never panics unless [`Self::bounds`] panics.
108    ///
109    /// # Usage notes
110    ///
111    /// This is a convenience method; override only if computing full bounds
112    /// is meaningfully more expensive than returning the height.
113    fn height(&self) -> u16 {
114        self.bounds().height
115    }
116
117    /// Test whether a position lies inside [`Self::bounds`].
118    ///
119    /// # Parameters
120    ///
121    /// - `pos`: coordinate in this value's coordinate space.
122    ///
123    /// # Returns
124    ///
125    /// `true` when `pos` is inside the half-open rectangle described by
126    /// [`Self::bounds`], otherwise `false`.
127    ///
128    /// # Panics
129    ///
130    /// Never panics unless [`Self::bounds`] panics.
131    ///
132    /// # Usage notes
133    ///
134    /// Surfaces commonly use this to clip reads and writes before touching
135    /// their backing storage.
136    fn contains(&self, pos: Position) -> bool {
137        self.bounds().contains(pos)
138    }
139}
140
141/// A rectangular cell grid that can be read.
142///
143/// `Surface` adds immutable cell access to [`Bounded`]. It is the trait to
144/// use for render sources, snapshots, and helpers that only need to inspect
145/// cells or copy them into another surface.
146///
147/// The provided [`Surface::draw`] method is intentionally conservative
148/// about wide cells: it avoids producing orphan continuation columns and
149/// blanks wide primaries that would be split by source or destination
150/// bounds.
151pub trait Surface: Bounded {
152    /// Read the cell at a position.
153    ///
154    /// # Parameters
155    ///
156    /// - `pos`: coordinate in this surface's coordinate space.
157    ///
158    /// # Returns
159    ///
160    /// `Some(&Cell)` when `pos` is readable, or `None` when it is outside
161    /// [`Bounded::bounds`] or otherwise unavailable.
162    ///
163    /// # Panics
164    ///
165    /// Implementations should not panic for out-of-bounds positions.
166    ///
167    /// # Usage notes
168    ///
169    /// A returned cell may be a wide primary or a continuation placeholder.
170    /// Callers that walk rows should advance by `cell.width().max(1)` for
171    /// primary cells and handle continuations explicitly.
172    fn cell(&self, pos: Position) -> Option<&Cell>;
173
174    /// Copy `self`'s cells into `target`, mapping the top-left of
175    /// `self.bounds()` to `at` in target coordinates.
176    ///
177    /// # Parameters
178    ///
179    /// - `target`: writable destination surface.
180    /// - `at`: destination coordinate for the source bounds' top-left
181    ///   corner.
182    ///
183    /// # Behavior
184    ///
185    /// The default walks the source row by row and emits one
186    /// [`SurfaceMut::set_cell`] call per source cell. Wide-cell
187    /// semantics are preserved:
188    ///
189    /// * Wide-primary cells advance the column cursor by their full
190    ///   `width` so the source's continuation cells are not written
191    ///   over independently.
192    /// * If the source has been sliced through the middle of a wide
193    ///   grapheme (a leading continuation with no primary in view, or
194    ///   a trailing primary with no room for its continuation), the
195    ///   default substitutes a blank rather than emitting an orphan
196    ///   half. The same blank substitution applies when either horizontal
197    ///   edge of `target` splits a wide cell.
198    ///
199    /// Implementations may override for a faster path (e.g. bulk line
200    /// copies), but must preserve the wide-cell invariants above.
201    ///
202    /// # Panics
203    ///
204    /// The default implementation does not panic unless the destination's
205    /// [`SurfaceMut::set_cell`] implementation panics.
206    ///
207    /// # Usage notes
208    ///
209    /// Destination clipping is delegated to `target`. Cells whose
210    /// destination coordinate lies outside the target bounds are passed to
211    /// `set_cell`, which is expected to ignore them.
212    fn draw<T: SurfaceMut + ?Sized>(&self, target: &mut T, at: Position) {
213        let b = self.bounds();
214        let tb = target.bounds();
215        let t_right = tb.x.saturating_add(tb.width);
216        for dy in 0..b.height {
217            let dst_y = at.y.saturating_add(dy);
218            let mut dx: u16 = 0;
219            while dx < b.width {
220                let src = Position::new(b.x + dx, b.y + dy);
221                let dst = Position::new(at.x.saturating_add(dx), dst_y);
222                let Some(cell) = self.cell(src) else {
223                    dx += 1;
224                    continue;
225                };
226
227                // Leading continuation with no primary in view: the
228                // source's left edge sliced a wide grapheme in half.
229                // Substitute a blank to avoid writing an orphan
230                // continuation into target.
231                if cell.is_continuation() {
232                    target.set_cell(dst, &Cell::BLANK);
233                    dx += 1;
234                    continue;
235                }
236
237                let w = (cell.width() as u16).max(1);
238
239                // Wide primary that won't fit — either source's right
240                // edge sliced through its continuation, or either edge
241                // of the target cuts it off. Emit a blank instead.
242                let fits_in_src = dx + w <= b.width;
243                let fits_in_dst = dst.x >= tb.x && dst.x.saturating_add(w) <= t_right;
244                if w > 1 && (!fits_in_src || !fits_in_dst) {
245                    target.set_cell(dst, &Cell::BLANK);
246                    dx += 1;
247                    continue;
248                }
249
250                target.set_cell(dst, cell);
251                dx += w;
252            }
253        }
254    }
255}
256
257/// A rectangular cell grid that can be modified.
258///
259/// `SurfaceMut` is the trait to use for render targets. It includes a
260/// primitive cell write plus higher-level operations used by terminal
261/// emulation and drawing code: fills, clears, line insertion/deletion, and
262/// cell insertion/deletion within a row.
263///
264/// Implementations are responsible for preserving the same wide-cell
265/// invariants as [`Buffer`](super::Buffer): a wide primary owns the
266/// following continuation slot, continuations should not become visible
267/// without their primary, and clipped wide writes should leave blanks
268/// rather than half a grapheme.
269pub trait SurfaceMut: Surface {
270    /// Place `cell` at `pos`. Implementations are responsible for
271    /// wide-cell semantics (continuation markers, blanking covered
272    /// cells) and any dirty tracking they care to do. Taking `&Cell`
273    /// lets implementations skip the clone when the destination
274    /// already matches.
275    ///
276    /// # Parameters
277    ///
278    /// - `pos`: destination coordinate in this surface's coordinate space.
279    /// - `cell`: cell to write.
280    ///
281    /// # Returns
282    ///
283    /// Nothing.
284    ///
285    /// # Panics
286    ///
287    /// Implementations should not panic for out-of-bounds positions.
288    ///
289    /// # Usage notes
290    ///
291    /// Out-of-bounds writes should be ignored. Use this method instead of
292    /// [`Self::cell_mut`] whenever changing content could affect display
293    /// width or neighboring continuation slots.
294    // A continuation belongs to the wide cell on its left and is placed by
295    // that cell's own write, so an implementor ignores one passed on its
296    // own rather than storing it.
297    fn set_cell(&mut self, pos: Position, cell: &Cell);
298
299    /// Mutable handle to the cell at `pos`. Returns `None` for
300    /// out-of-bounds positions.
301    ///
302    /// # Parameters
303    ///
304    /// - `pos`: coordinate in this surface's coordinate space.
305    ///
306    /// # Returns
307    ///
308    /// `Some(&mut Cell)` for an in-bounds cell, or `None` when `pos` is not
309    /// writable.
310    ///
311    /// # Panics
312    ///
313    /// Implementations should not panic for out-of-bounds positions.
314    ///
315    /// # Usage notes
316    ///
317    /// Implementations that track dirty state must mark the cell as
318    /// touched eagerly — the caller may mutate any field through this
319    /// handle and the surface has no way to observe a write. Callers
320    /// must not change the cell's display width through this handle; use
321    /// [`Self::set_cell`] for wide-cell writes that need
322    /// continuation-column accounting.
323    fn cell_mut(&mut self, pos: Position) -> Option<&mut Cell>;
324
325    /// Fill the entire surface bounds with `cell`.
326    ///
327    /// # Parameters
328    ///
329    /// - `cell`: fill cell to write repeatedly.
330    ///
331    /// # Returns
332    ///
333    /// Nothing.
334    ///
335    /// # Panics
336    ///
337    /// Does not panic unless [`Self::fill_rect`] panics.
338    ///
339    /// # Usage notes
340    ///
341    /// This delegates to [`Self::fill_rect`] with [`Bounded::bounds`].
342    /// Wide fills are handled by `fill_rect`.
343    fn fill(&mut self, cell: &Cell) {
344        let b = self.bounds();
345        self.fill_rect(b, cell);
346    }
347
348    /// Fill the intersection of `rect` and [`Bounded::bounds`] with
349    /// `cell`.
350    ///
351    /// # Parameters
352    ///
353    /// - `rect`: requested fill rectangle in this surface's coordinate
354    ///   space.
355    /// - `cell`: fill cell to write.
356    ///
357    /// # Behavior
358    ///
359    /// Stepped by `cell.width()` so a wide cell lays down a clean primary
360    /// and its continuations; whatever region is left at the right edge,
361    /// narrower than one more cell, falls back to blanks with `cell`'s style.
362    /// Implementations may override for a bulk-blit fast path.
363    ///
364    /// # Panics
365    ///
366    /// The default implementation does not panic unless [`Self::set_cell`]
367    /// panics.
368    ///
369    /// # Usage notes
370    ///
371    /// Empty intersections are no-ops. A region whose width is not a
372    /// multiple of `cell.width()` ends in blanks, because the cell cannot be
373    /// drawn in fewer columns than it takes: a width-8 fill into ten columns
374    /// leaves the last two blank.
375    fn fill_rect(&mut self, rect: Rect, cell: &Cell) {
376        let clipped = self.bounds().intersection(rect);
377        let step = (cell.width() as u16).max(1);
378        let mut blank = Cell::BLANK;
379        blank.copy_style_from(cell);
380        for y in clipped.top()..clipped.bottom() {
381            let mut x = clipped.left();
382            while !overruns(x, step, clipped.right()) {
383                self.set_cell(Position::new(x, y), cell);
384                x += step;
385            }
386            while x < clipped.right() {
387                self.set_cell(Position::new(x, y), &blank);
388                x += 1;
389            }
390        }
391    }
392
393    /// Clear the entire surface bounds to [`Cell::BLANK`].
394    ///
395    /// # Returns
396    ///
397    /// Nothing.
398    ///
399    /// # Panics
400    ///
401    /// Does not panic unless [`Self::fill`] panics.
402    ///
403    /// # Usage notes
404    ///
405    /// This is equivalent to `self.fill(&Cell::BLANK)`.
406    fn clear(&mut self) {
407        self.fill(&Cell::BLANK);
408    }
409
410    /// Clear a rectangle to [`Cell::BLANK`].
411    ///
412    /// # Parameters
413    ///
414    /// - `rect`: requested clear rectangle in this surface's coordinate
415    ///   space.
416    ///
417    /// # Returns
418    ///
419    /// Nothing.
420    ///
421    /// # Panics
422    ///
423    /// Does not panic unless [`Self::fill_rect`] panics.
424    ///
425    /// # Usage notes
426    ///
427    /// Only the intersection of `rect` and [`Bounded::bounds`] is modified.
428    fn clear_rect(&mut self, rect: Rect) {
429        self.fill_rect(rect, &Cell::BLANK);
430    }
431
432    /// Insert `n` blank rows at `y`, pushing existing rows down within
433    /// `[y, bounds_bottom)`. Rows pushed past `bounds_bottom` are lost.
434    /// Freed top rows are filled with `fill`.
435    ///
436    /// # Parameters
437    ///
438    /// - `y`: first row to insert at, in this surface's coordinate space.
439    /// - `n`: number of rows to insert.
440    /// - `bounds_bottom`: exclusive lower row bound for the affected region.
441    /// - `fill`: cell used to fill the newly opened rows.
442    ///
443    /// # Behavior
444    ///
445    /// The default implementation copies cells through [`Self::set_cell`]
446    /// row-by-row from the bottom up, advancing along each source row by
447    /// the source cell's width so wide-primary cells move as a unit and
448    /// their continuation columns are not independently rewritten.
449    /// Wide primaries that no longer fit are replaced by a blank.
450    /// Implementations backed by contiguous row storage may override
451    /// with a row-swap fast path.
452    ///
453    /// # Panics
454    ///
455    /// The default implementation does not panic unless [`Self::set_cell`]
456    /// panics.
457    ///
458    /// # Usage notes
459    ///
460    /// `bounds_bottom` is clamped to the surface height. Calls with
461    /// `n == 0` or `y >= bounds_bottom` are no-ops.
462    fn insert_lines(&mut self, y: u16, n: u16, bounds_bottom: u16, fill: &Cell) {
463        let h = self.bounds().height;
464        let bottom = bounds_bottom.min(h);
465        if y >= bottom || n == 0 {
466            return;
467        }
468        let n = n.min(bottom - y);
469        let width = self.bounds().width;
470        let mut dst = bottom;
471        while dst > y + n {
472            dst -= 1;
473            let src = dst - n;
474            copy_row(self, src, dst, width);
475        }
476        for row in y..y + n {
477            blank_row(self, row, width, fill);
478        }
479    }
480
481    /// Delete `n` rows at `y`, pulling existing rows up within
482    /// `[y, bounds_bottom)`. The bottom `n` rows of the window are
483    /// filled with `fill`.
484    ///
485    /// # Parameters
486    ///
487    /// - `y`: first row to delete, in this surface's coordinate space.
488    /// - `n`: number of rows to delete.
489    /// - `bounds_bottom`: exclusive lower row bound for the affected region.
490    /// - `fill`: cell used to fill the freed bottom rows.
491    ///
492    /// # Behavior
493    ///
494    /// The default implementation copies cells through [`Self::set_cell`]
495    /// row-by-row from top down, advancing along each source row by the
496    /// source cell's width so wide-primary cells move as a unit and
497    /// their continuation columns are not independently rewritten.
498    /// Wide primaries that no longer fit are replaced by a blank.
499    /// Implementations backed by contiguous row storage may override
500    /// with a row-swap fast path.
501    ///
502    /// # Panics
503    ///
504    /// The default implementation does not panic unless [`Self::set_cell`]
505    /// panics.
506    ///
507    /// # Usage notes
508    ///
509    /// `bounds_bottom` is clamped to the surface height. Calls with
510    /// `n == 0` or `y >= bounds_bottom` are no-ops.
511    fn delete_lines(&mut self, y: u16, n: u16, bounds_bottom: u16, fill: &Cell) {
512        let h = self.bounds().height;
513        let bottom = bounds_bottom.min(h);
514        if y >= bottom || n == 0 {
515            return;
516        }
517        let n = n.min(bottom - y);
518        let width = self.bounds().width;
519        for dst in y..bottom - n {
520            let src = dst + n;
521            copy_row(self, src, dst, width);
522        }
523        for row in bottom - n..bottom {
524            blank_row(self, row, width, fill);
525        }
526    }
527
528    /// Insert `n` blank cells at `pos`, pushing cells in
529    /// `[pos.x, bounds_right)` right within row `pos.y`. Cells pushed
530    /// past `bounds_right` are lost. The freed slots `[pos.x, pos.x + n)`
531    /// are filled with `fill`.
532    ///
533    /// # Parameters
534    ///
535    /// - `pos`: row and starting column for insertion.
536    /// - `n`: number of cells to insert.
537    /// - `bounds_right`: exclusive right column bound for the affected row
538    ///   region.
539    /// - `fill`: cell used to fill the newly opened slots.
540    ///
541    /// # Behavior
542    ///
543    /// The default implementation snapshots the row's primary cells in
544    /// the affected window through [`Surface::cell`], blanks the window
545    /// via [`Self::set_cell`], then replays each surviving primary at
546    /// its shifted position. Wide primaries whose new footprint would
547    /// cross `bounds_right` are dropped. Implementations backed by a
548    /// contiguous row slice may override with an in-place rotate.
549    ///
550    /// # Panics
551    ///
552    /// The default implementation does not panic unless [`Self::set_cell`]
553    /// panics.
554    ///
555    /// # Usage notes
556    ///
557    /// `bounds_right` is clamped to the surface width. Calls with `n == 0`,
558    /// an out-of-bounds row, or `pos.x >= bounds_right` are no-ops.
559    fn insert_cells(&mut self, pos: Position, n: u16, bounds_right: u16, fill: &Cell) {
560        let bounds = self.bounds();
561        if pos.y >= bounds.height || pos.x >= bounds.width || n == 0 {
562            return;
563        }
564        let right = bounds_right.min(bounds.width);
565        if pos.x >= right {
566            return;
567        }
568        let n = n.min(right - pos.x);
569
570        let primaries = collect_primaries(self, pos.y, pos.x, right);
571        blank_span(self, pos.y, pos.x, right);
572
573        for (src_x, cell) in primaries.iter().rev() {
574            let dst_x = src_x.saturating_add(n);
575            let cw = (cell.width() as u16).max(1);
576            if overruns(dst_x, cw, right) {
577                continue;
578            }
579            self.set_cell(Position::new(dst_x, pos.y), cell);
580        }
581
582        fill_span(self, pos.y, pos.x, pos.x + n, fill);
583    }
584
585    /// Delete `n` cells at `pos`, pulling cells in
586    /// `[pos.x + n, bounds_right)` left within row `pos.y`. The freed
587    /// slots `[bounds_right - n, bounds_right)` are filled with `fill`.
588    ///
589    /// # Parameters
590    ///
591    /// - `pos`: row and starting column for deletion.
592    /// - `n`: number of cells to delete.
593    /// - `bounds_right`: exclusive right column bound for the affected row
594    ///   region.
595    /// - `fill`: cell used to fill the freed right-edge slots.
596    ///
597    /// # Behavior
598    ///
599    /// The default implementation snapshots the row's primary cells in
600    /// the affected window through [`Surface::cell`], blanks the window
601    /// via [`Self::set_cell`], then replays each surviving primary at
602    /// its shifted position. Primaries whose source column falls inside
603    /// `[pos.x, pos.x + n)` are dropped. Implementations backed by a
604    /// contiguous row slice may override with an in-place rotate.
605    ///
606    /// # Panics
607    ///
608    /// The default implementation does not panic unless [`Self::set_cell`]
609    /// panics.
610    ///
611    /// # Usage notes
612    ///
613    /// `bounds_right` is clamped to the surface width. Calls with `n == 0`,
614    /// an out-of-bounds row, or `pos.x >= bounds_right` are no-ops.
615    fn delete_cells(&mut self, pos: Position, n: u16, bounds_right: u16, fill: &Cell) {
616        let bounds = self.bounds();
617        if pos.y >= bounds.height || pos.x >= bounds.width || n == 0 {
618            return;
619        }
620        let right = bounds_right.min(bounds.width);
621        if pos.x >= right {
622            return;
623        }
624        let n = n.min(right - pos.x);
625
626        let primaries = collect_primaries(self, pos.y, pos.x, right);
627        blank_span(self, pos.y, pos.x, right);
628
629        let cut = pos.x + n;
630        for (src_x, cell) in primaries.iter() {
631            if *src_x < cut {
632                continue;
633            }
634            let dst_x = src_x - n;
635            let cw = (cell.width() as u16).max(1);
636            if overruns(dst_x, cw, right) {
637                continue;
638            }
639            self.set_cell(Position::new(dst_x, pos.y), cell);
640        }
641
642        fill_span(self, pos.y, right - n, right, fill);
643    }
644}
645
646fn collect_primaries<S: SurfaceMut + ?Sized>(
647    s: &S,
648    y: u16,
649    left: u16,
650    right: u16,
651) -> Vec<(u16, Cell)> {
652    let mut out = Vec::new();
653    let mut x = left;
654    while x < right {
655        if let Some(cell) = s.cell(Position::new(x, y))
656            && !cell.is_continuation()
657        {
658            let cw = (cell.width() as u16).max(1);
659            out.push((x, cell.clone()));
660            x = x.saturating_add(cw);
661            continue;
662        }
663        x = x.saturating_add(1);
664    }
665    out
666}
667
668fn blank_span<S: SurfaceMut + ?Sized>(s: &mut S, y: u16, left: u16, right: u16) {
669    for x in left..right {
670        s.set_cell(Position::new(x, y), &Cell::BLANK);
671    }
672}
673
674fn fill_span<S: SurfaceMut + ?Sized>(s: &mut S, y: u16, left: u16, right: u16, fill: &Cell) {
675    if left >= right {
676        return;
677    }
678    let fill_w = (fill.width() as u16).max(1);
679    let mut col = left;
680    while !overruns(col, fill_w, right) {
681        s.set_cell(Position::new(col, y), fill);
682        col += fill_w;
683    }
684    while col < right {
685        s.set_cell(Position::new(col, y), &Cell::BLANK);
686        col += 1;
687    }
688}
689
690fn copy_row<S: SurfaceMut + ?Sized>(s: &mut S, src_y: u16, dst_y: u16, width: u16) {
691    let mut x: u16 = 0;
692    while x < width {
693        let src = Position::new(x, src_y);
694        let dst = Position::new(x, dst_y);
695        let Some(cell) = s.cell(src).cloned() else {
696            x += 1;
697            continue;
698        };
699        if cell.is_continuation() {
700            s.set_cell(dst, &Cell::BLANK);
701            x += 1;
702            continue;
703        }
704        let cw = (cell.width() as u16).max(1);
705        if cw > 1 && x + cw > width {
706            s.set_cell(dst, &Cell::BLANK);
707            x += 1;
708        } else {
709            s.set_cell(dst, &cell);
710            x += cw;
711        }
712    }
713}
714
715fn blank_row<S: SurfaceMut + ?Sized>(s: &mut S, y: u16, width: u16, fill: &Cell) {
716    for x in 0..width {
717        s.set_cell(Position::new(x, y), fill);
718    }
719}
720
721impl Bounded for Rect {
722    fn bounds(&self) -> Rect {
723        *self
724    }
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730    use crate::buffer::Buffer;
731    use crate::buffer::View;
732
733    #[test]
734    fn the_default_row_edits_fill_a_row_as_wide_as_the_address_space() {
735        // `Buffer` overrides both of these, so the default walks need their
736        // own cover. Both fill a freed span with a cell that can claim 255
737        // columns, and near the end of the address space the column plus
738        // that width no longer fits a `u16`.
739        let mut buf = Buffer::new(u16::MAX, 1);
740        let mut view = View::new(&mut buf, Rect::new(0, 0, u16::MAX, 1));
741        let wide = Cell::new("\u{1f468}\u{200d}\u{1f469}", 255);
742
743        view.insert_cells(Position::new(u16::MAX - 1, 0), 1, u16::MAX, &wide);
744        view.delete_cells(Position::new(0, 0), 1, u16::MAX, &wide);
745
746        assert!(!buf.cell(Position::new(u16::MAX - 1, 0)).unwrap().is_wide());
747    }
748
749    #[test]
750    fn the_default_wide_fill_spans_a_row_as_wide_as_the_address_space() {
751        // `Buffer` inlines its own copy of this walk, so the two have to
752        // agree about a row wide enough that the column plus the step no
753        // longer fits a `u16`.
754        let mut buf = Buffer::new(u16::MAX, 1);
755        let mut view = View::new(&mut buf, Rect::new(0, 0, u16::MAX, 1));
756        view.fill_rect(
757            Rect::new(0, 0, u16::MAX, 1),
758            &Cell::new("\u{1f468}\u{200d}\u{1f469}", 255),
759        );
760
761        assert!(buf.cell(Position::new(0, 0)).unwrap().is_wide());
762    }
763
764    fn wide(s: &str) -> Cell {
765        Cell::new(s, 2)
766    }
767
768    #[test]
769    fn draw_copies_normal_cells() {
770        let mut src = Buffer::new(2, 1);
771        src.set((0, 0), &Cell::new("A", 1));
772        src.set((1, 0), &Cell::new("B", 1));
773        let mut dst = Buffer::new(4, 1);
774        src.draw(&mut dst, Position::new(1, 0));
775        assert_eq!(dst.cell(Position::new(0, 0)).unwrap().content(), " ");
776        assert_eq!(dst.cell(Position::new(1, 0)).unwrap().content(), "A");
777        assert_eq!(dst.cell(Position::new(2, 0)).unwrap().content(), "B");
778    }
779
780    #[test]
781    fn draw_preserves_wide_pair() {
782        let mut src = Buffer::new(2, 1);
783        src.set((0, 0), &wide("世"));
784        // Buffer::set already wrote the continuation at (1,0).
785        let mut dst = Buffer::new(2, 1);
786        src.draw(&mut dst, Position::new(0, 0));
787        let primary = dst.cell(Position::new(0, 0)).unwrap();
788        let cont_cell = dst.cell(Position::new(1, 0)).unwrap();
789        assert_eq!(primary.content(), "世");
790        assert_eq!(primary.width(), 2);
791        assert!(cont_cell.is_continuation());
792    }
793
794    #[test]
795    fn draw_blanks_leading_continuation_in_source_slice() {
796        // Construct a source whose first column is the orphan
797        // continuation half of a wide cell that lives outside the
798        // slice. The default must not propagate the orphan.
799        let mut src = Buffer::new(3, 1);
800        src.set((0, 0), &wide("世"));
801        src.set((2, 0), &Cell::new("X", 1));
802        let src = View::new(&mut src, Rect::new(1, 0, 2, 1));
803
804        let mut dst = Buffer::new(2, 1);
805        // Seed the target with nonblank cells so a skipped write is visible.
806        dst.set((0, 0), &Cell::new("Y", 1));
807        dst.set((1, 0), &Cell::new("Z", 1));
808
809        src.draw(&mut dst, Position::new(0, 0));
810
811        // The orphan continuation became a blank — no spurious
812        // continuation marker carried over.
813        assert!(!dst.cell(Position::new(0, 0)).unwrap().is_continuation());
814        assert_eq!(dst.cell(Position::new(0, 0)).unwrap().content(), " ");
815        assert_eq!(dst.cell(Position::new(1, 0)).unwrap().content(), "X");
816    }
817
818    #[test]
819    fn draw_blanks_wide_primary_with_no_room_in_target() {
820        // Wide primary lands at the last column of the target — its
821        // continuation would fall outside target bounds. Substitute
822        // a blank rather than emitting a half-drawn grapheme.
823        let mut src = Buffer::new(2, 1);
824        src.set((0, 0), &wide("世"));
825
826        let mut dst = Buffer::new(2, 1);
827        src.draw(&mut dst, Position::new(1, 0));
828
829        let landed = dst.cell(Position::new(1, 0)).unwrap();
830        assert_eq!(landed.content(), " ");
831        assert_eq!(landed.width(), 1);
832    }
833
834    #[test]
835    fn draw_clears_a_wide_cell_clipped_by_the_target_left_edge() {
836        use crate::buffer::View;
837
838        for (text, width) in [("中", 2), ("👩‍👩", 4), ("👩‍👩‍👧‍👦", 8)] {
839            let cell = Cell::new(text, width);
840            let width = u16::from(width);
841            for origin in [Position::ORIGIN, Position::new(2, 1)] {
842                let mut source = Buffer::new(origin.x + width + 1, origin.y + 1);
843                source.set(origin, &cell);
844                source.set((origin.x + width, origin.y), &Cell::new("M", 1));
845                let source = View::new(&mut source, Rect::new(origin.x, origin.y, width + 1, 1));
846
847                for at in [Position::ORIGIN, Position::new(3, 2)] {
848                    for clipped in 0..=width {
849                        let mut target = Buffer::new(at.x + width + 2, at.y + 2);
850                        target.fill(&Cell::new("Z", 1));
851                        let mut expected = target.clone();
852                        for x in at.x + clipped..at.x + width {
853                            expected.set((x, at.y), &Cell::BLANK);
854                        }
855                        if clipped == 0 {
856                            expected.set(at, &cell);
857                        }
858                        expected.set((at.x + width, at.y), &Cell::new("M", 1));
859
860                        let mut view = View::new(
861                            &mut target,
862                            Rect::new(at.x + clipped, at.y, width + 1 - clipped, 1),
863                        );
864                        source.draw(&mut view, at);
865
866                        for y in 0..target.height() {
867                            assert_eq!(
868                                target.line(y),
869                                expected.line(y),
870                                "width {width}, clipped {clipped}, origin {origin:?}, at {at:?}, row {y}",
871                            );
872                        }
873                    }
874                }
875            }
876        }
877    }
878
879    // The remaining tests exercise the SurfaceMut default implementations
880    // of insert/delete lines and insert/delete cells via Window, which
881    // does not override them.
882    use crate::buffer::Window;
883
884    fn window_with(content: &[&str]) -> Window {
885        let w = content[0].chars().count() as u16;
886        let h = content.len() as u16;
887        let mut win = Window::new(w, h);
888        for (y, row) in content.iter().enumerate() {
889            for (x, ch) in row.chars().enumerate() {
890                win.set_cell(
891                    Position::new(x as u16, y as u16),
892                    &Cell::new(ch.to_string(), 1),
893                );
894            }
895        }
896        win
897    }
898
899    fn row_content(win: &Window, y: u16) -> String {
900        (0..win.bounds().width)
901            .map(|x| {
902                win.cell(Position::new(x, y))
903                    .map(|c| c.content().to_string())
904                    .unwrap_or_default()
905            })
906            .collect()
907    }
908
909    #[test]
910    fn default_insert_lines_shifts_down_and_blanks_top() {
911        let mut win = window_with(&["AAA", "BBB", "CCC", "DDD"]);
912        SurfaceMut::insert_lines(&mut win, 1, 1, 4, &Cell::BLANK);
913        assert_eq!(row_content(&win, 0), "AAA");
914        assert_eq!(row_content(&win, 1), "   ");
915        assert_eq!(row_content(&win, 2), "BBB");
916        assert_eq!(row_content(&win, 3), "CCC");
917    }
918
919    #[test]
920    fn default_delete_lines_pulls_up_and_blanks_bottom() {
921        let mut win = window_with(&["AAA", "BBB", "CCC", "DDD"]);
922        SurfaceMut::delete_lines(&mut win, 1, 1, 4, &Cell::BLANK);
923        assert_eq!(row_content(&win, 0), "AAA");
924        assert_eq!(row_content(&win, 1), "CCC");
925        assert_eq!(row_content(&win, 2), "DDD");
926        assert_eq!(row_content(&win, 3), "   ");
927    }
928
929    #[test]
930    fn default_insert_cells_shifts_right_and_blanks_left() {
931        let mut win = window_with(&["ABCDE"]);
932        SurfaceMut::insert_cells(&mut win, Position::new(1, 0), 2, 5, &Cell::BLANK);
933        assert_eq!(row_content(&win, 0), "A  BC");
934    }
935
936    #[test]
937    fn default_delete_cells_pulls_left_and_blanks_right() {
938        let mut win = window_with(&["ABCDE"]);
939        SurfaceMut::delete_cells(&mut win, Position::new(1, 0), 2, 5, &Cell::BLANK);
940        assert_eq!(row_content(&win, 0), "ADE  ");
941    }
942
943    #[test]
944    fn default_insert_cells_preserves_wide_that_still_fits() {
945        // Row: A 世(prim) 世(cont) B, then insert 1 at col 1 with right=4.
946        // 世's new primary would be at col 2, continuation at col 3.
947        // That still fits (col 3 < right=4). So 世 is preserved.
948        let mut win = Window::new(4, 1);
949        win.set_cell(Position::new(0, 0), &Cell::new("A", 1));
950        win.set_cell(Position::new(1, 0), &wide("世"));
951        win.set_cell(Position::new(3, 0), &Cell::new("B", 1));
952        SurfaceMut::insert_cells(&mut win, Position::new(1, 0), 1, 4, &Cell::BLANK);
953
954        assert_eq!(win.cell(Position::new(0, 0)).unwrap().content(), "A");
955        assert_eq!(win.cell(Position::new(1, 0)).unwrap().content(), " ");
956        assert_eq!(win.cell(Position::new(2, 0)).unwrap().content(), "世");
957        assert!(win.cell(Position::new(3, 0)).unwrap().is_continuation());
958    }
959
960    #[test]
961    fn default_insert_cells_blanks_wide_that_overflows() {
962        // Row: A B 世(prim) 世(cont), then insert 1 at col 1 with right=4.
963        // 世 would move from col 2 to col 3, continuation to col 4 (out).
964        // So 世 must be dropped, leaving a blank at col 3.
965        let mut win = Window::new(4, 1);
966        win.set_cell(Position::new(0, 0), &Cell::new("A", 1));
967        win.set_cell(Position::new(1, 0), &Cell::new("B", 1));
968        win.set_cell(Position::new(2, 0), &wide("世"));
969        SurfaceMut::insert_cells(&mut win, Position::new(1, 0), 1, 4, &Cell::BLANK);
970
971        assert_eq!(win.cell(Position::new(0, 0)).unwrap().content(), "A");
972        assert_eq!(win.cell(Position::new(1, 0)).unwrap().content(), " ");
973        assert_eq!(win.cell(Position::new(2, 0)).unwrap().content(), "B");
974        assert_eq!(win.cell(Position::new(3, 0)).unwrap().content(), " ");
975    }
976
977    #[test]
978    fn default_delete_cells_drops_primary_in_deletion_window() {
979        // Row: A 世(prim) 世(cont) B, delete 2 at col 1 with right=4.
980        // 世's primary falls inside [1, 3) → dropped entirely.
981        let mut win = Window::new(4, 1);
982        win.set_cell(Position::new(0, 0), &Cell::new("A", 1));
983        win.set_cell(Position::new(1, 0), &wide("世"));
984        win.set_cell(Position::new(3, 0), &Cell::new("B", 1));
985        SurfaceMut::delete_cells(&mut win, Position::new(1, 0), 2, 4, &Cell::BLANK);
986
987        assert_eq!(win.cell(Position::new(0, 0)).unwrap().content(), "A");
988        assert_eq!(win.cell(Position::new(1, 0)).unwrap().content(), "B");
989        assert_eq!(win.cell(Position::new(2, 0)).unwrap().content(), " ");
990        assert_eq!(win.cell(Position::new(3, 0)).unwrap().content(), " ");
991    }
992}