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';
13 * The number of pixels the mouse needs to be above or below the viewport in
14 * order to scroll at the maximum speed.
16 const DRAG_SCROLL_MAX_THRESHOLD = 50;
19 * The maximum scrolling speed
21 const DRAG_SCROLL_MAX_SPEED = 15;
24 * The number of milliseconds between drag scroll updates.
26 const DRAG_SCROLL_INTERVAL = 50;
29 * The amount of time before mousedown events are no longer stacked to create
30 * double/triple click events.
32 const CLEAR_MOUSE_DOWN_TIME = 400;
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.
38 const CLEAR_MOUSE_DISTANCE = 10;
41 * A string containing all characters that are considered word separated by the
42 * double click to select work logic.
44 const WORD_SEPARATORS = ' ()[]{}:\'"';
46 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
48 const LINE_DATA_CHAR_INDEX = 1;
49 const LINE_DATA_WIDTH_INDEX = 2;
51 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
52 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
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.
62 export class SelectionManager extends EventEmitter {
63 protected _model: SelectionModel;
66 * The amount to scroll every drag scroll update (depends on how far the mouse
67 * drag is above or below the terminal).
69 private _dragScrollAmount: number;
72 * The last time the mousedown event fired, this is used to track double and
75 private _lastMouseDownTime: number;
78 * The last position the mouse was clicked [x, y].
80 private _lastMousePosition: [number, number];
83 * The number of clicks of the mousedown event. This is used to keep track of
84 * double and triple clicks.
86 private _clickCount: number;
89 * Whether line select mode is active, this occurs after a triple click.
91 private _isLineSelectModeActive: boolean;
94 * A setInterval timer that is active while the mouse is down whose callback
95 * scrolls the viewport when necessary.
97 private _dragScrollIntervalTimer: NodeJS.Timer;
100 * The animation frame ID used for refreshing the selection.
102 private _refreshAnimationFrame: number;
104 private _bufferTrimListener: any;
105 private _mouseMoveListener: EventListener;
106 private _mouseDownListener: EventListener;
107 private _mouseUpListener: EventListener;
110 private _terminal: ITerminal,
111 private _buffer: CircularList<any>,
112 private _rowContainer: HTMLElement,
113 private _charMeasure: CharMeasure
116 this._initListeners();
119 this._model = new SelectionModel(_terminal);
120 this._lastMouseDownTime = 0;
121 this._isLineSelectModeActive = false;
125 * Initializes listener variables.
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);
135 * Disables the selection manager. This is useful for when terminal mouse
139 this.clearSelection();
140 this._buffer.off('trim', this._bufferTrimListener);
141 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
145 * Enable the selection manager.
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);
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.
161 public setBuffer(buffer: CircularList<any>): void {
162 this._buffer = buffer;
166 * Gets whether there is an active text selection.
168 public get hasSelection(): boolean {
169 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
173 * Gets the text currently selected.
175 public get selectionText(): string {
176 const start = this._model.finalSelectionStart;
177 const end = this._model.finalSelectionEnd;
178 if (!start || !end) {
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));
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;
194 result.push(lineText);
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;
205 result.push(lineText);
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, ' ');
215 return formattedResult;
219 * Clears the current terminal selection.
221 public clearSelection(): void {
222 this._model.clearSelection();
223 this._removeMouseDownListeners();
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
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.
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
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
249 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
251 widthAdjustedStartCol--;
254 widthAdjustedEndCol--;
259 // Calculate the final end col by trimming whitespace on the right of the
261 let finalEndCol = widthAdjustedEndCol || line.length;
263 const rightWhitespaceIndex = lineString.search(/\s+$/);
264 if (rightWhitespaceIndex !== -1) {
265 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
267 // Return the empty string if only trimmed whitespace is selected
268 if (finalEndCol <= widthAdjustedStartCol) {
273 return lineString.substring(widthAdjustedStartCol, finalEndCol);
277 * Queues a refresh, redrawing the selection on the next opportunity.
279 public refresh(): void {
280 if (!this._refreshAnimationFrame) {
281 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
286 * Fires the refresh event, causing consumers to pick it up and redraw the
289 private _refresh(): void {
290 this._refreshAnimationFrame = null;
291 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
295 * Selects all text within the terminal.
297 public selectAll(): void {
298 this._model.isSelectAllActive = true;
303 * Handle the buffer being trimmed, adjust the selection position.
304 * @param amount The amount the buffer is being trimmed.
306 private _onTrim(amount: number) {
307 const needsRefresh = this._model.onTrim(amount);
314 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
315 * @param event The mouse event.
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
322 // Convert viewport coords to buffer coords
323 coords[1] += this._terminal.ydisp;
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.
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) {
338 if (offset > terminalHeight) {
339 offset -= terminalHeight;
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));
348 * Handles te mousedown event, setting up for a new selection.
349 * @param event The mousedown event.
351 private _onMouseDown(event: MouseEvent) {
352 // Only action the primary button
353 if (event.button !== 0) {
357 // Tell the browser not to start a regular selection
358 event.preventDefault();
360 // Reset drag scroll state
361 this._dragScrollAmount = 0;
363 this._setMouseClickCount(event);
365 if (event.shiftKey) {
366 this._onShiftClick(event);
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);
377 this._addMouseDownListeners();
382 * Adds listeners when mousedown is triggered.
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);
392 * Removes the listeners that are registered when mousedown is triggered.
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;
402 * Performs a shift click, setting the selection end position to the mouse
404 * @param event The mouse event.
406 private _onShiftClick(event: MouseEvent): void {
407 if (this._model.selectionStart) {
408 this._model.selectionEnd = this._getMouseBufferCoords(event);
413 * Performs a single click, resetting relevant state and setting the selection
415 * @param event The mouse event.
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]++;
434 * Performs a double click, selecting the current work.
435 * @param event The mouse event.
437 private _onDoubleClick(event: MouseEvent): void {
438 const coords = this._getMouseBufferCoords(event);
440 this._selectWordAt(coords);
445 * Performs a triple click, selecting the current line and activating line
447 * @param event The mouse event.
449 private _onTripleClick(event: MouseEvent): void {
450 const coords = this._getMouseBufferCoords(event);
452 this._isLineSelectModeActive = true;
453 this._selectLineAt(coords[1]);
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.
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;
467 this._lastMouseDownTime = currentTime;
468 this._lastMousePosition = [event.pageX, event.pageY];
473 * Gets the maximum number of pixels in each direction the mouse has moved.
474 * @param event The mouse event.
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));
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.
488 private _onMouseMove(event: MouseEvent) {
489 // Record the previous position so we know whether to redraw the selection
491 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
493 // Set the initial selection end based on the mouse coordinates
494 this._model.selectionEnd = this._getMouseBufferCoords(event);
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;
501 this._model.selectionEnd[0] = this._terminal.cols;
505 // Determine the amount of scrolling that will happen.
506 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
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;
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
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]++;
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]) {
535 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
536 * scrolling of the viewport.
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];
545 this._model.selectionEnd = [0, this._terminal.ydisp];
552 * Handles the mouseup event, removing the mousedown listeners.
553 * @param event The mouseup event.
555 private _onMouseUp(event: MouseEvent) {
556 this._removeMouseDownListeners();
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.
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) {
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.
580 protected _selectWordAt(coords: [number, number]): void {
581 const bufferLine = this._buffer.get(coords[1]);
582 const line = this._translateBufferLineToString(bufferLine, false);
584 // Get actual index, taking into consideration wide characters
585 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
586 let startIndex = endIndex;
588 // Record offset to be used later
589 const charOffset = coords[0] - startIndex;
590 let leftWideCharCount = 0;
591 let rightWideCharCount = 0;
593 if (line.charAt(startIndex) === ' ') {
594 // Expand until non-whitespace is hit
595 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
598 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
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
610 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
614 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
615 rightWideCharCount++;
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
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++;
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);
645 * Gets whether the character is considered a word separator by the select
647 * @param char The character to check.
649 private _isCharWordSeparator(char: string): boolean {
650 return WORD_SEPARATORS.indexOf(char) >= 0;
654 * Selects the line specified.
655 * @param line The line index.
657 protected _selectLineAt(line: number): void {
658 this._model.selectionStart = [0, line];
659 this._model.selectionStartLength = this._terminal.cols;