]> git.proxmox.com Git - mirror_xterm.js.git/blame - src/SelectionManager.ts
Resolve TODOs
[mirror_xterm.js.git] / src / SelectionManager.ts
CommitLineData
70fda994
DI
1/**
2 * @license MIT
3 */
4
5import { CharMeasure } from './utils/CharMeasure';
6import { CircularList } from './utils/CircularList';
b594407c 7import { EventEmitter } from './EventEmitter';
70fda994 8import * as Mouse from './utils/Mouse';
ad3ae67e 9import { ITerminal } from './Interfaces';
f7d6ab5f 10import { SelectionModel } from './SelectionModel';
70fda994 11
0dc3dd03
DI
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 */
16const DRAG_SCROLL_MAX_THRESHOLD = 100;
17
18/**
19 * The maximum scrolling speed
20 */
21const DRAG_SCROLL_MAX_SPEED = 5;
22
23/**
24 * The number of milliseconds between drag scroll updates.
25 */
26const DRAG_SCROLL_INTERVAL = 100;
27
9f271de8 28/**
f380153f
DI
29 * The amount of time before mousedown events are no longer stacked to create
30 * double/triple click events.
9f271de8
DI
31 */
32const CLEAR_MOUSE_DOWN_TIME = 400;
33
f380153f
DI
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 */
38const CLEAR_MOUSE_DISTANCE = 10;
39
2621be81
DI
40// TODO: Move these constants elsewhere, they belong in a buffer or buffer
41// data/line class.
54e7f65d
DI
42const LINE_DATA_CHAR_INDEX = 1;
43const LINE_DATA_WIDTH_INDEX = 2;
44
b594407c 45export class SelectionManager extends EventEmitter {
fd91c5e1 46 protected _model: SelectionModel;
9f271de8
DI
47
48 /**
49 * The amount to scroll every drag scroll update (depends on how far the mouse
50 * drag is above or below the terminal).
51 */
0dc3dd03 52 private _dragScrollAmount: number;
70fda994 53
9f271de8
DI
54 /**
55 * The last time the mousedown event fired, this is used to track double and
56 * triple clicks.
57 */
58 private _lastMouseDownTime: number;
59
f380153f
DI
60 /**
61 * The last position the mouse was clicked [x, y].
62 */
63 private _lastMousePosition: [number, number];
64
2621be81
DI
65 /**
66 * The number of clicks of the mousedown event. This is used to keep track of
67 * double and triple clicks.
68 */
9f271de8
DI
69 private _clickCount: number;
70
2621be81
DI
71 /**
72 * Whether line select mode is active, this occurs after a triple click.
73 */
5bc11121
DI
74 private _isLineSelectModeActive: boolean;
75
d0b603d0
DI
76 /**
77 * A setInterval timer that is active while the mouse is down whose callback
78 * scrolls the viewport when necessary.
79 */
80 private _dragScrollIntervalTimer: NodeJS.Timer;
81
ab40908f 82 private _bufferTrimListener: any;
70fda994 83 private _mouseMoveListener: EventListener;
ab40908f
DI
84 private _mouseDownListener: EventListener;
85 private _mouseUpListener: EventListener;
70fda994 86
ad3ae67e
DI
87 constructor(
88 private _terminal: ITerminal,
89 private _buffer: CircularList<any>,
90 private _rowContainer: HTMLElement,
ad3ae67e
DI
91 private _charMeasure: CharMeasure
92 ) {
b594407c 93 super();
ab40908f
DI
94 this._initListeners();
95 this.enable();
9f271de8 96
f7d6ab5f 97 this._model = new SelectionModel(_terminal);
9f271de8 98 this._lastMouseDownTime = 0;
5bc11121 99 this._isLineSelectModeActive = false;
70fda994
DI
100 }
101
d0b603d0
DI
102 /**
103 * Initializes listener variables.
104 */
ab40908f
DI
105 private _initListeners() {
106 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
70fda994 107 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
ab40908f
DI
108 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
109 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
ab40908f 110 }
70fda994 111
ab40908f
DI
112 /**
113 * Disables the selection manager. This is useful for when terminal mouse
114 * are enabled.
115 */
116 public disable() {
f7d6ab5f
DI
117 this._model.selectionStart = null;
118 this._model.selectionEnd = null;
ab40908f
DI
119 this.refresh();
120 this._buffer.off('trim', this._bufferTrimListener);
121 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
0dc3dd03
DI
122 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
123 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
2621be81 124 clearInterval(this._dragScrollIntervalTimer);
ab40908f
DI
125 }
126
127 /**
128 * Enable the selection manager.
129 */
130 public enable() {
f380153f
DI
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.
ab40908f
DI
135 this._buffer.on('trim', this._bufferTrimListener);
136 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
70fda994
DI
137 }
138
9f271de8
DI
139 /**
140 * Gets the text currently selected.
141 */
70fda994 142 public get selectionText(): string {
f7d6ab5f
DI
143 const start = this._model.finalSelectionStart;
144 const end = this._model.finalSelectionEnd;
e29ab294 145 if (!start || !end) {
293ae18a 146 return '';
70fda994 147 }
43c796a7 148
43c796a7 149 // Get first row
293ae18a 150 const startRowEndCol = start[1] === end[1] ? end[0] : null;
32b34cbe 151 let result: string[] = [];
ec61f3ac 152 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
43c796a7
DI
153
154 // Get middle rows
293ae18a 155 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
ec61f3ac 156 result.push(this._translateBufferLineToString(this._buffer.get(i), true));
32b34cbe 157 }
43c796a7
DI
158
159 // Get final row
293ae18a 160 if (start[1] !== end[1]) {
ec61f3ac 161 result.push(this._translateBufferLineToString(this._buffer.get(end[1]), true, 0, end[0]));
32b34cbe 162 }
54e7f65d 163 console.log('selectionText result: "' + result + '"');
32b34cbe
DI
164 return result.join('\n');
165 }
166
d0b603d0
DI
167 /**
168 * Translates a buffer line to a string, with optional start and end columns.
169 * Wide characters will count as two columns in the resulting string. This
170 * function is useful for getting the actual text underneath the raw selection
171 * position.
172 * @param line The line being translated.
173 * @param trimRight Whether to trim whitespace to the right.
174 * @param startCol The column to start at.
175 * @param endCol The column to end at.
176 */
ec61f3ac 177 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
32b34cbe 178 // TODO: This function should live in a buffer or buffer line class
ec61f3ac
DI
179
180 // Get full line
181 let lineString = '';
54e7f65d
DI
182 let widthAdjustedStartCol = startCol;
183 let widthAdjustedEndCol = endCol;
ec61f3ac 184 for (let i = 0; i < line.length; i++) {
54e7f65d
DI
185 const char = line[i];
186 lineString += char[LINE_DATA_CHAR_INDEX];
187 // Adjust start and end cols for wide characters if they affect their
188 // column indexes
189 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
190 if (startCol >= i) {
191 widthAdjustedStartCol--;
192 }
193 if (endCol >= i) {
194 widthAdjustedEndCol--;
195 }
196 }
ec61f3ac
DI
197 }
198
54e7f65d
DI
199 // Calculate the final end col by trimming whitespace on the right of the
200 // line if needed.
d3865ad2 201 let finalEndCol = widthAdjustedEndCol || line.length;
ec61f3ac
DI
202 if (trimRight) {
203 const rightWhitespaceIndex = lineString.search(/\s+$/);
a53a0acd
DI
204 if (rightWhitespaceIndex !== -1) {
205 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
206 }
ec61f3ac 207 // Return the empty string if only trimmed whitespace is selected
54e7f65d 208 if (finalEndCol <= widthAdjustedStartCol) {
ec61f3ac
DI
209 return '';
210 }
211 }
212
54e7f65d 213 return lineString.substring(widthAdjustedStartCol, finalEndCol);
70fda994
DI
214 }
215
207c4cf9
DI
216 /**
217 * Redraws the selection.
218 */
219 public refresh(): void {
f7d6ab5f 220 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
25152e44
DI
221 }
222
223 /**
224 * Selects all text within the terminal.
225 */
226 public selectAll(): void {
f7d6ab5f 227 this._model.isSelectAllActive = true;
25152e44 228 this.refresh();
207c4cf9
DI
229 }
230
231 /**
232 * Handle the buffer being trimmed, adjust the selection position.
233 * @param amount The amount the buffer is being trimmed.
234 */
70fda994 235 private _onTrim(amount: number) {
f7d6ab5f
DI
236 const needsRefresh = this._model.onTrim(amount);
237 if (needsRefresh) {
207c4cf9 238 this.refresh();
207c4cf9 239 }
70fda994
DI
240 }
241
d0b603d0
DI
242 /**
243 * Gets the 0-based [x, y] buffer coordinates of the current mouse event.
244 * @param event The mouse event.
245 */
0dc3dd03
DI
246 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
247 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
248 console.log(coords);
ad3ae67e
DI
249 // Convert to 0-based
250 coords[0]--;
251 coords[1]--;
252 // Convert viewport coords to buffer coords
253 coords[1] += this._terminal.ydisp;
254 return coords;
b36d8780
DI
255 }
256
d0b603d0
DI
257 /**
258 * Gets the amount the viewport should be scrolled based on how far out of the
259 * terminal the mouse is.
260 * @param event The mouse event.
261 */
0dc3dd03
DI
262 private _getMouseEventScrollAmount(event: MouseEvent): number {
263 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
264 const terminalHeight = this._terminal.rows * this._charMeasure.height;
265 if (offset >= 0 && offset <= terminalHeight) {
266 return 0;
267 }
268 if (offset > terminalHeight) {
269 offset -= terminalHeight;
270 }
271
272 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
273 offset /= DRAG_SCROLL_MAX_THRESHOLD;
274 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
275 }
276
e63fdf58
DI
277 /**
278 * Handles te mousedown event, setting up for a new selection.
279 * @param event The mousedown event.
280 */
70fda994 281 private _onMouseDown(event: MouseEvent) {
0dc3dd03
DI
282 // Only action the primary button
283 if (event.button !== 0) {
284 return;
285 }
286
f380153f 287 this._setMouseClickCount(event);
9f271de8
DI
288 console.log(this._clickCount);
289
db8ded2a
DI
290 if (event.shiftKey) {
291 this._onShiftClick(event);
292 } else {
293 if (this._clickCount === 1) {
294 this._onSingleClick(event);
295 } else if (this._clickCount === 2) {
296 this._onDoubleClick(event);
297 } else if (this._clickCount === 3) {
298 this._onTripleClick(event);
299 }
9f271de8 300 }
e29ab294
DI
301
302 // Listen on the document so that dragging outside of viewport works
303 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
304 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
2621be81 305 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
e29ab294 306 this.refresh();
9f271de8
DI
307 }
308
d0b603d0
DI
309 /**
310 * Performs a shift click, setting the selection end position to the mouse
311 * position.
312 * @param event The mouse event.
313 */
db8ded2a
DI
314 private _onShiftClick(event: MouseEvent): void {
315 if (this._model.selectionStart) {
316 this._model.selectionEnd = this._getMouseBufferCoords(event);
317 }
318 }
319
d0b603d0
DI
320 /**
321 * Performs a single click, resetting relevant state and setting the selection
322 * start position.
323 * @param event The mouse event.
324 */
9f271de8 325 private _onSingleClick(event: MouseEvent): void {
f7d6ab5f
DI
326 this._model.selectionStartLength = 0;
327 this._model.isSelectAllActive = false;
5bc11121 328 this._isLineSelectModeActive = false;
f7d6ab5f
DI
329 this._model.selectionStart = this._getMouseBufferCoords(event);
330 if (this._model.selectionStart) {
331 this._model.selectionEnd = null;
54e7f65d
DI
332 // If the mouse is over the second half of a wide character, adjust the
333 // selection to cover the whole character
334 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
335 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
336 this._model.selectionStart[0]++;
337 }
70fda994
DI
338 }
339 }
340
d0b603d0
DI
341 /**
342 * Performs a double click, selecting the current work.
343 * @param event The mouse event.
344 */
9f271de8
DI
345 private _onDoubleClick(event: MouseEvent): void {
346 const coords = this._getMouseBufferCoords(event);
347 if (coords) {
348 this._selectWordAt(coords);
349 }
350 }
351
d0b603d0
DI
352 /**
353 * Performs a triple click, selecting the current line and activating line
354 * select mode.
355 * @param event The mouse event.
356 */
9f271de8
DI
357 private _onTripleClick(event: MouseEvent): void {
358 const coords = this._getMouseBufferCoords(event);
359 if (coords) {
5bc11121 360 this._isLineSelectModeActive = true;
9f271de8
DI
361 this._selectLineAt(coords[1]);
362 }
363 }
364
d0b603d0
DI
365 /**
366 * Sets the number of clicks for the current mousedown event based on the time
367 * and position of the last mousedown event.
368 * @param event The mouse event.
369 */
f380153f 370 private _setMouseClickCount(event: MouseEvent): void {
9f271de8 371 let currentTime = (new Date()).getTime();
f380153f 372 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
9f271de8 373 this._clickCount = 0;
d3865ad2
DI
374 }
375 this._lastMouseDownTime = currentTime;
f380153f 376 this._lastMousePosition = [event.pageX, event.pageY];
9f271de8 377 this._clickCount++;
f380153f 378 }
9f271de8 379
d0b603d0
DI
380 /**
381 * Gets the maximum number of pixels in each direction the mouse has moved.
382 * @param event The mouse event.
383 */
f380153f
DI
384 private _distanceFromLastMousePosition(event: MouseEvent): number {
385 const result = Math.max(
386 Math.abs(this._lastMousePosition[0] - event.pageX),
387 Math.abs(this._lastMousePosition[1] - event.pageY));
388 return result;
9f271de8
DI
389 }
390
e63fdf58
DI
391 /**
392 * Handles the mousemove event when the mouse button is down, recording the
393 * end of the selection and refreshing the selection.
394 * @param event The mousemove event.
395 */
70fda994 396 private _onMouseMove(event: MouseEvent) {
2621be81
DI
397 // Record the previous position so we know whether to redraw the selection
398 // at the end.
399 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
400
401 // Set the initial selection end based on the mouse coordinates
402 this._model.selectionEnd = this._getMouseBufferCoords(event);
403
404 // Select the entire line if line select mode is active.
5bc11121 405 if (this._isLineSelectModeActive) {
5bc11121
DI
406 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
407 this._model.selectionEnd[0] = 0;
408 } else {
409 this._model.selectionEnd[0] = this._terminal.cols;
410 }
5bc11121
DI
411 }
412
2621be81 413 // Determine the amount of scrolling that will happen.
0dc3dd03 414 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
2621be81 415
0dc3dd03 416 // If the cursor was above or below the viewport, make sure it's at the
2621be81 417 // start or end of the viewport respectively.
0dc3dd03 418 if (this._dragScrollAmount > 0) {
f7d6ab5f 419 this._model.selectionEnd[0] = this._terminal.cols - 1;
0dc3dd03 420 } else if (this._dragScrollAmount < 0) {
f7d6ab5f 421 this._model.selectionEnd[0] = 0;
0dc3dd03 422 }
54e7f65d
DI
423
424 // If the character is a wide character include the cell to the right in the
5bc11121
DI
425 // selection. Note that selections at the very end of the line will never
426 // have a character.
cb6533f3 427 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
5bc11121 428 if (char && char[2] === 0) {
54e7f65d
DI
429 this._model.selectionEnd[0]++;
430 }
431
2621be81
DI
432 // Only draw here if the selection changes.
433 if (!previousSelectionEnd ||
434 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
435 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
436 this.refresh();
437 }
70fda994
DI
438 }
439
d0b603d0
DI
440 /**
441 * The callback that occurs every DRAG_SCROLL_INTERVAL ms that does the
442 * scrolling of the viewport.
443 */
0dc3dd03
DI
444 private _dragScroll() {
445 if (this._dragScrollAmount) {
446 this._terminal.scrollDisp(this._dragScrollAmount, false);
447 // Re-evaluate selection
448 if (this._dragScrollAmount > 0) {
f7d6ab5f 449 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
0dc3dd03 450 } else {
f7d6ab5f 451 this._model.selectionEnd = [0, this._terminal.ydisp];
0dc3dd03
DI
452 }
453 this.refresh();
454 }
455 }
456
e63fdf58
DI
457 /**
458 * Handles the mouseup event, removing the mousemove listener when
459 * appropriate.
460 * @param event The mouseup event.
461 */
70fda994 462 private _onMouseUp(event: MouseEvent) {
b3b2bd1f 463 this._dragScrollAmount = 0;
f7d6ab5f 464 if (!this._model.selectionStart) {
70fda994
DI
465 return;
466 }
0dc3dd03
DI
467 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
468 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
70fda994 469 }
597c6939 470
cb6533f3
DI
471 /**
472 * Converts a viewport column to the character index on the buffer line, the
473 * latter takes into account wide characters.
d3865ad2 474 * @param coords The coordinates to find the 2 index for.
cb6533f3 475 */
11cec31d 476 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
cb6533f3 477 let charIndex = coords[0];
d9991b25 478 for (let i = 0; coords[0] >= i; i++) {
11cec31d 479 const char = bufferLine[i];
cb6533f3
DI
480 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
481 charIndex--;
482 }
483 }
484 return charIndex;
485 }
486
597c6939
DI
487 /**
488 * Selects the word at the coordinates specified. Words are defined as all
489 * non-whitespace characters.
490 * @param coords The coordinates to get the word at.
491 */
a53a0acd 492 protected _selectWordAt(coords: [number, number]): void {
11cec31d
DI
493 const bufferLine = this._buffer.get(coords[1]);
494 const line = this._translateBufferLineToString(bufferLine, false);
cb6533f3
DI
495
496 // Get actual index, taking into consideration wide characters
11cec31d 497 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
cb6533f3 498 let startIndex = endIndex;
cb6533f3
DI
499
500 // Record offset to be used later
501 const charOffset = coords[0] - startIndex;
11cec31d
DI
502 let leftWideCharCount = 0;
503 let rightWideCharCount = 0;
cb6533f3 504
cb6533f3 505 if (line.charAt(startIndex) === ' ') {
11cec31d 506 // Expand until non-whitespace is hit
cb6533f3
DI
507 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
508 startIndex--;
509 }
510 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
511 endIndex++;
512 }
cb6533f3 513 } else {
11cec31d
DI
514 // Expand until whitespace is hit. This algorithm works by scanning left
515 // and right from the starting position, keeping both the index format
516 // (line) and the column format (bufferLine) in sync. When a wide
517 // character is hit, it is recorded and the column index is adjusted.
d9991b25
DI
518 let startCol = coords[0];
519 let endCol = coords[0];
520 // Consider the initial position, skip it and increment the wide char
521 // variable
11cec31d 522 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
d9991b25
DI
523 leftWideCharCount++;
524 startCol--;
525 }
11cec31d 526 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
d9991b25
DI
527 rightWideCharCount++;
528 endCol++;
529 }
cb6533f3
DI
530 // Expand the string in both directions until a space is hit
531 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
11cec31d
DI
532 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
533 // If the next character is a wide char, record it and skip the column
d9991b25
DI
534 leftWideCharCount++;
535 startCol--;
cb6533f3
DI
536 }
537 startIndex--;
d9991b25 538 startCol--;
cb6533f3 539 }
d3865ad2 540 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
11cec31d
DI
541 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
542 // If the next character is a wide char, record it and skip the column
d9991b25
DI
543 rightWideCharCount++;
544 endCol++;
cb6533f3
DI
545 }
546 endIndex++;
d9991b25 547 endCol++;
cb6533f3 548 }
597c6939 549 }
11cec31d
DI
550
551 // Record the resulting selection
d9991b25 552 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
f61d852f 553 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
597c6939 554 }
9f271de8 555
d0b603d0
DI
556 /**
557 * Selects the line specified.
558 * @param line The line index.
559 */
fd91c5e1 560 protected _selectLineAt(line: number): void {
f7d6ab5f
DI
561 this._model.selectionStart = [0, line];
562 this._model.selectionStartLength = this._terminal.cols;
9f271de8 563 }
70fda994 564}