]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Merge pull request #700 from Tyriar/698_mousedown_preventDefault
[mirror_xterm.js.git] / src / SelectionManager.ts
1 /**
2 * @license MIT
3 */
4
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
12 /**
13 * The number of pixels the mouse needs to be above or below the viewport in
14 * order to scroll at the maximum speed.
15 */
16 const DRAG_SCROLL_MAX_THRESHOLD = 50;
17
18 /**
19 * The maximum scrolling speed
20 */
21 const DRAG_SCROLL_MAX_SPEED = 15;
22
23 /**
24 * The number of milliseconds between drag scroll updates.
25 */
26 const DRAG_SCROLL_INTERVAL = 50;
27
28 /**
29 * The amount of time before mousedown events are no longer stacked to create
30 * double/triple click events.
31 */
32 const CLEAR_MOUSE_DOWN_TIME = 400;
33
34 /**
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.
37 */
38 const CLEAR_MOUSE_DISTANCE = 10;
39
40 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
41 // data/line class.
42 const LINE_DATA_CHAR_INDEX = 1;
43 const LINE_DATA_WIDTH_INDEX = 2;
44
45 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
46 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
47
48 /**
49 * A class that manages the selection of the terminal. With help from
50 * SelectionModel, SelectionManager handles with all logic associated with
51 * dealing with the selection, including handling mouse interaction, wide
52 * characters and fetching the actual text within the selection. Rendering is
53 * not handled by the SelectionManager but a 'refresh' event is fired when the
54 * selection is ready to be redrawn.
55 */
56 export class SelectionManager extends EventEmitter {
57 protected _model: SelectionModel;
58
59 /**
60 * The amount to scroll every drag scroll update (depends on how far the mouse
61 * drag is above or below the terminal).
62 */
63 private _dragScrollAmount: number;
64
65 /**
66 * The last time the mousedown event fired, this is used to track double and
67 * triple clicks.
68 */
69 private _lastMouseDownTime: number;
70
71 /**
72 * The last position the mouse was clicked [x, y].
73 */
74 private _lastMousePosition: [number, number];
75
76 /**
77 * The number of clicks of the mousedown event. This is used to keep track of
78 * double and triple clicks.
79 */
80 private _clickCount: number;
81
82 /**
83 * Whether line select mode is active, this occurs after a triple click.
84 */
85 private _isLineSelectModeActive: boolean;
86
87 /**
88 * A setInterval timer that is active while the mouse is down whose callback
89 * scrolls the viewport when necessary.
90 */
91 private _dragScrollIntervalTimer: NodeJS.Timer;
92
93 /**
94 * The animation frame ID used for refreshing the selection.
95 */
96 private _refreshAnimationFrame: number;
97
98 private _bufferTrimListener: any;
99 private _mouseMoveListener: EventListener;
100 private _mouseDownListener: EventListener;
101 private _mouseUpListener: EventListener;
102
103 constructor(
104 private _terminal: ITerminal,
105 private _buffer: CircularList<any>,
106 private _rowContainer: HTMLElement,
107 private _charMeasure: CharMeasure
108 ) {
109 super();
110 this._initListeners();
111 this.enable();
112
113 this._model = new SelectionModel(_terminal);
114 this._lastMouseDownTime = 0;
115 this._isLineSelectModeActive = false;
116 }
117
118 /**
119 * Initializes listener variables.
120 */
121 private _initListeners() {
122 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
123 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
124 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
125 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
126 }
127
128 /**
129 * Disables the selection manager. This is useful for when terminal mouse
130 * are enabled.
131 */
132 public disable() {
133 this.clearSelection();
134 this._buffer.off('trim', this._bufferTrimListener);
135 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
136 }
137
138 /**
139 * Enable the selection manager.
140 */
141 public enable() {
142 // Only adjust the selection on trim, shiftElements is rarely used (only in
143 // reverseIndex) and delete in a splice is only ever used when the same
144 // number of elements was just added. Given this is could actually be
145 // beneficial to leave the selection as is for these cases.
146 this._buffer.on('trim', this._bufferTrimListener);
147 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
148 }
149
150 /**
151 * Sets the active buffer, this should be called when the alt buffer is
152 * switched in or out.
153 * @param buffer The active buffer.
154 */
155 public setBuffer(buffer: CircularList<any>): void {
156 this._buffer = buffer;
157 }
158
159 /**
160 * Gets whether there is an active text selection.
161 */
162 public get hasSelection(): boolean {
163 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
164 }
165
166 /**
167 * Gets the text currently selected.
168 */
169 public get selectionText(): string {
170 const start = this._model.finalSelectionStart;
171 const end = this._model.finalSelectionEnd;
172 if (!start || !end) {
173 return '';
174 }
175
176 // Get first row
177 const startRowEndCol = start[1] === end[1] ? end[0] : null;
178 let result: string[] = [];
179 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
180
181 // Get middle rows
182 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
183 result.push(this._translateBufferLineToString(this._buffer.get(i), true));
184 }
185
186 // Get final row
187 if (start[1] !== end[1]) {
188 result.push(this._translateBufferLineToString(this._buffer.get(end[1]), true, 0, end[0]));
189 }
190
191 // Format string by replacing non-breaking space chars with regular spaces
192 // and joining the array into a multi-line string.
193 const formattedResult = result.map(line => {
194 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
195 }).join('\n');
196
197 return formattedResult;
198 }
199
200 /**
201 * Clears the current terminal selection.
202 */
203 public clearSelection(): void {
204 this._model.clearSelection();
205 this._removeMouseDownListeners();
206 this.refresh();
207 }
208
209 /**
210 * Translates a buffer line to a string, with optional start and end columns.
211 * Wide characters will count as two columns in the resulting string. This
212 * function is useful for getting the actual text underneath the raw selection
213 * position.
214 * @param line The line being translated.
215 * @param trimRight Whether to trim whitespace to the right.
216 * @param startCol The column to start at.
217 * @param endCol The column to end at.
218 */
219 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
220 // TODO: This function should live in a buffer or buffer line class
221
222 // Get full line
223 let lineString = '';
224 let widthAdjustedStartCol = startCol;
225 let widthAdjustedEndCol = endCol;
226 for (let i = 0; i < line.length; i++) {
227 const char = line[i];
228 lineString += char[LINE_DATA_CHAR_INDEX];
229 // Adjust start and end cols for wide characters if they affect their
230 // column indexes
231 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
232 if (startCol >= i) {
233 widthAdjustedStartCol--;
234 }
235 if (endCol >= i) {
236 widthAdjustedEndCol--;
237 }
238 }
239 }
240
241 // Calculate the final end col by trimming whitespace on the right of the
242 // line if needed.
243 let finalEndCol = widthAdjustedEndCol || line.length;
244 if (trimRight) {
245 const rightWhitespaceIndex = lineString.search(/\s+$/);
246 if (rightWhitespaceIndex !== -1) {
247 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
248 }
249 // Return the empty string if only trimmed whitespace is selected
250 if (finalEndCol <= widthAdjustedStartCol) {
251 return '';
252 }
253 }
254
255 return lineString.substring(widthAdjustedStartCol, finalEndCol);
256 }
257
258 /**
259 * Queues a refresh, redrawing the selection on the next opportunity.
260 */
261 public refresh(): void {
262 if (!this._refreshAnimationFrame) {
263 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
264 }
265 }
266
267 /**
268 * Fires the refresh event, causing consumers to pick it up and redraw the
269 * selection state.
270 */
271 private _refresh(): void {
272 this._refreshAnimationFrame = null;
273 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
274 }
275
276 /**
277 * Selects all text within the terminal.
278 */
279 public selectAll(): void {
280 this._model.isSelectAllActive = true;
281 this.refresh();
282 }
283
284 /**
285 * Handle the buffer being trimmed, adjust the selection position.
286 * @param amount The amount the buffer is being trimmed.
287 */
288 private _onTrim(amount: number) {
289 const needsRefresh = this._model.onTrim(amount);
290 if (needsRefresh) {
291 this.refresh();
292 }
293 }
294
295 /**
296 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
297 * @param event The mouse event.
298 */
299 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
300 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
301 // Convert to 0-based
302 coords[0]--;
303 coords[1]--;
304 // Convert viewport coords to buffer coords
305 coords[1] += this._terminal.ydisp;
306 return coords;
307 }
308
309 /**
310 * Gets the amount the viewport should be scrolled based on how far out of the
311 * terminal the mouse is.
312 * @param event The mouse event.
313 */
314 private _getMouseEventScrollAmount(event: MouseEvent): number {
315 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
316 const terminalHeight = this._terminal.rows * this._charMeasure.height;
317 if (offset >= 0 && offset <= terminalHeight) {
318 return 0;
319 }
320 if (offset > terminalHeight) {
321 offset -= terminalHeight;
322 }
323
324 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
325 offset /= DRAG_SCROLL_MAX_THRESHOLD;
326 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
327 }
328
329 /**
330 * Handles te mousedown event, setting up for a new selection.
331 * @param event The mousedown event.
332 */
333 private _onMouseDown(event: MouseEvent) {
334 // Only action the primary button
335 if (event.button !== 0) {
336 return;
337 }
338
339 // Tell the browser not to start a regular selection
340 event.preventDefault();
341
342 // Reset drag scroll state
343 this._dragScrollAmount = 0;
344
345 this._setMouseClickCount(event);
346
347 if (event.shiftKey) {
348 this._onShiftClick(event);
349 } else {
350 if (this._clickCount === 1) {
351 this._onSingleClick(event);
352 } else if (this._clickCount === 2) {
353 this._onDoubleClick(event);
354 } else if (this._clickCount === 3) {
355 this._onTripleClick(event);
356 }
357 }
358
359 this._addMouseDownListeners();
360 this.refresh();
361 }
362
363 /**
364 * Adds listeners when mousedown is triggered.
365 */
366 private _addMouseDownListeners(): void {
367 // Listen on the document so that dragging outside of viewport works
368 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
369 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
370 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
371 }
372
373 /**
374 * Removes the listeners that are registered when mousedown is triggered.
375 */
376 private _removeMouseDownListeners(): void {
377 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
378 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
379 clearInterval(this._dragScrollIntervalTimer);
380 this._dragScrollIntervalTimer = null;
381 }
382
383 /**
384 * Performs a shift click, setting the selection end position to the mouse
385 * position.
386 * @param event The mouse event.
387 */
388 private _onShiftClick(event: MouseEvent): void {
389 if (this._model.selectionStart) {
390 this._model.selectionEnd = this._getMouseBufferCoords(event);
391 }
392 }
393
394 /**
395 * Performs a single click, resetting relevant state and setting the selection
396 * start position.
397 * @param event The mouse event.
398 */
399 private _onSingleClick(event: MouseEvent): void {
400 this._model.selectionStartLength = 0;
401 this._model.isSelectAllActive = false;
402 this._isLineSelectModeActive = false;
403 this._model.selectionStart = this._getMouseBufferCoords(event);
404 if (this._model.selectionStart) {
405 this._model.selectionEnd = null;
406 // If the mouse is over the second half of a wide character, adjust the
407 // selection to cover the whole character
408 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
409 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
410 this._model.selectionStart[0]++;
411 }
412 }
413 }
414
415 /**
416 * Performs a double click, selecting the current work.
417 * @param event The mouse event.
418 */
419 private _onDoubleClick(event: MouseEvent): void {
420 const coords = this._getMouseBufferCoords(event);
421 if (coords) {
422 this._selectWordAt(coords);
423 }
424 }
425
426 /**
427 * Performs a triple click, selecting the current line and activating line
428 * select mode.
429 * @param event The mouse event.
430 */
431 private _onTripleClick(event: MouseEvent): void {
432 const coords = this._getMouseBufferCoords(event);
433 if (coords) {
434 this._isLineSelectModeActive = true;
435 this._selectLineAt(coords[1]);
436 }
437 }
438
439 /**
440 * Sets the number of clicks for the current mousedown event based on the time
441 * and position of the last mousedown event.
442 * @param event The mouse event.
443 */
444 private _setMouseClickCount(event: MouseEvent): void {
445 let currentTime = (new Date()).getTime();
446 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
447 this._clickCount = 0;
448 }
449 this._lastMouseDownTime = currentTime;
450 this._lastMousePosition = [event.pageX, event.pageY];
451 this._clickCount++;
452 }
453
454 /**
455 * Gets the maximum number of pixels in each direction the mouse has moved.
456 * @param event The mouse event.
457 */
458 private _distanceFromLastMousePosition(event: MouseEvent): number {
459 const result = Math.max(
460 Math.abs(this._lastMousePosition[0] - event.pageX),
461 Math.abs(this._lastMousePosition[1] - event.pageY));
462 return result;
463 }
464
465 /**
466 * Handles the mousemove event when the mouse button is down, recording the
467 * end of the selection and refreshing the selection.
468 * @param event The mousemove event.
469 */
470 private _onMouseMove(event: MouseEvent) {
471 // Record the previous position so we know whether to redraw the selection
472 // at the end.
473 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
474
475 // Set the initial selection end based on the mouse coordinates
476 this._model.selectionEnd = this._getMouseBufferCoords(event);
477
478 // Select the entire line if line select mode is active.
479 if (this._isLineSelectModeActive) {
480 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
481 this._model.selectionEnd[0] = 0;
482 } else {
483 this._model.selectionEnd[0] = this._terminal.cols;
484 }
485 }
486
487 // Determine the amount of scrolling that will happen.
488 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
489
490 // If the cursor was above or below the viewport, make sure it's at the
491 // start or end of the viewport respectively.
492 if (this._dragScrollAmount > 0) {
493 this._model.selectionEnd[0] = this._terminal.cols - 1;
494 } else if (this._dragScrollAmount < 0) {
495 this._model.selectionEnd[0] = 0;
496 }
497
498 // If the character is a wide character include the cell to the right in the
499 // selection. Note that selections at the very end of the line will never
500 // have a character.
501 if (this._model.selectionEnd[1] < this._buffer.length) {
502 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
503 if (char && char[2] === 0) {
504 this._model.selectionEnd[0]++;
505 }
506 }
507
508 // Only draw here if the selection changes.
509 if (!previousSelectionEnd ||
510 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
511 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
512 this.refresh();
513 }
514 }
515
516 /**
517 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
518 * scrolling of the viewport.
519 */
520 private _dragScroll() {
521 if (this._dragScrollAmount) {
522 this._terminal.scrollDisp(this._dragScrollAmount, false);
523 // Re-evaluate selection
524 if (this._dragScrollAmount > 0) {
525 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
526 } else {
527 this._model.selectionEnd = [0, this._terminal.ydisp];
528 }
529 this.refresh();
530 }
531 }
532
533 /**
534 * Handles the mouseup event, removing the mousedown listeners.
535 * @param event The mouseup event.
536 */
537 private _onMouseUp(event: MouseEvent) {
538 this._removeMouseDownListeners();
539 }
540
541 /**
542 * Converts a viewport column to the character index on the buffer line, the
543 * latter takes into account wide characters.
544 * @param coords The coordinates to find the 2 index for.
545 */
546 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
547 let charIndex = coords[0];
548 for (let i = 0; coords[0] >= i; i++) {
549 const char = bufferLine[i];
550 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
551 charIndex--;
552 }
553 }
554 return charIndex;
555 }
556
557 /**
558 * Selects the word at the coordinates specified. Words are defined as all
559 * non-whitespace characters.
560 * @param coords The coordinates to get the word at.
561 */
562 protected _selectWordAt(coords: [number, number]): void {
563 const bufferLine = this._buffer.get(coords[1]);
564 const line = this._translateBufferLineToString(bufferLine, false);
565
566 // Get actual index, taking into consideration wide characters
567 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
568 let startIndex = endIndex;
569
570 // Record offset to be used later
571 const charOffset = coords[0] - startIndex;
572 let leftWideCharCount = 0;
573 let rightWideCharCount = 0;
574
575 if (line.charAt(startIndex) === ' ') {
576 // Expand until non-whitespace is hit
577 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
578 startIndex--;
579 }
580 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
581 endIndex++;
582 }
583 } else {
584 // Expand until whitespace is hit. This algorithm works by scanning left
585 // and right from the starting position, keeping both the index format
586 // (line) and the column format (bufferLine) in sync. When a wide
587 // character is hit, it is recorded and the column index is adjusted.
588 let startCol = coords[0];
589 let endCol = coords[0];
590 // Consider the initial position, skip it and increment the wide char
591 // variable
592 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
593 leftWideCharCount++;
594 startCol--;
595 }
596 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
597 rightWideCharCount++;
598 endCol++;
599 }
600 // Expand the string in both directions until a space is hit
601 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
602 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
603 // If the next character is a wide char, record it and skip the column
604 leftWideCharCount++;
605 startCol--;
606 }
607 startIndex--;
608 startCol--;
609 }
610 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
611 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
612 // If the next character is a wide char, record it and skip the column
613 rightWideCharCount++;
614 endCol++;
615 }
616 endIndex++;
617 endCol++;
618 }
619 }
620
621 // Record the resulting selection
622 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
623 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
624 }
625
626 /**
627 * Selects the line specified.
628 * @param line The line index.
629 */
630 protected _selectLineAt(line: number): void {
631 this._model.selectionStart = [0, line];
632 this._model.selectionStartLength = this._terminal.cols;
633 }
634 }