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 * Represents a position of a word on a line.
57 interface IWordPosition {
63 * A selection mode, this drives how the selection behaves on mouse move.
72 * A class that manages the selection of the terminal. With help from
73 * SelectionModel, SelectionManager handles with all logic associated with
74 * dealing with the selection, including handling mouse interaction, wide
75 * characters and fetching the actual text within the selection. Rendering is
76 * not handled by the SelectionManager but a 'refresh' event is fired when the
77 * selection is ready to be redrawn.
79 export class SelectionManager extends EventEmitter {
80 protected _model: SelectionModel;
83 * The amount to scroll every drag scroll update (depends on how far the mouse
84 * drag is above or below the terminal).
86 private _dragScrollAmount: number;
89 * The last time the mousedown event fired, this is used to track double and
92 private _lastMouseDownTime: number;
95 * The last position the mouse was clicked [x, y].
97 private _lastMousePosition: [number, number];
100 * The number of clicks of the mousedown event. This is used to keep track of
101 * double and triple clicks.
103 private _clickCount: number;
106 * The current selection mode.
108 private _activeSelectionMode: SelectionMode;
111 * A setInterval timer that is active while the mouse is down whose callback
112 * scrolls the viewport when necessary.
114 private _dragScrollIntervalTimer: NodeJS.Timer;
117 * The animation frame ID used for refreshing the selection.
119 private _refreshAnimationFrame: number;
121 private _bufferTrimListener: any;
122 private _mouseMoveListener: EventListener;
123 private _mouseDownListener: EventListener;
124 private _mouseUpListener: EventListener;
127 private _terminal: ITerminal,
128 private _buffer: CircularList<any>,
129 private _rowContainer: HTMLElement,
130 private _charMeasure: CharMeasure
133 this._initListeners();
136 this._model = new SelectionModel(_terminal);
137 this._lastMouseDownTime = 0;
138 this._activeSelectionMode = SelectionMode.NORMAL;
142 * Initializes listener variables.
144 private _initListeners() {
145 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
146 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
147 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
148 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
152 * Disables the selection manager. This is useful for when terminal mouse
156 this.clearSelection();
157 this._buffer.off('trim', this._bufferTrimListener);
158 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
162 * Enable the selection manager.
165 // Only adjust the selection on trim, shiftElements is rarely used (only in
166 // reverseIndex) and delete in a splice is only ever used when the same
167 // number of elements was just added. Given this is could actually be
168 // beneficial to leave the selection as is for these cases.
169 this._buffer.on('trim', this._bufferTrimListener);
170 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
174 * Sets the active buffer, this should be called when the alt buffer is
175 * switched in or out.
176 * @param buffer The active buffer.
178 public setBuffer(buffer: CircularList<any>): void {
179 this._buffer = buffer;
183 * Gets whether there is an active text selection.
185 public get hasSelection(): boolean {
186 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
190 * Gets the text currently selected.
192 public get selectionText(): string {
193 const start = this._model.finalSelectionStart;
194 const end = this._model.finalSelectionEnd;
195 if (!start || !end) {
200 const startRowEndCol = start[1] === end[1] ? end[0] : null;
201 let result: string[] = [];
202 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
205 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
206 const bufferLine = this._buffer.get(i);
207 const lineText = this._translateBufferLineToString(bufferLine, true);
208 if (bufferLine.isWrapped) {
209 result[result.length - 1] += lineText;
211 result.push(lineText);
216 if (start[1] !== end[1]) {
217 const bufferLine = this._buffer.get(end[1]);
218 const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
219 if (bufferLine.isWrapped) {
220 result[result.length - 1] += lineText;
222 result.push(lineText);
226 // Format string by replacing non-breaking space chars with regular spaces
227 // and joining the array into a multi-line string.
228 const formattedResult = result.map(line => {
229 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
232 return formattedResult;
236 * Clears the current terminal selection.
238 public clearSelection(): void {
239 this._model.clearSelection();
240 this._removeMouseDownListeners();
245 * Translates a buffer line to a string, with optional start and end columns.
246 * Wide characters will count as two columns in the resulting string. This
247 * function is useful for getting the actual text underneath the raw selection
249 * @param line The line being translated.
250 * @param trimRight Whether to trim whitespace to the right.
251 * @param startCol The column to start at.
252 * @param endCol The column to end at.
254 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
255 // TODO: This function should live in a buffer or buffer line class
259 let widthAdjustedStartCol = startCol;
260 let widthAdjustedEndCol = endCol;
261 for (let i = 0; i < line.length; i++) {
262 const char = line[i];
263 lineString += char[LINE_DATA_CHAR_INDEX];
264 // Adjust start and end cols for wide characters if they affect their
266 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
268 widthAdjustedStartCol--;
271 widthAdjustedEndCol--;
276 // Calculate the final end col by trimming whitespace on the right of the
278 let finalEndCol = widthAdjustedEndCol || line.length;
280 const rightWhitespaceIndex = lineString.search(/\s+$/);
281 if (rightWhitespaceIndex !== -1) {
282 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
284 // Return the empty string if only trimmed whitespace is selected
285 if (finalEndCol <= widthAdjustedStartCol) {
290 return lineString.substring(widthAdjustedStartCol, finalEndCol);
294 * Queues a refresh, redrawing the selection on the next opportunity.
296 public refresh(): void {
297 if (!this._refreshAnimationFrame) {
298 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
303 * Fires the refresh event, causing consumers to pick it up and redraw the
306 private _refresh(): void {
307 this._refreshAnimationFrame = null;
308 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
312 * Selects all text within the terminal.
314 public selectAll(): void {
315 this._model.isSelectAllActive = true;
320 * Handle the buffer being trimmed, adjust the selection position.
321 * @param amount The amount the buffer is being trimmed.
323 private _onTrim(amount: number) {
324 const needsRefresh = this._model.onTrim(amount);
331 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
332 * @param event The mouse event.
334 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
335 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
336 // Convert to 0-based
339 // Convert viewport coords to buffer coords
340 coords[1] += this._terminal.ydisp;
345 * Gets the amount the viewport should be scrolled based on how far out of the
346 * terminal the mouse is.
347 * @param event The mouse event.
349 private _getMouseEventScrollAmount(event: MouseEvent): number {
350 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
351 const terminalHeight = this._terminal.rows * this._charMeasure.height;
352 if (offset >= 0 && offset <= terminalHeight) {
355 if (offset > terminalHeight) {
356 offset -= terminalHeight;
359 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
360 offset /= DRAG_SCROLL_MAX_THRESHOLD;
361 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
365 * Handles te mousedown event, setting up for a new selection.
366 * @param event The mousedown event.
368 private _onMouseDown(event: MouseEvent) {
369 // Only action the primary button
370 if (event.button !== 0) {
374 // Tell the browser not to start a regular selection
375 event.preventDefault();
377 // Reset drag scroll state
378 this._dragScrollAmount = 0;
380 this._setMouseClickCount(event);
382 if (event.shiftKey) {
383 this._onShiftClick(event);
385 if (this._clickCount === 1) {
386 this._onSingleClick(event);
387 } else if (this._clickCount === 2) {
388 this._onDoubleClick(event);
389 } else if (this._clickCount === 3) {
390 this._onTripleClick(event);
394 this._addMouseDownListeners();
399 * Adds listeners when mousedown is triggered.
401 private _addMouseDownListeners(): void {
402 // Listen on the document so that dragging outside of viewport works
403 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
404 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
405 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
409 * Removes the listeners that are registered when mousedown is triggered.
411 private _removeMouseDownListeners(): void {
412 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
413 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
414 clearInterval(this._dragScrollIntervalTimer);
415 this._dragScrollIntervalTimer = null;
419 * Performs a shift click, setting the selection end position to the mouse
421 * @param event The mouse event.
423 private _onShiftClick(event: MouseEvent): void {
424 if (this._model.selectionStart) {
425 this._model.selectionEnd = this._getMouseBufferCoords(event);
430 * Performs a single click, resetting relevant state and setting the selection
432 * @param event The mouse event.
434 private _onSingleClick(event: MouseEvent): void {
435 this._model.selectionStartLength = 0;
436 this._model.isSelectAllActive = false;
437 this._activeSelectionMode = SelectionMode.NORMAL;
438 this._model.selectionStart = this._getMouseBufferCoords(event);
439 if (this._model.selectionStart) {
440 this._model.selectionEnd = null;
441 // If the mouse is over the second half of a wide character, adjust the
442 // selection to cover the whole character
443 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
444 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
445 this._model.selectionStart[0]++;
451 * Performs a double click, selecting the current work.
452 * @param event The mouse event.
454 private _onDoubleClick(event: MouseEvent): void {
455 const coords = this._getMouseBufferCoords(event);
457 this._activeSelectionMode = SelectionMode.WORD;
458 this._selectWordAt(coords);
463 * Performs a triple click, selecting the current line and activating line
465 * @param event The mouse event.
467 private _onTripleClick(event: MouseEvent): void {
468 const coords = this._getMouseBufferCoords(event);
470 this._activeSelectionMode = SelectionMode.LINE;
471 this._selectLineAt(coords[1]);
476 * Sets the number of clicks for the current mousedown event based on the time
477 * and position of the last mousedown event.
478 * @param event The mouse event.
480 private _setMouseClickCount(event: MouseEvent): void {
481 let currentTime = (new Date()).getTime();
482 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
483 this._clickCount = 0;
485 this._lastMouseDownTime = currentTime;
486 this._lastMousePosition = [event.pageX, event.pageY];
491 * Gets the maximum number of pixels in each direction the mouse has moved.
492 * @param event The mouse event.
494 private _distanceFromLastMousePosition(event: MouseEvent): number {
495 const result = Math.max(
496 Math.abs(this._lastMousePosition[0] - event.pageX),
497 Math.abs(this._lastMousePosition[1] - event.pageY));
502 * Handles the mousemove event when the mouse button is down, recording the
503 * end of the selection and refreshing the selection.
504 * @param event The mousemove event.
506 private _onMouseMove(event: MouseEvent) {
507 // Record the previous position so we know whether to redraw the selection
509 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
511 // Set the initial selection end based on the mouse coordinates
512 this._model.selectionEnd = this._getMouseBufferCoords(event);
514 // Select the entire line if line select mode is active.
515 if (this._activeSelectionMode === SelectionMode.LINE) {
516 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
517 this._model.selectionEnd[0] = 0;
519 this._model.selectionEnd[0] = this._terminal.cols;
521 } else if (this._activeSelectionMode === SelectionMode.WORD) {
522 this._selectToWordAt(this._model.selectionEnd);
525 // Determine the amount of scrolling that will happen.
526 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
528 // If the cursor was above or below the viewport, make sure it's at the
529 // start or end of the viewport respectively.
530 if (this._dragScrollAmount > 0) {
531 this._model.selectionEnd[0] = this._terminal.cols - 1;
532 } else if (this._dragScrollAmount < 0) {
533 this._model.selectionEnd[0] = 0;
536 // If the character is a wide character include the cell to the right in the
537 // selection. Note that selections at the very end of the line will never
539 if (this._model.selectionEnd[1] < this._buffer.length) {
540 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
541 if (char && char[2] === 0) {
542 this._model.selectionEnd[0]++;
546 // Only draw here if the selection changes.
547 if (!previousSelectionEnd ||
548 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
549 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
555 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
556 * scrolling of the viewport.
558 private _dragScroll() {
559 if (this._dragScrollAmount) {
560 this._terminal.scrollDisp(this._dragScrollAmount, false);
561 // Re-evaluate selection
562 if (this._dragScrollAmount > 0) {
563 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
565 this._model.selectionEnd = [0, this._terminal.ydisp];
572 * Handles the mouseup event, removing the mousedown listeners.
573 * @param event The mouseup event.
575 private _onMouseUp(event: MouseEvent) {
576 this._removeMouseDownListeners();
580 * Converts a viewport column to the character index on the buffer line, the
581 * latter takes into account wide characters.
582 * @param coords The coordinates to find the 2 index for.
584 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
585 let charIndex = coords[0];
586 for (let i = 0; coords[0] >= i; i++) {
587 const char = bufferLine[i];
588 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
596 * Gets positional information for the word at the coordinated specified.
597 * @param coords The coordinates to get the word at.
599 private _getWordAt(coords: [number, number]): IWordPosition {
600 const bufferLine = this._buffer.get(coords[1]);
601 const line = this._translateBufferLineToString(bufferLine, false);
603 // Get actual index, taking into consideration wide characters
604 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
605 let startIndex = endIndex;
607 // Record offset to be used later
608 const charOffset = coords[0] - startIndex;
609 let leftWideCharCount = 0;
610 let rightWideCharCount = 0;
612 if (line.charAt(startIndex) === ' ') {
613 // Expand until non-whitespace is hit
614 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
617 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
621 // Expand until whitespace is hit. This algorithm works by scanning left
622 // and right from the starting position, keeping both the index format
623 // (line) and the column format (bufferLine) in sync. When a wide
624 // character is hit, it is recorded and the column index is adjusted.
625 let startCol = coords[0];
626 let endCol = coords[0];
627 // Consider the initial position, skip it and increment the wide char
629 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
633 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
634 rightWideCharCount++;
637 // Expand the string in both directions until a space is hit
638 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
639 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
640 // If the next character is a wide char, record it and skip the column
647 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
648 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
649 // If the next character is a wide char, record it and skip the column
650 rightWideCharCount++;
658 const start = startIndex + charOffset - leftWideCharCount;
659 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
660 return {start, length};
664 * Selects the word at the coordinates specified.
665 * @param coords The coordinates to get the word at.
667 protected _selectWordAt(coords: [number, number]): void {
668 const wordPosition = this._getWordAt(coords);
669 this._model.selectionStart = [wordPosition.start, coords[1]];
670 this._model.selectionStartLength = wordPosition.length;
674 * Sets the selection end to the word at the coordinated specified.
675 * @param coords The coordinates to get the word at.
677 private _selectToWordAt(coords: [number, number]): void {
678 const wordPosition = this._getWordAt(coords);
679 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
683 * Gets whether the character is considered a word separator by the select
685 * @param char The character to check.
687 private _isCharWordSeparator(char: string): boolean {
688 return WORD_SEPARATORS.indexOf(char) >= 0;
692 * Selects the line specified.
693 * @param line The line index.
695 protected _selectLineAt(line: number): void {
696 this._model.selectionStart = [0, line];
697 this._model.selectionStartLength = this._terminal.cols;