]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Merge remote-tracking branch 'origin/master' into 553_find_api
[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 import { translateBufferLineToString } from './utils/BufferLine';
12
13 /**
14 * The number of pixels the mouse needs to be above or below the viewport in
15 * order to scroll at the maximum speed.
16 */
17 const DRAG_SCROLL_MAX_THRESHOLD = 50;
18
19 /**
20 * The maximum scrolling speed
21 */
22 const DRAG_SCROLL_MAX_SPEED = 15;
23
24 /**
25 * The number of milliseconds between drag scroll updates.
26 */
27 const DRAG_SCROLL_INTERVAL = 50;
28
29 /**
30 * The amount of time before mousedown events are no longer stacked to create
31 * double/triple click events.
32 */
33 const CLEAR_MOUSE_DOWN_TIME = 400;
34
35 /**
36 * The number of pixels in each direction that the mouse must move before
37 * mousedown events are no longer stacked to create double/triple click events.
38 */
39 const CLEAR_MOUSE_DISTANCE = 10;
40
41 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
42 // data/line class.
43 const LINE_DATA_CHAR_INDEX = 1;
44 const LINE_DATA_WIDTH_INDEX = 2;
45
46 const NON_BREAKING_SPACE_CHAR = String.fromCharCode(160);
47 const ALL_NON_BREAKING_SPACE_REGEX = new RegExp(NON_BREAKING_SPACE_CHAR, 'g');
48
49 /**
50 * A class that manages the selection of the terminal. With help from
51 * SelectionModel, SelectionManager handles with all logic associated with
52 * dealing with the selection, including handling mouse interaction, wide
53 * characters and fetching the actual text within the selection. Rendering is
54 * not handled by the SelectionManager but a 'refresh' event is fired when the
55 * selection is ready to be redrawn.
56 */
57 export class SelectionManager extends EventEmitter {
58 protected _model: SelectionModel;
59
60 /**
61 * The amount to scroll every drag scroll update (depends on how far the mouse
62 * drag is above or below the terminal).
63 */
64 private _dragScrollAmount: number;
65
66 /**
67 * The last time the mousedown event fired, this is used to track double and
68 * triple clicks.
69 */
70 private _lastMouseDownTime: number;
71
72 /**
73 * The last position the mouse was clicked [x, y].
74 */
75 private _lastMousePosition: [number, number];
76
77 /**
78 * The number of clicks of the mousedown event. This is used to keep track of
79 * double and triple clicks.
80 */
81 private _clickCount: number;
82
83 /**
84 * Whether line select mode is active, this occurs after a triple click.
85 */
86 private _isLineSelectModeActive: boolean;
87
88 /**
89 * A setInterval timer that is active while the mouse is down whose callback
90 * scrolls the viewport when necessary.
91 */
92 private _dragScrollIntervalTimer: NodeJS.Timer;
93
94 /**
95 * The animation frame ID used for refreshing the selection.
96 */
97 private _refreshAnimationFrame: number;
98
99 private _bufferTrimListener: any;
100 private _mouseMoveListener: EventListener;
101 private _mouseDownListener: EventListener;
102 private _mouseUpListener: EventListener;
103
104 constructor(
105 private _terminal: ITerminal,
106 private _buffer: CircularList<any>,
107 private _rowContainer: HTMLElement,
108 private _charMeasure: CharMeasure
109 ) {
110 super();
111 this._initListeners();
112 this.enable();
113
114 this._model = new SelectionModel(_terminal);
115 this._lastMouseDownTime = 0;
116 this._isLineSelectModeActive = false;
117 }
118
119 /**
120 * Initializes listener variables.
121 */
122 private _initListeners() {
123 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
124 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
125 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
126 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
127 }
128
129 /**
130 * Disables the selection manager. This is useful for when terminal mouse
131 * are enabled.
132 */
133 public disable() {
134 this.clearSelection();
135 this._buffer.off('trim', this._bufferTrimListener);
136 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
137 }
138
139 /**
140 * Enable the selection manager.
141 */
142 public enable() {
143 // Only adjust the selection on trim, shiftElements is rarely used (only in
144 // reverseIndex) and delete in a splice is only ever used when the same
145 // number of elements was just added. Given this is could actually be
146 // beneficial to leave the selection as is for these cases.
147 this._buffer.on('trim', this._bufferTrimListener);
148 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
149 }
150
151 /**
152 * Sets the active buffer, this should be called when the alt buffer is
153 * switched in or out.
154 * @param buffer The active buffer.
155 */
156 public setBuffer(buffer: CircularList<any>): void {
157 this._buffer = buffer;
158 }
159
160 public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
161 public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
162
163 /**
164 * Gets whether there is an active text selection.
165 */
166 public get hasSelection(): boolean {
167 return !!this._model.finalSelectionStart && !!this._model.finalSelectionEnd;
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 (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 (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('\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 */
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 // Tell the browser not to start a regular selection
307 event.preventDefault();
308
309 // Reset drag scroll state
310 this._dragScrollAmount = 0;
311
312 this._setMouseClickCount(event);
313
314 if (event.shiftKey) {
315 this._onShiftClick(event);
316 } else {
317 if (this._clickCount === 1) {
318 this._onSingleClick(event);
319 } else if (this._clickCount === 2) {
320 this._onDoubleClick(event);
321 } else if (this._clickCount === 3) {
322 this._onTripleClick(event);
323 }
324 }
325
326 this._addMouseDownListeners();
327 this.refresh();
328 }
329
330 /**
331 * Adds listeners when mousedown is triggered.
332 */
333 private _addMouseDownListeners(): void {
334 // Listen on the document so that dragging outside of viewport works
335 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
336 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
337 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
338 }
339
340 /**
341 * Removes the listeners that are registered when mousedown is triggered.
342 */
343 private _removeMouseDownListeners(): void {
344 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
345 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
346 clearInterval(this._dragScrollIntervalTimer);
347 this._dragScrollIntervalTimer = null;
348 }
349
350 /**
351 * Performs a shift click, setting the selection end position to the mouse
352 * position.
353 * @param event The mouse event.
354 */
355 private _onShiftClick(event: MouseEvent): void {
356 if (this._model.selectionStart) {
357 this._model.selectionEnd = this._getMouseBufferCoords(event);
358 }
359 }
360
361 /**
362 * Performs a single click, resetting relevant state and setting the selection
363 * start position.
364 * @param event The mouse event.
365 */
366 private _onSingleClick(event: MouseEvent): void {
367 this._model.selectionStartLength = 0;
368 this._model.isSelectAllActive = false;
369 this._isLineSelectModeActive = false;
370 this._model.selectionStart = this._getMouseBufferCoords(event);
371 if (this._model.selectionStart) {
372 this._model.selectionEnd = null;
373 // If the mouse is over the second half of a wide character, adjust the
374 // selection to cover the whole character
375 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
376 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
377 this._model.selectionStart[0]++;
378 }
379 }
380 }
381
382 /**
383 * Performs a double click, selecting the current work.
384 * @param event The mouse event.
385 */
386 private _onDoubleClick(event: MouseEvent): void {
387 const coords = this._getMouseBufferCoords(event);
388 if (coords) {
389 this._selectWordAt(coords);
390 }
391 }
392
393 /**
394 * Performs a triple click, selecting the current line and activating line
395 * select mode.
396 * @param event The mouse event.
397 */
398 private _onTripleClick(event: MouseEvent): void {
399 const coords = this._getMouseBufferCoords(event);
400 if (coords) {
401 this._isLineSelectModeActive = true;
402 this._selectLineAt(coords[1]);
403 }
404 }
405
406 /**
407 * Sets the number of clicks for the current mousedown event based on the time
408 * and position of the last mousedown event.
409 * @param event The mouse event.
410 */
411 private _setMouseClickCount(event: MouseEvent): void {
412 let currentTime = (new Date()).getTime();
413 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
414 this._clickCount = 0;
415 }
416 this._lastMouseDownTime = currentTime;
417 this._lastMousePosition = [event.pageX, event.pageY];
418 this._clickCount++;
419 }
420
421 /**
422 * Gets the maximum number of pixels in each direction the mouse has moved.
423 * @param event The mouse event.
424 */
425 private _distanceFromLastMousePosition(event: MouseEvent): number {
426 const result = Math.max(
427 Math.abs(this._lastMousePosition[0] - event.pageX),
428 Math.abs(this._lastMousePosition[1] - event.pageY));
429 return result;
430 }
431
432 /**
433 * Handles the mousemove event when the mouse button is down, recording the
434 * end of the selection and refreshing the selection.
435 * @param event The mousemove event.
436 */
437 private _onMouseMove(event: MouseEvent) {
438 // Record the previous position so we know whether to redraw the selection
439 // at the end.
440 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
441
442 // Set the initial selection end based on the mouse coordinates
443 this._model.selectionEnd = this._getMouseBufferCoords(event);
444
445 // Select the entire line if line select mode is active.
446 if (this._isLineSelectModeActive) {
447 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
448 this._model.selectionEnd[0] = 0;
449 } else {
450 this._model.selectionEnd[0] = this._terminal.cols;
451 }
452 }
453
454 // Determine the amount of scrolling that will happen.
455 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
456
457 // If the cursor was above or below the viewport, make sure it's at the
458 // start or end of the viewport respectively.
459 if (this._dragScrollAmount > 0) {
460 this._model.selectionEnd[0] = this._terminal.cols - 1;
461 } else if (this._dragScrollAmount < 0) {
462 this._model.selectionEnd[0] = 0;
463 }
464
465 // If the character is a wide character include the cell to the right in the
466 // selection. Note that selections at the very end of the line will never
467 // have a character.
468 if (this._model.selectionEnd[1] < this._buffer.length) {
469 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
470 if (char && char[2] === 0) {
471 this._model.selectionEnd[0]++;
472 }
473 }
474
475 // Only draw here if the selection changes.
476 if (!previousSelectionEnd ||
477 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
478 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
479 this.refresh();
480 }
481 }
482
483 /**
484 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
485 * scrolling of the viewport.
486 */
487 private _dragScroll() {
488 if (this._dragScrollAmount) {
489 this._terminal.scrollDisp(this._dragScrollAmount, false);
490 // Re-evaluate selection
491 if (this._dragScrollAmount > 0) {
492 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
493 } else {
494 this._model.selectionEnd = [0, this._terminal.ydisp];
495 }
496 this.refresh();
497 }
498 }
499
500 /**
501 * Handles the mouseup event, removing the mousedown listeners.
502 * @param event The mouseup event.
503 */
504 private _onMouseUp(event: MouseEvent) {
505 this._removeMouseDownListeners();
506 }
507
508 /**
509 * Converts a viewport column to the character index on the buffer line, the
510 * latter takes into account wide characters.
511 * @param coords The coordinates to find the 2 index for.
512 */
513 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
514 let charIndex = coords[0];
515 for (let i = 0; coords[0] >= i; i++) {
516 const char = bufferLine[i];
517 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
518 charIndex--;
519 }
520 }
521 return charIndex;
522 }
523
524 public setSelection(col: number, row: number, length: number): void {
525 this._model.clearSelection();
526 this._removeMouseDownListeners();
527 console.log('setSelection', arguments);
528 this._model.selectionStart = [col, row];
529 this._model.selectionStartLength = length;
530 this.refresh();
531 }
532
533 /**
534 * Selects the word at the coordinates specified. Words are defined as all
535 * non-whitespace characters.
536 * @param coords The coordinates to get the word at.
537 */
538 protected _selectWordAt(coords: [number, number]): void {
539 const bufferLine = this._buffer.get(coords[1]);
540 const line = translateBufferLineToString(bufferLine, false);
541
542 // Get actual index, taking into consideration wide characters
543 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
544 let startIndex = endIndex;
545
546 // Record offset to be used later
547 const charOffset = coords[0] - startIndex;
548 let leftWideCharCount = 0;
549 let rightWideCharCount = 0;
550
551 if (line.charAt(startIndex) === ' ') {
552 // Expand until non-whitespace is hit
553 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
554 startIndex--;
555 }
556 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
557 endIndex++;
558 }
559 } else {
560 // Expand until whitespace is hit. This algorithm works by scanning left
561 // and right from the starting position, keeping both the index format
562 // (line) and the column format (bufferLine) in sync. When a wide
563 // character is hit, it is recorded and the column index is adjusted.
564 let startCol = coords[0];
565 let endCol = coords[0];
566 // Consider the initial position, skip it and increment the wide char
567 // variable
568 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
569 leftWideCharCount++;
570 startCol--;
571 }
572 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
573 rightWideCharCount++;
574 endCol++;
575 }
576 // Expand the string in both directions until a space is hit
577 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
578 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
579 // If the next character is a wide char, record it and skip the column
580 leftWideCharCount++;
581 startCol--;
582 }
583 startIndex--;
584 startCol--;
585 }
586 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
587 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
588 // If the next character is a wide char, record it and skip the column
589 rightWideCharCount++;
590 endCol++;
591 }
592 endIndex++;
593 endCol++;
594 }
595 }
596
597 // Record the resulting selection
598 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
599 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
600 }
601
602 /**
603 * Selects the line specified.
604 * @param line The line index.
605 */
606 protected _selectLineAt(line: number): void {
607 this._model.selectionStart = [0, line];
608 this._model.selectionStartLength = this._terminal.cols;
609 }
610 }