]> git.proxmox.com Git - mirror_xterm.js.git/blobdiff - src/SelectionManager.ts
Add null check when mouse coords are bad
[mirror_xterm.js.git] / src / SelectionManager.ts
index eb9e2bb5e0e9a0989f38965bcddf44f2fea3c463..78494ae19304c195e0770a412de889a1eeec1433 100644 (file)
@@ -7,8 +7,9 @@ import * as Browser from './utils/Browser';
 import { CharMeasure } from './utils/CharMeasure';
 import { CircularList } from './utils/CircularList';
 import { EventEmitter } from './EventEmitter';
-import { ITerminal } from './Interfaces';
+import { ITerminal, ICircularList } from './Interfaces';
 import { SelectionModel } from './SelectionModel';
+import { translateBufferLineToString } from './utils/BufferLine';
 
 /**
  * The number of pixels the mouse needs to be above or below the viewport in
@@ -26,23 +27,11 @@ const DRAG_SCROLL_MAX_SPEED = 15;
  */
 const DRAG_SCROLL_INTERVAL = 50;
 
-/**
- * The amount of time before mousedown events are no longer stacked to create
- * double/triple click events.
- */
-const CLEAR_MOUSE_DOWN_TIME = 400;
-
-/**
- * The number of pixels in each direction that the mouse must move before
- * mousedown events are no longer stacked to create double/triple click events.
- */
-const CLEAR_MOUSE_DISTANCE = 10;
-
 /**
  * A string containing all characters that are considered word separated by the
  * double click to select work logic.
  */
-const WORD_SEPARATORS = ' ()[]{}:\'"';
+const WORD_SEPARATORS = ' ()[]{}\'"';
 
 // TODO: Move these constants elsewhere, they belong in a buffer or buffer
 //       data/line class.
