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