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, ICircularList } 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 * A string containing all characters that are considered word separated by the
32 * double click to select work logic.
34 const WORD_SEPARATORS = ' ()[]{}\'"';
36 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
38 const LINE_DATA_CHAR_INDEX = 1;
39 const LINE_DATA_WIDTH_INDEX = 2;
41 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
42 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
45 * Represents a position of a word on a line.
47 interface IWordPosition {
53 * A selection mode, this drives how the selection behaves on mouse move.
62 * A class that manages the selection of the terminal. With help from
63 * SelectionModel, SelectionManager handles with all logic associated with
64 * dealing with the selection, including handling mouse interaction, wide
65 * characters and fetching the actual text within the selection. Rendering is
66 * not handled by the SelectionManager but a 'refresh' event is fired when the
67 * selection is ready to be redrawn.
69 export class SelectionManager extends EventEmitter {
70 protected _model: SelectionModel;
73 * The amount to scroll every drag scroll update (depends on how far the mouse
74 * drag is above or below the terminal).
76 private _dragScrollAmount: number;
79 * The current selection mode.
81 private _activeSelectionMode: SelectionMode;
84 * A setInterval timer that is active while the mouse is down whose callback
85 * scrolls the viewport when necessary.
87 private _dragScrollIntervalTimer: NodeJS.Timer;
90 * The animation frame ID used for refreshing the selection.
92 private _refreshAnimationFrame: number;
94 private _bufferTrimListener: any;
95 private _mouseMoveListener: EventListener;
96 private _mouseDownListener: EventListener;
97 private _mouseUpListener: EventListener;
100 private _terminal: ITerminal,
101 private _buffer: ICircularList<[number, string, number][]>,
102 private _rowContainer: HTMLElement,
103 private _charMeasure: CharMeasure
106 this._initListeners();
109 this._model = new SelectionModel(_terminal);
110 this._activeSelectionMode = SelectionMode.NORMAL;
114 * Initializes listener variables.
116 private _initListeners() {
117 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
118 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
119 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
120 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
124 * Disables the selection manager. This is useful for when terminal mouse
128 this.clearSelection();
129 this._buffer.off('trim', this._bufferTrimListener);
130 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
134 * Enable the selection manager.
137 // Only adjust the selection on trim, shiftElements is rarely used (only in
138 // reverseIndex) and delete in a splice is only ever used when the same
139 // number of elements was just added. Given this is could actually be
140 // beneficial to leave the selection as is for these cases.
141 this._buffer.on('trim', this._bufferTrimListener);
142 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
146 * Sets the active buffer, this should be called when the alt buffer is
147 * switched in or out.
148 * @param buffer The active buffer.
150 public setBuffer(buffer: ICircularList<[number, string, number][]>): void {
151 this._buffer = buffer;
152 this.clearSelection();
155 public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
156 public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
159 * Gets whether there is an active text selection.
161 public get hasSelection(): boolean {
162 const start = this._model.finalSelectionStart;
163 const end = this._model.finalSelectionEnd;
164 if (!start || !end) {
167 return start[0] !== end[0] || start[1] !== end[1];
171 * Gets the text currently selected.
173 public get selectionText(): string {
174 const start = this._model.finalSelectionStart;
175 const end = this._model.finalSelectionEnd;
176 if (!start || !end) {
181 const startRowEndCol = start[1] === end[1] ? end[0] : null;
182 let result: string[] = [];
183 result.push(translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
186 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
187 const bufferLine = this._buffer.get(i);
188 const lineText = translateBufferLineToString(bufferLine, true);
189 if ((<any>bufferLine).isWrapped) {
190 result[result.length - 1] += lineText;
192 result.push(lineText);
197 if (start[1] !== end[1]) {
198 const bufferLine = this._buffer.get(end[1]);
199 const lineText = translateBufferLineToString(bufferLine, true, 0, end[0]);
200 if ((<any>bufferLine).isWrapped) {
201 result[result.length - 1] += lineText;
203 result.push(lineText);
207 // Format string by replacing non-breaking space chars with regular spaces
208 // and joining the array into a multi-line string.
209 const formattedResult = result.map(line => {
210 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
211 }).join(Browser.isMSWindows ? '\r\n' : '\n');
213 return formattedResult;
217 * Clears the current terminal selection.
219 public clearSelection(): void {
220 this._model.clearSelection();
221 this._removeMouseDownListeners();
226 * Queues a refresh, redrawing the selection on the next opportunity.
227 * @param isNewSelection Whether the selection should be registered as a new
228 * selection on Linux.
230 public refresh(isNewSelection?: boolean): void {
231 // Queue the refresh for the renderer
232 if (!this._refreshAnimationFrame) {
233 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
236 // If the platform is Linux and the refresh call comes from a mouse event,
237 // we need to update the selection for middle click to paste selection.
238 if (Browser.isLinux && isNewSelection) {
239 const selectionText = this.selectionText;
240 if (selectionText.length) {
241 this.emit('newselection', this.selectionText);
247 * Fires the refresh event, causing consumers to pick it up and redraw the
250 private _refresh(): void {
251 this._refreshAnimationFrame = null;
252 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
256 * Selects all text within the terminal.
258 public selectAll(): void {
259 this._model.isSelectAllActive = true;
264 * Handle the buffer being trimmed, adjust the selection position.
265 * @param amount The amount the buffer is being trimmed.
267 private _onTrim(amount: number) {
268 const needsRefresh = this._model.onTrim(amount);
275 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
276 * @param event The mouse event.
278 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
279 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
284 // Convert to 0-based
287 // Convert viewport coords to buffer coords
288 coords[1] += this._terminal.buffer.ydisp;
293 * Gets the amount the viewport should be scrolled based on how far out of the
294 * terminal the mouse is.
295 * @param event The mouse event.
297 private _getMouseEventScrollAmount(event: MouseEvent): number {
298 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
299 const terminalHeight = this._terminal.rows * this._charMeasure.height;
300 if (offset >= 0 && offset <= terminalHeight) {
303 if (offset > terminalHeight) {
304 offset -= terminalHeight;
307 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
308 offset /= DRAG_SCROLL_MAX_THRESHOLD;
309 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
313 * Handles te mousedown event, setting up for a new selection.
314 * @param event The mousedown event.
316 private _onMouseDown(event: MouseEvent) {
317 // Only action the primary button
318 if (event.button !== 0) {
322 // Tell the browser not to start a regular selection
323 event.preventDefault();
325 // Reset drag scroll state
326 this._dragScrollAmount = 0;
328 if (event.shiftKey) {
329 this._onShiftClick(event);
331 if (event.detail === 1) {
332 this._onSingleClick(event);
333 } else if (event.detail === 2) {
334 this._onDoubleClick(event);
335 } else if (event.detail === 3) {
336 this._onTripleClick(event);
340 this._addMouseDownListeners();
345 * Adds listeners when mousedown is triggered.
347 private _addMouseDownListeners(): void {
348 // Listen on the document so that dragging outside of viewport works
349 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
350 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
351 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
355 * Removes the listeners that are registered when mousedown is triggered.
357 private _removeMouseDownListeners(): void {
358 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
359 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
360 clearInterval(this._dragScrollIntervalTimer);
361 this._dragScrollIntervalTimer = null;
365 * Performs a shift click, setting the selection end position to the mouse
367 * @param event The mouse event.
369 private _onShiftClick(event: MouseEvent): void {
370 if (this._model.selectionStart) {
371 this._model.selectionEnd = this._getMouseBufferCoords(event);
376 * Performs a single click, resetting relevant state and setting the selection
378 * @param event The mouse event.
380 private _onSingleClick(event: MouseEvent): void {
381 this._model.selectionStartLength = 0;
382 this._model.isSelectAllActive = false;
383 this._activeSelectionMode = SelectionMode.NORMAL;
385 // Initialize the new selection
386 this._model.selectionStart = this._getMouseBufferCoords(event);
387 if (!this._model.selectionStart) {
390 this._model.selectionEnd = null;
392 // Ensure the line exists
393 const line = this._buffer.get(this._model.selectionStart[1]);
398 // If the mouse is over the second half of a wide character, adjust the
399 // selection to cover the whole character
400 const char = line[this._model.selectionStart[0]];
401 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
402 this._model.selectionStart[0]++;
407 * Performs a double click, selecting the current work.
408 * @param event The mouse event.
410 private _onDoubleClick(event: MouseEvent): void {
411 const coords = this._getMouseBufferCoords(event);
413 this._activeSelectionMode = SelectionMode.WORD;
414 this._selectWordAt(coords);
419 * Performs a triple click, selecting the current line and activating line
421 * @param event The mouse event.
423 private _onTripleClick(event: MouseEvent): void {
424 const coords = this._getMouseBufferCoords(event);
426 this._activeSelectionMode = SelectionMode.LINE;
427 this._selectLineAt(coords[1]);
432 * Handles the mousemove event when the mouse button is down, recording the
433 * end of the selection and refreshing the selection.
434 * @param event The mousemove event.
436 private _onMouseMove(event: MouseEvent) {
437 // Record the previous position so we know whether to redraw the selection
439 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
441 // Set the initial selection end based on the mouse coordinates
442 this._model.selectionEnd = this._getMouseBufferCoords(event);
443 if (!this._model.selectionEnd) {
448 // Select the entire line if line select mode is active.
449 if (this._activeSelectionMode === SelectionMode.LINE) {
450 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
451 this._model.selectionEnd[0] = 0;
453 this._model.selectionEnd[0] = this._terminal.cols;
455 } else if (this._activeSelectionMode === SelectionMode.WORD) {
456 this._selectToWordAt(this._model.selectionEnd);
459 // Determine the amount of scrolling that will happen.
460 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
462 // If the cursor was above or below the viewport, make sure it's at the
463 // start or end of the viewport respectively.
464 if (this._dragScrollAmount > 0) {
465 this._model.selectionEnd[0] = this._terminal.cols - 1;
466 } else if (this._dragScrollAmount < 0) {
467 this._model.selectionEnd[0] = 0;
470 // If the character is a wide character include the cell to the right in the
471 // selection. Note that selections at the very end of the line will never
473 if (this._model.selectionEnd[1] < this._buffer.length) {
474 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
475 if (char && char[2] === 0) {
476 this._model.selectionEnd[0]++;
480 // Only draw here if the selection changes.
481 if (!previousSelectionEnd ||
482 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
483 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
489 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
490 * scrolling of the viewport.
492 private _dragScroll() {
493 if (this._dragScrollAmount) {
494 this._terminal.scrollDisp(this._dragScrollAmount, false);
495 // Re-evaluate selection
496 if (this._dragScrollAmount > 0) {
497 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.buffer.ydisp + this._terminal.rows];
499 this._model.selectionEnd = [0, this._terminal.buffer.ydisp];
506 * Handles the mouseup event, removing the mousedown listeners.
507 * @param event The mouseup event.
509 private _onMouseUp(event: MouseEvent) {
510 this._removeMouseDownListeners();
514 * Converts a viewport column to the character index on the buffer line, the
515 * latter takes into account wide characters.
516 * @param coords The coordinates to find the 2 index for.
518 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
519 let charIndex = coords[0];
520 for (let i = 0; coords[0] >= i; i++) {
521 const char = bufferLine[i];
522 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
529 public setSelection(col: number, row: number, length: number): void {
530 this._model.clearSelection();
531 this._removeMouseDownListeners();
532 this._model.selectionStart = [col, row];
533 this._model.selectionStartLength = length;
538 * Gets positional information for the word at the coordinated specified.
539 * @param coords The coordinates to get the word at.
541 private _getWordAt(coords: [number, number]): IWordPosition {
542 const bufferLine = this._buffer.get(coords[1]);
547 const line = translateBufferLineToString(bufferLine, false);
549 // Get actual index, taking into consideration wide characters
550 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
551 let startIndex = endIndex;
553 // Record offset to be used later
554 const charOffset = coords[0] - startIndex;
555 let leftWideCharCount = 0;
556 let rightWideCharCount = 0;
558 if (line.charAt(startIndex) === ' ') {
559 // Expand until non-whitespace is hit
560 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
563 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
567 // Expand until whitespace is hit. This algorithm works by scanning left
568 // and right from the starting position, keeping both the index format
569 // (line) and the column format (bufferLine) in sync. When a wide
570 // character is hit, it is recorded and the column index is adjusted.
571 let startCol = coords[0];
572 let endCol = coords[0];
573 // Consider the initial position, skip it and increment the wide char
575 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
579 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
580 rightWideCharCount++;
583 // Expand the string in both directions until a space is hit
584 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
585 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
586 // If the next character is a wide char, record it and skip the column
593 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
594 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
595 // If the next character is a wide char, record it and skip the column
596 rightWideCharCount++;
604 const start = startIndex + charOffset - leftWideCharCount;
605 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
606 return {start, length};
610 * Selects the word at the coordinates specified.
611 * @param coords The coordinates to get the word at.
613 protected _selectWordAt(coords: [number, number]): void {
614 const wordPosition = this._getWordAt(coords);
616 this._model.selectionStart = [wordPosition.start, coords[1]];
617 this._model.selectionStartLength = wordPosition.length;
622 * Sets the selection end to the word at the coordinated specified.
623 * @param coords The coordinates to get the word at.
625 private _selectToWordAt(coords: [number, number]): void {
626 const wordPosition = this._getWordAt(coords);
628 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
633 * Gets whether the character is considered a word separator by the select
635 * @param char The character to check.
637 private _isCharWordSeparator(char: string): boolean {
638 return WORD_SEPARATORS.indexOf(char) >= 0;
642 * Selects the line specified.
643 * @param line The line index.
645 protected _selectLineAt(line: number): void {
646 this._model.selectionStart = [0, line];
647 this._model.selectionStartLength = this._terminal.cols;