@trismegisto/terminal 3.4.0 → 4.0.1

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 (155) hide show
  1. package/MIGRATION.md +831 -0
  2. package/NOTICE +4 -36
  3. package/README.md +50 -23
  4. package/dist/core/buffer.d.ts +3 -3
  5. package/dist/core/buffer.js +5 -5
  6. package/dist/core/buffer.js.map +1 -1
  7. package/dist/core/colors.d.ts +9 -2
  8. package/dist/core/colors.js +23 -11
  9. package/dist/core/colors.js.map +1 -1
  10. package/dist/core/event.d.ts +11 -7
  11. package/dist/core/event.js +10 -8
  12. package/dist/core/event.js.map +1 -1
  13. package/dist/core/index.d.ts +4 -4
  14. package/dist/core/index.js +1 -1
  15. package/dist/core/index.js.map +1 -1
  16. package/dist/core/keyboard.d.ts +6 -6
  17. package/dist/core/keyboard.js +19 -20
  18. package/dist/core/keyboard.js.map +1 -1
  19. package/dist/core/parser.d.ts +6 -6
  20. package/dist/core/parser.js +9 -10
  21. package/dist/core/parser.js.map +1 -1
  22. package/dist/core/terminal-core.d.ts +67 -59
  23. package/dist/core/terminal-core.js +93 -95
  24. package/dist/core/terminal-core.js.map +1 -1
  25. package/dist/core/unicode.d.ts +8 -9
  26. package/dist/core/unicode.js +2 -2
  27. package/dist/core/unicode.js.map +1 -1
  28. package/dist/{addons → features}/clipboard.d.ts +8 -8
  29. package/dist/{addons → features}/clipboard.js +6 -6
  30. package/dist/features/clipboard.js.map +1 -0
  31. package/dist/features/connect.d.ts +16 -0
  32. package/dist/{addons/attach.js → features/connect.js} +7 -7
  33. package/dist/features/connect.js.map +1 -0
  34. package/dist/features/fit.d.ts +22 -0
  35. package/dist/{addons → features}/fit.js +46 -17
  36. package/dist/features/fit.js.map +1 -0
  37. package/dist/{addons/webgl → features/gpu}/atlas.js.map +1 -1
  38. package/dist/{addons/webgl → features/gpu}/box.js.map +1 -1
  39. package/dist/{addons/webgl → features/gpu}/frame-model.d.ts +2 -2
  40. package/dist/{addons/webgl → features/gpu}/frame-model.js +2 -2
  41. package/dist/{addons/webgl → features/gpu}/frame-model.js.map +1 -1
  42. package/dist/{addons/webgl → features/gpu}/gl-renderer.js +3 -3
  43. package/dist/{addons/webgl → features/gpu}/gl-renderer.js.map +1 -1
  44. package/dist/features/gpu/index.d.ts +31 -0
  45. package/dist/{addons/webgl/webgl-addon.js → features/gpu/index.js} +14 -41
  46. package/dist/features/gpu/index.js.map +1 -0
  47. package/dist/{addons/image/kitty.d.ts → features/image/graphics-protocol.d.ts} +8 -8
  48. package/dist/{addons/image/kitty.js → features/image/graphics-protocol.js} +6 -7
  49. package/dist/features/image/graphics-protocol.js.map +1 -0
  50. package/dist/{addons → features}/image/iip.js +2 -2
  51. package/dist/features/image/iip.js.map +1 -0
  52. package/dist/{addons → features}/image/index.d.ts +36 -27
  53. package/dist/{addons → features}/image/index.js +89 -89
  54. package/dist/features/image/index.js.map +1 -0
  55. package/dist/features/image/qoi.js.map +1 -0
  56. package/dist/{addons → features}/image/sixel.d.ts +1 -1
  57. package/dist/{addons → features}/image/sixel.js +3 -3
  58. package/dist/features/image/sixel.js.map +1 -0
  59. package/dist/{addons → features}/image/storage.d.ts +2 -2
  60. package/dist/{addons → features}/image/storage.js +1 -1
  61. package/dist/features/image/storage.js.map +1 -0
  62. package/dist/{addons → features}/ligatures.d.ts +6 -6
  63. package/dist/{addons → features}/ligatures.js +9 -10
  64. package/dist/features/ligatures.js.map +1 -0
  65. package/dist/features/links.d.ts +24 -0
  66. package/dist/{addons/web-links.js → features/links.js} +25 -28
  67. package/dist/features/links.js.map +1 -0
  68. package/dist/{addons → features}/program-status.d.ts +7 -7
  69. package/dist/{addons → features}/program-status.js +9 -9
  70. package/dist/features/program-status.js.map +1 -0
  71. package/dist/{addons → features}/progress.d.ts +8 -8
  72. package/dist/{addons → features}/progress.js +5 -6
  73. package/dist/features/progress.js.map +1 -0
  74. package/dist/{addons → features}/search.d.ts +13 -12
  75. package/dist/{addons → features}/search.js +33 -33
  76. package/dist/features/search.js.map +1 -0
  77. package/dist/features/serialize.d.ts +33 -0
  78. package/dist/{addons → features}/serialize.js +8 -20
  79. package/dist/features/serialize.js.map +1 -0
  80. package/dist/features/unicode.d.ts +22 -0
  81. package/dist/features/unicode.js +39 -0
  82. package/dist/features/unicode.js.map +1 -0
  83. package/dist/{addons → features}/web-fonts.d.ts +3 -3
  84. package/dist/{addons → features}/web-fonts.js +8 -6
  85. package/dist/features/web-fonts.js.map +1 -0
  86. package/dist/index.d.ts +16 -18
  87. package/dist/index.js +11 -22
  88. package/dist/index.js.map +1 -1
  89. package/dist/terminal/api.d.ts +488 -0
  90. package/dist/terminal/api.js +2 -0
  91. package/dist/terminal/api.js.map +1 -0
  92. package/dist/terminal/create-terminal.d.ts +12 -0
  93. package/dist/terminal/create-terminal.js +17 -0
  94. package/dist/terminal/create-terminal.js.map +1 -0
  95. package/dist/terminal/engine.d.ts +219 -0
  96. package/dist/terminal/{terminal.js → engine.js} +581 -395
  97. package/dist/terminal/engine.js.map +1 -0
  98. package/dist/terminal/glyphs.js +1 -1
  99. package/dist/terminal/glyphs.js.map +1 -1
  100. package/dist/terminal/renderer.d.ts +13 -13
  101. package/dist/terminal/renderer.js +15 -15
  102. package/dist/terminal/renderer.js.map +1 -1
  103. package/dist/terminal/screen.d.ts +18 -0
  104. package/dist/terminal/screen.js +132 -0
  105. package/dist/terminal/screen.js.map +1 -0
  106. package/dist/terminal/terminal-messages.d.ts +2 -2
  107. package/dist/terminal/terminal-messages.js.map +1 -1
  108. package/dist/terminal/terminal-view.d.ts +26 -28
  109. package/dist/terminal/terminal-view.js +69 -95
  110. package/dist/terminal/terminal-view.js.map +1 -1
  111. package/dist/terminal/token-theme.d.ts +3 -3
  112. package/dist/terminal/token-theme.js +3 -3
  113. package/dist/terminal/token-theme.js.map +1 -1
  114. package/package.json +5 -4
  115. package/dist/addons/attach.d.ts +0 -16
  116. package/dist/addons/attach.js.map +0 -1
  117. package/dist/addons/clipboard.js.map +0 -1
  118. package/dist/addons/fit.d.ts +0 -19
  119. package/dist/addons/fit.js.map +0 -1
  120. package/dist/addons/image/iip.js.map +0 -1
  121. package/dist/addons/image/index.js.map +0 -1
  122. package/dist/addons/image/kitty.js.map +0 -1
  123. package/dist/addons/image/qoi.js.map +0 -1
  124. package/dist/addons/image/sixel.js.map +0 -1
  125. package/dist/addons/image/storage.js.map +0 -1
  126. package/dist/addons/ligatures.js.map +0 -1
  127. package/dist/addons/program-status.js.map +0 -1
  128. package/dist/addons/progress.js.map +0 -1
  129. package/dist/addons/search.js.map +0 -1
  130. package/dist/addons/serialize.d.ts +0 -35
  131. package/dist/addons/serialize.js.map +0 -1
  132. package/dist/addons/unicode.d.ts +0 -19
  133. package/dist/addons/unicode.js +0 -44
  134. package/dist/addons/unicode.js.map +0 -1
  135. package/dist/addons/web-fonts.js.map +0 -1
  136. package/dist/addons/web-links.d.ts +0 -22
  137. package/dist/addons/web-links.js.map +0 -1
  138. package/dist/addons/webgl/webgl-addon.d.ts +0 -42
  139. package/dist/addons/webgl/webgl-addon.js.map +0 -1
  140. package/dist/terminal/buffer-api.d.ts +0 -59
  141. package/dist/terminal/buffer-api.js +0 -174
  142. package/dist/terminal/buffer-api.js.map +0 -1
  143. package/dist/terminal/terminal.d.ts +0 -198
  144. package/dist/terminal/terminal.js.map +0 -1
  145. package/dist/terminal/types.d.ts +0 -364
  146. package/dist/terminal/types.js +0 -2
  147. package/dist/terminal/types.js.map +0 -1
  148. /package/dist/{addons/webgl → features/gpu}/atlas.d.ts +0 -0
  149. /package/dist/{addons/webgl → features/gpu}/atlas.js +0 -0
  150. /package/dist/{addons/webgl → features/gpu}/box.d.ts +0 -0
  151. /package/dist/{addons/webgl → features/gpu}/box.js +0 -0
  152. /package/dist/{addons/webgl → features/gpu}/gl-renderer.d.ts +0 -0
  153. /package/dist/{addons → features}/image/iip.d.ts +0 -0
  154. /package/dist/{addons → features}/image/qoi.d.ts +0 -0
  155. /package/dist/{addons → features}/image/qoi.js +0 -0
@@ -1,65 +1,79 @@
1
- // A classe pública: a API no formato do xterm.js sobre o núcleo deste pacote, com renderização DOM, teclado,
2
- // mouse, seleção, links, decorações, leitor de tela e complementos.
1
+ // O terminal montado: o núcleo deste pacote com renderização DOM, teclado, mouse, seleção, links, decorações, leitor de
2
+ // tela e os recursos ligados por opção. É a implementação do `TerminalHandle` que o `createTerminal` devolve; a classe
3
+ // em si não é exportada pelo pacote.
3
4
  import { CircularList } from '../core/circular-list';
4
- import { ANSI_DEFAULTS, defaultPalette, parseCssColor } from '../core/colors';
5
- import { DisposableStore, Emitter, toDisposable } from '../core/event';
6
- import { encodeKey, encodeKittyKey, encodeMouse, encodePaste, encodeWin32Key } from '../core/keyboard';
5
+ import { ANSI_DEFAULTS, DEFAULT_BACKGROUND, DEFAULT_FOREGROUND, defaultPalette, parseCssColor } from '../core/colors';
6
+ import { DisposableStore, Emitter } from '../core/event';
7
+ import { encodeKey, encodeProgressiveKey, encodeMouse, encodePaste, encodeWin32Key } from '../core/keyboard';
7
8
  import { TerminalCore } from '../core/terminal-core';
