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