]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Merge branch 'master' into 443_retain_wrapped_lines_copy
[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 const bufferLine = this._buffer.get(i);
184 const lineText = this._translateBufferLineToString(bufferLine, true);
185 if (bufferLine.isWrapped) {
186 result[result.length - 1] += lineText;
187 } else {
188 result.push(lineText);
189 }
190 }
191
192 // Get final row
193 if (start[1] !== end[1]) {
194 const bufferLine = this._buffer.get(end[1]);
195 const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
196 if (bufferLine.isWrapped) {
197 result[result.length - 1] += lineText;
198 } else {
199 result.push(lineText);
200 }
201 }
202
203 // Format string by replacing non-breaking space chars with regular spaces
204 // and joining the array into a multi-line string.
205 const formattedResult = result.map(line => {
206 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
207 }).join('\n');
208
209 return formattedResult;
210 }
211
212 /**
213 * Clears the current terminal selection.
214 */
215 public clearSelection(): void {
216 this._model.clearSelection();
217 this._removeMouseDownListeners();
218 this.refresh();
219 }
220
221 /**
222 * Translates a buffer line to a string, with optional start and end columns.
223 * Wide characters will count as two columns in the resulting string. This
224 * function is useful for getting the actual text underneath the raw selection
225 * position.
226 * @param line The line being translated.
227 * @param trimRight Whether to trim whitespace to the right.
228 * @param startCol The column to start at.
229 * @param endCol The column to end at.
230 */
231 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
232 // TODO: This function should live in a buffer or buffer line class
233
234 // Get full line
235 let lineString = '';
236 let widthAdjustedStartCol = startCol;
237 let widthAdjustedEndCol = endCol;
238 for (let i = 0; i < line.length; i++) {
239 const char = line[i];
240 lineString += char[LINE_DATA_CHAR_INDEX];
241 // Adjust start and end cols for wide characters if they affect their
242 // column indexes
243 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
244 if (startCol >= i) {
245 widthAdjustedStartCol--;
246 }
247 if (endCol >= i) {
248 widthAdjustedEndCol--;
249 }
250 }
251 }
252
253 // Calculate the final end col by trimming whitespace on the right of the
254 // line if needed.
255 let finalEndCol = widthAdjustedEndCol || line.length;
256 if (trimRight) {
257 const rightWhitespaceIndex = lineString.search(/\s+$/);
258 if (rightWhitespaceIndex !== -1) {
259 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
260 }
261 // Return the empty string if only trimmed whitespace is selected
262 if (finalEndCol <= widthAdjustedStartCol) {
263 return '';
264 }
265 }
266
267 return lineString.substring(widthAdjustedStartCol, finalEndCol);
268 }
269
270 /**
271 * Queues a refresh, redrawing the selection on the next opportunity.
272 */
273 public refresh(): void {
274 if (!this._refreshAnimationFrame) {
275 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
276 }
277 }
278
279 /**
280 * Fires the refresh event, causing consumers to pick it up and redraw the
281 * selection state.
282 */
283 private _refresh(): void {
284 this._refreshAnimationFrame = null;
285 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
286 }
287
288 /**
289 * Selects all text within the terminal.
290 */
291 public selectAll(): void {
292 this._model.isSelectAllActive = true;
293 this.refresh();
294 }
295
296 /**
297 * Handle the buffer being trimmed, adjust the selection position.
298 * @param amount The amount the buffer is being trimmed.
299 */
300 private _onTrim(amount: number) {
301 const needsRefresh = this._model.onTrim(amount);
302 if (needsRefresh) {
303 this.refresh();
304 }
305 }
306
307 /**
308 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
309 * @param event The mouse event.
310 */
311 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
312 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
313 // Convert to 0-based
314 coords[0]--;
315 coords[1]--;
316 // Convert viewport coords to buffer coords
317 coords[1] += this._terminal.ydisp;
318 return coords;
319 }
320
321 /**
322 * Gets the amount the viewport should be scrolled based on how far out of the
323 * terminal the mouse is.
324 * @param event The mouse event.
325 */
326 private _getMouseEventScrollAmount(event: MouseEvent): number {
327 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
328 const terminalHeight = this._terminal.rows * this._charMeasure.height;
329 if (offset >= 0 && offset <= terminalHeight) {
330 return 0;
331 }
332 if (offset > terminalHeight) {
333 offset -= terminalHeight;
334 }
335
336 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
337 offset /= DRAG_SCROLL_MAX_THRESHOLD;
338 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
339 }
340
341 /**
342 * Handles te mousedown event, setting up for a new selection.
343 * @param event The mousedown event.
344 */
345 private _onMouseDown(event: MouseEvent) {
346 // Only action the primary button
347 if (event.button !== 0) {
348 return;
349 }
350
351 // Tell the browser not to start a regular selection
352 event.preventDefault();
353
354 // Reset drag scroll state
355 this._dragScrollAmount = 0;
356
357 this._setMouseClickCount(event);
358
359 if (event.shiftKey) {
360 this._onShiftClick(event);
361 } else {
362 if (this._clickCount === 1) {
363 this._onSingleClick(event);
364 } else if (this._clickCount === 2) {
365 this._onDoubleClick(event);
366 } else if (this._clickCount === 3) {
367 this._onTripleClick(event);
368 }
369 }
370
371 this._addMouseDownListeners();
372 this.refresh();
373 }
374
375 /**
376 * Adds listeners when mousedown is triggered.
377 */
378 private _addMouseDownListeners(): void {
379 // Listen on the document so that dragging outside of viewport works
380 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
381 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
382 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
383 }
384
385 /**
386 * Removes the listeners that are registered when mousedown is triggered.
387 */
388 private _removeMouseDownListeners(): void {
389 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
390 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
391 clearInterval(this._dragScrollIntervalTimer);
392 this._dragScrollIntervalTimer = null;
393 }
394
395 /**
396 * Performs a shift click, setting the selection end position to the mouse
397 * position.
398 * @param event The mouse event.
399 */
400 private _onShiftClick(event: MouseEvent): void {
401 if (this._model.selectionStart) {
402 this._model.selectionEnd = this._getMouseBufferCoords(event);
403 }
404 }
405
406 /**
407 * Performs a single click, resetting relevant state and setting the selection
408 * start position.
409 * @param event The mouse event.
410 */
411 private _onSingleClick(event: MouseEvent): void {
412 this._model.selectionStartLength = 0;
413 this._model.isSelectAllActive = false;
414 this._isLineSelectModeActive = false;
415 this._model.selectionStart = this._getMouseBufferCoords(event);
416 if (this._model.selectionStart) {
417 this._model.selectionEnd = null;
418 // If the mouse is over the second half of a wide character, adjust the
419 // selection to cover the whole character
420 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
421 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
422 this._model.selectionStart[0]++;
423 }
424 }
425 }
426
427 /**
428 * Performs a double click, selecting the current work.
429 * @param event The mouse event.
430 */
431 private _onDoubleClick(event: MouseEvent): void {
432 const coords = this._getMouseBufferCoords(event);
433 if (coords) {
434 this._selectWordAt(coords);
435 }
436 }
437
438 /**
439 * Performs a triple click, selecting the current line and activating line
440 * select mode.
441 * @param event The mouse event.
442 */
443 private _onTripleClick(event: MouseEvent): void {
444 const coords = this._getMouseBufferCoords(event);
445 if (coords) {
446 this._isLineSelectModeActive = true;
447 this._selectLineAt(coords[1]);
448 }
449 }
450
451 /**
452 * Sets the number of clicks for the current mousedown event based on the time
453 * and position of the last mousedown event.
454 * @param event The mouse event.
455 */
456 private _setMouseClickCount(event: MouseEvent): void {
457 let currentTime = (new Date()).getTime();
458 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
459 this._clickCount = 0;
460 }
461 this._lastMouseDownTime = currentTime;
462 this._lastMousePosition = [event.pageX, event.pageY];
463 this._clickCount++;
464 }
465
466 /**
467 * Gets the maximum number of pixels in each direction the mouse has moved.
468 * @param event The mouse event.
469 */
470 private _distanceFromLastMousePosition(event: MouseEvent): number {
471 const result = Math.max(
472 Math.abs(this._lastMousePosition[0] - event.pageX),
473 Math.abs(this._lastMousePosition[1] - event.pageY));
474 return result;
475 }
476
477 /**
478 * Handles the mousemove event when the mouse button is down, recording the
479 * end of the selection and refreshing the selection.
480 * @param event The mousemove event.
481 */
482 private _onMouseMove(event: MouseEvent) {
483 // Record the previous position so we know whether to redraw the selection
484 // at the end.
485 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
486
487 // Set the initial selection end based on the mouse coordinates
488 this._model.selectionEnd = this._getMouseBufferCoords(event);
489
490 // Select the entire line if line select mode is active.
491 if (this._isLineSelectModeActive) {
492 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
493 this._model.selectionEnd[0] = 0;
494 } else {
495 this._model.selectionEnd[0] = this._terminal.cols;
496 }
497 }
498
499 // Determine the amount of scrolling that will happen.
500 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
501
502 // If the cursor was above or below the viewport, make sure it's at the
503 // start or end of the viewport respectively.
504 if (this._dragScrollAmount > 0) {
505 this._model.selectionEnd[0] = this._terminal.cols - 1;
506 } else if (this._dragScrollAmount < 0) {
507 this._model.selectionEnd[0] = 0;
508 }
509
510 // If the character is a wide character include the cell to the right in the
511 // selection. Note that selections at the very end of the line will never
512 // have a character.
513 if (this._model.selectionEnd[1] < this._buffer.length) {
514 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
515 if (char && char[2] === 0) {
516 this._model.selectionEnd[0]++;
517 }
518 }
519
520 // Only draw here if the selection changes.
521 if (!previousSelectionEnd ||
522 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
523 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
524 this.refresh();
525 }
526 }
527
528 /**
529 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
530 * scrolling of the viewport.
531 */
532 private _dragScroll() {
533 if (this._dragScrollAmount) {
534 this._terminal.scrollDisp(this._dragScrollAmount, false);
535 // Re-evaluate selection
536 if (this._dragScrollAmount > 0) {
537 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
538 } else {
539 this._model.selectionEnd = [0, this._terminal.ydisp];
540 }
541 this.refresh();
542 }
543 }
544
545 /**
546 * Handles the mouseup event, removing the mousedown listeners.
547 * @param event The mouseup event.
548 */
549 private _onMouseUp(event: MouseEvent) {
550 this._removeMouseDownListeners();
551 }
552
553 /**
554 * Converts a viewport column to the character index on the buffer line, the
555 * latter takes into account wide characters.
556 * @param coords The coordinates to find the 2 index for.
557 */
558 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
559 let charIndex = coords[0];
560 for (let i = 0; coords[0] >= i; i++) {
561 const char = bufferLine[i];
562 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
563 charIndex--;
564 }
565 }
566 return charIndex;
567 }
568
569 /**
570 * Selects the word at the coordinates specified. Words are defined as all
571 * non-whitespace characters.
572 * @param coords The coordinates to get the word at.
573 */
574 protected _selectWordAt(coords: [number, number]): void {
575 const bufferLine = this._buffer.get(coords[1]);
576 const line = this._translateBufferLineToString(bufferLine, false);
577
578 // Get actual index, taking into consideration wide characters
579 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
580 let startIndex = endIndex;
581
582 // Record offset to be used later
583 const charOffset = coords[0] - startIndex;
584 let leftWideCharCount = 0;
585 let rightWideCharCount = 0;
586
587 if (line.charAt(startIndex) === ' ') {
588 // Expand until non-whitespace is hit
589 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
590 startIndex--;
591 }
592 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
593 endIndex++;
594 }
595 } else {
596 // Expand until whitespace is hit. This algorithm works by scanning left
597 // and right from the starting position, keeping both the index format
598 // (line) and the column format (bufferLine) in sync. When a wide
599 // character is hit, it is recorded and the column index is adjusted.
600 let startCol = coords[0];
601 let endCol = coords[0];
602 // Consider the initial position, skip it and increment the wide char
603 // variable
604 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
605 leftWideCharCount++;
606 startCol--;
607 }
608 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
609 rightWideCharCount++;
610 endCol++;
611 }
612 // Expand the string in both directions until a space is hit
613 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
614 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
615 // If the next character is a wide char, record it and skip the column
616 leftWideCharCount++;
617 startCol--;
618 }
619 startIndex--;
620 startCol--;
621 }
622 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
623 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
624 // If the next character is a wide char, record it and skip the column
625 rightWideCharCount++;
626 endCol++;
627 }
628 endIndex++;
629 endCol++;
630 }
631 }
632
633 // Record the resulting selection
634 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
635 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
636 }
637
638 /**
639 * Selects the line specified.
640 * @param line The line index.
641 */
642 protected _selectLineAt(line: number): void {
643 this._model.selectionStart = [0, line];
644 this._model.selectionStartLength = this._terminal.cols;
645 }
646 }