8
- import { BufferApi } from './buffer-api';
9
+ import { ClipboardFeature } from '../features/clipboard';
10
+ import { Connection } from '../features/connect';
11
+ import { FitFeature } from '../features/fit';
12
+ import { LigaturesFeature } from '../features/ligatures';
13
+ import { LinksFeature } from '../features/links';
14
+ import { ProgramStatusFeature } from '../features/program-status';
15
+ import { ProgressFeature } from '../features/progress';
16
+ import { SearchFeature } from '../features/search';
17
+ import { Serializer } from '../features/serialize';
18
+ import { Unicode11Feature, UnicodeGraphemesFeature } from '../features/unicode';
19
+ import { WebFontsFeature } from '../features/web-fonts';
9
20
  import { DomRenderer } from './renderer';
21
+ import { ScreenView } from './screen';
10
22
  import { ensureStyles } from './styles';
11
23
  import { DEFAULT_TERMINAL_STRINGS } from './terminal-messages';
12
- const DEFAULT_OPTIONS = {
24
+ const FEATURE_KEYS = [
25
+ 'fit', 'links', 'search', 'clipboard', 'images', 'gpu', 'unicode', 'ligatures', 'progress', 'programStatus', 'webFonts',
26
+ ];
27
+ export const DEFAULT_TERMINAL_OPTIONS = {
13
28
  cols: 80,
14
29
  rows: 24,
15
- allowProposedApi: false,
16
- allowTransparency: false,
17
- altClickMovesCursor: true,
18
- convertEol: false,
19
- cursorBlink: false,
20
- cursorStyle: 'block',
21
- cursorWidth: 1,
22
- cursorInactiveStyle: 'outline',
23
- customGlyphs: true,
24
- disableStdin: false,
25
- drawBoldTextInBrightColors: true,
26
- fastScrollModifier: 'alt',
27
- fastScrollSensitivity: 5,
30
+ scrollback: 1000,
31
+ theme: {},
32
+ fontFamily: 'ui-monospace, monospace',
28
33
  fontSize: 15,
29
- fontFamily: 'courier-new, courier, monospace',
30
34
  fontWeight: 'normal',
31
- fontWeightBold: 'bold',
32
- ignoreBracketedPasteMode: false,
35
+ boldFontWeight: 'bold',
33
36
  letterSpacing: 0,
34
37
  lineHeight: 1,
35
- linkHandler: null,
38
+ cursorShape: 'block',
39
+ cursorBlink: false,
40
+ cursorBarWidth: 1,
41
+ cursorUnfocusedShape: 'outline',
42
+ builtinBoxGlyphs: true,
43
+ boldAsBright: true,
44
+ minimumContrast: 1,
45
+ squeezeWideGlyphs: false,
46
+ transparentBackground: false,
47
+ textBlinkInterval: 0,
48
+ lineFeedAsNewline: false,
49
+ readOnly: false,
50
+ screenReader: false,
51
+ plainPaste: false,
52
+ optionAsMeta: false,
53
+ optionClickSelects: false,
54
+ moveCursorOnAltClick: true,
55
+ contextMenuSelectsWord: false,
56
+ mouseReportNeedsAlt: false,
57
+ wordSeparators: ' ()[]{}\',"`',
58
+ scrollFactor: 1,
59
+ fastScrollKey: 'alt',
60
+ fastScrollFactor: 5,
61
+ smoothScrollTime: 0,
62
+ followInput: true,
63
+ eraseScrollsIntoHistory: false,
64
+ rewrapCursorLine: false,
65
+ tabWidth: 8,
66
+ scrollbar: {},
67
+ extensions: {},
68
+ windowOps: {},
69
+ windowsPty: null,
70
+ hyperlinkHandler: null,
71
+ strings: DEFAULT_TERMINAL_STRINGS,
36
72
  logLevel: 'info',
37
- macOptionIsMeta: false,
38
- macOptionClickForcesSelection: false,
39
- minimumContrastRatio: 1,
40
- rightClickSelectsWord: false,
41
- screenReaderMode: false,
42
- scrollback: 1000,
43
- scrollOnEraseInDisplay: false,
44
- scrollOnUserInput: true,
45
- scrollSensitivity: 1,
46
- smoothScrollDuration: 0,
47
- tabStopWidth: 8,
48
- theme: {},
49
- windowsPty: {},
50
- wordSeparator: ' ()[]{}\',"`',
51
- blinkIntervalDuration: 0,
52
- documentOverride: null,
53
73
  logger: null,
54
- mouseEventsRequireAlt: false,
55
- quirks: {},
56
- reflowCursorLine: false,
57
- rescaleOverlappingGlyphs: false,
58
- scrollbar: {},
59
- vtExtensions: {},
60
- windowOptions: {},
74
+ targetDocument: null,
61
75
  };
62
- /** Inatividade depois da qual o cursor para de piscar (como no xterm.js). */
76
+ /** Inatividade depois da qual o cursor para de piscar. */
63
77
  const BLINK_IDLE_MS = 5 * 60 * 1000;
64
78
  const THEME_ANSI = [
65
79
  'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white',
@@ -74,10 +88,8 @@ class Decoration {
74
88
  disposeEmitter = new Emitter();
75
89
  onRender = this.renderEmitter.event;
76
90
  onDispose = this.disposeEmitter.event;
77
- options;
78
91
  constructor(config) {
79
92
  this.config = config;
80
- this.options = { overviewRulerOptions: config.overviewRulerOptions };
81
93
  }
82
94
  get marker() {
83
95
  return this.config.marker;
@@ -96,15 +108,28 @@ class Decoration {
96
108
  this.disposeEmitter.dispose();
97
109
  }
98
110
  }
99
- export class Terminal {
100
- /** O elemento do terminal, depois do `open`. */
111
+ /** Separa as opções em configurações e recursos. */
112
+ function splitOptions(options) {
113
+ const settings = {};
114
+ const features = {};
115
+ for (const [key, value] of Object.entries(options)) {
116
+ if (value === undefined)
117
+ continue;
118
+ if (FEATURE_KEYS.includes(key))
119
+ features[key] = value;
120
+ else
121
+ settings[key] = value;
122
+ }
123
+ return { settings: settings, features: features };
124
+ }
125
+ export class TerminalEngine {
126
+ /** O elemento do terminal, depois de montado. */
101
127
  element;
102
128
  /** A área de texto escondida que recebe o foco e o teclado (IME incluído). */
103
- textarea;
129
+ inputElement;
104
130
  core;
105
131
  store = new DisposableStore();
106
132
  resolved;
107
- options;
108
133
  renderer;
109
134
  viewport;
110
135
  scrollArea;
@@ -112,11 +137,10 @@ export class Terminal {
112
137
  liveRegion;
113
138
  liveText = '';
114
139
  liveTimer;
115
- customKeyHandler;
116
- customWheelHandler;
117
- linkProviders = [];
140
+ keyFilter = null;
141
+ wheelFilter = null;
142
+ linkSources = [];
118
143
  decorations = [];
119
- addons = [];
120
144
  hoveredLink;
121
145
  linkRequest = 0;
122
146
  selecting;
@@ -125,17 +149,29 @@ export class Terminal {
125
149
  composing = false;
126
150
  keyHandled = false;
127
151
  disposed = false;
152
+ mounted = false;
153
+ // Recursos ligados por opção.
154
+ featureOptions = { search: true };
155
+ features = new Map();
156
+ /** Versão do pedido de cada recurso: um carregamento sob demanda que chega depois de outro pedido é descartado. */
157
+ featureTokens = new Map();
158
+ fitter = new FitFeature(false);
159
+ serializer = new Serializer();
160
+ loading = 0;
161
+ loads = [];
162
+ /** O que foi escrito enquanto um recurso sob demanda carregava (sai na ordem, depois). */
163
+ queued = [];
128
164
  keyEmitter = new Emitter();
129
165
  renderEmitter = new Emitter();
130
166
  scrollEmitter = new Emitter();
131
167
  selectionEmitter = new Emitter();
132
- bufferEmitter = new Emitter();
133
- dimensionsEmitter = new Emitter();
134
- /** As medidas da tela mudaram (fonte, entrelinha, tamanho). */
135
- onDimensionsChange = this.dimensionsEmitter.event;
136
- /** Textos que o terminal mesmo usa; troque para traduzir (vale para os terminais abertos depois). */
137
- static strings = { ...DEFAULT_TERMINAL_STRINGS };
168
+ screenEmitter = new Emitter();
169
+ metricsEmitter = new Emitter();
170
+ searchEmitter = new Emitter();
171
+ progressEmitter = new Emitter();
172
+ programStatusEmitter = new Emitter();
138
173
  nextJoinerId = 1;
174
+ joiners = new Map();
139
175
  blinkTimer;
140
176
  smoothTarget = null;
141
177
  smoothFrame = 0;
@@ -145,56 +181,74 @@ export class Terminal {
145
181
  onKey = this.keyEmitter.event;
146
182
  onRender = this.renderEmitter.event;
147
183
  onScroll = this.scrollEmitter.event;
148
- onSelectionChange = this.selectionEmitter.event;
149
- buffer;
150
- parser;
184
+ onSelection = this.selectionEmitter.event;
185
+ onScreenChange = this.screenEmitter.event;
186
+ onMetrics = this.metricsEmitter.event;
187
+ onProgress = this.progressEmitter.event;
188
+ onProgramStatus = this.programStatusEmitter.event;
189
+ screens;
190
+ selection;
191
+ search;
192
+ sequences;
151
193
  unicode;
194
+ programStatus;
152
195
  constructor(options = {}) {
153
- this.resolved = { ...DEFAULT_OPTIONS, ...stripUndefined(options), theme: { ...(options.theme ?? {}) } };
196
+ const { settings, features } = splitOptions(options);
197
+ this.resolved = {
198
+ ...DEFAULT_TERMINAL_OPTIONS,
199
+ ...settings,
200
+ theme: { ...(settings.theme ?? {}) },
201
+ strings: { ...DEFAULT_TERMINAL_STRINGS, ...(settings.strings ?? {}) },
202
+ };
203
+ this.featureOptions = { ...this.featureOptions, ...features };
204
+ const o = this.resolved;
154
205
  this.core = new TerminalCore({
155
- cols: this.resolved.cols,
156
- rows: this.resolved.rows,
157
- scrollback: this.resolved.scrollback,
158
- tabStopWidth: this.resolved.tabStopWidth,
159
- convertEol: this.resolved.convertEol,
160
- scrollOnEraseInDisplay: this.resolved.scrollOnEraseInDisplay,
161
- cursorStyle: this.resolved.cursorStyle,
162
- cursorBlink: this.resolved.cursorBlink,
163
- disableStdin: this.resolved.disableStdin,
164
- allowSetCursorBlink: !!this.resolved.quirks?.allowSetCursorBlink,
165
- reflowCursorLine: this.resolved.reflowCursorLine,
166
- windowsPty: { ...(this.resolved.windowsPty ?? {}) },
167
- vtExtensions: { ...this.resolved.vtExtensions },
168
- windowOptions: { ...this.resolved.windowOptions },
169
- logLevel: this.resolved.logLevel,
170
- logger: this.resolved.logger,
206
+ cols: o.cols,
207
+ rows: o.rows,
208
+ scrollback: o.scrollback,
209
+ tabWidth: o.tabWidth,
210
+ lineFeedAsNewline: o.lineFeedAsNewline,
211
+ eraseScrollsIntoHistory: o.eraseScrollsIntoHistory,
212
+ cursorShape: o.cursorShape,
213
+ cursorBlink: o.cursorBlink,
214
+ readOnly: o.readOnly,
215
+ cursorBlinkMode: !!o.extensions.cursorBlinkMode,
216
+ rewrapCursorLine: o.rewrapCursorLine,
217
+ windowsPty: o.windowsPty ? { ...o.windowsPty } : null,
218
+ extensions: { ...o.extensions },
219
+ windowOps: { ...o.windowOps },
220
+ logLevel: o.logLevel,
221
+ logger: o.logger,
171
222
  });
172
223
  this.applyTheme();
173
- // `terminal.options.fontSize = 16` aplica na hora, como no xterm.
174
- this.options = new Proxy(this.resolved, {
175
- set: (target, key, value) => {
176
- target[key] = value;
177
- this.applyOption(String(key));
178
- return true;
179
- },
180
- });
181
224
  const core = this.core;
182
- const normal = new BufferApi(() => core.normal);
183
- const alternate = new BufferApi(() => core.alt);
184
- this.buffer = {
225
+ this.screens = { normal: new ScreenView(() => core.normal), alternate: new ScreenView(() => core.alt) };
226
+ this.selection = {
185
227
  get active() {
186
- return core.buffer === core.normal ? normal : alternate;
228
+ return core.hasSelection();
187
229
  },
188
- normal,
189
- alternate,
190
- onBufferChange: this.bufferEmitter.event,
230
+ text: () => core.getSelection(),
231
+ range: () => {
232
+ const s = core.selection;
233
+ return s ? { start: { col: s.start.x, row: s.start.y }, end: { col: s.end.x, row: s.end.y } } : undefined;
234
+ },
235
+ select: (col, row, length) => core.select(col, row, length),
236
+ selectLines: (first, last) => core.selectLines(first, last),
237
+ selectAll: () => core.selectAll(),
238
+ clear: () => core.clearSelection(),
239
+ };
240
+ this.search = {
241
+ next: (query, opts) => this.searchFeature?.findNext(query, opts) ?? false,
242
+ previous: (query, opts) => this.searchFeature?.findPrevious(query, opts) ?? false,
243
+ clear: (keepActive) => this.searchFeature?.clearDecorations(keepActive),
244
+ onResults: this.searchEmitter.event,
191
245
  };
192
- this.parser = {
193
- registerCsiHandler: (id, cb) => core.parser.registerCsiHandler(id, cb),
194
- registerDcsHandler: (id, cb) => core.parser.registerDcsHandler(id, cb),
195
- registerEscHandler: (id, cb) => core.parser.registerEscHandler(id, cb),
196
- registerOscHandler: (ident, cb) => core.parser.registerOscHandler(ident, cb),
197
- registerApcHandler: (id, cb) => core.parser.registerApcHandler(id, cb),
246
+ this.sequences = {
247
+ csi: (id, handler) => core.parser.addCsiHandler(id, handler),
248
+ esc: (id, handler) => core.parser.addEscHandler(id, handler),
249
+ osc: (code, handler) => core.parser.addOscHandler(code, handler),
250
+ dcs: (id, handler) => core.parser.addDcsHandler(id, handler),
251
+ apc: (id, handler) => core.parser.addApcHandler(id, handler),
198
252
  };
199
253
  const unicode = core.unicode;
200
254
  this.unicode = {
@@ -202,41 +256,50 @@ export class Terminal {
202
256
  get versions() {
203
257
  return unicode.versions;
204
258
  },
205
- get activeVersion() {
259
+ get active() {
206
260
  return unicode.activeVersion;
207
261
  },
208
- set activeVersion(version) {
262
+ set active(version) {
209
263
  unicode.activeVersion = version;
210
264
  },
211
265
  };
266
+ const status = () => this.features.get('programStatus');
267
+ this.programStatus = {
268
+ get records() {
269
+ return status()?.records ?? [];
270
+ },
271
+ clear: (id) => status()?.clear(id),
272
+ processExited: () => status()?.processExited(),
273
+ promptStarted: () => status()?.promptStarted(),
274
+ };
212
275
  this.store.add(core.onDirty(({ start, end }) => this.renderer?.refreshRows(start, end)));
213
276
  this.store.add(core.onScroll((ydisp) => {
214
277
  this.syncScrollArea();
215
278
  this.scrollEmitter.fire(ydisp);
216
279
  }));
217
- this.store.add(core.onCursorMove(() => {
280
+ this.store.add(core.onCursor(() => {
218
281
  this.renderer?.refreshRows(this.core.buffer.y, this.core.buffer.y);
219
282
  this.wakeBlink();
220
283
  }));
221
- this.store.add(core.onSelectionChange(() => {
284
+ this.store.add(core.onSelection(() => {
222
285
  this.renderer?.refreshRows(0, -1);
223
286
  this.selectionEmitter.fire();
224
287
  }));
225
- this.store.add(core.onBufferChange(() => {
288
+ this.store.add(core.onScreenChange(() => {
226
289
  this.syncScrollArea();
227
- this.bufferEmitter.fire(this.buffer.active);
290
+ this.screenEmitter.fire(this.screen);
228
291
  }));
229
292
  this.store.add(core.onResize(() => {
230
293
  this.renderer?.layout();
231
294
  this.syncScrollArea();
232
295
  }));
233
- this.store.add(core.onCursorStyleChange(() => this.renderer?.refreshAll()));
296
+ this.store.add(core.onCursorShapeChange(() => this.renderer?.refreshAll()));
234
297
  this.store.add(core.onColorsChange(() => {
235
298
  this.applyBackground();
236
299
  this.renderer?.refreshAll();
237
300
  this.renderOverviewRuler();
238
301
  }));
239
- this.store.add(core.onWriteParsed(() => this.announce()));
302
+ this.store.add(core.onParsed(() => this.announce()));
240
303
  }
241
304
  // ---------------------------------------------------------------- propriedades
242
305
  get cols() {
@@ -245,97 +308,113 @@ export class Terminal {
245
308
  get rows() {
246
309
  return this.core.rows;
247
310
  }
311
+ get title() {
312
+ return this.core.title;
313
+ }
314
+ get settings() {
315
+ return this.resolved;
316
+ }
317
+ get screen() {
318
+ return this.core.buffer === this.core.normal ? this.screens.normal : this.screens.alternate;
319
+ }
248
320
  get modes() {
249
321
  const m = this.core.modes;
250
322
  return {
251
- applicationCursorKeysMode: m.applicationCursorKeysMode,
252
- applicationKeypadMode: m.applicationKeypadMode,
253
- bracketedPasteMode: m.bracketedPasteMode,
254
- insertMode: m.insertMode,
255
- mouseTrackingMode: m.mouseTrackingMode,
256
- originMode: m.originMode,
257
- reverseWraparoundMode: m.reverseWraparoundMode,
258
- sendFocusMode: m.sendFocusMode,
259
- showCursor: m.showCursor,
260
- synchronizedOutputMode: m.synchronizedOutputMode,
261
- wraparoundMode: m.wraparoundMode,
323
+ applicationCursorKeys: m.applicationCursorKeysMode,
324
+ applicationKeypad: m.applicationKeypadMode,
325
+ bracketedPaste: m.bracketedPasteMode,
326
+ insert: m.insertMode,
327
+ mouseTracking: m.mouseTrackingMode,
328
+ origin: m.originMode,
329
+ reverseWraparound: m.reverseWraparoundMode,
330
+ focusReports: m.sendFocusMode,
331
+ cursorVisible: m.showCursor,
332
+ synchronizedOutput: m.synchronizedOutputMode,
333
+ autoWrap: m.wraparoundMode,
262
334
  };
263
335
  }
264
336
  /** O elemento das camadas de desenho (linhas, cursor, seleção, decorações), sem o viewport nem a barra. */
265
337
  get screenElement() {
266
- return this.renderer?.screen;
338
+ return this.renderer.screen;
267
339
  }
268
- /** Medidas da tela e da célula; `undefined` antes do `open`. */
269
- get dimensions() {
340
+ /** Medidas da tela e da célula; `undefined` antes de montar e medir. */
341
+ get metrics() {
270
342
  const r = this.renderer;
271
343
  if (!r || !r.cellWidth)
272
344
  return undefined;
273
- const dpr = this.element?.ownerDocument.defaultView?.devicePixelRatio || 1;
274
- const cell = { width: r.cellWidth, height: r.cellHeight };
275
- const canvas = { width: r.cellWidth * this.cols, height: r.cellHeight * this.rows };
276
- const charHeight = Math.round((r.cellHeight / this.resolved.lineHeight) * dpr);
277
345
  return {
278
- css: { canvas, cell },
279
- device: {
280
- canvas: { width: Math.round(canvas.width * dpr), height: Math.round(canvas.height * dpr) },
281
- cell: { width: Math.round(cell.width * dpr), height: Math.round(cell.height * dpr) },
282
- char: {
283
- width: Math.round((cell.width - this.resolved.letterSpacing) * dpr),
284
- height: charHeight,
285
- left: Math.round((this.resolved.letterSpacing * dpr) / 2),
286
- top: Math.round((cell.height * dpr - charHeight) / 2),
287
- },
288
- },
346
+ cell: { width: r.cellWidth, height: r.cellHeight },
347
+ screen: { width: r.cellWidth * this.cols, height: r.cellHeight * this.rows },
348
+ devicePixelRatio: this.element?.ownerDocument.defaultView?.devicePixelRatio || 1,
289
349
  };
290
350
  }
291
- /**
292
- * Juntor de caracteres: recebe o texto de cada linha desenhada e devolve faixas `[início, fim)` que viram uma unidade
293
- * (ligaduras, grafemas). Devolve o id para `deregisterCharacterJoiner`.
294
- */
295
- registerCharacterJoiner(handler) {
296
- const id = this.nextJoinerId++;
297
- this.pendingJoiners.set(id, handler);
298
- this.renderer?.joiners.set(id, handler);
299
- this.renderer?.refreshAll();
300
- return id;
301
- }
302
- deregisterCharacterJoiner(joinerId) {
303
- this.pendingJoiners.delete(joinerId);
304
- if (this.renderer?.joiners.delete(joinerId))
305
- this.renderer.refreshAll();
306
- }
307
- pendingJoiners = new Map();
308
351
  get markers() {
309
352
  return this.core.markers;
310
353
  }
354
+ /** Medidas da célula em px (zero antes de medir). */
311
355
  get cellSize() {
312
356
  return { width: this.renderer?.cellWidth ?? 0, height: this.renderer?.cellHeight ?? 0 };
313
357
  }
314
- get onData() {
315
- return this.core.onData;
358
+ get progress() {
359
+ return this.features.get('progress')?.progress ?? { state: 0, value: 0 };
360
+ }
361
+ get ready() {
362
+ return Promise.all(this.loads).then(() => undefined);
363
+ }
364
+ get searchFeature() {
365
+ return this.features.get('search');
366
+ }
367
+ addJoiner(joiner) {
368
+ const id = this.nextJoinerId++;
369
+ this.joiners.set(id, joiner);
370
+ this.renderer?.joiners.set(id, joiner);
371
+ this.renderer?.refreshAll();
372
+ return () => {
373
+ this.joiners.delete(id);
374
+ if (this.renderer?.joiners.delete(id))
375
+ this.renderer.refreshAll();
376
+ };
377
+ }
378
+ onInput(listener) {
379
+ return this.core.onInput(listener);
316
380
  }
317
- get onBinary() {
318
- return this.core.onBinary;
381
+ onBinaryInput(listener) {
382
+ return this.core.onBinaryInput(listener);
319
383
  }
320
- get onBell() {
321
- return this.core.onBell;
384
+ onBell(listener) {
385
+ return this.core.onBell(listener);
322
386
  }
323
- get onTitleChange() {
324
- return this.core.onTitleChange;
387
+ onTitle(listener) {
388
+ return this.core.onTitle(listener);
325
389
  }
326
- get onLineFeed() {
327
- return this.core.onLineFeed;
390
+ onLineFeed(listener) {
391
+ return this.core.onLineFeed(listener);
328
392
  }
329
- get onCursorMove() {
330
- return this.core.onCursorMove;
393
+ onCursor(listener) {
394
+ return this.core.onCursor(listener);
331
395
  }
332
- get onResize() {
333
- return this.core.onResize;
396
+ onResize(listener) {
397
+ return this.core.onResize(listener);
334
398
  }
335
- get onWriteParsed() {
336
- return this.core.onWriteParsed;
399
+ onParsed(listener) {
400
+ return this.core.onParsed(listener);
337
401
  }
338
402
  // ---------------------------------------------------------------- opções e tema
403
+ configure(options) {
404
+ const { settings, features } = splitOptions(options);
405
+ const o = this.resolved;
406
+ for (const [key, value] of Object.entries(settings)) {
407
+ o[key] = key === 'theme' ? { ...value } : key === 'strings' ? { ...DEFAULT_TERMINAL_STRINGS, ...value } : value;
408
+ this.applyOption(key);
409
+ }
410
+ for (const [key, value] of Object.entries(features)) {
411
+ if (sameValue(this.featureOptions[key], value))
412
+ continue;
413
+ this.featureOptions[key] = value;
414
+ if (this.mounted)
415
+ this.setFeature(key);
416
+ }
417
+ }
339
418
  applyOption(key) {
340
419
  const o = this.resolved;
341
420
  const core = this.core;
@@ -344,13 +423,16 @@ export class Terminal {
344
423
  core.setScrollback(o.scrollback);
345
424
  this.syncScrollArea();
346
425
  break;
347
- case 'tabStopWidth':
348
- case 'convertEol':
349
- case 'scrollOnEraseInDisplay':
350
- case 'disableStdin':
426
+ case 'tabWidth':
427
+ case 'lineFeedAsNewline':
428
+ case 'eraseScrollsIntoHistory':
429
+ case 'readOnly':
430
+ case 'rewrapCursorLine':
431
+ case 'logLevel':
432
+ case 'logger':
351
433
  core.options[key] = o[key];
352
434
  break;
353
- case 'cursorStyle':
435
+ case 'cursorShape':
354
436
  case 'cursorBlink':
355
437
  core.options[key] = o[key];
356
438
  core.modes.cursorBlinkOverride = null;
@@ -359,35 +441,31 @@ export class Terminal {
359
441
  case 'theme':
360
442
  this.applyTheme();
361
443
  break;
362
- case 'screenReaderMode':
444
+ case 'screenReader':
363
445
  this.setupA11y();
364
446
  break;
365
447
  case 'cols':
366
448
  case 'rows':
367
449
  this.resize(o.cols, o.rows);
368
450
  break;
369
- case 'quirks':
370
- core.options.allowSetCursorBlink = !!o.quirks?.allowSetCursorBlink;
371
- if (!core.options.allowSetCursorBlink)
372
- core.modes.cursorBlinkOverride = null;
373
- break;
374
- case 'reflowCursorLine':
375
- case 'logLevel':
376
- case 'logger':
377
- core.options[key] = o[key];
378
- break;
379
451
  case 'windowsPty':
380
- core.options.windowsPty = { ...(o.windowsPty ?? {}) };
452
+ core.options.windowsPty = o.windowsPty ? { ...o.windowsPty } : null;
381
453
  break;
382
- case 'vtExtensions':
383
- core.options.vtExtensions = { ...o.vtExtensions };
454
+ case 'extensions':
455
+ core.options.extensions = { ...o.extensions };
456
+ core.options.cursorBlinkMode = !!o.extensions.cursorBlinkMode;
457
+ if (!core.options.cursorBlinkMode)
458
+ core.modes.cursorBlinkOverride = null;
384
459
  break;
385
- case 'windowOptions':
386
- core.options.windowOptions = { ...o.windowOptions };
460
+ case 'windowOps':
461
+ core.options.windowOps = { ...o.windowOps };
387
462
  break;
388
463
  case 'scrollbar':
389
464
  this.applyScrollbar();
390
465
  break;
466
+ case 'strings':
467
+ this.inputElement?.setAttribute('aria-label', o.strings.promptLabel);
468
+ break;
391
469
  }
392
470
  this.renderer?.setOptions(this.renderOptions());
393
471
  this.syncScrollArea();
@@ -396,12 +474,12 @@ export class Terminal {
396
474
  const theme = this.resolved.theme ?? {};
397
475
  const ansi = THEME_ANSI.map((name, i) => cssOr(theme[name], ANSI_DEFAULTS[i]));
398
476
  const palette = defaultPalette(ansi);
399
- theme.extendedAnsi?.forEach((css, i) => {
477
+ theme.extended?.forEach((css, i) => {
400
478
  if (16 + i < 256)
401
479
  palette[16 + i] = cssOr(css, palette[16 + i]);
402
480
  });
403
- const foreground = cssOr(theme.foreground, 0xffffff);
404
- const background = cssOr(theme.background, 0x000000);
481
+ const foreground = cssOr(theme.foreground, DEFAULT_FOREGROUND);
482
+ const background = cssOr(theme.background, DEFAULT_BACKGROUND);
405
483
  this.core.colors.setBase(palette, foreground, background, cssOr(theme.cursor, foreground));
406
484
  this.core.notifyColorScheme();
407
485
  this.applyBackground();
@@ -413,10 +491,10 @@ export class Terminal {
413
491
  const { foreground, background } = this.core.colors;
414
492
  const hex = (v) => `#${v.toString(16).padStart(6, '0')}`;
415
493
  this.element.style.setProperty('--hmt-foreground', hex(foreground));
416
- this.element.style.setProperty('--hmt-background', this.resolved.allowTransparency && this.resolved.theme.background === 'transparent' ? 'transparent' : hex(background));
494
+ this.element.style.setProperty('--hmt-background', this.resolved.transparentBackground && this.resolved.theme.background === 'transparent' ? 'transparent' : hex(background));
417
495
  const t = this.resolved.theme;
418
- if (t.scrollbarSliderBackground)
419
- this.element.style.setProperty('--hmt-scrollbar', t.scrollbarSliderBackground);
496
+ if (t.scrollbarThumb)
497
+ this.element.style.setProperty('--hmt-scrollbar', t.scrollbarThumb);
420
498
  }
421
499
  renderOptions() {
422
500
  const o = this.resolved;
@@ -425,29 +503,112 @@ export class Terminal {
425
503
  fontFamily: o.fontFamily,
426
504
  fontSize: o.fontSize,
427
505
  fontWeight: o.fontWeight,
428
- fontWeightBold: o.fontWeightBold,
506
+ boldFontWeight: o.boldFontWeight,
429
507
  lineHeight: o.lineHeight,
430
508
  letterSpacing: o.letterSpacing,
431
- cursorStyle: o.cursorStyle,
432
- cursorInactiveStyle: o.cursorInactiveStyle,
433
- cursorWidth: o.cursorWidth,
509
+ cursorShape: o.cursorShape,
510
+ cursorUnfocusedShape: o.cursorUnfocusedShape,
511
+ cursorBarWidth: o.cursorBarWidth,
434
512
  cursorBlink: o.cursorBlink,
435
- drawBoldTextInBrightColors: o.drawBoldTextInBrightColors,
436
- customGlyphs: o.customGlyphs,
437
- blinkIntervalDuration: o.blinkIntervalDuration,
438
- minimumContrastRatio: o.minimumContrastRatio,
439
- rescaleOverlappingGlyphs: o.rescaleOverlappingGlyphs,
513
+ boldAsBright: o.boldAsBright,
514
+ builtinBoxGlyphs: o.builtinBoxGlyphs,
515
+ textBlinkInterval: o.textBlinkInterval,
516
+ minimumContrast: o.minimumContrast,
517
+ squeezeWideGlyphs: o.squeezeWideGlyphs,
440
518
  selectionBackground: t.selectionBackground ?? 'rgba(255, 255, 255, 0.3)',
441
519
  selectionForeground: t.selectionForeground,
442
- selectionInactiveBackground: t.selectionInactiveBackground ?? t.selectionBackground ?? 'rgba(255, 255, 255, 0.2)',
443
- cursorAccent: t.cursorAccent,
520
+ selectionUnfocusedBackground: t.selectionUnfocusedBackground ?? t.selectionBackground ?? 'rgba(255, 255, 255, 0.2)',
521
+ cursorText: t.cursorText,
444
522
  };
445
523
  }
524
+ // ---------------------------------------------------------------- recursos
525
+ /** Liga, troca ou desliga o recurso conforme a opção atual. */
526
+ setFeature(key) {
527
+ const token = (this.featureTokens.get(key) ?? 0) + 1;
528
+ this.featureTokens.set(key, token);
529
+ this.features.get(key)?.dispose();
530
+ this.features.delete(key);
531
+ const value = this.featureOptions[key];
532
+ if (!value)
533
+ return;
534
+ const opts = (v) => (typeof v === 'object' && v ? v : {});
535
+ switch (key) {
536
+ case 'fit':
537
+ return this.attachFeature(key, new FitFeature(true));
538
+ case 'links':
539
+ return this.attachFeature(key, new LinksFeature(opts(value)));
540
+ case 'search': {
541
+ const feature = new SearchFeature(opts(value));
542
+ feature.onResults((results) => this.searchEmitter.fire(results));
543
+ return this.attachFeature(key, feature);
544
+ }
545
+ case 'clipboard': {
546
+ const { codec, provider } = opts(value);
547
+ return this.attachFeature(key, new ClipboardFeature(codec, provider));
548
+ }
549
+ case 'unicode':
550
+ if (value === '11')
551
+ return this.attachFeature(key, new Unicode11Feature());
552
+ if (value === 'graphemes')
553
+ return this.attachFeature(key, new UnicodeGraphemesFeature());
554
+ this.core.unicode.activeVersion = String(value);
555
+ return;
556
+ case 'ligatures':
557
+ return this.attachFeature(key, new LigaturesFeature(opts(value)));
558
+ case 'progress': {
559
+ const feature = new ProgressFeature();
560
+ feature.onChange((state) => this.progressEmitter.fire(state));
561
+ return this.attachFeature(key, feature);
562
+ }
563
+ case 'programStatus': {
564
+ const feature = new ProgramStatusFeature();
565
+ feature.onChange((records) => this.programStatusEmitter.fire(records));
566
+ return this.attachFeature(key, feature);
567
+ }
568
+ case 'webFonts':
569
+ return this.attachFeature(key, new WebFontsFeature());
570
+ case 'images':
571
+ return this.loadFeature(key, token, () => import('../features/image/index').then((m) => new m.ImageFeature(opts(value))));
572
+ case 'gpu':
573
+ return this.loadFeature(key, token, () => import('../features/gpu/index').then((m) => new m.GpuFeature(opts(value))));
574
+ }
575
+ }
576
+ /** Liga o recurso; se ele recusar (sem WebGL, por exemplo), avisa no registro e o terminal segue sem ele. */
577
+ attachFeature(key, feature) {
578
+ try {
579
+ feature.attach(this);
580
+ this.features.set(key, feature);
581
+ }
582
+ catch (error) {
583
+ feature.dispose();
584
+ this.core.log('warn', `recurso ${key} desligado: ${error instanceof Error ? error.message : String(error)}`, error);
585
+ }
586
+ }
587
+ /** Recurso pesado, em chunk próprio: a escrita espera ele entrar para nenhuma sequência passar sem ele. */
588
+ loadFeature(key, token, load) {
589
+ this.loading++;
590
+ const done = load()
591
+ .then((feature) => {
592
+ if (this.disposed || this.featureTokens.get(key) !== token)
593
+ return;
594
+ this.attachFeature(key, feature);
595
+ })
596
+ .catch((error) => this.core.log('error', 'não foi possível carregar um recurso do terminal', key, error))
597
+ .finally(() => {
598
+ this.loading--;
599
+ if (!this.loading)
600
+ for (const item of this.queued.splice(0))
601
+ this.core.write(item.data, item.done);
602
+ });
603
+ this.loads.push(done);
604
+ }
446
605
  // ---------------------------------------------------------------- montar na página
447
- open(parent) {
448
- if (this.element)
449
- throw new Error('[hermes-terminal] O terminal já está aberto.');
450
- const doc = this.resolved.documentOverride ?? parent.ownerDocument;
606
+ /** Monta no host (o `createTerminal` chama) e liga os recursos pedidos. */
607
+ mount(parent) {
608
+ if (this.mounted)
609
+ throw new Error('[hermes-terminal] O terminal já está montado.');
610
+ this.mounted = true;
611
+ const doc = this.resolved.targetDocument ?? parent.ownerDocument;
451
612
  ensureStyles(doc);
452
613
  const el = doc.createElement('div');
453
614
  el.className = 'hmt';
@@ -469,11 +630,11 @@ export class Terminal {
469
630
  this.renderer.onMeasured = () => {
470
631
  const r = this.renderer;
471
632
  this.core.pixelMetrics = { cellWidth: r.cellWidth, cellHeight: r.cellHeight };
472
- const dims = this.dimensions;
473
- if (dims)
474
- this.dimensionsEmitter.fire(dims);
633
+ const metrics = this.metrics;
634
+ if (metrics)
635
+ this.metricsEmitter.fire(metrics);
475
636
  };
476
- for (const [id, joiner] of this.pendingJoiners)
637
+ for (const [id, joiner] of this.joiners)
477
638
  this.renderer.joiners.set(id, joiner);
478
639
  this.renderer.onRendered = (start, end) => {
479
640
  this.updateA11yRows(start, end);
@@ -485,11 +646,10 @@ export class Terminal {
485
646
  textarea.setAttribute('autocapitalize', 'off');
486
647
  textarea.setAttribute('spellcheck', 'false');
487
648
  textarea.setAttribute('tabindex', '0');
488
- // Nome acessível de `Terminal.strings` (o `hm-terminal` troca pelo do idioma ativo).
489
- textarea.setAttribute('aria-label', Terminal.strings.promptLabel);
649
+ textarea.setAttribute('aria-label', this.resolved.strings.promptLabel);
490
650
  textarea.setAttribute('aria-multiline', 'false');
491
651
  el.appendChild(textarea);
492
- this.textarea = textarea;
652
+ this.inputElement = textarea;
493
653
  parent.appendChild(el);
494
654
  this.applyBackground();
495
655
  this.renderer.measureCell();
@@ -499,14 +659,18 @@ export class Terminal {
499
659
  this.wakeBlink();
500
660
  this.syncScrollArea();
501
661
  this.renderer.refreshAll();
662
+ this.fitter.attach(this);
663
+ for (const key of FEATURE_KEYS)
664
+ if (this.featureOptions[key])
665
+ this.setFeature(key);
502
666
  }
503
667
  bindEvents() {
504
668
  const el = this.element;
505
- const ta = this.textarea;
669
+ const ta = this.inputElement;
506
670
  const screen = this.renderer.screen;
507
671
  const on = (target, type, fn, opts) => {
508
672
  target.addEventListener(type, fn, opts);
509
- this.store.add(toDisposable(() => target.removeEventListener(type, fn, opts)));
673
+ this.store.add(() => target.removeEventListener(type, fn, opts));
510
674
  };
511
675
  on(ta, 'keydown', (e) => this.handleKeyDown(e));
512
676
  on(ta, 'keyup', (e) => this.handleKeyUp(e));
@@ -534,9 +698,9 @@ export class Terminal {
534
698
  on(screen, 'mousemove', (e) => this.handleHover(e));
535
699
  on(screen, 'mouseleave', (e) => this.clearHoveredLink(e));
536
700
  on(screen, 'contextmenu', (e) => {
537
- if (this.resolved.rightClickSelectsWord)
701
+ if (this.resolved.contextMenuSelectsWord)
538
702
  this.selectWordAt(e);
539
- this.textarea?.focus();
703
+ this.inputElement?.focus();
540
704
  });
541
705
  on(el, 'wheel', (e) => this.handleWheel(e), { passive: false });
542
706
  on(this.viewport, 'scroll', () => {
@@ -560,36 +724,36 @@ export class Terminal {
560
724
  this.renderer.focused = focused;
561
725
  this.element?.classList.toggle('hmt-focus', focused);
562
726
  if (this.core.modes.sendFocusMode)
563
- this.core.triggerData(focused ? '\x1b[I' : '\x1b[O', false);
727
+ this.core.emitInput(focused ? '\x1b[I' : '\x1b[O', false);
564
728
  this.renderer.refreshAll();
565
729
  }
566
730
  focus() {
567
- this.textarea?.focus();
731
+ this.inputElement?.focus();
568
732
  }
569
733
  blur() {
570
- this.textarea?.blur();
734
+ this.inputElement?.blur();
571
735
  }
572
736
  // ---------------------------------------------------------------- teclado
573
- attachCustomKeyEventHandler(handler) {
574
- this.customKeyHandler = handler;
737
+ setKeyFilter(handler) {
738
+ this.keyFilter = handler;
575
739
  }
576
- attachCustomWheelEventHandler(handler) {
577
- this.customWheelHandler = handler;
740
+ setWheelFilter(handler) {
741
+ this.wheelFilter = handler;
578
742
  }
579
743
  handleKeyDown(e) {
580
744
  this.keyHandled = false;
581
- if (this.customKeyHandler && this.customKeyHandler(e) === false)
745
+ if (this.keyFilter && this.keyFilter(e) === false)
582
746
  return;
583
747
  if (this.composing || e.isComposing || e.key === 'Process' || e.keyCode === 229)
584
748
  return;
585
749
  this.wakeBlink();
586
- // Protocolos estendidos pedidos pelo processo: win32-input-mode e o teclado do kitty.
750
+ // Protocolos estendidos pedidos pelo processo: win32-input-mode e o teclado progressivo (CSI u).
587
751
  const extended = this.extendedKey(e, 'keydown');
588
752
  if (extended !== null) {
589
753
  e.preventDefault();
590
754
  this.keyHandled = true;
591
755
  if (extended) {
592
- this.keyEmitter.fire({ key: extended, domEvent: e });
756
+ this.keyEmitter.fire({ data: extended, event: e });
593
757
  this.sendUserInput(extended);
594
758
  }
595
759
  return;
@@ -597,15 +761,15 @@ export class Terminal {
597
761
  const result = encodeKey(e, {
598
762
  applicationCursorKeys: this.core.modes.applicationCursorKeysMode,
599
763
  applicationKeypad: this.core.modes.applicationKeypadMode,
600
- macOptionIsMeta: this.resolved.macOptionIsMeta,
764
+ optionAsMeta: this.resolved.optionAsMeta,
601
765
  isMac: isMac(),
602
766
  });
603
- // Shift+PageUp/PageDown/Home/End rolam a vista (atalhos do xterm), não vão para o processo.
767
+ // Shift+PageUp/PageDown/Home/End rolam a vista, não vão para o processo.
604
768
  if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey && this.core.buffer === this.core.normal) {
605
769
  const page = this.rows - 1;
606
770
  const scroll = { PageUp: -page, PageDown: page }[e.key];
607
771
  if (scroll) {
608
- this.scrollLines(scroll);
772
+ this.scrollBy(scroll);
609
773
  e.preventDefault();
610
774
  return;
611
775
  }
@@ -615,11 +779,11 @@ export class Terminal {
615
779
  this.keyHandled = true;
616
780
  if (result.cancel || result.data.length === 1)
617
781
  e.preventDefault();
618
- this.keyEmitter.fire({ key: result.data, domEvent: e });
782
+ this.keyEmitter.fire({ data: result.data, event: e });
619
783
  this.sendUserInput(result.data);
620
784
  }
621
785
  handleKeyUp(e) {
622
- if (this.customKeyHandler && this.customKeyHandler(e) === false)
786
+ if (this.keyFilter && this.keyFilter(e) === false)
623
787
  return;
624
788
  const extended = this.extendedKey(e, 'keyup');
625
789
  if (extended) {
@@ -645,14 +809,14 @@ export class Terminal {
645
809
  };
646
810
  if (this.core.modes.win32InputMode)
647
811
  return encodeWin32Key(input);
648
- const flags = this.core.kittyKeyboardFlags;
812
+ const flags = this.core.progressiveKeyFlags;
649
813
  if (flags)
650
- return encodeKittyKey(input, flags);
814
+ return encodeProgressiveKey(input, flags);
651
815
  return null;
652
816
  }
653
817
  /** Texto que chega sem `keydown` útil (teclado virtual, ditado): vai como digitado. */
654
818
  handleInput(e) {
655
- const ta = this.textarea;
819
+ const ta = this.inputElement;
656
820
  if (this.composing || e.isComposing)
657
821
  return;
658
822
  if (!this.keyHandled && e.inputType === 'insertText' && e.data)
@@ -661,42 +825,42 @@ export class Terminal {
661
825
  ta.value = '';
662
826
  }
663
827
  sendUserInput(data, clearSelection = true) {
664
- if (this.resolved.disableStdin)
828
+ if (this.resolved.readOnly)
665
829
  return;
666
- if (this.resolved.scrollOnUserInput)
830
+ if (this.resolved.followInput)
667
831
  this.scrollToBottom();
668
832
  if (clearSelection)
669
833
  this.core.clearSelection();
670
- this.core.triggerData(data, true);
834
+ this.core.emitInput(data, true);
671
835
  }
672
836
  handleCopy(e) {
673
- if (!this.hasSelection())
837
+ if (!this.core.hasSelection())
674
838
  return;
675
- e.clipboardData?.setData('text/plain', this.getSelection());
839
+ e.clipboardData?.setData("text/plain", this.core.getSelection());
676
840
  e.preventDefault();
677
841
  }
678
- /** Manda dados como se o usuário tivesse digitado (`wasUserInput` false: não rola nem limpa a seleção). */
679
- input(data, wasUserInput = true) {
680
- if (wasUserInput)
842
+ /** Manda dados como se a pessoa tivesse digitado (`asUser` false: não rola nem limpa a seleção). */
843
+ send(data, asUser = true) {
844
+ if (asUser)
681
845
  this.sendUserInput(data);
682
846
  else
683
- this.core.triggerData(data, false);
847
+ this.core.emitInput(data, false);
684
848
  }
685
849
  paste(data) {
686
- const bracketed = this.core.modes.bracketedPasteMode && !this.resolved.ignoreBracketedPasteMode;
850
+ const bracketed = this.core.modes.bracketedPasteMode && !this.resolved.plainPaste;
687
851
  this.sendUserInput(encodePaste(data, bracketed));
688
852
  }
689
853
  // ---------------------------------------------------------------- mouse
690
854
  mouseReportingActive(e, wheel = false) {
691
855
  if (this.core.modes.mouseTrackingMode === 'none')
692
856
  return false;
693
- // `mouseEventsRequireAlt`: cliques e movimento só vão para o processo com Alt (a roda não muda).
694
- if (this.resolved.mouseEventsRequireAlt && !wheel)
857
+ // `mouseReportNeedsAlt`: cliques e movimento só vão para o processo com Alt (a roda não muda).
858
+ if (this.resolved.mouseReportNeedsAlt && !wheel)
695
859
  return e.altKey;
696
860
  // Shift (ou Option no macOS, se ligado) força a seleção mesmo com o processo pedindo o mouse.
697
861
  if (e.shiftKey)
698
862
  return false;
699
- if (isMac() && e.altKey && this.resolved.macOptionClickForcesSelection)
863
+ if (isMac() && e.altKey && this.resolved.optionClickSelects)
700
864
  return false;
701
865
  return true;
702
866
  }
@@ -723,21 +887,21 @@ export class Terminal {
723
887
  col: col + 1,
724
888
  row: row + 1,
725
889
  shift: e.shiftKey,
726
- // Com `mouseEventsRequireAlt`, o Alt é o gesto de liberar o mouse, não um modificador do relatório.
727
- alt: e.altKey && !this.resolved.mouseEventsRequireAlt,
890
+ // Com `mouseReportNeedsAlt`, o Alt é o gesto de liberar o mouse, não um modificador do relatório.
891
+ alt: e.altKey && !this.resolved.mouseReportNeedsAlt,
728
892
  ctrl: e.ctrlKey,
729
893
  px: Math.max(1, Math.round(e.clientX - rect.left) + 1),
730
894
  py: Math.max(1, Math.round(e.clientY - rect.top) + 1),
731
895
  }, encoding);
732
896
  // No formato clássico, coordenadas acima de 223 viram bytes que não são UTF-8: vão como binário.
733
897
  if (encoding === 'default' && (col + 1 > 223 || row + 1 > 223))
734
- this.core.triggerBinary(data);
898
+ this.core.emitBinaryInput(data);
735
899
  else
736
- this.core.triggerData(data, true);
900
+ this.core.emitInput(data, true);
737
901
  }
738
902
  handleMouseDown(e) {
739
903
  const doc = this.element.ownerDocument;
740
- this.textarea?.focus({ preventScroll: true });
904
+ this.inputElement?.focus({ preventScroll: true });
741
905
  if (this.mouseReportingActive(e)) {
742
906
  const button = e.button === 1 ? 1 : e.button === 2 ? 2 : 0;
743
907
  this.mouseButton = button;
@@ -776,9 +940,9 @@ export class Terminal {
776
940
  this.selecting.moved = true;
777
941
  const { row } = this.renderer.edgeAt(ev.clientX, ev.clientY);
778
942
  if (row < 0)
779
- this.scrollLines(-1);
943
+ this.scrollBy(-1);
780
944
  else if (row >= this.rows)
781
- this.scrollLines(1);
945
+ this.scrollBy(1);
782
946
  this.extendSelection(this.bufferPoint(ev, true));
783
947
  };
784
948
  const up = (ev) => {
@@ -787,8 +951,8 @@ export class Terminal {
787
951
  doc.removeEventListener('mousemove', move);
788
952
  doc.removeEventListener('mouseup', up);
789
953
  if (state && state.mode === 'char' && !state.moved) {
790
- this.activateLinkAt(ev);
791
- if (ev.altKey && this.resolved.altClickMovesCursor)
954
+ this.openLinkAt(ev);
955
+ if (ev.altKey && this.resolved.moveCursorOnAltClick)
792
956
  this.moveCursorTo(ev);
793
957
  }
794
958
  };
@@ -835,7 +999,7 @@ export class Terminal {
835
999
  wordBounds(x, y) {
836
1000
  const lines = this.core.buffer.lines;
837
1001
  const cols = this.cols;
838
- const sep = this.resolved.wordSeparator;
1002
+ const sep = this.resolved.wordSeparators;
839
1003
  const charAt = (cx, cy) => {
840
1004
  const line = lines.get(cy);
841
1005
  if (!line)
@@ -882,7 +1046,7 @@ export class Terminal {
882
1046
  const [start, end] = this.wordBounds(point.x, point.y);
883
1047
  this.core.setSelection(start, end);
884
1048
  }
885
- /** Alt+clique: move o cursor do prompt até o ponto com setas (como o xterm faz). */
1049
+ /** Alt+clique: move o cursor do prompt até o ponto com setas. */
886
1050
  moveCursorTo(e) {
887
1051
  if (this.core.buffer !== this.core.normal)
888
1052
  return;
@@ -898,14 +1062,14 @@ export class Terminal {
898
1062
  this.sendUserInput(arrow.repeat(Math.abs(delta)));
899
1063
  }
900
1064
  handleWheel(e) {
901
- if (this.customWheelHandler && this.customWheelHandler(e) === false)
1065
+ if (this.wheelFilter && this.wheelFilter(e) === false)
902
1066
  return;
903
1067
  const cellHeight = this.renderer?.cellHeight || 16;
904
1068
  const unit = e.deltaMode === 1 ? 1 : e.deltaMode === 2 ? this.rows : 1 / cellHeight;
905
- const fast = (this.resolved.fastScrollModifier === 'alt' && e.altKey) ||
906
- (this.resolved.fastScrollModifier === 'ctrl' && e.ctrlKey) ||
907
- (this.resolved.fastScrollModifier === 'shift' && e.shiftKey);
908
- const sensitivity = fast ? this.resolved.fastScrollSensitivity : this.resolved.scrollSensitivity;
1069
+ const fast = (this.resolved.fastScrollKey === 'alt' && e.altKey) ||
1070
+ (this.resolved.fastScrollKey === 'ctrl' && e.ctrlKey) ||
1071
+ (this.resolved.fastScrollKey === 'shift' && e.shiftKey);
1072
+ const sensitivity = fast ? this.resolved.fastScrollFactor : this.resolved.scrollFactor;
909
1073
  const raw = e.deltaY * unit * sensitivity;
910
1074
  const lines = raw > 0 ? Math.max(1, Math.round(raw)) : raw < 0 ? Math.min(-1, Math.round(raw)) : 0;
911
1075
  if (!lines)
@@ -919,19 +1083,19 @@ export class Terminal {
919
1083
  // Tela alternativa sem mouse: a roda vira setas (o less e o vim rolam assim).
920
1084
  if (this.core.buffer === this.core.alt) {
921
1085
  const app = this.core.modes.applicationCursorKeysMode;
922
- this.core.triggerData(`\x1b${app ? 'O' : '['}${lines < 0 ? 'A' : 'B'}`.repeat(Math.abs(lines)), true);
1086
+ this.core.emitInput(`\x1b${app ? 'O' : '['}${lines < 0 ? 'A' : 'B'}`.repeat(Math.abs(lines)), true);
923
1087
  e.preventDefault();
924
1088
  return;
925
1089
  }
926
1090
  const b = this.core.buffer;
927
1091
  if ((lines < 0 && b.ydisp > 0) || (lines > 0 && b.ydisp < b.ybase))
928
1092
  e.preventDefault();
929
- if (this.resolved.smoothScrollDuration > 0)
1093
+ if (this.resolved.smoothScrollTime > 0)
930
1094
  this.smoothScrollBy(lines);
931
1095
  else
932
- this.scrollLines(lines);
1096
+ this.scrollBy(lines);
933
1097
  }
934
- /** Rolagem suave: anda até o alvo ao longo de `smoothScrollDuration`, linha a linha (a grade é por linhas). */
1098
+ /** Rolagem suave: anda até o alvo ao longo de `smoothScrollTime`, linha a linha (a grade é por linhas). */
935
1099
  smoothScrollBy(lines) {
936
1100
  const b = this.core.buffer;
937
1101
  const start = b.ydisp;
@@ -940,17 +1104,17 @@ export class Terminal {
940
1104
  const win = this.element?.ownerDocument.defaultView;
941
1105
  if (!win?.requestAnimationFrame) {
942
1106
  this.smoothTarget = null;
943
- this.scrollLines(target - start);
1107
+ this.scrollBy(target - start);
944
1108
  return;
945
1109
  }
946
1110
  win.cancelAnimationFrame(this.smoothFrame);
947
- const duration = this.resolved.smoothScrollDuration;
1111
+ const duration = this.resolved.smoothScrollTime;
948
1112
  const began = win.performance.now();
949
1113
  const step = (now) => {
950
1114
  const t = Math.min(1, (now - began) / duration);
951
1115
  const eased = 1 - (1 - t) ** 3;
952
1116
  const next = Math.round(start + (target - start) * eased);
953
- this.scrollLines(next - this.core.buffer.ydisp);
1117
+ this.scrollBy(next - this.core.buffer.ydisp);
954
1118
  if (t < 1)
955
1119
  this.smoothFrame = win.requestAnimationFrame(step);
956
1120
  else
@@ -964,15 +1128,15 @@ export class Terminal {
964
1128
  if (!el)
965
1129
  return;
966
1130
  const sb = this.resolved.scrollbar ?? {};
967
- const show = sb.showScrollbar !== false;
1131
+ const show = sb.visible !== false;
968
1132
  el.classList.toggle('hmt-no-scrollbar', !show);
969
1133
  el.classList.toggle('hmt-scrollbar-sized', show && sb.width !== undefined);
970
- el.classList.toggle('hmt-scrollbar-arrows', show && !!sb.showArrows);
1134
+ el.classList.toggle('hmt-scrollbar-arrows', show && !!sb.arrows);
971
1135
  if (sb.width !== undefined)
972
1136
  el.style.setProperty('--hmt-scrollbar-width', `${sb.width}px`);
973
1137
  else
974
1138
  el.style.removeProperty('--hmt-scrollbar-width');
975
- // A régua de visão geral liga com `width` (como no xterm.js) e mostra as decorações que pedem uma marca.
1139
+ // A régua de visão geral liga com `width` e mostra as decorações que pedem uma marca.
976
1140
  const ruler = show && sb.width !== undefined;
977
1141
  if (ruler && !this.overviewRuler) {
978
1142
  this.overviewRuler = el.ownerDocument.createElement('div');
@@ -985,9 +1149,9 @@ export class Terminal {
985
1149
  this.overviewRuler = undefined;
986
1150
  }
987
1151
  if (this.overviewRuler) {
988
- this.overviewRuler.classList.toggle('hmt-ruler-top', !!sb.overviewRuler?.showTopBorder);
989
- this.overviewRuler.classList.toggle('hmt-ruler-bottom', !!sb.overviewRuler?.showBottomBorder);
990
- const border = this.resolved.theme.overviewRulerBorder;
1152
+ this.overviewRuler.classList.toggle('hmt-ruler-top', !!sb.overview?.topBorder);
1153
+ this.overviewRuler.classList.toggle('hmt-ruler-bottom', !!sb.overview?.bottomBorder);
1154
+ const border = this.resolved.theme.overviewBorder;
991
1155
  if (border)
992
1156
  this.overviewRuler.style.setProperty('--hmt-ruler-border', border);
993
1157
  }
@@ -1005,7 +1169,7 @@ export class Terminal {
1005
1169
  const total = Math.max(1, b.lines.length);
1006
1170
  const doc = ruler.ownerDocument;
1007
1171
  for (const decoration of this.decorations) {
1008
- const o = decoration.options.overviewRulerOptions;
1172
+ const o = decoration.config.overview;
1009
1173
  if (!o || decoration.marker.isDisposed)
1010
1174
  continue;
1011
1175
  const mark = doc.createElement('div');
@@ -1036,13 +1200,13 @@ export class Terminal {
1036
1200
  }, BLINK_IDLE_MS);
1037
1201
  }
1038
1202
  // ---------------------------------------------------------------- links
1039
- registerLinkProvider(provider) {
1040
- this.linkProviders.push(provider);
1041
- return toDisposable(() => {
1042
- const index = this.linkProviders.indexOf(provider);
1203
+ addLinkSource(source) {
1204
+ this.linkSources.push(source);
1205
+ return () => {
1206
+ const index = this.linkSources.indexOf(source);
1043
1207
  if (index >= 0)
1044
- this.linkProviders.splice(index, 1);
1045
- });
1208
+ this.linkSources.splice(index, 1);
1209
+ };
1046
1210
  }
1047
1211
  handleHover(e) {
1048
1212
  if (this.selecting || !this.renderer || this.mouseButton >= 0)
@@ -1056,12 +1220,12 @@ export class Terminal {
1056
1220
  this.findLink(point, (link) => {
1057
1221
  if (request !== this.linkRequest || !link)
1058
1222
  return;
1059
- const ranges = rangesOf(link.range, this.cols);
1223
+ const ranges = rowRanges(link.range, this.cols);
1060
1224
  this.hoveredLink = { link, ranges };
1061
- const decorations = link.decorations ?? { pointerCursor: true, underline: true };
1062
- if (decorations.underline)
1225
+ const style = link.style ?? { pointer: true, underline: true };
1226
+ if (style.underline)
1063
1227
  this.renderer.linkRanges = ranges;
1064
- this.element?.classList.toggle('hmt-link-hover', decorations.pointerCursor);
1228
+ this.element?.classList.toggle('hmt-link-hover', style.pointer);
1065
1229
  this.renderer.refreshRows(0, -1);
1066
1230
  link.hover?.(e, link.text);
1067
1231
  });
@@ -1078,26 +1242,26 @@ export class Terminal {
1078
1242
  }
1079
1243
  hovered.link.leave?.(e, hovered.link.text);
1080
1244
  }
1081
- activateLinkAt(e) {
1245
+ openLinkAt(e) {
1082
1246
  const point = this.bufferPoint(e, false);
1083
1247
  const hovered = this.hoveredLink;
1084
1248
  if (hovered && hovered.ranges.some((r) => r.y === point.y && point.x >= r.start && point.x < r.end)) {
1085
- hovered.link.activate(e, hovered.link.text);
1249
+ hovered.link.open(e, hovered.link.text);
1086
1250
  return;
1087
1251
  }
1088
- this.findLink(point, (link) => link?.activate(e, link.text));
1252
+ this.findLink(point, (link) => link?.open(e, link.text));
1089
1253
  }
1090
- /** Procura o link sob `point`: primeiro os hiperlinks OSC 8, depois os provedores, na ordem de registro. */
1254
+ /** Procura o link sob `point`: primeiro os hiperlinks OSC 8, depois as fontes, na ordem de registro. */
1091
1255
  findLink(point, done) {
1092
1256
  const osc = this.hyperlinkAt(point);
1093
1257
  if (osc)
1094
1258
  return done(osc);
1095
- const providers = [...this.linkProviders];
1259
+ const sources = [...this.linkSources];
1096
1260
  const next = (i) => {
1097
- if (i >= providers.length)
1261
+ if (i >= sources.length)
1098
1262
  return done(undefined);
1099
- providers[i].provideLinks(point.y + 1, (links) => {
1100
- const hit = links?.find((link) => contains(link.range, point.x + 1, point.y + 1));
1263
+ sources[i].linksAt(point.y, (links) => {
1264
+ const hit = links?.find((link) => contains(link.range, point.x, point.y));
1101
1265
  if (hit)
1102
1266
  done(hit);
1103
1267
  else
@@ -1123,18 +1287,22 @@ export class Terminal {
1123
1287
  while (end < line.length - 1 && line.getExtended(end + 1).linkId === id)
1124
1288
  end++;
1125
1289
  const uri = link.uri;
1290
+ const range = { start: { col: start, row: point.y }, end: { col: end + 1, row: point.y } };
1291
+ const handler = () => this.resolved.hyperlinkHandler;
1126
1292
  return {
1127
- range: { start: { x: start + 1, y: point.y + 1 }, end: { x: end + 1, y: point.y + 1 } },
1293
+ range,
1128
1294
  text: uri,
1129
- activate: (event) => this.openLink(event, uri, { start: { x: start + 1, y: point.y + 1 }, end: { x: end + 1, y: point.y + 1 } }),
1295
+ open: (event) => this.openLink(event, uri, range),
1296
+ hover: (event) => handler()?.hover?.(event, uri, range),
1297
+ leave: (event) => handler()?.leave?.(event, uri, range),
1130
1298
  };
1131
1299
  }
1132
1300
  openLink(event, uri, range) {
1133
- const handler = this.resolved.linkHandler;
1301
+ const handler = this.resolved.hyperlinkHandler;
1134
1302
  if (handler) {
1135
1303
  const http = /^https?:/i.test(uri);
1136
- if (http || handler.allowNonHttpProtocols)
1137
- handler.activate(event, uri, range);
1304
+ if (http || handler.anyScheme)
1305
+ handler.open(event, uri, range);
1138
1306
  return;
1139
1307
  }
1140
1308
  if (!/^https?:/i.test(uri))
@@ -1143,17 +1311,17 @@ export class Terminal {
1143
1311
  win?.open(uri, '_blank', 'noopener,noreferrer');
1144
1312
  }
1145
1313
  // ---------------------------------------------------------------- marcadores e decorações
1146
- registerMarker(cursorYOffset = 0) {
1147
- return this.core.registerMarker(cursorYOffset);
1314
+ addMarker(cursorOffset = 0) {
1315
+ return this.core.addMarker(cursorOffset);
1148
1316
  }
1149
- registerDecoration(options) {
1317
+ decorate(options) {
1150
1318
  if (options.marker.isDisposed)
1151
1319
  return undefined;
1152
1320
  const decoration = new Decoration(options);
1153
1321
  this.decorations.push(decoration);
1154
- const sub = options.marker.onDispose(() => decoration.dispose());
1322
+ const off = options.marker.onDispose(() => decoration.dispose());
1155
1323
  decoration.onDispose(() => {
1156
- sub.dispose();
1324
+ off();
1157
1325
  const index = this.decorations.indexOf(decoration);
1158
1326
  if (index >= 0)
1159
1327
  this.decorations.splice(index, 1);
@@ -1196,10 +1364,10 @@ export class Terminal {
1196
1364
  el.style.left = `${x}px`;
1197
1365
  el.style.right = '';
1198
1366
  }
1199
- if (o.backgroundColor)
1200
- el.style.backgroundColor = o.backgroundColor;
1201
- if (o.foregroundColor)
1202
- el.style.color = o.foregroundColor;
1367
+ if (o.background)
1368
+ el.style.backgroundColor = o.background;
1369
+ if (o.color)
1370
+ el.style.color = o.color;
1203
1371
  decoration.fireRender(el);
1204
1372
  }
1205
1373
  }
@@ -1208,7 +1376,7 @@ export class Terminal {
1208
1376
  const el = this.element;
1209
1377
  if (!el)
1210
1378
  return;
1211
- if (!this.resolved.screenReaderMode) {
1379
+ if (!this.resolved.screenReader) {
1212
1380
  this.a11yTree?.remove();
1213
1381
  this.liveRegion?.remove();
1214
1382
  this.a11yTree = this.liveRegion = undefined;
@@ -1259,7 +1427,7 @@ export class Terminal {
1259
1427
  const text = line?.translateToString(true) ?? '';
1260
1428
  if (!text || text === this.liveText)
1261
1429
  return;
1262
- // Muitas linhas num instante: o leitor de tela não acompanha; avisa uma vez (`Terminal.strings.tooMuchOutput`).
1430
+ // Muitas linhas num instante: o leitor de tela não acompanha; avisa uma vez (`strings.tooMuchOutput`).
1263
1431
  const now = Date.now();
1264
1432
  if (now - this.announceWindow > 1000) {
1265
1433
  this.announceWindow = now;
@@ -1267,7 +1435,7 @@ export class Terminal {
1267
1435
  }
1268
1436
  if (++this.announcedLines > 20) {
1269
1437
  if (this.announcedLines === 21) {
1270
- this.liveText = Terminal.strings.tooMuchOutput;
1438
+ this.liveText = this.resolved.strings.tooMuchOutput;
1271
1439
  clearTimeout(this.liveTimer);
1272
1440
  this.liveTimer = setTimeout(() => {
1273
1441
  if (this.liveRegion)
@@ -1284,25 +1452,35 @@ export class Terminal {
1284
1452
  }, 50);
1285
1453
  }
1286
1454
  // ---------------------------------------------------------------- escrita e tamanho
1287
- write(data, callback) {
1288
- this.core.write(data, callback);
1455
+ write(data, done) {
1456
+ if (this.loading)
1457
+ this.queued.push({ data, done });
1458
+ else
1459
+ this.core.write(data, done);
1289
1460
  }
1290
- writeln(data, callback) {
1291
- this.core.write(data);
1292
- this.core.write('\r\n', callback);
1461
+ writeLine(data, done) {
1462
+ this.write(data);
1463
+ this.write('\r\n', done);
1293
1464
  }
1294
- resize(columns, rows) {
1295
- if (!Number.isFinite(columns) || !Number.isFinite(rows))
1465
+ resize(cols, rows) {
1466
+ if (!Number.isFinite(cols) || !Number.isFinite(rows))
1296
1467
  return;
1297
- this.core.resize(columns, rows);
1468
+ this.core.resize(cols, rows);
1298
1469
  this.resolved.cols = this.core.cols;
1299
1470
  this.resolved.rows = this.core.rows;
1300
1471
  }
1301
- refresh(start, end) {
1302
- this.renderer?.refreshRows(start, end);
1472
+ fit() {
1473
+ return this.fitter.fit();
1474
+ }
1475
+ proposeSize() {
1476
+ return this.fitter.proposeSize();
1477
+ }
1478
+ redraw(start = 0, end = -1) {
1479
+ if (end < 0)
1480
+ this.renderer?.refreshAll();
1481
+ else
1482
+ this.renderer?.refreshRows(start, end);
1303
1483
  }
1304
- /** Para a renderização por textura do xterm; aqui a renderização é DOM e não há o que limpar. */
1305
- clearTextureAtlas() { }
1306
1484
  reset() {
1307
1485
  this.core.reset();
1308
1486
  this.syncScrollArea();
@@ -1333,10 +1511,20 @@ export class Terminal {
1333
1511
  this.renderer?.refreshAll();
1334
1512
  this.scrollEmitter.fire(0);
1335
1513
  }
1514
+ async remeasure() {
1515
+ const fonts = this.element?.ownerDocument.fonts;
1516
+ if (fonts?.ready)
1517
+ await fonts.ready;
1518
+ if (this.disposed || !this.renderer)
1519
+ return;
1520
+ this.renderer.measureCell();
1521
+ this.renderer.refreshAll();
1522
+ this.syncScrollArea();
1523
+ }
1336
1524
  // ---------------------------------------------------------------- rolagem
1337
- scrollLines(amount) {
1525
+ scrollBy(lines) {
1338
1526
  const b = this.core.buffer;
1339
- const target = Math.max(0, Math.min(b.ybase, b.ydisp + Math.trunc(amount)));
1527
+ const target = Math.max(0, Math.min(b.ybase, b.ydisp + Math.trunc(lines)));
1340
1528
  if (target === b.ydisp)
1341
1529
  return;
1342
1530
  b.ydisp = target;
@@ -1344,18 +1532,18 @@ export class Terminal {
1344
1532
  this.renderer?.refreshAll();
1345
1533
  this.scrollEmitter.fire(target);
1346
1534
  }
1347
- scrollPages(pageCount) {
1348
- this.scrollLines(pageCount * (this.rows - 1));
1535
+ scrollByPages(pages) {
1536
+ this.scrollBy(pages * (this.rows - 1));
1349
1537
  }
1350
1538
  scrollToTop() {
1351
- this.scrollLines(-this.core.buffer.ydisp);
1539
+ this.scrollBy(-this.core.buffer.ydisp);
1352
1540
  }
1353
1541
  scrollToBottom() {
1354
1542
  const b = this.core.buffer;
1355
- this.scrollLines(b.ybase - b.ydisp);
1543
+ this.scrollBy(b.ybase - b.ydisp);
1356
1544
  }
1357
- scrollToLine(line) {
1358
- this.scrollLines(line - this.core.buffer.ydisp);
1545
+ scrollTo(line) {
1546
+ this.scrollBy(line - this.core.buffer.ydisp);
1359
1547
  }
1360
1548
  syncScrollArea() {
1361
1549
  const r = this.renderer;
@@ -1371,72 +1559,54 @@ export class Terminal {
1371
1559
  if (Math.abs(this.viewport.scrollTop - top) >= 1)
1372
1560
  this.viewport.scrollTop = top;
1373
1561
  }
1374
- // ---------------------------------------------------------------- seleção
1375
- hasSelection() {
1376
- return this.core.hasSelection();
1377
- }
1378
- getSelection() {
1379
- return this.core.getSelection();
1380
- }
1381
- /** Posição da seleção, a partir de 1; `end` é exclusivo. */
1382
- getSelectionPosition() {
1383
- const s = this.core.selection;
1384
- if (!s)
1385
- return undefined;
1386
- return { start: { x: s.start.x + 1, y: s.start.y + 1 }, end: { x: s.end.x + 1, y: s.end.y + 1 } };
1387
- }
1388
- clearSelection() {
1389
- this.core.clearSelection();
1390
- }
1391
- select(column, row, length) {
1392
- this.core.select(column, row, length);
1562
+ // ---------------------------------------------------------------- WebSocket, serialização e descarte
1563
+ connect(socket, options = {}) {
1564
+ const connection = new Connection(socket, options);
1565
+ connection.attach(this);
1566
+ return () => connection.dispose();
1393
1567
  }
1394
- selectAll() {
1395
- this.core.selectAll();
1568
+ serialize(options) {
1569
+ return this.serializer.serialize(this, options);
1396
1570
  }
1397
- selectLines(start, end) {
1398
- this.core.selectLines(start, end);
1399
- }
1400
- // ---------------------------------------------------------------- complementos e descarte
1401
- loadAddon(addon) {
1402
- this.addons.push(addon);
1403
- addon.activate(this);
1571
+ serializeHtml(options) {
1572
+ return this.serializer.serializeAsHTML(this, options);
1404
1573
  }
1405
1574
  dispose() {
1406
1575
  if (this.disposed)
1407
1576
  return;
1408
1577
  this.disposed = true;
1409
- for (const addon of this.addons.splice(0))
1410
- addon.dispose();
1578
+ for (const feature of this.features.values())
1579
+ feature.dispose();
1580
+ this.features.clear();
1581
+ this.fitter.dispose();
1411
1582
  for (const decoration of [...this.decorations])
1412
1583
  decoration.dispose();
1413
1584
  clearTimeout(this.liveTimer);
1414
1585
  clearTimeout(this.blinkTimer);
1415
1586
  this.element?.ownerDocument.defaultView?.cancelAnimationFrame?.(this.smoothFrame);
1416
- this.dimensionsEmitter.dispose();
1417
1587
  this.store.dispose();
1418
1588
  this.renderer?.dispose();
1419
1589
  this.element?.remove();
1420
1590
  this.core.dispose();
1421
- for (const emitter of [this.keyEmitter, this.renderEmitter, this.scrollEmitter, this.selectionEmitter, this.bufferEmitter])
1591
+ for (const emitter of [
1592
+ this.keyEmitter, this.renderEmitter, this.scrollEmitter, this.selectionEmitter, this.screenEmitter, this.metricsEmitter,
1593
+ this.searchEmitter, this.progressEmitter, this.programStatusEmitter,
1594
+ ])
1422
1595
  emitter.dispose();
1423
1596
  }
1424
- /** Só para os testes e para o componente Angular: desenha já o que está pendente. */
1597
+ /** Para os testes: desenha já o que está pendente. */
1425
1598
  renderNow() {
1426
1599
  this.renderer?.renderNow();
1427
1600
  }
1428
- /**
1429
- * Partes internas para os complementos deste pacote (imagens, renderizador WebGL…). Não é API pública estável:
1430
- * fora do pacote, use a API no formato do xterm.js.
1431
- */
1432
- get _internals() {
1601
+ /** Partes internas para os recursos deste pacote (imagens, GPU, serialização…). */
1602
+ get internals() {
1433
1603
  return {
1434
1604
  core: this.core,
1435
1605
  renderer: this.renderer,
1436
1606
  element: this.element,
1437
1607
  onFrame: (listener) => {
1438
1608
  this.renderer?.frameListeners.add(listener);
1439
- return toDisposable(() => this.renderer?.frameListeners.delete(listener));
1609
+ return () => this.renderer?.frameListeners.delete(listener);
1440
1610
  },
1441
1611
  refreshAll: () => this.renderer?.refreshAll(),
1442
1612
  };
@@ -1447,22 +1617,38 @@ function cssOr(css, fallback) {
1447
1617
  return fallback;
1448
1618
  return parseCssColor(css) ?? fallback;
1449
1619
  }
1450
- function stripUndefined(value) {
1451
- return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
1620
+ /** Mesmo valor de opção de recurso: objetos comparados campo a campo, para `[options]` recriado a cada render. */
1621
+ function sameValue(a, b) {
1622
+ if (a === b)
1623
+ return true;
1624
+ if (typeof a !== 'object' || typeof b !== 'object' || !a || !b)
1625
+ return false;
1626
+ const x = a;
1627
+ const y = b;
1628
+ const keys = Object.keys(x);
1629
+ if (keys.length !== Object.keys(y).length)
1630
+ return false;
1631
+ return keys.every((key) => {
1632
+ const p = x[key];
1633
+ const q = y[key];
1634
+ if (p instanceof RegExp && q instanceof RegExp)
1635
+ return p.source === q.source && p.flags === q.flags;
1636
+ return p === q;
1637
+ });
1452
1638
  }
1453
- function contains(range, x, y) {
1454
- const after = y > range.start.y || (y === range.start.y && x >= range.start.x);
1455
- const before = y < range.end.y || (y === range.end.y && x <= range.end.x);
1639
+ function contains(range, col, row) {
1640
+ const after = row > range.start.row || (row === range.start.row && col >= range.start.col);
1641
+ const before = row < range.end.row || (row === range.end.row && col < range.end.col);
1456
1642
  return after && before;
1457
1643
  }
1458
- /** Faixa 1-based e inclusiva → faixas por linha, 0-based, `end` exclusivo. */
1459
- function rangesOf(range, cols) {
1644
+ /** Faixa de células → faixas por linha da tela, `end` exclusivo. */
1645
+ function rowRanges(range, cols) {
1460
1646
  const out = [];
1461
- for (let y = range.start.y; y <= range.end.y; y++) {
1462
- const start = y === range.start.y ? range.start.x - 1 : 0;
1463
- const end = y === range.end.y ? range.end.x : cols;
1464
- out.push({ y: y - 1, start, end });
1647
+ for (let y = range.start.row; y <= range.end.row; y++) {
1648
+ const start = y === range.start.row ? range.start.col : 0;
1649
+ const end = y === range.end.row ? range.end.col : cols;
1650
+ out.push({ y, start, end });
1465
1651
  }
1466
1652
  return out;
1467
1653
  }
1468
- //# sourceMappingURL=terminal.js.map
1654
+ //# sourceMappingURL=engine.js.map