xterm.js icon indicating copy to clipboard operation
xterm.js copied to clipboard

Inertial fling sends NaN mouse coordinates when mouse reporting is on

Open Gaurav-Gosain opened this issue 3 months ago • 1 comments

Summary

On a touch device, flicking the terminal while a program has mouse reporting enabled sends mouse reports whose coordinates are the literal text NaN. A shell fills up with NaN;NaNMaN;NaNM…, and a program that parses the report gets garbage.

Measured on a phone-sized Chrome with gesture synthesis: three flings put 534 mouse reports on the wire, and 489 of them were \x1b[<65;NaN;NaNM.

It only shows up with a real touch gesture and a program that has turned mouse reporting on, so it is invisible on a desktop and invisible with reporting off. That is probably why it has lasted.

Versions

Present on master (29a7384) and on @xterm/[email protected].

Not present in 6.0.0. The consumer that feeds the event into coordinate math, _handleTouchScrollAsWheel, arrived in #5685 which post-dates 6.0.0, so this is a regression on the 6.1.0 line. Filing here since #5377 is the thread that work came from.

Reproduction

<!doctype html>
<div id="t" style="width: 100vw; height: 100vh"></div>
<script type="module">
  import { Terminal } from '@xterm/xterm';
  const term = new Terminal();
  term.open(document.getElementById('t'));
  term.onData(d => { if (d.includes('NaN')) console.error('NaN report:', JSON.stringify(d)); });
  // what a full screen program asks for: click, drag, SGR encoding
  term.write('\x1b[?1000;1002;1006h');
</script>

Open it on a phone and flick the terminal.

Over the DevTools protocol it needs the gesture synthesizer, because the fling is the recognizer's own animation loop and only real gesture timing starts one. Input.dispatchTouchEvent will not do it:

await cdp.send('Input.synthesizeScrollGesture', {
  x, y, xDistance: 0, yDistance: -260,
  speed: 6000, gestureSourceType: 'touch', preventFling: false,
});

Cause

Three guards in a row, and all of them fail open on NaN.

1. The inertial event is built without a position. src/browser/scrollable/touch.ts, Gesture._inertia, lines 412-443:

const evt = this._newGestureEvent(EventType.CHANGE);
evt.translationX = deltaPosX;
evt.translationY = deltaPosY;
dispatchTo.forEach(d => d.dispatchEvent(evt));

_handleTouchMove in the same file (459-466) builds the same event type properly:

const evt = this._newGestureEvent(EventType.CHANGE, data.initialTarget);
evt.translationX = touch.pageX - tail(data.rollingPageX)!;
evt.translationY = touch.pageY - tail(data.rollingPageY)!;
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
evt.clientX = touch.clientX;
evt.clientY = touch.clientY;
this._dispatchEvent(evt);

_newGestureEvent (359-365) creates a bare CustomEvent and sets only initialTarget and tapCount, so anything not assigned afterwards is undefined. IGestureEvent (150-159) declares pageX/pageY/clientX/clientY as required numbers, so the type checker does not catch the omission.

There is a second consequence: the inertial event goes straight to dispatchTo instead of through Gesture._dispatchEvent, so it carries initialTarget === undefined and skips the _ignoreTargets filtering and target depth sorting that a touchmove-built event gets.

2. The coordinate service returns NaN rather than failing. src/browser/input/Mouse.ts, getCoordsRelativeToElement (6-15) does arithmetic on event.clientX, and undefined - number is NaN. MouseCoordsService.getMouseReportCoords (33-46) then clamps and floors, both of which pass NaN through, and returns an object. Its only failure mode is an invalid char size, so {col: NaN, row: NaN, x: NaN, y: NaN} is a perfectly truthy return.

3. Both remaining checks are comparisons. MouseService._handleTouchScrollAsWheel (354-357) guards on truthiness:

const pos = this._mouseCoordsService.getMouseReportCoords(e, ctx.target.screenElement);
if (!pos) {
  return;
}

and _triggerMouseEvent (497-502) guards on range:

if (e.col < 0 || e.col >= this._bufferService.cols
  || e.row < 0 || e.row >= this._bufferService.rows) {
  return false;
}

Every comparison against NaN is false, so the rejecting condition is false and the event reaches the encoder.

Every encoding is affected, not just SGR

In src/common/services/MouseStateService.ts:

  • SGR (143-150) interpolates directly and sends \x1b[<65;NaN;NaNM.
  • SGR_PIXELS does the same with e.x and e.y.
  • DEFAULT (X10, 127-137) computes params[1] = NaN + 32, and its params[1] > 255 suppression is also false for NaN, so it emits String.fromCharCode(NaN). A program using the default encoding receives \x1b[M, the button byte, and two NUL bytes.

Suggested fix

  1. Gesture._inertia should carry a position, and it already has one to hand. Its x and y parameters are the running page position, seeded from the last touch and advanced by each frame's translation on the recursive call, and then never read. Writing them onto the event as pageX/pageY/clientX/clientY and dispatching through _dispatchEvent with an initialTarget, the way every other call site does, makes the inertial event the same shape as the real one and closes the _ignoreTargets bypass at the same time. This alone fixes the bug.
  2. getMouseReportCoords should return undefined for a non-finite result, which is what its callers already treat a falsy return as meaning.
  3. _triggerMouseEvent should reject a non-finite col or row explicitly rather than by comparison.

Happy to open a PR for 1 if that is useful.

Where it comes from

Gesture comes from vscode's src/vs/base/browser/touch.ts, which has the same omission: inertia (line 309, dispatch at 331-335) sets only the translations while onTouchMove sets the coordinates too. Only identifiers were renamed on the way in.

vscode's own scroll consumers look unaffected because they read nothing but the translations, for example pointerHandler.ts calling deltaScrollNow(-e.translationX, -e.translationY). xterm is the first consumer to feed the event into coordinate math, so the fix belongs here regardless of whether vscode takes one.

Gaurav-Gosain avatar Aug 16 '26 07:08 Gaurav-Gosain

There's already an open PR for this: #6059.

It fixes the root cause you identified (suggested fix 1) — stamps page/client coordinates onto the Gesture._inertia CHANGE events, matching what _handleTouchMove does for real touch frames. It also adds a defensive !isFinite(e.clientX) || !isFinite(e.clientY) guard in MouseService so a coordinate-less gesture event can't reach the PTY through that path even if something upstream regresses again.

It doesn't touch getMouseReportCoords (suggested fix 2) or _triggerMouseEvent's range check (suggested fix 3), but those become moot for this path once the events always carry finite coordinates.

arsyadal avatar Aug 17 '26 10:08 arsyadal