| 1 |
package cellbuf |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"errors" |
| 6 |
"io" |
| 7 |
"os" |
| 8 |
"strings" |
| 9 |
"sync" |
| 10 |
|
| 11 |
"github.com/charmbracelet/colorprofile" |
| 12 |
"github.com/charmbracelet/x/ansi" |
| 13 |
"github.com/charmbracelet/x/term" |
| 14 |
) |
| 15 |
|
| 16 |
// ErrInvalidDimensions is returned when the dimensions of a window are invalid |
| 17 |
// for the operation. |
| 18 |
var ErrInvalidDimensions = errors.New("invalid dimensions") |
| 19 |
|
| 20 |
// notLocal returns whether the coordinates are not considered local movement |
| 21 |
// using the defined thresholds. |
| 22 |
// This takes the number of columns, and the coordinates of the current and |
| 23 |
// target positions. |
| 24 |
func notLocal(cols, fx, fy, tx, ty int) bool { |
| 25 |
// The typical distance for a [ansi.CUP] sequence. Anything less than this |
| 26 |
// is considered local movement. |
| 27 |
const longDist = 8 - 1 |
| 28 |
return (tx > longDist) && |
| 29 |
(tx < cols-1-longDist) && |
| 30 |
(abs(ty-fy)+abs(tx-fx) > longDist) |
| 31 |
} |
| 32 |
|
| 33 |
// relativeCursorMove returns the relative cursor movement sequence using one or two |
| 34 |
// of the following sequences [ansi.CUU], [ansi.CUD], [ansi.CUF], [ansi.CUB], |
| 35 |
// [ansi.VPA], [ansi.HPA]. |
| 36 |
// When overwrite is true, this will try to optimize the sequence by using the |
| 37 |
// screen cells values to move the cursor instead of using escape sequences. |
| 38 |
func relativeCursorMove(s *Screen, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) string { |
| 39 |
var seq strings.Builder |
| 40 |
|
| 41 |
width, height := s.newbuf.Width(), s.newbuf.Height() |
| 42 |
if ty != fy { //nolint:nestif |
| 43 |
var yseq string |
| 44 |
if s.caps.Contains(capVPA) && !s.opts.RelativeCursor { |
| 45 |
yseq = ansi.VerticalPositionAbsolute(ty + 1) |
| 46 |
} |
| 47 |
|
| 48 |
// OPTIM: Use [ansi.LF] and [ansi.ReverseIndex] as optimizations. |
| 49 |
|
| 50 |
if ty > fy { |
| 51 |
n := ty - fy |
| 52 |
if cud := ansi.CursorDown(n); yseq == "" || len(cud) < len(yseq) { |
| 53 |
yseq = cud |
| 54 |
} |
| 55 |
shouldScroll := !s.opts.AltScreen && fy+n >= s.scrollHeight |
| 56 |
if lf := strings.Repeat("\n", n); shouldScroll || (fy+n < height && len(lf) < len(yseq)) { |
| 57 |
//nolint:godox |
| 58 |
// TODO: Ensure we're not unintentionally scrolling the screen down. |
| 59 |
yseq = lf |
| 60 |
s.scrollHeight = max(s.scrollHeight, fy+n) |
| 61 |
if s.opts.MapNL { |
| 62 |
fx = 0 |
| 63 |
} |
| 64 |
} |
| 65 |
} else if ty < fy { |
| 66 |
n := fy - ty |
| 67 |
if cuu := ansi.CursorUp(n); yseq == "" || len(cuu) < len(yseq) { |
| 68 |
yseq = cuu |
| 69 |
} |
| 70 |
if n == 1 && fy-1 > 0 { |
| 71 |
//nolint:godox |
| 72 |
// TODO: Ensure we're not unintentionally scrolling the screen up. |
| 73 |
yseq = ansi.ReverseIndex |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
seq.WriteString(yseq) |
| 78 |
} |
| 79 |
|
| 80 |
if tx != fx { //nolint:nestif |
| 81 |
var xseq string |
| 82 |
if s.caps.Contains(capHPA) && !s.opts.RelativeCursor { |
| 83 |
xseq = ansi.HorizontalPositionAbsolute(tx + 1) |
| 84 |
} |
| 85 |
|
| 86 |
if tx > fx { |
| 87 |
n := tx - fx |
| 88 |
if useTabs { |
| 89 |
var tabs int |
| 90 |
var col int |
| 91 |
for col = fx; s.tabs.Next(col) <= tx; col = s.tabs.Next(col) { |
| 92 |
tabs++ |
| 93 |
if col == s.tabs.Next(col) || col >= width-1 { |
| 94 |
break |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
if tabs > 0 { |
| 99 |
cht := ansi.CursorHorizontalForwardTab(tabs) |
| 100 |
tab := strings.Repeat("\t", tabs) |
| 101 |
if false && s.caps.Contains(capCHT) && len(cht) < len(tab) { |
| 102 |
//nolint:godox |
| 103 |
// TODO: The linux console and some terminals such as |
| 104 |
// Alacritty don't support [ansi.CHT]. Enable this when |
| 105 |
// we have a way to detect this, or after 5 years when |
| 106 |
// we're sure everyone has updated their terminals :P |
| 107 |
seq.WriteString(cht) |
| 108 |
} else { |
| 109 |
seq.WriteString(tab) |
| 110 |
} |
| 111 |
|
| 112 |
n = tx - col |
| 113 |
fx = col |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
if cuf := ansi.CursorForward(n); xseq == "" || len(cuf) < len(xseq) { |
| 118 |
xseq = cuf |
| 119 |
} |
| 120 |
|
| 121 |
// If we have no attribute and style changes, overwrite is cheaper. |
| 122 |
var ovw string |
| 123 |
if overwrite && ty >= 0 { |
| 124 |
for i := 0; i < n; i++ { |
| 125 |
cell := s.newbuf.Cell(fx+i, ty) |
| 126 |
if cell != nil && cell.Width > 0 { |
| 127 |
i += cell.Width - 1 |
| 128 |
if !cell.Style.Equal(&s.cur.Style) || !cell.Link.Equal(&s.cur.Link) { |
| 129 |
overwrite = false |
| 130 |
break |
| 131 |
} |
| 132 |
} |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
if overwrite && ty >= 0 { |
| 137 |
for i := 0; i < n; i++ { |
| 138 |
cell := s.newbuf.Cell(fx+i, ty) |
| 139 |
if cell != nil && cell.Width > 0 { |
| 140 |
ovw += cell.String() |
| 141 |
i += cell.Width - 1 |
| 142 |
} else { |
| 143 |
ovw += " " |
| 144 |
} |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
if overwrite && len(ovw) < len(xseq) { |
| 149 |
xseq = ovw |
| 150 |
} |
| 151 |
} else if tx < fx { |
| 152 |
n := fx - tx |
| 153 |
if useTabs && s.caps.Contains(capCBT) { |
| 154 |
// VT100 does not support backward tabs [ansi.CBT]. |
| 155 |
|
| 156 |
col := fx |
| 157 |
|
| 158 |
var cbt int // cursor backward tabs count |
| 159 |
for s.tabs.Prev(col) >= tx { |
| 160 |
col = s.tabs.Prev(col) |
| 161 |
cbt++ |
| 162 |
if col == s.tabs.Prev(col) || col <= 0 { |
| 163 |
break |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
if cbt > 0 { |
| 168 |
seq.WriteString(ansi.CursorBackwardTab(cbt)) |
| 169 |
n = col - tx |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
if cub := ansi.CursorBackward(n); xseq == "" || len(cub) < len(xseq) { |
| 174 |
xseq = cub |
| 175 |
} |
| 176 |
|
| 177 |
if useBackspace && n < len(xseq) { |
| 178 |
xseq = strings.Repeat("\b", n) |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
seq.WriteString(xseq) |
| 183 |
} |
| 184 |
|
| 185 |
return seq.String() |
| 186 |
} |
| 187 |
|
| 188 |
// moveCursor moves and returns the cursor movement sequence to move the cursor |
| 189 |
// to the specified position. |
| 190 |
// When overwrite is true, this will try to optimize the sequence by using the |
| 191 |
// screen cells values to move the cursor instead of using escape sequences. |
| 192 |
func moveCursor(s *Screen, x, y int, overwrite bool) (seq string) { |
| 193 |
fx, fy := s.cur.X, s.cur.Y |
| 194 |
|
| 195 |
if !s.opts.RelativeCursor { |
| 196 |
// Method #0: Use [ansi.CUP] if the distance is long. |
| 197 |
seq = ansi.CursorPosition(x+1, y+1) |
| 198 |
if fx == -1 || fy == -1 || notLocal(s.newbuf.Width(), fx, fy, x, y) { |
| 199 |
return seq |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
// Optimize based on options. |
| 204 |
trials := 0 |
| 205 |
if s.opts.HardTabs { |
| 206 |
trials |= 2 // 0b10 in binary |
| 207 |
} |
| 208 |
if s.opts.Backspace { |
| 209 |
trials |= 1 // 0b01 in binary |
| 210 |
} |
| 211 |
|
| 212 |
// Try all possible combinations of hard tabs and backspace optimizations. |
| 213 |
for i := 0; i <= trials; i++ { |
| 214 |
// Skip combinations that are not enabled. |
| 215 |
if i & ^trials != 0 { |
| 216 |
continue |
| 217 |
} |
| 218 |
|
| 219 |
useHardTabs := i&2 != 0 |
| 220 |
useBackspace := i&1 != 0 |
| 221 |
|
| 222 |
// Method #1: Use local movement sequences. |
| 223 |
nseq := relativeCursorMove(s, fx, fy, x, y, overwrite, useHardTabs, useBackspace) |
| 224 |
if (i == 0 && len(seq) == 0) || len(nseq) < len(seq) { |
| 225 |
seq = nseq |
| 226 |
} |
| 227 |
|
| 228 |
// Method #2: Use [ansi.CR] and local movement sequences. |
| 229 |
nseq = "\r" + relativeCursorMove(s, 0, fy, x, y, overwrite, useHardTabs, useBackspace) |
| 230 |
if len(nseq) < len(seq) { |
| 231 |
seq = nseq |
| 232 |
} |
| 233 |
|
| 234 |
if !s.opts.RelativeCursor { |
| 235 |
// Method #3: Use [ansi.CursorHomePosition] and local movement sequences. |
| 236 |
nseq = ansi.CursorHomePosition + relativeCursorMove(s, 0, 0, x, y, overwrite, useHardTabs, useBackspace) |
| 237 |
if len(nseq) < len(seq) { |
| 238 |
seq = nseq |
| 239 |
} |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
return seq |
| 244 |
} |
| 245 |
|
| 246 |
// moveCursor moves the cursor to the specified position. |
| 247 |
func (s *Screen) moveCursor(x, y int, overwrite bool) { |
| 248 |
if !s.opts.AltScreen && s.cur.X == -1 && s.cur.Y == -1 { |
| 249 |
// First cursor movement in inline mode, move the cursor to the first |
| 250 |
// column before moving to the target position. |
| 251 |
s.buf.WriteByte('\r') |
| 252 |
s.cur.X, s.cur.Y = 0, 0 |
| 253 |
} |
| 254 |
s.buf.WriteString(moveCursor(s, x, y, overwrite)) |
| 255 |
s.cur.X, s.cur.Y = x, y |
| 256 |
} |
| 257 |
|
| 258 |
func (s *Screen) move(x, y int) { |
| 259 |
// XXX: Make sure we use the max height and width of the buffer in case |
| 260 |
// we're in the middle of a resize operation. |
| 261 |
width := max(s.newbuf.Width(), s.curbuf.Width()) |
| 262 |
height := max(s.newbuf.Height(), s.curbuf.Height()) |
| 263 |
|
| 264 |
if width > 0 && x >= width { |
| 265 |
// Handle autowrap |
| 266 |
y += (x / width) |
| 267 |
x %= width |
| 268 |
} |
| 269 |
|
| 270 |
// XXX: Disable styles if there's any |
| 271 |
// Some move operations such as [ansi.LF] can apply styles to the new |
| 272 |
// cursor position, thus, we need to reset the styles before moving the |
| 273 |
// cursor. |
| 274 |
blank := s.clearBlank() |
| 275 |
resetPen := y != s.cur.Y && !blank.Equal(&BlankCell) |
| 276 |
if resetPen { |
| 277 |
s.updatePen(nil) |
| 278 |
} |
| 279 |
|
| 280 |
// Reset wrap around (phantom cursor) state |
| 281 |
if s.atPhantom { |
| 282 |
s.cur.X = 0 |
| 283 |
s.buf.WriteByte('\r') |
| 284 |
s.atPhantom = false // reset phantom cell state |
| 285 |
} |
| 286 |
|
| 287 |
//nolint:godox |
| 288 |
// TODO: Investigate if we need to handle this case and/or if we need the |
| 289 |
// following code. |
| 290 |
// |
| 291 |
// if width > 0 && s.cur.X >= width { |
| 292 |
// l := (s.cur.X + 1) / width |
| 293 |
// |
| 294 |
// s.cur.Y += l |
| 295 |
// if height > 0 && s.cur.Y >= height { |
| 296 |
// l -= s.cur.Y - height - 1 |
| 297 |
// } |
| 298 |
// |
| 299 |
// if l > 0 { |
| 300 |
// s.cur.X = 0 |
| 301 |
// s.buf.WriteString("\r" + strings.Repeat("\n", l)) |
| 302 |
// } |
| 303 |
// } |
| 304 |
|
| 305 |
if height > 0 { |
| 306 |
if s.cur.Y > height-1 { |
| 307 |
s.cur.Y = height - 1 |
| 308 |
} |
| 309 |
if y > height-1 { |
| 310 |
y = height - 1 |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
if x == s.cur.X && y == s.cur.Y { |
| 315 |
// We give up later because we need to run checks for the phantom cell |
| 316 |
// and others before we can determine if we can give up. |
| 317 |
return |
| 318 |
} |
| 319 |
|
| 320 |
// We set the new cursor in [Screen.moveCursor]. |
| 321 |
s.moveCursor(x, y, true) // Overwrite cells if possible |
| 322 |
} |
| 323 |
|
| 324 |
// Cursor represents a terminal Cursor. |
| 325 |
type Cursor struct { |
| 326 |
Style |
| 327 |
Link |
| 328 |
Position |
| 329 |
} |
| 330 |
|
| 331 |
// ScreenOptions are options for the screen. |
| 332 |
type ScreenOptions struct { |
| 333 |
// Term is the terminal type to use when writing to the screen. When empty, |
| 334 |
// `$TERM` is used from [os.Getenv]. |
| 335 |
Term string |
| 336 |
// Profile is the color profile to use when writing to the screen. |
| 337 |
Profile colorprofile.Profile |
| 338 |
// RelativeCursor is whether to use relative cursor movements. This is |
| 339 |
// useful when alt-screen is not used or when using inline mode. |
| 340 |
RelativeCursor bool |
| 341 |
// AltScreen is whether to use the alternate screen buffer. |
| 342 |
AltScreen bool |
| 343 |
// ShowCursor is whether to show the cursor. |
| 344 |
ShowCursor bool |
| 345 |
// HardTabs is whether to use hard tabs to optimize cursor movements. |
| 346 |
HardTabs bool |
| 347 |
// Backspace is whether to use backspace characters to move the cursor. |
| 348 |
Backspace bool |
| 349 |
// MapNL whether we have ONLCR mapping enabled. When we set the terminal to |
| 350 |
// raw mode, the ONLCR mode gets disabled. ONLCR maps any newline/linefeed |
| 351 |
// (`\n`) character to carriage return + line feed (`\r\n`). |
| 352 |
MapNL bool |
| 353 |
} |
| 354 |
|
| 355 |
// lineData represents the metadata for a line. |
| 356 |
type lineData struct { |
| 357 |
// first and last changed cell indices |
| 358 |
firstCell, lastCell int |
| 359 |
// old index used for scrolling |
| 360 |
oldIndex int //nolint:unused |
| 361 |
} |
| 362 |
|
| 363 |
// Screen represents the terminal screen. |
| 364 |
type Screen struct { |
| 365 |
w io.Writer |
| 366 |
buf *bytes.Buffer // buffer for writing to the screen |
| 367 |
curbuf *Buffer // the current buffer |
| 368 |
newbuf *Buffer // the new buffer |
| 369 |
tabs *TabStops |
| 370 |
touch map[int]lineData |
| 371 |
queueAbove []string // the queue of strings to write above the screen |
| 372 |
oldhash, newhash []uint64 // the old and new hash values for each line |
| 373 |
hashtab []hashmap // the hashmap table |
| 374 |
oldnum []int // old indices from previous hash |
| 375 |
cur, saved Cursor // the current and saved cursors |
| 376 |
opts ScreenOptions |
| 377 |
mu sync.Mutex |
| 378 |
method ansi.Method |
| 379 |
scrollHeight int // keeps track of how many lines we've scrolled down (inline mode) |
| 380 |
altScreenMode bool // whether alternate screen mode is enabled |
| 381 |
cursorHidden bool // whether text cursor mode is enabled |
| 382 |
clear bool // whether to force clear the screen |
| 383 |
caps capabilities // terminal control sequence capabilities |
| 384 |
queuedText bool // whether we have queued non-zero width text queued up |
| 385 |
atPhantom bool // whether the cursor is out of bounds and at a phantom cell |
| 386 |
} |
| 387 |
|
| 388 |
// SetMethod sets the method used to calculate the width of cells. |
| 389 |
func (s *Screen) SetMethod(method ansi.Method) { |
| 390 |
s.method = method |
| 391 |
} |
| 392 |
|
| 393 |
// UseBackspaces sets whether to use backspace characters to move the cursor. |
| 394 |
func (s *Screen) UseBackspaces(v bool) { |
| 395 |
s.opts.Backspace = v |
| 396 |
} |
| 397 |
|
| 398 |
// UseHardTabs sets whether to use hard tabs to optimize cursor movements. |
| 399 |
func (s *Screen) UseHardTabs(v bool) { |
| 400 |
s.opts.HardTabs = v |
| 401 |
} |
| 402 |
|
| 403 |
// SetColorProfile sets the color profile to use when writing to the screen. |
| 404 |
func (s *Screen) SetColorProfile(p colorprofile.Profile) { |
| 405 |
s.opts.Profile = p |
| 406 |
} |
| 407 |
|
| 408 |
// SetRelativeCursor sets whether to use relative cursor movements. |
| 409 |
func (s *Screen) SetRelativeCursor(v bool) { |
| 410 |
s.opts.RelativeCursor = v |
| 411 |
} |
| 412 |
|
| 413 |
// EnterAltScreen enters the alternate screen buffer. |
| 414 |
func (s *Screen) EnterAltScreen() { |
| 415 |
s.opts.AltScreen = true |
| 416 |
s.clear = true |
| 417 |
s.saved = s.cur |
| 418 |
} |
| 419 |
|
| 420 |
// ExitAltScreen exits the alternate screen buffer. |
| 421 |
func (s *Screen) ExitAltScreen() { |
| 422 |
s.opts.AltScreen = false |
| 423 |
s.clear = true |
| 424 |
s.cur = s.saved |
| 425 |
} |
| 426 |
|
| 427 |
// ShowCursor shows the cursor. |
| 428 |
func (s *Screen) ShowCursor() { |
| 429 |
s.opts.ShowCursor = true |
| 430 |
} |
| 431 |
|
| 432 |
// HideCursor hides the cursor. |
| 433 |
func (s *Screen) HideCursor() { |
| 434 |
s.opts.ShowCursor = false |
| 435 |
} |
| 436 |
|
| 437 |
// Bounds implements Window. |
| 438 |
func (s *Screen) Bounds() Rectangle { |
| 439 |
// Always return the new buffer bounds. |
| 440 |
return s.newbuf.Bounds() |
| 441 |
} |
| 442 |
|
| 443 |
// Cell implements Window. |
| 444 |
func (s *Screen) Cell(x int, y int) *Cell { |
| 445 |
return s.newbuf.Cell(x, y) |
| 446 |
} |
| 447 |
|
| 448 |
// Redraw forces a full redraw of the screen. |
| 449 |
func (s *Screen) Redraw() { |
| 450 |
s.mu.Lock() |
| 451 |
s.clear = true |
| 452 |
s.mu.Unlock() |
| 453 |
} |
| 454 |
|
| 455 |
// Clear clears the screen with blank cells. This is a convenience method for |
| 456 |
// [Screen.Fill] with a nil cell. |
| 457 |
func (s *Screen) Clear() bool { |
| 458 |
return s.ClearRect(s.newbuf.Bounds()) |
| 459 |
} |
| 460 |
|
| 461 |
// ClearRect clears the given rectangle with blank cells. This is a convenience |
| 462 |
// method for [Screen.FillRect] with a nil cell. |
| 463 |
func (s *Screen) ClearRect(r Rectangle) bool { |
| 464 |
return s.FillRect(nil, r) |
| 465 |
} |
| 466 |
|
| 467 |
// SetCell implements Window. |
| 468 |
func (s *Screen) SetCell(x int, y int, cell *Cell) (v bool) { |
| 469 |
s.mu.Lock() |
| 470 |
defer s.mu.Unlock() |
| 471 |
cellWidth := 1 |
| 472 |
if cell != nil { |
| 473 |
cellWidth = cell.Width |
| 474 |
} |
| 475 |
if prev := s.curbuf.Cell(x, y); !cellEqual(prev, cell) { |
| 476 |
chg, ok := s.touch[y] |
| 477 |
if !ok { |
| 478 |
chg = lineData{firstCell: x, lastCell: x + cellWidth} |
| 479 |
} else { |
| 480 |
chg.firstCell = min(chg.firstCell, x) |
| 481 |
chg.lastCell = max(chg.lastCell, x+cellWidth) |
| 482 |
} |
| 483 |
s.touch[y] = chg |
| 484 |
} |
| 485 |
|
| 486 |
return s.newbuf.SetCell(x, y, cell) |
| 487 |
} |
| 488 |
|
| 489 |
// Fill implements Window. |
| 490 |
func (s *Screen) Fill(cell *Cell) bool { |
| 491 |
return s.FillRect(cell, s.newbuf.Bounds()) |
| 492 |
} |
| 493 |
|
| 494 |
// FillRect implements Window. |
| 495 |
func (s *Screen) FillRect(cell *Cell, r Rectangle) bool { |
| 496 |
s.mu.Lock() |
| 497 |
defer s.mu.Unlock() |
| 498 |
s.newbuf.FillRect(cell, r) |
| 499 |
for i := r.Min.Y; i < r.Max.Y; i++ { |
| 500 |
s.touch[i] = lineData{firstCell: r.Min.X, lastCell: r.Max.X} |
| 501 |
} |
| 502 |
return true |
| 503 |
} |
| 504 |
|
| 505 |
// capabilities represents a mask of supported ANSI escape sequences. |
| 506 |
type capabilities uint |
| 507 |
|
| 508 |
const ( |
| 509 |
// Vertical Position Absolute [ansi.VPA]. |
| 510 |
capVPA capabilities = 1 << iota |
| 511 |
// Horizontal Position Absolute [ansi.HPA]. |
| 512 |
capHPA |
| 513 |
// Cursor Horizontal Tab [ansi.CHT]. |
| 514 |
capCHT |
| 515 |
// Cursor Backward Tab [ansi.CBT]. |
| 516 |
capCBT |
| 517 |
// Repeat Previous Character [ansi.REP]. |
| 518 |
capREP |
| 519 |
// Erase Character [ansi.ECH]. |
| 520 |
capECH |
| 521 |
// Insert Character [ansi.ICH]. |
| 522 |
capICH |
| 523 |
// Scroll Down [ansi.SD]. |
| 524 |
capSD |
| 525 |
// Scroll Up [ansi.SU]. |
| 526 |
capSU |
| 527 |
|
| 528 |
noCaps capabilities = 0 |
| 529 |
allCaps = capVPA | capHPA | capCHT | capCBT | capREP | capECH | capICH | |
| 530 |
capSD | capSU |
| 531 |
) |
| 532 |
|
| 533 |
// Contains returns whether the capabilities contains the given capability. |
| 534 |
func (v capabilities) Contains(c capabilities) bool { |
| 535 |
return v&c == c |
| 536 |
} |
| 537 |
|
| 538 |
// xtermCaps returns whether the terminal is xterm-like. This means that the |
| 539 |
// terminal supports ECMA-48 and ANSI X3.64 escape sequences. |
| 540 |
// xtermCaps returns a list of control sequence capabilities for the given |
| 541 |
// terminal type. This only supports a subset of sequences that can |
| 542 |
// be different among terminals. |
| 543 |
// NOTE: A hybrid approach would be to support Terminfo databases for a full |
| 544 |
// set of capabilities. |
| 545 |
func xtermCaps(termtype string) (v capabilities) { |
| 546 |
parts := strings.Split(termtype, "-") |
| 547 |
if len(parts) == 0 { |
| 548 |
return v |
| 549 |
} |
| 550 |
|
| 551 |
switch parts[0] { |
| 552 |
case |
| 553 |
"contour", |
| 554 |
"foot", |
| 555 |
"ghostty", |
| 556 |
"kitty", |
| 557 |
"rio", |
| 558 |
"st", |
| 559 |
"tmux", |
| 560 |
"wezterm", |
| 561 |
"xterm": |
| 562 |
v = allCaps |
| 563 |
case "alacritty": |
| 564 |
v = allCaps |
| 565 |
v &^= capCHT // NOTE: alacritty added support for [ansi.CHT] in 2024-12-28 #62d5b13. |
| 566 |
case "screen": |
| 567 |
// See https://www.gnu.org/software/screen/manual/screen.html#Control-Sequences-1 |
| 568 |
v = allCaps |
| 569 |
v &^= capREP |
| 570 |
case "linux": |
| 571 |
// See https://man7.org/linux/man-pages/man4/console_codes.4.html |
| 572 |
v = capVPA | capHPA | capECH | capICH |
| 573 |
} |
| 574 |
|
| 575 |
return v |
| 576 |
} |
| 577 |
|
| 578 |
// NewScreen creates a new Screen. |
| 579 |
func NewScreen(w io.Writer, width, height int, opts *ScreenOptions) (s *Screen) { |
| 580 |
s = new(Screen) |
| 581 |
s.w = w |
| 582 |
if opts != nil { |
| 583 |
s.opts = *opts |
| 584 |
} |
| 585 |
|
| 586 |
if s.opts.Term == "" { |
| 587 |
s.opts.Term = os.Getenv("TERM") |
| 588 |
} |
| 589 |
|
| 590 |
if width <= 0 || height <= 0 { |
| 591 |
if f, ok := w.(term.File); ok { |
| 592 |
width, height, _ = term.GetSize(f.Fd()) |
| 593 |
} |
| 594 |
} |
| 595 |
if width < 0 { |
| 596 |
width = 0 |
| 597 |
} |
| 598 |
if height < 0 { |
| 599 |
height = 0 |
| 600 |
} |
| 601 |
|
| 602 |
s.buf = new(bytes.Buffer) |
| 603 |
s.caps = xtermCaps(s.opts.Term) |
| 604 |
s.curbuf = NewBuffer(width, height) |
| 605 |
s.newbuf = NewBuffer(width, height) |
| 606 |
s.cur = Cursor{Position: Pos(-1, -1)} // start at -1 to force a move |
| 607 |
s.saved = s.cur |
| 608 |
s.reset() |
| 609 |
|
| 610 |
return s |
| 611 |
} |
| 612 |
|
| 613 |
// Width returns the width of the screen. |
| 614 |
func (s *Screen) Width() int { |
| 615 |
return s.newbuf.Width() |
| 616 |
} |
| 617 |
|
| 618 |
// Height returns the height of the screen. |
| 619 |
func (s *Screen) Height() int { |
| 620 |
return s.newbuf.Height() |
| 621 |
} |
| 622 |
|
| 623 |
// cellEqual returns whether the two cells are equal. A nil cell is considered |
| 624 |
// a [BlankCell]. |
| 625 |
func cellEqual(a, b *Cell) bool { |
| 626 |
if a == b { |
| 627 |
return true |
| 628 |
} |
| 629 |
if a == nil { |
| 630 |
a = &BlankCell |
| 631 |
} |
| 632 |
if b == nil { |
| 633 |
b = &BlankCell |
| 634 |
} |
| 635 |
return a.Equal(b) |
| 636 |
} |
| 637 |
|
| 638 |
// putCell draws a cell at the current cursor position. |
| 639 |
func (s *Screen) putCell(cell *Cell) { |
| 640 |
width, height := s.newbuf.Width(), s.newbuf.Height() |
| 641 |
if s.opts.AltScreen && s.cur.X == width-1 && s.cur.Y == height-1 { |
| 642 |
s.putCellLR(cell) |
| 643 |
} else { |
| 644 |
s.putAttrCell(cell) |
| 645 |
} |
| 646 |
} |
| 647 |
|
| 648 |
// wrapCursor wraps the cursor to the next line. |
| 649 |
// |
| 650 |
|
| 651 |
func (s *Screen) wrapCursor() { |
| 652 |
const autoRightMargin = true |
| 653 |
if autoRightMargin { |
| 654 |
// Assume we have auto wrap mode enabled. |
| 655 |
s.cur.X = 0 |
| 656 |
s.cur.Y++ |
| 657 |
} else { |
| 658 |
s.cur.X-- |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
func (s *Screen) putAttrCell(cell *Cell) { |
| 663 |
if cell != nil && cell.Empty() { |
| 664 |
// XXX: Zero width cells are special and should not be written to the |
| 665 |
// screen no matter what other attributes they have. |
| 666 |
// Zero width cells are used for wide characters that are split into |
| 667 |
// multiple cells. |
| 668 |
return |
| 669 |
} |
| 670 |
|
| 671 |
if cell == nil { |
| 672 |
cell = s.clearBlank() |
| 673 |
} |
| 674 |
|
| 675 |
// We're at pending wrap state (phantom cell), incoming cell should |
| 676 |
// wrap. |
| 677 |
if s.atPhantom { |
| 678 |
s.wrapCursor() |
| 679 |
s.atPhantom = false |
| 680 |
} |
| 681 |
|
| 682 |
s.updatePen(cell) |
| 683 |
s.buf.WriteRune(cell.Rune) |
| 684 |
for _, c := range cell.Comb { |
| 685 |
s.buf.WriteRune(c) |
| 686 |
} |
| 687 |
|
| 688 |
s.cur.X += cell.Width |
| 689 |
|
| 690 |
if cell.Width > 0 { |
| 691 |
s.queuedText = true |
| 692 |
} |
| 693 |
|
| 694 |
if s.cur.X >= s.newbuf.Width() { |
| 695 |
s.atPhantom = true |
| 696 |
} |
| 697 |
} |
| 698 |
|
| 699 |
// putCellLR draws a cell at the lower right corner of the screen. |
| 700 |
func (s *Screen) putCellLR(cell *Cell) { |
| 701 |
// Optimize for the lower right corner cell. |
| 702 |
curX := s.cur.X |
| 703 |
if cell == nil || !cell.Empty() { |
| 704 |
s.buf.WriteString(ansi.ResetAutoWrapMode) |
| 705 |
s.putAttrCell(cell) |
| 706 |
// Writing to lower-right corner cell should not wrap. |
| 707 |
s.atPhantom = false |
| 708 |
s.cur.X = curX |
| 709 |
s.buf.WriteString(ansi.SetAutoWrapMode) |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
// updatePen updates the cursor pen styles. |
| 714 |
func (s *Screen) updatePen(cell *Cell) { |
| 715 |
if cell == nil { |
| 716 |
cell = &BlankCell |
| 717 |
} |
| 718 |
|
| 719 |
if s.opts.Profile != 0 { |
| 720 |
// Downsample colors to the given color profile. |
| 721 |
cell.Style = ConvertStyle(cell.Style, s.opts.Profile) |
| 722 |
cell.Link = ConvertLink(cell.Link, s.opts.Profile) |
| 723 |
} |
| 724 |
|
| 725 |
if !cell.Style.Equal(&s.cur.Style) { |
| 726 |
seq := cell.Style.DiffSequence(s.cur.Style) |
| 727 |
if cell.Style.Empty() && len(seq) > len(ansi.ResetStyle) { |
| 728 |
seq = ansi.ResetStyle |
| 729 |
} |
| 730 |
s.buf.WriteString(seq) |
| 731 |
s.cur.Style = cell.Style |
| 732 |
} |
| 733 |
if !cell.Link.Equal(&s.cur.Link) { |
| 734 |
s.buf.WriteString(ansi.SetHyperlink(cell.Link.URL, cell.Link.Params)) |
| 735 |
s.cur.Link = cell.Link |
| 736 |
} |
| 737 |
} |
| 738 |
|
| 739 |
// emitRange emits a range of cells to the buffer. It it equivalent to calling |
| 740 |
// [Screen.putCell] for each cell in the range. This is optimized to use |
| 741 |
// [ansi.ECH] and [ansi.REP]. |
| 742 |
// Returns whether the cursor is at the end of interval or somewhere in the |
| 743 |
// middle. |
| 744 |
func (s *Screen) emitRange(line Line, n int) (eoi bool) { |
| 745 |
for n > 0 { |
| 746 |
var count int |
| 747 |
for n > 1 && !cellEqual(line.At(0), line.At(1)) { |
| 748 |
s.putCell(line.At(0)) |
| 749 |
line = line[1:] |
| 750 |
n-- |
| 751 |
} |
| 752 |
|
| 753 |
cell0 := line[0] |
| 754 |
if n == 1 { |
| 755 |
s.putCell(cell0) |
| 756 |
return false |
| 757 |
} |
| 758 |
|
| 759 |
count = 2 |
| 760 |
for count < n && cellEqual(line.At(count), cell0) { |
| 761 |
count++ |
| 762 |
} |
| 763 |
|
| 764 |
ech := ansi.EraseCharacter(count) |
| 765 |
cup := ansi.CursorPosition(s.cur.X+count, s.cur.Y) |
| 766 |
rep := ansi.RepeatPreviousCharacter(count) |
| 767 |
if s.caps.Contains(capECH) && count > len(ech)+len(cup) && cell0 != nil && cell0.Clear() { //nolint:nestif |
| 768 |
s.updatePen(cell0) |
| 769 |
s.buf.WriteString(ech) |
| 770 |
|
| 771 |
// If this is the last cell, we don't need to move the cursor. |
| 772 |
if count < n { |
| 773 |
s.move(s.cur.X+count, s.cur.Y) |
| 774 |
} else { |
| 775 |
return true // cursor in the middle |
| 776 |
} |
| 777 |
} else if s.caps.Contains(capREP) && count > len(rep) && |
| 778 |
(cell0 == nil || (len(cell0.Comb) == 0 && cell0.Rune < 256)) { |
| 779 |
// We only support ASCII characters. Most terminals will handle |
| 780 |
// non-ASCII characters correctly, but some might not, ahem xterm. |
| 781 |
// |
| 782 |
// NOTE: [ansi.REP] only repeats the last rune and won't work |
| 783 |
// if the last cell contains multiple runes. |
| 784 |
|
| 785 |
wrapPossible := s.cur.X+count >= s.newbuf.Width() |
| 786 |
repCount := count |
| 787 |
if wrapPossible { |
| 788 |
repCount-- |
| 789 |
} |
| 790 |
|
| 791 |
s.updatePen(cell0) |
| 792 |
s.putCell(cell0) |
| 793 |
repCount-- // cell0 is a single width cell ASCII character |
| 794 |
|
| 795 |
s.buf.WriteString(ansi.RepeatPreviousCharacter(repCount)) |
| 796 |
s.cur.X += repCount |
| 797 |
if wrapPossible { |
| 798 |
s.putCell(cell0) |
| 799 |
} |
| 800 |
} else { |
| 801 |
for i := range count { |
| 802 |
s.putCell(line.At(i)) |
| 803 |
} |
| 804 |
} |
| 805 |
|
| 806 |
line = line[clamp(count, 0, len(line)):] |
| 807 |
n -= count |
| 808 |
} |
| 809 |
|
| 810 |
return eoi |
| 811 |
} |
| 812 |
|
| 813 |
// putRange puts a range of cells from the old line to the new line. |
| 814 |
// Returns whether the cursor is at the end of interval or somewhere in the |
| 815 |
// middle. |
| 816 |
func (s *Screen) putRange(oldLine, newLine Line, y, start, end int) (eoi bool) { |
| 817 |
inline := min(len(ansi.CursorPosition(start+1, y+1)), |
| 818 |
min(len(ansi.HorizontalPositionAbsolute(start+1)), |
| 819 |
len(ansi.CursorForward(start+1)))) |
| 820 |
if (end - start + 1) > inline { //nolint:nestif |
| 821 |
var j, same int |
| 822 |
for j, same = start, 0; j <= end; j++ { |
| 823 |
oldCell, newCell := oldLine.At(j), newLine.At(j) |
| 824 |
if same == 0 && oldCell != nil && oldCell.Empty() { |
| 825 |
continue |
| 826 |
} |
| 827 |
if cellEqual(oldCell, newCell) { |
| 828 |
same++ |
| 829 |
} else { |
| 830 |
if same > end-start { |
| 831 |
s.emitRange(newLine[start:], j-same-start) |
| 832 |
s.move(j, y) |
| 833 |
start = j |
| 834 |
} |
| 835 |
same = 0 |
| 836 |
} |
| 837 |
} |
| 838 |
|
| 839 |
i := s.emitRange(newLine[start:], j-same-start) |
| 840 |
|
| 841 |
// Always return 1 for the next [Screen.move] after a [Screen.putRange] if |
| 842 |
// we found identical characters at end of interval. |
| 843 |
if same == 0 { |
| 844 |
return i |
| 845 |
} |
| 846 |
return true |
| 847 |
} |
| 848 |
|
| 849 |
return s.emitRange(newLine[start:], end-start+1) |
| 850 |
} |
| 851 |
|
| 852 |
// clearToEnd clears the screen from the current cursor position to the end of |
| 853 |
// line. |
| 854 |
func (s *Screen) clearToEnd(blank *Cell, force bool) { //nolint:unparam |
| 855 |
if s.cur.Y >= 0 { |
| 856 |
curline := s.curbuf.Line(s.cur.Y) |
| 857 |
for j := s.cur.X; j < s.curbuf.Width(); j++ { |
| 858 |
if j >= 0 { |
| 859 |
c := curline.At(j) |
| 860 |
if !cellEqual(c, blank) { |
| 861 |
curline.Set(j, blank) |
| 862 |
force = true |
| 863 |
} |
| 864 |
} |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
if force { |
| 869 |
s.updatePen(blank) |
| 870 |
count := s.newbuf.Width() - s.cur.X |
| 871 |
if s.el0Cost() <= count { |
| 872 |
s.buf.WriteString(ansi.EraseLineRight) |
| 873 |
} else { |
| 874 |
for range count { |
| 875 |
s.putCell(blank) |
| 876 |
} |
| 877 |
} |
| 878 |
} |
| 879 |
} |
| 880 |
|
| 881 |
// clearBlank returns a blank cell based on the current cursor background color. |
| 882 |
func (s *Screen) clearBlank() *Cell { |
| 883 |
c := BlankCell |
| 884 |
if !s.cur.Style.Empty() || !s.cur.Link.Empty() { |
| 885 |
c.Style = s.cur.Style |
| 886 |
c.Link = s.cur.Link |
| 887 |
} |
| 888 |
return &c |
| 889 |
} |
| 890 |
|
| 891 |
// insertCells inserts the count cells pointed by the given line at the current |
| 892 |
// cursor position. |
| 893 |
func (s *Screen) insertCells(line Line, count int) { |
| 894 |
supportsICH := s.caps.Contains(capICH) |
| 895 |
if supportsICH { |
| 896 |
// Use [ansi.ICH] as an optimization. |
| 897 |
s.buf.WriteString(ansi.InsertCharacter(count)) |
| 898 |
} else { |
| 899 |
// Otherwise, use [ansi.IRM] mode. |
| 900 |
s.buf.WriteString(ansi.SetInsertReplaceMode) |
| 901 |
} |
| 902 |
|
| 903 |
for i := 0; count > 0; i++ { |
| 904 |
s.putAttrCell(line[i]) |
| 905 |
count-- |
| 906 |
} |
| 907 |
|
| 908 |
if !supportsICH { |
| 909 |
s.buf.WriteString(ansi.ResetInsertReplaceMode) |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
// el0Cost returns the cost of using [ansi.EL] 0 i.e. [ansi.EraseLineRight]. If |
| 914 |
// this terminal supports background color erase, it can be cheaper to use |
| 915 |
// [ansi.EL] 0 i.e. [ansi.EraseLineRight] to clear |
| 916 |
// trailing spaces. |
| 917 |
func (s *Screen) el0Cost() int { |
| 918 |
if s.caps != noCaps { |
| 919 |
return 0 |
| 920 |
} |
| 921 |
return len(ansi.EraseLineRight) |
| 922 |
} |
| 923 |
|
| 924 |
// transformLine transforms the given line in the current window to the |
| 925 |
// corresponding line in the new window. It uses [ansi.ICH] and [ansi.DCH] to |
| 926 |
// insert or delete characters. |
| 927 |
func (s *Screen) transformLine(y int) { |
| 928 |
var firstCell, oLastCell, nLastCell int // first, old last, new last index |
| 929 |
oldLine := s.curbuf.Line(y) |
| 930 |
newLine := s.newbuf.Line(y) |
| 931 |
|
| 932 |
// Find the first changed cell in the line |
| 933 |
var lineChanged bool |
| 934 |
for i := range s.newbuf.Width() { |
| 935 |
if !cellEqual(newLine.At(i), oldLine.At(i)) { |
| 936 |
lineChanged = true |
| 937 |
break |
| 938 |
} |
| 939 |
} |
| 940 |
|
| 941 |
const ceolStandoutGlitch = false |
| 942 |
if ceolStandoutGlitch && lineChanged { //nolint:nestif |
| 943 |
s.move(0, y) |
| 944 |
s.clearToEnd(nil, false) |
| 945 |
s.putRange(oldLine, newLine, y, 0, s.newbuf.Width()-1) |
| 946 |
} else { |
| 947 |
blank := newLine.At(0) |
| 948 |
|
| 949 |
// It might be cheaper to clear leading spaces with [ansi.EL] 1 i.e. |
| 950 |
// [ansi.EraseLineLeft]. |
| 951 |
if blank == nil || blank.Clear() { |
| 952 |
var oFirstCell, nFirstCell int |
| 953 |
for oFirstCell = range s.curbuf.Width() { |
| 954 |
if !cellEqual(oldLine.At(oFirstCell), blank) { |
| 955 |
break |
| 956 |
} |
| 957 |
} |
| 958 |
for nFirstCell = range s.newbuf.Width() { |
| 959 |
if !cellEqual(newLine.At(nFirstCell), blank) { |
| 960 |
break |
| 961 |
} |
| 962 |
} |
| 963 |
|
| 964 |
if nFirstCell == oFirstCell { |
| 965 |
firstCell = nFirstCell |
| 966 |
|
| 967 |
// Find the first differing cell |
| 968 |
for firstCell < s.newbuf.Width() && |
| 969 |
cellEqual(oldLine.At(firstCell), newLine.At(firstCell)) { |
| 970 |
firstCell++ |
| 971 |
} |
| 972 |
} else if oFirstCell > nFirstCell { |
| 973 |
firstCell = nFirstCell |
| 974 |
} else if oFirstCell < nFirstCell { |
| 975 |
firstCell = oFirstCell |
| 976 |
el1Cost := len(ansi.EraseLineLeft) |
| 977 |
if el1Cost < nFirstCell-oFirstCell { |
| 978 |
if nFirstCell >= s.newbuf.Width() { |
| 979 |
s.move(0, y) |
| 980 |
s.updatePen(blank) |
| 981 |
s.buf.WriteString(ansi.EraseLineRight) |
| 982 |
} else { |
| 983 |
s.move(nFirstCell-1, y) |
| 984 |
s.updatePen(blank) |
| 985 |
s.buf.WriteString(ansi.EraseLineLeft) |
| 986 |
} |
| 987 |
|
| 988 |
for firstCell < nFirstCell { |
| 989 |
oldLine.Set(firstCell, blank) |
| 990 |
firstCell++ |
| 991 |
} |
| 992 |
} |
| 993 |
} |
| 994 |
} else { |
| 995 |
// Find the first differing cell |
| 996 |
for firstCell < s.newbuf.Width() && cellEqual(newLine.At(firstCell), oldLine.At(firstCell)) { |
| 997 |
firstCell++ |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
// If we didn't find one, we're done |
| 1002 |
if firstCell >= s.newbuf.Width() { |
| 1003 |
return |
| 1004 |
} |
| 1005 |
|
| 1006 |
blank = newLine.At(s.newbuf.Width() - 1) |
| 1007 |
if blank != nil && !blank.Clear() { |
| 1008 |
// Find the last differing cell |
| 1009 |
nLastCell = s.newbuf.Width() - 1 |
| 1010 |
for nLastCell > firstCell && cellEqual(newLine.At(nLastCell), oldLine.At(nLastCell)) { |
| 1011 |
nLastCell-- |
| 1012 |
} |
| 1013 |
|
| 1014 |
if nLastCell >= firstCell { |
| 1015 |
s.move(firstCell, y) |
| 1016 |
s.putRange(oldLine, newLine, y, firstCell, nLastCell) |
| 1017 |
if firstCell < len(oldLine) && firstCell < len(newLine) { |
| 1018 |
copy(oldLine[firstCell:], newLine[firstCell:]) |
| 1019 |
} else { |
| 1020 |
copy(oldLine, newLine) |
| 1021 |
} |
| 1022 |
} |
| 1023 |
|
| 1024 |
return |
| 1025 |
} |
| 1026 |
|
| 1027 |
// Find last non-blank cell in the old line. |
| 1028 |
oLastCell = s.curbuf.Width() - 1 |
| 1029 |
for oLastCell > firstCell && cellEqual(oldLine.At(oLastCell), blank) { |
| 1030 |
oLastCell-- |
| 1031 |
} |
| 1032 |
|
| 1033 |
// Find last non-blank cell in the new line. |
| 1034 |
nLastCell = s.newbuf.Width() - 1 |
| 1035 |
for nLastCell > firstCell && cellEqual(newLine.At(nLastCell), blank) { |
| 1036 |
nLastCell-- |
| 1037 |
} |
| 1038 |
|
| 1039 |
if nLastCell == firstCell && s.el0Cost() < oLastCell-nLastCell { |
| 1040 |
s.move(firstCell, y) |
| 1041 |
if !cellEqual(newLine.At(firstCell), blank) { |
| 1042 |
s.putCell(newLine.At(firstCell)) |
| 1043 |
} |
| 1044 |
s.clearToEnd(blank, false) |
| 1045 |
} else if nLastCell != oLastCell && |
| 1046 |
!cellEqual(newLine.At(nLastCell), oldLine.At(oLastCell)) { |
| 1047 |
s.move(firstCell, y) |
| 1048 |
if oLastCell-nLastCell > s.el0Cost() { |
| 1049 |
if s.putRange(oldLine, newLine, y, firstCell, nLastCell) { |
| 1050 |
s.move(nLastCell+1, y) |
| 1051 |
} |
| 1052 |
s.clearToEnd(blank, false) |
| 1053 |
} else { |
| 1054 |
n := max(nLastCell, oLastCell) |
| 1055 |
s.putRange(oldLine, newLine, y, firstCell, n) |
| 1056 |
} |
| 1057 |
} else { |
| 1058 |
nLastNonBlank := nLastCell |
| 1059 |
oLastNonBlank := oLastCell |
| 1060 |
|
| 1061 |
// Find the last cells that really differ. |
| 1062 |
// Can be -1 if no cells differ. |
| 1063 |
for cellEqual(newLine.At(nLastCell), oldLine.At(oLastCell)) { |
| 1064 |
if !cellEqual(newLine.At(nLastCell-1), oldLine.At(oLastCell-1)) { |
| 1065 |
break |
| 1066 |
} |
| 1067 |
nLastCell-- |
| 1068 |
oLastCell-- |
| 1069 |
if nLastCell == -1 || oLastCell == -1 { |
| 1070 |
break |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
n := min(oLastCell, nLastCell) |
| 1075 |
if n >= firstCell { |
| 1076 |
s.move(firstCell, y) |
| 1077 |
s.putRange(oldLine, newLine, y, firstCell, n) |
| 1078 |
} |
| 1079 |
|
| 1080 |
if oLastCell < nLastCell { |
| 1081 |
m := max(nLastNonBlank, oLastNonBlank) |
| 1082 |
if n != 0 { |
| 1083 |
for n > 0 { |
| 1084 |
wide := newLine.At(n + 1) |
| 1085 |
if wide == nil || !wide.Empty() { |
| 1086 |
break |
| 1087 |
} |
| 1088 |
n-- |
| 1089 |
oLastCell-- |
| 1090 |
} |
| 1091 |
} else if n >= firstCell && newLine.At(n) != nil && newLine.At(n).Width > 1 { |
| 1092 |
next := newLine.At(n + 1) |
| 1093 |
for next != nil && next.Empty() { |
| 1094 |
n++ |
| 1095 |
oLastCell++ |
| 1096 |
} |
| 1097 |
} |
| 1098 |
|
| 1099 |
s.move(n+1, y) |
| 1100 |
ichCost := 3 + nLastCell - oLastCell |
| 1101 |
if s.caps.Contains(capICH) && (nLastCell < nLastNonBlank || ichCost > (m-n)) { |
| 1102 |
s.putRange(oldLine, newLine, y, n+1, m) |
| 1103 |
} else { |
| 1104 |
s.insertCells(newLine[n+1:], nLastCell-oLastCell) |
| 1105 |
} |
| 1106 |
} else if oLastCell > nLastCell { |
| 1107 |
s.move(n+1, y) |
| 1108 |
dchCost := 3 + oLastCell - nLastCell |
| 1109 |
if dchCost > len(ansi.EraseLineRight)+nLastNonBlank-(n+1) { |
| 1110 |
if s.putRange(oldLine, newLine, y, n+1, nLastNonBlank) { |
| 1111 |
s.move(nLastNonBlank+1, y) |
| 1112 |
} |
| 1113 |
s.clearToEnd(blank, false) |
| 1114 |
} else { |
| 1115 |
s.updatePen(blank) |
| 1116 |
s.deleteCells(oLastCell - nLastCell) |
| 1117 |
} |
| 1118 |
} |
| 1119 |
} |
| 1120 |
} |
| 1121 |
|
| 1122 |
// Update the old line with the new line |
| 1123 |
if firstCell < len(oldLine) && firstCell < len(newLine) { |
| 1124 |
copy(oldLine[firstCell:], newLine[firstCell:]) |
| 1125 |
} else { |
| 1126 |
copy(oldLine, newLine) |
| 1127 |
} |
| 1128 |
} |
| 1129 |
|
| 1130 |
// deleteCells deletes the count cells at the current cursor position and moves |
| 1131 |
// the rest of the line to the left. This is equivalent to [ansi.DCH]. |
| 1132 |
func (s *Screen) deleteCells(count int) { |
| 1133 |
// [ansi.DCH] will shift in cells from the right margin so we need to |
| 1134 |
// ensure that they are the right style. |
| 1135 |
s.buf.WriteString(ansi.DeleteCharacter(count)) |
| 1136 |
} |
| 1137 |
|
| 1138 |
// clearToBottom clears the screen from the current cursor position to the end |
| 1139 |
// of the screen. |
| 1140 |
func (s *Screen) clearToBottom(blank *Cell) { |
| 1141 |
row, col := s.cur.Y, s.cur.X |
| 1142 |
if row < 0 { |
| 1143 |
row = 0 |
| 1144 |
} |
| 1145 |
|
| 1146 |
s.updatePen(blank) |
| 1147 |
s.buf.WriteString(ansi.EraseScreenBelow) |
| 1148 |
// Clear the rest of the current line |
| 1149 |
s.curbuf.ClearRect(Rect(col, row, s.curbuf.Width()-col, 1)) |
| 1150 |
// Clear everything below the current line |
| 1151 |
s.curbuf.ClearRect(Rect(0, row+1, s.curbuf.Width(), s.curbuf.Height()-row-1)) |
| 1152 |
} |
| 1153 |
|
| 1154 |
// clearBottom tests if clearing the end of the screen would satisfy part of |
| 1155 |
// the screen update. Scan backwards through lines in the screen checking if |
| 1156 |
// each is blank and one or more are changed. |
| 1157 |
// It returns the top line. |
| 1158 |
func (s *Screen) clearBottom(total int) (top int) { |
| 1159 |
if total <= 0 { |
| 1160 |
return top |
| 1161 |
} |
| 1162 |
|
| 1163 |
top = total |
| 1164 |
last := s.newbuf.Width() |
| 1165 |
blank := s.clearBlank() |
| 1166 |
canClearWithBlank := blank == nil || blank.Clear() |
| 1167 |
|
| 1168 |
if canClearWithBlank { //nolint:nestif |
| 1169 |
var row int |
| 1170 |
for row = total - 1; row >= 0; row-- { |
| 1171 |
oldLine := s.curbuf.Line(row) |
| 1172 |
newLine := s.newbuf.Line(row) |
| 1173 |
|
| 1174 |
var col int |
| 1175 |
ok := true |
| 1176 |
for col = 0; ok && col < last; col++ { |
| 1177 |
ok = cellEqual(newLine.At(col), blank) |
| 1178 |
} |
| 1179 |
if !ok { |
| 1180 |
break |
| 1181 |
} |
| 1182 |
|
| 1183 |
for col = 0; ok && col < last; col++ { |
| 1184 |
ok = len(oldLine) == last && cellEqual(oldLine.At(col), blank) |
| 1185 |
} |
| 1186 |
if !ok { |
| 1187 |
top = row |
| 1188 |
} |
| 1189 |
} |
| 1190 |
|
| 1191 |
if top < total { |
| 1192 |
s.move(0, top-1) // top is 1-based |
| 1193 |
s.clearToBottom(blank) |
| 1194 |
if s.oldhash != nil && s.newhash != nil && |
| 1195 |
row < len(s.oldhash) && row < len(s.newhash) { |
| 1196 |
for row := top; row < s.newbuf.Height(); row++ { |
| 1197 |
s.oldhash[row] = s.newhash[row] |
| 1198 |
} |
| 1199 |
} |
| 1200 |
} |
| 1201 |
} |
| 1202 |
|
| 1203 |
return top |
| 1204 |
} |
| 1205 |
|
| 1206 |
// clearScreen clears the screen and put cursor at home. |
| 1207 |
func (s *Screen) clearScreen(blank *Cell) { |
| 1208 |
s.updatePen(blank) |
| 1209 |
s.buf.WriteString(ansi.CursorHomePosition) |
| 1210 |
s.buf.WriteString(ansi.EraseEntireScreen) |
| 1211 |
s.cur.X, s.cur.Y = 0, 0 |
| 1212 |
s.curbuf.Fill(blank) |
| 1213 |
} |
| 1214 |
|
| 1215 |
// clearBelow clears everything below and including the row. |
| 1216 |
func (s *Screen) clearBelow(blank *Cell, row int) { |
| 1217 |
s.move(0, row) |
| 1218 |
s.clearToBottom(blank) |
| 1219 |
} |
| 1220 |
|
| 1221 |
// clearUpdate forces a screen redraw. |
| 1222 |
func (s *Screen) clearUpdate() { |
| 1223 |
blank := s.clearBlank() |
| 1224 |
var nonEmpty int |
| 1225 |
if s.opts.AltScreen { |
| 1226 |
// XXX: We're using the maximum height of the two buffers to ensure |
| 1227 |
// we write newly added lines to the screen in [Screen.transformLine]. |
| 1228 |
nonEmpty = max(s.curbuf.Height(), s.newbuf.Height()) |
| 1229 |
s.clearScreen(blank) |
| 1230 |
} else { |
| 1231 |
nonEmpty = s.newbuf.Height() |
| 1232 |
s.clearBelow(blank, 0) |
| 1233 |
} |
| 1234 |
nonEmpty = s.clearBottom(nonEmpty) |
| 1235 |
for i := range nonEmpty { |
| 1236 |
s.transformLine(i) |
| 1237 |
} |
| 1238 |
} |
| 1239 |
|
| 1240 |
// Flush flushes the buffer to the screen. |
| 1241 |
func (s *Screen) Flush() (err error) { |
| 1242 |
s.mu.Lock() |
| 1243 |
defer s.mu.Unlock() |
| 1244 |
return s.flush() |
| 1245 |
} |
| 1246 |
|
| 1247 |
func (s *Screen) flush() (err error) { |
| 1248 |
// Write the buffer |
| 1249 |
if s.buf.Len() > 0 { |
| 1250 |
_, err = s.w.Write(s.buf.Bytes()) |
| 1251 |
if err == nil { |
| 1252 |
s.buf.Reset() |
| 1253 |
} |
| 1254 |
} |
| 1255 |
|
| 1256 |
return err |
| 1257 |
} |
| 1258 |
|
| 1259 |
// Render renders changes of the screen to the internal buffer. Call |
| 1260 |
// [Screen.Flush] to flush pending changes to the screen. |
| 1261 |
func (s *Screen) Render() { |
| 1262 |
s.mu.Lock() |
| 1263 |
s.render() |
| 1264 |
s.mu.Unlock() |
| 1265 |
} |
| 1266 |
|
| 1267 |
func (s *Screen) render() { |
| 1268 |
// Do we need to render anything? |
| 1269 |
if s.opts.AltScreen == s.altScreenMode && |
| 1270 |
!s.opts.ShowCursor == s.cursorHidden && |
| 1271 |
!s.clear && |
| 1272 |
len(s.touch) == 0 && |
| 1273 |
len(s.queueAbove) == 0 { |
| 1274 |
return |
| 1275 |
} |
| 1276 |
|
| 1277 |
//nolint:godox |
| 1278 |
// TODO: Investigate whether this is necessary. Theoretically, terminals |
| 1279 |
// can add/remove tab stops and we should be able to handle that. We could |
| 1280 |
// use [ansi.DECTABSR] to read the tab stops, but that's not implemented in |
| 1281 |
// most terminals :/ |
| 1282 |
// // Are we using hard tabs? If so, ensure tabs are using the |
| 1283 |
// // default interval using [ansi.DECST8C]. |
| 1284 |
// if s.opts.HardTabs && !s.initTabs { |
| 1285 |
// s.buf.WriteString(ansi.SetTabEvery8Columns) |
| 1286 |
// s.initTabs = true |
| 1287 |
// } |
| 1288 |
|
| 1289 |
// Do we need alt-screen mode? |
| 1290 |
if s.opts.AltScreen != s.altScreenMode { |
| 1291 |
if s.opts.AltScreen { |
| 1292 |
s.buf.WriteString(ansi.SetAltScreenSaveCursorMode) |
| 1293 |
} else { |
| 1294 |
s.buf.WriteString(ansi.ResetAltScreenSaveCursorMode) |
| 1295 |
} |
| 1296 |
s.altScreenMode = s.opts.AltScreen |
| 1297 |
} |
| 1298 |
|
| 1299 |
// Do we need text cursor mode? |
| 1300 |
if !s.opts.ShowCursor != s.cursorHidden { |
| 1301 |
s.cursorHidden = !s.opts.ShowCursor |
| 1302 |
if s.cursorHidden { |
| 1303 |
s.buf.WriteString(ansi.HideCursor) |
| 1304 |
} |
| 1305 |
} |
| 1306 |
|
| 1307 |
// Do we have queued strings to write above the screen? |
| 1308 |
if len(s.queueAbove) > 0 { |
| 1309 |
//nolint:godox |
| 1310 |
// TODO: Use scrolling region if available. |
| 1311 |
//nolint:godox |
| 1312 |
// TODO: Use [Screen.Write] [io.Writer] interface. |
| 1313 |
|
| 1314 |
// We need to scroll the screen up by the number of lines in the queue. |
| 1315 |
// We can't use [ansi.SU] because we want the cursor to move down until |
| 1316 |
// it reaches the bottom of the screen. |
| 1317 |
s.move(0, s.newbuf.Height()-1) |
| 1318 |
s.buf.WriteString(strings.Repeat("\n", len(s.queueAbove))) |
| 1319 |
s.cur.Y += len(s.queueAbove) |
| 1320 |
// XXX: Now go to the top of the screen, insert new lines, and write |
| 1321 |
// the queued strings. It is important to use [Screen.moveCursor] |
| 1322 |
// instead of [Screen.move] because we don't want to perform any checks |
| 1323 |
// on the cursor position. |
| 1324 |
s.moveCursor(0, 0, false) |
| 1325 |
s.buf.WriteString(ansi.InsertLine(len(s.queueAbove))) |
| 1326 |
for _, line := range s.queueAbove { |
| 1327 |
s.buf.WriteString(line + "\r\n") |
| 1328 |
} |
| 1329 |
|
| 1330 |
// Clear the queue |
| 1331 |
s.queueAbove = s.queueAbove[:0] |
| 1332 |
} |
| 1333 |
|
| 1334 |
var nonEmpty int |
| 1335 |
|
| 1336 |
// XXX: In inline mode, after a screen resize, we need to clear the extra |
| 1337 |
// lines at the bottom of the screen. This is because in inline mode, we |
| 1338 |
// don't use the full screen height and the current buffer size might be |
| 1339 |
// larger than the new buffer size. |
| 1340 |
partialClear := !s.opts.AltScreen && s.cur.X != -1 && s.cur.Y != -1 && |
| 1341 |
s.curbuf.Width() == s.newbuf.Width() && |
| 1342 |
s.curbuf.Height() > 0 && |
| 1343 |
s.curbuf.Height() > s.newbuf.Height() |
| 1344 |
|
| 1345 |
if !s.clear && partialClear { |
| 1346 |
s.clearBelow(nil, s.newbuf.Height()-1) |
| 1347 |
} |
| 1348 |
|
| 1349 |
if s.clear { //nolint:nestif |
| 1350 |
s.clearUpdate() |
| 1351 |
s.clear = false |
| 1352 |
} else if len(s.touch) > 0 { |
| 1353 |
if s.opts.AltScreen { |
| 1354 |
// Optimize scrolling for the alternate screen buffer. |
| 1355 |
//nolint:godox |
| 1356 |
// TODO: Should we optimize for inline mode as well? If so, we need |
| 1357 |
// to know the actual cursor position to use [ansi.DECSTBM]. |
| 1358 |
s.scrollOptimize() |
| 1359 |
} |
| 1360 |
|
| 1361 |
var changedLines int |
| 1362 |
var i int |
| 1363 |
|
| 1364 |
if s.opts.AltScreen { |
| 1365 |
nonEmpty = min(s.curbuf.Height(), s.newbuf.Height()) |
| 1366 |
} else { |
| 1367 |
nonEmpty = s.newbuf.Height() |
| 1368 |
} |
| 1369 |
|
| 1370 |
nonEmpty = s.clearBottom(nonEmpty) |
| 1371 |
for i = range nonEmpty { |
| 1372 |
_, ok := s.touch[i] |
| 1373 |
if ok { |
| 1374 |
s.transformLine(i) |
| 1375 |
changedLines++ |
| 1376 |
} |
| 1377 |
} |
| 1378 |
} |
| 1379 |
|
| 1380 |
// Sync windows and screen |
| 1381 |
s.touch = make(map[int]lineData, s.newbuf.Height()) |
| 1382 |
|
| 1383 |
if s.curbuf.Width() != s.newbuf.Width() || s.curbuf.Height() != s.newbuf.Height() { |
| 1384 |
// Resize the old buffer to match the new buffer. |
| 1385 |
_, oldh := s.curbuf.Width(), s.curbuf.Height() |
| 1386 |
s.curbuf.Resize(s.newbuf.Width(), s.newbuf.Height()) |
| 1387 |
// Sync new lines to old lines |
| 1388 |
for i := oldh - 1; i < s.newbuf.Height(); i++ { |
| 1389 |
copy(s.curbuf.Line(i), s.newbuf.Line(i)) |
| 1390 |
} |
| 1391 |
} |
| 1392 |
|
| 1393 |
s.updatePen(nil) // nil indicates a blank cell with no styles |
| 1394 |
|
| 1395 |
// Do we have enough changes to justify toggling the cursor? |
| 1396 |
if s.buf.Len() > 1 && s.opts.ShowCursor && !s.cursorHidden && s.queuedText { |
| 1397 |
nb := new(bytes.Buffer) |
| 1398 |
nb.Grow(s.buf.Len() + len(ansi.HideCursor) + len(ansi.ShowCursor)) |
| 1399 |
nb.WriteString(ansi.HideCursor) |
| 1400 |
nb.Write(s.buf.Bytes()) |
| 1401 |
nb.WriteString(ansi.ShowCursor) |
| 1402 |
*s.buf = *nb |
| 1403 |
} |
| 1404 |
|
| 1405 |
s.queuedText = false |
| 1406 |
} |
| 1407 |
|
| 1408 |
// Close writes the final screen update and resets the screen. |
| 1409 |
func (s *Screen) Close() (err error) { |
| 1410 |
s.mu.Lock() |
| 1411 |
defer s.mu.Unlock() |
| 1412 |
|
| 1413 |
s.render() |
| 1414 |
s.updatePen(nil) |
| 1415 |
// Go to the bottom of the screen |
| 1416 |
s.move(0, s.newbuf.Height()-1) |
| 1417 |
|
| 1418 |
if s.altScreenMode { |
| 1419 |
s.buf.WriteString(ansi.ResetAltScreenSaveCursorMode) |
| 1420 |
s.altScreenMode = false |
| 1421 |
} |
| 1422 |
|
| 1423 |
if s.cursorHidden { |
| 1424 |
s.buf.WriteString(ansi.ShowCursor) |
| 1425 |
s.cursorHidden = false |
| 1426 |
} |
| 1427 |
|
| 1428 |
// Write the buffer |
| 1429 |
err = s.flush() |
| 1430 |
if err != nil { |
| 1431 |
return err |
| 1432 |
} |
| 1433 |
|
| 1434 |
s.reset() |
| 1435 |
return err |
| 1436 |
} |
| 1437 |
|
| 1438 |
// reset resets the screen to its initial state. |
| 1439 |
func (s *Screen) reset() { |
| 1440 |
s.scrollHeight = 0 |
| 1441 |
s.cursorHidden = false |
| 1442 |
s.altScreenMode = false |
| 1443 |
s.touch = make(map[int]lineData, s.newbuf.Height()) |
| 1444 |
if s.curbuf != nil { |
| 1445 |
s.curbuf.Clear() |
| 1446 |
} |
| 1447 |
if s.newbuf != nil { |
| 1448 |
s.newbuf.Clear() |
| 1449 |
} |
| 1450 |
s.buf.Reset() |
| 1451 |
s.tabs = DefaultTabStops(s.newbuf.Width()) |
| 1452 |
s.oldhash, s.newhash = nil, nil |
| 1453 |
|
| 1454 |
// We always disable HardTabs when termtype is "linux". |
| 1455 |
if strings.HasPrefix(s.opts.Term, "linux") { |
| 1456 |
s.opts.HardTabs = false |
| 1457 |
} |
| 1458 |
} |
| 1459 |
|
| 1460 |
// Resize resizes the screen. |
| 1461 |
func (s *Screen) Resize(width, height int) bool { |
| 1462 |
oldw := s.newbuf.Width() |
| 1463 |
oldh := s.newbuf.Height() |
| 1464 |
|
| 1465 |
if s.opts.AltScreen || width != oldw { |
| 1466 |
// We only clear the whole screen if the width changes. Adding/removing |
| 1467 |
// rows is handled by the [Screen.render] and [Screen.transformLine] |
| 1468 |
// methods. |
| 1469 |
s.clear = true |
| 1470 |
} |
| 1471 |
|
| 1472 |
// Clear new columns and lines |
| 1473 |
if width > oldh { |
| 1474 |
s.ClearRect(Rect(max(oldw-1, 0), 0, width-oldw, height)) |
| 1475 |
} else if width < oldw { |
| 1476 |
s.ClearRect(Rect(max(width-1, 0), 0, oldw-width, height)) |
| 1477 |
} |
| 1478 |
|
| 1479 |
if height > oldh { |
| 1480 |
s.ClearRect(Rect(0, max(oldh, 0), width, height-oldh)) |
| 1481 |
} else if height < oldh { |
| 1482 |
s.ClearRect(Rect(0, max(height, 0), width, oldh-height)) |
| 1483 |
} |
| 1484 |
|
| 1485 |
s.mu.Lock() |
| 1486 |
s.newbuf.Resize(width, height) |
| 1487 |
s.tabs.Resize(width) |
| 1488 |
s.oldhash, s.newhash = nil, nil |
| 1489 |
s.scrollHeight = 0 // reset scroll lines |
| 1490 |
s.mu.Unlock() |
| 1491 |
|
| 1492 |
return true |
| 1493 |
} |
| 1494 |
|
| 1495 |
// MoveTo moves the cursor to the given position. |
| 1496 |
func (s *Screen) MoveTo(x, y int) { |
| 1497 |
s.mu.Lock() |
| 1498 |
s.move(x, y) |
| 1499 |
s.mu.Unlock() |
| 1500 |
} |
| 1501 |
|
| 1502 |
// InsertAbove inserts string above the screen. The inserted string is not |
| 1503 |
// managed by the screen. This does nothing when alternate screen mode is |
| 1504 |
// enabled. |
| 1505 |
func (s *Screen) InsertAbove(str string) { |
| 1506 |
if s.opts.AltScreen { |
| 1507 |
return |
| 1508 |
} |
| 1509 |
s.mu.Lock() |
| 1510 |
for _, line := range strings.Split(str, "\n") { |
| 1511 |
s.queueAbove = append(s.queueAbove, s.method.Truncate(line, s.Width(), "")) |
| 1512 |
} |
| 1513 |
s.mu.Unlock() |
| 1514 |
} |