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 current selection mode.
93 private _activeSelectionMode: SelectionMode;
96 * A setInterval timer that is active while the mouse is down whose callback
97 * scrolls the viewport when necessary.
99 private _dragScrollIntervalTimer: NodeJS.Timer;
102 * The animation frame ID used for refreshing the selection.
104 private _refreshAnimationFrame: number;
106 private _bufferTrimListener: any;
107 private _mouseMoveListener: EventListener;
108 private _mouseDownListener: EventListener;
109 private _mouseUpListener: EventListener;
112 private _terminal: ITerminal,
113 private _buffer: CircularList<any>,
114 private _rowContainer: HTMLElement,
115 private _charMeasure: CharMeasure
118 this._initListeners();
121 this._model = new SelectionModel(_terminal);
122 this._activeSelectionMode = SelectionMode.NORMAL;
126 * Initializes listener variables.
128 private _initListeners() {
129 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
130 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
131 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
132 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
136 * Disables the selection manager. This is useful for when terminal mouse
140 this.clearSelection();
141 this._buffer.off('trim', this._bufferTrimListener);
142 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
146 * Enable the selection manager.
149 // Only adjust the selection on trim, shiftElements is rarely used (only in
150 // reverseIndex) and delete in a splice is only ever used when the same
151 // number of elements was just added. Given this is could actually be
152 // beneficial to leave the selection as is for these cases.
153 this._buffer.on('trim', this._bufferTrimListener);
154 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
158 * Sets the active buffer, this should be called when the alt buffer is
159 * switched in or out.
160 * @param buffer The active buffer.
162 public setBuffer(buffer: CircularList<any>): void {
163 this._buffer = buffer;
164 this.clearSelection();
167 public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
168 public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
171 * Gets whether there is an active text selection.
173 public get hasSelection(): boolean {
174 const start = this._model.finalSelectionStart;
175 const end = this._model.finalSelectionEnd;
176 if (!start || !end) {
179 return start[0] !== end[0] || start[1] !== end[1];
183 * Gets the text currently selected.
185 public get selectionText(): string {
186 const start = this._model.finalSelectionStart;
187 const end = this._model.finalSelectionEnd;
188 if (!start || !end) {
193 const startRowEndCol = start[1] === end[1] ? end[0] : null;
194 let result: string[] = [];
195 result.push(translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
198 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
199 const bufferLine = this._buffer.get(i);
200 const lineText = translateBufferLineToString(bufferLine, true);
201 if (bufferLine.isWrapped) {
202 result[result.length - 1] += lineText;
204 result.push(lineText);
209 if (start[1] !== end[1]) {
210 const bufferLine = this._buffer.get(end[1]);
211 const lineText = translateBufferLineToString(bufferLine, true, 0, end[0]);
212 if (bufferLine.isWrapped) {
213 result[result.length - 1] += lineText;
215 result.push(lineText);
219 // Format string by replacing non-breaking space chars with regular spaces
220 // and joining the array into a multi-line string.
221 const formattedResult = result.map(line => {
222 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
223 }).join(Browser.isMSWindows ? '\r\n' : '\n');
225 return formattedResult;
229 * Clears the current terminal selection.
231 public clearSelection(): void {
232 this._model.clearSelection();
233 this._removeMouseDownListeners();
238 * Queues a refresh, redrawing the selection on the next opportunity.
239 * @param isNewSelection Whether the selection should be registered as a new
240 * selection on Linux.
242 public refresh(isNewSelection?: boolean): void {
243 // Queue the refresh for the renderer
244 if (!this._refreshAnimationFrame) {
245 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
248 // If the platform is Linux and the refresh call comes from a mouse event,
249 // we need to update the selection for middle click to paste selection.
250 if (Browser.isLinux && isNewSelection) {
251 const selectionText = this.selectionText;
252 if (selectionText.length) {
253 this.emit('newselection', this.selectionText);
259 * Fires the refresh event, causing consumers to pick it up and redraw the
262 private _refresh(): void {
263 this._refreshAnimationFrame = null;
264 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
268 * Selects all text within the terminal.
270 public selectAll(): void {
271 this._model.isSelectAllActive = true;
276 * Handle the buffer being trimmed, adjust the selection position.
277 * @param amount The amount the buffer is being trimmed.
279 private _onTrim(amount: number) {
280 const needsRefresh = this._model.onTrim(amount);
287 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
288 * @param event The mouse event.
290 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
291 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows, true);
292 // Convert to 0-based
295 // Convert viewport coords to buffer coords
296 coords[1] += this._terminal.ydisp;
301 * Gets the amount the viewport should be scrolled based on how far out of the
302 * terminal the mouse is.
303 * @param event The mouse event.
305 private _getMouseEventScrollAmount(event: MouseEvent): number {
306 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
307 const terminalHeight = this._terminal.rows * this._charMeasure.height;
308 if (offset >= 0 && offset <= terminalHeight) {
311 if (offset > terminalHeight) {
312 offset -= terminalHeight;
315 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
316 offset /= DRAG_SCROLL_MAX_THRESHOLD;
317 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
321 * Handles te mousedown event, setting up for a new selection.
322 * @param event The mousedown event.
324 private _onMouseDown(event: MouseEvent) {
325 // Only action the primary button
326 if (event.button !== 0) {
330 // Tell the browser not to start a regular selection
331 event.preventDefault();
333 // Reset drag scroll state
334 this._dragScrollAmount = 0;
336 if (event.shiftKey) {
337 this._onShiftClick(event);
339 if (event.detail === 1) {
340 this._onSingleClick(event);
341 } else if (event.detail === 2) {
342 this._onDoubleClick(event);
343 } else if (event.detail === 3) {
344 this._onTripleClick(event);
348 this._addMouseDownListeners();
353 * Adds listeners when mousedown is triggered.
355 private _addMouseDownListeners(): void {
356 // Listen on the document so that dragging outside of viewport works
357 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
358 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
359 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
363 * Removes the listeners that are registered when mousedown is triggered.
365 private _removeMouseDownListeners(): void {
366 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
367 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
368 clearInterval(this._dragScrollIntervalTimer);
369 this._dragScrollIntervalTimer = null;
373 * Performs a shift click, setting the selection end position to the mouse
375 * @param event The mouse event.
377 private _onShiftClick(event: MouseEvent): void {
378 if (this._model.selectionStart) {
379 this._model.selectionEnd = this._getMouseBufferCoords(event);
384 * Performs a single click, resetting relevant state and setting the selection
386 * @param event The mouse event.
388 private _onSingleClick(event: MouseEvent): void {
389 this._model.selectionStartLength = 0;
390 this._model.isSelectAllActive = false;
391 this._activeSelectionMode = SelectionMode.NORMAL;
392 this._model.selectionStart = this._getMouseBufferCoords(event);
393 if (this._model.selectionStart) {
394 this._model.selectionEnd = null;
395 // If the mouse is over the second half of a wide character, adjust the
396 // selection to cover the whole character
397 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
398 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
399 this._model.selectionStart[0]++;
405 * Performs a double click, selecting the current work.
406 * @param event The mouse event.
408 private _onDoubleClick(event: MouseEvent): void {
409 const coords = this._getMouseBufferCoords(event);
411 this._activeSelectionMode = SelectionMode.WORD;
412 this._selectWordAt(coords);
417 * Performs a triple click, selecting the current line and activating line
419 * @param event The mouse event.
421 private _onTripleClick(event: MouseEvent): void {
422 const coords = this._getMouseBufferCoords(event);
424 this._activeSelectionMode = SelectionMode.LINE;
425 this._selectLineAt(coords[1]);
430 * Handles the mousemove event when the mouse button is down, recording the
431 * end of the selection and refreshing the selection.
432 * @param event The mousemove event.
434 private _onMouseMove(event: MouseEvent) {
435 // Record the previous position so we know whether to redraw the selection
437 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
439 // Set the initial selection end based on the mouse coordinates
440 this._model.selectionEnd = this._getMouseBufferCoords(event);
442 // Select the entire line if line select mode is active.
443 if (this._activeSelectionMode === SelectionMode.LINE) {
444 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
445 this._model.selectionEnd[0] = 0;
447 this._model.selectionEnd[0] = this._terminal.cols;
449 } else if (this._activeSelectionMode === SelectionMode.WORD) {
450 this._selectToWordAt(this._model.selectionEnd);
453 // Determine the amount of scrolling that will happen.
454 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
456 // If the cursor was above or below the viewport, make sure it's at the
457 // start or end of the viewport respectively.
458 if (this._dragScrollAmount > 0) {
459 this._model.selectionEnd[0] = this._terminal.cols - 1;
460 } else if (this._dragScrollAmount < 0) {
461 this._model.selectionEnd[0] = 0;
464 // If the character is a wide character include the cell to the right in the
465 // selection. Note that selections at the very end of the line will never
467 if (this._model.selectionEnd[1] < this._buffer.length) {
468 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
469 if (char && char[2] === 0) {
470 this._model.selectionEnd[0]++;
474 // Only draw here if the selection changes.
475 if (!previousSelectionEnd ||
476 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
477 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
483 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
484 * scrolling of the viewport.
486 private _dragScroll() {
487 if (this._dragScrollAmount) {
488 this._terminal.scrollDisp(this._dragScrollAmount, false);
489 // Re-evaluate selection
490 if (this._dragScrollAmount > 0) {
491 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
493 this._model.selectionEnd = [0, this._terminal.ydisp];
500 * Handles the mouseup event, removing the mousedown listeners.
501 * @param event The mouseup event.
503 private _onMouseUp(event: MouseEvent) {
504 this._removeMouseDownListeners();
508 * Converts a viewport column to the character index on the buffer line, the
509 * latter takes into account wide characters.
510 * @param coords The coordinates to find the 2 index for.
512 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
513 let charIndex = coords[0];
514 for (let i = 0; coords[0] >= i; i++) {
515 const char = bufferLine[i];
516 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
523 public setSelection(col: number, row: number, length: number): void {
524 this._model.clearSelection();
525 this._removeMouseDownListeners();
526 this._model.selectionStart = [col, row];
527 this._model.selectionStartLength = length;
532 * Gets positional information for the word at the coordinated specified.
533 * @param coords The coordinates to get the word at.
535 private _getWordAt(coords: [number, number]): IWordPosition {
536 const bufferLine = this._buffer.get(coords[1]);
537 const line = translateBufferLineToString(bufferLine, false);
539 // Get actual index, taking into consideration wide characters
540 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
541 let startIndex = endIndex;
543 // Record offset to be used later
544 const charOffset = coords[0] - startIndex;
545 let leftWideCharCount = 0;
546 let rightWideCharCount = 0;
548 if (line.charAt(startIndex) === ' ') {
549 // Expand until non-whitespace is hit
550 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
553 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
557 // Expand until whitespace is hit. This algorithm works by scanning left
558 // and right from the starting position, keeping both the index format
559 // (line) and the column format (bufferLine) in sync. When a wide
560 // character is hit, it is recorded and the column index is adjusted.
561 let startCol = coords[0];
562 let endCol = coords[0];
563 // Consider the initial position, skip it and increment the wide char
565 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
569 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
570 rightWideCharCount++;
573 // Expand the string in both directions until a space is hit
574 while (startIndex > 0 && !this._isCharWordSeparator(line.charAt(startIndex - 1))) {
575 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
576 // If the next character is a wide char, record it and skip the column
583 while (endIndex + 1 < line.length && !this._isCharWordSeparator(line.charAt(endIndex + 1))) {
584 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
585 // If the next character is a wide char, record it and skip the column
586 rightWideCharCount++;
594 const start = startIndex + charOffset - leftWideCharCount;
595 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
596 return {start, length};
600 * Selects the word at the coordinates specified.
601 * @param coords The coordinates to get the word at.
603 protected _selectWordAt(coords: [number, number]): void {
604 const wordPosition = this._getWordAt(coords);
605 this._model.selectionStart = [wordPosition.start, coords[1]];
606 this._model.selectionStartLength = wordPosition.length;
610 * Sets the selection end to the word at the coordinated specified.
611 * @param coords The coordinates to get the word at.
613 private _selectToWordAt(coords: [number, number]): void {
614 const wordPosition = this._getWordAt(coords);
615 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
619 * Gets whether the character is considered a word separator by the select
621 * @param char The character to check.
623 private _isCharWordSeparator(char: string): boolean {
624 return WORD_SEPARATORS.indexOf(char) >= 0;
628 * Selects the line specified.
629 * @param line The line index.
631 protected _selectLineAt(line: number): void {
632 this._model.selectionStart = [0, line];
633 this._model.selectionStartLength = this._terminal.cols;