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