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