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';
14 * The number of pixels the mouse needs to be above or below the viewport in
15 * order to scroll at the maximum speed.
17 const DRAG_SCROLL_MAX_THRESHOLD = 50;
20 * The maximum scrolling speed
22 const DRAG_SCROLL_MAX_SPEED = 15;
25 * The number of milliseconds between drag scroll updates.
27 const DRAG_SCROLL_INTERVAL = 50;
30 * The amount of time before mousedown events are no longer stacked to create
31 * double/triple click events.
33 const CLEAR_MOUSE_DOWN_TIME = 400;
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.
39 const CLEAR_MOUSE_DISTANCE = 10;
42 * A string containing all characters that are considered word separated by the
43 * double click to select work logic.
45 const WORD_SEPARATORS = ' ()[]{}\'"';
47 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
49 const LINE_DATA_CHAR_INDEX = 1;
50 const LINE_DATA_WIDTH_INDEX = 2;
52 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
53 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
56 * Represents a position of a word on a line.
58 interface IWordPosition {
64 * A selection mode, this drives how the selection behaves on mouse move.
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.
80 export class SelectionManager extends EventEmitter {
81 protected _model: SelectionModel;
84 * The amount to scroll every drag scroll update (depends on how far the mouse
85 * drag is above or below the terminal).
87 private _dragScrollAmount: number;
90 * The current selection mode.
92 private _activeSelectionMode: SelectionMode;
95 * A setInterval timer that is active while the mouse is down whose callback
96 * scrolls the viewport when necessary.
98 private _dragScrollIntervalTimer: NodeJS.Timer;
101 * The animation frame ID used for refreshing the selection.
103 private _refreshAnimationFrame: number;
105 private _bufferTrimListener: any;
106 private _mouseMoveListener: EventListener;
107 private _mouseDownListener: EventListener;
108 private _mouseUpListener: EventListener;
111 private _terminal: ITerminal,
112 private _buffer: CircularList<any>,
113 private _rowContainer: HTMLElement,
114 private _charMeasure: CharMeasure
117 this._initListeners();
120 this._model = new SelectionModel(_terminal);
121 this._activeSelectionMode = SelectionMode.NORMAL;
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;
163 this.clearSelection();
167 * Gets whether there is an active text selection.
169 public get hasSelection(): boolean {
170 const start = this._model.finalSelectionStart;
171 const end = this._model.finalSelectionEnd;
172 if (!start || !end) {
175 return start[0] !== end[0] || start[1] !== end[1];
179 * Gets the text currently selected.
181 public get selectionText(): string {
182 const start = this._model.finalSelectionStart;
183 const end = this._model.finalSelectionEnd;
184 if (!start || !end) {
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));
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;
200 result.push(lineText);
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;
211 result.push(lineText);
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');
221 return formattedResult;
225 * Clears the current terminal selection.
227 public clearSelection(): void {
228 this._model.clearSelection();
229 this._removeMouseDownListeners();
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
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.
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
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
255 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
257 widthAdjustedStartCol--;
260 widthAdjustedEndCol--;
265 // Calculate the final end col by trimming whitespace on the right of the
267 let finalEndCol = widthAdjustedEndCol || line.length;
269 const rightWhitespaceIndex = lineString.search(/\s+$/);
270 if (rightWhitespaceIndex !== -1) {
271 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
273 // Return the empty string if only trimmed whitespace is selected
274 if (finalEndCol <= widthAdjustedStartCol) {
279 return lineString.substring(widthAdjustedStartCol, finalEndCol);
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.
287 public refresh(isNewSelection?: boolean): void {
288 // Queue the refresh for the renderer
289 if (!this._refreshAnimationFrame) {
290 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
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);
304 * Fires the refresh event, causing consumers to pick it up and redraw the
307 private _refresh(): void {
308 this._refreshAnimationFrame = null;
309 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
313 * Selects all text within the terminal.
315 public selectAll(): void {
316 this._model.isSelectAllActive = true;
321 * Handle the buffer being trimmed, adjust the selection position.
322 * @param amount The amount the buffer is being trimmed.
324 private _onTrim(amount: number) {
325 const needsRefresh = this._model.onTrim(amount);
332 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
333 * @param event The mouse event.
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
340 // Convert viewport coords to buffer coords
341 coords[1] += this._terminal.ydisp;
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.
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) {
356 if (offset > terminalHeight) {
357 offset -= terminalHeight;
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));
366 * Handles te mousedown event, setting up for a new selection.
367 * @param event The mousedown event.
369 private _onMouseDown(event: MouseEvent) {
370 // Only action the primary button
371 if (event.button !== 0) {
375 // Tell the browser not to start a regular selection
376 event.preventDefault();
378 // Reset drag scroll state
379 this._dragScrollAmount = 0;
381 if (event.shiftKey) {
382 this._onShiftClick(event);
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);
393 this._addMouseDownListeners();
398 * Adds listeners when mousedown is triggered.
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);
408 * Removes the listeners that are registered when mousedown is triggered.
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;
418 * Performs a shift click, setting the selection end position to the mouse
420 * @param event The mouse event.
422 private _onShiftClick(event: MouseEvent): void {
423 if (this._model.selectionStart) {
424 this._model.selectionEnd = this._getMouseBufferCoords(event);
429 * Performs a single click, resetting relevant state and setting the selection
431 * @param event The mouse event.
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]++;
450 * Performs a double click, selecting the current work.
451 * @param event The mouse event.
453 private _onDoubleClick(event: MouseEvent): void {
454 const coords = this._getMouseBufferCoords(event);
456 this._activeSelectionMode = SelectionMode.WORD;
457 this._selectWordAt(coords);
462 * Performs a triple click, selecting the current line and activating line
464 * @param event The mouse event.
466 private _onTripleClick(event: MouseEvent): void {
467 const coords = this._getMouseBufferCoords(event);
469 this._activeSelectionMode = SelectionMode.LINE;
470 this._selectLineAt(coords[1]);
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.
479 private _onMouseMove(event: MouseEvent) {
480 // Record the previous position so we know whether to redraw the selection
482 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
484 // Set the initial selection end based on the mouse coordinates
485 this._model.selectionEnd = this._getMouseBufferCoords(event);
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;
492 this._model.selectionEnd[0] = this._terminal.cols;
494 } else if (this._activeSelectionMode === SelectionMode.WORD) {
495 this._selectToWordAt(this._model.selectionEnd);
498 // Determine the amount of scrolling that will happen.
499 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
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;
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
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]++;
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]) {
528 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
529 * scrolling of the viewport.
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];
538 this._model.selectionEnd = [0, this._terminal.ydisp];
545 * Handles the mouseup event, removing the mousedown listeners.
546 * @param event The mouseup event.
548 private _onMouseUp(event: MouseEvent) {
549 this._removeMouseDownListeners();
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.
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) {
569 * Gets positional information for the word at the coordinated specified.
570 * @param coords The coordinates to get the word at.
572 private _getWordAt(coords: [number, number]): IWordPosition {
573 const bufferLine = this._buffer.get(coords[1]);
574 const line = this._translateBufferLineToString(bufferLine, false);
576 // Get actual index, taking into consideration wide characters
577 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
578 let startIndex = endIndex;
580 // Record offset to be used later
581 const charOffset = coords[0] - startIndex;
582 let leftWideCharCount = 0;
583 let rightWideCharCount = 0;
585 if (line.charAt(startIndex) === ' ') {
586 // Expand until non-whitespace is hit
587 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
590 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
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
602 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
606 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
607 rightWideCharCount++;
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
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++;
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};
637 * Selects the word at the coordinates specified.
638 * @param coords The coordinates to get the word at.
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;
647 * Sets the selection end to the word at the coordinated specified.
648 * @param coords The coordinates to get the word at.
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]];
656 * Gets whether the character is considered a word separator by the select
658 * @param char The character to check.
660 private _isCharWordSeparator(char: string): boolean {
661 return WORD_SEPARATORS.indexOf(char) >= 0;
665 * Selects the line specified.
666 * @param line The line index.
668 protected _selectLineAt(line: number): void {
669 this._model.selectionStart = [0, line];
670 this._model.selectionStartLength = this._terminal.cols;