diff --git a/README.md b/README.md index f33472ef..0943d611 100644 --- a/README.md +++ b/README.md @@ -365,3 +365,4 @@ Since One UI updates may cause hooks to fail, if you find any invalid hook point - [Firefds Kit](https://github.com/Firefds/FirefdsKit) - [OneDesign](https://github.com/qlenlen/android_kernel_samsung_sm8550) +- [ColorMotion](https://github.com/juccul/ColorMotion) diff --git a/THIRD_PARTY_COLORMOTION.md b/THIRD_PARTY_COLORMOTION.md new file mode 100644 index 00000000..6bf7765a --- /dev/null +++ b/THIRD_PARTY_COLORMOTION.md @@ -0,0 +1,14 @@ +# ColorMotion + +The panel animation feature (`hook/src/main/java/dev/colormotion`, `hook/src/main/java/de/robv/android/xposed`, +`cm-native-api`, `cm-native-bridge`) is derived from **ColorMotion** by juccul, +, licensed under the GNU General Public License v3.0 +(see `licenses/ColorMotion-GPL-3.0.txt`). + +GPL v3 section 13 allows combining it with this AGPL v3 project. The combined work is +distributed under AGPL v3; the ColorMotion parts remain under their original copyright. + +Changes made for OneUIX: +- The module entry was replaced by `dev.colormotion.Entry.install`, called from OneUIX's SystemUI hook. +- A small compatibility layer in `de.robv.android.xposed` maps ColorMotion's legacy hook API onto libxposed. +- The Audio Eraser banner filter was dropped; OneUIX has its own. diff --git a/app/src/main/java/io/github/soclear/oneuix/ui/category/DetailPaneSystemUI.kt b/app/src/main/java/io/github/soclear/oneuix/ui/category/DetailPaneSystemUI.kt index 105e9e78..92055db7 100644 --- a/app/src/main/java/io/github/soclear/oneuix/ui/category/DetailPaneSystemUI.kt +++ b/app/src/main/java/io/github/soclear/oneuix/ui/category/DetailPaneSystemUI.kt @@ -717,6 +717,17 @@ fun DetailPaneSystemUI( onEvent(SystemUIEvent.QS.DisableHighBrightnessDialog(it)) } ) + if (ONE_UI_VERSION >= 80500) { + SwitchItem( + icon = ImageVector.vectorResource(id = R.drawable.fast_forward), + title = stringResource(id = R.string.colorMotionAnimation_title), + summary = stringResource(id = R.string.colorMotionAnimation_summary), + checked = uiState.qs.colorMotionAnimation, + onCheckedChange = { + onEvent(SystemUIEvent.QS.ColorMotionAnimation(it)) + } + ) + } if (ONE_UI_VERSION < 80500) { SwitchItem( icon = ImageVector.vectorResource(id = R.drawable.light_mode), @@ -1144,6 +1155,9 @@ sealed interface SystemUIEvent { @JvmInline value class DisableHighBrightnessDialog(val value: Boolean) : QS + @JvmInline + value class ColorMotionAnimation(val value: Boolean) : QS + @JvmInline value class AddBrightnessProgressToQsBar(val value: Boolean) : QS @@ -1674,6 +1688,16 @@ private fun SettingViewModel.onQSEvent(event: SystemUIEvent.QS) { ) } + is SystemUIEvent.QS.ColorMotionAnimation -> { + preference.copy( + systemUI = preference.systemUI.copy( + qs = preference.systemUI.qs.copy( + colorMotionAnimation = event.value + ) + ) + ) + } + is SystemUIEvent.QS.AddBrightnessProgressToQsBar -> { preference.copy( systemUI = preference.systemUI.copy( diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0d9edc9f..d2837423 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -259,4 +259,6 @@ Utilisable jusqu’à 1 % sans extinction automatique due à la batterie faible. La protection thermique est conservée Corriger la redirection du stockage réseau dans Mes fichiers Pour la version internationale de Mes fichiers sur une ROM chinoise : empêche le stockage réseau de rediriger vers la page de mise à jour du Galaxy Store. La dernière version en cache est alignée sur la version installée + Animation des notifications et réglages rapides + Animation à ressort plus fluide pour le volet de notifications et les Réglages rapides (One UI 8.5+). Nécessite des panneaux séparés : notifications à gauche, Réglages rapides à droite diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 1db34a1a..d1d0f75c 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -259,4 +259,6 @@ 배터리 부족으로 자동으로 꺼지지 않고 1%까지 사용합니다. 과열 보호는 유지됩니다 내 파일 네트워크 저장소 이동 문제 수정 중국 ROM에서 국제판 내 파일을 사용할 때 네트워크 저장소를 누르면 Galaxy Store 업데이트 페이지로 이동하는 문제를 막습니다. 캐시된 최신 버전을 설치된 버전과 동일하게 유지합니다 + 알림창 및 빠른 설정 애니메이션 + 알림창과 빠른 설정에 더 부드러운 스프링 애니메이션을 추가합니다(One UI 8.5 이상). 알림은 왼쪽, 빠른 설정은 오른쪽에서 내리는 분리형 패널이 필요합니다 diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6d7aa4fa..a3f4a3fa 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -259,4 +259,6 @@ Работа до 1 % без автоматического отключения из-за низкого заряда. Защита от перегрева сохраняется Исправить переход «Сетевого хранилища» в «Моих файлах» Для международной версии «Моих файлов» на китайской прошивке: не даёт «Сетевому хранилищу» перенаправлять на страницу обновления в Galaxy Store. Кэшированная последняя версия приравнивается к установленной + Анимация шторки и быстрых настроек + Более плавная пружинная анимация шторки уведомлений и быстрых настроек (One UI 8.5+). Нужны раздельные панели: уведомления слева, быстрые настройки справа diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index f7f7a878..5ac998a7 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -259,4 +259,6 @@ 电量低至 1% 时仍可使用,不因低电量自动关闭;保留过热保护 修复我的文件网络存储跳转 适用于国行系统上使用国际版“我的文件”:点击网络存储时不再跳转到应用商店更新页面。让缓存的最新版本与已安装版本保持一致 + 快捷通知面板动画 + 为通知面板和快捷设置添加更流畅的弹簧动画(One UI 8.5 及以上)。需要使用分开式面板:左侧下拉通知,右侧下拉快捷设置 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d7ed2fd4..6dd6a52b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -259,4 +259,6 @@ Allow use down to 1% without automatic shutoff due to low battery. Thermal protection is retained Fix My Files network storage redirect For the international My Files on a China ROM: stop Network storage from jumping to the Galaxy Store update page. Keeps the cached latest version equal to the installed version + Notification and Quick Settings animation + Smoother spring-based animation for the notification shade and Quick Settings (One UI 8.5+). Requires split panels: notifications from the left, Quick Settings from the right diff --git a/cm-native-api/build.gradle.kts b/cm-native-api/build.gradle.kts new file mode 100644 index 00000000..69231825 --- /dev/null +++ b/cm-native-api/build.gradle.kts @@ -0,0 +1,33 @@ +// Compile-only stubs of the SystemUI / Compose members used by cm-native-bridge. Never packaged. +import java.io.File +import java.util.Properties + +plugins { `java-library` } + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +fun androidSdkDir(): File { + val fromEnv = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") + if (fromEnv != null && File(fromEnv).isDirectory) return File(fromEnv) + val local = rootProject.file("local.properties") + if (local.isFile) { + val dir = Properties().apply { local.inputStream().use { load(it) } }.getProperty("sdk.dir") + if (dir != null && File(dir).isDirectory) return File(dir) + } + error("Android SDK not found: set ANDROID_HOME or sdk.dir in local.properties") +} + +// Newest installed platform that is at least API 35. +val androidJar: File = File(androidSdkDir(), "platforms").listFiles().orEmpty() + .mapNotNull { dir -> dir.name.removePrefix("android-").toDoubleOrNull()?.let { it to dir } } + .filter { it.first >= 35 && File(it.second, "android.jar").isFile } + .maxByOrNull { it.first } + ?.let { File(it.second, "android.jar") } + ?: error("No Android platform 35+ under ${androidSdkDir()}/platforms") + +dependencies { + compileOnly(files(androidJar)) +} diff --git a/cm-native-api/src/main/java/androidx/compose/runtime/MutableState.java b/cm-native-api/src/main/java/androidx/compose/runtime/MutableState.java new file mode 100644 index 00000000..fd0a6e56 --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/runtime/MutableState.java @@ -0,0 +1,4 @@ +package androidx.compose.runtime; + +/** Only the inherited/read and write contracts used by the bridge. Never packaged. */ +public interface MutableState extends State { void setValue(T value); } diff --git a/cm-native-api/src/main/java/androidx/compose/runtime/State.java b/cm-native-api/src/main/java/androidx/compose/runtime/State.java new file mode 100644 index 00000000..f0d470c1 --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/runtime/State.java @@ -0,0 +1,4 @@ +package androidx.compose.runtime; + +/** Compile-only ABI from the captured Samsung DEX. Never packaged or loaded. */ +public interface State { T getValue(); } diff --git a/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/MutableSnapshot.java b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/MutableSnapshot.java new file mode 100644 index 00000000..c083ab5b --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/MutableSnapshot.java @@ -0,0 +1,5 @@ +package androidx.compose.runtime.snapshots; + +public class MutableSnapshot extends Snapshot { + public SnapshotApplyResult apply() { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/Snapshot.java b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/Snapshot.java new file mode 100644 index 00000000..a4e58409 --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/Snapshot.java @@ -0,0 +1,14 @@ +package androidx.compose.runtime.snapshots; + +/** Compile-only Samsung runtime ABI. The bridge resolves the real types from SystemUI. */ +public abstract class Snapshot { + public static final Companion Companion = null; + public static final class Companion { + public static MutableSnapshot takeMutableSnapshot$default(Companion self) { + throw new UnsupportedOperationException("ABI stub"); + } + } + public Snapshot makeCurrent() { throw new UnsupportedOperationException("ABI stub"); } + public static void restoreCurrent(Snapshot previous) { throw new UnsupportedOperationException("ABI stub"); } + public void dispose() { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/SnapshotApplyResult.java b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/SnapshotApplyResult.java new file mode 100644 index 00000000..ceebef3b --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/runtime/snapshots/SnapshotApplyResult.java @@ -0,0 +1,3 @@ +package androidx.compose.runtime.snapshots; + +public abstract class SnapshotApplyResult { public abstract void check(); } diff --git a/cm-native-api/src/main/java/androidx/compose/ui/graphics/ReusableGraphicsLayerScope.java b/cm-native-api/src/main/java/androidx/compose/ui/graphics/ReusableGraphicsLayerScope.java new file mode 100644 index 00000000..8a199cc7 --- /dev/null +++ b/cm-native-api/src/main/java/androidx/compose/ui/graphics/ReusableGraphicsLayerScope.java @@ -0,0 +1,8 @@ +package androidx.compose.ui.graphics; + +/** Compile-only public fields verified against the phone's SystemUI DEX. */ +public final class ReusableGraphicsLayerScope { + public float alpha, scaleX, scaleY, translationY; + public int mutatedFields, compositingStrategy; + public ReusableGraphicsLayerScope() { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java new file mode 100644 index 00000000..59242637 --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java @@ -0,0 +1,7 @@ +package com.android.systemui.statusbar.notification.row; +public class ExpandableNotificationRow extends ExpandableView { + public boolean mIsFaded; + public void updateBlurBackgroundGradient() { throw new UnsupportedOperationException("ABI stub"); } + public java.util.List getAttachedChildren() { throw new UnsupportedOperationException("ABI stub"); } + public void setNotificationFaded(boolean faded) { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableView.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableView.java new file mode 100644 index 00000000..9c9eb19d --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/row/ExpandableView.java @@ -0,0 +1,11 @@ +package com.android.systemui.statusbar.notification.row; +import android.view.View; +import com.android.systemui.statusbar.notification.stack.ExpandableViewState; +/** Compile-only captured ABI; all real instances come from SystemUI. */ +public class ExpandableView extends View { + public int mActualHeight = 160; + public ExpandableViewState mViewState; + public boolean mWillBeGone; + public ExpandableView() { super(null); throw new UnsupportedOperationException("ABI stub"); } + public boolean mustStayOnScreen() { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/AmbientState.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/AmbientState.java new file mode 100644 index 00000000..b97ac5ea --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/AmbientState.java @@ -0,0 +1,2 @@ +package com.android.systemui.statusbar.notification.stack; +public class AmbientState { public float mStackY; public float mBlurTopFadeoutEnd = 300f, mBlurBottomFadeoutStart = 900f; } diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java new file mode 100644 index 00000000..3349c893 --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java @@ -0,0 +1,2 @@ +package com.android.systemui.statusbar.notification.stack; +public class ExpandableViewState extends ViewState {} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java new file mode 100644 index 00000000..4d4636b3 --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java @@ -0,0 +1,11 @@ +package com.android.systemui.statusbar.notification.stack; +import android.view.View; +/** Compile-only captured ABI. No stack/view implementation is packaged. */ +public class NotificationStackScrollLayout extends View { + public StackScrollAlgorithm mStackScrollAlgorithm; + public AmbientState mAmbientState; + public boolean mChildrenUpdateRequested; + public int mOwnScrollY; + public NotificationStackScrollLayout() { super(null); throw new UnsupportedOperationException("ABI stub"); } + public int getTopPadding() { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java new file mode 100644 index 00000000..b7cdcac5 --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java @@ -0,0 +1,7 @@ +package com.android.systemui.statusbar.notification.stack; +import java.util.ArrayList; +import com.android.systemui.statusbar.notification.row.ExpandableView; +public class StackScrollAlgorithm { + public StackScrollAlgorithmState mTempAlgorithmState; + public static class StackScrollAlgorithmState { public ArrayList visibleChildren; } +} diff --git a/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ViewState.java b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ViewState.java new file mode 100644 index 00000000..025079dc --- /dev/null +++ b/cm-native-api/src/main/java/com/android/systemui/statusbar/notification/stack/ViewState.java @@ -0,0 +1,8 @@ +package com.android.systemui.statusbar.notification.stack; +import android.view.View; +/** Compile-only captured ABI. */ +public class ViewState { + public float mYTranslation, mScaleX, mScaleY, mAlpha; + public boolean gone, hidden; + public static boolean isAnimating(View view) { throw new UnsupportedOperationException("ABI stub"); } +} diff --git a/cm-native-bridge/build.gradle.kts b/cm-native-bridge/build.gradle.kts new file mode 100644 index 00000000..bd1c43cc --- /dev/null +++ b/cm-native-bridge/build.gradle.kts @@ -0,0 +1,116 @@ +// The typed ColorMotion bridge: compiled against stubs, dexed with D8 and shipped as +// assets/colormotion-native.dex. It is loaded at runtime with SystemUI's class loader as parent. +import java.io.File +import java.util.Properties +import javax.inject.Inject +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.bundling.Jar +import org.gradle.process.ExecOperations + +plugins { `java-library` } + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +fun androidSdkDir(): File { + val fromEnv = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") + if (fromEnv != null && File(fromEnv).isDirectory) return File(fromEnv) + val local = rootProject.file("local.properties") + if (local.isFile) { + val dir = Properties().apply { local.inputStream().use { load(it) } }.getProperty("sdk.dir") + if (dir != null && File(dir).isDirectory) return File(dir) + } + error("Android SDK not found: set ANDROID_HOME or sdk.dir in local.properties") +} + +val sdkDir: File = androidSdkDir() + +// Newest installed platform that is at least API 35. +val androidJar: File = File(sdkDir, "platforms").listFiles().orEmpty() + .mapNotNull { dir -> dir.name.removePrefix("android-").toDoubleOrNull()?.let { it to dir } } + .filter { it.first >= 35 && File(it.second, "android.jar").isFile } + .maxByOrNull { it.first } + ?.let { File(it.second, "android.jar") } + ?: error("No Android platform 35+ under $sdkDir/platforms") + +// Newest installed build-tools that ships D8. +fun versionPart(name: String, index: Int): Int = + name.split('.').getOrNull(index)?.takeWhile { it.isDigit() }?.toIntOrNull() ?: 0 + +val d8Jar: File = File(sdkDir, "build-tools").listFiles().orEmpty() + .filter { File(it, "lib/d8.jar").isFile } + .maxWithOrNull( + compareBy({ versionPart(it.name, 0) }, { versionPart(it.name, 1) }, { versionPart(it.name, 2) }) + ) + ?.let { File(it, "lib/d8.jar") } + ?: error("No build-tools with lib/d8.jar under $sdkDir/build-tools") + +dependencies { + compileOnly(files(androidJar)) + compileOnly(project(":cm-native-api")) + compileOnly("org.jetbrains.kotlin:kotlin-stdlib:2.2.10") +} + +abstract class DexBridge @Inject constructor(private val execOps: ExecOperations) : DefaultTask() { + @get:InputFile + @get:PathSensitive(PathSensitivity.NONE) + abstract val bridgeJar: RegularFileProperty + + @get:InputFiles + @get:PathSensitive(PathSensitivity.NONE) + abstract val libraryJars: ConfigurableFileCollection + + @get:Input + abstract val androidJarPath: Property + + @get:Input + abstract val d8JarPath: Property + + @get:OutputDirectory + abstract val outDir: DirectoryProperty + + @TaskAction + fun dex() { + val out = outDir.get().asFile + out.deleteRecursively() + out.mkdirs() + val androidJarFile = androidJarPath.get() + val jars = libraryJars.files.filter { it.isFile && it.name.endsWith(".jar") } + execOps.javaexec { + classpath(d8JarPath.get()) + mainClass.set("com.android.tools.r8.D8") + val arguments = mutableListOf("--release", "--min-api", "35", "--lib", androidJarFile) + jars.filter { it.absolutePath != androidJarFile }.forEach { arguments += listOf("--lib", it.absolutePath) } + arguments += listOf("--output", out.absolutePath, bridgeJar.get().asFile.absolutePath) + args = arguments + } + } +} + +val apiJar = project(":cm-native-api").tasks.named("jar") + +val dexBridge = tasks.register("dexBridge") { + bridgeJar.set(tasks.named("jar").flatMap { it.archiveFile }) + libraryJars.from(configurations.named("compileClasspath")) + libraryJars.from(apiJar.flatMap { it.archiveFile }) + androidJarPath.set(androidJar.absolutePath) + d8JarPath.set(d8Jar.absolutePath) + outDir.set(layout.buildDirectory.dir("dex")) +} + +tasks.register("bridgeAssets") { + from(dexBridge.flatMap { it.outDir.file("classes.dex") }) { rename { "colormotion-native.dex" } } + into(layout.buildDirectory.dir("assets")) +} diff --git a/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBatch.java b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBatch.java new file mode 100644 index 00000000..f36798ef --- /dev/null +++ b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBatch.java @@ -0,0 +1,33 @@ +package dev.colormotion.nativebridge; + +import androidx.compose.runtime.snapshots.MutableSnapshot; +import androidx.compose.runtime.snapshots.Snapshot; + +/** One synchronous snapshot commit for all changed rows, before the current frame is drawn. */ +public final class LayerBatch implements Runnable { + private final Runnable[] pending; + private final int[] count; + + public LayerBatch(Runnable[] pending, int[] count) { + this.pending = pending; + this.count = count; + } + + @Override public void run() { + int size = count[0]; + if (size == 0) return; + MutableSnapshot snapshot = Snapshot.Companion.takeMutableSnapshot$default(Snapshot.Companion); + try { + Snapshot previous = snapshot.makeCurrent(); + try { + for (int i = 0; i < size; i++) pending[i].run(); + } finally { + Snapshot.restoreCurrent(previous); + } + snapshot.apply().check(); + count[0] = 0; // Keep the batch queued if a write or commit failed. + } finally { + snapshot.dispose(); + } + } +} diff --git a/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBlock.java b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBlock.java new file mode 100644 index 00000000..3650bed5 --- /dev/null +++ b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/LayerBlock.java @@ -0,0 +1,41 @@ +package dev.colormotion.nativebridge; + +import androidx.compose.runtime.MutableState; +import androidx.compose.ui.graphics.ReusableGraphicsLayerScope; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** Loaded with SystemUI as parent: native interfaces and fields resolve to its own Compose copy. */ +public final class LayerBlock implements Function1, Runnable { + private final MutableState signal; + private final float[] pose; + + @SuppressWarnings("unchecked") + public LayerBlock(Object signal, float[] pose) { + this.signal = (MutableState) signal; + this.pose = pose; + } + + @Override public Unit invoke(Object target) { + signal.getValue(); // Subscribe this layer, without a proxy or reflected call. + ReusableGraphicsLayerScope scope = (ReusableGraphicsLayerScope) target; + scope.alpha = pose[0]; + scope.scaleX = pose[1]; + scope.scaleY = pose[1]; + scope.translationY = pose[2]; + scope.compositingStrategy = 2; // ModulateAlpha: no implicit bounds around moving descendants. + // Compose resets this scope to identity and merges this mask with the layer's + // previous mask. A property returning to identity is therefore still restored once. + int changed = 32768; + if (pose[0] != 1f) changed |= 4; + if (pose[1] != 1f) changed |= 1 | 2; + if (pose[2] != 0f) changed |= 16; + scope.mutatedFields |= changed; + return Unit.INSTANCE; + } + + @Override public void run() { + // Read the committed/current-snapshot value, so a failed transaction can retry safely. + signal.setValue(signal.getValue() == Boolean.TRUE ? Boolean.FALSE : Boolean.TRUE); + } +} diff --git a/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/NotificationBlock.java b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/NotificationBlock.java new file mode 100644 index 00000000..263da296 --- /dev/null +++ b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/NotificationBlock.java @@ -0,0 +1,197 @@ +package dev.colormotion.nativebridge; + +import android.view.View; +import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow; +import com.android.systemui.statusbar.notification.row.ExpandableView; +import com.android.systemui.statusbar.notification.stack.ExpandableViewState; +import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout; +import com.android.systemui.statusbar.notification.stack.ViewState; +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntSupplier; +import java.util.function.BooleanSupplier; + +/** Typed render/state-consumer adapter. Shared buffers use bootstrap types across class loaders. */ +public final class NotificationBlock implements Runnable, IntSupplier, BooleanSupplier { + private final Object[] owner; + private final float[] poses; + private final int[] command; + private final ArrayList pool = new ArrayList<>(); + private int savedCount; + private int firstRow; + private float lastFadeTop=Float.NaN, lastFadeBottom=Float.NaN; + + public NotificationBlock(Object[] owner, float[] poses, int[] command) { + this.owner = owner; + this.poses = poses; + this.command = command; + } + + private NotificationStackScrollLayout stack() { return (NotificationStackScrollLayout) owner[0]; } + private ArrayList children(NotificationStackScrollLayout stack) { + return stack.mStackScrollAlgorithm.mTempAlgorithmState.visibleChildren; + } + @Override public int getAsInt() { + NotificationStackScrollLayout stack = stack(); + ArrayList children = children(stack); + firstRow = firstVisibleRow(stack, children); + return children.size() - firstRow; + } + + private int firstVisibleRow(NotificationStackScrollLayout stack, ArrayList children) { + if (stack.mOwnScrollY <= 0) return 0; + float offset = stack.getTopPadding() - stack.mAmbientState.mStackY; + for (int i = 0; i < children.size(); i++) { + ExpandableView child = children.get(i); + ExpandableViewState state = child.mViewState; + if (state != null && !state.gone && state.mYTranslation + offset + child.mActualHeight > 0f) return i; + } + return Math.max(0, children.size() - 1); + } + @Override public boolean getAsBoolean() { return stack().mChildrenUpdateRequested; } + + @Override public void run() { + if (command[0] == 2) { restore(); return; } + NotificationStackScrollLayout stack = stack(); + if (command[0] == 0) render(stack); + else if (command[0] == 1) apply(stack); + else throw new IllegalArgumentException("Unknown notification command"); + } + + private int poseIndex(int row) { return Math.min(row, (poses.length - 1) / 3 - 1) * 3; } + private float root() { return poses[poses.length - 1]; } + + private void render(NotificationStackScrollLayout stack) { + if (stack.mChildrenUpdateRequested) return; + ArrayList children = children(stack); + float fadeTop = stack.mAmbientState.mBlurTopFadeoutEnd; + float fadeBottom = stack.mAmbientState.mBlurBottomFadeoutStart; + boolean fadeChanged = fadeTop != lastFadeTop || fadeBottom != lastFadeBottom; + float stackOffset = stack.getTopPadding() - stack.mAmbientState.mStackY + root(); + int viewport = stack.getHeight(); + for (int i = firstRow; i < children.size(); i++) { + ExpandableView child = children.get(i); + if (child.isPressed() || child.mustStayOnScreen() || child.mWillBeGone) continue; + ExpandableViewState state = child.mViewState; + if (state == null || state.gone || ViewState.isAnimating(child)) continue; + int p = poseIndex(i - firstRow); + float alpha = poses[p], scale = poses[p + 1]; + float y = state.mYTranslation + stackOffset + poses[p + 2]; + float previousY = child.getTranslationY(); + if (!onStack(y, child.mActualHeight, viewport) && !onStack(previousY, child.mActualHeight, viewport)) { + // Still below/above the stack: its pose cannot be seen. Each write invalidates the + // tree and syncs another RenderNode. The first on-stack frame writes it again. + if (child instanceof ExpandableNotificationRow && ((ExpandableNotificationRow) child).mIsFaded) + ((ExpandableNotificationRow) child).setNotificationFaded(false); + continue; + } + if (previousY != y) child.setTranslationY(y); + if (child.getScaleX() != scale) child.setScaleX(scale); + if (child.getScaleY() != scale) child.setScaleY(scale); + boolean hidden = state.hidden || alpha == 0f; + // Fading gives each card's icons/buttons their own hardware layers. Cards below the + // stack draw nothing, so creating and rendering their layers is pure GPU cost. + boolean nextFaded = !hidden && alpha != 1f && onStack(y, child.mActualHeight, viewport); + if (child instanceof ExpandableNotificationRow) { + ExpandableNotificationRow row = (ExpandableNotificationRow) child; + if (row.mIsFaded != nextFaded) row.setNotificationFaded(nextFaded); + } else { + int layer = nextFaded && child.hasOverlappingRendering() ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; + if (child.getLayerType() != layer) child.setLayerType(layer, null); + } + if (child.getAlpha() != alpha) child.setAlpha(alpha); + int visibility = hidden ? View.INVISIBLE : View.VISIBLE; + int previousVisibility = child.getVisibility(); + boolean becameVisible = visibility == View.VISIBLE && previousVisibility != View.VISIBLE; + if (previousVisibility != visibility) child.setVisibility(visibility); + // Do not update blur drawables for cards hidden by the distance/fade gate. On + // reentry a forced refresh also clears masks retained during invisible movement. + if (!hidden && (previousY != y || fadeChanged || becameVisible) && child instanceof ExpandableNotificationRow) + refreshGradient((ExpandableNotificationRow) child, previousY, y, fadeTop, fadeBottom, + fadeChanged, becameVisible, viewport); + } + lastFadeTop = fadeTop; + lastFadeBottom = fadeBottom; + } + + /** A full card of margin covers entrance scale; native layout passes refresh every card. */ + private static boolean onStack(float y, int height, int viewport) { + return viewport <= 0 || (y < viewport + height && y + 2f * height > 0f); + } + + private void refreshGradient(ExpandableNotificationRow row, float oldY, float y, float top, + float bottom, boolean changed, boolean force, int viewport) { + int height = row.mActualHeight; + // Cards below the stack cross the bottom fade band on every moving frame, yet draw + // nothing. With many notifications this was most of the render cost. A full card of + // margin covers entrance scale; native layout passes refresh every card's gradient. + if (!onStack(y, height, viewport)) return; + boolean wasEdge = changed && (Float.isNaN(lastFadeTop) || lastFadeTop <= 0f || lastFadeBottom <= 0f + || oldY < lastFadeTop || y < lastFadeTop || oldY + height > lastFadeBottom || y + height > lastFadeBottom); + if (height <= 0 || !(force || wasEdge || top <= 0f || bottom <= 0f || oldY < top || y < top + || oldY + height > bottom || y + height > bottom)) return; + row.updateBlurBackgroundGradient(); + List attached = row.getAttachedChildren(); + if (attached == null) return; + for (int i = 0; i < attached.size(); i++) { + ExpandableNotificationRow child = (ExpandableNotificationRow) attached.get(i); + if (child.getVisibility() == View.VISIBLE && child.mActualHeight > 0) + child.updateBlurBackgroundGradient(); + } + } + + private void apply(NotificationStackScrollLayout stack) { + if (savedCount != 0) throw new IllegalStateException("Nested notification state application"); + ArrayList children = children(stack); + float nativeStackY = stack.mAmbientState.mStackY; + float fullStackY = stack.getTopPadding(); + try { + for (int i = firstRow; i < children.size(); i++) { + ExpandableView child = children.get(i); + if (child.isPressed() || child.mustStayOnScreen()) continue; + ExpandableViewState state = child.mViewState; + if (state == null) continue; + if (savedCount == pool.size()) pool.add(new Saved()); + Saved saved = pool.get(savedCount); + saved.capture(state); + savedCount++; + int p = poseIndex(i - firstRow); + // Keep the original expression order for float-identical compensation. + state.mYTranslation = saved.y + fullStackY - nativeStackY + root() + poses[p + 2]; + state.mScaleX = poses[p + 1]; + state.mScaleY = poses[p + 1]; + state.mAlpha = poses[p]; + } + } catch (Throwable failure) { + restore(); + throw failure; + } + } + + private void restore() { + for (int i = 0; i < savedCount; i++) { + Saved saved = pool.get(i); + ExpandableViewState state = saved.target; + state.mYTranslation = saved.y; + state.mScaleX = saved.sx; + state.mScaleY = saved.sy; + state.mAlpha = saved.alpha; + saved.target = null; + } + savedCount = 0; + } + + private static final class Saved { + // Package constructor avoids a synthetic D8 nest-access marker class. + Saved() {} + ExpandableViewState target; + float y, sx, sy, alpha; + void capture(ExpandableViewState state) { + y = state.mYTranslation; + sx = state.mScaleX; + sy = state.mScaleY; + alpha = state.mAlpha; + target = state; + } + } +} diff --git a/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/Probe.java b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/Probe.java new file mode 100644 index 00000000..9e885a26 --- /dev/null +++ b/cm-native-bridge/src/main/java/dev/colormotion/nativebridge/Probe.java @@ -0,0 +1,17 @@ +package dev.colormotion.nativebridge; + +import androidx.compose.ui.graphics.ReusableGraphicsLayerScope; + +/** Cold binding check before any bridge is handed to Compose; failure selects reflective binding. */ +public final class Probe { + public static void verify(Object state) { + ReusableGraphicsLayerScope scope = new ReusableGraphicsLayerScope(); + float[] pose = {0.6f, 0.8f, 24f}; + LayerBlock block = new LayerBlock(state, pose); + block.invoke(scope); + if (scope.alpha != pose[0] || scope.scaleX != pose[1] || scope.scaleY != pose[1] + || scope.translationY != pose[2] || scope.compositingStrategy != 2 + || (scope.mutatedFields & 32791) != 32791) throw new IllegalStateException("Layer ABI mismatch"); + new LayerBatch(new Runnable[] {block}, new int[] {1}).run(); + } +} diff --git a/common/src/main/java/io/github/soclear/oneuix/common/Preference.kt b/common/src/main/java/io/github/soclear/oneuix/common/Preference.kt index c0038cde..efe2c211 100644 --- a/common/src/main/java/io/github/soclear/oneuix/common/Preference.kt +++ b/common/src/main/java/io/github/soclear/oneuix/common/Preference.kt @@ -139,6 +139,7 @@ data class Preference( val showTraditionalChineseDateOnQS: Boolean = false, val modifyQSClockTextSize: Boolean = false, val qsClockTextSize: Float = 32f, + val colorMotionAnimation: Boolean = false, ) @Serializable diff --git a/hook/build.gradle.kts b/hook/build.gradle.kts index 119b6f0a..a6ff2ed2 100644 --- a/hook/build.gradle.kts +++ b/hook/build.gradle.kts @@ -18,6 +18,11 @@ android { } } + // ColorMotion's typed bridge dex is built by :cm-native-bridge and shipped as an asset. + sourceSets.getByName("main").assets.directories.add( + project(":cm-native-bridge").layout.buildDirectory.dir("assets").get().asFile.absolutePath + ) + externalNativeBuild { cmake { path = file("src/main/c/CMakeLists.txt") @@ -40,3 +45,5 @@ dependencies { compileOnly(libs.libxposed.api) compileOnly(project(":stub")) } + +tasks.named("preBuild") { dependsOn(":cm-native-bridge:bridgeAssets") } diff --git a/hook/src/main/java/de/robv/android/xposed/XC_MethodHook.java b/hook/src/main/java/de/robv/android/xposed/XC_MethodHook.java new file mode 100644 index 00000000..cb2bdc61 --- /dev/null +++ b/hook/src/main/java/de/robv/android/xposed/XC_MethodHook.java @@ -0,0 +1,112 @@ +package de.robv.android.xposed; + +import java.lang.reflect.Member; +import java.util.HashMap; + +/** + * Minimal subset of the legacy (API 82) callback type, implemented on top of libxposed by + * {@link XposedBridge}. It exists so ColorMotion's hooks can run unchanged inside OneUIX. + */ +public abstract class XC_MethodHook { + public XC_MethodHook() { } + + protected void beforeHookedMethod(MethodHookParam param) throws Throwable { } + + protected void afterHookedMethod(MethodHookParam param) throws Throwable { } + + void callBefore(MethodHookParam param) throws Throwable { + beforeHookedMethod(param); + } + + void callAfter(MethodHookParam param) throws Throwable { + afterHookedMethod(param); + } + + public static class MethodHookParam { + public Member method; + public Object thisObject; + public Object[] args; + + private Object result; + private Throwable throwable; + boolean returnEarly; + private HashMap extras; + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + this.throwable = null; + this.returnEarly = true; + } + + public Throwable getThrowable() { + return throwable; + } + + public boolean hasThrowable() { + return throwable != null; + } + + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + this.result = null; + this.returnEarly = true; + } + + public Object getResultOrThrowable() throws Throwable { + if (throwable != null) throw throwable; + return result; + } + + public Object getObjectExtra(String key) { + return extras == null ? null : extras.get(key); + } + + public void setObjectExtra(String key, Object value) { + if (extras == null) extras = new HashMap<>(); + extras.put(key, value); + } + + /** Result of the original method; unlike setResult it does not skip anything. */ + void setOriginalResult(Object result) { + this.result = result; + this.throwable = null; + } + + void setOriginalThrowable(Throwable throwable) { + this.throwable = throwable; + this.result = null; + } + + void resetEarlyReturn() { + this.result = null; + this.throwable = null; + this.returnEarly = false; + } + } + + /** Handle for one registered hook; unhooking turns the hook into a pass-through. */ + public final class Unhook { + private final Member hookedMethod; + volatile boolean disabled; + + Unhook(Member hookedMethod) { + this.hookedMethod = hookedMethod; + } + + public Member getHookedMethod() { + return hookedMethod; + } + + public XC_MethodHook getCallback() { + return XC_MethodHook.this; + } + + public void unhook() { + disabled = true; + } + } +} diff --git a/hook/src/main/java/de/robv/android/xposed/XposedBridge.java b/hook/src/main/java/de/robv/android/xposed/XposedBridge.java new file mode 100644 index 00000000..2a7c71e5 --- /dev/null +++ b/hook/src/main/java/de/robv/android/xposed/XposedBridge.java @@ -0,0 +1,93 @@ +package de.robv.android.xposed; + +import android.util.Log; + +import java.lang.reflect.Executable; +import java.lang.reflect.Member; + +import io.github.libxposed.api.XposedModule; + +/** + * Legacy-API facade over libxposed. Only what ColorMotion needs is implemented: + * hookMethod with before/after callbacks, and logging. + */ +public final class XposedBridge { + private static volatile XposedModule module; + + private XposedBridge() { } + + /** Called once by the module entry before any hook is installed. */ + public static void init(XposedModule xposedModule) { + module = xposedModule; + } + + public static void log(String text) { + XposedModule m = module; + // A null tag lets the framework pick the default tag its log filter accepts. + if (m != null) m.log(Log.INFO, null, text); + } + + public static void log(Throwable throwable) { + XposedModule m = module; + if (m != null) m.log(Log.ERROR, null, "ColorMotion: unexpected exception", throwable); + } + + public static XC_MethodHook.Unhook hookMethod(Member hookMethod, XC_MethodHook callback) { + XposedModule m = module; + if (m == null) throw new IllegalStateException("XposedBridge.init was not called"); + if (!(hookMethod instanceof Executable)) { + throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod); + } + final Executable executable = (Executable) hookMethod; + final XC_MethodHook.Unhook unhook = callback.new Unhook(hookMethod); + + m.hook(executable).intercept(chain -> { + if (unhook.disabled) { + try { + return chain.proceed(); + } catch (Throwable t) { + throw sneakyThrow(t); + } + } + + XC_MethodHook.MethodHookParam param = new XC_MethodHook.MethodHookParam(); + param.method = executable; + param.thisObject = chain.getThisObject(); + param.args = chain.getArgs().toArray(); + + try { + callback.callBefore(param); + } catch (Throwable t) { + log(t); + param.resetEarlyReturn(); + } + + if (!param.returnEarly) { + try { + param.setOriginalResult(chain.proceed(param.args)); + } catch (Throwable t) { + param.setOriginalThrowable(t); + } + } + + Object previousResult = param.getResult(); + Throwable previousThrowable = param.getThrowable(); + try { + callback.callAfter(param); + } catch (Throwable t) { + log(t); + if (previousThrowable != null) param.setOriginalThrowable(previousThrowable); + else param.setOriginalResult(previousResult); + } + + if (param.hasThrowable()) throw sneakyThrow(param.getThrowable()); + return param.getResult(); + }); + return unhook; + } + + @SuppressWarnings("unchecked") + private static T sneakyThrow(Throwable t) throws T { + throw (T) t; + } +} diff --git a/hook/src/main/java/de/robv/android/xposed/XposedHelpers.java b/hook/src/main/java/de/robv/android/xposed/XposedHelpers.java new file mode 100644 index 00000000..068fa235 --- /dev/null +++ b/hook/src/main/java/de/robv/android/xposed/XposedHelpers.java @@ -0,0 +1,153 @@ +package de.robv.android.xposed; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** Reflection helpers with the legacy semantics ColorMotion relies on. */ +public final class XposedHelpers { + private XposedHelpers() { } + + public static final class ClassNotFoundError extends Error { + public ClassNotFoundError(Throwable cause) { + super(cause); + } + } + + public static final class InvocationTargetError extends Error { + public InvocationTargetError(Throwable cause) { + super(cause); + } + } + + public static Class findClass(String className, ClassLoader classLoader) { + try { + return Class.forName(className, false, + classLoader != null ? classLoader : XposedHelpers.class.getClassLoader()); + } catch (ClassNotFoundException e) { + throw new ClassNotFoundError(e); + } + } + + public static Field findField(Class clazz, String fieldName) { + for (Class c = clazz; c != null; c = c.getSuperclass()) { + try { + Field field = c.getDeclaredField(fieldName); + field.setAccessible(true); + return field; + } catch (NoSuchFieldException ignored) { + // keep looking in the superclass + } + } + throw new NoSuchFieldError(clazz.getName() + "#" + fieldName); + } + + public static Object getObjectField(Object obj, String fieldName) { + try { + return findField(obj.getClass(), fieldName).get(obj); + } catch (IllegalAccessException e) { + throw new IllegalAccessError(e.getMessage()); + } + } + + public static Object getStaticObjectField(Class clazz, String fieldName) { + try { + return findField(clazz, fieldName).get(null); + } catch (IllegalAccessException e) { + throw new IllegalAccessError(e.getMessage()); + } + } + + public static Method findMethodExact(Class clazz, String methodName, Object... parameterTypes) { + Class[] types = new Class[parameterTypes.length]; + for (int i = 0; i < types.length; i++) { + Object type = parameterTypes[i]; + types[i] = type instanceof Class ? (Class) type + : findClass((String) type, clazz.getClassLoader()); + } + for (Class c = clazz; c != null; c = c.getSuperclass()) { + try { + Method method = c.getDeclaredMethod(methodName, types); + method.setAccessible(true); + return method; + } catch (NoSuchMethodException ignored) { + // keep looking in the superclass + } + } + throw new NoSuchMethodError(clazz.getName() + "#" + methodName); + } + + public static Method findMethodExact(String className, ClassLoader classLoader, String methodName, + Object... parameterTypes) { + return findMethodExact(findClass(className, classLoader), methodName, parameterTypes); + } + + public static Object callMethod(Object obj, String methodName, Object... args) { + return invoke(obj.getClass(), obj, methodName, args); + } + + public static Object callStaticMethod(Class clazz, String methodName, Object... args) { + return invoke(clazz, null, methodName, args); + } + + private static Object invoke(Class clazz, Object receiver, String methodName, Object[] args) { + Method method = findBestMethod(clazz, methodName, args); + try { + return method.invoke(receiver, args); + } catch (InvocationTargetException e) { + throw new InvocationTargetError(e.getCause()); + } catch (IllegalAccessException e) { + throw new IllegalAccessError(e.getMessage()); + } + } + + /** Same-arity method whose parameters accept the runtime arguments, closest types first. */ + private static Method findBestMethod(Class clazz, String name, Object[] args) { + Method best = null; + long bestScore = Long.MAX_VALUE; + for (Class c = clazz; c != null; c = c.getSuperclass()) { + for (Method method : c.getDeclaredMethods()) { + if (!method.getName().equals(name) || method.getParameterCount() != args.length) continue; + long score = score(method.getParameterTypes(), args); + if (score >= 0 && score < bestScore) { + best = method; + bestScore = score; + } + } + if (best != null) break; + } + if (best == null) throw new NoSuchMethodError(clazz.getName() + "#" + name); + best.setAccessible(true); + return best; + } + + private static long score(Class[] parameters, Object[] args) { + long total = 0; + for (int i = 0; i < parameters.length; i++) { + Class parameter = box(parameters[i]); + Object arg = args[i]; + if (arg == null) { + if (parameters[i].isPrimitive()) return -1; + continue; + } + if (!parameter.isInstance(arg)) return -1; + int distance = 0; + for (Class c = arg.getClass(); c != null && c != parameter; c = c.getSuperclass()) distance++; + total += distance; + } + return total; + } + + private static Class box(Class type) { + if (!type.isPrimitive()) return type; + if (type == int.class) return Integer.class; + if (type == long.class) return Long.class; + if (type == float.class) return Float.class; + if (type == double.class) return Double.class; + if (type == boolean.class) return Boolean.class; + if (type == byte.class) return Byte.class; + if (type == short.class) return Short.class; + if (type == char.class) return Character.class; + return type; + } +} diff --git a/hook/src/main/java/dev/colormotion/BlurFrameBinding.java b/hook/src/main/java/dev/colormotion/BlurFrameBinding.java new file mode 100644 index 00000000..cca0a582 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/BlurFrameBinding.java @@ -0,0 +1,62 @@ +package dev.colormotion; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedHelpers; + +/** Use Samsung's full frame operation on either legacy or refactored blur controllers. */ +final class BlurFrameBinding { + private static final Object[] NO_ARGS = new Object[0]; + final Method frame; + final Object skippedResult; + private final Field callback; + private final Method boundReceiver; + private final Object[] args = new Object[1]; + private Object lastCallback, lastController; + + BlurFrameBinding(Class controller, ClassLoader cl) throws ReflectiveOperationException { + Method legacy; + try { legacy = controller.getDeclaredMethod("access$doFrame", controller); } + catch (NoSuchMethodException absent) { legacy = null; } + if (legacy != null) { + frame = legacy; + callback = null; + boundReceiver = null; + skippedResult = null; + } else { + callback = controller.getField("updateBlurCallback"); + Class implementation = XposedHelpers.findClass(controller.getName() + "$updateBlurCallback$1", cl); + frame = implementation.getDeclaredMethod("invoke", Object.class); + boundReceiver = implementation.getMethod("getBoundReceiver"); + boundReceiver.setAccessible(true); + Class unit = XposedHelpers.findClass("kotlin.Unit", cl); + skippedResult = unit.getField("INSTANCE").get(null); + callback.setAccessible(true); + } + frame.setAccessible(true); + } + + Object controller(XC_MethodHook.MethodHookParam param) throws ReflectiveOperationException { + if (callback == null) return param.args[0]; + // Kotlin function references have an immutable receiver. Native rescheduling reuses + // the same reference; a new controller/reference must resolve its own receiver. + if (param.thisObject != lastCallback) { + Object receiver = boundReceiver.invoke(param.thisObject, NO_ARGS); + lastCallback = param.thisObject; + lastController = receiver; + } + return lastController; + } + + void request(Object controller) throws ReflectiveOperationException { + if (callback == null) { + args[0] = controller; + try { frame.invoke(null, args); } + finally { args[0] = null; } + } else { + args[0] = Long.valueOf(0L); + frame.invoke(callback.get(controller), args); + } + } +} diff --git a/hook/src/main/java/dev/colormotion/BlurFrameGate.java b/hook/src/main/java/dev/colormotion/BlurFrameGate.java new file mode 100644 index 00000000..6944cf89 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/BlurFrameGate.java @@ -0,0 +1,26 @@ +package dev.colormotion; + +/** Suppresses duplicate native/custom submissions within one frame, never a later native update. */ +final class BlurFrameGate { + private Object owner; + private float value = Float.NaN; + private long frame = Long.MIN_VALUE; + + void beginFrame(long frameTimeNanos) { + if (frame != frameTimeNanos) reset(); + frame = frameTimeNanos; + } + + boolean shouldApply(Object controller, float next) { + if (owner == controller && value == next) return false; + owner = controller; + value = next; + return true; + } + + void reset() { + owner = null; + value = Float.NaN; + frame = Long.MIN_VALUE; + } +} diff --git a/hook/src/main/java/dev/colormotion/ColorOsParams.java b/hook/src/main/java/dev/colormotion/ColorOsParams.java new file mode 100644 index 00000000..2ea54cd9 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/ColorOsParams.java @@ -0,0 +1,82 @@ +package dev.colormotion; + +/** + * Motion constants of the reference SystemUI build (PLK110_17.0.0.105, CN). + * Device tier for that build: persist.sys.oplus.anim_level=1 (my_product/build.prop), so + * ScrimUtil.isHighGaussianLevel() is true and PlatformBlurManagerImpl.useMotionBlur() is true; + * NotificationStackScrollLayoutExtImpl therefore picks Config.LEGACY_SCALE_ONLY. + */ +final class ColorOsParams { + private ColorOsParams() {} + + // ---- Notification shade (com.oplus.systemui.panelanimation.OplusPanelAnimationExImpl) ---- + + /** R.dimen.separate_distance_range; getAdjustExpandedHeight: min(d * max / range, max - 1). */ + static final float SHADE_DISTANCE_RANGE_DP = 100f; + /** PanelExpandedFraction drag stiffness: responseToStiffness(0.2f) (Lambda0 case 2). */ + static final float SHADE_DRAG_RESPONSE = 0.2f; + /** PanelExpandedFraction.expandedTo(): separate mode -> stiffness 400, damping 1. */ + static final float SHADE_FLING_STIFFNESS = 400f; + /** PanelExpandedFraction springs use SpringForce().setDampingRatio(1.0f); minimumVisibleChange 0.001. */ + static final float FRACTION_MIN_VISIBLE_CHANGE = 0.001f; + + /** PanelTranslationYValue: responseToStiffness(useMotionBlur ? 0.4f : 0.3f). */ + static final float SHADE_TRANSLATION_RESPONSE = 0.4f; + /** updatePanelTranslationY (separate mode): fraction / 0.86. */ + static final float SHADE_TRANSLATION_FRACTION_END = 0.86f; + /** animateToFinalPosition (separate mode): damping = 1 - 0.4 * clamp(vel, 0, 10000) / 10000. */ + static final float SHADE_TRANSLATION_VEL_DAMPING = 0.4f; + static final float SHADE_TRANSLATION_VEL_MAX = 10000f; + /** PanelTranslationYValue setMinimumVisibleChange(0.1f). */ + static final float SHADE_TRANSLATION_MIN_VISIBLE_CHANGE = 0.1f; + /** R.dimen.notification_center_header_top_margin, used when the header geometry is unknown. */ + static final float SHADE_TRANSLATION_FALLBACK_DP = 34f; + + /** updateElementShowing: element shows at 0.86, or 0.2 with isQuicklyElementShow. */ + static final float SHADE_ELEMENT_SHOW = 0.86f; + static final float SHADE_ELEMENT_SHOW_QUICK = 0.2f; + + // NsslAnimParams.legacyScaleOnly(): (1, 0, 0, 0, 0, 1, 0.9, 0.3, 0.2, 0.16, 0.16, 1, 0.002) + static final float NSSL_HIDE_SCALE = 0.9f; + static final float NSSL_SCALE_SHOW_RESPONSE = 0.3f; + static final float NSSL_SCALE_HIDE_RESPONSE = 0.2f; + static final float NSSL_SCALE_SHOW_BOUNCE = 0.16f; + static final float NSSL_SCALE_HIDE_BOUNCE = 0.16f; + static final float NSSL_MIN_VISIBLE_CHANGE = 0.002f; + /** NotificationStackScrollLayoutExtImpl.updatePivot(): pivotY -600 without alpha animation. */ + static final float NSSL_PIVOT_Y = -600f; + + // ---- Control center (com.oplus.systemui.plugins.qs.animator) ---- + + /** OplusQSRootViewComponent touch move: f3 = rawY * (engine / 300) + start. */ + static final float QS_DRAG_PX_FOR_FULL = 300f; + /** QSPanelExpandFraction: drag response 0.2, fast-start response 0.35 (maxFastResponse). */ + static final float QS_DRAG_RESPONSE = 0.2f; + static final float QS_MAX_FAST_RESPONSE = 0.35f; + /** onFling: expand 0.2, collapse getRawHideResponse() = 0.3; fast expand 0.45 (maxFastBlurResponse). */ + static final float QS_FLING_EXPAND_RESPONSE = 0.2f; + static final float QS_FLING_COLLAPSE_RESPONSE = 0.3f; + static final float QS_FLING_FAST_RESPONSE = 0.45f; + static final float QS_FAST_VELOCITY = 1000f; + static final float QS_FAST_FRACTION_RANGE = 0.2f; + + /** QSPanelTranslationY: destTranslationY default 102f, response 0.35, bounce 0.15, maxResponse 0.45. */ + static final float QS_DEST_TRANSLATION_PX = 102f; + static final float QS_TRANSLATION_RESPONSE = 0.35f; + static final float QS_TRANSLATION_BOUNCE = 0.15f; + static final float QS_TRANSLATION_MAX_RESPONSE = 0.45f; + static final float QS_TRANSLATION_MIN_VISIBLE_CHANGE = 1f; + /** getDefaultSettingEngine(): dest / 0.86. */ + static final float QS_ENGINE_DIVISOR = 0.86f; + + /** QSPanelExpandFraction.onFractionChanged thresholds. */ + static final float QS_SECOND_ELEMENT = 0.86f; + static final float QS_FAST_ELEMENT = 0.2f; + + /** setSecondElementVisible, node 0: scale from 0.8, response 0.3, bounce 0.25; alpha 0.35 / 0.2. */ + static final float QS_ELEMENT_HIDE_SCALE = 0.8f; + static final float QS_ELEMENT_SCALE_RESPONSE = 0.3f; + static final float QS_ELEMENT_SCALE_BOUNCE = 0.25f; + static final float QS_ELEMENT_ALPHA_SHOW_RESPONSE = 0.35f; + static final float QS_ELEMENT_ALPHA_HIDE_RESPONSE = 0.2f; +} diff --git a/hook/src/main/java/dev/colormotion/EdgeFadeMask.java b/hook/src/main/java/dev/colormotion/EdgeFadeMask.java new file mode 100644 index 00000000..dd1e95fb --- /dev/null +++ b/hook/src/main/java/dev/colormotion/EdgeFadeMask.java @@ -0,0 +1,32 @@ +package dev.colormotion; + +/** A continuous notification edge mask, transparent everywhere above/below its fade bands. */ +final class EdgeFadeMask { + final int[] colors; + final float[] positions; + + EdgeFadeMask(int height, int topStart, int topEnd, int bottomStart) { + float h = Math.max(1, height); + float[] points = new float[13]; + int count = 0; + points[count++] = 0f; + for (int i = 0; i <= 4; i++) points[count++] = QsModel.clamp( + (topStart + (topEnd - topStart) * i / 4f) / h, 0f, 1f); + for (int i = 0; i <= 4; i++) points[count++] = QsModel.clamp( + (bottomStart + (h - bottomStart) * i / 4f) / h, 0f, 1f); + points[count++] = 1f; + java.util.Arrays.sort(points, 0, count); + int unique = 0; + for (int i = 0; i < count; i++) + if (unique == 0 || points[i] > points[unique - 1]) points[unique++] = points[i]; + positions = java.util.Arrays.copyOf(points, unique); + colors = new int[unique]; + for (int i = 0; i < unique; i++) { + float y = positions[i] * h; + float top = QsModel.clamp((y - topStart) / Math.max(1f, topEnd - topStart), 0f, 1f); + float bottom = QsModel.clamp((h - y) / Math.max(1f, h - bottomStart), 0f, 1f); + int alpha = Math.round(255f * (float) (Math.pow(top, 2.5) * Math.pow(bottom, 2.5))); + colors[i] = alpha << 24; + } + } +} diff --git a/hook/src/main/java/dev/colormotion/Entry.java b/hook/src/main/java/dev/colormotion/Entry.java new file mode 100644 index 00000000..f9b17dde --- /dev/null +++ b/hook/src/main/java/dev/colormotion/Entry.java @@ -0,0 +1,27 @@ +package dev.colormotion; + +import de.robv.android.xposed.XposedBridge; + +/** + * Entry point used by OneUIX. The original ColorMotion module started from an + * IXposedHookLoadPackage; OneUIX owns the module entry and calls {@link #install} for SystemUI. + */ +public final class Entry { + static final String TAG = "ColorMotion"; + + private static boolean installed; + + private Entry() { } + + public static synchronized void install(ClassLoader systemUiLoader) { + if (installed) return; + installed = true; + try { + new ShadeMotion(systemUiLoader).install(); + XposedBridge.log(TAG + ": hooks installed"); + } catch (Throwable t) { + XposedBridge.log(TAG + ": install failed"); + XposedBridge.log(t); + } + } +} diff --git a/hook/src/main/java/dev/colormotion/FlingCurve.java b/hook/src/main/java/dev/colormotion/FlingCurve.java new file mode 100644 index 00000000..d840d103 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/FlingCurve.java @@ -0,0 +1,116 @@ +package dev.colormotion; + +import android.animation.TimeInterpolator; + +/** + * Pre-simulated spring trajectory used to drive Samsung's own fling ValueAnimator, so its + * listeners and end callbacks keep working while the motion follows the ColorOS spring. + */ +final class FlingCurve implements TimeInterpolator { + interface ResponseSchedule { + /** Returns the spring response (seconds) to use at the given fraction. */ + float responseAt(float fraction); + } + + private static final int MAX_MS = 4000; + + /** One UI-thread workspace; completed curves own copies and survive later simulations. */ + static final class Workspace { + final float[] positions = new float[MAX_MS + 1]; + final float[] velocities = new float[MAX_MS + 1]; + } + + final long durationMs; + private final float[] samples; + private final float start; + private final float end; + private final float[] velocities; + // UI-thread phase of the last successful interpolation, in model milliseconds. + private float sampledMs; + + private FlingCurve(float[] samples, float[] velocities, float start, float end) { + this.samples = samples; + this.velocities = velocities; + this.start = start; + this.end = end; + this.durationMs = samples.length - 1; + } + + static FlingCurve simulate(float x0, float v0, float target, ResponseSchedule schedule, + float minVisibleChange) { + return simulate(x0, v0, target, schedule, minVisibleChange, new Workspace()); + } + + static FlingCurve simulate(float x0, float v0, float target, ResponseSchedule schedule, + float minVisibleChange, Workspace workspace) { + Spring s = new Spring().damping(1.0).minimumVisibleChange(minVisibleChange); + s.value = x0; + s.velocity = v0; + s.target = target; + float[] buf = workspace.positions; + float[] vel = workspace.velocities; + buf[0] = x0; + vel[0] = v0; + int n = 0; + while (n < MAX_MS) { + s.response(schedule.responseAt(s.value)); + boolean done = s.step(1); + n++; + buf[n] = s.value; + vel[n] = s.velocity; + if (done) { + break; + } + } + float[] out = new float[n + 1]; + float[] outV = new float[n + 1]; + System.arraycopy(buf, 0, out, 0, n + 1); + System.arraycopy(vel, 0, outV, 0, n + 1); + out[n] = target; + return new FlingCurve(out, outV, x0, target); + } + + /** Spring value at elapsed milliseconds. */ + float valueAt(long ms) { + if (ms <= 0) return samples[0]; + if (ms >= durationMs) return samples[samples.length - 1]; + return samples[(int) ms]; + } + + float velocityAt(long ms) { + if (ms <= 0) return velocities[0]; + if (ms >= durationMs) return 0f; + return velocities[(int) ms]; + } + + /** Tangent at the last evaluated native pose, in fraction per model second. */ + float velocityAtLastSample() { + // Equal endpoints always produce the constant interpolation 1, even with initial momentum. + if (end == start || sampledMs >= durationMs) return 0f; + if (sampledMs <= 0f) return velocities[0]; + int i = (int) sampledMs; + float f = sampledMs - i; + return velocities[i] + (velocities[i + 1] - velocities[i]) * f; + } + + @Override + public float getInterpolation(float input) { + if (end == start) { + return 1f; + } + float pos = input * durationMs; + int i = (int) pos; + float x; + if (i >= samples.length - 1) { + x = samples[samples.length - 1]; + } else { + float f = pos - i; + x = samples[i] + (samples[i + 1] - samples[i]) * f; + } + float result = (x - start) / (end - start); + // Publish only after evaluation succeeds. Keep the interpolation's existing output and + // failure behavior; NaN is not a usable pose, and endpoint/extrapolated phases are bounded. + if (!Float.isNaN(result)) sampledMs = Math.max(0f, Math.min(pos, durationMs)); + return result; + } +} diff --git a/hook/src/main/java/dev/colormotion/FrameClock.java b/hook/src/main/java/dev/colormotion/FrameClock.java new file mode 100644 index 00000000..6a8a4233 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/FrameClock.java @@ -0,0 +1,53 @@ +package dev.colormotion; + +/** Accumulates fractional, duration-scaled milliseconds without advancing across an idle reset. */ +final class FrameClock { + static final long DISABLED_ANIMATION_MS = 100_000L; + private boolean started; + private long lastFrameNanos; + // Pending animation time, already scaled. A scale change only affects its new interval. + private double remainderNanos; + + boolean isStarted() { return started; } + + void reset() { + started = false; + remainderNanos = 0; + } + + void start(long frameTimeNanos) { + reset(); + started = true; + lastFrameNanos = frameTimeNanos; + } + + /** First call establishes the timestamp; zero duration scale completes model animations. */ + long advance(long frameTimeNanos, float durationScale) { + long elapsed = started ? frameTimeNanos - lastFrameNanos : 0L; + if (!started) start(frameTimeNanos); + else lastFrameNanos = frameTimeNanos; + if (!(durationScale > 0f) || !Float.isFinite(durationScale)) { + remainderNanos = 0; + return DISABLED_ANIMATION_MS; + } + if (elapsed < 0L) { + // A new timestamp domain needs a fresh baseline, just like explicit readiness. + remainderNanos = 0; + return 0L; + } + double nanos = elapsed / (double) durationScale + remainderNanos; + if (nanos / 1_000_000.0 >= Long.MAX_VALUE) { + remainderNanos = 0; + return Long.MAX_VALUE; + } + long millis = (long) (nanos / 1_000_000.0); + remainderNanos = nanos - millis * 1_000_000.0; + // Division by scales such as 10 can leave an integer boundary a few double + // ulps short. Normalize within one picosecond, below timestamp resolution. + if (1_000_000.0 - remainderNanos <= 0.001) { + millis++; + remainderNanos = 0; + } + return millis; + } +} diff --git a/hook/src/main/java/dev/colormotion/HookSet.java b/hook/src/main/java/dev/colormotion/HookSet.java new file mode 100644 index 00000000..d2f81f4f --- /dev/null +++ b/hook/src/main/java/dev/colormotion/HookSet.java @@ -0,0 +1,50 @@ +package dev.colormotion; + +import java.lang.reflect.Member; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** A failed compatibility binding must not leave half an animation pipeline installed. */ +final class HookSet { + private final ArrayList installed = new ArrayList<>(); + + XC_MethodHook.Unhook method(Member member, XC_MethodHook callback) { + XC_MethodHook.Unhook hook = XposedBridge.hookMethod(member, callback); + if (hook == null) throw new IllegalStateException("Native hook registration failed: " + member); + installed.add(hook); + return hook; + } + + void findAndHookMethod(Class owner, String name, Object... parameters) { + Class[] types = new Class[parameters.length - 1]; + for (int i = 0; i < types.length; i++) types[i] = (Class) parameters[i]; + method(XposedHelpers.findMethodExact(owner, name, (Object[]) types), + (XC_MethodHook) parameters[parameters.length - 1]); + } + + void findAndHookMethod(String owner, ClassLoader loader, String name, Object... parameters) { + findAndHookMethod(XposedHelpers.findClass(owner, loader), name, parameters); + } + + Set hookAllMethods(Class owner, String name, XC_MethodHook callback) { + Set result = new HashSet<>(); + // Record each handle immediately; a later overload can throw or return null. + for (Member member : owner.getDeclaredMethods()) { + if (member.getName().equals(name)) result.add(method(member, callback)); + } + return result; + } + + void rollback() { + for (int i = installed.size() - 1; i >= 0; i--) { + XC_MethodHook.Unhook hook = installed.get(i); + try { if (hook != null) hook.unhook(); } + catch (Throwable failure) { XposedBridge.log("ColorMotion: hook removal failed: " + failure); } + } + installed.clear(); + } +} diff --git a/hook/src/main/java/dev/colormotion/MotionPose.java b/hook/src/main/java/dev/colormotion/MotionPose.java new file mode 100644 index 00000000..f6af93f0 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/MotionPose.java @@ -0,0 +1,14 @@ +package dev.colormotion; + +/** Last pose published to a rendering layer. Invisible changes can wait until the reveal. */ +final class MotionPose { + private float alpha = Float.NaN, scale, y; + + boolean update(float nextAlpha, float nextScale, float nextY) { + if (alpha == nextAlpha && (nextAlpha == 0f || (scale == nextScale && y == nextY))) return false; + alpha = nextAlpha; + scale = nextScale; + y = nextY; + return true; + } +} diff --git a/hook/src/main/java/dev/colormotion/NativeLayers.java b/hook/src/main/java/dev/colormotion/NativeLayers.java new file mode 100644 index 00000000..a6c86d1a --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NativeLayers.java @@ -0,0 +1,47 @@ +package dev.colormotion; + +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.nio.ByteBuffer; + +import dalvik.system.InMemoryDexClassLoader; + +/** Loads the small typed bridge against SystemUI's classes, without bundling its Kotlin/Compose. */ +final class NativeLayers { + private final Constructor layer, batch; + private final ClassLoader loader; + + private NativeLayers(ClassLoader loader) throws ReflectiveOperationException { + this.loader = loader; + layer = loader.loadClass("dev.colormotion.nativebridge.LayerBlock") + .getConstructor(Object.class, float[].class); + batch = loader.loadClass("dev.colormotion.nativebridge.LayerBatch") + .getConstructor(Runnable[].class, int[].class); + } + + static NativeLayers load(ClassLoader systemUi, Object probeState) throws Exception { + byte[] code; + try (InputStream in = NativeLayers.class.getClassLoader() + .getResourceAsStream("assets/colormotion-native.dex")) { + if (in == null) throw new IllegalStateException("Native layer asset missing"); + code = in.readAllBytes(); + } + ClassLoader loader = new InMemoryDexClassLoader(ByteBuffer.wrap(code), systemUi); + loader.loadClass("dev.colormotion.nativebridge.Probe").getMethod("verify", Object.class) + .invoke(null, probeState); + return new NativeLayers(loader); + } + + Object layer(Object state, float[] pose) throws ReflectiveOperationException { + return layer.newInstance(state, pose); + } + + Runnable batch(Runnable[] pending, int[] count) throws ReflectiveOperationException { + return (Runnable) batch.newInstance(pending, count); + } + + Runnable notifications(Object[] stack, float[] poses, int[] command) throws ReflectiveOperationException { + return (Runnable) loader.loadClass("dev.colormotion.nativebridge.NotificationBlock") + .getConstructor(Object[].class, float[].class, int[].class).newInstance(stack, poses, command); + } +} diff --git a/hook/src/main/java/dev/colormotion/NativeNotifications.java b/hook/src/main/java/dev/colormotion/NativeNotifications.java new file mode 100644 index 00000000..3373a6dd --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NativeNotifications.java @@ -0,0 +1,78 @@ +package dev.colormotion; + +import java.util.function.IntSupplier; +import java.util.function.BooleanSupplier; + +/** Bootstrap-only connection to the typed notification adapter, with reused pose/command buffers. */ +final class NativeNotifications { + private final QsModel model; + private final Object[] stack = new Object[1]; + private final float[] poses = new float[QsModel.MAX_ROWS * 3 + 1]; + private final int[] command = new int[1]; + private final Runnable driver; + private final IntSupplier count; + private final BooleanSupplier layoutPending; + private boolean applied; + + NativeNotifications(NativeLayers bindings, QsModel model) throws ReflectiveOperationException { + this.model = model; + driver = bindings.notifications(stack, poses, command); + count = (IntSupplier) driver; + layoutPending = (BooleanSupplier) driver; + } + + void prepare(Object owner) { + stack[0] = owner; + try { model.setRowCount(count.getAsInt()); } + finally { stack[0] = null; } + } + + private void updatePoses() { + for (int row = 0; row < model.rowCount; row++) { + int p = row * 3; + poses[p] = model.rowAlpha(row); + poses[p + 1] = model.scale[row].value; + poses[p + 2] = model.rowTranslation(row); + } + poses[poses.length - 1] = model.translation.value; + } + + void render(Object owner) { + render(owner, false); + } + + /** See NotificationRows.renderPrepared: prepare and render share one synchronous frame. */ + void renderPrepared(Object owner) { + render(owner, true); + } + + private void render(Object owner, boolean prepared) { + stack[0] = owner; + try { + if (layoutPending.getAsBoolean()) return; + if (!prepared) model.setRowCount(count.getAsInt()); + updatePoses(); + command[0] = 0; + driver.run(); + } finally { stack[0] = null; } + } + + void apply(Object owner) { + if (applied) throw new IllegalStateException("Nested notification state application"); + stack[0] = owner; + try { + model.setRowCount(count.getAsInt()); + updatePoses(); + command[0] = 1; + driver.run(); + applied = true; + } finally { stack[0] = null; } + } + + void restore() { + if (!applied) return; + command[0] = 2; + try { driver.run(); } + finally { applied = false; } + } +} diff --git a/hook/src/main/java/dev/colormotion/NotificationEdgeFade.java b/hook/src/main/java/dev/colormotion/NotificationEdgeFade.java new file mode 100644 index 00000000..20fe5420 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NotificationEdgeFade.java @@ -0,0 +1,109 @@ +package dev.colormotion; + +import android.graphics.Canvas; +import android.graphics.LinearGradient; +import android.graphics.Shader; +import android.view.View; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import de.robv.android.xposed.XposedHelpers; + +/** Correct the native fade's top discontinuity while retaining native rendering and bottom masks. */ +final class NotificationEdgeFade { + private static final Object[] NO_ARGS = new Object[0]; + private final Field drawing, shader, topStart, topEnd, bottomStart; + private final Field ambient, scrim, appear, launching, shelf; + private final Field dependency, header; + private final Method dependencyGet, mustStay; + private final Class headerClass, expandable; + private View headerView; + private Object owner, stack; + private Canvas canvas; + private Shader original, continuous; + private int saveCount, cacheHeight = -1, cacheStart, cacheEnd, cacheBottom; + + NotificationEdgeFade(Class stackClass, Class expandableClass, ClassLoader cl) + throws ReflectiveOperationException { + expandable = expandableClass; + mustStay = expandableClass.getMethod("mustStayOnScreen"); + mustStay.setAccessible(true); + ambient = stackClass.getField("mAmbientState"); + scrim = ambient.getType().getField("mNotificationScrimTop"); + appear = stackClass.getField("mLastSentAppear"); + launching = stackClass.getDeclaredField("mLaunchingNotification"); + shelf = stackClass.getField("mShelf"); + Field nativeDrawing; + try { nativeDrawing = stackClass.getField("mDrawingEdgeFadeOut"); } + catch (NoSuchFieldException legacy) { nativeDrawing = null; } + drawing = nativeDrawing; + if (drawing != null) { + shader = stackClass.getField("mFadeClipShaderForDraw"); + topStart = stackClass.getField("mFadeClipTopStart"); + topEnd = stackClass.getField("mFadeTopEnd"); + bottomStart = stackClass.getField("mFadeBottomStart"); + dependency = header = null; + dependencyGet = null; + headerClass = null; + } else { + shader = topStart = topEnd = bottomStart = null; + Class dependencies = XposedHelpers.findClass("com.android.systemui.Dependency", cl); + dependency = dependencies.getField("sDependency"); + Method get; + try { get = dependencies.getMethod("getDependencyInner", Class.class); } + catch (NoSuchMethodException legacyKey) { get = dependencies.getMethod("getDependencyInner", Object.class); } + dependencyGet = get; + headerClass = XposedHelpers.findClass("com.android.systemui.shade.ShadeHeaderController", cl); + header = headerClass.getField("header"); + } + for (Field field : new Field[] {drawing,shader,topStart,topEnd,bottomStart,ambient,scrim, + appear,launching,shelf,dependency,header}) if (field != null) field.setAccessible(true); + } + + void begin(Object token, Object host, Canvas target, View child) throws ReflectiveOperationException { + if (owner != null || child == shelf.get(host) || launching.getBoolean(host) + || appear.getFloat(host) <= 0f || !expandable.isInstance(child)) return; + if (drawing != null) { + if (!drawing.getBoolean(host)) return; + int end = topEnd.getInt(host), bottom = bottomStart.getInt(host); + float childY = child.getY(); + // Match native drawChild exactly: central children never consume the shader. + // Avoid a cache build and the temporary field swap/restore for those draws. + if (!(childY < end || child.getHeight() + childY > bottom)) return; + Shader nativeShader = (Shader) shader.get(host); + if (nativeShader == null) return; + if ((Boolean) mustStay.invoke(child, NO_ARGS)) return; + int height = ((View) host).getHeight(), start = topStart.getInt(host); + if (continuous == null || height != cacheHeight || start != cacheStart + || end != cacheEnd || bottom != cacheBottom) { + EdgeFadeMask mask = new EdgeFadeMask(height,start,end,bottom); + continuous = new LinearGradient(0f,0f,0f,Math.max(1,height),mask.colors, + mask.positions,Shader.TileMode.CLAMP); + cacheHeight=height;cacheStart=start;cacheEnd=end;cacheBottom=bottom; + } + original = nativeShader; + stack = host; + owner = token; + shader.set(host, continuous); + } else { + if ((Boolean) mustStay.invoke(child, NO_ARGS)) return; + if (headerView == null || !headerView.isAttachedToWindow()) + headerView = (View) header.get(dependencyGet.invoke(dependency.get(null), headerClass)); + if (headerView == null) return; + float start = Math.min(headerView.getMeasuredHeight(),(int)scrim.getFloat(ambient.get(host))) - 20f; + canvas = target; + saveCount = canvas.save(); + owner = token; + // Legacy SystemUI applies DST_IN only inside the fade strip. Hide the region above + // its zero-alpha edge, which otherwise preserves an opaque, abruptly cut card. + canvas.clipRect(-1_000_000f,start,1_000_000f,1_000_000f); + } + } + + void end(Object token) throws IllegalAccessException { + if (owner != token) return; + try { + if (drawing != null) shader.set(stack, original); + else canvas.restoreToCount(saveCount); + } finally { owner=stack=null;canvas=null;original=null; } + } +} diff --git a/hook/src/main/java/dev/colormotion/NotificationFooter.java b/hook/src/main/java/dev/colormotion/NotificationFooter.java new file mode 100644 index 00000000..c1c512ed --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NotificationFooter.java @@ -0,0 +1,76 @@ +package dev.colormotion; + +import android.view.View; +import java.lang.reflect.Field; + +/** Samsung's bottom button shelf is deliberately absent from the animated visibleChildren list. */ +final class NotificationFooter { + private final Field shelf, state, y, scaleX, scaleY, alpha, hidden, gone, pending, shown; + private Object saved; + private float savedY, savedX, savedScaleY, savedAlpha; + + NotificationFooter(Class stackClass, Class expandableClass) throws ReflectiveOperationException { + shelf = stackClass.getField("mShelf"); + shown = shelf.getType().getField("mShowNotificationShelf"); + pending = stackClass.getField("mChildrenUpdateRequested"); + state = expandableClass.getField("mViewState"); + Class stateClass = state.getType(); + y = stateClass.getField("mYTranslation"); + scaleX = stateClass.getField("mScaleX"); + scaleY = stateClass.getField("mScaleY"); + alpha = stateClass.getField("mAlpha"); + hidden = stateClass.getField("hidden"); + gone = stateClass.getField("gone"); + for (Field f : new Field[] {shelf, state, y, scaleX, scaleY, alpha, hidden, gone, pending, shown}) + f.setAccessible(true); + } + + boolean isShelf(Object stack, Object view) throws IllegalAccessException { + return shelf.get(stack) == view; + } + + void apply(Object stack, QsModel model) throws ReflectiveOperationException { + if (saved != null) throw new IllegalStateException("Nested footer state application"); + View view = (View) shelf.get(stack); + if (view == null || view.isPressed() || !shown.getBoolean(view)) return; + Object target = state.get(view); + if (target == null || gone.getBoolean(target)) return; + savedY = y.getFloat(target); + savedX = scaleX.getFloat(target); + savedScaleY = scaleY.getFloat(target); + savedAlpha = alpha.getFloat(target); + saved = target; + // Shelf Y is already anchored to the screen bottom. It must not receive the cards' + // top-padding/stack-Y compensation or inherit a partially expanded card's stale scale. + y.setFloat(target, savedY + model.footerTranslation()); + scaleX.setFloat(target, model.footerScale()); + scaleY.setFloat(target, model.footerScale()); + alpha.setFloat(target, model.footerOpacity()); + } + + void restore() throws IllegalAccessException { + if (saved == null) return; + Object target = saved; + saved = null; + y.setFloat(target, savedY); + scaleX.setFloat(target, savedX); + scaleY.setFloat(target, savedScaleY); + alpha.setFloat(target, savedAlpha); + } + + void render(Object stack, QsModel model, boolean afterNative) throws ReflectiveOperationException { + if (!afterNative && pending.getBoolean(stack)) return; + View view = (View) shelf.get(stack); + if (view == null || view.isPressed() || !shown.getBoolean(view)) return; + Object target = state.get(view); + if (target == null || gone.getBoolean(target)) return; + float a = model.footerOpacity(), s = model.footerScale(); + float position = (saved == target ? savedY : y.getFloat(target)) + model.footerTranslation(); + if (view.getTranslationY() != position) view.setTranslationY(position); + if (view.getScaleX() != s) view.setScaleX(s); + if (view.getScaleY() != s) view.setScaleY(s); + if (view.getAlpha() != a) view.setAlpha(a); + int visibility = hidden.getBoolean(target) || a == 0f ? View.INVISIBLE : View.VISIBLE; + if (view.getVisibility() != visibility) view.setVisibility(visibility); + } +} diff --git a/hook/src/main/java/dev/colormotion/NotificationGeometry.java b/hook/src/main/java/dev/colormotion/NotificationGeometry.java new file mode 100644 index 00000000..2a0bbd41 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NotificationGeometry.java @@ -0,0 +1,97 @@ +package dev.colormotion; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +/** + * The notification cascade reveals a laid-out list, as the QS layers do. Keep Samsung's + * stack at its expanded geometry inside its layout consumers, without changing the real + * panel fraction used by input, window visibility, scrims or the rest of SystemUI. + */ +final class NotificationGeometry { + private final Field ambient, fraction, updater, trackedHeadsUp; + private final Field pinned, headsUpAway, launching; + private final Field expandedHeight; + private final Field scrollY, beingDragged; + private final Field[] eventWork; + private final Method setHeight; + private final Object[] heightArg = new Object[1]; + private final Object[] owners = new Object[16]; + private int depth; + private Object currentStack, currentAmbient; + private float savedFraction; + + NotificationGeometry(Class stack) throws ReflectiveOperationException { + ambient = field(stack, "mAmbientState"); + fraction = field(ambient.getType(), "mExpansionFraction"); + trackedHeadsUp = field(ambient.getType(), "mTrackedHeadsUpRow"); + updater = field(stack, "mChildrenUpdater"); + pinned = field(stack, "mInHeadsUpPinnedMode"); + headsUpAway = field(stack, "mHeadsUpAnimatingAway"); + launching = field(stack, "mLaunchingNotification"); + expandedHeight = field(stack, "mExpandedHeight"); + scrollY = field(stack, "mOwnScrollY"); + beingDragged = field(stack, "mIsBeingDragged"); + String[] events = {"mNeedsAnimation", "mAnimationRunning", "mClearAllInProgress", "mIsBeingDragged"}; + eventWork = new Field[events.length]; + for (int i = 0; i < events.length; i++) eventWork[i] = field(stack, events[i]); + setHeight = stack.getMethod("setExpandedHeight", float.class); + setHeight.setAccessible(true); + } + + private static Field field(Class type, String name) throws NoSuchFieldException { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + Object childrenUpdater(Object stack) throws IllegalAccessException { return updater.get(stack); } + + boolean scrolling(Object stack) throws IllegalAccessException { + return beingDragged.getBoolean(stack) || scrollY.getInt(stack) != 0; + } + + boolean fingerScrolling(Object stack) throws IllegalAccessException { return beingDragged.getBoolean(stack); } + int scrollPosition(Object stack) throws IllegalAccessException { return scrollY.getInt(stack); } + + boolean canDeferHiddenUpdate(Object stack) throws IllegalAccessException { + if (pinned.getBoolean(stack) || headsUpAway.getBoolean(stack) || launching.getBoolean(stack) + || trackedHeadsUp.get(ambient.get(stack)) != null) return false; + for (Field f : eventWork) if (f.getBoolean(stack)) return false; + return true; + } + + void restoreHeight(Object stack, float height) throws ReflectiveOperationException { + if (expandedHeight.getFloat(stack) == height) return; + heightArg[0] = height; + try { setHeight.invoke(stack, heightArg); } + finally { heightArg[0] = null; } + } + + boolean enter(Object owner, Object stack) throws IllegalAccessException { + if (depth == owners.length || (depth != 0 && currentStack != stack)) return false; + Object state = ambient.get(stack); + // Heads-up drags and notification launches retain their native geometry/clip behavior. + if (pinned.getBoolean(stack) || headsUpAway.getBoolean(stack) + || launching.getBoolean(stack) || trackedHeadsUp.get(state) != null) return false; + if (depth == 0) { + savedFraction = fraction.getFloat(state); + if (!(savedFraction > 0f)) return false; + currentStack = stack; + currentAmbient = state; + fraction.setFloat(state, 1f); + } + owners[depth++] = owner; + return true; + } + + /** Also called on native exceptions; nested consumers cannot restore an outer scope early. */ + void exit(Object owner) throws IllegalAccessException { + if (depth == 0 || owners[depth - 1] != owner) return; + owners[--depth] = null; + if (depth == 0) { + try { fraction.setFloat(currentAmbient, savedFraction); } + finally { currentAmbient = null; currentStack = null; } + } + } +} diff --git a/hook/src/main/java/dev/colormotion/NotificationRows.java b/hook/src/main/java/dev/colormotion/NotificationRows.java new file mode 100644 index 00000000..d88a2e47 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/NotificationRows.java @@ -0,0 +1,333 @@ +package dev.colormotion; + +import android.view.View; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** Applies the reference-fitted QS flow to notification cards, one card per motion node. */ +final class NotificationRows { + private static final Object[] NO_ARGS = new Object[0]; + final QsModel model = new QsModel(); + private final ArrayList pool = new ArrayList<>(); + private final ArrayList applied = new ArrayList<>(); + private Field stackAlgorithm, algorithmState, visibleChildren, stackAmbient, stackY, childState, layoutPending; + private Field stateY, stateScaleX, stateScaleY, stateAlpha; + private Method topPadding, mustStay, isAnimating, setFaded; + private Field stateGone, stateHidden, willBeGone, faded; + private Class notificationRow; + private Field actualHeight, topFadeEnd, bottomFadeStart; + private Field scrollY; + private int firstRow; + private Method updateGradient, attachedChildren; + private float lastFadeTop=Float.NaN, lastFadeBottom=Float.NaN; + private final Object[] childArg = new Object[1]; + private final Object[] fadeArg = new Object[1]; + private NativeNotifications nativeRows; + + void installNative(NativeLayers bindings) { + if (bindings == null) return; + try { + nativeRows = new NativeNotifications(bindings, model); + de.robv.android.xposed.XposedBridge.log(Entry.TAG + ": typed notification bridge ready"); + } catch (Throwable failure) { disableNative(failure); } + } + + private void disableNative(Throwable failure) { + nativeRows = null; + de.robv.android.xposed.XposedBridge.log(Entry.TAG + ": notification bridge unavailable, using reflective binding: " + failure); + } + + NotificationRows() { + model.rowCount = 1; + model.reset(); + } + + private List children(Object stack) throws IllegalAccessException { + return (List) visibleChildren.get(algorithmState.get(stackAlgorithm.get(stack))); + } + + boolean isBound() { return layoutPending != null; } + + boolean layoutPending(Object stack) throws IllegalAccessException { + return layoutPending.getBoolean(stack); + } + + void prepare(Object stack) throws IllegalAccessException { + if (nativeRows != null) { + try { nativeRows.prepare(stack); return; } + catch (LinkageError | ClassCastException failure) { disableNative(failure); } + } + List children = children(stack); + firstRow = firstVisibleRow(stack, children); + model.setRowCount(children.size() - firstRow); + } + + /** Resolve metadata once; no string-based field lookup or snapshot allocation per frame. */ + void bind(Class stack, Class expandableView) throws ReflectiveOperationException { + stackAlgorithm = stack.getField("mStackScrollAlgorithm"); + algorithmState = stackAlgorithm.getType().getField("mTempAlgorithmState"); + visibleChildren = algorithmState.getType().getField("visibleChildren"); + stackAmbient = stack.getField("mAmbientState"); + layoutPending = stack.getField("mChildrenUpdateRequested"); + scrollY = stack.getField("mOwnScrollY"); + stackY = stackAmbient.getType().getField("mStackY"); + childState = expandableView.getField("mViewState"); + Class state = childState.getType(); + stateY = state.getField("mYTranslation"); + stateScaleX = state.getField("mScaleX"); + stateScaleY = state.getField("mScaleY"); + stateAlpha = state.getField("mAlpha"); + topPadding = stack.getMethod("getTopPadding"); + mustStay = expandableView.getMethod("mustStayOnScreen"); + for (Field field : new Field[] {stackAlgorithm, algorithmState, visibleChildren, stackAmbient, + stackY, childState, stateY, stateScaleX, stateScaleY, stateAlpha, layoutPending, scrollY}) field.setAccessible(true); + topPadding.setAccessible(true); + mustStay.setAccessible(true); + } + + /** Extra native contracts used by render-only frames; native layout/event animations still run. */ + void bindRendering(Class row) throws ReflectiveOperationException { + notificationRow = row; + actualHeight = childState.getDeclaringClass().getField("mActualHeight"); + topFadeEnd = stackAmbient.getType().getField("mBlurTopFadeoutEnd"); + bottomFadeStart = stackAmbient.getType().getField("mBlurBottomFadeoutStart"); + updateGradient = row.getMethod("updateBlurBackgroundGradient"); + attachedChildren = row.getMethod("getAttachedChildren"); + for (Field f : new Field[] {actualHeight, topFadeEnd, bottomFadeStart}) f.setAccessible(true); + updateGradient.setAccessible(true); + attachedChildren.setAccessible(true); + Class state = childState.getType(); + stateGone = state.getField("gone"); + stateHidden = state.getField("hidden"); + willBeGone = childState.getDeclaringClass().getField("mWillBeGone"); + faded = row.getField("mIsFaded"); + setFaded = row.getMethod("setNotificationFaded", boolean.class); + isAnimating = state.getMethod("isAnimating", View.class); + for (Field f : new Field[] {stateGone, stateHidden, willBeGone, faded}) f.setAccessible(true); + setFaded.setAccessible(true); + isAnimating.setAccessible(true); + } + + /** + * Apply only the four animated properties from the latest native layout. In particular this + * does not schedule NSSL's complete stack algorithm, shelf pass or location callbacks. + * Native layout consumers above still receive the same temporary state overrides when + * expansion, scrolling, notification events or geometry actually require a layout pass. + */ + void render(Object stack) throws ReflectiveOperationException { + render(stack, false); + } + + /** + * Frame-clock fast path: call prepare(stack), step the model, then this method in the same + * synchronous callback. No native layout/scroll/list mutation may occur between those calls. + * Unlike a cross-frame cache, this only reuses the first-row scan already done for this step. + */ + void renderPrepared(Object stack) throws ReflectiveOperationException { + render(stack, true); + } + + private void render(Object stack, boolean prepared) throws ReflectiveOperationException { + if (nativeRows != null) { + try { + if (prepared) nativeRows.renderPrepared(stack); + else nativeRows.render(stack); + return; + } + catch (LinkageError | ClassCastException failure) { disableNative(failure); } + // The typed adapter owned prepare's first-row result. Recompute on fallback. + prepared = false; + } + // The pending native pre-draw will consume our latest pose through apply()/restore(). + // Avoid writing the same properties twice before that traversal. + if (layoutPending.getBoolean(stack)) return; + List children = children(stack); + if (!prepared) { + firstRow = firstVisibleRow(stack, children); + model.setRowCount(children.size() - firstRow); + } + Object ambient = stackAmbient.get(stack); + float fadeTop = topFadeEnd.getFloat(ambient), fadeBottom = bottomFadeStart.getFloat(ambient); + boolean fadeChanged = fadeTop != lastFadeTop || fadeBottom != lastFadeBottom; + float stackOffset = ((Number) topPadding.invoke(stack, NO_ARGS)).floatValue() + - stackY.getFloat(ambient) + model.translation.value; + int viewport = stack instanceof View ? ((View) stack).getHeight() : 0; + try { + for (int i = firstRow; i < children.size(); i++) { + View child = (View) children.get(i); + if (child.isPressed() || (Boolean) mustStay.invoke(child, NO_ARGS) + || willBeGone.getBoolean(child)) continue; + Object state = childState.get(child); + if (state == null || stateGone.getBoolean(state)) continue; + childArg[0] = child; + if ((Boolean) isAnimating.invoke(null, childArg)) continue; + int row = Math.min(i - firstRow, QsModel.MAX_ROWS - 1); + float alpha = model.rowAlpha(row); + float scale = model.scale[row].value; + float y = stateY.getFloat(state) + stackOffset + model.rowTranslation(row); + float previousY = child.getTranslationY(); + int cardHeight = actualHeight.getInt(child); + if (!onStack(y, cardHeight, viewport) && !onStack(previousY, cardHeight, viewport)) { + // Same off-stack skip as the typed bridge. + if (notificationRow.isInstance(child) && faded.getBoolean(child)) { + fadeArg[0] = Boolean.FALSE; + setFaded.invoke(child, fadeArg); + } + continue; + } + if (previousY != y) child.setTranslationY(y); + if (child.getScaleX() != scale) child.setScaleX(scale); + if (child.getScaleY() != scale) child.setScaleY(scale); + boolean hidden = stateHidden.getBoolean(state) || alpha == 0f; + // Off-stack cards draw nothing; do not build their fade hardware layers. + boolean nextFaded = !hidden && alpha != 1f && onStack(y, actualHeight.getInt(child), viewport); + if (notificationRow.isInstance(child)) { + if (faded.getBoolean(child) != nextFaded) { + fadeArg[0] = nextFaded ? Boolean.TRUE : Boolean.FALSE; + setFaded.invoke(child, fadeArg); + } + } else { + int layer = nextFaded && child.hasOverlappingRendering() ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; + if (child.getLayerType() != layer) child.setLayerType(layer, null); + } + if (child.getAlpha() != alpha) child.setAlpha(alpha); + int visibility = hidden ? View.INVISIBLE : View.VISIBLE; + int previousVisibility = child.getVisibility(); + boolean becameVisible = visibility == View.VISIBLE && previousVisibility != View.VISIBLE; + if (previousVisibility != visibility) child.setVisibility(visibility); + // A gated/delayed INVISIBLE card cannot contribute pixels. Native gradients + // allocate blur descriptors; defer that work until the card is visible again. + // Refresh even at an unchanged central Y on reentry to clear its old edge mask. + if (!hidden && (previousY != y || fadeChanged || becameVisible) && notificationRow.isInstance(child)) + refreshGradient(child, previousY, y, fadeTop, fadeBottom, fadeChanged, becameVisible, viewport); + } + lastFadeTop = fadeTop; + lastFadeBottom = fadeBottom; + } finally { + childArg[0] = null; + fadeArg[0] = null; + } + } + + private void refreshGradient(View child, float oldY, float y, float top, float bottom, + boolean changed, boolean force, int viewport) + throws ReflectiveOperationException { + int height = actualHeight.getInt(child); + // Same off-stack cull as the typed bridge; native layout passes refresh all cards. + if (!onStack(y, height, viewport)) return; + if (height <= 0 || !(force || crossesFade(oldY, y, height, top, bottom) + || (changed && (Float.isNaN(lastFadeTop) + || crossesFade(oldY, y, height, lastFadeTop, lastFadeBottom))))) return; + // The native shelf normally does this. Render-only motion bypasses that shelf pass, + // so an old background gradient can otherwise remain after its card leaves the band. + updateGradient.invoke(child, NO_ARGS); + List attached = (List) attachedChildren.invoke(child, NO_ARGS); + if (attached == null) return; + for (int i = 0; i < attached.size(); i++) { + View nested = (View) attached.get(i); + if (nested.getVisibility() == View.VISIBLE && actualHeight.getInt(nested) > 0) + updateGradient.invoke(nested, NO_ARGS); + } + } + + static boolean onStack(float y, int height, int viewport) { + return viewport <= 0 || (y < viewport + height && y + 2f * height > 0f); + } + + private static boolean crossesFade(float oldY, float y, int height, float top, float bottom) { + return top <= 0f || bottom <= 0f || oldY < top || y < top + || oldY + height > bottom || y + height > bottom; + } + + private int firstVisibleRow(Object stack, List children) throws IllegalAccessException { + // The algorithm's "visibleChildren" includes rows above the viewport. A retained + // scroll position must not give the first visible card row 23's delay/zero scale. + if (scrollY.getInt(stack) <= 0 || actualHeight == null) return 0; + float offset; + try { offset = ((Number) topPadding.invoke(stack, NO_ARGS)).floatValue() - stackY.getFloat(stackAmbient.get(stack)); } + catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + for (int i = 0; i < children.size(); i++) { + Object child = children.get(i), state = childState.get(child); + if (state != null && (stateGone == null || !stateGone.getBoolean(state)) + && stateY.getFloat(state) + offset + actualHeight.getInt(child) > 0f) return i; + } + return Math.max(0, children.size() - 1); + } + + /** Temporarily replaces expansion transforms, keeping native scrolling/shelf/heads-up layout. */ + List apply(Object stack) throws ReflectiveOperationException { + if (nativeRows != null) { + try { nativeRows.apply(stack); return null; } + catch (LinkageError | ClassCastException failure) { disableNative(failure); } + } + if (!applied.isEmpty()) throw new IllegalStateException("Nested notification state application"); + List children = children(stack); + // Only animate actual rows; absent offscreen slots must not keep the frame clock alive. + firstRow = firstVisibleRow(stack, children); + model.setRowCount(children.size() - firstRow); + float nativeStackY = stackY.getFloat(stackAmbient.get(stack)); + float fullStackY = ((Number) topPadding.invoke(stack, NO_ARGS)).floatValue(); + try { + for (int i = firstRow; i < children.size(); i++) { + Object child = children.get(i); + if (((View) child).isPressed() || (Boolean) mustStay.invoke(child, NO_ARGS)) continue; + Object target = childState.get(child); + if (target == null) continue; + int slot = applied.size(); + if (slot == pool.size()) pool.add(new State(this)); + State saved = pool.get(slot); + saved.capture(target); + applied.add(saved); + int row = Math.min(i - firstRow, QsModel.MAX_ROWS - 1); + // Replace Samsung's expansion-dependent mStackY component with the QS panel slide. + float y = saved.y + fullStackY - nativeStackY + + model.translation.value + model.rowTranslation(row); + stateY.setFloat(target, y); + stateScaleX.setFloat(target, model.scale[row].value); + stateScaleY.setFloat(target, model.scale[row].value); + stateAlpha.setFloat(target, model.rowAlpha(row)); + } + return applied; + } catch (Throwable t) { + restore(applied); + throw t; + } + } + + static void restore(List changes) throws IllegalAccessException { + if (changes == null) return; + for (int i = 0; i < changes.size(); i++) { + State s = changes.get(i); + s.owner.stateY.setFloat(s.target, s.y); + s.owner.stateScaleX.setFloat(s.target, s.scaleX); + s.owner.stateScaleY.setFloat(s.target, s.scaleY); + s.owner.stateAlpha.setFloat(s.target, s.alpha); + s.target = null; + } + changes.clear(); + } + + void restoreApplied(List changes) throws IllegalAccessException { + if (nativeRows != null) nativeRows.restore(); + restore(changes); + } + + static final class State { + final NotificationRows owner; + Object target; + float y, scaleX, scaleY, alpha; + + State(NotificationRows owner) { this.owner = owner; } + + void capture(Object target) throws IllegalAccessException { + this.target = target; + y = owner.stateY.getFloat(target); + scaleX = owner.stateScaleX.getFloat(target); + scaleY = owner.stateScaleY.getFloat(target); + alpha = owner.stateAlpha.getFloat(target); + } + } +} diff --git a/hook/src/main/java/dev/colormotion/OpeningReadiness.java b/hook/src/main/java/dev/colormotion/OpeningReadiness.java new file mode 100644 index 00000000..e6a6075d --- /dev/null +++ b/hook/src/main/java/dev/colormotion/OpeningReadiness.java @@ -0,0 +1,113 @@ +package dev.colormotion; + +import android.view.View; +import android.view.ViewTreeObserver; + +/** A scoped first-traversal latch. It sleeps without polling and retains no host after release. */ +final class OpeningReadiness { + interface Listener { + boolean isReady(View host) throws Throwable; + void onReady(); + void onFailure(Throwable failure); + } + + private final Listener listener; + private boolean waiting; + private View host; + private ViewTreeObserver observer; + private ViewTreeObserver.OnPreDrawListener preDraw; + private long generation; + private final View.OnAttachStateChangeListener attachment = new View.OnAttachStateChangeListener() { + @Override public void onViewAttachedToWindow(View view) { + if (waiting && view == host) observe(); + } + @Override public void onViewDetachedFromWindow(View view) { + try { if (view == host) stopPreDraw(); } + catch (Throwable failure) { fail(failure); } + } + }; + + OpeningReadiness(Listener listener) { this.listener = listener; } + + boolean isWaiting() { return waiting; } + + void begin(View next) { + cancel(); + waiting = true; + setHost(next); + } + + void setHost(View next) { + if (!waiting) return; + try { + if (host != next) { + stopPreDraw(); + if (host != null) host.removeOnAttachStateChangeListener(attachment); + host = next; + if (host != null) host.addOnAttachStateChangeListener(attachment); + } + observe(); + } catch (Throwable failure) { fail(failure); } + } + + private void observe() { + try { + if (!waiting || host == null) return; + ViewTreeObserver next = host.getViewTreeObserver(); + if (next == observer && next.isAlive()) return; + stopPreDraw(); + if (!next.isAlive()) return; + observer = next; + long token = generation; + preDraw = () -> onPreDraw(token); + observer.addOnPreDrawListener(preDraw); + } catch (Throwable failure) { fail(failure); } + } + + private boolean onPreDraw(long token) { + try { + if (!waiting || token != generation) return true; + View view = host; + if (view == null || !view.isAttachedToWindow() || !view.isShown() + || view.isLayoutRequested() || view.getWidth() <= 0 || view.getHeight() <= 0 + || !listener.isReady(view)) return true; + cancel(); + listener.onReady(); + } catch (Throwable failure) { fail(failure); } + return true; + } + + /** The native children updater may run after our listener in the same pre-draw dispatch. */ + void afterTraversal(View view) { + if (!waiting || view != host) return; + try { + observe(); + if (observer != null && observer == view.getViewTreeObserver() && observer.isAlive()) + onPreDraw(generation); + } catch (Throwable failure) { fail(failure); } + } + + private void stopPreDraw() { + generation++; + if (observer != null && observer.isAlive()) observer.removeOnPreDrawListener(preDraw); + // A floating tree's listeners can migrate into a different live observer on attach. + if (host != null && preDraw != null) { + ViewTreeObserver current = host.getViewTreeObserver(); + if (current != observer && current.isAlive()) current.removeOnPreDrawListener(preDraw); + } + observer = null; + preDraw = null; + } + + void cancel() { + waiting = false; + stopPreDraw(); + if (host != null) host.removeOnAttachStateChangeListener(attachment); + host = null; + } + + private void fail(Throwable failure) { + try { cancel(); } + finally { listener.onFailure(failure); } + } +} diff --git a/hook/src/main/java/dev/colormotion/PanelFields.java b/hook/src/main/java/dev/colormotion/PanelFields.java new file mode 100644 index 00000000..187b67d9 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/PanelFields.java @@ -0,0 +1,88 @@ +package dev.colormotion; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +/** Resolves the panel's hot contracts once, instead of Xposed string/argument lookup per frame. */ +final class PanelFields { + private static final Object[] NO_ARGS = new Object[0]; + private final Field bar, fraction, expandedHeight, initialOffset, closed, split, side, velocity; + private final Method tracking, maxDistance, setHeight; + private final Object[] heightArg = new Object[1]; + + PanelFields(Class panel) throws ReflectiveOperationException { + bar = panel.getField("mBarState"); + fraction = panel.getField("mExpandedFraction"); + Field nativeHeight; + try { nativeHeight = panel.getField("mExpandedHeight"); } + catch (NoSuchFieldException absent) { nativeHeight = null; } + if (nativeHeight != null && nativeHeight.getType() != float.class) nativeHeight = null; + expandedHeight = nativeHeight; + if (expandedHeight != null) expandedHeight.setAccessible(true); + initialOffset = panel.getField("mInitialOffsetOnTouch"); + closed = panel.getField("mPanelClosedOnDown"); + split = panel.getField("mPanelSplitHelper"); + side = split.getType().getField("currentState"); + velocity = panel.getField("mVelocityTracker"); + tracking = panel.getMethod("isTracking"); + maxDistance = panel.getMethod("getMaxPanelTransitionDistance"); + setHeight = panel.getMethod("setExpandedHeightInternal", float.class); + for (Field f : new Field[] {bar, fraction, initialOffset, closed, split, side, velocity}) f.setAccessible(true); + for (Method m : new Method[] {tracking, maxDistance, setHeight}) m.setAccessible(true); + } + + int barState(Object panel) { + try { return bar.getInt(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + float fraction(Object panel) { + try { return fraction.getFloat(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + float initialOffset(Object panel) { + try { return initialOffset.getFloat(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + /** Native height from the same consumer that writes mExpandedFraction; no geometry query. */ + float expandedHeight(Object panel) { + if (expandedHeight == null) return Float.NaN; + try { return expandedHeight.getFloat(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + boolean closedOnDown(Object panel) { + try { return closed.getBoolean(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + int side(Object panel) { + try { + Object helper = split.get(panel); + return helper != null ? side.getInt(helper) : 1; + } catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + Object velocityTracker(Object panel) { + try { return velocity.get(panel); } + catch (IllegalAccessException e) { throw new IllegalStateException(e); } + } + + boolean tracking(Object panel) { + try { return (Boolean) tracking.invoke(panel, NO_ARGS); } + catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + } + + float maxDistance(Object panel) { + try { return ((Number) maxDistance.invoke(panel, NO_ARGS)).floatValue(); } + catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + } + + void setHeight(Object panel, float value) { + heightArg[0] = value; + try { setHeight.invoke(panel, heightArg); } + catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + } +} diff --git a/hook/src/main/java/dev/colormotion/PanelHeightBinding.java b/hook/src/main/java/dev/colormotion/PanelHeightBinding.java new file mode 100644 index 00000000..7a6e6dd6 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/PanelHeightBinding.java @@ -0,0 +1,30 @@ +package dev.colormotion; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +/** The small public height setter is inlined by ART; its large Runnable remains hookable. */ +final class PanelHeightBinding { + final Field panel, height; + final Method run; + + PanelHeightBinding(ClassLoader cl, Class owner) throws ReflectiveOperationException { + Field selectedPanel = null, selectedHeight = null; + Method selected = null; + for (int suffix : new int[] {13, 14}) { + Class callback; + try { callback = Class.forName(owner.getName() + "$$ExternalSyntheticLambda" + suffix, false, cl); } + catch (ClassNotFoundException missing) { continue; } + if (!Runnable.class.isAssignableFrom(callback)) continue; + Field p, h; + try { p = callback.getField("f$0"); h = callback.getField("f$1"); } + catch (NoSuchFieldException otherCallback) { continue; } + if (p.getType() != owner || h.getType() != float.class || callback.getDeclaredFields().length != 2) continue; + if (selected != null) throw new NoSuchMethodException("Ambiguous panel height callback"); + selected = callback.getMethod("run"); selectedPanel = p; selectedHeight = h; + } + if (selected == null) throw new NoSuchMethodException("Unsupported panel height callback"); + run = selected; panel = selectedPanel; height = selectedHeight; + panel.setAccessible(true); height.setAccessible(true); + } +} diff --git a/hook/src/main/java/dev/colormotion/PanelSlideMotion.java b/hook/src/main/java/dev/colormotion/PanelSlideMotion.java new file mode 100644 index 00000000..3a6b081e --- /dev/null +++ b/hook/src/main/java/dev/colormotion/PanelSlideMotion.java @@ -0,0 +1,137 @@ +package dev.colormotion; + +import android.view.View; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import de.robv.android.xposed.XposedHelpers; + +/** Adds reversible depth/crossfade to Samsung's native horizontal panel-switch gesture. */ +final class PanelSlideMotion { + private static final Object[] NO_ARGS = new Object[0]; + final Method slide; + private final Field state, qsRoot, shadeRoot, displayMode; + private final Method getView, popOver; + private final Field[] exclusions; + private View lastQs, lastShade; + private final float[] qsNative = new float[4], shadeNative = new float[4]; + private final float[] qsOwned = new float[4], shadeOwned = new float[4]; + private boolean hasPose; + + PanelSlideMotion(ClassLoader cl) throws ReflectiveOperationException { + Class owner = XposedHelpers.findClass("com.android.systemui.qs.animator.PanelTransitionAnimator", cl); + Class direction = XposedHelpers.findClass("com.android.systemui.shade.PanelSlideEventHandler$Direction", cl); + slide = owner.getMethod("slide", float.class, float.class, direction, int.class); + state = owner.getField("panelTransitionState"); + qsRoot = owner.getField("qsRootView"); shadeRoot = owner.getField("shadeRootView"); + getView = qsRoot.getType().getMethod("getView"); + displayMode = owner.getField("secQsUiDisplayModeInteractor"); + popOver = displayMode.getType().getMethod("isPopOverEnabled"); + Class flags = XposedHelpers.findClass("com.android.systemui.qs.animator.QsAnimatorState", cl); + String[] names = {"isDetailShowing", "isDetailOpening", "isDetailClosing", "isCustomizerShowing"}; + java.util.ArrayList excluded = new java.util.ArrayList<>(); + for (String name : names) excluded.add(flags.getField(name)); + for (String name : new String[] {"isDetailPopupShowing", "isDetailPopupClosing"}) { + try { excluded.add(flags.getField(name)); } + catch (NoSuchFieldException removedInOneUi9) { /* audited optional contracts */ } + } + exclusions = excluded.toArray(new Field[0]); + } + + int state(Object animator) throws IllegalAccessException { return state.getInt(animator); } + + boolean isHorizontal(Object[] args) { + if (args[2] == null) return false; + String name = ((Enum) args[2]).name(); + return name.equals("LEFT") || name.equals("RIGHT"); + } + + boolean isPanelTransition(Object[] args) { + return isHorizontal(args) || (args[2] instanceof Enum && ((Enum) args[2]).name().equals("DOWN")); + } + + boolean allowed(Object animator) throws ReflectiveOperationException { + for (Field f : exclusions) if (f.getBoolean(null)) return false; + return !(Boolean) popOver.invoke(displayMode.get(animator), NO_ARGS); + } + + void apply(Object animator, Object[] args) throws ReflectiveOperationException { + Object q = qsRoot.get(animator), n = shadeRoot.get(animator); + View qs = q == null ? null : (View) getView.invoke(q, NO_ARGS); + View shade = n == null ? null : (View) getView.invoke(n, NO_ARGS); + if (lastQs != qs || lastShade != shade) abort(); + lastQs = qs; lastShade = shade; + // TouchAnimator may skip an identical fraction. Capture only native changes, + // retaining its earlier pose if this consumer still contains our last override. + capture(qs, qsNative, qsOwned); + capture(shade, shadeNative, shadeOwned); + float f = QsModel.clamp((Float) args[0], 0f, 1f); + int target = (Integer) args[3]; + float qsVisible = target == 0 ? f : 1f - f; + float shadeVisible = 1f - qsVisible; + // Native Compose already supplies QS's 300px horizontal travel, including reversed + // panels and RTL. Do not apply that displacement a second time to its Android host. + pose(qs, qsVisible, 0f); + read(qs, qsOwned); + if (shade != null) { + float sign = ((Enum) args[2]).name().equals("LEFT") ? -1f : 1f; + float travel = shade.getWidth() * 0.28f; + float x = target == 1 ? -sign * travel * (1f - f) : sign * travel * f; + pose(shade, shadeVisible, x); + } + read(shade, shadeOwned); + hasPose = true; + } + + private static void pose(View v, float visibility, float x) { + if (v == null) return; + float alpha = visibility * visibility * (3f - 2f * visibility); + float scale = 0.96f + 0.04f * visibility; + if (v.getAlpha() != alpha) v.setAlpha(alpha); + if (v.getTranslationX() != x) v.setTranslationX(x); + if (v.getScaleX() != scale) v.setScaleX(scale); + if (v.getScaleY() != scale) v.setScaleY(scale); + } + + void reset() { + for (View v : new View[] {lastQs, lastShade}) if (v != null) { + if (v.getTranslationX() != 0f) v.setTranslationX(0f); + if (v.getScaleX() != 1f) v.setScaleX(1f); + if (v.getScaleY() != 1f) v.setScaleY(1f); + } + lastQs = lastShade = null; + hasPose = false; + } + + private void capture(View v, float[] nativePose, float[] ownedPose) { + if (v == null) return; + float a = v.getAlpha(), x = v.getTranslationX(), sx = v.getScaleX(), sy = v.getScaleY(); + if (!hasPose || a != ownedPose[0]) nativePose[0] = a; + if (!hasPose || x != ownedPose[1]) nativePose[1] = x; + if (!hasPose || sx != ownedPose[2]) nativePose[2] = sx; + if (!hasPose || sy != ownedPose[3]) nativePose[3] = sy; + } + + private static void read(View v, float[] pose) { + if (v == null) return; + pose[0] = v.getAlpha(); pose[1] = v.getTranslationX(); + pose[2] = v.getScaleX(); pose[3] = v.getScaleY(); + } + + private static void restore(View v, float[] nativePose, float[] ownedPose) { + if (v == null) return; + if (v.getAlpha() == ownedPose[0] && v.getAlpha() != nativePose[0]) v.setAlpha(nativePose[0]); + if (v.getTranslationX() == ownedPose[1] && v.getTranslationX() != nativePose[1]) v.setTranslationX(nativePose[1]); + if (v.getScaleX() == ownedPose[2] && v.getScaleX() != nativePose[2]) v.setScaleX(nativePose[2]); + if (v.getScaleY() == ownedPose[3] && v.getScaleY() != nativePose[3]) v.setScaleY(nativePose[3]); + } + + /** Restore before the next native consumer, and on mode changes with no native endpoint. */ + void abort() { + if (hasPose) { + restore(lastQs, qsNative, qsOwned); + restore(lastShade, shadeNative, shadeOwned); + } + lastQs = lastShade = null; + hasPose = false; + } +} diff --git a/hook/src/main/java/dev/colormotion/QsAuxBinding.java b/hook/src/main/java/dev/colormotion/QsAuxBinding.java new file mode 100644 index 00000000..94faed0e --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsAuxBinding.java @@ -0,0 +1,33 @@ +package dev.colormotion; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import de.robv.android.xposed.XposedHelpers; + +/** The VPN disclosure and mic-mode banner live outside EditableItem on both native layouts. */ +final class QsAuxBinding { + final Method footer, banner; + + QsAuxBinding(ClassLoader cl) throws ReflectiveOperationException { + Class modifier = XposedHelpers.findClass("androidx.compose.ui.Modifier", cl); + Class composer = XposedHelpers.findClass("androidx.compose.runtime.Composer", cl); + String owner = "com.android.systemui.samsung.quicksetting.ui.banner."; + footer = find(XposedHelpers.findClass(owner + "SecurityFooterKt", cl), "SecurityFooterContent", 0, modifier, composer); + banner = find(XposedHelpers.findClass(owner + "TopBannerKt", cl), "TopBanner", 1, modifier, composer); + } + + static Method find(Class owner, String name, int modifierIndex, Class modifier, Class composer) + throws NoSuchMethodException { + Method selected = null; + for (Method m : owner.getDeclaredMethods()) { + Class[] p = m.getParameterTypes(); + if (!m.getName().equals(name) || !Modifier.isStatic(m.getModifiers()) || m.getReturnType() != void.class + || (p.length != 6 && p.length != 7) || p[modifierIndex] != modifier + || p[p.length - 2] != composer || p[p.length - 1] != int.class) continue; + if (selected != null) throw new NoSuchMethodException("Ambiguous QS auxiliary ABI: " + name); + selected = m; + } + if (selected == null) throw new NoSuchMethodException("Unsupported QS auxiliary ABI: " + name); + return selected; + } +} diff --git a/hook/src/main/java/dev/colormotion/QsClipping.java b/hook/src/main/java/dev/colormotion/QsClipping.java new file mode 100644 index 00000000..24a3c7cf --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsClipping.java @@ -0,0 +1,323 @@ +package dev.colormotion; + +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.view.ViewTreeObserver; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** Removes motion viewports within the QS host, preserving individual controls' shaped masks. */ +final class QsClipping { + private static final String ROOT = "com.android.systemui.samsung.quicksetting.view.SecQSPanelComposeRoot"; + private static final String UI = "com.android.systemui.samsung.quicksetting.ui."; + private final ClassLoader cl; + private final HookSet hooks; + private final ArrayList> hosts = new ArrayList<>(); + private WeakReference hostRoot = new WeakReference<>(null); + private boolean active = true, prepared, discoveryDirty = true, awaitingLayout; + private final ArrayList> watched = new ArrayList<>(); + private ViewTreeObserver discoveryObserver; + private ViewTreeObserver.OnGlobalLayoutListener discoveryLayout; + private long discoveryGeneration; + private Attachment attachment; + private final class Attachment implements View.OnAttachStateChangeListener { + private boolean owns(View view) { + if (attachment != this || !active) return false; + if (view == hostRoot.get()) return true; + for (WeakReference reference : watched) if (view == reference.get()) return true; + return false; + } + @Override public void onViewAttachedToWindow(View view) { + try { + if (!owns(view)) return; + invalidateHosts(); + awaitingLayout = true; + // ViewGroup attaches itself before its children. Discover after the resulting + // layout, rather than caching a partially attached tree from this callback. + observeDiscovery(); + } catch (Throwable failure) { lifecycleFailed(failure); } + } + @Override public void onViewDetachedFromWindow(View view) { + try { + if (!owns(view)) return; + invalidateHosts(); + awaitingLayout = true; + if (view == hostRoot.get()) stopObservingDiscovery(); + else observeDiscovery(); + // Android detaches before removing the child from its parent's array. Never + // rediscover synchronously here: that would cache the disappearing subtree. + } catch (Throwable failure) { lifecycleFailed(failure); } + } + } + + QsClipping(ClassLoader cl) { + this(cl, new HookSet()); + } + + QsClipping(ClassLoader cl, HookSet hooks) { + this.cl = cl; + this.hooks = hooks; + } + + void install() throws Throwable { + Class modifier = XposedHelpers.findClass("androidx.compose.ui.Modifier", cl); + Class shape = XposedHelpers.findClass("androidx.compose.ui.graphics.Shape", cl); + // ClipKt helpers are AOT-inlined. Their large default graphicsLayer factory is not. + // Adjust the viewport modifier when composed, instead of hooking every rendering backend + // for every animated layer throughout SystemUI. This also survives modifier updates. + hooks.findAndHookMethod("androidx.compose.ui.graphics.GraphicsLayerModifierKt", cl, + "graphicsLayer-_6ThJ44$default", modifier, float.class, float.class, float.class, + float.class, float.class, float.class, float.class, shape, boolean.class, + int.class, int.class, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + int defaults = (Integer) param.args[11]; + boolean clip = (defaults & 4096) == 0 && Boolean.TRUE.equals(param.args[9]); + if (!clip) return; + Object suppliedShape = param.args[8]; + String shapeName = (defaults & 2048) != 0 || suppliedShape == null + ? "androidx.compose.ui.graphics.RectangleShapeKt$RectangleShape$1" + : suppliedShape.getClass().getName(); + // Rounded tile/control masks can never match this policy. Avoid walking + // the UI thread's stack for each one during a cold scene composition. + if (!isViewportShape(shapeName)) return; + String caller = nearestQsCaller(); + adjustViewport(param.args, shapeName, caller); + } + }); + XposedBridge.log(Entry.TAG + ": QS viewport clips removed during composition (caller lookup: " + + (fastCallerLookup() ? "frame classes" : "stack trace") + ")"); + } + + // The tile box's rounded/bottom-cut masks also hide off-page tiles. Removing them + // exposes extra rows over the brightness/volume controls, especially on stock One UI 9. + // The outer grid item moves as one layer, so its internal scrolling masks stay native. + static boolean adjustViewport(Object[] args, String shapeName, String caller) { + int defaults = (Integer) args[11]; + if ((defaults & 4096) != 0 || !Boolean.TRUE.equals(args[9]) || caller == null + || !(caller.startsWith(UI + "panel.") || caller.startsWith(UI + "base.spannablegrid.")) + || !isViewportShape(shapeName)) return false; + args[9] = false; + // Auto alpha can still bound descendants to an intermediate texture. Change only + // these viewport layers; controls and explicit Offscreen retain native compositing. + if ((defaults & 65536) != 0 || (Integer) args[10] == 0) { + args[10] = 2; // CompositingStrategy.ModulateAlpha + args[11] = defaults & ~65536; + } + return true; + } + + static boolean isViewportShape(String shapeClass) { + return shapeClass.equals("androidx.compose.foundation.VerticalScrollableClipShape") + || shapeClass.equals("androidx.compose.foundation.HorizontalScrollableClipShape") + || shapeClass.equals("androidx.compose.ui.graphics.RectangleShapeKt$RectangleShape$1"); + } + + /** + * Modifier.alpha() and clipToBounds() also reach this hook with a rectangular clip, so it + * runs for most QS tiles on every composition. getStackTrace() builds a StackTraceElement + * per frame and decodes each method's line table from SystemUI's dex; after the phone idles + * those pages are evicted, and the first QS/shade composition stalls on disk reads. + * ART's internal trace already holds every frame's declaring class, in the same order. + */ + private static final java.lang.reflect.Field BACKTRACE = backtraceField(); + static final String UNRESOLVED = new String("unresolved"); + + private static java.lang.reflect.Field backtraceField() { + try { + java.lang.reflect.Field field = Throwable.class.getDeclaredField("backtrace"); + field.setAccessible(true); + return field; + } catch (Throwable unavailable) { return null; } + } + + private static boolean fastCallerLookup() { + try { + Object trace = BACKTRACE == null ? null : BACKTRACE.get(new Throwable()); + return trace instanceof Object[] && nearestQsCaller((Object[]) trace) != UNRESOLVED; + } catch (Throwable unavailable) { return false; } + } + + private static String nearestQsCaller() { + Throwable here = new Throwable(); + if (BACKTRACE != null) { + try { + Object trace = BACKTRACE.get(here); + if (trace instanceof Object[]) { + String caller = nearestQsCaller((Object[]) trace); + if (caller != UNRESOLVED) return caller; + } + } catch (Throwable ignored) { } + } + return nearestQsCaller(here.getStackTrace()); + } + + /** ART layout: [0] method/dex-pc pointer array (2 slots per frame), then each frame's class. */ + static String nearestQsCaller(Object[] trace) { + int depth = trace.length - 1; + if (depth < 1) return UNRESOLVED; + Object pointers = trace[0]; + int slots = pointers instanceof long[] ? ((long[]) pointers).length + : pointers instanceof int[] ? ((int[]) pointers).length : -1; + if (slots != depth * 2) return UNRESOLVED; + for (int i = 1; i <= depth; i++) { + // A copied default method stores its class loader here, and its reported frame + // class is the interface. Use the exact element path for such stacks. + if (!(trace[i] instanceof Class)) return UNRESOLVED; + String name = ((Class) trace[i]).getName(); + if (name.startsWith(UI)) return name; + } + return null; + } + + static String nearestQsCaller(StackTraceElement[] frames) { + for (StackTraceElement frame : frames) { + String name = frame.getClassName(); + if (name.startsWith(UI)) return name; + } + return null; + } + + /** View wrappers can still clip the entire Compose result, independently of Compose layers. */ + void prepareHosts(View qs) { + if (!active) return; + if (hostRoot.get() != qs) { + clearHost(); + if (qs == null) return; + hostRoot = new WeakReference<>(qs); + attachment = new Attachment(); + qs.addOnAttachStateChangeListener(attachment); + } + if (qs == null || prepared) return; + // A detached tree can be rewritten without detach callbacks. Do not certify its cache. + // Missing discovery sleeps until an actual layout/attachment signal, not every frame. + if (awaitingLayout || !qs.isAttachedToWindow() || !qs.isShown()) { observeDiscovery(); return; } + if (discoveryDirty) discoverHosts(qs); + } + + void setActive(boolean active) { + this.active = active; + if (!active) clearHost(); + } + + private void discoverHosts(View qs) { + discoveryDirty = false; + View root = findRoot(qs, 0); + if (root == null) { observeDiscovery(); return; } + collectHosts(root); + View current = root; + while (current != qs) { + ViewParent parent = current.getParent(); + if (!(parent instanceof ViewGroup)) break; + ViewGroup group = (ViewGroup) parent; + hosts.add(new WeakReference<>(group)); + current = group; + } + for (WeakReference reference : hosts) { + ViewGroup host = reference.get(); + if (host == null) continue; + if (host.getClipChildren()) host.setClipChildren(false); + if (host.getClipToPadding()) host.setClipToPadding(false); + if (host.getClipBounds() != null) host.setClipBounds(null); + if (host.getClipToOutline()) host.setClipToOutline(false); + if (host != qs) { + host.addOnAttachStateChangeListener(attachment); + watched.add(new WeakReference<>(host)); + } + } + prepared = true; + stopObservingDiscovery(); + } + + private void invalidateHosts() { + prepared = false; + discoveryDirty = true; + hosts.clear(); + for (WeakReference reference : watched) { + View view = reference.get(); + if (view != null) view.removeOnAttachStateChangeListener(attachment); + } + watched.clear(); + } + + /** Only unresolved discovery observes global layout; the successful cache has no global hook. */ + private void observeDiscovery() { + View qs = hostRoot.get(); + if (!active || qs == null || !qs.isAttachedToWindow()) return; + ViewTreeObserver observer = qs.getViewTreeObserver(); + if (discoveryObserver == observer && observer.isAlive()) return; + stopObservingDiscovery(); + if (!observer.isAlive()) return; + long generation = discoveryGeneration; + discoveryObserver = observer; + discoveryLayout = () -> { + try { + if (generation != discoveryGeneration || !active || qs != hostRoot.get() + || !qs.isAttachedToWindow() || !qs.isShown()) return; + // A failed scan is retried only after real layout/content availability changes. + awaitingLayout = false; + discoverHosts(qs); + } catch (Throwable failure) { lifecycleFailed(failure); } + }; + observer.addOnGlobalLayoutListener(discoveryLayout); + } + + private void stopObservingDiscovery() { + discoveryGeneration++; + if (discoveryLayout != null) { + if (discoveryObserver != null && discoveryObserver.isAlive()) + discoveryObserver.removeOnGlobalLayoutListener(discoveryLayout); + // Attachment merges a floating observer before attach listeners run. Its listener + // may now belong to the current live tree even when the stored observer is dead. + View qs = hostRoot.get(); + if (qs != null) { + ViewTreeObserver current = qs.getViewTreeObserver(); + if (current != discoveryObserver && current.isAlive()) + current.removeOnGlobalLayoutListener(discoveryLayout); + } + } + discoveryObserver = null; + discoveryLayout = null; + } + + private void clearHost() { + stopObservingDiscovery(); + invalidateHosts(); + View qs = hostRoot.get(); + if (qs != null) qs.removeOnAttachStateChangeListener(attachment); + attachment = null; + awaitingLayout = false; + hostRoot = new WeakReference<>(null); + } + + private void lifecycleFailed(Throwable failure) { + clearHost(); + XposedBridge.log(Entry.TAG + ": QS clipping lifecycle: " + failure); + } + + private static View findRoot(View v, int depth) { + if (ROOT.equals(v.getClass().getName())) return v; + if (!(v instanceof ViewGroup) || depth >= 4) return null; + ViewGroup group = (ViewGroup) v; + for (int i = 0; i < group.getChildCount(); i++) { + View found = findRoot(group.getChildAt(i), depth + 1); + if (found != null) return found; + } + return null; + } + + private void collectHosts(View v) { + if (!(v instanceof ViewGroup)) return; + ViewGroup group = (ViewGroup) v; + hosts.add(new WeakReference<>(group)); + // Stop here: embedded native controls below AndroidViewsHandler keep their own masks. + if (v.getClass().getName().equals("androidx.compose.ui.platform.AndroidComposeView")) return; + for (int i = 0; i < group.getChildCount(); i++) collectHosts(group.getChildAt(i)); + } + +} diff --git a/hook/src/main/java/dev/colormotion/QsComposeLifecycle.java b/hook/src/main/java/dev/colormotion/QsComposeLifecycle.java new file mode 100644 index 00000000..4a5de167 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsComposeLifecycle.java @@ -0,0 +1,214 @@ +package dev.colormotion; + +import android.view.View; +import android.view.ViewGroup; + +import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** Retires only the detached child observed during this controller's last native creation. + * + * Stock retains child-owned repeat listeners across controller attachments. UI9 disposes + * content but retains wrappers. Native creation/configuration/flows must still run afresh. + * This optional optimization does not recover children created before its observation, nor + * certify ownership against arbitrary third-party suppression/substitution of native calls. + */ +final class QsComposeLifecycle extends XC_MethodHook { + private static final String CONTROLLER = "com.android.systemui.samsung.quicksetting.SecQSPanelCompose"; + private static final String ROOT = "com.android.systemui.samsung.quicksetting.view.SecQSPanelComposeRoot"; + private static final String CALL = "dev.colormotion.QsComposeLifecycle.call"; + private static final int MAX_OWNERS = 32, MAX_CHILDREN = 256, MAX_LOGS = 4; + + private final Class controllerType, rootType, composeType; + private final Field rootField, composeField; + private final Method dispose; + private final ArrayList owners = new ArrayList<>(); + private boolean busy, reentered; + private int failures; + + /** No controller, root or view is strongly retained between calls. Identity, not equals. */ + private static final class Owner { + final WeakReference controller; + final WeakReference root; + final WeakReference view; + Owner(Object controller, ViewGroup root, View view) { + this.controller = new WeakReference<>(controller); + this.root = new WeakReference<>(root); + this.view = new WeakReference<>(view); + } + } + + /** Strong references exist only in the synchronous before/native/after invocation. */ + private static final class Call { + Object controller; + ViewGroup root; + View[] children; + } + + private QsComposeLifecycle(ClassLoader cl) throws ReflectiveOperationException { + controllerType = XposedHelpers.findClass(CONTROLLER, cl); + rootType = XposedHelpers.findClass(ROOT, cl); + composeType = XposedHelpers.findClass("androidx.compose.ui.platform.ComposeView", cl); + Class base = XposedHelpers.findClass("com.android.systemui.util.ViewController", cl); + Class abstractCompose = XposedHelpers.findClass("androidx.compose.ui.platform.AbstractComposeView", cl); + require(Modifier.isFinal(controllerType.getModifiers()) && controllerType.getSuperclass() == base); + require(ViewGroup.class.isAssignableFrom(rootType) && ViewGroup.class.isAssignableFrom(composeType) + && composeType.getSuperclass() == abstractCompose); + rootField = base.getDeclaredField("mView"); + require(rootField.getType() == View.class && !Modifier.isStatic(rootField.getModifiers())); + rootField.setAccessible(true); + Field optional; + try { + optional = controllerType.getDeclaredField("composeView"); + require(optional.getType() == composeType && !Modifier.isStatic(optional.getModifiers())); + optional.setAccessible(true); + } catch (NoSuchFieldException stock) { optional = null; } + composeField = optional; + dispose = abstractCompose.getDeclaredMethod("disposeComposition"); + requireVoidInstance(dispose); + } + + /** Binding precedes registration; the sole registered hook belongs to the caller's HookSet. */ + static void installOptional(ClassLoader cl, HookSet hooks) { + try { + QsComposeLifecycle callback = new QsComposeLifecycle(cl); + Method attach = callback.controllerType.getDeclaredMethod("attachComposeView"); + requireVoidInstance(attach); + int count = 0; + for (Method method : callback.controllerType.getDeclaredMethods()) { + if (method.getName().equals("attachComposeView")) count++; + } + require(count == 1); + // Do not put fallible binding/logging after this registration, or install a + // private HookSet that the containing QS pipeline cannot roll back. + hooks.method(attach, callback); + } catch (Throwable failure) { + try { XposedBridge.log("ColorMotion: optional QS Compose lifecycle unavailable: " + failure); } + catch (Throwable ignored) {} + } + } + + private static void require(boolean known) throws NoSuchMethodException { + if (!known) throw new NoSuchMethodException("Unsupported native QS Compose lifecycle shape"); + } + + private static void requireVoidInstance(Method method) throws NoSuchMethodException { + int flags = method.getModifiers(); + require(method.getReturnType() == void.class && method.getParameterCount() == 0 + && Modifier.isPublic(flags) && Modifier.isFinal(flags) && !Modifier.isStatic(flags)); + } + + @Override protected synchronized void beforeHookedMethod(MethodHookParam param) { + try { + if (param.thisObject == null || param.thisObject.getClass() != controllerType) return; + if (busy) { + // Disposal/removal can invoke external callbacks. Nested native calls still + // run, but neither their child nor the outer call's child is safe to claim. + reentered = true; + owners.clear(); + return; + } + Call call = new Call(); + param.setObjectExtra(CALL, call); + busy = true; + reentered = false; + call.controller = param.thisObject; + begin(call); + } catch (Throwable failure) { owners.clear(); failed(failure); } + } + + private void begin(Call call) throws Throwable { + Object value = rootField.get(call.controller); + ViewGroup root = value != null && value.getClass() == rootType ? (ViewGroup) value : null; + Owner previous = null; + for (int i = owners.size() - 1; i >= 0; i--) { + Owner owner = owners.get(i); + Object controller = owner.controller.get(); + ViewGroup oldRoot = owner.root.get(); + View old = owner.view.get(); + if (controller == null || oldRoot == null || old == null + || controller == call.controller || oldRoot == root) { + owners.remove(i); + if (controller == call.controller && oldRoot == root && old != null) previous = owner; + // A different controller using this root invalidates its former claim. + } + } + if (root == null || !root.isAttachedToWindow()) return; + if (previous != null) { + View old = previous.view.get(); + if (old == null || old.getClass() != composeType || old.getParent() != root + || old.isAttachedToWindow() || root.getLayoutTransition() != null + || old.getAnimation() != null) return; + // Forget the claim before cleanup. A failure must never retry a partially + // disposed/removed child on a future attachment. + dispose.invoke(old); + if (reentered || !root.isAttachedToWindow() || rootField.get(call.controller) != root || old.getParent() != root + || old.isAttachedToWindow() || root.getLayoutTransition() != null + || old.getAnimation() != null) return; + root.removeView(old); + if (reentered || !root.isAttachedToWindow() || old.getParent() != null || rootField.get(call.controller) != root) return; + } + if (reentered) return; + View[] children = snapshot(root); + call.root = root; + call.children = children; + } + + private static View[] snapshot(ViewGroup root) { + int count = root.getChildCount(); + if (count < 0 || count > MAX_CHILDREN) throw new IllegalStateException("Unexpected QS child count"); + View[] result = new View[count]; + for (int i = 0; i < count; i++) { + View view = root.getChildAt(i); + if (view == null || view.getParent() != root) throw new IllegalStateException("Unstable QS children"); + result[i] = view; + } + if (root.getChildCount() != count) throw new IllegalStateException("QS children changed during snapshot"); + return result; + } + + @Override protected synchronized void afterHookedMethod(MethodHookParam param) { + Call call = null; + try { + call = (Call) param.getObjectExtra(CALL); + if (call == null) return; + param.setObjectExtra(CALL, null); + if (param.hasThrowable() || reentered || call.root == null || call.children == null || !call.root.isAttachedToWindow() + || param.thisObject != call.controller || rootField.get(call.controller) != call.root) return; + View candidate = null; + for (View view : snapshot(call.root)) { + boolean existed = false; + for (View old : call.children) if (old == view) { existed = true; break; } + if (existed) continue; + if (candidate != null || view.getClass() != composeType) return; + candidate = view; + } + if (candidate == null || (composeField != null && composeField.get(call.controller) != candidate)) return; + if (owners.size() == MAX_OWNERS) owners.remove(0); + owners.add(new Owner(call.controller, call.root, candidate)); + } catch (Throwable failure) { owners.clear(); failed(failure); } + finally { + if (call != null) { + call.controller = null; + call.root = null; + call.children = null; + busy = reentered = false; + } + } + } + + private void failed(Throwable failure) { + if (failures < MAX_LOGS) { + failures++; + try { XposedBridge.log("ColorMotion: QS Compose lifecycle skipped: " + failure); } + catch (Throwable ignored) {} + } + } +} diff --git a/hook/src/main/java/dev/colormotion/QsItemBinding.java b/hook/src/main/java/dev/colormotion/QsItemBinding.java new file mode 100644 index 00000000..a4d3ee11 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsItemBinding.java @@ -0,0 +1,84 @@ +package dev.colormotion; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import de.robv.android.xposed.XposedHelpers; + +/** Match the native composable ABI and animate main grid cells, not nested/editable child tiles. */ +final class QsItemBinding { + final Method editableItem, header; + private final Class cellData; + private final Method foldIn; + private final Object containsCell; + + QsItemBinding(ClassLoader cl) throws ReflectiveOperationException { + Class modifier = XposedHelpers.findClass("androidx.compose.ui.Modifier", cl); + Class function2 = XposedHelpers.findClass("kotlin.jvm.functions.Function2", cl); + Class composer = XposedHelpers.findClass("androidx.compose.runtime.Composer", cl); + cellData = XposedHelpers.findClass( + "com.android.systemui.samsung.quicksetting.ui.base.spannablegrid.SpannableGridCellData", cl); + editableItem = findEditableItem(XposedHelpers.findClass( + "com.android.systemui.samsung.quicksetting.ui.base.editable.EditableItemKt", cl), modifier, composer); + header = findHeader(XposedHelpers.findClass( + "com.android.systemui.samsung.quicksetting.ui.panel.SecQuickSettingHeaderKt", cl), modifier, composer); + foldIn = modifier.getMethod("foldIn", Object.class, function2); + containsCell = Proxy.newProxyInstance(cl, new Class[] {function2}, (proxy, method, args) -> { + if (method.getName().equals("invoke")) + return Boolean.TRUE.equals(args[0]) || cellData.isInstance(args[1]); + if (method.getName().equals("hashCode")) return System.identityHashCode(proxy); + if (method.getName().equals("equals")) return proxy == args[0]; + return "ColorMotionGridCellScope"; + }); + } + + static Method findEditableItem(Class owner, Class modifier, Class composer) + throws NoSuchMethodException { + Method selected = null; + for (Method method : owner.getDeclaredMethods()) { + Class[] p = method.getParameterTypes(); + if (!method.getName().startsWith("EditableItem-") || !Modifier.isStatic(method.getModifiers()) + || method.getReturnType() != void.class || p.length < 8 + || p[0] != modifier || p[1] != String.class || p[2] != long.class || p[3] != long.class + || p[p.length - 4] != composer || p[p.length - 3] != int.class + || p[p.length - 2] != int.class || p[p.length - 1] != int.class) continue; + if (selected != null) throw new NoSuchMethodException("Ambiguous QS item ABI"); + selected = method; + } + if (selected == null) throw new NoSuchMethodException("Supported QS item ABI not found"); + return selected; + } + + static Method findHeader(Class owner, Class modifier, Class composer) throws NoSuchMethodException { + Method selected = null; + for (Method method : owner.getDeclaredMethods()) { + Class[] p = method.getParameterTypes(); + if (!method.getName().equals("SecQuickSettingHeader") || !Modifier.isStatic(method.getModifiers()) + || method.getReturnType() != void.class || (p.length != 5 && p.length != 6) + || p[1] != modifier || p[3] != composer || p[4] != int.class + || (p.length == 6 && p[5] != int.class)) continue; + if (selected != null) throw new NoSuchMethodException("Ambiguous QS header ABI"); + selected = method; + } + if (selected == null) throw new NoSuchMethodException("Supported QS header ABI not found"); + return selected; + } + + Object headerBase(Object[] args, Object companion) { + boolean defaultModifier = header.getParameterCount() == 6 && ((Integer) args[5] & 1) != 0; + return defaultModifier || args[1] == null ? companion : args[1]; + } + + void replaceHeader(Object[] args, Object decorated) { + args[1] = decorated; + if (header.getParameterCount() == 6) args[5] = (Integer) args[5] & ~1; + } + + boolean isMainGrid(Object modifier, long offset, long span) throws ReflectiveOperationException { + if (modifier == null || (int) offset < 0 || (int) span <= 0 || (int) (span >>> 32) <= 0) return false; + if (cellData.isInstance(modifier)) return true; + // One UI 9 adds a graphics layer after parent data. This traversal is composition-only, + // not a global modifier/render hook and not part of the per-frame animation path. + return Boolean.TRUE.equals(foldIn.invoke(modifier, Boolean.FALSE, containsCell)); + } +} diff --git a/hook/src/main/java/dev/colormotion/QsModel.java b/hook/src/main/java/dev/colormotion/QsModel.java new file mode 100644 index 00000000..1cfa2136 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsModel.java @@ -0,0 +1,560 @@ +package dev.colormotion; + +import java.util.Arrays; + +/** + * Control-center motion model (reference: com.oplus.systemui.plugins.qs.animator), free of Android + * dependencies so it can be replayed offline against reference recordings. + * + * Sources: QSPanelExpandFraction (fraction + element thresholds), QSPanelTranslationY (panel + * translation), QSPanelAnimatorManager.setFirst/SecondElementVisible + QSElementAnimator (header and + * row springs), PullAnimationProxy.negativeSpringOffsetY (row offsets), QsElementsChain (overscroll + * stretch and Rebound chain). + * + * Distances in ColorOS are raw pixels on a 1272 px wide panel; {@link #px} rescales them to the + * device so the motion keeps the same proportions on screen. + */ +final class QsModel { + static final int MAX_ROWS = 24; + static final float COLOROS_WIDTH_PX = 1272f; + + /** Device pixels per ColorOS pixel. */ + float px = 1f; + /** QSPanelTranslationY.destTranslationY in ColorOS px (layout dependent, default 102). */ + float destColorOs = ColorOsParams.QS_DEST_TRANSLATION_PX; + /** Row index within its component (PullAnimationProxy negativeSpringOffsetY). */ + int[] subIndexOfRow = new int[MAX_ROWS]; + /** + * Node index of each row: ColorOS counts grid cell rows, so a two-cell-tall block advances the + * index by two. Drives start scale, spring response, fade delay and chain position. + */ + int[] nodeOfRow = new int[MAX_ROWS]; + + // ---- blur (QSPanelExpandFraction.blurFractionAnimation: damping 1, response 0.35, mvc 0.001) + final Spring blurRaw = new Spring().damping(1.0).response(0.35f).minimumVisibleChange(0.001f); + private float lastFraction; + + // ---- panel translation (QSPanelTranslationY) + final Spring translation = new Spring().response(ColorOsParams.QS_TRANSLATION_RESPONSE) + .bounce(ColorOsParams.QS_TRANSLATION_BOUNCE).minimumVisibleChange(1f); + private float lastMoveResponse; + + // ---- elements + final Spring[] alpha = new Spring[MAX_ROWS]; + final Spring[] scale = new Spring[MAX_ROWS]; + final Spring[] neg = new Spring[MAX_ROWS]; + private final long[] showAt = new long[MAX_ROWS]; + private long secondVisibleSince; + /** Shared opening policy: distance gate, then a timed fade; independent of swipe velocity. */ + static final float OPENING_REVEAL_FRACTION = 0.25f; + static final long OPENING_FADE_MS = 200L; + static final long MIN_BLUR_OPEN_MS = 200L; + private static final float OPENING_ELEMENT_BOUNCE = 0.50f; + private static final float OPENING_HEADER_BOUNCE = 0.42f; + private boolean openingPresentation; + private boolean revealLatched; + private boolean openingContentReady = true; + private long blurStartedAt = -1L; + private long revealStartedAt = -1L; + private final long[] rowReadyAt = new long[MAX_ROWS]; + final Spring headerAlpha = new Spring().minimumVisibleChange(0.00390625f); + final Spring headerScale = new Spring().minimumVisibleChange(3.0E-4f); + int rowCount = 8; + boolean firstVisible; + boolean secondVisible; + + // ---- overscroll chain (QsElementsChain) + final Spring over = new Spring().bounce(0.14f).minimumVisibleChange(1f); + final float[] overY = new float[MAX_ROWS + 1]; + private final ReboundSpring[] chain = new ReboundSpring[MAX_ROWS + 1]; + private boolean chainActive; + float rootHeight = 2772f; + private float lastOverValue = Float.NaN, lastOverPx, lastOverHeight; + + // ---- gesture state + boolean closedOnDown = true; + float yVelocity; + boolean onFling; + boolean toExpand; + float curCalcFinalPosition; + private long nowMs; + + QsModel() { + for (int i = 0; i < MAX_ROWS; i++) { + alpha[i] = new Spring().minimumVisibleChange(0.00390625f); + scale[i] = new Spring().minimumVisibleChange(3.0E-4f); + neg[i] = new Spring().minimumVisibleChange(3.0E-4f); + subIndexOfRow[i] = i; + nodeOfRow[i] = i; + } + for (int i = 0; i <= MAX_ROWS; i++) { + chain[i] = new ReboundSpring(); + } + reset(); + } + + float dest() { + return destColorOs * px; + } + + /** getDefaultSettingEngine(): dest / 0.86. */ + float engine() { + return dest() / ColorOsParams.QS_ENGINE_DIVISOR; + } + + /** Finger travel (device px) for the full fraction range: 300 ColorOS px. */ + float dragDistanceForFull() { + return ColorOsParams.QS_DRAG_PX_FOR_FULL * px; + } + + // ------------------------------------------------------------------ fraction (QSPanelExpandFraction) + + /** onMove: response 0.2, or 0.35 -> 0.2 over the first 20% after a fast start from closed. */ + float dragResponse(float rawFraction) { + if (closedOnDown && yVelocity > ColorOsParams.QS_FAST_VELOCITY) { + float t = clamp(rawFraction / ColorOsParams.QS_FAST_FRACTION_RANGE, 0f, 1f); + return lerpResponse(ColorOsParams.QS_MAX_FAST_RESPONSE, ColorOsParams.QS_DRAG_RESPONSE, t); + } + return ColorOsParams.QS_DRAG_RESPONSE; + } + + /** onFling + fractionAnimation update listener: per-frame response while flinging. */ + float flingResponse(float rawFraction) { + float base = toExpand ? ColorOsParams.QS_FLING_EXPAND_RESPONSE : ColorOsParams.QS_FLING_COLLAPSE_RESPONSE; + if (closedOnDown && yVelocity > ColorOsParams.QS_FAST_VELOCITY) { + return lerpResponse(ColorOsParams.QS_FLING_FAST_RESPONSE, base, + clamp(rawFraction / ColorOsParams.QS_FAST_FRACTION_RANGE, 0f, 1f)); + } + return base; + } + + // ------------------------------------------------------------------ gesture input + + /** A new closed-panel gesture must reveal from hidden, including a fling with no drag frames. */ + void beginGesture(boolean closedOnDown, float startVelocity) { + if (closedOnDown) reset(); + dragStart(closedOnDown, startVelocity); + } + + void dragStart(boolean closedOnDown, float startVelocity) { + this.closedOnDown = closedOnDown; + this.yVelocity = startVelocity; + this.onFling = false; + this.toExpand = false; + } + + /** + * One finger move. delta = finger travel since touch down (device px), startFraction = panel + * fraction when the gesture started. Returns the fraction target for the expansion spring. + */ + float drag(float delta, float startFraction) { + onFling = false; + float engine = engine(); + float f2 = engine / dragDistanceForFull(); + float start = startFraction * engine; + float f3 = delta * f2 + start; + float target = clamp(f3 / engine, 1.0E-5f, 1f); + curCalcFinalPosition = target; + // QSPanelExpandFraction.onMove: blur response 0.35, 0.45 -> 0.35 over the first 20% after a + // fast start from closed, 0.1 when collapsing right at the top. + float blurResponse = 0.35f; + if (closedOnDown && yVelocity > ColorOsParams.QS_FAST_VELOCITY) { + blurResponse = lerpResponse(0.45f, 0.35f, clamp(blurRaw.value / 0.2f, 0f, 1f)); + } else if (target == 1.0E-5f && lastFraction < 0.015f) { + blurResponse = 0.1f; + } + blurRaw.response(blurResponse); + blurRaw.target = target; + translationOnMove(f3); + // Finger travel past 86% of the engine distance stretches the rows (onMoveOver). + float f4 = engine * ColorOsParams.QS_ENGINE_DIVISOR; + float overDistance = start < f4 ? (f3 - f4) / f2 : delta; + if (overDistance >= 0f) { + moveOver(overDistance); + } + return target; + } + + void release(float velocity, boolean expand) { + // Native layout/height handoffs can retarget the same release. Keep the live + // chain velocities instead of launching the rebound a second time. + boolean newRelease = !onFling || toExpand != expand; + onFling = true; + toExpand = expand; + if (!expand) { + closedOnDown = false; + } + if (velocity > 0f) { + yVelocity = velocity; + } + curCalcFinalPosition = expand ? 1f : 0f; + // QSPanelExpandFraction.onFling: blur 0.35 (0.45 for a fast open from closed; the 0.45 collapse + // value only applies without motion blur, which this device tier has). + blurRaw.response(expand && closedOnDown && yVelocity > ColorOsParams.QS_FAST_VELOCITY ? 0.45f : 0.35f); + blurRaw.target = expand ? 1f : 0f; + // QSPanelTranslationY.onFling + float response = (closedOnDown && velocity > ColorOsParams.QS_FAST_VELOCITY) + ? ColorOsParams.QS_TRANSLATION_MAX_RESPONSE : ColorOsParams.QS_TRANSLATION_RESPONSE; + translation.response(response).bounce(ColorOsParams.QS_TRANSLATION_BOUNCE); + lastMoveResponse = Float.NaN; // Release reconfigured the spring outside the MOVE cache. + translation.target = expand ? 0f : -dest(); + if (newRelease) startRebound(); + } + + /** QSPanelTranslationY.onMove. */ + private void translationOnMove(float f3) { + float dest = dest(); + float value = f3 - (closedOnDown ? dest : engine()); + float target = clamp(value, -dest, 0f); + float response = ColorOsParams.QS_TRANSLATION_RESPONSE; + if (yVelocity > ColorOsParams.QS_FAST_VELOCITY) { + float t = clamp(Math.abs((Math.abs(translation.value) - Math.abs(dest)) / (dest * 0.1f)), 0f, 1f); + response = lerpResponse(ColorOsParams.QS_TRANSLATION_MAX_RESPONSE, ColorOsParams.QS_TRANSLATION_RESPONSE, t); + } + if (response != lastMoveResponse) { + translation.response(response).bounce(ColorOsParams.QS_TRANSLATION_BOUNCE); + lastMoveResponse = response; + } + translation.target = target; + } + + // ------------------------------------------------------------------ elements + + /** QSPanelExpandFraction.onFractionChanged. */ + void onFraction(float f) { + lastFraction = f; + boolean fast = yVelocity > 1000f && curCalcFinalPosition >= ColorOsParams.QS_SECOND_ELEMENT; + setFirstElementVisible(f >= (fast ? ColorOsParams.QS_FAST_ELEMENT : 0.5f)); + setSecondElementVisible(f >= (fast ? ColorOsParams.QS_FAST_ELEMENT : ColorOsParams.QS_SECOND_ELEMENT)); + } + + /** Hold elements hidden until the panel reaches the same distance on every opening route. */ + void onOpeningFraction(float f) { + lastFraction = f; + if (!openingPresentation) { + openingPresentation = true; + if (closedOnDown) blurStartedAt = nowMs; + // Taking over an already visible panel must not hide or replay its elements. + if (firstVisible || secondVisible) { + revealLatched = true; + revealStartedAt = nowMs - OPENING_FADE_MS - 16L * MAX_ROWS; + } + } + if (!revealLatched && openingContentReady && f >= OPENING_REVEAL_FRACTION) { + revealLatched = true; + revealStartedAt = nowMs; + } + setFirstElementVisible(revealLatched); + setSecondElementVisible(revealLatched); + } + + /** QS first composition can arrive after the native panel has already crossed the gate. */ + void setOpeningContentReady(boolean ready) { + openingContentReady = ready; + if (ready && openingPresentation && !revealLatched) onOpeningFraction(lastFraction); + } + + void noteRowReady(int row) { + rowReadyAt[row] = nowMs; + } + + private void setFirstElementVisible(boolean visible) { + if (firstVisible == visible) { + return; + } + firstVisible = visible; + headerAlpha.response(visible ? 0.3f : 0.2f).bounce(visible ? 0f : 0.15f); + headerAlpha.target = visible ? 1f : 0f; + headerScale.response(0.4f).bounce(visible && openingPresentation ? OPENING_HEADER_BOUNCE : 0.15f); + headerScale.target = visible ? 1f : 0.72f; + } + + private void setSecondElementVisible(boolean visible) { + if (secondVisible == visible) { + return; + } + secondVisible = visible; + if (visible) secondVisibleSince = nowMs; + for (int i = 0; i < rowCount; i++) { + configureRowVisibility(i, visible); + } + } + + /** Compose can discover rows after a short flick has already crossed the reveal threshold. */ + void setRowCount(int count) { + int previous = rowCount; + rowCount = Math.max(1, Math.min(MAX_ROWS, count)); + for (int i = previous; i < rowCount; i++) configureRowVisibility(i, secondVisible); + } + + private void configureRowVisibility(int i, boolean visible) { + int node = nodeOfRow[i]; + float response = ColorOsParams.QS_ELEMENT_SCALE_RESPONSE + 0.05f * (node + 1); + scale[i].response(response).bounce(visible && openingPresentation + ? OPENING_ELEMENT_BOUNCE : ColorOsParams.QS_ELEMENT_SCALE_BOUNCE); + scale[i].target = visible ? 1f : hideScale(node); + neg[i].response(response).bounce(visible && openingPresentation ? OPENING_ELEMENT_BOUNCE : 0.2f); + neg[i].target = visible ? 1f : 0f; + if (visible) { + showAt[i] = secondVisibleSince + 16L * node; + } else { + showAt[i] = -1; + alpha[i].response(ColorOsParams.QS_ELEMENT_ALPHA_HIDE_RESPONSE).bounce(0f); + alpha[i].target = 0f; + } + } + + static float hideScale(int i) { + return Math.max(0f, ColorOsParams.QS_ELEMENT_HIDE_SCALE - 0.05f * i); + } + + // ------------------------------------------------------------------ overscroll chain + + private void moveOver(float distance) { + chainActive = false; + float response = 0.3f; + if (closedOnDown && yVelocity > 1000f) { + over.minimumVisibleChange(0.001f); + float t = clamp(over.value / (rootHeight * 0.2f), 0f, 1f); + response = 0.35f - (0.35f - 0.3f) * t; + } else { + over.minimumVisibleChange(1f); + } + over.response(response).bounce(0.14f); + over.target = Math.max(0f, distance); + } + + private void startRebound() { + lastOverValue = Float.NaN; + over.snapTo(0f); + if (overY[0] <= 0f) { + chainActive = false; + Arrays.fill(overY, 0f); + return; + } + chainActive = true; + for (int i = 0; i <= MAX_ROWS; i++) { + ReboundSpring s = chain[i]; + if (i == 0) { + s.origami(150, 30); + } else { + s.origami(450, 20); + } + s.setCurrentValue(overY[i]); + s.endValue = overY[i]; + s.restSpeed = 3.0; + s.restDisplacement = 0.5; + } + chain[0].setEndValue(0); + } + + /** QsElementsChain.setTranslationYOverValue (distances in ColorOS px, rescaled). */ + private void updateOverRows(float fDevice) { + // A held stretch can settle while row/header springs still request frames. Its + // geometry is independent of those springs, so reuse it until an input changes. + if (lastOverValue == fDevice && lastOverPx == px && lastOverHeight == rootHeight) return; + lastOverValue = fDevice; + lastOverPx = px; + lastOverHeight = rootHeight; + float f = fDevice / px; + float root = rootHeight / px; + float sign = Math.signum(f); + float absolute = Math.abs(f); + float common = (float) ((1.0 - Math.exp(-f / 120.0)) * 108.0); + for (int i = 0; i <= MAX_ROWS; i++) { + float big = 2000f * i + root; + float stretch = sign * (1f - 1f / ((absolute * (i * 0.02f + 0.25f)) / big + 1f)) * big; + overY[i] = (stretch + common) * px; + } + } + + // ------------------------------------------------------------------ stepping + + /** Disabled system animations finish the entire release, including not-yet-discovered rows. */ + void finishRebound() { + if (!chainActive) return; + chainActive = false; + Arrays.fill(overY, 0f); + lastOverValue = Float.NaN; + } + + /** Advances everything by dt milliseconds. Returns true while anything still moves. */ + boolean step(long dtMs) { + nowMs += dtMs; + boolean busy = false; + // Use the existing panel clock. No extra animator, timer or layout invalidation. + busy |= blurStartedAt >= 0L && nowMs - blurStartedAt < MIN_BLUR_OPEN_MS; + if (openingPresentation && revealLatched) { + int lastNode = 0; + for (int i = 0; i < rowCount; i++) lastNode = Math.max(lastNode, nodeOfRow[i]); + busy |= nowMs - revealStartedAt < OPENING_FADE_MS + 16L * lastNode; + for (int i = 0; i < rowCount; i++) busy |= nowMs - rowReadyAt[i] < OPENING_FADE_MS; + } + if (onFling && (closedOnDown || !toExpand)) { + // blurFractionAnimation update listener while flinging. + float r = 0.35f; + if (toExpand && yVelocity > ColorOsParams.QS_FAST_VELOCITY) { + r = lerpResponse(0.45f, 0.35f, clamp(blurRaw.value / 0.2f, 0f, 1f)); + } else if (!toExpand && lastFraction < 0.015f) { + r = 0.15f; + } + blurRaw.response(r); + } + busy |= stepOne(blurRaw, dtMs); + busy |= stepOne(translation, dtMs); + for (int i = 0; i < rowCount; i++) { + if (showAt[i] >= 0 && nowMs >= showAt[i]) { + showAt[i] = -1; + alpha[i].response(ColorOsParams.QS_ELEMENT_ALPHA_SHOW_RESPONSE).bounce(0f); + alpha[i].target = 1f; + } + busy |= showAt[i] >= 0; + busy |= stepOne(alpha[i], dtMs); + busy |= stepOne(scale[i], dtMs); + busy |= stepOne(neg[i], dtMs); + } + busy |= stepOne(headerAlpha, dtMs); + busy |= stepOne(headerScale, dtMs); + if (stepOne(over, dtMs) || over.value != 0f) { + updateOverRows(over.value); + busy |= over.value != over.target || over.velocity != 0f; + } + if (chainActive) { + // The chain writes overY directly; the next finger stretch must recompute it. + lastOverValue = Float.NaN; + boolean chainBusy = false; + for (int i = 0; i <= MAX_ROWS; i++) { + chainBusy |= chain[i].advance(dtMs / 1000.0); + // COUISpringChain.onSpringUpdate: each spring pulls the next one's end value. + if (i < MAX_ROWS) { + chain[i + 1].setEndValue(chain[i].position); + } + overY[i] = (float) chain[i].position; + } + if (!chainBusy) { + chainActive = false; + Arrays.fill(overY, 0f); + } + busy |= chainBusy; + } + return busy; + } + + private static boolean stepOne(Spring s, long dt) { + if (s.value == s.target && s.velocity == 0f) { + return false; + } + return !s.step(dt); + } + + /** Panel fully collapsed: hidden start state without animation. */ + void reset() { + for (int i = 0; i < MAX_ROWS; i++) { + showAt[i] = -1; + alpha[i].snapTo(0f); + scale[i].snapTo(hideScale(nodeOfRow[i])); + neg[i].snapTo(0f); + } + headerAlpha.snapTo(0f); + headerScale.snapTo(0.72f); + over.snapTo(0f); + Arrays.fill(overY, 0f); + lastOverValue = Float.NaN; + chainActive = false; + firstVisible = false; + secondVisible = false; + translation.snapTo(-dest()); + lastMoveResponse = Float.NaN; + blurRaw.snapTo(0f); + openingPresentation = false; + revealLatched = false; + openingContentReady = true; + blurStartedAt = -1L; + revealStartedAt = -1L; + Arrays.fill(rowReadyAt, 0L); + lastFraction = 0f; + yVelocity = 0f; + onFling = false; + } + + // ------------------------------------------------------------------ outputs + + /** Panel-to-panel handoff: content is already open; never launch a second entrance. */ + void snapShown() { + reset(); + firstVisible = secondVisible = true; + headerAlpha.snapTo(1f); + headerScale.snapTo(1f); + translation.snapTo(0f); + blurRaw.snapTo(1f); + lastFraction = 1f; + closedOnDown = false; + for (int i = 0; i < MAX_ROWS; i++) { + alpha[i].snapTo(1f); + scale[i].snapTo(1f); + neg[i].snapTo(1f); + } + } + + /** Row translation: PullAnimationProxy negativeSpringOffsetY + overTransYMap. */ + float rowTranslation(int row) { + int node = Math.min(MAX_ROWS, nodeOfRow[row] + 1); + // Give every row an entrance distance, including the first/tall QS block. This is + // the existing per-row spring, started at visible reveal rather than finger release. + int index = subIndexOfRow[row] + (openingPresentation ? 1 : 0); + return (1f - neg[row].value) * -60f * px * index + + overY[node]; + } + + float footerOpacity() { return rowAlpha(rowCount - 1); } + + float footerScale() { return 0.75f + 0.25f * headerScale.value; } + + float footerTranslation() { + int row = rowCount - 1; + int node = Math.min(MAX_ROWS, nodeOfRow[row] + 1); + return translation.value + (1f - neg[row].value) * -32f * px + overY[node]; + } + + /** QSPanelExpandFraction.getBlurFraction (motion blur: no 0.02 gate). */ + float blurFraction() { + float value = clamp(blurRaw.value / 0.86f, 0f, 1f); + return blurStartedAt < 0L ? value + : Math.min(value, timedProgress(nowMs - blurStartedAt, MIN_BLUR_OPEN_MS)); + } + + float rowAlpha(int row) { + float value = openingAlpha(alpha[row].value, 16L * nodeOfRow[row]); + return openingPresentation ? Math.min(value, + timedProgress(nowMs - rowReadyAt[row], OPENING_FADE_MS)) : value; + } + + float headerOpacity() { + return openingAlpha(headerAlpha.value, 0L); + } + + private float openingAlpha(float value, long delayMs) { + value = clamp(value, 0f, 1f); + if (!openingPresentation) return value; + if (!revealLatched) return 0f; + return Math.min(value, timedProgress(nowMs - revealStartedAt - delayMs, OPENING_FADE_MS)); + } + + private static float timedProgress(long elapsedMs, long durationMs) { + float t = clamp(elapsedMs / (float) durationMs, 0f, 1f); + return t * t * (3f - 2f * t); + } + + float headerTranslation() { + return Math.max(overY[0], 0f); + } + + static float clamp(float v, float lo, float hi) { + return Math.max(lo, Math.min(hi, v)); + } + + /** MonoSpline$$ExternalSyntheticOutline0.m(max, min, t, max) = max - (max - min) * t. */ + static float lerpResponse(float max, float min, float t) { + return max - (max - min) * t; + } +} diff --git a/hook/src/main/java/dev/colormotion/QsRows.java b/hook/src/main/java/dev/colormotion/QsRows.java new file mode 100644 index 00000000..43244f46 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsRows.java @@ -0,0 +1,666 @@ +package dev.colormotion; + +import android.view.Choreographer; +import android.view.View; +import android.view.ViewTreeObserver; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** + * Binds {@link QsModel} to One UI 8.5's Compose control center. + * + * Each grid item (EditableItem) and the header (SecQuickSettingHeader) get an extra graphicsLayer + * whose block reads the model. Each motion row has a separate snapshot state, changed only when + * its visible pose changes. Settled rows do not invalidate while other rows or blur continue + * animating. Grid cell rows map to ColorOS nodes; the offset index restarts + * below the block of tall items that starts at row 0 (ColorOS's personal component). + */ +final class QsRows { + private static final int MAX_ROWS = QsModel.MAX_ROWS; + private static final int HEADER = MAX_ROWS, FOOTER = MAX_ROWS + 1; + + interface FrameListener { + void onQsFrame(QsModel model); + default void onQsFrameTime(long frameTimeNanos) {} + default void onQsFailure(Throwable failure) {} + } + + final QsModel model = new QsModel(); + final QsClipping clipping; + private final ClassLoader cl; + private final HookSet hooks; + private FrameListener frameListener; + + /** False = layers are identity (lock screen, other surfaces, or not driven by ShadeMotion). */ + private boolean armed; + private boolean running; + private MotionFrame motionFrame; + private boolean installed; + private boolean awaitingContent; + private java.lang.ref.WeakReference motionHost = new java.lang.ref.WeakReference<>(null); + private final FrameClock frameClock = new FrameClock(); + private View contentHost; + private ViewTreeObserver contentObserver; + private ViewTreeObserver.OnPreDrawListener contentReady; + private long contentGeneration; + private View waitingHost; + private final View.OnAttachStateChangeListener contentAttachment = new View.OnAttachStateChangeListener() { + @Override public void onViewAttachedToWindow(View host) { + try { + if (host != waitingHost) return; + if (!armed || !awaitingContent) { stopObservingContent(); return; } + // A sleeping wait has no vsync that could discover a replacement window tree. + observeContent(); + } catch (Throwable failure) { contentReadinessFailed(failure); } + } + @Override public void onViewDetachedFromWindow(View host) { + try { + if (host == waitingHost) stopObservingPreDraw(); + } catch (Throwable failure) { contentReadinessFailed(failure); } + } + }; + private int maxRowSeen; + private int topBlockEnd = 3; + private boolean layoutDirty = true; + + private final LayerSignal[] signals = new LayerSignal[MAX_ROWS + 2]; + private Class stateKt; + private Method stateGet; + private Method stateSet; + private Method graphicsLayer; + private Method modifierThen; + private Method modifierFoldIn; + private Object motionModifierFold; + private Object modifierCompanion; + private Class function1; + private final Object[] rowBlocks = new Object[MAX_ROWS]; + private Object headerBlock; + private final Object[] rowModifiers = new Object[MAX_ROWS]; + private Object headerModifier; + private Object footerModifier; + private NativeLayers nativeLayers; + private final Runnable[] pending = new Runnable[MAX_ROWS + 2]; + private final int[] pendingCount = new int[1]; + private Runnable commitLayers; + private static final int MAX_PUBLICATION_FAILURES = 4; + private PublicationFrame publicationFrame; + private boolean publishing, publicationRequested, publicationFailed; + private int publicationFailures; + private Field layerAlpha, layerScaleX, layerScaleY, layerTranslationY, layerMutated, layerStrategy; + + QsRows(ClassLoader cl) { + this(cl, new HookSet()); + } + + QsRows(ClassLoader cl, HookSet hooks) { + this.cl = cl; + this.hooks = hooks; + this.clipping = new QsClipping(cl, hooks); + } + + void setFrameListener(FrameListener l) { + frameListener = l; + } + + NativeLayers nativeBindings() { return nativeLayers; } + + void install() throws Throwable { + install(true); + } + + void install(boolean installViewportHook) throws Throwable { + QsItemBinding itemBinding = new QsItemBinding(cl); + if (installViewportHook) clipping.install(); + Class composeModifier = XposedHelpers.findClass("androidx.compose.ui.Modifier", cl); + function1 = XposedHelpers.findClass("kotlin.jvm.functions.Function1", cl); + graphicsLayer = XposedHelpers.findMethodExact("androidx.compose.ui.graphics.GraphicsLayerModifierKt", cl, + "graphicsLayer", composeModifier, function1); + modifierThen = composeModifier.getMethod("then", composeModifier); + Class function2 = XposedHelpers.findClass("kotlin.jvm.functions.Function2", cl); + modifierFoldIn = composeModifier.getMethod("foldIn", Object.class, function2); + modifierCompanion = XposedHelpers.getStaticObjectField(composeModifier, "Companion"); + motionModifierFold = Proxy.newProxyInstance(cl, new Class[] {function2}, (proxy, method, args) -> { + switch (method.getName()) { + case "invoke": + int row = motionModifierIndex(args[1]); + if (args[0] instanceof Integer) { + int mask = (Integer) args[0]; + if (row < 0) return mask; + int bit = 1 << row; + return mask | bit | ((mask & bit) == 0 ? 0 : 1 << 30); + } + return row < 0 ? modifierThen.invoke(args[0], args[1]) : args[0]; + case "equals": return proxy == args[0]; + case "hashCode": return System.identityHashCode(proxy); + default: return "ColorMotionModifierFold"; + } + }); + stateKt = XposedHelpers.findClass("androidx.compose.runtime.SnapshotStateKt", cl); + stateGet = XposedHelpers.findClass("androidx.compose.runtime.State", cl).getMethod("getValue"); + stateSet = XposedHelpers.findClass("androidx.compose.runtime.MutableState", cl).getMethod("setValue", Object.class); + Class scope = XposedHelpers.findClass("androidx.compose.ui.graphics.ReusableGraphicsLayerScope", cl); + layerAlpha = scope.getField("alpha"); + layerScaleX = scope.getField("scaleX"); + layerScaleY = scope.getField("scaleY"); + layerTranslationY = scope.getField("translationY"); + layerMutated = scope.getField("mutatedFields"); + layerStrategy = scope.getField("compositingStrategy"); + try { + Object probe = XposedHelpers.callStaticMethod(stateKt, "mutableStateOf$default", Boolean.FALSE); + nativeLayers = NativeLayers.load(cl, probe); + commitLayers = nativeLayers.batch(pending, pendingCount); + XposedBridge.log(Entry.TAG + ": typed QS layer bridge active"); + } catch (Throwable t) { + nativeLayers = null; + XposedBridge.log(Entry.TAG + ": native layer bridge unavailable, using reflective binding: " + t); + } + + // EditableItem(Modifier cellData, String id, long topLeft(IntOffset x<<32|y), long size(w<<32|h), ...) + // Kotlin mangles inline-class signatures with '-': jadx shows this as m3162EditableItemlVIIpV8. + hooks.method(itemBinding.editableItem, new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + try { + if (param.args.length < 4 || !(param.args[2] instanceof Long) + || !(param.args[3] instanceof Long) || param.args[0] == null) { + return; + } + if (!itemBinding.isMainGrid(param.args[0], (Long) param.args[2], (Long) param.args[3])) return; + int row = (int) ((Long) param.args[2] & 0xFFFFFFFFL); + int spanH = (int) ((Long) param.args[3] & 0xFFFFFFFFL); + if (row < 0 || row >= MAX_ROWS) { + return; + } + noteItem(row, spanH); + param.args[0] = withMotionModifier(param.args[0], rowModifier(row), row); + } catch (Throwable t) { + log(t); + } + } + }); + + // One UI 9 removed the default-mask argument from this composable. + hooks.method(itemBinding.header, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + Object base = itemBinding.headerBase(param.args, modifierCompanion); + itemBinding.replaceHeader(param.args, withMotionModifier(base, headerModifier(), HEADER)); + } catch (Throwable t) { log(t); } + } + }); + QsAuxBinding auxiliary = new QsAuxBinding(cl); + hooks.method(auxiliary.footer, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + Object base = param.args[0] == null ? modifierCompanion : param.args[0]; + param.args[0] = withMotionModifier(base, footerModifier(), FOOTER); + } catch (Throwable t) { log(t); } + } + }); + hooks.method(auxiliary.banner, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + Object base = param.args[1] == null ? modifierCompanion : param.args[1]; + // The banner precedes the grid, alongside the Compose clock. Apply the + // same header chain displacement so a heavy pull keeps their spacing. + param.args[1] = withMotionModifier(base, headerModifier(), HEADER); + } catch (Throwable t) { log(t); } + } + }); + XposedBridge.log(Entry.TAG + ": compose hooks: EditableItem=1 [" + itemBinding.editableItem.getName() + "]" + + " SecQuickSettingHeader=1 [args=" + itemBinding.header.getParameterCount() + "]"); + QsComposeLifecycle.installOptional(cl, hooks); + installed = true; + } + + /** Grid layout bookkeeping: tall items starting at row 0 form the top block. */ + private void noteItem(int row, int spanH) { + if (row > maxRowSeen) { + maxRowSeen = row; + layoutDirty = true; + } + if (row == 0 && spanH > 1 && spanH > topBlockEnd) { + topBlockEnd = spanH; + layoutDirty = true; + } + if (layoutDirty && armed) start(); + } + + private void applyLayout() { + if (!layoutDirty) { + return; + } + layoutDirty = false; + for (int r = 0; r < MAX_ROWS; r++) { + model.nodeOfRow[r] = r; + model.subIndexOfRow[r] = r < topBlockEnd ? r : r - topBlockEnd; + } + model.setRowCount(maxRowSeen + 1); + } + + // ---------------------------------------------------------------- driving + + void setArmed(boolean armed) { + clipping.setActive(armed); + if (!armed) { + // An inactive surface must not keep advancing springs, moving its native host or + // submitting blur while the other shade owns the gesture (or the phone is locked). + stopMotion(); + awaitingContent = false; + stopObservingContent(); + } + if (this.armed != armed) { + this.armed = armed; + if (armed && awaitingContent) observeContent(); + publishLayers(); + } + } + + /** Applies layout bookkeeping before a gesture starts. */ + void prepare() { + applyLayout(); + } + + boolean isRunning() { return running; } + + void setMotionHost(View host) { + if (motionHost.get() != host) { + stopObservingContent(); + motionHost = new java.lang.ref.WeakReference<>(host); + } + if (armed && awaitingContent) observeContent(); + } + + private void observeContent() { + View host = motionHost.get(); + if (host == null) return; + if (waitingHost != host) { + stopObservingContent(); + waitingHost = host; + host.addOnAttachStateChangeListener(contentAttachment); + } + ViewTreeObserver observer = host.getViewTreeObserver(); + if (contentHost == host && contentObserver == observer && observer.isAlive()) return; + stopObservingPreDraw(); + if (!observer.isAlive()) return; + contentHost = host; + contentObserver = observer; + long generation = contentGeneration; + contentReady = () -> onContentPreDraw(generation); + observer.addOnPreDrawListener(contentReady); + } + + private void stopObservingPreDraw() { + // Removal does not cancel an old tree's already captured dispatch snapshot. + // Its listener must not satisfy a newer tree's readiness wait. + contentGeneration++; + if (contentObserver != null && contentObserver.isAlive()) + contentObserver.removeOnPreDrawListener(contentReady); + // Android can merge a floating observer into a different live tree and kill the + // stored object. Remove the migrated listener before losing its host reference. + if (contentHost != null) { + ViewTreeObserver current = contentHost.getViewTreeObserver(); + if (current != contentObserver && current.isAlive()) + current.removeOnPreDrawListener(contentReady); + } + contentObserver = null; + contentHost = null; + contentReady = null; + } + + private void stopObservingContent() { + stopObservingPreDraw(); + if (waitingHost != null) waitingHost.removeOnAttachStateChangeListener(contentAttachment); + waitingHost = null; + } + + private void contentReadinessFailed(Throwable failure) { + awaitingContent = false; + stopObservingContent(); + stopMotion(); + log(failure); + if (frameListener != null) frameListener.onQsFailure(failure); + } + + private boolean onContentPreDraw(long generation) { + try { + if (generation != contentGeneration) return true; + if (!armed || !awaitingContent) { stopObservingContent(); return true; } + View host = contentHost; + if (host == null || host != motionHost.get() || !host.isAttachedToWindow() + || !host.isShown() || host.isLayoutRequested() || host.getWidth() <= 0 + || host.getHeight() <= 0 || headerBlock == null || rowBlocks[0] == null) return true; + // Cached blocks and visibility are not proof that a reattached scene completed layout. + // Start the reveal after that traversal, excluding its cold work from entrance time. + awaitingContent = false; + stopObservingContent(); + model.setOpeningContentReady(true); + frameClock.reset(); + // A hidden/detached host can outlive every active spring. Its pre-draw observer, + // rather than an otherwise idle vsync loop, wakes the reveal after layout. + start(); + } catch (Throwable failure) { + contentReadinessFailed(failure); + } + return true; + } + + void beginOpening(boolean closed) { + if (!closed) return; + // A cached scene still needs its native host to become visible on each fresh opening. + stopObservingContent(); + awaitingContent = installed; + model.setOpeningContentReady(!awaitingContent); + if (armed && awaitingContent) observeContent(); + frameClock.reset(); + if (armed) publishLayers(); + } + + void start() { + if (armed && !running && !publicationFailed) { + MotionFrame frame = new MotionFrame(); + motionFrame = frame; + running = true; + frameClock.reset(); + // Publish the reset/hidden pose before the first traversal; the clock's first + // callback only establishes its timestamp and must not expose stale opaque rows. + publishLayers(); + if (isCurrent(frame)) frame.post(); + } + } + + void snapHidden() { + // A fully collapsed QS may remain armed until the native state/side changes later. + // Its discovery/lifecycle scope must still sleep; the next setArmed(true) reopens it. + clipping.setActive(false); + applyLayout(); + model.reset(); + awaitingContent = false; + stopObservingContent(); + stopMotion(); + if (frameListener != null) { + frameListener.onQsFrame(model); + } + publishLayers(); + } + + private void stopMotion() { + MotionFrame frame = motionFrame; + motionFrame = null; + running = false; + frameClock.reset(); + if (frame != null) Choreographer.getInstance().removeFrameCallback(frame); + } + + private boolean isCurrent(MotionFrame frame) { + return motionFrame == frame && running && armed; + } + + /** A removed callback may already be in Choreographer's dispatch snapshot. */ + private final class MotionFrame implements Choreographer.FrameCallback { + boolean queued; + void post() { + if (!queued && isCurrent(this)) { + queued = true; + Choreographer.getInstance().postFrameCallback(this); + } + } + @Override public void doFrame(long nanos) { + if (!isCurrent(this)) return; + queued = false; + onMotionFrame(this, nanos); + } + } + + private void onMotionFrame(MotionFrame frame, long frameTimeNanos) { + android.os.Trace.beginSection("ColorMotion.QSFrame"); + try { advanceFrame(frame, frameTimeNanos); } + catch (Throwable failure) { + stopMotion(); + awaitingContent = false; + stopObservingContent(); + log(failure); + if (frameListener != null) frameListener.onQsFailure(failure); + } + finally { android.os.Trace.endSection(); } + } + + private void advanceFrame(MotionFrame frame, long frameTimeNanos) { + if (!isCurrent(frame)) return; + if (frameListener != null) frameListener.onQsFrameTime(frameTimeNanos); + if (!isCurrent(frame)) return; + applyLayout(); + if (awaitingContent) observeContent(); + if (!frameClock.isStarted()) { + frameClock.start(frameTimeNanos); + frame.post(); + return; + } + float durationScale = android.animation.ValueAnimator.getDurationScale(); + long step = frameClock.advance(frameTimeNanos, durationScale); + if (durationScale == 0f) model.finishRebound(); + boolean busy = model.step(step); + if (frameListener != null) { + frameListener.onQsFrame(model); + } + if (!isCurrent(frame)) return; + publishLayers(); + if (!isCurrent(frame)) return; + if (busy) frame.post(); + else stopMotion(); + } + + // ---------------------------------------------------------------- Compose plumbing + + /** Native restart lambdas capture the decorated argument and call the same hook again. */ + private Object withMotionModifier(Object base, Object motion, int row) throws ReflectiveOperationException { + if (base == motion) return base; + int mask = (Integer) modifierFoldIn.invoke(base, 0, motionModifierFold); + if (mask == (1 << row)) return base; + // Preserve all native elements and their order. A moved grid cell must replace its old + // row layer, rather than nesting two different motion transforms. Also repair duplicate + // owned elements if a captured modifier is supplied more than once. + if (mask != 0) base = modifierFoldIn.invoke(base, modifierCompanion, motionModifierFold); + return modifierThen.invoke(base, motion); + } + + private int motionModifierIndex(Object element) { + if (element == null) return -1; + if (element == headerModifier) return HEADER; + if (element == footerModifier) return FOOTER; + for (int row = 0; row < MAX_ROWS; row++) if (element == rowModifiers[row]) return row; + return -1; + } + + /** Publish changed poses together, synchronously, before this frame's traversal. */ + private void publishLayers() { + // Snapshot apply observers and reflected state writers may reenter driving methods. + // Keep their newer pose/queue changes out of the in-flight transaction, then publish + // that latest pose on the next callback. Never recursively commit the same batch. + if (publishing) { publicationRequested = true; return; } + cancelPublicationFrame(); + publishing = true; + publicationRequested = false; + Throwable failure = null; + int count = 0; + try { + for (int row = 0; row < signals.length; row++) { + LayerSignal signal = signals[row]; + if (signal == null || !updatePose(row, signal) || signal.queued) continue; + signal.queued = true; + pending[pendingCount[0]++] = signal.publish; + } + count = pendingCount[0]; + if (count != 0) { + if (commitLayers != null) commitLayers.run(); + else { + for (int i = 0; i < count; i++) pending[i].run(); + pendingCount[0] = 0; + } + for (LayerSignal signal : signals) if (signal != null) signal.queued = false; + java.util.Arrays.fill(pending, 0, count, null); + } + publicationFailures = 0; + } catch (Throwable t) { + // Keep dirty entries queued. NativeBatch restores/disposes its snapshot on failure; + // it derives the next signal from the actual state, so a retry cannot lose a toggle. + // A backend may throw during post-apply cleanup, after clearing its count. Keep + // the entries retryable even then; a new toggle is derived from committed state. + if (pendingCount[0] == 0) pendingCount[0] = count; + log(t); + failure = t; + } finally { + publishing = false; + } + if (failure != null && !publicationFailed && ++publicationFailures >= MAX_PUBLICATION_FAILURES) { + // Latch before notifying: failOpen disarms and attempts identity publication itself. + // A permanently broken backend must not recurse into recovery or keep a vsync loop. + publicationFailed = true; + stopMotion(); + awaitingContent = false; + stopObservingContent(); + try { if (frameListener != null) frameListener.onQsFailure(failure); } + catch (Throwable recoveryFailure) { log(recoveryFailure); } + } + if (!publicationFailed && (pendingCount[0] != 0 || publicationRequested)) { + publicationFrame = new PublicationFrame(); + Choreographer.getInstance().postFrameCallback(publicationFrame); + } + } + + private void cancelPublicationFrame() { + PublicationFrame frame = publicationFrame; + publicationFrame = null; + if (frame != null) Choreographer.getInstance().removeFrameCallback(frame); + } + + /** Publication retries outlive model settling/disarm, but never run native motion or blur. */ + private final class PublicationFrame implements Choreographer.FrameCallback { + @Override public void doFrame(long nanos) { + if (publicationFrame != this) return; + publicationFrame = null; + publishLayers(); + } + } + + private boolean updatePose(int row, LayerSignal signal) { + boolean header = row == HEADER, footer = row == FOOTER; + boolean active = armed && (header || footer || row < model.rowCount); + float alpha = active ? (header ? model.headerOpacity() : footer ? model.footerOpacity() : model.rowAlpha(row)) : 1f; + float scale = active ? (header ? model.headerScale.value : footer ? model.footerScale() : model.scale[row].value) : 1f; + // Native host translation is already applied to all Compose content once. + float y = active ? (header ? model.headerTranslation() : footer + ? model.footerTranslation() - model.translation.value : model.rowTranslation(row)) : 0f; + if (!signal.pose.update(alpha, scale, y)) return false; + signal.values[0] = alpha; + signal.values[1] = scale; + signal.values[2] = y; + return true; + } + + private final class LayerSignal { + final Object state = XposedHelpers.callStaticMethod(stateKt, "mutableStateOf$default", Boolean.FALSE); + final MotionPose pose = new MotionPose(); + final float[] values = {1f, 1f, 0f}; + Runnable publish; + boolean queued; + } + + private Object rowBlock(int row) { + Object block = rowBlocks[row]; + if (block == null) rowBlocks[row] = block = layerBlock(row); + return block; + } + + private Object rowModifier(int row) throws ReflectiveOperationException { + Object modifier = rowModifiers[row]; + if (modifier == null) rowModifiers[row] = modifier = + graphicsLayer.invoke(null, modifierCompanion, rowBlock(row)); + return modifier; + } + + private Object headerModifier() throws ReflectiveOperationException { + if (headerModifier == null) headerModifier = + graphicsLayer.invoke(null, modifierCompanion, headerBlock()); + return headerModifier; + } + + private Object headerBlock() { + if (headerBlock == null) headerBlock = layerBlock(HEADER); + return headerBlock; + } + + private Object footerModifier() throws ReflectiveOperationException { + if (footerModifier == null) footerModifier = + graphicsLayer.invoke(null, modifierCompanion, layerBlock(FOOTER)); + return footerModifier; + } + + /** Same scope fields/dirty bits as its setters, without boxed floats and varargs per layer. */ + private void applyLayer(Object scope, float alpha, float scale, float y) throws IllegalAccessException { + layerAlpha.setFloat(scope, QsModel.clamp(alpha, 0f, 1f)); + layerScaleX.setFloat(scope, scale); + layerScaleY.setFloat(scope, scale); + layerTranslationY.setFloat(scope, y); + // This wrapper must not create a bounded alpha texture around moving child layers. + // Individual rounded masks and explicit offscreen/effect layers retain native compositing. + layerStrategy.setInt(scope, 2); // Samsung Compose CompositingStrategy.ModulateAlpha + // NodeCoordinator resets the reusable scope before invoking a block. Native setters + // mark only departures from those defaults; OwnedLayer also merges the previous + // mask to restore properties that have returned to identity. Matching that contract + // avoids redundant scale/alpha/translation work during other properties' tails. + int changed = 32768; + if (alpha != 1f) changed |= 4; + if (scale != 1f) changed |= 1 | 2; + if (y != 0f) changed |= 16; + layerMutated.setInt(scope, layerMutated.getInt(scope) | changed); + } + + private Object layerBlock(int row) { + applyLayout(); + if (row < MAX_ROWS) model.noteRowReady(row); + LayerSignal signal = new LayerSignal(); + signals[row] = signal; + updatePose(row, signal); + if (nativeLayers != null) { + try { + Object block = nativeLayers.layer(signal.state, signal.values); + signal.publish = (Runnable) block; + return block; + } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + } + // Compatibility path for builds whose native ABI differs. The bridge is probed before + // any layer is created, so one panel cannot mix half-initialized binding strategies. + Object unit = XposedHelpers.getStaticObjectField(XposedHelpers.findClass("kotlin.Unit", cl), "INSTANCE"); + signal.publish = () -> { + try { + Object value = stateGet.invoke(signal.state); + stateSet.invoke(signal.state, value == Boolean.TRUE ? Boolean.FALSE : Boolean.TRUE); + } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } + }; + InvocationHandler h = (proxy, method, args) -> { + switch (method.getName()) { + case "invoke": + stateGet.invoke(signal.state); + applyLayer(args[0], signal.values[0], signal.values[1], signal.values[2]); + return unit; + case "equals": return proxy == args[0]; + case "hashCode": return System.identityHashCode(proxy); + case "toString": return "ColorMotionLayer"; + default: return null; + } + }; + return Proxy.newProxyInstance(cl, new Class[] {function1}, h); + } + + private static void log(Throwable t) { + XposedBridge.log(Entry.TAG + ": " + t); + } +} diff --git a/hook/src/main/java/dev/colormotion/QsSceneBridge.java b/hook/src/main/java/dev/colormotion/QsSceneBridge.java new file mode 100644 index 00000000..16df310a --- /dev/null +++ b/hook/src/main/java/dev/colormotion/QsSceneBridge.java @@ -0,0 +1,311 @@ +package dev.colormotion; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import android.util.Property; +import android.view.View; + +import de.robv.android.xposed.XposedHelpers; + +/** Keeps the native QS content composed at its final geometry while our layers own its reveal. */ +final class QsSceneBridge { + private static final Float CONTENT_HIDDEN = Float.valueOf(0f), CONTENT_SHOWN = Float.valueOf(1f); + private static final Object[] NO_ARGS = new Object[0]; + private final Field composeEnabled; + private final Field[] excludedTransitions; + private final Field openPosition, userChanged, adapter, expansion; + private final Field[] animators; + private final boolean separateButtons; + private final Method setPosition, getValue, updateState; + private final Field lastPosition; + private final Object[] positionArg = new Object[1]; + private final Object[] flowArgs = new Object[2]; + private final DirectBinding direct; + private final Object[] plannedAnimators; + private final DirectPlan[] plans; + private final RejectedShape[] rejectedShapes; + + QsSceneBridge(ClassLoader cl) throws ReflectiveOperationException { + Class split = XposedHelpers.findClass("com.android.systemui.qs.animator.PanelSplitOpenAnimator", cl); + Class flags = XposedHelpers.findClass("com.android.systemui.qs.animator.QsAnimatorState", cl); + composeEnabled = XposedHelpers.findClass("com.android.systemui.QpRune", cl).getField("QUICK_PANEL_COMPOSE"); + String[] exclusions = {"isSliding", "isDetailShowing", "isDetailOpening", "isDetailClosing", + "isDetailPopupShowing", "isDetailPopupClosing", "isCustomizerShowing"}; + java.util.ArrayList present = new java.util.ArrayList<>(); + for (String name : exclusions) { + try { present.add(flags.getField(name)); } + catch (NoSuchFieldException missing) { + // Popup transitions were removed in One UI 9. Other transition flags remain + // required; an unknown ABI must roll back the complete hook installation. + if (!name.startsWith("isDetailPopup")) throw missing; + } + } + excludedTransitions = present.toArray(new Field[0]); + openPosition = split.getField("openPosition"); + userChanged = split.getField("mUserChanged"); + adapter = split.getField("composeAdapter"); + expansion = adapter.getType().getField("_expansionFraction"); + java.util.ArrayList nativeAnimators = new java.util.ArrayList<>(); + for (String name : new String[] {"headerAnimator", "blurViewAnimator", "clockDateAnimator"}) + nativeAnimators.add(split.getField(name)); + // Both APKs declare buttonAnimator, but only the newer Compose branch drives it. + // The removed popup flags distinguish these two audited native scene contracts. + separateButtons = present.size() == 5; + if (separateButtons) nativeAnimators.add(split.getField("buttonAnimator")); + animators = nativeAnimators.toArray(new Field[0]); + setPosition = animators[0].getType().getMethod("setPosition", float.class); + lastPosition = animators[0].getType().getField("mLastT"); + lastPosition.setAccessible(true); + DirectBinding candidate; + try { candidate = DirectBinding.bind(animators[0].getType(), cl, lastPosition); } + catch (ReflectiveOperationException | RuntimeException | LinkageError unsupported) { candidate = null; } + direct = candidate; + plannedAnimators = new Object[animators.length]; + plans = new DirectPlan[animators.length]; + rejectedShapes = new RejectedShape[animators.length]; + Class flow = expansion.getType(); + getValue = flow.getMethod("getValue"); + updateState = flow.getDeclaredMethod("updateState", Object.class, Object.class); + for (Field f : new Field[] {composeEnabled, openPosition, + userChanged, adapter, expansion}) f.setAccessible(true); + for (Field f : excludedTransitions) f.setAccessible(true); + for (Field f : animators) f.setAccessible(true); + setPosition.setAccessible(true); + getValue.setAccessible(true); + updateState.setAccessible(true); + } + + boolean apply(Object animator, float fraction) throws ReflectiveOperationException { + if (!composeEnabled.getBoolean(null)) return false; + for (Field f : excludedTransitions) if (f.getBoolean(null)) return false; + // Preserve Samsung's bookkeeping and native header/blur alpha timing. Only its Compose + // visual expansion is replaced: emitting every intermediate fraction otherwise rebuilds + // the QS scene and header underneath the independent ColorOS row transforms. + openPosition.setFloat(animator, fraction); + userChanged.setBoolean(animator, false); + for (int i = 0; i < animators.length; i++) { + Object touchAnimator = animators[i].get(animator); + position(touchAnimator, fraction, i); + } + Object flow = expansion.get(adapter.get(animator)); + float content = contentFraction(fraction); + if (((Number) getValue.invoke(flow, NO_ARGS)).floatValue() != content) { + flowArgs[1] = content == 0f ? CONTENT_HIDDEN : CONTENT_SHOWN; + updateState.invoke(flow, flowArgs); + } + return true; + } + + boolean hasSeparateButtons() { return separateButtons; } + + + static float contentFraction(float fraction) { + return fraction > 0f ? 1f : 0f; + } + + /** Restore Samsung's actual pose, including alpha=0 on collapse, rather than flashing identity. */ + void restoreHeaderPose(Object animator, float fraction) throws ReflectiveOperationException { + for (int i = 0; i < animators.length; i++) { + if (i == 1) continue; // Blur views have their own native ownership. + Object target = animators[i].get(animator); + if (target == null) { position(null, fraction, i); continue; } + // The native animator can already have cached this position before our overrides. + lastPosition.setFloat(target, Float.NaN); + position(target, fraction, i); + } + } + + private void position(Object animator, float fraction, int slot) throws ReflectiveOperationException { + if (animator == null) { + plannedAnimators[slot] = null; + plans[slot] = null; + rejectedShapes[slot] = null; + return; + } + if (direct != null) { + if (plannedAnimators[slot] != animator || (plans[slot] != null && !plans[slot].matches()) + || (rejectedShapes[slot] != null && !rejectedShapes[slot].matches())) { + plannedAnimators[slot] = animator; + plans[slot] = null; + rejectedShapes[slot] = null; + try { + plans[slot] = direct.plan(animator); + if (plans[slot] == null) rejectedShapes[slot] = direct.rejectedShape(animator); + } + catch (ReflectiveOperationException | RuntimeException | LinkageError unsupported) { /* native fallback */ } + } + DirectPlan plan = plans[slot]; + if (plan != null) { + plan.apply(fraction); + return; + } + } + if (positionArg[0] == null || ((Float) positionArg[0]).floatValue() != fraction) positionArg[0] = fraction; + setPosition.invoke(animator, positionArg); + } + + /** + * The audited listener-free split animators only forward float properties to Views. + * QSAnimView's alpha wrapper additionally captures caller stacks/timestamps for dump output + * (on every call in 8.5). Replay that exact keyframe math on the wrapped View, retaining + * native execution for unknown shapes, interpolators, listeners and wrapper subclasses. + */ + private static final class DirectBinding { + private final Class animatorType, keyframeType, wrapperType; + private final Field targets, keyframes, listener, interpolator, start, span, last; + private final Field property, values, size, width, view; + + static DirectBinding bind(Class type, ClassLoader cl, Field last) + throws ReflectiveOperationException { + if (!type.getName().equals("com.android.systemui.qs.TouchAnimator")) return null; + return new DirectBinding(type, cl, last); + } + + private DirectBinding(Class type, ClassLoader cl, Field last) throws ReflectiveOperationException { + animatorType = type; + keyframeType = Class.forName(type.getName() + "$FloatKeyframeSet", false, cl); + wrapperType = Class.forName("com.android.systemui.qs.animator.QSAnimView", false, cl); + targets = accessible(type.getField("mTargets")); + keyframes = accessible(type.getField("mKeyframeSets")); + listener = accessible(type.getField("mListener")); + interpolator = accessible(type.getField("mInterpolator")); + start = accessible(type.getField("mStartDelay")); + span = accessible(type.getField("mSpan")); + this.last = last; + property = accessible(keyframeType.getField("mProperty")); + values = accessible(keyframeType.getField("mValues")); + size = accessible(keyframeType.getField("mSize")); + width = accessible(keyframeType.getField("mFrameWidth")); + view = accessible(wrapperType.getDeclaredField("view")); + } + + private static Field accessible(Field field) { field.setAccessible(true); return field; } + + RejectedShape rejectedShape(Object animator) throws IllegalAccessException { + if (animator.getClass() != animatorType) return null; + return new RejectedShape((Object[]) targets.get(animator), (Object[]) keyframes.get(animator)); + } + + DirectPlan plan(Object animator) throws ReflectiveOperationException { + if (animator.getClass() != animatorType || listener.get(animator) != null + || interpolator.get(animator) != null) return null; + Object[] target = (Object[]) targets.get(animator), frames = (Object[]) keyframes.get(animator); + if (target.length != frames.length) return null; + View[] views = new View[target.length]; + int[] properties = new int[target.length]; + float[][] samples = new float[target.length][]; + float[] widths = new float[target.length]; + for (int i = 0; i < target.length; i++) { + if (target[i] == null || target[i].getClass() != wrapperType + || frames[i] == null || frames[i].getClass() != keyframeType) return null; + Property p = (Property) property.get(frames[i]); + // Property.of(QSAnimView.class, float.class, name) in both native Builders. + if (!p.getClass().getName().equals("android.util.ReflectiveProperty") + || p.getType() != float.class) return null; + int code; + switch (p.getName()) { + case "alpha": code = 0; break; + case "translationX": code = 1; break; + case "translationY": code = 2; break; + case "scaleX": code = 3; break; + case "scaleY": code = 4; break; + default: return null; + } + views[i] = (View) view.get(target[i]); + properties[i] = code; + samples[i] = (float[]) values.get(frames[i]); + if (samples[i].length < 2 || size.getInt(frames[i]) != samples[i].length) return null; + widths[i] = width.getFloat(frames[i]); + if (!(widths[i] > 0f) || !Float.isFinite(widths[i])) return null; + } + return new DirectPlan(animator, last, start.getFloat(animator), span.getFloat(animator), + target, frames, views, properties, samples, widths); + } + } + + /** Retain only a rejected shape, so element replacement can regain the guarded path. */ + private static final class RejectedShape { + private final Object[] targets, keyframes, originalTargets, originalKeyframes; + RejectedShape(Object[] targets, Object[] keyframes) { + this.targets = targets; this.keyframes = keyframes; + originalTargets = targets.clone(); originalKeyframes = keyframes.clone(); + } + boolean matches() { + for (int i = 0; i < targets.length; i++) + if (targets[i] != originalTargets[i]) return false; + for (int i = 0; i < keyframes.length; i++) + if (keyframes[i] != originalKeyframes[i]) return false; + return true; + } + } + + private static final class DirectPlan { + private final Object animator; + private final Field last; + private final float start, span; + private final View[] views; + private final int[] properties; + private final float[][] samples; + private final float[] widths; + private final boolean sharedGeometry; + private final Object[] targets, keyframes, originalTargets, originalKeyframes; + + DirectPlan(Object animator, Field last, float start, float span, Object[] targets, Object[] keyframes, View[] views, + int[] properties, float[][] samples, float[] widths) { + this.animator = animator; this.last = last; this.start = start; this.span = span; + this.views = views; this.properties = properties; this.samples = samples; this.widths = widths; + this.targets = targets; this.keyframes = keyframes; + originalTargets = targets.clone(); originalKeyframes = keyframes.clone(); + boolean shared = samples.length > 0; + for (int i = 1; i < samples.length; i++) { + if (samples[i].length != samples[0].length || widths[i] != widths[0]) shared = false; + } + sharedGeometry = shared; + } + + boolean matches() { + for (int i = 0; i < targets.length; i++) { + if (targets[i] != originalTargets[i] || keyframes[i] != originalKeyframes[i]) return false; + } + return true; + } + + void apply(float fraction) throws IllegalAccessException { + if (Float.isNaN(fraction)) return; + float t = (fraction - start) / span; + if (t < 0f) t = 0f; + else if (t > 1f) t = 1f; + if (t == last.getFloat(animator)) return; + // Native TouchAnimator only writes mLastT inside its listener branch. These + // listener-free plans intentionally keep that behavior, including repeat writes + // that can repair a pose changed by another native/module consumer. + int sharedIndex = 0; + float sharedFraction = 0f; + if (sharedGeometry) { + float width = widths[0]; + sharedIndex = Math.max(1, Math.min((int) Math.ceil(t / width), samples[0].length - 1)); + sharedFraction = (t - ((sharedIndex - 1) * width)) / width; + } + for (int k = 0; k < views.length; k++) { + View v = views[k]; + if (v == null) continue; + float[] values = samples[k]; + float width = widths[k]; + // Native split animators give every property the same keyframe geometry. + // Share only its index/fraction math; retain every property write and sample. + int i = sharedGeometry ? sharedIndex + : Math.max(1, Math.min((int) Math.ceil(t / width), values.length - 1)); + float f = sharedGeometry ? sharedFraction : (t - ((i - 1) * width)) / width; + float previous = values[i - 1]; + float value = ((values[i] - previous) * f) + previous; + switch (properties[k]) { + case 0: v.setAlpha(value); break; + case 1: v.setTranslationX(value); break; + case 2: v.setTranslationY(value); break; + case 3: v.setScaleX(value); break; + case 4: v.setScaleY(value); break; + } + } + } + } +} diff --git a/hook/src/main/java/dev/colormotion/ReboundSpring.java b/hook/src/main/java/dev/colormotion/ReboundSpring.java new file mode 100644 index 00000000..21a9c29a --- /dev/null +++ b/hook/src/main/java/dev/colormotion/ReboundSpring.java @@ -0,0 +1,107 @@ +package dev.colormotion; + +/** + * Port of Facebook Rebound's Spring as stepped by the reference + * AndroidSpringLooperFactory$ChoreographerAndroidSpringLooper: RK4 at a fixed 1 ms step, frame delta + * capped at 64 ms, interpolation of the leftover time, Origami tension/friction conversion from + * SpringConfig.fromOrigamiTensionAndFriction. + */ +final class ReboundSpring { + private static final double STEP = 0.001; + private static final double MAX_DELTA = 0.064; + + double tension; + double friction; + double position; + double velocity; + double endValue; + double restSpeed = 0.005; + double restDisplacement = 0.005; + + private double tempPosition; + private double tempVelocity; + private double prevPosition; + private double prevVelocity; + private double accumulator; + private boolean wasAtRest = true; + + ReboundSpring origami(double tension, double friction) { + this.tension = tension == 0 ? 0 : (tension - 30.0) * 3.62 + 194.0; + this.friction = friction == 0 ? 0 : 25.0 + (friction - 8.0) * 3.0; + return this; + } + + void setCurrentValue(double v) { + position = v; + tempPosition = v; + velocity = 0; + tempVelocity = 0; + accumulator = 0; + } + + void setEndValue(double v) { + if (endValue != v || !isAtRest()) { + endValue = v; + wasAtRest = false; + } + } + + boolean isAtRest() { + return Math.abs(velocity) <= restSpeed + && (Math.abs(endValue - position) <= restDisplacement || tension == 0); + } + + /** Returns true while the spring still needs frames. */ + boolean advance(double deltaSec) { + boolean atRest = isAtRest(); + if (atRest && wasAtRest) { + return false; + } + accumulator += Math.min(deltaSec, MAX_DELTA); + double k = tension, c = friction; + double pos = position, vel = velocity, tPos = tempPosition, tVel = tempVelocity; + while (accumulator >= STEP) { + accumulator -= STEP; + if (accumulator < STEP) { + prevPosition = pos; + prevVelocity = vel; + } + double end = endValue; + // Rebound evaluates the first acceleration from the previous step's temp position. + double aAcc = (end - tPos) * k - c * vel; + double bPos = pos + vel * STEP * 0.5; + double bVel = vel + aAcc * STEP * 0.5; + double bAcc = (end - bPos) * k - c * bVel; + double cPos = pos + bVel * STEP * 0.5; + double cVel = vel + bAcc * STEP * 0.5; + double cAcc = (end - cPos) * k - c * cVel; + double dPos = pos + cVel * STEP; + double dVel = vel + cAcc * STEP; + double dAcc = (end - dPos) * k - c * dVel; + pos = pos + (vel + 2.0 * (bVel + cVel) + dVel) / 6.0 * STEP; + vel = vel + (aAcc + 2.0 * (bAcc + cAcc) + dAcc) / 6.0 * STEP; + tPos = dPos; + tVel = dVel; + } + tempPosition = tPos; + tempVelocity = tVel; + position = pos; + velocity = vel; + if (accumulator > 0) { + double a = accumulator / STEP; + position = prevPosition * (1 - a) + pos * a; + velocity = prevVelocity * (1 - a) + vel * a; + } + if (isAtRest()) { + if (k > 0) { + position = endValue; + } else { + endValue = position; + } + velocity = 0; + atRest = true; + } + wasAtRest = atRest; + return !atRest; + } +} diff --git a/hook/src/main/java/dev/colormotion/ShadeMotion.java b/hook/src/main/java/dev/colormotion/ShadeMotion.java new file mode 100644 index 00000000..affb0a00 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/ShadeMotion.java @@ -0,0 +1,1523 @@ +package dev.colormotion; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; +import android.content.Context; +import android.view.VelocityTracker; +import android.view.View; +import android.view.MotionEvent; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.ref.WeakReference; +import java.util.ArrayList; + +import de.robv.android.xposed.XC_MethodHook; +import de.robv.android.xposed.XposedBridge; +import de.robv.android.xposed.XposedHelpers; + +/** + * Layered panel motion for One UI 8.5's split shade. + * + * Samsung drives every shade visual from NotificationPanelViewController's expanded height, so the + * ColorOS fraction spring is inserted between the finger and setExpandedHeightInternal(), and the + * release fling is replaced by the same spring. The reference-fitted QS flow drives both the + * Compose control center and notification cards, preserving Samsung's notification layout. + */ +final class ShadeMotion { + private static final String NPVC = "com.android.systemui.shade.NotificationPanelViewController"; + private static final String SPLIT_OPEN_ANIMATOR = "com.android.systemui.qs.animator.PanelSplitOpenAnimator"; + + private static final int SIDE_QS = 0; + private static final int SIDE_SHADE = 1; + + private final ClassLoader cl; + private final HookSet hooks = new HookSet(); + + private Object npvc; + private PanelFields panel; + private boolean injecting; + private boolean failed; + private boolean inFling; + private int side = SIDE_SHADE; + private boolean dragging; + // A physical gesture outlives tracking changes and repeated native fling callbacks. + private boolean gestureInitialized; + private boolean gestureReleased; + private boolean openingReveal; + private long gestureDownTime = Long.MIN_VALUE; + private int dragDispatchDepth; + private boolean panelClosedOnDown; + private float trackingStartVelocity; + private float dragStartFraction; + private boolean panelCollapsed = true; + private boolean heightDriven; + private boolean panelSwitching; + private PanelSlideMotion panelSlide; + private int heightDispatchDepth; + private float lastHeightFraction; + /** A primed opening drag must not return to height 0, which hides the shade window. */ + private boolean openingPrimed; + /** DOWN of a QS pull from a collapsed panel, until its UP/CANCEL. */ + private boolean qsTouchDown; + + /** PanelExpandedFraction / QSPanelExpandFraction.fractionAnimation while the finger is down. */ + private final SpringDriver fraction = new SpringDriver(new SpringDriver.Listener() { + @Override + public void onUpdate(Spring s) { + try { applyFraction(s.value); } + catch (Throwable failure) { failOpen(failure); } + } + }); + + private FlingCurve activeCurve; + private final FlingCurve.Workspace flingWorkspace = new FlingCurve.Workspace(); + + // Notifications deliberately reuse the QS reference flow, with one card per row. + private final NotificationRows notificationRows = new NotificationRows(); + private NotificationGeometry notificationGeometry; + private NotificationFooter notificationFooter; + private boolean notificationListNative; + private boolean notificationScrollKnown; + private int notificationScrollAtStart; + private boolean notificationDriven; + private boolean notificationAnimating; + private final OpeningReadiness notificationOpening = new OpeningReadiness(new OpeningReadiness.Listener() { + @Override public boolean isReady(View host) throws IllegalAccessException { + return ownsNotificationGeometry(host) && !notificationRows.layoutPending(host); + } + @Override public void onReady() { + notificationRows.model.setOpeningContentReady(true); + // Exclude the first native layout's work from the entrance clock, as QS does. + notifClock.reset(); + queueNotifFrame(); + } + @Override public void onFailure(Throwable failure) { failOpen(failure); } + }); + private XC_MethodHook.MethodHookParam notificationStateOwner; + private java.util.List notificationApplied; + /** Samsung's SecQpBlurController, captured from its first getCalculatedFraction() call. */ + private Object blurController; + private Object splitOpenAnimator; + private SplitViewBinding splitViewBinding; + private final View[] splitHeaderViews = new View[3]; + private final View[] splitBlurViews = new View[3]; + private final boolean[] nestedHeader = new boolean[3]; + private WeakReference qsMotionView = new WeakReference<>(null); + private WeakReference notificationStack = new WeakReference<>(null); + private WeakReference notificationStackPanel = new WeakReference<>(null); + private float lastRequestedBlur = Float.NaN; + private final BlurFrameGate blurFrameGate = new BlurFrameGate(); + private BlurFrameBinding blurFrame; + private Field mirrorVisible, bouncerShowing; + private QsSceneBridge qsScene; + /** True while ColorOS blur springs own the blur (from a hooked gesture until fully collapsed). */ + private boolean blurDriven; + + /** One clock advances the notification header, card cascade, blur and rebound. */ + private boolean notifFrameQueued; + private final FrameClock notifClock = new FrameClock(); + private NotificationRun notifRun; + private final class NotificationRun implements android.view.Choreographer.FrameCallback { + @Override public void doFrame(long frameTimeNanos) { + // Removed callbacks may still be in the current Choreographer dispatch snapshot. + if (notifRun == this) notifFrame.doFrame(frameTimeNanos); + } + } + private final android.view.Choreographer.FrameCallback notifFrame = new android.view.Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + android.os.Trace.beginSection("ColorMotion.NotificationFrame"); + try { advance(frameTimeNanos); } + catch (Throwable failure) { failOpen(failure); } + finally { android.os.Trace.endSection(); } + } + + private void advance(long frameTimeNanos) { + blurFrameGate.beginFrame(frameTimeNanos); + notifFrameQueued = false; + if (panelSwitching) return; + if (!notificationDriven || side != SIDE_SHADE || npvc == null + || panel.barState(npvc) != 0) { + stopNotificationMotion(); + return; + } + View stack = nssl(); + notificationOpening.setHost(stack); + boolean rowsPrepared = false; + if (stack != null) { + try { + notificationRows.prepare(stack); + rowsPrepared = true; + } + catch (IllegalAccessException e) { log(e); } + noticeNotificationScroll(stack); + } + float scale = ValueAnimator.getDurationScale(); + if (scale == 0f) notificationRows.model.finishRebound(); + boolean busy = notificationRows.model.step(notifClock.advance(frameTimeNanos, scale)); + notificationAnimating = busy; + if (stack != null) { + android.os.Trace.beginSection("ColorMotion.NotificationRender"); + try { + if (!notificationListNative) { + renderingCards = true; + try { + if (rowsPrepared) notificationRows.renderPrepared(stack); + else notificationRows.render(stack); + } finally { renderingCards = false; } + } + if (notificationFooter != null) notificationFooter.render(stack, notificationRows.model, false); + } + catch (ReflectiveOperationException e) { + // A native gradient/property call can fail after visibility is committed. + // Logging alone strands that pose with no retry once the clock settles. + // Use the same full native repair as the typed path's runtime failure. + throw new IllegalStateException("Notification render failed", e); + } + finally { android.os.Trace.endSection(); } + } + if (splitOpenAnimator != null) applySplitHeaderPosition(splitOpenAnimator); + requestBlurFrame(); + if (traversalOrder != null) traversalOrder.drawLast(stack); + if (busy) queueNotifFrame(); + else if (!notifFrameQueued) { + notifClock.reset(); + notifRun = null; + } + } + }; + + // Control center side: QsModel (QSPanelExpandFraction/QSPanelTranslationY/elements/chain) + private final QsRows qsRows; + private final TraversalOrder traversalOrder = TraversalOrder.create(); + + ShadeMotion(ClassLoader cl) { + this.cl = cl; + this.qsRows = new QsRows(cl, hooks); + qsRows.setFrameListener(new QsRows.FrameListener() { + @Override public void onQsFrameTime(long frameTimeNanos) { blurFrameGate.beginFrame(frameTimeNanos); } + @Override public void onQsFrame(QsModel m) { + applyQsTranslation(m.translation.value); + // The header must keep following the model after the native height animator ends. + if (splitOpenAnimator != null) applySplitHeaderPosition(splitOpenAnimator); + requestBlurFrame(); + if (traversalOrder != null) traversalOrder.drawLast(qsMotionView.get()); + } + @Override public void onQsFailure(Throwable failure) { failOpen(failure); } + }); + } + + /** A late native ABI failure must not escape a Choreographer callback and crash SystemUI. */ + private void failOpen(Throwable failure) { + if (failed) return; + failed = true; + hooks.rollback(); + fraction.cancel(); + blurDriven = dragging = inFling = false; + activeCurve = null; + panelSwitching = false; + try { if (panelSlide != null) panelSlide.abort(); } catch (Throwable restore) { log(restore); } + cancelNotifFrames(); + try { qsRows.setArmed(false); } catch (Throwable restore) { log(restore); } + try { stopNotificationMotion(); } catch (Throwable restore) { log(restore); } + notificationDriven = notificationAnimating = false; + try { requestNsslUpdate(); } catch (Throwable restore) { log(restore); } + XposedBridge.log(Entry.TAG + ": motion disabled after runtime binding failure: " + failure); + } + + void install() { + try { installHooks(); } + catch (Throwable failure) { + hooks.rollback(); + qsRows.setArmed(false); + throw new IllegalStateException("Motion bindings incompatible; all motion hooks removed", failure); + } + } + + private void installHooks() throws Throwable { + qsRows.install(false); + Class npvcClass = XposedHelpers.findClass(NPVC, cl); + try { panel = new PanelFields(npvcClass); } + catch (ReflectiveOperationException e) { throw new IllegalStateException("Panel binding failed", e); } + + installTouchHooks(XposedHelpers.findClass(NPVC + "$TouchHandler", cl)); + panelSlide = new PanelSlideMotion(cl); + hooks.method(panelSlide.slide, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + panelSlide.abort(); + if (canSwitchPanels() && panelSlide.allowed(param.thisObject) && panelSlide.isPanelTransition(param.args) + && panelSlide.state(param.thisObject) == 2 && !panelSwitching) + beginPanelSwitch(); + } catch (Throwable failure) { failOpen(failure); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + try { + if (canSwitchPanels()) afterPanelSlide(param.thisObject, param.args); + } catch (Throwable failure) { failOpen(failure); } + } + }); + + hooks.findAndHookMethod(npvcClass, "setExpandedHeightInternal", float.class, new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + heightDispatchDepth++; + android.os.Trace.beginSection("ColorMotion.PanelHeight"); + try { + beforeSetExpandedHeight(param); + } catch (Throwable t) { + log(t); + } + } + + @Override + protected void afterHookedMethod(MethodHookParam param) { + try { + afterSetExpandedHeight(param.thisObject); + } catch (Throwable t) { + log(t); + } finally { + heightDispatchDepth--; + android.os.Trace.endSection(); + } + } + }); + PanelHeightBinding height = new PanelHeightBinding(cl, npvcClass); + hooks.method(height.run, createHeightConsumerHook(height)); + + hooks.findAndHookMethod(npvcClass, "flingToHeight", + float.class, boolean.class, float.class, float.class, boolean.class, createFlingHook()); + + // SecQpBlurController.getCalculatedFraction() feeds both the panel blur (doBlur) and the panel + // background alpha; ColorOS drives its blur, scrim alpha and wallpaper zoom linearly from the + // blur fraction, so the fraction is replaced here. + Class blurClass = XposedHelpers.findClass("com.android.systemui.blur.SecQpBlurController", cl); + blurFrame = new BlurFrameBinding(blurClass, cl); + mirrorVisible = XposedHelpers.findField(blurClass, "isMirrorVisible"); + bouncerShowing = XposedHelpers.findField(blurClass, "isBouncerShowing"); + hooks.method(blurFrame.frame, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + Object controller = blurFrame.controller(param); + float owned = isMotionRunning() ? ownedBlurFraction(controller) : Float.NaN; + if (Float.isNaN(owned)) { blurFrameGate.reset(); return; } + if (!blurFrameGate.shouldApply(controller, owned)) param.setResult(blurFrame.skippedResult); + } catch (Throwable t) { blurFrameGate.reset(); log(t); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + if (param.hasThrowable()) blurFrameGate.reset(); + } + }); + hooks.findAndHookMethod(blurClass, "getCalculatedFraction", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) { + try { + blurController = param.thisObject; + float f = ownedBlurFraction(param.thisObject); + if (!Float.isNaN(f)) { + param.setResult(f); + } + } catch (Throwable t) { + log(t); + } + } + }); + + // Replace Samsung's card expansion transforms at the final state consumers. Restore the + // native state afterwards, so repeat applications never accumulate motion offsets. + Class nsslClass = XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout", cl); + try { + installNotificationGeometry(nsslClass); + notificationRows.bind(nsslClass, XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.row.ExpandableView", cl)); + notificationRows.bindRendering(XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.row.ExpandableNotificationRow", cl)); + installNotificationFooter(nsslClass, XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.row.ExpandableView", cl)); + installBlurBackgroundCache(); + installNotificationEdgeFade(nsslClass, XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.row.ExpandableView", cl)); + notificationRows.installNative(qsRows.nativeBindings()); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Notification state binding failed", e); + } + XC_MethodHook applyCards = new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + if (notificationStateOwner != null || !notificationDriven || param.thisObject != nssl()) return; + boolean cards = ownsNotificationMotion(); + boolean footer = notificationFooter != null && ownsNotificationGeometry(param.thisObject); + if (!cards && !footer) return; + notificationStateOwner = param; + android.os.Trace.beginSection("ColorMotion.StackState"); + try { + if (cards) { + int rows = notificationRows.model.rowCount; + notificationApplied = notificationRows.apply(param.thisObject); + if (rows != notificationRows.model.rowCount) queueNotifFrame(); + } + if (footer) notificationFooter.apply(param.thisObject, notificationRows.model); + } catch (Throwable t) { + log(t); + } + } + + @Override + protected void afterHookedMethod(MethodHookParam param) { + if (notificationStateOwner != param) return; + try { + notificationRows.restoreApplied(notificationApplied); + } catch (Throwable t) { + log(t); + } finally { + if (notificationFooter != null) { + try { + notificationFooter.restore(); + if (ownsNotificationGeometry(param.thisObject)) + notificationFooter.render(param.thisObject, notificationRows.model, true); + } catch (Throwable t) { log(t); } + } + notificationApplied = null; + notificationStateOwner = null; + android.os.Trace.endSection(); + } + } + }; + hooks.findAndHookMethod(nsslClass, "applyCurrentState", applyCards); + hooks.findAndHookMethod(nsslClass, "startAnimationToState$1", applyCards); + XposedBridge.log(Entry.TAG + ": notification QS cascade state hooks installed"); + + // Samsung's own split-open motion slides the header, clock and blur layers in from above + // (translationY -50/-150 -> 0). ColorOS moves these with the panel translation instead. + try { qsScene = new QsSceneBridge(cl); } + catch (ReflectiveOperationException e) { throw new IllegalStateException("QS scene binding failed", e); } + hooks.findAndHookMethod(XposedHelpers.findClass(SPLIT_OPEN_ANIMATOR, cl), "setPosition$1", + float.class, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + if (!blurDriven || npvc == null || panel.barState(npvc) != 0) return; + try { + if (qsScene.apply(param.thisObject, (Float) param.args[0])) param.setResult(null); + } catch (Throwable t) { log(t); } + } + @Override + protected void afterHookedMethod(MethodHookParam param) { + try { + afterSplitOpenPosition(param.thisObject); + } catch (Throwable t) { + log(t); + } + } + }); + hooks.findAndHookMethod(XposedHelpers.findClass(SPLIT_OPEN_ANIMATOR, cl), "updateAnimators", + new XC_MethodHook() { + @Override protected void afterHookedMethod(MethodHookParam param) { + try { captureSplitViews(param.thisObject); } + catch (Throwable t) { log(t); } + } + }); + // Vector can retain an empty trampoline after rollback. Bind the broad factory last. + qsRows.clipping.install(); + } + + /** Set only around the module's render-only card pass; Samsung's own calls stay uncached. */ + private boolean renderingCards; + private final java.util.IdentityHashMap blurBackground = new java.util.IdentityHashMap<>(); + + /** + * Samsung's card setAlpha() re-derives isBlurBackground() on every call: color picker, + * colorized/media checks, power-saving/theme/transparency settings and a resource lookup. + * That was ~0.2 ms per fading card per frame. Its inputs cannot change within one opening, + * so render-pass calls reuse each card's first result until the motion stops. + */ + private void installBlurBackgroundCache() { + try { + Method method = XposedHelpers.findClass( + "com.android.systemui.statusbar.notification.row.ActivatableNotificationView", cl) + .getDeclaredMethod("isBlurBackground"); + if (method.getReturnType() != boolean.class) throw new NoSuchMethodException("isBlurBackground ABI"); + hooks.method(method, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + if (!renderingCards) return; + Boolean cached = blurBackground.get(param.thisObject); + if (cached != null) param.setResult(cached); + } + @Override protected void afterHookedMethod(MethodHookParam param) { + if (renderingCards && !param.hasThrowable() && param.getResult() instanceof Boolean) + blurBackground.put(param.thisObject, (Boolean) param.getResult()); + } + }); + XposedBridge.log(Entry.TAG + ": card blur-background cache installed"); + } catch (Throwable unavailable) { + XposedBridge.log(Entry.TAG + ": card blur-background cache unavailable: " + unavailable); + } + } + + private void installNotificationEdgeFade(Class stackClass, Class expandableClass) + throws ReflectiveOperationException { + NotificationEdgeFade edge = new NotificationEdgeFade(stackClass, expandableClass, cl); + hooks.findAndHookMethod(stackClass,"drawChild",android.graphics.Canvas.class,View.class, + long.class,new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + if (!ownsNotificationGeometry(param.thisObject)) return; + try { edge.begin(param,param.thisObject,(android.graphics.Canvas)param.args[0],(View)param.args[1]); } + catch (Throwable t) { log(t); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + try { edge.end(param); } catch (Throwable t) { log(t); } + } + }); + XposedBridge.log(Entry.TAG + ": continuous notification edge fade installed"); + } + + private void installNotificationFooter(Class stackClass, Class expandableClass) + throws ReflectiveOperationException { + notificationFooter = new NotificationFooter(stackClass, expandableClass); + Class shelfClass = stackClass.getField("mShelf").getType(); + // Samsung also refreshes shelf visibility from its separate running-animation updater, + // after the main state consumer. Keep that refresh on the same model pose as well. + hooks.findAndHookMethod(shelfClass, "updateAppearance", new XC_MethodHook() { + @Override protected void afterHookedMethod(MethodHookParam param) { + if (param.hasThrowable()) return; + try { + View stack = nssl(); + if (stack != null && ownsNotificationGeometry(stack) + && notificationFooter.isShelf(stack, param.thisObject)) + notificationFooter.render(stack, notificationRows.model, true); + } catch (Throwable t) { log(t); } + } + }); + XposedBridge.log(Entry.TAG + ": notification footer motion hook installed"); + } + + private void installNotificationGeometry(Class stackClass) throws ReflectiveOperationException { + notificationGeometry = new NotificationGeometry(stackClass); + hooks.findAndHookMethod(stackClass, "setExpandedHeight", float.class, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + if ((Float) param.args[0] > 0f && lastMaxDist > 0f + && ownsNotificationGeometry(param.thisObject) + && notificationGeometry.enter(param, param.thisObject)) { + // Preserve native geometry/event processing. Repeated animation frames now + // see the same layout height instead of scheduling a complete stack pass. + param.args[0] = lastMaxDist; + } + } catch (Throwable t) { log(t); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + try { notificationGeometry.exit(param); } + catch (Throwable t) { log(t); } + } + }); + hooks.findAndHookMethod(stackClass, "updateStackPosition", boolean.class, new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + if (ownsNotificationGeometry(param.thisObject)) notificationGeometry.enter(param, param.thisObject); + } catch (Throwable t) { log(t); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + try { notificationGeometry.exit(param); } + catch (Throwable t) { log(t); } + } + }); + // Hook the actual captured updater class, rather than all pre-draw listeners in SystemUI. + Class updater = stackClass.getDeclaredField("mChildrenUpdater").getType(); + hooks.findAndHookMethod(updater, "onPreDraw", new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + try { + View stack = nssl(); + if (stack == null || notificationGeometry.childrenUpdater(stack) != param.thisObject) return; + // A QS pull hides the stack from its DOWN (Samsung selects the side there), + // before the first height arrives. Defer that first collapsed pass as well. + boolean qsOpening = npvc != null && blurDriven && side == SIDE_QS && panel.fraction(npvc) > 0f; + if ((qsOpening || qsTouchDown) && npvc != null && panel.barState(npvc) == 0 + && currentSide(npvc) == SIDE_QS + && stack.isAttachedToWindow() && !stack.isShown() + && notificationGeometry.canDeferHiddenUpdate(stack)) { + // Keep the pending flag AND this pre-draw listener registered. Changed + // heights coalesce while QS hides the stack; its first visible traversal + // consumes the latest layout. Native events/animations still run above. + android.os.Trace.beginSection("ColorMotion.HiddenStackDeferred"); + param.setResult(Boolean.TRUE); + android.os.Trace.endSection(); + } else if (ownsNotificationGeometry(stack)) notificationGeometry.enter(param, stack); + } catch (Throwable t) { log(t); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + try { + notificationGeometry.exit(param); + if (notificationOpening.isWaiting() && !param.hasThrowable()) { + View stack = nssl(); + if (stack != null && notificationGeometry.childrenUpdater(stack) == param.thisObject) { + notificationOpening.setHost(stack); + notificationOpening.afterTraversal(stack); + } + } + } catch (Throwable failure) { failOpen(failure); } + } + }); + } + + private boolean ownsNotificationGeometry(Object stack) { + return !panelSwitching && notificationDriven && side == SIDE_SHADE && npvc != null && panel.barState(npvc) == 0 + && currentSide(npvc) == SIDE_SHADE && stack == nssl(); + } + + private XC_MethodHook createHeightConsumerHook(PanelHeightBinding height) { + return new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + if (heightDispatchDepth != 0) return; + try { + Object callback = param.thisObject; + if (interceptPanelHeight(height.panel.get(callback), height.height.getFloat(callback))) + param.setResult(null); + } catch (Throwable failure) { failOpen(failure); } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + if (heightDispatchDepth != 0) return; + try { afterSetExpandedHeight(height.panel.get(param.thisObject)); } + catch (Throwable failure) { failOpen(failure); } + } + }; + } + + private void installTouchHooks(Class touchHandler) { + XC_MethodHook touchDispatch = createTouchDispatchHook(); + // Samsung's handleExternalTouch calls onTouchEvent directly. Guarding only the + // View.OnTouchListener wrapper misses the normal MOVE stream after interception. + if (hooks.hookAllMethods(touchHandler, "onTouchEvent", touchDispatch).isEmpty() + || hooks.hookAllMethods(touchHandler, "onInterceptTouchEvent", touchDispatch).isEmpty()) { + throw new IllegalStateException("Panel touch dispatch hooks missing"); + } + } + + private XC_MethodHook createTouchDispatchHook() { + return new XC_MethodHook() { + @Override protected void beforeHookedMethod(MethodHookParam param) { + Object event = param.args[param.args.length - 1]; + if (!(event instanceof MotionEvent)) return; + MotionEvent motion = (MotionEvent) event; + if (motion.getActionMasked() == MotionEvent.ACTION_MOVE) dragDispatchDepth++; + // Intercept and touch may both receive the same DOWN. Initialize once per + // physical gesture, and keep that identity through native release retargets. + if (motion.getActionMasked() == MotionEvent.ACTION_DOWN + && motion.getDownTime() != gestureDownTime) { + gestureDownTime = motion.getDownTime(); + gestureInitialized = false; + gestureReleased = false; + openingReveal = false; + } + } + @Override protected void afterHookedMethod(MethodHookParam param) { + Object event = param.args[param.args.length - 1]; + if (!(event instanceof MotionEvent)) return; + int action = ((MotionEvent) event).getActionMasked(); + if (action == MotionEvent.ACTION_MOVE) dragDispatchDepth--; + else if (action == MotionEvent.ACTION_DOWN) { + try { + qsTouchDown = !failed && npvc != null && panelCollapsed && panel.barState(npvc) == 0 + && currentSide(npvc) == SIDE_QS; + } catch (Throwable t) { qsTouchDown = false; } + } + else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + qsTouchDown = false; + // Some cancelled/handed-off gestures do not synchronously issue a fling. + // Keep the gesture's reveal and saved velocity, but stop its drag clock. + stopDrag(); + } + } + }; + } + + private XC_MethodHook createFlingHook() { + return new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + try { + beforeFling(param); + } catch (Throwable t) { + log(t); + } + } + + @Override + protected void afterHookedMethod(MethodHookParam param) { + try { + afterFling(param.thisObject); + } catch (Throwable t) { + log(t); + } finally { + inFling = false; + pendingCurve = null; + try { + afterSetExpandedHeight(param.thisObject); + } catch (Throwable t) { + log(t); + } + } + } + }; + } + + // ---------------------------------------------------------------- expansion fraction + + /** Set to true to trace hook activity in logcat (tag ColorMotion). */ + private static final boolean DEBUG = false; + + static void d(String msg) { + if (DEBUG) { + android.util.Log.d(Entry.TAG, msg); + } + } + + private void beforeSetExpandedHeight(XC_MethodHook.MethodHookParam param) { + if (interceptPanelHeight(param.thisObject, (Float) param.args[0])) param.setResult(null); + } + + /** Shared primitive input path; an inlined native setter needs no temporary hook args. */ + private boolean interceptPanelHeight(Object p, float requested) { + if (injecting) { + return false; + } + if (DEBUG) { + d("setExpandedHeightInternal h=" + requested + " bar=" + panel.barState(p) + + " tracking=" + panel.tracking(p) + " inFling=" + inFling + + " touch=" + calledFromTouchHandler() + " side=" + currentSide(p)); + } + npvc = p; + if (panel.barState(p) != 0) { + stopDrag(); + return false; + } + if (panel.side(p) > SIDE_SHADE) return false; + boolean tracking = panel.tracking(p); + if (!tracking || inFling) { + if (dragging && !tracking) { + stopDrag(); + } + return false; + } + if (!calledFromTouchHandler()) { + return false; + } + float initialOffset = panel.initialOffset(p); + if (!dragging) { + // Only first-drag readiness needs geometry here. MOVE samples merely retarget + // the spring; applyFraction queries current native geometry for each height + // update. Repeating the full native height calculation at input frequency + // adds scans without making the next applied height any fresher. + float maxDist = maxDistance(p); + if (maxDist <= 0f) return false; + lastMaxDist = maxDist; + startDrag(p, maxDist); + if (panelClosedOnDown && panel.fraction(p) <= 0f) primeOpening(p); + } + float delta = requested - initialOffset; + QsModel model = motionModel(); + if (delta > 0f && dragStartFraction < 1f) openingReveal = true; + updateReveal(model, panel.fraction(p)); + float fingerFraction = model.drag(delta, dragStartFraction); + fraction.spring.response(model.dragResponse(fraction.spring.value)); + startMotionFrames(); + fraction.animateTo(fingerFraction); + return true; + } + + private void startDrag(Object p, float maxDist) { + heightDriven = false; + dragging = true; + blurDriven = true; + side = currentSide(p); + panelClosedOnDown = panel.closedOnDown(p) || panel.fraction(p) <= 0f; + trackingStartVelocity = yVelocity(p); + float current = panel.fraction(p); + float velocity = 0f; + if (activeCurve != null) { + // Keep the momentum at the last native interpolation, including scaled/paused/seeked phase. + velocity = activeCurve.velocityAtLastSample(); + activeCurve = null; + } + fraction.cancel(); + fraction.spring.value = current; + fraction.spring.velocity = velocity; + fraction.spring.target = current; + fraction.spring.damping(1.0).minimumVisibleChange(ColorOsParams.FRACTION_MIN_VISIBLE_CHANGE); + dragStartFraction = current; + prepareMotionModel(); + // A panel gesture owns its cards again, even if the previous gesture scrolled the list. + if (side == SIDE_SHADE) { + notificationListNative = false; + captureNotificationScroll(); + } + if (!gestureInitialized) { + beginMotionGesture(panelClosedOnDown, trackingStartVelocity); + openingReveal = panelClosedOnDown; + } else motionModel().dragStart(panelClosedOnDown, trackingStartVelocity); + updateReveal(motionModel(), current); + gestureInitialized = true; + gestureReleased = false; + if (side == SIDE_QS) applyQsTranslation(qsRows.model.translation.value); + } + + /** + * The spring's first height arrives a frame after this MOVE. Samsung would apply the finger's + * height now; without it the first layout pass runs collapsed and the first visible frame pays + * the first-expansion listeners plus a second full stack pass. One pixel starts that work in + * this (still invisible) frame, before its traversal. + */ + private void primeOpening(Object p) { + openingPrimed = true; + injecting = true; + try { panel.setHeight(p, 1f); } + finally { injecting = false; } + } + + private QsModel motionModel() { + return side == SIDE_QS ? qsRows.model : notificationRows.model; + } + + private void beginMotionGesture(boolean closed, float velocity) { + motionModel().beginGesture(closed, velocity); + if (side == SIDE_QS) qsRows.beginOpening(closed); + else { + captureNotificationScroll(); + if (closed) { + notificationListNative = false; + // The same reveal gate must wait for the first native list traversal too. + // Metadata/rows retained from a prior opening do not establish readiness. + if (notificationRows.isBound()) { + notificationRows.model.setOpeningContentReady(false); + notificationOpening.begin(nssl()); + notifClock.reset(); + } + } + } + } + + private void captureNotificationScroll() { + notificationScrollKnown = false; + View stack = nssl(); + if (stack == null || notificationGeometry == null) return; + try { + notificationScrollAtStart = notificationGeometry.scrollPosition(stack); + notificationScrollKnown = true; + } catch (IllegalAccessException e) { log(e); } + } + + private void updateReveal(QsModel model, float fraction) { + if (openingReveal) model.onOpeningFraction(fraction); + else model.onFraction(fraction); + } + + private void prepareMotionModel() { + QsModel m = motionModel(); + m.px = devicePx(); + View root = side == SIDE_QS ? qsView() : nssl(); + if (root != null) { + int height = root.getMeasuredHeight(); + m.rootHeight = height > 0 ? height : root.getResources().getDisplayMetrics().heightPixels; + if (side == SIDE_QS) { + qsMotionView = new WeakReference<>(root); + qsRows.setMotionHost(root); + } + } + if (side == SIDE_QS) { + stopNotificationMotion(); + qsRows.prepare(); + qsRows.setArmed(true); + } else { + qsRows.setArmed(false); + releaseStaleQsHost(); + notificationDriven = true; + notificationOpening.setHost(root); + if (root != null) { + try { notificationRows.prepare(root); } + catch (IllegalAccessException e) { log(e); } + } + } + } + + private void startMotionFrames() { + if (side == SIDE_QS) qsRows.start(); + else queueNotifFrame(); + } + + private void stopDrag() { + openingPrimed = false; + if (dragging) { + dragging = false; + fraction.cancel(); + } + } + + private void applyFraction(float f) { + Object p = npvc; + if (p == null) { + return; + } + float maxDist = maxDistance(p); + if (maxDist <= 0) { + // Not laid out yet on the first frames after SystemUI starts. + maxDist = lastMaxDist; + } + if (maxDist <= 0) { + return; + } + lastMaxDist = maxDist; + float height = f * maxDist; + if (openingPrimed && dragging && height < 1f) height = 1f; + injecting = true; + try { + panel.setHeight(p, height); + } finally { + injecting = false; + } + } + + private void afterSetExpandedHeight(Object p) { + npvc = p; + if (panel.barState(p) != 0) { + if (panelSlide != null) panelSlide.abort(); + panelSwitching = false; + qsRows.setArmed(false); + stopNotificationMotion(); + return; + } + // Samsung has already computed this with the exact maximum used for this height. + // Recomputing getMaxPanelHeight here scans native geometry/notification state again. + float raw = panel.fraction(p); + int nativeSide = panel.side(p); + // Native state 2 means both panels are sliding, 3 means neither panel is active. + // Neither is a notification opening. Its own final slide consumer owns that handoff. + if (nativeSide > SIDE_SHADE || panelSwitching) { + if (raw <= 0f) { + panelCollapsed = true; + if (nativeSide == 3) { + if (panelSlide != null) panelSlide.abort(); + panelSwitching = false; + stopDrag(); + activeCurve = pendingCurve = null; + qsRows.snapHidden(); + qsRows.setArmed(false); + stopNotificationMotion(); + gestureInitialized = gestureReleased = heightDriven = false; + releaseBlurIfSettled(); + } + } + return; + } + if (raw > 0f && panelCollapsed && gestureInitialized && openingReveal && nativeSide != side) { + // A fast external/focus-transfer gesture can initialize motion before Samsung + // finalizes its side. This is still the first opening, not an open-panel switch. + float velocity = motionModel().yVelocity; + boolean released = gestureReleased; + side = nativeSide; + prepareMotionModel(); + beginMotionGesture(true, velocity); + if (released) motionModel().release(velocity, true); + } + if (raw > 0f && !panelCollapsed && nativeSide != side) { + // Some native direct/reversed routes switch the stable side without calling + // PanelTransitionAnimator.slide. An outgoing curve must not keep its model + // active or leave the newly shown QS host at its old hidden translation. + stopDrag(); + fraction.cancel(); + activeCurve = pendingCurve = null; + inFling = heightDriven = false; + side = nativeSide; + prepareMotionModel(); + motionModel().snapShown(); + if (side == SIDE_QS) applyQsTranslation(0f); + gestureInitialized = gestureReleased = true; + openingReveal = false; + blurDriven = true; + if (splitOpenAnimator != null) applySplitHeaderPosition(splitOpenAnimator); + startMotionFrames(); + } + boolean freshOpening = panelCollapsed && raw > 0f; + panelCollapsed = raw <= 0f; + if (!dragging && !inFling && activeCurve == null) { + side = currentSide(p); + } + if (raw <= 0f && !dragging && !inFling && activeCurve == null) { + gestureInitialized = gestureReleased = false; + heightDriven = false; + } + if (freshOpening && !gestureInitialized && !dragging && !inFling && activeCurve == null) { + // Notification launches, external/programmatic expansions and intercepted tiny + // pulls can update height without ever entering the tracking MOVE/fling hooks. + prepareMotionModel(); + beginMotionGesture(true, 0f); + gestureInitialized = true; + gestureReleased = true; + openingReveal = true; + heightDriven = true; + blurDriven = true; + lastHeightFraction = 0f; + } + if (heightDriven && !dragging && !inFling && activeCurve == null && raw > 0f) { + QsModel model = motionModel(); + if (raw < lastHeightFraction) { + openingReveal = false; + if (side == SIDE_SHADE) notificationListNative = false; + } + model.blurRaw.target = raw; + model.translation.target = -model.dest() * (1f - QsModel.clamp(raw / 0.86f, 0f, 1f)); + } + lastHeightFraction = raw; + if (side == SIDE_QS) { + stopNotificationMotion(); + qsOnFractionChanged(raw); + } else { + shadeOnFractionChanged(raw); + } + } + + // ---------------------------------------------------------------- release fling + + private void beforeFling(XC_MethodHook.MethodHookParam param) { + Object p = param.thisObject; + npvc = p; + inFling = false; + if (panel.barState(p) != 0 || panel.side(p) > SIDE_SHADE || panelSwitching) { + return; + } + heightDriven = false; + float maxDist = maxDistance(p); + if (maxDist <= 0) { + return; + } + float vel = (Float) param.args[0]; + lastMaxDist = maxDist; + boolean expand = (Boolean) param.args[1]; + if (DEBUG) { + d("flingToHeight vel=" + vel + " expand=" + expand + " target=" + param.args[2] + " dragging=" + dragging); + } + float x0 = panel.fraction(p); + boolean wasDragging = dragging || (gestureInitialized && !gestureReleased); + float v0 = wasDragging ? fraction.spring.velocity : 0f; + if (!wasDragging && activeCurve != null) { + v0 = activeCurve.velocityAtLastSample(); + } + stopDrag(); + float target = expand ? 1f : 0f; + int selectedSide = currentSide(p); + if (side != selectedSide) { + // finishInputFocusTransfer selects the native side immediately before fling. + // An earlier MOVE may still have initialized the previous panel's model. + // Reinitialize only that mismatched model; never replace Samsung's area policy. + side = selectedSide; + gestureInitialized = false; + } + prepareMotionModel(); + if (side == SIDE_SHADE && !expand) notificationListNative = false; + QsModel model = motionModel(); + if (!gestureInitialized) { + panelClosedOnDown = panel.closedOnDown(p) || x0 <= 0f; + // Tracking and direct native flings enter the same gesture/reveal sequence. + beginMotionGesture(expand && panelClosedOnDown, vel); + gestureInitialized = true; + } + if (expand) openingReveal = true; + else if (!expand) openingReveal = false; + model.release(vel, expand); + gestureReleased = true; + updateReveal(model, x0); + blurDriven = true; + android.os.Trace.beginSection("ColorMotion.FlingPrepare"); + try { + pendingCurve = FlingCurve.simulate(x0, v0, target, model::flingResponse, + ColorOsParams.FRACTION_MIN_VISIBLE_CHANGE, flingWorkspace); + } finally { android.os.Trace.endSection(); } + startMotionFrames(); + inFling = true; + } + + private FlingCurve pendingCurve; + private float lastMaxDist; + + /** + * flingToHeight builds the fling ValueAnimator, hands it to setAnimator() and starts it. setAnimator + * is small enough that the AOT-compiled SystemUI (compiler filter "speed") inlines it, so the + * animator is taken over here instead, right after start() and before its first frame. + */ + private void afterFling(Object p) { + FlingCurve curve = pendingCurve; + if (!inFling || curve == null) { + return; + } + Object fling = XposedHelpers.getObjectField(p, "mFlingAnimator"); + Object height = XposedHelpers.getObjectField(p, "mHeightAnimator"); + if (DEBUG) { + d("afterFling fling=" + fling + " height=" + height + " curveMs=" + curve.durationMs); + } + if (!(fling instanceof ValueAnimator) || fling != height) { + finishImmediateFling(p); + return; + } + ValueAnimator animator = (ValueAnimator) fling; + if (!animator.isStarted() || animator.getDuration() <= 1) { + // The card/tile cascade has its own clock even if Samsung finishes the height at once. + finishImmediateFling(p); + return; + } + zeroOvershoot(animator); + // Samsung's animator already runs mExpandedHeight -> target (ValueAnimator.ofFloat), which are + // the curve's endpoints, so only its timing is replaced. + animator.setInterpolator(curve); + animator.setDuration(Math.max(1, curve.durationMs)); + activeCurve = curve; + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + if (activeCurve == curve) { + activeCurve = null; + afterSetExpandedHeight(p); + } + } + }); + } + + private void finishImmediateFling(Object p) { + updateReveal(motionModel(), panel.fraction(p)); + startMotionFrames(); + } + + /** + * Samsung's fling update listener (NotificationPanelViewController$$ExternalSyntheticLambda52) + * adds an over-expansion bounce from its captured floats; ColorOS has no such overshoot. + */ + private static void zeroOvershoot(ValueAnimator animator) { + try { + Field f = ValueAnimator.class.getDeclaredField("mUpdateListeners"); + f.setAccessible(true); + @SuppressWarnings("unchecked") + ArrayList listeners = (ArrayList) f.get(animator); + if (listeners == null) { + return; + } + for (Object l : listeners) { + if (!l.getClass().getName().startsWith(NPVC + "$$ExternalSyntheticLambda")) { + continue; + } + for (Field lf : l.getClass().getDeclaredFields()) { + if (lf.getType() == float.class) { + lf.setAccessible(true); + lf.setFloat(l, 0f); + } + } + } + } catch (Throwable t) { + log(t); + } + } + + // ---------------------------------------------------------------- notification side + + private boolean ownsNotificationMotion() { + if (notificationDriven) noticeNotificationScroll(nssl()); + return !panelSwitching && notificationDriven && !notificationListNative && (notificationAnimating || dragging || activeCurve != null) + && side == SIDE_SHADE && npvc != null + && panel.barState(npvc) == 0; + } + + private void noticeNotificationScroll(View stack) { + if (notificationListNative || stack == null || notificationGeometry == null) return; + // NSSL can mark a closing/intercepted swipe as being dragged too. That is not an + // independent list scroll and must not disable the panel's exit animation. + if (dragging || inFling || activeCurve != null || (gestureInitialized && !gestureReleased)) return; + if (heightDriven && (panel.fraction(npvc) < 1f || notificationAnimating)) return; + try { + int offset = notificationGeometry.scrollPosition(stack); + if (!notificationScrollKnown) { + notificationScrollAtStart = offset; + notificationScrollKnown = true; + } + // A retained offset is not a new gesture. A real drag or changing offset + // still gives Samsung immediate ownership, even during the entrance. + if (notificationAnimating && offset == notificationScrollAtStart + && !notificationGeometry.fingerScrolling(stack)) return; + if (notificationGeometry.scrolling(stack)) notificationListNative = true; + } + catch (IllegalAccessException e) { log(e); } + } + + private void shadeOnFractionChanged(float f) { + if (!notificationDriven) return; + if (f == 0f && !dragging && !inFling && activeCurve == null) { + stopNotificationMotion(); + releaseBlurIfSettled(); + return; + } + updateReveal(notificationRows.model, f); + queueNotifFrame(); + } + + private void stopNotificationMotion() { + notificationOpening.cancel(); + cancelNotifFrames(); + blurBackground.clear(); + if (!notificationDriven) return; + notificationDriven = false; + notificationAnimating = false; + View stack = nssl(); + if (stack != null && notificationGeometry != null && npvc != null) { + try { notificationGeometry.restoreHeight(stack, panel.fraction(npvc) * lastMaxDist); } + catch (ReflectiveOperationException e) { log(e); } + } + notificationRows.model.reset(); + if (splitOpenAnimator != null) { + for (View v : splitHeaderViews) { + if (v != null) { + v.setScaleX(1f); + v.setScaleY(1f); + } + } + try { + float position = panel.fraction(npvc); + if (qsScene != null) qsScene.restoreHeaderPose(splitOpenAnimator, position); + else for (View v : splitHeaderViews) if (v != null) { + // Only used before native scene binding is available. + v.setAlpha(position == 0f ? 0f : 1f); + v.setTranslationY(0f); + } + } catch (ReflectiveOperationException e) { log(e); } + } + requestNsslUpdate(); + } + + // ---------------------------------------------------------------- control center side + + private boolean canSwitchPanels() { + return !failed && npvc != null && panel.barState(npvc) == 0 && panel.fraction(npvc) > 0f; + } + + private void beginPanelSwitch() { + notificationOpening.cancel(); + panelSwitching = true; + stopDrag(); + fraction.cancel(); + activeCurve = pendingCurve = null; + inFling = heightDriven = false; + cancelNotifFrames(); + notificationAnimating = false; + qsRows.setArmed(false); + qsRows.model.snapShown(); + notificationRows.model.snapShown(); + notificationListNative = false; + qsRows.setArmed(true); + applyQsTranslation(0f); + requestNsslUpdate(); + } + + private void afterPanelSlide(Object animator, Object[] args) throws ReflectiveOperationException { + if (!panelSlide.allowed(animator)) { + if (panelSwitching) { + panelSlide.abort(); + panelSwitching = false; + qsRows.setArmed(false); + stopNotificationMotion(); + } + return; + } + int state = panelSlide.state(animator); + if (state == 2 && panelSlide.isPanelTransition(args) && (Float) args[1] == 0f) { + if (!panelSwitching) beginPanelSwitch(); + if (panelSlide.isHorizontal(args)) panelSlide.apply(animator, args); + } else if ((state == SIDE_QS || state == SIDE_SHADE) && (panelSwitching + || (!panelCollapsed && side != state && panel.fraction(npvc) >= 0.99f))) { + // An immediate/vertical native side change may finish without another height + // callback. Adopt its side as well, retaining its native transition style. + if (!panelSwitching) beginPanelSwitch(); + panelSlide.reset(); + panelSwitching = false; + side = state; + prepareMotionModel(); + motionModel().snapShown(); + openingReveal = false; + gestureInitialized = gestureReleased = true; + panelCollapsed = false; + blurDriven = true; + startMotionFrames(); + } + } + + /** QSPanelExpandFraction.onFractionChanged -> header / tile-row visibility. */ + private void qsOnFractionChanged(float f) { + qsRows.setArmed(true); + if (f == 0f && !dragging && !inFling && activeCurve == null) { + qsRows.snapHidden(); + trackingStartVelocity = 0f; + releaseBlurIfSettled(); + return; + } + updateReveal(qsRows.model, f); + qsRows.start(); + } + + private void applyQsTranslation(float ty) { + View qs = qsMotionView.get(); + if (qs == null || !qs.isAttachedToWindow()) { + qs = qsView(); + qsMotionView = new WeakReference<>(qs); + } + if (qs != null) { + qsRows.setMotionHost(qs); + qsRows.clipping.prepareHosts(qs); + if (qs.getTranslationY() != ty) qs.setTranslationY(ty); + } + } + + private void afterSplitOpenPosition(Object animator) { + if (splitOpenAnimator != animator || splitHeaderViews[0] == null) captureSplitViews(animator); + applySplitHeaderPosition(animator); + } + + private void captureSplitViews(Object animator) { + splitOpenAnimator = animator; + if (splitViewBinding == null || splitViewBinding.owner != animator.getClass()) + splitViewBinding = new SplitViewBinding(animator.getClass()); + splitHeaderViews[0] = splitViewBinding.read(animator, 0); + splitHeaderViews[1] = splitViewBinding.read(animator, 1); + splitHeaderViews[2] = qsScene != null && qsScene.hasSeparateButtons() + ? splitViewBinding.read(animator, 2) : null; + splitBlurViews[0] = splitViewBinding.read(animator, 3); + splitBlurViews[1] = splitViewBinding.read(animator, 4); + splitBlurViews[2] = splitViewBinding.read(animator, 5); + for (int i = 0; i < splitHeaderViews.length; i++) { + nestedHeader[i] = false; + for (int j = 0; j < splitHeaderViews.length; j++) + if (i != j && isDescendant(splitHeaderViews[i], splitHeaderViews[j])) nestedHeader[i] = true; + } + } + + private static boolean isDescendant(View child, View parent) { + if (child == null || parent == null || child == parent) return false; + android.view.ViewParent p = child.getParent(); + for (int depth = 0; p != null && depth < 32; depth++, p = p.getParent()) { + if (p == parent) return true; + } + return false; + } + + /** + * The header clock lives inside the QS fragment's view. When a QS opening collapses, snapHidden() + * leaves that host translated to its hidden offset; the notification shade never reset it, so + * the next notification opening showed the clock lifted against the carrier row. + */ + private void releaseStaleQsHost() { + View host = qsMotionView.get(); + if (host == null) { + host = qsView(); + if (host != null) qsMotionView = new WeakReference<>(host); + } + if (host != null && host.getTranslationY() != 0f) host.setTranslationY(0f); + } + + private void applySplitHeaderPosition(Object animator) { + if (npvc == null || panel.barState(npvc) != 0 || panelSwitching || panel.side(npvc) > SIDE_SHADE) return; + if (side == SIDE_SHADE) releaseStaleQsHost(); + if (side == SIDE_SHADE && !notificationDriven) return; + if (panel.fraction(npvc) == 0f && !dragging && !inFling) return; + QsModel model = motionModel(); + float ty = model.translation.value; + if (side == SIDE_SHADE) ty += model.headerTranslation(); + for (int i = 0; i < splitHeaderViews.length; i++) { + View v = splitHeaderViews[i]; + if (v != null) { + // Both sides can contain nested native header views. QS also has its + // Compose header inside the translated native content host. + boolean nested = nestedHeader[i] || (side == SIDE_QS && isDescendant(v, qsMotionView.get())); + float y = nested ? 0f : ty; + if (v.getTranslationY() != y) v.setTranslationY(y); + float alpha = nested ? 1f : model.headerOpacity(); + if (v.getAlpha() != alpha) v.setAlpha(alpha); + if (side == SIDE_SHADE) { + float scale = nested ? 1f : model.headerScale.value; + if (v.getScaleX() != scale) v.setScaleX(scale); + if (v.getScaleY() != scale) v.setScaleY(scale); + } + } + } + for (View v : splitBlurViews) { + if (v != null && v.getTranslationY() != 0f) { + v.setTranslationY(0f); + } + } + } + + // ---------------------------------------------------------------- blur + + /** + * Both surfaces use the reference QS blur curve with the minimum opening duration. + * Returns null to keep Samsung's value (mirror, bouncer, lock screen, or not driven by us). + */ + private Float colorOsBlurFraction(Object controller) { + float value = ownedBlurFraction(controller); + return Float.isNaN(value) ? null : value; + } + + /** Primitive hot path; NaN hands the complete native operation back to Samsung. */ + private float ownedBlurFraction(Object controller) { + if (!blurDriven || npvc == null || panel.barState(npvc) != 0) { + return Float.NaN; + } + try { + if (mirrorVisible.getBoolean(controller) || bouncerShowing.getBoolean(controller)) return Float.NaN; + } catch (IllegalAccessException e) { throw new IllegalStateException(e); } + // A disarmed surface can retain an old full-blur spring. Taking the maximum would let + // that stale value bypass the active panel's opening clock, especially on notifications. + return motionModel().blurFraction(); + } + + /** Runs Samsung's blur frame (doBlur + background alpha) with the current ColorOS fraction. */ + private void requestBlurFrame() { + Object c = blurController; + if (c == null || !blurDriven) { + return; + } + try { + float value = ownedBlurFraction(c); + if (Float.isNaN(value) || value == lastRequestedBlur) return; + android.os.Trace.beginSection("ColorMotion.Blur"); + try { + blurFrame.request(c); + lastRequestedBlur = value; + } + finally { android.os.Trace.endSection(); } + } catch (Throwable t) { + log(t); + } + } + + /** Hands the blur back to Samsung once the panel has collapsed and both springs are at rest. */ + private void releaseBlurIfSettled() { + notificationRows.model.blurRaw.snapTo(0f); + qsRows.model.blurRaw.snapTo(0f); + requestBlurFrame(); + blurDriven = false; + blurFrameGate.reset(); + lastRequestedBlur = Float.NaN; + } + + private boolean isMotionRunning() { + // Coalesce only while an element clock advances the frame epoch. A settled + // held finger can leave dragging=true without any model callbacks; its later + // native blur invalidations must still run even at an unchanged fraction. + return notificationAnimating || qsRows.isRunning(); + } + + // ---------------------------------------------------------------- notification frame clock + + private void queueNotifFrame() { + notificationAnimating = true; + if (!notifFrameQueued) { + if (notifRun == null) notifRun = new NotificationRun(); + notifFrameQueued = true; + android.view.Choreographer.getInstance().postFrameCallback(notifRun); + } + } + + private void cancelNotifFrames() { + if (notifRun != null) android.view.Choreographer.getInstance().removeFrameCallback(notifRun); + notifRun = null; + notifFrameQueued = false; + notifClock.reset(); + } + + private void requestNsslUpdate() { + View nssl = nssl(); + if (nssl != null) { + XposedHelpers.callMethod(nssl, "requestChildrenUpdate"); + } + } + + private float devicePx() { + Context ctx = context(); + return ctx == null ? 1f : ctx.getResources().getDisplayMetrics().widthPixels / QsModel.COLOROS_WIDTH_PX; + } + + // ---------------------------------------------------------------- helpers + + private int currentSide(Object p) { + return panel.side(p); + } + + /** MOVE in either direct onTouchEvent or intercept feeds the spring; terminal events stay native. */ + private boolean calledFromTouchHandler() { + return dragDispatchDepth > 0; + } + + private float maxDistance(Object p) { + return panel.maxDistance(p); + } + + private float yVelocity(Object p) { + try { + VelocityTracker vt = (VelocityTracker) panel.velocityTracker(p); + vt.computeCurrentVelocity(1000); + return vt.getYVelocity(); + } catch (Throwable t) { + return 0f; + } + } + + private View nssl() { + View cached = notificationStack.get(); + if (notificationStackPanel.get() == npvc && cached != null && cached.isAttachedToWindow()) return cached; + try { + Object controller = XposedHelpers.getObjectField(npvc, "mNotificationStackScrollLayoutController"); + View view = (View) XposedHelpers.getObjectField(controller, "mView"); + notificationStack = new WeakReference<>(view); + notificationStackPanel = new WeakReference<>(npvc); + return view; + } catch (Throwable t) { + return null; + } + } + + private View qsView() { + try { + Object qsController = XposedHelpers.getObjectField(npvc, "mQsController"); + Object qs = XposedHelpers.getObjectField(qsController, "mQs"); + return qs == null ? null : (View) XposedHelpers.callMethod(qs, "getView"); + } catch (Throwable t) { + return null; + } + } + + private Context context() { + View root = (View) callOrNull(npvc, "getView"); + return root == null ? null : root.getContext(); + } + + private static Object callOrNull(Object o, String method) { + if (o == null) { + return null; + } + try { + return XposedHelpers.callMethod(o, method); + } catch (Throwable t) { + return null; + } + } + + private static float clamp(float v, float lo, float hi) { + return Math.max(lo, Math.min(hi, v)); + } + + private static float lerp(float a, float b, float t) { + return a + (b - a) * t; + } + + /** MonoSpline$$ExternalSyntheticOutline0.m(max, min, t, max) = max - (max - min) * t. */ + private static float lerpResponse(float max, float min, float t) { + return max - (max - min) * t; + } + + private static void log(Throwable t) { + XposedBridge.log(Entry.TAG + ": " + t); + } +} diff --git a/hook/src/main/java/dev/colormotion/SplitViewBinding.java b/hook/src/main/java/dev/colormotion/SplitViewBinding.java new file mode 100644 index 00000000..7088fd05 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/SplitViewBinding.java @@ -0,0 +1,57 @@ +package dev.colormotion; + +import android.view.View; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +/** Cached metadata only. Every capture still reads the live wrapper and calls its actual getter. */ +final class SplitViewBinding { + private static final Object[] NO_ARGS = new Object[0]; + private static final String[] NAMES = {"header", "clockDateContainer", "buttonContainer", + "blurParent", "largeShadowView", "smallShadowView"}; + final Class owner; + private final Field[] fields = new Field[NAMES.length]; + private final Class[] getterOwners = new Class[NAMES.length]; + private final Method[] getters = new Method[NAMES.length]; + + SplitViewBinding(Class owner) { + this.owner = owner; + for (int i = 0; i < fields.length; i++) { + for (Class type = owner; type != null; type = type.getSuperclass()) { + try { + Field f = type.getDeclaredField(NAMES[i]); + f.setAccessible(true); + fields[i] = f; + break; + } catch (NoSuchFieldException absent) { /* Search the inherited contract. */ } + catch (Throwable unsupported) { break; } + } + } + } + + View read(Object animator, int slot) { + try { + Field field = fields[slot]; + if (field == null) return null; + Object wrapper = field.get(animator); + if (wrapper == null) return null; + Class type = wrapper.getClass(); + if (getterOwners[slot] != type) { + Method selected = null; + for (Class candidate = type; candidate != null; candidate = candidate.getSuperclass()) { + try { + Method method = candidate.getDeclaredMethod("getView"); + method.setAccessible(true); + selected = method; + break; + } catch (NoSuchMethodException absent) { /* Search the inherited getter. */ } + } + // A failed access/linkage operation must not cache an unavailable getter. + getters[slot] = selected; + getterOwners[slot] = type; + } + Method method = getters[slot]; + return method == null ? null : (View) method.invoke(wrapper, NO_ARGS); + } catch (Throwable unavailable) { return null; } + } +} diff --git a/hook/src/main/java/dev/colormotion/Spring.java b/hook/src/main/java/dev/colormotion/Spring.java new file mode 100644 index 00000000..9b0644d0 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/Spring.java @@ -0,0 +1,146 @@ +package dev.colormotion; + +/** + * Damped harmonic oscillator stepped with the closed-form solution. + * + * Mirrors androidx.dynamicanimation SpringForce.updateValues and the reference + * COUISpringForce.updateValues (defpackage/COUISpringForce.java): stiffness = naturalFreq^2, + * setResponse(r) => naturalFreq = 2*pi/r, setBounce(b) => dampingRatio = 1 - b, + * valueThreshold = minimumVisibleChange * 0.75, velocityThreshold = valueThreshold * 62.5. + */ +final class Spring { + float value; + float velocity; + float target; + double naturalFreq = Math.sqrt(1500.0); + double dampingRatio = 1.0; + float valueThreshold = 0.00075f; + float velocityThreshold = 0.00075f * 62.5f; + private long cachedDt = Long.MIN_VALUE; + private double cachedW = Double.NaN, cachedZ = Double.NaN; + private double decay, sin, cos, dampedW, gPlus, gMinus, decayPlus, decayMinus; + // Integer-millisecond clocks commonly alternate between two frame intervals. Keep + // their time-dependent coefficients without changing the solver's arithmetic. + private long alternateDt = Long.MIN_VALUE; + private double alternateA, alternateB, alternateC; + private boolean alternateValid; + + static float responseToStiffness(float response) { + // OplusPanelAnimationExImplKt.responseToStiffness / AnimatorUtils.responseToStiffness + return (float) Math.pow(2 * Math.PI / (response == 0f ? 1.0 : response), 2.0); + } + + Spring stiffness(double k) { + naturalFreq = Math.sqrt(k); + return this; + } + + Spring response(float r) { + naturalFreq = 2 * Math.PI / r; + return this; + } + + Spring damping(double ratio) { + dampingRatio = ratio; + return this; + } + + Spring bounce(float b) { + dampingRatio = 1.0 - b; + return this; + } + + Spring minimumVisibleChange(float change) { + valueThreshold = Math.abs(change) * 0.75f; + velocityThreshold = valueThreshold * 62.5f; + return this; + } + + void snapTo(float v) { + value = v; + target = v; + velocity = 0f; + } + + boolean isAtRest() { + return Math.abs(velocity) < velocityThreshold && Math.abs(value - target) < valueThreshold; + } + + /** Advances the spring by dtMs milliseconds. Returns true once it has settled on the target. */ + boolean step(long dtMs) { + double t = dtMs / 1000.0; + double w = naturalFreq; + double z = dampingRatio; + boolean alternate = false; + if (cachedDt != dtMs || cachedW != w || cachedZ != z) { + if (cachedW == w && cachedZ == z) { + if (alternateValid && alternateDt == dtMs) { + alternate = true; + } else { + alternateDt = cachedDt; + alternateA = z > 1 ? decayMinus : decay; + alternateB = z > 1 ? decayPlus : sin; + alternateC = cos; + alternateValid = true; + } + } else { + // Both intervals belong to the same natural frequency and damping. + alternateDt = Long.MIN_VALUE; + alternateValid = false; + } + if (!alternate) { + cachedDt = dtMs; + cachedW = w; + cachedZ = z; + if (z > 1) { + double root = Math.sqrt(z * z - 1); + gPlus = -z * w + w * root; + gMinus = -z * w - w * root; + decayMinus = Math.exp(gMinus * t); + decayPlus = Math.exp(gPlus * t); + } else if (z == 1) { + decay = Math.exp(-w * t); + } else { + dampedW = w * Math.sqrt(1 - z * z); + decay = Math.exp(-z * w * t); + sin = Math.sin(dampedW * t); + cos = Math.cos(dampedW * t); + } + } + } + double x0 = value - target; + double v0 = velocity; + double x, v; + if (z > 1) { + double eMinus = alternate ? alternateA : decayMinus; + double ePlus = alternate ? alternateB : decayPlus; + double b = (gMinus * x0 - v0) / (gMinus - gPlus); + double a = x0 - b; + x = a * eMinus + b * ePlus; + v = a * gMinus * eMinus + b * gPlus * ePlus; + } else if (z == 1) { + double a = x0; + double b = v0 + w * x0; + double e = alternate ? alternateA : decay; + x = (a + b * t) * e; + v = (a + b * t) * e * -w + b * e; + } else { + double wd = dampedW; + double c = x0; + double s = (z * w * x0 + v0) / wd; + double e = alternate ? alternateA : decay; + double sn = alternate ? alternateB : sin; + double cs = alternate ? alternateC : cos; + x = e * (c * cs + s * sn); + v = x * -w * z + e * (-wd * c * sn + wd * s * cs); + } + value = (float) (x + target); + velocity = (float) v; + if (isAtRest()) { + value = target; + velocity = 0f; + return true; + } + return false; + } +} diff --git a/hook/src/main/java/dev/colormotion/SpringDriver.java b/hook/src/main/java/dev/colormotion/SpringDriver.java new file mode 100644 index 00000000..33a394ec --- /dev/null +++ b/hook/src/main/java/dev/colormotion/SpringDriver.java @@ -0,0 +1,103 @@ +package dev.colormotion; + +import android.animation.ValueAnimator; +import android.view.Choreographer; + +/** Runs a {@link Spring} on the Choreographer, like DynamicAnimation.doAnimationFrame. */ +final class SpringDriver implements Choreographer.FrameCallback { + interface Listener { + void onUpdate(Spring spring); + + default void onEnd(Spring spring) {} + } + + final Spring spring = new Spring(); + private final Listener listener; + private boolean running; + private final FrameClock clock = new FrameClock(); + private Run callback; + + /** A cancelled callback may already be in Choreographer's current dispatch snapshot. */ + private static final class Run implements Choreographer.FrameCallback { + private final SpringDriver driver; + Run(SpringDriver driver) { this.driver = driver; } + @Override public void doFrame(long frameTimeNanos) { + if (driver.callback == this) driver.doFrame(frameTimeNanos); + } + } + + SpringDriver(Listener listener) { + this.listener = listener; + } + + boolean isRunning() { + return running; + } + + /** Same semantics as SpringAnimation.animateToFinalPosition: keeps current value and velocity. */ + void animateTo(float target) { + spring.target = target; + if (!running) { + if (spring.isAtRest() && spring.value == target) { + return; + } + running = true; + callback = new Run(this); + clock.reset(); + Choreographer.getInstance().postFrameCallback(callback); + } + } + + void cancel() { + if (running) { + running = false; + Choreographer.getInstance().removeFrameCallback(callback); + callback = null; + clock.reset(); + } + } + + void snapTo(float v) { + cancel(); + spring.snapTo(v); + listener.onUpdate(spring); + } + + @Override + public void doFrame(long frameTimeNanos) { + if (!running) { + return; + } + if (!clock.isStarted()) { + clock.start(frameTimeNanos); + Choreographer.getInstance().postFrameCallback(callback); + return; + } + float scale = ValueAnimator.getDurationScale(); + long dtMs = clock.advance(frameTimeNanos, scale); + boolean done; + if (scale == 0f) { + spring.snapTo(spring.target); + done = true; + } else { + done = spring.step(dtMs); + } + Run currentCallback = callback; + float completedTarget = spring.target; + listener.onUpdate(spring); + // The update may fail open, cancel, or start a fresh run. That run owns its + // already queued callback and timestamp; this frame must not repost or end it. + if (!running || callback != currentCallback) return; + if (done && Float.floatToIntBits(spring.target) != Float.floatToIntBits(completedTarget)) { + done = false; // A settlement listener can retarget the still-running spring. + } + if (done) { + running = false; + callback = null; + clock.reset(); + listener.onEnd(spring); + } else { + Choreographer.getInstance().postFrameCallback(callback); + } + } +} diff --git a/hook/src/main/java/dev/colormotion/TraversalOrder.java b/hook/src/main/java/dev/colormotion/TraversalOrder.java new file mode 100644 index 00000000..ab97eff2 --- /dev/null +++ b/hook/src/main/java/dev/colormotion/TraversalOrder.java @@ -0,0 +1,91 @@ +package dev.colormotion; + +import android.view.Choreographer; +import android.view.View; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import de.robv.android.xposed.XposedBridge; + +/** + * Draws the notification shade window last within a motion frame. + * + * Every SystemUI window shares one RenderThread, and each window's draw blocks the UI thread + * until RenderThread can sync it. The shade's frame takes several milliseconds there. While + * the shade opens, Samsung also fades the status bar icons, and that small window was drawn + * after the shade: the UI thread waited for the whole shade frame before it could finish. + * Moving the shade's already scheduled traversal to the end of the traversal queue lets the + * small windows sync first. The same draws happen in the same vsync; only their order changes. + */ +final class TraversalOrder { + private static final int CALLBACK_INSETS_ANIMATION = 2, CALLBACK_TRAVERSAL = 3; + private final Method post, remove, viewRoot; + private final Field scheduled, runnable, choreographer; + private final Runnable reorder = this::reorder; + private Runnable pending; + private final Runnable deferred = () -> { + Runnable task = pending; + pending = null; + if (task != null) task.run(); + }; + private View host; + private boolean queued, disabled; + + private TraversalOrder() throws ReflectiveOperationException { + post = Choreographer.class.getMethod("postCallback", int.class, Runnable.class, Object.class); + remove = Choreographer.class.getMethod("removeCallbacks", int.class, Runnable.class, Object.class); + viewRoot = View.class.getMethod("getViewRootImpl"); + Class root = viewRoot.getReturnType(); + scheduled = root.getDeclaredField("mTraversalScheduled"); + runnable = root.getDeclaredField("mTraversalRunnable"); + choreographer = root.getDeclaredField("mChoreographer"); + if (scheduled.getType() != boolean.class || !Runnable.class.isAssignableFrom(runnable.getType()) + || choreographer.getType() != Choreographer.class) throw new NoSuchFieldException("ViewRootImpl ABI"); + for (Field f : new Field[] {scheduled, runnable, choreographer}) f.setAccessible(true); + for (Method m : new Method[] {post, remove, viewRoot}) m.setAccessible(true); + } + + static TraversalOrder create() { + try { return new TraversalOrder(); } + catch (Throwable unavailable) { + XposedBridge.log(Entry.TAG + ": traversal ordering unavailable: " + unavailable); + return null; + } + } + + /** Call from a frame's animation phase; runs after all animation callbacks of that frame. */ + void drawLast(View window) { + if (disabled || queued || window == null) return; + try { + post.invoke(Choreographer.getInstance(), CALLBACK_INSETS_ANIMATION, reorder, null); + host = window; + queued = true; + } catch (Throwable failure) { disable(failure); } + } + + private void reorder() { + queued = false; + View window = host; + host = null; + if (disabled || window == null) return; + try { + Object root = viewRoot.invoke(window); + if (root == null || !scheduled.getBoolean(root)) return; + Object task = runnable.get(root); + Object owner = choreographer.get(root); + if (task == null || owner == null) return; + // Post first: if removal then fails, both run and ViewRootImpl ignores the second + // (doTraversal checks mTraversalScheduled). A traversal can never be lost. + pending = (Runnable) task; + post.invoke(owner, CALLBACK_TRAVERSAL, deferred, null); + remove.invoke(owner, CALLBACK_TRAVERSAL, task, null); + } catch (Throwable failure) { disable(failure); } + } + + private void disable(Throwable failure) { + disabled = true; + host = null; + XposedBridge.log(Entry.TAG + ": traversal ordering disabled: " + failure); + } +} diff --git a/hook/src/main/java/io/github/soclear/oneuix/hook/Main.kt b/hook/src/main/java/io/github/soclear/oneuix/hook/Main.kt index 48bc511d..9dc3f913 100644 --- a/hook/src/main/java/io/github/soclear/oneuix/hook/Main.kt +++ b/hook/src/main/java/io/github/soclear/oneuix/hook/Main.kt @@ -22,6 +22,8 @@ class Main : XposedModule() { override fun onModuleLoaded(param: XposedModuleInterface.ModuleLoadedParam) { processName = param.processName + // ColorMotion's legacy-API layer logs and hooks through this module instance. + de.robv.android.xposed.XposedBridge.init(this) } override fun onPackageReady(param: XposedModuleInterface.PackageReadyParam) = with(param) { @@ -445,6 +447,10 @@ class Main : XposedModule() { QS.disableHighBrightnessDialog() } + if (preference.systemUI.qs.colorMotionAnimation) { + QS.colorMotionAnimation() + } + if (preference.systemUI.qs.addBrightnessProgressToQsBar) { QS.addBrightnessProgressToQsBar() } diff --git a/hook/src/main/java/io/github/soclear/oneuix/hook/systemui/QS.kt b/hook/src/main/java/io/github/soclear/oneuix/hook/systemui/QS.kt index 50ebe7a4..143a522c 100644 --- a/hook/src/main/java/io/github/soclear/oneuix/hook/systemui/QS.kt +++ b/hook/src/main/java/io/github/soclear/oneuix/hook/systemui/QS.kt @@ -786,6 +786,14 @@ object QS { } } + // Panel animation ported from ColorMotion (https://github.com/juccul/ColorMotion). + context(xposedModule: XposedModule) + fun colorMotionAnimation() = afterAttachTry( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && ONE_UI_VERSION >= 80500 + ) { + dev.colormotion.Entry.install(classLoader) + } + @SuppressLint("DiscouragedPrivateApi") context(xposedModule: XposedModule) fun disableHighBrightnessDialog() = afterAttachTry { diff --git a/licenses/ColorMotion-GPL-3.0.txt b/licenses/ColorMotion-GPL-3.0.txt new file mode 100644 index 00000000..53d1f3d0 --- /dev/null +++ b/licenses/ColorMotion-GPL-3.0.txt @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/settings.gradle.kts b/settings.gradle.kts index 682580d6..4a9596a0 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -27,3 +27,5 @@ include(":app") include(":common") include(":hook") include(":stub") +include(":cm-native-api") +include(":cm-native-bridge")