]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/SelectionManager.ts
Resolve more TODOs, add jsdoc
[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 = 100;
17
18 /**
19 * The maximum scrolling speed
20 */
21 const DRAG_SCROLL_MAX_SPEED = 5;
22
23 /**
24 * The number of milliseconds between drag scroll updates.
25 */
26 const DRAG_SCROLL_INTERVAL = 100;
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 export class SelectionManager extends EventEmitter {
46 protected _model: SelectionModel;
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 */
52 private _dragScrollAmount: number;
53
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
60 /**
61 * The last position the mouse was clicked [x, y].
62 */
63 private _lastMousePosition: [number, number];
64
65 /**
66 * The number of clicks of the mousedown event. This is used to keep track of
67 * double and triple clicks.
68 */
69 private _clickCount: number;
70
71 /**
72 * Whether line select mode is active, this occurs after a triple click.
73 */
74 private _isLineSelectModeActive: boolean;
75
76 private _bufferTrimListener: any;
77 private _mouseMoveListener: EventListener;
78 private _mouseDownListener: EventListener;
79 private _mouseUpListener: EventListener;
80
81 private _dragScrollIntervalTimer: NodeJS.Timer;
82
83 constructor(
84 private _terminal: ITerminal,
85 private _buffer: CircularList<any>,
86 private _rowContainer: HTMLElement,
87 private _charMeasure: CharMeasure
88 ) {
89 super();
90 this._initListeners();
91 this.enable();
92
93 this._model = new SelectionModel(_terminal);
94 this._lastMouseDownTime = 0;
95 this._isLineSelectModeActive = false;
96 }
97
98 private _initListeners() {
99 this._bufferTrimListener = (amount: number) => this._onTrim(amount);
100 this._mouseMoveListener = event => this._onMouseMove(<MouseEvent>event);
101 this._mouseDownListener = event => this._onMouseDown(<MouseEvent>event);
102 this._mouseUpListener = event => this._onMouseUp(<MouseEvent>event);
103 }
104
105 /**
106 * Disables the selection manager. This is useful for when terminal mouse
107 * are enabled.
108 */
109 public disable() {
110 this._model.selectionStart = null;
111 this._model.selectionEnd = null;
112 this.refresh();
113 this._buffer.off('trim', this._bufferTrimListener);
114 this._rowContainer.removeEventListener('mousedown', this._mouseDownListener);
115 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
116 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
117 clearInterval(this._dragScrollIntervalTimer);
118 }
119
120 /**
121 * Enable the selection manager.
122 */
123 public enable() {
124 // Only adjust the selection on trim, shiftElements is rarely used (only in
125 // reverseIndex) and delete in a splice is only ever used when the same
126 // number of elements was just added. Given this is could actually be
127 // beneficial to leave the selection as is for these cases.
128 this._buffer.on('trim', this._bufferTrimListener);
129 this._rowContainer.addEventListener('mousedown', this._mouseDownListener);
130 }
131
132 /**
133 * Gets the text currently selected.
134 */
135 public get selectionText(): string {
136 const start = this._model.finalSelectionStart;
137 const end = this._model.finalSelectionEnd;
138 if (!start || !end) {
139 return '';
140 }
141
142 // Get first row
143 const startRowEndCol = start[1] === end[1] ? end[0] : null;
144 let result: string[] = [];
145 result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
146
147 // Get middle rows
148 for (let i = start[1] + 1; i <= end[1] - 1; i++) {
149 result.push(this._translateBufferLineToString(this._buffer.get(i), true));
150 }
151
152 // Get final row
153 if (start[1] !== end[1]) {
154 result.push(this._translateBufferLineToString(this._buffer.get(end[1]), true, 0, end[0]));
155 }
156 console.log('selectionText result: "' + result + '"');
157 return result.join('\n');
158 }
159
160 private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
161 // TODO: This function should live in a buffer or buffer line class
162
163 // Get full line
164 let lineString = '';
165 let widthAdjustedStartCol = startCol;
166 let widthAdjustedEndCol = endCol;
167 for (let i = 0; i < line.length; i++) {
168 const char = line[i];
169 lineString += char[LINE_DATA_CHAR_INDEX];
170 // Adjust start and end cols for wide characters if they affect their
171 // column indexes
172 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
173 if (startCol >= i) {
174 widthAdjustedStartCol--;
175 }
176 if (endCol >= i) {
177 widthAdjustedEndCol--;
178 }
179 }
180 }
181
182 // Calculate the final end col by trimming whitespace on the right of the
183 // line if needed.
184 let finalEndCol = widthAdjustedEndCol || line.length;
185 if (trimRight) {
186 const rightWhitespaceIndex = lineString.search(/\s+$/);
187 if (rightWhitespaceIndex !== -1) {
188 finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
189 }
190 // Return the empty string if only trimmed whitespace is selected
191 if (finalEndCol <= widthAdjustedStartCol) {
192 return '';
193 }
194 }
195
196 return lineString.substring(widthAdjustedStartCol, finalEndCol);
197 }
198
199 /**
200 * Redraws the selection.
201 */
202 public refresh(): void {
203 this.emit('refresh', { start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd });
204 }
205
206 /**
207 * Selects all text within the terminal.
208 */
209 public selectAll(): void {
210 this._model.isSelectAllActive = true;
211 this.refresh();
212 }
213
214 /**
215 * Handle the buffer being trimmed, adjust the selection position.
216 * @param amount The amount the buffer is being trimmed.
217 */
218 private _onTrim(amount: number) {
219 const needsRefresh = this._model.onTrim(amount);
220 if (needsRefresh) {
221 this.refresh();
222 }
223 }
224
225 private _getMouseBufferCoords(event: MouseEvent): [number, number] {
226 const coords = Mouse.getCoords(event, this._rowContainer, this._charMeasure, this._terminal.cols, this._terminal.rows);
227 console.log(coords);
228 // Convert to 0-based
229 coords[0]--;
230 coords[1]--;
231 // Convert viewport coords to buffer coords
232 coords[1] += this._terminal.ydisp;
233 return coords;
234 }
235
236 private _getMouseEventScrollAmount(event: MouseEvent): number {
237 let offset = Mouse.getCoordsRelativeToElement(event, this._rowContainer)[1];
238 const terminalHeight = this._terminal.rows * this._charMeasure.height;
239 if (offset >= 0 && offset <= terminalHeight) {
240 return 0;
241 }
242 if (offset > terminalHeight) {
243 offset -= terminalHeight;
244 }
245
246 offset = Math.min(Math.max(offset, -DRAG_SCROLL_MAX_THRESHOLD), DRAG_SCROLL_MAX_THRESHOLD);
247 offset /= DRAG_SCROLL_MAX_THRESHOLD;
248 return (offset / Math.abs(offset)) + Math.round(offset * (DRAG_SCROLL_MAX_SPEED - 1));
249 }
250
251 /**
252 * Handles te mousedown event, setting up for a new selection.
253 * @param event The mousedown event.
254 */
255 private _onMouseDown(event: MouseEvent) {
256 // Only action the primary button
257 if (event.button !== 0) {
258 return;
259 }
260
261 this._setMouseClickCount(event);
262 console.log(this._clickCount);
263
264 if (event.shiftKey) {
265 this._onShiftClick(event);
266 } else {
267 if (this._clickCount === 1) {
268 this._onSingleClick(event);
269 } else if (this._clickCount === 2) {
270 this._onDoubleClick(event);
271 } else if (this._clickCount === 3) {
272 this._onTripleClick(event);
273 }
274 }
275
276 // Listen on the document so that dragging outside of viewport works
277 this._rowContainer.ownerDocument.addEventListener('mousemove', this._mouseMoveListener);
278 this._rowContainer.ownerDocument.addEventListener('mouseup', this._mouseUpListener);
279 this._dragScrollIntervalTimer = setInterval(() => this._dragScroll(), DRAG_SCROLL_INTERVAL);
280 this.refresh();
281 }
282
283 private _onShiftClick(event: MouseEvent): void {
284 if (this._model.selectionStart) {
285 this._model.selectionEnd = this._getMouseBufferCoords(event);
286 }
287 }
288
289 private _onSingleClick(event: MouseEvent): void {
290 this._model.selectionStartLength = 0;
291 this._model.isSelectAllActive = false;
292 this._isLineSelectModeActive = false;
293 this._model.selectionStart = this._getMouseBufferCoords(event);
294 if (this._model.selectionStart) {
295 this._model.selectionEnd = null;
296 // If the mouse is over the second half of a wide character, adjust the
297 // selection to cover the whole character
298 const char = this._buffer.get(this._model.selectionStart[1])[this._model.selectionStart[0]];
299 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
300 this._model.selectionStart[0]++;
301 }
302 }
303 }
304
305 private _onDoubleClick(event: MouseEvent): void {
306 const coords = this._getMouseBufferCoords(event);
307 if (coords) {
308 this._selectWordAt(coords);
309 }
310 }
311
312 private _onTripleClick(event: MouseEvent): void {
313 const coords = this._getMouseBufferCoords(event);
314 if (coords) {
315 this._isLineSelectModeActive = true;
316 this._selectLineAt(coords[1]);
317 }
318 }
319
320 private _setMouseClickCount(event: MouseEvent): void {
321 let currentTime = (new Date()).getTime();
322 if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
323 this._clickCount = 0;
324 }
325 this._lastMouseDownTime = currentTime;
326 this._lastMousePosition = [event.pageX, event.pageY];
327 this._clickCount++;
328 }
329
330 private _distanceFromLastMousePosition(event: MouseEvent): number {
331 const result = Math.max(
332 Math.abs(this._lastMousePosition[0] - event.pageX),
333 Math.abs(this._lastMousePosition[1] - event.pageY));
334 return result;
335 }
336
337 /**
338 * Handles the mousemove event when the mouse button is down, recording the
339 * end of the selection and refreshing the selection.
340 * @param event The mousemove event.
341 */
342 private _onMouseMove(event: MouseEvent) {
343 // Record the previous position so we know whether to redraw the selection
344 // at the end.
345 const previousSelectionEnd = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null;
346
347 // Set the initial selection end based on the mouse coordinates
348 this._model.selectionEnd = this._getMouseBufferCoords(event);
349
350 // Select the entire line if line select mode is active.
351 if (this._isLineSelectModeActive) {
352 if (this._model.selectionEnd[1] < this._model.selectionStart[1]) {
353 this._model.selectionEnd[0] = 0;
354 } else {
355 this._model.selectionEnd[0] = this._terminal.cols;
356 }
357 }
358
359 // Determine the amount of scrolling that will happen.
360 this._dragScrollAmount = this._getMouseEventScrollAmount(event);
361
362 // If the cursor was above or below the viewport, make sure it's at the
363 // start or end of the viewport respectively.
364 if (this._dragScrollAmount > 0) {
365 this._model.selectionEnd[0] = this._terminal.cols - 1;
366 } else if (this._dragScrollAmount < 0) {
367 this._model.selectionEnd[0] = 0;
368 }
369
370 // If the character is a wide character include the cell to the right in the
371 // selection. Note that selections at the very end of the line will never
372 // have a character.
373 const char = this._buffer.get(this._model.selectionEnd[1])[this._model.selectionEnd[0]];
374 if (char && char[2] === 0) {
375 this._model.selectionEnd[0]++;
376 }
377
378 // Only draw here if the selection changes.
379 if (!previousSelectionEnd ||
380 previousSelectionEnd[0] !== this._model.selectionEnd[0] ||
381 previousSelectionEnd[1] !== this._model.selectionEnd[1]) {
382 this.refresh();
383 }
384 }
385
386 private _dragScroll() {
387 if (this._dragScrollAmount) {
388 this._terminal.scrollDisp(this._dragScrollAmount, false);
389 // Re-evaluate selection
390 if (this._dragScrollAmount > 0) {
391 this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
392 } else {
393 this._model.selectionEnd = [0, this._terminal.ydisp];
394 }
395 this.refresh();
396 }
397 }
398
399 /**
400 * Handles the mouseup event, removing the mousemove listener when
401 * appropriate.
402 * @param event The mouseup event.
403 */
404 private _onMouseUp(event: MouseEvent) {
405 this._dragScrollAmount = 0;
406 if (!this._model.selectionStart) {
407 return;
408 }
409 this._rowContainer.ownerDocument.removeEventListener('mousemove', this._mouseMoveListener);
410 this._rowContainer.ownerDocument.removeEventListener('mouseup', this._mouseUpListener);
411 }
412
413 /**
414 * Converts a viewport column to the character index on the buffer line, the
415 * latter takes into account wide characters.
416 * @param coords The coordinates to find the 2 index for.
417 */
418 private _convertViewportColToCharacterIndex(bufferLine: any, coords: [number, number]): number {
419 let charIndex = coords[0];
420 for (let i = 0; coords[0] >= i; i++) {
421 const char = bufferLine[i];
422 if (char[LINE_DATA_WIDTH_INDEX] === 0) {
423 charIndex--;
424 }
425 }
426 return charIndex;
427 }
428
429 /**
430 * Selects the word at the coordinates specified. Words are defined as all
431 * non-whitespace characters.
432 * @param coords The coordinates to get the word at.
433 */
434 protected _selectWordAt(coords: [number, number]): void {
435 const bufferLine = this._buffer.get(coords[1]);
436 const line = this._translateBufferLineToString(bufferLine, false);
437
438 // Get actual index, taking into consideration wide characters
439 let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
440 let startIndex = endIndex;
441
442 // Record offset to be used later
443 const charOffset = coords[0] - startIndex;
444 let leftWideCharCount = 0;
445 let rightWideCharCount = 0;
446
447 if (line.charAt(startIndex) === ' ') {
448 // Expand until non-whitespace is hit
449 while (startIndex > 0 && line.charAt(startIndex - 1) === ' ') {
450 startIndex--;
451 }
452 while (endIndex < line.length && line.charAt(endIndex + 1) === ' ') {
453 endIndex++;
454 }
455 } else {
456 // Expand until whitespace is hit. This algorithm works by scanning left
457 // and right from the starting position, keeping both the index format
458 // (line) and the column format (bufferLine) in sync. When a wide
459 // character is hit, it is recorded and the column index is adjusted.
460 let startCol = coords[0];
461 let endCol = coords[0];
462 // Consider the initial position, skip it and increment the wide char
463 // variable
464 if (bufferLine[startCol][LINE_DATA_WIDTH_INDEX] === 0) {
465 leftWideCharCount++;
466 startCol--;
467 }
468 if (bufferLine[endCol][LINE_DATA_WIDTH_INDEX] === 2) {
469 rightWideCharCount++;
470 endCol++;
471 }
472 // Expand the string in both directions until a space is hit
473 while (startIndex > 0 && line.charAt(startIndex - 1) !== ' ') {
474 if (bufferLine[startCol - 1][LINE_DATA_WIDTH_INDEX] === 0) {
475 // If the next character is a wide char, record it and skip the column
476 leftWideCharCount++;
477 startCol--;
478 }
479 startIndex--;
480 startCol--;
481 }
482 while (endIndex + 1 < line.length && line.charAt(endIndex + 1) !== ' ') {
483 if (bufferLine[endCol + 1][LINE_DATA_WIDTH_INDEX] === 2) {
484 // If the next character is a wide char, record it and skip the column
485 rightWideCharCount++;
486 endCol++;
487 }
488 endIndex++;
489 endCol++;
490 }
491 }
492
493 // Record the resulting selection
494 this._model.selectionStart = [startIndex + charOffset - leftWideCharCount, coords[1]];
495 this._model.selectionStartLength = Math.min(endIndex - startIndex + leftWideCharCount + rightWideCharCount + 1/*include endIndex char*/, this._terminal.cols);
496 }
497
498 protected _selectLineAt(line: number): void {
499 this._model.selectionStart = [0, line];
500 this._model.selectionStartLength = this._terminal.cols;
501 }
502 }