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