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