From 7156ddb61bc2acccac08b60d72dac0397304a318 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 2 Nov 2026 13:59:07 -0500 Subject: [PATCH 1/4] Restore bounded tracked momentum and require declared input bounds for IME --- .../termux/view/TerminalViewKeyboardTest.java | 154 +++++++++--- .../termux/view/TerminalViewMouseTest.java | 111 +++++++-- .../com/termux/view/TerminalViewTestCase.java | 8 +- docs/touch-input.md | 46 ++++ .../com/termux/terminal/TerminalEmulator.java | 25 ++ .../com/termux/terminal/TextInputRegion.java | 34 +++ .../java/com/termux/view/TerminalView.java | 230 ++++++++++++++---- 7 files changed, 496 insertions(+), 112 deletions(-) create mode 100644 docs/touch-input.md create mode 100644 terminal-emulator/src/main/java/com/termux/terminal/TextInputRegion.java diff --git a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java index 5131bcf16a8..061a6ada89b 100644 --- a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java @@ -9,46 +9,116 @@ import static org.junit.Assert.assertEquals; -/** Tests keyboard-request intent, not Android IME display or a remote phone. */ +/** Real terminal input bounds and touch intent; Android IME display needs the phone. */ public class TerminalViewKeyboardTest extends TerminalViewTestCase { private void trackingTap() { input("\033[?1000h\033[?25l"); tap(InputDevice.SOURCE_TOUCHSCREEN); } - private void cursorResponse() { - input("\033[?25h"); + private void inputResponse() { + input("\033]777;input-region;1;2;8;3\033\\"); view.onScreenUpdated(); } @Test - public void cursorResponseAfterTrackingTapRequestsKeyboardOnce() { + public void declaredInputAfterTrackingTapRequestsKeyboardOnce() { trackingTap(); assertEquals(0, client.keyboardRequests); - cursorResponse(); + inputResponse(); assertEquals(1, client.keyboardRequests); - cursorResponse(); + inputResponse(); view.onScreenUpdated(); assertEquals(1, client.keyboardRequests); } @Test - public void unsolicitedCursorVisibilityDoesNotRequestKeyboard() { + public void unsolicitedInputBoundsDoNotRequestKeyboard() { input("\033[?1000h"); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @Test - public void animationPhaseDoesNotSubstituteForEnabledCursor() { + public void visibleCursorAndScreenRepaintsAreNotInputFocus() { trackingTap(); + input("\033[4;3H\033[?25h"); + view.onScreenUpdated(); + view.mEmulator.setCursorBlinkState(false); view.mEmulator.setCursorBlinkState(true); view.onScreenUpdated(); assertEquals(0, client.keyboardRequests); - cursorResponse(); + } + + @Test + public void inputElsewhereOnTheCursorRowDoesNotAuthorizeTranscriptTap() { + input("\033[?1000h\033[4;3H\033[?25h"); + input("\033]777;input-region;10;3;5;1\033\\"); + tap(InputDevice.SOURCE_TOUCHSCREEN); + view.onScreenUpdated(); + advance(ViewConfiguration.getDoubleTapTimeout() + 1); + assertEquals(0, client.keyboardRequests); + } + + @Test + public void knownInputBoundsRequestImmediatelyAndOnlyOncePerTap() { + input("\033[?1000h"); + inputResponse(); + tap(InputDevice.SOURCE_TOUCHSCREEN); assertEquals(1, client.keyboardRequests); - view.mEmulator.setCursorBlinkState(false); - view.mEmulator.setCursorBlinkState(true); + view.onScreenUpdated(); + assertEquals(1, client.keyboardRequests); + tap(InputDevice.SOURCE_TOUCHSCREEN); + assertEquals(2, client.keyboardRequests); + } + + @Test + public void rightAndBottomBoundsAreExclusive() { + input("\033[?1000h"); + inputResponse(); + tapAt(9.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + tapAt(2.5f, 5.5f, InputDevice.SOURCE_TOUCHSCREEN); + view.onScreenUpdated(); + assertEquals(0, client.keyboardRequests); + tapAt(8.5f, 4.5f, InputDevice.SOURCE_TOUCHSCREEN); + assertEquals(1, client.keyboardRequests); + } + + @Test + public void clearedBoundsDoNotAuthorizeTap() { + input("\033[?1000h"); + inputResponse(); + input("\033]777;input-region;0;0;0;0\033\\"); + tap(InputDevice.SOURCE_TOUCHSCREEN); + view.onScreenUpdated(); + assertEquals(0, client.keyboardRequests); + } + + @Test + public void malformedBoundsClearThePreviousAdvertisement() { + input("\033[?1000h"); + String[] malformed = { + "input-region;1;2;999999;3", "input-region;-1;2;8;3", + "input-region;1;2;8", "input-region;1;2;8;no", + "input-region;1;2;2147483648;3", "input-region;1;2;8;3;extra" + }; + for (String parameter : malformed) { + touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + inputResponse(); + input("\033]777;" + parameter + "\033\\"); + tap(InputDevice.SOURCE_TOUCHSCREEN); + view.onScreenUpdated(); + assertEquals(parameter, 0, client.keyboardRequests); + } + } + + @Test + public void incompleteControlIsNotAnAdvertisement() { + trackingTap(); + input("\033]777;input-region;1;2;8;3"); + view.onScreenUpdated(); + assertEquals(0, client.keyboardRequests); + input("\033\\"); view.onScreenUpdated(); assertEquals(1, client.keyboardRequests); } @@ -57,7 +127,7 @@ public void animationPhaseDoesNotSubstituteForEnabledCursor() { public void responseAfterRecentTapWindowHasExpiredIsIgnored() { trackingTap(); advance(TerminalView.MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS + 1); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -65,7 +135,7 @@ public void responseAfterRecentTapWindowHasExpiredIsIgnored() { public void newDownInvalidatesEarlierTap() { trackingTap(); touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -73,7 +143,7 @@ public void newDownInvalidatesEarlierTap() { public void cancelInvalidatesEarlierTap() { trackingTap(); touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -81,7 +151,7 @@ public void cancelInvalidatesEarlierTap() { public void lostWindowFocusInvalidatesEarlierTap() { trackingTap(); view.onWindowFocusChanged(false); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -89,17 +159,31 @@ public void lostWindowFocusInvalidatesEarlierTap() { public void detachInvalidatesEarlierTap() { trackingTap(); view.onDetachedFromWindow(); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @Test - public void trackingOffClearsAuthorizationBeforeTrackingReturns() { + public void trackingOffAndOnInOneReadRetiresEarlierTap() { trackingTap(); - input("\033[?1000l"); - view.onScreenUpdated(); - input("\033[?1000h"); - cursorResponse(); + input("\033[?1000l\033[?1000h"); + inputResponse(); + assertEquals(0, client.keyboardRequests); + } + + @Test + public void resizeRetiresEarlierTapAndBounds() { + trackingTap(); + view.mEmulator.resize(81, 24, 8, 16); + inputResponse(); + assertEquals(0, client.keyboardRequests); + } + + @Test + public void bufferSwitchRetiresEarlierTap() { + trackingTap(); + input("\033[?1049h"); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -108,43 +192,37 @@ public void trackingOffTapKeepsExistingClientCallback() { tap(InputDevice.SOURCE_TOUCHSCREEN); advance(ViewConfiguration.getDoubleTapTimeout() + 1); assertEquals(1, client.taps); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @Test public void mouseDeviceTapDoesNotAuthorizeKeyboard() { - input("\033[?1000h\033[?25l"); + input("\033[?1000h"); + inputResponse(); tap(InputDevice.SOURCE_MOUSE); - cursorResponse(); + view.onScreenUpdated(); assertEquals(0, client.keyboardRequests); } @Test public void longPressDoesNotAuthorizeKeyboardOnRelease() { - input("\033[?1000h\033[?25l"); + input("\033[?1000h"); + inputResponse(); longPress(InputDevice.SOURCE_TOUCHSCREEN); - cursorResponse(); + view.onScreenUpdated(); assertEquals(0, client.keyboardRequests); } @Test public void fingerScrollDoesNotAuthorizeKeyboardOnRelease() { - input("\033[?1000h\033[?25l"); + input("\033[?1000h"); + inputResponse(); long down = SystemClock.uptimeMillis(); touch(down, MotionEvent.ACTION_DOWN, 2.5f, 15.5f, InputDevice.SOURCE_TOUCHSCREEN); touch(down, MotionEvent.ACTION_MOVE, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); touch(down, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - cursorResponse(); - assertEquals(0, client.keyboardRequests); - } - - @Test - public void anotherTapCanRequestKeyboardForAnAlreadyEnabledCursor() { - trackingTap(); - cursorResponse(); - tap(InputDevice.SOURCE_TOUCHSCREEN); view.onScreenUpdated(); - assertEquals(2, client.keyboardRequests); + assertEquals(0, client.keyboardRequests); } } diff --git a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java index e88369bdb9c..969fa68fe1b 100644 --- a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java @@ -65,35 +65,106 @@ public void mouseDragStillSendsMotionRatherThanWheel() { assertEquals("\033[<32;3;4M", output.text()); } + private void fling(float velocityX, float velocityY) { + MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + view.mGestureRecognizer.mListener.onFling(up, velocityX, velocityY); + // Android owns/recycles the source event; the continuation owns its copy. + up.setLocation(1000, 1000); + up.recycle(); + } + @Test - public void horizontalGestureDoesNotStartVerticalFling() { + public void horizontalReleaseGlidesOnItsLockedAxis() { input("\033[?1000h\033[?1006h"); scroll(2, 0); - MotionEvent event = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.mGestureRecognizer.mListener.onFling(event, -1000, 2000); - event.recycle(); + String initial = output.text(); + fling(-20000, 20000); + assertFalse(view.mScroller.isFinished()); + assertEquals(initial, output.text()); + advance(TerminalView.MAX_MOUSE_FLING_MILLIS + 32); + String continuation = output.text().substring(initial.length()); + String report = "\033[<67;3;4M"; + assertFalse(continuation.isEmpty()); + assertEquals("", continuation.replace(report, "")); + assertTrue(continuation.length() / report.length() <= view.mEmulator.mColumns); assertTrue(view.mScroller.isFinished()); - assertEquals("\033[<67;3;4M\033[<67;3;4M", output.text()); } - private void assertTrackedVerticalReleaseStops(int mode) { + private void assertTrackedVerticalMomentum(int mode) { input("\033[?" + mode + "h\033[?1006h"); scroll(0, 2); - String actualRows = "\033[<65;3;4M\033[<65;3;4M"; - assertEquals(actualRows, output.text()); - MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.mGestureRecognizer.mListener.onFling(up, 0, -2000); - up.recycle(); + String initial = "\033[<65;3;4M\033[<65;3;4M"; + assertEquals(initial, output.text()); + fling(0, -20000); + assertFalse(view.mScroller.isFinished()); + assertEquals(initial, output.text()); + advance(TerminalView.MAX_MOUSE_FLING_MILLIS + 32); + String continuation = output.text().substring(initial.length()); + String report = "\033[<65;3;4M"; + assertFalse(continuation.isEmpty()); + assertEquals("", continuation.replace(report, "")); + assertTrue(continuation.length() / report.length() <= view.mEmulator.mRows); + assertTrue(view.mScroller.isFinished()); + String settled = output.text(); + advance(1000); + assertEquals(settled, output.text()); + } + + @Test + public void tracked1000VerticalReleaseHasBoundedMomentum() { assertTrackedVerticalMomentum(1000); } + + @Test + public void tracked1002VerticalReleaseHasBoundedMomentum() { assertTrackedVerticalMomentum(1002); } + + @Test + public void newDownStopsMomentumBeforeAnotherWheelReport() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + advance(1000); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } + + @Test + public void cancellationStopsMomentumBeforeAnotherWheelReport() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + advance(1000); assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } + + @Test + public void trackingRoundTripInOneReadRetiresOldMomentum() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + input("\033[?1000l\033[?1000h"); advance(1000); - assertEquals(actualRows, output.text()); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); } @Test - public void tracked1000VerticalReleaseDoesNotAddWheelRows() { assertTrackedVerticalReleaseStops(1000); } + public void bufferSwitchRetiresOldMomentum() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + input("\033[?1049h"); + advance(1000); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } @Test - public void tracked1002VerticalReleaseDoesNotAddWheelRows() { assertTrackedVerticalReleaseStops(1002); } + public void resizeRetiresOldMomentum() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + view.mEmulator.resize(81, 24, 8, 16); + advance(1000); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } private void prepareScrollback() { for (int i = 0; i < 60; i++) input("row\r\n"); @@ -107,11 +178,11 @@ public void trackingOffScrollbackStillStartsFling() { MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); view.mGestureRecognizer.mListener.onFling(up, 0, 2000); up.recycle(); - try { - assertFalse(view.mScroller.isFinished()); - } finally { - view.mScroller.abortAnimation(); - } + assertFalse(view.mScroller.isFinished()); + advance(1000); + assertTrue(view.mScroller.isFinished()); + assertTrue(view.getTopRow() < 0); + assertEquals("", output.text()); } @Test @@ -121,7 +192,7 @@ public void enablingTrackingAbortsAnUntrackedFlingWithoutWheelReports() { view.mGestureRecognizer.mListener.onFling(up, 0, 2000); up.recycle(); input("\033[?1000h\033[?1006h"); - advance(1); + advance(32); assertTrue(view.mScroller.isFinished()); assertEquals("", output.text()); } diff --git a/app/src/test/java/com/termux/view/TerminalViewTestCase.java b/app/src/test/java/com/termux/view/TerminalViewTestCase.java index 770aff41918..a9eea67652e 100644 --- a/app/src/test/java/com/termux/view/TerminalViewTestCase.java +++ b/app/src/test/java/com/termux/view/TerminalViewTestCase.java @@ -100,9 +100,13 @@ protected void touch(long down, int action, float column, float row, int source) } protected void tap(int source) { + tapAt(2.5f, 3.5f, source); + } + + protected void tapAt(float column, float row, int source) { long down = SystemClock.uptimeMillis(); - touch(down, MotionEvent.ACTION_DOWN, 2.5f, 3.5f, source); - touch(down, MotionEvent.ACTION_UP, 2.5f, 3.5f, source); + touch(down, MotionEvent.ACTION_DOWN, column, row, source); + touch(down, MotionEvent.ACTION_UP, column, row, source); } protected void longPress(int source) { diff --git a/docs/touch-input.md b/docs/touch-input.md new file mode 100644 index 00000000000..5baf3c8c6ca --- /dev/null +++ b/docs/touch-input.md @@ -0,0 +1,46 @@ +# Tracked touch scrolling and keyboard intent + +Finger flicks in mouse-tracking applications retain momentum. Both axes use the +same axis owner and mouse encoder as the finger drag. The continuation runs on +Android display frames, sends at most one wheel report per frame, lasts at most +500 ms, and contributes no more wheel steps than one terminal viewport on its +axis. It drops any remaining distance when it settles; it does not flush a tail +of queued reports. A new touch, cancellation, selection, window loss or detach +stops it. Session, tracking-mode, screen-buffer and size changes retire the old +input context. Untracked terminal scrollback keeps its existing fling physics. + +The original release patch incorrectly deleted tracked momentum. It also treated +a visible terminal cursor after any tap as permission to open the keyboard. A +cursor can remain visible in an input while the user taps somewhere else. + +## Application-declared input bounds + +An application can advertise its focused, visible text-input content rectangle: + +```text +ESC ] 777 ; input-region ; x ; y ; width ; height ESC \ +``` + +Coordinates and dimensions are decimal terminal cells. The origin is zero-based; +right and bottom edges are exclusive. The rectangle must fit the current terminal +size. `0;0;0;0` clears it. BEL also terminates OSC, as for other terminal controls. +Malformed controls are logged and clear the previous advertisement. Resize, +terminal reset, screen-buffer changes and mouse-tracking changes invalidate it. + +A short finger tap in a tracked terminal requests the keyboard once if its cell +is inside the advertised rectangle. If the tap changes focus, the application +may advertise the newly focused input in its reply; the same hit test can consume +that tap for up to three seconds. Another touch, cancellation, selection, window +loss, detach or input-context change retires the request. An unsolicited region +update, visible cursor, hardware mouse event, long press or scroll does not open +the keyboard. + +The application owns widget identity and geometry. The terminal never guesses +an input box from cursor visibility, cursor shape or a matching row. Applications +that do not advertise input bounds keep the explicit keyboard toggle; ordinary +tracking-off shell taps retain the existing client behavior. Native selection and +the opt-in RIGHT long press are unchanged (see `mouse-long-press.md`). + +The accompanying view controls exercise actual emulator decoding and native +view/gesture events. They test request intent, not physical Android IME display +or remote-widget integration; those require the paired sender and phone run. diff --git a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java index 2a518529c84..3c2d8a9e199 100644 --- a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java +++ b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java @@ -220,6 +220,17 @@ public final class TerminalEmulator { /** The cursor position. Between (0,0) and (mRows-1, mColumns-1). */ private int mCursorRow, mCursorCol; + private TextInputRegion mTextInputRegion = TextInputRegion.EMPTY; + private long mInputContextGeneration; + + public TextInputRegion getTextInputRegion() { return mTextInputRegion; } + public long getInputContextGeneration() { return mInputContextGeneration; } + + /** Geometry and in-flight gestures belong to the current terminal input context. */ + private void invalidateInputContext() { + mTextInputRegion = TextInputRegion.EMPTY; + mInputContextGeneration++; + } /** The number of character rows and columns in the terminal screen. */ public int mRows, mColumns; @@ -449,6 +460,9 @@ private boolean isDecsetInternalBitSet(int bit) { } private void setDecsetinternalBit(int internalBit, boolean set) { + if ((internalBit == DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE + || internalBit == DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT) + && isDecsetInternalBitSet(internalBit) != set) invalidateInputContext(); if (set) { // The mouse modes are mutually exclusive. if (internalBit == DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) { @@ -584,6 +598,7 @@ public void resize(int columns, int rows, int cellWidthPixels, int cellHeightPix throw new IllegalArgumentException("rows=" + rows + ", columns=" + columns); } + invalidateInputContext(); if (mRows != rows) { mRows = rows; mTopMargin = 0; @@ -1858,6 +1873,7 @@ public void doDecSetOrReset(boolean setting, int externalBit) { // Reset: Use Normal Screen Buffer and restore cursor as in DECRC. TerminalBuffer newScreen = setting ? mAltBuffer : mMainBuffer; if (newScreen != mScreen) { + invalidateInputContext(); boolean resized = !(newScreen.mColumns == mColumns && newScreen.mScreenRows == mRows); if (setting) saveCursor(); mScreen = newScreen; @@ -2894,6 +2910,14 @@ private void doOsc(String bellOrStringTerminator) { break; case 119: // Reset highlight color. break; + case 777: // Application-declared text-input bounds, never inferred from the cursor. + mTextInputRegion = TextInputRegion.EMPTY; + try { + mTextInputRegion = TextInputRegion.fromOsc(textParameter, mColumns, mRows); + } catch (IllegalArgumentException error) { + Logger.logError(mClient, LOG_TAG, "Invalid OSC 777 input region: " + error.getMessage()); + } + break; case 1337: // iTerm image // - https://iterm2.com/documentation-images.html // - https://iterm2.com/documentation-escape-codes.html @@ -3487,6 +3511,7 @@ public void setTopRow(int topRow) { /** Reset terminal state so user can interact with it regardless of present state. */ public void reset() { + invalidateInputContext(); setCursorStyle(); mArgIndex = 0; mContinueSequence = false; diff --git a/terminal-emulator/src/main/java/com/termux/terminal/TextInputRegion.java b/terminal-emulator/src/main/java/com/termux/terminal/TextInputRegion.java new file mode 100644 index 00000000000..035a74afab0 --- /dev/null +++ b/terminal-emulator/src/main/java/com/termux/terminal/TextInputRegion.java @@ -0,0 +1,34 @@ +package com.termux.terminal; + +/** An application's explicit focused text-input bounds, in zero-based terminal cells. */ +public final class TextInputRegion { + public static final TextInputRegion EMPTY = new TextInputRegion(0, 0, 0, 0); + + private final int x, y, width, height; + + private TextInputRegion(int x, int y, int width, int height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + /** Decode OSC 777;input-region;x;y;width;height at the terminal boundary. */ + static TextInputRegion fromOsc(String parameter, int columns, int rows) { + String[] fields = parameter.split(";", -1); + if (fields.length != 5 || !fields[0].equals("input-region")) + throw new IllegalArgumentException("Expected input-region;x;y;width;height"); + int x = Integer.parseInt(fields[1]); + int y = Integer.parseInt(fields[2]); + int width = Integer.parseInt(fields[3]); + int height = Integer.parseInt(fields[4]); + if (x < 0 || y < 0 || x > columns || y > rows || width < 0 || height < 0 + || width > columns - x || height > rows - y) + throw new IllegalArgumentException("Input region lies outside the terminal"); + return new TextInputRegion(x, y, width, height); + } + + public boolean contains(int column, int row) { + return column >= x && row >= y && column - x < width && row - y < height; + } +} diff --git a/terminal-view/src/main/java/com/termux/view/TerminalView.java b/terminal-view/src/main/java/com/termux/view/TerminalView.java index fca0062b998..fe41532da0c 100644 --- a/terminal-view/src/main/java/com/termux/view/TerminalView.java +++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java @@ -78,11 +78,16 @@ public final class TerminalView extends View { /** Keep track of the time when a touch event leading to sending mouse scroll events started. */ private long mMouseStartDownTime = -1; - /** A remote cursor response may request the keyboard once after a finger tap. */ + /** Explicit input bounds may acknowledge one recent finger tap. */ static final long MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS = 3000; - private long mMouseTapKeyboardDeadline; + private final KeyboardTapState mNoKeyboardTap = new KeyboardTapState(); + private KeyboardTapState mKeyboardTap = mNoKeyboardTap; final Scroller mScroller; + private final FlingState mNoFling = new FlingState(); + private FlingState mFling = mNoFling; + private static final float FLING_VELOCITY_SCALE = 0.25f; + static final int MAX_MOUSE_FLING_MILLIS = 500; /** What was left in from scrolling movement. */ float mScrollRemainder; @@ -137,12 +142,149 @@ public final class TerminalView extends View { private static final String LOG_TAG = "TerminalView"; + private class KeyboardTapState { + void screenUpdated() { } + } + + private final class PendingKeyboardTap extends KeyboardTapState { + private final int column, row; + private final long deadline, generation; + + PendingKeyboardTap(MotionEvent event) { + int[] cell = getColumnAndRow(event, false); + column = cell[0]; + row = cell[1]; + generation = mEmulator.getInputContextGeneration(); + deadline = SystemClock.uptimeMillis() + MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS; + } + + @Override void screenUpdated() { + if (!mEmulator.isMouseTrackingActive() || isSelectingText() + || mEmulator.getInputContextGeneration() != generation + || SystemClock.uptimeMillis() >= deadline) { + mKeyboardTap = mNoKeyboardTap; + } else if (mEmulator.getTextInputRegion().contains(column, row)) { + mKeyboardTap = mNoKeyboardTap; + mClient.onRequestSoftKeyboard(); + } + } + } + + private enum ScrollAxis { + VERTICAL { + @Override float component(float x, float y) { return y; } + @Override float cellSize(TerminalRenderer renderer) { return renderer.mFontLineSpacing; } + @Override int cells(TerminalEmulator emulator) { return emulator.mRows; } + @Override void scroll(TerminalView view, MotionEvent event, int steps) { + view.doScroll(event, steps); + } + @Override ScrollAxis forTracking(boolean tracking) { return this; } + }, + HORIZONTAL { + @Override float component(float x, float y) { return x; } + @Override float cellSize(TerminalRenderer renderer) { return renderer.mFontWidth; } + @Override int cells(TerminalEmulator emulator) { return emulator.mColumns; } + @Override void scroll(TerminalView view, MotionEvent event, int steps) { + view.doMouseScroll(event, steps, TerminalEmulator.MOUSE_WHEELLEFT_BUTTON, + TerminalEmulator.MOUSE_WHEELRIGHT_BUTTON); + } + @Override ScrollAxis forTracking(boolean tracking) { return tracking ? this : VERTICAL; } + }; + + abstract float component(float x, float y); + abstract float cellSize(TerminalRenderer renderer); + abstract int cells(TerminalEmulator emulator); + abstract void scroll(TerminalView view, MotionEvent event, int steps); + abstract ScrollAxis forTracking(boolean tracking); + } + + private class FlingState { + void stop() { } + } + + /** One owner of frame pacing, the copied gesture and its session/mode lifetime. */ + private abstract class ActiveFling extends FlingState implements Runnable { + final TerminalEmulator emulator = mEmulator; + final long generation = emulator.getInputContextGeneration(); + final MotionEvent event; + + ActiveFling(MotionEvent source) { event = MotionEvent.obtain(source); } + + final void start() { + mFling = this; + postOnAnimation(this); + } + + abstract boolean tracksMouse(); + abstract void scrollTo(int position); + + @Override final void stop() { + if (mFling != this) return; + removeCallbacks(this); + mScroller.abortAnimation(); + event.recycle(); + mFling = mNoFling; + } + + @Override public final void run() { + if (mFling != this) return; + if (mEmulator != emulator || emulator.getInputContextGeneration() != generation + || emulator.isMouseTrackingActive() != tracksMouse() + || isSelectingText() || mScroller.isFinished()) { + stop(); + return; + } + boolean more = mScroller.computeScrollOffset(); + scrollTo(mScroller.getCurrY()); + if (more && !mScroller.isFinished()) postOnAnimation(this); + else stop(); + } + } + + private final class ScrollbackFling extends ActiveFling { + ScrollbackFling(MotionEvent event, float velocityY) { + super(event); + mScroller.fling(0, mTopRow, 0, -(int) (velocityY * FLING_VELOCITY_SCALE), + 0, 0, -emulator.getScreen().getActiveTranscriptRows(), 0); + } + @Override boolean tracksMouse() { return false; } + @Override void scrollTo(int row) { doScroll(event, row - mTopRow); } + } + + private final class MouseFling extends ActiveFling { + private final ScrollAxis axis; + private final float cellSize; + private int steps; + + MouseFling(MotionEvent event, ScrollAxis axis, float velocityX, float velocityY) { + super(event); + this.axis = axis; + cellSize = axis.cellSize(mRenderer); + // Scroller's physics are pixels, not terminal rows. Bound the additional + // wheel reports to one viewport and emit only each newly crossed cell. + int extent = Math.max(1, Math.round(cellSize * axis.cells(emulator))); + mScroller.fling(0, 0, 0, -(int) (axis.component(velocityX, velocityY) * FLING_VELOCITY_SCALE), + 0, 0, -extent, extent); + mScroller.extendDuration(Math.max(1, + Math.min(mScroller.getDuration(), MAX_MOUSE_FLING_MILLIS) - mScroller.timePassed())); + } + @Override boolean tracksMouse() { return true; } + @Override void scrollTo(int pixels) { + int current = (int) (pixels / cellSize); + // At most one wheel report per display frame: no burst/backlog to flush + // after the bounded animation settles or another touch cancels it. + int delta = Math.max(-1, Math.min(1, current - steps)); + axis.scroll(TerminalView.this, event, delta); + steps += delta; + } + } + public TerminalView(Context context, AttributeSet attributes) { // NO_UCD (unused code) super(context, attributes); mGestureRecognizer = new GestureAndScaleRecognizer(context, new GestureAndScaleRecognizer.Listener() { boolean scrolledWithFinger; - boolean scrolledHorizontally; + ScrollAxis axis = ScrollAxis.VERTICAL; @Override public boolean onUp(MotionEvent event) { @@ -151,13 +293,14 @@ public boolean onUp(MotionEvent event) { // Quick event processing when mouse tracking is active - do not wait for check of double tapping // for zooming. requestFocus(); - mMouseTapKeyboardDeadline = SystemClock.uptimeMillis() + MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS; + mKeyboardTap = new PendingKeyboardTap(event); sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON, true); sendMouseEventCode(event, TerminalEmulator.MOUSE_LEFT_BUTTON, false); + mKeyboardTap.screenUpdated(); return true; } scrolledWithFinger = false; - scrolledHorizontally = false; + axis = ScrollAxis.VERTICAL; return false; } @@ -186,23 +329,20 @@ public boolean onScroll(MotionEvent e, float distanceX, float distanceY) { } else { if (!scrolledWithFinger) { // Lock the axis at the first scroll, after GestureDetector's touch slop. - scrolledHorizontally = mEmulator.isMouseTrackingActive() && !isSelectingText() - && Math.abs(distanceX) > Math.abs(distanceY); + axis = mEmulator.isMouseTrackingActive() && !isSelectingText() + && Math.abs(distanceX) > Math.abs(distanceY) ? ScrollAxis.HORIZONTAL : ScrollAxis.VERTICAL; } scrolledWithFinger = true; - if (scrolledHorizontally && !mEmulator.isMouseTrackingActive()) { - scrolledHorizontally = false; + ScrollAxis current = axis.forTracking(mEmulator.isMouseTrackingActive()); + if (current != axis) { + axis = current; mScrollRemainder = 0.0f; } - float cellSize = scrolledHorizontally ? mRenderer.mFontWidth : mRenderer.mFontLineSpacing; - float distance = (scrolledHorizontally ? distanceX : distanceY) + mScrollRemainder; + float cellSize = axis.cellSize(mRenderer); + float distance = axis.component(distanceX, distanceY) + mScrollRemainder; int delta = (int) (distance / cellSize); mScrollRemainder = distance - delta * cellSize; - if (scrolledHorizontally) { - doMouseScroll(e, delta, TerminalEmulator.MOUSE_WHEELLEFT_BUTTON, TerminalEmulator.MOUSE_WHEELRIGHT_BUTTON); - } else { - doScroll(e, delta); - } + axis.scroll(TerminalView.this, e, delta); } return true; } @@ -210,6 +350,7 @@ public boolean onScroll(MotionEvent e, float distanceX, float distanceY) { @Override public boolean onScale(float focusX, float focusY, float scale) { if (mEmulator == null || isSelectingText()) return true; + mFling.stop(); mScaleFactor *= scale; mScaleFactor = mClient.onScale(mScaleFactor); return true; @@ -217,29 +358,11 @@ public boolean onScale(float focusX, float focusY, float scale) { @Override public boolean onFling(final MotionEvent e2, float velocityX, float velocityY) { - // Tracked applications already received every gesture row; do not invent wheel - // reports after release. Preserve kinetic scrolling when tracking is off. - if (mEmulator == null || scrolledHorizontally || mEmulator.isMouseTrackingActive()) return true; - // Do not start scrolling until last fling has been taken care of: - if (!mScroller.isFinished()) return true; - - float SCALE = 0.25f; - mScroller.fling(0, mTopRow, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.getScreen().getActiveTranscriptRows(), 0); - - post(new Runnable() { - @Override - public void run() { - if (mEmulator == null || mEmulator.isMouseTrackingActive()) { - mScroller.abortAnimation(); - return; - } - if (mScroller.isFinished()) return; - boolean more = mScroller.computeScrollOffset(); - int newY = mScroller.getCurrY(); - doScroll(e2, newY - mTopRow); - if (more) post(this); - } - }); + if (mEmulator == null || isSelectingText() || e2.isFromSource(InputDevice.SOURCE_MOUSE)) return true; + mFling.stop(); + ActiveFling fling = mEmulator.isMouseTrackingActive() + ? new MouseFling(e2, axis, velocityX, velocityY) : new ScrollbackFling(e2, velocityY); + fling.start(); return true; } @@ -249,7 +372,7 @@ public boolean onDown(float x, float y) { // Also reset after a cancelled gesture or a long press, which skips onUp(). mScrollRemainder = 0.0f; scrolledWithFinger = false; - scrolledHorizontally = false; + axis = ScrollAxis.VERTICAL; // Why is true not returned here? // https://developer.android.com/training/gestures/detector.html#detect-a-subset-of-supported-gestures // Although setting this to true still does not solve the following errors when long pressing in terminal view text area @@ -316,7 +439,8 @@ public void setIsTerminalViewKeyLoggingEnabled(boolean value) { public boolean attachSession(TerminalSession session) { if (session == mTermSession) return false; - mMouseTapKeyboardDeadline = 0; + mKeyboardTap = mNoKeyboardTap; + mFling.stop(); mTermSession = session; mEmulator = null; mCombiningAccent = 0; @@ -486,14 +610,9 @@ public void onScreenUpdated() { public void onScreenUpdated(boolean skipScrolling) { if (mEmulator == null) return; - // Read only this view's emulator: the shared cursor callback has no session identity. - // Use DECTCEM, not the cursor's local animation phase, and consume before showing IME. - if (!mEmulator.isMouseTrackingActive() || isSelectingText()) { - mMouseTapKeyboardDeadline = 0; - } else if (mMouseTapKeyboardDeadline > SystemClock.uptimeMillis() && mEmulator.isCursorEnabled()) { - mMouseTapKeyboardDeadline = 0; - mClient.onRequestSoftKeyboard(); - } + // Only bounds declared by this session's application can acknowledge the + // tapped input. A cursor repaint carries neither widget identity nor bounds. + mKeyboardTap.screenUpdated(); int rowsInHistory = mEmulator.getScreen().getActiveTranscriptRows(); if (mTopRow < -rowsInHistory) setTopRow(-rowsInHistory); @@ -655,7 +774,8 @@ public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_CANCEL || event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { - mMouseTapKeyboardDeadline = 0; + mKeyboardTap = mNoKeyboardTap; + mFling.stop(); } if (isSelectingText()) { @@ -695,7 +815,10 @@ public boolean onTouchEvent(MotionEvent event) { @Override public void onWindowFocusChanged(boolean hasWindowFocus) { - if (!hasWindowFocus) mMouseTapKeyboardDeadline = 0; + if (!hasWindowFocus) { + mKeyboardTap = mNoKeyboardTap; + mFling.stop(); + } super.onWindowFocusChanged(hasWindowFocus); } @@ -1483,6 +1606,8 @@ private ActionMode getTextSelectionActionMode() { } public void startTextSelectionMode(MotionEvent event) { + mKeyboardTap = mNoKeyboardTap; + mFling.stop(); if (!requestFocus()) { return; } @@ -1517,7 +1642,8 @@ protected void onAttachedToWindow() { @Override protected void onDetachedFromWindow() { - mMouseTapKeyboardDeadline = 0; + mKeyboardTap = mNoKeyboardTap; + mFling.stop(); super.onDetachedFromWindow(); if (mTextSelectionCursorController != null) { From a2dfd60327ddfff8f4ac967db141c8b2a119679c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 2 Nov 2026 14:19:33 -0500 Subject: [PATCH 2/4] Retire delayed touch callbacks at their original event time --- .../com/termux/view/TerminalViewKeyboardTest.java | 15 +++++++++++++++ .../com/termux/view/TerminalViewMouseTest.java | 13 +++++++++++++ .../main/java/com/termux/view/TerminalView.java | 8 ++++++-- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java index 061a6ada89b..a669b48afa7 100644 --- a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java @@ -6,6 +6,9 @@ import android.view.ViewConfiguration; import org.junit.Test; +import org.robolectric.shadows.ShadowSystemClock; + +import java.time.Duration; import static org.junit.Assert.assertEquals; @@ -123,6 +126,18 @@ public void incompleteControlIsNotAnAdvertisement() { assertEquals(1, client.keyboardRequests); } + @Test + public void delayedTapDeliveryDoesNotCreateFreshKeyboardIntent() { + input("\033[?1000h"); + inputResponse(); + MotionEvent up = event(SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, + 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + ShadowSystemClock.advanceBy(Duration.ofMillis(TerminalView.MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS + 1)); + view.mGestureRecognizer.mListener.onUp(up); + up.recycle(); + assertEquals(0, client.keyboardRequests); + } + @Test public void responseAfterRecentTapWindowHasExpiredIsIgnored() { trackingTap(); diff --git a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java index 969fa68fe1b..940bd2adebe 100644 --- a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java @@ -9,6 +9,9 @@ import org.junit.Test; import org.robolectric.RuntimeEnvironment; +import org.robolectric.shadows.ShadowSystemClock; + +import java.time.Duration; import static org.junit.Assert.*; @@ -116,6 +119,16 @@ private void assertTrackedVerticalMomentum(int mode) { @Test public void tracked1002VerticalReleaseHasBoundedMomentum() { assertTrackedVerticalMomentum(1002); } + @Test + public void delayedDisplayFrameDropsTheSettledTail() { + input("\033[?1000h\033[?1006h"); + fling(0, -20000); + ShadowSystemClock.advanceBy(Duration.ofMillis(TerminalView.MAX_MOUSE_FLING_MILLIS + 1)); + advance(32); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } + @Test public void newDownStopsMomentumBeforeAnotherWheelReport() { input("\033[?1000h\033[?1006h"); diff --git a/terminal-view/src/main/java/com/termux/view/TerminalView.java b/terminal-view/src/main/java/com/termux/view/TerminalView.java index fe41532da0c..c9ec616288e 100644 --- a/terminal-view/src/main/java/com/termux/view/TerminalView.java +++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java @@ -155,7 +155,7 @@ private final class PendingKeyboardTap extends KeyboardTapState { column = cell[0]; row = cell[1]; generation = mEmulator.getInputContextGeneration(); - deadline = SystemClock.uptimeMillis() + MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS; + deadline = event.getEventTime() + MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS; } @Override void screenUpdated() { @@ -217,6 +217,7 @@ final void start() { abstract boolean tracksMouse(); abstract void scrollTo(int position); + boolean expired() { return false; } @Override final void stop() { if (mFling != this) return; @@ -230,7 +231,7 @@ final void start() { if (mFling != this) return; if (mEmulator != emulator || emulator.getInputContextGeneration() != generation || emulator.isMouseTrackingActive() != tracksMouse() - || isSelectingText() || mScroller.isFinished()) { + || isSelectingText() || expired() || mScroller.isFinished()) { stop(); return; } @@ -269,6 +270,9 @@ private final class MouseFling extends ActiveFling { Math.min(mScroller.getDuration(), MAX_MOUSE_FLING_MILLIS) - mScroller.timePassed())); } @Override boolean tracksMouse() { return true; } + @Override boolean expired() { + return SystemClock.uptimeMillis() - event.getEventTime() >= MAX_MOUSE_FLING_MILLIS; + } @Override void scrollTo(int pixels) { int current = (int) (pixels / cellSize); // At most one wheel report per display frame: no burst/backlog to flush From b18c61432eb2e39dc664b1757fd69b31faefb82a Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 2 Nov 2026 14:54:20 -0500 Subject: [PATCH 3/4] Restore upstream scrolling and fling implementation --- .../java/com/termux/view/TerminalView.java | 203 ++++-------------- 1 file changed, 37 insertions(+), 166 deletions(-) diff --git a/terminal-view/src/main/java/com/termux/view/TerminalView.java b/terminal-view/src/main/java/com/termux/view/TerminalView.java index c9ec616288e..95f99e43a5f 100644 --- a/terminal-view/src/main/java/com/termux/view/TerminalView.java +++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java @@ -84,10 +84,6 @@ public final class TerminalView extends View { private KeyboardTapState mKeyboardTap = mNoKeyboardTap; final Scroller mScroller; - private final FlingState mNoFling = new FlingState(); - private FlingState mFling = mNoFling; - private static final float FLING_VELOCITY_SCALE = 0.25f; - static final int MAX_MOUSE_FLING_MILLIS = 500; /** What was left in from scrolling movement. */ float mScrollRemainder; @@ -170,125 +166,11 @@ private final class PendingKeyboardTap extends KeyboardTapState { } } - private enum ScrollAxis { - VERTICAL { - @Override float component(float x, float y) { return y; } - @Override float cellSize(TerminalRenderer renderer) { return renderer.mFontLineSpacing; } - @Override int cells(TerminalEmulator emulator) { return emulator.mRows; } - @Override void scroll(TerminalView view, MotionEvent event, int steps) { - view.doScroll(event, steps); - } - @Override ScrollAxis forTracking(boolean tracking) { return this; } - }, - HORIZONTAL { - @Override float component(float x, float y) { return x; } - @Override float cellSize(TerminalRenderer renderer) { return renderer.mFontWidth; } - @Override int cells(TerminalEmulator emulator) { return emulator.mColumns; } - @Override void scroll(TerminalView view, MotionEvent event, int steps) { - view.doMouseScroll(event, steps, TerminalEmulator.MOUSE_WHEELLEFT_BUTTON, - TerminalEmulator.MOUSE_WHEELRIGHT_BUTTON); - } - @Override ScrollAxis forTracking(boolean tracking) { return tracking ? this : VERTICAL; } - }; - - abstract float component(float x, float y); - abstract float cellSize(TerminalRenderer renderer); - abstract int cells(TerminalEmulator emulator); - abstract void scroll(TerminalView view, MotionEvent event, int steps); - abstract ScrollAxis forTracking(boolean tracking); - } - - private class FlingState { - void stop() { } - } - - /** One owner of frame pacing, the copied gesture and its session/mode lifetime. */ - private abstract class ActiveFling extends FlingState implements Runnable { - final TerminalEmulator emulator = mEmulator; - final long generation = emulator.getInputContextGeneration(); - final MotionEvent event; - - ActiveFling(MotionEvent source) { event = MotionEvent.obtain(source); } - - final void start() { - mFling = this; - postOnAnimation(this); - } - - abstract boolean tracksMouse(); - abstract void scrollTo(int position); - boolean expired() { return false; } - - @Override final void stop() { - if (mFling != this) return; - removeCallbacks(this); - mScroller.abortAnimation(); - event.recycle(); - mFling = mNoFling; - } - - @Override public final void run() { - if (mFling != this) return; - if (mEmulator != emulator || emulator.getInputContextGeneration() != generation - || emulator.isMouseTrackingActive() != tracksMouse() - || isSelectingText() || expired() || mScroller.isFinished()) { - stop(); - return; - } - boolean more = mScroller.computeScrollOffset(); - scrollTo(mScroller.getCurrY()); - if (more && !mScroller.isFinished()) postOnAnimation(this); - else stop(); - } - } - - private final class ScrollbackFling extends ActiveFling { - ScrollbackFling(MotionEvent event, float velocityY) { - super(event); - mScroller.fling(0, mTopRow, 0, -(int) (velocityY * FLING_VELOCITY_SCALE), - 0, 0, -emulator.getScreen().getActiveTranscriptRows(), 0); - } - @Override boolean tracksMouse() { return false; } - @Override void scrollTo(int row) { doScroll(event, row - mTopRow); } - } - - private final class MouseFling extends ActiveFling { - private final ScrollAxis axis; - private final float cellSize; - private int steps; - - MouseFling(MotionEvent event, ScrollAxis axis, float velocityX, float velocityY) { - super(event); - this.axis = axis; - cellSize = axis.cellSize(mRenderer); - // Scroller's physics are pixels, not terminal rows. Bound the additional - // wheel reports to one viewport and emit only each newly crossed cell. - int extent = Math.max(1, Math.round(cellSize * axis.cells(emulator))); - mScroller.fling(0, 0, 0, -(int) (axis.component(velocityX, velocityY) * FLING_VELOCITY_SCALE), - 0, 0, -extent, extent); - mScroller.extendDuration(Math.max(1, - Math.min(mScroller.getDuration(), MAX_MOUSE_FLING_MILLIS) - mScroller.timePassed())); - } - @Override boolean tracksMouse() { return true; } - @Override boolean expired() { - return SystemClock.uptimeMillis() - event.getEventTime() >= MAX_MOUSE_FLING_MILLIS; - } - @Override void scrollTo(int pixels) { - int current = (int) (pixels / cellSize); - // At most one wheel report per display frame: no burst/backlog to flush - // after the bounded animation settles or another touch cancels it. - int delta = Math.max(-1, Math.min(1, current - steps)); - axis.scroll(TerminalView.this, event, delta); - steps += delta; - } - } - public TerminalView(Context context, AttributeSet attributes) { // NO_UCD (unused code) super(context, attributes); mGestureRecognizer = new GestureAndScaleRecognizer(context, new GestureAndScaleRecognizer.Listener() { boolean scrolledWithFinger; - ScrollAxis axis = ScrollAxis.VERTICAL; @Override public boolean onUp(MotionEvent event) { @@ -304,7 +186,6 @@ public boolean onUp(MotionEvent event) { return true; } scrolledWithFinger = false; - axis = ScrollAxis.VERTICAL; return false; } @@ -331,22 +212,11 @@ public boolean onScroll(MotionEvent e, float distanceX, float distanceY) { // which we do not do for touch input, only mouse in onTouchEvent(). sendMouseEventCode(e, TerminalEmulator.MOUSE_LEFT_BUTTON_MOVED, true); } else { - if (!scrolledWithFinger) { - // Lock the axis at the first scroll, after GestureDetector's touch slop. - axis = mEmulator.isMouseTrackingActive() && !isSelectingText() - && Math.abs(distanceX) > Math.abs(distanceY) ? ScrollAxis.HORIZONTAL : ScrollAxis.VERTICAL; - } scrolledWithFinger = true; - ScrollAxis current = axis.forTracking(mEmulator.isMouseTrackingActive()); - if (current != axis) { - axis = current; - mScrollRemainder = 0.0f; - } - float cellSize = axis.cellSize(mRenderer); - float distance = axis.component(distanceX, distanceY) + mScrollRemainder; - int delta = (int) (distance / cellSize); - mScrollRemainder = distance - delta * cellSize; - axis.scroll(TerminalView.this, e, delta); + distanceY += mScrollRemainder; + int deltaRows = (int) (distanceY / mRenderer.mFontLineSpacing); + mScrollRemainder = distanceY - deltaRows * mRenderer.mFontLineSpacing; + doScroll(e, deltaRows); } return true; } @@ -354,7 +224,6 @@ public boolean onScroll(MotionEvent e, float distanceX, float distanceY) { @Override public boolean onScale(float focusX, float focusY, float scale) { if (mEmulator == null || isSelectingText()) return true; - mFling.stop(); mScaleFactor *= scale; mScaleFactor = mClient.onScale(mScaleFactor); return true; @@ -362,21 +231,42 @@ public boolean onScale(float focusX, float focusY, float scale) { @Override public boolean onFling(final MotionEvent e2, float velocityX, float velocityY) { - if (mEmulator == null || isSelectingText() || e2.isFromSource(InputDevice.SOURCE_MOUSE)) return true; - mFling.stop(); - ActiveFling fling = mEmulator.isMouseTrackingActive() - ? new MouseFling(e2, axis, velocityX, velocityY) : new ScrollbackFling(e2, velocityY); - fling.start(); + if (mEmulator == null) return true; + // Do not start scrolling until last fling has been taken care of: + if (!mScroller.isFinished()) return true; + + final boolean mouseTrackingAtStartOfFling = mEmulator.isMouseTrackingActive(); + float SCALE = 0.25f; + if (mouseTrackingAtStartOfFling) { + mScroller.fling(0, 0, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.mRows / 2, mEmulator.mRows / 2); + } else { + mScroller.fling(0, mTopRow, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.getScreen().getActiveTranscriptRows(), 0); + } + + post(new Runnable() { + private int mLastY = 0; + + @Override + public void run() { + if (mouseTrackingAtStartOfFling != mEmulator.isMouseTrackingActive()) { + mScroller.abortAnimation(); + return; + } + if (mScroller.isFinished()) return; + boolean more = mScroller.computeScrollOffset(); + int newY = mScroller.getCurrY(); + int diff = mouseTrackingAtStartOfFling ? (newY - mLastY) : (newY - mTopRow); + doScroll(e2, diff); + mLastY = newY; + if (more) post(this); + } + }); return true; } @Override public boolean onDown(float x, float y) { - // Also reset after a cancelled gesture or a long press, which skips onUp(). - mScrollRemainder = 0.0f; - scrolledWithFinger = false; - axis = ScrollAxis.VERTICAL; // Why is true not returned here? // https://developer.android.com/training/gestures/detector.html#detect-a-subset-of-supported-gestures // Although setting this to true still does not solve the following errors when long pressing in terminal view text area @@ -444,7 +334,6 @@ public boolean attachSession(TerminalSession session) { if (session == mTermSession) return false; mKeyboardTap = mNoKeyboardTap; - mFling.stop(); mTermSession = session; mEmulator = null; mCombiningAccent = 0; @@ -732,14 +621,12 @@ void sendMouseEventCode(MotionEvent e, int button, boolean pressed) { /** Perform a scroll, either from dragging the screen or by scrolling a mouse wheel. */ void doScroll(MotionEvent event, int rowsDown) { - if (mEmulator.isMouseTrackingActive()) { - doMouseScroll(event, rowsDown, TerminalEmulator.MOUSE_WHEELUP_BUTTON, TerminalEmulator.MOUSE_WHEELDOWN_BUTTON); - return; - } boolean up = rowsDown < 0; int amount = Math.abs(rowsDown); for (int i = 0; i < amount; i++) { - if (mEmulator.isAlternateBufferActive()) { + if (mEmulator.isMouseTrackingActive()) { + sendMouseEventCode(event, up ? TerminalEmulator.MOUSE_WHEELUP_BUTTON : TerminalEmulator.MOUSE_WHEELDOWN_BUTTON, true); + } else if (mEmulator.isAlternateBufferActive()) { // Send up and down key events for scrolling, which is what some terminals do to make scroll work in // e.g. less, which shifts to the alt screen without mouse handling. handleKeyCode(up ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 0); @@ -750,14 +637,6 @@ void doScroll(MotionEvent event, int rowsDown) { } } - /** Both wheel axes use the same encoder and gesture-origin cell. */ - void doMouseScroll(MotionEvent event, int steps, int negativeButton, int positiveButton) { - int button = steps < 0 ? negativeButton : positiveButton; - for (int i = 0; i < Math.abs(steps); i++) { - sendMouseEventCode(event, button, true); - } - } - /** Overriding {@link View#onGenericMotionEvent(MotionEvent)}. */ @Override public boolean onGenericMotionEvent(MotionEvent event) { @@ -776,11 +655,6 @@ public boolean onGenericMotionEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) { if (mEmulator == null) return true; final int action = event.getAction(); - if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_CANCEL - || event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { - mKeyboardTap = mNoKeyboardTap; - mFling.stop(); - } if (isSelectingText()) { updateFloatingToolbarVisibility(event); @@ -821,7 +695,6 @@ public boolean onTouchEvent(MotionEvent event) { public void onWindowFocusChanged(boolean hasWindowFocus) { if (!hasWindowFocus) { mKeyboardTap = mNoKeyboardTap; - mFling.stop(); } super.onWindowFocusChanged(hasWindowFocus); } @@ -1611,7 +1484,6 @@ private ActionMode getTextSelectionActionMode() { public void startTextSelectionMode(MotionEvent event) { mKeyboardTap = mNoKeyboardTap; - mFling.stop(); if (!requestFocus()) { return; } @@ -1647,7 +1519,6 @@ protected void onAttachedToWindow() { @Override protected void onDetachedFromWindow() { mKeyboardTap = mNoKeyboardTap; - mFling.stop(); super.onDetachedFromWindow(); if (mTextSelectionCursorController != null) { From eef7194cd1aa09611821b72806211f203589b372 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 2 Nov 2026 15:05:50 -0500 Subject: [PATCH 4/4] Exercise stock fling displacement and retain keyboard intent cancellation --- .../termux/view/TerminalViewMouseTest.java | 249 +++++++----------- .../com/termux/view/TerminalViewTestCase.java | 2 +- docs/touch-input.md | 72 ++--- .../com/termux/terminal/TerminalEmulator.java | 2 - .../java/com/termux/view/TerminalView.java | 11 +- 5 files changed, 137 insertions(+), 199 deletions(-) diff --git a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java index 940bd2adebe..417f657465e 100644 --- a/app/src/test/java/com/termux/view/TerminalViewMouseTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewMouseTest.java @@ -1,6 +1,5 @@ package com.termux.view; -import android.os.SystemClock; import android.view.InputDevice; import android.view.MotionEvent; @@ -15,6 +14,7 @@ import static org.junit.Assert.*; +/** Stock scrolling/Scroller units and the independently retained long-press policy. */ public class TerminalViewMouseTest extends TerminalViewTestCase { private void scroll(float columns, float rows) { @@ -25,25 +25,31 @@ private void scroll(float columns, float rows) { } @Test - public void horizontalFractionalMotionUsesRightWheelAndLocksAxis() { + public void fractionalVerticalMotionAccumulatesThroughTheStockEncoder() { input("\033[?1000h\033[?1006h"); - scroll(0.4f, 0); + scroll(0, 0.4f); assertEquals("", output.text()); - scroll(0.7f, 0); - assertEquals("\033[<67;3;4M", output.text()); - scroll(1, 4); - assertEquals("\033[<67;3;4M\033[<67;3;4M", output.text()); + scroll(0, 0.7f); + assertEquals("\033[<65;3;4M", output.text()); } @Test - public void negativeMotionUsesLeftWheelThroughLegacyEncoder() { + public void diagonalMotionRetainsItsVerticalDistance() { + input("\033[?1000h\033[?1006h"); + scroll(5, 1); + scroll(-5, 2); + assertEquals("\033[<65;3;4M\033[<65;3;4M\033[<65;3;4M", output.text()); + } + + @Test + public void negativeVerticalMotionUsesTheLegacyUpWheelEncoder() { input("\033[?1002h"); - scroll(-2.25f, 0); - assertEquals("\033[Mb#$\033[Mb#$", output.text()); + scroll(0, -2.25f); + assertEquals("\033[M`#$\033[M`#$", output.text()); } @Test - public void verticalGestureKeepsUpWheelOriginAndAxis() { + public void verticalGestureKeepsItsOriginalCell() { input("\033[?1000h\033[?1006h"); scroll(0, -1); MotionEvent event = event(1, MotionEvent.ACTION_MOVE, 9.5f, 8.5f, InputDevice.SOURCE_TOUCHSCREEN); @@ -52,13 +58,6 @@ public void verticalGestureKeepsUpWheelOriginAndAxis() { assertEquals("\033[<64;3;4M\033[<64;3;4M", output.text()); } - @Test - public void trackingOffDoesNotSendHorizontalWheel() { - scroll(4, 0); - assertEquals("", output.text()); - assertEquals(0, view.getTopRow()); - } - @Test public void mouseDragStillSendsMotionRatherThanWheel() { input("\033[?1002h\033[?1006h"); @@ -68,115 +67,74 @@ public void mouseDragStillSendsMotionRatherThanWheel() { assertEquals("\033[<32;3;4M", output.text()); } - private void fling(float velocityX, float velocityY) { - MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.mGestureRecognizer.mListener.onFling(up, velocityX, velocityY); - // Android owns/recycles the source event; the continuation owns its copy. - up.setLocation(1000, 1000); - up.recycle(); - } - - @Test - public void horizontalReleaseGlidesOnItsLockedAxis() { - input("\033[?1000h\033[?1006h"); - scroll(2, 0); - String initial = output.text(); - fling(-20000, 20000); - assertFalse(view.mScroller.isFinished()); - assertEquals(initial, output.text()); - advance(TerminalView.MAX_MOUSE_FLING_MILLIS + 32); - String continuation = output.text().substring(initial.length()); - String report = "\033[<67;3;4M"; - assertFalse(continuation.isEmpty()); - assertEquals("", continuation.replace(report, "")); - assertTrue(continuation.length() / report.length() <= view.mEmulator.mColumns); - assertTrue(view.mScroller.isFinished()); + private void settleStockFling() { + // Advance the native clock before draining the stock immediate-post loop. + // This exercises its final displacement without a zero-time scheduler spin. + ShadowSystemClock.advanceBy(Duration.ofSeconds(30)); + advance(1); } private void assertTrackedVerticalMomentum(int mode) { input("\033[?" + mode + "h\033[?1006h"); scroll(0, 2); - String initial = "\033[<65;3;4M\033[<65;3;4M"; - assertEquals(initial, output.text()); - fling(0, -20000); - assertFalse(view.mScroller.isFinished()); - assertEquals(initial, output.text()); - advance(TerminalView.MAX_MOUSE_FLING_MILLIS + 32); - String continuation = output.text().substring(initial.length()); - String report = "\033[<65;3;4M"; - assertFalse(continuation.isEmpty()); - assertEquals("", continuation.replace(report, "")); - assertTrue(continuation.length() / report.length() <= view.mEmulator.mRows); - assertTrue(view.mScroller.isFinished()); - String settled = output.text(); - advance(1000); - assertEquals(settled, output.text()); - } - - @Test - public void tracked1000VerticalReleaseHasBoundedMomentum() { assertTrackedVerticalMomentum(1000); } - - @Test - public void tracked1002VerticalReleaseHasBoundedMomentum() { assertTrackedVerticalMomentum(1002); } - - @Test - public void delayedDisplayFrameDropsTheSettledTail() { - input("\033[?1000h\033[?1006h"); - fling(0, -20000); - ShadowSystemClock.advanceBy(Duration.ofMillis(TerminalView.MAX_MOUSE_FLING_MILLIS + 1)); - advance(32); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); - } - - @Test - public void newDownStopsMomentumBeforeAnotherWheelReport() { - input("\033[?1000h\033[?1006h"); - fling(0, -20000); - touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); + String initial = output.text(); + assertEquals("\033[<65;3;4M\033[<65;3;4M", initial); + MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + try { + view.mGestureRecognizer.mListener.onFling(up, 0, -20000); + assertFalse(view.mScroller.isFinished()); + int stockExtent = view.mEmulator.mRows / 2; + assertEquals(stockExtent, view.mScroller.getFinalY()); + settleStockFling(); + String continuation = output.text().substring(initial.length()); + String report = "\033[<65;3;4M"; + assertEquals("", continuation.replace(report, "")); + assertEquals(stockExtent, continuation.length() / report.length()); + assertTrue(view.mScroller.isFinished()); + String settled = output.text(); + advance(1000); + assertEquals(settled, output.text()); + } finally { + up.recycle(); + } } @Test - public void cancellationStopsMomentumBeforeAnotherWheelReport() { - input("\033[?1000h\033[?1006h"); - fling(0, -20000); - touch(SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); - } + public void tracked1000ReleaseUsesStockRowMomentum() { assertTrackedVerticalMomentum(1000); } @Test - public void trackingRoundTripInOneReadRetiresOldMomentum() { - input("\033[?1000h\033[?1006h"); - fling(0, -20000); - input("\033[?1000l\033[?1000h"); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); - } + public void tracked1002ReleaseUsesStockRowMomentum() { assertTrackedVerticalMomentum(1002); } @Test - public void bufferSwitchRetiresOldMomentum() { + public void reverseFlickUsesTheStockNegativeRowExtent() { input("\033[?1000h\033[?1006h"); - fling(0, -20000); - input("\033[?1049h"); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); + MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + try { + view.mGestureRecognizer.mListener.onFling(up, 0, 20000); + int stockExtent = view.mEmulator.mRows / 2; + assertEquals(-stockExtent, view.mScroller.getFinalY()); + settleStockFling(); + String report = "\033[<64;3;4M"; + assertEquals("", output.text().replace(report, "")); + assertEquals(stockExtent, output.text().length() / report.length()); + } finally { + up.recycle(); + } } @Test - public void resizeRetiresOldMomentum() { + public void activeFlingKeepsItsExistingScrollerDestination() { input("\033[?1000h\033[?1006h"); - fling(0, -20000); - view.mEmulator.resize(81, 24, 8, 16); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); + MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); + try { + view.mGestureRecognizer.mListener.onFling(up, 0, -20000); + int destination = view.mScroller.getFinalY(); + view.mGestureRecognizer.mListener.onFling(up, 0, 20000); + assertEquals(destination, view.mScroller.getFinalY()); + settleStockFling(); + } finally { + up.recycle(); + } } private void prepareScrollback() { @@ -186,62 +144,36 @@ private void prepareScrollback() { } @Test - public void trackingOffScrollbackStillStartsFling() { + public void trackingOffScrollbackRetainsStockFlingPhysics() { prepareScrollback(); MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.mGestureRecognizer.mListener.onFling(up, 0, 2000); - up.recycle(); - assertFalse(view.mScroller.isFinished()); - advance(1000); - assertTrue(view.mScroller.isFinished()); - assertTrue(view.getTopRow() < 0); - assertEquals("", output.text()); + try { + view.mGestureRecognizer.mListener.onFling(up, 0, 2000); + assertFalse(view.mScroller.isFinished()); + int destination = view.mScroller.getFinalY(); + assertTrue(destination < 0); + settleStockFling(); + assertTrue(view.mScroller.isFinished()); + assertEquals(destination, view.getTopRow()); + assertEquals("", output.text()); + } finally { + up.recycle(); + } } @Test public void enablingTrackingAbortsAnUntrackedFlingWithoutWheelReports() { prepareScrollback(); MotionEvent up = event(1, MotionEvent.ACTION_UP, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.mGestureRecognizer.mListener.onFling(up, 0, 2000); - up.recycle(); - input("\033[?1000h\033[?1006h"); - advance(32); - assertTrue(view.mScroller.isFinished()); - assertEquals("", output.text()); - } - - @Test - public void nextDownClearsCancelledGestureFractionAndAxis() { - input("\033[?1000h\033[?1006h"); - scroll(0.8f, 0); - MotionEvent cancel = event(1, MotionEvent.ACTION_CANCEL, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.onTouchEvent(cancel); - cancel.recycle(); - MotionEvent down = event(2, MotionEvent.ACTION_DOWN, 2.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.onTouchEvent(down); - down.recycle(); - scroll(0.3f, 0); - assertEquals("", output.text()); - } - - @Test - public void actualTouchSwipeDoesNotAlsoProduceVerticalWheelOrLeftTap() { - input("\033[?1000h\033[?1006h"); - long time = SystemClock.uptimeMillis(); - MotionEvent down = event(time, MotionEvent.ACTION_DOWN, 30.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.onTouchEvent(down); - down.recycle(); - MotionEvent move = event(time, MotionEvent.ACTION_MOVE, 10.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.onTouchEvent(move); - move.recycle(); - MotionEvent up = event(time, MotionEvent.ACTION_UP, 10.5f, 3.5f, InputDevice.SOURCE_TOUCHSCREEN); - view.onTouchEvent(up); - up.recycle(); - assertFalse(output.text().isEmpty()); - assertFalse(output.text().contains("\033[<0;")); - assertFalse(output.text().contains("\033[<64;")); - assertFalse(output.text().contains("\033[<65;")); - assertTrue(output.text().contains("\033[<67;")); + try { + view.mGestureRecognizer.mListener.onFling(up, 0, 2000); + input("\033[?1000h\033[?1006h"); + advance(1); + assertTrue(view.mScroller.isFinished()); + assertEquals("", output.text()); + } finally { + up.recycle(); + } } @Test @@ -317,5 +249,4 @@ public void rightClickPropertyIsExplicitlyOptIn() { assertEquals(Boolean.TRUE, TermuxSharedProperties.getInternalTermuxPropertyValueFromValue( RuntimeEnvironment.getApplication(), key, "true")); } - } diff --git a/app/src/test/java/com/termux/view/TerminalViewTestCase.java b/app/src/test/java/com/termux/view/TerminalViewTestCase.java index a9eea67652e..cae41b70231 100644 --- a/app/src/test/java/com/termux/view/TerminalViewTestCase.java +++ b/app/src/test/java/com/termux/view/TerminalViewTestCase.java @@ -95,7 +95,7 @@ protected MotionEvent event(long down, int action, float column, float row, int protected void touch(long down, int action, float column, float row, int source) { MotionEvent event = event(down, action, column, row, source); - view.onTouchEvent(event); + view.dispatchTouchEvent(event); event.recycle(); } diff --git a/docs/touch-input.md b/docs/touch-input.md index 5baf3c8c6ca..e7a87cd5b97 100644 --- a/docs/touch-input.md +++ b/docs/touch-input.md @@ -1,46 +1,46 @@ -# Tracked touch scrolling and keyboard intent +# Stock scrolling and application-declared keyboard intent -Finger flicks in mouse-tracking applications retain momentum. Both axes use the -same axis owner and mouse encoder as the finger drag. The continuation runs on -Android display frames, sends at most one wheel report per frame, lasts at most -500 ms, and contributes no more wheel steps than one terminal viewport on its -axis. It drops any remaining distance when it settles; it does not flush a tail -of queued reports. A new touch, cancellation, selection, window loss or detach -stops it. Session, tracking-mode, screen-buffer and size changes retire the old -input context. Untracked terminal scrollback keeps its existing fling physics. +Scrolling uses upstream Termux's gesture and Scroller implementation. `onScroll`, +`onFling`, `onDown`, `doScroll` and `onTouchEvent` are restored byte-for-byte from +upstream8629e632. Vertical movement keeps its fractional row remainder and the +existing wheel encoder; tracked flings keep Scroller's original row units and +half-screen destination. Untracked scrollback keeps its original physics. -The original release patch incorrectly deleted tracked momentum. It also treated -a visible terminal cursor after any tap as permission to open the keyboard. A -cursor can remain visible in an input while the user taps somewhere else. +The earlier fork removed tracked momentum, then introduced a pixel conversion, +500ms cap, one-report-per-frame limit and axis lock. Those policies produced an +unusable phone result despite passing their own controls. They are removed, +including horizontal-wheel behavior. Native selection and the opt-in RIGHT +long press remain (see `mouse-long-press.md`). ## Application-declared input bounds -An application can advertise its focused, visible text-input content rectangle: +An application advertises its focused, visible editable content rectangle: ```text ESC ] 777 ; input-region ; x ; y ; width ; height ESC \ ``` -Coordinates and dimensions are decimal terminal cells. The origin is zero-based; -right and bottom edges are exclusive. The rectangle must fit the current terminal -size. `0;0;0;0` clears it. BEL also terminates OSC, as for other terminal controls. -Malformed controls are logged and clear the previous advertisement. Resize, -terminal reset, screen-buffer changes and mouse-tracking changes invalidate it. - -A short finger tap in a tracked terminal requests the keyboard once if its cell -is inside the advertised rectangle. If the tap changes focus, the application -may advertise the newly focused input in its reply; the same hit test can consume -that tap for up to three seconds. Another touch, cancellation, selection, window -loss, detach or input-context change retires the request. An unsolicited region -update, visible cursor, hardware mouse event, long press or scroll does not open -the keyboard. - -The application owns widget identity and geometry. The terminal never guesses -an input box from cursor visibility, cursor shape or a matching row. Applications -that do not advertise input bounds keep the explicit keyboard toggle; ordinary -tracking-off shell taps retain the existing client behavior. Native selection and -the opt-in RIGHT long press are unchanged (see `mouse-long-press.md`). - -The accompanying view controls exercise actual emulator decoding and native -view/gesture events. They test request intent, not physical Android IME display -or remote-widget integration; those require the paired sender and phone run. +The actual control has no spaces. Coordinates and dimensions are decimal terminal +cells, zero-based, with exclusive right/bottom edges, within the terminal size. +`0;0;0;0` clears it. BEL also terminates OSC. Malformed controls are logged and clear +the previous advertisement. Resize, reset, buffer and tracking-mode changes +invalidate the input context and its bounds. + +A short tracked finger tap records its cell. Existing bounds or an application +reply can request the keyboard once when that cell is inside the advertised +rectangle, for at most three seconds from the event. Android touch dispatch +retires the old intent on a new touch or cancel without changing the stock +gesture methods. Selection, window loss, detach, session and input-context +changes also retire it. Unsolicited bounds, visible cursors, hardware mouse taps, +long presses and scrolling do not create a keyboard request. + +The application owns input identity and geometry, independently of cursor +appearance. The paired Textual sender includes normal/command-mode editors and +withdraws read-only targets. A running Toad must be relaunched on a build with +that sender; installing an APK alone cannot provide the missing application +data. Applications without this protocol retain the explicit keyboard toggle. +Tracking-off shell taps retain their existing client behavior. + +The view controls exercise real emulator decoding, touch dispatch and Scroller +row displacement. They are not physical Android IME or phone smoothness evidence. +The paired sender and a real tap/flick on the phone are the acceptance check. diff --git a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java index 3c2d8a9e199..c937b1c2084 100644 --- a/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java +++ b/terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java @@ -40,8 +40,6 @@ public final class TerminalEmulator { public static final int MOUSE_LEFT_BUTTON_MOVED = 32; public static final int MOUSE_WHEELUP_BUTTON = 64; public static final int MOUSE_WHEELDOWN_BUTTON = 65; - public static final int MOUSE_WHEELLEFT_BUTTON = 66; - public static final int MOUSE_WHEELRIGHT_BUTTON = 67; /** Used for invalid data - http://en.wikipedia.org/wiki/Replacement_character#Replacement_character */ public static final int UNICODE_REPLACEMENT_CHAR = 0xFFFD; diff --git a/terminal-view/src/main/java/com/termux/view/TerminalView.java b/terminal-view/src/main/java/com/termux/view/TerminalView.java index 95f99e43a5f..ea245bdf119 100644 --- a/terminal-view/src/main/java/com/termux/view/TerminalView.java +++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java @@ -606,7 +606,7 @@ void sendMouseEventCode(MotionEvent e, int button, boolean pressed) { int[] columnAndRow = getColumnAndRow(e, false); int x = columnAndRow[0] + 1; int y = columnAndRow[1] + 1; - if (pressed && button >= TerminalEmulator.MOUSE_WHEELUP_BUTTON && button <= TerminalEmulator.MOUSE_WHEELRIGHT_BUTTON) { + if (pressed && button >= TerminalEmulator.MOUSE_WHEELUP_BUTTON && button <= TerminalEmulator.MOUSE_WHEELDOWN_BUTTON) { if (mMouseStartDownTime == e.getDownTime()) { x = mMouseScrollStartX; y = mMouseScrollStartY; @@ -649,6 +649,15 @@ public boolean onGenericMotionEvent(MotionEvent event) { return false; } + /** Retire keyboard intent at the input boundary without changing stock gestures. */ + @Override + public boolean dispatchTouchEvent(MotionEvent event) { + int action = event.getActionMasked(); + if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_CANCEL + || action == MotionEvent.ACTION_POINTER_DOWN) mKeyboardTap = mNoKeyboardTap; + return super.dispatchTouchEvent(event); + } + @SuppressLint("ClickableViewAccessibility") @Override @TargetApi(23)