@xterm/xterm 5.4.0-beta.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -0
  3. package/css/xterm.css +209 -0
  4. package/lib/xterm.js +2 -0
  5. package/lib/xterm.js.map +1 -0
  6. package/package.json +101 -0
  7. package/src/browser/AccessibilityManager.ts +278 -0
  8. package/src/browser/Clipboard.ts +93 -0
  9. package/src/browser/ColorContrastCache.ts +34 -0
  10. package/src/browser/Lifecycle.ts +33 -0
  11. package/src/browser/Linkifier2.ts +416 -0
  12. package/src/browser/LocalizableStrings.ts +12 -0
  13. package/src/browser/OscLinkProvider.ts +128 -0
  14. package/src/browser/RenderDebouncer.ts +83 -0
  15. package/src/browser/Terminal.ts +1317 -0
  16. package/src/browser/TimeBasedDebouncer.ts +86 -0
  17. package/src/browser/Types.d.ts +181 -0
  18. package/src/browser/Viewport.ts +401 -0
  19. package/src/browser/decorations/BufferDecorationRenderer.ts +134 -0
  20. package/src/browser/decorations/ColorZoneStore.ts +117 -0
  21. package/src/browser/decorations/OverviewRulerRenderer.ts +218 -0
  22. package/src/browser/input/CompositionHelper.ts +246 -0
  23. package/src/browser/input/Mouse.ts +54 -0
  24. package/src/browser/input/MoveToCell.ts +249 -0
  25. package/src/browser/public/Terminal.ts +260 -0
  26. package/src/browser/renderer/dom/DomRenderer.ts +509 -0
  27. package/src/browser/renderer/dom/DomRendererRowFactory.ts +526 -0
  28. package/src/browser/renderer/dom/WidthCache.ts +160 -0
  29. package/src/browser/renderer/shared/CellColorResolver.ts +137 -0
  30. package/src/browser/renderer/shared/CharAtlasCache.ts +96 -0
  31. package/src/browser/renderer/shared/CharAtlasUtils.ts +75 -0
  32. package/src/browser/renderer/shared/Constants.ts +14 -0
  33. package/src/browser/renderer/shared/CursorBlinkStateManager.ts +146 -0
  34. package/src/browser/renderer/shared/CustomGlyphs.ts +687 -0
  35. package/src/browser/renderer/shared/DevicePixelObserver.ts +41 -0
  36. package/src/browser/renderer/shared/README.md +1 -0
  37. package/src/browser/renderer/shared/RendererUtils.ts +58 -0
  38. package/src/browser/renderer/shared/SelectionRenderModel.ts +91 -0
  39. package/src/browser/renderer/shared/TextureAtlas.ts +1082 -0
  40. package/src/browser/renderer/shared/Types.d.ts +173 -0
  41. package/src/browser/selection/SelectionModel.ts +144 -0
  42. package/src/browser/selection/Types.d.ts +15 -0
  43. package/src/browser/services/CharSizeService.ts +102 -0
  44. package/src/browser/services/CharacterJoinerService.ts +339 -0
  45. package/src/browser/services/CoreBrowserService.ts +137 -0
  46. package/src/browser/services/MouseService.ts +46 -0
  47. package/src/browser/services/RenderService.ts +279 -0
  48. package/src/browser/services/SelectionService.ts +1031 -0
  49. package/src/browser/services/Services.ts +147 -0
  50. package/src/browser/services/ThemeService.ts +237 -0
  51. package/src/common/CircularList.ts +241 -0
  52. package/src/common/Clone.ts +23 -0
  53. package/src/common/Color.ts +357 -0
  54. package/src/common/CoreTerminal.ts +284 -0
  55. package/src/common/EventEmitter.ts +78 -0
  56. package/src/common/InputHandler.ts +3461 -0
  57. package/src/common/Lifecycle.ts +108 -0
  58. package/src/common/MultiKeyMap.ts +42 -0
  59. package/src/common/Platform.ts +44 -0
  60. package/src/common/SortedList.ts +118 -0
  61. package/src/common/TaskQueue.ts +166 -0
  62. package/src/common/TypedArrayUtils.ts +17 -0
  63. package/src/common/Types.d.ts +553 -0
  64. package/src/common/WindowsMode.ts +27 -0
  65. package/src/common/buffer/AttributeData.ts +196 -0
  66. package/src/common/buffer/Buffer.ts +654 -0
  67. package/src/common/buffer/BufferLine.ts +524 -0
  68. package/src/common/buffer/BufferRange.ts +13 -0
  69. package/src/common/buffer/BufferReflow.ts +223 -0
  70. package/src/common/buffer/BufferSet.ts +134 -0
  71. package/src/common/buffer/CellData.ts +94 -0
  72. package/src/common/buffer/Constants.ts +149 -0
  73. package/src/common/buffer/Marker.ts +43 -0
  74. package/src/common/buffer/Types.d.ts +52 -0
  75. package/src/common/data/Charsets.ts +256 -0
  76. package/src/common/data/EscapeSequences.ts +153 -0
  77. package/src/common/input/Keyboard.ts +398 -0
  78. package/src/common/input/TextDecoder.ts +346 -0
  79. package/src/common/input/UnicodeV6.ts +145 -0
  80. package/src/common/input/WriteBuffer.ts +246 -0
  81. package/src/common/input/XParseColor.ts +80 -0
  82. package/src/common/parser/Constants.ts +58 -0
  83. package/src/common/parser/DcsParser.ts +192 -0
  84. package/src/common/parser/EscapeSequenceParser.ts +792 -0
  85. package/src/common/parser/OscParser.ts +238 -0
  86. package/src/common/parser/Params.ts +229 -0
  87. package/src/common/parser/Types.d.ts +275 -0
  88. package/src/common/public/AddonManager.ts +53 -0
  89. package/src/common/public/BufferApiView.ts +35 -0
  90. package/src/common/public/BufferLineApiView.ts +29 -0
  91. package/src/common/public/BufferNamespaceApi.ts +36 -0
  92. package/src/common/public/ParserApi.ts +37 -0
  93. package/src/common/public/UnicodeApi.ts +27 -0
  94. package/src/common/services/BufferService.ts +151 -0
  95. package/src/common/services/CharsetService.ts +34 -0
  96. package/src/common/services/CoreMouseService.ts +318 -0
  97. package/src/common/services/CoreService.ts +87 -0
  98. package/src/common/services/DecorationService.ts +140 -0
  99. package/src/common/services/InstantiationService.ts +85 -0
  100. package/src/common/services/LogService.ts +124 -0
  101. package/src/common/services/OptionsService.ts +202 -0
  102. package/src/common/services/OscLinkService.ts +115 -0
  103. package/src/common/services/ServiceRegistry.ts +49 -0
  104. package/src/common/services/Services.ts +373 -0
  105. package/src/common/services/UnicodeService.ts +111 -0
  106. package/src/headless/Terminal.ts +136 -0
  107. package/src/headless/public/Terminal.ts +195 -0
  108. package/typings/xterm.d.ts +1857 -0
