@trismegisto/terminal 3.3.14 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +12 -0
  2. package/dist/addons/attach.d.ts +16 -0
  3. package/dist/addons/attach.js +58 -0
  4. package/dist/addons/attach.js.map +1 -0
  5. package/dist/addons/clipboard.d.ts +31 -0
  6. package/dist/addons/clipboard.js +77 -0
  7. package/dist/addons/clipboard.js.map +1 -0
  8. package/dist/addons/fit.d.ts +19 -0
  9. package/dist/addons/fit.js +69 -0
  10. package/dist/addons/fit.js.map +1 -0
  11. package/dist/addons/image/iip.d.ts +38 -0
  12. package/dist/addons/image/iip.js +158 -0
  13. package/dist/addons/image/iip.js.map +1 -0
  14. package/dist/addons/image/index.d.ts +91 -0
  15. package/dist/addons/image/index.js +783 -0
  16. package/dist/addons/image/index.js.map +1 -0
  17. package/dist/addons/image/kitty.d.ts +57 -0
  18. package/dist/addons/image/kitty.js +92 -0
  19. package/dist/addons/image/kitty.js.map +1 -0
  20. package/dist/addons/image/qoi.d.ts +5 -0
  21. package/dist/addons/image/qoi.js +70 -0
  22. package/dist/addons/image/qoi.js.map +1 -0
  23. package/dist/addons/image/sixel.d.ts +30 -0
  24. package/dist/addons/image/sixel.js +251 -0
  25. package/dist/addons/image/sixel.js.map +1 -0
  26. package/dist/addons/image/storage.d.ts +68 -0
  27. package/dist/addons/image/storage.js +87 -0
  28. package/dist/addons/image/storage.js.map +1 -0
  29. package/dist/addons/ligatures.d.ts +17 -0
  30. package/dist/addons/ligatures.js +66 -0
  31. package/dist/addons/ligatures.js.map +1 -0
  32. package/dist/addons/program-status.d.ts +32 -0
  33. package/dist/addons/program-status.js +196 -0
  34. package/dist/addons/program-status.js.map +1 -0
  35. package/dist/addons/progress.d.ts +21 -0
  36. package/dist/addons/progress.js +56 -0
  37. package/dist/addons/progress.js.map +1 -0
  38. package/dist/addons/search.d.ts +46 -0
  39. package/dist/addons/search.js +188 -0
  40. package/dist/addons/search.js.map +1 -0
  41. package/dist/addons/serialize.d.ts +35 -0
  42. package/dist/addons/serialize.js +313 -0
  43. package/dist/addons/serialize.js.map +1 -0
  44. package/dist/addons/unicode.d.ts +19 -0
  45. package/dist/addons/unicode.js +44 -0
  46. package/dist/addons/unicode.js.map +1 -0
  47. package/dist/addons/web-fonts.d.ts +22 -0
  48. package/dist/addons/web-fonts.js +88 -0
  49. package/dist/addons/web-fonts.js.map +1 -0
  50. package/dist/addons/web-links.d.ts +22 -0
  51. package/dist/addons/web-links.js +89 -0
  52. package/dist/addons/web-links.js.map +1 -0
  53. package/dist/addons/webgl/atlas.d.ts +57 -0
  54. package/dist/addons/webgl/atlas.js +90 -0
  55. package/dist/addons/webgl/atlas.js.map +1 -0
  56. package/dist/addons/webgl/box.d.ts +12 -0
  57. package/dist/addons/webgl/box.js +105 -0
  58. package/dist/addons/webgl/box.js.map +1 -0
  59. package/dist/addons/webgl/frame-model.d.ts +28 -0
  60. package/dist/addons/webgl/frame-model.js +105 -0
  61. package/dist/addons/webgl/frame-model.js.map +1 -0
  62. package/dist/addons/webgl/gl-renderer.d.ts +24 -0
  63. package/dist/addons/webgl/gl-renderer.js +211 -0
  64. package/dist/addons/webgl/gl-renderer.js.map +1 -0
  65. package/dist/addons/webgl/webgl-addon.d.ts +42 -0
  66. package/dist/addons/webgl/webgl-addon.js +185 -0
  67. package/dist/addons/webgl/webgl-addon.js.map +1 -0
  68. package/dist/core/attributes.d.ts +53 -0
  69. package/dist/core/attributes.js +75 -0
  70. package/dist/core/attributes.js.map +1 -0
  71. package/dist/core/buffer-line.d.ts +55 -0
  72. package/dist/core/buffer-line.js +242 -0
  73. package/dist/core/buffer-line.js.map +1 -0
  74. package/dist/core/buffer.d.ts +74 -0
  75. package/dist/core/buffer.js +277 -0
  76. package/dist/core/buffer.js.map +1 -0
  77. package/dist/core/charsets.d.ts +8 -0
  78. package/dist/core/charsets.js +79 -0
  79. package/dist/core/charsets.js.map +1 -0
  80. package/dist/core/circular-list.d.ts +22 -0
  81. package/dist/core/circular-list.js +84 -0
  82. package/dist/core/circular-list.js.map +1 -0
  83. package/dist/core/colors.d.ts +25 -0
  84. package/dist/core/colors.js +111 -0
  85. package/dist/core/colors.js.map +1 -0
  86. package/dist/core/event.d.ts +19 -0
  87. package/dist/core/event.js +39 -0
  88. package/dist/core/event.js.map +1 -0
  89. package/dist/core/index.d.ts +11 -0
  90. package/dist/core/index.js +13 -0
  91. package/dist/core/index.js.map +1 -0
  92. package/dist/core/keyboard.d.ts +76 -0
  93. package/dist/core/keyboard.js +249 -0
  94. package/dist/core/keyboard.js.map +1 -0
  95. package/dist/core/parser.d.ts +73 -0
  96. package/dist/core/parser.js +483 -0
  97. package/dist/core/parser.js.map +1 -0
  98. package/dist/core/terminal-core.d.ts +314 -0
  99. package/dist/core/terminal-core.js +1514 -0
  100. package/dist/core/terminal-core.js.map +1 -0
  101. package/dist/core/unicode.d.ts +36 -0
  102. package/dist/core/unicode.js +185 -0
  103. package/dist/core/unicode.js.map +1 -0
  104. package/dist/index.d.ts +25 -0
  105. package/dist/index.js +30 -0
  106. package/dist/index.js.map +1 -0
  107. package/dist/terminal/buffer-api.d.ts +59 -0
  108. package/dist/terminal/buffer-api.js +174 -0
  109. package/dist/terminal/buffer-api.js.map +1 -0
  110. package/dist/terminal/glyphs.d.ts +7 -0
  111. package/dist/terminal/glyphs.js +135 -0
  112. package/dist/terminal/glyphs.js.map +1 -0
  113. package/dist/terminal/i18n/terminal-catalogs.d.ts +15 -0
  114. package/dist/terminal/i18n/terminal-catalogs.js +22 -0
  115. package/dist/terminal/i18n/terminal-catalogs.js.map +1 -0
  116. package/dist/terminal/i18n/terminal-messages.d.ts +32 -0
  117. package/dist/terminal/i18n/terminal-messages.en.d.ts +2 -0
  118. package/dist/terminal/i18n/terminal-messages.en.js +23 -0
  119. package/dist/terminal/i18n/terminal-messages.en.js.map +1 -0
  120. package/dist/terminal/i18n/terminal-messages.es.d.ts +2 -0
  121. package/dist/terminal/i18n/terminal-messages.es.js +23 -0
  122. package/dist/terminal/i18n/terminal-messages.es.js.map +1 -0
  123. package/dist/terminal/i18n/terminal-messages.js +23 -0
  124. package/dist/terminal/i18n/terminal-messages.js.map +1 -0
  125. package/dist/terminal/renderer.d.ts +120 -0
  126. package/dist/terminal/renderer.js +585 -0
  127. package/dist/terminal/renderer.js.map +1 -0
  128. package/dist/terminal/styles.d.ts +2 -0
  129. package/dist/terminal/styles.js +117 -0
  130. package/dist/terminal/styles.js.map +1 -0
  131. package/dist/terminal/terminal-messages.d.ts +2 -0
  132. package/dist/terminal/terminal-messages.js +5 -0
  133. package/dist/terminal/terminal-messages.js.map +1 -0
  134. package/dist/terminal/terminal-view.d.ts +118 -0
  135. package/dist/terminal/terminal-view.js +388 -0
  136. package/dist/terminal/terminal-view.js.map +1 -0
  137. package/dist/terminal/terminal.d.ts +198 -0
  138. package/dist/terminal/terminal.js +1468 -0
  139. package/dist/terminal/terminal.js.map +1 -0
  140. package/dist/terminal/token-theme.d.ts +12 -0
  141. package/dist/terminal/token-theme.js +66 -0
  142. package/dist/terminal/token-theme.js.map +1 -0
  143. package/dist/terminal/types.d.ts +364 -0
  144. package/dist/terminal/types.js +2 -0
  145. package/dist/terminal/types.js.map +1 -0
  146. package/package.json +31 -23
  147. package/fesm2022/trismegisto-terminal.mjs +0 -9717
  148. package/fesm2022/trismegisto-terminal.mjs.map +0 -1
  149. package/types/trismegisto-terminal.d.ts +0 -1952
  150. package/types/trismegisto-terminal.d.ts.map +0 -1
