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