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;
40 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
42 const LINE_DATA_CHAR_INDEX = 1;
43 const LINE_DATA_WIDTH_INDEX = 2;
45 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
46 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
49 * Represents a position of a word on a line.
51 interface IWordPosition {
57 * A selection mode, this drives how the selection behaves on mouse move.
66 * A class that manages the selection of the terminal. With help from
67 * SelectionModel, SelectionManager handles with all logic associated with
68 * dealing with the selection, including handling mouse interaction, wide
69 * characters and fetching the actual text within the selection. Rendering is
70 * not handled by the SelectionManager but a 'refresh' event is fired when the
71 * selection is ready to be redrawn.
73 export class SelectionManager extends EventEmitter {
74 protected _model: SelectionModel;
77 * The amount to scroll every drag scroll update (depends on how far the mouse
78 * drag is above or below the terminal).
80 private _dragScrollAmount: number;
83 * The last time the mousedown event fired, this is used to track double and
86 private _lastMouseDownTime: number;
89 * The last position the mouse was clicked [x, y].
91 private _lastMousePosition: [number, number];
94 * The number of clicks of the mousedown event. This is used to keep track of
95 * double and triple clicks.
97 private _clickCount: number;
100 * The current selection mode.
102 private _activeSelectionMode: SelectionMode;
105 * A setInterval timer that is active while the mouse is down whose callback
106 * scrolls the viewport when necessary.
108 private _dragScrollIntervalTimer: NodeJS.Timer;
111 * The animation frame ID used for refreshing the selection.
113 private _refreshAnimationFrame: number;
115 private _bufferTrimListener: any;
116 private _mouseMoveListener: EventListener;
117 private _mouseDownListener: EventListener;
118 private _mouseUpListener: EventListener;
121 private _terminal: ITerminal,
122 private _buffer: CircularList<any>,
123 private _rowContainer: HTMLElement,
124 private _charMeasure: CharMeasure
127 this._initListeners();
130 this._model = new SelectionModel(_terminal);
131 this._lastMouseDownTime = 0;
132 this._activeSelectionMode = SelectionMode.NORMAL;
136 * Initializes listener variables.
138 private _initListeners() {
139 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
140 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
141 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
142 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
146 * Disables the selection manager. This is useful for when terminal mouse
150 this.clearSelection();
151 this._buffer.off('trim', this._bufferTrimListener);
152 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
156 * Enable the selection manager.
159 // Only adjust the selection on trim, shiftElements is rarely used (only in
160 // reverseIndex) and delete in a splice is only ever used when the same
161 // number of elements was just added. Given this is could actually be
162 // beneficial to leave the selection as is for these cases.
163 this._buffer.on('trim', this._bufferTrimListener);
164 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
168 * Sets the active buffer, this should be called when the alt buffer is
169 * switched in or out.
170 * @param buffer The active buffer.
172 public setBuffer(buffer: CircularList<any>): void {
173 this._buffer = buffer;
177 * Gets whether there is an active text selection.
179 public get hasSelection(): boolean {
180 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
184 * Gets the text currently selected.
186 public get selectionText(): string {
187 const start = this._model.finalSelectionStart;
188 const end = this._model.finalSelectionEnd;
189 if (!start || !end) {
194 const startRowEndCol = start[1] === end[1] ? end[0] : null;
195 let result: string[] = [];
196 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
199 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
200 const bufferLine = this._buffer.get(i);
201 const lineText = this._translateBufferLineToString(bufferLine, true);
202 if (bufferLine.isWrapped) {
203 result[result.length - 1] += lineText;
205 result.push(lineText);
210 if (start[1] !== end[1]) {
211 const bufferLine = this._buffer.get(end[1]);
212 const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
213 if (bufferLine.isWrapped) {
214 result[result.length - 1] += lineText;
216 result.push(lineText);
220 // Format string by replacing non-breaking space chars with regular spaces
221 // and joining the array into a multi-line string.
222 const formattedResult = result.map(line => {
223 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
226 return formattedResult;
230 * Clears the current terminal selection.
232 public clearSelection(): void {
233 this._model.clearSelection();
234 this._removeMouseDownListeners();
239 * Translates a buffer line to a string, with optional start and end columns.
240 * Wide characters will count as two columns in the resulting string. This
241 * function is useful for getting the actual text underneath the raw selection
243 * @param line The line being translated.
244 * @param trimRight Whether to trim whitespace to the right.
245 * @param startCol The column to start at.
246 * @param endCol The column to end at.
248 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
249 // TODO: This function should live in a buffer or buffer line class
253 let widthAdjustedStartCol = startCol;
254 let widthAdjustedEndCol = endCol;
255 for (let i = 0; i < line.length; i++) {
256 const char = line[i];
257 lineString += char[LINE_DATA_CHAR_INDEX];
258 // Adjust start and end cols for wide characters if they affect their
260 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
262 widthAdjustedStartCol--;
265 widthAdjustedEndCol--;
270 // Calculate the final end col by trimming whitespace on the right of the
272 let finalEndCol = widthAdjustedEndCol || line.length;
274 const rightWhitespaceIndex = lineString.search(/\s+$/);
275 if (rightWhitespaceIndex !== -1) {
276 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
278 // Return the empty string if only trimmed whitespace is selected
279 if (finalEndCol <= widthAdjustedStartCol) {
284 return lineString.substring(widthAdjustedStartCol, finalEndCol);
288 * Queues a refresh, redrawing the selection on the next opportunity.
290 public refresh(): void {
291 if (!this._refreshAnimationFrame) {
292 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
297 * Fires the refresh event, causing consumers to pick it up and redraw the
300 private _refresh(): void {
301 this._refreshAnimationFrame = null;
302 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
306 * Selects all text within the terminal.
308 public selectAll(): void {
309 this._model.isSelectAllActive = true;
314 * Handle the buffer being trimmed, adjust the selection position.
315 * @param amount The amount the buffer is being trimmed.
317 private _onTrim(amount: number) {
318 const needsRefresh = this._model.onTrim(amount);
325 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
326 * @param event The mouse event.
328 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
329 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
330 // Convert to 0-based
333 // Convert viewport coords to buffer coords
334 coords[1] += this._terminal.ydisp;
339 * Gets the amount the viewport should be scrolled based on how far out of the
340 * terminal the mouse is.
341 * @param event The mouse event.
343 private _getMouseEventScrollAmount(event: MouseEvent): number {
344 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
345 const terminalHeight = this._terminal.rows * this._charMeasure.height;
346 if (offset >= 0 && offset <= terminalHeight) {
349 if (offset > terminalHeight) {
350 offset -= terminalHeight;
353 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
354 offset /= DRAG_SCROLL_MAX_THRESHOLD;
355 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
359 * Handles te mousedown event, setting up for a new selection.
360 * @param event The mousedown event.
362 private _onMouseDown(event: MouseEvent) {
363 // Only action the primary button
364 if (event.button !== 0) {
368 // Tell the browser not to start a regular selection
369 event.preventDefault();
371 // Reset drag scroll state
372 this._dragScrollAmount = 0;
374 this._setMouseClickCount(event);
376 if (event.shiftKey) {
377 this._onShiftClick(event);
379 if (this._clickCount === 1) {
380 this._onSingleClick(event);
381 } else if (this._clickCount === 2) {
382 this._onDoubleClick(event);
383 } else if (this._clickCount === 3) {
384 this._onTripleClick(event);
388 this._addMouseDownListeners();
393 * Adds listeners when mousedown is triggered.
395 private _addMouseDownListeners(): void {
396 // Listen on the document so that dragging outside of viewport works
397 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
398 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
399 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
403 * Removes the listeners that are registered when mousedown is triggered.
405 private _removeMouseDownListeners(): void {
406 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
407 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
408 clearInterval(this._dragScrollIntervalTimer);
409 this._dragScrollIntervalTimer = null;
413 * Performs a shift click, setting the selection end position to the mouse
415 * @param event The mouse event.
417 private _onShiftClick(event: MouseEvent): void {
418 if (this._model.selectionStart) {
419 this._model.selectionEnd = this._getMouseBufferCoords(event);
424 * Performs a single click, resetting relevant state and setting the selection
426 * @param event The mouse event.
428 private _onSingleClick(event: MouseEvent): void {
429 this._model.selectionStartLength = 0;
430 this._model.isSelectAllActive = false;
431 this._activeSelectionMode = SelectionMode.NORMAL;
432 this._model.selectionStart = this._getMouseBufferCoords(event);
433 if (this._model.selectionStart) {
434 this._model.selectionEnd = null;
435 // If the mouse is over the second half of a wide character, adjust the
436 // selection to cover the whole character
437 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
438 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
439 this._model.selectionStart[0]++;
445 * Performs a double click, selecting the current work.
446 * @param event The mouse event.
448 private _onDoubleClick(event: MouseEvent): void {
449 const coords = this._getMouseBufferCoords(event);
451 this._activeSelectionMode = SelectionMode.WORD;
452 this._selectWordAt(coords);
457 * Performs a triple click, selecting the current line and activating line
459 * @param event The mouse event.
461 private _onTripleClick(event: MouseEvent): void {
462 const coords = this._getMouseBufferCoords(event);
464 this._activeSelectionMode = SelectionMode.LINE;
465 this._selectLineAt(coords[1]);
470 * Sets the number of clicks for the current mousedown event based on the time
471 * and position of the last mousedown event.
472 * @param event The mouse event.
474 private _setMouseClickCount(event: MouseEvent): void {
475 let currentTime = (new Date()).getTime();
476 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
477 this._clickCount = 0;
479 this._lastMouseDownTime = currentTime;
480 this._lastMousePosition = [event.pageX, event.pageY];
485 * Gets the maximum number of pixels in each direction the mouse has moved.
486 * @param event The mouse event.
488 private _distanceFromLastMousePosition(event: MouseEvent): number {
489 const result = Math.max(
490 Math.abs(this._lastMousePosition[0] - event.pageX),
491 Math.abs(this._lastMousePosition[1] - event.pageY));
496 * Handles the mousemove event when the mouse button is down, recording the
497 * end of the selection and refreshing the selection.
498 * @param event The mousemove event.
500 private _onMouseMove(event: MouseEvent) {
501 // Record the previous position so we know whether to redraw the selection
503 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
505 // Set the initial selection end based on the mouse coordinates
506 this._model.selectionEnd = this._getMouseBufferCoords(event);
508 // Select the entire line if line select mode is active.
509 if (this._activeSelectionMode === SelectionMode.LINE) {
510 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
511 this._model.selectionEnd[0] = 0;
513 this._model.selectionEnd[0] = this._terminal.cols;
515 } else if (this._activeSelectionMode === SelectionMode.WORD) {
516 this._selectToWordAt(this._model.selectionEnd);
519 // Determine the amount of scrolling that will happen.
520 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
522 // If the cursor was above or below the viewport, make sure it's at the
523 // start or end of the viewport respectively.
524 if (this._dragScrollAmount > 0) {
525 this._model.selectionEnd[0] = this._terminal.cols - 1;
526 } else if (this._dragScrollAmount < 0) {
527 this._model.selectionEnd[0] = 0;
530 // If the character is a wide character include the cell to the right in the
531 // selection. Note that selections at the very end of the line will never
533 if (this._model.selectionEnd[1] < this._buffer.length) {
534 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
535 if (char && char[2] === 0) {
536 this._model.selectionEnd[0]++;
540 // Only draw here if the selection changes.
541 if (!previousSelectionEnd ||
542 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
543 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
549 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
550 * scrolling of the viewport.
552 private _dragScroll() {
553 if (this._dragScrollAmount) {
554 this._terminal.scrollDisp(this._dragScrollAmount, false);
555 // Re-evaluate selection
556 if (this._dragScrollAmount > 0) {
557 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
559 this._model.selectionEnd = [0, this._terminal.ydisp];
566 * Handles the mouseup event, removing the mousedown listeners.
567 * @param event The mouseup event.
569 private _onMouseUp(event: MouseEvent) {
570 this._removeMouseDownListeners();
574 * Converts a viewport column to the character index on the buffer line, the
575 * latter takes into account wide characters.
576 * @param coords The coordinates to find the 2 index for.
578 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
579 let charIndex = coords[0];
580 for (let i = 0; coords[0] >= i; i++) {
581 const char = bufferLine[i];
582 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
590 * Gets positional information for the word at the coordinated specified.
591 * @param coords The coordinates to get the word at.
593 private _getWordAt(coords: [number, number]): IWordPosition {
594 const bufferLine = this._buffer.get(coords[1]);
595 const line = this._translateBufferLineToString(bufferLine, false);
597 // Get actual index, taking into consideration wide characters
598 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
599 let startIndex = endIndex;
601 // Record offset to be used later
602 const charOffset = coords[0] - startIndex;
603 let leftWideCharCount = 0;
604 let rightWideCharCount = 0;
606 if (line.charAt(startIndex) === ' ') {
607 // Expand until non-whitespace is hit
608 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
611 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
615 // Expand until whitespace is hit. This algorithm works by scanning left
616 // and right from the starting position, keeping both the index format
617 // (line) and the column format (bufferLine) in sync. When a wide
618 // character is hit, it is recorded and the column index is adjusted.
619 let startCol = coords[0];
620 let endCol = coords[0];
621 // Consider the initial position, skip it and increment the wide char
623 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
627 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
628 rightWideCharCount++;
631 // Expand the string in both directions until a space is hit
632 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
633 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
634 // If the next character is a wide char, record it and skip the column
641 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
642 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
643 // If the next character is a wide char, record it and skip the column
644 rightWideCharCount++;
652 const start = startIndex + charOffset - leftWideCharCount;
653 const length = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
654 return {start, length};
658 * Selects the word at the coordinates specified.
659 * @param coords The coordinates to get the word at.
661 protected _selectWordAt(coords: [number, number]): void {
662 const wordPosition = this._getWordAt(coords);
663 this._model.selectionStart = [wordPosition.start, coords[1]];
664 this._model.selectionStartLength = wordPosition.length;
668 * Sets the selection end to the word at the coordinated specified.
669 * @param coords The coordinates to get the word at.
671 private _selectToWordAt(coords: [number, number]): void {
672 const wordPosition = this._getWordAt(coords);
673 this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
677 * Selects the line specified.
678 * @param line The line index.
680 protected _selectLineAt(line: number): void {
681 this._model.selectionStart = [0, line];
682 this._model.selectionStartLength = this._terminal.cols;