Debian Codegraph @

node/@xterm/xterm/src/browser/services/SelectionService.ts

raw
1 /**
2 * Copyright (c) 2017 The xterm.js authors. All rights reserved.
3 * @license MIT
4 */
5
6 import { IBufferRange, ILinkifier2 } from 'browser/Types';
7 import { getCoordsRelativeToElement } from 'browser/input/Mouse';
8 import { moveToCellSequence } from 'browser/input/MoveToCell';
9 import { SelectionModel } from 'browser/selection/SelectionModel';
10 import { ISelectionRedrawRequestEvent, ISelectionRequestScrollLinesEvent } from 'browser/selection/Types';
11 import { ICoreBrowserService, IMouseService, IRenderService, ISelectionService } from 'browser/services/Services';
12 import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
13 import * as Browser from 'common/Platform';
14 import { IBufferLine, IDisposable } from 'common/Types';
15 import { getRangeLength } from 'common/buffer/BufferRange';
16 import { CellData } from 'common/buffer/CellData';
17 import { IBuffer } from 'common/buffer/Types';
18 import { IBufferService, ICoreService, IOptionsService } from 'common/services/Services';
19 import { Emitter } from 'vs/base/common/event';
20
21 /**
22 * The number of pixels the mouse needs to be above or below the viewport in
23 * order to scroll at the maximum speed.
24 */
25 const DRAG_SCROLL_MAX_THRESHOLD = 50;
26
27 /**
28 * The maximum scrolling speed
29 */
30 const DRAG_SCROLL_MAX_SPEED = 15;
31
32 /**
33 * The number of milliseconds between drag scroll updates.
34 */
35 const DRAG_SCROLL_INTERVAL = 50;
36
37 /**
38 * The maximum amount of time that can have elapsed for an alt click to move the
39 * cursor.
40 */
41 const ALT_CLICK_MOVE_CURSOR_TIME = 500;
42
43 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
44 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
45
46 /**
47 * Represents a position of a word on a line.
48 */
49 interface IWordPosition {
50 start: number;
51 length: number;
52 }
53
54 /**
55 * A selection mode, this drives how the selection behaves on mouse move.
56 */
57 export const enum SelectionMode {
58 NORMAL,
59 WORD,
60 LINE,
61 COLUMN
62 }
63
64 /**
65 * A class that manages the selection of the terminal. With help from
66 * SelectionModel, SelectionService handles with all logic associated with
67 * dealing with the selection, including handling mouse interaction, wide
68 * characters and fetching the actual text within the selection. Rendering is
69 * not handled by the SelectionService but the onRedrawRequest event is fired
70 * when the selection is ready to be redrawn (on an animation frame).
71 */
72 export class SelectionService extends Disposable implements ISelectionService {
73 public serviceBrand: undefined;
74
75 protected _model: SelectionModel;
76
77 /**
78 * The amount to scroll every drag scroll update (depends on how far the mouse
79 * drag is above or below the terminal).
80 */
81 private _dragScrollAmount: number = 0;
82
83 /**
84 * The current selection mode.
85 */
86 protected _activeSelectionMode: SelectionMode;
87
88 /**
89 * A setInterval timer that is active while the mouse is down whose callback
90 * scrolls the viewport when necessary.
91 */
92 private _dragScrollIntervalTimer: number | undefined;
93
94 /**
95 * The animation frame ID used for refreshing the selection.
96 */
97 private _refreshAnimationFrame: number | undefined;
98
99 /**
100 * Whether selection is enabled.
101 */
102 private _enabled = true;
103
104 private _mouseMoveListener: EventListener;
105 private _mouseUpListener: EventListener;
106 private _trimListener: IDisposable;
107 private _workCell: CellData = new CellData();
108
109 private _mouseDownTimeStamp: number = 0;
110 private _oldHasSelection: boolean = false;
111 private _oldSelectionStart: [number, number] | undefined = undefined;
112 private _oldSelectionEnd: [number, number] | undefined = undefined;
113
114 private readonly _onLinuxMouseSelection = this._register(new Emitter<string>());
115 public readonly onLinuxMouseSelection = this._onLinuxMouseSelection.event;
116 private readonly _onRedrawRequest = this._register(new Emitter<ISelectionRedrawRequestEvent>());
117 public readonly onRequestRedraw = this._onRedrawRequest.event;
118 private readonly _onSelectionChange = this._register(new Emitter<void>());
119 public readonly onSelectionChange = this._onSelectionChange.event;
120 private readonly _onRequestScrollLines = this._register(new Emitter<ISelectionRequestScrollLinesEvent>());
121 public readonly onRequestScrollLines = this._onRequestScrollLines.event;
122
123 constructor(
124 private readonly _element: HTMLElement,
125 private readonly _screenElement: HTMLElement,
126 private readonly _linkifier: ILinkifier2,
127 @IBufferService private readonly _bufferService: IBufferService,
128 @ICoreService private readonly _coreService: ICoreService,
129 @IMouseService private readonly _mouseService: IMouseService,
130 @IOptionsService private readonly _optionsService: IOptionsService,
131 @IRenderService private readonly _renderService: IRenderService,
132 @ICoreBrowserService private readonly _coreBrowserService: ICoreBrowserService
133 ) {
134 super();
135
136 // Init listeners
137 this._mouseMoveListener = event => this._handleMouseMove(event as MouseEvent);
138 this._mouseUpListener = event => this._handleMouseUp(event as MouseEvent);
139 this._coreService.onUserInput(() => {
140 if (this.hasSelection) {
141 this.clearSelection();
142 }
143 });
144 this._trimListener = this._bufferService.buffer.lines.onTrim(amount => this._handleTrim(amount));
145 this._register(this._bufferService.buffers.onBufferActivate(e => this._handleBufferActivate(e)));
146
147 this.enable();
148
149 this._model = new SelectionModel(this._bufferService);
150 this._activeSelectionMode = SelectionMode.NORMAL;
151
152 this._register(toDisposable(() => {
153 this._removeMouseDownListeners();
154 }));
155
156 // Clear selection when resizing vertically. This experience could be improved, this is the
157 // simple option to fix the buggy behavior. https://github.com/xtermjs/xterm.js/issues/5300
158 this._register(this._bufferService.onResize(e => {
159 if (e.rowsChanged) {
160 this.clearSelection();
161 }
162 }));
163 }
164
165 public reset(): void {
166 this.clearSelection();
167 }
168
169 /**
170 * Disables the selection manager. This is useful for when terminal mouse
171 * are enabled.
172 */
173 public disable(): void {
174 this.clearSelection();
175 this._enabled = false;
176 }
177
178 /**
179 * Enable the selection manager.
180 */
181 public enable(): void {
182 this._enabled = true;
183 }
184
185 public get selectionStart(): [number, number] | undefined { return this._model.finalSelectionStart; }
186 public get selectionEnd(): [number, number] | undefined { return this._model.finalSelectionEnd; }
187
188 /**
189 * Gets whether there is an active text selection.
190 */
191 public get hasSelection(): boolean {
192 const start = this._model.finalSelectionStart;
193 const end = this._model.finalSelectionEnd;
194 if (!start || !end) {
195 return false;
196 }
197 return start[0] !== end[0] || start[1] !== end[1];
198 }
199
200 /**
201 * Gets the text currently selected.
202 */
203 public get selectionText(): string {
204 const start = this._model.finalSelectionStart;
205 const end = this._model.finalSelectionEnd;
206 if (!start || !end) {
207 return '';
208 }
209
210 const buffer = this._bufferService.buffer;
211 const result: string[] = [];
212
213 if (this._activeSelectionMode === SelectionMode.COLUMN) {
214 // Ignore zero width selections
215 if (start[0] === end[0]) {
216 return '';
217 }
218
219 // For column selection it's not enough to rely on final selection's swapping of reversed
220 // values, it also needs the x coordinates to swap independently of the y coordinate is needed
221 const startCol = start[0] < end[0] ? start[0] : end[0];
222 const endCol = start[0] < end[0] ? end[0] : start[0];
223 for (let i = start[1]; i <= end[1]; i++) {
224 const lineText = buffer.translateBufferLineToString(i, true, startCol, endCol);
225 result.push(lineText);
226 }
227 } else {
228 // Get first row
229 const startRowEndCol = start[1] === end[1] ? end[0] : undefined;
230 result.push(buffer.translateBufferLineToString(start[1], true, start[0], startRowEndCol));
231
232 // Get middle rows
233 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
234 const bufferLine = buffer.lines.get(i);
235 const lineText = buffer.translateBufferLineToString(i, true);
236 if (bufferLine?.isWrapped) {
237 result[result.length - 1] += lineText;
238 } else {
239 result.push(lineText);
240 }
241 }
242
243 // Get final row
244 if (start[1] !== end[1]) {
245 const bufferLine = buffer.lines.get(end[1]);
246 const lineText = buffer.translateBufferLineToString(end[1], true, 0, end[0]);
247 if (bufferLine && bufferLine!.isWrapped) {
248 result[result.length - 1] += lineText;
249 } else {
250 result.push(lineText);
251 }
252 }
253 }
254
255 // Format string by replacing non-breaking space chars with regular spaces
256 // and joining the array into a multi-line string.
257 const formattedResult = result.map(line => {
258 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
259 }).join(Browser.isWindows ? '\r\n' : '\n');
260
261 return formattedResult;
262 }
263
264 /**
265 * Clears the current terminal selection.
266 */
267 public clearSelection(): void {
268 this._model.clearSelection();
269 this._removeMouseDownListeners();
270 this.refresh();
271 this._onSelectionChange.fire();
272 }
273
274 /**
275 * Queues a refresh, redrawing the selection on the next opportunity.
276 * @param isLinuxMouseSelection Whether the selection should be registered as a new
277 * selection on Linux.
278 */
279 public refresh(isLinuxMouseSelection?: boolean): void {
280 // Queue the refresh for the renderer
281 if (!this._refreshAnimationFrame) {
282 this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh());
283 }
284
285 // If the platform is Linux and the refresh call comes from a mouse event,
286 // we need to update the selection for middle click to paste selection.
287 if (Browser.isLinux && isLinuxMouseSelection) {
288 const selectionText = this.selectionText;
289 if (selectionText.length) {
290 this._onLinuxMouseSelection.fire(this.selectionText);
291 }
292 }
293 }
294
295 /**
296 * Fires the refresh event, causing consumers to pick it up and redraw the
297 * selection state.
298 */
299 private _refresh(): void {
300 this._refreshAnimationFrame = undefined;
301 this._onRedrawRequest.fire({
302 start: this._model.finalSelectionStart,
303 end: this._model.finalSelectionEnd,
304 columnSelectMode: this._activeSelectionMode === SelectionMode.COLUMN
305 });
306 }
307
308 /**
309 * Checks if the current click was inside the current selection
310 * @param event The mouse event
311 */
312 private _isClickInSelection(event: MouseEvent): boolean {
313 const coords = this._getMouseBufferCoords(event);
314 const start = this._model.finalSelectionStart;
315 const end = this._model.finalSelectionEnd;
316
317 if (!start || !end || !coords) {
318 return false;
319 }
320
321 return this._areCoordsInSelection(coords, start, end);
322 }
323
324 public isCellInSelection(x: number, y: number): boolean {
325 const start = this._model.finalSelectionStart;
326 const end = this._model.finalSelectionEnd;
327 if (!start || !end) {
328 return false;
329 }
330 return this._areCoordsInSelection([x, y], start, end);
331 }
332
333 protected _areCoordsInSelection(coords: [number, number], start: [number, number], end: [number, number]): boolean {
334 return (coords[1] > start[1] && coords[1] < end[1]) ||
335 (start[1] === end[1] && coords[1] === start[1] && coords[0] >= start[0] && coords[0] < end[0]) ||
336 (start[1] < end[1] && coords[1] === end[1] && coords[0] < end[0]) ||
337 (start[1] < end[1] && coords[1] === start[1] && coords[0] >= start[0]);
338 }
339
340 /**
341 * Selects word at the current mouse event coordinates.
342 * @param event The mouse event.
343 */
344 private _selectWordAtCursor(event: MouseEvent, allowWhitespaceOnlySelection: boolean): boolean {
345 // Check if there is a link under the cursor first and select that if so
346 const range = this._linkifier.currentLink?.link?.range;
347 if (range) {
348 this._model.selectionStart = [range.start.x - 1, range.start.y - 1];
349 this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);
350 this._model.selectionEnd = undefined;
351 return true;
352 }
353
354 const coords = this._getMouseBufferCoords(event);
355 if (coords) {
356 this._selectWordAt(coords, allowWhitespaceOnlySelection);
357 this._model.selectionEnd = undefined;
358 return true;
359 }
360 return false;
361 }
362
363 /**
364 * Selects all text within the terminal.
365 */
366 public selectAll(): void {
367 this._model.isSelectAllActive = true;
368 this.refresh();
369 this._onSelectionChange.fire();
370 }
371
372 public selectLines(start: number, end: number): void {
373 this._model.clearSelection();
374 start = Math.max(start, 0);
375 end = Math.min(end, this._bufferService.buffer.lines.length - 1);
376 this._model.selectionStart = [0, start];
377 this._model.selectionEnd = [this._bufferService.cols, end];
378 this.refresh();
379 this._onSelectionChange.fire();
380 }
381
382 /**
383 * Handle the buffer being trimmed, adjust the selection position.
384 * @param amount The amount the buffer is being trimmed.
385 */
386 private _handleTrim(amount: number): void {
387 const needsRefresh = this._model.handleTrim(amount);
388 if (needsRefresh) {
389 this.refresh();
390 }
391 }
392
393 /**
394 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
395 * @param event The mouse event.
396 */
397 private _getMouseBufferCoords(event: MouseEvent): [number, number] | undefined {
398 const coords = this._mouseService.getCoords(event, this._screenElement, this._bufferService.cols, this._bufferService.rows, true);
399 if (!coords) {
400 return undefined;
401 }
402
403 // Convert to 0-based
404 coords[0]--;
405 coords[1]--;
406
407 // Convert viewport coords to buffer coords
408 coords[1] += this._bufferService.buffer.ydisp;
409 return coords;
410 }
411
412 /**
413 * Gets the amount the viewport should be scrolled based on how far out of the
414 * terminal the mouse is.
415 * @param event The mouse event.
416 */
417 private _getMouseEventScrollAmount(event: MouseEvent): number {
418 let offset = getCoordsRelativeToElement(this._coreBrowserService.window, event, this._screenElement)[1];
419 const terminalHeight = this._renderService.dimensions.css.canvas.height;
420 if (offset >= 0 && offset <= terminalHeight) {
421 return 0;
422 }
423 if (offset > terminalHeight) {
424 offset -= terminalHeight;
425 }
426
427 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
428 offset /= DRAG_SCROLL_MAX_THRESHOLD;
429 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
430 }
431
432 /**
433 * Returns whether the selection manager should force selection, regardless of
434 * whether the terminal is in mouse events mode.
435 * @param event The mouse event.
436 */
437 public shouldForceSelection(event: MouseEvent): boolean {
438 if (Browser.isMac) {
439 return event.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection;
440 }
441
442 return event.shiftKey;
443 }
444
445 /**
446 * Handles te mousedown event, setting up for a new selection.
447 * @param event The mousedown event.
448 */
449 public handleMouseDown(event: MouseEvent): void {
450 this._mouseDownTimeStamp = event.timeStamp;
451 // If we have selection, we want the context menu on right click even if the
452 // terminal is in mouse mode.
453 if (event.button === 2 && this.hasSelection) {
454 return;
455 }
456
457 // Only action the primary button
458 if (event.button !== 0) {
459 return;
460 }
461
462 // Allow selection when using a specific modifier key, even when disabled
463 if (!this._enabled) {
464 if (!this.shouldForceSelection(event)) {
465 return;
466 }
467
468 // Don't send the mouse down event to the current process, we want to select
469 event.stopPropagation();
470 }
471
472 // Tell the browser not to start a regular selection
473 event.preventDefault();
474
475 // Reset drag scroll state
476 this._dragScrollAmount = 0;
477
478 if (this._enabled && event.shiftKey) {
479 this._handleIncrementalClick(event);
480 } else {
481 if (event.detail === 1) {
482 this._handleSingleClick(event);
483 } else if (event.detail === 2) {
484 this._handleDoubleClick(event);
485 } else if (event.detail === 3) {
486 this._handleTripleClick(event);
487 }
488 }
489
490 this._addMouseDownListeners();
491 this.refresh(true);
492 }
493
494 /**
495 * Adds listeners when mousedown is triggered.
496 */
497 private _addMouseDownListeners(): void {
498 // Listen on the document so that dragging outside of viewport works
499 if (this._screenElement.ownerDocument) {
500 this._screenElement.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
501 this._screenElement.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
502 }
503 this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
504 }
505
506 /**
507 * Removes the listeners that are registered when mousedown is triggered.
508 */
509 private _removeMouseDownListeners(): void {
510 if (this._screenElement.ownerDocument) {
511 this._screenElement.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
512 this._screenElement.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
513 }
514 this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer);
515 this._dragScrollIntervalTimer = undefined;
516 }
517
518 /**
519 * Performs an incremental click, setting the selection end position to the mouse
520 * position.
521 * @param event The mouse event.
522 */
523 private _handleIncrementalClick(event: MouseEvent): void {
524 if (this._model.selectionStart) {
525 this._model.selectionEnd = this._getMouseBufferCoords(event);
526 }
527 }
528
529 /**
530 * Performs a single click, resetting relevant state and setting the selection
531 * start position.
532 * @param event The mouse event.
533 */
534 private _handleSingleClick(event: MouseEvent): void {
535 this._model.selectionStartLength = 0;
536 this._model.isSelectAllActive = false;
537 this._activeSelectionMode = this.shouldColumnSelect(event) ? SelectionMode.COLUMN : SelectionMode.NORMAL;
538
539 // Initialize the new selection
540 this._model.selectionStart = this._getMouseBufferCoords(event);
541 if (!this._model.selectionStart) {
542 return;
543 }
544 this._model.selectionEnd = undefined;
545
546 // Ensure the line exists
547 const line = this._bufferService.buffer.lines.get(this._model.selectionStart[1]);
548 if (!line) {
549 return;
550 }
551
552 // Return early if the click event is not in the buffer (eg. in scroll bar)
553 if (line.length === this._model.selectionStart[0]) {
554 return;
555 }
556
557 // If the mouse is over the second half of a wide character, adjust the
558 // selection to cover the whole character
559 if (line.hasWidth(this._model.selectionStart[0]) === 0) {
560 this._model.selectionStart[0]++;
561 }
562 }
563
564 /**
565 * Performs a double click, selecting the current word.
566 * @param event The mouse event.
567 */
568 private _handleDoubleClick(event: MouseEvent): void {
569 if (this._selectWordAtCursor(event, true)) {
570 this._activeSelectionMode = SelectionMode.WORD;
571 }
572 }
573
574 /**
575 * Performs a triple click, selecting the current line and activating line
576 * select mode.
577 * @param event The mouse event.
578 */
579 private _handleTripleClick(event: MouseEvent): void {
580 const coords = this._getMouseBufferCoords(event);
581 if (coords) {
582 this._activeSelectionMode = SelectionMode.LINE;
583 this._selectLineAt(coords[1]);
584 }
585 }
586
587 /**
588 * Returns whether the selection manager should operate in column select mode
589 * @param event the mouse or keyboard event
590 */
591 public shouldColumnSelect(event: KeyboardEvent | MouseEvent): boolean {
592 return event.altKey && !(Browser.isMac && this._optionsService.rawOptions.macOptionClickForcesSelection);
593 }
594
595 /**
596 * Handles the mousemove event when the mouse button is down, recording the
597 * end of the selection and refreshing the selection.
598 * @param event The mousemove event.
599 */
600 private _handleMouseMove(event: MouseEvent): void {
601 // If the mousemove listener is active it means that a selection is
602 // currently being made, we should stop propagation to prevent mouse events
603 // to be sent to the pty.
604 event.stopImmediatePropagation();
605
606 // Do nothing if there is no selection start, this can happen if the first
607 // click in the terminal is an incremental click
608 if (!this._model.selectionStart) {
609 return;
610 }
611
612 // Record the previous position so we know whether to redraw the selection
613 // at the end.
614 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
615
616 // Set the initial selection end based on the mouse coordinates
617 this._model.selectionEnd = this._getMouseBufferCoords(event);
618 if (!this._model.selectionEnd) {
619 this.refresh(true);
620 return;
621 }
622
623 // Select the entire line if line select mode is active.
624 if (this._activeSelectionMode === SelectionMode.LINE) {
625 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
626 this._model.selectionEnd[0] = 0;
627 } else {
628 this._model.selectionEnd[0] = this._bufferService.cols;
629 }
630 } else if (this._activeSelectionMode === SelectionMode.WORD) {
631 this._selectToWordAt(this._model.selectionEnd);
632 }
633
634 // Determine the amount of scrolling that will happen.
635 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
636
637 // If the cursor was above or below the viewport, make sure it's at the
638 // start or end of the viewport respectively. This should only happen when
639 // NOT in column select mode.
640 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
641 if (this._dragScrollAmount > 0) {
642 this._model.selectionEnd[0] = this._bufferService.cols;
643 } else if (this._dragScrollAmount < 0) {
644 this._model.selectionEnd[0] = 0;
645 }
646 }
647
648 // If the character is a wide character include the cell to the right in the
649 // selection. Note that selections at the very end of the line will never
650 // have a character.
651 const buffer = this._bufferService.buffer;
652 if (this._model.selectionEnd[1] < buffer.lines.length) {
653 const line = buffer.lines.get(this._model.selectionEnd[1]);
654 if (line && line.hasWidth(this._model.selectionEnd[0]) === 0) {
655 if (this._model.selectionEnd[0] < this._bufferService.cols) {
656 this._model.selectionEnd[0]++;
657 }
658 }
659 }
660
661 // Only draw here if the selection changes.
662 if (!previousSelectionEnd ||
663 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
664 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
665 this.refresh(true);
666 }
667 }
668
669 /**
670 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
671 * scrolling of the viewport.
672 */
673 private _dragScroll(): void {
674 if (!this._model.selectionEnd || !this._model.selectionStart) {
675 return;
676 }
677 if (this._dragScrollAmount) {
678 this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false });
679 // Re-evaluate selection
680 // If the cursor was above or below the viewport, make sure it's at the
681 // start or end of the viewport respectively. This should only happen when
682 // NOT in column select mode.
683 const buffer = this._bufferService.buffer;
684 if (this._dragScrollAmount > 0) {
685 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
686 this._model.selectionEnd[0] = this._bufferService.cols;
687 }
688 this._model.selectionEnd[1] = Math.min(buffer.ydisp + this._bufferService.rows, buffer.lines.length - 1);
689 } else {
690 if (this._activeSelectionMode !== SelectionMode.COLUMN) {
691 this._model.selectionEnd[0] = 0;
692 }
693 this._model.selectionEnd[1] = buffer.ydisp;
694 }
695 this.refresh();
696 }
697 }
698
699 /**
700 * Handles the mouseup event, removing the mousedown listeners.
701 * @param event The mouseup event.
702 */
703 private _handleMouseUp(event: MouseEvent): void {
704 const timeElapsed = event.timeStamp - this._mouseDownTimeStamp;
705
706 this._removeMouseDownListeners();
707
708 if (this.selectionText.length <= 1 && timeElapsed < ALT_CLICK_MOVE_CURSOR_TIME && event.altKey && this._optionsService.rawOptions.altClickMovesCursor) {
709 if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) {
710 const coordinates = this._mouseService.getCoords(
711 event,
712 this._element,
713 this._bufferService.cols,
714 this._bufferService.rows,
715 false
716 );
717 if (coordinates && coordinates[0] !== undefined && coordinates[1] !== undefined) {
718 const sequence = moveToCellSequence(coordinates[0] - 1, coordinates[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys);
719 this._coreService.triggerDataEvent(sequence, true);
720 }
721 }
722 } else {
723 this._fireEventIfSelectionChanged();
724 }
725 }
726
727 private _fireEventIfSelectionChanged(): void {
728 const start = this._model.finalSelectionStart;
729 const end = this._model.finalSelectionEnd;
730 const hasSelection = !!start && !!end && (start[0] !== end[0] || start[1] !== end[1]);
731
732 if (!hasSelection) {
733 if (this._oldHasSelection) {
734 this._fireOnSelectionChange(start, end, hasSelection);
735 }
736 return;
737 }
738
739 // Sanity check, these should not be undefined as there is a selection
740 if (!start || !end) {
741 return;
742 }
743
744 if (!this._oldSelectionStart || !this._oldSelectionEnd || (
745 start[0] !== this._oldSelectionStart[0] || start[1] !== this._oldSelectionStart[1] ||
746 end[0] !== this._oldSelectionEnd[0] || end[1] !== this._oldSelectionEnd[1])) {
747
748 this._fireOnSelectionChange(start, end, hasSelection);
749 }
750 }
751
752 private _fireOnSelectionChange(start: [number, number] | undefined, end: [number, number] | undefined, hasSelection: boolean): void {
753 this._oldSelectionStart = start;
754 this._oldSelectionEnd = end;
755 this._oldHasSelection = hasSelection;
756 this._onSelectionChange.fire();
757 }
758
759 private _handleBufferActivate(e: {activeBuffer: IBuffer, inactiveBuffer: IBuffer}): void {
760 this.clearSelection();
761 // Only adjust the selection on trim, shiftElements is rarely used (only in
762 // reverseIndex) and delete in a splice is only ever used when the same
763 // number of elements was just added. Given this is could actually be
764 // beneficial to leave the selection as is for these cases.
765 this._trimListener.dispose();
766 this._trimListener = e.activeBuffer.lines.onTrim(amount => this._handleTrim(amount));
767 }
768
769 /**
770 * Converts a viewport column (0 to cols - 1) to the character index on the
771 * buffer line, the latter takes into account wide and null characters.
772 * @param bufferLine The buffer line to use.
773 * @param x The x index in the buffer line to convert.
774 */
775 private _convertViewportColToCharacterIndex(bufferLine: IBufferLine, x: number): number {
776 let charIndex = x;
777 for (let i = 0; x >= i; i++) {
778 const length = bufferLine.loadCell(i, this._workCell).getChars().length;
779 if (this._workCell.getWidth() === 0) {
780 // Wide characters aren't included in the line string so decrement the
781 // index so the index is back on the wide character.
782 charIndex--;
783 } else if (length > 1 && x !== i) {
784 // Emojis take up multiple characters, so adjust accordingly. For these
785 // we don't want ot include the character at the column as we're
786 // returning the start index in the string, not the end index.
787 charIndex += length - 1;
788 }
789 }
790 return charIndex;
791 }
792
793 public setSelection(col: number, row: number, length: number): void {
794 this._model.clearSelection();
795 this._removeMouseDownListeners();
796 this._model.selectionStart = [col, row];
797 this._model.selectionStartLength = length;
798 this.refresh();
799 this._fireEventIfSelectionChanged();
800 }
801
802 public rightClickSelect(ev: MouseEvent): void {
803 if (!this._isClickInSelection(ev)) {
804 if (this._selectWordAtCursor(ev, false)) {
805 this.refresh(true);
806 }
807 this._fireEventIfSelectionChanged();
808 }
809 }
810
811 /**
812 * Gets positional information for the word at the coordinated specified.
813 * @param coords The coordinates to get the word at.
814 */
815 private _getWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean, followWrappedLinesAbove: boolean = true, followWrappedLinesBelow: boolean = true): IWordPosition | undefined {
816 // Ensure coords are within viewport (eg. not within scroll bar)
817 if (coords[0] >= this._bufferService.cols) {
818 return undefined;
819 }
820
821 const buffer = this._bufferService.buffer;
822 const bufferLine = buffer.lines.get(coords[1]);
823 if (!bufferLine) {
824 return undefined;
825 }
826
827 const line = buffer.translateBufferLineToString(coords[1], false);
828
829 // Get actual index, taking into consideration wide characters
830 let startIndex = this._convertViewportColToCharacterIndex(bufferLine, coords[0]);
831 let endIndex = startIndex;
832
833 // Record offset to be used later
834 const charOffset = coords[0] - startIndex;
835 let leftWideCharCount = 0;
836 let rightWideCharCount = 0;
837 let leftLongCharOffset = 0;
838 let rightLongCharOffset = 0;
839
840 if (line.charAt(startIndex) === ' ') {
841 // Expand until non-whitespace is hit
842 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
843 startIndex--;
844 }
845 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
846 endIndex++;
847 }
848 } else {
849 // Expand until whitespace is hit. This algorithm works by scanning left
850 // and right from the starting position, keeping both the index format
851 // (line) and the column format (bufferLine) in sync. When a wide
852 // character is hit, it is recorded and the column index is adjusted.
853 let startCol = coords[0];
854 let endCol = coords[0];
855
856 // Consider the initial position, skip it and increment the wide char
857 // variable
858 if (bufferLine.getWidth(startCol) === 0) {
859 leftWideCharCount++;
860 startCol--;
861 }
862 if (bufferLine.getWidth(endCol) === 2) {
863 rightWideCharCount++;
864 endCol++;
865 }
866
867 // Adjust the end index for characters whose length are > 1 (emojis)
868 const length = bufferLine.getString(endCol).length;
869 if (length > 1) {
870 rightLongCharOffset += length - 1;
871 endIndex += length - 1;
872 }
873
874 // Expand the string in both directions until a space is hit
875 while (startCol > 0 && startIndex > 0 && !this._isCharWordSeparator(bufferLine.loadCell(startCol - 1, this._workCell))) {
876 bufferLine.loadCell(startCol - 1, this._workCell);
877 const length = this._workCell.getChars().length;
878 if (this._workCell.getWidth() === 0) {
879 // If the next character is a wide char, record it and skip the column
880 leftWideCharCount++;
881 startCol--;
882 } else if (length > 1) {
883 // If the next character's string is longer than 1 char (eg. emoji),
884 // adjust the index
885 leftLongCharOffset += length - 1;
886 startIndex -= length - 1;
887 }
888 startIndex--;
889 startCol--;
890 }
891 while (endCol < bufferLine.length && endIndex + 1 < line.length && !this._isCharWordSeparator(bufferLine.loadCell(endCol + 1, this._workCell))) {
892 bufferLine.loadCell(endCol + 1, this._workCell);
893 const length = this._workCell.getChars().length;
894 if (this._workCell.getWidth() === 2) {
895 // If the next character is a wide char, record it and skip the column
896 rightWideCharCount++;
897 endCol++;
898 } else if (length > 1) {
899 // If the next character's string is longer than 1 char (eg. emoji),
900 // adjust the index
901 rightLongCharOffset += length - 1;
902 endIndex += length - 1;
903 }
904 endIndex++;
905 endCol++;
906 }
907 }
908
909 // Incremenet the end index so it is at the start of the next character
910 endIndex++;
911
912 // Calculate the start _column_, converting the the string indexes back to
913 // column coordinates.
914 let start =
915 startIndex // The index of the selection's start char in the line string
916 + charOffset // The difference between the initial char's column and index
917 - leftWideCharCount // The number of wide chars left of the initial char
918 + leftLongCharOffset; // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
919
920 // Calculate the length in _columns_, converting the the string indexes back
921 // to column coordinates.
922 let length = Math.min(this._bufferService.cols, // Disallow lengths larger than the terminal cols
923 endIndex // The index of the selection's end char in the line string
924 - startIndex // The index of the selection's start char in the line string
925 + leftWideCharCount // The number of wide chars left of the initial char
926 + rightWideCharCount // The number of wide chars right of the initial char (inclusive)
927 - leftLongCharOffset // The number of additional chars left of the initial char added by columns with strings longer than 1 (emojis)
928 - rightLongCharOffset); // The number of additional chars right of the initial char (inclusive) added by columns with strings longer than 1 (emojis)
929
930 if (!allowWhitespaceOnlySelection && line.slice(startIndex, endIndex).trim() === '') {
931 return undefined;
932 }
933
934 // Recurse upwards if the line is wrapped and the word wraps to the above line
935 if (followWrappedLinesAbove) {
936 if (start === 0 && bufferLine.getCodePoint(0) !== 32 /* ' ' */) {
937 const previousBufferLine = buffer.lines.get(coords[1] - 1);
938 if (previousBufferLine && bufferLine.isWrapped && previousBufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {
939 const previousLineWordPosition = this._getWordAt([this._bufferService.cols - 1, coords[1] - 1], false, true, false);
940 if (previousLineWordPosition) {
941 const offset = this._bufferService.cols - previousLineWordPosition.start;
942 start -= offset;
943 length += offset;
944 }
945 }
946 }
947 }
948
949 // Recurse downwards if the line is wrapped and the word wraps to the next line
950 if (followWrappedLinesBelow) {
951 if (start + length === this._bufferService.cols && bufferLine.getCodePoint(this._bufferService.cols - 1) !== 32 /* ' ' */) {
952 const nextBufferLine = buffer.lines.get(coords[1] + 1);
953 if (nextBufferLine?.isWrapped && nextBufferLine.getCodePoint(0) !== 32 /* ' ' */) {
954 const nextLineWordPosition = this._getWordAt([0, coords[1] + 1], false, false, true);
955 if (nextLineWordPosition) {
956 length += nextLineWordPosition.length;
957 }
958 }
959 }
960 }
961
962 return { start, length };
963 }
964
965 /**
966 * Selects the word at the coordinates specified.
967 * @param coords The coordinates to get the word at.
968 * @param allowWhitespaceOnlySelection If whitespace should be selected
969 */
970 protected _selectWordAt(coords: [number, number], allowWhitespaceOnlySelection: boolean): void {
971 const wordPosition = this._getWordAt(coords, allowWhitespaceOnlySelection);
972 if (wordPosition) {
973 // Adjust negative start value
974 while (wordPosition.start < 0) {
975 wordPosition.start += this._bufferService.cols;
976 coords[1]--;
977 }
978 this._model.selectionStart = [wordPosition.start, coords[1]];
979 this._model.selectionStartLength = wordPosition.length;
980 }
981 }
982
983 /**
984 * Sets the selection end to the word at the coordinated specified.
985 * @param coords The coordinates to get the word at.
986 */
987 private _selectToWordAt(coords: [number, number]): void {
988 const wordPosition = this._getWordAt(coords, true);
989 if (wordPosition) {
990 let endRow = coords[1];
991
992 // Adjust negative start value
993 while (wordPosition.start < 0) {
994 wordPosition.start += this._bufferService.cols;
995 endRow--;
996 }
997
998 // Adjust wrapped length value, this only needs to happen when values are reversed as in that
999 // case we're interested in the start of the word, not the end
1000 if (!this._model.areSelectionValuesReversed()) {
1001 while (wordPosition.start + wordPosition.length > this._bufferService.cols) {
1002 wordPosition.length -= this._bufferService.cols;
1003 endRow++;
1004 }
1005 }
1006
1007 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : wordPosition.start + wordPosition.length, endRow];
1008 }
1009 }
1010
1011 /**
1012 * Gets whether the character is considered a word separator by the select
1013 * word logic.
1014 * @param cell The cell to check.
1015 */
1016 private _isCharWordSeparator(cell: CellData): boolean {
1017 // Zero width characters are never separators as they are always to the
1018 // right of wide characters
1019 if (cell.getWidth() === 0) {
1020 return false;
1021 }
1022 return this._optionsService.rawOptions.wordSeparator.indexOf(cell.getChars()) >= 0;
1023 }
1024
1025 /**
1026 * Selects the line specified.
1027 * @param line The line index.
1028 */
1029 protected _selectLineAt(line: number): void {
1030 const wrappedRange = this._bufferService.buffer.getWrappedRangeForLine(line);
1031 const range: IBufferRange = {
1032 start: { x: 0, y: wrappedRange.first },
1033 end: { x: this._bufferService.cols - 1, y: wrappedRange.last }
1034 };
1035 this._model.selectionStart = [0, wrappedRange.first];
1036 this._model.selectionEnd = undefined;
1037 this._model.selectionStartLength = getRangeLength(range, this._bufferService.cols);
1038 }
1039 }