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