diff --git a/README.md b/README.md new file mode 100644 index 0000000..76f2ee1 --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# Unfloat + +libxposed (API 101+) module that moves the rotation suggestion button back into the 3-button navigation bar, as it was up to Android 14, instead of the floating button Android 15 introduced. + +| | Navigation bar | +|---|---| +| **Stock** | ![Stock floating rotation button](screenshots/stock.jpg) | +| **Unfloat** | ![Rotation button inside the nav bar](screenshots/unfloat.jpg) | + +With auto-rotate off, turning the phone shows a "rotate screen" suggestion button. Since Android 15 that button is always a floating circle hovering over the app, even with 3-button navigation, where it covers app content right above the nav bar. With Unfloat it sits in the nav bar's right-hand contextual slot again (where the IME switcher and accessibility button live), sized, tinted and rippled like the other nav buttons. Gesture navigation keeps the stock floating button. + +## What it changes + +AOSP commit *"Replace Contextual Rotation Button with Floating Action Button"* (bug 324070001), shipped in Android 15, deleted `RotationContextButton`. Since then the rotation controller is always given a `FloatingRotationButton`, which adds its own little window via `WindowManager`. + +On this device (crDroid, Android 17) the 3-button nav bar isn't drawn by SystemUI at all. SystemUI's `NavigationBarControllerImpl.supportsTaskbar()` returns `true`, so the bar is the Launcher3 taskbar (`NavbarButtonsViewController`), and the rotation button is Launcher3's copy of the shared `FloatingRotationButton`. Reconstructed from the decompiled `Launcher3QuickStep.apk`, it looks roughly like this: + +```java +// NavbarButtonsViewController.setupController() +mFloatingRotationButton = new FloatingRotationButton(...); +mControllers.rotationButtonController.setRotationButton(mFloatingRotationButton, mRotationButtonListener); + +// RotationButtonController.setRotateSuggestionButtonState(true, ...) +View view = mRotationButton.getCurrentView(); +Drawable icon = mRotationButton.getImageDrawable(); +view.setAlpha(1f); +((AnimatedVectorDrawable) icon).start(); +mRotationButton.show(); // FloatingRotationButton: WindowManager.addView(...) +// ...and on hide: fade getCurrentView() to alpha 0, then mRotationButton.hide() +``` + +The controller only ever talks to the button through the `RotationButton` interface. Unfloat leaves the controller alone and redirects that interface when the taskbar is in phone 3-button mode: + +```java +// after NavbarButtonsViewController.setupController(), in phone 3-button mode only +ImageView inBar = nbvc.addButton(contextualContainer, id, R.layout.taskbar_contextual_button); + +hook(FloatingRotationButton::getCurrentView) -> inBar +hook(FloatingRotationButton::getImageDrawable) -> AVD loaded from controller.getIconResId() +hook(FloatingRotationButton::show) -> inBar.setVisibility(VISIBLE) // no floating window +hook(FloatingRotationButton::hide) -> inBar.setVisibility(INVISIBLE) +hook(FloatingRotationButton::isVisible) -> our state +hook(FloatingRotationButton::setOnClickListener) -> remember the controller's listener, inBar forwards to it +``` + +Because `getCurrentView()` and `getImageDrawable()` return the in-bar view, the stock controller logic (icon animation, ripple hint for the first suggestions, 100 ms fade-out, 5 s timeout, hide on rotation) runs unchanged on the new button. + +### Why this hook point + +- **The `RotationButton` interface, not the controller.** `RotationContextButton` can't be restored: it extended SystemUI's `ContextualButton`, and a module class can't subclass across classloaders. Redirecting the interface methods of the existing `FloatingRotationButton` keeps the controller's proposal, timeout and click logic intact without reimplementing any of it. +- **The launcher builds the button.** The view is created with the launcher's own `addButton(ViewGroup, int, int)` and the stock `taskbar_contextual_button` layout, the same path as the accessibility button. That puts it in `mAllButtons`, so the launcher itself gives it the nav button size, the `KeyButtonRipple`, the light/dark icon tint (`applyButtonColors`) and a touchable region. No tint hook is needed. +- **Re-attached after every layout.** The phone layouters clear the contextual containers and re-add the IME switcher and accessibility button (end container in portrait and seascape, start container in landscape). A hook on `updateButtonLayoutSpacing()` puts the rotation button back into whichever container holds them, on top. +- **Slot priority follows Android 14:** accessibility button > rotation > IME switcher. While the accessibility button is shown, the rotation button stays hidden. While the rotation button is shown, the IME switcher's `transitionAlpha` is set to 0 (rather than fighting the launcher's own alpha animators) and the rotation button, on top, takes the touches. +- **Nav mode switches.** Changing navigation mode rebuilds the taskbar. The button is only created when `isPhoneButtonNavMode()` is true, so gesture navigation (and tablet taskbars) keep the stock floating button. + +### SystemUI fallback + +If the launcher has no taskbar, SystemUI's own `NavigationBarView` draws the bar. SystemUI is scoped too, with an equivalent path for that case. There, R8 has inlined `FloatingRotationButton.show()` and `isVisible()`, so it hooks `RotationButtonController.setRotateSuggestionButtonState()` and drives the leftover `@id/rotate_suggestion` `KeyButtonView` that `menu_ime.xml` still contains. On a device where the launcher draws the nav bar, those hooks attach but stay idle. + +### Safety + +Every hook body is wrapped in try/catch and falls back to the original method. If a required class, field or method is missing, nothing is hooked and the stock floating button stays. The redirect is only enabled once all of its supporting hooks have attached. + +## Build + +Uses `io.github.libxposed:api:101.0.1` from Maven Central (compile-only). + +```bash +./gradlew assembleDebug +adb install -r app/build/outputs/apk/debug/app-debug.apk +``` + +Vector discovers the module through `app/src/main/resources/META-INF/xposed/` (`java_init.list`, `module.prop`, `scope.list`). + +## Usage + +1. Enable **Unfloat** in Vector. The scope is preset to Launcher3 (`com.android.launcher3`) and System UI. +2. Restart the launcher: `adb shell am force-stop com.android.launcher3` (or reboot). +3. Check that the hooks attached: `adb logcat -s unfloat` diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 1e45858..5233fc5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -16,30 +16,20 @@ android { targetSdk = 36 versionCode = 1 versionName = "1.0" - - testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { isMinifyEnabled = false - proguardFiles( - getDefaultProguardFile("proguard-android-optimize.txt"), - "proguard-rules.pro" - ) } } compileOptions { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } } dependencies { - implementation(libs.androidx.appcompat) - implementation(libs.androidx.core.ktx) - implementation(libs.material) - testImplementation(libs.junit) - androidTestImplementation(libs.androidx.espresso.core) - androidTestImplementation(libs.androidx.junit) -} \ No newline at end of file + // Provided at runtime by the Xposed framework (Vector); must not be bundled. + compileOnly(libs.libxposed.api) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 481bb43..751bc22 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -1,21 +1,2 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile \ No newline at end of file +# Keep the Xposed entry class (listed in META-INF/xposed/java_init.list). +-keep class sh.sar.unfloat.UnfloatModule { (); } diff --git a/app/src/androidTest/java/sh/sar/unfloat/ExampleInstrumentedTest.kt b/app/src/androidTest/java/sh/sar/unfloat/ExampleInstrumentedTest.kt deleted file mode 100644 index 1a2f501..0000000 --- a/app/src/androidTest/java/sh/sar/unfloat/ExampleInstrumentedTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package sh.sar.unfloat - -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.ext.junit.runners.AndroidJUnit4 - -import org.junit.Test -import org.junit.runner.RunWith - -import org.junit.Assert.* - -/** - * Instrumented test, which will execute on an Android device. - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -@RunWith(AndroidJUnit4::class) -class ExampleInstrumentedTest { - @Test - fun useAppContext() { - // Context of the app under test. - val appContext = InstrumentationRegistry.getInstrumentation().targetContext - assertEquals("sh.sar.unfloat", appContext.packageName) - } -} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e606f88..ce1f2cb 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,15 +1,14 @@ - + + + android:roundIcon="@mipmap/ic_launcher_round" /> - \ No newline at end of file + diff --git a/app/src/main/java/sh/sar/unfloat/LauncherHooks.java b/app/src/main/java/sh/sar/unfloat/LauncherHooks.java new file mode 100644 index 0000000..914f475 --- /dev/null +++ b/app/src/main/java/sh/sar/unfloat/LauncherHooks.java @@ -0,0 +1,500 @@ +package sh.sar.unfloat; + +import android.graphics.drawable.AnimatedVectorDrawable; +import android.graphics.drawable.Drawable; +import android.util.Log; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.widget.FrameLayout; +import android.widget.ImageView; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.WeakHashMap; + +import io.github.libxposed.api.XposedInterface.Chain; +import io.github.libxposed.api.XposedInterface.ExceptionMode; +import io.github.libxposed.api.XposedModule; + +/** + * Launcher3 (Quickstep taskbar) variant. + * + *

