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';
11 import { translateBufferLineToString } from './utils/BufferLine';
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;
41 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
43 const LINE_DATA_CHAR_INDEX = 1;
44 const LINE_DATA_WIDTH_INDEX = 2;
46 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
47 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
50 * A class that manages the selection of the terminal. With help from
51 * SelectionModel, SelectionManager handles with all logic associated with
52 * dealing with the selection, including handling mouse interaction, wide
53 * characters and fetching the actual text within the selection. Rendering is
54 * not handled by the SelectionManager but a 'refresh' event is fired when the
55 * selection is ready to be redrawn.
57 export class SelectionManager extends EventEmitter {
58 protected _model: SelectionModel;
61 * The amount to scroll every drag scroll update (depends on how far the mouse
62 * drag is above or below the terminal).
64 private _dragScrollAmount: number;
67 * The last time the mousedown event fired, this is used to track double and
70 private _lastMouseDownTime: number;
73 * The last position the mouse was clicked [x, y].
75 private _lastMousePosition: [number, number];
78 * The number of clicks of the mousedown event. This is used to keep track of
79 * double and triple clicks.
81 private _clickCount: number;
84 * Whether line select mode is active, this occurs after a triple click.
86 private _isLineSelectModeActive: boolean;
89 * A setInterval timer that is active while the mouse is down whose callback
90 * scrolls the viewport when necessary.
92 private _dragScrollIntervalTimer: NodeJS.Timer;
95 * The animation frame ID used for refreshing the selection.
97 private _refreshAnimationFrame: number;
99 private _bufferTrimListener: any;
100 private _mouseMoveListener: EventListener;
101 private _mouseDownListener: EventListener;
102 private _mouseUpListener: EventListener;
105 private _terminal: ITerminal,
106 private _buffer: CircularList<any>,
107 private _rowContainer: HTMLElement,
108 private _charMeasure: CharMeasure
111 this._initListeners();
114 this._model = new SelectionModel(_terminal);
115 this._lastMouseDownTime = 0;
116 this._isLineSelectModeActive = false;
120 * Initializes listener variables.
122 private _initListeners() {
123 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
124 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
125 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
126 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
130 * Disables the selection manager. This is useful for when terminal mouse
134 this.clearSelection();
135 this._buffer.off('trim', this._bufferTrimListener);
136 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
140 * Enable the selection manager.
143 // Only adjust the selection on trim, shiftElements is rarely used (only in
144 // reverseIndex) and delete in a splice is only ever used when the same
145 // number of elements was just added. Given this is could actually be
146 // beneficial to leave the selection as is for these cases.
147 this._buffer.on('trim', this._bufferTrimListener);
148 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
152 * Sets the active buffer, this should be called when the alt buffer is
153 * switched in or out.
154 * @param buffer The active buffer.
156 public setBuffer(buffer: CircularList<any>): void {
157 this._buffer = buffer;
160 public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
161 public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
164 * Gets whether there is an active text selection.
166 public get hasSelection(): boolean {
167 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
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 (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 (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, ' ');
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.
228 public refresh(): void {
229 if (!this._refreshAnimationFrame) {
230 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
235 * Fires the refresh event, causing consumers to pick it up and redraw the
238 private _refresh(): void {
239 this._refreshAnimationFrame = null;
240 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
244 * Selects all text within the terminal.
246 public selectAll(): void {
247 this._model.isSelectAllActive = true;
252 * Handle the buffer being trimmed, adjust the selection position.
253 * @param amount The amount the buffer is being trimmed.
255 private _onTrim(amount: number) {
256 const needsRefresh = this._model.onTrim(amount);
263 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
264 * @param event The mouse event.
266 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
267 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
268 // Convert to 0-based
271 // Convert viewport coords to buffer coords
272 coords[1] += this._terminal.ydisp;
277 * Gets the amount the viewport should be scrolled based on how far out of the
278 * terminal the mouse is.
279 * @param event The mouse event.
281 private _getMouseEventScrollAmount(event: MouseEvent): number {
282 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
283 const terminalHeight = this._terminal.rows * this._charMeasure.height;
284 if (offset >= 0 && offset <= terminalHeight) {
287 if (offset > terminalHeight) {
288 offset -= terminalHeight;
291 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
292 offset /= DRAG_SCROLL_MAX_THRESHOLD;
293 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
297 * Handles te mousedown event, setting up for a new selection.
298 * @param event The mousedown event.
300 private _onMouseDown(event: MouseEvent) {
301 // Only action the primary button
302 if (event.button !== 0) {
306 // Tell the browser not to start a regular selection
307 event.preventDefault();
309 // Reset drag scroll state
310 this._dragScrollAmount = 0;
312 this._setMouseClickCount(event);
314 if (event.shiftKey) {
315 this._onShiftClick(event);
317 if (this._clickCount === 1) {
318 this._onSingleClick(event);
319 } else if (this._clickCount === 2) {
320 this._onDoubleClick(event);
321 } else if (this._clickCount === 3) {
322 this._onTripleClick(event);
326 this._addMouseDownListeners();
331 * Adds listeners when mousedown is triggered.
333 private _addMouseDownListeners(): void {
334 // Listen on the document so that dragging outside of viewport works
335 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
336 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
337 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
341 * Removes the listeners that are registered when mousedown is triggered.
343 private _removeMouseDownListeners(): void {
344 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
345 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
346 clearInterval(this._dragScrollIntervalTimer);
347 this._dragScrollIntervalTimer = null;
351 * Performs a shift click, setting the selection end position to the mouse
353 * @param event The mouse event.
355 private _onShiftClick(event: MouseEvent): void {
356 if (this._model.selectionStart) {
357 this._model.selectionEnd = this._getMouseBufferCoords(event);
362 * Performs a single click, resetting relevant state and setting the selection
364 * @param event The mouse event.
366 private _onSingleClick(event: MouseEvent): void {
367 this._model.selectionStartLength = 0;
368 this._model.isSelectAllActive = false;
369 this._isLineSelectModeActive = false;
370 this._model.selectionStart = this._getMouseBufferCoords(event);
371 if (this._model.selectionStart) {
372 this._model.selectionEnd = null;
373 // If the mouse is over the second half of a wide character, adjust the
374 // selection to cover the whole character
375 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
376 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
377 this._model.selectionStart[0]++;
383 * Performs a double click, selecting the current work.
384 * @param event The mouse event.
386 private _onDoubleClick(event: MouseEvent): void {
387 const coords = this._getMouseBufferCoords(event);
389 this._selectWordAt(coords);
394 * Performs a triple click, selecting the current line and activating line
396 * @param event The mouse event.
398 private _onTripleClick(event: MouseEvent): void {
399 const coords = this._getMouseBufferCoords(event);
401 this._isLineSelectModeActive = true;
402 this._selectLineAt(coords[1]);
407 * Sets the number of clicks for the current mousedown event based on the time
408 * and position of the last mousedown event.
409 * @param event The mouse event.
411 private _setMouseClickCount(event: MouseEvent): void {
412 let currentTime = (new Date()).getTime();
413 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
414 this._clickCount = 0;
416 this._lastMouseDownTime = currentTime;
417 this._lastMousePosition = [event.pageX, event.pageY];
422 * Gets the maximum number of pixels in each direction the mouse has moved.
423 * @param event The mouse event.
425 private _distanceFromLastMousePosition(event: MouseEvent): number {
426 const result = Math.max(
427 Math.abs(this._lastMousePosition[0] - event.pageX),
428 Math.abs(this._lastMousePosition[1] - event.pageY));
433 * Handles the mousemove event when the mouse button is down, recording the
434 * end of the selection and refreshing the selection.
435 * @param event The mousemove event.
437 private _onMouseMove(event: MouseEvent) {
438 // Record the previous position so we know whether to redraw the selection
440 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
442 // Set the initial selection end based on the mouse coordinates
443 this._model.selectionEnd = this._getMouseBufferCoords(event);
445 // Select the entire line if line select mode is active.
446 if (this._isLineSelectModeActive) {
447 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
448 this._model.selectionEnd[0] = 0;
450 this._model.selectionEnd[0] = this._terminal.cols;
454 // Determine the amount of scrolling that will happen.
455 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
457 // If the cursor was above or below the viewport, make sure it's at the
458 // start or end of the viewport respectively.
459 if (this._dragScrollAmount > 0) {
460 this._model.selectionEnd[0] = this._terminal.cols - 1;
461 } else if (this._dragScrollAmount < 0) {
462 this._model.selectionEnd[0] = 0;
465 // If the character is a wide character include the cell to the right in the
466 // selection. Note that selections at the very end of the line will never
468 if (this._model.selectionEnd[1] < this._buffer.length) {
469 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
470 if (char && char[2] === 0) {
471 this._model.selectionEnd[0]++;
475 // Only draw here if the selection changes.
476 if (!previousSelectionEnd ||
477 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
478 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
484 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
485 * scrolling of the viewport.
487 private _dragScroll() {
488 if (this._dragScrollAmount) {
489 this._terminal.scrollDisp(this._dragScrollAmount, false);
490 // Re-evaluate selection
491 if (this._dragScrollAmount > 0) {
492 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
494 this._model.selectionEnd = [0, this._terminal.ydisp];
501 * Handles the mouseup event, removing the mousedown listeners.
502 * @param event The mouseup event.
504 private _onMouseUp(event: MouseEvent) {
505 this._removeMouseDownListeners();
509 * Converts a viewport column to the character index on the buffer line, the
510 * latter takes into account wide characters.
511 * @param coords The coordinates to find the 2 index for.
513 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
514 let charIndex = coords[0];
515 for (let i = 0; coords[0] >= i; i++) {
516 const char = bufferLine[i];
517 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
524 public setSelection(col: number, row: number, length: number): void {
525 this._model.clearSelection();
526 this._removeMouseDownListeners();
527 console.log('setSelection', arguments);
528 this._model.selectionStart = [col, row];
529 this._model.selectionStartLength = length;
534 * Selects the word at the coordinates specified. Words are defined as all
535 * non-whitespace characters.
536 * @param coords The coordinates to get the word at.
538 protected _selectWordAt(coords: [number, number]): void {
539 const bufferLine = this._buffer.get(coords[1]);
540 const line = translateBufferLineToString(bufferLine, false);
542 // Get actual index, taking into consideration wide characters
543 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
544 let startIndex = endIndex;
546 // Record offset to be used later
547 const charOffset = coords[0] - startIndex;
548 let leftWideCharCount = 0;
549 let rightWideCharCount = 0;
551 if (line.charAt(startIndex) === ' ') {
552 // Expand until non-whitespace is hit
553 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
556 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
560 // Expand until whitespace is hit. This algorithm works by scanning left
561 // and right from the starting position, keeping both the index format
562 // (line) and the column format (bufferLine) in sync. When a wide
563 // character is hit, it is recorded and the column index is adjusted.
564 let startCol = coords[0];
565 let endCol = coords[0];
566 // Consider the initial position, skip it and increment the wide char
568 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
572 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
573 rightWideCharCount++;
576 // Expand the string in both directions until a space is hit
577 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
578 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
579 // If the next character is a wide char, record it and skip the column
586 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
587 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
588 // If the next character is a wide char, record it and skip the column
589 rightWideCharCount++;
597 // Record the resulting selection
598 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
599 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
603 * Selects the line specified.
604 * @param line The line index.
606 protected _selectLineAt(line: number): void {
607 this._model.selectionStart = [0, line];
608 this._model.selectionStartLength = this._terminal.cols;