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