]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Ensure outside selection pastes are respected
[mirror_xterm.js.git] / src / SelectionManager.ts
1 /**
2 * @license MIT
3 */
4
5 import * as Mouse from './utils/Mouse';
6 import * as Browser from './utils/Browser';
7 import { CharMeasure } from './utils/CharMeasure';
8 import { CircularList } from './utils/CircularList';
9 import { EventEmitter } from './EventEmitter';
10 import { ITerminal } from './Interfaces';
11 import { SelectionModel } from './SelectionModel';
12
13 /**
14 * The number of pixels the mouse needs to be above or below the viewport in
15 * order to scroll at the maximum speed.
16 */
17 const DRAG_SCROLL_MAX_THRESHOLD = 50;
18
19 /**
20 * The maximum scrolling speed
21 */
22 const DRAG_SCROLL_MAX_SPEED = 15;
23
24 /**
25 * The number of milliseconds between drag scroll updates.
26 */
27 const DRAG_SCROLL_INTERVAL = 50;
28
29 /**
30 * The amount of time before mousedown events are no longer stacked to create
31 * double/triple click events.
32 */
33 const CLEAR_MOUSE_DOWN_TIME = 400;
34
35 /**
36 * The number of pixels in each direction that the mouse must move before
37 * mousedown events are no longer stacked to create double/triple click events.
38 */
39 const CLEAR_MOUSE_DISTANCE = 10;
40
41 /**
42 * A string containing all characters that are considered word separated by the
43 * double click to select work logic.
44 */
45 const WORD_SEPARATORS = ' ()[]{}:\'"';
46
47 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
48 // data/line class.
49 const LINE_DATA_CHAR_INDEX = 1;
50 const LINE_DATA_WIDTH_INDEX = 2;
51
52 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
53 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
54
55 /**
56 * Represents a position of a word on a line.
57 */
58 interface IWordPosition {
59 start: number;
60 length: number;
61 }
62
63 /**
64 * A selection mode, this drives how the selection behaves on mouse move.
65 */
66 enum SelectionMode {
67 NORMAL,
68 WORD,
69 LINE
70 }
71
72 /**
73 * A class that manages the selection of the terminal. With help from
74 * SelectionModel, SelectionManager handles with all logic associated with
75 * dealing with the selection, including handling mouse interaction, wide
76 * characters and fetching the actual text within the selection. Rendering is
77 * not handled by the SelectionManager but a 'refresh' event is fired when the
78 * selection is ready to be redrawn.
79 */
80 export class SelectionManager extends EventEmitter {
81 protected _model: SelectionModel;
82
83 /**
84 * The amount to scroll every drag scroll update (depends on how far the mouse
85 * drag is above or below the terminal).
86 */
87 private _dragScrollAmount: number;
88
89 /**
90 * The last time the mousedown event fired, this is used to track double and
91 * triple clicks.
92 */
93 private _lastMouseDownTime: number;
94
95 /**
96 * The last position the mouse was clicked [x, y].
97 */
98 private _lastMousePosition: [number, number];
99
100 /**
101 * The number of clicks of the mousedown event. This is used to keep track of
102 * double and triple clicks.
103 */
104 private _clickCount: number;
105
106 /**
107 * The current selection mode.
108 */
109 private _activeSelectionMode: SelectionMode;
110
111 /**
112 * A setInterval timer that is active while the mouse is down whose callback
113 * scrolls the viewport when necessary.
114 */
115 private _dragScrollIntervalTimer: NodeJS.Timer;
116
117 /**
118 * The animation frame ID used for refreshing the selection.
119 */
120 private _refreshAnimationFrame: number;
121
122 private _bufferTrimListener: any;
123 private _mouseMoveListener: EventListener;
124 private _mouseDownListener: EventListener;
125 private _mouseUpListener: EventListener;
126
127 constructor(
128 private _terminal: ITerminal,
129 private _buffer: CircularList<any>,
130 private _rowContainer: HTMLElement,
131 private _charMeasure: CharMeasure
132 ) {
133 super();
134 this._initListeners();
135 this.enable();
136
137 this._model = new SelectionModel(_terminal);
138 this._lastMouseDownTime = 0;
139 this._activeSelectionMode = SelectionMode.NORMAL;
140 }
141
142 /**
143 * Initializes listener variables.
144 */
145 private _initListeners() {
146 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
147 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
148 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
149 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
150 }
151
152 /**
153 * Disables the selection manager. This is useful for when terminal mouse
154 * are enabled.
155 */
156 public disable() {
157 this.clearSelection();
158 this._buffer.off('trim', this._bufferTrimListener);
159 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
160 }
161
162 /**
163 * Enable the selection manager.
164 */
165 public enable() {
166 // Only adjust the selection on trim, shiftElements is rarely used (only in
167 // reverseIndex) and delete in a splice is only ever used when the same
168 // number of elements was just added. Given this is could actually be
169 // beneficial to leave the selection as is for these cases.
170 this._buffer.on('trim', this._bufferTrimListener);
171 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
172 }
173
174 /**
175 * Sets the active buffer, this should be called when the alt buffer is
176 * switched in or out.
177 * @param buffer The active buffer.
178 */
179 public setBuffer(buffer: CircularList<any>): void {
180 this._buffer = buffer;
181 }
182
183 /**
184 * Gets whether there is an active text selection.
185 */
186 public get hasSelection(): boolean {
187 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
188 }
189
190 /**
191 * Gets the text currently selected.
192 */
193 public get selectionText(): string {
194 const start = this._model.finalSelectionStart;
195 const end = this._model.finalSelectionEnd;
196 if (!start || !end) {
197 return '';
198 }
199
200 // Get first row
201 const startRowEndCol = start[1] === end[1] ? end[0] : null;
202 let result: string[] = [];
203 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
204
205 // Get middle rows
206 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
207 const bufferLine = this._buffer.get(i);
208 const lineText = this._translateBufferLineToString(bufferLine, true);
209 if (bufferLine.isWrapped) {
210 result[result.length - 1] += lineText;
211 } else {
212 result.push(lineText);
213 }
214 }
215
216 // Get final row
217 if (start[1] !== end[1]) {
218 const bufferLine = this._buffer.get(end[1]);
219 const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
220 if (bufferLine.isWrapped) {
221 result[result.length - 1] += lineText;
222 } else {
223 result.push(lineText);
224 }
225 }
226
227 // Format string by replacing non-breaking space chars with regular spaces
228 // and joining the array into a multi-line string.
229 const formattedResult = result.map(line => {
230 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
231 }).join('\n');
232
233 return formattedResult;
234 }
235
236 /**
237 * Clears the current terminal selection.
238 */
239 public clearSelection(): void {
240 this._model.clearSelection();
241 this._removeMouseDownListeners();
242 this.refresh();
243 }
244
245 /**
246 * Translates a buffer line to a string, with optional start and end columns.
247 * Wide characters will count as two columns in the resulting string. This
248 * function is useful for getting the actual text underneath the raw selection
249 * position.
250 * @param line The line being translated.
251 * @param trimRight Whether to trim whitespace to the right.
252 * @param startCol The column to start at.
253 * @param endCol The column to end at.
254 */
255 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
256 // TODO: This function should live in a buffer or buffer line class
257
258 // Get full line
259 let lineString = '';
260 let widthAdjustedStartCol = startCol;
261 let widthAdjustedEndCol = endCol;
262 for (let i = 0; i < line.length; i++) {
263 const char = line[i];
264 lineString += char[LINE_DATA_CHAR_INDEX];
265 // Adjust start and end cols for wide characters if they affect their
266 // column indexes
267 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
268 if (startCol >= i) {
269 widthAdjustedStartCol--;
270 }
271 if (endCol >= i) {
272 widthAdjustedEndCol--;
273 }
274 }
275 }
276
277 // Calculate the final end col by trimming whitespace on the right of the
278 // line if needed.
279 let finalEndCol = widthAdjustedEndCol || line.length;
280 if (trimRight) {
281 const rightWhitespaceIndex = lineString.search(/\s+$/);
282 if (rightWhitespaceIndex !== -1) {
283 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
284 }
285 // Return the empty string if only trimmed whitespace is selected
286 if (finalEndCol <= widthAdjustedStartCol) {
287 return '';
288 }
289 }
290
291 return lineString.substring(widthAdjustedStartCol, finalEndCol);
292 }
293
294 /**
295 * Queues a refresh, redrawing the selection on the next opportunity.
296 * @param isNewSelection Whether the selection should be registered as a new
297 * selection on Linux.
298 */
299 public refresh(isNewSelection?: boolean): void {
300 // Queue the refresh for the renderer
301 if (!this._refreshAnimationFrame) {
302 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
303 }
304
305 // If the platform is Linux and the refresh call comes from a mouse event,
306 // we need to update the selection for middle click to paste selection.
307 if (Browser.isLinux && isNewSelection) {
308 const selectionText = this.selectionText;
309 if (selectionText.length) {
310 this.emit('newselection', this.selectionText);
311 }
312 }
313 }
314
315 /**
316 * Fires the refresh event, causing consumers to pick it up and redraw the
317 * selection state.
318 */
319 private _refresh(): void {
320 this._refreshAnimationFrame = null;
321 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
322 }
323
324 /**
325 * Selects all text within the terminal.
326 */
327 public selectAll(): void {
328 this._model.isSelectAllActive = true;
329 this.refresh();
330 }
331
332 /**
333 * Handle the buffer being trimmed, adjust the selection position.
334 * @param amount The amount the buffer is being trimmed.
335 */
336 private _onTrim(amount: number) {
337 const needsRefresh = this._model.onTrim(amount);
338 if (needsRefresh) {
339 this.refresh();
340 }
341 }
342
343 /**
344 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
345 * @param event The mouse event.
346 */
347 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
348 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
349 // Convert to 0-based
350 coords[0]--;
351 coords[1]--;
352 // Convert viewport coords to buffer coords
353 coords[1] += this._terminal.ydisp;
354 return coords;
355 }
356
357 /**
358 * Gets the amount the viewport should be scrolled based on how far out of the
359 * terminal the mouse is.
360 * @param event The mouse event.
361 */
362 private _getMouseEventScrollAmount(event: MouseEvent): number {
363 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
364 const terminalHeight = this._terminal.rows * this._charMeasure.height;
365 if (offset >= 0 && offset <= terminalHeight) {
366 return 0;
367 }
368 if (offset > terminalHeight) {
369 offset -= terminalHeight;
370 }
371
372 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
373 offset /= DRAG_SCROLL_MAX_THRESHOLD;
374 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
375 }
376
377 /**
378 * Handles te mousedown event, setting up for a new selection.
379 * @param event The mousedown event.
380 */
381 private _onMouseDown(event: MouseEvent) {
382 // Only action the primary button
383 if (event.button !== 0) {
384 return;
385 }
386
387 // Tell the browser not to start a regular selection
388 event.preventDefault();
389
390 // Reset drag scroll state
391 this._dragScrollAmount = 0;
392
393 this._setMouseClickCount(event);
394
395 if (event.shiftKey) {
396 this._onShiftClick(event);
397 } else {
398 if (this._clickCount === 1) {
399 this._onSingleClick(event);
400 } else if (this._clickCount === 2) {
401 this._onDoubleClick(event);
402 } else if (this._clickCount === 3) {
403 this._onTripleClick(event);
404 }
405 }
406
407 this._addMouseDownListeners();
408 this.refresh(true);
409 }
410
411 /**
412 * Adds listeners when mousedown is triggered.
413 */
414 private _addMouseDownListeners(): void {
415 // Listen on the document so that dragging outside of viewport works
416 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
417 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
418 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
419 }
420
421 /**
422 * Removes the listeners that are registered when mousedown is triggered.
423 */
424 private _removeMouseDownListeners(): void {
425 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
426 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
427 clearInterval(this._dragScrollIntervalTimer);
428 this._dragScrollIntervalTimer = null;
429 }
430
431 /**
432 * Performs a shift click, setting the selection end position to the mouse
433 * position.
434 * @param event The mouse event.
435 */
436 private _onShiftClick(event: MouseEvent): void {
437 if (this._model.selectionStart) {
438 this._model.selectionEnd = this._getMouseBufferCoords(event);
439 }
440 }
441
442 /**
443 * Performs a single click, resetting relevant state and setting the selection
444 * start position.
445 * @param event The mouse event.
446 */
447 private _onSingleClick(event: MouseEvent): void {
448 this._model.selectionStartLength = 0;
449 this._model.isSelectAllActive = false;
450 this._activeSelectionMode = SelectionMode.NORMAL;
451 this._model.selectionStart = this._getMouseBufferCoords(event);
452 if (this._model.selectionStart) {
453 this._model.selectionEnd = null;
454 // If the mouse is over the second half of a wide character, adjust the
455 // selection to cover the whole character
456 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
457 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
458 this._model.selectionStart[0]++;
459 }
460 }
461 }
462
463 /**
464 * Performs a double click, selecting the current work.
465 * @param event The mouse event.
466 */
467 private _onDoubleClick(event: MouseEvent): void {
468 const coords = this._getMouseBufferCoords(event);
469 if (coords) {
470 this._activeSelectionMode = SelectionMode.WORD;
471 this._selectWordAt(coords);
472 }
473 }
474
475 /**
476 * Performs a triple click, selecting the current line and activating line
477 * select mode.
478 * @param event The mouse event.
479 */
480 private _onTripleClick(event: MouseEvent): void {
481 const coords = this._getMouseBufferCoords(event);
482 if (coords) {
483 this._activeSelectionMode = SelectionMode.LINE;
484 this._selectLineAt(coords[1]);
485 }
486 }
487
488 /**
489 * Sets the number of clicks for the current mousedown event based on the time
490 * and position of the last mousedown event.
491 * @param event The mouse event.
492 */
493 private _setMouseClickCount(event: MouseEvent): void {
494 let currentTime = (new Date()).getTime();
495 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
496 this._clickCount = 0;
497 }
498 this._lastMouseDownTime = currentTime;
499 this._lastMousePosition = [event.pageX, event.pageY];
500 this._clickCount++;
501 }
502
503 /**
504 * Gets the maximum number of pixels in each direction the mouse has moved.
505 * @param event The mouse event.
506 */
507 private _distanceFromLastMousePosition(event: MouseEvent): number {
508 const result = Math.max(
509 Math.abs(this._lastMousePosition[0] - event.pageX),
510 Math.abs(this._lastMousePosition[1] - event.pageY));
511 return result;
512 }
513
514 /**
515 * Handles the mousemove event when the mouse button is down, recording the
516 * end of the selection and refreshing the selection.
517 * @param event The mousemove event.
518 */
519 private _onMouseMove(event: MouseEvent) {
520 // Record the previous position so we know whether to redraw the selection
521 // at the end.
522 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
523
524 // Set the initial selection end based on the mouse coordinates
525 this._model.selectionEnd = this._getMouseBufferCoords(event);
526
527 // Select the entire line if line select mode is active.
528 if (this._activeSelectionMode === SelectionMode.LINE) {
529 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
530 this._model.selectionEnd[0] = 0;
531 } else {
532 this._model.selectionEnd[0] = this._terminal.cols;
533 }
534 } else if (this._activeSelectionMode === SelectionMode.WORD) {
535 this._selectToWordAt(this._model.selectionEnd);
536 }
537
538 // Determine the amount of scrolling that will happen.
539 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
540
541 // If the cursor was above or below the viewport, make sure it's at the
542 // start or end of the viewport respectively.
543 if (this._dragScrollAmount > 0) {
544 this._model.selectionEnd[0] = this._terminal.cols - 1;
545 } else if (this._dragScrollAmount < 0) {
546 this._model.selectionEnd[0] = 0;
547 }
548
549 // If the character is a wide character include the cell to the right in the
550 // selection. Note that selections at the very end of the line will never
551 // have a character.
552 if (this._model.selectionEnd[1] < this._buffer.length) {
553 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
554 if (char && char[2] === 0) {
555 this._model.selectionEnd[0]++;
556 }
557 }
558
559 // Only draw here if the selection changes.
560 if (!previousSelectionEnd ||
561 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
562 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
563 this.refresh(true);
564 }
565 }
566
567 /**
568 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
569 * scrolling of the viewport.
570 */
571 private _dragScroll() {
572 if (this._dragScrollAmount) {
573 this._terminal.scrollDisp(this._dragScrollAmount, false);
574 // Re-evaluate selection
575 if (this._dragScrollAmount > 0) {
576 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
577 } else {
578 this._model.selectionEnd = [0, this._terminal.ydisp];
579 }
580 this.refresh();
581 }
582 }
583
584 /**
585 * Handles the mouseup event, removing the mousedown listeners.
586 * @param event The mouseup event.
587 */
588 private _onMouseUp(event: MouseEvent) {
589 this._removeMouseDownListeners();
590 }
591
592 /**
593 * Converts a viewport column to the character index on the buffer line, the
594 * latter takes into account wide characters.
595 * @param coords The coordinates to find the 2 index for.
596 */
597 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
598 let charIndex = coords[0];
599 for (let i = 0; coords[0] >= i; i++) {
600 const char = bufferLine[i];
601 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
602 charIndex--;
603 }
604 }
605 return charIndex;
606 }
607
608 /**
609 * Gets positional information for the word at the coordinated specified.
610 * @param coords The coordinates to get the word at.
611 */
612 private _getWordAt(coords: [number, number]): IWordPosition {
613 const bufferLine = this._buffer.get(coords[1]);
614 const line = this._translateBufferLineToString(bufferLine, false);
615
616 // Get actual index, taking into consideration wide characters
617 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
618 let startIndex = endIndex;
619
620 // Record offset to be used later
621 const charOffset = coords[0] - startIndex;
622 let leftWideCharCount = 0;
623 let rightWideCharCount = 0;
624
625 if (line.charAt(startIndex) === ' ') {
626 // Expand until non-whitespace is hit
627 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
628 startIndex--;
629 }
630 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
631 endIndex++;
632 }
633 } else {
634 // Expand until whitespace is hit. This algorithm works by scanning left
635 // and right from the starting position, keeping both the index format
636 // (line) and the column format (bufferLine) in sync. When a wide
637 // character is hit, it is recorded and the column index is adjusted.
638 let startCol = coords[0];
639 let endCol = coords[0];
640 // Consider the initial position, skip it and increment the wide char
641 // variable
642 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
643 leftWideCharCount++;
644 startCol--;
645 }
646 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
647 rightWideCharCount++;
648 endCol++;
649 }
650 // Expand the string in both directions until a space is hit
651 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
652 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
653 // If the next character is a wide char, record it and skip the column
654 leftWideCharCount++;
655 startCol--;
656 }
657 startIndex--;
658 startCol--;
659 }
660 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
661 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
662 // If the next character is a wide char, record it and skip the column
663 rightWideCharCount++;
664 endCol++;
665 }
666 endIndex++;
667 endCol++;
668 }
669 }
670
671 const start = startIndex + charOffset - leftWideCharCount;
672 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
673 return {start, length};
674 }
675
676 /**
677 * Selects the word at the coordinates specified.
678 * @param coords The coordinates to get the word at.
679 */
680 protected _selectWordAt(coords: [number, number]): void {
681 const wordPosition = this._getWordAt(coords);
682 this._model.selectionStart = [wordPosition.start, coords[1]];
683 this._model.selectionStartLength = wordPosition.length;
684 }
685
686 /**
687 * Sets the selection end to the word at the coordinated specified.
688 * @param coords The coordinates to get the word at.
689 */
690 private _selectToWordAt(coords: [number, number]): void {
691 const wordPosition = this._getWordAt(coords);
692 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
693 }
694
695 /**
696 * Gets whether the character is considered a word separator by the select
697 * word logic.
698 * @param char The character to check.
699 */
700 private _isCharWordSeparator(char: string): boolean {
701 return WORD_SEPARATORS.indexOf(char) >= 0;
702 }
703
704 /**
705 * Selects the line specified.
706 * @param line The line index.
707 */
708 protected _selectLineAt(line: number): void {
709 this._model.selectionStart = [0, line];
710 this._model.selectionStartLength = this._terminal.cols;
711 }
712 }