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 import { translateBufferLineToString } from './utils/BufferLine';
15 * The number of pixels the mouse needs to be above or below the viewport in
16 * order to scroll at the maximum speed.
18 const DRAG_SCROLL_MAX_THRESHOLD = 50;
21 * The maximum scrolling speed
23 const DRAG_SCROLL_MAX_SPEED = 15;
26 * The number of milliseconds between drag scroll updates.
28 const DRAG_SCROLL_INTERVAL = 50;
31 * The amount of time before mousedown events are no longer stacked to create
32 * double/triple click events.
34 const CLEAR_MOUSE_DOWN_TIME = 400;
37 * The number of pixels in each direction that the mouse must move before
38 * mousedown events are no longer stacked to create double/triple click events.
40 const CLEAR_MOUSE_DISTANCE = 10;
43 * A string containing all characters that are considered word separated by the
44 * double click to select work logic.
46 const WORD_SEPARATORS = ' ()[]{}\'"';
48 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
50 const LINE_DATA_CHAR_INDEX = 1;
51 const LINE_DATA_WIDTH_INDEX = 2;
53 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
54 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
57 * Represents a position of a word on a line.
59 interface IWordPosition {
65 * A selection mode, this drives how the selection behaves on mouse move.
74 * A class that manages the selection of the terminal. With help from
75 * SelectionModel, SelectionManager handles with all logic associated with
76 * dealing with the selection, including handling mouse interaction, wide
77 * characters and fetching the actual text within the selection. Rendering is
78 * not handled by the SelectionManager but a 'refresh' event is fired when the
79 * selection is ready to be redrawn.
81 export class SelectionManager extends EventEmitter {
82 protected _model: SelectionModel;
85 * The amount to scroll every drag scroll update (depends on how far the mouse
86 * drag is above or below the terminal).
88 private _dragScrollAmount: number;
91 * The last time the mousedown event fired, this is used to track double and
94 private _lastMouseDownTime: number;
97 * The last position the mouse was clicked [x, y].
99 private _lastMousePosition: [number, number];
102 * The number of clicks of the mousedown event. This is used to keep track of
103 * double and triple clicks.
105 private _clickCount: number;
108 * The current selection mode.
110 private _activeSelectionMode: SelectionMode;
113 * A setInterval timer that is active while the mouse is down whose callback
114 * scrolls the viewport when necessary.
116 private _dragScrollIntervalTimer: NodeJS.Timer;
119 * The animation frame ID used for refreshing the selection.
121 private _refreshAnimationFrame: number;
123 private _bufferTrimListener: any;
124 private _mouseMoveListener: EventListener;
125 private _mouseDownListener: EventListener;
126 private _mouseUpListener: EventListener;
129 private _terminal: ITerminal,
130 private _buffer: CircularList<any>,
131 private _rowContainer: HTMLElement,
132 private _charMeasure: CharMeasure
135 this._initListeners();
138 this._model = new SelectionModel(_terminal);
139 this._lastMouseDownTime = 0;
140 this._activeSelectionMode = SelectionMode.NORMAL;
144 * Initializes listener variables.
146 private _initListeners() {
147 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
148 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
149 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
150 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
154 * Disables the selection manager. This is useful for when terminal mouse
158 this.clearSelection();
159 this._buffer.off('trim', this._bufferTrimListener);
160 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
164 * Enable the selection manager.
167 // Only adjust the selection on trim, shiftElements is rarely used (only in
168 // reverseIndex) and delete in a splice is only ever used when the same
169 // number of elements was just added. Given this is could actually be
170 // beneficial to leave the selection as is for these cases.
171 this._buffer.on('trim', this._bufferTrimListener);
172 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
176 * Sets the active buffer, this should be called when the alt buffer is
177 * switched in or out.
178 * @param buffer The active buffer.
180 public setBuffer(buffer: CircularList<any>): void {
181 this._buffer = buffer;
182 this.clearSelection();
185 public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
186 public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
189 * Gets whether there is an active text selection.
191 public get hasSelection(): boolean {
192 const start = this._model.finalSelectionStart;
193 const end = this._model.finalSelectionEnd;
194 if (!start || !end) {
197 return start[0] !== end[0] || start[1] !== end[1];
201 * Gets the text currently selected.
203 public get selectionText(): string {
204 const start = this._model.finalSelectionStart;
205 const end = this._model.finalSelectionEnd;
206 if (!start || !end) {
211 const startRowEndCol = start[1] === end[1] ? end[0] : null;
212 let result: string[] = [];
213 result.push(translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
216 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
217 const bufferLine = this._buffer.get(i);
218 const lineText = translateBufferLineToString(bufferLine, true);
219 if (bufferLine.isWrapped) {
220 result[result.length - 1] += lineText;
222 result.push(lineText);
227 if (start[1] !== end[1]) {
228 const bufferLine = this._buffer.get(end[1]);
229 const lineText = translateBufferLineToString(bufferLine, true, 0, end[0]);
230 if (bufferLine.isWrapped) {
231 result[result.length - 1] += lineText;
233 result.push(lineText);
237 // Format string by replacing non-breaking space chars with regular spaces
238 // and joining the array into a multi-line string.
239 const formattedResult = result.map(line => {
240 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
241 }).join(Browser.isMSWindows ? '\r\n' : '\n');
243 return formattedResult;
247 * Clears the current terminal selection.
249 public clearSelection(): void {
250 this._model.clearSelection();
251 this._removeMouseDownListeners();
256 * Queues a refresh, redrawing the selection on the next opportunity.
257 * @param isNewSelection Whether the selection should be registered as a new
258 * selection on Linux.
260 public refresh(isNewSelection?: boolean): void {
261 // Queue the refresh for the renderer
262 if (!this._refreshAnimationFrame) {
263 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
266 // If the platform is Linux and the refresh call comes from a mouse event,
267 // we need to update the selection for middle click to paste selection.
268 if (Browser.isLinux && isNewSelection) {
269 const selectionText = this.selectionText;
270 if (selectionText.length) {
271 this.emit('newselection', this.selectionText);
277 * Fires the refresh event, causing consumers to pick it up and redraw the
280 private _refresh(): void {
281 this._refreshAnimationFrame = null;
282 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
286 * Selects all text within the terminal.
288 public selectAll(): void {
289 this._model.isSelectAllActive = true;
294 * Handle the buffer being trimmed, adjust the selection position.
295 * @param amount The amount the buffer is being trimmed.
297 private _onTrim(amount: number) {
298 const needsRefresh = this._model.onTrim(amount);
305 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
306 * @param event The mouse event.
308 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
309 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
310 // Convert to 0-based
313 // Convert viewport coords to buffer coords
314 coords[1] += this._terminal.ydisp;
319 * Gets the amount the viewport should be scrolled based on how far out of the
320 * terminal the mouse is.
321 * @param event The mouse event.
323 private _getMouseEventScrollAmount(event: MouseEvent): number {
324 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
325 const terminalHeight = this._terminal.rows * this._charMeasure.height;
326 if (offset >= 0 && offset <= terminalHeight) {
329 if (offset > terminalHeight) {
330 offset -= terminalHeight;
333 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
334 offset /= DRAG_SCROLL_MAX_THRESHOLD;
335 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
339 * Handles te mousedown event, setting up for a new selection.
340 * @param event The mousedown event.
342 private _onMouseDown(event: MouseEvent) {
343 // Only action the primary button
344 if (event.button !== 0) {
348 // Tell the browser not to start a regular selection
349 event.preventDefault();
351 // Reset drag scroll state
352 this._dragScrollAmount = 0;
354 this._setMouseClickCount(event);
356 if (event.shiftKey) {
357 this._onShiftClick(event);
359 if (this._clickCount === 1) {
360 this._onSingleClick(event);
361 } else if (this._clickCount === 2) {
362 this._onDoubleClick(event);
363 } else if (this._clickCount === 3) {
364 this._onTripleClick(event);
368 this._addMouseDownListeners();
373 * Adds listeners when mousedown is triggered.
375 private _addMouseDownListeners(): void {
376 // Listen on the document so that dragging outside of viewport works
377 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
378 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
379 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
383 * Removes the listeners that are registered when mousedown is triggered.
385 private _removeMouseDownListeners(): void {
386 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
387 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
388 clearInterval(this._dragScrollIntervalTimer);
389 this._dragScrollIntervalTimer = null;
393 * Performs a shift click, setting the selection end position to the mouse
395 * @param event The mouse event.
397 private _onShiftClick(event: MouseEvent): void {
398 if (this._model.selectionStart) {
399 this._model.selectionEnd = this._getMouseBufferCoords(event);
404 * Performs a single click, resetting relevant state and setting the selection
406 * @param event The mouse event.
408 private _onSingleClick(event: MouseEvent): void {
409 this._model.selectionStartLength = 0;
410 this._model.isSelectAllActive = false;
411 this._activeSelectionMode = SelectionMode.NORMAL;
412 this._model.selectionStart = this._getMouseBufferCoords(event);
413 if (this._model.selectionStart) {
414 this._model.selectionEnd = null;
415 // If the mouse is over the second half of a wide character, adjust the
416 // selection to cover the whole character
417 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
418 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
419 this._model.selectionStart[0]++;
425 * Performs a double click, selecting the current work.
426 * @param event The mouse event.
428 private _onDoubleClick(event: MouseEvent): void {
429 const coords = this._getMouseBufferCoords(event);
431 this._activeSelectionMode = SelectionMode.WORD;
432 this._selectWordAt(coords);
437 * Performs a triple click, selecting the current line and activating line
439 * @param event The mouse event.
441 private _onTripleClick(event: MouseEvent): void {
442 const coords = this._getMouseBufferCoords(event);
444 this._activeSelectionMode = SelectionMode.LINE;
445 this._selectLineAt(coords[1]);
450 * Sets the number of clicks for the current mousedown event based on the time
451 * and position of the last mousedown event.
452 * @param event The mouse event.
454 private _setMouseClickCount(event: MouseEvent): void {
455 let currentTime = (new Date()).getTime();
456 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
457 this._clickCount = 0;
459 this._lastMouseDownTime = currentTime;
460 this._lastMousePosition = [event.pageX, event.pageY];
465 * Gets the maximum number of pixels in each direction the mouse has moved.
466 * @param event The mouse event.
468 private _distanceFromLastMousePosition(event: MouseEvent): number {
469 const result = Math.max(
470 Math.abs(this._lastMousePosition[0] - event.pageX),
471 Math.abs(this._lastMousePosition[1] - event.pageY));
476 * Handles the mousemove event when the mouse button is down, recording the
477 * end of the selection and refreshing the selection.
478 * @param event The mousemove event.
480 private _onMouseMove(event: MouseEvent) {
481 // Record the previous position so we know whether to redraw the selection
483 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
485 // Set the initial selection end based on the mouse coordinates
486 this._model.selectionEnd = this._getMouseBufferCoords(event);
488 // Select the entire line if line select mode is active.
489 if (this._activeSelectionMode === SelectionMode.LINE) {
490 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
491 this._model.selectionEnd[0] = 0;
493 this._model.selectionEnd[0] = this._terminal.cols;
495 } else if (this._activeSelectionMode === SelectionMode.WORD) {
496 this._selectToWordAt(this._model.selectionEnd);
499 // Determine the amount of scrolling that will happen.
500 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
502 // If the cursor was above or below the viewport, make sure it's at the
503 // start or end of the viewport respectively.
504 if (this._dragScrollAmount > 0) {
505 this._model.selectionEnd[0] = this._terminal.cols - 1;
506 } else if (this._dragScrollAmount < 0) {
507 this._model.selectionEnd[0] = 0;
510 // If the character is a wide character include the cell to the right in the
511 // selection. Note that selections at the very end of the line will never
513 if (this._model.selectionEnd[1] < this._buffer.length) {
514 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
515 if (char && char[2] === 0) {
516 this._model.selectionEnd[0]++;
520 // Only draw here if the selection changes.
521 if (!previousSelectionEnd ||
522 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
523 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
529 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
530 * scrolling of the viewport.
532 private _dragScroll() {
533 if (this._dragScrollAmount) {
534 this._terminal.scrollDisp(this._dragScrollAmount, false);
535 // Re-evaluate selection
536 if (this._dragScrollAmount > 0) {
537 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
539 this._model.selectionEnd = [0, this._terminal.ydisp];
546 * Handles the mouseup event, removing the mousedown listeners.
547 * @param event The mouseup event.
549 private _onMouseUp(event: MouseEvent) {
550 this._removeMouseDownListeners();
554 * Converts a viewport column to the character index on the buffer line, the
555 * latter takes into account wide characters.
556 * @param coords The coordinates to find the 2 index for.
558 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
559 let charIndex = coords[0];
560 for (let i = 0; coords[0] >= i; i++) {
561 const char = bufferLine[i];
562 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
569 public setSelection(col: number, row: number, length: number): void {
570 this._model.clearSelection();
571 this._removeMouseDownListeners();
572 this._model.selectionStart = [col, row];
573 this._model.selectionStartLength = length;
578 * Gets positional information for the word at the coordinated specified.
579 * @param coords The coordinates to get the word at.
581 private _getWordAt(coords: [number, number]): IWordPosition {
582 const bufferLine = this._buffer.get(coords[1]);
583 const line = translateBufferLineToString(bufferLine, false);
585 // Get actual index, taking into consideration wide characters
586 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
587 let startIndex = endIndex;
589 // Record offset to be used later
590 const charOffset = coords[0] - startIndex;
591 let leftWideCharCount = 0;
592 let rightWideCharCount = 0;
594 if (line.charAt(startIndex) === ' ') {
595 // Expand until non-whitespace is hit
596 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
599 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
603 // Expand until whitespace is hit. This algorithm works by scanning left
604 // and right from the starting position, keeping both the index format
605 // (line) and the column format (bufferLine) in sync. When a wide
606 // character is hit, it is recorded and the column index is adjusted.
607 let startCol = coords[0];
608 let endCol = coords[0];
609 // Consider the initial position, skip it and increment the wide char
611 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
615 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
616 rightWideCharCount++;
619 // Expand the string in both directions until a space is hit
620 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
621 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
622 // If the next character is a wide char, record it and skip the column
629 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
630 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
631 // If the next character is a wide char, record it and skip the column
632 rightWideCharCount++;
640 const start = startIndex + charOffset - leftWideCharCount;
641 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
642 return {start, length};
646 * Selects the word at the coordinates specified.
647 * @param coords The coordinates to get the word at.
649 protected _selectWordAt(coords: [number, number]): void {
650 const wordPosition = this._getWordAt(coords);
651 this._model.selectionStart = [wordPosition.start, coords[1]];
652 this._model.selectionStartLength = wordPosition.length;
656 * Sets the selection end to the word at the coordinated specified.
657 * @param coords The coordinates to get the word at.
659 private _selectToWordAt(coords: [number, number]): void {
660 const wordPosition = this._getWordAt(coords);
661 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
665 * Gets whether the character is considered a word separator by the select
667 * @param char The character to check.
669 private _isCharWordSeparator(char: string): boolean {
670 return WORD_SEPARATORS.indexOf(char) >= 0;
674 * Selects the line specified.
675 * @param line The line index.
677 protected _selectLineAt(line: number): void {
678 this._model.selectionStart = [0, line];
679 this._model.selectionStartLength = this._terminal.cols;