Debian Codegraph @

node/@xterm/xterm/src/browser/CoreBrowserTerminal.ts

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