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 = 100;
19 * The maximum scrolling speed
21 const DRAG_SCROLL_MAX_SPEED = 5;
24 * The number of milliseconds between drag scroll updates.
26 const DRAG_SCROLL_INTERVAL = 100;
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 export class SelectionManager extends EventEmitter {
46 protected _model: SelectionModel;
49 * The amount to scroll every drag scroll update (depends on how far the mouse
50 * drag is above or below the terminal).
52 private _dragScrollAmount: number;
55 * The last time the mousedown event fired, this is used to track double and
58 private _lastMouseDownTime: number;
61 * The last position the mouse was clicked [x, y].
63 private _lastMousePosition: [number, number];
66 * The number of clicks of the mousedown event. This is used to keep track of
67 * double and triple clicks.
69 private _clickCount: number;
72 * Whether line select mode is active, this occurs after a triple click.
74 private _isLineSelectModeActive: boolean;
76 private _bufferTrimListener: any;
77 private _mouseMoveListener: EventListener;
78 private _mouseDownListener: EventListener;
79 private _mouseUpListener: EventListener;
81 private _dragScrollIntervalTimer: NodeJS.Timer;
84 private _terminal: ITerminal,
85 private _buffer: CircularList<any>,
86 private _rowContainer: HTMLElement,
87 private _charMeasure: CharMeasure
90 this._initListeners();
93 this._model = new SelectionModel(_terminal);
94 this._lastMouseDownTime = 0;
95 this._isLineSelectModeActive = false;
98 private _initListeners() {
99 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
100 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
101 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
102 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
106 * Disables the selection manager. This is useful for when terminal mouse
110 this._model.selectionStart = null;
111 this._model.selectionEnd = null;
113 this._buffer.off('trim', this._bufferTrimListener);
114 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
115 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
116 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
117 clearInterval(this._dragScrollIntervalTimer);
121 * Enable the selection manager.
124 // Only adjust the selection on trim, shiftElements is rarely used (only in
125 // reverseIndex) and delete in a splice is only ever used when the same
126 // number of elements was just added. Given this is could actually be
127 // beneficial to leave the selection as is for these cases.
128 this._buffer.on('trim', this._bufferTrimListener);
129 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
133 * Gets the text currently selected.
135 public get selectionText(): string {
136 const start = this._model.finalSelectionStart;
137 const end = this._model.finalSelectionEnd;
138 if (!start || !end) {
143 const startRowEndCol = start[1] === end[1] ? end[0] : null;
144 let result: string[] = [];
145 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
148 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
149 result.push(this._translateBufferLineToString(this._buffer.get(i), true));
153 if (start[1] !== end[1]) {
154 result.push(this._translateBufferLineToString(this._buffer.get(end[1]), true, 0, end[0]));
156 console.log('selectionText result: "' + result + '"');
157 return result.join('\n');
160 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
161 // TODO: This function should live in a buffer or buffer line class
165 let widthAdjustedStartCol = startCol;
166 let widthAdjustedEndCol = endCol;
167 for (let i = 0; i < line.length; i++) {
168 const char = line[i];
169 lineString += char[LINE_DATA_CHAR_INDEX];
170 // Adjust start and end cols for wide characters if they affect their
172 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
174 widthAdjustedStartCol--;
177 widthAdjustedEndCol--;
182 // Calculate the final end col by trimming whitespace on the right of the
184 let finalEndCol = widthAdjustedEndCol || line.length;
186 const rightWhitespaceIndex = lineString.search(/\s+$/);
187 if (rightWhitespaceIndex !== -1) {
188 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
190 // Return the empty string if only trimmed whitespace is selected
191 if (finalEndCol <= widthAdjustedStartCol) {
196 return lineString.substring(widthAdjustedStartCol, finalEndCol);
200 * Redraws the selection.
202 public refresh(): void {
203 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
207 * Selects all text within the terminal.
209 public selectAll(): void {
210 this._model.isSelectAllActive = true;
215 * Handle the buffer being trimmed, adjust the selection position.
216 * @param amount The amount the buffer is being trimmed.
218 private _onTrim(amount: number) {
219 const needsRefresh = this._model.onTrim(amount);
225 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
226 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
228 // Convert to 0-based
231 // Convert viewport coords to buffer coords
232 coords[1] += this._terminal.ydisp;
236 private _getMouseEventScrollAmount(event: MouseEvent): number {
237 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
238 const terminalHeight = this._terminal.rows * this._charMeasure.height;
239 if (offset >= 0 && offset <= terminalHeight) {
242 if (offset > terminalHeight) {
243 offset -= terminalHeight;
246 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
247 offset /= DRAG_SCROLL_MAX_THRESHOLD;
248 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
252 * Handles te mousedown event, setting up for a new selection.
253 * @param event The mousedown event.
255 private _onMouseDown(event: MouseEvent) {
256 // Only action the primary button
257 if (event.button !== 0) {
261 this._setMouseClickCount(event);
262 console.log(this._clickCount);
264 if (event.shiftKey) {
265 this._onShiftClick(event);
267 if (this._clickCount === 1) {
268 this._onSingleClick(event);
269 } else if (this._clickCount === 2) {
270 this._onDoubleClick(event);
271 } else if (this._clickCount === 3) {
272 this._onTripleClick(event);
276 // Listen on the document so that dragging outside of viewport works
277 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
278 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
279 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
283 private _onShiftClick(event: MouseEvent): void {
284 if (this._model.selectionStart) {
285 this._model.selectionEnd = this._getMouseBufferCoords(event);
289 private _onSingleClick(event: MouseEvent): void {
290 this._model.selectionStartLength = 0;
291 this._model.isSelectAllActive = false;
292 this._isLineSelectModeActive = false;
293 this._model.selectionStart = this._getMouseBufferCoords(event);
294 if (this._model.selectionStart) {
295 this._model.selectionEnd = null;
296 // If the mouse is over the second half of a wide character, adjust the
297 // selection to cover the whole character
298 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
299 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
300 this._model.selectionStart[0]++;
305 private _onDoubleClick(event: MouseEvent): void {
306 const coords = this._getMouseBufferCoords(event);
308 this._selectWordAt(coords);
312 private _onTripleClick(event: MouseEvent): void {
313 const coords = this._getMouseBufferCoords(event);
315 this._isLineSelectModeActive = true;
316 this._selectLineAt(coords[1]);
320 private _setMouseClickCount(event: MouseEvent): void {
321 let currentTime = (new Date()).getTime();
322 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
323 this._clickCount = 0;
325 this._lastMouseDownTime = currentTime;
326 this._lastMousePosition = [event.pageX, event.pageY];
330 private _distanceFromLastMousePosition(event: MouseEvent): number {
331 const result = Math.max(
332 Math.abs(this._lastMousePosition[0] - event.pageX),
333 Math.abs(this._lastMousePosition[1] - event.pageY));
338 * Handles the mousemove event when the mouse button is down, recording the
339 * end of the selection and refreshing the selection.
340 * @param event The mousemove event.
342 private _onMouseMove(event: MouseEvent) {
343 // Record the previous position so we know whether to redraw the selection
345 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
347 // Set the initial selection end based on the mouse coordinates
348 this._model.selectionEnd = this._getMouseBufferCoords(event);
350 // Select the entire line if line select mode is active.
351 if (this._isLineSelectModeActive) {
352 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
353 this._model.selectionEnd[0] = 0;
355 this._model.selectionEnd[0] = this._terminal.cols;
359 // Determine the amount of scrolling that will happen.
360 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
362 // If the cursor was above or below the viewport, make sure it's at the
363 // start or end of the viewport respectively.
364 if (this._dragScrollAmount > 0) {
365 this._model.selectionEnd[0] = this._terminal.cols - 1;
366 } else if (this._dragScrollAmount < 0) {
367 this._model.selectionEnd[0] = 0;
370 // If the character is a wide character include the cell to the right in the
371 // selection. Note that selections at the very end of the line will never
373 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
374 if (char && char[2] === 0) {
375 this._model.selectionEnd[0]++;
378 // Only draw here if the selection changes.
379 if (!previousSelectionEnd ||
380 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
381 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
386 private _dragScroll() {
387 if (this._dragScrollAmount) {
388 this._terminal.scrollDisp(this._dragScrollAmount, false);
389 // Re-evaluate selection
390 if (this._dragScrollAmount > 0) {
391 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
393 this._model.selectionEnd = [0, this._terminal.ydisp];
400 * Handles the mouseup event, removing the mousemove listener when
402 * @param event The mouseup event.
404 private _onMouseUp(event: MouseEvent) {
405 this._dragScrollAmount = 0;
406 if (!this._model.selectionStart) {
409 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
410 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
414 * Converts a viewport column to the character index on the buffer line, the
415 * latter takes into account wide characters.
416 * @param coords The coordinates to find the 2 index for.
418 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
419 let charIndex = coords[0];
420 for (let i = 0; coords[0] >= i; i++) {
421 const char = bufferLine[i];
422 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
430 * Selects the word at the coordinates specified. Words are defined as all
431 * non-whitespace characters.
432 * @param coords The coordinates to get the word at.
434 protected _selectWordAt(coords: [number, number]): void {
435 const bufferLine = this._buffer.get(coords[1]);
436 const line = this._translateBufferLineToString(bufferLine, false);
438 // Get actual index, taking into consideration wide characters
439 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
440 let startIndex = endIndex;
442 // Record offset to be used later
443 const charOffset = coords[0] - startIndex;
444 let leftWideCharCount = 0;
445 let rightWideCharCount = 0;
447 if (line.charAt(startIndex) === ' ') {
448 // Expand until non-whitespace is hit
449 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
452 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
456 // Expand until whitespace is hit. This algorithm works by scanning left
457 // and right from the starting position, keeping both the index format
458 // (line) and the column format (bufferLine) in sync. When a wide
459 // character is hit, it is recorded and the column index is adjusted.
460 let startCol = coords[0];
461 let endCol = coords[0];
462 // Consider the initial position, skip it and increment the wide char
464 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
468 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
469 rightWideCharCount++;
472 // Expand the string in both directions until a space is hit
473 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
474 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
475 // If the next character is a wide char, record it and skip the column
482 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
483 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
484 // If the next character is a wide char, record it and skip the column
485 rightWideCharCount++;
493 // Record the resulting selection
494 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
495 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
498 protected _selectLineAt(line: number): void {
499 this._model.selectionStart = [0, line];
500 this._model.selectionStartLength = this._terminal.cols;