diff --git a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java index 5131bcf16a8..a669b48afa7 100644 --- a/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java +++ b/app/src/test/java/com/termux/view/TerminalViewKeyboardTest.java @@ -6,58 +6,143 @@ import android.view.ViewConfiguration; import org.junit.Test; +import org.robolectric.shadows.ShadowSystemClock; + +import java.time.Duration; 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); + } + + @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(); advance(TerminalView.MOUSE_TAP_KEYBOARD_TIMEOUT_MILLIS + 1); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -65,7 +150,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 +158,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 +166,7 @@ public void cancelInvalidatesEarlierTap() { public void lostWindowFocusInvalidatesEarlierTap() { trackingTap(); view.onWindowFocusChanged(false); - cursorResponse(); + inputResponse(); assertEquals(0, client.keyboardRequests); } @@ -89,17 +174,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 +207,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..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; @@ -9,9 +8,13 @@ import org.junit.Test; import org.robolectric.RuntimeEnvironment; +import org.robolectric.shadows.ShadowSystemClock; + +import java.time.Duration; 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) { @@ -22,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); @@ -49,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"); @@ -65,35 +67,75 @@ public void mouseDragStillSendsMotionRatherThanWheel() { assertEquals("\033[<32;3;4M", output.text()); } - @Test - public void horizontalGestureDoesNotStartVerticalFling() { - 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(); - assertTrue(view.mScroller.isFinished()); - assertEquals("\033[<67;3;4M\033[<67;3;4M", output.text()); + 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 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()); + 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); - view.mGestureRecognizer.mListener.onFling(up, 0, -2000); - up.recycle(); - assertTrue(view.mScroller.isFinished()); - advance(1000); - assertEquals(actualRows, output.text()); + 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 tracked1000VerticalReleaseDoesNotAddWheelRows() { assertTrackedVerticalReleaseStops(1000); } + public void tracked1000ReleaseUsesStockRowMomentum() { assertTrackedVerticalMomentum(1000); } + + @Test + public void tracked1002ReleaseUsesStockRowMomentum() { assertTrackedVerticalMomentum(1002); } @Test - public void tracked1002VerticalReleaseDoesNotAddWheelRows() { assertTrackedVerticalReleaseStops(1002); } + public void reverseFlickUsesTheStockNegativeRowExtent() { + input("\033[?1000h\033[?1006h"); + 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 activeFlingKeepsItsExistingScrollerDestination() { + input("\033[?1000h\033[?1006h"); + 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() { for (int i = 0; i < 60; i++) input("row\r\n"); @@ -102,15 +144,20 @@ 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(); 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 { - view.mScroller.abortAnimation(); + up.recycle(); } } @@ -118,46 +165,15 @@ public void trackingOffScrollbackStillStartsFling() { 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(1); - 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 @@ -233,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 770aff41918..cae41b70231 100644 --- a/app/src/test/java/com/termux/view/TerminalViewTestCase.java +++ b/app/src/test/java/com/termux/view/TerminalViewTestCase.java @@ -95,14 +95,18 @@ 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(); } 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..e7a87cd5b97 --- /dev/null +++ b/docs/touch-input.md @@ -0,0 +1,46 @@ +# Stock scrolling and application-declared keyboard intent + +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 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 advertises its focused, visible editable content rectangle: + +```text +ESC ] 777 ; input-region ; x ; y ; width ; height ESC \ +``` + +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 2a518529c84..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; @@ -220,6 +218,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 +458,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 +596,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 +1871,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 +2908,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 +3509,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..ea245bdf119 100644 --- a/terminal-view/src/main/java/com/termux/view/TerminalView.java +++ b/terminal-view/src/main/java/com/termux/view/TerminalView.java @@ -78,9 +78,10 @@ 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; @@ -137,12 +138,39 @@ 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 = event.getEventTime() + 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(); + } + } + } + public TerminalView(Context context, AttributeSet attributes) { // NO_UCD (unused code) super(context, attributes); mGestureRecognizer = new GestureAndScaleRecognizer(context, new GestureAndScaleRecognizer.Listener() { boolean scrolledWithFinger; - boolean scrolledHorizontally; @Override public boolean onUp(MotionEvent event) { @@ -151,13 +179,13 @@ 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; return false; } @@ -184,25 +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. - scrolledHorizontally = mEmulator.isMouseTrackingActive() && !isSelectingText() - && Math.abs(distanceX) > Math.abs(distanceY); - } scrolledWithFinger = true; - if (scrolledHorizontally && !mEmulator.isMouseTrackingActive()) { - scrolledHorizontally = false; - mScrollRemainder = 0.0f; - } - float cellSize = scrolledHorizontally ? mRenderer.mFontWidth : mRenderer.mFontLineSpacing; - float distance = (scrolledHorizontally ? 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); - } + distanceY += mScrollRemainder; + int deltaRows = (int) (distanceY / mRenderer.mFontLineSpacing); + mScrollRemainder = distanceY - deltaRows * mRenderer.mFontLineSpacing; + doScroll(e, deltaRows); } return true; } @@ -217,26 +231,33 @@ 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; + 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; - mScroller.fling(0, mTopRow, 0, -(int) (velocityY * SCALE), 0, 0, -mEmulator.getScreen().getActiveTranscriptRows(), 0); + 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 (mEmulator == null || mEmulator.isMouseTrackingActive()) { + if (mouseTrackingAtStartOfFling != mEmulator.isMouseTrackingActive()) { mScroller.abortAnimation(); return; } if (mScroller.isFinished()) return; boolean more = mScroller.computeScrollOffset(); int newY = mScroller.getCurrY(); - doScroll(e2, newY - mTopRow); + int diff = mouseTrackingAtStartOfFling ? (newY - mLastY) : (newY - mTopRow); + doScroll(e2, diff); + mLastY = newY; if (more) post(this); } }); @@ -246,10 +267,6 @@ public void run() { @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; - scrolledHorizontally = false; // 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 +333,7 @@ public void setIsTerminalViewKeyLoggingEnabled(boolean value) { public boolean attachSession(TerminalSession session) { if (session == mTermSession) return false; - mMouseTapKeyboardDeadline = 0; + mKeyboardTap = mNoKeyboardTap; mTermSession = session; mEmulator = null; mCombiningAccent = 0; @@ -486,14 +503,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); @@ -594,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; @@ -609,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); @@ -627,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) { @@ -647,16 +649,21 @@ 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) 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) { - mMouseTapKeyboardDeadline = 0; - } if (isSelectingText()) { updateFloatingToolbarVisibility(event); @@ -695,7 +702,9 @@ public boolean onTouchEvent(MotionEvent event) { @Override public void onWindowFocusChanged(boolean hasWindowFocus) { - if (!hasWindowFocus) mMouseTapKeyboardDeadline = 0; + if (!hasWindowFocus) { + mKeyboardTap = mNoKeyboardTap; + } super.onWindowFocusChanged(hasWindowFocus); } @@ -1483,6 +1492,7 @@ private ActionMode getTextSelectionActionMode() { } public void startTextSelectionMode(MotionEvent event) { + mKeyboardTap = mNoKeyboardTap; if (!requestFocus()) { return; } @@ -1517,7 +1527,7 @@ protected void onAttachedToWindow() { @Override protected void onDetachedFromWindow() { - mMouseTapKeyboardDeadline = 0; + mKeyboardTap = mNoKeyboardTap; super.onDetachedFromWindow(); if (mTextSelectionCursorController != null) {