@@ -86,23 +75,6 @@ export class SelectionManager extends EventEmitter {
    */
   private _dragScrollAmount: number;
 
-  /**
-   * The last time the mousedown event fired, this is used to track double and
-   * triple clicks.
-   */
-  private _lastMouseDownTime: number;
-
-  /**
-   * The last position the mouse was clicked [x, y].
-   */
-  private _lastMousePosition: [number, number];
-
-  /**
-   * The number of clicks of the mousedown event. This is used to keep track of
-   * double and triple clicks.
-   */
-  private _clickCount: number;
-
   /**
    * The current selection mode.
    */
@@ -126,7 +98,7 @@ export class SelectionManager extends EventEmitter {
 
   constructor(
     private _terminal: ITerminal,
-    private _buffer: CircularList<any>,
+    private _buffer: ICircularList<[number, string, number][]>,
     private _rowContainer: HTMLElement,
     private _charMeasure: CharMeasure
   ) {
@@ -135,7 +107,6 @@ export class SelectionManager extends EventEmitter {
     this.enable();
 
     this._model = new SelectionModel(_terminal);
-    this._lastMouseDownTime = 0;
     this._activeSelectionMode = SelectionMode.NORMAL;
   }
 
@@ -176,11 +147,14 @@ export class SelectionManager extends EventEmitter {
    * switched in or out.
    * @param buffer The active buffer.
    */
-  public setBuffer(buffer: CircularList<any>): void {
+  public setBuffer(buffer: ICircularList<[number, string, number][]>): void {
     this._buffer = buffer;
     this.clearSelection();
   }
 
+  public get selectionStart(): [number, number] { return this._model.finalSelectionStart; }
+  public get selectionEnd(): [number, number] { return this._model.finalSelectionEnd; }
+
   /**
    * Gets whether there is an active text selection.
    */
@@ -206,13 +180,13 @@ export class SelectionManager extends EventEmitter {
     // Get first row
     const startRowEndCol = start[1] === end[1] ? end[0] : null;
     let result: string[] = [];
-    result.push(this._translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
+    result.push(translateBufferLineToString(this._buffer.get(start[1]), true, start[0], startRowEndCol));
 
     // Get middle rows
     for (let i = start[1] + 1; i <= end[1] - 1; i++) {
       const bufferLine = this._buffer.get(i);
-      const lineText = this._translateBufferLineToString(bufferLine, true);
-      if (bufferLine.isWrapped) {
+      const lineText = translateBufferLineToString(bufferLine, true);
+      if ((<any>bufferLine).isWrapped) {
         result[result.length - 1] += lineText;
       } else {
         result.push(lineText);
@@ -222,8 +196,8 @@ export class SelectionManager extends EventEmitter {
     // Get final row
     if (start[1] !== end[1]) {
       const bufferLine = this._buffer.get(end[1]);
-      const lineText = this._translateBufferLineToString(bufferLine, true, 0, end[0]);
-      if (bufferLine.isWrapped) {
+      const lineText = translateBufferLineToString(bufferLine, true, 0, end[0]);
+      if ((<any>bufferLine).isWrapped) {
         result[result.length - 1] += lineText;
       } else {
         result.push(lineText);
@@ -234,7 +208,7 @@ export class SelectionManager extends EventEmitter {
     // and joining the array into a multi-line string.
     const formattedResult = result.map(line => {
       return line.replace(ALL_NON_BREAKING_SPACE_REGEX, ' ');
-    }).join('\n');
+    }).join(Browser.isMSWindows ? '\r\n' : '\n');
 
     return formattedResult;
   }
@@ -248,55 +222,6 @@ export class SelectionManager extends EventEmitter {
     this.refresh();
   }
 
-  /**
-   * Translates a buffer line to a string, with optional start and end columns.
-   * Wide characters will count as two columns in the resulting string. This
-   * function is useful for getting the actual text underneath the raw selection
-   * position.
-   * @param line The line being translated.
-   * @param trimRight Whether to trim whitespace to the right.
-   * @param startCol The column to start at.
-   * @param endCol The column to end at.
-   */
-  private _translateBufferLineToString(line: any, trimRight: boolean, startCol: number = 0, endCol: number = null): string {
-    // TODO: This function should live in a buffer or buffer line class
-
-    // Get full line
-    let lineString = '';
-    let widthAdjustedStartCol = startCol;
-    let widthAdjustedEndCol = endCol;
-    for (let i = 0; i < line.length; i++) {
-      const char = line[i];
-      lineString += char[LINE_DATA_CHAR_INDEX];
-      // Adjust start and end cols for wide characters if they affect their
-      // column indexes
-      if (char[LINE_DATA_WIDTH_INDEX] === 0) {
-        if (startCol >= i) {
-          widthAdjustedStartCol--;
-        }
-        if (endCol >= i) {
-          widthAdjustedEndCol--;
-        }
-      }
-    }
-
-    // Calculate the final end col by trimming whitespace on the right of the
-    // line if needed.
-    let finalEndCol = widthAdjustedEndCol || line.length;
-    if (trimRight) {
-      const rightWhitespaceIndex = lineString.search(/\s+$/);
-      if (rightWhitespaceIndex !== -1) {
-        finalEndCol = Math.min(finalEndCol, rightWhitespaceIndex);
-      }
-      // Return the empty string if only trimmed whitespace is selected
-      if (finalEndCol <= widthAdjustedStartCol) {
-        return '';
-      }
-    }
-
-    return lineString.substring(widthAdjustedStartCol, finalEndCol);
-  }
-
   /**
    * Queues a refresh, redrawing the selection on the next opportunity.
    * @param isNewSelection Whether the selection should be registered as a new
@@ -356,7 +281,7 @@ export class SelectionManager extends EventEmitter {
     coords[0]--;
     coords[1]--;
     // Convert viewport coords to buffer coords
-    coords[1] += this._terminal.ydisp;
+    coords[1] += this._terminal.buffer.ydisp;
     return coords;
   }
 
@@ -396,16 +321,14 @@ export class SelectionManager extends EventEmitter {
     // Reset drag scroll state
     this._dragScrollAmount = 0;
 
-    this._setMouseClickCount(event);
-
     if (event.shiftKey) {
       this._onShiftClick(event);
     } else {
-      if (this._clickCount === 1) {
+      if (event.detail === 1) {
           this._onSingleClick(event);
-      } else if (this._clickCount === 2) {
+      } else if (event.detail === 2) {
           this._onDoubleClick(event);
-      } else if (this._clickCount === 3) {
+      } else if (event.detail === 3) {
           this._onTripleClick(event);
       }
     }
@@ -491,32 +414,6 @@ export class SelectionManager extends EventEmitter {
     }
   }
 
-  /**
-   * Sets the number of clicks for the current mousedown event based on the time
-   * and position of the last mousedown event.
-   * @param event The mouse event.
-   */
-  private _setMouseClickCount(event: MouseEvent): void {
-    let currentTime = (new Date()).getTime();
-    if (currentTime - this._lastMouseDownTime > CLEAR_MOUSE_DOWN_TIME || this._distanceFromLastMousePosition(event) > CLEAR_MOUSE_DISTANCE) {
-      this._clickCount = 0;
-    }
-    this._lastMouseDownTime = currentTime;
-    this._lastMousePosition = [event.pageX, event.pageY];
-    this._clickCount++;
-  }
-
-  /**
-   * Gets the maximum number of pixels in each direction the mouse has moved.
-   * @param event The mouse event.
-   */
-  private _distanceFromLastMousePosition(event: MouseEvent): number {
-    const result = Math.max(
-        Math.abs(this._lastMousePosition[0] - event.pageX),
-        Math.abs(this._lastMousePosition[1] - event.pageY));
-    return result;
-  }
-
   /**
    * Handles the mousemove event when the mouse button is down, recording the
    * end of the selection and refreshing the selection.
@@ -579,9 +476,9 @@ export class SelectionManager extends EventEmitter {
       this._terminal.scrollDisp(this._dragScrollAmount, false);
       // Re-evaluate selection
       if (this._dragScrollAmount > 0) {
-        this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.ydisp + this._terminal.rows];
+        this._model.selectionEnd = [this._terminal.cols - 1, this._terminal.buffer.ydisp + this._terminal.rows];
       } else {
-        this._model.selectionEnd = [0, this._terminal.ydisp];
+        this._model.selectionEnd = [0, this._terminal.buffer.ydisp];
       }
       this.refresh();
     }
@@ -611,13 +508,25 @@ export class SelectionManager extends EventEmitter {
     return charIndex;
   }
 
+  public setSelection(col: number, row: number, length: number): void {
+    this._model.clearSelection();
+    this._removeMouseDownListeners();
+    this._model.selectionStart = [col, row];
+    this._model.selectionStartLength = length;
+    this.refresh();
+  }
+
   /**
    * Gets positional information for the word at the coordinated specified.
    * @param coords The coordinates to get the word at.
    */
   private _getWordAt(coords: [number, number]): IWordPosition {
     const bufferLine = this._buffer.get(coords[1]);
-    const line = this._translateBufferLineToString(bufferLine, false);
+    if (!bufferLine) {
+      return null;
+    }
+
+    const line = translateBufferLineToString(bufferLine, false);
 
     // Get actual index, taking into consideration wide characters
     let endIndex = this._convertViewportColToCharacterIndex(bufferLine, coords);
@@ -685,8 +594,10 @@ export class SelectionManager extends EventEmitter {
    */
   protected _selectWordAt(coords: [number, number]): void {
     const wordPosition = this._getWordAt(coords);
-    this._model.selectionStart = [wordPosition.start, coords[1]];
-    this._model.selectionStartLength = wordPosition.length;
+    if (wordPosition) {
+      this._model.selectionStart = [wordPosition.start, coords[1]];
+      this._model.selectionStartLength = wordPosition.length;
+    }
   }
 
   /**
@@ -695,7 +606,9 @@ export class SelectionManager extends EventEmitter {
    */
   private _selectToWordAt(coords: [number, number]): void {
     const wordPosition = this._getWordAt(coords);
-    this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
+    if (wordPosition) {
+      this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? wordPosition.start : (wordPosition.start + wordPosition.length), coords[1]];
+    }
   }
 
   /**