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
//! Cursor/glyph emission helpers.
//!
//! Routines that the diff loop and other phases use to
//! relocate the cursor and to push glyph bytes through the right-margin
//! phantom and lower-right corner edge cases.
use std::io;
use crate::ansi;
use crate::layout::{Position, Size};
use crate::renderer::Renderer;
use crate::renderer::buffer::RenderBuffer;
/// What a cursor move is allowed to do to the active pen.
///
/// An inline downward move is emitted as literal `\n`, which scrolls the
/// host when the target row does not exist yet. Under back-color erase
/// that scroll paints the freshly exposed row with the pen's background.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PenPolicy {
/// Reset the pen before a `\n` that can scroll, so the exposed row
/// is erased with the terminal's default background — which is what
/// an untouched row in `cur_buf` claims. The default.
ResetBeforeScroll,
/// Leave the pen alone: the caller is about to erase or scroll with
/// it deliberately and records the resulting fill itself.
Keep,
}
impl Renderer {
/// Move cursor to the given position. Runs all the pre-move
/// bookkeeping (width autowrap, phantom-cell snap, height clamp,
/// no-op shortcut), then defers the actual emission to
/// [`Renderer::move_cursor`] so the destination row is available
/// for overwrite consideration.
///
/// May reset the pen: an inline downward move is emitted as a
/// literal `\n` that can scroll the host, and under back-color
/// erase the exposed row would otherwise keep the active
/// background. Callers that erase or scroll with the active pen
/// deliberately want [`Renderer::move_to_keeping_pen`].
///
/// Most callers want this. Callers that have already done the
/// bookkeeping and need to skip it can call
/// [`Renderer::move_cursor`] or [`Renderer::move_cursor_to`]
/// directly.
pub(crate) fn move_to(
&mut self,
out: &mut Vec<u8>,
buf: &RenderBuffer,
y: u16,
x: u16,
) -> io::Result<()> {
self.move_to_with_pen(out, Some(buf), y, x, PenPolicy::ResetBeforeScroll)
}
/// Like [`Renderer::move_to`], but plans over no cell contents, and
/// measures the move against `size` rather than the last rendered frame.
///
/// For a caller moving the cursor *between* frames rather than during a
/// diff. Two things separate that caller from the diff loop.
///
/// The planner can pay for a short forward move by re-emitting the cells
/// it passes over, which is only sound when those cells are what the
/// terminal currently shows. Inside the diff loop they are: a move there
/// targets a column the transform has proven equal between the tracked
/// and the new line. Between frames nothing establishes that — the
/// desired grid can hold an edit that has not been rendered, or a whole
/// frame belonging to the other screen buffer — and the planner does not
/// record the cells it re-emits in the tracked buffer, so the divergence
/// it creates is never diffed away. Withholding the row makes that
/// unrepresentable rather than guarded, and costs nothing: a resting
/// cursor is essentially never reached by a forward move short enough for
/// the overwrite candidate to win.
///
/// `size` is the surface the wrap and the clamp are measured against. The
/// renderer's own size is whatever it last rendered, which is what a move
/// inside a frame wants; between a resize and the frame that answers it
/// the caller's is the newer one, and measuring against the stale one
/// wraps a column that now fits and clamps to a row that no longer
/// exists, landing somewhere the caller never named.
pub(crate) fn move_to_between_frames(
&mut self,
out: &mut Vec<u8>,
size: Size,
y: u16,
x: u16,
) -> io::Result<()> {
self.move_to_sized(
out,
None,
size.width,
size.height,
y,
x,
PenPolicy::ResetBeforeScroll,
)
}
/// Like [`Renderer::move_to`], but leaves the pen alone.
///
/// For callers that immediately follow the move with an erase or
/// scroll which is *meant* to fill with the active pen, and which
/// record that fill in `cur_buf` themselves — the scroll emitters in
/// [`crate::renderer::scroll`] and
/// [`Renderer::clear_to_bottom`]. Resetting the pen underneath them
/// would erase with the default background while the frame model
/// recorded the styled one, which is the very divergence
/// [`PenPolicy::ResetBeforeScroll`] exists to prevent.
pub(crate) fn move_to_keeping_pen(
&mut self,
out: &mut Vec<u8>,
buf: &RenderBuffer,
y: u16,
x: u16,
) -> io::Result<()> {
self.move_to_with_pen(out, Some(buf), y, x, PenPolicy::Keep)
}
/// Measures the move against the last rendered size, which is what a
/// caller inside a frame wants: the frame being diffed is that size.
fn move_to_with_pen(
&mut self,
out: &mut Vec<u8>,
buf: Option<&RenderBuffer>,
y: u16,
x: u16,
pen: PenPolicy,
) -> io::Result<()> {
self.move_to_sized(out, buf, self.last_width, self.last_height, y, x, pen)
}
#[allow(clippy::too_many_arguments)]
fn move_to_sized(
&mut self,
out: &mut Vec<u8>,
buf: Option<&RenderBuffer>,
width: u16,
height: u16,
y: u16,
x: u16,
pen: PenPolicy,
) -> io::Result<()> {
let mut y = y;
let mut x = x;
// A target that exceeds the surface width is treated as a
// wrap: y += x / width, x %= width. Keeps the cursor model
// consistent with autowrap-on terminals.
if width > 0 && x >= width {
y = y.saturating_add(x / width);
x %= width;
}
// Right-margin phantom: the terminal cursor is in the last
// column with the pending-wrap flag set, but our tracked
// column is one past the last column. A bare `\r` resyncs.
if self.cur.at_phantom {
out.push(b'\r');
self.cur.x = Some(0);
self.cur.at_phantom = false;
}
// Clamp the target to the surface height: we may be mid-resize
// and `height` could already reflect the new size. The
// tracked source position is left untouched — when it sits
// outside the new bounds (e.g. a finalize-snapped cursor at
// the bottom of the previous, taller surface), the relative
// move planner must still emit the full CUU back to the new
// bounds. Clamping the source would silently drop those rows
// and leave the physical cursor below where the renderer
// believes it is, leaving stale content above the new surface
// on inline shrinks.
if height > 0 {
let max_y = height - 1;
if y > max_y {
y = max_y;
}
}
if self.cur.x == Some(x) && self.cur.y == Some(y) {
return Ok(());
}
self.move_cursor_with_pen(out, buf, y, x, pen)
}
/// Emit a cursor move using the destination row's cells from
/// `buf` for overwrite consideration. The bare wrapper for
/// `move_to`: handles only the inline-mode initial `\r` snap,
/// then defers to the optimal-move planner. Use
/// [`Renderer::move_to`] unless you already handled the
/// pre-move bookkeeping yourself.
///
/// Test-only convenience wrapper: production callers reach the
/// planner through [`Renderer::move_to`] so the pen policy is
/// always stated explicitly.
#[cfg(test)]
pub(crate) fn move_cursor(
&mut self,
out: &mut Vec<u8>,
buf: &RenderBuffer,
y: u16,
x: u16,
) -> io::Result<()> {
self.move_cursor_with_pen(out, Some(buf), y, x, PenPolicy::ResetBeforeScroll)
}
fn move_cursor_with_pen(
&mut self,
out: &mut Vec<u8>,
buf: Option<&RenderBuffer>,
y: u16,
x: u16,
pen: PenPolicy,
) -> io::Result<()> {
// Inline mode + cursor fully unknown on both axes: snap to
// column 0 with a bare `\r` so the relative move below has a
// deterministic starting column. The row stays unknown until
// the planner emits a vertical step. Fullscreen mode handles
// the same condition by emitting absolute CUP from the
// planner.
if !self.fullscreen && self.relative_cursor && self.cur.x.is_none() && self.cur.y.is_none()
{
out.push(b'\r');
// Re-home the column and assume the current physical row is the
// top of the surface, so the relative move below only ever steps
// downward — it can never CUU above a reflowed/handed-off cursor.
self.cur.x = Some(0);
self.cur.y = Some(0);
}
let target = Position { x, y };
let line = buf.and_then(|buf| buf.line(y));
self.write_optimal_move_with_pen(out, self.cur.pos(), target, line, pen)?;
self.cur.set_pos(target);
Ok(())
}
/// Mark the tracked cursor position as no longer matching the
/// terminal on either axis. The next [`Renderer::move_to`]
/// reasserts position.
pub(crate) fn invalidate_cursor(&mut self) {
self.cur.x = None;
self.cur.y = None;
}
/// Write a single grapheme to the output buffer, handling the
/// right-margin auto-wrap "phantom" state and protecting the lower
/// right corner from triggering an unwanted scroll in fullscreen mode.
///
/// Returns whether the cell was written. `width` here is the buffer
/// width — the column count of the surface we render into.
pub(crate) fn put_glyph_bytes(
&mut self,
out: &mut Vec<u8>,
content: &[u8],
cell_width: u16,
surface_width: u16,
surface_height: u16,
) -> io::Result<()> {
if cell_width == 0 {
return Ok(());
}
// If we are sitting in the right-margin phantom cell from a prior
// write, advancing the cursor before writing this glyph would
// happen via terminal auto-wrap. We don't want to depend on that
// implicit behavior — emit an explicit move to the start of the
// next row so the result is the same on every terminal.
if self.cur.at_phantom {
let next_y = self.cur.pos().y.saturating_add(1);
if next_y < surface_height {
let target = Position { y: next_y, x: 0 };
self.write_optimal_move(out, self.cur.pos(), target, None)?;
self.cur.set_pos(target);
}
self.cur.at_phantom = false;
}
// True lower-right corner: cursor sitting at (width-1, height-1)
// with a single-column cell about to be written. Multi-column
// cells that merely *reach* the last column don't apply — a
// width-2 cell starting at width-2 occupies the last column but
// the cursor itself is at width-2, not width-1, so writing it
// doesn't trigger the bottom-right scroll quirk.
let is_lower_right_corner = self.fullscreen
&& cell_width == 1
&& self.cur.pos().x + 1 == surface_width
&& self.cur.pos().y + 1 == surface_height;
if is_lower_right_corner {
// Writing the bottom-right corner in alt-screen normally pushes
// the cursor into pending-wrap. The very next emission (or
// sometimes even the next CSI) can then provoke an auto-wrap
// that scrolls the alt screen up by one row. Disable auto-wrap
// for just this glyph and restore it immediately.
ansi::mode::Mode::AUTO_WRAP.reset(out)?;
out.extend_from_slice(content);
ansi::mode::Mode::AUTO_WRAP.set(out)?;
// Cursor stays at the corner — explicitly. No phantom.
// (Some terminals leave it at width-1, others at width; treat
// it as width-1 since auto-wrap is now off and a subsequent
// print would just overwrite the same cell.)
self.cur.x = Some(surface_width.saturating_sub(1));
self.cur.at_phantom = false;
return Ok(());
}
out.extend_from_slice(content);
let new_x = self.cur.pos().x.saturating_add(cell_width);
if new_x >= surface_width {
// Park at the right-margin phantom; clamp tracked column so it
// doesn't drift past `surface_width` over successive writes.
self.cur.x = Some(surface_width);
self.cur.at_phantom = true;
} else {
self.cur.x = Some(new_x);
}
Ok(())
}
}