@wendongfly/zihi 1.0.0

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