diff --git a/app/build.gradle b/app/build.gradle index 5b8ad6d..7399bbd 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -53,6 +53,12 @@ android { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } + testOptions { + unitTests.includeAndroidResources = true + unitTests.all { + jvmArgs '--add-opens=java.base/jdk.internal.access=ALL-UNNAMED' + } + } externalNativeBuild { cmake { path file('src/main/cpp/CMakeLists.txt') @@ -71,6 +77,9 @@ android { dependencies { + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.robolectric:robolectric:4.17' + implementation( platform 'org.jetbrains.kotlin:kotlin-bom:1.8.0') implementation 'com.google.android.material:material:1.11.0' diff --git a/app/src/main/java/com/tgc/sky/GameActivity.java b/app/src/main/java/com/tgc/sky/GameActivity.java index d975723..4004dd1 100644 --- a/app/src/main/java/com/tgc/sky/GameActivity.java +++ b/app/src/main/java/com/tgc/sky/GameActivity.java @@ -107,10 +107,7 @@ public class GameActivity extends TGCNativeActivity implements View.OnCapturedPo private boolean m_motionEventsDisabled = false; private int m_lastDpadDirection = 23; - // Device motion (accelerometer / gyroscope / rotation), forwarded to native. - // Sky 0.34.0 (401861) calls setMotionEnabled(boolean) via JNI; without it the - // native code aborts at startup with NoSuchMethodError setMotionEnabled(Z)V. - static final float INV_GRAVITY = 0.10197162f; // 1 / SensorManager.GRAVITY_EARTH (m/s^2 -> g) + static final float INV_GRAVITY = 0.10197162f; private SensorManager m_sensorManager = null; private Sensor m_gravitySensor = null; private Sensor m_linearAccelSensor = null; @@ -268,41 +265,37 @@ public void onCreate(Bundle bundle) { } Intent intent = getIntent(); if (intent != null) HandleNewIntent(intent); - getWindow().getDecorView().setOnApplyWindowInsetsListener((view, windowInsets) -> { - try { - int max = Integer.max(windowInsets.getStableInsetTop(), windowInsets.getStableInsetBottom()); - if (Build.VERSION.SDK_INT >= 27) { - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - if (windowInsets.getDisplayCutout() != null) { - max = Integer.max(max, Integer.max( - windowInsets.getDisplayCutout().getSafeInsetLeft(), - windowInsets.getDisplayCutout().getSafeInsetRight())); - } + getWindow().getDecorView().setOnApplyWindowInsetsListener(this::onApplyWindowInsets); + getWindow().getDecorView().requestApplyInsets(); + if (Build.VERSION.SDK_INT >= 30) setupDisplayListener(); + } + + public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { + try { + int max = Integer.max(windowInsets.getStableInsetTop(), windowInsets.getStableInsetBottom()); + if (Build.VERSION.SDK_INT >= 27) { + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + if (windowInsets.getDisplayCutout() != null) { + max = Integer.max(max, Integer.max( + windowInsets.getDisplayCutout().getSafeInsetLeft(), + windowInsets.getDisplayCutout().getSafeInsetRight())); } - } catch (NoSuchMethodError ignored) {} - } - GameActivity.this.mSafeAreaInsets.left = max; - GameActivity.this.mSafeAreaInsets.top = 0; - GameActivity.this.mSafeAreaInsets.right = max; - GameActivity.this.mSafeAreaInsets.bottom = 0; - float t = GameActivity.this.transformWidthToProgram(max); - GameActivity.this.onSafeAreaInsetsChanged(new float[]{t, 0.0f, t, 0.0f}); - return view.onApplyWindowInsets(windowInsets); - } catch (Exception | NoSuchMethodError unused) { - return windowInsets; + } + } catch (NoSuchMethodError ignored) {} } - }); - if (Build.VERSION.SDK_INT >= 30) setupDisplayListener(); + mSafeAreaInsets.left = max; + mSafeAreaInsets.top = 0; + mSafeAreaInsets.right = max; + mSafeAreaInsets.bottom = 0; + float t = transformWidthToProgram(max); + onSafeAreaInsetsChanged(new float[]{t, 0.0f, t, 0.0f}); + } catch (Exception | NoSuchMethodError ignored) {} + + handleKeyboardInsets(view, windowInsets); + return view.onApplyWindowInsets(windowInsets); } - // Parity with stock Sky 0.34.5 (410941): the captured-pointer callback - // exists ONLY for Sony gamepad touchpads (button taps forwarded as key - // 0x6d at inputSource 1; touchpad MOTION is dropped, as in stock). ANY - // other captured device - a hardware mouse above all - releases capture - // immediately, so a mouse can never get stuck in relative mode: captured - // input bypasses the whole view tree, which would leave it click-dead - // and delta-driven for as long as capture held. @Override public boolean onCapturedPointer(View view, MotionEvent event) { if (isGamepadWithTouchpadEvent(event)) { @@ -368,12 +361,6 @@ public void onPause() { super.onPause(); } - // ==== Device motion sensors (Sky 0.34.0 / 401861) ==================== - // Restores GameActivity.setMotionEnabled(boolean) and its sensor subsystem. - // The game's native code calls setMotionEnabled(boolean) via JNI every frame; - // without it startup aborts with: - // NoSuchMethodError: com.tgc.sky.GameActivity.setMotionEnabled(Z)V - // Ported to match TGC's own GameActivity so native behavior is identical. private static final class MotionSample { final float gravityX, gravityY, gravityZ; @@ -399,9 +386,6 @@ private void setupMotionSensors() { if (this.m_sensorManager != null) { this.m_gravitySensor = this.m_sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); this.m_linearAccelSensor = this.m_sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); - // NOTE: TGC registers GAME_ROTATION_VECTOR here but onSensorChanged - // matches ROTATION_VECTOR (below), so in the official app the - // quaternion stays identity. Kept identical to match native behavior. this.m_rotationVectorSensor = this.m_sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR); this.m_gyroscopeSensor = this.m_sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); } @@ -409,8 +393,6 @@ private void setupMotionSensors() { && this.m_rotationVectorSensor != null && this.m_gyroscopeSensor != null; } - // Called by native every frame to enable/disable device-motion streaming and - // to pull the latest sample. Must match the JNI signature setMotionEnabled(Z)V. public void setMotionEnabled(boolean enabled) { onMotionAvailabilityNative(this.m_motionAvailable); if (!this.m_motionAvailable) return; @@ -486,9 +468,6 @@ private void publishMotionSample() { float outGravityX, outGravityY, outAccelX, outAccelY, outRotX, outRotY; float outQuatX, outQuatY, outQuatZ, outQuatW; if (isNaturalLandscape()) { - // Remap device frame -> game's natural-landscape frame: (x, y) -> (y, -x) - // for the vectors, and rotate the orientation quaternion by 45 degrees - // (0.70710677 = cos 45deg = sqrt(1/2)). final float c = 0.70710677f; outGravityX = gy; outGravityY = -gx; outAccelX = ay; outAccelY = -ax; @@ -532,14 +511,14 @@ private int getMotionDeviceOrientation() { case Surface.ROTATION_90: return 2; case Surface.ROTATION_180: return 4; case Surface.ROTATION_270: return 1; - default: return 3; // ROTATION_0 + default: return 3; } } switch (rotation) { case Surface.ROTATION_90: return 3; case Surface.ROTATION_180: return 2; case Surface.ROTATION_270: return 4; - default: return 1; // ROTATION_0 + default: return 1; } } @@ -713,11 +692,6 @@ public boolean onTouchEvent(MotionEvent motionEvent) { motionEvent.getY(actionIndex) + m_gameInputOffset[1]); } - // Hardware-mouse input for the ImGui overlay (no stock counterpart - - // stock has no overlay): feed the pointer exactly the way onTouchEvent - // feeds touches - bridge-view-relative coordinates into the same - // submitPositionEvent path, with ImGUI.wantsMouse() deciding whether the - // game sees the event at all. private void submitImGuiMousePosition(MotionEvent motionEvent) { float x = motionEvent.getX(); float y = motionEvent.getY(); @@ -760,11 +734,6 @@ public boolean dispatchTouchEvent(MotionEvent motionEvent) { PointF point = transformPointToProgram( motionEvent.getX() + m_gameInputOffset[0], motionEvent.getY() + m_gameInputOffset[1]); - // Mouse-to-ImGui: primary-button gestures mirror the touch path - // - position plus button 0 - and wantsMouse() then arbitrates - // ownership just like onTouchEvent does for touches. The - // backend's MouseDownOwned logic keeps a drag that began on the - // game out of ImGui and vice versa. int actionMasked = motionEvent.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN || actionMasked == MotionEvent.ACTION_MOVE @@ -774,10 +743,6 @@ public boolean dispatchTouchEvent(MotionEvent motionEvent) { if (actionMasked == MotionEvent.ACTION_UP) ImGUI.submitButtonEvent(0, false); } if (ImGUI.wantsMouse()) { - // ImGui owns this gesture: the game sees neither the camera - // delta nor the cursor move. Still advance the delta anchor - // so the first game-owned event afterwards computes no - // spurious camera jump. m_lastMouseLocation = point; return true; } @@ -842,7 +807,10 @@ protected void toggleKeyboard(boolean z, int i) { lbm.sendBroadcast(intent); } + @Override public void onGlobalLayout() { + super.onGlobalLayout(); + if (Build.VERSION.SDK_INT >= 30 || this.m_relativeLayout == null) return; Rect rect = new Rect(); this.m_relativeLayout.getWindowVisibleDisplayFrame(rect); int height = this.m_relativeLayout.getHeight() - rect.height(); @@ -1070,12 +1038,6 @@ public boolean onKeyUp(int keyCode, KeyEvent keyEvent) { public boolean onGenericMotionEvent(MotionEvent motionEvent) { if (this.m_motionEventsDisabled) return true; if (isHardwareMouseEvent(motionEvent)) { - // Hardware-mouse dispatch, parity with stock Sky 0.34.5 - // (410941): stock dispatches on the action and forwards mouse - // BUTTONS to the game (onButtonPress at inputSource 3) and one - // synthesized key tap per wheel notch, alongside hover and the - // scroll delta. Dropping the button cases means no - // hardware-mouse click ever reaches the game. int vendorId = getDeviceVendorId(motionEvent); int productId = getDeviceProductId(motionEvent); if (isGamepadWithTouchpadEvent(motionEvent)) { @@ -1085,12 +1047,6 @@ public boolean onGenericMotionEvent(MotionEvent motionEvent) { } return true; } - // Mouse-to-ImGui: keep the overlay's pointer position fresh - it - // powers ImGui hover and the wantsMouse() ownership checks - // below. Button 0 itself is submitted from dispatchTouchEvent's - // DOWN/UP, which Android delivers alongside - // ACTION_BUTTON_PRESS/RELEASE for the primary button, so it is - // not repeated here. submitImGuiMousePosition(motionEvent); switch (motionEvent.getAction()) { case MotionEvent.ACTION_HOVER_MOVE: @@ -1105,13 +1061,9 @@ public boolean onGenericMotionEvent(MotionEvent motionEvent) { float scrollX = motionEvent.getAxisValue(MotionEvent.AXIS_HSCROLL); float scrollY = motionEvent.getAxisValue(MotionEvent.AXIS_VSCROLL); if (ImGUI.wantsMouse()) { - // Over the overlay the wheel scrolls ImGui and never - // reaches the game - no camera zoom behind the menu. ImGUI.submitScrollEvent(scrollX, scrollY); break; } - // One synthesized key tap per notch, exactly as stock: - // wheel down -> key 11, wheel up -> key 10, inputSource 3. int key = scrollY < 0.0f ? 11 : (scrollY > 0.0f ? 10 : 0); if (key != 0) { onButtonPress(key, 3, true, vendorId, productId); @@ -1121,10 +1073,6 @@ public boolean onGenericMotionEvent(MotionEvent motionEvent) { break; } case MotionEvent.ACTION_BUTTON_PRESS: - // wantsMouse() keeps clicks over the overlay away from - // the game; a press that began on the game keeps its - // release too (MouseDownOwned makes wantsMouse() stay - // false for that whole drag, even ending over ImGui). if (!ImGUI.wantsMouse() && !isEventInTextField(motionEvent)) { onButtonPress(motionEvent.getActionButton(), 3, true, vendorId, productId); } diff --git a/app/src/main/java/com/tgc/sky/ui/TextField.java b/app/src/main/java/com/tgc/sky/ui/TextField.java index 5fdd8bc..c058871 100644 --- a/app/src/main/java/com/tgc/sky/ui/TextField.java +++ b/app/src/main/java/com/tgc/sky/ui/TextField.java @@ -45,6 +45,7 @@ public class TextField { private int m_selectPosProgram = -1; private boolean m_submitted = false; + private boolean m_hiding = false; private State m_state = State.kTextFieldState_Hidden; private boolean m_init = false; @@ -149,17 +150,11 @@ public void onTextChanged(CharSequence s, int start, int before, int count) { this.m_activity.getBridgeView().addView(this.m_textField); this.m_activity.addOnKeyboardListener((visible, kbHeight) -> { - if (visible) { - TextField.this.resizeTextField(false, kbHeight); - return; + TextField.this.resizeTextField(false, kbHeight); + if (!visible && TextField.this.isVirtualKeyboard() + && TextField.this.getState() == State.kTextFieldState_Showing) { + TextField.this.hideTextField(); } - if (!TextField.this.m_submitted) { - if (TextField.this.m_isDraftEnabled) { - TextField.sChatDraft = TextField.this.m_textField.getText().toString(); - } - TextField.this.m_activity.onKeyboardCompleteNative("", TextField.this.m_isCallbackTextfield, true); - } - TextField.this.hideTextField(); }); this.m_init = true; @@ -222,10 +217,17 @@ public void hideTextFieldAsync() { } public void hideTextField() { - if (!this.m_submitted) { - this.m_activity.onKeyboardCompleteNative("", this.m_isCallbackTextfield, true); + if (getState() == State.kTextFieldState_Hidden || this.m_hiding) { + return; } - if (getState() != State.kTextFieldState_Hidden) { + this.m_hiding = true; + try { + if (!this.m_submitted) { + if (this.m_isDraftEnabled) { + sChatDraft = this.m_textField.getText().toString(); + } + this.m_activity.onKeyboardCompleteNative("", this.m_isCallbackTextfield, true); + } ((InputMethodManager) this.m_activity.getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(this.m_textField.getWindowToken(), 0); GameActivity.hideNavigationFullScreen(this.m_activity.getBridgeView()); @@ -238,9 +240,11 @@ public void hideTextField() { this.m_textField.setVisibility(View.GONE); this.m_activity.getBridgeView().requestFocus(); this.m_activity.getBridgeView().requestFocusFromTouch(); + clearId(); setState(State.kTextFieldState_Hidden); + } finally { + this.m_hiding = false; } - clearId(); } public void resizeTextField(boolean top, int keyboardHeight) { diff --git a/app/src/main/java/git/artdeell/skymodloader/ImGUITextInput.java b/app/src/main/java/git/artdeell/skymodloader/ImGUITextInput.java index 9eafc59..15a46ae 100644 --- a/app/src/main/java/git/artdeell/skymodloader/ImGUITextInput.java +++ b/app/src/main/java/git/artdeell/skymodloader/ImGUITextInput.java @@ -48,8 +48,8 @@ public ImGUITextInput(@NonNull Context context, @Nullable AttributeSet attrs, in } private final InputMethodManager imm; - /** Last IME visibility seen by the inset listener; see installImeVisibilityListener(). */ private boolean imeWasVisible = false; + private long keyboardStateGeneration = 0; /** * When we change from app to app, the keyboard gets disabled. @@ -266,6 +266,7 @@ private interface InputConnectionAction { /** Regain ability to exist, take focus and have some text being input */ public void enable(){ + keyboardStateGeneration++; setEnabled(true); setFocusable(true); setVisibility(VISIBLE); @@ -275,23 +276,11 @@ public void enable(){ /** Lose ability to exist, take focus and have some text being input */ public void disable(){ + keyboardStateGeneration++; clear(); setVisibility(GONE); clearFocus(); setEnabled(false); - // End the ImGui editing session in lockstep. Hiding this view alone - // leaves the InputText active and io.WantTextInput stuck true, which - // desynchronises GameActivity's imguiKeybaordShowing latch: it believes - // the keyboard is already up and never re-shows it, so tapping a text - // field afterwards only moves the caret. - // Placed here rather than at the individual dismissal sites so the view - // state and the ImGui session cannot diverge - every route that hides - // the IME (BACK key, window focus change, IME "done" on a multiline - // field, GameActivity lowering the keyboard) passes through here. - // Safe to call unconditionally: the native side only acts when the - // ImGui item being edited is the one holding ActiveId, so this is a - // no-op when ImGui has already deactivated the field or is busy with - // some other widget. ImGUI.clearTextFocus(); } @@ -305,11 +294,6 @@ private void sendEnter(){ /** This function deals with anything that has to be executed when the constructor is called */ private void setup(){ setRawInputType(INPUT_TYPE); - // NO_FULLSCREEN matters here beyond cosmetics: the host activity is - // landscape-only, and a fullscreen (extract-mode) IME stops the window - // from dispatching inset changes at all, which would leave the listener - // below permanently silent. NO_EXTRACT_UI alone does not prevent that - - // it only suppresses the extracted-text editor. setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING); @@ -324,30 +308,21 @@ private void setup(){ disable(); } - /** - * The only reliable way to learn that the IME went away. - * - * An IME can close itself without ever dispatching a key event to us - the - * "hide keyboard" control in Gboard and friends does exactly that, and under - * gesture navigation there is no BACK key in the picture at all. Google - * closed issuetracker.google.com/issues/242222756 as intended behaviour for - * this very reason ("an IME can close itself without going through all of - * that path") and points at the ime() inset as the supported signal. - * - * Without this, the view stays enabled while the IME is gone, the ImGui - * InputText stays active, io.WantTextInput stays true, and GameActivity's - * imguiKeybaordShowing latch never re-raises the keyboard - so tapping a text - * field afterwards only moves the caret. - */ private void installImeVisibilityListener() { ViewCompat.setOnApplyWindowInsetsListener(this, (v, insets) -> { final boolean imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime()); - if (imeWasVisible && !imeVisible) { - // Posted, not inline: disable() flips visibility and clears focus, - // neither of which may happen during an inset dispatch. - post(this::disable); + if (imeWasVisible != imeVisible) { + imeWasVisible = imeVisible; + final long generation = ++keyboardStateGeneration; + if (!imeVisible && isEnabled()) { + post(() -> { + if (generation == keyboardStateGeneration + && !imeWasVisible && isEnabled()) { + disable(); + } + }); + } } - imeWasVisible = imeVisible; return insets; }); } diff --git a/app/src/test/java/com/tgc/sky/GameActivityKeyboardTest.java b/app/src/test/java/com/tgc/sky/GameActivityKeyboardTest.java new file mode 100644 index 0000000..94849ca --- /dev/null +++ b/app/src/test/java/com/tgc/sky/GameActivityKeyboardTest.java @@ -0,0 +1,244 @@ +package com.tgc.sky; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.robolectric.Shadows.shadowOf; + +import android.app.Application; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.graphics.Insets; +import android.graphics.Rect; +import android.os.Looper; +import android.view.View; +import android.view.WindowInsets; +import android.widget.FrameLayout; +import android.widget.RelativeLayout; + +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import org.robolectric.util.ReflectionHelpers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +@Config(application = Application.class, manifest = Config.NONE, sdk = {30, 34}) +public class GameActivityKeyboardTest { + private TestActivity activity; + private FrameView bridge; + private final List changes = new ArrayList<>(); + + public static class TestActivity extends GameActivity { + int safeAreaFailure; + + @Override + public void onSafeAreaInsetsChanged(float[] insets) { + if (safeAreaFailure == 1) throw new IllegalStateException("test safe-area failure"); + if (safeAreaFailure == 2) throw new NoSuchMethodError("test safe-area failure"); + } + } + + private static class FrameView extends RelativeLayout { + final Rect visibleFrame = new Rect(); + + FrameView(Context context) { super(context); } + + @Override + public void getWindowVisibleDisplayFrame(Rect out) { out.set(visibleFrame); } + } + + @Before + public void setUp() { + + activity = Robolectric.buildActivity(TestActivity.class).get(); + bridge = new FrameView(activity); + activity.setContentView(bridge); + ReflectionHelpers.setField(activity, "m_relativeLayout", bridge); + + ReflectionHelpers.setField(activity, "m_destroyed", true); + activity.addOnKeyboardListener((visible, height) -> changes.add(visible + ":" + height)); + } + + private void frame(int width, int height, int left, int top) { + activity.getWindow().getDecorView().layout(0, 0, width, height); + bridge.layout(0, 0, width, height); + bridge.visibleFrame.set(left, top, width, height); + } + + private WindowInsets ime(boolean visible, int height) { + return new WindowInsets.Builder() + .setInsets(WindowInsets.Type.systemBars(), Insets.of(0, 120, 0, 0)) + .setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, height)) + .setVisible(WindowInsets.Type.ime(), visible) + .build(); + } + + private void applyIme(boolean visible, int height) { + activity.onApplyWindowInsets(bridge, ime(visible, height)); + } + + private boolean showing() { + return ReflectionHelpers.getField(activity, "m_isKeyboardShowing"); + } + + private int keyboardHeight() { + return ReflectionHelpers.getField(activity, "m_keyboardHeight"); + } + + @Test + public void capturedRotationSequenceNeverAnnouncesKeyboard() { + + for (int repeat = 0; repeat < 3; repeat++) { + frame(2376, 1080, 120, 0); + applyIme(false, 0); + activity.onGlobalLayout(); + frame(1080, 2376, 0, 120); + activity.onGlobalLayout(); + applyIme(false, 0); + activity.onGlobalLayout(); + assertFalse(showing()); + assertEquals(0, keyboardHeight()); + } + assertTrue(changes.isEmpty()); + } + + @Test + public void realKeyboardShowResizeAndHideReachListenersAndBroadcastsOnce() { + List broadcasts = new ArrayList<>(); + LocalBroadcastManager manager = LocalBroadcastManager.getInstance(activity); + BroadcastReceiver receiver = new BroadcastReceiver() { + @Override public void onReceive(Context context, Intent intent) { + broadcasts.add(intent.getAction() + ":" + intent.getIntExtra("KeyboardHeight", 0)); + } + }; + IntentFilter filter = new IntentFilter("KeyboardWillShow"); + filter.addAction("KeyboardWillHide"); + manager.registerReceiver(receiver, filter); + try { + applyIme(true, 720); + applyIme(true, 720); + assertTrue(showing()); + assertEquals(720, keyboardHeight()); + applyIme(true, 480); + assertEquals(480, keyboardHeight()); + applyIme(false, 0); + applyIme(false, 0); + assertFalse(showing()); + assertEquals(0, keyboardHeight()); + shadowOf(Looper.getMainLooper()).idle(); + assertEquals(Arrays.asList("true:720", "true:480", "false:0"), changes); + assertEquals(Arrays.asList("KeyboardWillShow:720", "KeyboardWillShow:480", + "KeyboardWillHide:0"), broadcasts); + } finally { + manager.unregisterReceiver(receiver); + } + } + + @Test + public void floatingKeyboardVisibilityDoesNotDependOnHeightOrEditFocus() { + frame(1080, 2376, 0, 120); + applyIme(true, 0); + activity.notifyEditTextFocus(false); + activity.onGlobalLayout(); + assertTrue(showing()); + assertEquals(Arrays.asList("true:0"), changes); + applyIme(false, 0); + assertFalse(showing()); + } + + @Test + public void rotationLayoutCannotHideAnActuallyOpenKeyboard() { + applyIme(true, 720); + frame(2376, 1080, 120, 0); + activity.onGlobalLayout(); + frame(1080, 2376, 0, 120); + activity.onGlobalLayout(); + assertTrue(showing()); + assertEquals(720, keyboardHeight()); + assertEquals(Arrays.asList("true:720"), changes); + } + + @Test + public void insetsAreForwardedToChildrenEvenWhenSafeAreaCallbackFails() { + FrameLayout parent = new FrameLayout(activity); + View child = new View(activity); + parent.addView(child); + parent.setOnApplyWindowInsetsListener(activity::onApplyWindowInsets); + List received = new ArrayList<>(); + child.setOnApplyWindowInsetsListener((view, insets) -> { + received.add(insets); + return insets; + }); + for (int failure = 0; failure <= 2; failure++) { + activity.safeAreaFailure = failure; + WindowInsets shown = ime(true, 720); + parent.dispatchApplyWindowInsets(shown); + assertTrue(showing()); + assertEquals(720, keyboardHeight()); + assertEquals(shown, received.get(received.size() - 1)); + parent.dispatchApplyWindowInsets(ime(false, 0)); + assertFalse(showing()); + } + assertEquals(6, received.size()); + assertEquals(6, changes.size()); + } + + @Test + public void callbackPreservesTheViewsInsetsReturnValue() { + View consumer = new View(activity) { + @Override public WindowInsets onApplyWindowInsets(WindowInsets insets) { + return WindowInsets.CONSUMED; + } + }; + assertSame(WindowInsets.CONSUMED, activity.onApplyWindowInsets(consumer, ime(false, 0))); + } + + @Test + public void baseContentRectCacheTracksRotation() { + frame(2376, 1080, 120, 0); + activity.onGlobalLayout(); + assertEquals(2376, activity.m_lastContentWidth); + assertEquals(1080, activity.m_lastContentHeight); + frame(1080, 2376, 0, 120); + activity.onGlobalLayout(); + assertEquals(1080, activity.m_lastContentWidth); + assertEquals(2376, activity.m_lastContentHeight); + } + + @Test + @Config(sdk = {26, 29}) + public void legacyKeyboardLayoutNotificationsArePreserved() { + frame(1080, 2376, 0, 720); + activity.onGlobalLayout(); + activity.onGlobalLayout(); + assertTrue(showing()); + frame(1080, 2376, 0, 0); + activity.onGlobalLayout(); + activity.onGlobalLayout(); + assertFalse(showing()); + assertEquals(Arrays.asList("true:720", "false:0"), changes); + assertEquals(2376, activity.m_lastContentHeight); + } + + @Test + @Config(sdk = {26, 29, 30, 34}) + public void layoutBeforeBridgeIsReadyStillUpdatesBaseContent() { + frame(1080, 2376, 0, 0); + ReflectionHelpers.setField(activity, "m_relativeLayout", null); + activity.onGlobalLayout(); + assertEquals(2376, activity.m_lastContentHeight); + assertTrue(changes.isEmpty()); + } +} diff --git a/app/src/test/java/com/tgc/sky/KeyboardLifecycleTest.java b/app/src/test/java/com/tgc/sky/KeyboardLifecycleTest.java new file mode 100644 index 0000000..2b0be42 --- /dev/null +++ b/app/src/test/java/com/tgc/sky/KeyboardLifecycleTest.java @@ -0,0 +1,405 @@ +package com.tgc.sky; + +import static org.junit.Assert.*; +import static org.robolectric.Shadows.shadowOf; + +import android.content.Context; +import android.content.res.Configuration; +import android.graphics.Insets; +import android.graphics.Rect; +import android.os.Looper; +import android.view.View; +import android.view.WindowInsets; +import android.view.inputmethod.EditorInfo; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.RelativeLayout; + +import com.tgc.sky.ui.TextField; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.util.ReflectionHelpers; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import git.artdeell.skymodloader.ImGUI; +import git.artdeell.skymodloader.ImGUITextInput; +import git.artdeell.skymodloader.MainActivity; +import git.artdeell.skymodloader.R; +import git.artdeell.skymodloader.SMLApplication; + +@RunWith(RobolectricTestRunner.class) +@Config(application = KeyboardLifecycleTest.AuditApplication.class, + manifest = Config.NONE, sdk = {30, 34, 36}, + shadows = {KeyboardLifecycleTest.ImGuiShadow.class, + KeyboardLifecycleTest.MainActivityShadow.class}) +public class KeyboardLifecycleTest { + private AuditActivity activity; + private AuditBridge bridge; + private FrameLayout parent; + + public static class AuditApplication extends SMLApplication { + @Override public void onCreate() { + ReflectionHelpers.setStaticField(SMLApplication.class, "smlApplication", this); + } + } + + public static class AuditActivity extends GameActivity { + final List completions = new ArrayList<>(); + Runnable onCompletion; + @Override public void onSafeAreaInsetsChanged(float[] insets) {} + @Override public void onKeyboardCompleteNative(String text, boolean callback, boolean cancel) { + completions.add(text + ":" + callback + ":" + cancel); + if (onCompletion != null) onCompletion.run(); + } + } + + @Implements(ImGUI.class) + public static class ImGuiShadow { + static int focusClears; + @Implementation protected static void __staticInitializer__() {} + @Implementation protected static void clearTextFocus() { focusClears++; } + } + + @Implements(MainActivity.class) + public static class MainActivityShadow { + static final List submissions = new ArrayList<>(); + @Implementation protected static void onKeyboardCompleteNative(String text) { + submissions.add(text); + } + } + + private static class AuditBridge extends RelativeLayout { + final Rect frame = new Rect(); + AuditBridge(Context context) { super(context); } + @Override public void getWindowVisibleDisplayFrame(Rect out) { out.set(frame); } + } + + private static class QueuedOverlay extends ImGUITextInput { + final List posted = new ArrayList<>(); + QueuedOverlay(Context context) { super(context); } + @Override public boolean post(Runnable action) { + if (posted == null) return super.post(action); + posted.add(action); + return true; + } + } + + @Before public void setUp() { + ImGuiShadow.focusClears = 0; + MainActivityShadow.submissions.clear(); + ReflectionHelpers.setStaticField(TextField.class, "sChatDraft", ""); + activity = Robolectric.buildActivity(AuditActivity.class).get(); + activity.setTheme(R.style.SkyFullscreenTheme); + parent = new FrameLayout(activity); + bridge = new AuditBridge(activity); + parent.addView(bridge); + activity.setContentView(parent); + ReflectionHelpers.setField(activity, "m_relativeLayout", bridge); + ReflectionHelpers.setField(activity, "m_destroyed", true); + SMLApplication.skyRes = activity.getResources(); + SMLApplication.skyPName = activity.getPackageName(); + geometry(1080, 2376, 0, 120, 0, 0); + } + + private void geometry(int width, int height, int left, int top, int right, int bottom) { + activity.getWindow().getDecorView().layout(0, 0, width, height); + bridge.layout(0, 0, width, height); + bridge.frame.set(left, top, width - right, height - bottom); + } + + private SystemUI_android systemUi() { + SystemUI_android ui = new SystemUI_android(activity); + activity.m_systemUI = ui; + return ui; + } + + private TextField textField(SystemUI_android ui) { + return ReflectionHelpers.getField(ui, "m_textField"); + } + + private WindowInsets ime(boolean shown, int height) { + return new WindowInsets.Builder() + .setInsets(WindowInsets.Type.ime(), Insets.of(0, 0, 0, height)) + .setVisible(WindowInsets.Type.ime(), shown).build(); + } + + private void apply(boolean shown, int height) { + activity.onApplyWindowInsets(parent, ime(shown, height)); + } + + @Test public void systemUiStaysClearAcrossPhoneTabletAndWindowGeometryMatrix() { + SystemUI_android ui = systemUi(); + int[][] sizes = {{1080,2376},{2376,1080},{2560,1600},{1600,2560}, + {2048,1536},{1536,2048},{900,700}}; + int[][] gaps = {{0,0,0,0},{0,120,0,0},{0,0,0,160}, + {0,120,0,160},{80,0,0,0},{0,0,80,0}}; + for (int[] size : sizes) for (int[] gap : gaps) { + geometry(size[0], size[1], gap[0], gap[1], gap[2], gap[3]); + activity.onGlobalLayout(); + apply(false, 0); + activity.onGlobalLayout(); + assertFalse(ui.IsKeyboardShowing()); + assertEquals(0f, ui.GetKeyboardHeight(), 0f); + } + assertTrue(activity.completions.isEmpty()); + } + + @Test public void chatShowResizeAndHideCompleteOnce() { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + int id = field.showTextFieldWithPromptAsync("Chat", "draft", 100, 100, false); + assertNotEquals(-1, id); + apply(true, 720); + assertTrue(ui.IsTextFieldShowing()); + assertTrue(ui.IsKeyboardShowing()); + assertEquals(720f, ui.GetKeyboardHeight(), 0f); + EditText edit = ReflectionHelpers.getField(field, "m_textField"); + int firstMargin = ((RelativeLayout.LayoutParams) edit.getLayoutParams()).bottomMargin; + apply(true, 480); + assertEquals(firstMargin - 240, + ((RelativeLayout.LayoutParams) edit.getLayoutParams()).bottomMargin); + apply(false, 0); + assertFalse(ui.IsKeyboardShowing()); + assertEquals(0f, ui.GetKeyboardHeight(), 0f); + assertFalse(ui.IsTextFieldShowing()); + assertFalse(ui.IsTextFieldIdActive(id)); + assertEquals(View.GONE, edit.getVisibility()); + assertEquals(1, activity.completions.size()); + assertEquals(":false:true", activity.completions.get(0)); + apply(false, 0); + ui.HideTextField(); + field.hideTextField(); + assertEquals(1, activity.completions.size()); + } + + @Test public void foreignImeHideDoesNotCancelInactiveChat() { + SystemUI_android ui = systemUi(); + assertFalse(ui.IsTextFieldShowing()); + apply(true, 480); + apply(false, 0); + textField(ui).hideTextField(); + assertTrue(activity.completions.isEmpty()); + } + + @Test public void hardwareChatSurvivesSoftImeHideButExplicitHideStillWorks() { + Configuration config = new Configuration(activity.getResources().getConfiguration()); + config.keyboard = Configuration.KEYBOARD_QWERTY; + activity.getResources().updateConfiguration(config, activity.getResources().getDisplayMetrics()); + SystemUI_android ui = systemUi(); + textField(ui).showTextFieldWithPromptAsync("Chat", "draft", 100, 100, false); + EditText edit = ReflectionHelpers.getField(textField(ui), "m_textField"); + int closedMargin = ((RelativeLayout.LayoutParams) edit.getLayoutParams()).bottomMargin; + apply(true, 480); + apply(false, 0); + assertTrue(ui.IsTextFieldShowing()); + assertFalse(ui.IsKeyboardShowing()); + assertEquals(0f, ui.GetKeyboardHeight(), 0f); + assertEquals(closedMargin, ((RelativeLayout.LayoutParams) edit.getLayoutParams()).bottomMargin); + assertTrue(activity.completions.isEmpty()); + ui.HideTextField(); + assertFalse(ui.IsTextFieldShowing()); + assertEquals(1, activity.completions.size()); + } + + @Test public void cancelledDraftSurvivesReopenAndForeignImeCycle() { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + field.showTextFieldWithPromptAsync("Chat", "", 100, 100, false); + EditText edit = ReflectionHelpers.getField(field, "m_textField"); + edit.setText("unsent draft"); + apply(true, 480); + apply(false, 0); + apply(true, 480); + apply(false, 0); + assertEquals(1, activity.completions.size()); + assertNotEquals(-1, field.showTextFieldWithPromptAsync("Chat", "", 100, 100, false)); + assertEquals("unsent draft", edit.getText().toString()); + ui.HideTextField(); + assertEquals(2, activity.completions.size()); + } + + @Test public void submittedChatDoesNotCancelOrResurrectDraftOnHide() { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + field.showTextFieldWithPromptAsync("Chat", "send me", 100, 100, false); + EditText edit = ReflectionHelpers.getField(field, "m_textField"); + apply(true, 480); + edit.onEditorAction(EditorInfo.IME_ACTION_SEND); + assertEquals("send me:false:false", activity.completions.get(0)); + assertEquals(1, MainActivityShadow.submissions.size()); + assertEquals("send me", MainActivityShadow.submissions.get(0)); + apply(false, 0); + ui.HideTextField(); + assertEquals(1, activity.completions.size()); + field.showTextFieldWithPromptAsync("Chat", "", 100, 100, false); + assertEquals("", edit.getText().toString()); + } + + @Test public void callbackFieldKeepsItsCompletionFlagsAndCancelsOnlyOnce() { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + field.showTextFieldWithPromptAsync("Callback", "", 100, 100, true); + apply(true, 480); + apply(false, 0); + ui.HideTextField(); + assertEquals(1, activity.completions.size()); + assertEquals(":true:true", activity.completions.get(0)); + field.showTextFieldWithPromptAsync("Callback", "answer", 100, 100, true); + EditText edit = ReflectionHelpers.getField(field, "m_textField"); + edit.onEditorAction(EditorInfo.IME_ACTION_SEND); + ui.HideTextField(); + assertEquals(2, activity.completions.size()); + assertEquals("answer:true:true", activity.completions.get(1)); + } + + @Test @Config(sdk = {26, 29, 30, 34, 36}) + public void reentrantHideCannotDuplicateCancellationOrOpenDuringCleanup() { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + int id = field.showTextFieldWithPromptAsync("Chat", "draft", 100, 100, false); + activity.onCompletion = () -> { + ui.HideTextField(); + field.hideTextField(); + assertEquals(-1, field.showTextFieldWithPromptAsync("Chat", "new", 100, 100, false)); + }; + field.hideTextField(); + activity.onCompletion = null; + assertEquals(1, activity.completions.size()); + assertFalse(ui.IsTextFieldShowing()); + assertFalse(ui.IsTextFieldIdActive(id)); + int nextId = field.showTextFieldWithPromptAsync("Chat", "new", 100, 100, false); + assertNotEquals(-1, nextId); + assertNotEquals(id, nextId); + assertTrue(ui.IsTextFieldIdActive(nextId)); + } + + @Test public void unrelatedImeHideDoesNotCancelQueuedShow() throws InterruptedException { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + AtomicInteger id = new AtomicInteger(-1); + Thread nativeCaller = new Thread(() -> id.set( + field.showTextFieldWithPromptAsync("Chat", "queued", 100, 100, false))); + nativeCaller.start(); + nativeCaller.join(); + assertEquals(TextField.State.kTextFieldState_RequestShow, field.getState()); + apply(true, 480); + apply(false, 0); + assertTrue(activity.completions.isEmpty()); + shadowOf(Looper.getMainLooper()).idle(); + assertTrue(ui.IsTextFieldShowing()); + assertTrue(ui.IsTextFieldIdActive(id.get())); + ui.HideTextField(); + assertEquals(1, activity.completions.size()); + } + + @Test @Config(sdk = {26, 29, 30, 34, 36}) + public void queuedShowThenExplicitHideCompletesOnce() throws InterruptedException { + SystemUI_android ui = systemUi(); + TextField field = textField(ui); + AtomicInteger id = new AtomicInteger(-1); + Thread nativeCaller = new Thread(() -> { + id.set(field.showTextFieldWithPromptAsync("Chat", "queued", 100, 100, false)); + ui.HideTextField(); + }); + nativeCaller.start(); + nativeCaller.join(); + assertEquals(TextField.State.kTextFieldState_RequestHide, field.getState()); + shadowOf(Looper.getMainLooper()).idle(); + assertEquals(TextField.State.kTextFieldState_Hidden, field.getState()); + assertEquals(1, activity.completions.size()); + assertFalse(ui.IsTextFieldIdActive(id.get())); + assertNotEquals(-1, field.showTextFieldWithPromptAsync("Chat", "new", 100, 100, false)); + } + + @Test public void overlayHideCallbackDisablesEditingWhenDrained() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + assertTrue(overlay.isEnabled()); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertFalse(overlay.isEnabled()); + assertEquals(View.GONE, overlay.getVisibility()); + assertEquals(clears + 1, ImGuiShadow.focusClears); + } + + @Test public void oldOverlayHideCannotCloseANewerEditingSession() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + overlay.setKeyboardState(true); + parent.dispatchApplyWindowInsets(ime(true, 480)); + assertTrue(ReflectionHelpers.getField(overlay, "imeWasVisible")); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertTrue(overlay.isEnabled()); + assertEquals(View.VISIBLE, overlay.getVisibility()); + assertEquals(clears, ImGuiShadow.focusClears); + } + + @Test public void oldOverlayHideCannotCloseNewSessionBeforeImeShows() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + overlay.setKeyboardState(true); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertTrue(overlay.isEnabled()); + assertEquals(View.VISIBLE, overlay.getVisibility()); + assertEquals(clears, ImGuiShadow.focusClears); + } + + @Test public void reshownImeInvalidatesHideWithoutExplicitEnable() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + parent.dispatchApplyWindowInsets(ime(true, 480)); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertTrue(overlay.isEnabled()); + assertEquals(clears, ImGuiShadow.focusClears); + } + + @Test public void onlyLatestHideCanDisableOverlay() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + parent.dispatchApplyWindowInsets(ime(true, 480)); + parent.dispatchApplyWindowInsets(ime(false, 0)); + assertEquals(2, overlay.posted.size()); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertTrue(overlay.isEnabled()); + assertEquals(clears, ImGuiShadow.focusClears); + overlay.posted.remove(0).run(); + assertFalse(overlay.isEnabled()); + assertEquals(clears + 1, ImGuiShadow.focusClears); + } + + @Test public void explicitDisableInvalidatesPendingNativeFocusClear() { + QueuedOverlay overlay = queuedOverlayAfterHide(); + overlay.disable(); + int clears = ImGuiShadow.focusClears; + overlay.posted.remove(0).run(); + assertFalse(overlay.isEnabled()); + assertEquals(clears, ImGuiShadow.focusClears); + + parent.dispatchApplyWindowInsets(ime(true, 480)); + parent.dispatchApplyWindowInsets(ime(false, 0)); + assertTrue(overlay.posted.isEmpty()); + } + + private QueuedOverlay queuedOverlayAfterHide() { + SystemUI_android ui = systemUi(); + QueuedOverlay overlay = new QueuedOverlay(activity); + parent.addView(overlay, 0); + overlay.setKeyboardState(true); + parent.setOnApplyWindowInsetsListener(activity::onApplyWindowInsets); + parent.dispatchApplyWindowInsets(ime(true, 480)); + assertTrue(ui.IsKeyboardShowing()); + parent.dispatchApplyWindowInsets(ime(false, 0)); + assertFalse(ui.IsKeyboardShowing()); + assertEquals(1, overlay.posted.size()); + return overlay; + } +} diff --git a/gradle.properties b/gradle.properties index 259ef66..0a12622 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,4 +19,5 @@ android.useAndroidX=true # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library android.nonTransitiveRClass=true -android.enableJetifier=true \ No newline at end of file +android.enableJetifier=true +android.jetifier.ignorelist=bcprov-jdk18on-.*