@@ -0,0 +1,1317 @@
1
+ /**
2
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4
+ * @license MIT
5
+ *
6
+ * Originally forked from (with the author's permission):
7
+ * Fabrice Bellard's javascript vt100 for jslinux:
8
+ * http://bellard.org/jslinux/
9
+ * Copyright (c) 2011 Fabrice Bellard
10
+ * The original design remains. The terminal itself
11
+ * has been extended to include xterm CSI codes, among
12
+ * other features.
13
+ *
14
+ * Terminal Emulation References:
15
+ * http://vt100.net/
16
+ * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
17
+ * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
18
+ * http://invisible-island.net/vttest/
19
+ * http://www.inwap.com/pdp10/ansicode.txt
20
+ * http://linux.die.net/man/4/console_codes
21
+ * http://linux.die.net/man/7/urxvt
22
+ */
23
+
24
+ import { copyHandler, handlePasteEvent, moveTextAreaUnderMouseCursor, paste, rightClickHandler } from 'browser/Clipboard';
25
+ import { addDisposableDomListener } from 'browser/Lifecycle';
26
+ import { Linkifier2 } from 'browser/Linkifier2';
27
+ import * as Strings from 'browser/LocalizableStrings';
28
+ import { OscLinkProvider } from 'browser/OscLinkProvider';
29
+ import { CharacterJoinerHandler, CustomKeyEventHandler, IBrowser, IBufferRange, ICompositionHelper, ILinkifier2, ITerminal, IViewport } from 'browser/Types';
30
+ import { Viewport } from 'browser/Viewport';
31
+ import { BufferDecorationRenderer } from 'browser/decorations/BufferDecorationRenderer';
32
+ import { OverviewRulerRenderer } from 'browser/decorations/OverviewRulerRenderer';
33
+ import { CompositionHelper } from 'browser/input/CompositionHelper';
34
+ import { DomRenderer } from 'browser/renderer/dom/DomRenderer';
35
+ import { IRenderer } from 'browser/renderer/shared/Types';
36
+ import { CharSizeService } from 'browser/services/CharSizeService';
37
+ import { CharacterJoinerService } from 'browser/services/CharacterJoinerService';
38
+ import { CoreBrowserService } from 'browser/services/CoreBrowserService';
39
+ import { MouseService } from 'browser/services/MouseService';
40
+ import { RenderService } from 'browser/services/RenderService';
41
+ import { SelectionService } from 'browser/services/SelectionService';
42
+ import { ICharSizeService, ICharacterJoinerService, ICoreBrowserService, IMouseService, IRenderService, ISelectionService, IThemeService } from 'browser/services/Services';
43
+ import { ThemeService } from 'browser/services/ThemeService';
44
+ import { color, rgba } from 'common/Color';
45
+ import { CoreTerminal } from 'common/CoreTerminal';
46
+ import { EventEmitter, IEvent, forwardEvent } from 'common/EventEmitter';
47
+ import { MutableDisposable, toDisposable } from 'common/Lifecycle';
48
+ import * as Browser from 'common/Platform';
49
+ import { ColorRequestType, CoreMouseAction, CoreMouseButton, CoreMouseEventType, IColorEvent, ITerminalOptions, KeyboardResultType, ScrollSource, SpecialColorIndex } from 'common/Types';
50
+ import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
51
+ import { IBuffer } from 'common/buffer/Types';
52
+ import { C0, C1_ESCAPED } from 'common/data/EscapeSequences';
53
+ import { evaluateKeyboardEvent } from 'common/input/Keyboard';
54
+ import { toRgbString } from 'common/input/XParseColor';
55
+ import { DecorationService } from 'common/services/DecorationService';
56
+ import { IDecorationService } from 'common/services/Services';
57
+ import { IDecoration, IDecorationOptions, IDisposable, ILinkProvider, IMarker } from '@xterm/xterm';
58
+ import { WindowsOptionsReportType } from '../common/InputHandler';
59
+ import { AccessibilityManager } from './AccessibilityManager';
60
+
61
+ export class Terminal extends CoreTerminal implements ITerminal {
62
+ public textarea: HTMLTextAreaElement | undefined;
63
+ public element: HTMLElement | undefined;
64
+ public screenElement: HTMLElement | undefined;
65
+
66
+ private _document: Document | undefined;
67
+ private _viewportScrollArea: HTMLElement | undefined;
68
+ private _viewportElement: HTMLElement | undefined;
69
+ private _helperContainer: HTMLElement | undefined;
70
+ private _compositionView: HTMLElement | undefined;
71
+
72
+ private _overviewRulerRenderer: OverviewRulerRenderer | undefined;
73
+
74
+ public browser: IBrowser = Browser as any;
75
+
76
+ private _customKeyEventHandler: CustomKeyEventHandler | undefined;
77
+
78
+ // browser services
79
+ private _decorationService: DecorationService;
80
+ private _charSizeService: ICharSizeService | undefined;
81
+ private _coreBrowserService: ICoreBrowserService | undefined;
82
+ private _mouseService: IMouseService | undefined;
83
+ private _renderService: IRenderService | undefined;
84
+ private _themeService: IThemeService | undefined;
85
+ private _characterJoinerService: ICharacterJoinerService | undefined;
86
+ private _selectionService: ISelectionService | undefined;
87
+
88
+ /**
89
+ * Records whether the keydown event has already been handled and triggered a data event, if so
90
+ * the keypress event should not trigger a data event but should still print to the textarea so
91
+ * screen readers will announce it.
92
+ */
93
+ private _keyDownHandled: boolean = false;
94
+
95
+ /**
96
+ * Records whether a keydown event has occured since the last keyup event, i.e. whether a key
97
+ * is currently "pressed".
98
+ */
99
+ private _keyDownSeen: boolean = false;
100
+
101
+ /**
102
+ * Records whether the keypress event has already been handled and triggered a data event, if so
103
+ * the input event should not trigger a data event but should still print to the textarea so
104
+ * screen readers will announce it.
105
+ */
106
+ private _keyPressHandled: boolean = false;
107
+
108
+ /**
109
+ * Records whether there has been a keydown event for a dead key without a corresponding keydown
110
+ * event for the composed/alternative character. If we cancel the keydown event for the dead key,
111
+ * no events will be emitted for the final character.
112
+ */
113
+ private _unprocessedDeadKey: boolean = false;
114
+
115
+ public linkifier2: ILinkifier2;
116
+ public viewport: IViewport | undefined;
117
+ private _compositionHelper: ICompositionHelper | undefined;
118
+ private _accessibilityManager: MutableDisposable<AccessibilityManager> = this.register(new MutableDisposable());
119
+
120
+ private readonly _onCursorMove = this.register(new EventEmitter<void>());
121
+ public readonly onCursorMove = this._onCursorMove.event;
122
+ private readonly _onKey = this.register(new EventEmitter<{ key: string, domEvent: KeyboardEvent }>());
123
+ public readonly onKey = this._onKey.event;
124
+ private readonly _onRender = this.register(new EventEmitter<{ start: number, end: number }>());
125
+ public readonly onRender = this._onRender.event;
126
+ private readonly _onSelectionChange = this.register(new EventEmitter<void>());
127
+ public readonly onSelectionChange = this._onSelectionChange.event;
128
+ private readonly _onTitleChange = this.register(new EventEmitter<string>());
129
+ public readonly onTitleChange = this._onTitleChange.event;
130
+ private readonly _onBell = this.register(new EventEmitter<void>());
131
+ public readonly onBell = this._onBell.event;
132
+
133
+ private _onFocus = this.register(new EventEmitter<void>());
134
+ public get onFocus(): IEvent<void> { return this._onFocus.event; }
135
+ private _onBlur = this.register(new EventEmitter<void>());
136
+ public get onBlur(): IEvent<void> { return this._onBlur.event; }
137
+ private _onA11yCharEmitter = this.register(new EventEmitter<string>());
138
+ public get onA11yChar(): IEvent<string> { return this._onA11yCharEmitter.event; }
139
+ private _onA11yTabEmitter = this.register(new EventEmitter<number>());
140
+ public get onA11yTab(): IEvent<number> { return this._onA11yTabEmitter.event; }
141
+ private _onWillOpen = this.register(new EventEmitter<HTMLElement>());
142
+ public get onWillOpen(): IEvent<HTMLElement> { return this._onWillOpen.event; }
143
+
144
+ constructor(
145
+ options: Partial<ITerminalOptions> = {}
146
+ ) {
147
+ super(options);
148
+
149
+ this._setup();
150
+
151
+ this.linkifier2 = this.register(this._instantiationService.createInstance(Linkifier2));
152
+ this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(OscLinkProvider));
153
+ this._decorationService = this._instantiationService.createInstance(DecorationService);
154
+ this._instantiationService.setService(IDecorationService, this._decorationService);
155
+
156
+ // Setup InputHandler listeners
157
+ this.register(this._inputHandler.onRequestBell(() => this._onBell.fire()));
158
+ this.register(this._inputHandler.onRequestRefreshRows((start, end) => this.refresh(start, end)));
159
+ this.register(this._inputHandler.onRequestSendFocus(() => this._reportFocus()));
160
+ this.register(this._inputHandler.onRequestReset(() => this.reset()));
161
+ this.register(this._inputHandler.onRequestWindowsOptionsReport(type => this._reportWindowsOptions(type)));
162
+ this.register(this._inputHandler.onColor((event) => this._handleColorEvent(event)));
163
+ this.register(forwardEvent(this._inputHandler.onCursorMove, this._onCursorMove));
164
+ this.register(forwardEvent(this._inputHandler.onTitleChange, this._onTitleChange));
165
+ this.register(forwardEvent(this._inputHandler.onA11yChar, this._onA11yCharEmitter));
166
+ this.register(forwardEvent(this._inputHandler.onA11yTab, this._onA11yTabEmitter));
167
+
168
+ // Setup listeners
169
+ this.register(this._bufferService.onResize(e => this._afterResize(e.cols, e.rows)));
170
+
171
+ this.register(toDisposable(() => {
172
+ this._customKeyEventHandler = undefined;
173
+ this.element?.parentNode?.removeChild(this.element);
174
+ }));
175
+ }
176
+
177
+ /**
178
+ * Handle color event from inputhandler for OSC 4|104 | 10|110 | 11|111 | 12|112.
179
+ * An event from OSC 4|104 may contain multiple set or report requests, and multiple
180
+ * or none restore requests (resetting all),
181
+ * while an event from OSC 10|110 | 11|111 | 12|112 always contains a single request.
182
+ */
183
+ private _handleColorEvent(event: IColorEvent): void {
184
+ if (!this._themeService) return;
185
+ for (const req of event) {
186
+ let acc: 'foreground' | 'background' | 'cursor' | 'ansi';
187
+ let ident = '';
188
+ switch (req.index) {
189
+ case SpecialColorIndex.FOREGROUND: // OSC 10 | 110
190
+ acc = 'foreground';
191
+ ident = '10';
192
+ break;
193
+ case SpecialColorIndex.BACKGROUND: // OSC 11 | 111
194
+ acc = 'background';
195
+ ident = '11';
196
+ break;
197
+ case SpecialColorIndex.CURSOR: // OSC 12 | 112
198
+ acc = 'cursor';
199
+ ident = '12';
200
+ break;
201
+ default: // OSC 4 | 104
202
+ // we can skip the [0..255] range check here (already done in inputhandler)
203
+ acc = 'ansi';
204
+ ident = '4;' + req.index;
205
+ }
206
+ switch (req.type) {
207
+ case ColorRequestType.REPORT:
208
+ const channels = color.toColorRGB(acc === 'ansi'
209
+ ? this._themeService.colors.ansi[req.index]
210
+ : this._themeService.colors[acc]);
211
+ this.coreService.triggerDataEvent(`${C0.ESC}]${ident};${toRgbString(channels)}${C1_ESCAPED.ST}`);
212
+ break;
213
+ case ColorRequestType.SET:
214
+ if (acc === 'ansi') {
215
+ this._themeService.modifyColors(colors => colors.ansi[req.index] = rgba.toColor(...req.color));
216
+ } else {
217
+ const narrowedAcc = acc;
218
+ this._themeService.modifyColors(colors => colors[narrowedAcc] = rgba.toColor(...req.color));
219
+ }
220
+ break;
221
+ case ColorRequestType.RESTORE:
222
+ this._themeService.restoreColor(req.index);
223
+ break;
224
+ }
225
+ }
226
+ }
227
+
228
+ protected _setup(): void {
229
+ super._setup();
230
+
231
+ this._customKeyEventHandler = undefined;
232
+ }
233
+
234
+ /**
235
+ * Convenience property to active buffer.
236
+ */
237
+ public get buffer(): IBuffer {
238
+ return this.buffers.active;
239
+ }
240
+
241
+ /**
242
+ * Focus the terminal. Delegates focus handling to the terminal's DOM element.
243
+ */
244
+ public focus(): void {
245
+ if (this.textarea) {
246
+ this.textarea.focus({ preventScroll: true });
247
+ }
248
+ }
249
+
250
+ private _handleScreenReaderModeOptionChange(value: boolean): void {
251
+ if (value) {
252
+ if (!this._accessibilityManager.value && this._renderService) {
253
+ this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);
254
+ }
255
+ } else {
256
+ this._accessibilityManager.clear();
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Binds the desired focus behavior on a given terminal object.
262
+ */
263
+ private _handleTextAreaFocus(ev: KeyboardEvent): void {
264
+ if (this.coreService.decPrivateModes.sendFocus) {
265
+ this.coreService.triggerDataEvent(C0.ESC + '[I');
266
+ }
267
+ this.updateCursorStyle(ev);
268
+ this.element!.classList.add('focus');
269
+ this._showCursor();
270
+ this._onFocus.fire();
271
+ }
272
+
273
+ /**
274
+ * Blur the terminal, calling the blur function on the terminal's underlying
275
+ * textarea.
276
+ */
277
+ public blur(): void {
278
+ return this.textarea?.blur();
279
+ }
280
+
281
+ /**
282
+ * Binds the desired blur behavior on a given terminal object.
283
+ */
284
+ private _handleTextAreaBlur(): void {
285
+ // Text can safely be removed on blur. Doing it earlier could interfere with
286
+ // screen readers reading it out.
287
+ this.textarea!.value = '';
288
+ this.refresh(this.buffer.y, this.buffer.y);
289
+ if (this.coreService.decPrivateModes.sendFocus) {
290
+ this.coreService.triggerDataEvent(C0.ESC + '[O');
291
+ }
292
+ this.element!.classList.remove('focus');
293
+ this._onBlur.fire();
294
+ }
295
+
296
+ private _syncTextArea(): void {
297
+ if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper!.isComposing || !this._renderService) {
298
+ return;
299
+ }
300
+ const cursorY = this.buffer.ybase + this.buffer.y;
301
+ const bufferLine = this.buffer.lines.get(cursorY);
302
+ if (!bufferLine) {
303
+ return;
304
+ }
305
+ const cursorX = Math.min(this.buffer.x, this.cols - 1);
306
+ const cellHeight = this._renderService.dimensions.css.cell.height;
307
+ const width = bufferLine.getWidth(cursorX);
308
+ const cellWidth = this._renderService.dimensions.css.cell.width * width;
309
+ const cursorTop = this.buffer.y * this._renderService.dimensions.css.cell.height;
310
+ const cursorLeft = cursorX * this._renderService.dimensions.css.cell.width;
311
+
312
+ // Sync the textarea to the exact position of the composition view so the IME knows where the
313
+ // text is.
314
+ this.textarea.style.left = cursorLeft + 'px';
315
+ this.textarea.style.top = cursorTop + 'px';
316
+ this.textarea.style.width = cellWidth + 'px';
317
+ this.textarea.style.height = cellHeight + 'px';
318
+ this.textarea.style.lineHeight = cellHeight + 'px';
319
+ this.textarea.style.zIndex = '-5';
320
+ }
321
+
322
+ /**
323
+ * Initialize default behavior
324
+ */
325
+ private _initGlobal(): void {
326
+ this._bindKeys();
327
+
328
+ // Bind clipboard functionality
329
+ this.register(addDisposableDomListener(this.element!, 'copy', (event: ClipboardEvent) => {
330
+ // If mouse events are active it means the selection manager is disabled and
331
+ // copy should be handled by the host program.
332
+ if (!this.hasSelection()) {
333
+ return;
334
+ }
335
+ copyHandler(event, this._selectionService!);
336
+ }));
337
+ const pasteHandlerWrapper = (event: ClipboardEvent): void => handlePasteEvent(event, this.textarea!, this.coreService, this.optionsService);
338
+ this.register(addDisposableDomListener(this.textarea!, 'paste', pasteHandlerWrapper));
339
+ this.register(addDisposableDomListener(this.element!, 'paste', pasteHandlerWrapper));
340
+
341
+ // Handle right click context menus
342
+ if (Browser.isFirefox) {
343
+ // Firefox doesn't appear to fire the contextmenu event on right click
344
+ this.register(addDisposableDomListener(this.element!, 'mousedown', (event: MouseEvent) => {
345
+ if (event.button === 2) {
346
+ rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);
347
+ }
348
+ }));
349
+ } else {
350
+ this.register(addDisposableDomListener(this.element!, 'contextmenu', (event: MouseEvent) => {
351
+ rightClickHandler(event, this.textarea!, this.screenElement!, this._selectionService!, this.options.rightClickSelectsWord);
352
+ }));
353
+ }
354
+
355
+ // Move the textarea under the cursor when middle clicking on Linux to ensure
356
+ // middle click to paste selection works. This only appears to work in Chrome
357
+ // at the time is writing.
358
+ if (Browser.isLinux) {
359
+ // Use auxclick event over mousedown the latter doesn't seem to work. Note
360
+ // that the regular click event doesn't fire for the middle mouse button.
361
+ this.register(addDisposableDomListener(this.element!, 'auxclick', (event: MouseEvent) => {
362
+ if (event.button === 1) {
363
+ moveTextAreaUnderMouseCursor(event, this.textarea!, this.screenElement!);
364
+ }
365
+ }));
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Apply key handling to the terminal
371
+ */
372
+ private _bindKeys(): void {
373
+ this.register(addDisposableDomListener(this.textarea!, 'keyup', (ev: KeyboardEvent) => this._keyUp(ev), true));
374
+ this.register(addDisposableDomListener(this.textarea!, 'keydown', (ev: KeyboardEvent) => this._keyDown(ev), true));
375
+ this.register(addDisposableDomListener(this.textarea!, 'keypress', (ev: KeyboardEvent) => this._keyPress(ev), true));
376
+ this.register(addDisposableDomListener(this.textarea!, 'compositionstart', () => this._compositionHelper!.compositionstart()));
377
+ this.register(addDisposableDomListener(this.textarea!, 'compositionupdate', (e: CompositionEvent) => this._compositionHelper!.compositionupdate(e)));
378
+ this.register(addDisposableDomListener(this.textarea!, 'compositionend', () => this._compositionHelper!.compositionend()));
379
+ this.register(addDisposableDomListener(this.textarea!, 'input', (ev: InputEvent) => this._inputEvent(ev), true));
380
+ this.register(this.onRender(() => this._compositionHelper!.updateCompositionElements()));
381
+ }
382
+
383
+ /**
384
+ * Opens the terminal within an element.
385
+ *
386
+ * @param parent The element to create the terminal within.
387
+ */
388
+ public open(parent: HTMLElement): void {
389
+ if (!parent) {
390
+ throw new Error('Terminal requires a parent element.');
391
+ }
392
+
393
+ if (!parent.isConnected) {
394
+ this._logService.debug('Terminal.open was called on an element that was not attached to the DOM');
395
+ }
396
+
397
+ // If the terminal is already opened
398
+ if (this.element?.ownerDocument.defaultView && this._coreBrowserService) {
399
+ // Adjust the window if needed
400
+ if (this.element.ownerDocument.defaultView !== this._coreBrowserService.window) {
401
+ this._coreBrowserService.window = this.element.ownerDocument.defaultView;
402
+ }
403
+ return;
404
+ }
405
+
406
+ this._document = parent.ownerDocument;
407
+ if (this.options.documentOverride && this.options.documentOverride instanceof Document) {
408
+ this._document = this.optionsService.rawOptions.documentOverride as Document;
409
+ }
410
+
411
+ // Create main element container
412
+ this.element = this._document.createElement('div');
413
+ this.element.dir = 'ltr'; // xterm.css assumes LTR
414
+ this.element.classList.add('terminal');
415
+ this.element.classList.add('xterm');
416
+ parent.appendChild(this.element);
417
+
418
+ // Performance: Use a document fragment to build the terminal
419
+ // viewport and helper elements detached from the DOM
420
+ const fragment = this._document.createDocumentFragment();
421
+ this._viewportElement = this._document.createElement('div');
422
+ this._viewportElement.classList.add('xterm-viewport');
423
+ fragment.appendChild(this._viewportElement);
424
+
425
+ this._viewportScrollArea = this._document.createElement('div');
426
+ this._viewportScrollArea.classList.add('xterm-scroll-area');
427
+ this._viewportElement.appendChild(this._viewportScrollArea);
428
+
429
+ this.screenElement = this._document.createElement('div');
430
+ this.screenElement.classList.add('xterm-screen');
431
+ // Create the container that will hold helpers like the textarea for
432
+ // capturing DOM Events. Then produce the helpers.
433
+ this._helperContainer = this._document.createElement('div');
434
+ this._helperContainer.classList.add('xterm-helpers');
435
+ this.screenElement.appendChild(this._helperContainer);
436
+ fragment.appendChild(this.screenElement);
437
+
438
+ this.textarea = this._document.createElement('textarea');
439
+ this.textarea.classList.add('xterm-helper-textarea');
440
+ this.textarea.setAttribute('aria-label', Strings.promptLabel);
441
+ if (!Browser.isChromeOS) {
442
+ // ChromeVox on ChromeOS does not like this. See
443
+ // https://issuetracker.google.com/issues/260170397
444
+ this.textarea.setAttribute('aria-multiline', 'false');
445
+ }
446
+ this.textarea.setAttribute('autocorrect', 'off');
447
+ this.textarea.setAttribute('autocapitalize', 'off');
448
+ this.textarea.setAttribute('spellcheck', 'false');
449
+ this.textarea.tabIndex = 0;
450
+
451
+ // Register the core browser service before the generic textarea handlers are registered so it
452
+ // handles them first. Otherwise the renderers may use the wrong focus state.
453
+ this._coreBrowserService = this.register(this._instantiationService.createInstance(CoreBrowserService,
454
+ this.textarea,
455
+ parent.ownerDocument.defaultView ?? window,
456
+ // Force unsafe null in node.js environment for tests
457
+ this._document ?? (typeof window !== 'undefined') ? window.document : null as any
458
+ ));
459
+ this._instantiationService.setService(ICoreBrowserService, this._coreBrowserService);
460
+
461
+ this.register(addDisposableDomListener(this.textarea, 'focus', (ev: KeyboardEvent) => this._handleTextAreaFocus(ev)));
462
+ this.register(addDisposableDomListener(this.textarea, 'blur', () => this._handleTextAreaBlur()));
463
+ this._helperContainer.appendChild(this.textarea);
464
+
465
+
466
+ this._charSizeService = this._instantiationService.createInstance(CharSizeService, this._document, this._helperContainer);
467
+ this._instantiationService.setService(ICharSizeService, this._charSizeService);
468
+
469
+ this._themeService = this._instantiationService.createInstance(ThemeService);
470
+ this._instantiationService.setService(IThemeService, this._themeService);
471
+
472
+ this._characterJoinerService = this._instantiationService.createInstance(CharacterJoinerService);
473
+ this._instantiationService.setService(ICharacterJoinerService, this._characterJoinerService);
474
+
475
+ this._renderService = this.register(this._instantiationService.createInstance(RenderService, this.rows, this.screenElement));
476
+ this._instantiationService.setService(IRenderService, this._renderService);
477
+ this.register(this._renderService.onRenderedViewportChange(e => this._onRender.fire(e)));
478
+ this.onResize(e => this._renderService!.resize(e.cols, e.rows));
479
+
480
+ this._compositionView = this._document.createElement('div');
481
+ this._compositionView.classList.add('composition-view');
482
+ this._compositionHelper = this._instantiationService.createInstance(CompositionHelper, this.textarea, this._compositionView);
483
+ this._helperContainer.appendChild(this._compositionView);
484
+
485
+ // Performance: Add viewport and helper elements from the fragment
486
+ this.element.appendChild(fragment);
487
+
488
+ try {
489
+ this._onWillOpen.fire(this.element);
490
+ }
491
+ catch { /* fails to load addon for some reason */ }
492
+ if (!this._renderService.hasRenderer()) {
493
+ this._renderService.setRenderer(this._createRenderer());
494
+ }
495
+
496
+ this._mouseService = this._instantiationService.createInstance(MouseService);
497
+ this._instantiationService.setService(IMouseService, this._mouseService);
498
+
499
+ this.viewport = this._instantiationService.createInstance(Viewport, this._viewportElement, this._viewportScrollArea);
500
+ this.viewport.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent, ScrollSource.VIEWPORT)),
501
+ this.register(this._inputHandler.onRequestSyncScrollBar(() => this.viewport!.syncScrollArea()));
502
+ this.register(this.viewport);
503
+
504
+ this.register(this.onCursorMove(() => {
505
+ this._renderService!.handleCursorMove();
506
+ this._syncTextArea();
507
+ }));
508
+ this.register(this.onResize(() => this._renderService!.handleResize(this.cols, this.rows)));
509
+ this.register(this.onBlur(() => this._renderService!.handleBlur()));
510
+ this.register(this.onFocus(() => this._renderService!.handleFocus()));
511
+ this.register(this._renderService.onDimensionsChange(() => this.viewport!.syncScrollArea()));
512
+
513
+ this._selectionService = this.register(this._instantiationService.createInstance(SelectionService,
514
+ this.element,
515
+ this.screenElement,
516
+ this.linkifier2
517
+ ));
518
+ this._instantiationService.setService(ISelectionService, this._selectionService);
519
+ this.register(this._selectionService.onRequestScrollLines(e => this.scrollLines(e.amount, e.suppressScrollEvent)));
520
+ this.register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire()));
521
+ this.register(this._selectionService.onRequestRedraw(e => this._renderService!.handleSelectionChanged(e.start, e.end, e.columnSelectMode)));
522
+ this.register(this._selectionService.onLinuxMouseSelection(text => {
523
+ // If there's a new selection, put it into the textarea, focus and select it
524
+ // in order to register it as a selection on the OS. This event is fired
525
+ // only on Linux to enable middle click to paste selection.
526
+ this.textarea!.value = text;
527
+ this.textarea!.focus();
528
+ this.textarea!.select();
529
+ }));
530
+ this.register(this._onScroll.event(ev => {
531
+ this.viewport!.syncScrollArea();
532
+ this._selectionService!.refresh();
533
+ }));
534
+ this.register(addDisposableDomListener(this._viewportElement, 'scroll', () => this._selectionService!.refresh()));
535
+
536
+ this.linkifier2.attachToDom(this.screenElement, this._mouseService, this._renderService);
537
+ this.register(this._instantiationService.createInstance(BufferDecorationRenderer, this.screenElement));
538
+ this.register(addDisposableDomListener(this.element, 'mousedown', (e: MouseEvent) => this._selectionService!.handleMouseDown(e)));
539
+
540
+ // apply mouse event classes set by escape codes before terminal was attached
541
+ if (this.coreMouseService.areMouseEventsActive) {
542
+ this._selectionService.disable();
543
+ this.element.classList.add('enable-mouse-events');
544
+ } else {
545
+ this._selectionService.enable();
546
+ }
547
+
548
+ if (this.options.screenReaderMode) {
549
+ // Note that this must be done *after* the renderer is created in order to
550
+ // ensure the correct order of the dprchange event
551
+ this._accessibilityManager.value = this._instantiationService.createInstance(AccessibilityManager, this);
552
+ }
553
+ this.register(this.optionsService.onSpecificOptionChange('screenReaderMode', e => this._handleScreenReaderModeOptionChange(e)));
554
+
555
+ if (this.options.overviewRulerWidth) {
556
+ this._overviewRulerRenderer = this.register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));
557
+ }
558
+ this.optionsService.onSpecificOptionChange('overviewRulerWidth', value => {
559
+ if (!this._overviewRulerRenderer && value && this._viewportElement && this.screenElement) {
560
+ this._overviewRulerRenderer = this.register(this._instantiationService.createInstance(OverviewRulerRenderer, this._viewportElement, this.screenElement));
561
+ }
562
+ });
563
+ // Measure the character size
564
+ this._charSizeService.measure();
565
+
566
+ // Setup loop that draws to screen
567
+ this.refresh(0, this.rows - 1);
568
+
569
+ // Initialize global actions that need to be taken on the document.
570
+ this._initGlobal();
571
+
572
+ // Listen for mouse events and translate
573
+ // them into terminal mouse protocols.
574
+ this.bindMouse();
575
+ }
576
+
577
+ private _createRenderer(): IRenderer {
578
+ return this._instantiationService.createInstance(DomRenderer, this._document!, this.element!, this.screenElement!, this._viewportElement!, this._helperContainer!, this.linkifier2);
579
+ }
580
+
581
+ /**
582
+ * Bind certain mouse events to the terminal.
583
+ * By default only 3 button + wheel up/down is ativated. For higher buttons
584
+ * no mouse report will be created. Typically the standard actions will be active.
585
+ *
586
+ * There are several reasons not to enable support for higher buttons/wheel:
587
+ * - Button 4 and 5 are typically used for history back and forward navigation,
588
+ * there is no straight forward way to supress/intercept those standard actions.
589
+ * - Support for higher buttons does not work in some platform/browser combinations.
590
+ * - Left/right wheel was not tested.
591
+ * - Emulators vary in mouse button support, typically only 3 buttons and
592
+ * wheel up/down work reliable.
593
+ *
594
+ * TODO: Move mouse event code into its own file.
595
+ */
596
+ public bindMouse(): void {
597
+ const self = this;
598
+ const el = this.element!;
599
+
600
+ // send event to CoreMouseService
601
+ function sendEvent(ev: MouseEvent | WheelEvent): boolean {
602
+ // get mouse coordinates
603
+ const pos = self._mouseService!.getMouseReportCoords(ev, self.screenElement!);
604
+ if (!pos) {
605
+ return false;
606
+ }
607
+
608
+ let but: CoreMouseButton;
609
+ let action: CoreMouseAction | undefined;
610
+ switch ((ev as any).overrideType || ev.type) {
611
+ case 'mousemove':
612
+ action = CoreMouseAction.MOVE;
613
+ if (ev.buttons === undefined) {
614
+ // buttons is not supported on macOS, try to get a value from button instead
615
+ but = CoreMouseButton.NONE;
616
+ if (ev.button !== undefined) {
617
+ but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
618
+ }
619
+ } else {
620
+ // according to MDN buttons only reports up to button 5 (AUX2)
621
+ but = ev.buttons & 1 ? CoreMouseButton.LEFT :
622
+ ev.buttons & 4 ? CoreMouseButton.MIDDLE :
623
+ ev.buttons & 2 ? CoreMouseButton.RIGHT :
624
+ CoreMouseButton.NONE; // fallback to NONE
625
+ }
626
+ break;
627
+ case 'mouseup':
628
+ action = CoreMouseAction.UP;
629
+ but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
630
+ break;
631
+ case 'mousedown':
632
+ action = CoreMouseAction.DOWN;
633
+ but = ev.button < 3 ? ev.button : CoreMouseButton.NONE;
634
+ break;
635
+ case 'wheel':
636
+ const amount = self.viewport!.getLinesScrolled(ev as WheelEvent);
637
+
638
+ if (amount === 0) {
639
+ return false;
640
+ }
641
+
642
+ action = (ev as WheelEvent).deltaY < 0 ? CoreMouseAction.UP : CoreMouseAction.DOWN;
643
+ but = CoreMouseButton.WHEEL;
644
+ break;
645
+ default:
646
+ // dont handle other event types by accident
647
+ return false;
648
+ }
649
+
650
+ // exit if we cannot determine valid button/action values
651
+ // do nothing for higher buttons than wheel
652
+ if (action === undefined || but === undefined || but > CoreMouseButton.WHEEL) {
653
+ return false;
654
+ }
655
+
656
+ return self.coreMouseService.triggerMouseEvent({
657
+ col: pos.col,
658
+ row: pos.row,
659
+ x: pos.x,
660
+ y: pos.y,
661
+ button: but,
662
+ action,
663
+ ctrl: ev.ctrlKey,
664
+ alt: ev.altKey,
665
+ shift: ev.shiftKey
666
+ });
667
+ }
668
+
669
+ /**
670
+ * Event listener state handling.
671
+ * We listen to the onProtocolChange event of CoreMouseService and put
672
+ * requested listeners in `requestedEvents`. With this the listeners
673
+ * have all bits to do the event listener juggling.
674
+ * Note: 'mousedown' currently is "always on" and not managed
675
+ * by onProtocolChange.
676
+ */
677
+ const requestedEvents: { [key: string]: ((ev: Event) => void) | null } = {
678
+ mouseup: null,
679
+ wheel: null,
680
+ mousedrag: null,
681
+ mousemove: null
682
+ };
683
+ const eventListeners: { [key: string]: (ev: any) => void | boolean } = {
684
+ mouseup: (ev: MouseEvent) => {
685
+ sendEvent(ev);
686
+ if (!ev.buttons) {
687
+ // if no other button is held remove global handlers
688
+ this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);
689
+ if (requestedEvents.mousedrag) {
690
+ this._document!.removeEventListener('mousemove', requestedEvents.mousedrag);
691
+ }
692
+ }
693
+ return this.cancel(ev);
694
+ },
695
+ wheel: (ev: WheelEvent) => {
696
+ sendEvent(ev);
697
+ return this.cancel(ev, true);
698
+ },
699
+ mousedrag: (ev: MouseEvent) => {
700
+ // deal only with move while a button is held
701
+ if (ev.buttons) {
702
+ sendEvent(ev);
703
+ }
704
+ },
705
+ mousemove: (ev: MouseEvent) => {
706
+ // deal only with move without any button
707
+ if (!ev.buttons) {
708
+ sendEvent(ev);
709
+ }
710
+ }
711
+ };
712
+ this.register(this.coreMouseService.onProtocolChange(events => {
713
+ // apply global changes on events
714
+ if (events) {
715
+ if (this.optionsService.rawOptions.logLevel === 'debug') {
716
+ this._logService.debug('Binding to mouse events:', this.coreMouseService.explainEvents(events));
717
+ }
718
+ this.element!.classList.add('enable-mouse-events');
719
+ this._selectionService!.disable();
720
+ } else {
721
+ this._logService.debug('Unbinding from mouse events.');
722
+ this.element!.classList.remove('enable-mouse-events');
723
+ this._selectionService!.enable();
724
+ }
725
+
726
+ // add/remove handlers from requestedEvents
727
+
728
+ if (!(events & CoreMouseEventType.MOVE)) {
729
+ el.removeEventListener('mousemove', requestedEvents.mousemove!);
730
+ requestedEvents.mousemove = null;
731
+ } else if (!requestedEvents.mousemove) {
732
+ el.addEventListener('mousemove', eventListeners.mousemove);
733
+ requestedEvents.mousemove = eventListeners.mousemove;
734
+ }
735
+
736
+ if (!(events & CoreMouseEventType.WHEEL)) {
737
+ el.removeEventListener('wheel', requestedEvents.wheel!);
738
+ requestedEvents.wheel = null;
739
+ } else if (!requestedEvents.wheel) {
740
+ el.addEventListener('wheel', eventListeners.wheel, { passive: false });
741
+ requestedEvents.wheel = eventListeners.wheel;
742
+ }
743
+
744
+ if (!(events & CoreMouseEventType.UP)) {
745
+ this._document!.removeEventListener('mouseup', requestedEvents.mouseup!);
746
+ requestedEvents.mouseup = null;
747
+ } else if (!requestedEvents.mouseup) {
748
+ requestedEvents.mouseup = eventListeners.mouseup;
749
+ }
750
+
751
+ if (!(events & CoreMouseEventType.DRAG)) {
752
+ this._document!.removeEventListener('mousemove', requestedEvents.mousedrag!);
753
+ requestedEvents.mousedrag = null;
754
+ } else if (!requestedEvents.mousedrag) {
755
+ requestedEvents.mousedrag = eventListeners.mousedrag;
756
+ }
757
+ }));
758
+ // force initial onProtocolChange so we dont miss early mouse requests
759
+ this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol;
760
+
761
+ /**
762
+ * "Always on" event listeners.
763
+ */
764
+ this.register(addDisposableDomListener(el, 'mousedown', (ev: MouseEvent) => {
765
+ ev.preventDefault();
766
+ this.focus();
767
+
768
+ // Don't send the mouse button to the pty if mouse events are disabled or
769
+ // if the selection manager is having selection forced (ie. a modifier is
770
+ // held).
771
+ if (!this.coreMouseService.areMouseEventsActive || this._selectionService!.shouldForceSelection(ev)) {
772
+ return;
773
+ }
774
+
775
+ sendEvent(ev);
776
+
777
+ // Register additional global handlers which should keep reporting outside
778
+ // of the terminal element.
779
+ // Note: Other emulators also do this for 'mousedown' while a button
780
+ // is held, we currently limit 'mousedown' to the terminal only.
781
+ if (requestedEvents.mouseup) {
782
+ this._document!.addEventListener('mouseup', requestedEvents.mouseup);
783
+ }
784
+ if (requestedEvents.mousedrag) {
785
+ this._document!.addEventListener('mousemove', requestedEvents.mousedrag);
786
+ }
787
+
788
+ return this.cancel(ev);
789
+ }));
790
+
791
+ this.register(addDisposableDomListener(el, 'wheel', (ev: WheelEvent) => {
792
+ // do nothing, if app side handles wheel itself
793
+ if (requestedEvents.wheel) return;
794
+
795
+ if (!this.buffer.hasScrollback) {
796
+ // Convert wheel events into up/down events when the buffer does not have scrollback, this
797
+ // enables scrolling in apps hosted in the alt buffer such as vim or tmux.
798
+ const amount = this.viewport!.getLinesScrolled(ev);
799
+
800
+ // Do nothing if there's no vertical scroll
801
+ if (amount === 0) {
802
+ return;
803
+ }
804
+
805
+ // Construct and send sequences
806
+ const sequence = C0.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? 'O' : '[') + (ev.deltaY < 0 ? 'A' : 'B');
807
+ let data = '';
808
+ for (let i = 0; i < Math.abs(amount); i++) {
809
+ data += sequence;
810
+ }
811
+ this.coreService.triggerDataEvent(data, true);
812
+ return this.cancel(ev, true);
813
+ }
814
+
815
+ // normal viewport scrolling
816
+ // conditionally stop event, if the viewport still had rows to scroll within
817
+ if (this.viewport!.handleWheel(ev)) {
818
+ return this.cancel(ev);
819
+ }
820
+ }, { passive: false }));
821
+
822
+ this.register(addDisposableDomListener(el, 'touchstart', (ev: TouchEvent) => {
823
+ if (this.coreMouseService.areMouseEventsActive) return;
824
+ this.viewport!.handleTouchStart(ev);
825
+ return this.cancel(ev);
826
+ }, { passive: true }));
827
+
828
+ this.register(addDisposableDomListener(el, 'touchmove', (ev: TouchEvent) => {
829
+ if (this.coreMouseService.areMouseEventsActive) return;
830
+ if (!this.viewport!.handleTouchMove(ev)) {
831
+ return this.cancel(ev);
832
+ }
833
+ }, { passive: false }));
834
+ }
835
+
836
+
837
+ /**
838
+ * Tells the renderer to refresh terminal content between two rows (inclusive) at the next
839
+ * opportunity.
840
+ * @param start The row to start from (between 0 and this.rows - 1).
841
+ * @param end The row to end at (between start and this.rows - 1).
842
+ */
843
+ public refresh(start: number, end: number): void {
844
+ this._renderService?.refreshRows(start, end);
845
+ }
846
+
847
+ /**
848
+ * Change the cursor style for different selection modes
849
+ */
850
+ public updateCursorStyle(ev: KeyboardEvent): void {
851
+ if (this._selectionService?.shouldColumnSelect(ev)) {
852
+ this.element!.classList.add('column-select');
853
+ } else {
854
+ this.element!.classList.remove('column-select');
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Display the cursor element
860
+ */
861
+ private _showCursor(): void {
862
+ if (!this.coreService.isCursorInitialized) {
863
+ this.coreService.isCursorInitialized = true;
864
+ this.refresh(this.buffer.y, this.buffer.y);
865
+ }
866
+ }
867
+
868
+ public scrollLines(disp: number, suppressScrollEvent?: boolean, source = ScrollSource.TERMINAL): void {
869
+ if (source === ScrollSource.VIEWPORT) {
870
+ super.scrollLines(disp, suppressScrollEvent, source);
871
+ this.refresh(0, this.rows - 1);
872
+ } else {
873
+ this.viewport?.scrollLines(disp);
874
+ }
875
+ }
876
+
877
+ public paste(data: string): void {
878
+ paste(data, this.textarea!, this.coreService, this.optionsService);
879
+ }
880
+
881
+ /**
882
+ * Attaches a custom key event handler which is run before keys are processed,
883
+ * giving consumers of xterm.js ultimate control as to what keys should be
884
+ * processed by the terminal and what keys should not.
885
+ * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
886
+ * This is a function that takes a KeyboardEvent, allowing consumers to stop
887
+ * propagation and/or prevent the default action. The function returns whether
888
+ * the event should be processed by xterm.js.
889
+ */
890
+ public attachCustomKeyEventHandler(customKeyEventHandler: CustomKeyEventHandler): void {
891
+ this._customKeyEventHandler = customKeyEventHandler;
892
+ }
893
+
894
+ public registerLinkProvider(linkProvider: ILinkProvider): IDisposable {
895
+ return this.linkifier2.registerLinkProvider(linkProvider);
896
+ }
897
+
898
+ public registerCharacterJoiner(handler: CharacterJoinerHandler): number {
899
+ if (!this._characterJoinerService) {
900
+ throw new Error('Terminal must be opened first');
901
+ }
902
+ const joinerId = this._characterJoinerService.register(handler);
903
+ this.refresh(0, this.rows - 1);
904
+ return joinerId;
905
+ }
906
+
907
+ public deregisterCharacterJoiner(joinerId: number): void {
908
+ if (!this._characterJoinerService) {
909
+ throw new Error('Terminal must be opened first');
910
+ }
911
+ if (this._characterJoinerService.deregister(joinerId)) {
912
+ this.refresh(0, this.rows - 1);
913
+ }
914
+ }
915
+
916
+ public get markers(): IMarker[] {
917
+ return this.buffer.markers;
918
+ }
919
+
920
+ public registerMarker(cursorYOffset: number): IMarker {
921
+ return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + cursorYOffset);
922
+ }
923
+
924
+ public registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined {
925
+ return this._decorationService.registerDecoration(decorationOptions);
926
+ }
927
+
928
+ /**
929
+ * Gets whether the terminal has an active selection.
930
+ */
931
+ public hasSelection(): boolean {
932
+ return this._selectionService ? this._selectionService.hasSelection : false;
933
+ }
934
+
935
+ /**
936
+ * Selects text within the terminal.
937
+ * @param column The column the selection starts at..
938
+ * @param row The row the selection starts at.
939
+ * @param length The length of the selection.
940
+ */
941
+ public select(column: number, row: number, length: number): void {
942
+ this._selectionService!.setSelection(column, row, length);
943
+ }
944
+
945
+ /**
946
+ * Gets the terminal's current selection, this is useful for implementing copy
947
+ * behavior outside of xterm.js.
948
+ */
949
+ public getSelection(): string {
950
+ return this._selectionService ? this._selectionService.selectionText : '';
951
+ }
952
+
953
+ public getSelectionPosition(): IBufferRange | undefined {
954
+ if (!this._selectionService || !this._selectionService.hasSelection) {
955
+ return undefined;
956
+ }
957
+
958
+ return {
959
+ start: {
960
+ x: this._selectionService.selectionStart![0],
961
+ y: this._selectionService.selectionStart![1]
962
+ },
963
+ end: {
964
+ x: this._selectionService.selectionEnd![0],
965
+ y: this._selectionService.selectionEnd![1]
966
+ }
967
+ };
968
+ }
969
+
970
+ /**
971
+ * Clears the current terminal selection.
972
+ */
973
+ public clearSelection(): void {
974
+ this._selectionService?.clearSelection();
975
+ }
976
+
977
+ /**
978
+ * Selects all text within the terminal.
979
+ */
980
+ public selectAll(): void {
981
+ this._selectionService?.selectAll();
982
+ }
983
+
984
+ public selectLines(start: number, end: number): void {
985
+ this._selectionService?.selectLines(start, end);
986
+ }
987
+
988
+ /**
989
+ * Handle a keydown [KeyboardEvent].
990
+ *
991
+ * [KeyboardEvent]: https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
992
+ */
993
+ protected _keyDown(event: KeyboardEvent): boolean | undefined {
994
+ this._keyDownHandled = false;
995
+ this._keyDownSeen = true;
996
+
997
+ if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {
998
+ return false;
999
+ }
1000
+
1001
+ // Ignore composing with Alt key on Mac when macOptionIsMeta is enabled
1002
+ const shouldIgnoreComposition = this.browser.isMac && this.options.macOptionIsMeta && event.altKey;
1003
+
1004
+ if (!shouldIgnoreComposition && !this._compositionHelper!.keydown(event)) {
1005
+ if (this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp) {
1006
+ this.scrollToBottom();
1007
+ }
1008
+ return false;
1009
+ }
1010
+
1011
+ if (!shouldIgnoreComposition && (event.key === 'Dead' || event.key === 'AltGraph')) {
1012
+ this._unprocessedDeadKey = true;
1013
+ }
1014
+
1015
+ const result = evaluateKeyboardEvent(event, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta);
1016
+
1017
+ this.updateCursorStyle(event);
1018
+
1019
+ if (result.type === KeyboardResultType.PAGE_DOWN || result.type === KeyboardResultType.PAGE_UP) {
1020
+ const scrollCount = this.rows - 1;
1021
+ this.scrollLines(result.type === KeyboardResultType.PAGE_UP ? -scrollCount : scrollCount);
1022
+ return this.cancel(event, true);
1023
+ }
1024
+
1025
+ if (result.type === KeyboardResultType.SELECT_ALL) {
1026
+ this.selectAll();
1027
+ }
1028
+
1029
+ if (this._isThirdLevelShift(this.browser, event)) {
1030
+ return true;
1031
+ }
1032
+
1033
+ if (result.cancel) {
1034
+ // The event is canceled at the end already, is this necessary?
1035
+ this.cancel(event, true);
1036
+ }
1037
+
1038
+ if (!result.key) {
1039
+ return true;
1040
+ }
1041
+
1042
+ // HACK: Process A-Z in the keypress event to fix an issue with macOS IMEs where lower case
1043
+ // letters cannot be input while caps lock is on.
1044
+ if (event.key && !event.ctrlKey && !event.altKey && !event.metaKey && event.key.length === 1) {
1045
+ if (event.key.charCodeAt(0) >= 65 && event.key.charCodeAt(0) <= 90) {
1046
+ return true;
1047
+ }
1048
+ }
1049
+
1050
+ if (this._unprocessedDeadKey) {
1051
+ this._unprocessedDeadKey = false;
1052
+ return true;
1053
+ }
1054
+
1055
+ // If ctrl+c or enter is being sent, clear out the textarea. This is done so that screen readers
1056
+ // will announce deleted characters. This will not work 100% of the time but it should cover
1057
+ // most scenarios.
1058
+ if (result.key === C0.ETX || result.key === C0.CR) {
1059
+ this.textarea!.value = '';
1060
+ }
1061
+
1062
+ this._onKey.fire({ key: result.key, domEvent: event });
1063
+ this._showCursor();
1064
+ this.coreService.triggerDataEvent(result.key, true);
1065
+
1066
+ // Cancel events when not in screen reader mode so events don't get bubbled up and handled by
1067
+ // other listeners. When screen reader mode is enabled, we don't cancel them (unless ctrl or alt
1068
+ // is also depressed) so that the cursor textarea can be updated, which triggers the screen
1069
+ // reader to read it.
1070
+ if (!this.optionsService.rawOptions.screenReaderMode || event.altKey || event.ctrlKey) {
1071
+ return this.cancel(event, true);
1072
+ }
1073
+
1074
+ this._keyDownHandled = true;
1075
+ }
1076
+
1077
+ private _isThirdLevelShift(browser: IBrowser, ev: KeyboardEvent): boolean {
1078
+ const thirdLevelKey =
1079
+ (browser.isMac && !this.options.macOptionIsMeta && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
1080
+ (browser.isWindows && ev.altKey && ev.ctrlKey && !ev.metaKey) ||
1081
+ (browser.isWindows && ev.getModifierState('AltGraph'));
1082
+
1083
+ if (ev.type === 'keypress') {
1084
+ return thirdLevelKey;
1085
+ }
1086
+
1087
+ // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
1088
+ return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
1089
+ }
1090
+
1091
+ protected _keyUp(ev: KeyboardEvent): void {
1092
+ this._keyDownSeen = false;
1093
+
1094
+ if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
1095
+ return;
1096
+ }
1097
+
1098
+ if (!wasModifierKeyOnlyEvent(ev)) {
1099
+ this.focus();
1100
+ }
1101
+
1102
+ this.updateCursorStyle(ev);
1103
+ this._keyPressHandled = false;
1104
+ }
1105
+
1106
+ /**
1107
+ * Handle a keypress event.
1108
+ * Key Resources:
1109
+ * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
1110
+ * @param ev The keypress event to be handled.
1111
+ */
1112
+ protected _keyPress(ev: KeyboardEvent): boolean {
1113
+ let key;
1114
+
1115
+ this._keyPressHandled = false;
1116
+
1117
+ if (this._keyDownHandled) {
1118
+ return false;
1119
+ }
1120
+
1121
+ if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
1122
+ return false;
1123
+ }
1124
+
1125
+ this.cancel(ev);
1126
+
1127
+ if (ev.charCode) {
1128
+ key = ev.charCode;
1129
+ } else if (ev.which === null || ev.which === undefined) {
1130
+ key = ev.keyCode;
1131
+ } else if (ev.which !== 0 && ev.charCode !== 0) {
1132
+ key = ev.which;
1133
+ } else {
1134
+ return false;
1135
+ }
1136
+
1137
+ if (!key || (
1138
+ (ev.altKey || ev.ctrlKey || ev.metaKey) && !this._isThirdLevelShift(this.browser, ev)
1139
+ )) {
1140
+ return false;
1141
+ }
1142
+
1143
+ key = String.fromCharCode(key);
1144
+
1145
+ this._onKey.fire({ key, domEvent: ev });
1146
+ this._showCursor();
1147
+ this.coreService.triggerDataEvent(key, true);
1148
+
1149
+ this._keyPressHandled = true;
1150
+
1151
+ // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow
1152
+ // keys could be ignored
1153
+ this._unprocessedDeadKey = false;
1154
+
1155
+ return true;
1156
+ }
1157
+
1158
+ /**
1159
+ * Handle an input event.
1160
+ * Key Resources:
1161
+ * - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent
1162
+ * @param ev The input event to be handled.
1163
+ */
1164
+ protected _inputEvent(ev: InputEvent): boolean {
1165
+ // Only support emoji IMEs when screen reader mode is disabled as the event must bubble up to
1166
+ // support reading out character input which can doubling up input characters
1167
+ // Based on these event traces: https://github.com/xtermjs/xterm.js/issues/3679
1168
+ if (ev.data && ev.inputType === 'insertText' && (!ev.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) {
1169
+ if (this._keyPressHandled) {
1170
+ return false;
1171
+ }
1172
+
1173
+ // The key was handled so clear the dead key state, otherwise certain keystrokes like arrow
1174
+ // keys could be ignored
1175
+ this._unprocessedDeadKey = false;
1176
+
1177
+ const text = ev.data;
1178
+ this.coreService.triggerDataEvent(text, true);
1179
+
1180
+ this.cancel(ev);
1181
+ return true;
1182
+ }
1183
+
1184
+ return false;
1185
+ }
1186
+
1187
+ /**
1188
+ * Resizes the terminal.
1189
+ *
1190
+ * @param x The number of columns to resize to.
1191
+ * @param y The number of rows to resize to.
1192
+ */
1193
+ public resize(x: number, y: number): void {
1194
+ if (x === this.cols && y === this.rows) {
1195
+ // Check if we still need to measure the char size (fixes #785).
1196
+ if (this._charSizeService && !this._charSizeService.hasValidSize) {
1197
+ this._charSizeService.measure();
1198
+ }
1199
+ return;
1200
+ }
1201
+
1202
+ super.resize(x, y);
1203
+ }
1204
+
1205
+ private _afterResize(x: number, y: number): void {
1206
+ this._charSizeService?.measure();
1207
+
1208
+ // Sync the scroll area to make sure scroll events don't fire and scroll the viewport to an
1209
+ // invalid location
1210
+ this.viewport?.syncScrollArea(true);
1211
+ }
1212
+
1213
+ /**
1214
+ * Clear the entire buffer, making the prompt line the new first line.
1215
+ */
1216
+ public clear(): void {
1217
+ if (this.buffer.ybase === 0 && this.buffer.y === 0) {
1218
+ // Don't clear if it's already clear
1219
+ return;
1220
+ }
1221
+ this.buffer.clearAllMarkers();
1222
+ this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)!);
1223
+ this.buffer.lines.length = 1;
1224
+ this.buffer.ydisp = 0;
1225
+ this.buffer.ybase = 0;
1226
+ this.buffer.y = 0;
1227
+ for (let i = 1; i < this.rows; i++) {
1228
+ this.buffer.lines.push(this.buffer.getBlankLine(DEFAULT_ATTR_DATA));
1229
+ }
1230
+ // IMPORTANT: Fire scroll event before viewport is reset. This ensures embedders get the clear
1231
+ // scroll event and that the viewport's state will be valid for immediate writes.
1232
+ this._onScroll.fire({ position: this.buffer.ydisp, source: ScrollSource.TERMINAL });
1233
+ this.viewport?.reset();
1234
+ this.refresh(0, this.rows - 1);
1235
+ }
1236
+
1237
+ /**
1238
+ * Reset terminal.
1239
+ * Note: Calling this directly from JS is synchronous but does not clear
1240
+ * input buffers and does not reset the parser, thus the terminal will
1241
+ * continue to apply pending input data.
1242
+ * If you need in band reset (synchronous with input data) consider
1243
+ * using DECSTR (soft reset, CSI ! p) or RIS instead (hard reset, ESC c).
1244
+ */
1245
+ public reset(): void {
1246
+ /**
1247
+ * Since _setup handles a full terminal creation, we have to carry forward
1248
+ * a few things that should not reset.
1249
+ */
1250
+ this.options.rows = this.rows;
1251
+ this.options.cols = this.cols;
1252
+ const customKeyEventHandler = this._customKeyEventHandler;
1253
+
1254
+ this._setup();
1255
+ super.reset();
1256
+ this._selectionService?.reset();
1257
+ this._decorationService.reset();
1258
+ this.viewport?.reset();
1259
+
1260
+ // reattach
1261
+ this._customKeyEventHandler = customKeyEventHandler;
1262
+
1263
+ // do a full screen refresh
1264
+ this.refresh(0, this.rows - 1);
1265
+ }
1266
+
1267
+ public clearTextureAtlas(): void {
1268
+ this._renderService?.clearTextureAtlas();
1269
+ }
1270
+
1271
+ private _reportFocus(): void {
1272
+ if (this.element?.classList.contains('focus')) {
1273
+ this.coreService.triggerDataEvent(C0.ESC + '[I');
1274
+ } else {
1275
+ this.coreService.triggerDataEvent(C0.ESC + '[O');
1276
+ }
1277
+ }
1278
+
1279
+ private _reportWindowsOptions(type: WindowsOptionsReportType): void {
1280
+ if (!this._renderService) {
1281
+ return;
1282
+ }
1283
+
1284
+ switch (type) {
1285
+ case WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:
1286
+ const canvasWidth = this._renderService.dimensions.css.canvas.width.toFixed(0);
1287
+ const canvasHeight = this._renderService.dimensions.css.canvas.height.toFixed(0);
1288
+ this.coreService.triggerDataEvent(`${C0.ESC}[4;${canvasHeight};${canvasWidth}t`);
1289
+ break;
1290
+ case WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:
1291
+ const cellWidth = this._renderService.dimensions.css.cell.width.toFixed(0);
1292
+ const cellHeight = this._renderService.dimensions.css.cell.height.toFixed(0);
1293
+ this.coreService.triggerDataEvent(`${C0.ESC}[6;${cellHeight};${cellWidth}t`);
1294
+ break;
1295
+ }
1296
+ }
1297
+
1298
+ // TODO: Remove cancel function and cancelEvents option
1299
+ public cancel(ev: Event, force?: boolean): boolean | undefined {
1300
+ if (!this.options.cancelEvents && !force) {
1301
+ return;
1302
+ }
1303
+ ev.preventDefault();
1304
+ ev.stopPropagation();
1305
+ return false;
1306
+ }
1307
+ }
1308
+
1309
+ /**
1310
+ * Helpers
1311
+ */
1312
+
1313
+ function wasModifierKeyOnlyEvent(ev: KeyboardEvent): boolean {
1314
+ return ev.keyCode === 16 || // Shift
1315
+ ev.keyCode === 17 || // Ctrl
1316
+ ev.keyCode === 18; // Alt
1317
+ }