On this device SystemUI never creates its own NavigationBarView: SystemUI's + * {@code NavigationBarControllerImpl.supportsTaskbar()} returns true, so the 3-button nav bar + * is drawn by Launcher3's taskbar ({@code NavbarButtonsViewController}) and the floating rotation + * button is Launcher3's own copy of {@code com.android.systemui.shared.rotation.FloatingRotationButton}. + * That copy is not R8-inlined, so the redirect goes through its {@code RotationButton} methods: + * show / hide / isVisible / getCurrentView / getImageDrawable / updateIcon.

+ * + *

The in-bar button is created with the launcher's own + * {@code NavbarButtonsViewController.addButton(ViewGroup, int id, int layout)} and the stock + * {@code taskbar_contextual_button} layout (same path as the accessibility button), so it is in + * {@code mAllButtons}: the launcher itself sizes it, gives it the KeyButtonRipple, tints it in + * {@code applyButtonColors} (light/dark nav icons) and includes it in the touchable region.

+ * + *

Because {@code getCurrentView()} / {@code getImageDrawable()} return our view and icon, the + * stock RotationButtonController logic (alpha reset, AVD start, ripple hint, 100 ms fade-out, + * timeouts) runs unchanged on our view.

+ */ +final class LauncherHooks { + static final String PKG = "com.android.launcher3"; + private static final String TAG = UnfloatModule.TAG; + + private static final String C_NBVC = "com.android.launcher3.taskbar.NavbarButtonsViewController"; + private static final String C_FRB = "com.android.systemui.shared.rotation.FloatingRotationButton"; + private static final String C_RBC = "com.android.systemui.shared.rotation.RotationButtonController"; + + private final XposedModule mModule; + private final ClassLoader mCl; + + private Class cNbvc, cFrb, cRbc; + private Field fNbvcA11y, fNbvcIme, fNbvcEnd, fNbvcContext, fNbvcFrb; + private Method mNbvcAddButton, mNbvcIsA11yVisible, mNbvcUpdateSpacing, mCtxIsPhoneButtonNav; + private Field fFrbCanShow, fFrbIsShowing, fFrbRbc; + private Method mRbcGetIconResId; + + /** Per launcher FloatingRotationButton. Removed in NavbarButtonsViewController.onDestroy. */ + private static final class Slot { + Object nbvc; + ImageView view; + AnimatedVectorDrawable avd; + Drawable icon; + boolean shown; + boolean imeHiddenByUs; + } + + private final Map mSlots = new WeakHashMap<>(); + private final Map mClick = new WeakHashMap<>(); + private final Map mHover = new WeakHashMap<>(); + + LauncherHooks(XposedModule module, ClassLoader cl) { + mModule = module; + mCl = cl; + } + + // ===================================================================================== + // Install + // ===================================================================================== + + void install() { + Method show, hide, isVisible, getCurrentView, getImageDrawable, updateIcon, setClick, setHover; + Method setupController, onDestroy; + try { + cNbvc = mCl.loadClass(C_NBVC); + cFrb = mCl.loadClass(C_FRB); + cRbc = mCl.loadClass(C_RBC); + + fNbvcA11y = field(cNbvc, "mA11yButton"); + fNbvcIme = field(cNbvc, "mImeSwitcherButton"); + fNbvcEnd = field(cNbvc, "mEndContextualContainer"); + fNbvcContext = field(cNbvc, "mContext"); + fNbvcFrb = field(cNbvc, "mFloatingRotationButton"); + mNbvcAddButton = method(cNbvc, "addButton", ViewGroup.class, int.class, int.class); + mNbvcIsA11yVisible = method(cNbvc, "isA11yButtonVisible"); + mNbvcUpdateSpacing = method(cNbvc, "updateButtonLayoutSpacing"); + mCtxIsPhoneButtonNav = fNbvcContext.getType().getMethod("isPhoneButtonNavMode"); + mCtxIsPhoneButtonNav.setAccessible(true); + setupController = method(cNbvc, "setupController"); + onDestroy = method(cNbvc, "onDestroy"); + + fFrbCanShow = field(cFrb, "mCanShow"); + fFrbIsShowing = field(cFrb, "mIsShowing"); + fFrbRbc = field(cFrb, "mRotationButtonController"); + show = method(cFrb, "show"); + hide = method(cFrb, "hide"); + isVisible = method(cFrb, "isVisible"); + getCurrentView = method(cFrb, "getCurrentView"); + getImageDrawable = method(cFrb, "getImageDrawable"); + updateIcon = method(cFrb, "updateIcon", int.class, int.class); + setClick = method(cFrb, "setOnClickListener", View.OnClickListener.class); + setHover = method(cFrb, "setOnHoverListener", View.OnHoverListener.class); + + mRbcGetIconResId = method(cRbc, "getIconResId"); + } catch (Throwable t) { + log(Log.ERROR, "launcher: required class/field/method missing; NOT hooking anything," + + " stock floating rotation button kept", t); + return; + } + + // Listener capture first (setRotationButton runs inside setupController). + int ok = 0; + ok += hook(setClick, "FloatingRotationButton#setOnClickListener", this::onSetClick); + ok += hook(setHover, "FloatingRotationButton#setOnHoverListener", this::onSetHover); + ok += hook(onDestroy, "NavbarButtonsViewController#onDestroy", this::onNbvcDestroy); + ok += hook(mNbvcUpdateSpacing, "NavbarButtonsViewController#updateButtonLayoutSpacing", this::onUpdateSpacing); + ok += hook(hide, "FloatingRotationButton#hide", this::onHide); + ok += hook(isVisible, "FloatingRotationButton#isVisible", this::onIsVisible); + ok += hook(getCurrentView, "FloatingRotationButton#getCurrentView", this::onGetCurrentView); + ok += hook(getImageDrawable, "FloatingRotationButton#getImageDrawable", this::onGetImageDrawable); + ok += hook(updateIcon, "FloatingRotationButton#updateIcon", this::onUpdateIcon); + ok += hook(show, "FloatingRotationButton#show", this::onShow); + if (ok != 10) { + log(Log.ERROR, "launcher: some hooks failed; not creating the in-bar button so stock" + + " floating behaviour stays", null); + return; + } + // Slots are only ever created by this hook, so nothing redirects unless all of the above attached. + if (hook(setupController, "NavbarButtonsViewController#setupController", this::onSetupController) == 1) { + log(Log.INFO, "launcher: core hooks active", null); + } + } + + private interface Body { + Object run(Chain chain) throws Throwable; + } + + private int hook(Method m, String name, Body body) { + try { + mModule.hook(m).setExceptionMode(ExceptionMode.PROTECTIVE).intercept(body::run); + log(Log.INFO, "hooked " + name, null); + return 1; + } catch (Throwable t) { + log(Log.ERROR, "failed to hook " + name, t); + return 0; + } + } + + // ===================================================================================== + // NavbarButtonsViewController + // ===================================================================================== + + private Object onSetupController(Chain chain) throws Throwable { + Object r = chain.proceed(); + Object nbvc = chain.getThisObject(); + try { + Object frb = fNbvcFrb.get(nbvc); + if (frb == null) return r; + if (!isPhoneButtonNav(nbvc)) { + log(Log.INFO, "launcher: taskbar is not phone 3-button nav; stock floating rotation button", null); + return r; + } + ViewGroup end = (ViewGroup) fNbvcEnd.get(nbvc); + if (end == null) return r; + int layout = end.getResources().getIdentifier("taskbar_contextual_button", "layout", PKG); + if (layout == 0) { + log(Log.ERROR, "launcher: layout taskbar_contextual_button not found; floating kept", null); + return r; + } + ImageView view = (ImageView) mNbvcAddButton.invoke(nbvc, end, View.generateViewId(), layout); + view.setVisibility(View.INVISIBLE); + int desc = end.getResources().getIdentifier("accessibility_rotate_button", "string", PKG); + if (desc != 0) view.setContentDescription(end.getContext().getString(desc)); + final Object key = frb; + view.setOnClickListener(v -> { + try { + View.OnClickListener l = mClick.get(key); + if (l != null) l.onClick(v); + else log(Log.WARN, "launcher: no rotation click listener captured", null); + } catch (Throwable t) { + log(Log.ERROR, "launcher: rotation click failed", t); + } + }); + view.setOnHoverListener((v, e) -> { + try { + View.OnHoverListener l = mHover.get(key); + return l != null && l.onHover(v, e); + } catch (Throwable t) { + return false; + } + }); + + Slot s = new Slot(); + s.nbvc = nbvc; + s.view = view; + mSlots.put(frb, s); + loadIcon(s, frb); + // Let the launcher lay out, background (KeyButtonRipple) and tint the new button; + // our updateButtonLayoutSpacing hook then moves it into the right contextual container. + mNbvcUpdateSpacing.invoke(nbvc); + log(Log.INFO, "launcher: in-bar rotation button ready (click listener captured=" + + (mClick.get(frb) != null) + ")", null); + } catch (Throwable t) { + log(Log.ERROR, "launcher: creating in-bar rotation button failed; floating kept", t); + try { + mSlots.remove(fNbvcFrb.get(nbvc)); + } catch (Throwable ignored) { + } + } + return r; + } + + private Object onUpdateSpacing(Chain chain) throws Throwable { + Object r = chain.proceed(); + try { + Slot s = slotForNbvc(chain.getThisObject()); + if (s != null) { + ensureAttached(s); + sync(s); + } + } catch (Throwable t) { + log(Log.ERROR, "launcher: updateButtonLayoutSpacing post-processing failed", t); + } + return r; + } + + private Object onNbvcDestroy(Chain chain) throws Throwable { + Object nbvc = chain.getThisObject(); + Object frb = null; + try { + frb = fNbvcFrb.get(nbvc); // read before onDestroy nulls it + } catch (Throwable ignored) { + } + try { + return chain.proceed(); // calls frb.hide() -> our hide hook + } finally { + if (frb != null) { + mSlots.remove(frb); + mClick.remove(frb); + mHover.remove(frb); + } + } + } + + // ===================================================================================== + // FloatingRotationButton + // ===================================================================================== + + private Object onSetClick(Chain chain) throws Throwable { + try { + Object l = chain.getArg(0); + if (l instanceof View.OnClickListener) mClick.put(chain.getThisObject(), (View.OnClickListener) l); + else mClick.remove(chain.getThisObject()); + } catch (Throwable ignored) { + } + return chain.proceed(); + } + + private Object onSetHover(Chain chain) throws Throwable { + try { + Object l = chain.getArg(0); + if (l instanceof View.OnHoverListener) mHover.put(chain.getThisObject(), (View.OnHoverListener) l); + else mHover.remove(chain.getThisObject()); + } catch (Throwable ignored) { + } + return chain.proceed(); + } + + private Object onShow(Chain chain) throws Throwable { + Object frb = chain.getThisObject(); + Slot s; + try { + s = active(frb); + } catch (Throwable t) { + log(Log.ERROR, "launcher: show() pre-check failed; floating", t); + return chain.proceed(); + } + if (s == null) return chain.proceed(); + try { + if (!fFrbCanShow.getBoolean(frb) || s.shown) return false; // same as stock + s.shown = true; + ensureAttached(s); + s.view.setAlpha(1f); + sync(s); + log(Log.INFO, "launcher: rotation suggestion shown in nav bar", null); + return true; + } catch (Throwable t) { + log(Log.ERROR, "launcher: in-bar show failed; falling back to floating", t); + s.shown = false; + safeSync(s); + mSlots.remove(frb); + return chain.proceed(); + } + } + + private Object onHide(Chain chain) throws Throwable { + Object frb = chain.getThisObject(); + boolean handled = false; + try { + Slot s = mSlots.get(frb); + if (s != null && s.shown) { + s.shown = false; + sync(s); + s.view.setAlpha(1f); + handled = true; + log(Log.INFO, "launcher: rotation suggestion hidden from nav bar", null); + } + } catch (Throwable t) { + log(Log.ERROR, "launcher: in-bar hide failed", t); + } + // Also let stock remove a real floating window if one is up. + boolean floating = false; + try { + floating = fFrbIsShowing.getBoolean(frb); + } catch (Throwable ignored) { + } + if (floating || !handled) { + Object r = chain.proceed(); + return handled || Boolean.TRUE.equals(r); + } + return true; + } + + private Object onIsVisible(Chain chain) throws Throwable { + try { + Slot s = mSlots.get(chain.getThisObject()); + if (s != null && s.shown) return true; + } catch (Throwable ignored) { + } + return chain.proceed(); + } + + private Object onGetCurrentView(Chain chain) throws Throwable { + try { + Slot s = active(chain.getThisObject()); + if (s != null) return s.view; + } catch (Throwable t) { + log(Log.ERROR, "launcher: getCurrentView redirect failed", t); + } + return chain.proceed(); + } + + private Object onGetImageDrawable(Chain chain) throws Throwable { + try { + Slot s = active(chain.getThisObject()); + if (s != null) { + if (s.icon == null) loadIcon(s, chain.getThisObject()); + if (s.icon != null) return s.icon; + } + } catch (Throwable t) { + log(Log.ERROR, "launcher: getImageDrawable redirect failed", t); + } + return chain.proceed(); + } + + private Object onUpdateIcon(Chain chain) throws Throwable { + Object r = chain.proceed(); + try { + Slot s = mSlots.get(chain.getThisObject()); + if (s != null) loadIcon(s, chain.getThisObject()); + } catch (Throwable t) { + log(Log.ERROR, "launcher: updateIcon post-processing failed", t); + } + return r; + } + + // ===================================================================================== + // Helpers + // ===================================================================================== + + /** The slot to redirect to, or null for stock floating behaviour. */ + private Slot active(Object frb) throws Throwable { + Slot s = mSlots.get(frb); + if (s == null || s.view == null) return null; + if (!isPhoneButtonNav(s.nbvc)) { + if (s.shown) { + s.shown = false; + safeSync(s); + } + return null; + } + return s; + } + + private Slot slotForNbvc(Object nbvc) throws Throwable { + Object frb = fNbvcFrb.get(nbvc); + return frb == null ? null : mSlots.get(frb); + } + + private boolean isPhoneButtonNav(Object nbvc) throws Throwable { + Object ctx = fNbvcContext.get(nbvc); + return ctx != null && Boolean.TRUE.equals(mCtxIsPhoneButtonNav.invoke(ctx)); + } + + private void loadIcon(Slot s, Object frb) throws Throwable { + Object rbc = fFrbRbc.get(frb); + if (rbc == null) return; + int res = (Integer) mRbcGetIconResId.invoke(rbc); + if (res == 0) return; + Drawable d = s.view.getContext().getDrawable(res); + if (d == null) return; + d = d.mutate(); + s.icon = d; + s.avd = d instanceof AnimatedVectorDrawable ? (AnimatedVectorDrawable) d : null; + s.view.setImageDrawable(d); // ImageView re-applies the launcher's imageTintList + } + + /** + * The phone layoutters clear the contextual containers and re-add the IME switcher and a11y + * button (end container in portrait/seascape, start container in landscape). Put ours in the + * same container, on top. + */ + private void ensureAttached(Slot s) throws Throwable { + ViewGroup target = null; + for (Field f : new Field[]{fNbvcA11y, fNbvcIme}) { + Object b = f.get(s.nbvc); + if (b instanceof View && ((View) b).getParent() instanceof ViewGroup) { + target = (ViewGroup) ((View) b).getParent(); + break; + } + } + if (target == null) target = (ViewGroup) fNbvcEnd.get(s.nbvc); + if (target == null) return; + ViewParent cur = s.view.getParent(); + if (cur == target) { + if (target.indexOfChild(s.view) != target.getChildCount() - 1) target.bringChildToFront(s.view); + return; + } + if (cur instanceof ViewGroup) ((ViewGroup) cur).removeView(s.view); + ViewGroup.LayoutParams lp = target instanceof FrameLayout + ? new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER) + : new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT); + target.addView(s.view, lp); + } + + /** + * Slot rule (Android 14 order, last wins): accessibility button > rotation > IME switcher. + * The launcher drives the IME switcher's alpha/visibility with its own animators, so instead + * of fighting them we zero its transitionAlpha while rotation is up; our view sits on top of + * it in the same container and takes the touches. + */ + private void sync(Slot s) throws Throwable { + boolean a11y = Boolean.TRUE.equals(mNbvcIsA11yVisible.invoke(s.nbvc)); + boolean vis = s.shown && !a11y && isPhoneButtonNav(s.nbvc); + int want = vis ? View.VISIBLE : View.INVISIBLE; + if (s.view.getVisibility() != want) s.view.setVisibility(want); + Object ime = fNbvcIme.get(s.nbvc); + if (ime instanceof View) { + if (vis) { + ((View) ime).setTransitionAlpha(0f); + s.imeHiddenByUs = true; + } else if (s.imeHiddenByUs) { + ((View) ime).setTransitionAlpha(1f); + s.imeHiddenByUs = false; + } + } + } + + private void safeSync(Slot s) { + try { + sync(s); + } catch (Throwable t) { + log(Log.ERROR, "launcher: sync failed", t); + } + } + + private static Field field(Class c, String name) throws NoSuchFieldException { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + private static Method method(Class c, String name, Class... params) throws NoSuchMethodException { + Method m = c.getDeclaredMethod(name, params); + m.setAccessible(true); + return m; + } + + private void log(int prio, String msg, Throwable t) { + try { + if (t != null) mModule.log(prio, TAG, msg, t); + else mModule.log(prio, TAG, msg); + } catch (Throwable ignored) { + Log.println(prio, TAG, msg); + } + } +} diff --git a/app/src/main/java/sh/sar/unfloat/RotationHooks.java b/app/src/main/java/sh/sar/unfloat/RotationHooks.java new file mode 100644 index 0000000..1607c0f --- /dev/null +++ b/app/src/main/java/sh/sar/unfloat/RotationHooks.java @@ -0,0 +1,856 @@ +package sh.sar.unfloat; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ArgbEvaluator; +import android.animation.ValueAnimator; +import android.content.Context; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; +import android.graphics.drawable.AnimatedVectorDrawable; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.provider.Settings; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.LinearInterpolator; +import android.widget.FrameLayout; +import android.widget.ImageView; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; + +import io.github.libxposed.api.XposedInterface.ExceptionMode; +import io.github.libxposed.api.XposedModule; + +/** + * Redirects the rotation suggestion UI of SystemUI's FloatingRotationButton into the 3-button + * navigation bar's contextual slot (menu_container), like Android 14's RotationContextButton. + * + *

All names below were taken from the decompiled SystemUI.apk of the target device + * (crDroid, Android 17). In that build {@code FloatingRotationButton.show()}, + * {@code isVisible()} and {@code RotationButtonController.getIconResId()} no longer exist as + * methods: R8 inlined them into {@code RotationButtonController.setRotateSuggestionButtonState} + * and field reads ({@code mIsShowing}, {@code mIconResId}). So the "show" side is handled by + * replacing {@code setRotateSuggestionButtonState} while we own the button.

+ * + *

Everything runs on SystemUI's main thread. Every hook body is wrapped in try/catch and falls + * back to the original method so stock floating behaviour stays intact on any failure.

+ */ +final class RotationHooks { + private static final String TAG = UnfloatModule.TAG; + private static final String PKG = UnfloatModule.SYSTEMUI; + private static final String VIEW_TAG = "unfloat_rotate"; + private static final int NAV_BAR_MODE_3BUTTON = 0; + + private static final String C_NBV = "com.android.systemui.navigationbar.views.NavigationBarView"; + private static final String C_NBT = "com.android.systemui.navigationbar.views.NavigationBarTransitions"; + private static final String C_RBC = "com.android.systemui.shared.rotation.RotationButtonController"; + private static final String C_FRB = "com.android.systemui.shared.rotation.FloatingRotationButton"; + private static final String C_BD = "com.android.systemui.navigationbar.views.buttons.ButtonDispatcher"; + private static final String C_CBG = "com.android.systemui.navigationbar.views.buttons.ContextualButtonGroup"; + private static final String C_CBG_DATA = C_CBG + "$ButtonData"; + private static final String C_KBD = "com.android.systemui.navigationbar.views.buttons.KeyButtonDrawable"; + private static final String C_RIPPLER = "com.android.systemui.shared.recents.utilities.ViewRippler"; + + private final XposedModule mModule; + private final ClassLoader mCl; + + // ---- reflection (required) ---- + private Class cNbv, cFrb, cRbc, cNbt, cCbg, cBd; + private Field fRbcRotationButton, fRbcUiHandler, fRbcCancelPending, fRbcPending, fRbcHideAnimator, + fRbcIconResId; + private Field fFrbIsShowing, fFrbUpdatesCallback, fFrbKeyButtonView; + private Field fCbThis0; + private Field fNbvMode, fNbvHorizontal, fNbvVertical, fNbvLightContext, fNbvLightColor, + fNbvDarkColor, fNbvGroup, fNbvFrb, fNbvRbc; + private Field fNbtView; + private Field fCbgButtonData, fBdMarked, fBdButton, fBdId; + private Method mBdSetVisibility, mCbgSetButtonVisibility; + // ---- reflection (optional; feature degrades gracefully when missing) ---- + private Field fFrbCanShow, fRbcViewRippler, fRipplerRoot, fRipplerRipple; + private Field fNbvBarTransitions, fNbtLtc, fLtcDark; + private Method mKbdCreate, mKbdSetDark; + private Field fKbdAvd; + private Field fViewListenerInfo, fLiClick, fLiHover; + + // ---- resource ids (SystemUI) ---- + private int idMenuContainer, idRotate, idIme, idA11y, strRotateDesc; + + // ---- state (main thread) ---- + private final Set mOwned = Collections.newSetFromMap(new WeakHashMap<>()); + private final Map mFrbToNav = new WeakHashMap<>(); + private final Map mGroupToNav = new WeakHashMap<>(); + private final Map mDark = new WeakHashMap<>(); + private final Map mClick = new WeakHashMap<>(); + private final Map mHover = new WeakHashMap<>(); + private final Set mConfigured = Collections.newSetFromMap(new WeakHashMap<>()); + private final ArgbEvaluator mArgb = new ArgbEvaluator(); + + RotationHooks(XposedModule module, ClassLoader cl) { + mModule = module; + mCl = cl; + } + + // ===================================================================================== + // Install + // ===================================================================================== + + void install() { + try { + resolveRequired(); + } catch (Throwable t) { + log(Log.ERROR, "required SystemUI class/field/method missing; NOT hooking anything," + + " stock floating rotation button kept", t); + return; + } + resolveOptional(); + + Method setState = findMethod(cRbc, "setRotateSuggestionButtonState", boolean.class, boolean.class); + Method frbHide = findMethod(cFrb, "hide"); + Method setRotationButton = null; + for (Method m : cRbc.getDeclaredMethods()) { + if (m.getName().equals("setRotationButton") && m.getParameterCount() == 2 + && m.getParameterTypes()[0] == cFrb) { + setRotationButton = m; + } + } + Method applyDark = findMethod(cNbt, "applyDarkIntensity", float.class); + Method setButtonVis = mCbgSetButtonVisibility; + Method onConfig = findMethod(cNbv, "onConfigurationChanged", android.content.res.Configuration.class); + + // All five are needed for a consistent redirect. Without them, do nothing. + if (setState == null || frbHide == null || setRotationButton == null || setButtonVis == null + || onConfig == null) { + log(Log.ERROR, "core method missing (setRotateSuggestionButtonState=" + (setState != null) + + " FloatingRotationButton.hide=" + (frbHide != null) + + " setRotationButton=" + (setRotationButton != null) + + " ContextualButtonGroup.setButtonVisibility=" + (setButtonVis != null) + + " NavigationBarView.onConfigurationChanged=" + (onConfig != null) + + "); NOT hooking anything", null); + return; + } + + int ok = 0; + ok += hook(setRotationButton, "RotationButtonController#setRotationButton", this::onSetRotationButton); + ok += hook(frbHide, "FloatingRotationButton#hide", this::onFrbHide); + ok += hook(setButtonVis, "ContextualButtonGroup#setButtonVisibility", this::onSetButtonVisibility); + ok += hook(onConfig, "NavigationBarView#onConfigurationChanged", this::onNavConfigChanged); + if (ok != 4) { + log(Log.ERROR, "support hooks failed; not hooking setRotateSuggestionButtonState so stock" + + " floating behaviour stays", null); + return; + } + // The redirect itself is installed last so it is only active if all support hooks are. + if (hook(setState, "RotationButtonController#setRotateSuggestionButtonState", this::onSetState) == 1) { + log(Log.INFO, "core hooks active", null); + } + if (applyDark != null) { + hook(applyDark, "NavigationBarTransitions#applyDarkIntensity", this::onApplyDark); + } else { + log(Log.WARN, "NavigationBarTransitions#applyDarkIntensity missing; icon will not follow" + + " light/dark nav bar changes while visible", null); + } + } + + private interface Body { + Object run(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable; + } + + private int hook(Method m, String name, Body body) { + try { + m.setAccessible(true); + mModule.hook(m).setExceptionMode(ExceptionMode.PROTECTIVE).intercept(body::run); + log(Log.INFO, "hooked " + name, null); + return 1; + } catch (Throwable t) { + log(Log.ERROR, "failed to hook " + name, t); + return 0; + } + } + + private void resolveRequired() throws Throwable { + cNbv = mCl.loadClass(C_NBV); + cFrb = mCl.loadClass(C_FRB); + cRbc = mCl.loadClass(C_RBC); + cNbt = mCl.loadClass(C_NBT); + cCbg = mCl.loadClass(C_CBG); + cBd = mCl.loadClass(C_BD); + Class cData = mCl.loadClass(C_CBG_DATA); + + fRbcRotationButton = field(cRbc, "mRotationButton"); + fRbcUiHandler = field(cRbc, "mUiHandler"); + fRbcCancelPending = field(cRbc, "mCancelPendingRotationProposal"); + fRbcPending = field(cRbc, "mPendingRotationSuggestion"); + fRbcHideAnimator = field(cRbc, "mRotateHideAnimator"); + fRbcIconResId = field(cRbc, "mIconResId"); + + fFrbIsShowing = field(cFrb, "mIsShowing"); + fFrbUpdatesCallback = field(cFrb, "mUpdatesCallback"); + fFrbKeyButtonView = field(cFrb, "mKeyButtonView"); + // NavigationBarView's anonymous rotation callback (NavigationBarView$2 in this build); + // take its class from the field type instead of hardcoding the synthetic name. + Class cCb = fFrbUpdatesCallback.getType(); + + fCbThis0 = field(cCb, "this$0"); + + fNbvMode = field(cNbv, "mNavBarMode"); + fNbvHorizontal = field(cNbv, "mHorizontal"); + fNbvVertical = field(cNbv, "mVertical"); + fNbvLightContext = field(cNbv, "mLightContext"); + fNbvLightColor = field(cNbv, "mLightIconColor"); + fNbvDarkColor = field(cNbv, "mDarkIconColor"); + fNbvGroup = field(cNbv, "mContextualButtonGroup"); + fNbvFrb = field(cNbv, "mFloatingRotationButton"); + fNbvRbc = field(cNbv, "mRotationButtonController"); + + fNbtView = field(cNbt, "mView"); + + fCbgButtonData = field(cCbg, "mButtonData"); + fBdMarked = field(cData, "markedVisible"); + fBdButton = field(cData, "button"); + fBdId = field(cBd, "mId"); + mBdSetVisibility = cBd.getDeclaredMethod("setVisibility", int.class); + mBdSetVisibility.setAccessible(true); + mCbgSetButtonVisibility = cCbg.getDeclaredMethod("setButtonVisibility", int.class, boolean.class); + mCbgSetButtonVisibility.setAccessible(true); + } + + /** Resource ids are resolved lazily from the nav bar's own resources (Application may not exist yet at install time). */ + private boolean mIdsResolved; + + private void ids(Object nav) { + if (mIdsResolved || !(nav instanceof View)) return; + mIdsResolved = true; + try { + android.content.res.Resources res = ((View) nav).getResources(); + idMenuContainer = res.getIdentifier("menu_container", "id", PKG); + idRotate = res.getIdentifier("rotate_suggestion", "id", PKG); + idIme = res.getIdentifier("ime_switcher", "id", PKG); + idA11y = res.getIdentifier("accessibility_button", "id", PKG); + strRotateDesc = res.getIdentifier("accessibility_rotate_button", "string", PKG); + } catch (Throwable t) { + log(Log.ERROR, "resource id lookup failed", t); + } + log(idMenuContainer == 0 ? Log.ERROR : Log.INFO, "resources: menu_container=0x" + Integer.toHexString(idMenuContainer) + + " rotate_suggestion=0x" + Integer.toHexString(idRotate) + + " ime_switcher=0x" + Integer.toHexString(idIme) + + " accessibility_button=0x" + Integer.toHexString(idA11y) + + (idMenuContainer == 0 ? " (menu_container missing: floating button will be used)" : ""), null); + } + + private void resolveOptional() { + fFrbCanShow = optField(cFrb, "mCanShow"); + fRbcViewRippler = optField(cRbc, "mViewRippler"); + try { + Class r = mCl.loadClass(C_RIPPLER); + fRipplerRoot = optField(r, "mRoot"); + fRipplerRipple = optField(r, "mRipple"); + } catch (Throwable ignored) { + } + fNbvBarTransitions = optField(cNbv, "mBarTransitions"); + fNbtLtc = optField(cNbt, "mLightTransitionsController"); + if (fNbtLtc != null) fLtcDark = optField(fNbtLtc.getType(), "mDarkIntensity"); + try { + Class kbd = mCl.loadClass(C_KBD); + Method create = kbd.getDeclaredMethod("create", Context.class, int.class, int.class, int.class, boolean.class); + Method setDark = kbd.getDeclaredMethod("setDarkIntensity", float.class); + Field avd = kbd.getDeclaredField("mAnimatedDrawable"); + create.setAccessible(true); + setDark.setAccessible(true); + avd.setAccessible(true); + mKbdCreate = create; + mKbdSetDark = setDark; + fKbdAvd = avd; + log(Log.INFO, "using KeyButtonDrawable for the icon", null); + } catch (Throwable t) { + log(Log.WARN, "KeyButtonDrawable.create unavailable; falling back to plain tinted ImageView", t); + } + try { + fViewListenerInfo = View.class.getDeclaredField("mListenerInfo"); + fViewListenerInfo.setAccessible(true); + Class li = fViewListenerInfo.getType(); + fLiClick = li.getDeclaredField("mOnClickListener"); + fLiClick.setAccessible(true); + fLiHover = li.getDeclaredField("mOnHoverListener"); + fLiHover.setAccessible(true); + } catch (Throwable t) { + log(Log.WARN, "View.mListenerInfo not accessible; clicks will be forwarded via performClick()", t); + fViewListenerInfo = null; + } + log(Log.INFO, "optional: mCanShow=" + (fFrbCanShow != null) + " viewRippler=" + + (fRbcViewRippler != null && fRipplerRoot != null && fRipplerRipple != null) + + " lightTransitions=" + (fLtcDark != null), null); + } + + // ===================================================================================== + // Hooks + // ===================================================================================== + + /** + * RotationButtonController#setRotateSuggestionButtonState(boolean visible, boolean hideImmediately). + * In this build FloatingRotationButton.show() is inlined here, so this is our show/hide entry. + */ + private Object onSetState(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object rbc = chain.getThisObject(); + boolean visible = (Boolean) chain.getArg(0); + boolean immediate = (Boolean) chain.getArg(1); + Object frb; + Object nav; + boolean owned; + boolean threeButton; + try { + frb = fRbcRotationButton.get(rbc); + nav = frb == null ? null : navOf(frb); + if (nav == null) return chain.proceed(); // e.g. PhoneStatusBarView's nav-less instance + owned = mOwned.contains(frb); + threeButton = isThreeButton(nav); + } catch (Throwable t) { + log(Log.ERROR, "setRotateSuggestionButtonState pre-check failed", t); + return chain.proceed(); + } + + if (!threeButton) { + if (owned) safeInternalHide(frb, nav, "nav mode is no longer 3-button"); + return chain.proceed(); + } + + if (visible) { + try { + if (showInBar(rbc, frb, nav)) return null; + } catch (Throwable t) { + log(Log.ERROR, "showing in-bar rotation button failed; falling back to floating", t); + safeInternalHide(frb, nav, "show failure"); + } + return chain.proceed(); + } + + if (!owned) return chain.proceed(); // a floating button left over from gesture mode + try { + hideInBar(rbc, frb, nav, immediate); + } catch (Throwable t) { + log(Log.ERROR, "hiding in-bar rotation button failed", t); + safeInternalHide(frb, nav, "hide failure"); + } + return null; + } + + /** FloatingRotationButton#hide(): when we own it, the floating window was never added. */ + private Object onFrbHide(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object frb = chain.getThisObject(); + boolean owned; + try { + owned = mOwned.contains(frb); + } catch (Throwable t) { + owned = false; + } + if (!owned) return chain.proceed(); + safeInternalHide(frb, mFrbToNav.get(frb), "hide()"); + return null; + } + + /** + * RotationButtonController#setRotationButton(FloatingRotationButton, NavigationBarView$AnonymousClass2). + * Called on nav bar attach and on every nav mode change (NavigationBar.setNavBarMode). We use it + * to grab the click/hover listeners the controller installs and to drop out of 3-button mode. + */ + private Object onSetRotationButton(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object r = chain.proceed(); + try { + Object frb = chain.getArg(0); + if (frb == null) return r; + captureListeners(frb); + Object nav = navOf(frb); + if (nav != null) { + mGroupToNav.put(fNbvGroup.get(nav), nav); + if (mOwned.contains(frb) && !isThreeButton(nav)) { + safeInternalHide(frb, nav, "nav mode changed to " + fNbvMode.getInt(nav)); + } + } + } catch (Throwable t) { + log(Log.ERROR, "setRotationButton post-processing failed", t); + } + return r; + } + + /** ContextualButtonGroup#setButtonVisibility(int, boolean): re-assert our slot rules. */ + private Object onSetButtonVisibility(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object r = chain.proceed(); + try { + Object nav = mGroupToNav.get(chain.getThisObject()); + if (nav != null) sync(nav); + } catch (Throwable t) { + log(Log.ERROR, "setButtonVisibility post-processing failed", t); + } + return r; + } + + /** + * NavigationBarView#onConfigurationChanged: stock code calls WindowManager.updateViewLayout() + * on the floating container when mIsShowing is true. That container is not attached while we + * own the button, so hide the flag for the duration of the call. + */ + private Object onNavConfigChanged(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object nav = chain.getThisObject(); + Object frb = null; + boolean owned = false; + try { + frb = fNbvFrb.get(nav); + owned = frb != null && mOwned.contains(frb); + if (owned) fFrbIsShowing.setBoolean(frb, false); + } catch (Throwable t) { + log(Log.ERROR, "onConfigurationChanged pre-processing failed", t); + } + try { + return chain.proceed(); + } finally { + if (owned) { + try { + if (mOwned.contains(frb)) { + fFrbIsShowing.setBoolean(frb, true); + // density / theme may have changed: rebuild the icon (no animation) + Object rbc = fNbvRbc.get(nav); + for (View v : rotateViews(nav, false)) { + if (rbc != null) applyIcon(nav, rbc, v, false); + } + sync(nav); + } + } catch (Throwable t) { + log(Log.ERROR, "onConfigurationChanged post-processing failed", t); + } + } + } + } + + /** NavigationBarTransitions#applyDarkIntensity(float): tint our icon like the other buttons. */ + private Object onApplyDark(io.github.libxposed.api.XposedInterface.Chain chain) throws Throwable { + Object r = chain.proceed(); + try { + Object nav = fNbtView.get(chain.getThisObject()); + if (nav != null) { + float f = (Float) chain.getArg(0); + mDark.put(nav, f); + for (View v : rotateViews(nav, false)) { + if (mConfigured.contains(v)) applyDark(nav, v, f); + } + } + } catch (Throwable t) { + log(Log.ERROR, "applyDarkIntensity post-processing failed", t); + } + return r; + } + + // ===================================================================================== + // Show / hide + // ===================================================================================== + + /** @return false if we couldn't take over (caller then runs the stock floating path). */ + private boolean showInBar(Object rbc, Object frb, Object nav) throws Throwable { + Object group = fNbvGroup.get(nav); + mGroupToNav.put(group, nav); + mFrbToNav.put(frb, nav); + + if (rotateViews(nav, true).isEmpty()) { + log(Log.WARN, "no menu_container in nav bar; using floating button", null); + return false; + } + boolean owned = mOwned.contains(frb); + // A floating button left over from gesture mode: remove its window first (stock hide()). + if (!owned && fFrbIsShowing.getBoolean(frb)) { + Method hide = cFrb.getDeclaredMethod("hide"); + hide.setAccessible(true); + hide.invoke(frb); + } + + // Mirror the bookkeeping of the stock (inlined) show path. + Animator anim = (Animator) fRbcHideAnimator.get(rbc); + if (anim != null && anim.isRunning()) anim.cancel(); + fRbcHideAnimator.set(rbc, null); + fRbcPending.setBoolean(rbc, false); + Handler h = (Handler) fRbcUiHandler.get(rbc); + Object cancel = fRbcCancelPending.get(rbc); + if (h != null && cancel instanceof Runnable) h.removeCallbacks((Runnable) cancel); + if (fFrbCanShow != null && !fFrbCanShow.getBoolean(frb)) return true; // stock: silently not shown + + mOwned.add(frb); + fFrbIsShowing.setBoolean(frb, true); + List views = rotateViews(nav, true); + for (View v : views) { + ensureConfigured(frb, v); + v.animate().cancel(); + v.setAlpha(1f); + applyIcon(nav, rbc, v, true); + } + sync(nav); + startRippleHint(rbc, nav, views); + if (!owned) log(Log.INFO, "rotation suggestion shown in nav bar", null); + return true; + } + + private void hideInBar(Object rbc, Object frb, Object nav, boolean immediate) throws Throwable { + stopRippleHint(rbc); + Animator anim = (Animator) fRbcHideAnimator.get(rbc); + if (immediate) { + if (anim != null && anim.isRunning()) anim.pause(); + internalHide(frb, nav); + return; + } + if (anim != null && anim.isRunning()) return; + + final List views = rotateViews(nav, false); + ValueAnimator fade = ValueAnimator.ofFloat(1f, 0f); + fade.setDuration(100); + fade.setInterpolator(new LinearInterpolator()); + fade.addUpdateListener(a -> { + float v = (Float) a.getAnimatedValue(); + for (View view : views) view.setAlpha(v); + }); + fade.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + // Same as the stock listener: hide when the fade ends (also fires on cancel()). + if (mOwned.contains(frb)) safeInternalHide(frb, nav, "fade end"); + } + }); + // Stored in the controller so its isRunning() checks (timeouts, show-cancel) keep working. + fRbcHideAnimator.set(rbc, fade); + fade.start(); + } + + private void safeInternalHide(Object frb, Object nav, String why) { + try { + internalHide(frb, nav); + } catch (Throwable t) { + log(Log.ERROR, "internal hide (" + why + ") failed", t); + try { + mOwned.remove(frb); + fFrbIsShowing.setBoolean(frb, false); + } catch (Throwable ignored) { + } + } + } + + private void internalHide(Object frb, Object nav) throws Throwable { + boolean wasOwned = mOwned.remove(frb); + fFrbIsShowing.setBoolean(frb, false); + if (nav == null) return; + ids(nav); + for (View v : rotateViews(nav, false)) { + v.animate().cancel(); + v.setVisibility(View.INVISIBLE); + v.setAlpha(1f); + } + // Let the stock group logic recompute visibility (restores the IME switcher if we hid it). + Object group = fNbvGroup.get(nav); + Boolean imeMarked = markedVisible(group, idIme); + if (imeMarked != null) { + mCbgSetButtonVisibility.invoke(group, idIme, imeMarked); + } else { + sync(nav); + } + if (wasOwned) log(Log.INFO, "rotation suggestion hidden from nav bar", null); + } + + /** + * Applies the slot rule to the contextual group. Priority (same order as Android 14's + * ContextualButtonGroup: ime_switcher, rotate_suggestion, accessibility_button; last wins): + * accessibility button > rotation suggestion > IME switcher. + */ + private void sync(Object nav) throws Throwable { + ids(nav); + Object frb = fNbvFrb.get(nav); + boolean show = frb != null && mOwned.contains(frb) && isThreeButton(nav); + Object group = fNbvGroup.get(nav); + if (show && Boolean.TRUE.equals(markedVisible(group, idA11y))) show = false; + List views = rotateViews(nav, show); + if (show) { + Object ime = button(group, idIme); + if (ime != null) mBdSetVisibility.invoke(ime, View.INVISIBLE); + mBdSetVisibility.invoke(group, View.VISIBLE); + Object rbc = fNbvRbc.get(nav); + for (View v : views) { + if (!mConfigured.contains(v) || ((ImageView) v).getDrawable() == null) { + ensureConfigured(frb, v); + if (rbc != null) applyIcon(nav, rbc, v, false); // e.g. layout re-inflated + } + if (v.getVisibility() != View.VISIBLE) v.setVisibility(View.VISIBLE); + } + } else { + for (View v : views) { + if (v.getVisibility() != View.INVISIBLE) v.setVisibility(View.INVISIBLE); + } + } + } + + // ===================================================================================== + // Views, icon, tint + // ===================================================================================== + + /** + * Rotation views in both the horizontal and vertical nav layouts. SystemUI's menu_ime.xml on + * this device still contains the Android 14 {@code KeyButtonView @id/rotate_suggestion}, but no + * code drives it any more; we reuse it (correct size, padding, ripple). If it is missing (or + * KeyButtonDrawable is unavailable, which KeyButtonView requires) we add our own ImageView. + */ + private List rotateViews(Object nav, boolean create) throws Throwable { + List out = new ArrayList<>(2); + ids(nav); + if (idMenuContainer == 0) return out; + for (Field f : new Field[]{fNbvHorizontal, fNbvVertical}) { + Object root = f.get(nav); + if (!(root instanceof View)) continue; + View c = ((View) root).findViewById(idMenuContainer); + if (!(c instanceof ViewGroup)) continue; + ViewGroup menu = (ViewGroup) c; + View v = null; + if (mKbdCreate != null && idRotate != 0) { + View cand = menu.findViewById(idRotate); + if (cand instanceof ImageView) v = cand; + } + if (v == null) v = menu.findViewWithTag(VIEW_TAG); + if (v == null && create) { + ImageView iv = new ImageView(menu.getContext()); + iv.setTag(VIEW_TAG); + iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE); + iv.setVisibility(View.INVISIBLE); + iv.setClickable(true); + if (strRotateDesc != 0) iv.setContentDescription(menu.getContext().getString(strRotateDesc)); + applyBorderlessRipple(iv); + menu.addView(iv, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + log(Log.INFO, "added own ImageView to menu_container", null); + v = iv; + } + if (v != null) out.add(v); + } + return out; + } + + private void ensureConfigured(Object frb, View v) { + if (mConfigured.contains(v)) return; + final Object key = frb; + v.setOnClickListener(view -> { + try { + View.OnClickListener l = mClick.get(key); + if (l != null) { + l.onClick(view); + } else { + View fv = (View) fFrbKeyButtonView.get(key); + if (fv != null) fv.performClick(); + } + } catch (Throwable t) { + log(Log.ERROR, "rotation click failed", t); + } + }); + v.setOnHoverListener((view, event) -> { + try { + View.OnHoverListener l = mHover.get(key); + return l != null && l.onHover(view, event); + } catch (Throwable t) { + return false; + } + }); + mConfigured.add(v); + } + + private void applyIcon(Object nav, Object rbc, View v, boolean animate) throws Throwable { + int res = fRbcIconResId.getInt(rbc); + if (res == 0) return; + Context lc = (Context) fNbvLightContext.get(nav); + if (lc == null) lc = v.getContext(); + int light = fNbvLightColor.getInt(nav); + int dark = fNbvDarkColor.getInt(nav); + Drawable d; + AnimatedVectorDrawable avd = null; + if (mKbdCreate != null) { + d = (Drawable) mKbdCreate.invoke(null, lc, light, dark, res, false); + Object a = fKbdAvd.get(d); + if (a instanceof AnimatedVectorDrawable) avd = (AnimatedVectorDrawable) a; + } else { + d = lc.getDrawable(res); + if (d instanceof AnimatedVectorDrawable) avd = (AnimatedVectorDrawable) d; + } + ((ImageView) v).setImageDrawable(d); + applyDark(nav, v, darkFor(nav)); + if (animate && avd != null) { + avd.reset(); + avd.start(); + } + } + + private void applyDark(Object nav, View v, float f) throws Throwable { + Drawable d = ((ImageView) v).getDrawable(); + if (d == null) return; + if (mKbdCreate != null && mKbdSetDark.getDeclaringClass().isInstance(d)) { + // KeyButtonView#setDarkIntensity also updates its ripple; use it when available. + try { + Method m = v.getClass().getMethod("setDarkIntensity", float.class); + m.invoke(v, f); + return; + } catch (NoSuchMethodException ignored) { + } + mKbdSetDark.invoke(d, f); + v.invalidate(); + return; + } + int c = (Integer) mArgb.evaluate(f, fNbvLightColor.getInt(nav), fNbvDarkColor.getInt(nav)); + d.setColorFilter(new PorterDuffColorFilter(c, PorterDuff.Mode.SRC_IN)); + v.invalidate(); + } + + private float darkFor(Object nav) { + Float f = mDark.get(nav); + if (f != null) return f; + try { + if (fNbvBarTransitions != null && fNbtLtc != null && fLtcDark != null) { + Object nbt = fNbvBarTransitions.get(nav); + Object ltc = nbt == null ? null : fNbtLtc.get(nbt); + if (ltc != null) return fLtcDark.getFloat(ltc); + } + } catch (Throwable ignored) { + } + return 0f; + } + + // ---- ripple hint (stock: first 3 suggestions ripple a few times) ---- + + private void startRippleHint(Object rbc, Object nav, List views) { + try { + if (fRbcViewRippler == null || fRipplerRoot == null || fRipplerRipple == null) return; + Context ctx = (Context) fNbvLightContext.get(nav); + if (ctx == null || Settings.Secure.getInt(ctx.getContentResolver(), + "num_rotation_suggestions_accepted", 0) >= 3) return; + View target = null; + for (View v : views) if (v.isShown()) target = v; + if (target == null) return; + Object rippler = fRbcViewRippler.get(rbc); + Runnable ripple = (Runnable) fRipplerRipple.get(rippler); + View old = (View) fRipplerRoot.get(rippler); + if (old != null) old.removeCallbacks(ripple); + fRipplerRoot.set(rippler, target); + for (long delay : new long[]{50, 2000, 4000, 6000, 8000}) { + target.postOnAnimationDelayed(ripple, delay); + } + } catch (Throwable t) { + log(Log.WARN, "ripple hint failed", t); + } + } + + private void stopRippleHint(Object rbc) { + try { + if (fRbcViewRippler == null || fRipplerRoot == null || fRipplerRipple == null) return; + Object rippler = fRbcViewRippler.get(rbc); + View root = (View) fRipplerRoot.get(rippler); + if (root != null) root.removeCallbacks((Runnable) fRipplerRipple.get(rippler)); + } catch (Throwable ignored) { + } + } + + // ===================================================================================== + // Helpers + // ===================================================================================== + + private void captureListeners(Object frb) { + if (fViewListenerInfo == null) return; + try { + Object view = fFrbKeyButtonView.get(frb); + Object li = view == null ? null : fViewListenerInfo.get(view); + if (li == null) return; + Object click = fLiClick.get(li); + Object hover = fLiHover.get(li); + if (click instanceof View.OnClickListener) mClick.put(frb, (View.OnClickListener) click); + if (hover instanceof View.OnHoverListener) mHover.put(frb, (View.OnHoverListener) hover); + } catch (Throwable t) { + log(Log.WARN, "could not capture rotation click listener; using performClick()", t); + } + } + + private Object navOf(Object frb) throws Throwable { + Object nav = mFrbToNav.get(frb); + if (nav != null) return nav; + Object cb = fFrbUpdatesCallback.get(frb); + if (cb == null) return null; + nav = fCbThis0.get(cb); + if (nav != null) mFrbToNav.put(frb, nav); + return nav; + } + + private boolean isThreeButton(Object nav) throws Throwable { + return fNbvMode.getInt(nav) == NAV_BAR_MODE_3BUTTON; + } + + private Object buttonData(Object group, int id) throws Throwable { + if (id == 0 || group == null) return null; + Object list = fCbgButtonData.get(group); + if (!(list instanceof List)) return null; + for (Object bd : (List) list) { + Object b = fBdButton.get(bd); + if (b != null && fBdId.getInt(b) == id) return bd; + } + return null; + } + + private Object button(Object group, int id) throws Throwable { + Object bd = buttonData(group, id); + return bd == null ? null : fBdButton.get(bd); + } + + private Boolean markedVisible(Object group, int id) throws Throwable { + Object bd = buttonData(group, id); + return bd == null ? null : fBdMarked.getBoolean(bd); + } + + private static Field field(Class c, String name) throws NoSuchFieldException { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + private Field optField(Class c, String name) { + try { + return field(c, name); + } catch (Throwable t) { + log(Log.WARN, "optional field missing: " + c.getName() + "#" + name, null); + return null; + } + } + + private Method findMethod(Class c, String name, Class... params) { + try { + Method m = c.getDeclaredMethod(name, params); + m.setAccessible(true); + return m; + } catch (Throwable t) { + log(Log.ERROR, "method missing: " + c.getName() + "#" + name, null); + return null; + } + } + + private void log(int prio, String msg, Throwable t) { + try { + if (t != null) mModule.log(prio, TAG, msg, t); + else mModule.log(prio, TAG, msg); + } catch (Throwable ignored) { + Log.println(prio, TAG, msg); + } + } + + /** Fallback-view styling helper. */ + private static void applyBorderlessRipple(ImageView v) { + try { + android.util.TypedValue tv = new android.util.TypedValue(); + if (v.getContext().getTheme().resolveAttribute( + android.R.attr.selectableItemBackgroundBorderless, tv, true) && tv.resourceId != 0) { + v.setBackground(v.getContext().getDrawable(tv.resourceId)); + } + } catch (Throwable ignored) { + } + } +} diff --git a/app/src/main/java/sh/sar/unfloat/UnfloatModule.java b/app/src/main/java/sh/sar/unfloat/UnfloatModule.java new file mode 100644 index 0000000..1494732 --- /dev/null +++ b/app/src/main/java/sh/sar/unfloat/UnfloatModule.java @@ -0,0 +1,45 @@ +package sh.sar.unfloat; + +import android.util.Log; + +import io.github.libxposed.api.XposedModule; + +/** Entry point (listed in META-INF/xposed/java_init.list). */ +public class UnfloatModule extends XposedModule { + static final String TAG = "unfloat"; + static final String SYSTEMUI = "com.android.systemui"; + + private boolean mInstalled; + + @Override + public void onModuleLoaded(ModuleLoadedParam param) { + try { + log(Log.INFO, TAG, "module loaded in " + param.getProcessName() + + " (framework " + getFrameworkName() + " " + getFrameworkVersion() + + ", api " + getApiVersion() + ")"); + } catch (Throwable ignored) { + } + } + + @Override + public void onPackageReady(PackageReadyParam param) { + try { + if (mInstalled || !param.isFirstPackage()) return; + String pkg = param.getPackageName(); + if (LauncherHooks.PKG.equals(pkg)) { + // Taskbar / "navbar unification": the 3-button nav bar is drawn by Launcher3. + mInstalled = true; + new LauncherHooks(this, param.getClassLoader()).install(); + } else if (SYSTEMUI.equals(pkg)) { + // Classic SystemUI NavigationBarView (only used when the launcher has no taskbar). + mInstalled = true; + new RotationHooks(this, param.getClassLoader()).install(); + } + } catch (Throwable t) { + try { + log(Log.ERROR, TAG, "failed to install hooks; stock behaviour kept", t); + } catch (Throwable ignored) { + } + } + } +} diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml deleted file mode 100644 index 91c171c..0000000 --- a/app/src/main/res/values-night/themes.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml deleted file mode 100644 index f8c6127..0000000 --- a/app/src/main/res/values/colors.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - #FFBB86FC - #FF6200EE - #FF3700B3 - #FF03DAC5 - #FF018786 - #FF000000 - #FFFFFFFF - \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a7c674d..c9b8bb8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,4 @@ Unfloat - \ No newline at end of file + Shows the rotation suggestion inside the 3-button navigation bar (Launcher3 taskbar or SystemUI) again (Android 14 style) instead of the floating button. Gesture navigation is left untouched. + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml deleted file mode 100644 index 6f20639..0000000 --- a/app/src/main/res/values/themes.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml deleted file mode 100644 index 4df9255..0000000 --- a/app/src/main/res/xml/backup_rules.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml deleted file mode 100644 index 9ee9997..0000000 --- a/app/src/main/res/xml/data_extraction_rules.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/app/src/main/resources/META-INF/xposed/java_init.list b/app/src/main/resources/META-INF/xposed/java_init.list new file mode 100644 index 0000000..6737e16 --- /dev/null +++ b/app/src/main/resources/META-INF/xposed/java_init.list @@ -0,0 +1 @@ +sh.sar.unfloat.UnfloatModule diff --git a/app/src/main/resources/META-INF/xposed/module.prop b/app/src/main/resources/META-INF/xposed/module.prop new file mode 100644 index 0000000..508d461 --- /dev/null +++ b/app/src/main/resources/META-INF/xposed/module.prop @@ -0,0 +1,4 @@ +minApiVersion=101 +targetApiVersion=101 +staticScope=true +exceptionMode=protective diff --git a/app/src/main/resources/META-INF/xposed/scope.list b/app/src/main/resources/META-INF/xposed/scope.list new file mode 100644 index 0000000..aca0139 --- /dev/null +++ b/app/src/main/resources/META-INF/xposed/scope.list @@ -0,0 +1,2 @@ +com.android.launcher3 +com.android.systemui diff --git a/app/src/test/java/sh/sar/unfloat/ExampleUnitTest.kt b/app/src/test/java/sh/sar/unfloat/ExampleUnitTest.kt deleted file mode 100644 index 2bcf1ed..0000000 --- a/app/src/test/java/sh/sar/unfloat/ExampleUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package sh.sar.unfloat - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 34c5e9e..a4710ec 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,5 +11,5 @@ org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # This option should only be used with decoupled projects. For more details, visit # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects # org.gradle.parallel=true -# Kotlin code style for this project: "official" or "obsolete": -kotlin.code.style=official \ No newline at end of file +# Pure-Java module: disable AGP 9 built-in Kotlin so kotlin-stdlib is not bundled. +android.builtInKotlin=false \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 6764ee4..ac61d62 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,20 +1,9 @@ [versions] agp = "9.2.1" -coreKtx = "1.19.1" -junit = "4.13.2" -junitVersion = "1.3.0" -espressoCore = "3.7.0" -appcompat = "1.8.0" -material = "1.14.0" +libxposed = "101.0.1" [libraries] -androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } -junit = { group = "junit", name = "junit", version.ref = "junit" } -androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } -androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } -androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } -material = { group = "com.google.android.material", name = "material", version.ref = "material" } +libxposed-api = { group = "io.github.libxposed", name = "api", version.ref = "libxposed" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } - diff --git a/screenshots/stock.jpg b/screenshots/stock.jpg new file mode 100644 index 0000000..8e2bd19 Binary files /dev/null and b/screenshots/stock.jpg differ diff --git a/screenshots/unfloat.jpg b/screenshots/unfloat.jpg new file mode 100644 index 0000000..0ca754f Binary files /dev/null and b/screenshots/unfloat.jpg differ