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