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