]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Consolidate translateBufferLineToString functions
[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 result.push(translateBufferLineToString(this._buffer.get(i), true));
188 }
189
190 // Get final row
191 if (start[1] !== end[1]) {
192 result.push(translateBufferLineToString(this._buffer.get(end[1]), true, 0, end[0]));
193 }
194
195 // Format string by replacing non-breaking space chars with regular spaces
196 // and joining the array into a multi-line string.
197 const formattedResult = result.map(line => {
198 return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
199 }).join('\n');
200
201 return formattedResult;
202 }
203
204 /**
205 * Clears the current terminal selection.
206 */
207 public clearSelection(): void {
208 this._model.clearSelection();
209 this._removeMouseDownListeners();
210 this.refresh();
211 }
212
213 /**
214 * Queues a refresh, redrawing the selection on the next opportunity.
215 */
216 public refresh(): void {
217 if (!this._refreshAnimationFrame) {
218 this._refreshAnimationFrame = window.requestAnimationFrame(() => this._refresh());
219 }
220 }
221
222 /**
223 * Fires the refresh event, causing consumers to pick it up and redraw the
224 * selection state.
225 */
226 private _refresh(): void {
227 this._refreshAnimationFrame = null;
228 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
229 }
230
231 /**
232 * Selects all text within the terminal.
233 */
234 public selectAll(): void {
235 this._model.isSelectAllActive = true;
236 this.refresh();
237 }
238
239 /**
240 * Handle the buffer being trimmed, adjust the selection position.
241 * @param amount The amount the buffer is being trimmed.
242 */
243 private _onTrim(amount: number) {
244 const needsRefresh = this._model.onTrim(amount);
245 if (needsRefresh) {
246 this.refresh();
247 }
248 }
249
250 /**
251 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
252 * @param event The mouse event.
253 */
254 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
255 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
256 // Convert to 0-based
257 coords[0]--;
258 coords[1]--;
259 // Convert viewport coords to buffer coords
260 coords[1] += this._terminal.ydisp;
261 return coords;
262 }
263
264 /**
265 * Gets the amount the viewport should be scrolled based on how far out of the
266 * terminal the mouse is.
267 * @param event The mouse event.
268 */
269 private _getMouseEventScrollAmount(event: MouseEvent): number {
270 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
271 const terminalHeight = this._terminal.rows * this._charMeasure.height;
272 if (offset >= 0 && offset <= terminalHeight) {
273 return 0;
274 }
275 if (offset > terminalHeight) {
276 offset -= terminalHeight;
277 }
278
279 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
280 offset /= DRAG_SCROLL_MAX_THRESHOLD;
281 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
282 }
283
284 /**
285 * Handles te mousedown event, setting up for a new selection.
286 * @param event The mousedown event.
287 */
288 private _onMouseDown(event: MouseEvent) {
289 // Only action the primary button
290 if (event.button !== 0) {
291 return;
292 }
293
294 // Reset drag scroll state
295 this._dragScrollAmount = 0;
296
297 this._setMouseClickCount(event);
298
299 if (event.shiftKey) {
300 this._onShiftClick(event);
301 } else {
302 if (this._clickCount === 1) {
303 this._onSingleClick(event);
304 } else if (this._clickCount === 2) {
305 this._onDoubleClick(event);
306 } else if (this._clickCount === 3) {
307 this._onTripleClick(event);
308 }
309 }
310
311 this._addMouseDownListeners();
312 this.refresh();
313 }
314
315 /**
316 * Adds listeners when mousedown is triggered.
317 */
318 private _addMouseDownListeners(): void {
319 // Listen on the document so that dragging outside of viewport works
320 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
321 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
322 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
323 }
324
325 /**
326 * Removes the listeners that are registered when mousedown is triggered.
327 */
328 private _removeMouseDownListeners(): void {
329 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
330 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
331 clearInterval(this._dragScrollIntervalTimer);
332 this._dragScrollIntervalTimer = null;
333 }
334
335 /**
336 * Performs a shift click, setting the selection end position to the mouse
337 * position.
338 * @param event The mouse event.
339 */
340 private _onShiftClick(event: MouseEvent): void {
341 if (this._model.selectionStart) {
342 this._model.selectionEnd = this._getMouseBufferCoords(event);
343 }
344 }
345
346 /**
347 * Performs a single click, resetting relevant state and setting the selection
348 * start position.
349 * @param event The mouse event.
350 */
351 private _onSingleClick(event: MouseEvent): void {
352 this._model.selectionStartLength = 0;
353 this._model.isSelectAllActive = false;
354 this._isLineSelectModeActive = false;
355 this._model.selectionStart = this._getMouseBufferCoords(event);
356 if (this._model.selectionStart) {
357 this._model.selectionEnd = null;
358 // If the mouse is over the second half of a wide character, adjust the
359 // selection to cover the whole character
360 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
361 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
362 this._model.selectionStart[0]++;
363 }
364 }
365 }
366
367 /**
368 * Performs a double click, selecting the current work.
369 * @param event The mouse event.
370 */
371 private _onDoubleClick(event: MouseEvent): void {
372 const coords = this._getMouseBufferCoords(event);
373 if (coords) {
374 this._selectWordAt(coords);
375 }
376 }
377
378 /**
379 * Performs a triple click, selecting the current line and activating line
380 * select mode.
381 * @param event The mouse event.
382 */
383 private _onTripleClick(event: MouseEvent): void {
384 const coords = this._getMouseBufferCoords(event);
385 if (coords) {
386 this._isLineSelectModeActive = true;
387 this._selectLineAt(coords[1]);
388 }
389 }
390
391 /**
392 * Sets the number of clicks for the current mousedown event based on the time
393 * and position of the last mousedown event.
394 * @param event The mouse event.
395 */
396 private _setMouseClickCount(event: MouseEvent): void {
397 let currentTime = (new Date()).getTime();
398 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
399 this._clickCount = 0;
400 }
401 this._lastMouseDownTime = currentTime;
402 this._lastMousePosition = [event.pageX, event.pageY];
403 this._clickCount++;
404 }
405
406 /**
407 * Gets the maximum number of pixels in each direction the mouse has moved.
408 * @param event The mouse event.
409 */
410 private _distanceFromLastMousePosition(event: MouseEvent): number {
411 const result = Math.max(
412 Math.abs(this._lastMousePosition[0] - event.pageX),
413 Math.abs(this._lastMousePosition[1] - event.pageY));
414 return result;
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._isLineSelectModeActive) {
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 }
438
439 // Determine the amount of scrolling that will happen.
440 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
441
442 // If the cursor was above or below the viewport, make sure it's at the
443 // start or end of the viewport respectively.
444 if (this._dragScrollAmount > 0) {
445 this._model.selectionEnd[0] = this._terminal.cols - 1;
446 } else if (this._dragScrollAmount < 0) {
447 this._model.selectionEnd[0] = 0;
448 }
449
450 // If the character is a wide character include the cell to the right in the
451 // selection. Note that selections at the very end of the line will never
452 // have a character.
453 if (this._model.selectionEnd[1] < this._buffer.length) {
454 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
455 if (char && char[2] === 0) {
456 this._model.selectionEnd[0]++;
457 }
458 }
459
460 // Only draw here if the selection changes.
461 if (!previousSelectionEnd ||
462 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
463 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
464 this.refresh();
465 }
466 }
467
468 /**
469 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
470 * scrolling of the viewport.
471 */
472 private _dragScroll() {
473 if (this._dragScrollAmount) {
474 this._terminal.scrollDisp(this._dragScrollAmount, false);
475 // Re-evaluate selection
476 if (this._dragScrollAmount > 0) {
477 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
478 } else {
479 this._model.selectionEnd = [0, this._terminal.ydisp];
480 }
481 this.refresh();
482 }
483 }
484
485 /**
486 * Handles the mouseup event, removing the mousedown listeners.
487 * @param event The mouseup event.
488 */
489 private _onMouseUp(event: MouseEvent) {
490 this._removeMouseDownListeners();
491 }
492
493 /**
494 * Converts a viewport column to the character index on the buffer line, the
495 * latter takes into account wide characters.
496 * @param coords The coordinates to find the 2 index for.
497 */
498 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
499 let charIndex = coords[0];
500 for (let i = 0; coords[0] >= i; i++) {
501 const char = bufferLine[i];
502 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
503 charIndex--;
504 }
505 }
506 return charIndex;
507 }
508
509 public setSelection(col: number, row: number, length: number): void {
510 this._model.clearSelection();
511 this._removeMouseDownListeners();
512 console.log('setSelection', arguments);
513 this._model.selectionStart = [col, row];
514 this._model.selectionStartLength = length;
515 this.refresh();
516 }
517
518 /**
519 * Selects the word at the coordinates specified. Words are defined as all
520 * non-whitespace characters.
521 * @param coords The coordinates to get the word at.
522 */
523 protected _selectWordAt(coords: [number, number]): void {
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 && 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 && 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 // Record the resulting selection
583 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
584 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
585 }
586
587 /**
588 * Selects the line specified.
589 * @param line The line index.
590 */
591 protected _selectLineAt(line: number): void {
592 this._model.selectionStart = [0, line];
593 this._model.selectionStartLength = this._terminal.cols;
594 }
595 }