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