@@ -0,0 +1,1514 @@
1
+ // O terminal sem tela: estado (buffers, cursor, atributos, modos, cores), as sequências de controle e os eventos.
2
+ // A renderização (DOM) e a classe pública `Terminal` ficam por cima disto; aqui não há DOM nenhum, o que deixa tudo
3
+ // testável e utilizável sem navegador.
4
+ //
5
+ // Sequências: XTerm Control Sequences (Thomas Dickey), ECMA-48 e a documentação dos VT100/VT220/VT510 da DEC.
6
+ import { AttributeData, color, ColorMode, DEFAULT_COLOR, Flags, UnderlineStyle } from './attributes';
7
+ import { Buffer } from './buffer';
8
+ import { emptyCell } from './buffer-line';
9
+ import { ALL_CHARSETS, translate } from './charsets';
10
+ import { ColorState, formatColorSpec, parseColorSpec } from './colors';
11
+ import { Emitter } from './event';
12
+ import { Parser } from './parser';
13
+ import { propsJoins, propsWidth, UnicodeService } from './unicode';
14
+ export const DEFAULT_CORE_OPTIONS = {
15
+ cols: 80,
16
+ rows: 24,
17
+ scrollback: 1000,
18
+ tabStopWidth: 8,
19
+ convertEol: false,
20
+ scrollOnEraseInDisplay: false,
21
+ cursorStyle: 'block',
22
+ cursorBlink: false,
23
+ disableStdin: false,
24
+ allowSetCursorBlink: false,
25
+ reflowCursorLine: false,
26
+ windowsPty: {},
27
+ vtExtensions: {},
28
+ windowOptions: {},
29
+ logLevel: 'info',
30
+ logger: null,
31
+ };
32
+ const LOG_ORDER = ['trace', 'debug', 'info', 'warn', 'error', 'off'];
33
+ /** Os modos que a API pública expõe (`IModes`), mais os internos. */
34
+ export class Modes {
35
+ applicationCursorKeysMode = false;
36
+ applicationKeypadMode = false;
37
+ bracketedPasteMode = false;
38
+ insertMode = false;
39
+ mouseTrackingMode = 'none';
40
+ /** Formato das coordenadas do mouse: 1005 (UTF-8), 1006 (SGR), 1015 (urxvt), 1016 (SGR em pixels). */
41
+ mouseEncoding = 'default';
42
+ /** Codificação SGR (1006 ou 1016) das coordenadas do mouse. */
43
+ get mouseSgrEncoding() {
44
+ return this.mouseEncoding === 'sgr' || this.mouseEncoding === 'sgr-pixels';
45
+ }
46
+ /** win32-input-mode (DECSET 9001): teclas como registros INPUT_RECORD. */
47
+ win32InputMode = false;
48
+ /** DECSET 2031: avisar quando o esquema de cores (claro/escuro) muda. */
49
+ colorSchemeUpdates = false;
50
+ /** Protocolo de teclado do kitty: pilha de flags por tela (a de cima vale). */
51
+ kittyKeyboardNormal = [];
52
+ kittyKeyboardAlt = [];
53
+ originMode = false;
54
+ reverseWraparoundMode = false;
55
+ sendFocusMode = false;
56
+ showCursor = true;
57
+ synchronizedOutputMode = false;
58
+ wraparoundMode = true;
59
+ /** LNM: LF também volta ao início da linha. */
60
+ newlineMode = false;
61
+ cursorBlinkOverride = null;
62
+ }
63
+ /** Marcador de uma linha do buffer normal, que acompanha a linha enquanto o texto rola (API `IMarker`). */
64
+ export class Marker {
65
+ line;
66
+ static nextId = 1;
67
+ id = Marker.nextId++;
68
+ isDisposed = false;
69
+ disposeEmitter = new Emitter();
70
+ onDispose = this.disposeEmitter.event;
71
+ constructor(line) {
72
+ this.line = line;
73
+ }
74
+ dispose() {
75
+ if (this.isDisposed)
76
+ return;
77
+ this.isDisposed = true;
78
+ this.line = -1;
79
+ this.disposeEmitter.fire();
80
+ this.disposeEmitter.dispose();
81
+ }
82
+ }
83
+ export class TerminalCore {
84
+ options;
85
+ parser = new Parser();
86
+ unicode = new UnicodeService();
87
+ modes = new Modes();
88
+ colors = new ColorState();
89
+ normal;
90
+ alt;
91
+ buffer;
92
+ curAttr = new AttributeData();
93
+ charsets = [null, null, null, null];
94
+ glevel = 0;
95
+ title = '';
96
+ links = new Map();
97
+ nextLinkId = 1;
98
+ markers = [];
99
+ /** Último caractere impresso (para REP). */
100
+ lastPrinted = '';
101
+ /** Seleção: âncora e ponta em coordenadas absolutas; `null` sem seleção. */
102
+ selection = null;
103
+ /** Medidas em pixels, dadas pela renderização (sem tela, zero). */
104
+ pixelMetrics = { cellWidth: 0, cellHeight: 0 };
105
+ /** Pilha de títulos (XTWINOPS 22/23). */
106
+ titleStack = [];
107
+ /** Pedidos de janela que o terminal não faz sozinho (mover, iconizar…), para quem hospeda decidir. */
108
+ windowRequestEmitter = new Emitter();
109
+ onWindowRequest = this.windowRequestEmitter.event;
110
+ /** Flags ativas do protocolo de teclado do kitty (0 sem a extensão). */
111
+ get kittyKeyboardFlags() {
112
+ if (!this.options.vtExtensions.kittyKeyboard)
113
+ return 0;
114
+ const stack = this.buffer === this.alt ? this.modes.kittyKeyboardAlt : this.modes.kittyKeyboardNormal;
115
+ return stack.length ? stack[stack.length - 1] : 0;
116
+ }
117
+ /** Registra no `logger` (ou no console), respeitando `logLevel`. */
118
+ log(level, message, ...args) {
119
+ if (LOG_ORDER.indexOf(level) < LOG_ORDER.indexOf(this.options.logLevel))
120
+ return;
121
+ const target = this.options.logger ?? console;
122
+ target[level](`[hermes-terminal] ${message}`, ...args);
123
+ }
124
+ /** Sem as heurísticas do pty do Windows, ou ConPTY novo o bastante para re-quebrar (build 21376+). */
125
+ get windowsReflowOk() {
126
+ const w = this.options.windowsPty;
127
+ if (w.backend === undefined && w.buildNumber === undefined)
128
+ return true;
129
+ return w.backend === 'conpty' && (w.buildNumber ?? 0) >= 21376;
130
+ }
131
+ writeQueue = [];
132
+ writing = false;
133
+ decoder = new TextDecoder('utf-8');
134
+ /** Linhas tocadas desde o último aviso (para a renderização redesenhar só o necessário). */
135
+ dirtyStart = Number.POSITIVE_INFINITY;
136
+ dirtyEnd = -1;
137
+ dataEmitter = new Emitter();
138
+ binaryEmitter = new Emitter();
139
+ bellEmitter = new Emitter();
140
+ titleEmitter = new Emitter();
141
+ lineFeedEmitter = new Emitter();
142
+ cursorMoveEmitter = new Emitter();
143
+ scrollEmitter = new Emitter();
144
+ resizeEmitter = new Emitter();
145
+ writeParsedEmitter = new Emitter();
146
+ bufferChangeEmitter = new Emitter();
147
+ dirtyEmitter = new Emitter();
148
+ selectionEmitter = new Emitter();
149
+ cursorStyleEmitter = new Emitter();
150
+ colorsEmitter = new Emitter();
151
+ /** Dados para o processo do outro lado: o que a pessoa digita e as respostas às consultas. */
152
+ onData = this.dataEmitter.event;
153
+ /** Dados binários (relatório de mouse X10 com coordenadas acima de 95). */
154
+ onBinary = this.binaryEmitter.event;
155
+ onBell = this.bellEmitter.event;
156
+ onTitleChange = this.titleEmitter.event;
157
+ onLineFeed = this.lineFeedEmitter.event;
158
+ onCursorMove = this.cursorMoveEmitter.event;
159
+ onScroll = this.scrollEmitter.event;
160
+ onResize = this.resizeEmitter.event;
161
+ onWriteParsed = this.writeParsedEmitter.event;
162
+ onBufferChange = this.bufferChangeEmitter.event;
163
+ /** Linhas da tela (`start`–`end`, relativas ao topo da tela) que mudaram. */
164
+ onDirty = this.dirtyEmitter.event;
165
+ onSelectionChange = this.selectionEmitter.event;
166
+ onCursorStyleChange = this.cursorStyleEmitter.event;
167
+ onColorsChange = this.colorsEmitter.event;
168
+ constructor(options = {}) {
169
+ this.options = { ...DEFAULT_CORE_OPTIONS, ...options };
170
+ this.normal = new Buffer('normal', this.options.cols, this.options.rows, this.options.scrollback);
171
+ this.alt = new Buffer('alternate', this.options.cols, this.options.rows, 0);
172
+ this.buffer = this.normal;
173
+ this.applyTabStops();
174
+ this.registerHandlers();
175
+ this.lastScheme = this.isDarkScheme();
176
+ }
177
+ get cols() {
178
+ return this.buffer.cols;
179
+ }
180
+ get rows() {
181
+ return this.buffer.rows;
182
+ }
183
+ dispose() {
184
+ for (const emitter of [
185
+ this.dataEmitter, this.binaryEmitter, this.bellEmitter, this.titleEmitter, this.lineFeedEmitter, this.cursorMoveEmitter,
186
+ this.scrollEmitter, this.resizeEmitter, this.writeParsedEmitter, this.bufferChangeEmitter, this.dirtyEmitter,
187
+ this.selectionEmitter, this.cursorStyleEmitter, this.colorsEmitter,
188
+ ])
189
+ emitter.dispose();
190
+ for (const marker of [...this.markers])
191
+ marker.dispose();
192
+ }
193
+ // ---------------------------------------------------------------- escrita
194
+ /** Põe na fila; o texto é analisado em seguida (fora da pilha de quem chamou), na ordem, e `callback` avisa. */
195
+ write(data, callback) {
196
+ this.writeQueue.push({ data, callback });
197
+ if (!this.writing) {
198
+ this.writing = true;
199
+ queueMicrotask(() => void this.drain());
200
+ }
201
+ }
202
+ /** Analisa já (testes e quem precisa do estado na hora). Manipuladores assíncronos ainda atrasam o resto. */
203
+ writeSync(data) {
204
+ const text = typeof data === 'string' ? data : this.decoder.decode(data, { stream: true });
205
+ const result = this.parser.parse(text);
206
+ this.flushDirty();
207
+ if (result instanceof Promise)
208
+ return result.then(() => this.flushDirty());
209
+ }
210
+ async drain() {
211
+ while (this.writeQueue.length) {
212
+ const { data, callback } = this.writeQueue.shift();
213
+ const pending = this.writeSync(data);
214
+ if (pending)
215
+ await pending;
216
+ this.writeParsedEmitter.fire();
217
+ callback?.();
218
+ }
219
+ this.writing = false;
220
+ }
221
+ /** Manda para o processo do outro lado (respostas e entrada). */
222
+ triggerData(data, wasUserInput = true) {
223
+ if (this.options.disableStdin && wasUserInput)
224
+ return;
225
+ this.dataEmitter.fire(data);
226
+ }
227
+ triggerBinary(data) {
228
+ if (!this.options.disableStdin)
229
+ this.binaryEmitter.fire(data);
230
+ }
231
+ reply(data) {
232
+ if (!this.options.disableStdin)
233
+ this.dataEmitter.fire(data);
234
+ }
235
+ // ---------------------------------------------------------------- linhas sujas
236
+ markDirty(y, end = y) {
237
+ this.dirtyStart = Math.min(this.dirtyStart, y);
238
+ this.dirtyEnd = Math.max(this.dirtyEnd, end);
239
+ }
240
+ markAllDirty() {
241
+ this.markDirty(0, this.rows - 1);
242
+ }
243
+ flushDirty() {
244
+ if (this.dirtyEnd < 0)
245
+ return;
246
+ const start = Math.max(0, this.dirtyStart);
247
+ const end = Math.min(this.rows - 1, this.dirtyEnd);
248
+ this.dirtyStart = Number.POSITIVE_INFINITY;
249
+ this.dirtyEnd = -1;
250
+ this.dirtyEmitter.fire({ start, end });
251
+ }
252
+ // ---------------------------------------------------------------- impressão
253
+ print(data, start, end) {
254
+ const b = this.buffer;
255
+ const charset = this.charsets[this.glevel];
256
+ this.markDirty(b.y);
257
+ for (let i = start; i < end;) {
258
+ const code = data.codePointAt(i);
259
+ const size = code > 0xffff ? 2 : 1;
260
+ let char = data.slice(i, i + size);
261
+ i += size;
262
+ if (charset && size === 1)
263
+ char = translate(char, charset);
264
+ const cp = char.codePointAt(0);
265
+ // O estado do grafema só vale se o cursor não saiu de onde o último caractere foi escrito.
266
+ const here = b.wrapPending ? -1 - (b.y * b.cols + b.x) : b.y * b.cols + b.x;
267
+ const preceding = this.graphemeAt === here && b === this.graphemeBuffer ? this.graphemeProps : 0;
268
+ const props = this.unicode.charProperties(cp, preceding);
269
+ const width = propsWidth(props);
270
+ if (propsJoins(props) || width === 0) {
271
+ this.combine(char, width);
272
+ this.graphemeProps = props;
273
+ this.graphemeAt = b.wrapPending ? -1 - (b.y * b.cols + b.x) : b.y * b.cols + b.x;
274
+ continue;
275
+ }
276
+ if (b.wrapPending)
277
+ this.wrapOrOverwrite();
278
+ // Caractere largo na última coluna: quebra antes (com quebra automática) ou não cabe.
279
+ if (width === 2 && b.x === b.cols - 1) {
280
+ if (!this.modes.wraparoundMode)
281
+ continue;
282
+ b.line(b.y).eraseCell(b.x, this.curAttr.eraseAttributes());
283
+ b.wrapPending = true;
284
+ this.wrapOrOverwrite();
285
+ }
286
+ const line = b.line(b.y);
287
+ if (this.modes.insertMode)
288
+ line.insertCells(b.x, width, this.curAttr.eraseAttributes());
289
+ this.breakWideAt(line, b.x, width);
290
+ line.setCell(b.x, char, width, this.curAttr);
291
+ if (width === 2 && b.x + 1 < b.cols)
292
+ line.setCell(b.x + 1, '', 0, this.curAttr);
293
+ this.lastPrinted = char;
294
+ if (b.x + width >= b.cols) {
295
+ b.x = b.cols - 1;
296
+ b.wrapPending = this.modes.wraparoundMode;
297
+ }
298
+ else {
299
+ b.x += width;
300
+ }
301
+ this.graphemeProps = props;
302
+ this.graphemeBuffer = b;
303
+ this.graphemeAt = b.wrapPending ? -1 - (b.y * b.cols + b.x) : b.y * b.cols + b.x;
304
+ }
305
+ this.cursorMoveEmitter.fire();
306
+ }
307
+ /** Estado do último grafema escrito e onde o cursor ficou (para juntar o próximo caractere a ele). */
308
+ graphemeProps = 0;
309
+ graphemeAt = Number.NaN;
310
+ graphemeBuffer = null;
311
+ /** Escrever por cima de metade de um caractere largo apaga a outra metade. */
312
+ breakWideAt(line, x, width) {
313
+ const erase = this.curAttr.eraseAttributes();
314
+ if (line.getWidth(x) === 0 && x > 0)
315
+ line.eraseCell(x - 1, erase);
316
+ const after = x + width;
317
+ if (after < line.length && line.getWidth(after) === 0 && line.getWidth(after - 1) === 2)
318
+ line.eraseCell(after, erase);
319
+ if (width === 1 && line.getWidth(x) === 2 && x + 1 < line.length)
320
+ line.eraseCell(x + 1, erase);
321
+ }
322
+ /**
323
+ * Junta o caractere à célula escrita por último (combinante, ZWJ, tom de pele…). Se o grafema passa a ter largura
324
+ * 2 (VS16, bandeira), a célula alarga e o cursor anda uma coluna, quando cabe.
325
+ */
326
+ combine(char, width = 0) {
327
+ const b = this.buffer;
328
+ let x = b.wrapPending ? b.x : b.x - 1;
329
+ if (x < 0)
330
+ return;
331
+ const line = b.line(b.y);
332
+ if (line.getWidth(x) === 0 && x > 0)
333
+ x--;
334
+ line.addCombining(x, char);
335
+ if (width === 2 && line.getWidth(x) === 1 && x + 1 < b.cols && !b.wrapPending) {
336
+ const chars = line.getChars(x);
337
+ this.breakWideAt(line, x + 1, 1);
338
+ line.setCell(x, chars, 2, this.curAttr);
339
+ line.setCell(x + 1, '', 0, this.curAttr);
340
+ if (x + 2 >= b.cols) {
341
+ b.x = b.cols - 1;
342
+ b.wrapPending = this.modes.wraparoundMode;
343
+ }
344
+ else
345
+ b.x = x + 2;
346
+ }
347
+ }
348
+ /** A quebra pendente: vai para a próxima linha (marcada como continuação) ou, sem DECAWM, fica na última coluna. */
349
+ wrapOrOverwrite() {
350
+ const b = this.buffer;
351
+ b.wrapPending = false;
352
+ if (!this.modes.wraparoundMode)
353
+ return;
354
+ b.x = 0;
355
+ if (b.y === b.scrollBottom) {
356
+ this.scrollUp(true);
357
+ }
358
+ else if (b.y < b.rows - 1) {
359
+ b.y++;
360
+ b.line(b.y).isWrapped = true;
361
+ }
362
+ this.markDirty(b.y);
363
+ }
364
+ // ---------------------------------------------------------------- movimento e rolagem
365
+ scrollUp(isWrapped = false) {
366
+ const trimmed = this.buffer.scrollUp(this.curAttr, isWrapped);
367
+ if (trimmed)
368
+ this.trimMarkers(trimmed);
369
+ this.markDirty(this.buffer.scrollTop, this.buffer.scrollBottom);
370
+ this.scrollEmitter.fire(this.buffer.ydisp);
371
+ }
372
+ trimMarkers(count) {
373
+ for (const marker of [...this.markers]) {
374
+ marker.line -= count;
375
+ if (marker.line < 0)
376
+ this.removeMarker(marker);
377
+ }
378
+ }
379
+ removeMarker(marker) {
380
+ const index = this.markers.indexOf(marker);
381
+ if (index >= 0)
382
+ this.markers.splice(index, 1);
383
+ marker.dispose();
384
+ }
385
+ /** IND/LF: desce uma linha; no fim da região, rola. */
386
+ index() {
387
+ const b = this.buffer;
388
+ b.wrapPending = false;
389
+ if (b.y === b.scrollBottom)
390
+ this.scrollUp();
391
+ else if (b.y < b.rows - 1)
392
+ b.y++;
393
+ this.markDirty(b.y);
394
+ }
395
+ lineFeed() {
396
+ const b = this.buffer;
397
+ const previous = b.line(b.y);
398
+ this.index();
399
+ // Pty antigo do Windows: ele mesmo quebra as linhas e manda CR LF; a linha que acabou cheia (último caractere não
400
+ // branco) conta como quebrada, para a seleção e a busca juntarem o texto.
401
+ if (!this.windowsReflowOk && b === this.normal) {
402
+ const last = previous.getChars(b.cols - 1);
403
+ if (last && last.trim())
404
+ b.line(b.y).isWrapped = true;
405
+ }
406
+ if (this.modes.newlineMode || this.options.convertEol)
407
+ this.buffer.x = 0;
408
+ this.lineFeedEmitter.fire();
409
+ this.cursorMoveEmitter.fire();
410
+ }
411
+ /** RI: sobe uma linha; no topo da região, rola para baixo. */
412
+ reverseIndex() {
413
+ const b = this.buffer;
414
+ b.wrapPending = false;
415
+ if (b.y === b.scrollTop) {
416
+ b.scrollDown(this.curAttr);
417
+ this.markDirty(b.scrollTop, b.scrollBottom);
418
+ }
419
+ else if (b.y > 0)
420
+ b.y--;
421
+ }
422
+ carriageReturn() {
423
+ this.buffer.x = 0;
424
+ this.buffer.wrapPending = false;
425
+ }
426
+ backspace() {
427
+ const b = this.buffer;
428
+ if (b.wrapPending) {
429
+ b.wrapPending = false;
430
+ return;
431
+ }
432
+ if (b.x > 0) {
433
+ b.x--;
434
+ return;
435
+ }
436
+ // Rolagem reversa (DEC 45): do começo de uma continuação, volta para o fim da linha de cima.
437
+ if (this.modes.reverseWraparoundMode && b.y > 0 && b.line(b.y).isWrapped) {
438
+ b.y--;
439
+ b.x = b.cols - 1;
440
+ }
441
+ }
442
+ tab() {
443
+ const b = this.buffer;
444
+ b.wrapPending = false;
445
+ b.x = b.nextTab(b.x);
446
+ }
447
+ /** Limites verticais do cursor: a região de rolagem com DECOM, a tela inteira sem. */
448
+ cursorBounds() {
449
+ const b = this.buffer;
450
+ return this.modes.originMode ? { top: b.scrollTop, bottom: b.scrollBottom } : { top: 0, bottom: b.rows - 1 };
451
+ }
452
+ /** CUP: linha e coluna a partir de 1 (relativas à região com DECOM). */
453
+ cursorTo(row, col) {
454
+ const b = this.buffer;
455
+ const { top, bottom } = this.cursorBounds();
456
+ b.wrapPending = false;
457
+ b.x = Math.max(0, Math.min(b.cols - 1, col - 1));
458
+ b.y = Math.max(top, Math.min(bottom, top + row - 1));
459
+ this.cursorMoveEmitter.fire();
460
+ }
461
+ /** Movimento relativo que para nas margens da região de rolagem (CUU/CUD dentro dela). */
462
+ moveVertical(delta) {
463
+ const b = this.buffer;
464
+ b.wrapPending = false;
465
+ const top = b.y >= b.scrollTop ? b.scrollTop : 0;
466
+ const bottom = b.y <= b.scrollBottom ? b.scrollBottom : b.rows - 1;
467
+ b.y = Math.max(top, Math.min(bottom, b.y + delta));
468
+ this.cursorMoveEmitter.fire();
469
+ }
470
+ moveHorizontal(delta) {
471
+ const b = this.buffer;
472
+ b.wrapPending = false;
473
+ b.x = Math.max(0, Math.min(b.cols - 1, b.x + delta));
474
+ this.cursorMoveEmitter.fire();
475
+ }
476
+ // ---------------------------------------------------------------- apagar
477
+ eraseInLine(y, start, end) {
478
+ const b = this.buffer;
479
+ const line = b.line(y);
480
+ line.fill(this.curAttr.eraseAttributes(), start, end);
481
+ if (start === 0 && end >= b.cols)
482
+ line.isWrapped = false;
483
+ if (end >= b.cols && y + 1 < b.rows)
484
+ b.line(y + 1).isWrapped = false;
485
+ this.markDirty(y);
486
+ }
487
+ /** ED/DECSED. */
488
+ eraseInDisplay(mode) {
489
+ const b = this.buffer;
490
+ switch (mode) {
491
+ case 0:
492
+ this.eraseInLine(b.y, b.x, b.cols);
493
+ for (let y = b.y + 1; y < b.rows; y++)
494
+ this.eraseInLine(y, 0, b.cols);
495
+ break;
496
+ case 1:
497
+ for (let y = 0; y < b.y; y++)
498
+ this.eraseInLine(y, 0, b.cols);
499
+ this.eraseInLine(b.y, 0, b.x + 1);
500
+ break;
501
+ case 2:
502
+ if (this.options.scrollOnEraseInDisplay && b === this.normal) {
503
+ // A tela atual vai para o histórico antes de limpar.
504
+ let last = b.rows - 1;
505
+ while (last >= 0 && b.line(last).getTrimmedLength() === 0)
506
+ last--;
507
+ for (let i = 0; i <= last; i++)
508
+ this.scrollUp();
509
+ }
510
+ for (let y = 0; y < b.rows; y++)
511
+ this.eraseInLine(y, 0, b.cols);
512
+ break;
513
+ case 3:
514
+ this.clearScrollback();
515
+ break;
516
+ }
517
+ }
518
+ /** ED 3 e `clear()`: some o histórico; a tela fica. */
519
+ clearScrollback() {
520
+ const b = this.normal;
521
+ if (!b.ybase)
522
+ return;
523
+ b.lines.trimStart(b.ybase);
524
+ this.trimMarkers(b.ybase);
525
+ b.ybase = 0;
526
+ b.ydisp = 0;
527
+ this.scrollEmitter.fire(0);
528
+ }
529
+ // ---------------------------------------------------------------- inserir e apagar linhas e caracteres
530
+ insertLines(count) {
531
+ const b = this.buffer;
532
+ if (b.y < b.scrollTop || b.y > b.scrollBottom)
533
+ return;
534
+ count = Math.min(count, b.scrollBottom - b.y + 1);
535
+ for (let i = 0; i < count; i++) {
536
+ b.lines.splice(b.ybase + b.scrollBottom, 1);
537
+ b.lines.splice(b.ybase + b.y, 0, b.blankLine(this.curAttr.eraseAttributes()));
538
+ }
539
+ b.x = 0;
540
+ b.wrapPending = false;
541
+ this.markDirty(b.y, b.scrollBottom);
542
+ }
543
+ deleteLines(count) {
544
+ const b = this.buffer;
545
+ if (b.y < b.scrollTop || b.y > b.scrollBottom)
546
+ return;
547
+ count = Math.min(count, b.scrollBottom - b.y + 1);
548
+ for (let i = 0; i < count; i++) {
549
+ b.lines.splice(b.ybase + b.y, 1);
550
+ b.lines.splice(b.ybase + b.scrollBottom, 0, b.blankLine(this.curAttr.eraseAttributes()));
551
+ }
552
+ b.x = 0;
553
+ b.wrapPending = false;
554
+ this.markDirty(b.y, b.scrollBottom);
555
+ }
556
+ // ---------------------------------------------------------------- cursor salvo e telas
557
+ saveCursor() {
558
+ const b = this.buffer;
559
+ b.saved = {
560
+ x: b.x,
561
+ y: b.y,
562
+ attr: this.curAttr.clone(),
563
+ charsets: [...this.charsets],
564
+ glevel: this.glevel,
565
+ originMode: this.modes.originMode,
566
+ wrapPending: b.wrapPending,
567
+ };
568
+ }
569
+ restoreCursor() {
570
+ const b = this.buffer;
571
+ const saved = b.saved;
572
+ if (!saved) {
573
+ b.x = 0;
574
+ b.y = 0;
575
+ b.wrapPending = false;
576
+ this.curAttr.reset();
577
+ this.modes.originMode = false;
578
+ return;
579
+ }
580
+ b.x = Math.min(saved.x, b.cols - 1);
581
+ b.y = Math.min(saved.y, b.rows - 1);
582
+ b.wrapPending = saved.wrapPending;
583
+ this.curAttr = saved.attr.clone();
584
+ this.charsets = [...saved.charsets];
585
+ this.glevel = saved.glevel;
586
+ this.modes.originMode = saved.originMode;
587
+ this.cursorMoveEmitter.fire();
588
+ }
589
+ useAltBuffer(clear) {
590
+ if (this.buffer === this.alt)
591
+ return;
592
+ this.alt.resize(this.normal.cols, this.normal.rows, this.curAttr);
593
+ this.alt.x = this.normal.x;
594
+ this.alt.y = this.normal.y;
595
+ if (clear)
596
+ for (let y = 0; y < this.alt.rows; y++)
597
+ this.alt.line(y).fill(this.curAttr.eraseAttributes());
598
+ this.buffer = this.alt;
599
+ this.clearSelection();
600
+ this.markAllDirty();
601
+ this.bufferChangeEmitter.fire(this.buffer);
602
+ }
603
+ useNormalBuffer() {
604
+ if (this.buffer === this.normal)
605
+ return;
606
+ this.normal.x = this.alt.x;
607
+ this.normal.y = this.alt.y;
608
+ this.buffer = this.normal;
609
+ this.clearSelection();
610
+ this.markAllDirty();
611
+ this.bufferChangeEmitter.fire(this.buffer);
612
+ }
613
+ // ---------------------------------------------------------------- redimensionar e redefinir
614
+ resize(cols, rows) {
615
+ cols = Math.max(2, Math.floor(cols));
616
+ rows = Math.max(1, Math.floor(rows));
617
+ if (cols === this.cols && rows === this.rows)
618
+ return;
619
+ const w = this.options.windowsPty;
620
+ const map = this.normal.resize(cols, rows, this.curAttr, {
621
+ reflow: this.windowsReflowOk,
622
+ reflowCursorLine: this.options.reflowCursorLine,
623
+ growIntoScrollback: w.backend !== undefined || w.buildNumber !== undefined,
624
+ });
625
+ // Os marcadores acompanham o texto na re-quebra (e somem com a linha que sai do histórico).
626
+ for (const marker of [...this.markers]) {
627
+ const line = map(marker.line);
628
+ if (line < 0)
629
+ this.removeMarker(marker);
630
+ else
631
+ marker.line = line;
632
+ }
633
+ this.alt.resize(cols, rows, this.curAttr);
634
+ this.options.cols = cols;
635
+ this.options.rows = rows;
636
+ this.clearSelection();
637
+ this.markAllDirty();
638
+ this.flushDirty();
639
+ this.resizeEmitter.fire({ cols, rows });
640
+ }
641
+ applyTabStops() {
642
+ for (const b of [this.normal, this.alt]) {
643
+ b.tabs.clear();
644
+ for (let x = this.options.tabStopWidth; x < b.cols; x += this.options.tabStopWidth)
645
+ b.tabs.add(x);
646
+ }
647
+ }
648
+ setScrollback(scrollback) {
649
+ this.options.scrollback = scrollback;
650
+ const dropped = this.normal.setScrollback(scrollback);
651
+ if (dropped)
652
+ this.trimMarkers(dropped);
653
+ }
654
+ /** RIS: volta tudo ao estado inicial (o tamanho fica). */
655
+ reset() {
656
+ const { cols, rows } = this;
657
+ this.normal = new Buffer('normal', cols, rows, this.options.scrollback);
658
+ this.alt = new Buffer('alternate', cols, rows, 0);
659
+ this.buffer = this.normal;
660
+ this.applyTabStops();
661
+ this.curAttr = new AttributeData();
662
+ this.charsets = [null, null, null, null];
663
+ this.glevel = 0;
664
+ Object.assign(this.modes, new Modes());
665
+ this.colors.reset();
666
+ this.parser.reset();
667
+ this.selection = null;
668
+ for (const marker of [...this.markers])
669
+ this.removeMarker(marker);
670
+ this.markAllDirty();
671
+ this.flushDirty();
672
+ this.bufferChangeEmitter.fire(this.buffer);
673
+ this.cursorStyleEmitter.fire();
674
+ this.colorsEmitter.fire();
675
+ }
676
+ /** DECSTR: a redefinição suave (modos, região, atributos e cursor salvo; o texto fica). */
677
+ softReset() {
678
+ const b = this.buffer;
679
+ this.modes.insertMode = false;
680
+ this.modes.originMode = false;
681
+ this.modes.wraparoundMode = true;
682
+ this.modes.showCursor = true;
683
+ this.modes.applicationCursorKeysMode = false;
684
+ this.modes.applicationKeypadMode = false;
685
+ b.scrollTop = 0;
686
+ b.scrollBottom = b.rows - 1;
687
+ this.curAttr = new AttributeData();
688
+ this.charsets = [null, null, null, null];
689
+ this.glevel = 0;
690
+ b.saved = null;
691
+ b.wrapPending = false;
692
+ }
693
+ // ---------------------------------------------------------------- marcadores
694
+ registerMarker(cursorYOffset = 0) {
695
+ if (this.buffer !== this.normal)
696
+ return undefined;
697
+ const b = this.normal;
698
+ const line = b.ybase + b.y + cursorYOffset;
699
+ if (line < 0 || line >= b.lines.length)
700
+ return undefined;
701
+ const marker = new Marker(line);
702
+ marker.onDispose(() => {
703
+ const index = this.markers.indexOf(marker);
704
+ if (index >= 0)
705
+ this.markers.splice(index, 1);
706
+ });
707
+ this.markers.push(marker);
708
+ return marker;
709
+ }
710
+ // ---------------------------------------------------------------- seleção
711
+ /** Seleciona `length` células a partir de `(column, row)` (linha absoluta), em ordem de leitura. */
712
+ select(column, row, length) {
713
+ const b = this.buffer;
714
+ const startOffset = row * b.cols + column;
715
+ const endOffset = startOffset + Math.max(0, length);
716
+ this.setSelection({ x: startOffset % b.cols, y: Math.floor(startOffset / b.cols) }, { x: endOffset % b.cols, y: Math.floor(endOffset / b.cols) });
717
+ }
718
+ selectLines(start, end) {
719
+ const [from, to] = start <= end ? [start, end] : [end, start];
720
+ this.setSelection({ x: 0, y: from }, { x: this.cols, y: to });
721
+ }
722
+ selectAll() {
723
+ this.setSelection({ x: 0, y: 0 }, { x: this.cols, y: this.buffer.lines.length - 1 });
724
+ }
725
+ setSelection(start, end) {
726
+ const [a, z] = start.y < end.y || (start.y === end.y && start.x <= end.x) ? [start, end] : [end, start];
727
+ this.selection = a.x === z.x && a.y === z.y ? null : { start: { ...a }, end: { ...z } };
728
+ this.selectionEmitter.fire();
729
+ }
730
+ clearSelection() {
731
+ if (!this.selection)
732
+ return;
733
+ this.selection = null;
734
+ this.selectionEmitter.fire();
735
+ }
736
+ hasSelection() {
737
+ return !!this.selection;
738
+ }
739
+ /** O texto selecionado; linhas unidas por quebra automática viram uma linha só. */
740
+ getSelection() {
741
+ const selection = this.selection;
742
+ if (!selection)
743
+ return '';
744
+ const b = this.buffer;
745
+ const out = [];
746
+ for (let y = selection.start.y; y <= selection.end.y; y++) {
747
+ const line = b.lines.get(y);
748
+ if (!line)
749
+ break;
750
+ const from = y === selection.start.y ? selection.start.x : 0;
751
+ const to = y === selection.end.y ? selection.end.x : b.cols;
752
+ const next = b.lines.get(y + 1);
753
+ const continues = y < selection.end.y && !!next?.isWrapped;
754
+ const text = line.translateToString(!continues, from, to);
755
+ if (y > selection.start.y && line.isWrapped)
756
+ out[out.length - 1] += text;
757
+ else
758
+ out.push(text);
759
+ }
760
+ return out.join('\n');
761
+ }
762
+ // ---------------------------------------------------------------- leitura
763
+ getCell(x, y) {
764
+ const line = this.buffer.lines.get(y);
765
+ return line && x >= 0 && x < line.length ? line.loadCell(x, emptyCell()) : undefined;
766
+ }
767
+ // ---------------------------------------------------------------- manipuladores
768
+ registerHandlers() {
769
+ const p = this.parser;
770
+ p.printHandler = (data, start, end) => this.print(data, start, end);
771
+ p.fallback = (kind, key) => this.log('debug', `sequência não tratada: ${kind} ${key}`);
772
+ // C0
773
+ p.setExecuteHandler(0x07, () => this.bellEmitter.fire());
774
+ p.setExecuteHandler(0x08, () => this.backspace());
775
+ p.setExecuteHandler(0x09, () => this.tab());
776
+ p.setExecuteHandler(0x0a, () => this.lineFeed());
777
+ p.setExecuteHandler(0x0b, () => this.lineFeed());
778
+ p.setExecuteHandler(0x0c, () => this.lineFeed());
779
+ p.setExecuteHandler(0x0d, () => this.carriageReturn());
780
+ p.setExecuteHandler(0x0e, () => (this.glevel = 1));
781
+ p.setExecuteHandler(0x0f, () => (this.glevel = 0));
782
+ // ESC
783
+ const esc = (final, run, intermediates) => p.registerEscHandler({ final, intermediates }, () => {
784
+ run();
785
+ return true;
786
+ });
787
+ esc('7', () => this.saveCursor());
788
+ esc('8', () => this.restoreCursor());
789
+ esc('D', () => this.index());
790
+ esc('E', () => {
791
+ this.carriageReturn();
792
+ this.index();
793
+ });
794
+ esc('H', () => this.buffer.tabs.add(this.buffer.x));
795
+ esc('M', () => this.reverseIndex());
796
+ esc('c', () => this.reset());
797
+ esc('=', () => (this.modes.applicationKeypadMode = true));
798
+ esc('>', () => (this.modes.applicationKeypadMode = false));
799
+ esc('8', () => this.alignmentTest(), '#');
800
+ for (const [intermediate, slot] of [['(', 0], [')', 1], ['*', 2], ['+', 3]]) {
801
+ for (const name of Object.keys(ALL_CHARSETS))
802
+ esc(name, () => (this.charsets[slot] = ALL_CHARSETS[name]), intermediate);
803
+ }
804
+ // CSI
805
+ const csi = (final, run, prefix, intermediates) => p.registerCsiHandler({ final, prefix, intermediates }, (params) => {
806
+ run(params);
807
+ this.markDirty(this.buffer.y);
808
+ return true;
809
+ });
810
+ const n = (params, i = 0, fallback = 1) => {
811
+ const value = params[i];
812
+ const v = Array.isArray(value) ? value[0] : value;
813
+ return v === undefined || v <= 0 ? fallback : v;
814
+ };
815
+ const raw = (params, i = 0) => {
816
+ const value = params[i];
817
+ return Array.isArray(value) ? value[0] : (value ?? 0);
818
+ };
819
+ csi('@', (ps) => {
820
+ this.buffer.wrapPending = false;
821
+ this.buffer.line(this.buffer.y).insertCells(this.buffer.x, n(ps), this.curAttr.eraseAttributes());
822
+ });
823
+ csi('A', (ps) => this.moveVertical(-n(ps)));
824
+ csi('B', (ps) => this.moveVertical(n(ps)));
825
+ csi('C', (ps) => this.moveHorizontal(n(ps)));
826
+ csi('D', (ps) => this.moveHorizontal(-n(ps)));
827
+ csi('E', (ps) => {
828
+ this.moveVertical(n(ps));
829
+ this.buffer.x = 0;
830
+ });
831
+ csi('F', (ps) => {
832
+ this.moveVertical(-n(ps));
833
+ this.buffer.x = 0;
834
+ });
835
+ csi('G', (ps) => this.moveHorizontal(n(ps) - 1 - this.buffer.x));
836
+ csi('`', (ps) => this.moveHorizontal(n(ps) - 1 - this.buffer.x));
837
+ csi('a', (ps) => this.moveHorizontal(n(ps)));
838
+ csi('H', (ps) => this.cursorTo(n(ps, 0), n(ps, 1)));
839
+ csi('f', (ps) => this.cursorTo(n(ps, 0), n(ps, 1)));
840
+ csi('d', (ps) => this.cursorTo(n(ps), this.buffer.x + 1));
841
+ csi('e', (ps) => this.moveVertical(n(ps)));
842
+ csi('I', (ps) => {
843
+ for (let i = 0; i < n(ps); i++)
844
+ this.tab();
845
+ });
846
+ csi('Z', (ps) => {
847
+ const b = this.buffer;
848
+ b.wrapPending = false;
849
+ for (let i = 0; i < n(ps); i++)
850
+ b.x = b.prevTab(b.x);
851
+ });
852
+ csi('J', (ps) => this.eraseInDisplay(raw(ps)));
853
+ csi('J', (ps) => this.eraseInDisplay(raw(ps)), '?');
854
+ csi('K', (ps) => this.eraseLineMode(raw(ps)));
855
+ csi('K', (ps) => this.eraseLineMode(raw(ps)), '?');
856
+ csi('L', (ps) => this.insertLines(n(ps)));
857
+ csi('M', (ps) => this.deleteLines(n(ps)));
858
+ csi('P', (ps) => {
859
+ this.buffer.wrapPending = false;
860
+ this.buffer.line(this.buffer.y).deleteCells(this.buffer.x, n(ps), this.curAttr.eraseAttributes());
861
+ });
862
+ csi('S', (ps) => {
863
+ for (let i = 0; i < n(ps); i++)
864
+ this.scrollRegionUp();
865
+ });
866
+ csi('T', (ps) => {
867
+ for (let i = 0; i < n(ps); i++) {
868
+ this.buffer.scrollDown(this.curAttr);
869
+ }
870
+ this.markDirty(this.buffer.scrollTop, this.buffer.scrollBottom);
871
+ });
872
+ csi('X', (ps) => {
873
+ const b = this.buffer;
874
+ b.wrapPending = false;
875
+ b.line(b.y).fill(this.curAttr.eraseAttributes(), b.x, b.x + n(ps));
876
+ });
877
+ csi('b', (ps) => {
878
+ if (!this.lastPrinted)
879
+ return;
880
+ const text = this.lastPrinted.repeat(Math.min(n(ps), this.cols * this.rows));
881
+ this.print(text, 0, text.length);
882
+ });
883
+ csi('c', (ps) => {
884
+ if (raw(ps) === 0)
885
+ this.reply('\x1b[?1;2c');
886
+ });
887
+ csi('c', (ps) => {
888
+ if (raw(ps) === 0)
889
+ this.reply('\x1b[>0;276;0c');
890
+ }, '>');
891
+ csi('g', (ps) => {
892
+ const mode = raw(ps);
893
+ if (mode === 0)
894
+ this.buffer.tabs.delete(this.buffer.x);
895
+ else if (mode === 3)
896
+ this.buffer.tabs.clear();
897
+ });
898
+ csi('h', (ps) => this.setAnsiModes(ps, true));
899
+ csi('l', (ps) => this.setAnsiModes(ps, false));
900
+ csi('h', (ps) => this.setDecModes(ps, true), '?');
901
+ csi('l', (ps) => this.setDecModes(ps, false), '?');
902
+ csi('m', (ps) => this.sgr(ps));
903
+ csi('n', (ps) => this.deviceStatus(raw(ps), false));
904
+ csi('n', (ps) => this.deviceStatus(raw(ps), true), '?');
905
+ csi('r', (ps) => this.setScrollRegion(raw(ps, 0), raw(ps, 1)));
906
+ csi('s', () => this.saveCursor());
907
+ csi('u', () => this.restoreCursor());
908
+ csi('q', (ps) => this.setCursorStyle(raw(ps)), undefined, ' ');
909
+ csi('p', () => this.softReset(), undefined, '!');
910
+ csi('p', (ps) => this.reportAnsiMode(raw(ps)), undefined, '$');
911
+ csi('p', (ps) => this.reportDecMode(raw(ps)), '?', '$');
912
+ csi('t', (ps) => this.windowOp(ps.map((v) => (Array.isArray(v) ? v[0] : v))));
913
+ csi('u', () => this.kittyQuery(), '?');
914
+ csi('u', (ps) => this.kittyPush(raw(ps)), '>');
915
+ csi('u', (ps) => this.kittyPop(n(ps)), '<');
916
+ csi('u', (ps) => this.kittySet(raw(ps, 0), n(ps, 1)), '=');
917
+ p.registerDcsHandler({ intermediates: '$', final: 'q' }, (data) => {
918
+ this.requestStatusString(data);
919
+ return true;
920
+ });
921
+ // OSC
922
+ const osc = (ident, run) => p.registerOscHandler(ident, (data) => {
923
+ run(data);
924
+ return true;
925
+ });
926
+ osc(0, (data) => this.setTitle(data));
927
+ osc(2, (data) => this.setTitle(data));
928
+ osc(1, () => undefined);
929
+ osc(4, (data) => this.oscPalette(data));
930
+ osc(8, (data) => this.oscHyperlink(data));
931
+ osc(10, (data) => this.oscSpecial('foreground', 10, data));
932
+ osc(11, (data) => this.oscSpecial('background', 11, data));
933
+ osc(12, (data) => this.oscSpecial('cursor', 12, data));
934
+ osc(104, (data) => {
935
+ if (!data)
936
+ this.colors.resetPalette();
937
+ else
938
+ for (const part of data.split(';'))
939
+ this.colors.resetPalette(Number(part));
940
+ this.colorsChanged();
941
+ });
942
+ osc(110, () => this.resetSpecialColor('foreground'));
943
+ osc(111, () => this.resetSpecialColor('background'));
944
+ osc(112, () => this.resetSpecialColor('cursor'));
945
+ }
946
+ scrollRegionUp() {
947
+ // SU nunca manda linha para o histórico (só a quebra de linha manda).
948
+ const b = this.buffer;
949
+ b.lines.splice(b.ybase + b.scrollTop, 1);
950
+ b.lines.splice(b.ybase + b.scrollBottom, 0, b.blankLine(this.curAttr.eraseAttributes()));
951
+ this.markDirty(b.scrollTop, b.scrollBottom);
952
+ }
953
+ eraseLineMode(mode) {
954
+ const b = this.buffer;
955
+ if (mode === 0)
956
+ this.eraseInLine(b.y, b.x, b.cols);
957
+ else if (mode === 1)
958
+ this.eraseInLine(b.y, 0, b.x + 1);
959
+ else if (mode === 2)
960
+ this.eraseInLine(b.y, 0, b.cols);
961
+ }
962
+ alignmentTest() {
963
+ const b = this.buffer;
964
+ const attr = new AttributeData();
965
+ for (let y = 0; y < b.rows; y++) {
966
+ const line = b.line(y);
967
+ for (let x = 0; x < b.cols; x++)
968
+ line.setCell(x, 'E', 1, attr);
969
+ line.isWrapped = false;
970
+ }
971
+ b.scrollTop = 0;
972
+ b.scrollBottom = b.rows - 1;
973
+ b.x = 0;
974
+ b.y = 0;
975
+ this.markAllDirty();
976
+ }
977
+ setScrollRegion(top, bottom) {
978
+ const b = this.buffer;
979
+ const t = (top || 1) - 1;
980
+ const bt = (bottom || b.rows) - 1;
981
+ if (t >= bt || bt >= b.rows)
982
+ return;
983
+ b.scrollTop = t;
984
+ b.scrollBottom = bt;
985
+ // DECSTBM leva o cursor para a origem.
986
+ this.cursorTo(1, 1);
987
+ }
988
+ setAnsiModes(params, on) {
989
+ for (const param of params) {
990
+ const mode = Array.isArray(param) ? param[0] : param;
991
+ if (mode === 4)
992
+ this.modes.insertMode = on;
993
+ else if (mode === 20)
994
+ this.modes.newlineMode = on;
995
+ }
996
+ }
997
+ setDecModes(params, on) {
998
+ for (const param of params) {
999
+ const mode = Array.isArray(param) ? param[0] : param;
1000
+ switch (mode) {
1001
+ case 1:
1002
+ this.modes.applicationCursorKeysMode = on;
1003
+ break;
1004
+ case 3:
1005
+ // DECCOLM (132/80 colunas): só com `windowOptions.setWinLines`; muda a largura, limpa e volta à origem.
1006
+ if (this.options.windowOptions.setWinLines) {
1007
+ this.resize(on ? 132 : 80, this.rows);
1008
+ this.eraseInDisplay(2);
1009
+ this.buffer.scrollTop = 0;
1010
+ this.buffer.scrollBottom = this.rows - 1;
1011
+ this.cursorTo(1, 1);
1012
+ }
1013
+ break;
1014
+ case 6:
1015
+ this.modes.originMode = on;
1016
+ this.cursorTo(1, 1);
1017
+ break;
1018
+ case 7:
1019
+ this.modes.wraparoundMode = on;
1020
+ break;
1021
+ case 12:
1022
+ // Programas ligam e esquecem de desligar: só vale com `quirks.allowSetCursorBlink` (o DECRQM responde sempre).
1023
+ if (this.options.allowSetCursorBlink) {
1024
+ this.modes.cursorBlinkOverride = on;
1025
+ this.cursorStyleEmitter.fire();
1026
+ }
1027
+ break;
1028
+ case 25:
1029
+ this.modes.showCursor = on;
1030
+ this.cursorStyleEmitter.fire();
1031
+ break;
1032
+ case 45:
1033
+ this.modes.reverseWraparoundMode = on;
1034
+ break;
1035
+ case 66:
1036
+ this.modes.applicationKeypadMode = on;
1037
+ break;
1038
+ case 9:
1039
+ this.modes.mouseTrackingMode = on ? 'x10' : 'none';
1040
+ break;
1041
+ case 1000:
1042
+ this.modes.mouseTrackingMode = on ? 'vt200' : 'none';
1043
+ break;
1044
+ case 1002:
1045
+ this.modes.mouseTrackingMode = on ? 'drag' : 'none';
1046
+ break;
1047
+ case 1003:
1048
+ this.modes.mouseTrackingMode = on ? 'any' : 'none';
1049
+ break;
1050
+ case 1004:
1051
+ this.modes.sendFocusMode = on;
1052
+ break;
1053
+ case 1005:
1054
+ case 1006:
1055
+ case 1015:
1056
+ case 1016: {
1057
+ const encoding = { 1005: 'utf8', 1006: 'sgr', 1015: 'urxvt', 1016: 'sgr-pixels' }[mode];
1058
+ if (on)
1059
+ this.modes.mouseEncoding = encoding;
1060
+ else if (this.modes.mouseEncoding === encoding)
1061
+ this.modes.mouseEncoding = 'default';
1062
+ break;
1063
+ }
1064
+ case 2031:
1065
+ if (this.options.vtExtensions.colorSchemeQuery !== false)
1066
+ this.modes.colorSchemeUpdates = on;
1067
+ break;
1068
+ case 9001:
1069
+ if (this.options.vtExtensions.win32InputMode)
1070
+ this.modes.win32InputMode = on;
1071
+ break;
1072
+ case 47:
1073
+ case 1047:
1074
+ if (on)
1075
+ this.useAltBuffer(mode === 1047);
1076
+ else
1077
+ this.useNormalBuffer();
1078
+ break;
1079
+ case 1048:
1080
+ if (on)
1081
+ this.saveCursor();
1082
+ else
1083
+ this.restoreCursor();
1084
+ break;
1085
+ case 1049:
1086
+ if (on) {
1087
+ this.saveCursor();
1088
+ this.useAltBuffer(true);
1089
+ }
1090
+ else {
1091
+ this.useNormalBuffer();
1092
+ this.restoreCursor();
1093
+ }
1094
+ break;
1095
+ case 2004:
1096
+ this.modes.bracketedPasteMode = on;
1097
+ break;
1098
+ case 2026:
1099
+ this.modes.synchronizedOutputMode = on;
1100
+ break;
1101
+ }
1102
+ }
1103
+ }
1104
+ /** DECRQM: 1 ligado, 2 desligado, 0 desconhecido. */
1105
+ reportAnsiMode(mode) {
1106
+ const state = mode === 4 ? (this.modes.insertMode ? 1 : 2) : mode === 20 ? (this.modes.newlineMode ? 1 : 2) : 0;
1107
+ this.reply(`\x1b[${mode};${state}$y`);
1108
+ }
1109
+ reportDecMode(mode) {
1110
+ const m = this.modes;
1111
+ const flags = {
1112
+ 1: m.applicationCursorKeysMode,
1113
+ 6: m.originMode,
1114
+ 7: m.wraparoundMode,
1115
+ 12: m.cursorBlinkOverride ?? this.options.cursorBlink,
1116
+ 25: m.showCursor,
1117
+ 45: m.reverseWraparoundMode,
1118
+ 66: m.applicationKeypadMode,
1119
+ 9: m.mouseTrackingMode === 'x10',
1120
+ 1000: m.mouseTrackingMode === 'vt200',
1121
+ 1002: m.mouseTrackingMode === 'drag',
1122
+ 1003: m.mouseTrackingMode === 'any',
1123
+ 1004: m.sendFocusMode,
1124
+ 1005: m.mouseEncoding === 'utf8',
1125
+ 1006: m.mouseEncoding === 'sgr',
1126
+ 1015: m.mouseEncoding === 'urxvt',
1127
+ 1016: m.mouseEncoding === 'sgr-pixels',
1128
+ 2031: m.colorSchemeUpdates,
1129
+ 9001: m.win32InputMode,
1130
+ 47: this.buffer === this.alt,
1131
+ 1047: this.buffer === this.alt,
1132
+ 1049: this.buffer === this.alt,
1133
+ 2004: m.bracketedPasteMode,
1134
+ 2026: m.synchronizedOutputMode,
1135
+ };
1136
+ const state = mode in flags ? (flags[mode] ? 1 : 2) : 0;
1137
+ this.reply(`\x1b[?${mode};${state}$y`);
1138
+ }
1139
+ deviceStatus(mode, dec) {
1140
+ const b = this.buffer;
1141
+ if (mode === 5 && !dec)
1142
+ this.reply('\x1b[0n');
1143
+ // Consulta do esquema de cores: 1 escuro, 2 claro (pela luminância do fundo contra a do texto).
1144
+ if (mode === 996 && dec && this.options.vtExtensions.colorSchemeQuery !== false)
1145
+ this.reply(`\x1b[?997;${this.isDarkScheme() ? 1 : 2}n`);
1146
+ if (mode === 6) {
1147
+ const top = this.modes.originMode ? b.scrollTop : 0;
1148
+ this.reply(`\x1b[${dec ? '?' : ''}${b.y - top + 1};${b.x + 1}R`);
1149
+ }
1150
+ }
1151
+ setCursorStyle(param) {
1152
+ const styles = {
1153
+ 0: ['block', true],
1154
+ 1: ['block', true],
1155
+ 2: ['block', false],
1156
+ 3: ['underline', true],
1157
+ 4: ['underline', false],
1158
+ 5: ['bar', true],
1159
+ 6: ['bar', false],
1160
+ };
1161
+ const style = styles[param];
1162
+ if (!style)
1163
+ return;
1164
+ this.options.cursorStyle = style[0];
1165
+ this.modes.cursorBlinkOverride = style[1];
1166
+ this.cursorStyleEmitter.fire();
1167
+ }
1168
+ // ---------------------------------------------------------------- SGR
1169
+ sgr(params) {
1170
+ const attr = this.curAttr;
1171
+ for (let i = 0; i < params.length; i++) {
1172
+ const param = params[i];
1173
+ const code = Array.isArray(param) ? param[0] : param;
1174
+ if (Array.isArray(param) && (code === 38 || code === 48 || code === 58)) {
1175
+ this.extendedColor(code, param.slice(1));
1176
+ continue;
1177
+ }
1178
+ if (Array.isArray(param) && code === 4) {
1179
+ const style = Math.max(0, param[1] ?? 1);
1180
+ attr.setExtended({ underlineStyle: Math.min(5, style) });
1181
+ if (style === 0)
1182
+ attr.flags &= ~Flags.UNDERLINE;
1183
+ else
1184
+ attr.flags |= Flags.UNDERLINE;
1185
+ continue;
1186
+ }
1187
+ if (code === 38 || code === 48 || code === 58) {
1188
+ // Forma com `;`: os números seguintes pertencem à cor.
1189
+ const kind = params[i + 1];
1190
+ if (kind === 5) {
1191
+ this.extendedColor(code, [5, params[i + 2]]);
1192
+ i += 2;
1193
+ }
1194
+ else if (kind === 2) {
1195
+ this.extendedColor(code, [2, params[i + 2], params[i + 3], params[i + 4]]);
1196
+ i += 4;
1197
+ }
1198
+ continue;
1199
+ }
1200
+ this.sgrSimple(code);
1201
+ }
1202
+ }
1203
+ sgrSimple(code) {
1204
+ const attr = this.curAttr;
1205
+ if (code === 0)
1206
+ return attr.reset();
1207
+ if (code >= 30 && code <= 37)
1208
+ attr.fg = color(ColorMode.P16, code - 30);
1209
+ else if (code >= 40 && code <= 47)
1210
+ attr.bg = color(ColorMode.P16, code - 40);
1211
+ else if (code >= 90 && code <= 97)
1212
+ attr.fg = color(ColorMode.P16, code - 90 + 8);
1213
+ else if (code >= 100 && code <= 107)
1214
+ attr.bg = color(ColorMode.P16, code - 100 + 8);
1215
+ else if (code === 39)
1216
+ attr.fg = DEFAULT_COLOR;
1217
+ else if (code === 49)
1218
+ attr.bg = DEFAULT_COLOR;
1219
+ else if (code === 59)
1220
+ attr.setExtended({ underlineColor: DEFAULT_COLOR });
1221
+ else if ((code === 221 || code === 222) && this.options.vtExtensions.kittySgrBoldFaintControl !== false) {
1222
+ // Extensão do kitty: 221 tira só o negrito; 222, só o esmaecido (o 22 tira os dois).
1223
+ attr.flags &= ~(code === 221 ? Flags.BOLD : Flags.DIM);
1224
+ }
1225
+ else {
1226
+ const on = { 1: Flags.BOLD, 2: Flags.DIM, 3: Flags.ITALIC, 4: Flags.UNDERLINE, 5: Flags.BLINK, 7: Flags.INVERSE, 8: Flags.INVISIBLE, 9: Flags.STRIKETHROUGH, 53: Flags.OVERLINE };
1227
+ const off = { 22: Flags.BOLD | Flags.DIM, 23: Flags.ITALIC, 24: Flags.UNDERLINE, 25: Flags.BLINK, 27: Flags.INVERSE, 28: Flags.INVISIBLE, 29: Flags.STRIKETHROUGH, 55: Flags.OVERLINE };
1228
+ if (code in on) {
1229
+ attr.flags |= on[code];
1230
+ if (code === 4)
1231
+ attr.setExtended({ underlineStyle: UnderlineStyle.SINGLE });
1232
+ }
1233
+ else if (code === 21) {
1234
+ attr.flags |= Flags.UNDERLINE;
1235
+ attr.setExtended({ underlineStyle: UnderlineStyle.DOUBLE });
1236
+ }
1237
+ else if (code in off) {
1238
+ attr.flags &= ~off[code];
1239
+ if (code === 24)
1240
+ attr.setExtended({ underlineStyle: UnderlineStyle.NONE });
1241
+ }
1242
+ }
1243
+ }
1244
+ /** 38/48/58 com `5;n` (paleta) ou `2;r;g;b` (RGB); na forma com `:`, `2` pode trazer o espaço de cor antes. */
1245
+ extendedColor(target, rest) {
1246
+ let value = null;
1247
+ if (rest[0] === 5 && rest[1] !== undefined && rest[1] >= 0)
1248
+ value = color(ColorMode.P256, Math.min(255, rest[1]));
1249
+ if (rest[0] === 2) {
1250
+ const channels = rest.length >= 5 ? rest.slice(2, 5) : rest.slice(1, 4);
1251
+ if (channels.length === 3 && channels.every((c) => c !== undefined)) {
1252
+ const [r, g, b] = channels.map((c) => Math.max(0, Math.min(255, c < 0 ? 0 : c)));
1253
+ value = color(ColorMode.RGB, (r << 16) | (g << 8) | b);
1254
+ }
1255
+ }
1256
+ if (value === null)
1257
+ return;
1258
+ if (target === 38)
1259
+ this.curAttr.fg = value;
1260
+ else if (target === 48)
1261
+ this.curAttr.bg = value;
1262
+ else
1263
+ this.curAttr.setExtended({ underlineColor: value });
1264
+ }
1265
+ // ---------------------------------------------------------------- OSC
1266
+ setTitle(title) {
1267
+ this.title = title;
1268
+ this.titleEmitter.fire(title);
1269
+ }
1270
+ colorsChanged() {
1271
+ this.markAllDirty();
1272
+ this.colorsEmitter.fire();
1273
+ this.notifyColorScheme();
1274
+ }
1275
+ lastScheme = null;
1276
+ /** DECSET 2031: avisa o processo quando o esquema (claro/escuro) muda — pelo OSC ou pelo tema do app. */
1277
+ notifyColorScheme() {
1278
+ const dark = this.isDarkScheme();
1279
+ if (this.lastScheme !== null && dark !== this.lastScheme && this.modes.colorSchemeUpdates)
1280
+ this.reply(`[?997;${dark ? 1 : 2}n`);
1281
+ this.lastScheme = dark;
1282
+ }
1283
+ oscPalette(data) {
1284
+ const parts = data.split(';');
1285
+ let changed = false;
1286
+ for (let i = 0; i + 1 < parts.length; i += 2) {
1287
+ const index = Number(parts[i]);
1288
+ if (!Number.isInteger(index) || index < 0 || index > 255)
1289
+ continue;
1290
+ if (parts[i + 1] === '?') {
1291
+ this.reply(`\x1b]4;${index};${formatColorSpec(this.colors.palette[index])}\x1b\\`);
1292
+ continue;
1293
+ }
1294
+ const rgb = parseColorSpec(parts[i + 1]);
1295
+ if (rgb !== null) {
1296
+ this.colors.palette[index] = rgb;
1297
+ changed = true;
1298
+ }
1299
+ }
1300
+ if (changed)
1301
+ this.colorsChanged();
1302
+ }
1303
+ oscSpecial(which, ident, data) {
1304
+ // OSC 10;cor1;cor2… define a 10, a 11 e a 12 em sequência.
1305
+ const order = ['foreground', 'background', 'cursor'];
1306
+ let slot = order.indexOf(which);
1307
+ let changed = false;
1308
+ for (const spec of data.split(';')) {
1309
+ const target = order[slot];
1310
+ if (!target)
1311
+ break;
1312
+ if (spec === '?')
1313
+ this.reply(`\x1b]${ident + slot - order.indexOf(which)};${formatColorSpec(this.colors[target])}\x1b\\`);
1314
+ else {
1315
+ const rgb = parseColorSpec(spec);
1316
+ if (rgb !== null) {
1317
+ this.colors[target] = rgb;
1318
+ changed = true;
1319
+ }
1320
+ }
1321
+ slot++;
1322
+ }
1323
+ if (changed)
1324
+ this.colorsChanged();
1325
+ }
1326
+ resetSpecialColor(which) {
1327
+ this.colors.resetSpecial(which);
1328
+ this.colorsChanged();
1329
+ }
1330
+ /** OSC 8 ; parâmetros ; URI — URI vazia fecha o link. */
1331
+ oscHyperlink(data) {
1332
+ const separator = data.indexOf(';');
1333
+ if (separator === -1)
1334
+ return;
1335
+ const params = data.slice(0, separator);
1336
+ const uri = data.slice(separator + 1);
1337
+ if (!uri) {
1338
+ this.curAttr.setExtended({ linkId: 0 });
1339
+ return;
1340
+ }
1341
+ const idParam = /(?:^|:)id=([^:]*)/.exec(params)?.[1];
1342
+ // O mesmo `id=` com a mesma URI reaproveita o link (os trechos viram um link só).
1343
+ let link = idParam ? [...this.links.values()].find((l) => l.linkId === idParam && l.uri === uri) : undefined;
1344
+ if (!link) {
1345
+ link = { id: this.nextLinkId++, uri, linkId: idParam };
1346
+ this.links.set(link.id, link);
1347
+ }
1348
+ this.curAttr.setExtended({ linkId: link.id });
1349
+ }
1350
+ // ---------------------------------------------------------------- relatórios e extensões
1351
+ /** Fundo mais escuro que o texto = esquema escuro (luminância relativa, WCAG). */
1352
+ isDarkScheme() {
1353
+ const lum = (rgb) => {
1354
+ const c = [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].map((v) => {
1355
+ const s = v / 255;
1356
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
1357
+ });
1358
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
1359
+ };
1360
+ return lum(this.colors.background) < lum(this.colors.foreground);
1361
+ }
1362
+ /** XTWINOPS (`CSI Ps ; … t`): só o que `windowOptions` liga. O resto vira pedido para quem hospeda. */
1363
+ windowOp(params) {
1364
+ const w = this.options.windowOptions;
1365
+ const op = params[0] ?? 0;
1366
+ const { cellWidth, cellHeight } = this.pixelMetrics;
1367
+ const names = {
1368
+ 1: 'restoreWin', 2: 'minimizeWin', 3: 'setWinPosition', 4: 'setWinSizePixels', 5: 'raiseWin', 6: 'lowerWin',
1369
+ 7: 'refreshWin', 8: 'setWinSizeChars', 9: 'maximizeWin', 10: 'fullscreenWin', 11: 'getWinState',
1370
+ 13: 'getWinPosition', 14: 'getWinSizePixels', 15: 'getScreenSizePixels', 16: 'getCellSizePixels',
1371
+ 18: 'getWinSizeChars', 19: 'getScreenSizeChars', 20: 'getIconTitle', 21: 'getWinTitle', 22: 'pushTitle', 23: 'popTitle',
1372
+ };
1373
+ const name = op >= 24 ? 'setWinLines' : names[op];
1374
+ if (!name || !w[name])
1375
+ return;
1376
+ switch (op) {
1377
+ case 7:
1378
+ this.markAllDirty();
1379
+ return;
1380
+ case 14:
1381
+ if (cellWidth)
1382
+ this.reply(`\x1b[4;${Math.round(this.rows * cellHeight)};${Math.round(this.cols * cellWidth)}t`);
1383
+ return;
1384
+ case 16:
1385
+ if (cellWidth)
1386
+ this.reply(`\x1b[6;${Math.round(cellHeight)};${Math.round(cellWidth)}t`);
1387
+ return;
1388
+ case 18:
1389
+ this.reply(`\x1b[8;${this.rows};${this.cols}t`);
1390
+ return;
1391
+ case 20:
1392
+ this.reply(`\x1b]L${this.title}\x1b\\`);
1393
+ return;
1394
+ case 21:
1395
+ this.reply(`\x1b]l${this.title}\x1b\\`);
1396
+ return;
1397
+ case 22:
1398
+ // 0 e 2 guardam o título da janela (o do ícone é o mesmo aqui); a pilha tem limite.
1399
+ if ((params[1] ?? 0) !== 1) {
1400
+ this.titleStack.push(this.title);
1401
+ if (this.titleStack.length > 10)
1402
+ this.titleStack.shift();
1403
+ }
1404
+ return;
1405
+ case 23:
1406
+ if ((params[1] ?? 0) !== 1 && this.titleStack.length)
1407
+ this.setTitle(this.titleStack.pop());
1408
+ return;
1409
+ default:
1410
+ // Sem implementação própria (mexer na janela do navegador): avisa quem hospeda.
1411
+ this.windowRequestEmitter.fire({ op, params: params.slice(1) });
1412
+ }
1413
+ }
1414
+ kittyStack() {
1415
+ return this.buffer === this.alt ? this.modes.kittyKeyboardAlt : this.modes.kittyKeyboardNormal;
1416
+ }
1417
+ /** `CSI ? u`: responde as flags ativas. */
1418
+ kittyQuery() {
1419
+ if (this.options.vtExtensions.kittyKeyboard)
1420
+ this.reply(`\x1b[?${this.kittyKeyboardFlags}u`);
1421
+ }
1422
+ /** `CSI > flags u`: empilha (a pilha tem limite; o mais antigo sai). */
1423
+ kittyPush(flags) {
1424
+ if (!this.options.vtExtensions.kittyKeyboard)
1425
+ return;
1426
+ const stack = this.kittyStack();
1427
+ stack.push(flags & 31);
1428
+ if (stack.length > 16)
1429
+ stack.shift();
1430
+ }
1431
+ /** `CSI < n u`: desempilha n (esvaziar volta ao teclado legado). */
1432
+ kittyPop(count) {
1433
+ if (!this.options.vtExtensions.kittyKeyboard)
1434
+ return;
1435
+ const stack = this.kittyStack();
1436
+ stack.splice(Math.max(0, stack.length - count), count);
1437
+ }
1438
+ /** `CSI = flags ; modo u`: 1 troca, 2 liga os bits, 3 desliga os bits (no topo da pilha). */
1439
+ kittySet(flags, mode) {
1440
+ if (!this.options.vtExtensions.kittyKeyboard)
1441
+ return;
1442
+ const stack = this.kittyStack();
1443
+ if (!stack.length)
1444
+ stack.push(0);
1445
+ const top = stack[stack.length - 1];
1446
+ stack[stack.length - 1] = (mode === 2 ? top | flags : mode === 3 ? top & ~flags : flags) & 31;
1447
+ }
1448
+ /** DECRQSS (`DCS $ q Pt ST`): responde o estado pedido (`DCS 1 $ r … ST`) ou `DCS 0 $ r ST` se não souber. */
1449
+ requestStatusString(request) {
1450
+ const b = this.buffer;
1451
+ const ok = (value) => this.reply(`\x1bP1$r${value}\x1b\\`);
1452
+ switch (request) {
1453
+ case 'm':
1454
+ return ok(`${this.sgrString()}m`);
1455
+ case 'r':
1456
+ return ok(`${b.scrollTop + 1};${b.scrollBottom + 1}r`);
1457
+ case ' q': {
1458
+ const base = { block: 1, underline: 3, bar: 5 }[this.options.cursorStyle];
1459
+ const blink = this.modes.cursorBlinkOverride ?? this.options.cursorBlink;
1460
+ return ok(`${base + (blink ? 0 : 1)} q`);
1461
+ }
1462
+ case '"q':
1463
+ return ok('0"q');
1464
+ case '"p':
1465
+ return ok('61;1"p');
1466
+ default:
1467
+ this.reply('\x1bP0$r\x1b\\');
1468
+ }
1469
+ }
1470
+ /** Os atributos atuais como parâmetros SGR (para o DECRQSS e a serialização). */
1471
+ sgrString(attr = this.curAttr) {
1472
+ const out = ['0'];
1473
+ const flagCodes = [
1474
+ [Flags.BOLD, '1'], [Flags.DIM, '2'], [Flags.ITALIC, '3'], [Flags.BLINK, '5'], [Flags.INVERSE, '7'],
1475
+ [Flags.INVISIBLE, '8'], [Flags.STRIKETHROUGH, '9'], [Flags.OVERLINE, '53'],
1476
+ ];
1477
+ for (const [flag, code] of flagCodes)
1478
+ if (attr.flags & flag)
1479
+ out.push(code);
1480
+ if (attr.flags & Flags.UNDERLINE) {
1481
+ const style = attr.extended.underlineStyle;
1482
+ out.push(style > 1 ? `4:${style}` : '4');
1483
+ }
1484
+ const colorCode = (packed, base, bright, ext) => {
1485
+ const mode = (packed >>> 24) & 3;
1486
+ const value = packed & 0xffffff;
1487
+ if (mode === ColorMode.P16)
1488
+ return value < 8 ? `${base + value}` : `${bright + value - 8}`;
1489
+ if (mode === ColorMode.P256)
1490
+ return `${ext};5;${value}`;
1491
+ if (mode === ColorMode.RGB)
1492
+ return `${ext};2;${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}`;
1493
+ return '';
1494
+ };
1495
+ const fg = colorCode(attr.fg, 30, 90, 38);
1496
+ const bg = colorCode(attr.bg, 40, 100, 48);
1497
+ if (fg)
1498
+ out.push(fg);
1499
+ if (bg)
1500
+ out.push(bg);
1501
+ const ul = attr.extended.underlineColor;
1502
+ const ulMode = (ul >>> 24) & 3;
1503
+ if (ulMode === ColorMode.P16 || ulMode === ColorMode.P256)
1504
+ out.push(`58;5;${ul & 0xffffff}`);
1505
+ else if (ulMode === ColorMode.RGB)
1506
+ out.push(`58;2;${(ul >> 16) & 255};${(ul >> 8) & 255};${ul & 255}`);
1507
+ return out.join(';');
1508
+ }
1509
+ /** Para a API (`IBufferCell`): os atributos estendidos por id de link. */
1510
+ linkFor(extended) {
1511
+ return extended.linkId ? this.links.get(extended.linkId) : undefined;
1512
+ }
1513
+ }
1514
+ //# sourceMappingURL=terminal-core.js.map