diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c20d209 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +# Release credentials come from Vault via ./scripts/release-dev.sh. +# Never store GITEA_TOKEN in this file or .env. +# Optional environment override for tests or another Gitea repository: +# GITEA_API_URL=https://git.molberg.cloud/api/v1/repos/alex/mg-utility diff --git a/.gitignore b/.gitignore index 861b9a6..ae8ee86 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,14 @@ # Generated Android build output /build/ +telemetry-service/data/ +telemetry-service/data/*.sqlite* # Local signing material *.keystore *.jks *.idsig -# In-progress WIP that isn't part of any current feature branch -/src/cloud/molberg/mgutility/SetupWizardActivity.java +# Local release credentials +.env +.env.* +!.env.example diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..64c9421 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,31 @@ +# MG Utility release workflow + +When Zeb asks to **release a new Dev build**, run this from the repository: + +```bash +./scripts/release-dev.sh +``` + +This one-command Vault-backed workflow unlocks Bitwarden through the configured +Vault helper, reads the Gitea personal access token from the configured Vault +item, invokes the existing `scripts/release.sh` version/build/publish flow, and +verifies the published Dev APK by downloading it and comparing its SHA-256 with +the release metadata and local artifact. It also checks signature schemes, +manifest metadata, and ZIP integrity. Do not commit or push source changes. + +For a calculation-only authenticated preview, use +`./scripts/release-dev.sh --dry-run`. This obtains the token from Vault and +uses the live release list; never rely on an unauthenticated dry-run for version +allocation. + +Never put the Gitea token in `.env`, source, shell arguments, or logs. Defaults +use `/root/.openclaw/workspace/scripts/vault.sh` and the configured Gitea Vault +item ID in the wrapper. Override `VAULT_HELPER` or `GITEA_VAULT_ITEM_ID` only +when those locations change. If Vault, signing keystore, SDK, or network access +is unavailable, stop and report the actual blocker; do not bypass checks. + +Stable releases are distinct and require explicit user intent; never use +`--stable` for a Dev request. Preserve dirty source changes: the release +process builds the current checkout and does not clean or commit it. After +publishing, report the generated version, release tag, artifact path, checksum, +and actual verification output. diff --git a/AndroidManifest.xml b/AndroidManifest.xml index ea994fe..f1e8370 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,6 +1,12 @@ + + + + + + @@ -30,8 +36,9 @@ + - + @@ -48,20 +55,35 @@ + + + + + + + + + + + + @@ -91,5 +113,15 @@ android:exported="true" android:readPermission="android.permission.DUMP" android:grantUriPermissions="false" /> + + diff --git a/README.md b/README.md index f2d25be..ff859a3 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ The app is designed to run across MG vehicles by detecting available services an - [Permissions and privacy](#permissions-and-privacy) - [Read-only vehicle data provider](#read-only-vehicle-data-provider) - [Development and testing](#development-and-testing) +- [Plugin SDK and marketplace](#plugin-sdk-and-marketplace) - [Troubleshooting](#troubleshooting) - [The dashboard shows connecting or unavailable vehicle values](#the-dashboard-shows-connecting-or-unavailable-vehicle-values) - [Trip tracking does not start after reboot or sleep](#trip-tracking-does-not-start-after-reboot-or-sleep) @@ -66,6 +67,7 @@ The app does not require an internet connection for its core dashboard or local - Automatic daily screen-brightness schedule with smooth fade-in/fade-out (see Settings → Appearance → Screen brightness). - Swipe-up app drawer populated from the user's pinned applications. - Swipe-down control panel with configurable quick controls, sliders, toggles, and shortcuts. +- Quick controls include automatic brightness, Liquid Sound Balance, adaptive audio leveling, the official SAIC launcher, Software Update, and Vehicle Settings. Hold a toggle to open its settings. Existing custom layouts are preserved; add controls from **Settings → Appearance → Configure control panel**, or restore defaults to show the expanded layout. - Physical key remapping for supported foreground actions, with short, long, double, and repeat gestures. ### Vehicle data and energy @@ -192,7 +194,65 @@ From the repository root: ./build.sh ``` -The script compiles the Java sources and resources without Gradle, creates a signed APK, verifies its signature, and writes: +Every ordinary build is a local Dev-channel build. It uses the stable base version +with a `.0` suffix unless a release script supplies an explicit version: + +```bash +./build.sh +``` + +Dev releases use the Vault-backed wrapper, which supplies `GITEA_TOKEN` only +through the environment and verifies the downloaded release artifact: + +```bash +./scripts/release-dev.sh # next Dev release, including verification +./scripts/release-dev.sh --dry-run # authenticated version calculation only +``` + +Never store the token in `.env`, source, command arguments, or logs. Stable +releases require explicit intent and use `scripts/release.sh --stable` with +credentials supplied securely through the environment. + +Stable releases use `X.Y.Z`. Dev releases use `X.Y.Z.N`, where `N` increments +from the latest stable release. `--stable` increments the patch component and +publishes both `X.Y.Z` and its first `X.Y.Z.1` Dev build. Android `versionCode` +is assigned automatically above every existing release so channel switching +never attempts an Android downgrade. The publisher creates a Gitea Release with +the signed `MG-Utility.apk` and a machine-readable JSON release body containing +the channel, branch, versionCode, versionName, and SHA-256 checksum. Dev +releases are marked pre-release; Stable releases are normal releases. + +When the Dev channel has no newer Dev build but a newer Stable release exists, +the app presents that stable artifact as the equivalent Dev version `X.Y.Z.0`. +The APK is byte-for-byte the Stable artifact; `.0` is only the Dev-channel +presentation used to make the transition explicit. + +The app reads releases from +`https://git.molberg.cloud/api/v1/repos/alex/mg-utility` and only accepts HTTPS +APK assets from `git.molberg.cloud` whose package name, version code, checksum, +and signing certificate match the installed app. Keep `.env`, `GITEA_TOKEN`, and +all signing material out of the repository. + +### In-app updates + +Open **Settings → Config → Software updates**. The page displays the installed +version and its embedded channel/branch, lets the user choose **Dev** or +**Stable**, and provides an immediate check/download/install action. Downloads +are stored in app-private storage until verified. Android still displays its +required final package-install confirmation (and the one-time “install unknown +apps” permission on Android 8+). + +**Notify on updates** is enabled by default. When enabled, MG Utility schedules +a network-aware check approximately every six hours and repairs the schedule +after boot or app replacement. A short, clickable notification opens the update +page; disabling the toggle cancels the scheduled check. + +The update page also lists the current build, newer releases, and up to five +previous releases for the selected channel. Selecting an older release requires +confirmation with a warning that configuration or other app-data changes may +make features incompatible after downgrading. + +The script compiles the Java sources and resources without Gradle, creates a signed APK, and writes: ```text build/MG-Utility.apk @@ -287,6 +347,22 @@ Unknown or unsupported profiles remain read-only by design. Do not force a setti └── README.md # This document ``` +## Plugin SDK and marketplace + +MG Utility now includes a Java 8 plugin SDK and a built-in marketplace foundation. Plugins are +separate APKs declaring `assets/mg-plugin.json`, implementing the SDK `Plugin` lifecycle, and +contributing dashboard tiles, settings pages, key actions, or background work through scoped host +registries. Plugin preferences are isolated by plugin ID and repository APKs must be HTTPS downloads +with a matching SHA-256 checksum before installation. + +Open **Settings → Config → Plugin marketplace** to add repository index URLs. A reserved official +repository entry is shown as “coming soon”; the remote official repository itself has not been +created. Existing speed-reactive audio, soundboard, and key-remapping features remain built into +the app for now. Their extraction into plugins will happen after the host contracts are validated. + +See [docs/PLUGIN_SDK.md](docs/PLUGIN_SDK.md) for the manifest format, lifecycle guidance, capability +allow-list, repository schema, and a minimal plugin example. + ## Status and limitations MG Utility is a vehicle-specific Android integration project intended to be adaptable across SAIC-based MG cars. Its generic UI, local storage, launcher behaviour, and fallback paths are designed for broad use; live vehicle data and vehicle settings depend on private OEM services and the specific MG trim/firmware. diff --git a/assets/sherpa-en/decoder.int8.onnx b/assets/sherpa-en/decoder.int8.onnx new file mode 100644 index 0000000..8519f85 Binary files /dev/null and b/assets/sherpa-en/decoder.int8.onnx differ diff --git a/assets/sherpa-en/encoder.int8.onnx b/assets/sherpa-en/encoder.int8.onnx new file mode 100644 index 0000000..a514395 Binary files /dev/null and b/assets/sherpa-en/encoder.int8.onnx differ diff --git a/assets/sherpa-en/joiner.int8.onnx b/assets/sherpa-en/joiner.int8.onnx new file mode 100644 index 0000000..355e3b3 Binary files /dev/null and b/assets/sherpa-en/joiner.int8.onnx differ diff --git a/assets/sherpa-en/tokens.txt b/assets/sherpa-en/tokens.txt new file mode 100644 index 0000000..b4d1bf8 --- /dev/null +++ b/assets/sherpa-en/tokens.txt @@ -0,0 +1,502 @@ + 0 + 1 + 2 +S 3 +▁THE 4 +▁A 5 +T 6 +▁AND 7 +ED 8 +▁OF 9 +▁TO 10 +E 11 +D 12 +N 13 +ING 14 +▁IN 15 +Y 16 +M 17 +C 18 +▁I 19 +A 20 +P 21 +▁HE 22 +R 23 +O 24 +L 25 +RE 26 +I 27 +U 28 +ER 29 +▁IT 30 +LY 31 +▁THAT 32 +▁WAS 33 +▁ 34 +▁S 35 +AR 36 +▁BE 37 +F 38 +▁C 39 +IN 40 +B 41 +▁FOR 42 +OR 43 +LE 44 +' 45 +▁HIS 46 +▁YOU 47 +AL 48 +▁RE 49 +V 50 +▁B 51 +G 52 +RI 53 +▁E 54 +▁WITH 55 +▁T 56 +▁AS 57 +LL 58 +▁P 59 +▁HER 60 +ST 61 +▁HAD 62 +▁SO 63 +▁F 64 +W 65 +CE 66 +▁IS 67 +ND 68 +▁NOT 69 +TH 70 +▁BUT 71 +EN 72 +▁SHE 73 +▁ON 74 +VE 75 +ON 76 +SE 77 +▁DE 78 +UR 79 +▁G 80 +CH 81 +K 82 +TER 83 +▁AT 84 +IT 85 +▁ME 86 +RO 87 +NE 88 +RA 89 +ES 90 +IL 91 +NG 92 +IC 93 +▁NO 94 +▁HIM 95 +ENT 96 +IR 97 +▁WE 98 +H 99 +▁DO 100 +▁ALL 101 +▁HAVE 102 +LO 103 +▁BY 104 +▁MY 105 +▁MO 106 +▁THIS 107 +LA 108 +▁ST 109 +▁WHICH 110 +▁CON 111 +▁THEY 112 +CK 113 +TE 114 +▁SAID 115 +▁FROM 116 +▁GO 117 +▁WHO 118 +▁TH 119 +▁OR 120 +▁D 121 +▁W 122 +VER 123 +LI 124 +▁SE 125 +▁ONE 126 +▁CA 127 +▁AN 128 +▁LA 129 +▁WERE 130 +EL 131 +▁HA 132 +▁MAN 133 +▁FA 134 +▁EX 135 +AD 136 +▁SU 137 +RY 138 +▁MI 139 +AT 140 +▁BO 141 +▁WHEN 142 +AN 143 +THER 144 +PP 145 +ATION 146 +▁FI 147 +▁WOULD 148 +▁PRO 149 +OW 150 +ET 151 +▁O 152 +▁THERE 153 +▁HO 154 +ION 155 +▁WHAT 156 +▁FE 157 +▁PA 158 +US 159 +MENT 160 +▁MA 161 +UT 162 +▁OUT 163 +▁THEIR 164 +▁IF 165 +▁LI 166 +▁K 167 +▁WILL 168 +▁ARE 169 +ID 170 +▁RO 171 +DE 172 +TION 173 +▁WA 174 +PE 175 +▁UP 176 +▁SP 177 +▁PO 178 +IGHT 179 +▁UN 180 +RU 181 +▁LO 182 +AS 183 +OL 184 +▁LE 185 +▁BEEN 186 +▁SH 187 +▁RA 188 +▁SEE 189 +KE 190 +UL 191 +TED 192 +▁SA 193 +UN 194 +UND 195 +ANT 196 +▁NE 197 +IS 198 +▁THEM 199 +CI 200 +GE 201 +▁COULD 202 +▁DIS 203 +OM 204 +ISH 205 +HE 206 +EST 207 +▁SOME 208 +ENCE 209 +ITY 210 +IVE 211 +▁US 212 +▁MORE 213 +▁EN 214 +ARD 215 +ATE 216 +▁YOUR 217 +▁INTO 218 +▁KNOW 219 +▁CO 220 +ANCE 221 +▁TIME 222 +▁WI 223 +▁YE 224 +AGE 225 +▁NOW 226 +TI 227 +FF 228 +ABLE 229 +▁VERY 230 +▁LIKE 231 +AM 232 +HI 233 +Z 234 +▁OTHER 235 +▁THAN 236 +▁LITTLE 237 +▁DID 238 +▁LOOK 239 +TY 240 +ERS 241 +▁CAN 242 +▁CHA 243 +▁AR 244 +X 245 +FUL 246 +UGH 247 +▁BA 248 +▁DAY 249 +▁ABOUT 250 +TEN 251 +IM 252 +▁ANY 253 +▁PRE 254 +▁OVER 255 +IES 256 +NESS 257 +ME 258 +BLE 259 +▁M 260 +ROW 261 +▁HAS 262 +▁GREAT 263 +▁VI 264 +TA 265 +▁AFTER 266 +PER 267 +▁AGAIN 268 +HO 269 +SH 270 +▁UPON 271 +▁DI 272 +▁HAND 273 +▁COM 274 +IST 275 +TURE 276 +▁STA 277 +▁THEN 278 +▁SHOULD 279 +▁GA 280 +OUS 281 +OUR 282 +▁WELL 283 +▁ONLY 284 +MAN 285 +▁GOOD 286 +▁TWO 287 +▁MAR 288 +▁SAY 289 +▁HU 290 +TING 291 +▁OUR 292 +RESS 293 +▁DOWN 294 +IOUS 295 +▁BEFORE 296 +▁DA 297 +▁NA 298 +QUI 299 +▁MADE 300 +▁EVERY 301 +▁OLD 302 +▁EVEN 303 +IG 304 +▁COME 305 +▁GRA 306 +▁RI 307 +▁LONG 308 +OT 309 +SIDE 310 +WARD 311 +▁FO 312 +▁WHERE 313 +MO 314 +LESS 315 +▁SC 316 +▁MUST 317 +▁NEVER 318 +▁HOW 319 +▁CAME 320 +▁SUCH 321 +▁RU 322 +▁TAKE 323 +▁WO 324 +▁CAR 325 +UM 326 +AK 327 +▁THINK 328 +▁MUCH 329 +▁MISTER 330 +▁MAY 331 +▁JO 332 +▁WAY 333 +▁COMP 334 +▁THOUGHT 335 +▁STO 336 +▁MEN 337 +▁BACK 338 +▁DON 339 +J 340 +▁LET 341 +▁TRA 342 +▁FIRST 343 +▁JUST 344 +▁VA 345 +▁OWN 346 +▁PLA 347 +▁MAKE 348 +ATED 349 +▁HIMSELF 350 +▁WENT 351 +▁PI 352 +GG 353 +RING 354 +▁DU 355 +▁MIGHT 356 +▁PART 357 +▁GIVE 358 +▁IMP 359 +▁BU 360 +▁PER 361 +▁PLACE 362 +▁HOUSE 363 +▁THROUGH 364 +IAN 365 +▁SW 366 +▁UNDER 367 +QUE 368 +▁AWAY 369 +▁LOVE 370 +QUA 371 +▁LIFE 372 +▁GET 373 +▁WITHOUT 374 +▁PASS 375 +▁TURN 376 +IGN 377 +▁HEAD 378 +▁MOST 379 +▁THOSE 380 +▁SHALL 381 +▁EYES 382 +▁COL 383 +▁STILL 384 +▁NIGHT 385 +▁NOTHING 386 +ITION 387 +HA 388 +▁TELL 389 +▁WORK 390 +▁LAST 391 +▁NEW 392 +▁FACE 393 +▁HI 394 +▁WORD 395 +▁FOUND 396 +▁COUNT 397 +▁OB 398 +▁WHILE 399 +▁SHA 400 +▁MEAN 401 +▁SAW 402 +▁PEOPLE 403 +▁FRIEND 404 +▁THREE 405 +▁ROOM 406 +▁SAME 407 +▁THOUGH 408 +▁RIGHT 409 +▁CHILD 410 +▁FATHER 411 +▁ANOTHER 412 +▁HEART 413 +▁WANT 414 +▁TOOK 415 +OOK 416 +▁LIGHT 417 +▁MISSUS 418 +▁OPEN 419 +▁JU 420 +▁ASKED 421 +PORT 422 +▁LEFT 423 +▁JA 424 +▁WORLD 425 +▁HOME 426 +▁WHY 427 +▁ALWAYS 428 +▁ANSWER 429 +▁SEEMED 430 +▁SOMETHING 431 +▁GIRL 432 +▁BECAUSE 433 +▁NAME 434 +▁TOLD 435 +▁NI 436 +▁HIGH 437 +IZE 438 +▁WOMAN 439 +▁FOLLOW 440 +▁RETURN 441 +▁KNEW 442 +▁EACH 443 +▁KIND 444 +▁JE 445 +▁ACT 446 +▁LU 447 +▁CERTAIN 448 +▁YEARS 449 +▁QUITE 450 +▁APPEAR 451 +▁BETTER 452 +▁HALF 453 +▁PRESENT 454 +▁PRINCE 455 +SHIP 456 +▁ALSO 457 +▁BEGAN 458 +▁HAVING 459 +▁ENOUGH 460 +▁PERSON 461 +▁LADY 462 +▁WHITE 463 +▁COURSE 464 +▁VOICE 465 +▁SPEAK 466 +▁POWER 467 +▁MORNING 468 +▁BETWEEN 469 +▁AMONG 470 +▁KEEP 471 +▁WALK 472 +▁MATTER 473 +▁TEA 474 +▁BELIEVE 475 +▁SMALL 476 +▁TALK 477 +▁FELT 478 +▁HORSE 479 +▁MYSELF 480 +▁SIX 481 +▁HOWEVER 482 +▁FULL 483 +▁HERSELF 484 +▁POINT 485 +▁STOOD 486 +▁HUNDRED 487 +▁ALMOST 488 +▁SINCE 489 +▁LARGE 490 +▁LEAVE 491 +▁PERHAPS 492 +▁DARK 493 +▁SUDDEN 494 +▁REPLIED 495 +▁ANYTHING 496 +▁WONDER 497 +▁UNTIL 498 +Q 499 +#0 500 +#1 501 diff --git a/build.sh b/build.sh index 0666850..925b356 100755 --- a/build.sh +++ b/build.sh @@ -1,13 +1,36 @@ #!/bin/sh # Build a signed APK without Gradle. Requires Android SDK build-tools 34+ and a JDK. +# Release numbering and publishing are handled by scripts/release.sh. set -eu ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +CHANNEL=${1:-dev} +if [ "$CHANNEL" != "dev" ] && [ "$CHANNEL" != "stable" ]; then + echo "Usage: ./build.sh [dev|stable]" >&2 + exit 2 +fi SDK=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/opt/android-sdk}} TOOLS=$(find "$SDK/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -n 1) ANDROID_JAR=$(find "$SDK/platforms" -mindepth 2 -maxdepth 2 -name android.jar -type f | sort -V | tail -n 1) OUT="$ROOT/build" APK="$OUT/MG-Utility.apk" KEYSTORE="$ROOT/mg-utility.keystore" +BASE_VERSION=$(sed -n 's/.*android:versionName="\([^"]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1) +BASE_CODE=$(sed -n 's/.*android:versionCode="\([0-9]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1) +BRANCH=${UPDATE_BRANCH:-$(git -C "$ROOT" branch --show-current 2>/dev/null || true)} +[ -n "$BRANCH" ] || BRANCH=main +if [ "$CHANNEL" = "stable" ] && [ -z "${UPDATE_BRANCH:-}" ]; then BRANCH=main; fi +if [ "$CHANNEL" = "dev" ]; then + BUILD_VERSION_CODE=${UPDATE_VERSION_CODE:-$(date -u +%s)} + BUILD_VERSION_NAME=${UPDATE_VERSION_NAME:-"${BASE_VERSION}.0"} +else + BUILD_VERSION_CODE=${UPDATE_VERSION_CODE:-$BASE_CODE} + BUILD_VERSION_NAME=${UPDATE_VERSION_NAME:-$BASE_VERSION} +fi + +case "$BUILD_VERSION_CODE" in + *[!0-9]*|'') echo "versionCode must be an integer" >&2; exit 2 ;; +esac +[ "$BUILD_VERSION_CODE" -le 2147483647 ] || { echo "versionCode must fit Android's signed 32-bit limit" >&2; exit 2; } if [ -z "$TOOLS" ] || [ -z "$ANDROID_JAR" ]; then echo "Android SDK build-tools and a platform are required (set ANDROID_HOME)." >&2 @@ -15,15 +38,33 @@ if [ -z "$TOOLS" ] || [ -z "$ANDROID_JAR" ]; then fi rm -rf "$OUT" -mkdir -p "$OUT/classes" "$OUT/dex" "$OUT/generated" +mkdir -p "$OUT/classes" "$OUT/dex" "$OUT/generated" "$OUT/assets" "$OUT/lib/arm64-v8a" "$OUT/vendor/sherpa" +AAR="$ROOT/vendor/sherpa-onnx/sherpa-onnx-1.13.8.aar" +KOTLIN_STDLIB="$ROOT/vendor/sherpa-onnx/kotlin-stdlib-2.0.21.jar" +if [ ! -f "$AAR" ] || [ ! -f "$KOTLIN_STDLIB" ]; then + echo "Sherpa-onnx vendor AAR and Kotlin stdlib are required." >&2 + exit 1 +fi +unzip -q -o "$AAR" 'classes.jar' 'jni/arm64-v8a/*.so' -d "$OUT/vendor/sherpa" +cp "$OUT/vendor/sherpa/jni/arm64-v8a/"*.so "$OUT/lib/arm64-v8a/" +rm -rf "$OUT/vendor/sherpa/jni" +cp -R "$ROOT/assets/sherpa-en" "$OUT/assets/" +mkdir -p "$OUT/sherpa-classes" +(cd "$OUT/sherpa-classes" && unzip -q -o "$OUT/vendor/sherpa/classes.jar") +printf '{"schema":1,"channel":"%s","branch":"%s","versionCode":%s,"versionName":"%s"}\n' \ + "$CHANNEL" "$BRANCH" "$BUILD_VERSION_CODE" "$BUILD_VERSION_NAME" > "$OUT/assets/mg-update-build.json" "$TOOLS/aapt2" compile --dir "$ROOT/res" -o "$OUT/res.zip" "$TOOLS/aapt2" link -I "$ANDROID_JAR" --manifest "$ROOT/AndroidManifest.xml" \ - --java "$OUT/generated" -o "$OUT/resources.apk" "$OUT/res.zip" -javac -source 8 -target 8 -bootclasspath "$ANDROID_JAR" -d "$OUT/classes" \ + --replace-version --version-code "$BUILD_VERSION_CODE" --version-name "$BUILD_VERSION_NAME" \ + -A "$OUT/assets" --java "$OUT/generated" -o "$OUT/resources.apk" "$OUT/res.zip" +javac -source 8 -target 8 -bootclasspath "$ANDROID_JAR" \ + -cp "$OUT/sherpa-classes:$KOTLIN_STDLIB" -d "$OUT/classes" \ $(find "$ROOT/src" "$OUT/generated" -name '*.java') -"$TOOLS/d8" --lib "$ANDROID_JAR" --output "$OUT/dex" $(find "$OUT/classes" -name '*.class') +"$TOOLS/d8" --lib "$ANDROID_JAR" --output "$OUT/dex" \ + $(find "$OUT/classes" "$OUT/sherpa-classes" -name '*.class') "$KOTLIN_STDLIB" cp "$OUT/resources.apk" "$OUT/MG-Utility-unsigned.apk" (cd "$OUT/dex" && jar uf "$OUT/MG-Utility-unsigned.apk" classes.dex) +(cd "$OUT" && zip -q -r "$OUT/MG-Utility-unsigned.apk" lib) "$TOOLS/zipalign" -f 4 "$OUT/MG-Utility-unsigned.apk" "$APK" rm -f "$APK.idsig" "$TOOLS/apksigner" sign \ diff --git a/docs/HERMES_AGENT.md b/docs/HERMES_AGENT.md new file mode 100644 index 0000000..8334bcd --- /dev/null +++ b/docs/HERMES_AGENT.md @@ -0,0 +1,130 @@ +# Hermes agent assistant + +MG Utility connects directly to Hermes Agent's native API server. It does not +use webhook routes or the dashboard's browser/OAuth session. + +The native API is the appropriate car integration because it exposes durable +sessions, agent tools, message history, streaming, runs, steering, approvals, +models, skills, and toolsets through an authenticated HTTP API. The dashboard +uses a browser-oriented JSON-RPC WebSocket with short-lived authentication +tickets and does not add agent capabilities needed by this feature. + +## Running Hermes instance + +The development Hermes instance is configured as: + +```text +API server: http://10.0.0.74:18793 +API key: API_SERVER_KEY in ~/.hermes/.env +Dashboard: https://gateway.bonzi.cc +``` + +The dashboard is useful for inspecting the resulting `MG car voice assistant` +session, but the app talks to port `18793` directly. The car must be able to +reach `10.0.0.74` on the local network. Use an HTTPS reverse proxy or VPN when +connecting across an untrusted network. + +In MG Utility, open **Settings → Misc → Hermes agent assistant**, enter the API +server address and `API_SERVER_KEY`, enable the integration, and select **Test +connection**. The key is encrypted at rest using Android Keystore and is not +included in MG Utility settings exports. + +## Conversation behavior + +The first prompt creates a persistent Hermes session with an in-car system +instruction. Subsequent steering-wheel prompts reuse that session, giving +Hermes conversation history and follow-up context. Select **New conversation** +in settings to rotate to a fresh session. + +The car session is scoped to the instance's verified Anthropic +`claude-haiku-4-5-20251001` route for low latency. This does not change Hermes' +global model or sessions used by the dashboard and other integrations. + +Every turn also tells Hermes that the user is speaking hands-free through an MG +car head unit and asks for concise, driving-safe responses. Hermes' returned +answer is displayed on the listening screen. + +## Steering-wheel binding + +Open **Settings → Misc → Key remapping**, capture a steering-wheel key, select +**Hermes voice assistant**, and save. MG Utility automatically stores that +action as the **Push to talk (press / release)** gesture. + +For use over navigation, media, or other apps, select **Global key access** on +the key-remapping page (or **Enable global steering-wheel access** in Hermes +settings). In Android Accessibility, enable **MG Utility global keys**. Return +to key remapping and check that it says **GLOBAL KEYS ACTIVE**. This user-granted +service captures both key down and key up without requiring MG Utility to be +in the foreground. It does not request screen-content access. If another +key-filtering accessibility service owns the button, disable that conflicting +service before testing. Keys intercepted by the car firmware before Android +receives them cannot be remapped by this app. + +Grant microphone access in Hermes settings before using the key. Hold it until +the popup shows **RECORDING** or **LISTENING**, speak, then release. Releasing +before the screen/microphone is ready asks you to try again rather than sending +an empty prompt. Existing Hermes mappings with old short/long gestures are +automatically interpreted as push-to-talk. + +Hermes opens in its own temporary task, so closing it returns to the previously +visible app rather than bringing the MG dashboard forward. Each new press opens +a fresh voice turn, including while an earlier reply is still displayed. +Repeated down events do not restart recording; cancelled key sequences do not +send a prompt. Turning off the accessibility service cancels any held voice turn. + +Pressing the key opens the listening screen. Android's speech recognizer shows +partial text live; releasing the key finalizes the transcript and sends it to +the persistent Hermes session. Microphone permission must be granted. + +### Head units without Android speech recognition + +If the head unit has no Android recognition service, configure a separate +**Transcription endpoint**, **Transcription API key**, and **Transcription model** +in Hermes settings. The endpoint must accept an OpenAI-compatible multipart +`POST` containing `file` (AAC audio in an M4A container) and `model`, and return +JSON such as `{"text":"your spoken request"}`. Enter the full endpoint URL, +for example `https://your-speech-server/v1/audio/transcriptions`, and the model +name supported by that server. The key can be blank for a trusted local server +that does not require authentication. It is stored encrypted, separately from +the Hermes key. Do not enter the Hermes chat URL or API key in these fields: +this requires a speech-to-text server, not the Hermes session API. + +When a transcription endpoint is configured, MG Utility uses direct microphone +recording instead of Android recognition. Hold the steering-wheel button to +record, then release to upload, transcribe, and send the text to Hermes. Live +partial text is not available in this mode. Recording is capped at 60 seconds; +reaching the limit submits automatically. Temporary audio is deleted after +upload completes or fails, or when an unfinished recording is cancelled by +closing the activity. Use HTTPS or a trusted private network: the configured +speech server receives the recording. No speech server is provisioned by the app. + +Leave the endpoint blank to keep using an installed Android recognition service. +Microphone permission alone does not install such a service. + +If `SpeechRecognizer` is unavailable, MG Utility now tries Android's +`ACTION_RECOGNIZE_SPEECH` activity instead. This lets head units that expose +their OEM/Google voice UI as a normal Android voice-input activity work without +another API key. That activity owns the listening session, so the system voice +dialog determines when speech ends; releasing the steering-wheel key cannot +force-stop it. Speak normally, finish, and wait for the result to return to +Hermes. If Android reports that no activity handles the intent, the OEM and +Android Auto implementations are private integrations and cannot provide their +audio/transcript to an unrelated app. In that case no app-only code can reuse +them; installing/enabling a system recognition provider or using the optional +transcription endpoint is required. + +Validation: `sh tests/run_hermes_tests.sh` checks multipart upload, credential +separation, HTTP errors, and redirect rejection against a local test server. +Actual microphone capture and transcription must also be tested on the head unit. + +## Server verification + +The API follows the official Hermes API-server contract: + +```bash +curl -H "Authorization: Bearer $API_SERVER_KEY" \ + http://10.0.0.74:18793/v1/capabilities +``` + +MG Utility requires the server to advertise `features.session_chat: true`, then +uses `POST /api/sessions` and `POST /api/sessions/{id}/chat`. diff --git a/docs/LIQUID_SOUND_BALANCE.md b/docs/LIQUID_SOUND_BALANCE.md new file mode 100644 index 0000000..ee4cdbb --- /dev/null +++ b/docs/LIQUID_SOUND_BALANCE.md @@ -0,0 +1,35 @@ +# Liquid Sound Balance + +The OEM `ISmartSoundService.setSoundField(balance, fader)` takes **0 through 14 inclusive on both axes**, with **(7, 7) at dead center**. These are absolute positions, not signed offsets. Sending balance 0 selects the far left; negative positions are rejected. + +Verified against the locally extracted `SystemSettingsService_eh32_P.apk`: `com.saicmotor.service.systemsettings.binder.ISmartSoundBinder.setSoundField`, source lines 503–507, rejects either argument below 0 or above `0xe` (14). The service's reset settings code initializes both axes to 7 (source lines 1227–1229). The stock `SystemSettings_eh32_P.apk` `SoundFieldBalanceView` also marks index 7 as the center of its 15-position axes. + +## Resting point + +Set **Resting point X** (left/right) and **Resting point Y** (front/rear), then **Save & Apply**. Both support every OEM position from 0 to 14; existing installations default to (7, 7). Reset resting point to center resets both sliders; save to persist it. Motion is relative to this anchor and clips at the cabin edges. Stopping, steady straight driving, zero power, and disabling liquid mode return to the saved point, not necessarily the center. A failed restore is retried while the service runs. + +## Force-driven movement + +Horizontal sway no longer uses a timer or borrows the braking/acceleration amplitude. It reads `arcsoft.avm.mCurCarWheelAngle` and combines it with road speed. Acceleration pulls sound rearward, braking forward, and a turn pushes sound outward. Holding a steady turn holds an outward displacement; straightening up releases it. Turning the wheel while parked does not cause displacement. + +The lateral model is an approximation: `v² × tan(steeringDegrees / 15) / 2.7`, converted from m/s² to km/h/s for the shared threshold. The effective steering ratio (15) and wheelbase (2.7 m) are tuning assumptions, not a measured G-force sensor or a verified vehicle calibration. Speed excludes the dashboard's 1.03 display correction. Both axes use a damped spring with bounded integration steps; Bounce enables rebound, while off uses critical damping. Power limits movement to at most seven steps from the resting point, clipped to the OEM endpoints. + +The confirmed property range is **−520.0000 at right lock**, **0.0000 centered**, and **+520.0000 at left lock**. Positive steering therefore produces rightward audio displacement. **Reverse steering signal direction** remains available for firmware with the opposite convention, but should stay off for this property. Live steering status displays the angle or an unavailable reason; there is no fabricated oscillation fallback. + +## Steering integration evidence + +The locally extracted `360Camera_eh32_P.apk` `CarManager` also reads `arcsoft.avm.mCurCarWheelAngle` with `android.os.SystemProperties.get`, followed by `Float.parseFloat`. The app uses the same system-property reader via reflection, without a proprietary SDK dependency, camera activation, sensor subscription, or additional car permissions. + +Missing, malformed, non-finite, or out-of-range values lock X to the saved anchor. The property does **not** expose a timestamp, so an unchanged valid value cannot be distinguished from a stale value. Verify that the vehicle keeps it updated outside the camera screen. The integration deliberately does not substitute a guessed timer animation when the signal is missing. + +## Live visualization + +The settings screen polls OEM balance/fader readback on a background thread every 200 ms. The red dot is the reported sound-field position; the gold crosshair is the saved anchor. The dot is omitted when readback is unavailable rather than presenting the requested position as confirmed. This shows the mixer's position, not measured acoustic output. Numeric X/Y, media-volume step, steering, and distance-boost target accompany the view. Monitoring stops when the screen is paused. + +## Distance volume compensation + +The toggle defaults off; the slider sets a maximum **+0–100%** multiplier of the driver's media-volume setting (default +25%). Compensation uses the **observed OEM position**, not an unconfirmed command. Distance is `hypot(X − anchorX, Y − anchorY) / 7`, capped at 1. Front, rear, left, right, and diagonal movement all count. Seven steps or more receives the selected maximum; the anchor receives no boost. Unknown readback receives no boost. + +Compensation and adaptive speed leveling share one volume controller and base-volume reference: `base × speed multiplier × distance multiplier`, capped to the actual stream range. A muted base stays muted. Manual volume changes remain authoritative. Adjustments ramp one hardware notch at a time (at least 150 ms apart while distance compensation is active), so returning to normal is smooth rather than instantaneous. Disabling compensation removes its multiplier; speed leveling remains active if enabled. Failed restoration writes retain the reference for retry. Percentage refers to hardware volume steps, not measured decibels or loudness. + +Run `sh tests/run_tests.sh` for anchor, endpoint, turn direction, speed scaling, independent-axis, lost-signal, settling, and volume-curve coverage. Build with `./build.sh`. Property accessibility/update behavior and actual speaker behavior still require an in-car check. Configure settings while parked; have a passenger assess motion during a drive. diff --git a/docs/PLUGIN_SDK.md b/docs/PLUGIN_SDK.md new file mode 100644 index 0000000..ef5e480 --- /dev/null +++ b/docs/PLUGIN_SDK.md @@ -0,0 +1,178 @@ +# MG Utility plugin SDK + +The SDK lets an independently packaged plugin contribute pages, dashboard +tiles, background work, audio, and key actions without coupling plugin code to +MG Utility's Android activities. The API is Java 8 and Android API 28 +compatible. SDK sources live in `src/cloud/molberg/mgutility/sdk`; the host +implementation is under `src/cloud/molberg/mgutility/plugin`. + +## Minimal plugin + +```java +package com.example.speed; + +import cloud.molberg.mgutility.sdk.Contribution; +import cloud.molberg.mgutility.sdk.Plugin; +import cloud.molberg.mgutility.sdk.PluginContext; + +public final class SpeedPlugin implements Plugin { + private PluginContext context; + + @Override public void onLoad(PluginContext context) { + this.context = context; + context.logger().info("Loaded"); + } + + @Override public void onEnable(PluginContext context) { + context.contributions().register(new Contribution( + "speed.tile", Contribution.Type.DASHBOARD_WIDGET, + "Speed", "Show current speed", "speed://dashboard")); + } + + @Override public void onDisable(PluginContext context) { + context.contributions().remove("speed.tile"); + } + + @Override public void onUnload(PluginContext context) { } +} +``` + +Lifecycle callbacks are idempotent from the host's perspective. Register +listeners/contributions in `onEnable` and remove them in `onDisable`; release +threads and players in `onUnload`. Exceptions are caught by the host and mark +the plugin as `FAILED`. + +## `mg-plugin.json` + +Place this file in the plugin APK's `assets/` directory: + +```json +{ + "schema": 1, + "id": "com.example.speed", + "name": "Speed display", + "versionName": "1.0.0", + "versionCode": 1, + "entryPoint": "com.example.speed.SpeedPlugin", + "sdkVersion": "1.0.0", + "publisher": "Example", + "description": "Displays vehicle speed on the dashboard.", + "capabilities": ["DASHBOARD", "VEHICLE_DATA_READ"], + "permissions": ["vehicle_data"] +} +``` + +`id` is a stable reverse-DNS-like identifier and must be unique. `entryPoint` +is the class implementing `Plugin`. `versionName` and `versionCode` identify a +release; `sdkVersion` is the SDK compatibility declaration. The parser accepts +the legacy aliases `version` and `entry` while new plugins should use the +explicit names above. Unknown manifest schema versions are rejected. + +Capabilities are an allow-list requested by the plugin. The host may grant a +smaller set (for example when a vehicle does not expose telemetry). Always +check `context.hasCapability(...)` before using a capability. Available values +are `DASHBOARD`, `SETTINGS`, `AUDIO_PLAYBACK`, `VEHICLE_DATA_READ`, +`KEY_REMAP`, `BACKGROUND_WORK`, `STORAGE`, `NETWORK`, and `NOTIFICATIONS`. + +## Contributions and hooks + +Use `ContributionRegistry` for UI or behaviour contributions. IDs are unique +within a plugin. `HookRegistry` provides named, opaque host events and is safe +to publish from a worker thread; listeners are invoked outside the registry's +lock. Keep payload handling defensive because hosts may add fields over time. + +`ScopedPreferences` is automatically namespaced by plugin ID. Never write to +the host's `mg_config` store directly. `runAsync` supplies a host-managed +executor; stop work when `onDisable` is called. + +### Standard hooks + +`HookRegistry` supports both custom string hooks and typed standard hooks. Typed hooks use +`PluginHook` plus an immutable `HookEvent`, so event names and common value accessors are +discoverable in the SDK and payloads can grow without breaking old plugins. The standard catalog is: + +| Area | Hooks | +|---|---| +| App/display | `APP_STARTED`, `APP_STOPPED`, `SCREEN_ON`, `SCREEN_OFF`, `DASHBOARD_REFRESH`, `THEME_CHANGED` | +| Vehicle | `VEHICLE_CONNECTED`, `VEHICLE_DISCONNECTED`, `VEHICLE_STATE`, `SPEED_CHANGED`, `SOC_CHANGED`, `DRIVE_MODE_CHANGED`, `REGENERATION_CHANGED`, `CHARGING_STATE_CHANGED` | +| Media/audio | `MEDIA_STATE_CHANGED`, `AUDIO_FFT`, `VOLUME_CHANGED` | +| Input | `KEY_EVENT` | +| Trips/arrival | `TRIP_STARTED`, `TRIP_UPDATED`, `TRIP_FINISHED`, `ARRIVAL_ENTERED`, `ARRIVAL_EXITED` | +| Plugins | `PLUGIN_ENABLED`, `PLUGIN_DISABLED` | + +Example typed subscription: + +```java +HookRegistry.TypedListener listener = new HookRegistry.TypedListener() { + @Override public void onEvent(PluginHook hook, HookEvent event) { + double speed = event.getDouble("speedKph", 0); + context.logger().debug("speed=" + speed); + } +}; +context.hooks().subscribe(PluginHook.SPEED_CHANGED, listener); +``` + +The host publishes events on its own threads; listeners must be quick and non-blocking. Use +`runAsync` for work. Unsubscribe in `onDisable`. Capability checks still apply: for example, +vehicle hooks require `VEHICLE_DATA_READ`, audio hooks require `AUDIO_PLAYBACK`, and key hooks +require `KEY_REMAP`. + +Host code publishes typed events through `PluginHostEvents.publish(HookEvent)`; this keeps event +production decoupled from plugin loading and allows vehicle services, media listeners, and trip +tracking to feed the same bus. + +## Building and testing + +The current repository intentionally has no Gradle dependency. Add the SDK +source files to a plugin module and compile with Java 8 against the Android SDK +(`android.jar`). The JVM contract tests can be run with: + +```sh +./tests/run_tests.sh +``` + +The test suite includes manifest schema/capability validation, semantic +version ranges, contribution registration, and hook subscribe/unsubscribe +behaviour. + +To produce a reusable SDK jar for a plugin project, run: + +```sh +./scripts/build-plugin-sdk.sh +``` + +The resulting `build/plugin-sdk/mg-utility-plugin-sdk.jar` contains only the +Android-free contract classes. Compile the Android host adapter against +`android.jar` when a plugin needs Android resources or activities. + +## Marketplace repository format + +The marketplace consumes a JSON index containing `schema` and a `plugins` +array. Each entry includes `id`, `version`, `apkUrl`, `sha256`, and optional +`sdkRange`, `entry`, `publisher`, and description fields. APK URLs must use +HTTPS and are checked against the SHA-256 digest before installation. A sample +entry is: + +```json +{ + "schema": 1, + "plugins": [{ + "id": "com.example.speed", + "name": "Speed display", + "version": "1.0.0", + "apkUrl": "https://example.org/speed-1.0.0.apk", + "sha256": "…64 lowercase hexadecimal characters…", + "sdkRange": "1.0.0-2.0.0", + "entry": "com.example.speed.SpeedPlugin" + }] +} +``` + +## Roadmap + +Three existing features — speed-reactive audio, the soundboard, and the button-key remapper — +will become SDK consumers during the next phase. They keep their current screens and behaviour +until their code is rewritten against `Contribution`, `HookRegistry`, and `ScopedPreferences` +and published from the official repository index. Removing in-app code only happens once a +replacement plugin is signed and published, so functionality never disappears without a working +install path. diff --git a/docs/settings-navigation.md b/docs/settings-navigation.md new file mode 100644 index 0000000..b537541 --- /dev/null +++ b/docs/settings-navigation.md @@ -0,0 +1,148 @@ +# Settings navigation + +`SettingsActivity` contains seven tabs. Switching tabs resets the content scroll +position to the top after layout. Refreshing the same tab (including returning +from another page or changing a picker value) retains its scroll offset, clamped +to the available content height. Theme-driven view rebuilds retain that offset too. + +Existing preference stores, keys, defaults, and feature callbacks are unchanged. +Brightness scheduling and music display controls remain grouped inline on +Dashboard; there are no separate brightness or music-display activities. +All internal activity destinations below are registered in `AndroidManifest.xml`. +OEM destinations depend on the software installed on the head unit. + +## Tab → group → setting → destination + +```text +Vehicle + Vehicle settings → VehicleSettingsActivity (capability-gated startup profile) + Vehicle power / Turn off car → confirmation → guarded OEM power-off request + Default drive mode → VehicleSettingsActivity (current value shown in hub) + Default recovery level → VehicleSettingsActivity (current value shown in hub) + +Driving + Performance + 0–100 tester → SpeedTestActivity + Trip tracking + Trip reports → TripsActivity + Arrival areas → ArrivalGeofenceActivity + Drive log sample interval → inline single-choice dialog + Maps + Map tile cache storage → preset selector / custom MB dialog + Map cache current use → read-only usage summary + +Charging + Charging management + Charging automation → ChargingActivity + Energy dashboard → EnergyActivity + Vehicle charging + Vehicle charging settings → OEM ChargeManagementActivity + +Audio + Sound and volume + Soundboard → SoundboardActivity + Speed reactive audio → SpeedAudioActivity + Adaptive audio leveling → AdaptiveAudioLevelingActivity + Liquid Sound Balance → LiquidSoundBalanceActivity + Assistant + Hermes agent assistant → HermesSettingsActivity + +Dashboard + Theme + Font size → inline slider + Theme → CustomThemeEditorActivity + Navigation + Page animations → inline toggle + Panels + App Drawer → inline toggle + App drawer opacity → inline slider + Control panel → inline toggle + Configure control panel → ControlPanelSettingsActivity + Widgets Panel → inline toggle + Camping mode + Camping mode settings → CampingModeSettingsActivity + Brightness schedule + Automatic brightness → inline toggle; rearms BrightnessScheduler + Peak brightness time → time picker; rearms BrightnessScheduler + Dark brightness time → time picker; rearms BrightnessScheduler + Peak brightness → inline percentage slider; rearms BrightnessScheduler + Dark brightness → inline percentage slider; rearms BrightnessScheduler + Transition duration → inline minutes slider; rearms BrightnessScheduler + Music player + Music Player → inline toggle / notification-access permission prompt + Music visualizer + Music Visualizer → inline toggle + Visualizer framerate → single-choice dialog + Visualizer effect → single-choice dialog + Visualizer opacity → inline slider + +Apps + Pinned apps + Reorder → inline toggle enabling drag-and-drop ordering + Pinned app tile → launch configured app/activity + Edit / remove pin → existing tile controls and dialogs + Add New → pin editor with app/activity pickers (outside reorder mode) + +System + Setup + Run setup wizard → SetupWizardActivity (review mode) + Diagnostics + Debug console → DebugActivity + Upload diagnostics → consent dialog; upload only after confirmation + Keys and launcher + Key remapping → KeyRemappingActivity + Official SAIC launcher → OEM home activity; generic home intent fallback + Change Launcher → Android home settings; default-app settings fallback + OEM and system tools + Engineer mode → OEM EngineeringModeActivity + SAIC vehicle settings → OEM VehicleSettingsActivity + System settings → OEM SettingsActivity + Software updates + Software updates → UpdateActivity + Plugins + Plugin marketplace → PluginMarketplaceActivity + Transfer + Included settings → informational dialog listing ConfigStore sections + Export settings → Android create-document picker; JSON export + Import settings → Android open-document picker; JSON import + Reset + Reset settings → confirmation dialog; reset preferences and recreate hub +``` + +## External destinations + +| Entry | Component or intent | +| --- | --- | +| Vehicle charging settings | `com.saicmotor.hmi.vehiclesettings/com.saicmotor.hmi.vehiclesettings.chargemanagement.ui.ChargeManagementActivity` | +| Official SAIC launcher | `com.saicmotor.hmi.launcher/com.saicmotor.hmi.launcher.ui.MainActivity`; fallback `ACTION_MAIN` + `CATEGORY_HOME` | +| Change Launcher | `Settings.ACTION_HOME_SETTINGS`; fallback `Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS` | +| Engineer mode | `com.saicmotor.hmi.engmode/com.saicmotor.hmi.engmode.home.ui.EngineeringModeActivity` | +| SAIC vehicle settings | `com.saicmotor.hmi.vehiclesettings/com.saicmotor.hmi.vehiclesettings.vehicleconfig.ui.VehicleSettingsActivity` | +| System settings | `com.saicmotor.hmi.systemsettings/com.saicmotor.hmi.systemsettings.SettingsActivity` | +| Music Player permission | `Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS` | + +## Entry points and migration + +The original Driving tab is split into Vehicle and Driving. Charging stays +together. Misc is split into Audio and System. Appearance becomes Dashboard. +Apps retains its pinned-app tools. Config is incorporated into System, with the +old export section list available through Included settings instead of repeated rows. + +`EXTRA_CATEGORY` remains an integer intent extra with zero-based tab order: +Vehicle (0), Driving (1), Charging (2), Audio (3), Dashboard (4), Apps (5), System (6). +The control panel's automatic-brightness settings shortcut uses +`SettingsActivity.CATEGORY_DASHBOARD` rather than the old Appearance index (3). +Vehicle default summary rows intentionally share the same destination; editing +remains centralized in the capability-gated vehicle settings page. + +## Manual navigation checks + +On a head unit or emulator, scroll down Dashboard, switch to System, and confirm +System starts at the top; repeat between other tabs. Scroll to brightness or +visualizer controls, change a picker, and confirm the same-tab refresh preserves +position. Return from a child page and from notification access, and verify the +same behavior. Change theme/font size, then verify the rebuilt tab and controls. +Check the control panel brightness shortcut lands on Dashboard. Exercise pinned +app editing and reordering, and verify settings still export/import as before. +Diagnostic upload and reset require explicit confirmation; cancel them during +navigation-only checks. diff --git a/docs/vehicle-power-off.md b/docs/vehicle-power-off.md new file mode 100644 index 0000000..05add12 --- /dev/null +++ b/docs/vehicle-power-off.md @@ -0,0 +1,68 @@ +# Manual vehicle power off + +Open **Settings → Vehicle → Vehicle settings → Vehicle power → TURN OFF CAR**. +The button opens a confirmation prompt. Cancel, Back, or leaving the activity +does not submit a command. Confirming checks the live vehicle state on a worker +thread, then sends the same power-off request used by the captured OEM app. +This is not an Android shutdown/reboot or a screen-blanking command. + +## OEM evidence + +Source: local `mg4-luxury-2022-info` checkout at commit +`6bbf5385d0de5f8102979b5d13b04f8b1930fefc`. +Paths below are relative to that repository's `device-info/decomp/` directory. + +| Evidence | File and method | +| --- | --- | +| OEM button opens a warning dialog; confirmation passes integer `2` | `com.saicmotor.hmi.vehiclesettings/smali/com/saicmotor/hmi/vehiclesettings/vehicleconfig/viewmodel/VehiclePowerViewModel.smali`: `defPowerOffClick`, `lambda$defPowerOffClick$0$VehiclePowerViewModel` | +| Button enabled only when gear equals `1` (Park) | Same view model: `updatePowerModeSwitch`; `vehicleconfig/repository/VehiclePowerRepository.smali`: `getPowerModeSwitchEnable` returns `getCarGear()` | +| Repository forwards the request to `VehicleSettingManager.setPowerModeSwitch` | `com.saicmotor.hmi.vehiclesettings/smali/com/saicmotor/hmi/vehiclesettings/vehicleconfig/repository/VehiclePowerRepository.smali`: `setPowerModeSwitch` | +| Setter uses token `com.saicmotor.sdk.vehiclesettings.IVehicleSettingService`, transaction `0xad`, integer argument, no reply, one-way flag `1` | `com.saicmotor.hmi.vehiclesettings/smali_classes2/com/saicmotor/sdk/vehiclesettings/IVehicleSettingService$Stub$Proxy.smali`: `setPowerModeSwitch` | +| Vehicle service validates the value, then writes integer global property `0x2140d70f` using `CarComfortableManager` | `com.saicmotor.service.vehicle/smali/com/saicmotor/service/vehicle/binder/VehicleSettingBinder.smali`: `setPowerModeSwitch` | +| Captured service version | `com.saicmotor.service.vehicle/apktool.yml`: `VehicleSettingsService.44041` | +| OEM UI explicitly says the function is available in P | `com.saicmotor.hmi.vehiclesettings/res/values/strings.xml`: `vehicle_power_off_all_sub` | + +MG Utility uses its existing exported vehicle hub connection and retrieves the +`vehiclesetting` and `vehiclecondition` binders. It does **not** directly write the +underlying global vehicle property, bypass the OEM service, or invoke a generic +shutdown broadcast. + +## Safety and compatibility behavior + +- Only the exact captured service version `VehicleSettingsService.44041` and + matching setting/condition Binder descriptors are allowed. Other versions + report unsupported rather than guessing transaction compatibility. +- A fresh gear reading must be `1` (Park). A fresh speed reading must be finite + and exactly zero. Unknown, negative, nonzero, or invalid readings block the + command. Gear is read again after speed, before submitting the request. +- These sequential reads are not an atomic vehicle-state guarantee. The driver + must remain safely parked, and the OEM vehicle service remains responsible for + applying the request and any vehicle-side interlocks. +- No action runs at startup, on service connection, or from a saved preference. + There is no key-remapping, plugin, automation, or remote-trigger integration. +- Cancel never calls the controller. Leaving the activity or a service + disconnect dismisses an outstanding confirmation. A request already confirmed + and submitted cannot be recalled by navigating away. +- Repeated/concurrent calls on the same controller cannot send a second command. + Failed or uncertain writes are never retried automatically. A blocked safety + check can be tried again through a new explicit confirmation. +- A successful one-way Binder submission is reported as **request sent**, not + proof that the car powered off. No fallback write or retry occurs if the OEM + service rejects or ignores the command. + +## Validation and limits + +`VehiclePowerOffControllerTest` covers cancellation/no side effects, unsupported +service, unknown/non-Park gears, invalid/nonzero speed, gear changes during the +check, read/write failures, duplicate and concurrent requests, and new state +reads after a blocked attempt. `VehiclePowerOffGatewayTest` uses fake Binder/Parcel +objects to check exact transaction/payload/flags, version/descriptor rejection, +missing services, telemetry failures, and failed submission. The Android build +checks the real Android API and UI wiring. + +Static OEM analysis identifies the command path, but does not prove this +sideloaded app can successfully power off the physical car. No physical shutdown +is executed during development validation. First on-car validation must be +supervised with the car safely stationary in Park, and should verify cancellation +before explicitly confirming a power-off request. Use OEM controls if MG Utility +reports an unsupported service or unavailable telemetry. diff --git a/examples/plugin-template/README.md b/examples/plugin-template/README.md new file mode 100644 index 0000000..c3875ea --- /dev/null +++ b/examples/plugin-template/README.md @@ -0,0 +1,7 @@ +# MG Utility plugin template + +This is a dependency-light Java 8 starter plugin. Compile the SDK sources in +`src/cloud/molberg/mgutility/sdk` together with `src/main/java`, package +`assets/mg-plugin.json` into your APK, and publish the APK plus SHA-256 digest +in a marketplace repository index. See [PLUGIN_SDK.md](../../docs/PLUGIN_SDK.md) +for lifecycle and repository details. diff --git a/examples/plugin-template/assets/mg-plugin.json b/examples/plugin-template/assets/mg-plugin.json new file mode 100644 index 0000000..c3a9d6e --- /dev/null +++ b/examples/plugin-template/assets/mg-plugin.json @@ -0,0 +1,13 @@ +{ + "schema": 1, + "id": "com.example.mgutility.template", + "name": "MG Utility plugin template", + "versionName": "0.1.0", + "versionCode": 1, + "entryPoint": "com.example.mgutility.template.TemplatePlugin", + "sdkVersion": "1.0.0", + "publisher": "Your name", + "description": "Minimal plugin template.", + "capabilities": ["DASHBOARD", "VEHICLE_DATA_READ"], + "permissions": [] +} diff --git a/examples/plugin-template/src/main/java/com/example/mgutility/template/TemplatePlugin.java b/examples/plugin-template/src/main/java/com/example/mgutility/template/TemplatePlugin.java new file mode 100644 index 0000000..20d0490 --- /dev/null +++ b/examples/plugin-template/src/main/java/com/example/mgutility/template/TemplatePlugin.java @@ -0,0 +1,28 @@ +package com.example.mgutility.template; + +import cloud.molberg.mgutility.sdk.Contribution; +import cloud.molberg.mgutility.sdk.Plugin; +import cloud.molberg.mgutility.sdk.PluginContext; +import cloud.molberg.mgutility.sdk.PluginHook; +import cloud.molberg.mgutility.sdk.HookRegistry; + +/** Copy this class and change the manifest ID to start a plugin. */ +public final class TemplatePlugin implements Plugin { + private HookRegistry.TypedListener speedListener; + @Override public void onEnable(PluginContext context) { + context.contributions().register(new Contribution( + "template.tile", Contribution.Type.HOME_TILE, + "Template", "A plugin-provided home tile", "template://tile")); + speedListener = new HookRegistry.TypedListener() { + @Override public void onEvent(PluginHook hook, cloud.molberg.mgutility.sdk.HookEvent event) { + context.logger().debug("speed=" + event.getDouble("speedKph", 0)); + } + }; + if (context.hasCapability(cloud.molberg.mgutility.sdk.PluginCapability.VEHICLE_DATA_READ)) + context.hooks().subscribe(PluginHook.SPEED_CHANGED, speedListener); + } + @Override public void onDisable(PluginContext context) { + context.contributions().remove("template.tile"); + if (speedListener != null) context.hooks().unsubscribe(PluginHook.SPEED_CHANGED, speedListener); + } +} diff --git a/res/drawable/ic_add.xml b/res/drawable/ic_add.xml new file mode 100644 index 0000000..2f38f22 --- /dev/null +++ b/res/drawable/ic_add.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_air.xml b/res/drawable/ic_air.xml new file mode 100644 index 0000000..8106049 --- /dev/null +++ b/res/drawable/ic_air.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_apps.xml b/res/drawable/ic_apps.xml new file mode 100644 index 0000000..d35843e --- /dev/null +++ b/res/drawable/ic_apps.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_arrow_back.xml b/res/drawable/ic_arrow_back.xml new file mode 100644 index 0000000..5a6635c --- /dev/null +++ b/res/drawable/ic_arrow_back.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_battery_charging_full.xml b/res/drawable/ic_battery_charging_full.xml new file mode 100644 index 0000000..5dd3ebd --- /dev/null +++ b/res/drawable/ic_battery_charging_full.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_bluetooth.xml b/res/drawable/ic_bluetooth.xml new file mode 100644 index 0000000..4543770 --- /dev/null +++ b/res/drawable/ic_bluetooth.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_bolt.xml b/res/drawable/ic_bolt.xml new file mode 100644 index 0000000..cda36f9 --- /dev/null +++ b/res/drawable/ic_bolt.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_brightness_6.xml b/res/drawable/ic_brightness_6.xml new file mode 100644 index 0000000..568dc15 --- /dev/null +++ b/res/drawable/ic_brightness_6.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_bug_report.xml b/res/drawable/ic_bug_report.xml new file mode 100644 index 0000000..201312b --- /dev/null +++ b/res/drawable/ic_bug_report.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_build.xml b/res/drawable/ic_build.xml new file mode 100644 index 0000000..dd35b40 --- /dev/null +++ b/res/drawable/ic_build.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_check_circle.xml b/res/drawable/ic_check_circle.xml new file mode 100644 index 0000000..f21061b --- /dev/null +++ b/res/drawable/ic_check_circle.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_chevron_right.xml b/res/drawable/ic_chevron_right.xml new file mode 100644 index 0000000..7d27823 --- /dev/null +++ b/res/drawable/ic_chevron_right.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_cloud.xml b/res/drawable/ic_cloud.xml new file mode 100644 index 0000000..71f2dce --- /dev/null +++ b/res/drawable/ic_cloud.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_dashboard.xml b/res/drawable/ic_dashboard.xml new file mode 100644 index 0000000..5eff61d --- /dev/null +++ b/res/drawable/ic_dashboard.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_delete.xml b/res/drawable/ic_delete.xml new file mode 100644 index 0000000..6251d59 --- /dev/null +++ b/res/drawable/ic_delete.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_directions_car.xml b/res/drawable/ic_directions_car.xml new file mode 100644 index 0000000..4ecfce4 --- /dev/null +++ b/res/drawable/ic_directions_car.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_download.xml b/res/drawable/ic_download.xml new file mode 100644 index 0000000..cefbcc0 --- /dev/null +++ b/res/drawable/ic_download.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_edit.xml b/res/drawable/ic_edit.xml new file mode 100644 index 0000000..f8db763 --- /dev/null +++ b/res/drawable/ic_edit.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_error.xml b/res/drawable/ic_error.xml new file mode 100644 index 0000000..ad949ef --- /dev/null +++ b/res/drawable/ic_error.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_explore.xml b/res/drawable/ic_explore.xml new file mode 100644 index 0000000..3ad143d --- /dev/null +++ b/res/drawable/ic_explore.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_extension.xml b/res/drawable/ic_extension.xml new file mode 100644 index 0000000..76e4944 --- /dev/null +++ b/res/drawable/ic_extension.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_favorite.xml b/res/drawable/ic_favorite.xml new file mode 100644 index 0000000..5a49c66 --- /dev/null +++ b/res/drawable/ic_favorite.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_file_download.xml b/res/drawable/ic_file_download.xml new file mode 100644 index 0000000..6da766d --- /dev/null +++ b/res/drawable/ic_file_download.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_file_upload.xml b/res/drawable/ic_file_upload.xml new file mode 100644 index 0000000..4a67447 --- /dev/null +++ b/res/drawable/ic_file_upload.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_flight_takeoff.xml b/res/drawable/ic_flight_takeoff.xml new file mode 100644 index 0000000..d3acbcb --- /dev/null +++ b/res/drawable/ic_flight_takeoff.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_folder.xml b/res/drawable/ic_folder.xml new file mode 100644 index 0000000..d5752fe --- /dev/null +++ b/res/drawable/ic_folder.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_graphic_eq.xml b/res/drawable/ic_graphic_eq.xml new file mode 100644 index 0000000..e5873d2 --- /dev/null +++ b/res/drawable/ic_graphic_eq.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_help.xml b/res/drawable/ic_help.xml new file mode 100644 index 0000000..4b0c107 --- /dev/null +++ b/res/drawable/ic_help.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/res/drawable/ic_home.xml b/res/drawable/ic_home.xml new file mode 100644 index 0000000..43b5017 --- /dev/null +++ b/res/drawable/ic_home.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_info.xml b/res/drawable/ic_info.xml new file mode 100644 index 0000000..d596b74 --- /dev/null +++ b/res/drawable/ic_info.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_keyboard.xml b/res/drawable/ic_keyboard.xml new file mode 100644 index 0000000..54a7315 --- /dev/null +++ b/res/drawable/ic_keyboard.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_location_on.xml b/res/drawable/ic_location_on.xml new file mode 100644 index 0000000..b58e128 --- /dev/null +++ b/res/drawable/ic_location_on.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_lock.xml b/res/drawable/ic_lock.xml new file mode 100644 index 0000000..7b8cb4f --- /dev/null +++ b/res/drawable/ic_lock.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_manage_accounts.xml b/res/drawable/ic_manage_accounts.xml new file mode 100644 index 0000000..45f694c --- /dev/null +++ b/res/drawable/ic_manage_accounts.xml @@ -0,0 +1,4 @@ + + + + diff --git a/res/drawable/ic_map.xml b/res/drawable/ic_map.xml new file mode 100644 index 0000000..550e6e9 --- /dev/null +++ b/res/drawable/ic_map.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_mic.xml b/res/drawable/ic_mic.xml new file mode 100644 index 0000000..23d4fbc --- /dev/null +++ b/res/drawable/ic_mic.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_music_note.xml b/res/drawable/ic_music_note.xml new file mode 100644 index 0000000..3bf6d1b --- /dev/null +++ b/res/drawable/ic_music_note.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_nightlight.xml b/res/drawable/ic_nightlight.xml new file mode 100644 index 0000000..44de7b1 --- /dev/null +++ b/res/drawable/ic_nightlight.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_open_in_new.xml b/res/drawable/ic_open_in_new.xml new file mode 100644 index 0000000..6ef9e36 --- /dev/null +++ b/res/drawable/ic_open_in_new.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_palette.xml b/res/drawable/ic_palette.xml new file mode 100644 index 0000000..d0f9337 --- /dev/null +++ b/res/drawable/ic_palette.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_place.xml b/res/drawable/ic_place.xml new file mode 100644 index 0000000..b58e128 --- /dev/null +++ b/res/drawable/ic_place.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_play_arrow.xml b/res/drawable/ic_play_arrow.xml new file mode 100644 index 0000000..d8eece7 --- /dev/null +++ b/res/drawable/ic_play_arrow.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_refresh.xml b/res/drawable/ic_refresh.xml new file mode 100644 index 0000000..2cc7a34 --- /dev/null +++ b/res/drawable/ic_refresh.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_remove.xml b/res/drawable/ic_remove.xml new file mode 100644 index 0000000..e4cd0ab --- /dev/null +++ b/res/drawable/ic_remove.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_restart_alt.xml b/res/drawable/ic_restart_alt.xml new file mode 100644 index 0000000..431689d --- /dev/null +++ b/res/drawable/ic_restart_alt.xml @@ -0,0 +1,4 @@ + + + + diff --git a/res/drawable/ic_schedule.xml b/res/drawable/ic_schedule.xml new file mode 100644 index 0000000..f0b023d --- /dev/null +++ b/res/drawable/ic_schedule.xml @@ -0,0 +1,4 @@ + + + + diff --git a/res/drawable/ic_settings.xml b/res/drawable/ic_settings.xml new file mode 100644 index 0000000..6cf0d87 --- /dev/null +++ b/res/drawable/ic_settings.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_signal_cellular_alt.xml b/res/drawable/ic_signal_cellular_alt.xml new file mode 100644 index 0000000..e7300d5 --- /dev/null +++ b/res/drawable/ic_signal_cellular_alt.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_speed.xml b/res/drawable/ic_speed.xml new file mode 100644 index 0000000..ae9084f --- /dev/null +++ b/res/drawable/ic_speed.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_star.xml b/res/drawable/ic_star.xml new file mode 100644 index 0000000..a4e8b2d --- /dev/null +++ b/res/drawable/ic_star.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_stop.xml b/res/drawable/ic_stop.xml new file mode 100644 index 0000000..b2d3680 --- /dev/null +++ b/res/drawable/ic_stop.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_storage.xml b/res/drawable/ic_storage.xml new file mode 100644 index 0000000..1a1b438 --- /dev/null +++ b/res/drawable/ic_storage.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_swap_horiz.xml b/res/drawable/ic_swap_horiz.xml new file mode 100644 index 0000000..27536b0 --- /dev/null +++ b/res/drawable/ic_swap_horiz.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_system_update.xml b/res/drawable/ic_system_update.xml new file mode 100644 index 0000000..ac35f02 --- /dev/null +++ b/res/drawable/ic_system_update.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_thermostat.xml b/res/drawable/ic_thermostat.xml new file mode 100644 index 0000000..fb5bfa9 --- /dev/null +++ b/res/drawable/ic_thermostat.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_timer.xml b/res/drawable/ic_timer.xml new file mode 100644 index 0000000..22734c7 --- /dev/null +++ b/res/drawable/ic_timer.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_tune.xml b/res/drawable/ic_tune.xml new file mode 100644 index 0000000..9ab1ef7 --- /dev/null +++ b/res/drawable/ic_tune.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_update.xml b/res/drawable/ic_update.xml new file mode 100644 index 0000000..d1d4081 --- /dev/null +++ b/res/drawable/ic_update.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_upload.xml b/res/drawable/ic_upload.xml new file mode 100644 index 0000000..5fba0a1 --- /dev/null +++ b/res/drawable/ic_upload.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_verified.xml b/res/drawable/ic_verified.xml new file mode 100644 index 0000000..19ebbd9 --- /dev/null +++ b/res/drawable/ic_verified.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_visibility.xml b/res/drawable/ic_visibility.xml new file mode 100644 index 0000000..fe79840 --- /dev/null +++ b/res/drawable/ic_visibility.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_volume_down.xml b/res/drawable/ic_volume_down.xml new file mode 100644 index 0000000..26eb3db --- /dev/null +++ b/res/drawable/ic_volume_down.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_volume_up.xml b/res/drawable/ic_volume_up.xml new file mode 100644 index 0000000..7773108 --- /dev/null +++ b/res/drawable/ic_volume_up.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_warning.xml b/res/drawable/ic_warning.xml new file mode 100644 index 0000000..1ccd509 --- /dev/null +++ b/res/drawable/ic_warning.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_widgets.xml b/res/drawable/ic_widgets.xml new file mode 100644 index 0000000..a20fa70 --- /dev/null +++ b/res/drawable/ic_widgets.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/drawable/ic_wifi.xml b/res/drawable/ic_wifi.xml new file mode 100644 index 0000000..a320040 --- /dev/null +++ b/res/drawable/ic_wifi.xml @@ -0,0 +1,3 @@ + + + diff --git a/res/values/strings.xml b/res/values/strings.xml new file mode 100644 index 0000000..49ca157 --- /dev/null +++ b/res/values/strings.xml @@ -0,0 +1,4 @@ + + MG Utility global keys + Open Hermes and remap steering-wheel keys over other apps. Hold your mapped Hermes key to record and release to send. This service filters hardware keys; it does not read screen contents. + diff --git a/res/xml/key_remapping_accessibility_service.xml b/res/xml/key_remapping_accessibility_service.xml new file mode 100644 index 0000000..7a11ae0 --- /dev/null +++ b/res/xml/key_remapping_accessibility_service.xml @@ -0,0 +1,8 @@ + + diff --git a/scripts/build-plugin-sdk.sh b/scripts/build-plugin-sdk.sh new file mode 100755 index 0000000..5f12c03 --- /dev/null +++ b/scripts/build-plugin-sdk.sh @@ -0,0 +1,24 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +OUT=${1:-"$ROOT/build/plugin-sdk"} +rm -rf "$OUT" +mkdir -p "$OUT/classes" +javac -source 8 -target 8 -d "$OUT/classes" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/Plugin.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginCapability.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginContext.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/ScopedPreferences.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginLogger.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/Contribution.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/ContributionRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/HookRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginHook.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/HookEvent.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/InMemoryContributionRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/InMemoryHookRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/VersionRange.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginManifest.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginManifestParser.java" +(cd "$OUT/classes" && jar cf "$OUT/mg-utility-plugin-sdk.jar" .) +echo "Built $OUT/mg-utility-plugin-sdk.jar" diff --git a/scripts/release-dev.sh b/scripts/release-dev.sh new file mode 100755 index 0000000..8f67eb6 --- /dev/null +++ b/scripts/release-dev.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# One-command, Vault-backed Dev build/release with remote artifact verification. +set -euo pipefail +ROOT="$(cd -- "$(dirname -- "$0")/.." && pwd)" +DRY_RUN=0 +for arg in "$@"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + --help|-h) printf '%s\n' 'Usage: ./scripts/release-dev.sh [--dry-run]'; exit 0 ;; + *) printf 'Unknown option: %s\n' "$arg" >&2; exit 2 ;; + esac +done +ITEM_ID="${GITEA_VAULT_ITEM_ID:-9fb0e528-b7bd-4ad8-a390-21dc95763374}" +VAULT_HELPER="${VAULT_HELPER:-/root/.openclaw/workspace/scripts/vault.sh}" +SCRATCH="${TMPDIR:-/root/.hermes/cache/scratch}" +mkdir -p "$SCRATCH" + +command -v bw >/dev/null || { echo "Bitwarden CLI (bw) is required" >&2; exit 1; } +command -v curl >/dev/null || { echo "curl is required" >&2; exit 1; } +command -v python3 >/dev/null || { echo "python3 is required" >&2; exit 1; } +command -v sha256sum >/dev/null || { echo "sha256sum is required" >&2; exit 1; } +[[ -f "$VAULT_HELPER" ]] || { echo "Vault helper not found: $VAULT_HELPER" >&2; exit 1; } + +item_file=$(mktemp "$SCRATCH/mg-release-vault.XXXXXX") +trap 'rm -f "$item_file"' EXIT + +# The helper loads VAULT_MASTER_PW; use Bitwarden's environment-based unlock +# so the master password is not placed in command arguments. +source "$VAULT_HELPER" +if [[ -z "${BW_SESSION:-}" ]]; then + echo "Could not obtain a Bitwarden session from the Vault helper" >&2 + exit 1 +fi +export BW_PASSWORD="${VAULT_MASTER_PW:-}" +if [[ -z "$BW_PASSWORD" ]]; then + echo "VAULT_MASTER_PW was not loaded by the Vault helper" >&2 + exit 1 +fi +export BW_SESSION="$(bw unlock --passwordenv BW_PASSWORD --raw 2>/dev/null)" +unset BW_PASSWORD +[[ -n "$BW_SESSION" ]] || { echo "Bitwarden unlock failed" >&2; exit 1; } + +bw get item "$ITEM_ID" > "$item_file" +export GITEA_TOKEN="$(python3 - "$item_file" <<'PY' +import json, sys +with open(sys.argv[1], encoding="utf-8") as f: + item = json.load(f) +print(next((field["value"] for field in item.get("fields", []) + if field.get("name") == "personal_access_token"), ""), end="") +PY +)" +[[ -n "$GITEA_TOKEN" ]] || { echo "Gitea token field is missing from the configured Vault item" >&2; exit 1; } + +# Run the established release flow without ever writing credentials into the +# repository or printing them. Dry-run does authenticated version allocation. +"$ROOT/scripts/release.sh" --dry-run +if [[ "$DRY_RUN" -eq 1 ]]; then + exit 0 +fi +"$ROOT/scripts/release.sh" + +APK="$ROOT/build/MG-Utility.apk" +python3 - "$ROOT" <<'PY' +import hashlib +import json +import os +from pathlib import Path +import sys +import urllib.parse +import urllib.request + +root = Path(sys.argv[1]) +build = json.loads((root / "build/assets/mg-update-build.json").read_text()) +tag = f"dev-v{build['versionName']}-c{build['versionCode']}" +api = os.environ.get("GITEA_API_URL", "https://git.molberg.cloud/api/v1/repos/alex/mg-utility") +headers = {"Authorization": "token " + os.environ["GITEA_TOKEN"], "User-Agent": "MG-Utility-release-verifier"} +class SameOriginRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request, response, code, message, headers, new_url): + original = urllib.parse.urlsplit(api) + redirected = urllib.parse.urlsplit(new_url) + if (original.scheme, original.netloc) != (redirected.scheme, redirected.netloc): + raise SystemExit("Refusing an authenticated cross-origin redirect") + return super().redirect_request(request, response, code, message, headers, new_url) + +opener = urllib.request.build_opener(SameOriginRedirect()) +with opener.open(urllib.request.Request(api + "/releases/tags/" + tag, headers=headers), timeout=60) as response: + release = json.load(response) +metadata = json.loads(release["body"]) +for field in ("channel", "versionName", "versionCode", "branch"): + if metadata.get(field) != build[field]: + raise SystemExit("Release metadata mismatch: " + field) +assets = [asset for asset in release["assets"] if asset["name"] == "MG-Utility.apk"] +if len(assets) != 1: + raise SystemExit("Expected exactly one published MG-Utility.apk") +url = assets[0]["browser_download_url"] +asset_origin = urllib.parse.urlsplit(url) +api_origin = urllib.parse.urlsplit(api) +if (asset_origin.scheme, asset_origin.netloc) != (api_origin.scheme, api_origin.netloc): + raise SystemExit("Refusing to send release credentials to a different asset host") +digest = hashlib.sha256() +with opener.open(urllib.request.Request(url, headers=headers), timeout=120) as response: + while True: + chunk = response.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) +local_digest = hashlib.sha256((root / "build/MG-Utility.apk").read_bytes()).hexdigest() +if digest.hexdigest() != local_digest or metadata.get("sha256") != local_digest: + raise SystemExit("Published APK SHA-256 does not match metadata and local artifact") +print("Verified published Dev APK: downloaded SHA-256 = release metadata = local artifact") +print("Version:", build["versionName"]) +print("Release tag:", tag) +print("SHA-256:", local_digest) +PY +SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/opt/android-sdk}}" +TOOLS="$(find "$SDK/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -n 1)" +"$TOOLS/apksigner" verify -v --min-sdk-version 23 "$APK" +"$TOOLS/aapt2" dump badging "$APK" | sed -n '1,3p' +unzip -t "$APK" | tail -n 1 +printf '\nArtifact: %s\n' "$APK" +ls -lh "$APK" +sha256sum "$APK" diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..9f6fd03 --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,183 @@ +#!/bin/sh +# Build and publish MG Utility releases. +# +# Without flags: publish the next Dev build for the latest stable line. +# With --stable: publish the next Stable release, then its first Dev build. +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +STABLE=0 +DRY_RUN=0 + +for arg in "$@"; do + case "$arg" in + --stable) STABLE=1 ;; + --dry-run) DRY_RUN=1 ;; + --help|-h) + printf '%s\n' 'Usage: ./scripts/release.sh [--stable] [--dry-run]' + printf '%s\n' ' (default) publish the next Dev build' + printf '%s\n' ' --stable publish the next Stable build and its first Dev build' + printf '%s\n' ' --dry-run calculate and print versions without building or publishing' + exit 0 + ;; + *) echo "Unknown option: $arg" >&2; exit 2 ;; + esac +done + +API=${GITEA_API_URL:-https://git.molberg.cloud/api/v1/repos/alex/mg-utility} + +if [ "$DRY_RUN" -eq 0 ] && [ -z "${GITEA_TOKEN:-}" ]; then + echo "Use scripts/release-dev.sh to obtain GITEA_TOKEN securely from Vault" >&2 + exit 2 +fi + +api_curl() { + case "${GITEA_TOKEN:-}" in + *[!a-zA-Z0-9]*) echo "Invalid Gitea token format" >&2; return 2 ;; + esac + printf 'header = "Authorization: token %s"\n' "$GITEA_TOKEN" | + curl --config - -fsS -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' "$@" +} + +RELEASES_JSON=$(mktemp) +PLAN_JSON=$(mktemp) +trap 'rm -f "$RELEASES_JSON" "$PLAN_JSON"' EXIT HUP INT TERM + +if [ -n "${GITEA_TOKEN:-}" ]; then + api_curl "$API/releases?limit=50" > "$RELEASES_JSON" +else + printf '%s\n' '[]' > "$RELEASES_JSON" +fi + +BASE_VERSION=$(sed -n 's/.*android:versionName="\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1) +BASE_CODE=$(sed -n 's/.*android:versionCode="\([0-9][0-9]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1) + +python3 - "$RELEASES_JSON" "$PLAN_JSON" "$BASE_VERSION" "$BASE_CODE" "$STABLE" <<'PY' +import json +import re +import sys + +releases_path, plan_path, base_version, base_code, stable_flag = sys.argv[1:] +stable_flag = int(stable_flag) +semver = re.compile(r"^(\d+)\.(\d+)\.(\d+)$") +devver = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$") + +with open(releases_path, encoding="utf-8") as handle: + releases = json.load(handle) + +stable_versions = [] +dev_versions = [] +version_codes = [int(base_code or 0)] +for release in releases: + try: + metadata = json.loads(release.get("body", "")) + code = int(metadata.get("versionCode", 0)) + if code > 0: + version_codes.append(code) + name = str(metadata.get("versionName", "")) + channel = metadata.get("channel") + match = semver.fullmatch(name) + if channel == "stable" and match: + stable_versions.append(tuple(map(int, match.groups()))) + match = devver.fullmatch(name) + if channel == "dev" and match: + dev_versions.append(tuple(map(int, match.groups()))) + except (TypeError, ValueError, json.JSONDecodeError): + continue + +base_match = semver.fullmatch(base_version or "") +if not stable_versions: + if not base_match: + raise SystemExit("AndroidManifest.xml must contain a base X.Y.Z versionName") + latest_stable = tuple(map(int, base_match.groups())) +else: + latest_stable = max(stable_versions) + +if stable_flag: + major, minor, patch = latest_stable + stable_version = (major, minor, patch + 1) + stable_name = ".".join(map(str, stable_version)) + dev_name = stable_name + ".1" + stable_code = max(version_codes) + 1 + dev_code = stable_code + 1 + plan = [ + {"channel": "stable", "versionName": stable_name, "versionCode": stable_code}, + {"channel": "dev", "versionName": dev_name, "versionCode": dev_code}, + ] +else: + major, minor, patch = latest_stable + counter = max((v[3] for v in dev_versions if v[:3] == latest_stable), default=0) + 1 + dev_name = f"{major}.{minor}.{patch}.{counter}" + plan = [{"channel": "dev", "versionName": dev_name, "versionCode": max(version_codes) + 1}] + +with open(plan_path, "w", encoding="utf-8") as handle: + json.dump(plan, handle) +PY + +python3 - "$PLAN_JSON" <<'PY' +import json +import sys +for item in json.load(open(sys.argv[1], encoding="utf-8")): + print(f"{item['channel']} {item['versionName']} {item['versionCode']}") +PY + +[ "$DRY_RUN" -eq 0 ] || exit 0 + +publish() { + channel=$1 + apk=$2 + version_code=$3 + version_name=$4 + branch=${5:-main} + tag="${channel}-v${version_name}-c${version_code}" + sha=$(sha256sum "$apk" | cut -d' ' -f1) + body=$(printf '{"schema":1,"channel":"%s","versionCode":%s,"versionName":"%s","branch":"%s","sha256":"%s"}' \ + "$channel" "$version_code" "$version_name" "$branch" "$sha") + response=$(mktemp) + body_json=$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$body") + api_curl -X POST "$API/releases" -H 'Content-Type: application/json' \ + --data "{\"tag_name\":\"$tag\",\"target_commitish\":\"$branch\",\"name\":\"MG Utility $version_name\",\"body\":$body_json,\"draft\":false,\"prerelease\":$([ "$channel" = dev ] && echo true || echo false)}" > "$response" + release_id=$(python3 - "$response" <<'PY' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as handle: + print(json.load(handle)["id"]) +PY +) + rm -f "$response" + curl_status=0 + api_curl -X POST \ + "$API/releases/$release_id/assets?name=MG-Utility.apk" \ + -F "attachment=@$apk;type=application/vnd.android.package-archive" >/dev/null || curl_status=$? + [ "$curl_status" -eq 0 ] || return "$curl_status" + printf 'Published %s release %s (%s)\n' "$channel" "$tag" "$sha" +} + +publish_plan_item() { + channel=$1 + version_name=$2 + version_code=$3 + UPDATE_VERSION_CODE="$version_code" UPDATE_VERSION_NAME="$version_name" UPDATE_BRANCH=main \ + "$ROOT/build.sh" "$channel" + publish "$channel" "$ROOT/build/MG-Utility.apk" "$version_code" "$version_name" main +} + +if [ "$STABLE" -eq 1 ]; then + stable=$(python3 - "$PLAN_JSON" <<'PY' +import json,sys +for item in json.load(open(sys.argv[1], encoding="utf-8")): + if item["channel"] == "stable": print(item["versionName"], item["versionCode"]) +PY +) + set -- $stable + publish_plan_item stable "$1" "$2" +fi + +dev=$(python3 - "$PLAN_JSON" <<'PY' +import json,sys +for item in json.load(open(sys.argv[1], encoding="utf-8")): + if item["channel"] == "dev": print(item["versionName"], item["versionCode"]) +PY +) +set -- $dev +publish_plan_item dev "$1" "$2" diff --git a/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java b/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java index fe60534..6d5e2a9 100644 --- a/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java +++ b/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java @@ -4,6 +4,12 @@ package cloud.molberg.mgutility; public final class AdaptiveAudioCurve { private AdaptiveAudioCurve() { } + public static float combinedMultiplier(float speedMultiplier, float positionMultiplier) { + float speed = finite(speedMultiplier) ? clamp(speedMultiplier, 0.5f, 1.5f) : 1f; + float position = finite(positionMultiplier) ? clamp(positionMultiplier, 1f, 2f) : 1f; + return speed * position; + } + /** * Returns a volume multiplier percentage for the supplied speed. Values at * and below level 1 use level 1, values at and above level 3 use level 3, diff --git a/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java index 1ccb593..6abc487 100644 --- a/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java +++ b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java @@ -110,16 +110,23 @@ public final class AdaptiveAudioLevelingManager { /** Called by the always-on vehicle worker whenever a fresh speed is available. */ public static void updateSpeed(Context context, float speedKph) { + updateSpeed(context, speedKph, 1f, false); + } + + public static void updateSpeed(Context context, float speedKph, float positionMultiplier, + boolean positionCompensation) { if (context == null || Float.isNaN(speedKph) || Float.isInfinite(speedKph)) return; Config cfg = config(context); - if (!cfg.enabled) { + if (!cfg.enabled && !positionCompensation) { stopAndRestore(context); return; } synchronized (LOCK) { VolumeState volume = readVolume(context); if (volume == null) return; - float multiplier = cfg.multiplierPercent(Math.max(0f, speedKph)) / 100f; + float speedMultiplier = cfg.enabled ? cfg.multiplierPercent(Math.max(0f, speedKph)) / 100f : 1f; + float multiplier = AdaptiveAudioCurve.combinedMultiplier(speedMultiplier, + positionCompensation ? positionMultiplier : 1f); float currentFraction = volume.fraction(); float tolerance = Math.max(0.01f, 0.55f / volume.range()); long now = SystemClock.elapsedRealtime(); @@ -141,7 +148,7 @@ public final class AdaptiveAudioLevelingManager { // the newly selected audible value as authoritative and infer the // corresponding unmodified base for subsequent speed changes. baseFraction = AdaptiveAudioCurve.referenceFraction(currentFraction, - multiplier * 100f); + lastMultiplier * 100f); lastAutomaticStepAt = now; lastVolumeWriteAt = 0L; } @@ -152,7 +159,7 @@ public final class AdaptiveAudioLevelingManager { // The underlying mixer is integer-stepped, so ramp one notch at a // time. Steering-wheel changes bypass this path and remain immediate. if (lastAutomaticStepAt != 0L && - now - lastAutomaticStepAt < AUTOMATIC_STEP_INTERVAL_MS) { + now - lastAutomaticStepAt < (positionCompensation ? 150L : AUTOMATIC_STEP_INTERVAL_MS)) { lastAppliedFraction = currentFraction; lastMultiplier = multiplier; return; @@ -192,8 +199,8 @@ public final class AdaptiveAudioLevelingManager { lastMultiplier * 100f); } int target = volume.fromFraction(baseFraction); - if (target != volume.current) volume.write(context, target); - } + if (target != volume.current && !volume.write(context, target)) return; + } else return; resetSession(); } } diff --git a/src/cloud/molberg/mgutility/AnimatedActivity.java b/src/cloud/molberg/mgutility/AnimatedActivity.java index a75e554..ddede4b 100644 --- a/src/cloud/molberg/mgutility/AnimatedActivity.java +++ b/src/cloud/molberg/mgutility/AnimatedActivity.java @@ -51,6 +51,12 @@ abstract class AnimatedActivity extends Activity { finish(); } + /** Make physical-key mappings, including Hermes push-to-talk, available on every in-app page. */ + @Override public boolean dispatchKeyEvent(android.view.KeyEvent event) { + if (KeyRemappingManager.handle(this, event)) return true; + return super.dispatchKeyEvent(event); + } + @Override public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { // The vehicle hardware Home key is delivered as a real key event when // the activity currently has focus. Forward that to the dashboard so diff --git a/src/cloud/molberg/mgutility/BootReceiver.java b/src/cloud/molberg/mgutility/BootReceiver.java index ac9b7c2..26bf91b 100644 --- a/src/cloud/molberg/mgutility/BootReceiver.java +++ b/src/cloud/molberg/mgutility/BootReceiver.java @@ -17,6 +17,10 @@ public final class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (context == null) return; String action = intent == null ? null : intent.getAction(); + // JobScheduler jobs are persisted on API 24+, but a few automotive ROMs + // clear them during an update. Re-arm the update check on every boot and + // package replacement without coupling it to trip tracking startup. + if (UpdateManager.notifyEnabled(context)) UpdateScheduler.schedule(context); if (!isStartAction(context, intent, action)) return; // Restore the daily brightness alarm across boot, unlock, updates and // screen/power broadcasts. The scheduler is a no-op when disabled. diff --git a/src/cloud/molberg/mgutility/CampingModeController.java b/src/cloud/molberg/mgutility/CampingModeController.java new file mode 100644 index 0000000..1185fa3 --- /dev/null +++ b/src/cloud/molberg/mgutility/CampingModeController.java @@ -0,0 +1,139 @@ +package cloud.molberg.mgutility; + +import android.app.Activity; +import android.graphics.Color; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.widget.FrameLayout; + +/** Applies Camping mode's in-app dim filter and touch-to-wake blackout. */ +final class CampingModeController { + private final Activity activity; + private final Handler handler = new Handler(Looper.getMainLooper()); + private FrameLayout root; + private FrameLayout dimLayer; + private boolean enabled; + private boolean blackedOut; + private boolean consumingWakeGesture; + private long lastActivityMillis; + + private final Runnable blackout = new Runnable() { + @Override public void run() { + if (root == null || !enabled) return; + int timeout = timeoutSeconds(); + long now = SystemClock.uptimeMillis(); + if (CampingModePolicy.isBlackoutDue(enabled, timeout, lastActivityMillis, now)) { + blackedOut = true; + render(); + } else { + scheduleBlackout(); + } + } + }; + + CampingModeController(Activity activity) { + this.activity = activity; + dimLayer = new FrameLayout(activity); + dimLayer.setBackgroundColor(Color.BLACK); + dimLayer.setClickable(false); + dimLayer.setFocusable(false); + dimLayer.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + } + + void attach(FrameLayout newRoot) { + if (newRoot == null) return; + handler.removeCallbacks(blackout); + root = newRoot; + ViewParent parent = dimLayer.getParent(); + if (parent instanceof ViewGroup) ((ViewGroup) parent).removeView(dimLayer); + root.addView(dimLayer, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + enabled = activity.getSharedPreferences(UiTheme.UI_PREFS, Activity.MODE_PRIVATE) + .getBoolean(CampingModePolicy.PREF_ENABLED, false); + blackedOut = false; + consumingWakeGesture = false; + lastActivityMillis = SystemClock.uptimeMillis(); + render(); + scheduleBlackout(); + } + + void setEnabled(boolean value) { + activity.getSharedPreferences(UiTheme.UI_PREFS, Activity.MODE_PRIVATE).edit() + .putBoolean(CampingModePolicy.PREF_ENABLED, value).apply(); + enabled = value; + blackedOut = false; + consumingWakeGesture = false; + lastActivityMillis = SystemClock.uptimeMillis(); + render(); + scheduleBlackout(); + } + + /** Returns true only while consuming the touch used to wake a blacked-out screen. */ + boolean onTouchEvent(MotionEvent event) { + if (!enabled || event == null) return false; + int action = event.getActionMasked(); + if (consumingWakeGesture) { + if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + consumingWakeGesture = false; + } + return true; + } + if (blackedOut) { + if (action == MotionEvent.ACTION_DOWN) { + consumingWakeGesture = true; + blackedOut = false; + lastActivityMillis = SystemClock.uptimeMillis(); + render(); + scheduleBlackout(); + } + return true; + } + if (action == MotionEvent.ACTION_DOWN) { + lastActivityMillis = SystemClock.uptimeMillis(); + scheduleBlackout(); + } + return false; + } + + void onActivityPaused() { + handler.removeCallbacks(blackout); + if (root != null && dimLayer.getParent() == root) root.removeView(dimLayer); + root = null; + blackedOut = false; + consumingWakeGesture = false; + } + + void onActivityDestroyed() { + onActivityPaused(); + } + + private int dimPercent() { + int value = activity.getSharedPreferences(UiTheme.UI_PREFS, Activity.MODE_PRIVATE) + .getInt(CampingModePolicy.PREF_DIM_PERCENT, CampingModePolicy.DEFAULT_DIM_PERCENT); + return CampingModePolicy.clampDimPercent(value); + } + + private int timeoutSeconds() { + int value = activity.getSharedPreferences(UiTheme.UI_PREFS, Activity.MODE_PRIVATE) + .getInt(CampingModePolicy.PREF_TIMEOUT_SECONDS, CampingModePolicy.DEFAULT_TIMEOUT_SECONDS); + return CampingModePolicy.clampTimeoutSeconds(value); + } + + private void scheduleBlackout() { + handler.removeCallbacks(blackout); + int seconds = timeoutSeconds(); + if (root == null || !enabled || seconds <= 0) return; + handler.postDelayed(blackout, seconds * 1000L); + } + + private void render() { + if (dimLayer == null) return; + dimLayer.setVisibility(enabled ? View.VISIBLE : View.GONE); + dimLayer.setAlpha(blackedOut ? 1f : dimPercent() / 100f); + } +} diff --git a/src/cloud/molberg/mgutility/CampingModePolicy.java b/src/cloud/molberg/mgutility/CampingModePolicy.java new file mode 100644 index 0000000..e7ec7db --- /dev/null +++ b/src/cloud/molberg/mgutility/CampingModePolicy.java @@ -0,0 +1,33 @@ +package cloud.molberg.mgutility; + +/** Pure configuration bounds and inactivity policy for Camping mode. */ +public final class CampingModePolicy { + public static final String PREF_ENABLED = "camping_mode_enabled"; + public static final String PREF_DIM_PERCENT = "camping_mode_screen_dim_percent"; + public static final String PREF_TIMEOUT_SECONDS = "camping_mode_screen_timeout_seconds"; + + public static final int DEFAULT_DIM_PERCENT = 35; + public static final int MAX_DIM_PERCENT = 90; + public static final int DEFAULT_TIMEOUT_SECONDS = 60; + public static final int MIN_TIMEOUT_SECONDS = 5; + public static final int MAX_TIMEOUT_SECONDS = 600; + + private CampingModePolicy() { } + + public static int clampDimPercent(int percent) { + return Math.max(0, Math.min(MAX_DIM_PERCENT, percent)); + } + + /** Zero disables auto-blackout; non-zero values are clamped to 5–600 seconds. */ + public static int clampTimeoutSeconds(int seconds) { + if (seconds <= 0) return 0; + return Math.max(MIN_TIMEOUT_SECONDS, Math.min(MAX_TIMEOUT_SECONDS, seconds)); + } + + public static boolean isBlackoutDue(boolean enabled, int timeoutSeconds, + long lastActivityMillis, long nowMillis) { + int timeout = clampTimeoutSeconds(timeoutSeconds); + if (!enabled || timeout == 0 || nowMillis < lastActivityMillis) return false; + return nowMillis - lastActivityMillis >= timeout * 1000L; + } +} diff --git a/src/cloud/molberg/mgutility/CampingModeSettingsActivity.java b/src/cloud/molberg/mgutility/CampingModeSettingsActivity.java new file mode 100644 index 0000000..8e26412 --- /dev/null +++ b/src/cloud/molberg/mgutility/CampingModeSettingsActivity.java @@ -0,0 +1,165 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.pm.ActivityInfo; +import android.os.Bundle; +import android.graphics.Typeface; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.CompoundButton; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.SeekBar; +import android.widget.Switch; +import android.widget.TextView; + +/** User-configurable display behavior for Camping mode. */ +public final class CampingModeSettingsActivity extends AnimatedActivity { + private TextView dimValue; + private TextView timeoutValue; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + setContentView(buildUi()); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(UiTheme.dp(this, 24), UiTheme.dp(this, 10), + UiTheme.dp(this, 24), UiTheme.dp(this, 16)); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + TextView title = UiTheme.title(this, "CAMPING MODE", 26); + header.addView(title, new LinearLayout.LayoutParams(0, UiTheme.dp(this, 56), 1f)); + Button back = UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }); + header.addView(back, new LinearLayout.LayoutParams(UiTheme.dp(this, 112), UiTheme.dp(this, 48))); + root.addView(header); + + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + LinearLayout content = new LinearLayout(this); + content.setOrientation(LinearLayout.VERTICAL); + scroll.addView(content); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1f)); + + addSection(content, "Mode", "Changes apply while MG Utility's dashboard is in the foreground."); + Switch enabled = new Switch(this); + enabled.setText("Enable Camping mode"); + enabled.setTextSize(15); + enabled.setTextColor(UiTheme.TEXT); + enabled.setPadding(UiTheme.dp(this, 10), UiTheme.dp(this, 6), UiTheme.dp(this, 10), UiTheme.dp(this, 6)); + enabled.setChecked(prefs().getBoolean(CampingModePolicy.PREF_ENABLED, false)); + enabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override public void onCheckedChanged(CompoundButton button, boolean checked) { + prefs().edit().putBoolean(CampingModePolicy.PREF_ENABLED, checked).apply(); + } + }); + content.addView(enabled, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 56))); + + addSection(content, "Screen lighting", "Add a black filter on top of the normal brightness control."); + int initialDim = CampingModePolicy.clampDimPercent(prefs().getInt( + CampingModePolicy.PREF_DIM_PERCENT, CampingModePolicy.DEFAULT_DIM_PERCENT)); + dimValue = UiTheme.text(this, dimLabel(initialDim), 13, UiTheme.TEXT, Typeface.BOLD); + content.addView(dimValue, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 30))); + SeekBar dim = new SeekBar(this); + dim.setMax(CampingModePolicy.MAX_DIM_PERCENT); + dim.setProgress(initialDim); + dim.setContentDescription("Extra screen dim filter percentage"); + content.addView(dim, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 52))); + dim.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + int value = CampingModePolicy.clampDimPercent(progress); + dimValue.setText(dimLabel(value)); + if (fromUser) prefs().edit().putInt(CampingModePolicy.PREF_DIM_PERCENT, value).apply(); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + + addSection(content, "Screen blackout", "After inactivity the app covers the display in black. Tap once to wake; the wake tap is consumed so it won't activate a control."); + int timeout = CampingModePolicy.clampTimeoutSeconds(prefs().getInt( + CampingModePolicy.PREF_TIMEOUT_SECONDS, CampingModePolicy.DEFAULT_TIMEOUT_SECONDS)); + timeoutValue = UiTheme.text(this, timeoutLabel(timeout), 13, UiTheme.TEXT, Typeface.BOLD); + content.addView(timeoutValue, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 30))); + SeekBar inactivity = new SeekBar(this); + inactivity.setMax(CampingModePolicy.MAX_TIMEOUT_SECONDS / 5); + inactivity.setProgress(timeout / 5); + inactivity.setContentDescription("Screen blackout inactivity timeout in seconds; zero disables it"); + content.addView(inactivity, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 52))); + inactivity.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + int seconds = CampingModePolicy.clampTimeoutSeconds(progress * 5); + timeoutValue.setText(timeoutLabel(seconds)); + if (fromUser) prefs().edit().putInt(CampingModePolicy.PREF_TIMEOUT_SECONDS, seconds).apply(); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + TextView screenNote = UiTheme.text(this, + "This is a touch-responsive in-app blackout, not a verified hardware power-off of the head-unit display.", + 11, UiTheme.MUTED, Typeface.NORMAL); + content.addView(screenNote, new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT)); + + addSection(content, "Exterior lights", "Headlights and rear lights are left unchanged."); + TextView lights = UiTheme.text(this, + "The current app catalog does not expose a verified command to turn exterior headlights or tail lights off. Related vehicle settings are read-only/trim-dependent, so Camping mode will not send lighting commands.", + 13, UiTheme.TEXT, Typeface.NORMAL); + lights.setPadding(UiTheme.dp(this, 12), UiTheme.dp(this, 10), + UiTheme.dp(this, 12), UiTheme.dp(this, 10)); + lights.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + content.addView(lights, new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT)); + + addSection(content, "Climate", "Heating and temperature automation is planned for a later step."); + TextView climate = UiTheme.text(this, + "Camping mode does not currently start or change HVAC, seat heating, or temperature settings.", + 13, UiTheme.MUTED, Typeface.NORMAL); + content.addView(climate, new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT)); + return root; + } + + private void addSection(LinearLayout parent, String title, String subtitle) { + TextView heading = UiTheme.label(this, title.toUpperCase(java.util.Locale.US)); + heading.setPadding(0, UiTheme.dp(this, 14), 0, UiTheme.dp(this, 3)); + parent.addView(heading, new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT)); + TextView hint = UiTheme.text(this, subtitle, 11, UiTheme.MUTED, Typeface.NORMAL); + parent.addView(hint, new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT)); + } + + private SharedPreferences prefs() { + return getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + } + + private static String dimLabel(int percent) { + return "Extra dim filter • " + percent + "%"; + } + + private static String timeoutLabel(int seconds) { + return seconds == 0 ? "Blackout timeout • Never" : + "Blackout timeout • " + seconds + " seconds"; + } +} diff --git a/src/cloud/molberg/mgutility/ConfigStore.java b/src/cloud/molberg/mgutility/ConfigStore.java index 127d167..aa63991 100644 --- a/src/cloud/molberg/mgutility/ConfigStore.java +++ b/src/cloud/molberg/mgutility/ConfigStore.java @@ -20,11 +20,13 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import cloud.molberg.mgutility.plugin.PluginRepository; /** Centralized preference store and JSON export/import helper. */ public final class ConfigStore { public static final String STORE_NAME = "mg_config"; public static final int SCHEMA_VERSION = 1; + public static final String PLUGIN_REPOSITORIES_KEY = "plugin_repositories"; /** Pure-JSON variant of {@link #exportJson()} for tests. */ public static String exportJson(Map values) throws JSONException { @@ -102,6 +104,38 @@ public final class ConfigStore { } public SharedPreferences sharedPreferences() { return prefs; } + /** Persist marketplace repositories as a JSON array in the central config store. */ + public synchronized List pluginRepositories() { + ArrayList result = new ArrayList(); + String raw = prefs.getString(PLUGIN_REPOSITORIES_KEY, ""); + try { + JSONArray array = raw.length() == 0 ? new JSONArray() : new JSONArray(raw); + for (int i = 0; i < array.length(); i++) { + JSONObject value = array.optJSONObject(i); + if (value == null) continue; + String id = value.optString("id", ""); + String url = value.optString("url", ""); + if (id.length() == 0 || url.length() == 0) continue; + result.add(new PluginRepository(id, value.optString("name", id), url, + value.optBoolean("enabled", true), value.optBoolean("official", false))); + } + } catch (Exception ignored) { } + if (result.isEmpty()) result.add(PluginRepository.officialPlaceholder()); + return result; + } + + public synchronized void savePluginRepositories(List repositories) { + JSONArray array = new JSONArray(); + if (repositories != null) for (PluginRepository repository : repositories) { + JSONObject value = new JSONObject(); + try { + value.put("id", repository.id); value.put("name", repository.name); value.put("url", repository.url); + value.put("enabled", repository.enabled); value.put("official", repository.official); array.put(value); + } catch (JSONException ignored) { } + } + prefs.edit().putString(PLUGIN_REPOSITORIES_KEY, array.toString()).apply(); + } + /** Export all settings to a versioned, diffable JSON document. */ public String exportJson() throws JSONException { // Existing screens in older releases still write their legacy preference @@ -193,7 +227,7 @@ public final class ConfigStore { public static List sections() { ArrayList sections = new ArrayList(); Collections.addAll(sections, "Appearance", "Pinned apps", "Home screen", "Trip tracker", - "Audio", "Charging automation", "Vehicle defaults", "Key remapping", "Map cache", "0–100 leaderboard"); + "Audio", "Charging automation", "Vehicle defaults", "Key remapping", "Map cache", "0–100 leaderboard", "Plugins"); return Collections.unmodifiableList(sections); } @@ -210,6 +244,7 @@ public final class ConfigStore { if (key.startsWith("vehicle_") || key.equals("drive_mode") || key.equals("regenerative_level")) return "Vehicle defaults"; if (key.startsWith("key_") || key.contains("remap")) return "Key remapping"; if (key.startsWith("map_") || key.contains("tile")) return "Map cache"; + if (key.equals(PLUGIN_REPOSITORIES_KEY) || key.startsWith("plugin_")) return "Plugins"; return "Other"; } diff --git a/src/cloud/molberg/mgutility/ControlPanelCatalog.java b/src/cloud/molberg/mgutility/ControlPanelCatalog.java index 10043df..b8de87d 100644 --- a/src/cloud/molberg/mgutility/ControlPanelCatalog.java +++ b/src/cloud/molberg/mgutility/ControlPanelCatalog.java @@ -19,6 +19,8 @@ public final class ControlPanelCatalog { public static final String PREF_OPACITY = "home_control_panel_opacity"; public static final String PREF_ORDER = "home_control_panel_order"; public static final String PREF_VALUES = "home_control_panel_values"; + private static final String PREF_CATALOG_VERSION = "home_control_panel_catalog_version"; + private static final int CATALOG_VERSION = 1; public enum Kind { SLIDER, TOGGLE, SHORTCUT } @@ -41,6 +43,13 @@ public final class ControlPanelCatalog { new Control("voice_volume", "Voice volume", "voice", Kind.SLIDER, "Levels"), new Control("bluetooth", "Bluetooth", "bluetooth", Kind.TOGGLE, "System"), new Control("wifi", "Wi-Fi", "wifi", Kind.TOGGLE, "System"), + new Control("auto_brightness", "Automatic brightness", "brightness", Kind.TOGGLE, "MG Utility"), + new Control("liquid_sound_balance", "Liquid Sound Balance", "balance", Kind.TOGGLE, "MG Utility"), + new Control("adaptive_audio", "Adaptive audio leveling", "media", Kind.TOGGLE, "MG Utility"), + new Control("camping_mode", "Camping mode", "camping", Kind.TOGGLE, "MG Utility"), + new Control("saic_launcher", "Official SAIC Launcher", "home", Kind.SHORTCUT, "System"), + new Control("software_update", "Software Update", "update", Kind.SHORTCUT, "MG Utility"), + new Control("vehicle_settings", "Vehicle settings", "settings", Kind.SHORTCUT, "MG Utility"), new Control("energy", "Energy dashboard", "energy", Kind.SHORTCUT, "MG Utility"), new Control("charging", "Charging automation", "charging", Kind.SHORTCUT, "MG Utility"), new Control("settings", "Settings", "settings", Kind.SHORTCUT, "MG Utility") @@ -48,7 +57,8 @@ public final class ControlPanelCatalog { private static final String[] DEFAULT_ORDER = { "brightness", "media_volume", "phone_volume", "voice_volume", - "bluetooth", "wifi" + "bluetooth", "wifi", "auto_brightness", "liquid_sound_balance", "adaptive_audio", "camping_mode", + "saic_launcher", "software_update", "vehicle_settings" }; public static List all() { return ALL; } @@ -75,9 +85,23 @@ public final class ControlPanelCatalog { } } } catch (Exception ignored) { } - // A partially written or older arrangement gets any newly-added controls - // appended, while a first install starts with the official MG defaults. - if (raw.length() == 0) result.addAll(defaultOrder()); + // First install gets the official defaults. Existing non-empty layouts + // receive this catalog's newly-added Camping mode toggle once; a user's + // intentionally empty panel stays empty. + int catalogVersion = prefs.getInt(PREF_CATALOG_VERSION, 0); + if (catalogVersion < CATALOG_VERSION) { + if (raw.length() == 0) result.addAll(defaultOrder()); + else if (!result.isEmpty() && seen.add("camping_mode")) result.add("camping_mode"); + SharedPreferences.Editor editor = prefs.edit().putInt(PREF_CATALOG_VERSION, CATALOG_VERSION); + if (raw.length() == 0 || !result.isEmpty()) { + JSONArray migrated = new JSONArray(); + for (String id : result) migrated.put(id); + editor.putString(PREF_ORDER, migrated.toString()); + } + editor.apply(); + } else if (raw.length() == 0) { + result.addAll(defaultOrder()); + } return result; } @@ -85,7 +109,8 @@ public final class ControlPanelCatalog { JSONArray array = new JSONArray(); Set seen = new HashSet(); if (ids != null) for (String id : ids) if (find(id) != null && seen.add(id)) array.put(id); - prefs(context).edit().putString(PREF_ORDER, array.toString()).apply(); + prefs(context).edit().putString(PREF_ORDER, array.toString()) + .putInt(PREF_CATALOG_VERSION, CATALOG_VERSION).apply(); } public static void restoreDefaults(Context context) { diff --git a/src/cloud/molberg/mgutility/ControlPanelOverlay.java b/src/cloud/molberg/mgutility/ControlPanelOverlay.java index 951410a..da87767 100644 --- a/src/cloud/molberg/mgutility/ControlPanelOverlay.java +++ b/src/cloud/molberg/mgutility/ControlPanelOverlay.java @@ -604,10 +604,10 @@ final class ControlPanelOverlay extends FrameLayout { TextView name = UiTheme.text(activity, control.label, 12, UiTheme.TEXT, Typeface.BOLD); name.setGravity(Gravity.CENTER); - name.setSingleLine(true); + name.setMaxLines(2); name.setEllipsize(TextUtils.TruncateAt.END); name.setPadding(0, UiTheme.dp(activity, 8), 0, 0); - tile.addView(name, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 28))); + tile.addView(name, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 48))); final Runnable render = new Runnable() { @Override public void run() { @@ -615,6 +615,7 @@ final class ControlPanelOverlay extends FrameLayout { ringView.setOn(current); icon.setColor(current ? UiTheme.CYAN_BRIGHT : UiTheme.MUTED); name.setTextColor(current ? UiTheme.TEXT : UiTheme.MUTED); + tile.setContentDescription(control.label + (current ? ", on" : ", off")); } }; render.run(); @@ -674,42 +675,30 @@ final class ControlPanelOverlay extends FrameLayout { } } - /** Vector-style control icons. Avoids font glyph fallbacks and matches the official panel. */ - private static final class ControlIconView extends View { - private final String iconKey; + /** Vector-style control icons use the shared Material vector pack. */ + private static final class ControlIconView extends android.widget.ImageView { private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - private int tint = UiTheme.MUTED; - ControlIconView(Context context, String iconKey) { super(context); - this.iconKey = iconKey; - paint.setStyle(Paint.Style.FILL); - paint.setStrokeCap(Paint.Cap.ROUND); - paint.setStrokeJoin(Paint.Join.ROUND); + String name = "balance".equals(iconKey) ? "graphic_eq" + : "camping".equals(iconKey) ? "nightlight" + : "home".equals(iconKey) ? "home" + : "update".equals(iconKey) ? "system_update" + : "media".equals(iconKey) ? "music_note" + : "voice".equals(iconKey) ? "mic" + : "energy".equals(iconKey) ? "bolt" + : "charging".equals(iconKey) ? "battery_charging_full" + : "brightness".equals(iconKey) ? "brightness_6" + : "phone".equals(iconKey) ? "call" + : iconKey; + int resource = context.getResources().getIdentifier("ic_" + name, "drawable", context.getPackageName()); + setImageResource(resource == 0 ? R.drawable.ic_help : resource); + setColorFilter(UiTheme.MUTED); + setScaleType(android.widget.ImageView.ScaleType.FIT_CENTER); + setContentDescription(name.replace('_', ' ')); } - void setColor(int color) { - if (tint != color) { - tint = color; - invalidate(); - } - } - - @Override protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - paint.setColor(tint); - float w = getWidth(), h = getHeight(); - if ("bluetooth".equals(iconKey)) drawBluetooth(canvas, w, h); - else if ("wifi".equals(iconKey)) drawWifi(canvas, w, h); - else if ("brightness".equals(iconKey)) drawBrightness(canvas, w, h); - else if ("media".equals(iconKey)) drawMedia(canvas, w, h); - else if ("phone".equals(iconKey)) drawPhone(canvas, w, h); - else if ("voice".equals(iconKey)) drawVoice(canvas, w, h); - else if ("energy".equals(iconKey)) drawEnergy(canvas, w, h); - else if ("charging".equals(iconKey)) drawCharging(canvas, w, h); - else if ("settings".equals(iconKey)) drawSettings(canvas, w, h); - else drawGlyph(canvas, w, h, "?"); - } + void setColor(int color) { setColorFilter(color); } private void drawBluetooth(Canvas canvas, float w, float h) { // Iconic Bluetooth rune: two crossing strokes meeting at the centre. @@ -865,6 +854,12 @@ final class ControlPanelOverlay extends FrameLayout { private boolean readToggleState(String id) { Context context = activity.getApplicationContext(); + if ("camping_mode".equals(id)) return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(CampingModePolicy.PREF_ENABLED, false); + if ("auto_brightness".equals(id)) return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false); + if ("liquid_sound_balance".equals(id)) return LiquidSoundBalanceManager.config(context).enabled; + if ("adaptive_audio".equals(id)) return AdaptiveAudioLevelingManager.config(context).enabled; MgServiceBridge bridge = MgServiceBridge.get(); try { bridge.ensureBound(activity); } catch (Exception ignored) { } if ("bluetooth".equals(id)) { @@ -893,6 +888,41 @@ final class ControlPanelOverlay extends FrameLayout { catch (Exception e) { current = false; } final boolean target = !current; + if ("camping_mode".equals(id)) { + if (activity instanceof MainActivity) { + ((MainActivity) activity).setCampingModeEnabled(target); + } else { + activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE).edit() + .putBoolean(CampingModePolicy.PREF_ENABLED, target).apply(); + } + refreshContent(); + return; + } + + if ("auto_brightness".equals(id)) { + activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE).edit() + .putBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, target) + .remove(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL).apply(); + BrightnessScheduler.rearm(activity); + refreshContent(); + return; + } + if ("liquid_sound_balance".equals(id)) { + LiquidSoundBalanceManager.Config config = LiquidSoundBalanceManager.config(activity); + LiquidSoundBalanceManager.save(activity, target, config.thresholdKphPerSecond, + config.powerPercent, config.bounce, config.horizontalSway); + refreshContent(); + return; + } + if ("adaptive_audio".equals(id)) { + AdaptiveAudioLevelingManager.Config config = AdaptiveAudioLevelingManager.config(activity); + AdaptiveAudioLevelingManager.save(activity, target, config.level1AudioPercent, + config.level1SpeedKph, config.level2AudioPercent, config.level2SpeedKph, + config.level3AudioPercent, config.level3SpeedKph); + refreshContent(); + return; + } + if ("bluetooth".equals(id)) { MgServiceBridge bridge = MgServiceBridge.get(); try { bridge.ensureBound(activity); } catch (Exception ignored) { } @@ -982,6 +1012,14 @@ final class ControlPanelOverlay extends FrameLayout { intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); } else if ("wifi".equals(id)) { intent = new Intent(Settings.ACTION_WIFI_SETTINGS); + } else if ("auto_brightness".equals(id)) { + intent = new Intent(activity, SettingsActivity.class).putExtra(SettingsActivity.EXTRA_CATEGORY, SettingsActivity.CATEGORY_DASHBOARD); + } else if ("liquid_sound_balance".equals(id)) { + intent = new Intent(activity, LiquidSoundBalanceActivity.class); + } else if ("adaptive_audio".equals(id)) { + intent = new Intent(activity, AdaptiveAudioLevelingActivity.class); + } else if ("camping_mode".equals(id)) { + intent = new Intent(activity, CampingModeSettingsActivity.class); } if (intent == null) return; try { @@ -1026,10 +1064,24 @@ final class ControlPanelOverlay extends FrameLayout { } private void launchShortcut(String id) { + if ("saic_launcher".equals(id)) { + Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME) + .setClassName("com.saicmotor.hmi.launcher", "com.saicmotor.hmi.launcher.ui.MainActivity") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + activity.startActivity(intent); + closePanel(); + } catch (Exception e) { + Toast.makeText(activity, "Official SAIC Launcher unavailable", Toast.LENGTH_LONG).show(); + } + return; + } Class target = null; if ("energy".equals(id)) target = EnergyActivity.class; else if ("charging".equals(id)) target = ChargingActivity.class; else if ("settings".equals(id)) target = ControlPanelSettingsActivity.class; + else if ("software_update".equals(id)) target = UpdateActivity.class; + else if ("vehicle_settings".equals(id)) target = VehicleSettingsActivity.class; if (target == null) return; try { Intent intent = new Intent(activity, target); diff --git a/src/cloud/molberg/mgutility/ControlPanelSettingsActivity.java b/src/cloud/molberg/mgutility/ControlPanelSettingsActivity.java index 20b4154..cebc9e1 100644 --- a/src/cloud/molberg/mgutility/ControlPanelSettingsActivity.java +++ b/src/cloud/molberg/mgutility/ControlPanelSettingsActivity.java @@ -277,7 +277,7 @@ public final class ControlPanelSettingsActivity extends AnimatedActivity { private void confirmRestoreDefaults() { UiTheme.dialog(this) .setTitle("Restore control panel defaults?") - .setMessage("This removes your custom ordering and restores the original brightness, volume, system, and vehicle controls.") + .setMessage("This removes your custom ordering and restores the default brightness, volume, system, vehicle, and Camping mode controls.") .setNegativeButton("CANCEL", null) .setPositiveButton("RESTORE", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(android.content.DialogInterface dialog, int which) { diff --git a/src/cloud/molberg/mgutility/CustomThemeEditActivity.java b/src/cloud/molberg/mgutility/CustomThemeEditActivity.java index cea9c08..f3fe83c 100644 --- a/src/cloud/molberg/mgutility/CustomThemeEditActivity.java +++ b/src/cloud/molberg/mgutility/CustomThemeEditActivity.java @@ -25,7 +25,7 @@ import java.util.Locale; /** * Live preview editor for a custom theme. Two halves: - * - LEFT: the 14 palette roles. Tap a row to pick a new colour. + * - LEFT: six semantic color groups. Tap a row to pick a new colour. * - RIGHT: a scrollable preview of every themed component in the app. * * Picking a colour pushes the new palette into UiTheme in-memory (no SharedPreferences @@ -157,12 +157,49 @@ public final class CustomThemeEditActivity extends AnimatedActivity { TextView heading = UiTheme.label(this, "COLORS"); heading.setPadding(6, 4, 0, 6); leftContent.addView(heading, new LinearLayout.LayoutParams(-1, 30)); - for (int i = 0; i < keys.length; i++) { + for (int i = 0; i < labels.length; i++) { final int index = i; leftContent.addView(colorRow(i), new LinearLayout.LayoutParams(-1, 64)); } } + private int semanticColor(int index) { return semanticColor(palette, index); } + + private static int semanticColor(int[] colors, int index) { + switch (index) { + case 0: return colors[6]; + case 1: return colors[8]; + case 2: return colors[0]; + case 3: return colors[13]; + case 4: return colors[10]; + default: return colors[8]; + } + } + + private static void applySemanticColor(int[] colors, int index, int color) { + switch (index) { + case 0: colors[6] = color; colors[7] = color; colors[11] = color; colors[12] = color; break; + case 1: colors[8] = color; colors[9] = color; break; + case 2: + int red = android.graphics.Color.red(colors[0]); + int green = android.graphics.Color.green(colors[0]); + int blue = android.graphics.Color.blue(colors[0]); + int dr = android.graphics.Color.red(color) - red; + int dg = android.graphics.Color.green(color) - green; + int db = android.graphics.Color.blue(color) - blue; + for (int i = 0; i < 4; i++) colors[i] = android.graphics.Color.rgb( + clamp(android.graphics.Color.red(colors[i]) + dr), + clamp(android.graphics.Color.green(colors[i]) + dg), + clamp(android.graphics.Color.blue(colors[i]) + db)); + break; + case 3: colors[13] = color; break; + case 4: colors[10] = color; break; + case 5: colors[8] = color; colors[9] = color; break; + } + } + + private static int clamp(int channel) { return Math.max(0, Math.min(255, channel)); } + private View colorRow(int index) { LinearLayout row = new LinearLayout(this); row.setGravity(Gravity.CENTER_VERTICAL); @@ -170,12 +207,13 @@ public final class CustomThemeEditActivity extends AnimatedActivity { row.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); TextView label = UiTheme.text(this, labels[index], 14, UiTheme.TEXT, Typeface.NORMAL); row.addView(label, new LinearLayout.LayoutParams(0, 56, 1)); - TextView hex = UiTheme.text(this, String.format(Locale.US, "#%06X", palette[index] & 0xFFFFFF), + int color = semanticColor(index); + TextView hex = UiTheme.text(this, String.format(Locale.US, "#%06X", color & 0xFFFFFF), 12, UiTheme.MUTED, Typeface.NORMAL); hex.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); row.addView(hex, new LinearLayout.LayoutParams(110, 56)); View swatch = new View(this); - swatch.setBackground(UiTheme.surface(palette[index], 0)); + swatch.setBackground(UiTheme.surface(color, 0)); row.addView(swatch, new LinearLayout.LayoutParams(40, 40)); row.setClickable(true); row.setOnClickListener(new View.OnClickListener() { @@ -303,7 +341,7 @@ public final class CustomThemeEditActivity extends AnimatedActivity { private void editColor(final int index) { final ColorPickerView wheel = new ColorPickerView(this); - wheel.setColor(palette[index]); + wheel.setColor(semanticColor(index)); final TextView hex = UiTheme.text(this, String.format(Locale.US, "#%06X", wheel.getColor() & 0xFFFFFF), 12, UiTheme.MUTED, Typeface.NORMAL); hex.setGravity(Gravity.CENTER); @@ -328,9 +366,9 @@ public final class CustomThemeEditActivity extends AnimatedActivity { } private void applyColor(int index, int color) { - palette[index] = color; + applySemanticColor(palette, index, color); UiTheme.applyLive(palette); - RecentColors.record(this, keys[index], color); + RecentColors.record(this, labels[index].toLowerCase(Locale.US), color); dirty = true; // Replace the left row and rebuild the right panel so its components re-tint. View row = leftContent.getChildAt(index + 1); // +1 for the heading row diff --git a/src/cloud/molberg/mgutility/DebugActivity.java b/src/cloud/molberg/mgutility/DebugActivity.java index d3cdcac..ea66517 100644 --- a/src/cloud/molberg/mgutility/DebugActivity.java +++ b/src/cloud/molberg/mgutility/DebugActivity.java @@ -19,6 +19,9 @@ import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Locale; + +import org.json.JSONObject; /** Advanced diagnostic information kept away from the everyday vehicle dashboard. */ public final class DebugActivity extends AnimatedActivity { @@ -93,6 +96,39 @@ public final class DebugActivity extends AnimatedActivity { note.setGravity(Gravity.CENTER_VERTICAL); root.addView(note, new LinearLayout.LayoutParams(-1, 30)); + Button micDiag = UiTheme.button(this, "TEMP: MIC ROUTE TEST", new View.OnClickListener() { + @Override public void onClick(View v) { + startActivity(new android.content.Intent(DebugActivity.this, MicRouteDiagnosticActivity.class)); + } + }, false); + root.addView(micDiag, new LinearLayout.LayoutParams(-1, 50)); + + Button uploadDiagnostics = UiTheme.button(this, "UPLOAD DIAGNOSTICS", new View.OnClickListener() { + @Override public void onClick(View v) { + v.setEnabled(false); + new Thread(new Runnable() { + @Override public void run() { + DiagnosticsClient.uploadDiagnostics(DebugActivity.this, collectUploadReport(), new DiagnosticsClient.Callback() { + @Override public void complete(final String message) { + runOnUiThread(new Runnable() { + @Override public void run() { + v.setEnabled(true); + android.widget.Toast.makeText(DebugActivity.this, message, android.widget.Toast.LENGTH_LONG).show(); + } + }); + } + }); + } + }, "mg-diagnostics-collect").start(); + } + }, false); + root.addView(uploadDiagnostics, new LinearLayout.LayoutParams(-1, 50)); + TextView uploadNotice = UiTheme.text(this, + "UPLOAD IS MANUAL: sends a random per-install car ID, head-unit/app profile, read-only vehicle-service availability, supported feature list, filtered build properties, and up to 150 app-owned warnings/errors. No VIN, hardware serial, or live vehicle readings are uploaded.", + 11, UiTheme.MUTED, android.graphics.Typeface.NORMAL); + uploadNotice.setPadding(4, 5, 4, 8); + root.addView(uploadNotice, new LinearLayout.LayoutParams(-1, -2)); + LinearLayout controls = new LinearLayout(this); controls.setGravity(Gravity.CENTER_VERTICAL); controls.setPadding(14, 0, 10, 0); @@ -187,8 +223,72 @@ public final class DebugActivity extends AnimatedActivity { return result.toString(); } + private JSONObject collectUploadReport() { + JSONObject report = VehicleDiagnosticsCollector.collect(this); + try { report.put("systemProperties", readSafeProperties()); } catch (Exception ignored) { } + try { report.put("appWarningsAndErrors", readOwnAppWarnings()); } catch (Exception ignored) { } + return report; + } + + /** Collect only non-unique product/build properties; never include serial-like keys or all-props mode. */ + private String readSafeProperties() { + StringBuilder result = new StringBuilder(); + try { + Process process = Runtime.getRuntime().exec("getprop"); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + while ((line = reader.readLine()) != null && result.length() < 10000) { + int split = line.indexOf("]: ["); + if (split < 2 || !line.startsWith("[")) continue; + String key = line.substring(1, split).toLowerCase(Locale.US); + if (!(key.startsWith("ro.product.") || key.startsWith("ro.build.") || key.startsWith("ro.board.") || + key.startsWith("ro.hardware.") || key.startsWith("ro.vehicle."))) continue; + if (key.contains("serial") || key.contains("imei") || key.contains("android_id") || key.contains("mac") || key.contains("vin")) continue; + String value = line.substring(split + 4).replaceAll("\\]$", ""); + value = redactSensitiveText(value); + result.append(key).append(" = ").append(value, 0, Math.min(value.length(), 500)).append('\n'); + } + reader.close(); + process.destroy(); + } catch (Exception ignored) { } + return result.length() == 0 ? "No whitelisted build properties available." : result.toString(); + } + + /** Own-process warnings only; bounded, allowlisted by tag, and redacted before upload. */ + private String readOwnAppWarnings() { + StringBuilder result = new StringBuilder(); + try { + String pid = String.valueOf(android.os.Process.myPid()); + Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "brief", "--pid=" + pid, "-t", "250", "*:W"}); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + int kept = 0; + while ((line = reader.readLine()) != null && kept < 150 && result.length() < 14000) { + if (!(line.startsWith("W/") || line.startsWith("E/"))) continue; + boolean relevant = line.contains("/MGDiagnostics") || line.contains("/MgServiceBridge") || + line.contains("/VehicleDataProvider") || line.contains("/VehicleSettings") || + line.contains("/EnergyActivity") || line.contains("/TripTrackingService") || + line.contains("/BootReceiver") || line.contains("/AndroidRuntime"); + if (!relevant) continue; + result.append(redactSensitiveText(line)).append('\n'); + kept++; + } + reader.close(); + process.destroy(); + } catch (Exception ignored) { } + return result.length() == 0 ? "No matching app warnings/errors available (or log access is restricted)." : result.toString(); + } + + private String redactSensitiveText(String value) { + String safe = value.replaceAll("(?i)((?:authorization|access[_-]?token|refresh[_-]?token|token|password|secret|api[_-]?key|vin|serial(?:number)?|imei|imsi|android[_ ]?id|mac(?: address)?)\\s*[:=]\\s*)[^\\s,;]+", "$1[REDACTED]"); + safe = safe.replaceAll("(?i)bearer\\s+[^\\s]+", "Bearer [REDACTED]"); + return safe.replaceAll("(?= 200 && status < 300) prefs.edit().putString("last_fingerprint", build + ":" + version).apply(); + } catch (Exception error) { Log.w(TAG, "Startup compatibility report failed", error); } + finally { if (c != null) c.disconnect(); } + } }, "mg-startup-analytics").start(); + } + + private static String getAppVersion(Context context) { + try { String value = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; return value == null ? "unknown" : value; } + catch (Exception ignored) { return "unknown"; } + } + + /** Random app-install-scoped identifier; never derived from VIN or hardware IDs. */ + public static String getVehicleId(Context context) { + synchronized (VEHICLE_ID_LOCK) { + SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String id = prefs.getString(VEHICLE_ID_KEY, ""); + try { UUID.fromString(id); return id; } catch (Exception ignored) { } + id = UUID.randomUUID().toString(); + prefs.edit().putString(VEHICLE_ID_KEY, id).commit(); + return id; + } + } + + public static void queueCrash(Context context, Throwable error) { + if (error == null) return; + try { + JSONObject report = new JSONObject(); + report.put("vehicleId", getVehicleId(context)); + report.put("appVersion", getAppVersion(context)); + report.put("platform", "android-" + Build.VERSION.SDK_INT); + report.put("manufacturer", Build.MANUFACTURER); report.put("carModel", Build.MODEL); + report.put("carBuild", Build.FINGERPRINT); report.put("exceptionType", error.getClass().getName()); + report.put("message", error.getMessage() == null ? "" : error.getMessage()); + java.io.StringWriter trace = new java.io.StringWriter(); error.printStackTrace(new java.io.PrintWriter(trace)); + report.put("stack", trace.toString()); + context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("pending_crash", report.toString()).commit(); + } catch (Exception ignored) { } + } + + public static void queueCrash(Context context, String type, String message, String stack) { + try { + JSONObject report = new JSONObject(); + report.put("vehicleId", getVehicleId(context)); + report.put("appVersion", getAppVersion(context)); + report.put("platform", "android-" + Build.VERSION.SDK_INT); + report.put("manufacturer", Build.MANUFACTURER); report.put("carModel", Build.MODEL); + report.put("carBuild", Build.FINGERPRINT); report.put("exceptionType", type); + report.put("message", message == null ? "" : message); + report.put("stack", stack == null ? "" : stack); + context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("pending_crash", report.toString()).commit(); + } catch (Exception ignored) { } + } + + public static void reportPendingCrash(final Context context) { + SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + reportPendingCrash(context, prefs.getString("upload_url", "")); + } + + private static void reportPendingCrash(final Context context, String endpoint) { + final SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + final String pending = prefs.getString("pending_crash", ""); + if (pending.isEmpty() || endpoint == null || endpoint.isEmpty()) return; + final String base = endpoint.endsWith("/") ? endpoint : endpoint + "/"; + new Thread(new Runnable() { @Override public void run() { + HttpURLConnection c = null; + try { + c = (HttpURLConnection) new URL(base + "v1/crashes").openConnection(); + c.setConnectTimeout(5000); c.setReadTimeout(5000); c.setRequestMethod("POST"); c.setDoOutput(true); + c.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + try (OutputStream out = c.getOutputStream()) { out.write(pending.getBytes(StandardCharsets.UTF_8)); } + int status = c.getResponseCode(); if (status >= 200 && status < 300) prefs.edit().remove("pending_crash").apply(); + } catch (Exception error) { Log.w(TAG, "Crash report upload failed", error); } + finally { if (c != null) c.disconnect(); } + } }, "mg-crash-report").start(); + } + + public static void uploadDiagnostics(final Context context, final JSONObject report, final Callback callback) { + final SharedPreferences p = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + if (!p.getBoolean("enabled", false) || p.getString("upload_url", "").isEmpty()) { + callback.complete("Diagnostics upload is not enabled in the published client config."); return; + } + new Thread(new Runnable() { @Override public void run() { + HttpURLConnection c = null; + try { + String endpoint = p.getString("upload_url", ""); + if (!endpoint.endsWith("/")) endpoint += "/"; + c = (HttpURLConnection) new URL(endpoint + "v1/events").openConnection(); + c.setConnectTimeout(8000); c.setReadTimeout(8000); c.setRequestMethod("POST"); + c.setDoOutput(true); c.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + JSONObject payload = new JSONObject(); + String version = "unknown"; + try { version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (Exception ignored) {} + payload.put("appVersion", version == null ? "unknown" : version); + payload.put("platform", "android-" + Build.VERSION.SDK_INT); + payload.put("product", "mg-utility"); + payload.put("category", "user_diagnostic_upload"); + payload.put("message", "User requested diagnostics upload"); + payload.put("vehicleId", report.optString("vehicleId", "")); + payload.put("appProfile", report.optString("appProfile", "")); + payload.put("details", report.toString()); + byte[] bytes = payload.toString().getBytes(StandardCharsets.UTF_8); + try (OutputStream out = c.getOutputStream()) { out.write(bytes); } + int status = c.getResponseCode(); + callback.complete(status >= 200 && status < 300 ? "Diagnostics uploaded." : "Upload failed (HTTP " + status + ")."); + } catch (Exception error) { Log.w(TAG, "Diagnostics upload failed", error); callback.complete("Upload failed: " + error.getClass().getSimpleName()); } + finally { if (c != null) c.disconnect(); } + } }, "mg-diagnostics-upload").start(); + } + + private static String read(InputStream in) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[2048]; int n; + while ((n = in.read(b)) != -1) { if (out.size() + n > 65536) throw new IllegalStateException("response too large"); out.write(b, 0, n); } + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/src/cloud/molberg/mgutility/EnergyActivity.java b/src/cloud/molberg/mgutility/EnergyActivity.java index ad87039..ea9ea12 100644 --- a/src/cloud/molberg/mgutility/EnergyActivity.java +++ b/src/cloud/molberg/mgutility/EnergyActivity.java @@ -291,6 +291,29 @@ public class EnergyActivity extends AnimatedActivity { dischargingMinutes); } + /** Read-only capability probe; returns availability flags, never vehicle values. */ + Bundle capabilities(){ + Bundle out=new Bundle(); + out.putBoolean("vehiclecharging.bound",alive(charging)); + out.putBoolean("vehiclecondition.bound",alive(condition)); + out.putBoolean("vehiclesetting.bound",alive(setting)); + Sample sample=read(); + out.putBoolean("signal.stateOfCharge",sample!=null&&finite(sample.soc)); + out.putBoolean("signal.range",sample!=null&&sample.range>=0); + out.putBoolean("signal.speed",sample!=null&&finite(sample.speed)); + out.putBoolean("signal.batteryVoltage",sample!=null&&finite(sample.volts)&&sample.volts>0f); + out.putBoolean("signal.energyConsumption",sample!=null&&finite(sample.total)&&sample.total>=0f); + out.putBoolean("signal.chargingStatus",sample!=null&&sample.charging>=0); + out.putBoolean("signal.dischargingStatus",sample!=null&&sample.discharging>=0); + out.putBoolean("signal.regenEnergy",sample!=null&&validCounter(sample.regenEnergyKwh)); + out.putBoolean("signal.regenRange",sample!=null&&validCounter(sample.regenRangeKm)); + out.putBoolean("vehicleValuesIncluded",false); + return out; + } + + private static boolean alive(IBinder binder){return binder!=null&&binder.pingBinder();} + private static boolean finite(float value){return !Float.isNaN(value)&&!Float.isInfinite(value);} + /** Fast, read-only speed signal used by the dashboard's 100 ms instrument loop. */ float readSpeed(){ return calibratedSpeed(f(condition, CONDITION_TOKEN, 3)); } diff --git a/src/cloud/molberg/mgutility/HermesApiClient.java b/src/cloud/molberg/mgutility/HermesApiClient.java new file mode 100644 index 0000000..4bf571e --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesApiClient.java @@ -0,0 +1,165 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.os.Handler; +import android.os.Looper; + +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** Client for Hermes' native, authenticated session API. */ +final class HermesApiClient { + private static final String CAR_CONTEXT = + "The user is speaking to you hands-free from an MG car head unit through a steering-wheel " + + "push-to-talk button. Treat this as an ongoing in-car conversation. Keep responses concise, " + + "easy to understand by voice, and safe to use while driving."; + + interface Callback { void complete(boolean success, String message, String assistantResponse); } + + static void test(final HermesConfig config, final Callback callback) { + run("hermes-api-test", new Request() { + @Override public Result execute() throws Exception { + Response response = request(config, "GET", "/v1/capabilities", null, 15000); + if (!response.success()) return Result.error(errorMessage(response)); + JSONObject body = new JSONObject(response.body); + JSONObject features = body.optJSONObject("features"); + if (features == null || !features.optBoolean("session_chat", false)) + return Result.error("This Hermes server does not advertise session chat"); + return Result.success("Connected to Hermes native API", ""); + } + }, callback); + } + + static void send(final Context context, final HermesConfig config, final String prompt, + final Callback callback) { + run("hermes-api-chat", new Request() { + @Override public Result execute() throws Exception { + String sessionId = HermesConfig.sessionId(context); + Response session = request(config, "GET", "/api/sessions/" + encode(sessionId), null, 15000); + if (session.code == 404) { + JSONObject create = new JSONObject(); + create.put("id", sessionId); + create.put("source", "api_server"); + create.put("title", "MG car voice assistant"); + create.put("system_prompt", CAR_CONTEXT); + // The instance's global custom route uses short-lived upstream credentials. + // Keep the car conversation on its verified, fast direct provider without + // changing the model used by any other Hermes surface. + create.put("provider", "anthropic"); + create.put("model", "claude-haiku-4-5-20251001"); + create.put("require_model_lock", true); + session = request(config, "POST", "/api/sessions", create, 20000); + } + if (!session.success() && session.code != 409) + return Result.error("Could not open Hermes conversation: " + errorMessage(session)); + + JSONObject turn = new JSONObject(); + turn.put("message", prompt); + // The instruction is repeated so an existing/restored session always knows its surface. + turn.put("instructions", CAR_CONTEXT); + Response response = request(config, "POST", + "/api/sessions/" + encode(sessionId) + "/chat", turn, 300000); + if (!response.success()) return Result.error(errorMessage(response)); + JSONObject root = new JSONObject(response.body); + JSONObject message = root.optJSONObject("message"); + String content = message == null ? "" : message.optString("content", "").trim(); + return Result.success("Hermes replied", content); + } + }, callback); + } + + private interface Request { Result execute() throws Exception; } + + private static void run(String threadName, final Request request, final Callback callback) { + new Thread(new Runnable() { + @Override public void run() { + Result result; + try { result = request.execute(); } + catch (Exception error) { result = Result.error("Could not reach Hermes: " + safeMessage(error)); } + final Result delivered = result; + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override public void run() { + callback.complete(delivered.success, delivered.message, delivered.response); + } + }); + } + }, threadName).start(); + } + + private static Response request(HermesConfig config, String method, String path, + JSONObject body, int readTimeout) throws Exception { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) new URL(config.serverUrl + path).openConnection(); + connection.setConnectTimeout(10000); + connection.setReadTimeout(readTimeout); + connection.setRequestMethod(method); + connection.setRequestProperty("Accept", "application/json"); + connection.setRequestProperty("Authorization", "Bearer " + config.apiKey); + if (body != null) { + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8); + OutputStream output = connection.getOutputStream(); + output.write(bytes); + output.close(); + } + int code = connection.getResponseCode(); + InputStream stream = code >= 200 && code < 300 ? connection.getInputStream() : connection.getErrorStream(); + return new Response(code, readBody(stream)); + } finally { + if (connection != null) connection.disconnect(); + } + } + + private static String readBody(InputStream stream) throws Exception { + if (stream == null) return ""; + BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + StringBuilder value = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) value.append(line); + reader.close(); + return value.toString(); + } + + private static String errorMessage(Response response) { + try { + JSONObject error = new JSONObject(response.body).optJSONObject("error"); + String message = error == null ? "" : error.optString("message", ""); + if (message.length() > 0) return "Hermes: " + message; + } catch (Exception ignored) { } + return "Hermes returned HTTP " + response.code; + } + + private static String encode(String value) throws Exception { + return URLEncoder.encode(value, "UTF-8").replace("+", "%20"); + } + + private static String safeMessage(Exception error) { + String value = error.getMessage(); + return value == null || value.trim().length() == 0 ? error.getClass().getSimpleName() : value; + } + + private static final class Response { + final int code; final String body; + Response(int code, String body) { this.code = code; this.body = body; } + boolean success() { return code >= 200 && code < 300; } + } + + private static final class Result { + final boolean success; final String message; final String response; + Result(boolean success, String message, String response) { + this.success = success; this.message = message; this.response = response; + } + static Result success(String message, String response) { return new Result(true, message, response); } + static Result error(String message) { return new Result(false, message, ""); } + } +} diff --git a/src/cloud/molberg/mgutility/HermesAudioCapture.java b/src/cloud/molberg/mgutility/HermesAudioCapture.java new file mode 100644 index 0000000..7902f8b --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesAudioCapture.java @@ -0,0 +1,165 @@ +package cloud.molberg.mgutility; + +import android.media.AudioRecord; +import android.media.MediaRecorder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** Continuously captures 16 kHz mono PCM for streaming to sherpa-onnx and also writes a WAV file. */ +final class HermesAudioCapture { + interface SampleListener { void onSamples(float[] samples, int count); void onLevel(float level); } + + static final int SAMPLE_RATE = 16000; + static final int CHANNEL_CONFIG = android.media.AudioFormat.CHANNEL_IN_MONO; + static final int AUDIO_FORMAT = android.media.AudioFormat.ENCODING_PCM_16BIT; + + private final File wavFile; + private final SampleListener sampleListener; + + private AudioRecord recorder; + private Thread captureThread; + private FileOutputStream wavOutput; + private int totalBytes; + private boolean released; + private boolean failed; + + HermesAudioCapture(File wavFile, SampleListener sampleListener) { + this.wavFile = wavFile; + this.sampleListener = sampleListener; + } + + boolean start() { + try { + int bufferBytes = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT); + if (bufferBytes <= 0) bufferBytes = 4096; + recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, CHANNEL_CONFIG, + AUDIO_FORMAT, bufferBytes * 4); + if (recorder.getState() != AudioRecord.STATE_INITIALIZED) { + fail("Could not initialize microphone"); + return false; + } + wavFile.delete(); + wavOutput = new FileOutputStream(wavFile); + writeWavHeader(wavOutput, 0); + totalBytes = 0; + recorder.startRecording(); + captureThread = new Thread(new Runnable() { @Override public void run() { captureLoop(); } }, + "hermes-audio-capture"); + captureThread.start(); + return true; + } catch (Throwable error) { + fail("Could not record audio: " + safeMessage(error)); + return false; + } + } + + File stop() { + if (captureThread != null) { + try { captureThread.join(250); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + captureThread = null; + } + if (recorder != null) { + try { if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) recorder.stop(); } catch (Throwable ignored) { } + try { recorder.release(); } catch (Throwable ignored) { } + recorder = null; + } + if (wavOutput != null) { + try { wavOutput.flush(); } catch (IOException ignored) { } + try { + if (totalBytes > 0) { + byte[] header = buildWavHeader(totalBytes); + RandomAccessFile raf = new RandomAccessFile(wavFile, "rw"); + raf.seek(0); + raf.write(header); + raf.close(); + } + } catch (IOException ignored) { } + try { wavOutput.close(); } catch (IOException ignored) { } + wavOutput = null; + } + if (failed || totalBytes < 3200) { + if (wavFile != null && wavFile.isFile()) wavFile.delete(); + return null; + } + return wavFile; + } + + void cancel() { + released = true; + if (recorder != null) { + try { if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) recorder.stop(); } catch (Throwable ignored) { } + try { recorder.release(); } catch (Throwable ignored) { } + recorder = null; + } + if (wavOutput != null) { try { wavOutput.close(); } catch (IOException ignored) { } wavOutput = null; } + if (wavFile != null && wavFile.isFile()) wavFile.delete(); + } + + private void captureLoop() { + short[] pcm = new short[2048]; + while (!released && recorder != null) { + int read = recorder.read(pcm, 0, pcm.length); + if (read <= 0) continue; + try { + if (wavOutput != null) { + ByteBuffer bb = ByteBuffer.allocate(read * 2).order(ByteOrder.LITTLE_ENDIAN); + for (int i = 0; i < read; i++) bb.putShort(pcm[i]); + wavOutput.write(bb.array(), 0, read * 2); + totalBytes += read * 2; + } + } catch (IOException error) { + fail("Audio file write failed: " + safeMessage(error)); + break; + } + if (sampleListener != null && !released) { + float sum = 0f; + for (int i = 0; i < read; i++) { float value = pcm[i] / 32768.0f; sum += value * value; } + sampleListener.onLevel((float) Math.min(1.0, Math.sqrt(sum / Math.max(1, read)) * 8.0)); + sampleListener.onSamples(toFloat(pcm, read), read); + } + } + } + + private void fail(String message) { + failed = true; + released = true; + } + + private static float[] toFloat(short[] pcm, int count) { + float[] result = new float[count]; + for (int i = 0; i < count; i++) result[i] = pcm[i] / 32768.0f; + return result; + } + + private static void writeWavHeader(FileOutputStream out, int dataBytes) throws IOException { + out.write(buildWavHeader(dataBytes)); + } + + private static byte[] buildWavHeader(int dataBytes) { + int totalBytes = 36 + dataBytes; + ByteBuffer header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN); + header.put(new byte[]{ 'R','I','F','F' }); + header.putInt(totalBytes); + header.put(new byte[]{ 'W','A','V','E','f','m','t',' ' }); + header.putInt(16); + header.putShort((short) 1); // PCM + header.putShort((short) 1); // mono + header.putInt(SAMPLE_RATE); + header.putInt(SAMPLE_RATE * 2); + header.putShort((short) 2); + header.putShort((short) 16); + header.put(new byte[]{ 'd','a','t','a' }); + header.putInt(dataBytes); + return header.array(); + } + + private static String safeMessage(Throwable error) { + String value = error.getMessage(); + return value == null || value.trim().length() == 0 ? error.getClass().getSimpleName() : value; + } +} \ No newline at end of file diff --git a/src/cloud/molberg/mgutility/HermesConfig.java b/src/cloud/molberg/mgutility/HermesConfig.java new file mode 100644 index 0000000..73c9efa --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesConfig.java @@ -0,0 +1,175 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyProperties; +import android.util.Base64; + +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.util.UUID; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; + +/** Private configuration for the Hermes native API integration. */ +final class HermesConfig { + static final String DEFAULT_SERVER_URL = "http://10.0.0.74:18793"; + private static final String PREFS = "hermes_agent"; + private static final String KEY_ALIAS = "mg_utility_hermes_credentials"; + private static final String URL = "api_server_url"; + private static final String ENABLED = "enabled"; + private static final String API_KEY = "api_server_key"; + private static final String SESSION_ID = "api_session_id"; + + static final String VOICE_ENGINE_SYSTEM = "system"; + static final String VOICE_ENGINE_SHERPA = "sherpa_onnx"; + static final String VOICE_ENGINE_UPLOAD = "upload"; + + final boolean enabled; + final String serverUrl; + final String apiKey; + final String sessionId; + String transcriptionUrl; + String transcriptionKey; + String transcriptionModel; + String voiceEngine; + String sherpaModelDir; + + private HermesConfig(boolean enabled, String serverUrl, String apiKey, String sessionId) { + this.enabled = enabled; + this.serverUrl = serverUrl; + this.apiKey = apiKey; + this.sessionId = sessionId; + } + + static HermesConfig load(Context context) { + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + HermesConfig config = new HermesConfig(prefs.getBoolean(ENABLED, false), prefs.getString(URL, ""), + decrypt(prefs.getString(API_KEY, "")), prefs.getString(SESSION_ID, "")); + config.transcriptionUrl = prefs.getString("transcription_url", ""); + config.transcriptionKey = decrypt(prefs.getString("transcription_key", "")); + config.transcriptionModel = prefs.getString("transcription_model", "whisper-1"); + config.voiceEngine = normalizeVoiceEngine(prefs.getString("voice_engine", VOICE_ENGINE_SYSTEM)); + config.sherpaModelDir = prefs.getString("sherpa_model_dir", ""); + return config; + } + + static void saveTranscription(Context context, String url, String key, String model) throws Exception { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString("transcription_url", url.trim()) + .putString("transcription_key", encrypt(key.trim())) + .putString("transcription_model", model.trim()).apply(); + } + + static void saveVoiceEngine(Context context, String voiceEngine, String sherpaModelDir) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString("voice_engine", normalizeVoiceEngine(voiceEngine)) + .putString("sherpa_model_dir", sherpaModelDir == null ? "" : sherpaModelDir.trim()) + .apply(); + } + + static String normalizeVoiceEngine(String value) { + if (VOICE_ENGINE_SHERPA.equals(value)) return VOICE_ENGINE_SHERPA; + if (VOICE_ENGINE_UPLOAD.equals(value)) return VOICE_ENGINE_UPLOAD; + return VOICE_ENGINE_SYSTEM; + } + + static String voiceEngineLabel(String engine) { + if (VOICE_ENGINE_SHERPA.equals(engine)) return "Local sherpa-onnx (offline)"; + if (VOICE_ENGINE_UPLOAD.equals(engine)) return "Record + upload to transcription server"; + return "System speech recognizer"; + } + + boolean sherpaModelReady() { + if (!VOICE_ENGINE_SHERPA.equals(voiceEngine)) return false; + if (sherpaModelDir.length() == 0) return false; + java.io.File dir = new java.io.File(sherpaModelDir); + if (!dir.isDirectory()) return false; + return new java.io.File(dir, "tokens.txt").isFile() + && new java.io.File(dir, "encoder.int8.onnx").isFile() + && new java.io.File(dir, "decoder.int8.onnx").isFile() + && new java.io.File(dir, "joiner.int8.onnx").isFile(); + } + + boolean uploadTranscriptionReady() { + if (!VOICE_ENGINE_UPLOAD.equals(voiceEngine)) return false; + return transcriptionUrl.length() > 0; + } + + static void save(Context context, boolean enabled, String url, String apiKey) throws Exception { + HermesConfig previous = load(context); + String normalized = normalizeServerUrl(url); + SharedPreferences.Editor editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putBoolean(ENABLED, enabled) + .putString(URL, normalized) + .putString(API_KEY, encrypt(apiKey.trim())) + // Remove the beta webhook fields so they cannot be mistaken for API credentials. + .remove("webhook_url").remove("hmac_secret").remove("bearer_token"); + if (!normalized.equals(previous.serverUrl) || !apiKey.trim().equals(previous.apiKey)) + editor.remove(SESSION_ID); + editor.apply(); + } + + boolean isReady() { + return enabled && serverUrl.length() > 0 && apiKey.length() > 0; + } + + static String sessionId(Context context) { + HermesConfig config = load(context); + if (config.sessionId.length() > 0) return config.sessionId; + String value = "mg_car_" + UUID.randomUUID().toString().replace("-", ""); + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(SESSION_ID, value).apply(); + return value; + } + + static void newConversation(Context context) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(SESSION_ID).apply(); + } + + static String normalizeServerUrl(String value) { + String result = value == null ? "" : value.trim(); + while (result.endsWith("/")) result = result.substring(0, result.length() - 1); + if (result.endsWith("/v1")) result = result.substring(0, result.length() - 3); + return result; + } + + private static String encrypt(String value) throws Exception { + if (value.length() == 0) return ""; + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key()); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + return Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP) + "." + + Base64.encodeToString(encrypted, Base64.NO_WRAP); + } + + private static String decrypt(String stored) { + if (stored == null || stored.length() == 0) return ""; + try { + String[] parts = stored.split("\\.", 2); + if (parts.length != 2) return ""; + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key(), + new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP))); + return new String(cipher.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), StandardCharsets.UTF_8); + } catch (Exception ignored) { + return ""; + } + } + + private static SecretKey key() throws Exception { + KeyStore store = KeyStore.getInstance("AndroidKeyStore"); + store.load(null); + if (store.containsAlias(KEY_ALIAS)) return (SecretKey) store.getKey(KEY_ALIAS, null); + KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + generator.init(new KeyGenParameterSpec.Builder(KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .build()); + return generator.generateKey(); + } +} diff --git a/src/cloud/molberg/mgutility/HermesLocalRecognizer.java b/src/cloud/molberg/mgutility/HermesLocalRecognizer.java new file mode 100644 index 0000000..60f85f4 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesLocalRecognizer.java @@ -0,0 +1,98 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.os.Handler; +import android.os.Looper; + +import com.k2fsa.sherpa.onnx.FeatureConfig; +import com.k2fsa.sherpa.onnx.EndpointConfig; +import com.k2fsa.sherpa.onnx.OnlineCtcFstDecoderConfig; +import com.k2fsa.sherpa.onnx.OnlineLMConfig; +import com.k2fsa.sherpa.onnx.OnlineModelConfig; +import com.k2fsa.sherpa.onnx.QnnConfig; +import com.k2fsa.sherpa.onnx.OnlineRecognizer; +import com.k2fsa.sherpa.onnx.OnlineRecognizerConfig; +import com.k2fsa.sherpa.onnx.OnlineRecognizerResult; +import com.k2fsa.sherpa.onnx.OnlineStream; +import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig; +import java.io.File; + +/** Offline streaming recognizer wrapper around the bundled sherpa-onnx AAR. */ +final class HermesLocalRecognizer { + interface Listener { void onPartial(String text); void onFinal(String text); void onError(String message); } + private final Handler MAIN = new Handler(Looper.getMainLooper()); + private final Context context; + private OnlineRecognizer recognizer; + private OnlineStream stream; + private Listener listener; + private boolean released; + + HermesLocalRecognizer(Context context) { this.context = context.getApplicationContext(); } + + boolean start(Listener listener) { + this.listener = listener; + try { + File modelDir = new File(context.getFilesDir(), "sherpa-en"); + modelDir.mkdirs(); + String encoder = copyAsset("sherpa-en/encoder.int8.onnx", new File(modelDir, "encoder.int8.onnx")); + String decoder = copyAsset("sherpa-en/decoder.int8.onnx", new File(modelDir, "decoder.int8.onnx")); + String joiner = copyAsset("sherpa-en/joiner.int8.onnx", new File(modelDir, "joiner.int8.onnx")); + String tokens = copyAsset("sherpa-en/tokens.txt", new File(modelDir, "tokens.txt")); + OnlineTransducerModelConfig transducer = new OnlineTransducerModelConfig(); + transducer.setEncoder(encoder); transducer.setDecoder(decoder); transducer.setJoiner(joiner); transducer.setQnnConfig(new QnnConfig()); + OnlineModelConfig model = new OnlineModelConfig(); + model.setTransducer(transducer); model.setTokens(tokens); model.setNumThreads(1); model.setDebug(false); model.setProvider("cpu"); + OnlineRecognizerConfig config = new OnlineRecognizerConfig(); + config.setFeatConfig(new FeatureConfig(16000, 80, 0.0f)); config.setModelConfig(model); config.setLmConfig(new OnlineLMConfig()); + config.setCtcFstDecoderConfig(new OnlineCtcFstDecoderConfig()); config.setEndpointConfig(new EndpointConfig()); + config.setEnableEndpoint(true); config.setDecodingMethod("greedy_search"); config.setMaxActivePaths(4); + recognizer = new OnlineRecognizer(null, config); + stream = recognizer.createStream(""); + // The upstream Android example primes this transducer with 300 ms of leading silence. + stream.acceptWaveform(new float[4800], 16000); + return true; + } catch (Throwable error) { deliverError("Local recognizer failed to start: " + safeMessage(error)); release(); return false; } + } + + private String copyAsset(String asset, File destination) throws java.io.IOException { + if (!destination.isFile() || destination.length() == 0) { + java.io.InputStream input = context.getAssets().open(asset); + java.io.FileOutputStream output = new java.io.FileOutputStream(destination); + byte[] buffer = new byte[65536]; int count; + while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count); + input.close(); output.close(); + } + return destination.getAbsolutePath(); + } + + void acceptSamples(float[] samples, int count) { + if (released || recognizer == null || stream == null) return; + try { + stream.acceptWaveform(samples, 16000); + while (recognizer.isReady(stream)) recognizer.decode(stream); + OnlineRecognizerResult result = recognizer.getResult(stream); + String text = result == null ? "" : result.getText(); + if (text != null && text.length() > 0) deliverPartial(text); + } catch (Throwable error) { deliverError("Local recognizer error: " + safeMessage(error)); release(); } + } + + void finish() { + if (released || recognizer == null || stream == null) { release(); return; } + try { + // The upstream example supplies 600 ms trailing silence before final decode. + stream.acceptWaveform(new float[9600], 16000); + stream.inputFinished(); + while (recognizer.isReady(stream)) recognizer.decode(stream); + OnlineRecognizerResult result = recognizer.getResult(stream); + deliverFinal(result == null || result.getText() == null ? "" : result.getText().trim()); + } catch (Throwable error) { deliverError("Local recognizer finalization failed: " + safeMessage(error)); } + finally { release(); } + } + + void cancel() { release(); } + private void release() { released = true; if (stream != null) { try { stream.release(); } catch (Throwable ignored) { } stream = null; } if (recognizer != null) { try { recognizer.release(); } catch (Throwable ignored) { } recognizer = null; } } + private void deliverPartial(final String text) { MAIN.post(new Runnable() { public void run() { if (listener != null && !released) listener.onPartial(text); }}); } + private void deliverFinal(final String text) { MAIN.post(new Runnable() { public void run() { if (listener != null) listener.onFinal(text); }}); } + private void deliverError(final String message) { MAIN.post(new Runnable() { public void run() { if (listener != null) listener.onError(message); }}); } + private static String safeMessage(Throwable error) { String value = error.getMessage(); return value == null || value.trim().length() == 0 ? error.getClass().getSimpleName() : value; } +} \ No newline at end of file diff --git a/src/cloud/molberg/mgutility/HermesSettingsActivity.java b/src/cloud/molberg/mgutility/HermesSettingsActivity.java new file mode 100644 index 0000000..5515195 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesSettingsActivity.java @@ -0,0 +1,277 @@ +package cloud.molberg.mgutility; + +import android.Manifest; +import android.content.pm.PackageManager; +import android.graphics.Typeface; +import android.os.Bundle; +import android.text.InputType; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Spinner; +import android.widget.ArrayAdapter; +import android.widget.TextView; +import android.widget.Toast; + +import java.net.URL; + +/** Configuration screen for the Hermes native API voice assistant. */ +public final class HermesSettingsActivity extends AnimatedActivity { + private static final int AUDIO_PERMISSION = 9401; + private EditText url; + private EditText apiKey; + private EditText transcriptionUrl; + private EditText transcriptionKey; + private EditText transcriptionModel; + private Spinner voiceEngine; + private EditText sherpaModelDir; + private CheckBox enabled; + private TextView connectionStatus; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + setContentView(buildUi()); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + private View buildUi() { + HermesConfig config = HermesConfig.load(this); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(28, 12, 28, 18); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "HERMES AGENT", 29), new LinearLayout.LayoutParams(0, 58, 1)); + header.addView(UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }), new LinearLayout.LayoutParams(120, 52)); + root.addView(header); + + ScrollView scroll = new ScrollView(this); + LinearLayout form = new LinearLayout(this); + form.setOrientation(LinearLayout.VERTICAL); + form.setPadding(8, 8, 8, 12); + + TextView intro = UiTheme.text(this, + "Connect steering-wheel push-to-talk directly to the Hermes Agent session API.", + 14, UiTheme.TEXT, Typeface.NORMAL); + intro.setPadding(0, 2, 0, 14); + form.addView(intro); + form.addView(UiTheme.button(this, "ENABLE GLOBAL STEERING-WHEEL ACCESS", new View.OnClickListener() { + @Override public void onClick(View view) { KeyRemappingAccessibilityService.openSettings(HermesSettingsActivity.this); } + }, false), new LinearLayout.LayoutParams(-1, 48)); + form.addView(UiTheme.text(this, + "Enable MG Utility global keys in Android Accessibility to open Hermes over other apps and receive " + + "both press and release events. Grant microphone access before using the steering-wheel button.", + 12, UiTheme.MUTED, Typeface.NORMAL)); + + enabled = new CheckBox(this); + enabled.setText("Enable Hermes voice assistant"); + enabled.setTextColor(UiTheme.TEXT); + enabled.setTextSize(17); + enabled.setChecked(config.enabled); + form.addView(enabled, new LinearLayout.LayoutParams(-1, 52)); + + url = field(HermesConfig.DEFAULT_SERVER_URL, + config.serverUrl.length() == 0 ? HermesConfig.DEFAULT_SERVER_URL : config.serverUrl, false); + form.addView(labeled("HERMES SERVER", url)); + apiKey = field("API_SERVER_KEY from ~/.hermes/.env", config.apiKey, true); + form.addView(labeled("API KEY", apiKey)); + transcriptionUrl = field("https://your-speech-server/v1/audio/transcriptions", config.transcriptionUrl, false); + form.addView(labeled("TRANSCRIPTION ENDPOINT (OPTIONAL)", transcriptionUrl)); + transcriptionKey = field("Speech server key (not the Hermes key)", config.transcriptionKey, true); + form.addView(labeled("TRANSCRIPTION API KEY", transcriptionKey)); + transcriptionModel = field("whisper-1", config.transcriptionModel, false); + form.addView(labeled("TRANSCRIPTION MODEL", transcriptionModel)); + form.addView(UiTheme.label(this, "VOICE ENGINE")); + voiceEngine = new Spinner(this); + String[] engines = new String[]{ + "System speech recognizer", + "Local sherpa-onnx (offline)", + "Record + upload to transcription server"}; + voiceEngine.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, engines)); + voiceEngine.setSelection(HermesConfig.VOICE_ENGINE_SHERPA.equals(config.voiceEngine) ? 1 : + HermesConfig.VOICE_ENGINE_UPLOAD.equals(config.voiceEngine) ? 2 : 0); + form.addView(voiceEngine, new LinearLayout.LayoutParams(-1, 52)); + sherpaModelDir = field("/data/data/cloud.molberg.mgutility/files/sherpa-en", config.sherpaModelDir, false); + form.addView(labeled("LOCAL SHERPA MODEL DIRECTORY", sherpaModelDir)); + form.addView(UiTheme.text(this, + "System uses the head unit recognizer. Local sherpa-onnx keeps speech on the car and needs the " + + "English streaming model files in the directory above. Upload mode sends recorded audio only to " + + "the configured OpenAI-compatible transcription endpoint; the result is then sent to Hermes as text. " + + "Hermes installations are not modified and do not receive arbitrary file attachments from this app.", + 12, UiTheme.MUTED, Typeface.NORMAL)); + + TextView help = UiTheme.text(this, + "This machine's Hermes API is http://10.0.0.74:18793. Enter its API_SERVER_KEY; no webhook, " + + "route, HMAC secret, or dashboard login is needed. The app keeps one Hermes session so follow-up " + + "requests share conversation history. The API key is encrypted with Android Keystore.", + 12, UiTheme.MUTED, Typeface.NORMAL); + help.setPadding(2, 12, 2, 12); + form.addView(help); + + LinearLayout actions = new LinearLayout(this); + actions.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); + Button microphone = UiTheme.button(this, "MICROPHONE ACCESS", new View.OnClickListener() { + @Override public void onClick(View v) { requestMicrophone(); } + }, false); + Button test = UiTheme.button(this, "TEST CONNECTION", new View.OnClickListener() { + @Override public void onClick(View v) { testConnection(); } + }, false); + Button conversation = UiTheme.button(this, "NEW CONVERSATION", new View.OnClickListener() { + @Override public void onClick(View v) { + HermesConfig.newConversation(HermesSettingsActivity.this); + Toast.makeText(HermesSettingsActivity.this, "The next prompt starts a new Hermes conversation", Toast.LENGTH_SHORT).show(); + } + }, false); + Button save = UiTheme.button(this, "SAVE", new View.OnClickListener() { + @Override public void onClick(View v) { save(true); } + }, true); + actions.addView(microphone, new LinearLayout.LayoutParams(190, 48)); + LinearLayout.LayoutParams testParams = new LinearLayout.LayoutParams(170, 48); + testParams.setMargins(8, 0, 0, 0); + actions.addView(test, testParams); + LinearLayout.LayoutParams conversationParams = new LinearLayout.LayoutParams(190, 48); + conversationParams.setMargins(8, 0, 0, 0); + actions.addView(conversation, conversationParams); + LinearLayout.LayoutParams saveParams = new LinearLayout.LayoutParams(130, 48); + saveParams.setMargins(8, 0, 0, 0); + actions.addView(save, saveParams); + form.addView(actions, new LinearLayout.LayoutParams(-1, 60)); + + connectionStatus = UiTheme.text(this, "", 12, UiTheme.MUTED, Typeface.NORMAL); + connectionStatus.setGravity(Gravity.RIGHT); + form.addView(connectionStatus, new LinearLayout.LayoutParams(-1, 30)); + + TextView mapping = UiTheme.text(this, + "NEXT • Open Key remapping, capture the steering-wheel button, choose “Push to talk” and “Hermes voice assistant”.", + 13, UiTheme.CYAN_BRIGHT, Typeface.BOLD); + mapping.setPadding(2, 14, 2, 4); + form.addView(mapping); + + scroll.addView(form); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private LinearLayout labeled(String label, EditText input) { + LinearLayout block = new LinearLayout(this); + block.setOrientation(LinearLayout.VERTICAL); + TextView name = UiTheme.label(this, label); + name.setPadding(2, 8, 0, 3); + block.addView(name, new LinearLayout.LayoutParams(-1, 31)); + block.addView(input, new LinearLayout.LayoutParams(-1, 52)); + return block; + } + + private EditText field(String hint, String value, boolean password) { + EditText input = new EditText(this); + input.setSingleLine(true); + input.setHint(hint); + input.setText(value); + input.setTextColor(UiTheme.TEXT); + input.setHintTextColor(UiTheme.MUTED); + input.setTextSize(16); + input.setPadding(12, 0, 12, 0); + input.setBackground(UiTheme.outline(UiTheme.DIVIDER, 1, 5)); + if (password) input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + return input; + } + + private boolean save(boolean requestAudio) { + String speechUrl = transcriptionUrl.getText().toString().trim(); + if (speechUrl.length() > 0) { + try { + URL parsed = new URL(speechUrl); + if (!("https".equalsIgnoreCase(parsed.getProtocol()) || "http".equalsIgnoreCase(parsed.getProtocol())) || + parsed.getHost().length() == 0 || parsed.getUserInfo() != null || parsed.getRef() != null || + transcriptionModel.getText().toString().trim().length() == 0) throw new Exception(); + } catch (Exception ignored) { + Toast.makeText(this, "Enter a valid transcription HTTP(S) endpoint and model", Toast.LENGTH_LONG).show(); + return false; + } + } + String address = url.getText().toString().trim(); + String key = apiKey.getText().toString().trim(); + if (enabled.isChecked()) { + try { + URL parsed = new URL(address); + if (!("https".equalsIgnoreCase(parsed.getProtocol()) || "http".equalsIgnoreCase(parsed.getProtocol()))) + throw new Exception(); + } catch (Exception ignored) { + Toast.makeText(this, "Enter a valid Hermes HTTP or HTTPS server URL", Toast.LENGTH_LONG).show(); + return false; + } + if (key.length() == 0) { + Toast.makeText(this, "The Hermes API_SERVER_KEY is required", Toast.LENGTH_LONG).show(); + return false; + } + } + try { + HermesConfig.saveTranscription(this, speechUrl, transcriptionKey.getText().toString(), + transcriptionModel.getText().toString()); + String selectedEngine = voiceEngine.getSelectedItemPosition() == 1 ? HermesConfig.VOICE_ENGINE_SHERPA : + voiceEngine.getSelectedItemPosition() == 2 ? HermesConfig.VOICE_ENGINE_UPLOAD : HermesConfig.VOICE_ENGINE_SYSTEM; + if (HermesConfig.VOICE_ENGINE_UPLOAD.equals(selectedEngine) && speechUrl.length() == 0) { + Toast.makeText(this, "Upload mode needs a transcription endpoint", Toast.LENGTH_LONG).show(); + return false; + } + HermesConfig.saveVoiceEngine(this, selectedEngine, sherpaModelDir.getText().toString()); + HermesConfig.save(this, enabled.isChecked(), address, key); + Toast.makeText(this, "Hermes settings saved", Toast.LENGTH_SHORT).show(); + if (requestAudio && enabled.isChecked()) requestMicrophone(); + return true; + } catch (Exception error) { + Toast.makeText(this, "Could not securely save credentials", Toast.LENGTH_LONG).show(); + return false; + } + } + + private void testConnection() { + if (!save(false)) return; + final HermesConfig config = HermesConfig.load(this); + if (!config.isReady()) { + connectionStatus.setText("Enable Hermes before testing"); + return; + } + connectionStatus.setTextColor(UiTheme.CYAN_BRIGHT); + connectionStatus.setText("CONNECTING…"); + HermesApiClient.test(config, new HermesApiClient.Callback() { + @Override public void complete(boolean success, String message, String ignored) { + connectionStatus.setTextColor(success ? UiTheme.SUCCESS : UiTheme.WARNING); + connectionStatus.setText(message); + } + }); + } + + private void requestMicrophone() { + if (android.os.Build.VERSION.SDK_INT < 23 || + checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { + Toast.makeText(this, "Microphone access is ready", Toast.LENGTH_SHORT).show(); + return; + } + requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_PERMISSION); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } +} diff --git a/src/cloud/molberg/mgutility/HermesTranscriptionClient.java b/src/cloud/molberg/mgutility/HermesTranscriptionClient.java new file mode 100644 index 0000000..cb737c8 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesTranscriptionClient.java @@ -0,0 +1,83 @@ +package cloud.molberg.mgutility; + +import android.os.Handler; +import android.os.Looper; +import org.json.JSONObject; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +final class HermesTranscriptionClient { + interface Callback { void complete(String text, String error); } + + static void transcribe(final HermesConfig config, final File audio, final Callback callback) { + new Thread(new Runnable() { + @Override public void run() { + String text = ""; + String error = ""; + try { text = request(config, audio); } + catch (Exception failure) { + error = "Transcription failed. Check the speech endpoint, credentials, model and network."; + if (failure instanceof TranscriptionException) error = failure.getMessage(); + } finally { audio.delete(); } + final String result = text; + final String message = error; + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override public void run() { callback.complete(result, message); } + }); + } + }, "hermes-transcription").start(); + } + + private static String request(HermesConfig config, File audio) throws Exception { + String boundary = "mg-" + UUID.randomUUID(); + HttpURLConnection connection = (HttpURLConnection) new URL(config.transcriptionUrl).openConnection(); + try { + connection.setConnectTimeout(10000); + connection.setReadTimeout(60000); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setRequestProperty("Accept", "application/json"); + connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + if (!config.transcriptionKey.isEmpty()) + connection.setRequestProperty("Authorization", "Bearer " + config.transcriptionKey); + byte[] prefix = ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\n" + + config.transcriptionModel + "\r\n--" + boundary + + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"speech.m4a\"\r\n" + + "Content-Type: audio/mp4\r\n\r\n").getBytes(StandardCharsets.UTF_8); + byte[] suffix = ("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8); + connection.setFixedLengthStreamingMode(prefix.length + audio.length() + suffix.length); + try (OutputStream output = connection.getOutputStream(); InputStream input = new FileInputStream(audio)) { + output.write(prefix); + byte[] buffer = new byte[8192]; + int count; + while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count); + output.write(suffix); + } + int status = connection.getResponseCode(); + if (status < 200 || status >= 300) + throw new TranscriptionException("Transcription server returned HTTP " + status + + ". Check the speech endpoint, key and model in Hermes settings."); + try (InputStream input = connection.getInputStream(); ByteArrayOutputStream body = new ByteArrayOutputStream()) { + byte[] buffer = new byte[4096]; + int count; + while ((count = input.read(buffer)) != -1) { + if (body.size() + count > 1024 * 1024) throw new TranscriptionException("Transcription response is too large"); + body.write(buffer, 0, count); + } + return new JSONObject(new String(body.toByteArray(), StandardCharsets.UTF_8)).getString("text").trim(); + } + } finally { connection.disconnect(); } + } + + private static final class TranscriptionException extends Exception { + TranscriptionException(String message) { super(message); } + } +} diff --git a/src/cloud/molberg/mgutility/HermesVoiceActivity.java b/src/cloud/molberg/mgutility/HermesVoiceActivity.java new file mode 100644 index 0000000..d5abbc5 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesVoiceActivity.java @@ -0,0 +1,460 @@ +package cloud.molberg.mgutility; + +import android.Manifest; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.graphics.Typeface; +import android.media.MediaRecorder; +import android.os.Bundle; +import android.os.Handler; +import android.speech.RecognitionListener; +import android.speech.RecognizerIntent; +import android.speech.SpeechRecognizer; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import java.lang.ref.WeakReference; +import java.io.File; +import java.util.ArrayList; + +/** Full-screen, glanceable push-to-talk surface for the Hermes assistant. */ +public final class HermesVoiceActivity extends AnimatedActivity implements RecognitionListener { + private static final int AUDIO_PERMISSION = 9501; + private static final int SYSTEM_RECOGNITION = 9502; + private final Handler MAIN = new Handler(); + private static WeakReference active = new WeakReference(null); + private static boolean releasePending; + private static boolean cancelPending; + private static long latestLaunch; + private static final String EXTRA_LAUNCH = "hermes_launch"; + private static final Handler LAUNCH = new Handler(android.os.Looper.getMainLooper()); + private long launchId; + + private SpeechRecognizer recognizer; + private TextView state; + private TextView transcript; + private TextView indicator; + private MicScopeView scope; + private final StringBuilder committed = new StringBuilder(); + private String partial = ""; + private boolean released; + private boolean submitted; + private boolean recognitionStarted; + private MediaRecorder recorder; + private File recording; + private HermesAudioCapture audioCapture; + private HermesLocalRecognizer localRecognizer; + private boolean destroyed; + private boolean transcribing; + private boolean systemRecognitionStarted; + private HermesConfig voiceConfig; + + static synchronized void begin(final Context context) { + releasePending = false; + cancelPending = false; + final long requestedLaunch = ++latestLaunch; + LAUNCH.post(new Runnable() { + @Override public void run() { + synchronized (HermesVoiceActivity.class) { + if (requestedLaunch != latestLaunch || cancelPending) return; + } + HermesConfig config = HermesConfig.load(context); + Intent intent; + if (!config.isReady()) { + Toast.makeText(context, "Configure and enable Hermes in Settings first", Toast.LENGTH_LONG).show(); + intent = new Intent(context, HermesSettingsActivity.class); + } else { + intent = new Intent(context, HermesVoiceActivity.class); + intent.putExtra(EXTRA_LAUNCH, requestedLaunch); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + } + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { context.startActivity(intent); } + catch (RuntimeException error) { + KeyRemappingManager.cancelPushToTalk(); + Toast.makeText(context, "Could not open Hermes. Enable MG Utility global keys in Accessibility.", + Toast.LENGTH_LONG).show(); + } + } + }); + } + + static synchronized void release() { + releasePending = true; + final HermesVoiceActivity activity = active.get(); + if (activity != null && activity.launchId == latestLaunch) activity.runOnUiThread(new Runnable() { + @Override public void run() { activity.releaseAndSubmit(); } + }); + } + + static synchronized void cancel() { + cancelPending = true; + final HermesVoiceActivity activity = active.get(); + if (activity != null && activity.launchId == latestLaunch) activity.runOnUiThread(new Runnable() { + @Override public void run() { activity.discardRecording(); activity.finish(); } + }); + } + + @Override public void onCreate(Bundle saved) { + super.onCreate(saved); + launchId = getIntent().getLongExtra(EXTRA_LAUNCH, 0L); + synchronized (HermesVoiceActivity.class) { + if (launchId != latestLaunch || cancelPending) { finish(); return; } + } + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + setContentView(buildUi()); + synchronized (HermesVoiceActivity.class) { active = new WeakReference(this); } + final boolean releasedBeforeReady; + synchronized (HermesVoiceActivity.class) { + releasedBeforeReady = releasePending; + releasePending = false; + } + if (android.os.Build.VERSION.SDK_INT >= 23 && + checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + state.setText("MICROPHONE ACCESS NEEDED"); + requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_PERMISSION); + } else { + startRecognition(); + } + if (releasedBeforeReady) MAIN.postDelayed(new Runnable() { + @Override public void run() { releaseAndSubmit(); } + }, 450L); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setGravity(Gravity.CENTER); + root.setPadding(55, 24, 55, 26); + root.setBackgroundColor(UiTheme.BACKGROUND); + + indicator = UiTheme.text(this, "●", 58, UiTheme.RED_BRIGHT, Typeface.BOLD); + indicator.setGravity(Gravity.CENTER); + root.addView(indicator, new LinearLayout.LayoutParams(-1, 82)); + state = UiTheme.text(this, "LISTENING • HOLD THE BUTTON", 20, UiTheme.CYAN_BRIGHT, Typeface.BOLD); + state.setGravity(Gravity.CENTER); + root.addView(state, new LinearLayout.LayoutParams(-1, 52)); + scope = new MicScopeView(this); + root.addView(scope, new LinearLayout.LayoutParams(-1, 30)); + transcript = UiTheme.text(this, "Speak now…", 24, UiTheme.TEXT, Typeface.NORMAL); + transcript.setGravity(Gravity.CENTER); + transcript.setPadding(28, 12, 28, 12); + transcript.setBackground(UiTheme.surface(UiTheme.SURFACE, 10)); + root.addView(transcript, new LinearLayout.LayoutParams(-1, 0, 1)); + TextView hint = UiTheme.text(this, "Release the steering-wheel button to send to Hermes", 13, + UiTheme.MUTED, Typeface.NORMAL); + hint.setGravity(Gravity.CENTER); + root.addView(hint, new LinearLayout.LayoutParams(-1, 48)); + return root; + } + + private void startRecognition() { + if (released || submitted || inactive()) return; + voiceConfig = HermesConfig.load(this); + if (HermesConfig.VOICE_ENGINE_SHERPA.equals(voiceConfig.voiceEngine)) { startLocalRecognition(); return; } + if (HermesConfig.VOICE_ENGINE_UPLOAD.equals(voiceConfig.voiceEngine)) { startRecording(); return; } + try { + if (!SpeechRecognizer.isRecognitionAvailable(this)) { startSystemRecognition(); return; } + if (recognizer == null) { + recognizer = SpeechRecognizer.createSpeechRecognizer(this); + recognizer.setRecognitionListener(this); + } + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); + intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + recognitionStarted = true; + recognizer.startListening(intent); + } catch (SecurityException error) { + recognitionStarted = false; destroyRecognizer(); startSystemRecognition(); + } catch (RuntimeException error) { + recognitionStarted = false; destroyRecognizer(); + fail("The Android speech service is unavailable. Select Local sherpa-onnx or Upload in Hermes settings."); + } + } + + private void startLocalRecognition() { + localRecognizer = new HermesLocalRecognizer(this); + audioCapture = new HermesAudioCapture(new File(getCacheDir(), "hermes-local-voice.wav"), + new HermesAudioCapture.SampleListener() { + @Override public void onSamples(float[] samples, int count) { + if (localRecognizer != null) localRecognizer.acceptSamples(samples, count); + } + @Override public void onLevel(final float level) { + MAIN.post(new Runnable() { @Override public void run() { if (scope != null && !destroyed) scope.setLevel(level); }}); + } + }); + localRecognizer.start(new HermesLocalRecognizer.Listener() { + @Override public void onPartial(String text) { if (!inactive() && !released) transcript.setText(text); } + @Override public void onFinal(String text) { if (!inactive() && !submitted) { partial = text; submitBestTranscript(); } } + @Override public void onError(String message) { if (!inactive()) fail(message); } + }); + if (!audioCapture.start()) { + if (localRecognizer != null) localRecognizer.cancel(); + fail("Could not open the microphone for local sherpa-onnx recognition"); + return; + } + state.setText("LOCAL SHERPA-ONNX • LISTENING"); + transcript.setText("Speak now… Audio stays on this head unit."); + } + + private void destroyRecognizer() { + if (recognizer != null) { + try { recognizer.cancel(); recognizer.destroy(); } catch (RuntimeException ignored) { } + recognizer = null; + } + } + + private void startSystemRecognition() { + if (systemRecognitionStarted || released || submitted || inactive()) return; + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to Hermes"); + intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); + intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + try { + systemRecognitionStarted = true; + state.setText("SYSTEM VOICE INPUT • SPEAK NOW"); + transcript.setText("The head unit voice dialog is listening. Finish speaking normally."); + startActivityForResult(intent, SYSTEM_RECOGNITION); + } catch (android.content.ActivityNotFoundException error) { + systemRecognitionStarted = false; + fail("This head unit does not expose its OEM voice input to third-party apps. " + + "Android Auto/OEM voice can still work privately, but MG Utility cannot read that audio."); + } catch (RuntimeException error) { + systemRecognitionStarted = false; + fail("The head unit rejected Android system voice input. Try the OEM assistant once, then try Hermes again."); + } + } + + private void startRecording() { + if (recorder != null) return; + try { + recording = File.createTempFile("hermes-voice-", ".m4a", getCacheDir()); + recorder = new MediaRecorder(); + recorder.setAudioSource(MediaRecorder.AudioSource.MIC); + recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); + recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); + recorder.setAudioChannels(1); + recorder.setAudioSamplingRate(16000); + recorder.setAudioEncodingBitRate(64000); + recorder.setOutputFile(recording.getAbsolutePath()); + recorder.setMaxDuration(60000); + recorder.setOnInfoListener(new MediaRecorder.OnInfoListener() { + @Override public void onInfo(MediaRecorder source, int what, int extra) { + if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) releaseAndSubmit(); + } + }); + recorder.setOnErrorListener(new MediaRecorder.OnErrorListener() { + @Override public void onError(MediaRecorder source, int what, int extra) { + discardRecording(); + fail("Microphone recording failed — try again"); + } + }); + recorder.prepare(); + recorder.start(); + state.setText("RECORDING • HOLD THE BUTTON"); + transcript.setText("Speak now… Your recording will be transcribed on release."); + } catch (Exception error) { + discardRecording(); + fail("Could not record audio. Check microphone permission and whether another app is using it."); + } + } + + private void discardRecording() { + if (recorder != null) { recorder.release(); recorder = null; } + if (recording != null) { recording.delete(); recording = null; } + } + + private void releaseAndSubmit() { + if (released || submitted || inactive()) return; + if (systemRecognitionStarted) { + state.setText("SYSTEM VOICE INPUT • FINISH SPEAKING"); + return; + } + released = true; + if (audioCapture != null) { + state.setText("FINISHING LOCAL TRANSCRIPT…"); + indicator.setTextColor(UiTheme.WARNING); + audioCapture.stop(); + audioCapture = null; + if (localRecognizer != null) { localRecognizer.finish(); localRecognizer = null; } + return; + } + if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + fail("Grant microphone access, then hold the button again"); + return; + } + if (recorder != null) { + try { recorder.stop(); } + catch (RuntimeException error) { + discardRecording(); + fail("Recording was too short — hold the button while speaking and try again"); + return; + } + recorder.release(); + recorder = null; + File audio = recording; + recording = null; + transcribing = true; + state.setText("TRANSCRIBING…"); + indicator.setTextColor(UiTheme.WARNING); + HermesTranscriptionClient.transcribe(voiceConfig, audio, new HermesTranscriptionClient.Callback() { + @Override public void complete(String text, String error) { + transcribing = false; + if (inactive() || submitted) return; + if (!error.isEmpty()) { fail(error); return; } + partial = text; + submitBestTranscript(); + } + }); + return; + } + state.setText("FINISHING TRANSCRIPT…"); + indicator.setTextColor(UiTheme.WARNING); + if (recognizer != null && recognitionStarted) recognizer.stopListening(); + // Some recognizers never send a final callback after an explicit stop. + MAIN.postDelayed(new Runnable() { @Override public void run() { submitBestTranscript(); } }, 1800L); + } + + private void submitBestTranscript() { + if (submitted || inactive() || transcribing) return; + String prompt = combined(partial).trim(); + if (prompt.length() == 0) { + fail("Nothing was heard — hold the button and try again"); + return; + } + submitted = true; + transcript.setText(prompt); + state.setText("SENDING TO HERMES…"); + indicator.setTextColor(UiTheme.CYAN_BRIGHT); + HermesApiClient.send(this, HermesConfig.load(this), prompt, new HermesApiClient.Callback() { + @Override public void complete(boolean success, String message, String assistantResponse) { + if (inactive()) return; + state.setText(success ? "HERMES REPLIED" : "NOT SENT"); + indicator.setText(success ? "H" : "!"); + indicator.setTextColor(success ? UiTheme.SUCCESS : UiTheme.WARNING); + transcript.setText(success && assistantResponse.length() > 0 ? assistantResponse : message); + MAIN.postDelayed(new Runnable() { @Override public void run() { finish(); } }, success ? 8000L : 4000L); + } + }); + } + + private void acceptResults(Bundle results, boolean finalResult) { + if (submitted || inactive()) return; + ArrayList values = results == null ? null : results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); + String best = values == null || values.isEmpty() ? "" : values.get(0).trim(); + if (finalResult) { + if (best.length() > 0) { + if (committed.length() > 0) committed.append(' '); + committed.append(best); + } + partial = ""; + } else { + partial = best; + } + String shown = combined(partial).trim(); + transcript.setText(shown.length() == 0 ? "Listening…" : shown); + if (finalResult) { + recognitionStarted = false; + if (released) submitBestTranscript(); + else MAIN.postDelayed(new Runnable() { @Override public void run() { startRecognition(); } }, 120L); + } + } + + private String combined(String tail) { + if (committed.length() == 0) return tail == null ? "" : tail; + if (tail == null || tail.length() == 0) return committed.toString(); + return committed.toString() + " " + tail; + } + + private boolean inactive() { + return destroyed || isFinishing() || launchId != latestLaunch || cancelPending; + } + + private void fail(String message) { + submitted = true; + state.setText("HERMES VOICE UNAVAILABLE"); + indicator.setText("!"); + indicator.setTextColor(UiTheme.WARNING); + transcript.setText(message); + MAIN.postDelayed(new Runnable() { @Override public void run() { finish(); } }, 3500L); + } + + @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { + super.onRequestPermissionsResult(requestCode, permissions, results); + if (requestCode != AUDIO_PERMISSION) return; + if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) { + startRecognition(); + synchronized (HermesVoiceActivity.class) { + if (releasePending) { + releasePending = false; + MAIN.postDelayed(new Runnable() { @Override public void run() { releaseAndSubmit(); } }, 450L); + } + } + } + else fail("Microphone permission was denied. Enable it from Hermes settings."); + } + + @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode != SYSTEM_RECOGNITION || !systemRecognitionStarted || inactive()) return; + systemRecognitionStarted = false; + if (resultCode != RESULT_OK || data == null) { + fail("No speech was returned by the head unit voice input"); + return; + } + ArrayList values = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); + String best = values == null || values.isEmpty() ? "" : values.get(0).trim(); + if (best.length() == 0) { + fail("The head unit voice input returned an empty transcript"); + return; + } + partial = best; + submitBestTranscript(); + } + + @Override protected void onDestroy() { + destroyed = true; + MAIN.removeCallbacksAndMessages(null); + discardRecording(); + if (audioCapture != null) { audioCapture.cancel(); audioCapture = null; } + if (localRecognizer != null) { localRecognizer.cancel(); localRecognizer = null; } + synchronized (HermesVoiceActivity.class) { + if (active.get() == this) active.clear(); + } + destroyRecognizer(); + super.onDestroy(); + } + + @Override public void onReadyForSpeech(Bundle params) { if (!inactive() && !released && !submitted) state.setText("LISTENING • HOLD THE BUTTON"); } + @Override public void onBeginningOfSpeech() { if (!inactive() && !released && !submitted) state.setText("HEARING YOU…"); } + @Override public void onRmsChanged(float rmsdB) { } + @Override public void onBufferReceived(byte[] buffer) { } + @Override public void onEndOfSpeech() { if (!inactive() && !released && !submitted) state.setText("LISTENING…"); } + @Override public void onError(int error) { + if (submitted || inactive()) return; + recognitionStarted = false; + if (released) { submitBestTranscript(); return; } + if (error == SpeechRecognizer.ERROR_NO_MATCH || error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) { + MAIN.postDelayed(new Runnable() { @Override public void run() { startRecognition(); } }, 180L); + } else fail("Speech recognizer error " + error); + } + @Override public void onResults(Bundle results) { acceptResults(results, true); } + @Override public void onPartialResults(Bundle partialResults) { acceptResults(partialResults, false); } + @Override public void onEvent(int eventType, Bundle params) { } +} diff --git a/src/cloud/molberg/mgutility/IconPack.java b/src/cloud/molberg/mgutility/IconPack.java new file mode 100644 index 0000000..93a6a9b --- /dev/null +++ b/src/cloud/molberg/mgutility/IconPack.java @@ -0,0 +1,46 @@ +package cloud.molberg.mgutility; + +/** Semantic mapping from app features to the bundled Material Icons vector pack. */ +final class IconPack { + private IconPack() { } + + static String forLabel(String value) { + if (value == null) return "help"; + String s = value.toLowerCase(java.util.Locale.ROOT); + if (s.contains("update") || s.contains("version")) return "system_update"; + if (s.contains("plugin")) return "extension"; + if (s.contains("export")) return "file_upload"; + if (s.contains("import")) return "file_download"; + if (s.contains("reset")) return "restart_alt"; + if (s.contains("trip") || s.contains("drive log")) return "map"; + if (s.contains("arrival") || s.contains("geofence")) return "place"; + if (s.contains("map") || s.contains("cache")) return "map"; + if (s.contains("charging") || s.contains("charge")) return "battery_charging_full"; + if (s.contains("energy") || s.contains("consumption")) return "bolt"; + if (s.contains("soundboard") || s.contains("music")) return "music_note"; + if (s.contains("audio") || s.contains("sound")) return "graphic_eq"; + if (s.contains("visualizer")) return "graphic_eq"; + if (s.contains("hermes") || s.contains("voice") || s.contains("mic")) return "mic"; + if (s.contains("setup") || s.contains("wizard")) return "build"; + if (s.contains("debug") || s.contains("diagnostic")) return "bug_report"; + if (s.contains("upload")) return "upload"; + if (s.contains("key") || s.contains("remap")) return "keyboard"; + if (s.contains("launcher") || s.contains("home")) return "home"; + if (s.contains("system settings") || s.contains("settings")) return "settings"; + if (s.contains("theme") || s.contains("appearance")) return "palette"; + if (s.contains("brightness")) return "brightness_6"; + if (s.contains("camping")) return "nightlight"; + if (s.contains("widget")) return "widgets"; + if (s.contains("drawer") || s.contains("app")) return "apps"; + if (s.contains("control panel") || s.contains("control")) return "tune"; + if (s.contains("speed") || s.contains("0–100")) return "speed"; + if (s.contains("sample interval") || s.contains("time")) return "schedule"; + if (s.contains("vehicle")) return "directions_car"; + if (s.contains("notify") || s.contains("notification")) return "notifications"; + if (s.contains("reorder")) return "swap_horiz"; + if (s.contains("page animation")) return "swap_horiz"; + if (s.contains("wifi")) return "wifi"; + if (s.contains("bluetooth")) return "bluetooth"; + return "dashboard"; + } +} diff --git a/src/cloud/molberg/mgutility/KeyRemappingAccessibilityService.java b/src/cloud/molberg/mgutility/KeyRemappingAccessibilityService.java new file mode 100644 index 0000000..03cec6c --- /dev/null +++ b/src/cloud/molberg/mgutility/KeyRemappingAccessibilityService.java @@ -0,0 +1,54 @@ +package cloud.molberg.mgutility; + +import android.accessibilityservice.AccessibilityService; +import android.accessibilityservice.AccessibilityServiceInfo; +import android.view.KeyEvent; + +/** + * Receives hardware keys before an OEM application consumes them. This is the + * same system-level hook used by dedicated key-remapper applications. Android + * requires the user to enable the service in Accessibility settings. + */ +public final class KeyRemappingAccessibilityService extends AccessibilityService { + private static boolean connected; + + static boolean isConnected() { return connected; } + + static void openSettings(android.content.Context context) { + android.content.Intent intent = new android.content.Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS); + intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK); + try { context.startActivity(intent); } + catch (android.content.ActivityNotFoundException error) { + android.widget.Toast.makeText(context, "Open Android Settings → Accessibility and enable MG Utility global keys", + android.widget.Toast.LENGTH_LONG).show(); + } + } + + @Override protected void onServiceConnected() { + super.onServiceConnected(); + AccessibilityServiceInfo info = getServiceInfo(); + if (info == null) info = new AccessibilityServiceInfo(); + info.eventTypes = 0; + info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC; + info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS; + info.notificationTimeout = 0; + setServiceInfo(info); + connected = true; + } + + @Override public boolean onKeyEvent(KeyEvent event) { + if (KeyRemappingActivity.consumeCapturedGlobalKey(event)) return true; + // Returning true is required for FLAG_REQUEST_FILTER_KEY_EVENTS to + // suppress the OEM action once a mapping claims this physical key. + return KeyRemappingManager.handle(this, event); + } + + @Override public void onAccessibilityEvent(android.view.accessibility.AccessibilityEvent event) { } + @Override public void onInterrupt() { KeyRemappingManager.cancelPushToTalk(); } + + @Override public void onDestroy() { + connected = false; + KeyRemappingManager.cancelPushToTalk(); + super.onDestroy(); + } +} diff --git a/src/cloud/molberg/mgutility/KeyRemappingActivity.java b/src/cloud/molberg/mgutility/KeyRemappingActivity.java index 4666a1b..87d20c9 100644 --- a/src/cloud/molberg/mgutility/KeyRemappingActivity.java +++ b/src/cloud/molberg/mgutility/KeyRemappingActivity.java @@ -31,7 +31,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -/** Settings page for physical head-unit key mappings. No accessibility service is required. */ +/** Settings page for physical head-unit key mappings. */ public final class KeyRemappingActivity extends AnimatedActivity { private long renderedThemeVersion; private static final int OPEN_FILE = 7101; @@ -39,16 +39,60 @@ public final class KeyRemappingActivity extends AnimatedActivity { private final ArrayList mappings = new ArrayList(); private LinearLayout list; private TextView captureStatus; + private TextView globalStatus; private boolean capturing; - private int capturedKeyCode; + private final PushToTalkPress capturePress = new PushToTalkPress(); private KeyRemappingManager.Mapping pending; + private static KeyRemappingActivity activeCaptureActivity; @Override public void onCreate(Bundle state) { - super.onCreate(state); UiTheme.applyFontScale(this); setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + super.onCreate(state); activeCaptureActivity = this; UiTheme.applyFontScale(this); setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); immersive(); mappings.addAll(KeyRemappingManager.load(this)); setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); render(); } + @Override protected void onDestroy() { if (activeCaptureActivity == this) activeCaptureActivity = null; super.onDestroy(); } + + /** Called by the global accessibility hook while this capture screen is open. */ + static boolean consumeCapturedGlobalKey(KeyEvent event) { + final KeyRemappingActivity activity = activeCaptureActivity; + if (activity == null || event == null) return false; + if (activity.consumeCaptureRelease(event)) return true; + if (!activity.capturing) return false; + final KeyEvent captured = new KeyEvent(event); + activity.runOnUiThread(new Runnable() { @Override public void run() { activity.capture(captured); } }); + return true; + } + + private boolean consumeCaptureRelease(KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_UP) return capturePress.end(event.getDeviceId(), + event.getKeyCode(), event.getScanCode(), event.getDownTime()); + return capturePress.matches(event.getDeviceId(), event.getKeyCode(), event.getScanCode(), event.getDownTime()); + } + + private void capture(KeyEvent event) { + if (!capturing || event.getAction() != KeyEvent.ACTION_DOWN || event.getRepeatCount() != 0) return; + int code = event.getKeyCode(); + if (code == KeyEvent.KEYCODE_BACK || code == KeyEvent.KEYCODE_VOLUME_DOWN) return; + if (code == KeyEvent.KEYCODE_UNKNOWN && event.getScanCode() == 0) { + captureStatus.setText("KEY NOT EXPOSED BY ANDROID • try another physical key"); return; + } + capturing = false; pending = new KeyRemappingManager.Mapping(); pending.keyCode = code; + capturePress.begin(event.getDeviceId(), code, event.getScanCode(), event.getDownTime(), 0); + pending.scanCode = event.getScanCode(); pending.deviceId = event.getDeviceId(); + InputDevice device = InputDevice.getDevice(event.getDeviceId()); pending.deviceName = device == null ? "unknown" : device.getName(); + captureStatus.setText("CAPTURED • " + KeyRemappingManager.keyLabel(code) + " • " + pending.deviceName); captureStatus.setTextColor(UiTheme.SUCCESS); + showMappingEditor(pending, -1); + } @Override public void onWindowFocusChanged(boolean focused) { super.onWindowFocusChanged(focused); if (focused) immersive(); } - @Override protected void onResume() { super.onResume(); UiTheme.refreshTheme(this); if (UiTheme.version() != renderedThemeVersion) { setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); render(); } } + @Override protected void onResume() { super.onResume(); UiTheme.refreshTheme(this); if (UiTheme.version() != renderedThemeVersion) { setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); render(); } updateGlobalStatus(); } + @Override protected void onPause() { capturing = false; super.onPause(); } + + private void updateGlobalStatus() { + if (globalStatus == null) return; + boolean connected = KeyRemappingAccessibilityService.isConnected(); + globalStatus.setText(connected ? "GLOBAL KEYS ACTIVE • Hermes works over other apps" : + "GLOBAL KEYS OFF • enable MG Utility global keys in Accessibility"); + globalStatus.setTextColor(connected ? UiTheme.SUCCESS : UiTheme.WARNING); + } private void immersive() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | @@ -66,35 +110,48 @@ public final class KeyRemappingActivity extends AnimatedActivity { Button back = UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); header.addView(export, new LinearLayout.LayoutParams(120, 52)); header.addView(importButton, new LinearLayout.LayoutParams(120, 52)); header.addView(reset, new LinearLayout.LayoutParams(120, 52)); header.addView(back, new LinearLayout.LayoutParams(120, 52)); root.addView(header); - TextView note = UiTheme.text(this, "MAP PHYSICAL HEAD-UNIT KEYS • read-only vehicle actions • mappings stay on this device", 11, UiTheme.MUTED, Typeface.NORMAL); + TextView note = UiTheme.text(this, "MAP PHYSICAL HEAD-UNIT KEYS • enable MG Utility in Accessibility for global/OEM steering-wheel keys", 11, UiTheme.MUTED, Typeface.NORMAL); note.setGravity(Gravity.CENTER_VERTICAL); root.addView(note, new LinearLayout.LayoutParams(-1, 28)); + LinearLayout global = new LinearLayout(this); + global.setGravity(Gravity.CENTER_VERTICAL); + globalStatus = UiTheme.text(this, "", 12, UiTheme.MUTED, Typeface.NORMAL); + global.addView(globalStatus, new LinearLayout.LayoutParams(0, 48, 1)); + global.addView(UiTheme.button(this, "GLOBAL KEY ACCESS", new View.OnClickListener() { + @Override public void onClick(View view) { KeyRemappingAccessibilityService.openSettings(KeyRemappingActivity.this); } + }, false), new LinearLayout.LayoutParams(210, 44)); + root.addView(global); + updateGlobalStatus(); LinearLayout capture = new LinearLayout(this); capture.setGravity(Gravity.CENTER_VERTICAL); capture.setPadding(14, 0, 14, 0); capture.setBackground(UiTheme.surface(UiTheme.SURFACE, 8)); captureStatus = UiTheme.text(this, "Press CAPTURE, then press a head-unit key", 14, UiTheme.TEXT, Typeface.NORMAL); captureStatus.setGravity(Gravity.CENTER_VERTICAL); capture.addView(captureStatus, new LinearLayout.LayoutParams(0, 58, 1)); Button captureButton = UiTheme.button(this, "CAPTURE KEY", new View.OnClickListener() { @Override public void onClick(View v) { beginCapture(); } }, true); capture.addView(captureButton, new LinearLayout.LayoutParams(150, 44)); root.addView(capture, new LinearLayout.LayoutParams(-1, 68)); ScrollView scroll = new ScrollView(this); list = new LinearLayout(this); list.setOrientation(LinearLayout.VERTICAL); list.setPadding(0, 10, 0, 0); scroll.addView(list); root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); - TextView footer = UiTheme.text(this, "Gestures: short, long (650 ms), double, or repeat. Emergency reset: hold BACK + VOLUME DOWN for 1.5 seconds.", 11, UiTheme.MUTED, Typeface.NORMAL); footer.setPadding(8, 8, 8, 0); root.addView(footer, new LinearLayout.LayoutParams(-1, 34)); + TextView footer = UiTheme.text(this, "Gestures: short, long, double, repeat, or push-to-talk. Emergency reset: hold BACK + VOLUME DOWN for 1.5 seconds.", 11, UiTheme.MUTED, Typeface.NORMAL); footer.setPadding(8, 8, 8, 0); root.addView(footer, new LinearLayout.LayoutParams(-1, 34)); return root; } - private void beginCapture() { capturing = true; captureStatus.setText("WAITING FOR NEXT KEY • press a physical key now"); captureStatus.setTextColor(UiTheme.CYAN_BRIGHT); } - @Override public boolean dispatchKeyEvent(KeyEvent event) { - if (capturing && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { - int code = event.getKeyCode(); if (code == KeyEvent.KEYCODE_BACK || code == KeyEvent.KEYCODE_VOLUME_DOWN) return true; - if (code == KeyEvent.KEYCODE_UNKNOWN) { captureStatus.setText("KEY NOT EXPOSED BY ANDROID • try another physical key"); return true; } - capturing = false; pending = new KeyRemappingManager.Mapping(); pending.keyCode = code; pending.scanCode = event.getScanCode(); pending.deviceId = event.getDeviceId(); - capturedKeyCode = code; - InputDevice device = InputDevice.getDevice(event.getDeviceId()); pending.deviceName = device == null ? "unknown" : device.getName(); - captureStatus.setText("CAPTURED • " + KeyRemappingManager.keyLabel(code) + " • " + pending.deviceName); captureStatus.setTextColor(UiTheme.SUCCESS); showMappingEditor(pending, -1); return true; + private void beginCapture() { + if (!accessibilityEnabled()) { + KeyRemappingAccessibilityService.openSettings(this); + captureStatus.setText("ENABLE MG UTILITY IN ACCESSIBILITY, THEN PRESS CAPTURE AGAIN"); + captureStatus.setTextColor(UiTheme.WARNING); return; } - if (!capturing && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == capturedKeyCode) { capturedKeyCode = 0; return true; } - if (!capturing && KeyRemappingManager.handle(this, event)) return true; + capturing = true; captureStatus.setText("WAITING FOR NEXT KEY • press a physical key now"); captureStatus.setTextColor(UiTheme.CYAN_BRIGHT); + } + + private boolean accessibilityEnabled() { + return KeyRemappingAccessibilityService.isConnected(); + } + @Override public boolean dispatchKeyEvent(KeyEvent event) { + if (consumeCaptureRelease(event)) return true; + if (capturing && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { capture(event); return true; } + return super.dispatchKeyEvent(event); } private void showMappingEditor(final KeyRemappingManager.Mapping mapping, final int editingIndex) { LinearLayout form = new LinearLayout(this); form.setOrientation(LinearLayout.VERTICAL); form.setPadding(8, 0, 8, 0); TextView key = UiTheme.text(this, "KEY " + KeyRemappingManager.keyLabel(mapping.keyCode) + " • scan " + mapping.scanCode + " • " + mapping.deviceName, 13, UiTheme.MUTED, Typeface.NORMAL); key.setPadding(4, 4, 4, 10); form.addView(key); - final Spinner gesture = spinner(new String[]{"Short press", "Long press", "Double press", "Press-and-hold / repeat"}, gestureIndex(mapping.gesture)); form.addView(labeled("GESTURE", gesture)); + final Spinner gesture = spinner(new String[]{"Short press", "Long press", "Double press", "Press-and-hold / repeat", "Push to talk (press / release)"}, gestureIndex(mapping.gesture)); form.addView(labeled("GESTURE", gesture)); String[] actionLabels = new String[KeyRemappingManager.ACTIONS.length]; for (int i = 0; i < actionLabels.length; i++) actionLabels[i] = KeyRemappingManager.ACTIONS[i].label; final Spinner action = spinner(actionLabels, actionIndex(mapping.action)); final ArrayAdapter actionAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, new ArrayList(java.util.Arrays.asList(actionLabels))); @@ -112,6 +169,7 @@ public final class KeyRemappingActivity extends AnimatedActivity { form.addView(labeled("ACTION", action)); form.addView(search, new LinearLayout.LayoutParams(-1, 48)); final EditText intentUri = new EditText(this); intentUri.setSingleLine(true); intentUri.setText(mapping.intentUri); intentUri.setHint("intent:#Intent;component=package/.Activity;end"); intentUri.setTextColor(UiTheme.TEXT); intentUri.setHintTextColor(UiTheme.MUTED); intentUri.setTextSize(15); intentUri.setPadding(8, 0, 8, 0); form.addView(intentUri, new LinearLayout.LayoutParams(-1, 48)); + final android.widget.CheckBox passThrough = new android.widget.CheckBox(this); passThrough.setText("Pass this key through to the OEM head unit"); passThrough.setTextColor(UiTheme.TEXT); passThrough.setChecked(mapping.passThrough); form.addView(passThrough, new LinearLayout.LayoutParams(-1, 48)); final TextView conflict = UiTheme.text(this, "", 12, UiTheme.WARNING, Typeface.NORMAL); conflict.setPadding(4, 8, 4, 0); form.addView(conflict); TextView warning = UiTheme.text(this, "CONFIRM OEM REPLACEMENT • saving this mapping may override the key's original head-unit action", 11, UiTheme.WARNING, Typeface.NORMAL); warning.setPadding(4, 8, 4, 0); form.addView(warning); final AlertDialog dialog = UiTheme.dialog(this).setTitle(editingIndex < 0 ? "ADD KEY MAPPING" : "EDIT KEY MAPPING").setView(form).setNegativeButton("CANCEL", null).setPositiveButton("SAVE", null).create(); @@ -119,9 +177,15 @@ public final class KeyRemappingActivity extends AnimatedActivity { @Override public void onShow(android.content.DialogInterface ignored) { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - mapping.gesture = new String[]{KeyRemappingManager.GESTURE_SHORT, KeyRemappingManager.GESTURE_LONG, KeyRemappingManager.GESTURE_DOUBLE, KeyRemappingManager.GESTURE_REPEAT}[gesture.getSelectedItemPosition()]; + mapping.gesture = new String[]{KeyRemappingManager.GESTURE_SHORT, KeyRemappingManager.GESTURE_LONG, KeyRemappingManager.GESTURE_DOUBLE, KeyRemappingManager.GESTURE_REPEAT, KeyRemappingManager.GESTURE_PUSH_TO_TALK}[gesture.getSelectedItemPosition()]; mapping.action = actionIdForLabel(action.getSelectedItem() == null ? "" : String.valueOf(action.getSelectedItem())); + // Hermes is inherently a down/up interaction. Prevent an easy-to-miss + // configuration where a short/long action opens the listener but can + // never deliver the matching release event. + if (KeyRemappingManager.ACTION_HERMES.equals(mapping.action)) + mapping.gesture = KeyRemappingManager.GESTURE_PUSH_TO_TALK; mapping.intentUri = intentUri.getText().toString().trim(); + mapping.passThrough = passThrough.isChecked(); if (hasConflict(mapping, editingIndex)) { conflict.setText("CONFLICT • another mapping already owns this key and gesture"); return; } if (editingIndex < 0) mappings.add(mapping); else mappings.set(editingIndex, mapping); KeyRemappingManager.save(KeyRemappingActivity.this, mappings); dialog.dismiss(); render(); } @@ -131,7 +195,7 @@ public final class KeyRemappingActivity extends AnimatedActivity { } private View labeled(String name, Spinner spinner) { LinearLayout row = new LinearLayout(this); row.setGravity(Gravity.CENTER_VERTICAL); TextView label = UiTheme.label(this, name); row.addView(label, new LinearLayout.LayoutParams(130, 52)); row.addView(spinner, new LinearLayout.LayoutParams(0, 52, 1)); return row; } private Spinner spinner(String[] values, int selected) { Spinner s = new Spinner(this); s.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, values)); s.setSelection(Math.max(0, selected)); return s; } - private int gestureIndex(String g) { if (KeyRemappingManager.GESTURE_LONG.equals(g)) return 1; if (KeyRemappingManager.GESTURE_DOUBLE.equals(g)) return 2; if (KeyRemappingManager.GESTURE_REPEAT.equals(g)) return 3; return 0; } + private int gestureIndex(String g) { if (KeyRemappingManager.GESTURE_LONG.equals(g)) return 1; if (KeyRemappingManager.GESTURE_DOUBLE.equals(g)) return 2; if (KeyRemappingManager.GESTURE_REPEAT.equals(g)) return 3; if (KeyRemappingManager.GESTURE_PUSH_TO_TALK.equals(g)) return 4; return 0; } private int actionIndex(String id) { for (int i = 0; i < KeyRemappingManager.ACTIONS.length; i++) if (KeyRemappingManager.ACTIONS[i].id.equals(id)) return i; return 0; } private String actionIdForLabel(String label) { for (KeyRemappingManager.Action a : KeyRemappingManager.ACTIONS) if (a.label.equals(label)) return a.id; return KeyRemappingManager.ACTION_DASHBOARD; } private boolean hasConflict(KeyRemappingManager.Mapping candidate, int editingIndex) { for (int i = 0; i < mappings.size(); i++) if (i != editingIndex && mappings.get(i).signature().equals(candidate.signature())) return true; return false; } diff --git a/src/cloud/molberg/mgutility/KeyRemappingManager.java b/src/cloud/molberg/mgutility/KeyRemappingManager.java index 40551e8..54b44cc 100644 --- a/src/cloud/molberg/mgutility/KeyRemappingManager.java +++ b/src/cloud/molberg/mgutility/KeyRemappingManager.java @@ -25,6 +25,7 @@ final class KeyRemappingManager { static final String GESTURE_LONG = "LONG"; static final String GESTURE_DOUBLE = "DOUBLE"; static final String GESTURE_REPEAT = "REPEAT"; + static final String GESTURE_PUSH_TO_TALK = "PUSH_TO_TALK"; static final long LONG_PRESS_MS = 650L; static final long DOUBLE_TAP_MS = 360L; @@ -40,6 +41,7 @@ final class KeyRemappingManager { static final String ACTION_SOUND_BOOT = "SOUND_BOOT"; static final String ACTION_SOUND_BEST = "SOUND_BEST"; static final String ACTION_SOUND_BATTERY = "SOUND_BATTERY"; + static final String ACTION_HERMES = "HERMES_VOICE"; static final String ACTION_USER_INTENT = "USER_INTENT"; static final class Action { @@ -64,6 +66,7 @@ final class KeyRemappingManager { new Action(ACTION_SOUND_BOOT, "Play car booted sound", "Saved soundboard event"), new Action(ACTION_SOUND_BEST, "Play personal-best sound", "Saved soundboard event"), new Action(ACTION_SOUND_BATTERY, "Play battery threshold sound", "Saved soundboard event"), + new Action(ACTION_HERMES, "Hermes voice assistant", "Hold a mapped key to dictate a prompt"), new Action(ACTION_USER_INTENT, "Open user-defined intent", "Explicit Android intent URI") }; @@ -76,11 +79,12 @@ final class KeyRemappingManager { String action = ACTION_DASHBOARD; String intentUri = ""; boolean enabled = true; + boolean passThrough = false; Mapping copy() { Mapping m = new Mapping(); m.deviceName = deviceName; m.deviceId = deviceId; m.keyCode = keyCode; m.scanCode = scanCode; m.gesture = gesture; - m.action = action; m.intentUri = intentUri; m.enabled = enabled; return m; + m.action = action; m.intentUri = intentUri; m.enabled = enabled; m.passThrough = passThrough; return m; } String signature() { return deviceId + ":" + keyCode + ":" + scanCode + ":" + gesture; } @@ -88,7 +92,7 @@ final class KeyRemappingManager { JSONObject o = new JSONObject(); o.put("deviceName", deviceName); o.put("deviceId", deviceId); o.put("keyCode", keyCode); o.put("scanCode", scanCode); - o.put("gesture", gesture); o.put("action", action); o.put("intentUri", intentUri); o.put("enabled", enabled); + o.put("gesture", gesture); o.put("action", action); o.put("intentUri", intentUri); o.put("enabled", enabled); o.put("passThrough", passThrough); return o; } static Mapping from(JSONObject o) { @@ -97,8 +101,10 @@ final class KeyRemappingManager { m.keyCode = o.optInt("keyCode", 0); m.scanCode = o.optInt("scanCode", 0); m.gesture = normalizeGesture(o.optString("gesture", GESTURE_SHORT)); m.action = knownAction(o.optString("action", ACTION_DASHBOARD)) ? o.optString("action") : ACTION_DASHBOARD; + if (ACTION_HERMES.equals(m.action)) m.gesture = GESTURE_PUSH_TO_TALK; m.intentUri = o.optString("intentUri", ""); - m.enabled = o.optBoolean("enabled", true); return m; + m.enabled = o.optBoolean("enabled", true); + m.passThrough = o.optBoolean("passThrough", false); return m; } } @@ -109,6 +115,15 @@ final class KeyRemappingManager { private static boolean volumeDownDown; private static long emergencyStarted; private static boolean emergencyFired; + private static Mapping activePushToTalk; + private static final PushToTalkPress PUSH_PRESS = new PushToTalkPress(); + + static void cancelPushToTalk() { + Mapping previous = activePushToTalk; + activePushToTalk = null; + PUSH_PRESS.clear(); + if (previous != null && ACTION_HERMES.equals(previous.action)) HermesVoiceActivity.cancel(); + } static List load(Context context) { ArrayList result = new ArrayList(); @@ -147,17 +162,23 @@ final class KeyRemappingManager { static Mapping find(List mappings, KeyEvent event, String gesture) { if (event == null) return null; - int deviceId = event.getDeviceId(); int scan = event.getScanCode(); - for (Mapping m : mappings) if (m.enabled && m.keyCode == event.getKeyCode() && + int deviceId = event.getDeviceId(); int scan = event.getScanCode(); int code = event.getKeyCode(); + // OEM steering-wheel buttons are often vendor/private keys. Android may + // expose only their scan code, or recreate the input device with a + // different transient id. The scan code is the stable physical identity. + if (scan != 0) for (Mapping m : mappings) if (m.enabled && m.scanCode == scan && + (m.keyCode == code || m.keyCode == KeyEvent.KEYCODE_UNKNOWN) && gesture.equals(m.gesture)) return m; + for (Mapping m : mappings) if (m.enabled && m.keyCode == code && m.scanCode == 0 && + gesture.equals(m.gesture)) return m; + // Legacy mappings captured before scan-code matching was added. + for (Mapping m : mappings) if (m.enabled && m.keyCode == code && m.scanCode == scan && m.deviceId == deviceId && gesture.equals(m.gesture)) return m; - // Some Android builds expose a different transient device id; retain scan-code safety. - if (scan != 0) for (Mapping m : mappings) if (m.enabled && m.keyCode == event.getKeyCode() && - m.scanCode == scan && gesture.equals(m.gesture)) return m; return null; } static String normalizeGesture(String value) { - if (GESTURE_LONG.equals(value) || GESTURE_DOUBLE.equals(value) || GESTURE_REPEAT.equals(value)) return value; + if (GESTURE_LONG.equals(value) || GESTURE_DOUBLE.equals(value) || GESTURE_REPEAT.equals(value) || + GESTURE_PUSH_TO_TALK.equals(value)) return value; return GESTURE_SHORT; } static boolean knownAction(String value) { for (Action a : ACTIONS) if (a.id.equals(value)) return true; return false; } @@ -166,6 +187,21 @@ final class KeyRemappingManager { static boolean handle(Context context, KeyEvent event) { if (event == null) return false; + if (event.getAction() == KeyEvent.ACTION_UP && PUSH_PRESS.end(event.getDeviceId(), + event.getKeyCode(), event.getScanCode(), event.getDownTime())) { + Mapping previous = activePushToTalk; + activePushToTalk = null; + if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) backDown = false; + if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) volumeDownDown = false; + if (!backDown || !volumeDownDown) emergencyStarted = 0L; + if (previous != null && ACTION_HERMES.equals(previous.action)) { + if (event.isCanceled()) HermesVoiceActivity.cancel(); + else HermesVoiceActivity.release(); + } + return true; + } + if (event.getAction() == KeyEvent.ACTION_DOWN && PUSH_PRESS.matches(event.getDeviceId(), + event.getKeyCode(), event.getScanCode(), event.getDownTime())) return true; int code = event.getKeyCode(); if (code == KeyEvent.KEYCODE_BACK || code == KeyEvent.KEYCODE_VOLUME_DOWN) { if (event.getAction() == KeyEvent.ACTION_DOWN) { @@ -189,24 +225,42 @@ final class KeyRemappingManager { List mappings = load(context); if (event.getAction() == KeyEvent.ACTION_DOWN) { if ((code == KeyEvent.KEYCODE_BACK && volumeDownDown) || (code == KeyEvent.KEYCODE_VOLUME_DOWN && backDown)) return true; - if (event.getRepeatCount() > 0) { Mapping repeat = find(mappings, event, GESTURE_REPEAT); if (repeat != null) { execute(context, repeat); return true; } return false; } + Mapping push = find(mappings, event, GESTURE_PUSH_TO_TALK); + if (push != null) { + if (PUSH_PRESS.begin(event.getDeviceId(), code, event.getScanCode(), + event.getDownTime(), event.getRepeatCount())) { + if (activePushToTalk != null && ACTION_HERMES.equals(activePushToTalk.action)) HermesVoiceActivity.cancel(); + activePushToTalk = push; + if (ACTION_HERMES.equals(push.action)) HermesVoiceActivity.begin(context); + else execute(context, push); + } + return !push.passThrough; + } + if (event.getRepeatCount() > 0) { Mapping repeat = find(mappings, event, GESTURE_REPEAT); if (repeat != null) { execute(context, repeat); return !repeat.passThrough; } return false; } DOWN_AT.put(code, event.getEventTime()); // Claim a mapped key on the down event too, so the OEM action cannot fire underneath // a configured MG Utility gesture. - return find(mappings, event, GESTURE_SHORT) != null || find(mappings, event, GESTURE_LONG) != null || - find(mappings, event, GESTURE_DOUBLE) != null; + Mapping shortMap = find(mappings, event, GESTURE_SHORT); + Mapping longMap = find(mappings, event, GESTURE_LONG); + Mapping doubleMap = find(mappings, event, GESTURE_DOUBLE); + Mapping repeatMap = find(mappings, event, GESTURE_REPEAT); + Mapping pushMap = find(mappings, event, GESTURE_PUSH_TO_TALK); + Mapping owner = pushMap != null ? pushMap : shortMap != null ? shortMap : longMap != null ? longMap : doubleMap != null ? doubleMap : repeatMap; + return owner != null && !owner.passThrough; } if (event.getAction() != KeyEvent.ACTION_UP) return false; if ((code == KeyEvent.KEYCODE_BACK && volumeDownDown) || (code == KeyEvent.KEYCODE_VOLUME_DOWN && backDown)) return true; + Mapping pushRelease = find(mappings, event, GESTURE_PUSH_TO_TALK); + if (pushRelease != null) return !pushRelease.passThrough; Long down = DOWN_AT.remove(code); long duration = down == null ? 0L : event.getEventTime() - down; final Mapping longMap = find(mappings, event, GESTURE_LONG); - if (duration >= LONG_PRESS_MS && longMap != null) { cancelSingle(code); execute(context, longMap); return true; } + if (duration >= LONG_PRESS_MS && longMap != null) { cancelSingle(code); execute(context, longMap); return !longMap.passThrough; } final Mapping doubleMap = find(mappings, event, GESTURE_DOUBLE); - if (doubleMap != null && SINGLE_PENDING.containsKey(code)) { cancelSingle(code); execute(context, doubleMap); return true; } + if (doubleMap != null && SINGLE_PENDING.containsKey(code)) { cancelSingle(code); execute(context, doubleMap); return !doubleMap.passThrough; } final Mapping shortMap = find(mappings, event, GESTURE_SHORT); if (shortMap != null) { Runnable pending = new Runnable() { @Override public void run() { execute(context, shortMap); SINGLE_PENDING.remove(eventKey(shortMap)); } }; - SINGLE_PENDING.put(code, pending); HANDLER.postDelayed(pending, DOUBLE_TAP_MS); return true; + SINGLE_PENDING.put(code, pending); HANDLER.postDelayed(pending, DOUBLE_TAP_MS); return !shortMap.passThrough; } // A double/long-only mapping still owns the key, including an unmatched // first tap or a short release below the long-press threshold. @@ -235,6 +289,7 @@ final class KeyRemappingManager { else if (ACTION_SOUND_BOOT.equals(action)) { SoundboardManager.play(context, SoundboardManager.EVENT_CAR_BOOTED); return; } else if (ACTION_SOUND_BEST.equals(action)) { SoundboardManager.play(context, SoundboardManager.EVENT_PERSONAL_BEST_REGEN); return; } else if (ACTION_SOUND_BATTERY.equals(action)) { SoundboardManager.play(context, SoundboardManager.EVENT_BATTERY_THRESHOLD); return; } + else if (ACTION_HERMES.equals(action)) { HermesVoiceActivity.begin(context); return; } else if (ACTION_USER_INTENT.equals(action)) { try { intent = Intent.parseUri(mapping.intentUri, Intent.URI_INTENT_SCHEME); } catch (Exception error) { Toast.makeText(context, "Invalid user intent URI", Toast.LENGTH_SHORT).show(); return; } diff --git a/src/cloud/molberg/mgutility/LiquidSoundBalanceActivity.java b/src/cloud/molberg/mgutility/LiquidSoundBalanceActivity.java new file mode 100644 index 0000000..ec242e5 --- /dev/null +++ b/src/cloud/molberg/mgutility/LiquidSoundBalanceActivity.java @@ -0,0 +1,314 @@ +package cloud.molberg.mgutility; + +import android.graphics.Typeface; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.SeekBar; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +/** Configure acceleration-reactive MG OEM sound-field fader changes. */ +public final class LiquidSoundBalanceActivity extends AnimatedActivity { + private Switch enabled; + private Switch bounce; + private Switch horizontalSway; + private Switch reverseSteering; + private SeekBar anchorX; + private SeekBar anchorY; + private TextView steeringStatus; + private Switch volumeBoost; + private SeekBar boostPercent; + private LiquidSoundFieldView soundField; + private TextView livePosition; + private final android.os.Handler statusHandler = new android.os.Handler(); + private final java.util.concurrent.ScheduledExecutorService liveReader = + java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + private java.util.concurrent.ScheduledFuture livePoll; + private volatile boolean monitoring; + private final SteeringAngleSource liveSteering = new SteeringAngleSource(); + private final Runnable refreshStatus = new Runnable() { + @Override public void run() { + if (!monitoring) return; + MgServiceBridge bridge = MgServiceBridge.get(); + final int balance = bridge.getSoundFieldBalance(); + final int fader = bridge.getSoundFieldFader(); + final int volume = bridge.getVolume(MgServiceBridge.VOL_TYPE_MEDIA); + liveSteering.read(); + final String steering = SteeringAngleSource.status(); + final LiquidSoundBalanceManager.Config cfg = LiquidSoundBalanceManager.config(LiquidSoundBalanceActivity.this); + final float multiplier = LiquidSoundBalanceCurve.volumeMultiplier(balance, fader, cfg.anchorX, + cfg.anchorY, cfg.enabled && cfg.volumeBoost, cfg.boostPercent); + statusHandler.post(new Runnable() { + @Override public void run() { + if (!monitoring) return; + steeringStatus.setText(steering); + soundField.update(balance, fader, cfg.anchorX, cfg.anchorY); + boolean valid = balance >= 0 && balance <= 14 && fader >= 0 && fader <= 14; + livePosition.setText((valid ? "OEM position: X " + balance + " / Y " + fader : + "OEM position unavailable — no simulated dot") + + "\nSaved resting point: X " + cfg.anchorX + " / Y " + cfg.anchorY + + "\nDistance boost target: +" + Math.round((multiplier - 1f) * 100f) + "%" + + " • Media volume: " + (volume >= 0 ? String.valueOf(volume) : "unavailable")); + } + }); + } + }; + private SeekBar threshold; + private SeekBar power; + private TextView thresholdValue; + private TextView powerValue; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + setContentView(buildUi()); + MgServiceBridge.get().ensureBound(this); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + @Override public void onResume() { + super.onResume(); + monitoring = true; + livePoll = liveReader.scheduleWithFixedDelay(refreshStatus, 0L, 200L, java.util.concurrent.TimeUnit.MILLISECONDS); + } + + @Override public void onPause() { + monitoring = false; + if (livePoll != null) livePoll.cancel(false); + statusHandler.removeCallbacksAndMessages(null); + super.onPause(); + } + + @Override public void onDestroy() { + liveReader.shutdownNow(); + super.onDestroy(); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + LiquidSoundBalanceManager.Config cfg = LiquidSoundBalanceManager.config(this); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(28, 16, 28, 16); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout bar = new LinearLayout(this); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.addView(UiTheme.title(this, "LIQUID SOUND BALANCE", 26), + new LinearLayout.LayoutParams(0, 58, 1)); + bar.addView(UiTheme.button(this, "SAVE & APPLY", new View.OnClickListener() { + @Override public void onClick(View view) { save(); } + }, true), new LinearLayout.LayoutParams(190, 58)); + Button back = UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View view) { finish(); } + }); + LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(120, 58); + backParams.setMargins(12, 0, 0, 0); + bar.addView(back, backParams); + root.addView(bar); + + TextView intro = text("Sound moves like a loose object: rearward when accelerating, forward when braking, and outward in turns. It settles at your chosen resting point.", 12, UiTheme.MUTED); + intro.setPadding(4, 4, 4, 10); + root.addView(intro); + + ScrollView scroll = new ScrollView(this); + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + list.setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); + LinearLayout monitor = new LinearLayout(this); + monitor.setOrientation(LinearLayout.VERTICAL); + soundField = new LiquidSoundFieldView(this); + soundField.update(-1, -1, cfg.anchorX, cfg.anchorY); + monitor.addView(soundField, new LinearLayout.LayoutParams(-1, + Math.round(250f * getResources().getDisplayMetrics().density))); + livePosition = text("Connecting to OEM sound service…", 11, UiTheme.TEXT); + monitor.addView(livePosition); + list.addView(card("LIVE CABIN • Red = OEM audio position / Gold = saved resting point", monitor)); + enabled = new Switch(this); + enabled.setText("ENABLE AUTOMATIC SOUND-FIELD MOVEMENT"); + enabled.setTextColor(UiTheme.TEXT); + enabled.setChecked(cfg.enabled); + list.addView(card("FEATURE", enabled)); + + anchorX = anchorSlider(cfg.anchorX, "Horizontal resting position"); + anchorY = anchorSlider(cfg.anchorY, "Front/rear resting position"); + list.addView(card("RESTING POINT X • 0 left / 7 center / 14 right", anchorRow(anchorX))); + list.addView(card("RESTING POINT Y • 0 front / 7 center / 14 rear", anchorRow(anchorY))); + list.addView(UiTheme.button(this, "RESET RESTING POINT TO CENTER", new View.OnClickListener() { + @Override public void onClick(View view) { + anchorX.setProgress(LiquidSoundBalanceCurve.CENTER); + anchorY.setProgress(LiquidSoundBalanceCurve.CENTER); + } + }, false)); + + threshold = new SeekBar(this); + UiTheme.tintSeekBar(threshold); + threshold.setMax(77); + threshold.setProgress(Math.round((cfg.thresholdKphPerSecond - 0.3f) * 10f)); + threshold.setContentDescription("Acceleration threshold in kilometres per hour per second"); + thresholdValue = valueLabel(String.format(java.util.Locale.US, "%.1f km/h/s", cfg.thresholdKphPerSecond)); + threshold.setOnSeekBarChangeListener(new SliderLabelListener(thresholdValue, true)); + list.addView(card("THRESHOLD • Ignore longitudinal / estimated cornering force below this level", sliderRow(threshold, thresholdValue))); + + power = new SeekBar(this); + UiTheme.tintSeekBar(power); + power.setMax(100); + power.setProgress(cfg.powerPercent); + power.setContentDescription("Sound-field movement power percent"); + powerValue = valueLabel(cfg.powerPercent + "%"); + power.setOnSeekBarChangeListener(new SliderLabelListener(powerValue, false)); + list.addView(card("POWER • Maximum movement from your resting point", sliderRow(power, powerValue))); + + volumeBoost = new Switch(this); + volumeBoost.setText("COMPENSATE VOLUME AWAY FROM RESTING POINT"); + volumeBoost.setTextColor(UiTheme.TEXT); + volumeBoost.setChecked(cfg.volumeBoost); + list.addView(card("DISTANCE VOLUME COMPENSATION", volumeBoost)); + boostPercent = new SeekBar(this); + UiTheme.tintSeekBar(boostPercent); + boostPercent.setMax(100); + boostPercent.setProgress(cfg.boostPercent); + boostPercent.setContentDescription("Maximum distance volume boost percent"); + final TextView boostLabel = valueLabel("+" + cfg.boostPercent + "%"); + boostPercent.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int value, boolean fromUser) { + boostLabel.setText("+" + value + "%"); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + list.addView(card("MAX BOOST • +0–100% of media volume setting; no boost at rest", sliderRow(boostPercent, boostLabel))); + + bounce = new Switch(this); + bounce.setText("BOUNCE BACK AND FORTH, THEN SETTLE"); + bounce.setTextColor(UiTheme.TEXT); + bounce.setChecked(cfg.bounce); + list.addView(card("BOUNCE", bounce)); + + horizontalSway = new Switch(this); + horizontalSway.setText("STEERING-DRIVEN LEFT / RIGHT MOVEMENT"); + horizontalSway.setTextColor(UiTheme.TEXT); + horizontalSway.setChecked(cfg.horizontalSway); + list.addView(card("HORIZONTAL SWAY • Off locks X to your resting point", horizontalSway)); + + reverseSteering = new Switch(this); + reverseSteering.setText("REVERSE STEERING SIGNAL DIRECTION"); + reverseSteering.setTextColor(UiTheme.TEXT); + reverseSteering.setChecked(cfg.reverseSteering); + list.addView(card("DIRECTION • Use only if sound moves inward instead of outward in turns", reverseSteering)); + steeringStatus = text(SteeringAngleSource.status(), 11, UiTheme.MUTED); + list.addView(card("LIVE STEERING • Vehicle property readback", steeringStatus)); + + TextView footer = text("Steering reads arcsoft.avm.mCurCarWheelAngle: −520° right / 0° center / +520° left. Cornering force is estimated from angle and speed, not a measured G sensor. Turning while parked causes no movement. Straight steady driving and disabling return to the saved anchor. Missing or invalid steering locks X to the anchor; the property has no timestamp to detect stale values. Distance compensation grows with actual OEM displacement (including diagonals), reaches the slider maximum at seven steps, and fades to normal at rest. It shares the speed-leveling volume controller, respects manual changes, never unmutes, and clips at the hardware maximum. Volume percentages scale the volume setting, not measured loudness. Configure while parked.", 11, UiTheme.MUTED); + footer.setPadding(14, 12, 14, 14); + list.addView(footer); + scroll.addView(list); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private final class SliderLabelListener implements SeekBar.OnSeekBarChangeListener { + private final TextView label; + private final boolean isThreshold; + SliderLabelListener(TextView label, boolean isThreshold) { this.label = label; this.isThreshold = isThreshold; } + @Override public void onProgressChanged(SeekBar bar, int value, boolean fromUser) { + label.setText(isThreshold ? String.format(java.util.Locale.US, "%.1f km/h/s", 0.3f + value / 10f) : value + "%"); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + } + + private View sliderRow(SeekBar slider, TextView value) { + LinearLayout row = new LinearLayout(this); + row.setGravity(Gravity.CENTER_VERTICAL); + row.addView(slider, new LinearLayout.LayoutParams(0, 54, 1)); + row.addView(value, new LinearLayout.LayoutParams(150, 54)); + return row; + } + + private SeekBar anchorSlider(int position, String description) { + SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); + slider.setMax(LiquidSoundBalanceCurve.MAX_FADER); + slider.setProgress(position); + slider.setContentDescription(description); + return slider; + } + + private View anchorRow(SeekBar slider) { + final TextView label = valueLabel(slider.getProgress() + " / 14"); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int value, boolean fromUser) { + label.setText(value + " / 14"); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + return sliderRow(slider, label); + } + + private View card(String title, View body) { + LinearLayout card = new LinearLayout(this); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(14, 10, 14, 10); + card.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10)); + card.addView(text(title, 12, UiTheme.TEXT)); + card.addView(body); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.setMargins(8, 8, 8, 0); + card.setLayoutParams(params); + return card; + } + + private TextView valueLabel(String value) { + TextView label = text(value, 11, UiTheme.RED); + label.setGravity(Gravity.CENTER); + return label; + } + + private TextView text(String value, int size, int color) { + TextView view = new TextView(this); + view.setText(value); + view.setTextSize(size * 1.25f); + view.setTextColor(color); + view.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL)); + return view; + } + + private void save() { + LiquidSoundBalanceManager.save(this, enabled.isChecked(), 0.3f + threshold.getProgress() / 10f, + power.getProgress(), bounce.isChecked(), horizontalSway.isChecked(), + anchorX.getProgress(), anchorY.getProgress(), reverseSteering.isChecked(), + volumeBoost.isChecked(), boostPercent.getProgress()); + MgServiceBridge.get().ensureBound(this); + if (!enabled.isChecked()) { + liveReader.execute(new Runnable() { + @Override public void run() { + LiquidSoundBalanceManager.Config cfg = LiquidSoundBalanceManager.config(LiquidSoundBalanceActivity.this); + if (!cfg.enabled) MgServiceBridge.get().setSoundField(cfg.anchorX, cfg.anchorY); + } + }); + } + Toast.makeText(this, "Liquid Sound Balance settings saved", Toast.LENGTH_SHORT).show(); + } +} diff --git a/src/cloud/molberg/mgutility/LiquidSoundBalanceCurve.java b/src/cloud/molberg/mgutility/LiquidSoundBalanceCurve.java new file mode 100644 index 0000000..9e905d9 --- /dev/null +++ b/src/cloud/molberg/mgutility/LiquidSoundBalanceCurve.java @@ -0,0 +1,66 @@ +package cloud.molberg.mgutility; + +/** Pure force-to-OEM-position mapping. */ +public final class LiquidSoundBalanceCurve { + public static final int MIN_FADER = 0; + public static final int MAX_FADER = 14; + public static final int CENTER = (MIN_FADER + MAX_FADER) / 2; + private static final float DEAD_BAND_KPH_PER_SECOND = 0.35f; + + private LiquidSoundBalanceCurve() { } + + public static float parseSteering(String value) { + try { + float angle = Float.parseFloat(value); + return finite(angle) && Math.abs(angle) <= 520f ? angle : Float.NaN; + } catch (RuntimeException ignored) { return Float.NaN; } + } + + public static float volumeMultiplier(int balance, int fader, int anchorX, int anchorY, + boolean enabled, int boostPercent) { + if (!enabled || balance < MIN_FADER || balance > MAX_FADER || + fader < MIN_FADER || fader > MAX_FADER) return 1f; + float distance = (float) Math.hypot(balance - clampFader(anchorX), fader - clampFader(anchorY)); + return 1f + Math.min(1f, distance / CENTER) * clamp(boostPercent, 0, 100) / 100f; + } + + /** Positive longitudinal acceleration moves sound rearward; braking moves it forward. */ + public static int targetFader(float accelerationKphPerSecond, + float thresholdKphPerSecond, int powerPercent) { + if (!finite(accelerationKphPerSecond) || !finite(thresholdKphPerSecond)) return 0; + float threshold = Math.max(0.1f, thresholdKphPerSecond); + float magnitude = Math.abs(accelerationKphPerSecond); + if (magnitude < Math.max(DEAD_BAND_KPH_PER_SECOND, threshold * 0.12f)) return 0; + float strength = clamp((magnitude - threshold) / Math.max(0.1f, threshold * 2f), 0f, 1f); + int safePower = clamp(powerPercent, 0, 100); + if (safePower == 0) return 0; + int extent = Math.round(7f * safePower / 100f * strength); + if (extent == 0 && magnitude >= threshold) extent = 1; + return accelerationKphPerSecond > 0f ? extent : -extent; + } + + public static float lateralAcceleration(float speedKph, float steeringDegrees, boolean reverseSteering) { + if (!finite(speedKph) || !finite(steeringDegrees) || speedKph < 2f || speedKph > 300f || + Math.abs(steeringDegrees) > 520f) return 0f; + if (Math.abs(steeringDegrees) < 1f) return 0f; + float speedMetersPerSecond = speedKph / 3.6f; + double roadWheelRadians = Math.toRadians(steeringDegrees / 15f); + float acceleration = (float) (speedMetersPerSecond * speedMetersPerSecond * + Math.tan(roadWheelRadians) / 2.7 * 3.6); + return reverseSteering ? -acceleration : acceleration; + } + + public static int clampFader(int value) { return Math.max(MIN_FADER, Math.min(MAX_FADER, value)); } + + public static int positionForOffset(int offset) { + return positionForOffset(CENTER, offset); + } + + public static int positionForOffset(int anchor, int offset) { + return clampFader(clampFader(anchor) + clamp(offset, -MAX_FADER, MAX_FADER)); + } + + private static int clamp(int value, int min, int max) { return Math.max(min, Math.min(max, value)); } + private static float clamp(float value, float min, float max) { return Math.max(min, Math.min(max, value)); } + private static boolean finite(float value) { return !Float.isNaN(value) && !Float.isInfinite(value); } +} diff --git a/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java b/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java new file mode 100644 index 0000000..7db3446 --- /dev/null +++ b/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java @@ -0,0 +1,97 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; + +/** Persistence and controls for Liquid Sound Balance. */ +public final class LiquidSoundBalanceManager { + private static final String PREFS = "liquid_sound_balance"; + private static final String KEY_ENABLED = "enabled"; + private static final String KEY_THRESHOLD = "threshold_kph_s"; + private static final String KEY_POWER = "power_percent"; + private static final String KEY_BOUNCE = "bounce"; + private static final String KEY_HORIZONTAL_SWAY = "horizontal_sway"; + private static final String KEY_ANCHOR_X = "anchor_x"; + private static final String KEY_ANCHOR_Y = "anchor_y"; + private static final String KEY_REVERSE_STEERING = "reverse_steering"; + private static final String KEY_VOLUME_BOOST = "volume_boost"; + private static final String KEY_BOOST_PERCENT = "boost_percent"; + public static final float DEFAULT_THRESHOLD = 1.5f; + public static final int DEFAULT_POWER = 65; + + private LiquidSoundBalanceManager() { } + + public static final class Config { + public final boolean enabled; + public final float thresholdKphPerSecond; + public final int powerPercent; + public final boolean bounce; + public final boolean horizontalSway; + public final int anchorX; + public final int anchorY; + public final boolean reverseSteering; + public final boolean volumeBoost; + public final int boostPercent; + + Config(boolean enabled, float threshold, int power, boolean bounce, boolean horizontalSway, + int anchorX, int anchorY, boolean reverseSteering, boolean volumeBoost, int boostPercent) { + this.enabled = enabled; + this.thresholdKphPerSecond = Float.isNaN(threshold) || Float.isInfinite(threshold) + ? DEFAULT_THRESHOLD : Math.max(0.3f, Math.min(8f, threshold)); + this.powerPercent = Math.max(0, Math.min(100, power)); + this.bounce = bounce; + this.horizontalSway = horizontalSway; + this.anchorX = LiquidSoundBalanceCurve.clampFader(anchorX); + this.anchorY = LiquidSoundBalanceCurve.clampFader(anchorY); + this.reverseSteering = reverseSteering; + this.volumeBoost = volumeBoost; + this.boostPercent = Math.max(0, Math.min(100, boostPercent)); + } + } + + public static Config config(Context context) { + if (context == null) return defaults(); + SharedPreferences prefs = preferences(context); + return new Config(prefs.getBoolean(KEY_ENABLED, false), + prefs.getFloat(KEY_THRESHOLD, DEFAULT_THRESHOLD), + prefs.getInt(KEY_POWER, DEFAULT_POWER), prefs.getBoolean(KEY_BOUNCE, true), + prefs.getBoolean(KEY_HORIZONTAL_SWAY, false), + prefs.getInt(KEY_ANCHOR_X, LiquidSoundBalanceCurve.CENTER), + prefs.getInt(KEY_ANCHOR_Y, LiquidSoundBalanceCurve.CENTER), + prefs.getBoolean(KEY_REVERSE_STEERING, false), + prefs.getBoolean(KEY_VOLUME_BOOST, false), prefs.getInt(KEY_BOOST_PERCENT, 25)); + } + + public static boolean shouldPoll(Context context) { return config(context).enabled; } + + public static void save(Context context, boolean enabled, float threshold, + int power, boolean bounce, boolean horizontalSway) { + Config current = config(context); + save(context, enabled, threshold, power, bounce, horizontalSway, + current.anchorX, current.anchorY, current.reverseSteering, current.volumeBoost, current.boostPercent); + } + + public static void save(Context context, boolean enabled, float threshold, + int power, boolean bounce, boolean horizontalSway, int anchorX, int anchorY, boolean reverseSteering, + boolean volumeBoost, int boostPercent) { + if (context == null) return; + Config safe = new Config(enabled, threshold, power, bounce, horizontalSway, anchorX, anchorY, + reverseSteering, volumeBoost, boostPercent); + preferences(context).edit().putBoolean(KEY_ENABLED, safe.enabled) + .putFloat(KEY_THRESHOLD, safe.thresholdKphPerSecond) + .putInt(KEY_POWER, safe.powerPercent).putBoolean(KEY_BOUNCE, safe.bounce) + .putBoolean(KEY_HORIZONTAL_SWAY, safe.horizontalSway) + .putInt(KEY_ANCHOR_X, safe.anchorX).putInt(KEY_ANCHOR_Y, safe.anchorY) + .putBoolean(KEY_REVERSE_STEERING, safe.reverseSteering) + .putBoolean(KEY_VOLUME_BOOST, safe.volumeBoost).putInt(KEY_BOOST_PERCENT, safe.boostPercent).apply(); + } + + private static Config defaults() { + return new Config(false, DEFAULT_THRESHOLD, DEFAULT_POWER, true, false, + LiquidSoundBalanceCurve.CENTER, LiquidSoundBalanceCurve.CENTER, false, false, 25); + } + + private static SharedPreferences preferences(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/cloud/molberg/mgutility/LiquidSoundBalanceMotion.java b/src/cloud/molberg/mgutility/LiquidSoundBalanceMotion.java new file mode 100644 index 0000000..7a4c302 --- /dev/null +++ b/src/cloud/molberg/mgutility/LiquidSoundBalanceMotion.java @@ -0,0 +1,64 @@ +package cloud.molberg.mgutility; + +public final class LiquidSoundBalanceMotion { + private final Axis horizontal = new Axis(); + private final Axis longitudinal = new Axis(); + + public void reset() { + horizontal.reset(); + longitudinal.reset(); + } + + public void update(float acceleration, float speed, float steering, float threshold, int power, + boolean sway, boolean reverseSteering, boolean bounce, int anchorX, int anchorY, float seconds) { + if (Float.isNaN(seconds) || Float.isInfinite(seconds) || seconds <= 0f || seconds > 2f || power <= 0) { + reset(); + return; + } + float lateral = LiquidSoundBalanceCurve.lateralAcceleration(speed, steering, reverseSteering); + int targetX = sway ? LiquidSoundBalanceCurve.targetFader(lateral, threshold, power) : 0; + int targetY = LiquidSoundBalanceCurve.targetFader(acceleration, threshold, power); + int extent = Math.max(1, Math.round(7f * Math.min(100, power) / 100f)); + if (!sway || Float.isNaN(steering) || Float.isInfinite(steering) || Math.abs(steering) > 520f) { + horizontal.reset(); + } else { + horizontal.update(targetX, anchorX, extent, bounce, seconds); + } + longitudinal.update(targetY, anchorY, extent, bounce, seconds); + } + + public int balance(int anchor) { + return LiquidSoundBalanceCurve.positionForOffset(anchor, Math.round(horizontal.position)); + } + + public int fader(int anchor) { + return LiquidSoundBalanceCurve.positionForOffset(anchor, Math.round(longitudinal.position)); + } + + private static final class Axis { + private float position; + private float velocity; + + void reset() { position = 0f; velocity = 0f; } + + void update(float target, int anchor, int extent, boolean bounce, float seconds) { + int safeAnchor = LiquidSoundBalanceCurve.clampFader(anchor); + float min = Math.max(-extent, -safeAnchor); + float max = Math.min(extent, LiquidSoundBalanceCurve.MAX_FADER - safeAnchor); + target = Math.max(min, Math.min(max, target)); + int steps = Math.max(1, (int) Math.ceil(seconds / 0.01f)); + float step = seconds / steps; + float damping = bounce ? 7f : 14f; + for (int index = 0; index < steps; index++) { + velocity += (49f * (target - position) - damping * velocity) * step; + position += velocity * step; + if (position < min) { position = min; velocity = Math.max(0f, velocity); } + if (position > max) { position = max; velocity = Math.min(0f, velocity); } + } + if (Math.abs(position - target) < 0.01f && Math.abs(velocity) < 0.01f) { + position = target; + velocity = 0f; + } + } + } +} diff --git a/src/cloud/molberg/mgutility/LiquidSoundFieldView.java b/src/cloud/molberg/mgutility/LiquidSoundFieldView.java new file mode 100644 index 0000000..15ba32e --- /dev/null +++ b/src/cloud/molberg/mgutility/LiquidSoundFieldView.java @@ -0,0 +1,89 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.RectF; +import android.view.View; + +final class LiquidSoundFieldView extends View { + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private int balance = -1; + private int fader = -1; + private int anchorX = 7; + private int anchorY = 7; + + LiquidSoundFieldView(Context context) { + super(context); + setContentDescription("Live audio position unavailable"); + } + + void update(int balance, int fader, int anchorX, int anchorY) { + this.balance = balance; + this.fader = fader; + this.anchorX = anchorX; + this.anchorY = anchorY; + setContentDescription(validPosition() ? "Live audio X " + balance + ", Y " + fader + + "; resting point X " + anchorX + ", Y " + anchorY : "Live audio position unavailable"); + invalidate(); + } + + private boolean validPosition() { + return balance >= 0 && balance <= 14 && fader >= 0 && fader <= 14; + } + + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + float scale = getResources().getDisplayMetrics().density; + float top = 32f * scale; + float bottom = getHeight() - 36f * scale; + float center = getWidth() / 2f; + float halfWidth = Math.min(getWidth() * 0.3f, (bottom - top) * 0.38f); + float left = center - halfWidth; + float right = center + halfWidth; + paint.setStyle(Paint.Style.FILL); + paint.setColor(UiTheme.SURFACE); + canvas.drawRoundRect(new RectF(left - 15f * scale, top - 12f * scale, + right + 15f * scale, bottom + 12f * scale), 28f * scale, 28f * scale, paint); + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(2f * scale); + paint.setColor(UiTheme.MUTED); + canvas.drawRoundRect(new RectF(left - 15f * scale, top - 12f * scale, + right + 15f * scale, bottom + 12f * scale), 28f * scale, 28f * scale, paint); + paint.setStrokeWidth(scale); + paint.setAlpha(50); + for (int index = 0; index <= 14; index++) { + float horizontal = left + (right - left) * index / 14f; + float vertical = top + (bottom - top) * index / 14f; + canvas.drawLine(horizontal, top, horizontal, bottom, paint); + canvas.drawLine(left, vertical, right, vertical, paint); + } + paint.setAlpha(255); + paint.setStyle(Paint.Style.FILL); + paint.setTextSize(12f * scale); + paint.setTextAlign(Paint.Align.CENTER); + canvas.drawText("FRONT", center, 14f * scale, paint); + canvas.drawText("REAR", center, getHeight() - 3f * scale, paint); + canvas.drawText("LEFT", left - 45f * scale, (top + bottom) / 2f, paint); + canvas.drawText("RIGHT", right + 45f * scale, (top + bottom) / 2f, paint); + float restingX = left + (right - left) * anchorX / 14f; + float restingY = top + (bottom - top) * anchorY / 14f; + paint.setColor(0xffffc066); + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(2f * scale); + canvas.drawCircle(restingX, restingY, 9f * scale, paint); + canvas.drawLine(restingX - 13f * scale, restingY, restingX + 13f * scale, restingY, paint); + canvas.drawLine(restingX, restingY - 13f * scale, restingX, restingY + 13f * scale, paint); + if (validPosition()) { + float currentX = left + (right - left) * balance / 14f; + float currentY = top + (bottom - top) * fader / 14f; + paint.setColor(UiTheme.RED); + paint.setAlpha(100); + canvas.drawLine(restingX, restingY, currentX, currentY, paint); + paint.setStyle(Paint.Style.FILL); + canvas.drawCircle(currentX, currentY, 14f * scale, paint); + paint.setAlpha(255); + canvas.drawCircle(currentX, currentY, 6f * scale, paint); + } + } +} diff --git a/src/cloud/molberg/mgutility/MainActivity.java b/src/cloud/molberg/mgutility/MainActivity.java index f747cf0..8fb9746 100644 --- a/src/cloud/molberg/mgutility/MainActivity.java +++ b/src/cloud/molberg/mgutility/MainActivity.java @@ -64,6 +64,8 @@ import android.webkit.WebViewClient; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; import java.nio.ByteBuffer; @@ -76,6 +78,7 @@ import java.util.Locale; * settings page; this activity remains a read-only dashboard and manual entry point. */ public class MainActivity extends AnimatedActivity { + private static final String CRASH_MARKER = "mg_analytics_unclean_exit"; // Theme colors are read directly from UiTheme; capturing them as static final // aliases snapshots the palette at class-init time and prevents later theme // changes from propagating without restarting the process. @@ -107,6 +110,7 @@ public class MainActivity extends AnimatedActivity { private AppDrawerOverlay appDrawer; private ControlPanelOverlay controlPanel; private WidgetsPanelOverlay widgetsPanel; + private CampingModeController campingModeController; private float appDrawerTouchDownY; private boolean appDrawerTrackingTouch; private float controlPanelTouchDownY; @@ -127,6 +131,7 @@ public class MainActivity extends AnimatedActivity { private boolean gaugeReadInFlight; private boolean speedReadInFlight; private boolean applicationStarted; + private String pendingRemoteAnnouncement; private final Runnable dismissBoot = new Runnable() { @Override public void run() { finishBootAnimation(); } }; @@ -162,6 +167,21 @@ public class MainActivity extends AnimatedActivity { @Override public void onCreate(Bundle state) { super.onCreate(state); + installCrashCapture(); + getSharedPreferences("remote_diagnostics", MODE_PRIVATE).edit().remove(CRASH_MARKER).apply(); + DiagnosticsClient.refreshConfig(this, new DiagnosticsClient.Callback() { + @Override public void complete(final String message) { + runOnUiThread(new Runnable() { + @Override public void run() { + pendingRemoteAnnouncement = message; + if (applicationStarted) showRemoteAnnouncement(message); + } + }); + } + }); + // Keep the periodic Gitea check alive even when the user never opens + // Settings. JobScheduler persists this across restarts and reboots. + UpdateScheduler.schedule(this); BrightnessScheduler.rearm(this); UiTheme.applyFontScale(this); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); @@ -173,6 +193,7 @@ public class MainActivity extends AnimatedActivity { installAppDrawerOverlay(); installControlPanelOverlay(); installWidgetsPanelOverlay(); + attachCampingModeController(); if (getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean(PREF_BOOT_SEEN, false)) { startApplication(); } else { @@ -180,6 +201,28 @@ public class MainActivity extends AnimatedActivity { } } + private void installCrashCapture() { + final android.content.SharedPreferences prefs = getSharedPreferences("remote_diagnostics", MODE_PRIVATE); + if (prefs.contains(CRASH_MARKER)) { + String type = prefs.getString("crash_type", "java.lang.RuntimeException"); + String message = prefs.getString("crash_message", "Previous app process exited unexpectedly"); + String stack = prefs.getString("crash_stack", ""); + DiagnosticsClient.queueCrash(this, type, message, stack); + } + prefs.edit().putBoolean(CRASH_MARKER, true).commit(); + final Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override public void uncaughtException(Thread thread, Throwable error) { + StringWriter trace = new StringWriter(); + error.printStackTrace(new PrintWriter(trace)); + prefs.edit().putString("crash_type", error.getClass().getName()) + .putString("crash_message", error.getMessage() == null ? "" : error.getMessage()) + .putString("crash_stack", trace.toString().substring(0, Math.min(trace.toString().length(), 12000))).commit(); + if (previous != null) previous.uncaughtException(thread, error); + } + }); + } + /** Read-only now-playing card: metadata comes from the active system media session. */ private static final class MusicPlayerPanel extends FrameLayout { private final TextView title, artist, status, elapsed, duration; @@ -660,6 +703,17 @@ public class MainActivity extends AnimatedActivity { if (focused) immersive(); } + void setCampingModeEnabled(boolean enabled) { + if (campingModeController == null) campingModeController = new CampingModeController(this); + campingModeController.setEnabled(enabled); + } + + private void attachCampingModeController() { + if (screenRoot == null) return; + if (campingModeController == null) campingModeController = new CampingModeController(this); + campingModeController.attach(screenRoot); + } + @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); @@ -686,6 +740,7 @@ public class MainActivity extends AnimatedActivity { installWidgetsPanelOverlay(); renderedThemeVersion = UiTheme.version(); } + attachCampingModeController(); // Returning to the launcher after another app was opened (for example by // pressing the Android Home button) always starts on the normal home screen. // Do not leave the app drawer persisted over that launcher transition. @@ -712,6 +767,7 @@ public class MainActivity extends AnimatedActivity { @Override protected void onPause() { if (dashboardGauges != null) dashboardGauges.stopVisualizer(); MusicPlayerManager.setListener(null); + if (campingModeController != null) campingModeController.onActivityPaused(); super.onPause(); } @@ -740,6 +796,7 @@ public class MainActivity extends AnimatedActivity { handler.removeCallbacks(gaugeRefresh); handler.removeCallbacks(speedRefresh); handler.removeCallbacks(dismissBoot); + if (campingModeController != null) campingModeController.onActivityDestroyed(); if (vehicleServiceBindingRequested) { try { unbindService(vehicleConnection); } catch (Exception ignored) { } vehicleServiceBindingRequested = false; @@ -771,6 +828,11 @@ public class MainActivity extends AnimatedActivity { private void startApplication() { if (applicationStarted) return; applicationStarted = true; + showRemoteAnnouncement(pendingRemoteAnnouncement); + cloud.molberg.mgutility.plugin.PluginHostEvents.publish( + new cloud.molberg.mgutility.sdk.HookEvent( + cloud.molberg.mgutility.sdk.PluginHook.APP_STARTED, + System.currentTimeMillis(), null)); TripTrackingService.start(this); requestLocationAccess(); probeVehicleService(); @@ -807,6 +869,26 @@ public class MainActivity extends AnimatedActivity { screenRoot.addView(banner, screenBannerParams); } + private void showRemoteAnnouncement(String message) { + if (screenRoot == null || message == null || message.trim().isEmpty()) return; + final LinearLayout banner = new LinearLayout(this); + banner.setOrientation(LinearLayout.HORIZONTAL); + banner.setGravity(Gravity.CENTER_VERTICAL); + banner.setBackgroundColor(UiTheme.withAlpha(UiTheme.CYAN, 46)); + TextView copy = UiTheme.text(this, message.trim(), 13, UiTheme.TEXT, Typeface.NORMAL); + copy.setPadding(UiTheme.dp(this, 16), UiTheme.dp(this, 12), UiTheme.dp(this, 12), UiTheme.dp(this, 12)); + banner.addView(copy, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); + Button dismiss = UiTheme.button(this, "DISMISS", new View.OnClickListener() { + @Override public void onClick(View v) { screenRoot.removeView(banner); } + }, false); + LinearLayout.LayoutParams dismissParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UiTheme.dp(this, 48)); + dismissParams.setMargins(0, 0, UiTheme.dp(this, 12), 0); + banner.addView(dismiss, dismissParams); + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(-1, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.FILL_HORIZONTAL); + params.setMargins(UiTheme.dp(this, 12), UiTheme.dp(this, 12), UiTheme.dp(this, 12), 0); + screenRoot.addView(banner, params); + } + /** Auto-launch the setup wizard on the very first run of a new install. */ private void maybeRunSetupWizard() { if (SetupWizardActivity.isCompleted(this)) return; @@ -829,13 +911,14 @@ public class MainActivity extends AnimatedActivity { View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } - /** Dispatch allow-listed key mappings while the dashboard is in the foreground. */ - @Override public boolean dispatchKeyEvent(android.view.KeyEvent event) { - if (KeyRemappingManager.handle(this, event)) return true; - return super.dispatchKeyEvent(event); - } - @Override public boolean dispatchTouchEvent(MotionEvent event) { + if (campingModeController != null && campingModeController.onTouchEvent(event)) { + musicProgressGesture = false; + widgetsPanelTrackingTouch = false; + appDrawerTrackingTouch = false; + controlPanelTrackingTouch = false; + return true; + } // Closed-overlay swipes are observed globally so they work from any part of // the home screen, including the music panel and gauge surface. Taps and // short gestures continue through to the existing child views unchanged. diff --git a/src/cloud/molberg/mgutility/MgServiceBridge.java b/src/cloud/molberg/mgutility/MgServiceBridge.java index d66fb10..e8dab8b 100644 --- a/src/cloud/molberg/mgutility/MgServiceBridge.java +++ b/src/cloud/molberg/mgutility/MgServiceBridge.java @@ -48,6 +48,9 @@ final class MgServiceBridge { private static final int SOUND_SET_VOLUME = 0x29; private static final int SOUND_GET_MAX_VOLUME = 0x2a; private static final int SOUND_GET_MIN_VOLUME = 0x2b; + private static final int SOUND_GET_FIELD_BALANCE = 0x11; + private static final int SOUND_GET_FIELD_FADER = 0x12; + private static final int SOUND_SET_FIELD = 0x13; // IWiFiService transactions private static final int WIFI_GET_ENABLED = 0x4; @@ -260,6 +263,55 @@ final class MgServiceBridge { return readIntWithType(SOUND_GET_MIN_VOLUME, volType); } + /** Reads the OEM balance axis (0 left through 7 centre to 14 right). */ + int getSoundFieldBalance() { return readSoundFieldValue(SOUND_GET_FIELD_BALANCE); } + + /** Reads the OEM fader axis (0 front through 7 centre to 14 rear). */ + int getSoundFieldFader() { return readSoundFieldValue(SOUND_GET_FIELD_FADER); } + + /** Applies OEM balance/fader values; documented by the stock Settings AIDL. */ + boolean setSoundField(int balance, int fader) { + if (balance < LiquidSoundBalanceCurve.MIN_FADER || balance > LiquidSoundBalanceCurve.MAX_FADER || + fader < LiquidSoundBalanceCurve.MIN_FADER || fader > LiquidSoundBalanceCurve.MAX_FADER) return false; + IBinder binder = soundBinder; + if (binder == null || !binder.pingBinder()) return false; + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + try { + data.writeInterfaceToken(IFACE_SMART_SOUND); + data.writeInt(balance); + data.writeInt(fader); + if (!binder.transact(SOUND_SET_FIELD, data, reply, 0)) return false; + reply.readException(); + return reply.readInt() != 0; + } catch (Exception e) { + Log.w(TAG, "setSoundField failed: " + e.getMessage()); + return false; + } finally { + data.recycle(); + reply.recycle(); + } + } + + private int readSoundFieldValue(int transaction) { + IBinder binder = soundBinder; + if (binder == null || !binder.pingBinder()) return Integer.MIN_VALUE; + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + try { + data.writeInterfaceToken(IFACE_SMART_SOUND); + if (!binder.transact(transaction, data, reply, 0)) return Integer.MIN_VALUE; + reply.readException(); + return reply.readInt(); + } catch (Exception e) { + Log.w(TAG, "readSoundField failed: " + e.getMessage()); + return Integer.MIN_VALUE; + } finally { + data.recycle(); + reply.recycle(); + } + } + private int readIntWithType(int code, int volType) { IBinder binder = soundBinder; if (binder == null || !binder.pingBinder()) return -1; diff --git a/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java b/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java new file mode 100644 index 0000000..71f3ff0 --- /dev/null +++ b/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java @@ -0,0 +1,98 @@ +package cloud.molberg.mgutility; + +import android.media.AudioFormat; +import android.media.AudioRecord; +import android.media.MediaRecorder; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +/** Temporary diagnostic: probes Android input profiles and reports whether PCM is non-silent. */ +public final class MicRouteDiagnosticActivity extends AnimatedActivity { + private TextView output; + private Button run; + private volatile boolean running; + + private static final int[] SOURCES = { + MediaRecorder.AudioSource.MIC, + MediaRecorder.AudioSource.VOICE_RECOGNITION, + MediaRecorder.AudioSource.VOICE_COMMUNICATION, + 1999 // OEM/API 29 HOTWORD constant; harmlessly rejected on older runtimes. + }; + private static final String[] NAMES = {"MIC", "VOICE_RECOGNITION", "VOICE_COMMUNICATION", "HOTWORD(1999)"}; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + setContentView(buildUi()); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(28, 18, 28, 18); + root.setBackgroundColor(UiTheme.BACKGROUND); + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "TEMP MIC ROUTE TEST", 28), new LinearLayout.LayoutParams(0, 56, 1)); + header.addView(UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }), new LinearLayout.LayoutParams(120, 52)); + root.addView(header); + TextView note = UiTheme.text(this, "TEMPORARY DIAGNOSTIC • speak while each profile runs for 3 seconds", 13, UiTheme.WARNING, android.graphics.Typeface.NORMAL); + root.addView(note, new LinearLayout.LayoutParams(-1, 38)); + run = UiTheme.button(this, "RUN ALL INPUT PROFILES", new View.OnClickListener() { @Override public void onClick(View v) { runTests(); } }, true); + root.addView(run, new LinearLayout.LayoutParams(-1, 50)); + output = UiTheme.text(this, "Press RUN to test the normal, voice-recognition, voice-communication and hotword routes.", 15, UiTheme.TEXT, android.graphics.Typeface.NORMAL); + output.setPadding(16, 16, 16, 16); + ScrollView scroll = new ScrollView(this); scroll.addView(output); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private void runTests() { + if (running) return; + running = true; run.setEnabled(false); output.setText("Starting…\n"); + new Thread(new Runnable() { @Override public void run() { + final StringBuilder result = new StringBuilder("TEMP MIC ROUTE TEST\n\n"); + for (int i = 0; i < SOURCES.length; i++) { + result.append(testSource(SOURCES[i], NAMES[i])).append("\n"); + final String shown = result.toString(); + runOnUiThread(new Runnable() { @Override public void run() { output.setText(shown); } }); + } + runOnUiThread(new Runnable() { @Override public void run() { run.setEnabled(true); running = false; } }); + }}, "mic-route-diagnostic").start(); + } + + private String testSource(int source, String name) { + final int rate = 16000; + int min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); + if (min <= 0) min = 4096; + AudioRecord record = null; + long samples = 0; + double sum = 0; + int peak = 0; + try { + record = new AudioRecord(source, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, min * 4); + if (record.getState() != AudioRecord.STATE_INITIALIZED) return name + ": NOT_INITIALIZED"; + record.startRecording(); + short[] buffer = new short[2048]; + long deadline = System.currentTimeMillis() + 3000L; + while (System.currentTimeMillis() < deadline) { + int count = record.read(buffer, 0, buffer.length); + if (count <= 0) continue; + for (int i = 0; i < count; i++) { int value = Math.abs((int) buffer[i]); sum += (double) value * value; peak = Math.max(peak, value); } + samples += count; + } + double rms = samples == 0 ? 0 : Math.sqrt(sum / samples) / 32768.0; + return String.format(java.util.Locale.US, "%s: samples=%d rms=%.5f peak=%.5f %s", name, samples, rms, peak / 32768.0, rms > 0.002 ? "AUDIO_DETECTED" : "SILENT"); + } catch (Throwable error) { + return name + ": ERROR " + error.getClass().getSimpleName() + " — " + String.valueOf(error.getMessage()); + } finally { + if (record != null) { try { record.stop(); } catch (Throwable ignored) { } try { record.release(); } catch (Throwable ignored) { } } + } + } +} \ No newline at end of file diff --git a/src/cloud/molberg/mgutility/MicScopeView.java b/src/cloud/molberg/mgutility/MicScopeView.java new file mode 100644 index 0000000..31f0499 --- /dev/null +++ b/src/cloud/molberg/mgutility/MicScopeView.java @@ -0,0 +1,45 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.view.View; + +/** Tiny microphone level scope; deliberately lightweight for the old head unit. */ +final class MicScopeView extends View { + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private float level; + private long phase; + + MicScopeView(Context context) { + super(context); + paint.setStrokeWidth(2f); + setMinimumHeight(26); + } + + void setLevel(float value) { + level = Math.max(0f, Math.min(1f, value)); + phase++; + invalidate(); + } + + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + float center = getHeight() / 2f; + paint.setColor(UiTheme.DIVIDER); + paint.setStrokeWidth(1f); + canvas.drawLine(0, center, getWidth(), center, paint); + paint.setColor(level > 0.04f ? UiTheme.CYAN_BRIGHT : UiTheme.WARNING); + paint.setStrokeWidth(2f); + float amp = Math.max(2f, level * getHeight() * 0.42f); + float step = Math.max(2f, getWidth() / 72f); + float previousX = 0f; + float previousY = center; + for (float x = 0; x <= getWidth(); x += step) { + float y = center + (float) Math.sin((x / Math.max(1f, getWidth())) * 18.0 + phase * 0.35) * amp; + if (x > 0) canvas.drawLine(previousX, previousY, x, y, paint); + previousX = x; + previousY = y; + } + } +} \ No newline at end of file diff --git a/src/cloud/molberg/mgutility/PluginApkProvider.java b/src/cloud/molberg/mgutility/PluginApkProvider.java new file mode 100644 index 0000000..763f4b6 --- /dev/null +++ b/src/cloud/molberg/mgutility/PluginApkProvider.java @@ -0,0 +1,19 @@ +package cloud.molberg.mgutility; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.os.ParcelFileDescriptor; +import java.io.File; + +/** Read-only provider for verified plugin APKs. */ +public final class PluginApkProvider extends ContentProvider { + @Override public boolean onCreate() { return true; } + private File file(Uri uri) { String name = uri == null ? "" : uri.getLastPathSegment(); if (name.indexOf("..") >= 0 || !name.endsWith(".apk")) return null; return new File(new File(getContext().getFilesDir(), "plugins"), name); } + @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws java.io.FileNotFoundException { if (!"r".equals(mode)) throw new java.io.FileNotFoundException("Plugin APK is read-only"); File file=file(uri); if(file==null||!file.isFile()) throw new java.io.FileNotFoundException("Plugin APK not found"); return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } + @Override public String getType(Uri uri) { return "application/vnd.android.package-archive"; } + @Override public Cursor query(Uri uri,String[] p,String s,String[] a,String sort) { File f=file(uri); MatrixCursor c=new MatrixCursor(new String[]{"_display_name","_size"}); if(f!=null&&f.isFile())c.addRow(new Object[]{f.getName(),f.length()}); return c; } + @Override public int delete(Uri u,String s,String[] a){return 0;} @Override public int update(Uri u,ContentValues v,String s,String[] a){return 0;} @Override public Uri insert(Uri u,ContentValues v){return null;} +} diff --git a/src/cloud/molberg/mgutility/PluginMarketplaceActivity.java b/src/cloud/molberg/mgutility/PluginMarketplaceActivity.java new file mode 100644 index 0000000..d4e16dd --- /dev/null +++ b/src/cloud/molberg/mgutility/PluginMarketplaceActivity.java @@ -0,0 +1,86 @@ +package cloud.molberg.mgutility; + +import android.app.AlertDialog; +import android.os.Bundle; +import android.graphics.Typeface; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import cloud.molberg.mgutility.plugin.PluginMarketplace; +import cloud.molberg.mgutility.plugin.PluginRepository; +import cloud.molberg.mgutility.plugin.PluginRepositoryIndex; +import cloud.molberg.mgutility.plugin.PluginRepositoryIndexParser; +import cloud.molberg.mgutility.sdk.PluginManifest; + +/** Built-in marketplace screen. Repositories are user-editable; the official source is reserved. */ +public final class PluginMarketplaceActivity extends AnimatedActivity { + private LinearLayout content; + private ConfigStore store; + private final PluginMarketplace marketplace = new PluginMarketplace(); + @Override public void onCreate(Bundle state) { super.onCreate(state); store = ConfigStore.of(this); render(); } + private void render() { + LinearLayout root = new LinearLayout(this); root.setOrientation(LinearLayout.VERTICAL); root.setPadding(24,20,24,20); root.setBackgroundColor(UiTheme.BACKGROUND); + LinearLayout header = new LinearLayout(this); header.setGravity(Gravity.CENTER_VERTICAL); + TextView title = UiTheme.text(this, "PLUGIN MARKETPLACE", 22, UiTheme.TEXT, Typeface.BOLD); header.addView(title, new LinearLayout.LayoutParams(0,60,1)); + Button add = new Button(this); add.setText("ADD REPOSITORY"); add.setOnClickListener(new View.OnClickListener(){public void onClick(View v){showAddRepository();}}); header.addView(add, new LinearLayout.LayoutParams(-2,60)); root.addView(header); + TextView note = UiTheme.text(this, "Repositories publish signed MG Utility plugins. The official repository is reserved and will appear here when published.", 14, UiTheme.MUTED, Typeface.NORMAL); note.setPadding(0,0,0,12); root.addView(note); + ScrollView scroll = new ScrollView(this); content = new LinearLayout(this); content.setOrientation(LinearLayout.VERTICAL); scroll.addView(content); root.addView(scroll, new LinearLayout.LayoutParams(-1,0,1)); + setContentView(root); renderRepositories(); + } + private void renderRepositories() { + content.removeAllViews(); List repos = store.pluginRepositories(); + for (final PluginRepository repo : repos) { marketplace.addRepository(repo); content.addView(row(repo)); } + if (repos.isEmpty()) content.addView(UiTheme.text(this,"No repositories configured.",16,UiTheme.MUTED,Typeface.NORMAL)); + } + private View row(final PluginRepository repo) { + LinearLayout item = new LinearLayout(this); item.setGravity(Gravity.CENTER_VERTICAL); item.setPadding(14,8,14,8); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 4)); + LinearLayout labels = new LinearLayout(this); labels.setOrientation(LinearLayout.VERTICAL); TextView name=UiTheme.text(this,repo.name,16,UiTheme.TEXT,Typeface.BOLD); TextView url=UiTheme.text(this,repo.url,12,UiTheme.MUTED,Typeface.NORMAL); labels.addView(name); labels.addView(url); item.addView(labels,new LinearLayout.LayoutParams(0,64,1)); + Button refresh = new Button(this); refresh.setText("REFRESH"); refresh.setEnabled(repo.enabled); refresh.setOnClickListener(new View.OnClickListener(){public void onClick(View v){refresh(repo);}}); item.addView(refresh,new LinearLayout.LayoutParams(-2,56)); + if (!repo.official) { Button remove=new Button(this); remove.setText("REMOVE"); remove.setOnClickListener(new View.OnClickListener(){public void onClick(View v){ArrayList all=new ArrayList(store.pluginRepositories()); for(int i=all.size()-1;i>=0;i--)if(all.get(i).id.equals(repo.id))all.remove(i);store.savePluginRepositories(all);renderRepositories();}}); item.addView(remove,new LinearLayout.LayoutParams(-2,56)); } + LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(-1,80); p.setMargins(0,0,0,4); item.setLayoutParams(p); return item; + } + private void showAddRepository() { + final EditText input=new EditText(this); input.setSingleLine(true); input.setHint("https://example.com/mg-plugins.json"); + UiTheme.dialog(this).setTitle("ADD PLUGIN REPOSITORY").setMessage("Use an HTTPS repository index URL.").setView(input).setNegativeButton("CANCEL",null).setPositiveButton("ADD", new android.content.DialogInterface.OnClickListener() { + @Override public void onClick(android.content.DialogInterface d, int w) { + String url=input.getText().toString().trim(); + if(!url.startsWith("https://")){android.widget.Toast.makeText(PluginMarketplaceActivity.this,"Repository must use HTTPS",android.widget.Toast.LENGTH_LONG).show();return;} + ArrayList all=new ArrayList(store.pluginRepositories()); String id="repo-"+Integer.toHexString(url.hashCode()); + all.add(new PluginRepository(id,url,url,true,false)); store.savePluginRepositories(all); renderRepositories(); + } + }).show(); + } + private void refresh(final PluginRepository repo) { + new Thread(new Runnable(){public void run(){try { HttpURLConnection c=(HttpURLConnection)new URL(repo.url).openConnection(); c.setConnectTimeout(8000); c.setReadTimeout(8000); BufferedReader r=new BufferedReader(new InputStreamReader(c.getInputStream(),"UTF-8")); StringBuilder json=new StringBuilder();String line;while((line=r.readLine())!=null)json.append(line);r.close(); final PluginRepositoryIndex index=PluginRepositoryIndexParser.parse(json.toString()); marketplace.addRepository(repo); marketplace.refresh(new PluginMarketplace.RepositoryClient(){public PluginRepositoryIndex fetch(PluginRepository ignored){return index;}}); runOnUiThread(new Runnable(){public void run(){renderPlugins(); android.widget.Toast.makeText(PluginMarketplaceActivity.this,"Repository loaded: "+index.plugins.size()+" plugins",android.widget.Toast.LENGTH_SHORT).show();}}); } catch(final Exception e){runOnUiThread(new Runnable(){public void run(){android.widget.Toast.makeText(PluginMarketplaceActivity.this,"Repository unavailable: "+e.getMessage(),android.widget.Toast.LENGTH_LONG).show();}});}}}).start(); + } + + private void renderPlugins() { + List plugins = marketplace.available(cloud.molberg.mgutility.sdk.PluginManifest.SDK_VERSION); + if (plugins.isEmpty()) return; + content.addView(UiTheme.text(this, "AVAILABLE PLUGINS", 15, UiTheme.CYAN, Typeface.BOLD), 0); + for (final cloud.molberg.mgutility.plugin.PluginCatalogEntry plugin : plugins) { + LinearLayout item = new LinearLayout(this); item.setGravity(Gravity.CENTER_VERTICAL); item.setPadding(14,8,14,8); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 4)); + LinearLayout labels = new LinearLayout(this); labels.setOrientation(LinearLayout.VERTICAL); + labels.addView(UiTheme.text(this, plugin.name + " v" + plugin.version, 16, UiTheme.TEXT, Typeface.BOLD)); + labels.addView(UiTheme.text(this, plugin.description.length() == 0 ? plugin.id : plugin.description, 12, UiTheme.MUTED, Typeface.NORMAL)); + item.addView(labels, new LinearLayout.LayoutParams(0,64,1)); + Button install = new Button(this); install.setText("INSTALL"); install.setEnabled(plugin.apkUrl.length() > 0 && plugin.sha256.length() == 64); + install.setOnClickListener(new View.OnClickListener(){public void onClick(View v){ + android.widget.Toast.makeText(PluginMarketplaceActivity.this,"Downloading and verifying plugin…",android.widget.Toast.LENGTH_SHORT).show(); + new Thread(new Runnable(){public void run(){try { byte[] apk=cloud.molberg.mgutility.plugin.PluginApkInstaller.download(plugin); new cloud.molberg.mgutility.plugin.PluginApkInstaller(PluginMarketplaceActivity.this).install(plugin, apk); } catch(final Exception e) { runOnUiThread(new Runnable(){public void run(){android.widget.Toast.makeText(PluginMarketplaceActivity.this,"Plugin install failed: "+e.getMessage(),android.widget.Toast.LENGTH_LONG).show();}}); }}}).start(); + }}); + item.addView(install, new LinearLayout.LayoutParams(-2,56)); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1,80); p.setMargins(0,0,0,4); item.setLayoutParams(p); content.addView(item); + } + } +} diff --git a/src/cloud/molberg/mgutility/PushToTalkPress.java b/src/cloud/molberg/mgutility/PushToTalkPress.java new file mode 100644 index 0000000..f6f4ee1 --- /dev/null +++ b/src/cloud/molberg/mgutility/PushToTalkPress.java @@ -0,0 +1,35 @@ +package cloud.molberg.mgutility; + +final class PushToTalkPress { + private boolean held; + private int deviceId; + private int keyCode; + private int scanCode; + private long downTime; + + boolean begin(int device, int key, int scan, long started, int repeats) { + if (repeats != 0) return false; + if (held && (deviceId != device || downTime >= started || + !(scanCode != 0 && scan != 0 ? scanCode == scan : keyCode == key))) return false; + held = true; + deviceId = device; + keyCode = key; + scanCode = scan; + downTime = started; + return true; + } + + boolean matches(int device, int key, int scan, long started) { + if (!held || deviceId != device || downTime != started) return false; + if (scanCode != 0 && scan != 0) return scanCode == scan; + return keyCode == key; + } + + boolean end(int device, int key, int scan, long started) { + if (!matches(device, key, scan, started)) return false; + clear(); + return true; + } + + void clear() { held = false; } +} diff --git a/src/cloud/molberg/mgutility/SettingsActivity.java b/src/cloud/molberg/mgutility/SettingsActivity.java index dbbf438..3bf1c93 100644 --- a/src/cloud/molberg/mgutility/SettingsActivity.java +++ b/src/cloud/molberg/mgutility/SettingsActivity.java @@ -45,12 +45,16 @@ import java.util.Locale; /** Categorized settings hub styled after the SAIC head-unit Settings experience. */ public final class SettingsActivity extends AnimatedActivity { - private static final String[] CATEGORIES = { "Driving", "Charging", "Misc", "Appearance", "Apps", "Config" }; + public static final String EXTRA_CATEGORY = "settings_category"; + public static final int CATEGORY_DASHBOARD = 4; + private static final String[] CATEGORIES = { "Vehicle", "Driving", "Charging", "Audio", "Dashboard", "Apps", "System" }; private static final String PREF_APPS_REORDER = "apps_reorder_enabled"; private static final int REQUEST_EXPORT = 8801; private static final int REQUEST_IMPORT = 8802; private LinearLayout content; private LinearLayout tabs; + private ScrollView scroll; + private int pendingScrollY = -1; private GridLayout appsGrid; /** Pin id currently being dragged, or 0 when nothing is. */ private long draggedPinId; @@ -72,13 +76,15 @@ public final class SettingsActivity extends AnimatedActivity { immersive(); setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); - showCategory(state == null ? 0 : state.getInt("selected_category", 0)); + int category = state == null ? getIntent().getIntExtra(EXTRA_CATEGORY, 0) : state.getInt("selected_category", 0); + showCategory(Math.max(0, Math.min(CATEGORIES.length - 1, category))); } @Override protected void onResume() { super.onResume(); UiTheme.refreshTheme(this); if (UiTheme.version() != renderedThemeVersion && content != null) { + if (pendingScrollY < 0) pendingScrollY = scroll.getScrollY(); setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); } @@ -127,7 +133,15 @@ public final class SettingsActivity extends AnimatedActivity { tabs.setGravity(Gravity.CENTER_VERTICAL); root.addView(tabs, new LinearLayout.LayoutParams(-1, 60)); - ScrollView scroll = new ScrollView(this); + scroll = new ScrollView(this) { + @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + if (pendingScrollY >= 0) { + scrollTo(0, pendingScrollY); + pendingScrollY = -1; + } + } + }; scroll.setFillViewport(true); content = new LinearLayout(this); content.setOrientation(LinearLayout.VERTICAL); @@ -138,6 +152,8 @@ public final class SettingsActivity extends AnimatedActivity { } private void showCategory(int category) { + pendingScrollY = category != selectedCategory ? 0 + : pendingScrollY >= 0 ? pendingScrollY : scroll.getScrollY(); selectedCategory = category; tabs.removeAllViews(); for (int i = 0; i < CATEGORIES.length; i++) { @@ -154,20 +170,41 @@ public final class SettingsActivity extends AnimatedActivity { tabs.addView(tab, p); } content.removeAllViews(); - if (category == 0) driving(); - else if (category == 1) charging(); - else if (category == 2) misc(); - else if (category == 3) appearance(); - else if (category == 4) apps(); - else config(); + if (category == 0) vehicle(); + else if (category == 1) driving(); + else if (category == 2) charging(); + else if (category == 3) audio(); + else if (category == CATEGORY_DASHBOARD) dashboard(); + else if (category == 5) apps(); + else system(); } - /** Centralized settings export/import and reset controls. */ - private void config() { - section("Config", "Export, import, or reset every MG Utility setting"); + private void system() { + section("System", "Updates, extensions, diagnostics, and settings maintenance"); + systemTools(); + subsection("Software updates", "Choose the Gitea release channel and install updates inside MG Utility"); + content.addView(row("↥", "Software updates", + UpdateManager.installedVersion(this) + " • " + + UpdateManager.selectedChannel(this) + " channel", + new View.OnClickListener() { + @Override public void onClick(View v) { + startActivity(new Intent(SettingsActivity.this, UpdateActivity.class)); + } + })); + subsection("Plugins", "Install optional features from trusted plugin repositories"); + content.addView(row("▦", "Plugin marketplace", "Add repositories and browse plugins", new View.OnClickListener() { + @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, PluginMarketplaceActivity.class)); } + })); ConfigStore store = ConfigStore.of(this); int keyCount = store.visibleKeyCount(); subsection("Transfer", "Move settings between MG Utility installations"); + content.addView(row("•", "Included settings", "View the configuration included in exports", new View.OnClickListener() { + @Override public void onClick(View v) { + UiTheme.dialog(SettingsActivity.this).setTitle("INCLUDED SETTINGS") + .setItems(ConfigStore.sections().toArray(new String[0]), null) + .setPositiveButton("CLOSE", null).show(); + } + })); content.addView(row("⇧", "Export settings", "Save a versioned JSON file (" + keyCount + " keys)", new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); @@ -187,6 +224,7 @@ public final class SettingsActivity extends AnimatedActivity { catch (Exception e) { Toast.makeText(SettingsActivity.this, "No file picker available", Toast.LENGTH_LONG).show(); } } })); + subsection("Reset", "Restore MG Utility defaults"); content.addView(row("↺", "Reset settings", "Clear saved settings and return to defaults", new View.OnClickListener() { @Override public void onClick(View v) { UiTheme.dialog(SettingsActivity.this) @@ -202,10 +240,6 @@ public final class SettingsActivity extends AnimatedActivity { }).show(); } })); - subsection("Included", "The export contains all user-visible configuration"); - for (String name : ConfigStore.sections()) { - content.addView(row("•", name, "Included in export", null)); - } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { @@ -255,16 +289,19 @@ public final class SettingsActivity extends AnimatedActivity { } } - private void driving() { - section("Driving", "Vehicle defaults, performance, and trip history"); - subsection("Vehicle defaults", "Choose the profile applied when driving starts"); - content.addView(row("V", "Vehicle settings", "Capability-gated startup profile", open(VehicleSettingsActivity.class))); + private void vehicle() { + section("Vehicle", "Vehicle behavior and startup defaults"); + content.addView(row("V", "Vehicle settings", "Startup defaults and manual vehicle power off", open(VehicleSettingsActivity.class))); content.addView(row("D", "Default drive mode", driveModeName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); } })); content.addView(row("R", "Default recovery level", regenName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); } })); + } + + private void driving() { + section("Driving", "Trips, route history, and performance"); subsection("Performance", "Tools for measuring acceleration"); content.addView(row("0", "0–100 tester", "Open performance timer", open(SpeedTestActivity.class))); subsection("Trip tracking", "Choose how drive samples are collected and reviewed"); @@ -291,65 +328,61 @@ public final class SettingsActivity extends AnimatedActivity { })); } - private void misc() { - section("Misc", "Head-unit and application tools"); - subsection("Audio", "Configure event sounds and speed-aware playback"); + private void confirmDiagnosticsUpload() { + UiTheme.dialog(this).setTitle("UPLOAD DIAGNOSTICS?") + .setMessage("This sends the diagnostic snapshot and filtered app-owned warnings/errors to help troubleshoot compatibility. It excludes unrestricted system logcat and VIN. Upload is only sent after you choose UPLOAD.") + .setNegativeButton("CANCEL", null) + .setPositiveButton("UPLOAD", new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + final android.app.ProgressDialog progress = new android.app.ProgressDialog(SettingsActivity.this); + progress.setMessage("Preparing diagnostics…"); progress.setCancelable(false); progress.show(); + new Thread(new Runnable() { @Override public void run() { + final org.json.JSONObject report = VehicleDiagnosticsCollector.collect(SettingsActivity.this); + DiagnosticsClient.uploadDiagnostics(SettingsActivity.this, report, new DiagnosticsClient.Callback() { + @Override public void complete(final String message) { + runOnUiThread(new Runnable() { @Override public void run() { + if (!isFinishing()) progress.dismiss(); + Toast.makeText(SettingsActivity.this, message, Toast.LENGTH_LONG).show(); + }}); + } + }); + }}).start(); + } + }).show(); + } + + private void audio() { + section("Audio", "Playback, sound field, and assistant controls"); + subsection("Sound and volume", "Configure event sounds and speed-aware playback"); content.addView(row("♫", "Soundboard", "Configure event audio", open(SoundboardActivity.class))); content.addView(row("♪", "Speed reactive audio", "Looping clip that reacts to driving speed", open(SpeedAudioActivity.class))); content.addView(row("≈", "Adaptive audio leveling", "Scale media volume smoothly with vehicle speed", open(AdaptiveAudioLevelingActivity.class))); - subsection("Setup", "Review the first-time configuration"); - content.addView(row("★", "Run setup wizard", "Reopen the first-time setup review", new View.OnClickListener() { - @Override public void onClick(View v) { - Intent intent = new Intent(SettingsActivity.this, SetupWizardActivity.class); - intent.putExtra(SetupWizardActivity.EXTRA_REVIEW_MODE, true); - startActivity(intent); - } - })); - subsection("Diagnostics", "Troubleshooting and input customization"); - content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class))); - content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class))); - - subsection("OEM Apps", "Original SAIC launchers and tools"); - content.addView(row("⌂", "Official SAIC launcher", "Open OEM home screen", new View.OnClickListener() { - @Override public void onClick(View v) { launchOemLauncher(); } - })); - content.addView(row("⇄", "Change Launcher", "Choose the default home app", new View.OnClickListener() { - @Override public void onClick(View v) { openLauncherSettings(); } - })); - content.addView(row("X", "Engineer mode", "SAIC engineering tools", new View.OnClickListener() { - @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.engmode", "com.saicmotor.hmi.engmode.home.ui.EngineeringModeActivity"); } - })); - content.addView(row("V", "SAIC vehicle settings", "OEM vehicle configuration", new View.OnClickListener() { - @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.vehicleconfig.ui.VehicleSettingsActivity"); } - })); - content.addView(row("⚙", "System settings", "SAIC system settings", new View.OnClickListener() { - @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.systemsettings", "com.saicmotor.hmi.systemsettings.SettingsActivity"); } - })); + content.addView(row("◉", "Liquid Sound Balance", "Move the sound field with acceleration and braking", open(LiquidSoundBalanceActivity.class))); + subsection("Assistant", "Hands-free prompts from a steering-wheel button"); + HermesConfig hermes = HermesConfig.load(this); + content.addView(row("H", "Hermes agent assistant", + hermes.isReady() ? "Configured • push-to-talk ready" : "Connect to the Hermes native API server", + open(HermesSettingsActivity.class))); } - private void appearance() { - section("Appearance", "Personalise the MG Utility dashboard"); + private void dashboard() { + section("Dashboard", "Appearance, home-screen panels, and visual behavior"); subsection("Theme", "Choose colours and text sizing"); content.addView(fontScaleControl()); content.addView(row("◈", "Theme", themeName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, CustomThemeEditorActivity.class)); } })); subsection("Navigation", "Choose how pages open and close"); - content.addView(toggleRow("→", "Page animations", "Slide transitions between MG Utility pages", - UiTheme.UI_PREFS, AnimatedActivity.PREF_PAGE_ANIMATIONS_ENABLED, true)); - subsection("Music player", "Show currently playing music on the dashboard"); - content.addView(toggleRow("♫", "Music Player", "Show current song, artist, and album art", UiTheme.UI_PREFS, MusicPlayerManager.PREF_ENABLED, false)); - subsection("App drawer", "Control the swipe-up launcher and its appearance"); + content.addView(toggleRow("→", "Page animations", "Slide transitions between MG Utility pages", UiTheme.UI_PREFS, AnimatedActivity.PREF_PAGE_ANIMATIONS_ENABLED, true)); + subsection("Panels", "Enable dashboard panels and configure their appearance"); content.addView(toggleRow("⌃", "App Drawer", "Swipe up from the home screen to reveal your pinned apps", "ui_state", MainActivity.PREF_APP_DRAWER_ENABLED, false)); content.addView(appDrawerOpacityControl()); - subsection("Control panel", "Choose the quick controls available from the dashboard"); content.addView(toggleRow("⌄", "Control panel", "Swipe down from the home screen for quick controls", "ui_state", ControlPanelCatalog.PREF_ENABLED, true)); - content.addView(row("◈", "Configure control panel", "Add, remove, and reorder quick controls", new View.OnClickListener() { - @Override public void onClick(View v) { - startActivity(new Intent(SettingsActivity.this, ControlPanelSettingsActivity.class)); - } - })); - subsection("Screen brightness", "Follow a daily peak/dark schedule with a smooth fade"); + content.addView(row("◈", "Configure control panel", "Add, remove, and reorder quick controls", open(ControlPanelSettingsActivity.class))); + content.addView(toggleRow("←", "Widgets Panel", "Swipe right from the home screen for widgets", "ui_state", MainActivity.PREF_WIDGETS_PANEL_ENABLED, false)); + subsection("Camping mode", "Configure extra screen dimming and tap-to-wake blackout"); + content.addView(row("☾", "Camping mode settings", "Exterior lights stay unchanged; climate automation is not enabled yet", open(CampingModeSettingsActivity.class))); + subsection("Brightness schedule", "Daily peak/dark levels with a smooth fade"); content.addView(toggleRow("☼", "Automatic brightness", "Apply the schedule while the head unit is on", UiTheme.UI_PREFS, UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false, new Runnable() { @Override public void run() { BrightnessScheduler.rearm(SettingsActivity.this); } @@ -363,8 +396,8 @@ public final class SettingsActivity extends AnimatedActivity { content.addView(brightnessSchedulePercentControl("D", "Dark brightness", UiTheme.PREF_AUTO_BRIGHTNESS_DARK_PERCENT, BrightnessSchedule.DEFAULT_DARK_PERCENT)); content.addView(brightnessTransitionControl()); - subsection("Widgets panel", "Choose whether the dashboard exposes widgets"); - content.addView(toggleRow("←", "Widgets Panel", "Swipe right from the home screen for widgets", "ui_state", MainActivity.PREF_WIDGETS_PANEL_ENABLED, false)); + subsection("Music player", "Show currently playing music on the dashboard"); + content.addView(toggleRow("♫", "Music Player", "Show current song, artist, and album art", UiTheme.UI_PREFS, MusicPlayerManager.PREF_ENABLED, false)); subsection("Music visualizer", "Choose how live playback is drawn on the dashboard"); content.addView(toggleRow("≋", "Music Visualizer", "Show a live playback effect", "ui_state", "home_visualizer_enabled", true)); content.addView(row("F", "Visualizer framerate", visualizerFps() + " FPS", new View.OnClickListener() { @@ -376,6 +409,41 @@ public final class SettingsActivity extends AnimatedActivity { content.addView(visualizerOpacityControl()); } + private void systemTools() { + subsection("Setup", "Review the first-time configuration"); + content.addView(row("★", "Run setup wizard", "Reopen the first-time setup review", new View.OnClickListener() { + @Override public void onClick(View v) { + Intent intent = new Intent(SettingsActivity.this, SetupWizardActivity.class); + intent.putExtra(SetupWizardActivity.EXTRA_REVIEW_MODE, true); + startActivity(intent); + } + })); + subsection("Diagnostics", "Troubleshooting and voluntary diagnostic uploads"); + content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class))); + content.addView(row("↑", "Upload diagnostics", "Review data and voluntarily upload detailed logs", new View.OnClickListener() { + @Override public void onClick(View v) { confirmDiagnosticsUpload(); } + })); + subsection("Keys and launcher", "Customize physical inputs and the home app"); + content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class))); + + content.addView(row("⌂", "Official SAIC launcher", "Open OEM home screen", new View.OnClickListener() { + @Override public void onClick(View v) { launchOemLauncher(); } + })); + content.addView(row("⇄", "Change Launcher", "Choose the default home app", new View.OnClickListener() { + @Override public void onClick(View v) { openLauncherSettings(); } + })); + subsection("OEM and system tools", "Original SAIC configuration and engineering tools"); + content.addView(row("X", "Engineer mode", "SAIC engineering tools", new View.OnClickListener() { + @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.engmode", "com.saicmotor.hmi.engmode.home.ui.EngineeringModeActivity"); } + })); + content.addView(row("V", "SAIC vehicle settings", "OEM vehicle configuration", new View.OnClickListener() { + @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.vehicleconfig.ui.VehicleSettingsActivity"); } + })); + content.addView(row("⚙", "System settings", "SAIC system settings", new View.OnClickListener() { + @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.systemsettings", "com.saicmotor.hmi.systemsettings.SettingsActivity"); } + })); + } + private void apps() { List pins = LauncherPins.loadAll(this); final boolean reorderEnabled = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE) @@ -1084,8 +1152,8 @@ public final class SettingsActivity extends AnimatedActivity { item.setPadding(18, 0, 18, 0); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 5)); if (listener != null) item.setOnClickListener(listener); - TextView iconView = UiTheme.text(this, icon, 16, UiTheme.CYAN, Typeface.BOLD); - iconView.setGravity(Gravity.CENTER); + ImageView iconView = UiTheme.icon(this, IconPack.forLabel(label), UiTheme.CYAN, 24); + iconView.setPadding(11, 11, 11, 11); item.addView(iconView, new LinearLayout.LayoutParams(46, 68)); TextView name = UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL); name.setGravity(Gravity.CENTER_VERTICAL); @@ -1113,8 +1181,8 @@ public final class SettingsActivity extends AnimatedActivity { item.setGravity(Gravity.CENTER_VERTICAL); item.setPadding(18, 0, 18, 0); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); - TextView iconView = UiTheme.text(this, icon, 18, UiTheme.CYAN, Typeface.BOLD); - iconView.setGravity(Gravity.CENTER); + ImageView iconView = UiTheme.icon(this, IconPack.forLabel(label), UiTheme.CYAN, 24); + iconView.setPadding(11, 11, 11, 11); item.addView(iconView, new LinearLayout.LayoutParams(46, 68)); LinearLayout copy = new LinearLayout(this); copy.setOrientation(LinearLayout.VERTICAL); @@ -1509,55 +1577,6 @@ public final class SettingsActivity extends AnimatedActivity { }).show(); } - private void chooseDriveMode() { - final String[] values = { "Snow", "Eco", "Normal", "Sport", "Custom" }; - UiTheme.dialog(this).setTitle("DRIVE MODE").setSingleChoiceItems(values, - java.util.Arrays.asList(values).indexOf(driveModeName()), new DialogInterface.OnClickListener() { - @Override public void onClick(DialogInterface dialog, int which) { - int[] codes = {6, 2, 3, 4, 7}; - new VehicleSettingsRepository(SettingsActivity.this).setDesired("drive_mode", - VehicleSettingsCatalog.Policy.RESTORE, Integer.valueOf(codes[which])); - dialog.dismiss(); showCategory(selectedCategory); - } - }).show(); - } - - private void chooseRegen() { - final String[] values = { "Low", "Standard", "High", "Auto", - "Level 5 — Regeneration Off (experimental)" }; - final int[] codes = { 0, 1, 2, 3, 5 }; - UiTheme.dialog(this).setTitle("ENERGY RECOVERY").setSingleChoiceItems(values, - regenSelection(codes), new DialogInterface.OnClickListener() { - @Override public void onClick(DialogInterface dialog, int which) { - if (codes[which] == VehicleSettingsCatalog.REGEN_LEVEL_OFF_EXPERIMENTAL) { - UiTheme.dialog(SettingsActivity.this) - .setTitle("EXPERIMENTAL REGENERATION OFF") - .setMessage("This changes lift-off deceleration and is not a normal driving preset. The car must be parked and stationary. Use Apply now, verify read-back, and restore the previous level when finished.") - .setNegativeButton("CANCEL", null) - .setPositiveButton("ACKNOWLEDGE", new DialogInterface.OnClickListener() { - @Override public void onClick(DialogInterface warning, int ignored) { - VehicleSettingsRepository repository = new VehicleSettingsRepository(SettingsActivity.this); - repository.acknowledgeLevelFive(VehicleSettingsProfile.MG4_LUXURY_2022, 1); - repository.setDesired("regenerative_level", VehicleSettingsCatalog.Policy.APPLY_NOW, Integer.valueOf(5)); - dialog.dismiss(); showCategory(selectedCategory); - } - }).show(); - } else { - new VehicleSettingsRepository(SettingsActivity.this).setDesired("regenerative_level", - VehicleSettingsCatalog.Policy.RESTORE, Integer.valueOf(codes[which])); - dialog.dismiss(); showCategory(selectedCategory); - } - } - }).show(); - } - - private int regenSelection(int[] codes) { - Integer desired = new VehicleSettingsRepository(this).desiredValue("regenerative_level"); - if (desired == null) return -1; - for (int i = 0; i < codes.length; i++) if (codes[i] == desired.intValue()) return i; - return -1; - } - private String tileCacheLabel() { return MapTileCache.label(this) + " • default " + MapTileCache.DEFAULT_BUDGET_MB + " MB"; } diff --git a/src/cloud/molberg/mgutility/SetupWizardActivity.java b/src/cloud/molberg/mgutility/SetupWizardActivity.java new file mode 100644 index 0000000..12420d2 --- /dev/null +++ b/src/cloud/molberg/mgutility/SetupWizardActivity.java @@ -0,0 +1,892 @@ +package cloud.molberg.mgutility; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.graphics.Color; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.os.Bundle; +import android.provider.Settings; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.FrameLayout; +import android.widget.HorizontalScrollView; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.SeekBar; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; + +/** + * First-run / on-demand setup wizard for MG Utility. + * + * Walks the user through the same preferences they would otherwise tweak + * individually in Settings, in a single linear flow. Re-running the wizard + * from Settings shows every control pre-populated with the current value + * so the user can click Next and Finish without changing anything. + */ +public final class SetupWizardActivity extends AnimatedActivity { + + public static final String PREF_COMPLETED = "setup_wizard_completed"; + public static final String PREF_LAST_VERSION = "setup_wizard_last_version"; + public static final String EXTRA_REVIEW_MODE = "review_mode"; + + private static final int LOCATION_REQUEST = 5711; + private static final int AUDIO_REQUEST = 5713; + + private LinearLayout bodyContainer; + private TextView progressLabel; + private LinearLayout stepRail; + private Button backButton; + private Button nextButton; + private boolean reviewMode; + + private int currentStep; + private long renderedThemeVersion; + private final List steps = new ArrayList(); + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + Intent intent = getIntent(); + reviewMode = intent != null && intent.getBooleanExtra(EXTRA_REVIEW_MODE, false); + buildSteps(); + setContentView(buildUi()); + showStep(state == null ? 0 : Math.max(0, Math.min(steps.size() - 1, state.getInt("step", 0)))); + renderedThemeVersion = UiTheme.version(); + } + + @Override protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt("step", currentStep); + } + + @Override protected void onResume() { + super.onResume(); + UiTheme.refreshTheme(this); + // If the theme changed since we last built the chrome (e.g. the user + // picked a new theme on this step, or Android re-applied a saved one), + // rebuild the entire activity so the header, footer, and step rail + // repaint with the new palette. A partial body re-render would leave + // every view built by buildUi() holding the previous colors. + if (bodyContainer != null && !steps.isEmpty()) { + if (UiTheme.version() != renderedThemeVersion) { + setContentView(buildUi()); + showStep(currentStep); + renderedThemeVersion = UiTheme.version(); + } else { + showStep(currentStep); + } + } + } + + @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (!steps.isEmpty()) showStep(currentStep); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private void buildSteps() { + steps.clear(); + steps.add(new WelcomeStep()); + steps.add(new PermissionsStep()); + steps.add(new AppearanceStep()); + steps.add(new FeatureTogglesStep()); + steps.add(new AppDrawerStep()); + steps.add(new FinishStep()); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(UiTheme.BACKGROUND); + root.setPadding(UiTheme.dp(this, 24), UiTheme.dp(this, 12), + UiTheme.dp(this, 24), UiTheme.dp(this, 18)); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + TextView title = UiTheme.title(this, reviewMode ? "SETUP REVIEW" : "SETUP WIZARD", 24); + header.addView(title, new LinearLayout.LayoutParams(0, 56, 1)); + progressLabel = UiTheme.text(this, "", 12, UiTheme.MUTED, Typeface.NORMAL); + progressLabel.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); + header.addView(progressLabel, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 56)); + root.addView(header); + + stepRail = new LinearLayout(this); + stepRail.setOrientation(LinearLayout.HORIZONTAL); + stepRail.setGravity(Gravity.CENTER_VERTICAL); + root.addView(stepRail, new LinearLayout.LayoutParams(-1, UiTheme.dp(this, 36))); + + bodyContainer = new LinearLayout(this); + bodyContainer.setOrientation(LinearLayout.VERTICAL); + bodyContainer.setPadding(0, UiTheme.dp(this, 8), 0, 0); + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + scroll.addView(bodyContainer, new FrameLayout.LayoutParams(-1, -1)); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + + LinearLayout footer = new LinearLayout(this); + footer.setGravity(Gravity.CENTER_VERTICAL); + footer.setPadding(0, UiTheme.dp(this, 12), 0, 0); + TextView note = UiTheme.text(this, + "All of these settings can be changed later in Settings.", + 12, UiTheme.MUTED, Typeface.NORMAL); + footer.addView(note, new LinearLayout.LayoutParams(0, 48, 1)); + backButton = UiTheme.button(this, "BACK", null, false); + backButton.setContentDescription("Previous step"); + footer.addView(backButton, new LinearLayout.LayoutParams(UiTheme.dp(this, 120), UiTheme.dp(this, 44))); + nextButton = UiTheme.button(this, "NEXT", null, true); + nextButton.setContentDescription("Next step"); + LinearLayout.LayoutParams nextLp = new LinearLayout.LayoutParams(UiTheme.dp(this, 160), UiTheme.dp(this, 44)); + nextLp.setMargins(UiTheme.dp(this, 12), 0, 0, 0); + footer.addView(nextButton, nextLp); + root.addView(footer); + + backButton.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + if (currentStep <= 0) { finish(); return; } + showStep(currentStep - 1); + } + }); + nextButton.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { advance(); } + }); + return root; + } + + private void showStep(int index) { + currentStep = Math.max(0, Math.min(steps.size() - 1, index)); + bodyContainer.removeAllViews(); + steps.get(currentStep).render(this, bodyContainer); + progressLabel.setText("STEP " + (currentStep + 1) + " OF " + steps.size() + + " - " + steps.get(currentStep).title().toUpperCase(Locale.US)); + renderRail(); + boolean first = currentStep == 0; + boolean last = currentStep == steps.size() - 1; + backButton.setText(first ? "EXIT" : "BACK"); + nextButton.setText(last ? (reviewMode ? "DONE" : "FINISH") : "NEXT"); + } + + private void renderRail() { + stepRail.removeAllViews(); + for (int i = 0; i < steps.size(); i++) { + Step step = steps.get(i); + LinearLayout pill = new LinearLayout(this); + pill.setOrientation(LinearLayout.HORIZONTAL); + pill.setGravity(Gravity.CENTER_VERTICAL); + pill.setPadding(UiTheme.dp(this, 10), 0, UiTheme.dp(this, 10), 0); + int bg = i == currentStep ? UiTheme.CYAN + : (i < currentStep ? UiTheme.SURFACE_HIGH : UiTheme.SURFACE); + pill.setBackground(UiTheme.surface(bg, 0)); + int dot = i == currentStep ? UiTheme.RED + : (i < currentStep ? UiTheme.SUCCESS : UiTheme.MUTED); + View dotView = new View(this); + dotView.setBackgroundColor(dot); + LinearLayout.LayoutParams dotLp = new LinearLayout.LayoutParams(UiTheme.dp(this, 8), UiTheme.dp(this, 8)); + dotLp.setMargins(0, 0, UiTheme.dp(this, 8), 0); + pill.addView(dotView, dotLp); + TextView label = UiTheme.text(this, step.title(), 12, + i == currentStep ? Color.WHITE : (i < currentStep ? UiTheme.TEXT : UiTheme.MUTED), + Typeface.BOLD); + label.setAllCaps(true); + label.setLetterSpacing(.08f); + pill.addView(label); + LinearLayout.LayoutParams pillLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UiTheme.dp(this, 28)); + pillLp.setMargins(i == 0 ? 0 : UiTheme.dp(this, 6), 0, 0, 0); + stepRail.addView(pill, pillLp); + } + } + + private void advance() { + Step step = steps.get(currentStep); + if (!step.commit(this)) return; + if (currentStep == steps.size() - 1) { + finishWizard(); + return; + } + showStep(currentStep + 1); + } + + private void finishWizard() { + SharedPreferences prefs = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE); + prefs.edit() + .putBoolean(PREF_COMPLETED, true) + .putString(PREF_LAST_VERSION, currentVersionName()) + .apply(); + Toast.makeText(this, "Setup complete. Open Settings any time to change these.", Toast.LENGTH_LONG).show(); + finish(); + } + + private String currentVersionName() { + try { + return getPackageManager().getPackageInfo(getPackageName(), 0).versionName; + } catch (Exception e) { return ""; } + } + + public static boolean isCompleted(Context ctx) { + return ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(PREF_COMPLETED, false); + } + + public static boolean isStale(Context ctx) { + SharedPreferences prefs = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + if (!prefs.getBoolean(PREF_COMPLETED, false)) return true; + String last = prefs.getString(PREF_LAST_VERSION, ""); + try { + String current = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName; + return !current.equals(last); + } catch (Exception e) { return false; } + } + + private interface Step { + String title(); + void render(Activity host, LinearLayout body); + boolean commit(Activity host); + } + + private static View sectionLabel(Context ctx, String heading, String sub) { + LinearLayout wrap = new LinearLayout(ctx); + wrap.setOrientation(LinearLayout.VERTICAL); + wrap.setPadding(UiTheme.dp(ctx, 6), UiTheme.dp(ctx, 6), 0, UiTheme.dp(ctx, 6)); + wrap.addView(UiTheme.label(ctx, heading)); + if (sub != null) { + TextView s = UiTheme.text(ctx, sub, 12, UiTheme.MUTED, Typeface.NORMAL); + s.setPadding(0, UiTheme.dp(ctx, 2), 0, 0); + wrap.addView(s); + } + return wrap; + } + + private static LinearLayout row(Context ctx, String icon, String label, String value) { + LinearLayout item = new LinearLayout(ctx); + item.setGravity(Gravity.CENTER_VERTICAL); + item.setPadding(UiTheme.dp(ctx, 16), 0, UiTheme.dp(ctx, 16), 0); + item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + ImageView iconView = UiTheme.icon(ctx, IconPack.forLabel(label), UiTheme.CYAN, 24); + iconView.setPadding(UiTheme.dp(ctx, 11), UiTheme.dp(ctx, 11), UiTheme.dp(ctx, 11), UiTheme.dp(ctx, 11)); + item.addView(iconView, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 46), UiTheme.dp(ctx, 72))); + LinearLayout copy = new LinearLayout(ctx); + copy.setOrientation(LinearLayout.VERTICAL); + copy.setGravity(Gravity.CENTER_VERTICAL); + copy.addView(UiTheme.text(ctx, label, 16, UiTheme.TEXT, Typeface.NORMAL)); + if (value != null) copy.addView(UiTheme.text(ctx, value, 12, UiTheme.MUTED, Typeface.NORMAL)); + item.addView(copy, new LinearLayout.LayoutParams(0, UiTheme.dp(ctx, 72), 1)); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, UiTheme.dp(ctx, 72)); + lp.setMargins(0, 0, 0, UiTheme.dp(ctx, 2)); + item.setLayoutParams(lp); + return item; + } + + private static Button toggleButton(Context ctx, boolean on) { + Button b = UiTheme.button(ctx, on ? "ON" : "OFF", null, false); + b.setBackground(on ? UiTheme.surface(UiTheme.CYAN, 0) : UiTheme.outline(UiTheme.DIVIDER, 1, 0)); + b.setTextColor(on ? Color.WHITE : UiTheme.TEXT); + return b; + } + + private static View paddedCard(Context ctx) { + LinearLayout card = new LinearLayout(ctx); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(UiTheme.dp(ctx, 14), UiTheme.dp(ctx, 10), UiTheme.dp(ctx, 14), UiTheme.dp(ctx, 10)); + card.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, LinearLayout.LayoutParams.WRAP_CONTENT); + lp.setMargins(0, 0, 0, UiTheme.dp(ctx, 8)); + card.setLayoutParams(lp); + return card; + } + + private final class WelcomeStep implements Step { + @Override public String title() { return "Welcome"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + body.addView(sectionLabel(ctx, "WELCOME TO MG UTILITY", + "A short tour to help you pick a starting theme, font size, and the dashboard widgets you actually want.")); + LinearLayout card = (LinearLayout) paddedCard(ctx); + TextView intro = UiTheme.text(ctx, + "MG Utility unlocks extra features on your head unit: a music visualizer, music player, control panel, app drawer, trip tracking, charging automation, and more.", + 14, UiTheme.TEXT, Typeface.NORMAL); + intro.setPadding(0, 0, 0, UiTheme.dp(ctx, 10)); + card.addView(intro); + card.addView(UiTheme.text(ctx, + "This wizard takes about a minute. Every choice is just a starting point - you can change anything in Settings at any time, and you can re-run this wizard from Settings later.", + 13, UiTheme.MUTED, Typeface.NORMAL)); + body.addView(card); + LinearLayout list = (LinearLayout) paddedCard(ctx); + String[][] bullets = { + {"1.", "Pick the permissions you want to grant."}, + {"2.", "Choose a theme and font size."}, + {"3.", "Turn on the dashboard widgets you'd like."}, + {"4.", "Optionally enable the App Drawer and pin apps."}, + {"5.", "You're ready to go."} + }; + for (String[] bullet : bullets) { + LinearLayout line = new LinearLayout(ctx); + line.setGravity(Gravity.CENTER_VERTICAL); + TextView num = UiTheme.text(ctx, bullet[0], 14, UiTheme.CYAN, Typeface.BOLD); + line.addView(num, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 32), -2)); + line.addView(UiTheme.text(ctx, bullet[1], 14, UiTheme.TEXT, Typeface.NORMAL), + new LinearLayout.LayoutParams(0, -2, 1)); + list.addView(line); + } + body.addView(list); + } + @Override public boolean commit(Activity host) { return true; } + } + + private final class PermissionsStep implements Step { + @Override public String title() { return "Permissions"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + body.addView(sectionLabel(ctx, "PERMISSIONS", + "Allow MG Utility to access what it needs. You can grant or revoke these any time in Android Settings.")); + body.addView(permissionRow(host, "Fine location", + "Records route maps for Trip reports.", Manifest.permission.ACCESS_FINE_LOCATION)); + body.addView(permissionRow(host, "Microphone / audio capture", + "Powers the live music visualizer. Not used for recording.", Manifest.permission.RECORD_AUDIO)); + body.addView(notificationRow(host)); + } + @Override public boolean commit(Activity host) { return true; } + } + + private View permissionRow(final Activity host, String title, String summary, final String permission) { + final Context ctx = host; + LinearLayout item = row(ctx, "✓", title, summary); + final Button button = UiTheme.button(ctx, "", null, false); + refreshPermissionButton(button, permission); + button.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + if (Build.VERSION.SDK_INT >= 23 && host.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { + host.requestPermissions(new String[]{permission}, + permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) ? LOCATION_REQUEST : AUDIO_REQUEST); + } else Toast.makeText(host, "Already granted", Toast.LENGTH_SHORT).show(); + } + }); + item.addView(button, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 130), UiTheme.dp(ctx, 40))); + return item; + } + + private void refreshPermissionButton(Button button, String permission) { + boolean granted = Build.VERSION.SDK_INT < 23 + || checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; + button.setText(granted ? "GRANTED" : "GRANT"); + button.setBackground(granted ? UiTheme.surface(UiTheme.SUCCESS, 0) : UiTheme.outline(UiTheme.CYAN, 1, 0)); + button.setTextColor(granted ? Color.WHITE : UiTheme.TEXT); + } + + private View notificationRow(final Activity host) { + final Context ctx = host; + LinearLayout item = row(ctx, "♪", "Notification access", + "Reads currently playing song, artist, and album art for the music widget."); + final Button button = UiTheme.button(ctx, "", null, false); + final Activity activity = host; + boolean granted = MusicPlayerManager.hasNotificationAccess(ctx); + button.setText(granted ? "GRANTED" : "GRANT"); + button.setBackground(granted ? UiTheme.surface(UiTheme.SUCCESS, 0) : UiTheme.outline(UiTheme.CYAN, 1, 0)); + button.setTextColor(granted ? Color.WHITE : UiTheme.TEXT); + button.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + try { activity.startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)); } + catch (Exception e) { try { activity.startActivity(new Intent(Settings.ACTION_SETTINGS)); } catch (Exception ignored) {} } + } + }); + item.addView(button, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 130), UiTheme.dp(ctx, 40))); + return item; + } + + private final class AppearanceStep implements Step { + @Override public String title() { return "Appearance"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + body.addView(sectionLabel(ctx, "APPEARANCE", + "Pick a starting theme and choose how large the text should be.")); + body.addView(themeRow(host)); + body.addView(fontSizeRow(host)); + } + @Override public boolean commit(Activity host) { return true; } + } + + private View themeRow(final Activity host) { + final Context ctx = host; + LinearLayout item = row(ctx, "◈", "Theme", null); + HorizontalScrollView scroller = new HorizontalScrollView(ctx); + scroller.setHorizontalScrollBarEnabled(false); + final LinearLayout choices = new LinearLayout(ctx); + choices.setOrientation(LinearLayout.HORIZONTAL); + scroller.addView(choices); + final String[] themeNames = { "MG Dark", "Light", "Amber", "Ocean" }; + final CustomThemes.Theme[] customThemes = CustomThemes.loadAll(ctx).toArray(new CustomThemes.Theme[0]); + int total = themeNames.length + customThemes.length; + SharedPreferences prefs = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + final String activeCustomId = prefs.getString("theme_id", ""); + final int activeBuiltIn = prefs.getInt(UiTheme.PREF_THEME, UiTheme.THEME_DEFAULT); + for (int i = 0; i < total; i++) { + final int themeIndex = i; + final Button swatch = new Button(ctx); + swatch.setAllCaps(false); + swatch.setTextSize(13); + swatch.setMinHeight(0); swatch.setMinimumHeight(0); + swatch.setPadding(UiTheme.dp(ctx, 16), 0, UiTheme.dp(ctx, 16), 0); + int[] palette = resolvePaletteForIndex(ctx, themeIndex, customThemes); + swatch.setBackground(UiTheme.surface(palette[0], 0)); + swatch.setTextColor(palette[4]); + final String label = themeIndex < themeNames.length + ? themeNames[themeIndex] + : customThemes[themeIndex - themeNames.length].name; + swatch.setText(label); + // Mark the active theme with a thicker stroke. + boolean active = themeIndex < themeNames.length + ? (activeCustomId.length() == 0 && themeIndex == activeBuiltIn) + : customThemes[themeIndex - themeNames.length].id.equals(activeCustomId); + if (active) swatch.setBackground(UiTheme.outline(UiTheme.CYAN, 2, 0)); + swatch.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + SharedPreferences p = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + if (themeIndex < 4) { + p.edit().putInt(UiTheme.PREF_THEME, themeIndex).putString("theme_id", "").apply(); + } else { + p.edit().putString("theme_id", customThemes[themeIndex - 4].id).apply(); + } + UiTheme.refreshTheme(host); + // Pull a fresh setContentView so the chrome (title bar, + // progress label, footer note, BACK/NEXT buttons) repaints + // with the new palette. showStep alone only redraws the + // step body and rail. + setContentView(buildUi()); + showStep(currentStep); + renderedThemeVersion = UiTheme.version(); + } + }); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UiTheme.dp(ctx, 56)); + lp.setMargins(UiTheme.dp(ctx, 4), 0, UiTheme.dp(ctx, 4), 0); + choices.addView(swatch, lp); + } + item.addView(scroller, new LinearLayout.LayoutParams(0, UiTheme.dp(ctx, 72), 1)); + return item; + } + + private static int[] resolvePaletteForIndex(Context ctx, int index, CustomThemes.Theme[] customThemes) { + int[][] palettes = UiTheme.builtInPalettes(); + if (index >= 0 && index < palettes.length) return palettes[index]; + CustomThemes.Theme custom = customThemes[index - palettes.length]; + if (custom == null || custom.colors == null) return palettes[0]; + int[] out = new int[palettes[0].length]; + for (int i = 0; i < out.length; i++) out[i] = i < custom.colors.length ? custom.colors[i] : palettes[0][i]; + return out; + } + private View fontSizeRow(final Activity host) { + final Context ctx = host; + LinearLayout item = row(ctx, "A", "Font size", null); + final TextView value = UiTheme.text(ctx, "", 13, UiTheme.MUTED, Typeface.NORMAL); + item.addView(value, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 88), UiTheme.dp(ctx, 40))); + final SeekBar slider = new SeekBar(ctx); + slider.setMax(70); + slider.setProgress(currentFontProgress(ctx)); + Runnable refreshLabel = new Runnable() { + @Override public void run() { + int percent = Math.round((.80f + slider.getProgress() / 100f) * 100f); + value.setText(percent + "%"); + } + }; + refreshLabel.run(); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + refreshLabel.run(); + if (!fromUser) return; + float scale = Math.max(.80f, Math.min(1.50f, .80f + progress / 100f)); + ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE).edit() + .putFloat(UiTheme.PREF_FONT_SCALE, scale).apply(); + } + @Override public void onStartTrackingTouch(SeekBar bar) {} + @Override public void onStopTrackingTouch(SeekBar bar) { + // Reapply the final value and rebuild the activity so every + // TextView re-measures against the new font scale. This mirrors + // the font slider in Settings -> Appearance. + UiTheme.applyFontScale(host); + host.recreate(); + } + }); + item.addView(slider, new LinearLayout.LayoutParams(0, UiTheme.dp(ctx, 60), 1)); + return item; + } + + private static int currentFontProgress(Context ctx) { + float scale = UiTheme.fontScale(ctx); + return Math.max(0, Math.min(70, Math.round((scale - .80f) * 100f))); + } + + private final class FeatureTogglesStep implements Step { + @Override public String title() { return "Features"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + body.addView(sectionLabel(ctx, "DASHBOARD WIDGETS", + "Turn on the dashboard widgets you'd like to see. Each can be toggled on or off individually.")); + body.addView(featureRow(ctx, "≋", "Music Visualizer", + "Live full-width playback spectrum on the home screen.", + UiTheme.UI_PREFS, "home_visualizer_enabled", true)); + body.addView(featureRow(ctx, "♫", "Music Player", + "Now-playing card with song, artist, and album art.", + UiTheme.UI_PREFS, MusicPlayerManager.PREF_ENABLED, false)); + body.addView(featureRow(ctx, "⌄", "Control Panel", + "Swipe down from the home screen for quick controls.", + UiTheme.UI_PREFS, ControlPanelCatalog.PREF_ENABLED, true)); + } + @Override public boolean commit(Activity host) { return true; } + } + + private View featureRow(final Context ctx, String icon, String label, String summary, + final String prefsName, final String key, final boolean defaultValue) { + LinearLayout item = row(ctx, icon, label, summary); + final Button button = toggleButton(ctx, ctx.getSharedPreferences(prefsName, Context.MODE_PRIVATE).getBoolean(key, defaultValue)); + button.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + SharedPreferences p = ctx.getSharedPreferences(prefsName, Context.MODE_PRIVATE); + boolean nowOn = !p.getBoolean(key, defaultValue); + if (UiTheme.UI_PREFS.equals(prefsName) && MusicPlayerManager.PREF_ENABLED.equals(key)) { + MusicPlayerManager.setEnabled(((Activity) ctx), nowOn); + if (nowOn && !MusicPlayerManager.hasNotificationAccess(ctx)) { + Activity a = (Activity) ctx; + try { a.startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)); } + catch (Exception e) { try { a.startActivity(new Intent(Settings.ACTION_SETTINGS)); } catch (Exception ignored) {} } + } + boolean display = MusicPlayerManager.hasNotificationAccess(ctx); + button.setText(nowOn ? (display ? "ON" : "GRANT") : "OFF"); + button.setBackground(nowOn + ? (display ? UiTheme.surface(UiTheme.CYAN, 0) : UiTheme.surface(UiTheme.WARNING, 0)) + : UiTheme.outline(UiTheme.DIVIDER, 1, 0)); + } else { + p.edit().putBoolean(key, nowOn).apply(); + button.setText(nowOn ? "ON" : "OFF"); + button.setBackground(nowOn ? UiTheme.surface(UiTheme.CYAN, 0) : UiTheme.outline(UiTheme.DIVIDER, 1, 0)); + } + } + }); + item.addView(button, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 88), UiTheme.dp(ctx, 40))); + return item; + } + + private final class AppDrawerStep implements Step { + @Override public String title() { return "App Drawer"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + final SharedPreferences prefs = host.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + boolean enabled = prefs.getBoolean(MainActivity.PREF_APP_DRAWER_ENABLED, false); + body.addView(sectionLabel(ctx, "APP DRAWER", + "Add a swipe-up app drawer to the dashboard. Pin the apps you want to launch quickly.")); + body.addView(appDrawerToggleRow(host, prefs, enabled)); + if (enabled) { + body.addView(suggestedAppsCard(host)); + body.addView(openAppsLink(host)); + } else { + TextView skipped = UiTheme.text(ctx, + "You skipped the App Drawer. You can turn it on later in Settings - Appearance - Home screen - App Drawer.", + 12, UiTheme.MUTED, Typeface.NORMAL); + skipped.setPadding(UiTheme.dp(ctx, 14), UiTheme.dp(ctx, 8), UiTheme.dp(ctx, 14), 0); + body.addView(skipped); + } + } + @Override public boolean commit(Activity host) { return true; } + } + + private View appDrawerToggleRow(final Activity host, final SharedPreferences prefs, boolean initial) { + final Context ctx = host; + LinearLayout item = row(ctx, "⌃", "Enable App Drawer", + "Swipe up from the home screen to reveal your pinned apps."); + final Button button = toggleButton(ctx, initial); + button.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + boolean nowOn = !prefs.getBoolean(MainActivity.PREF_APP_DRAWER_ENABLED, false); + prefs.edit().putBoolean(MainActivity.PREF_APP_DRAWER_ENABLED, nowOn).apply(); + showStep(currentStep); + } + }); + item.addView(button, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 88), UiTheme.dp(ctx, 40))); + return item; + } + + private View suggestedAppsCard(final Activity host) { + final Context ctx = host; + LinearLayout card = (LinearLayout) paddedCard(ctx); + TextView title = UiTheme.text(ctx, "SUGGESTED APPS", + 12, UiTheme.MUTED, Typeface.BOLD); + title.setAllCaps(true); + title.setLetterSpacing(.10f); + card.addView(title); + TextView intro = UiTheme.text(ctx, + "Pin anything you'd like to launch from the dashboard. Skip the rest - you can change pins any time in Settings - Apps.", + 12, UiTheme.MUTED, Typeface.NORMAL); + intro.setPadding(0, UiTheme.dp(ctx, 2), 0, UiTheme.dp(ctx, 6)); + card.addView(intro); + + List suggestions = computeSuggestions(host); + if (suggestions.isEmpty()) { + card.addView(UiTheme.text(ctx, "No installed launcher apps detected.", 13, UiTheme.TEXT, Typeface.NORMAL)); + return card; + } + List existing = LauncherPins.loadAll(host); + HashSet alreadyPinned = new HashSet(); + for (LauncherPins.LauncherPin pin : existing) alreadyPinned.add(pin.packageName + "|" + (pin.activityName == null ? "" : pin.activityName)); + for (final SuggestedApp app : suggestions) { + String key = app.packageName + "|" + (app.activityName == null ? "" : app.activityName); + final boolean alreadyPinnedForRow = alreadyPinned.contains(key); + LinearLayout rowLine = new LinearLayout(ctx); + rowLine.setOrientation(LinearLayout.HORIZONTAL); + rowLine.setGravity(Gravity.CENTER_VERTICAL); + rowLine.setPadding(0, UiTheme.dp(ctx, 6), 0, UiTheme.dp(ctx, 6)); + ImageView iconView = new ImageView(ctx); + if (app.icon != null) { + iconView.setImageDrawable(app.icon); + iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); + } else { + iconView.setImageDrawable(null); + } + rowLine.addView(iconView, new LinearLayout.LayoutParams(UiTheme.dp(ctx, 44), UiTheme.dp(ctx, 44))); + LinearLayout labelBox = new LinearLayout(ctx); + labelBox.setOrientation(LinearLayout.VERTICAL); + labelBox.setPadding(UiTheme.dp(ctx, 12), 0, 0, 0); + labelBox.addView(UiTheme.text(ctx, app.label, 15, UiTheme.TEXT, Typeface.NORMAL)); + if (app.reason != null) labelBox.addView(UiTheme.text(ctx, app.reason, 11, UiTheme.MUTED, Typeface.NORMAL)); + rowLine.addView(labelBox, new LinearLayout.LayoutParams(0, -2, 1)); + final Button pin = new Button(ctx); + pin.setAllCaps(true); + pin.setTextSize(13); + pin.setLetterSpacing(.08f); + pin.setMinHeight(0); pin.setMinimumHeight(0); + pin.setText(alreadyPinnedForRow ? "PINNED" : "PIN"); + pin.setBackground(alreadyPinnedForRow ? UiTheme.surface(UiTheme.SUCCESS, 0) : UiTheme.outline(UiTheme.CYAN, 1, 0)); + pin.setTextColor(alreadyPinnedForRow ? Color.WHITE : UiTheme.TEXT); + pin.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + List pins = LauncherPins.loadAll(host); + HashSet keySet = new HashSet(); + for (LauncherPins.LauncherPin p : pins) keySet.add(p.packageName + "|" + (p.activityName == null ? "" : p.activityName)); + String key = app.packageName + "|" + (app.activityName == null ? "" : app.activityName); + if (keySet.contains(key)) { + for (int i = 0; i < pins.size(); i++) { + LauncherPins.LauncherPin p = pins.get(i); + String k = p.packageName + "|" + (p.activityName == null ? "" : p.activityName); + if (k.equals(key)) { pins.remove(i); break; } + } + LauncherPins.saveAll(host, pins); + pin.setText("PIN"); + pin.setBackground(UiTheme.outline(UiTheme.CYAN, 1, 0)); + pin.setTextColor(UiTheme.TEXT); + } else { + String letter = (app.label == null || app.label.length() == 0) ? "A" : app.label.substring(0, 1).toUpperCase(Locale.US); + LauncherPins.add(host, new LauncherPins.LauncherPin(0L, app.packageName, + app.activityName, app.label, "APP", letter)); + pin.setText("PINNED"); + pin.setBackground(UiTheme.surface(UiTheme.SUCCESS, 0)); + pin.setTextColor(Color.WHITE); + } + } + }); + LinearLayout.LayoutParams pinLp = new LinearLayout.LayoutParams(UiTheme.dp(ctx, 110), UiTheme.dp(ctx, 40)); + pinLp.setMargins(UiTheme.dp(ctx, 8), 0, 0, 0); + rowLine.addView(pin, pinLp); + card.addView(rowLine); + } + return card; + } + + private View openAppsLink(final Activity host) { + final Context ctx = host; + LinearLayout wrap = new LinearLayout(ctx); + wrap.setOrientation(LinearLayout.HORIZONTAL); + wrap.setGravity(Gravity.CENTER_VERTICAL); + wrap.setPadding(UiTheme.dp(ctx, 8), UiTheme.dp(ctx, 8), 0, 0); + wrap.addView(UiTheme.text(ctx, "Want a custom pin?", 12, UiTheme.MUTED, Typeface.NORMAL), + new LinearLayout.LayoutParams(0, -2, 1)); + Button open = UiTheme.button(ctx, "OPEN APPS", new View.OnClickListener() { + @Override public void onClick(View v) { + host.startActivity(new Intent(host, SettingsActivity.class)); + } + }, false); + open.setTextSize(12); + wrap.addView(open, new LinearLayout.LayoutParams(-2, UiTheme.dp(ctx, 40))); + return wrap; + } + + private static final class SuggestedApp { + final String packageName; + final String activityName; + final String label; + final String reason; + final Drawable icon; + SuggestedApp(String packageName, String activityName, String label, String reason, Drawable icon) { + this.packageName = packageName; this.activityName = activityName; + this.label = label; this.reason = reason; this.icon = icon; + } + } + + private List computeSuggestions(Activity host) { + ArrayList result = new ArrayList(); + PackageManager pm = host.getPackageManager(); + HashSet seen = new HashSet(); + String[][] known = { + { "com.saicmotor.hmi.launcher", null, "SAIC launcher" }, + { "com.android.settings", null, "Android Settings" }, + { "com.android.contacts", null, "Contacts" }, + { "com.android.dialer", null, "Phone" }, + { "com.android.mms", null, "Messages" }, + { "com.google.android.gms", null, "Google Play services" }, + { "com.google.android.googlequicksearchbox", null, "Google Search" }, + { "com.google.android.apps.maps", null, "Maps" }, + { "com.android.music", null, "Music" }, + { "com.android.chrome", null, "Chrome" }, + { "com.android.camera2", null, "Camera" } + }; + for (String[] k : known) { + String pkg = k[0]; String reason = k[2]; + ResolveInfo info = resolveLauncherActivity(pm, pkg, null); + if (info == null) continue; + String key = info.activityInfo.packageName + "|" + info.activityInfo.name; + if (!seen.add(key)) continue; + String label = info.loadLabel(pm).toString(); + Drawable icon = null; + try { icon = pm.getApplicationIcon(info.activityInfo.packageName); } catch (Exception e) { } + result.add(new SuggestedApp(info.activityInfo.packageName, info.activityInfo.name, label, reason, icon)); + } + if (result.size() < 12) { + Intent query = new Intent(Intent.ACTION_MAIN); + query.addCategory(Intent.CATEGORY_LAUNCHER); + List apps = pm.queryIntentActivities(query, 0); + HashMap counts = new HashMap(); + for (ResolveInfo info : apps) { + Integer current = counts.get(info.activityInfo.packageName); + counts.put(info.activityInfo.packageName, current == null ? 1 : current + 1); + } + List extras = new ArrayList(); + for (ResolveInfo info : apps) { + String key = info.activityInfo.packageName + "|" + info.activityInfo.name; + if (!seen.add(key)) continue; + Drawable icon = null; + try { icon = pm.getApplicationIcon(info.activityInfo.packageName); } catch (Exception e) { } + String label = info.loadLabel(pm).toString(); + Integer count = counts.get(info.activityInfo.packageName); + String reason = (count != null && count > 1) ? "Multiple activities" : null; + extras.add(new SuggestedApp(info.activityInfo.packageName, info.activityInfo.name, label, reason, icon)); + } + Collections.sort(extras, new Comparator() { + @Override public int compare(SuggestedApp a, SuggestedApp b) { + return a.label.toLowerCase(Locale.US).compareTo(b.label.toLowerCase(Locale.US)); + } + }); + for (SuggestedApp s : extras) { + if (result.size() >= 12) break; + result.add(s); + } + } + return result; + } + + private static ResolveInfo resolveLauncherActivity(PackageManager pm, String packageName, String activityName) { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + if (activityName == null) intent.setPackage(packageName); + List matches = pm.queryIntentActivities(intent, 0); + if (activityName == null) { + for (ResolveInfo info : matches) if (info.activityInfo.packageName.equals(packageName)) return info; + return null; + } + for (ResolveInfo info : matches) if (info.activityInfo.packageName.equals(packageName) && info.activityInfo.name.equals(activityName)) return info; + return null; + } + + private final class FinishStep implements Step { + @Override public String title() { return "Finish"; } + @Override public void render(Activity host, LinearLayout body) { + Context ctx = host; + body.addView(sectionLabel(ctx, "YOU'RE ALL SET", + "Summary of what you've chosen. Press Finish to save and return to the dashboard.")); + LinearLayout card = (LinearLayout) paddedCard(ctx); + addSummaryRow(ctx, card, "Fine location", permissionSummary(ctx, Manifest.permission.ACCESS_FINE_LOCATION)); + addSummaryRow(ctx, card, "Audio capture", permissionSummary(ctx, Manifest.permission.RECORD_AUDIO)); + addSummaryRow(ctx, card, "Notification access", + MusicPlayerManager.hasNotificationAccess(ctx) ? "Granted" : "Not granted"); + addSummaryRow(ctx, card, "Theme", currentThemeLabel(ctx)); + addSummaryRow(ctx, card, "Font size", Math.round(UiTheme.fontScale(ctx) * 100f) + "%"); + addSummaryRow(ctx, card, "Music Visualizer", featureLabel(ctx, "home_visualizer_enabled", true)); + addSummaryRow(ctx, card, "Music Player", featureLabel(ctx, MusicPlayerManager.PREF_ENABLED, false)); + addSummaryRow(ctx, card, "Control Panel", featureLabel(ctx, ControlPanelCatalog.PREF_ENABLED, true)); + SharedPreferences prefs = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + boolean drawerOn = prefs.getBoolean(MainActivity.PREF_APP_DRAWER_ENABLED, false); + addSummaryRow(ctx, card, "App Drawer", drawerOn ? ("Enabled - " + LauncherPins.loadAll(ctx).size() + " pinned") : "Disabled"); + body.addView(card); + + TextView trailing = UiTheme.text(ctx, + "Re-run this wizard any time from Settings - Misc - Run setup wizard.", + 12, UiTheme.MUTED, Typeface.NORMAL); + trailing.setPadding(UiTheme.dp(ctx, 14), UiTheme.dp(ctx, 8), UiTheme.dp(ctx, 14), 0); + body.addView(trailing); + } + @Override public boolean commit(Activity host) { return true; } + } + + private static void addSummaryRow(Context ctx, LinearLayout body, String label, String value) { + LinearLayout rowLine = new LinearLayout(ctx); + rowLine.setOrientation(LinearLayout.HORIZONTAL); + rowLine.setGravity(Gravity.CENTER_VERTICAL); + rowLine.setPadding(0, UiTheme.dp(ctx, 4), 0, UiTheme.dp(ctx, 4)); + rowLine.addView(UiTheme.text(ctx, label, 13, UiTheme.MUTED, Typeface.NORMAL), + new LinearLayout.LayoutParams(0, -2, 1)); + TextView valueView = UiTheme.text(ctx, value == null ? "-" : value, 13, UiTheme.TEXT, Typeface.BOLD); + valueView.setGravity(Gravity.RIGHT); + rowLine.addView(valueView, new LinearLayout.LayoutParams(-2, -2)); + body.addView(rowLine); + } + + private static String permissionSummary(Context ctx, String permission) { + if (Build.VERSION.SDK_INT < 23) return "Always granted"; + return ctx.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED + ? "Granted" : "Not granted"; + } + + private static String featureLabel(Context ctx, String key, boolean defaultValue) { + boolean on = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE).getBoolean(key, defaultValue); + return on ? "On" : "Off"; + } + + private static String currentThemeLabel(Context ctx) { + SharedPreferences prefs = ctx.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + String customId = prefs.getString("theme_id", ""); + if (customId.length() > 0) return "Custom"; + int theme = prefs.getInt(UiTheme.PREF_THEME, UiTheme.THEME_DEFAULT); + if (theme == UiTheme.THEME_LIGHT) return "Light"; + if (theme == UiTheme.THEME_AMBER) return "Amber"; + if (theme == UiTheme.THEME_OCEAN) return "Ocean"; + return "MG Dark"; + } +} diff --git a/src/cloud/molberg/mgutility/SteeringAngleSource.java b/src/cloud/molberg/mgutility/SteeringAngleSource.java new file mode 100644 index 0000000..4f1e647 --- /dev/null +++ b/src/cloud/molberg/mgutility/SteeringAngleSource.java @@ -0,0 +1,26 @@ +package cloud.molberg.mgutility; + +import java.lang.reflect.Method; + +final class SteeringAngleSource { + private static final String PROPERTY = "arcsoft.avm.mCurCarWheelAngle"; + private static volatile String status = "Steering: waiting for enabled liquid mode"; + private Method getter; + + static String status() { return status; } + + float read() { + try { + if (getter == null) getter = Class.forName("android.os.SystemProperties") + .getMethod("get", String.class, String.class); + String raw = (String) getter.invoke(null, PROPERTY, ""); + float angle = LiquidSoundBalanceCurve.parseSteering(raw); + status = Float.isNaN(angle) ? "Steering unavailable: missing or invalid property" : + String.format(java.util.Locale.US, "Steering: %.1f° • + left / − right", angle); + return angle; + } catch (Exception error) { + status = "Steering unavailable: " + error.getClass().getSimpleName(); + return Float.NaN; + } + } +} diff --git a/src/cloud/molberg/mgutility/TripTrackingService.java b/src/cloud/molberg/mgutility/TripTrackingService.java index 0a5dec8..e013503 100644 --- a/src/cloud/molberg/mgutility/TripTrackingService.java +++ b/src/cloud/molberg/mgutility/TripTrackingService.java @@ -44,6 +44,7 @@ public final class TripTrackingService extends Service { private static final int MIN_SAMPLE_INTERVAL_SECONDS = 1; private static final int MAX_SAMPLE_INTERVAL_SECONDS = 60; private static final long SPEED_AUDIO_INTERVAL_MS = 200L; + private static final long LIQUID_BALANCE_INTERVAL_MS = 100L; private static final long PARKED_GRACE_MS = 45 * 1000L; /** SAIC VehicleConstant.CarGearValue.CAR_GEAR_PARK_RANGE is 1. */ private static final int PARK_GEAR_VALUE = 1; @@ -89,6 +90,15 @@ public final class TripTrackingService extends Service { private double regenEventEnergyKwh; private double regenEventRangeKm; private float regenEventPeakSpeedKph; + private float previousLiquidBalanceSpeedKph = Float.NaN; + private long previousLiquidBalanceAt; + private int liquidBalanceLastAppliedBalance = Integer.MIN_VALUE; + private int liquidBalanceLastAppliedFader = Integer.MIN_VALUE; + private final LiquidSoundBalanceMotion liquidBalanceMotion = new LiquidSoundBalanceMotion(); + private final SteeringAngleSource liquidSteering = new SteeringAngleSource(); + private float liquidFilteredAcceleration; + private float liquidVolumeMultiplier = 1f; + private boolean liquidBalanceSessionStarted; private final BroadcastReceiver soundboardReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { @@ -113,11 +123,16 @@ public final class TripTrackingService extends Service { @Override public void run() { boolean reactiveAudio = SpeedAudioManager.shouldPoll(TripTrackingService.this); boolean adaptiveLeveling = AdaptiveAudioLevelingManager.shouldPoll(TripTrackingService.this); - if (reactiveAudio || adaptiveLeveling) pollSpeedAudio(reactiveAudio, adaptiveLeveling); + boolean liquidBalance = LiquidSoundBalanceManager.shouldPoll(TripTrackingService.this); + if (reactiveAudio || adaptiveLeveling || liquidBalance) pollSpeedAudio(reactiveAudio, liquidBalance); if (!reactiveAudio) SpeedAudioManager.stopReactive(); - if (!adaptiveLeveling) AdaptiveAudioLevelingManager.stopAndRestore(TripTrackingService.this); + if (!adaptiveLeveling && !liquidBalance) AdaptiveAudioLevelingManager.stopAndRestore(TripTrackingService.this); + if (!liquidBalance) { + restoreLiquidSoundBalance(); + } if (worker != null) worker.postDelayed(this, - reactiveAudio || adaptiveLeveling ? SPEED_AUDIO_INTERVAL_MS : 1000L); + liquidBalance ? LIQUID_BALANCE_INTERVAL_MS : + reactiveAudio || adaptiveLeveling ? SPEED_AUDIO_INTERVAL_MS : 1000L); } }; @@ -288,6 +303,7 @@ public final class TripTrackingService extends Service { vehicle = null; SpeedAudioManager.stopReactive(); AdaptiveAudioLevelingManager.stopAndRestore(this); + restoreLiquidSoundBalance(); if (workerThread != null) workerThread.quitSafely(); finishRegenEvent(System.currentTimeMillis()); if (database != null) database.close(); @@ -417,15 +433,84 @@ public final class TripTrackingService extends Service { processSample(sample, System.currentTimeMillis()); } - private void pollSpeedAudio(boolean reactiveAudio, boolean adaptiveLeveling) { + private void pollSpeedAudio(boolean reactiveAudio, boolean liquidBalance) { EnergyActivity.VehicleGateway gateway = vehicle; - if (gateway == null) return; + if (gateway == null) { + if (liquidBalance) restoreLiquidSoundBalance(); + AdaptiveAudioLevelingManager.stopAndRestore(this); + return; + } float speed; try { speed = gateway.readSpeed(); } - catch (Exception ignored) { return; } + catch (Exception ignored) { + if (liquidBalance) restoreLiquidSoundBalance(); + AdaptiveAudioLevelingManager.stopAndRestore(this); + return; + } float validSpeed = validSpeed(speed); if (reactiveAudio) SpeedAudioManager.updateSpeed(this, validSpeed); - if (adaptiveLeveling) AdaptiveAudioLevelingManager.updateSpeed(this, validSpeed); + if (liquidBalance) { + if (Float.isNaN(speed) || Float.isInfinite(speed) || speed < 0f || speed > 300f) { + restoreLiquidSoundBalance(); + } else { + updateLiquidSoundBalance(validSpeed / EnergyActivity.VehicleGateway.DISPLAY_SPEED_FACTOR); + } + } + LiquidSoundBalanceManager.Config liquidConfig = LiquidSoundBalanceManager.config(this); + AdaptiveAudioLevelingManager.updateSpeed(this, validSpeed, + liquidBalance ? liquidVolumeMultiplier : 1f, + liquidBalance && liquidConfig.volumeBoost); + } + + private void updateLiquidSoundBalance(float speedKph) { + LiquidSoundBalanceManager.Config config = LiquidSoundBalanceManager.config(this); + MgServiceBridge bridge = MgServiceBridge.get(); + long now = android.os.SystemClock.elapsedRealtime(); + float acceleration = 0f; + float seconds = (now - previousLiquidBalanceAt) / 1000f; + if (previousLiquidBalanceAt > 0L && seconds > 0f && seconds <= 2f) { + acceleration = (speedKph - previousLiquidBalanceSpeedKph) * 1000f / + (now - previousLiquidBalanceAt); + liquidFilteredAcceleration += (acceleration - liquidFilteredAcceleration) * + (1f - (float) Math.exp(-seconds / 0.25f)); + } else { + liquidBalanceMotion.reset(); + liquidFilteredAcceleration = 0f; + seconds = 0.1f; + } + previousLiquidBalanceSpeedKph = speedKph; + previousLiquidBalanceAt = now; + liquidBalanceSessionStarted = true; + liquidBalanceLastAppliedBalance = bridge.getSoundFieldBalance(); + liquidBalanceLastAppliedFader = bridge.getSoundFieldFader(); + liquidVolumeMultiplier = LiquidSoundBalanceCurve.volumeMultiplier(liquidBalanceLastAppliedBalance, + liquidBalanceLastAppliedFader, config.anchorX, config.anchorY, config.volumeBoost, config.boostPercent); + float steering = Float.NaN; + if (config.horizontalSway) steering = liquidSteering.read(); + liquidBalanceMotion.update(liquidFilteredAcceleration, speedKph, steering, + config.thresholdKphPerSecond, config.powerPercent, config.horizontalSway, + config.reverseSteering, config.bounce, config.anchorX, config.anchorY, seconds); + int requested = liquidBalanceMotion.fader(config.anchorY); + int balance = liquidBalanceMotion.balance(config.anchorX); + if ((requested != liquidBalanceLastAppliedFader || balance != liquidBalanceLastAppliedBalance) && + bridge.setSoundField(balance, requested)) { + liquidBalanceLastAppliedFader = requested; + liquidBalanceLastAppliedBalance = balance; + } + } + + private void restoreLiquidSoundBalance() { + LiquidSoundBalanceManager.Config config = LiquidSoundBalanceManager.config(this); + liquidBalanceMotion.reset(); + liquidVolumeMultiplier = 1f; + liquidFilteredAcceleration = 0f; + previousLiquidBalanceSpeedKph = Float.NaN; + previousLiquidBalanceAt = 0L; + if (liquidBalanceSessionStarted && !MgServiceBridge.get().setSoundField( + config.anchorX, config.anchorY)) return; + liquidBalanceSessionStarted = false; + liquidBalanceLastAppliedFader = Integer.MIN_VALUE; + liquidBalanceLastAppliedBalance = Integer.MIN_VALUE; } private int readGearSafely() { diff --git a/src/cloud/molberg/mgutility/UiTheme.java b/src/cloud/molberg/mgutility/UiTheme.java index becb28f..d9b5568 100644 --- a/src/cloud/molberg/mgutility/UiTheme.java +++ b/src/cloud/molberg/mgutility/UiTheme.java @@ -4,6 +4,7 @@ import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.Drawable; import android.app.Activity; import android.app.AlertDialog; import android.content.res.Configuration; @@ -53,7 +54,7 @@ final class UiTheme { if (seekBar == null) return; // AppTheme's platform accent is only a fallback. Explicitly tint controls // so switching to a custom/preset palette also updates the slider track/thumb. - ColorStateList colors = ColorStateList.valueOf(RED); + ColorStateList colors = ColorStateList.valueOf(CYAN); seekBar.setProgressTintList(colors); seekBar.setThumbTintList(colors); } @@ -168,15 +169,15 @@ final class UiTheme { return DIVIDER; } - /** Stable ordering and display labels for the palette roles shown in the custom theme editor. */ + /** Stable ordering for the 14-color compatibility palette used by saved themes. */ static String[] colorKeys() { return new String[] { "background", "surface", "surface_high", "surface_pressed", "text", "muted", "red", "red_bright", "cyan", "cyan_bright", "success", "warning", "blue", "divider" }; } + /** The editor exposes six simple semantic colors; each drives related UI roles. */ static String[] colorLabels() { - return new String[] { "Background", "Surface", "Raised surface", "Pressed surface", "Text", "Muted text", - "Primary red", "Bright red", "Accent cyan", "Bright cyan", "Success", "Warning", "Blue", "Divider" }; + return new String[] { "Primary", "Secondary", "Background", "Borders", "Sliders", "Toggles" }; } /** Built-in palettes indexed by their THEME_* ids. Kept in sync with `loadTheme`. */ @@ -266,6 +267,20 @@ final class UiTheme { return v; } + /** Material-style vector icon catalog for consistent rendering across head units. */ + static ImageView icon(Context context, String name, int color, int sizeDp) { + int resource = context.getResources().getIdentifier("ic_" + name, "drawable", context.getPackageName()); + ImageView image = new ImageView(context); + image.setImageResource(resource == 0 ? R.drawable.ic_help : resource); + image.setColorFilter(color); + image.setScaleType(ImageView.ScaleType.FIT_CENTER); + image.setContentDescription(name.replace('_', ' ')); + image.setLayoutParams(new LinearLayout.LayoutParams(dp(context, sizeDp), dp(context, sizeDp))); + return image; + } + + static ImageView icon(Context context, String name, int color) { return icon(context, name, color, 24); } + static void card(View view, Context c) { view.setBackground(surface(SURFACE, 12)); view.setElevation(dp(c, 2)); diff --git a/src/cloud/molberg/mgutility/UpdateActivity.java b/src/cloud/molberg/mgutility/UpdateActivity.java new file mode 100644 index 0000000..c834942 --- /dev/null +++ b/src/cloud/molberg/mgutility/UpdateActivity.java @@ -0,0 +1,164 @@ +package cloud.molberg.mgutility; + +import android.content.DialogInterface; +import android.content.Intent; +import android.graphics.Typeface; +import android.net.Uri; +import android.os.Bundle; +import android.provider.Settings; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.io.File; +import java.util.List; +import java.util.Locale; + +/** Update settings and the complete download/install experience. */ +public final class UpdateActivity extends AnimatedActivity { + public static final String EXTRA_VERSION_CODE = "update_version_code"; + private LinearLayout content; + private LinearLayout history; + private TextView status; + private Button download; + private UpdateManager.Release available; + private File downloaded; + private boolean downgradeConfirmed; + private boolean waitingForInstallPermission; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); UiTheme.applyFontScale(this); immersive(); + setContentView(buildUi()); render(); UpdateScheduler.schedule(this); checkForUpdate(); + } + + @Override protected void onResume() { + super.onResume(); immersive(); + if (waitingForInstallPermission && android.os.Build.VERSION.SDK_INT >= 26 && getPackageManager().canRequestPackageInstalls()) { + waitingForInstallPermission = false; UpdateManager.install(this, downloaded); + } + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); root.setOrientation(LinearLayout.VERTICAL); root.setPadding(28, 12, 28, 18); root.setBackgroundColor(UiTheme.BACKGROUND); + LinearLayout header = new LinearLayout(this); header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "SOFTWARE UPDATE", 30), new LinearLayout.LayoutParams(0, 62, 1)); + header.addView(UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }), new LinearLayout.LayoutParams(120, 52)); root.addView(header); + ScrollView scroll = new ScrollView(this); content = new LinearLayout(this); content.setOrientation(LinearLayout.VERTICAL); content.setPadding(0, 12, 0, 0); scroll.addView(content); root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private void render() { + content.removeAllViews(); + subsection("Installed build", "The version and source used by this installation"); + content.addView(row("▣", "Installed version", UpdateManager.installedVersion(this), null)); + content.addView(row("⌁", "Installed channel / branch", titleCase(UpdateManager.installedChannel(this)) + " • " + UpdateManager.installedBranch(this), null)); + subsection("Update source", "Only signed releases from the MG Utility Gitea repository are accepted"); + content.addView(row("◈", "Update channel", titleCase(UpdateManager.selectedChannel(this)) + " releases", new View.OnClickListener() { @Override public void onClick(View v) { chooseChannel(); } })); + content.addView(toggleRow("●", "Notify on updates", "Check automatically and show a short notification when a release is ready", UpdateManager.notifyEnabled(this))); + status = UiTheme.text(this, "Checking " + titleCase(UpdateManager.selectedChannel(this)) + " releases…", 13, UiTheme.MUTED, Typeface.NORMAL); status.setPadding(18, 14, 18, 14); content.addView(status); + download = UiTheme.button(this, "DOWNLOAD UPDATE", null, false); download.setVisibility(View.GONE); download.setEnabled(false); content.addView(download, new LinearLayout.LayoutParams(-1, 52)); + content.addView(row("↻", "Check now", "Ask Gitea for the latest " + UpdateManager.selectedChannel(this) + " release", new View.OnClickListener() { @Override public void onClick(View v) { checkForUpdate(); } })); + subsection("Available versions", "Current, newer, and up to five earlier " + UpdateManager.selectedChannel(this) + " builds"); + history = new LinearLayout(this); history.setOrientation(LinearLayout.VERTICAL); content.addView(history, new LinearLayout.LayoutParams(-1, -2)); + subsection("How updates work", "A verified APK is downloaded privately, then Android asks for the final install confirmation. MG Utility never installs an APK silently."); + } + + private void checkForUpdate() { + if (status != null) status.setText("Checking " + titleCase(UpdateManager.selectedChannel(this)) + " releases…"); + if (download != null) { download.setVisibility(View.GONE); download.setText("DOWNLOAD UPDATE"); download.setEnabled(false); } + available = null; downgradeConfirmed = false; + UpdateManager.checkAsync(this, new UpdateManager.Callback() { + @Override public void onResult(List releases, Exception error) { + if (history != null) renderHistory(releases); + if (error != null) { showStatus("Unable to check Gitea right now", UiTheme.WARNING); return; } + UpdateManager.Release newest = null; + int installedCode = UpdateManager.installedVersionCode(UpdateActivity.this); + for (UpdateManager.Release release : releases) { + if (release.versionCode > installedCode) { newest = release; break; } + } + if (newest == null) { showStatus("You are up to date", UiTheme.SUCCESS); return; } + prepareRelease(newest, false); + } + }); + } + + private void renderHistory(List releases) { + history.removeAllViews(); + int installedCode = UpdateManager.installedVersionCode(this); + int earlierCount = 0; + for (final UpdateManager.Release release : releases) { + boolean current = release.versionCode == installedCode; + boolean downgrade = release.versionCode < installedCode; + if (downgrade && earlierCount++ >= 5) continue; + String kind = current ? "CURRENT" : (downgrade ? "DOWNGRADE" : "UPDATE"); + String detail = kind + " • " + titleCase(release.channel); + history.addView(row("◌", release.versionName, detail, current ? null : new View.OnClickListener() { + @Override public void onClick(View v) { selectRelease(release); } + })); + } + if (history.getChildCount() == 0) history.addView(row("·", "No releases available", "Try Check now again later", null)); + } + + private void selectRelease(final UpdateManager.Release release) { + if (release.versionCode == UpdateManager.installedVersionCode(this)) return; + if (release.versionCode < UpdateManager.installedVersionCode(this)) { + UiTheme.dialog(this) + .setTitle("CONFIRM DOWNGRADE") + .setMessage("Downgrading may break features because configuration formats or other app data may have changed. Keep a backup before continuing.") + .setNegativeButton("CANCEL", null) + .setPositiveButton("CONTINUE", new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { prepareRelease(release, true); } + }).show(); + } else { + prepareRelease(release, false); + } + } + + private void prepareRelease(final UpdateManager.Release release, boolean downgrade) { + available = release; downgradeConfirmed = !downgrade; + showStatus((downgrade ? "Downgrade ready: " : "Update ready: ") + release.label(), downgrade ? UiTheme.WARNING : UiTheme.CYAN); + download.setVisibility(View.VISIBLE); download.setText((downgrade ? "DOWNLOAD DOWNGRADE " : "DOWNLOAD ") + formatBytes(release.size)); download.setEnabled(true); + download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { downloadUpdate(); } }); + } + + private void downloadUpdate() { + final UpdateManager.Release release = available; if (release == null) return; + if (release.versionCode < UpdateManager.installedVersionCode(this) && !downgradeConfirmed) return; + download.setEnabled(false); download.setText("DOWNLOADING…"); showStatus("Downloading " + release.versionName + "…", UiTheme.CYAN); + new Thread(new Runnable() { @Override public void run() { try { final File file = UpdateManager.download(UpdateActivity.this, release, new UpdateManager.Progress() { @Override public void onProgress(final long done, final long total) { runOnUiThread(new Runnable() { @Override public void run() { if (download != null) download.setText(total > 0 ? "DOWNLOADING " + (done * 100 / total) + "%" : "DOWNLOADING…"); } }); } }); runOnUiThread(new Runnable() { @Override public void run() { downloaded = file; showStatus("Download verified. Android is ready to install it.", UiTheme.SUCCESS); download.setText("INSTALL UPDATE"); download.setEnabled(true); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { installDownloaded(); } }); installDownloaded(); } }); } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { showStatus("Download rejected: " + (e.getMessage() == null ? "verification failed" : e.getMessage()), UiTheme.WARNING); download.setText("RETRY DOWNLOAD"); download.setEnabled(true); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { downloadUpdate(); } }); } }); } } }, "mg-update-download").start(); + } + + private void installDownloaded() { + if (downloaded == null || !downloaded.exists()) return; + if (android.os.Build.VERSION.SDK_INT >= 26 && !getPackageManager().canRequestPackageInstalls()) { waitingForInstallPermission = true; startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()))); return; } + UpdateManager.install(this, downloaded); + } + + private void chooseChannel() { + final String[] options = { "Dev — newest builds from main", "Stable — explicitly published releases" }; final String current = UpdateManager.selectedChannel(this); int checked = UpdateManager.CHANNEL_STABLE.equals(current) ? 1 : 0; + UiTheme.dialog(this).setTitle("UPDATE CHANNEL").setSingleChoiceItems(options, checked, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UpdateManager.setChannel(UpdateActivity.this, which == 1 ? UpdateManager.CHANNEL_STABLE : UpdateManager.CHANNEL_DEV); dialog.dismiss(); render(); checkForUpdate(); } }).show(); + } + + private View toggleRow(String icon, String label, String detail, final boolean enabled) { + LinearLayout item = new LinearLayout(this); item.setGravity(Gravity.CENTER_VERTICAL); item.setPadding(18, 0, 18, 0); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); ImageView iconView = UiTheme.icon(this, IconPack.forLabel(label), UiTheme.CYAN, 24); iconView.setPadding(11, 11, 11, 11); item.addView(iconView, new LinearLayout.LayoutParams(46, 68)); LinearLayout copy = new LinearLayout(this); copy.setOrientation(LinearLayout.VERTICAL); copy.setGravity(Gravity.CENTER_VERTICAL); copy.addView(UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL)); copy.addView(UiTheme.text(this, detail, 12, UiTheme.MUTED, Typeface.NORMAL)); item.addView(copy, new LinearLayout.LayoutParams(0, 68, 1)); final Button button = UiTheme.button(this, enabled ? "ON" : "OFF", null, false); button.setBackground(enabled ? UiTheme.surface(UiTheme.CYAN, 0) : UiTheme.outline(UiTheme.DIVIDER, 1, 0)); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdateManager.setNotifyEnabled(UpdateActivity.this, !UpdateManager.notifyEnabled(UpdateActivity.this)); render(); checkForUpdate(); } }); item.addView(button, new LinearLayout.LayoutParams(88, 46)); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68); p.setMargins(0, 0, 0, 2); item.setLayoutParams(p); return item; + } + + private View row(String icon, String label, String value, View.OnClickListener listener) { + LinearLayout item = new LinearLayout(this); item.setGravity(Gravity.CENTER_VERTICAL); item.setPadding(18, 0, 18, 0); item.setBackground(UiTheme.surface(UiTheme.SURFACE, 5)); if (listener != null) item.setOnClickListener(listener); ImageView iconView = UiTheme.icon(this, IconPack.forLabel(label), UiTheme.CYAN, 24); iconView.setPadding(11, 11, 11, 11); item.addView(iconView, new LinearLayout.LayoutParams(46, 68)); TextView name = UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL); name.setGravity(Gravity.CENTER_VERTICAL); item.addView(name, new LinearLayout.LayoutParams(0, 68, 1)); TextView detail = UiTheme.text(this, value, 13, UiTheme.MUTED, Typeface.NORMAL); detail.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); item.addView(detail, new LinearLayout.LayoutParams(400, 68)); ImageView arrow = listener == null ? new ImageView(this) : UiTheme.icon(this, "chevron_right", UiTheme.CYAN, 20); arrow.setContentDescription(listener == null ? null : "Open"); item.addView(arrow, new LinearLayout.LayoutParams(32, 68)); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68); p.setMargins(0, 0, 0, 2); item.setLayoutParams(p); return item; + } + + private void subsection(String title, String subtitle) { TextView heading = UiTheme.label(this, title.toUpperCase(Locale.US)); heading.setPadding(18, 12, 0, 3); content.addView(heading, new LinearLayout.LayoutParams(-1, 32)); TextView hint = UiTheme.text(this, subtitle, 11, UiTheme.MUTED, Typeface.NORMAL); hint.setPadding(18, 0, 0, 5); content.addView(hint, new LinearLayout.LayoutParams(-1, 30)); } + private void showStatus(String text, int color) { if (status != null) { status.setText(text); status.setTextColor(color); } } + private String titleCase(String value) { return value.length() == 0 ? value : value.substring(0, 1).toUpperCase(Locale.US) + value.substring(1); } + private String formatBytes(long bytes) { if (bytes <= 0) return "UPDATE"; return String.format(Locale.US, "UPDATE %.1f MB", bytes / 1048576.0); } +} diff --git a/src/cloud/molberg/mgutility/UpdateApkProvider.java b/src/cloud/molberg/mgutility/UpdateApkProvider.java new file mode 100644 index 0000000..6e5e7fe --- /dev/null +++ b/src/cloud/molberg/mgutility/UpdateApkProvider.java @@ -0,0 +1,22 @@ +package cloud.molberg.mgutility; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.os.ParcelFileDescriptor; + +import java.io.File; + +/** Narrow read-only provider exposing only the verified APK to Android's installer. */ +public final class UpdateApkProvider extends ContentProvider { + @Override public boolean onCreate() { return true; } + private File file() { File directory = new File(getContext().getFilesDir(), "updates"); File[] files = directory.listFiles(); if (files == null) return null; File best = null; for (File f : files) if (f.getName().endsWith(".apk") && (best == null || f.lastModified() > best.lastModified())) best = f; return best; } + @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws java.io.FileNotFoundException { if (!"r".equals(mode) || uri == null || !"apk".equals(uri.getLastPathSegment())) throw new java.io.FileNotFoundException("Update APK is read-only"); File file = file(); if (file == null) throw new java.io.FileNotFoundException("No downloaded update"); return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } + @Override public String getType(Uri uri) { return "application/vnd.android.package-archive"; } + @Override public Cursor query(Uri uri, String[] projection, String selection, String[] args, String sortOrder) { File file = file(); MatrixCursor cursor = new MatrixCursor(new String[] { "_display_name", "_size" }); if (file != null) cursor.addRow(new Object[] { file.getName(), file.length() }); return cursor; } + @Override public int delete(Uri uri, String selection, String[] args) { return 0; } + @Override public int update(Uri uri, ContentValues values, String selection, String[] args) { return 0; } + @Override public Uri insert(Uri uri, ContentValues values) { return null; } +} diff --git a/src/cloud/molberg/mgutility/UpdateManager.java b/src/cloud/molberg/mgutility/UpdateManager.java new file mode 100644 index 0000000..79b7876 --- /dev/null +++ b/src/cloud/molberg/mgutility/UpdateManager.java @@ -0,0 +1,264 @@ +package cloud.molberg.mgutility; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.provider.Settings; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; + +/** Gitea release updater. Releases are the update store; no account or server is needed on-device. */ +public final class UpdateManager { + public static final String CHANNEL_DEV = "dev"; + public static final String CHANNEL_STABLE = "stable"; + public static final String PREF_CHANNEL = "update_channel"; + public static final String PREF_NOTIFY = "notify_on_updates"; + public static final String PREF_NOTIFIED_CODE = "update_notified_code"; + public static final String PREF_LAST_CHECK = "update_last_check"; + public static final String API_URL = "https://git.molberg.cloud/api/v1/repos/alex/mg-utility/releases?limit=50"; + public static final String RELEASE_HOST = "git.molberg.cloud"; + public static final String APK_AUTHORITY = "cloud.molberg.mgutility.updates"; + public static final int NOTIFICATION_ID = 7314; + private static final String NOTIFICATION_CHANNEL = "software_updates"; + private static final int CONNECT_TIMEOUT_MS = 12000; + private static final int READ_TIMEOUT_MS = 30000; + + private UpdateManager() { } + + public interface Callback { + void onResult(List releases, Exception error); + } + + public interface Progress { + void onProgress(long downloaded, long total); + } + + public static final class Release { + public final String channel, versionName, branch, tag, notes, apkUrl, sha256; + public final int versionCode; + public final long size; + + Release(String channel, String versionName, int versionCode, String branch, String tag, + String notes, String apkUrl, String sha256, long size) { + this.channel = channel; this.versionName = versionName; this.versionCode = versionCode; + this.branch = branch; this.tag = tag; this.notes = notes; this.apkUrl = apkUrl; + this.sha256 = sha256; this.size = size; + } + + public String label() { return versionName + " • " + channel + " • " + branch; } + } + + public static String selectedChannel(Context context) { + String value = prefs(context).getString(PREF_CHANNEL, CHANNEL_DEV); + return CHANNEL_STABLE.equals(value) ? CHANNEL_STABLE : CHANNEL_DEV; + } + + public static boolean notifyEnabled(Context context) { + return prefs(context).getBoolean(PREF_NOTIFY, true); + } + + public static void setChannel(Context context, String channel) { + prefs(context).edit().putString(PREF_CHANNEL, + CHANNEL_STABLE.equals(channel) ? CHANNEL_STABLE : CHANNEL_DEV).apply(); + } + + public static void setNotifyEnabled(Context context, boolean enabled) { + prefs(context).edit().putBoolean(PREF_NOTIFY, enabled).apply(); + if (enabled) UpdateScheduler.schedule(context); else UpdateScheduler.cancel(context); + } + + public static String installedVersion(Context context) { + try { + PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + return info.versionName == null ? String.valueOf(info.versionCode) : info.versionName; + } catch (Exception e) { return "unknown"; } + } + + public static int installedVersionCode(Context context) { + try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; } + catch (Exception e) { return 0; } + } + + /** Reads build channel/branch embedded by build.sh, with a safe fallback for old APKs. */ + public static String installedChannel(Context context) { + String version = installedVersion(context); + boolean semanticDev = version.matches("[0-9]+\\\\.[0-9]+\\\\.[0-9]+\\\\.[0-9]+"); + return buildValue(context, "channel", semanticDev ? CHANNEL_DEV : CHANNEL_STABLE); + } + + public static String installedBranch(Context context) { + return buildValue(context, "branch", CHANNEL_DEV.equals(installedChannel(context)) ? "main" : "release"); + } + + private static String buildValue(Context context, String key, String fallback) { + try { + JSONObject json = new JSONObject(readAsset(context, "mg-update-build.json")); + String value = json.optString(key, fallback); + return value.length() == 0 ? fallback : value; + } catch (Exception ignored) { return fallback; } + } + + private static String readAsset(Context context, String name) throws Exception { + InputStream in = context.getAssets().open(name); + StringBuilder out = new StringBuilder(); byte[] buf = new byte[2048]; int n; + while ((n = in.read(buf)) >= 0) out.append(new String(buf, 0, n, "UTF-8")); + in.close(); return out.toString(); + } + + private static android.content.SharedPreferences prefs(Context context) { + return ConfigStore.of(context).sharedPreferences(); + } + + public static void checkAsync(final Context context, final Callback callback) { + new Thread(new Runnable() { + @Override public void run() { + List result = Collections.emptyList(); Exception error = null; + try { result = findReleases(context, selectedChannel(context)); } + catch (Exception e) { error = e; } + final List found = result; final Exception failure = error; + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override public void run() { if (callback != null) callback.onResult(found, failure); } + }); + } + }, "mg-update-check").start(); + } + + public static Release findUpdate(Context context, String channel) throws Exception { + int current = installedVersionCode(context); + List releases = findReleases(context, channel); + for (Release release : releases) if (release.versionCode > current) return release; + return null; + } + + /** Returns release history for a channel, newest first. Dev also sees stable releases as .0 variants. */ + public static List findReleases(Context context, String channel) throws Exception { + JSONArray releases = new JSONArray(getText(API_URL)); + List result = new ArrayList<>(); + for (int i = 0; i < releases.length(); i++) { + JSONObject raw = releases.optJSONObject(i); if (raw == null) continue; + JSONObject meta = parseMetadata(raw); if (meta == null) continue; + String releaseChannel = meta.optString("channel"); + boolean stableAsDev = CHANNEL_DEV.equals(channel) && CHANNEL_STABLE.equals(releaseChannel); + if (!channel.equals(releaseChannel) && !stableAsDev) continue; + JSONArray assets = raw.optJSONArray("assets"); JSONObject apk = null; + for (int j = 0; assets != null && j < assets.length(); j++) { + JSONObject asset = assets.optJSONObject(j); + String name = asset == null ? "" : asset.optString("name", ""); + if (name.toLowerCase(Locale.US).endsWith(".apk")) { apk = asset; break; } + } + if (apk == null) continue; + String url = apk.optString("browser_download_url", apk.optString("download_url", "")); + if (!isTrustedUrl(url)) continue; + String versionName = meta.optString("versionName", raw.optString("name", "")); + if (stableAsDev && versionName.matches("[0-9]+\\\\.[0-9]+\\\\.[0-9]+")) versionName += ".0"; + result.add(new Release(channel, versionName, meta.optInt("versionCode", 0), + meta.optString("branch", "main"), raw.optString("tag_name", ""), raw.optString("body", ""), + url, meta.optString("sha256", ""), apk.optLong("size", 0L))); + } + Collections.sort(result, new Comparator() { + @Override public int compare(Release left, Release right) { return right.versionCode - left.versionCode; } + }); + prefs(context).edit().putLong(PREF_LAST_CHECK, System.currentTimeMillis()).apply(); + return result; + } + + private static JSONObject parseMetadata(JSONObject release) { + try { + String body = release.optString("body", "").trim(); + if (body.length() == 0) return null; + JSONObject meta = new JSONObject(body); + return meta.optInt("schema", 0) == 1 ? meta : null; + } catch (Exception ignored) { return null; } + } + + private static boolean isTrustedUrl(String value) { + try { URL url = new URL(value); return "https".equalsIgnoreCase(url.getProtocol()) && RELEASE_HOST.equalsIgnoreCase(url.getHost()); } + catch (Exception e) { return false; } + } + + private static String getText(String address) throws Exception { + HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection(); + connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); + connection.setRequestProperty("Accept", "application/json"); + if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300) throw new java.io.IOException("Gitea HTTP " + connection.getResponseCode()); + InputStream in = connection.getInputStream(); StringBuilder out = new StringBuilder(); byte[] buf = new byte[8192]; int n; + while ((n = in.read(buf)) >= 0) out.append(new String(buf, 0, n, "UTF-8")); in.close(); connection.disconnect(); return out.toString(); + } + + public static File download(Context context, Release release, Progress progress) throws Exception { + if (release == null || release.sha256.length() < 32) throw new java.io.IOException("Release has no checksum"); + File directory = new File(context.getFilesDir(), "updates"); if (!directory.exists() && !directory.mkdirs()) throw new java.io.IOException("Cannot create update directory"); + File partial = new File(directory, "mg-utility-" + release.versionCode + ".apk.part"); + File apk = new File(directory, "mg-utility-" + release.versionCode + ".apk"); + HttpURLConnection connection = (HttpURLConnection) new URL(release.apkUrl).openConnection(); + connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); connection.setInstanceFollowRedirects(false); + int status = connection.getResponseCode(); + if (status >= 300 && status < 400) { String location = connection.getHeaderField("Location"); if (!isTrustedUrl(location)) throw new java.io.IOException("Untrusted download redirect"); connection.disconnect(); connection = (HttpURLConnection) new URL(location).openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); status = connection.getResponseCode(); } + if (status < 200 || status >= 300) throw new java.io.IOException("APK HTTP " + status); + long total = connection.getContentLengthLong(); InputStream in = connection.getInputStream(); OutputStream out = new FileOutputStream(partial, false); byte[] buffer = new byte[32768]; long count = 0; int n; + while ((n = in.read(buffer)) >= 0) { out.write(buffer, 0, n); count += n; if (progress != null) progress.onProgress(count, total); } + out.close(); in.close(); connection.disconnect(); + if (!apkChecksum(partial).equalsIgnoreCase(release.sha256)) { partial.delete(); throw new java.io.IOException("APK checksum mismatch"); } + verifyPackage(context, partial, release); if (apk.exists()) apk.delete(); if (!partial.renameTo(apk)) throw new java.io.IOException("Cannot store downloaded APK"); return apk; + } + + private static String apkChecksum(File file) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); InputStream in = new FileInputStream(file); byte[] buffer = new byte[32768]; int n; + while ((n = in.read(buffer)) >= 0) digest.update(buffer, 0, n); in.close(); StringBuilder hex = new StringBuilder(); for (byte b : digest.digest()) hex.append(String.format(Locale.US, "%02x", b)); return hex.toString(); + } + + private static void verifyPackage(Context context, File file, Release release) throws Exception { + PackageManager pm = context.getPackageManager(); PackageInfo candidate = pm.getPackageArchiveInfo(file.getAbsolutePath(), PackageManager.GET_SIGNATURES); + if (candidate == null || !context.getPackageName().equals(candidate.packageName) || candidate.versionCode != release.versionCode) throw new java.io.IOException("APK identity/version mismatch"); + PackageInfo installed = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); + if (installed.signatures == null || candidate.signatures == null || installed.signatures.length == 0 || candidate.signatures.length == 0 || !installed.signatures[0].equals(candidate.signatures[0])) throw new java.io.IOException("APK signing certificate mismatch"); + } + + public static File downloadedFile(Context context, int versionCode) { return new File(new File(context.getFilesDir(), "updates"), "mg-utility-" + versionCode + ".apk"); } + + public static void install(Context context, File file) { + if (file == null || !file.exists()) return; + if (Build.VERSION.SDK_INT >= 26 && !context.getPackageManager().canRequestPackageInstalls()) { + Intent permission = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName())); permission.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(permission); return; + } + Uri uri = Uri.parse("content://" + APK_AUTHORITY + "/apk"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.setDataAndType(uri, "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); + } + + public static void checkAndNotify(Context context) { + if (!notifyEnabled(context)) return; + try { Release release = findUpdate(context, selectedChannel(context)); if (release != null && prefs(context).getInt(PREF_NOTIFIED_CODE, 0) < release.versionCode) { prefs(context).edit().putInt(PREF_NOTIFIED_CODE, release.versionCode).apply(); showNotification(context, release); } } + catch (Exception ignored) { } + } + + private static void showNotification(Context context, Release release) { + NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + if (Build.VERSION.SDK_INT >= 26) manager.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL, "Software updates", NotificationManager.IMPORTANCE_HIGH)); + Intent open = new Intent(context, UpdateActivity.class); open.putExtra(UpdateActivity.EXTRA_VERSION_CODE, release.versionCode); int flags = PendingIntent.FLAG_UPDATE_CURRENT; if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE; + PendingIntent pending = PendingIntent.getActivity(context, NOTIFICATION_ID, open, flags); Notification.Builder builder = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(context, NOTIFICATION_CHANNEL) : new Notification.Builder(context); + builder.setSmallIcon(android.R.drawable.stat_sys_download_done).setContentTitle("MG Utility update available").setContentText(release.versionName + " on " + release.channel + " channel").setContentIntent(pending).setAutoCancel(true).setTimeoutAfter(12000L); manager.notify(NOTIFICATION_ID, builder.build()); + } +} diff --git a/src/cloud/molberg/mgutility/UpdateScheduler.java b/src/cloud/molberg/mgutility/UpdateScheduler.java new file mode 100644 index 0000000..238e1b3 --- /dev/null +++ b/src/cloud/molberg/mgutility/UpdateScheduler.java @@ -0,0 +1,39 @@ +package cloud.molberg.mgutility; + +import android.app.job.JobInfo; +import android.app.job.JobParameters; +import android.app.job.JobScheduler; +import android.app.job.JobService; +import android.content.ComponentName; +import android.content.Context; +import android.net.NetworkCapabilities; +import android.os.Build; + +/** Persistent, network-aware periodic updater. */ +public final class UpdateScheduler { + private static final int JOB_ID = 7315; + private static final long PERIOD_MS = 6L * 60L * 60L * 1000L; + private UpdateScheduler() { } + + public static void schedule(Context context) { + if (Build.VERSION.SDK_INT < 24 || !UpdateManager.notifyEnabled(context)) return; + JobScheduler jobs = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(context, UpdateJobService.class)) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setPeriodic(PERIOD_MS); + if (Build.VERSION.SDK_INT >= 24) builder.setPersisted(true); + jobs.schedule(builder.build()); + } + + public static void cancel(Context context) { + if (Build.VERSION.SDK_INT < 21) return; + JobScheduler jobs = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); if (jobs != null) jobs.cancel(JOB_ID); + } + + public static final class UpdateJobService extends JobService { + @Override public boolean onStartJob(final JobParameters params) { + new Thread(new Runnable() { @Override public void run() { UpdateManager.checkAndNotify(UpdateJobService.this); jobFinished(params, false); } }, "mg-update-job").start(); + return true; + } + @Override public boolean onStopJob(JobParameters params) { return true; } + } +} diff --git a/src/cloud/molberg/mgutility/VehicleDataProvider.java b/src/cloud/molberg/mgutility/VehicleDataProvider.java index 49dbc9a..113efb9 100644 --- a/src/cloud/molberg/mgutility/VehicleDataProvider.java +++ b/src/cloud/molberg/mgutility/VehicleDataProvider.java @@ -69,6 +69,17 @@ public class VehicleDataProvider extends ContentProvider { result.putString("status", "permission_denied"); return result; } + if ("capabilities".equals(method)) { + EnergyActivity.VehicleGateway gateway = vehicle; + if (gateway == null) { + bindVehicleService(); + result.putString("status", binding ? "connecting" : "service_unavailable"); + return result; + } + result.putString("status", "connected"); + result.putAll(gateway.capabilities()); + return result; + } if (!"sample".equals(method)) { result.putString("status", "unsupported_method"); return result; diff --git a/src/cloud/molberg/mgutility/VehicleDiagnosticsCollector.java b/src/cloud/molberg/mgutility/VehicleDiagnosticsCollector.java new file mode 100644 index 0000000..1e0c3c4 --- /dev/null +++ b/src/cloud/molberg/mgutility/VehicleDiagnosticsCollector.java @@ -0,0 +1,186 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; + +/** Builds a privacy-conscious, read-only compatibility snapshot for an explicit upload. */ +public final class VehicleDiagnosticsCollector { + private static final String VEHICLE_PROVIDER = "content://" + VehicleDataProvider.AUTHORITY; + + private VehicleDiagnosticsCollector() { } + + public static JSONObject collect(Context context) { + JSONObject snapshot = new JSONObject(); + try { + snapshot.put("schema", 1); + snapshot.put("collectionMode", "user_initiated"); + snapshot.put("vehicleId", DiagnosticsClient.getVehicleId(context)); + snapshot.put("vehicleIdScope", "random_app_install_id"); + snapshot.put("vehicleIdNote", "Random ID stored in app-private storage; not VIN, serial, or hardware-derived."); + snapshot.put("appProfile", VehicleSettingsProfile.MG4_LUXURY_2022); + + JSONObject device = new JSONObject(); + device.put("manufacturer", Build.MANUFACTURER); + device.put("brand", Build.BRAND); + device.put("model", Build.MODEL); + device.put("device", Build.DEVICE); + device.put("product", Build.PRODUCT); + device.put("board", Build.BOARD); + device.put("hardware", Build.HARDWARE); + device.put("androidRelease", Build.VERSION.RELEASE); + device.put("androidApi", Build.VERSION.SDK_INT); + device.put("buildDisplay", Build.DISPLAY); + device.put("buildType", Build.TYPE); + device.put("supportedAbis", new JSONArray(Build.SUPPORTED_ABIS)); + snapshot.put("headUnit", device); + + JSONObject app = new JSONObject(); + app.put("package", context.getPackageName()); + try { + app.put("version", context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName); + } catch (Exception ignored) { app.put("version", "unknown"); } + snapshot.put("app", app); + snapshot.put("vehicleService", collectVehicleService(context)); + snapshot.put("vehicleServiceOperations", collectVehicleServiceOperations()); + snapshot.put("systemSettingsServices", collectSystemSettingsServices(context)); + snapshot.put("vehicleSettingsCatalog", collectVehicleSettingsCatalog()); + snapshot.put("appControlCatalog", collectAppControlCatalog()); + } catch (Exception error) { + try { snapshot.put("collectorError", error.getClass().getSimpleName()); } catch (Exception ignored) { } + } + return snapshot; + } + + private static JSONObject collectVehicleService(Context context) { + JSONObject result = new JSONObject(); + try { + Bundle bundle = context.getContentResolver().call(Uri.parse(VEHICLE_PROVIDER), "capabilities", null, null); + if (bundle == null) { + result.put("status", "no_response"); + return result; + } + result.put("status", bundle.getString("status", "unknown")); + for (String key : bundle.keySet()) { + if (!"status".equals(key)) result.put(key, bundle.get(key)); + } + } catch (Exception error) { + try { result.put("status", "probe_failed"); result.put("errorType", error.getClass().getSimpleName()); } + catch (Exception ignored) { } + } + try { + result.put("serviceComponent", "com.saicmotor.service.vehicle.VehicleService"); + result.put("probeMode", "read_only_availability_flags; values_not_uploaded"); + } catch (Exception ignored) { } + return result; + } + + private static JSONObject collectSystemSettingsServices(Context context) { + JSONObject result = new JSONObject(); + MgServiceBridge bridge = MgServiceBridge.get(); + try { bridge.ensureBound(context.getApplicationContext()); } catch (Exception ignored) { } + boolean general = bridge.hasBrightnessService(); + boolean sound = bridge.hasSoundService(); + boolean wifi = bridge.hasWifiService(); + boolean bluetooth = bridge.hasBluetoothService(); + try { + result.put("servicePackage", "com.saicmotor.service.systemsettings"); + result.put("generalServiceBound", general); + result.put("smartSoundServiceBound", sound); + result.put("wifiServiceBound", wifi); + result.put("bluetoothServiceBound", bluetooth); + result.put("bindingAttempted", bridge.hasAttemptedBind()); + + JSONObject probes = new JSONObject(); + probes.put("getBrightness", general && bridge.getBrightness() >= 0); + probes.put("getMediaVolume", sound && bridge.getVolume(MgServiceBridge.VOL_TYPE_MEDIA) >= 0); + probes.put("getPhoneVolume", sound && bridge.getVolume(MgServiceBridge.VOL_TYPE_PHONE) >= 0); + probes.put("getVoiceVolume", sound && bridge.getVolume(MgServiceBridge.VOL_TYPE_VOICE) >= 0); + probes.put("getRingtoneVolume", sound && bridge.getVolume(MgServiceBridge.VOL_TYPE_RINGTONE) >= 0); + probes.put("getNavigationVolume", sound && bridge.getVolume(MgServiceBridge.VOL_TYPE_NAVIGATION) >= 0); + probes.put("getSoundFieldBalance", sound && bridge.getSoundFieldBalance() != Integer.MIN_VALUE); + probes.put("getSoundFieldFader", sound && bridge.getSoundFieldFader() != Integer.MIN_VALUE); + probes.put("getWifiEnabled", wifi && bridge.isWifiEnabled() != null); + probes.put("getBluetoothEnabled", bluetooth && bridge.isBluetoothEnabled() != null); + result.put("readOnlyFunctionProbes", probes); + JSONArray implementedWrites = new JSONArray(); + if (general) implementedWrites.put("setBrightness"); + if (sound) { implementedWrites.put("setVolume"); implementedWrites.put("setSoundField"); } + if (wifi) implementedWrites.put("setWifiEnabled"); + if (bluetooth) implementedWrites.put("setBluetoothEnabled"); + result.put("writeOperationsImplementedByApp", implementedWrites); + result.put("writeOperationsInvoked", false); + } catch (Exception error) { + try { result.put("probeError", error.getClass().getSimpleName()); } catch (Exception ignored) { } + } + return result; + } + + private static JSONObject collectVehicleServiceOperations() { + JSONObject result = new JSONObject(); + try { + result.put("source", "EnergyActivity.VehicleGateway + VehicleSettingsCatalog"); + result.put("readFunctions", stringArray( + "read", "readSpeed", "getDriveMode", "getRegenerativeLevel", + "getChargingStatus", "getDischargingStatus", "getActualChargingCurrent", + "getPredictChargingTime", "getPredictDischargingTime", "getChargingControlSwitch", + "getChargingCloseSoc", "getChargingCurrent", "getReserveChargingControl", + "getReserveStartHour", "getReserveStartMinute", "getReserveStopHour", "getReserveStopMinute")); + result.put("writeFunctionsImplementedByApp", stringArray( + "setDriveMode", "setRegenerativeLevel", "setChargingControlSwitch", + "setChargingCloseSoc", "setChargingCurrent", "setReserveChargingControl", + "setReserveStart", "setReserveStop")); + result.put("writeFunctionsInvokedDuringCollection", false); + result.put("scopeNote", "App-wired function list only; not a full OEM AIDL inventory."); + } catch (Exception ignored) { } + return result; + } + + private static JSONArray stringArray(String... values) { + JSONArray result = new JSONArray(); + for (String value : values) result.put(value); + return result; + } + + private static JSONArray collectVehicleSettingsCatalog() { + JSONArray result = new JSONArray(); + for (VehicleSettingsCatalog.Definition definition : VehicleSettingsCatalog.all()) { + JSONObject item = new JSONObject(); + try { + item.put("id", definition.id); + item.put("label", definition.label); + item.put("category", definition.category); + item.put("service", definition.service.name()); + item.put("risk", definition.risk.name()); + item.put("policy", definition.initialPolicy.name()); + item.put("startupApplyEnabled", definition.startupWritable); + item.put("requiresPark", definition.requiresPark); + item.put("experimental", definition.experimental); + JSONArray values = new JSONArray(); + for (VehicleSettingsCatalog.Value value : definition.values()) values.put(value.label); + item.put("knownValues", values); + result.put(item); + } catch (Exception ignored) { } + } + return result; + } + + private static JSONArray collectAppControlCatalog() { + JSONArray result = new JSONArray(); + for (ControlPanelCatalog.Control control : ControlPanelCatalog.all()) { + JSONObject item = new JSONObject(); + try { + item.put("id", control.id); + item.put("label", control.label); + item.put("kind", control.kind.name()); + item.put("category", control.category); + result.put(item); + } catch (Exception ignored) { } + } + return result; + } +} diff --git a/src/cloud/molberg/mgutility/VehiclePowerOffController.java b/src/cloud/molberg/mgutility/VehiclePowerOffController.java new file mode 100644 index 0000000..633d083 --- /dev/null +++ b/src/cloud/molberg/mgutility/VehiclePowerOffController.java @@ -0,0 +1,48 @@ +package cloud.molberg.mgutility; + +final class VehiclePowerOffController { + static final String SUPPORTED_SERVICE_VERSION = "VehicleSettingsService.44041"; + + interface Transport { + boolean isCompatible(); + int getGear(); + float getSpeed(); + boolean sendPowerOff(); + } + + enum Result { + CANCELLED("Power off cancelled."), + UNSUPPORTED("Power off is unavailable: the connected vehicle service is not the supported MG4 version."), + NOT_PARKED("Power off blocked: select P (Park). Unknown gear also blocks power off."), + NOT_STATIONARY("Power off blocked: the car must be stationary with a valid zero-speed reading."), + ALREADY_REQUESTED("A power-off request was already attempted. No repeat request was sent."), + REQUEST_SENT("Power-off request sent to the OEM service. Vehicle shutdown is not confirmed."), + FAILED("Unable to confirm delivery of the power-off request. No automatic retry; check the car and use OEM controls."); + + final String message; + Result(String message) { this.message = message; } + } + + private final Transport transport; + private boolean attempted; + + VehiclePowerOffController(Transport transport) { + this.transport = transport; + } + + synchronized Result request(boolean confirmed) { + if (!confirmed) return Result.CANCELLED; + if (attempted) return Result.ALREADY_REQUESTED; + try { + if (transport == null || !transport.isCompatible()) return Result.UNSUPPORTED; + if (transport.getGear() != 1) return Result.NOT_PARKED; + float speed = transport.getSpeed(); + if (Float.isNaN(speed) || Float.isInfinite(speed) || speed != 0f) return Result.NOT_STATIONARY; + if (transport.getGear() != 1) return Result.NOT_PARKED; + attempted = true; + return transport.sendPowerOff() ? Result.REQUEST_SENT : Result.FAILED; + } catch (Exception ignored) { + return Result.FAILED; + } + } +} diff --git a/src/cloud/molberg/mgutility/VehicleSettingsActivity.java b/src/cloud/molberg/mgutility/VehicleSettingsActivity.java index c9126c6..9185b89 100644 --- a/src/cloud/molberg/mgutility/VehicleSettingsActivity.java +++ b/src/cloud/molberg/mgutility/VehicleSettingsActivity.java @@ -27,9 +27,14 @@ public final class VehicleSettingsActivity extends AnimatedActivity { private VehicleSettingsApplyCoordinator coordinator; private VehicleSettingsProfile profile = VehicleSettingsProfile.unknown(); private boolean bound; + private VehiclePowerOffController powerOffController; + private AlertDialog powerOffDialog; + private boolean powerOffInFlight; + private String powerOffStatus = "Manual vehicle shutdown only. Select P and stop completely before continuing."; private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { gateway = new VehicleSettingsGateway(service); + powerOffController = gateway.powerOffController(serviceVersion()); // This screen targets the captured MG4 profile. A future build matcher can // replace the package marker without changing the catalog or UI. profile = VehicleSettingsProfile.match( @@ -38,7 +43,11 @@ public final class VehicleSettingsActivity extends AnimatedActivity { coordinator = new VehicleSettingsApplyCoordinator(repository, gateway, profile); render(); } - @Override public void onServiceDisconnected(ComponentName name) { gateway = null; coordinator = null; profile = VehicleSettingsProfile.unknown(); render(); } + @Override public void onServiceDisconnected(ComponentName name) { + gateway = null; coordinator = null; powerOffController = null; + dismissPowerOffDialog(); + profile = VehicleSettingsProfile.unknown(); render(); + } }; @Override public void onCreate(Bundle state) { @@ -49,18 +58,37 @@ public final class VehicleSettingsActivity extends AnimatedActivity { repository = new VehicleSettingsRepository(this); setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); - bound = bindService(new Intent("com.saicmotor.service.vehicle.VehicleService") - .setPackage("com.saicmotor.service.vehicle"), connection, Context.BIND_AUTO_CREATE); + try { + bound = bindService(new Intent("com.saicmotor.service.vehicle.VehicleService") + .setPackage("com.saicmotor.service.vehicle"), connection, Context.BIND_AUTO_CREATE); + } catch (SecurityException ignored) { bound = false; } + if (!bound) powerOffStatus = "Vehicle service unavailable. Use the OEM vehicle power controls."; + render(); } @Override protected void onDestroy() { + dismissPowerOffDialog(); if (bound) try { unbindService(connection); } catch (Exception ignored) { } super.onDestroy(); } + @Override protected void onPause() { + dismissPowerOffDialog(); + super.onPause(); + } + + private void dismissPowerOffDialog() { + if (powerOffDialog != null) { + powerOffDialog.dismiss(); + powerOffDialog = null; + } + } + @Override protected void onResume() { super.onResume(); UiTheme.refreshTheme(this); - if (UiTheme.version() != renderedThemeVersion) { setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); } + if (UiTheme.version() != renderedThemeVersion) { + setContentView(buildUi()); renderedThemeVersion = UiTheme.version(); render(); + } } private View buildUi() { @@ -97,6 +125,18 @@ public final class VehicleSettingsActivity extends AnimatedActivity { "CONNECTED • values are read-only until the firmware profile is identified", 13, gateway == null ? UiTheme.MUTED : UiTheme.SUCCESS, Typeface.NORMAL); status.setPadding(12, 8, 12, 12); content.addView(status); + TextView powerHeading = UiTheme.label(this, "VEHICLE POWER"); + powerHeading.setPadding(10, 10, 0, 5); + content.addView(powerHeading, new LinearLayout.LayoutParams(-1, 34)); + TextView powerHint = UiTheme.text(this, powerOffStatus, 13, UiTheme.MUTED, Typeface.NORMAL); + powerHint.setPadding(12, 8, 12, 12); content.addView(powerHint); + Button powerOff = UiTheme.button(this, powerOffInFlight ? "REQUESTING POWER OFF…" : "TURN OFF CAR", + new View.OnClickListener() { + @Override public void onClick(View view) { confirmPowerOff(); } + }, false); + powerOff.setTextColor(UiTheme.WARNING); + powerOff.setEnabled(powerOffController != null && !powerOffInFlight); + content.addView(powerOff, new LinearLayout.LayoutParams(260, 56)); String[] categories = { "Drive and energy", "Driving assistance", "Convenience", "HVAC and non-ambient lighting", "Manual and trim-dependent", "Safety controls" }; for (String category : categories) { java.util.List definitions = VehicleSettingsCatalog.byCategory(category); @@ -107,6 +147,40 @@ public final class VehicleSettingsActivity extends AnimatedActivity { } } + private void confirmPowerOff() { + if (powerOffController == null || powerOffInFlight || powerOffDialog != null) return; + final VehiclePowerOffController confirmedController = powerOffController; + powerOffDialog = UiTheme.dialog(this).setTitle("TURN OFF CAR?") + .setMessage("This requests vehicle power off using the same command as the OEM Vehicle Power button. " + + "Park safely, select P, and stop completely. Vehicle systems may become unavailable. " + + "MG Utility will check Park and zero speed again before sending the request. Continue?") + .setNegativeButton("CANCEL", null) + .setPositiveButton("TURN OFF CAR", new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + if (confirmedController != powerOffController || powerOffInFlight || isFinishing()) return; + powerOffInFlight = true; + powerOffStatus = "Checking vehicle state and requesting power off…"; + render(); + new Thread(new Runnable() { + @Override public void run() { + final VehiclePowerOffController.Result result = confirmedController.request(true); + runOnUiThread(new Runnable() { + @Override public void run() { + powerOffInFlight = false; + powerOffStatus = result.message; + if (!isFinishing() && !isDestroyed()) render(); + } + }); + } + }, "vehicle-power-off").start(); + } + }).create(); + powerOffDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override public void onDismiss(DialogInterface dialog) { powerOffDialog = null; } + }); + powerOffDialog.show(); + } + private void addRow(final VehicleSettingsCatalog.Definition definition) { final Integer desired = repository.desiredValue(definition.id); int observed = gateway == null ? -1 : gateway.get(definition); diff --git a/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java b/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java index 9f66608..9cf28f9 100644 --- a/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java +++ b/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java @@ -84,7 +84,7 @@ public final class VehicleSettingsApplyCoordinator { String token = plan.profileId + ":" + plan.revision + ":" + ignitionSession; if (token.equals(appliedSession)) return Collections.emptyList(); if (!profile.isKnown() || !profile.allowsWrites() || !gateway.available()) return Collections.emptyList(); - if (!parked()) return rejectedPlan(plan, "ignition/park/speed condition is not safe"); + if (!ignitionReady()) return rejectedPlan(plan, "ignition is not ready"); appliedSession = token; ArrayList results = new ArrayList(); for (PlanEntry entry : plan.entries) results.add(apply(entry)); @@ -103,7 +103,7 @@ public final class VehicleSettingsApplyCoordinator { if (plan.entries.isEmpty()) return Collections.emptyList(); if (!profile.isKnown() || !profile.allowsWrites() || !gateway.available()) return rejectedPlan(plan, "vehicle settings service/profile is not ready"); - if (!parked()) return rejectedPlan(plan, "ignition/park/speed condition is not safe"); + if (!ignitionReady()) return rejectedPlan(plan, "ignition is not ready"); ArrayList results = new ArrayList(); for (PlanEntry entry : plan.entries) results.add(apply(entry)); return results; @@ -163,6 +163,11 @@ public final class VehicleSettingsApplyCoordinator { return new Result(entry.definition.id, status, entry.value, readBack, status == Status.VERIFIED ? "read-back matched" : "queued without matching read-back"); } + private boolean ignitionReady() { + int ignition = gateway.getIgnition(); + return ignition == 1 || ignition == 2 || ignition == 3; + } + private boolean parked() { int ignition = gateway.getIgnition(); int gear = gateway.getGear(); diff --git a/src/cloud/molberg/mgutility/VehicleSettingsGateway.java b/src/cloud/molberg/mgutility/VehicleSettingsGateway.java index 9c946dc..9e3547e 100644 --- a/src/cloud/molberg/mgutility/VehicleSettingsGateway.java +++ b/src/cloud/molberg/mgutility/VehicleSettingsGateway.java @@ -74,6 +74,22 @@ public class VehicleSettingsGateway implements VehicleSettingsApplyCoordinator.C } public boolean available() { return setting != null; } + VehiclePowerOffController powerOffController(final String serviceVersion) { + return new VehiclePowerOffController(new VehiclePowerOffController.Transport() { + @Override public boolean isCompatible() { + try { + return VehiclePowerOffController.SUPPORTED_SERVICE_VERSION.equals(serviceVersion) + && setting != null && condition != null + && SETTING_TOKEN.equals(setting.getInterfaceDescriptor()) + && CONDITION_TOKEN.equals(condition.getInterfaceDescriptor()); + } catch (Exception ignored) { return false; } + } + @Override public int getGear() { return VehicleSettingsGateway.this.getGear(); } + @Override public float getSpeed() { return VehicleSettingsGateway.this.getSpeed(); } + @Override public boolean sendPowerOff() { return writeInt(setting, SETTING_TOKEN, 0xad, 2); } + }); + } + private int readInt(IBinder binder, String token, int transaction) { if (binder == null) return -1; Parcel data = Parcel.obtain(), reply = Parcel.obtain(); diff --git a/src/cloud/molberg/mgutility/plugin/AndroidPluginContext.java b/src/cloud/molberg/mgutility/plugin/AndroidPluginContext.java new file mode 100644 index 0000000..45e7a18 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/AndroidPluginContext.java @@ -0,0 +1,38 @@ +package cloud.molberg.mgutility.plugin; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; +import cloud.molberg.mgutility.sdk.ContributionRegistry; +import cloud.molberg.mgutility.sdk.HookRegistry; +import cloud.molberg.mgutility.sdk.InMemoryContributionRegistry; +import cloud.molberg.mgutility.sdk.InMemoryHookRegistry; +import cloud.molberg.mgutility.sdk.PluginContext; +import cloud.molberg.mgutility.sdk.PluginLogger; +import cloud.molberg.mgutility.sdk.PluginCapability; +import cloud.molberg.mgutility.sdk.ScopedPreferences; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; + +/** Default Android-backed context supplied to loaded plugins by the host. */ +public final class AndroidPluginContext implements PluginContext { + private final Context app; private final String id, name, version, sdk; + private final ContributionRegistry contributions = new InMemoryContributionRegistry(); + private final HookRegistry hooks; + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private Set capabilities; + public AndroidPluginContext(Context context, String id, String name, String version, String sdk) { this(context,id,name,version,sdk, Collections.emptySet(), PluginHostEvents.bus()); } + public AndroidPluginContext(Context context, String id, String name, String version, String sdk, Set granted) { this(context,id,name,version,sdk,granted,PluginHostEvents.bus()); } + public AndroidPluginContext(Context context, String id, String name, String version, String sdk, Set granted, HookRegistry eventBus) { app=context.getApplicationContext(); this.id=id; this.name=name; this.version=version; this.sdk=sdk; hooks=eventBus==null?PluginHostEvents.bus():eventBus; EnumSet set=EnumSet.noneOf(PluginCapability.class); if(granted!=null)set.addAll(granted); capabilities=Collections.unmodifiableSet(set); } + public String pluginId(){return id;} public String displayName(){return name;} public String pluginVersion(){return version;} public String sdkVersion(){return sdk;} + public Set capabilities(){return capabilities;} public boolean hasCapability(PluginCapability capability){return capability!=null&&capabilities.contains(capability);} + public ScopedPreferences preferences(){return new Preferences(app.getSharedPreferences("plugin_"+id, Context.MODE_PRIVATE));} + public PluginLogger logger(){return new PluginLogger(){public void debug(String m){Log.d("MGPlugin/"+id,m);}public void info(String m){Log.i("MGPlugin/"+id,m);}public void warn(String m){Log.w("MGPlugin/"+id,m);}public void error(String m,Throwable t){Log.e("MGPlugin/"+id,m,t);}};} + public ContributionRegistry contributions(){return contributions;} public HookRegistry hooks(){return hooks;} + public void runAsync(Runnable work){if(work!=null)executor.submit(work);} public String assetUri(String path){return "asset://"+id+"/"+(path==null?"":path.replace("..",""));} + public void shutdown(){executor.shutdownNow();} + private static final class Preferences implements ScopedPreferences { private final SharedPreferences p; Preferences(SharedPreferences p){this.p=p;} public String getString(String k,String f){return p.getString(k,f);}public boolean getBoolean(String k,boolean f){return p.getBoolean(k,f);}public int getInt(String k,int f){return p.getInt(k,f);}public long getLong(String k,long f){return p.getLong(k,f);}public float getFloat(String k,float f){return p.getFloat(k,f);}public boolean contains(String k){return p.contains(k);}public void putString(String k,String v){p.edit().putString(k,v).apply();}public void putBoolean(String k,boolean v){p.edit().putBoolean(k,v).apply();}public void putInt(String k,int v){p.edit().putInt(k,v).apply();}public void putLong(String k,long v){p.edit().putLong(k,v).apply();}public void putFloat(String k,float v){p.edit().putFloat(k,v).apply();}public void remove(String k){p.edit().remove(k).apply();}public void clear(){p.edit().clear().apply();}} +} diff --git a/src/cloud/molberg/mgutility/plugin/InstalledPlugin.java b/src/cloud/molberg/mgutility/plugin/InstalledPlugin.java new file mode 100644 index 0000000..b82aa5f --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/InstalledPlugin.java @@ -0,0 +1,12 @@ +package cloud.molberg.mgutility.plugin; + +import cloud.molberg.mgutility.sdk.PluginManifest; +import android.content.Context; + +/** An installed plugin package and its parsed manifest. */ +public final class InstalledPlugin { + public final String packageName; + public final PluginManifest manifest; + public final Context packageContext; + public InstalledPlugin(String packageName, PluginManifest manifest, Context packageContext) { this.packageName=packageName; this.manifest=manifest; this.packageContext=packageContext; } +} diff --git a/src/cloud/molberg/mgutility/plugin/InstalledPluginScanner.java b/src/cloud/molberg/mgutility/plugin/InstalledPluginScanner.java new file mode 100644 index 0000000..a02be11 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/InstalledPluginScanner.java @@ -0,0 +1,30 @@ +package cloud.molberg.mgutility.plugin; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import cloud.molberg.mgutility.sdk.PluginManifest; +import cloud.molberg.mgutility.sdk.PluginManifestParser; + +/** Discovers installed APKs carrying the SDK manifest asset. Invalid packages are ignored safely. */ +public final class InstalledPluginScanner { + private InstalledPluginScanner() { } + public static List scan(Context context) { + ArrayList result = new ArrayList(); + PackageManager pm=context.getPackageManager(); + for (PackageInfo info : pm.getInstalledPackages(0)) { + try { + Context pluginContext=context.createPackageContext(info.packageName, Context.CONTEXT_IGNORE_SECURITY); + InputStream in=pluginContext.getAssets().open(PluginManifest.ASSET_NAME); byte[] data=new byte[4096]; StringBuilder json=new StringBuilder(); int n; + while((n=in.read(data))>0) json.append(new String(data,0,n,"UTF-8")); in.close(); + PluginManifest manifest=PluginManifestParser.parse(json.toString()); + if (!manifest.id.equals(info.packageName)) continue; + result.add(new InstalledPlugin(info.packageName, manifest, pluginContext)); + } catch (Exception ignored) { } + } + return result; + } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginApkInstaller.java b/src/cloud/molberg/mgutility/plugin/PluginApkInstaller.java new file mode 100644 index 0000000..55c82c0 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginApkInstaller.java @@ -0,0 +1,38 @@ +package cloud.molberg.mgutility.plugin; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.provider.Settings; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** Streams the plugin APK into the app's private cache after checksum verification, then asks the OS installer to open it. */ +public final class PluginApkInstaller { + private final Context app; + public PluginApkInstaller(Context context) { this.app = context.getApplicationContext(); } + public void install(PluginCatalogEntry entry, byte[] downloaded) throws Exception { + PluginInstaller.validateDownload(entry, downloaded); + File directory = new File(app.getFilesDir(), "plugins"); if (!directory.exists() && !directory.mkdirs()) throw new IllegalStateException("plugin cache unavailable"); + File apk = new File(directory, entry.id + "-" + entry.version + ".apk"); + FileOutputStream out = new FileOutputStream(apk); out.write(downloaded); out.close(); + Uri uri; if (Build.VERSION.SDK_INT >= 24) { String authority = app.getPackageName() + ".plugins"; /* install helper to be supplied by next SDK phase */ uri = Uri.parse("content://" + authority + "/" + apk.getName()); } + else { uri = Uri.fromFile(apk); } + Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION); + app.startActivity(intent); + } + /** Convenience helper for tests/CLI: downloads an entry into memory and validates the checksum before installation. */ + public static byte[] download(PluginCatalogEntry entry) throws Exception { + if (entry == null || entry.apkUrl == null || !entry.apkUrl.startsWith("https://")) throw new SecurityException("plugin downloads must use HTTPS"); + HttpURLConnection connection = (HttpURLConnection) new URL(entry.apkUrl).openConnection(); + connection.setConnectTimeout(8000); connection.setReadTimeout(8000); + InputStream in = connection.getInputStream(); java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); + byte[] chunk = new byte[8192]; int read; while ((read = in.read(chunk)) > 0) buffer.write(chunk, 0, read); in.close(); return buffer.toByteArray(); + } + /** Hidden helper used by the activity when the user has not yet enabled "install unknown apps". */ + public Intent unknownSourcesIntent() { return new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse("package:" + app.getPackageName())); } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginCatalogEntry.java b/src/cloud/molberg/mgutility/plugin/PluginCatalogEntry.java new file mode 100644 index 0000000..a65281e --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginCatalogEntry.java @@ -0,0 +1,16 @@ +package cloud.molberg.mgutility.plugin; + +import cloud.molberg.mgutility.sdk.VersionRange; + +/** One downloadable plugin advertised by a repository index. */ +public final class PluginCatalogEntry { + public final String id, name, version, description, apkUrl, sha256, publisher, sdkRange, entryClass; + public PluginCatalogEntry(String id,String name,String version,String description,String apkUrl,String sha256,String publisher,String sdkRange) { + this(id,name,version,description,apkUrl,sha256,publisher,sdkRange, null); + } + public PluginCatalogEntry(String id,String name,String version,String description,String apkUrl,String sha256,String publisher,String sdkRange,String entryClass) { + if (id == null || id.length() == 0 || version == null || version.length() == 0) throw new IllegalArgumentException("plugin id and version are required"); + this.id=id; this.name=name==null?id:name; this.version=version; this.description=description==null?"":description; this.apkUrl=apkUrl==null?"":apkUrl; this.sha256=sha256==null?"":sha256.toLowerCase(); this.publisher=publisher==null?"":publisher; this.sdkRange=sdkRange==null?"":sdkRange; this.entryClass=entryClass; + } + public boolean supportsSdk(String sdkVersion) { if (sdkRange.length()==0) return true; String[] p=sdkRange.split("\\s*[-,]\\s*",2); return new VersionRange(p.length>0&&p[0].length()>0?p[0]:null,p.length>1&&p[1].length()>0?p[1]:null).contains(sdkVersion); } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginHostEvents.java b/src/cloud/molberg/mgutility/plugin/PluginHostEvents.java new file mode 100644 index 0000000..c936e7f --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginHostEvents.java @@ -0,0 +1,13 @@ +package cloud.molberg.mgutility.plugin; + +import cloud.molberg.mgutility.sdk.HookEvent; +import cloud.molberg.mgutility.sdk.HookRegistry; + +/** Process-wide event bus used by host services to publish events to every plugin. */ +public final class PluginHostEvents { + private static final HookRegistry BUS = new cloud.molberg.mgutility.sdk.InMemoryHookRegistry(); + private PluginHostEvents() { } + public static HookRegistry bus() { return BUS; } + public static void publish(HookEvent event) { BUS.publish(event); } + public static void publish(String hook, Object payload) { BUS.publish(hook, payload); } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginInstallRecord.java b/src/cloud/molberg/mgutility/plugin/PluginInstallRecord.java new file mode 100644 index 0000000..80b00ae --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginInstallRecord.java @@ -0,0 +1,8 @@ +package cloud.molberg.mgutility.plugin; + +/** Persistable result of a plugin installation decision. */ +public final class PluginInstallRecord { + public final String pluginId, version, apkPath, repositoryId; + public final long installedAt; + public PluginInstallRecord(String pluginId,String version,String apkPath,String repositoryId,long installedAt){this.pluginId=pluginId;this.version=version;this.apkPath=apkPath;this.repositoryId=repositoryId;this.installedAt=installedAt;} +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginInstaller.java b/src/cloud/molberg/mgutility/plugin/PluginInstaller.java new file mode 100644 index 0000000..1a4f415 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginInstaller.java @@ -0,0 +1,11 @@ +package cloud.molberg.mgutility.plugin; + +/** Security checks shared by any future Android PackageInstaller integration. */ +public final class PluginInstaller { + private PluginInstaller() { } + public static void validateDownload(PluginCatalogEntry entry, byte[] apkBytes) { + if (entry == null || apkBytes == null) throw new IllegalArgumentException("plugin and APK are required"); + if (entry.apkUrl.length() == 0 || !(entry.apkUrl.startsWith("https://"))) throw new SecurityException("plugin downloads must use HTTPS"); + if (entry.sha256.length() != 64 || !PluginSignatureVerifier.matches(apkBytes, entry.sha256)) throw new SecurityException("plugin checksum mismatch"); + } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginMarketplace.java b/src/cloud/molberg/mgutility/plugin/PluginMarketplace.java new file mode 100644 index 0000000..2335ac5 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginMarketplace.java @@ -0,0 +1,25 @@ +package cloud.molberg.mgutility.plugin; + +import cloud.molberg.mgutility.sdk.VersionRange; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Repository aggregation and version selection, independent of networking and UI. */ +public final class PluginMarketplace { + public interface RepositoryClient { PluginRepositoryIndex fetch(PluginRepository repository) throws Exception; } + private final List repositories = new ArrayList(); + private final Map indexes = new LinkedHashMap(); + public synchronized void addRepository(PluginRepository repository) { removeRepository(repository.id); repositories.add(repository); } + public synchronized void removeRepository(String id) { for (int i=repositories.size()-1;i>=0;i--) if (repositories.get(i).id.equals(id)) repositories.remove(i); indexes.remove(id); } + public synchronized List repositories() { return Collections.unmodifiableList(new ArrayList(repositories)); } + public synchronized void refresh(RepositoryClient client) throws Exception { for (PluginRepository r:repositories) if (r.enabled) indexes.put(r.id, client.fetch(r)); } + public synchronized List available(String sdkVersion) { + Map best=new LinkedHashMap(); + for (PluginRepository r:repositories) { PluginRepositoryIndex index=indexes.get(r.id); if(index==null) continue; for(PluginCatalogEntry e:index.plugins) if(e.supportsSdk(sdkVersion) && (!best.containsKey(e.id)||VersionRange.compare(e.version,best.get(e.id).version)>0)) best.put(e.id,e); } + ArrayList result=new ArrayList(best.values()); Collections.sort(result,new Comparator(){public int compare(PluginCatalogEntry a,PluginCatalogEntry b){return a.name.compareToIgnoreCase(b.name);}}); return result; + } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginRegistry.java b/src/cloud/molberg/mgutility/plugin/PluginRegistry.java new file mode 100644 index 0000000..2130c1b --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginRegistry.java @@ -0,0 +1,29 @@ +package cloud.molberg.mgutility.plugin; + +import cloud.molberg.mgutility.sdk.Plugin; +import cloud.molberg.mgutility.sdk.PluginContext; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Lifecycle owner for loaded plugins. Loading is explicit so the host can verify signatures first. */ +public final class PluginRegistry { + public enum State { DISCOVERED, LOADED, ENABLED, DISABLED, FAILED } + public static final class Handle { public final PluginCatalogEntry entry; public final Plugin plugin; public State state; public Throwable failure; Handle(PluginCatalogEntry e,Plugin p){entry=e;plugin=p;state=State.LOADED;} } + private final Map handles=new LinkedHashMap(); + public synchronized Handle load(PluginCatalogEntry entry, ClassLoader loader, PluginContext context) { + try { String className = entry.entryClass == null || entry.entryClass.length() == 0 ? entry.id : entry.entryClass; Plugin p=(Plugin)Class.forName(className, true, loader).newInstance(); Handle h=new Handle(entry,p); handles.put(entry.id,h); p.onLoad(context); return h; } + catch(Throwable t){ Handle h=new Handle(entry,null); h.state=State.FAILED; h.failure=t; handles.put(entry.id,h); return h; } + } + public synchronized boolean enable(String id, PluginContext context) { Handle h=handles.get(id); if(h==null||h.state==State.FAILED||h.plugin==null)return false; try{h.plugin.onEnable(context);h.state=State.ENABLED;return true;}catch(Throwable t){h.failure=t;h.state=State.FAILED;return false;} } + public synchronized boolean disable(String id, PluginContext context) { Handle h=handles.get(id); if(h==null||h.plugin==null||h.state!=State.ENABLED)return false; try{h.plugin.onDisable(context);h.state=State.DISABLED;return true;}catch(Throwable t){h.failure=t;h.state=State.FAILED;return false;} } + /** Unloads a plugin and invokes its cleanup callback. */ + public synchronized boolean unload(String id, PluginContext context) { + Handle h=handles.get(id); if(h==null||h.plugin==null||h.state==State.FAILED)return false; + try { + if (h.state == State.ENABLED) h.plugin.onDisable(context); + h.plugin.onUnload(context); handles.remove(id); return true; + } catch (Throwable t) { h.failure=t; h.state=State.FAILED; return false; } + } + public synchronized Map snapshot(){return Collections.unmodifiableMap(new LinkedHashMap(handles));} +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginRepository.java b/src/cloud/molberg/mgutility/plugin/PluginRepository.java new file mode 100644 index 0000000..202ab69 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginRepository.java @@ -0,0 +1,19 @@ +package cloud.molberg.mgutility.plugin; + +/** A user-configurable plugin index. URLs must be HTTPS in production. */ +public final class PluginRepository { + /** Reserved display entry until the official repository is published. */ + public static PluginRepository officialPlaceholder() { + return new PluginRepository("mg-official", "MG Utility official plugins (coming soon)", + "https://plugins.mg-utility.invalid/index.json", false, true); + } + public final String id, name, url; + public final boolean enabled, official; + public PluginRepository(String id, String name, String url, boolean enabled, boolean official) { + if (id == null || id.trim().length() == 0) throw new IllegalArgumentException("repository id is required"); + if (url == null || url.trim().length() == 0) throw new IllegalArgumentException("repository url is required"); + if (!url.startsWith("https://")) throw new IllegalArgumentException("repository url must use HTTPS"); + this.id=id; this.name=name==null?id:name; this.url=url; this.enabled=enabled; this.official=official; + } + public PluginRepository withEnabled(boolean value) { return new PluginRepository(id,name,url,value,official); } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndex.java b/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndex.java new file mode 100644 index 0000000..9f2929a --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndex.java @@ -0,0 +1,12 @@ +package cloud.molberg.mgutility.plugin; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** Parsed repository response. The wire format is intentionally tiny and stable. */ +public final class PluginRepositoryIndex { + public final int schema; + public final List plugins; + public PluginRepositoryIndex(int schema, List plugins) { this.schema=schema; this.plugins=Collections.unmodifiableList(new ArrayList(plugins)); } +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java b/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java new file mode 100644 index 0000000..47c8cd3 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java @@ -0,0 +1,23 @@ +package cloud.molberg.mgutility.plugin; + +import java.util.ArrayList; +import java.util.List; + +/** Dependency-free parser for marketplace index JSON (suitable for host and CLI tests). */ +public final class PluginRepositoryIndexParser { + private PluginRepositoryIndexParser() { } + public static PluginRepositoryIndex parse(String json) { + if (json == null) throw new IllegalArgumentException("index is null"); + int schema = number(json, "schema", 1); + ArrayList entries = new ArrayList(); + java.util.regex.Matcher objects = java.util.regex.Pattern.compile("\\{([^{}]*)\\}").matcher(json); + while (objects.find()) { + String value = objects.group(1); String id = string(value,"id"); + if (id == null || id.length() == 0) continue; + entries.add(new PluginCatalogEntry(id, string(value,"name"), string(value,"version"), string(value,"description"), string(value,"apkUrl"), string(value,"sha256"), string(value,"publisher"), string(value,"sdkRange"), string(value,"entry"))); + } + return new PluginRepositoryIndex(schema, entries); + } + private static int number(String json,String key,int fallback){try{java.util.regex.Matcher m=java.util.regex.Pattern.compile("\\\""+key+"\\\"\\s*:\\s*(\\d+)").matcher(json);return m.find()?Integer.parseInt(m.group(1)):fallback;}catch(Exception e){return fallback;}} + private static String string(String json,String key){java.util.regex.Matcher m=java.util.regex.Pattern.compile("\\\""+key+"\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"").matcher(json);return m.find()?m.group(1):null;} +} diff --git a/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java b/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java new file mode 100644 index 0000000..140f0c2 --- /dev/null +++ b/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java @@ -0,0 +1,11 @@ +package cloud.molberg.mgutility.plugin; + +import java.security.MessageDigest; +import java.util.Locale; + +/** Validates repository checksums before an APK is handed to Android's installer. */ +public final class PluginSignatureVerifier { + private PluginSignatureVerifier() { } + public static String sha256(byte[] data) { try { byte[] digest=MessageDigest.getInstance("SHA-256").digest(data); StringBuilder out=new StringBuilder(); for(byte b:digest)out.append(String.format(Locale.US,"%02x",b&255)); return out.toString(); } catch(Exception e){throw new IllegalStateException(e);} } + public static boolean matches(byte[] data,String expected) { return expected!=null && sha256(data).equalsIgnoreCase(expected.trim()); } +} diff --git a/src/cloud/molberg/mgutility/sdk/Contribution.java b/src/cloud/molberg/mgutility/sdk/Contribution.java new file mode 100644 index 0000000..7c60af9 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/Contribution.java @@ -0,0 +1,18 @@ +package cloud.molberg.mgutility.sdk; + +/** A contribution made by a plugin to the host UI or behaviour surface. */ +public final class Contribution { + public enum Type { HOME_TILE, DASHBOARD_WIDGET, SETTINGS_PAGE, BACKGROUND_SERVICE, KEY_ACTION } + public final String id; + public final Type type; + public final String title; + public final String description; + public final Object payload; + + public Contribution(String id, Type type, String title, String description, Object payload) { + if (id == null || id.trim().length() == 0) throw new IllegalArgumentException("id is required"); + if (type == null) throw new IllegalArgumentException("type is required"); + this.id = id; this.type = type; this.title = title == null ? "" : title; + this.description = description == null ? "" : description; this.payload = payload; + } +} diff --git a/src/cloud/molberg/mgutility/sdk/ContributionRegistry.java b/src/cloud/molberg/mgutility/sdk/ContributionRegistry.java new file mode 100644 index 0000000..3445f3c --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/ContributionRegistry.java @@ -0,0 +1,11 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.List; + +/** Registry for plugin contributions. IDs are unique within a plugin. */ +public interface ContributionRegistry { + void register(Contribution contribution); + void remove(String contributionId); + void clear(); + List all(); +} diff --git a/src/cloud/molberg/mgutility/sdk/HookEvent.java b/src/cloud/molberg/mgutility/sdk/HookEvent.java new file mode 100644 index 0000000..21c97fe --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/HookEvent.java @@ -0,0 +1,25 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Immutable, forwards-compatible event payload shared by all standard hooks. */ +public final class HookEvent { + public final PluginHook hook; + public final long timestampMillis; + private final Map values; + public HookEvent(PluginHook hook, long timestampMillis, Map values) { + if (hook == null) throw new IllegalArgumentException("hook is required"); + this.hook = hook; this.timestampMillis = timestampMillis; + this.values = Collections.unmodifiableMap(new LinkedHashMap(values == null ? Collections.emptyMap() : values)); + } + public static HookEvent now(PluginHook hook, Map values) { return new HookEvent(hook, System.currentTimeMillis(), values); } + public Map values() { return values; } + public Object get(String key) { return values.get(key); } + public String getString(String key, String fallback) { Object value=get(key); return value == null ? fallback : String.valueOf(value); } + public int getInt(String key, int fallback) { Object value=get(key); return value instanceof Number ? ((Number)value).intValue() : fallback; } + public long getLong(String key, long fallback) { Object value=get(key); return value instanceof Number ? ((Number)value).longValue() : fallback; } + public double getDouble(String key, double fallback) { Object value=get(key); return value instanceof Number ? ((Number)value).doubleValue() : fallback; } + public boolean getBoolean(String key, boolean fallback) { Object value=get(key); return value instanceof Boolean ? ((Boolean)value).booleanValue() : fallback; } +} diff --git a/src/cloud/molberg/mgutility/sdk/HookRegistry.java b/src/cloud/molberg/mgutility/sdk/HookRegistry.java new file mode 100644 index 0000000..75a2ec4 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/HookRegistry.java @@ -0,0 +1,13 @@ +package cloud.molberg.mgutility.sdk; + +/** Registry for named host events. Hook payloads are intentionally opaque for forwards compatibility. */ +public interface HookRegistry { + interface Listener { void onEvent(String hook, Object payload); } + interface TypedListener { void onEvent(PluginHook hook, HookEvent event); } + void subscribe(String hook, Listener listener); + void unsubscribe(String hook, Listener listener); + void publish(String hook, Object payload); + void subscribe(PluginHook hook, TypedListener listener); + void unsubscribe(PluginHook hook, TypedListener listener); + void publish(HookEvent event); +} diff --git a/src/cloud/molberg/mgutility/sdk/InMemoryContributionRegistry.java b/src/cloud/molberg/mgutility/sdk/InMemoryContributionRegistry.java new file mode 100644 index 0000000..8634cce --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/InMemoryContributionRegistry.java @@ -0,0 +1,16 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Reference registry used by the host and by plugin unit tests. */ +public final class InMemoryContributionRegistry implements ContributionRegistry { + private final Map values = new LinkedHashMap(); + public synchronized void register(Contribution contribution) { values.put(contribution.id, contribution); } + public synchronized void remove(String id) { values.remove(id); } + public synchronized void clear() { values.clear(); } + public synchronized List all() { return Collections.unmodifiableList(new ArrayList(values.values())); } +} diff --git a/src/cloud/molberg/mgutility/sdk/InMemoryHookRegistry.java b/src/cloud/molberg/mgutility/sdk/InMemoryHookRegistry.java new file mode 100644 index 0000000..b9b8e2f --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/InMemoryHookRegistry.java @@ -0,0 +1,31 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Thread-safe reference hook registry. */ +public final class InMemoryHookRegistry implements HookRegistry { + private final Map> listeners = new HashMap>(); + private final Map> typedListeners = new HashMap>(); + public synchronized void subscribe(String hook, Listener listener) { + if (hook == null || listener == null) throw new IllegalArgumentException("hook and listener are required"); + List list = listeners.get(hook); if (list == null) { list = new ArrayList(); listeners.put(hook, list); } + if (!list.contains(listener)) list.add(listener); + } + public synchronized void unsubscribe(String hook, Listener listener) { List list = listeners.get(hook); if (list != null) { list.remove(listener); if (list.isEmpty()) listeners.remove(hook); } } + public void publish(String hook, Object payload) { + List copy; + synchronized (this) { List list = listeners.get(hook); copy = list == null ? new ArrayList() : new ArrayList(list); } + for (Listener listener : copy) listener.onEvent(hook, payload); + } + public synchronized void subscribe(PluginHook hook, TypedListener listener) { + if (hook == null || listener == null) throw new IllegalArgumentException("hook and listener are required"); + List list=typedListeners.get(hook.id); if(list==null){list=new ArrayList();typedListeners.put(hook.id,list);} if(!list.contains(listener))list.add(listener); + } + public synchronized void unsubscribe(PluginHook hook, TypedListener listener) { if(hook==null)return; List list=typedListeners.get(hook.id); if(list!=null){list.remove(listener);if(list.isEmpty())typedListeners.remove(hook.id);} } + public void publish(HookEvent event) { + if(event==null)return; List copy; synchronized(this){List list=typedListeners.get(event.hook.id);copy=list==null?new ArrayList():new ArrayList(list);} for(TypedListener listener:copy)listener.onEvent(event.hook,event); + } +} diff --git a/src/cloud/molberg/mgutility/sdk/Plugin.java b/src/cloud/molberg/mgutility/sdk/Plugin.java new file mode 100644 index 0000000..50c6ab9 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/Plugin.java @@ -0,0 +1,11 @@ +package cloud.molberg.mgutility.sdk; + +/** Entry point implemented by an MG Utility plugin. */ +public interface Plugin { + default void onLoad(PluginContext context) { } + default void onEnable(PluginContext context) { } + default void onDisable(PluginContext context) { } + default void onUnload(PluginContext context) { } + /** Lifecycle contract that the host relies on. */ + String PLUGIN_API_VERSION = "1.0.0"; +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginCapability.java b/src/cloud/molberg/mgutility/sdk/PluginCapability.java new file mode 100644 index 0000000..a829698 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginCapability.java @@ -0,0 +1,14 @@ +package cloud.molberg.mgutility.sdk; + +/** Explicit host capability that a plugin may request in its manifest. */ +public enum PluginCapability { + DASHBOARD, + SETTINGS, + AUDIO_PLAYBACK, + VEHICLE_DATA_READ, + KEY_REMAP, + BACKGROUND_WORK, + STORAGE, + NETWORK, + NOTIFICATIONS +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginContext.java b/src/cloud/molberg/mgutility/sdk/PluginContext.java new file mode 100644 index 0000000..e31248c --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginContext.java @@ -0,0 +1,24 @@ +package cloud.molberg.mgutility.sdk; + +/** Services and scoped state exposed to a plugin. */ +public interface PluginContext { + String pluginId(); + String displayName(); + String pluginVersion(); + String sdkVersion(); + ScopedPreferences preferences(); + PluginLogger logger(); + ContributionRegistry contributions(); + HookRegistry hooks(); + void runAsync(Runnable work); + String assetUri(String relativePath); + + /** Capabilities granted by the host (empty for older hosts). */ + default java.util.Set capabilities() { + return java.util.Collections.emptySet(); + } + + default boolean hasCapability(PluginCapability capability) { + return capability != null && capabilities().contains(capability); + } +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginHook.java b/src/cloud/molberg/mgutility/sdk/PluginHook.java new file mode 100644 index 0000000..4ef2952 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginHook.java @@ -0,0 +1,16 @@ +package cloud.molberg.mgutility.sdk; + +/** Stable host events a plugin can consume. Hosts may add events, but will not change the meaning of existing ones. */ +public enum PluginHook { + APP_STARTED("app.started"), APP_STOPPED("app.stopped"), SCREEN_ON("screen.on"), SCREEN_OFF("screen.off"), + VEHICLE_CONNECTED("vehicle.connected"), VEHICLE_DISCONNECTED("vehicle.disconnected"), VEHICLE_STATE("vehicle.state"), + SPEED_CHANGED("vehicle.speed_changed"), SOC_CHANGED("vehicle.soc_changed"), CHARGING_STATE_CHANGED("vehicle.charging_changed"), + DRIVE_MODE_CHANGED("vehicle.drive_mode_changed"), REGENERATION_CHANGED("vehicle.regeneration_changed"), + MEDIA_STATE_CHANGED("media.state_changed"), AUDIO_FFT("audio.fft"), VOLUME_CHANGED("audio.volume_changed"), + KEY_EVENT("input.key_event"), TRIP_STARTED("trip.started"), TRIP_UPDATED("trip.updated"), TRIP_FINISHED("trip.finished"), + ARRIVAL_ENTERED("arrival.entered"), ARRIVAL_EXITED("arrival.exited"), DASHBOARD_REFRESH("dashboard.refresh"), + THEME_CHANGED("dashboard.theme_changed"), PLUGIN_ENABLED("plugin.enabled"), PLUGIN_DISABLED("plugin.disabled"); + public final String id; + PluginHook(String id) { this.id = id; } + public static PluginHook fromId(String id) { if (id != null) for (PluginHook hook : values()) if (hook.id.equals(id)) return hook; return null; } +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginLogger.java b/src/cloud/molberg/mgutility/sdk/PluginLogger.java new file mode 100644 index 0000000..eeb53a9 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginLogger.java @@ -0,0 +1,9 @@ +package cloud.molberg.mgutility.sdk; + +/** Small logging facade so plugins do not depend on Android's Log class. */ +public interface PluginLogger { + void debug(String message); + void info(String message); + void warn(String message); + void error(String message, Throwable cause); +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginManifest.java b/src/cloud/molberg/mgutility/sdk/PluginManifest.java new file mode 100644 index 0000000..3951c3d --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginManifest.java @@ -0,0 +1,29 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** Immutable metadata declared in {@code assets/mg-plugin.json}. */ +public final class PluginManifest { + public static final String ASSET_NAME = "mg-plugin.json"; + public static final int SCHEMA_VERSION = 1; + public static final String SDK_VERSION = "1.0.0"; + public final String id, name, version, entry, sdkVersion, description, publisher; + public final List permissions; + /** Parsed capability names, retained as strings for forward compatibility. */ + public final List capabilities; + public PluginManifest(String id, String name, String version, String entry, String sdkVersion, String description, String publisher, List permissions) { + this(id, name, version, entry, sdkVersion, description, publisher, permissions, null); + } + public PluginManifest(String id, String name, String version, String entry, String sdkVersion, String description, String publisher, List permissions, List capabilities) { + if (id == null || !id.matches("[a-zA-Z0-9][a-zA-Z0-9._-]{1,127}")) throw new IllegalArgumentException("invalid plugin id"); + if (entry == null || entry.trim().length() == 0) throw new IllegalArgumentException("entry is required"); + this.id=id; this.name=name==null?id:name; this.version=version==null?"0.0.0":version; this.entry=entry; this.sdkVersion=sdkVersion==null?"1.0.0":sdkVersion; this.description=description==null?"":description; this.publisher=publisher==null?"":publisher; + this.permissions=Collections.unmodifiableList(new ArrayList(permissions==null?Collections.emptyList():permissions)); + this.capabilities=Collections.unmodifiableList(new ArrayList(capabilities==null?Collections.emptyList():new LinkedHashSet(capabilities))); + } + public boolean requests(PluginCapability capability) { return capability != null && capabilities.contains(capability.name()); } +} diff --git a/src/cloud/molberg/mgutility/sdk/PluginManifestParser.java b/src/cloud/molberg/mgutility/sdk/PluginManifestParser.java new file mode 100644 index 0000000..0d0cd30 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/PluginManifestParser.java @@ -0,0 +1,28 @@ +package cloud.molberg.mgutility.sdk; + +import java.util.ArrayList; +import java.util.List; + +/** Minimal dependency-free parser for the SDK's deliberately small manifest format. */ +public final class PluginManifestParser { + private PluginManifestParser() { } + public static PluginManifest parse(String json) { + if (json == null) throw new IllegalArgumentException("manifest is null"); + int schema = number(json, "schema", 1); + if (schema != PluginManifest.SCHEMA_VERSION) throw new IllegalArgumentException("unsupported manifest schema: " + schema); + String id=req(json,"id"); + String entry=opt(json,"entry"); + if (entry == null) entry=opt(json,"entryPoint"); + if (entry == null || entry.trim().length()==0) throw new IllegalArgumentException("manifest field required: entryPoint"); + String version = opt(json,"version"); + if (version == null) version = opt(json,"versionName"); + String entryPoint = entry; + String parsedEntryPoint = opt(json,"entryPoint"); + if (parsedEntryPoint != null) entryPoint = parsedEntryPoint; + return new PluginManifest(id, opt(json,"name"), version, entryPoint, opt(json,"sdkVersion"), opt(json,"description"), opt(json,"publisher"), array(json,"permissions"), array(json,"capabilities")); + } + private static int number(String json,String key,int fallback){try{java.util.regex.Matcher m=java.util.regex.Pattern.compile("\\\""+java.util.regex.Pattern.quote(key)+"\\\"\\s*:\\s*(\\d+)").matcher(json);return m.find()?Integer.parseInt(m.group(1)):fallback;}catch(Exception e){return fallback;}} + private static String req(String j,String k) { String v=opt(j,k); if (v==null||v.trim().length()==0) throw new IllegalArgumentException("manifest field required: "+k); return v; } + private static String opt(String j,String k) { java.util.regex.Matcher m=java.util.regex.Pattern.compile("\\\""+java.util.regex.Pattern.quote(k)+"\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"").matcher(j); if(!m.find()) return null; return m.group(1).replace("\\\"","\\\"").replace("\\\\","\\"); } + private static List array(String j,String k) { ArrayList out=new ArrayList(); java.util.regex.Matcher m=java.util.regex.Pattern.compile("\\\""+java.util.regex.Pattern.quote(k)+"\\\"\\s*:\\s*\\[([^]]*)\\]").matcher(j); if(m.find()){ java.util.regex.Matcher x=java.util.regex.Pattern.compile("\\\"((?:\\\\.|[^\\\"])*)\\\"").matcher(m.group(1)); while(x.find()) out.add(x.group(1)); } return out; } +} diff --git a/src/cloud/molberg/mgutility/sdk/ScopedPreferences.java b/src/cloud/molberg/mgutility/sdk/ScopedPreferences.java new file mode 100644 index 0000000..ee71a33 --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/ScopedPreferences.java @@ -0,0 +1,18 @@ +package cloud.molberg.mgutility.sdk; + +/** Preference operations scoped to one plugin. */ +public interface ScopedPreferences { + String getString(String key, String fallback); + boolean getBoolean(String key, boolean fallback); + int getInt(String key, int fallback); + long getLong(String key, long fallback); + float getFloat(String key, float fallback); + boolean contains(String key); + void putString(String key, String value); + void putBoolean(String key, boolean value); + void putInt(String key, int value); + void putLong(String key, long value); + void putFloat(String key, float value); + void remove(String key); + void clear(); +} diff --git a/src/cloud/molberg/mgutility/sdk/VersionRange.java b/src/cloud/molberg/mgutility/sdk/VersionRange.java new file mode 100644 index 0000000..02902ca --- /dev/null +++ b/src/cloud/molberg/mgutility/sdk/VersionRange.java @@ -0,0 +1,20 @@ +package cloud.molberg.mgutility.sdk; + +/** Inclusive semantic version range used for SDK compatibility checks. */ +public final class VersionRange { + public final String minInclusive; + public final String maxExclusive; + public VersionRange(String minInclusive, String maxExclusive) { this.minInclusive = minInclusive; this.maxExclusive = maxExclusive; } + public boolean contains(String version) { + if (version == null) return false; + return (minInclusive == null || compare(version, minInclusive) >= 0) && (maxExclusive == null || compare(version, maxExclusive) < 0); + } + public static int compare(String left, String right) { + String[] a = clean(left).split("\\."), b = clean(right).split("\\."); + int n = Math.max(a.length, b.length); + for (int i=0;i + + + + + MG Fielddesk · Analytics + + + +
+
+
MG
FielddeskTelemetry & support
+
Connecting
+
+ + +
MG FIELD DESK · private operator console · no user IPs stored
+
+ +
+ + diff --git a/telemetry-service/package.json b/telemetry-service/package.json new file mode 100644 index 0000000..e7b65df --- /dev/null +++ b/telemetry-service/package.json @@ -0,0 +1,8 @@ +{ + "name": "mg-utility-telemetry", + "version": "0.1.0", + "private": true, + "description": "Local MG Utility diagnostics and announcements service", + "scripts": {"start": "node server.js", "test": "node --test"}, + "engines": {"node": ">=20"} +} diff --git a/telemetry-service/run-server.sh b/telemetry-service/run-server.sh new file mode 100755 index 0000000..588290b --- /dev/null +++ b/telemetry-service/run-server.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +VAULT_CLI=/root/.openclaw/workspace/scripts/bw +VAULT_ITEM_ID=b06d15fd-1a7f-4d65-a396-60211709b640 +TMPDIR=/root/.hermes/cache/scratch +export TMPDIR +ITEM_FILE=$(mktemp) +chmod 600 "$ITEM_FILE" +trap 'rm -f "$ITEM_FILE"' EXIT HUP INT TERM +"$VAULT_CLI" get item "$VAULT_ITEM_ID" > "$ITEM_FILE" +ADMIN_PASSWORD=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["login"]["password"],end="")' "$ITEM_FILE") +test -n "$ADMIN_PASSWORD" +export ADMIN_PASSWORD +rm -f "$ITEM_FILE" +trap - EXIT HUP INT TERM +cd "$ROOT" +exec node server.js diff --git a/telemetry-service/server.js b/telemetry-service/server.js new file mode 100644 index 0000000..c6bbf81 --- /dev/null +++ b/telemetry-service/server.js @@ -0,0 +1,450 @@ +'use strict'; + +const http = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const { randomUUID, randomBytes, createHmac, timingSafeEqual } = require('node:crypto'); +const { DatabaseSync } = require('node:sqlite'); + +const HOST = process.env.HOST || '0.0.0.0'; +const PORT = Number(process.env.PORT || 7013); +const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data'); +const CONFIG_FILE = process.env.CONFIG_FILE || path.join(__dirname, 'client-config.json'); + +const DATABASE_FILE = process.env.DATABASE_FILE || path.join(DATA_DIR, 'analytics.sqlite'); +const SESSION_COOKIE = 'mgadm'; +const SESSION_TTL_MS = 12 * 60 * 60 * 1000; +const MAX_BODY = 256 * 1024; +const MAX_EVENTS = 20000; + +fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 }); +try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {} +const db = new DatabaseSync(DATABASE_FILE); +db.exec(`CREATE TABLE IF NOT EXISTS events ( + id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, product TEXT NOT NULL, appVersion TEXT, + platform TEXT, vehicleId TEXT, appProfile TEXT, category TEXT NOT NULL, message TEXT, + details TEXT, kind TEXT NOT NULL DEFAULT 'support' +); +CREATE INDEX IF NOT EXISTS events_receivedAt_idx ON events(receivedAt); +CREATE INDEX IF NOT EXISTS events_vehicleId_idx ON events(vehicleId); +CREATE TABLE IF NOT EXISTS installs (vehicleId TEXT PRIMARY KEY, firstSeenAt TEXT NOT NULL, lastSeenAt TEXT NOT NULL, + appVersion TEXT, platform TEXT, manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT); +CREATE TABLE IF NOT EXISTS crashes (id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, vehicleId TEXT, appVersion TEXT, platform TEXT, + manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT, exceptionType TEXT, message TEXT, stack TEXT); +`); +try { fs.chmodSync(DATABASE_FILE, 0o600); } catch (_) {} + + +fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 }); +try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {} +// Admin password is injected from the credential store by the service launcher; +// never persist credentials beside application data. Session signing key is ephemeral. +const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || ''; +const SESSION_SECRET = randomBytes(32).toString('hex'); + +function json(res, status, body) { + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer' }); + res.end(JSON.stringify(body)); +} +function readBody(req, limit) { + return new Promise((resolve, reject) => { + let data = ''; let size = 0; + req.on('data', chunk => { + size += chunk.length; + if (size > (limit || MAX_BODY)) { reject(Object.assign(new Error('request too large'), { status: 413 })); req.destroy(); return; } + data += chunk.toString('utf8'); + }); + req.on('end', () => resolve(data)); + req.on('error', reject); + }); +} +function readJsonBody(req, limit) { + return readBody(req, limit).then(text => { try { return JSON.parse(text || '{}'); } catch (_) { throw Object.assign(new Error('invalid JSON'), { status: 400 }); } }); +} +function safeText(value, limit) { + return typeof value === 'string' ? value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, limit) : ''; +} +function loopback(req) { + const addr = req.socket.remoteAddress || ''; + return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1'; +} +function loadConfig() { + try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } + catch (_) { return { schema: 1, enabled: false, uploadUrl: '', announcement: null, changelog: [] }; } +} +function saveConfig(config) { + const tmp = CONFIG_FILE + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n'); + fs.renameSync(tmp, CONFIG_FILE); +} +function registerInstall(event) { + const config = loadConfig(); + if (config.telemetryEnabled === false) return false; + if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); } + const id = safeText(event.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, ''); + if (!id) return false; + const receivedAt = new Date().toISOString(); + const values = [safeText(event.appVersion,40), safeText(event.platform,60), safeText(event.manufacturer,80), safeText(event.carModel,100), safeText(event.carBuild,180), safeText(event.appProfile,100)]; + db.prepare(`INSERT INTO installs(vehicleId,firstSeenAt,lastSeenAt,appVersion,platform,manufacturer,carModel,carBuild,appProfile) + VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(vehicleId) DO UPDATE SET lastSeenAt=excluded.lastSeenAt,appVersion=excluded.appVersion, + platform=excluded.platform,manufacturer=excluded.manufacturer,carModel=excluded.carModel,carBuild=excluded.carBuild,appProfile=excluded.appProfile`) + .run(id,receivedAt,receivedAt,...values); + return true; +} +function insertCrash(input) { + const config = loadConfig(); + if (config.telemetryEnabled === false) return false; + if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); } + const fields = [safeText(input.vehicleId,80),safeText(input.appVersion,40),safeText(input.platform,60),safeText(input.manufacturer,80),safeText(input.carModel,100),safeText(input.carBuild,180),safeText(input.appProfile,100),safeText(input.exceptionType,160),safeText(input.message,2000),safeText(input.stack,12000)]; + if (!fields[0] || !fields[7]) return false; + db.prepare(`INSERT INTO crashes(id,receivedAt,vehicleId,appVersion,platform,manufacturer,carModel,carBuild,appProfile,exceptionType,message,stack) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(randomUUID(),new Date().toISOString(),...fields); + return true; +} + +function analyticsPage() { + return `MG Utility Analytics
MG Utility · Compatibility analytics
Anonymous install fingerprints, crash summaries, and voluntary diagnostics
+ +
+ `; +} +function readEvents() { + return db.prepare('SELECT * FROM events ORDER BY receivedAt ASC').all(); +} +function appendEvent(event) { + db.prepare(`INSERT INTO events(id,receivedAt,product,appVersion,platform,vehicleId,appProfile,category,message,details,kind) + VALUES(?,?,?,?,?,?,?,?,?,?,?)`).run(event.id,event.receivedAt,event.product,event.appVersion,event.platform,event.vehicleId,event.appProfile,event.category,event.message,event.details,event.kind || 'support'); + + const old = db.prepare('SELECT id FROM events ORDER BY receivedAt DESC LIMIT -1 OFFSET ?').all(MAX_EVENTS); + const remove = db.prepare('DELETE FROM events WHERE id=?'); + for (const row of old) remove.run(row.id); +} + +// --- Sessions (HMAC-signed token; no server-side store) --- +function sign(value) { return createHmac('sha256', SESSION_SECRET).update(value).digest('base64url'); } +function issueSession() { + const payload = String(Date.now() + SESSION_TTL_MS); + return payload + '.' + sign(payload); +} +function validSession(token) { + if (typeof token !== 'string') return false; + const dot = token.lastIndexOf('.'); + if (dot < 1) return false; + const payload = token.slice(0, dot), mac = token.slice(dot + 1); + const expected = sign(payload); + if (mac.length !== expected.length) return false; + try { if (!timingSafeEqual(Buffer.from(mac), Buffer.from(expected))) return false; } catch (_) { return false; } + return Number(payload) > Date.now(); +} +function cookies(req) { + const out = {}; + for (const part of String(req.headers.cookie || '').split(';')) { + const eq = part.indexOf('='); + if (eq > 0) out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim(); + } + return out; +} +const loginFails = new Map(); +function loginAllowed(ip) { + const entry = loginFails.get(ip); + return !entry || entry.until < Date.now(); +} +function recordLoginFail(ip) { + const entry = loginFails.get(ip) || { count: 0, until: 0 }; + entry.count += 1; + entry.until = Date.now() + Math.min(5 * entry.count, 30) * 1000; + loginFails.set(ip, entry); +} +function authorized(req) { return validSession(cookies(req)[SESSION_COOKIE]); } + +// --- Dashboard (single page; all dynamic content rendered via textContent) --- +function legacyPage() { + return ` + +MG Utility Telemetry + +

MG Utility Telemetry

+
+ + +
+`; +} + +function page() { return fs.readFileSync(path.join(__dirname, 'dashboard.html'), 'utf8'); } + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://localhost'); + const p = url.pathname; + const ip = req.socket.remoteAddress || ''; + + if (req.method === 'GET' && p === '/health') return json(res, 200, { ok: true, service: 'mg-utility-telemetry' }); + + // Public client config: fetched by every app instance on startup. + if (req.method === 'GET' && p === '/v1/config') { + const c = loadConfig(); + return json(res, 200, { schema: 1, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), announcement: c.announcement || null, changelog: Array.isArray(c.changelog) ? c.changelog.slice(-50) : [] }); + } + + // Minimal startup compatibility snapshot and crash-only intake. + if (req.method === 'POST' && p === '/v1/install') { + try { + const input = await readJsonBody(req, 8192); + if (!registerInstall(input)) return json(res, 400, { error: 'invalid install identity' }); + return json(res, 202, { accepted: true }); + } catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); } + } + if (req.method === 'POST' && p === '/v1/crashes') { + try { + const input = await readJsonBody(req, 20000); + if (!insertCrash(input)) return json(res, 400, { error: 'invalid crash report' }); + return json(res, 202, { accepted: true }); + } catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); } + } + + // Public intake endpoint used by the app's explicit upload action. + if (req.method === 'POST' && p === '/v1/events') { + try { + const input = await readJsonBody(req); + if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' }); + const product = safeText(input.product, 60).replace(/[^a-zA-Z0-9._-]/g, '') || 'mg-utility'; + const vehicleId = safeText(input.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, ''); + const event = { + id: randomUUID(), receivedAt: new Date().toISOString(), + product, appVersion: safeText(input.appVersion, 40), platform: safeText(input.platform, 60), + vehicleId, appProfile: safeText(input.appProfile, 80), + category: safeText(input.category, 40), message: safeText(input.message, 4000), + details: safeText(input.details, 60000), kind: 'support' + }; + if (!event.category || (!event.message && !event.details)) return json(res, 400, { error: 'category and message or details required' }); + if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' }); + appendEvent(event); + return json(res, 202, { accepted: true, id: event.id }); + } catch (error) { return json(res, error.status || 400, { error: error.status === 413 ? 'request too large' : 'invalid request' }); } + } + + // --- Admin dashboard --- + if (req.method === 'GET' && (p === '/admin' || p === '/admin/')) return sendHtml(res, page()); + if (req.method === 'GET' && p === '/admin/analytics') return sendHtml(res, analyticsPage()); + if (req.method === 'POST' && p === '/admin/api/login') { + if (!loginAllowed(ip)) return json(res, 429, { error: 'too many attempts; wait a moment' }); + let body = {}; try { body = JSON.parse((await readBody(req, 4096)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); } + const pw = Buffer.from(String(body.password || '')); + if (!ADMIN_PASSWORD) return json(res, 503, { error: 'admin login is not configured' }); + const expected = Buffer.from(ADMIN_PASSWORD); + if (pw.length === expected.length && timingSafeEqual(pw, expected)) { + res.setHeader('set-cookie', `${SESSION_COOKIE}=${issueSession()}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL_MS / 1000}`); + loginFails.delete(ip); + return json(res, 200, { ok: true }); + } + recordLoginFail(ip); + return json(res, 401, { error: 'invalid password' }); + } + if (req.method === 'POST' && p === '/admin/api/logout') { + res.setHeader('set-cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`); + return json(res, 200, { ok: true }); + } + if (p === '/admin/api/session') return json(res, 200, { authorized: authorized(req) }); + + if (p.startsWith('/admin/api/')) { + if (!authorized(req)) return json(res, 401, { error: 'unauthorized' }); + if (req.method === 'GET' && p === '/admin/api/analytics') { + const installs = db.prepare('SELECT * FROM installs ORDER BY lastSeenAt DESC').all(); + const crashes = db.prepare('SELECT * FROM crashes ORDER BY receivedAt DESC LIMIT 500').all(); + const events = db.prepare('SELECT * FROM events ORDER BY receivedAt DESC LIMIT 500').all(); + return json(res, 200, { installs, crashes, events, stats: { activeInstalls: db.prepare('SELECT COUNT(*) AS n FROM installs').get().n, crashReports: db.prepare('SELECT COUNT(*) AS n FROM crashes').get().n } }); + } + if (req.method === 'GET' && p === '/admin/api/events') { + const product = url.searchParams.get('product') || ''; + const category = url.searchParams.get('category') || ''; + const vehicleId = url.searchParams.get('vehicleId') || ''; + const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200); + const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0); + const all = readEvents(); + let events = all.slice(); + if (product) events = events.filter(e => e.product === product); + if (category) events = events.filter(e => e.category === category); + if (vehicleId) events = events.filter(e => e.vehicleId === vehicleId); + const productCounts = new Map(); + for (const event of all) { + const name = event.product || 'mg-utility'; + productCounts.set(name, (productCounts.get(name) || 0) + 1); + } + const products = [...productCounts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => a.name.localeCompare(b.name)); + const vehicleCounts = new Map(); + for (const event of all) if (event.vehicleId) { + const row = vehicleCounts.get(event.vehicleId) || { id: event.vehicleId, appProfile: event.appProfile || '', count: 0 }; + row.count++; + if (!row.appProfile && event.appProfile) row.appProfile = event.appProfile; + vehicleCounts.set(event.vehicleId, row); + } + const vehicles = [...vehicleCounts.values()].sort((a, b) => a.id.localeCompare(b.id)); + const categories = [...new Set(all.map(e => e.category).filter(Boolean))].sort(); + const dayStart = Date.now() - 86400000; + const stats = { + total: all.length, + last24h: all.filter(e => new Date(e.receivedAt).getTime() >= dayStart).length, + builds: new Set(all.map(e => e.appVersion).filter(Boolean)).size, + products: products.length, + vehicles: vehicles.length, + productList: products + }; + events.reverse(); + return json(res, 200, { events: events.slice(offset, offset + limit), total: events.length, hasMore: offset + limit < events.length, products, vehicles, categories, stats }); + } + if (req.method === 'GET' && p === '/admin/api/export') { + res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-disposition': 'attachment; filename="mg-utility-reports.json"', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); + return res.end(JSON.stringify({ exportedAt: new Date().toISOString(), events: readEvents() }, null, 2)); + } + if (req.method === 'DELETE' && p.startsWith('/admin/api/events/')) { + const id = p.slice('/admin/api/events/'.length); + if (!/^[a-f0-9-]{36}$/i.test(id)) return json(res, 400, { error: 'invalid report id' }); + const result = db.prepare('DELETE FROM events WHERE id=?').run(id); + if (result.changes === 0) return json(res, 404, { error: 'report not found' }); + return json(res, 200, { deleted: true }); + } + if (req.method === 'GET' && p === '/admin/api/config') { + const c = loadConfig(); + return json(res, 200, { announcement: c.announcement || null, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), changelog: c.changelog || [] }); + } + if (req.method === 'POST' && p === '/admin/api/config') { + let body = {}; try { body = JSON.parse((await readBody(req, 65536)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); } + const c = loadConfig(); + if (typeof body.announcement === 'string') { + c.announcement = body.announcement.trim() ? { text: body.announcement.trim().slice(0, 2000), updatedAt: new Date().toISOString() } : null; + } + if (typeof body.enabled === 'boolean') c.enabled = body.enabled; + if (typeof body.telemetryEnabled === 'boolean') c.telemetryEnabled = body.telemetryEnabled; + if (typeof body.uploadUrl === 'string') { + const value = body.uploadUrl.trim(); + if (value && !/^https:\/\//i.test(value)) return json(res, 400, { error: 'uploadUrl must use HTTPS' }); + c.uploadUrl = value; + } + if (Array.isArray(body.changelog)) { + if (body.changelog.length > 50) return json(res, 400, { error: 'maximum 50 release notes' }); + c.changelog = body.changelog.map(item => ({ + version: safeText(item && item.version, 40), + title: safeText(item && item.title, 120), + notes: safeText(item && item.notes, 2000) + })).filter(item => item.version || item.title || item.notes); + } + saveConfig(c); + return json(res, 200, { ok: true, announcement: c.announcement }); + } + } + return json(res, 404, { error: 'not found' }); +}); + +function sendHtml(res, html) { + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer', 'content-security-policy': "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'" }); + res.end(html); +} + +server.listen(PORT, HOST, () => console.log(`MG Utility telemetry listening on ${HOST}:${PORT}`)); diff --git a/telemetry-service/server.test.js b/telemetry-service/server.test.js new file mode 100644 index 0000000..cce3acf --- /dev/null +++ b/telemetry-service/server.test.js @@ -0,0 +1,73 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { spawn } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const http = require('node:http'); + +test('health, config and event intake/readback', async t => { + const port = 22000 + Math.floor(Math.random() * 20000); + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mg-telemetry-')); + const configFile = path.join(dataDir, 'config.json'); + fs.writeFileSync(configFile, JSON.stringify({ schema: 1, enabled: true, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: null, changelog: [] })); + const child = spawn(process.execPath, ['server.js'], { cwd: __dirname, env: { ...process.env, HOST: '127.0.0.1', PORT: String(port), DATA_DIR: dataDir, CONFIG_FILE: configFile, ADMIN_PASSWORD: 'test-only-password' }, stdio: 'ignore' }); + t.after(() => { child.kill(); fs.rmSync(dataDir, { recursive: true, force: true }); }); + async function request(method, route, body, cookie) { + return new Promise((resolve, reject) => { + const headers = body ? { 'content-type': 'application/json' } : {}; + if (cookie) headers.cookie = cookie; + const req = http.request({ host: '127.0.0.1', port, path: route, method, headers }, res => { + let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data), headers: res.headers })); + }); + req.on('error', reject); if (body) req.write(JSON.stringify(body)); req.end(); + }); + } + let health; + for (let i = 0; i < 40; i++) { try { health = await request('GET', '/health'); break; } catch (_) { await new Promise(r => setTimeout(r, 50)); } } + assert.equal(health.status, 200); + assert.equal((await request('GET', '/v1/config')).body.schema, 1); + assert.equal((await request('GET', '/admin/api/events')).status, 401); + const login = await request('POST', '/admin/api/login', { password: 'test-only-password' }); + assert.equal(login.status, 200); + const cookie = login.headers['set-cookie'][0].split(';')[0]; + const vehicleId = 'd49300a0-85b2-4aa1-a8ee-27ac227d53a5'; + const startup = await request('POST', '/v1/install', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', appProfile: 'unknown-read-only' }); + assert.equal(startup.status, 202); + const crash = await request('POST', '/v1/crashes', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', exceptionType: 'IllegalStateException', message: 'synthetic', stack: 'synthetic stack' }); + assert.equal(crash.status, 202); + const analyticsPage = await new Promise((resolve, reject) => http.get({ host: '127.0.0.1', port, path: '/admin/analytics' }, res => { let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: data })); }).on('error', reject)); + assert.equal(analyticsPage.status, 200); + assert.match(analyticsPage.body, /MG Utility · Compatibility analytics/); + assert.match(analyticsPage.body, /copyFleet/); + const analytics = await request('GET', '/admin/api/analytics', null, cookie); + assert.equal(analytics.body.stats.activeInstalls, 1); + assert.equal(analytics.body.installs[0].carModel, 'MG4'); + assert.ok(fs.existsSync(path.join(dataDir, 'analytics.sqlite'))); + assert.equal(analytics.body.stats.crashReports, 1); + assert.equal((await request('GET', '/admin/api/analytics', null, cookie)).body.events.length, 0); + assert.equal((await request('GET', '/admin/api/analytics')).status, 401); + const submitted = await request('POST', '/v1/events', { product: 'saic-demo', vehicleId, appProfile: 'mg4-luxury-2022-saic-v2', category: 'diagnostic', message: 'test event', details: 'safe test' }); + assert.equal(submitted.status, 202); + const readback = await request('GET', '/admin/api/events', null, cookie); + assert.equal(readback.body.events.length, 1); + assert.equal(readback.body.events[0].message, 'test event'); + assert.equal(readback.body.events[0].product, 'saic-demo'); + assert.equal(readback.body.events[0].vehicleId, vehicleId); + assert.equal(readback.body.events[0].appProfile, 'mg4-luxury-2022-saic-v2'); + assert.equal(readback.body.stats.vehicles, 1); + assert.equal((await request('GET', '/admin/api/events?vehicleId=' + vehicleId, null, cookie)).body.total, 1); + assert.equal(readback.body.stats.total, 1); + assert.equal(readback.body.stats.productList[0].name, 'saic-demo'); + const deleted = await request('DELETE', '/admin/api/events/' + readback.body.events[0].id, null, cookie); + assert.equal(deleted.status, 200); + assert.equal((await request('GET', '/admin/api/events', null, cookie)).body.events.length, 0); + const config = await request('POST', '/admin/api/config', { enabled: false, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: 'test announcement', changelog: [{ version: '1.2', title: 'Test release', notes: 'test notes' }] }, cookie); + assert.equal(config.status, 200); + const publicConfig = (await request('GET', '/v1/config')).body; + assert.equal(publicConfig.enabled, false); + assert.equal(publicConfig.telemetryEnabled, true); + assert.equal(publicConfig.changelog[0].title, 'Test release'); + assert.equal((await request('POST', '/v1/events', {})).status, 403); +}); diff --git a/tests/AdaptiveAudioCurveTest.java b/tests/AdaptiveAudioCurveTest.java index 0df3726..bfd1be1 100644 --- a/tests/AdaptiveAudioCurveTest.java +++ b/tests/AdaptiveAudioCurveTest.java @@ -52,6 +52,11 @@ public final class AdaptiveAudioCurveTest { close(AdaptiveAudioCurve.multiplierPercent(180, 20, 90, 70, 100, 110, 110), 110f, "speed above level 3 cannot increase multiplier further"); + close(AdaptiveAudioCurve.combinedMultiplier(1.1f, 1.5f), 1.65f, "speed and distance compose once"); + close(AdaptiveAudioCurve.combinedMultiplier(1.1f, 1f), 1.1f, "anchor retains only speed compensation"); + close(AdaptiveAudioCurve.combinedMultiplier(Float.NaN, Float.NaN), 1f, "invalid multipliers are neutral"); + check(AdaptiveAudioCurve.targetVolume(0, 0, 30, 200f) == 0, "distance compensation never unmutes"); + check(AdaptiveAudioCurve.targetVolume(25, 0, 30, 300f) == 30, "combined boost respects hardware maximum"); System.out.println("AdaptiveAudioCurveTest: OK"); } } diff --git a/tests/CampingModePolicyTest.java b/tests/CampingModePolicyTest.java new file mode 100644 index 0000000..5299e52 --- /dev/null +++ b/tests/CampingModePolicyTest.java @@ -0,0 +1,35 @@ +package cloud.molberg.mgutility; + +public final class CampingModePolicyTest { + public static void main(String[] args) { + assertEquals(0, CampingModePolicy.clampDimPercent(-1), "dim lower bound"); + assertEquals(0, CampingModePolicy.clampDimPercent(0), "zero dim"); + assertEquals(47, CampingModePolicy.clampDimPercent(47), "dim value preserved"); + assertEquals(90, CampingModePolicy.clampDimPercent(100), "dim upper bound"); + + assertEquals(0, CampingModePolicy.clampTimeoutSeconds(-1), "negative timeout means never"); + assertEquals(0, CampingModePolicy.clampTimeoutSeconds(0), "zero timeout means never"); + assertEquals(5, CampingModePolicy.clampTimeoutSeconds(1), "short timeout minimum"); + assertEquals(300, CampingModePolicy.clampTimeoutSeconds(300), "timeout value preserved"); + assertEquals(600, CampingModePolicy.clampTimeoutSeconds(900), "timeout upper bound"); + + assertFalse(CampingModePolicy.isBlackoutDue(false, 30, 1000L, 31000L), "disabled mode never blacks out"); + assertFalse(CampingModePolicy.isBlackoutDue(true, 0, 1000L, 100000L), "zero timeout never blacks out"); + assertFalse(CampingModePolicy.isBlackoutDue(true, 15, 1000L, 15999L), "before deadline stays visible"); + assertTrue(CampingModePolicy.isBlackoutDue(true, 15, 1000L, 16000L), "deadline blacks out"); + assertFalse(CampingModePolicy.isBlackoutDue(true, 15, 1000L, 999L), "clock reset stays visible"); + System.out.println("CampingModePolicyTest: OK"); + } + + private static void assertEquals(int expected, int actual, String label) { + if (expected != actual) throw new AssertionError(label + ": expected " + expected + ", got " + actual); + } + + private static void assertTrue(boolean value, String label) { + if (!value) throw new AssertionError(label); + } + + private static void assertFalse(boolean value, String label) { + if (value) throw new AssertionError(label); + } +} diff --git a/tests/HermesTranscriptionClientTest.java b/tests/HermesTranscriptionClientTest.java new file mode 100644 index 0000000..a987b3b --- /dev/null +++ b/tests/HermesTranscriptionClientTest.java @@ -0,0 +1,96 @@ +package cloud.molberg.mgutility; + +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public final class HermesTranscriptionClientTest { + public static void main(String[] args) throws Exception { + Constructor constructor = HermesConfig.class.getDeclaredConstructor( + boolean.class, String.class, String.class, String.class); + constructor.setAccessible(true); + HermesConfig config = constructor.newInstance(true, "http://hermes.invalid", "hermes-secret", "session"); + config.transcriptionKey = "speech-secret"; + config.transcriptionModel = "local-whisper"; + Method request = HermesTranscriptionClient.class.getDeclaredMethod("request", HermesConfig.class, File.class); + request.setAccessible(true); + final AtomicReference payload = new AtomicReference(); + final AtomicReference authorization = new AtomicReference(); + final AtomicReference contentType = new AtomicReference(); + final AtomicInteger redirected = new AtomicInteger(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/transcribe", exchange -> { + authorization.set(exchange.getRequestHeaders().getFirst("Authorization")); + contentType.set(exchange.getRequestHeaders().getFirst("Content-Type")); + try (InputStream input = exchange.getRequestBody(); ByteArrayOutputStream body = new ByteArrayOutputStream()) { + byte[] buffer = new byte[4096]; + int count; + while ((count = input.read(buffer)) != -1) body.write(buffer, 0, count); + payload.set(new String(body.toByteArray(), StandardCharsets.UTF_8)); + } + exchange.sendResponseHeaders(401, -1); + exchange.close(); + }); + server.createContext("/redirect", exchange -> { + exchange.getResponseHeaders().set("Location", "/destination"); + exchange.sendResponseHeaders(307, -1); + exchange.close(); + }); + server.createContext("/destination", exchange -> { + redirected.incrementAndGet(); + exchange.sendResponseHeaders(500, -1); + exchange.close(); + }); + File audio = File.createTempFile("hermes-test-", ".m4a"); + Files.write(audio.toPath(), "test-audio".getBytes(StandardCharsets.UTF_8)); + server.start(); + try { + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + config.transcriptionUrl = base + "/transcribe"; + expectStatus(request, config, audio, 401); + require("Bearer speech-secret".equals(authorization.get()), "Separate speech credentials"); + require(!payload.get().contains("hermes-secret"), "Hermes key must not leak"); + require(payload.get().contains("name=\"model\"\r\n\r\nlocal-whisper\r\n"), "Model field"); + require(payload.get().contains("filename=\"speech.m4a\""), "Audio filename"); + require(payload.get().contains("Content-Type: audio/mp4\r\n\r\ntest-audio"), "Audio payload"); + String boundary = contentType.get().split("boundary=")[1]; + require(payload.get().endsWith("\r\n--" + boundary + "--\r\n"), "Closing boundary"); + config.transcriptionKey = ""; + expectStatus(request, config, audio, 401); + require(authorization.get() == null, "Unauthenticated local server"); + config.transcriptionUrl = base + "/redirect"; + expectStatus(request, config, audio, 307); + require(redirected.get() == 0, "Do not redirect audio or credentials"); + } finally { + server.stop(0); + audio.delete(); + } + require("system".equals(HermesConfig.normalizeVoiceEngine("system")), "System voice engine"); + require("sherpa_onnx".equals(HermesConfig.normalizeVoiceEngine("sherpa_onnx")), "Sherpa voice engine"); + require("upload".equals(HermesConfig.normalizeVoiceEngine("upload")), "Upload voice engine"); + require("system".equals(HermesConfig.normalizeVoiceEngine("unknown")), "Unknown voice engine defaults safely"); + System.out.println("HermesTranscriptionClientTest: OK"); + } + + private static void expectStatus(Method request, HermesConfig config, File audio, int status) throws Exception { + try { + request.invoke(null, config, audio); + throw new AssertionError("Expected HTTP error"); + } catch (InvocationTargetException error) { + require(error.getCause().getMessage().contains("HTTP " + status), "Actionable HTTP error"); + } + } + + private static void require(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tests/LiquidAudioIntegrationTest.java b/tests/LiquidAudioIntegrationTest.java new file mode 100644 index 0000000..8f2cdb9 --- /dev/null +++ b/tests/LiquidAudioIntegrationTest.java @@ -0,0 +1,78 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.os.SystemClock; + +public final class LiquidAudioIntegrationTest { + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + private static void tick(Context context, float distance, boolean active, int samples) { + for (int index = 0; index < samples; index++) { + SystemClock.now += 1000L; + AdaptiveAudioLevelingManager.updateSpeed(context, 60f, distance, active); + } + } + + public static void main(String[] args) { + Context context = new Context(); + MgServiceBridge bridge = MgServiceBridge.get(); + LiquidSoundBalanceManager.Config defaults = LiquidSoundBalanceManager.config(context); + check(defaults.anchorX == 7 && defaults.anchorY == 7 && !defaults.volumeBoost, "safe migration defaults"); + LiquidSoundBalanceManager.save(context, true, 1.5f, 65, true, true, 3, 11, false, true, 50); + LiquidSoundBalanceManager.save(context, false, 1.5f, 65, true, true); + LiquidSoundBalanceManager.Config saved = LiquidSoundBalanceManager.config(context); + check(!saved.enabled && saved.anchorX == 3 && saved.anchorY == 11 && saved.volumeBoost && saved.boostPercent == 50, + "control-panel toggle preserves anchors and boost preferences"); + LiquidSoundBalanceManager.save(context, true, 1f, 100, true, true, -1, 99, false, true, 200); + saved = LiquidSoundBalanceManager.config(context); + check(saved.anchorX == 0 && saved.anchorY == 14 && saved.boostPercent == 100, "persisted settings are clamped"); + + tick(context, 1.5f, true, 20); + check(bridge.volume == 15, "distance boost reaches 150% without compounding on each poll"); + tick(context, 1f, true, 20); + check(bridge.volume == 10, "settling returns exactly to base volume"); + tick(context, 1.5f, true, 20); + bridge.volume = 18; + tick(context, 1.5f, true, 1); + check(bridge.volume == 18, "manual volume is not immediately overwritten"); + tick(context, 1f, true, 20); + check(bridge.volume == 12, "manual change updates the base, not the boosted value"); + tick(context, 1.5f, true, 20); + tick(context, 1f, false, 1); + check(bridge.volume == 12, "disabling compensation restores latest base"); + + bridge.volume = 10; + AdaptiveAudioLevelingManager.save(context, true, 120, 20, 120, 70, 120, 110); + tick(context, 1.5f, true, 20); + check(bridge.volume == 18, "speed and position boosts share one base reference"); + tick(context, 1f, false, 20); + check(bridge.volume == 12, "disabling distance boost leaves speed leveling intact"); + AdaptiveAudioLevelingManager.save(context, false, 120, 20, 120, 70, 120, 110); + check(bridge.volume == 10, "disabling both restores original base"); + + bridge.volume = 0; + tick(context, 2f, true, 10); + check(bridge.volume == 0, "compensation does not unmute"); + tick(context, 1f, false, 1); + bridge.volume = 15; + tick(context, 2f, true, 20); + check(bridge.volume == 20, "boost never exceeds hardware maximum"); + bridge.failWrites = true; + tick(context, 1f, false, 1); + check(bridge.volume == 20, "failed restore does not claim success"); + bridge.failWrites = false; + tick(context, 1f, false, 1); + check(bridge.volume == 15, "failed restore retains base for retry"); + + bridge.volume = 10; + tick(context, 1.5f, true, 20); + bridge.failReads = true; + tick(context, 1f, false, 1); + bridge.failReads = false; + tick(context, 1f, false, 1); + check(bridge.volume == 10, "unavailable mixer retains restoration reference"); + System.out.println("LiquidAudioIntegrationTest: OK"); + } +} diff --git a/tests/LiquidSoundBalanceCurveTest.java b/tests/LiquidSoundBalanceCurveTest.java new file mode 100644 index 0000000..f4374c8 --- /dev/null +++ b/tests/LiquidSoundBalanceCurveTest.java @@ -0,0 +1,118 @@ +import cloud.molberg.mgutility.LiquidSoundBalanceCurve; +import cloud.molberg.mgutility.LiquidSoundBalanceMotion; + +public final class LiquidSoundBalanceCurveTest { + private static void check(boolean ok, String message) { + if (!ok) throw new AssertionError(message); + } + + private static void advance(LiquidSoundBalanceMotion motion, float acceleration, float speed, + float steering, boolean sway, boolean bounce, int anchorX, int anchorY, int samples) { + for (int index = 0; index < samples; index++) { + motion.update(acceleration, speed, steering, 1f, 100, sway, false, bounce, + anchorX, anchorY, 0.1f); + check(motion.balance(anchorX) >= 0 && motion.balance(anchorX) <= 14, "X stays in OEM range"); + check(motion.fader(anchorY) >= 0 && motion.fader(anchorY) <= 14, "Y stays in OEM range"); + } + } + + public static void main(String[] args) { + check(LiquidSoundBalanceCurve.parseSteering("-520.0000") == -520f, "right lock property parses"); + check(LiquidSoundBalanceCurve.parseSteering("+520.0000") == 520f, "left lock property parses"); + check(LiquidSoundBalanceCurve.parseSteering("0.0000") == 0f, "center property parses"); + for (String invalid : new String[] {null, "", "NaN", "Infinity", "-521", "521", "unavailable"}) { + check(Float.isNaN(LiquidSoundBalanceCurve.parseSteering(invalid)), "invalid property fails neutral"); + } + check(LiquidSoundBalanceCurve.volumeMultiplier(7, 7, 7, 7, true, 100) == 1f, "no volume boost at center"); + check(LiquidSoundBalanceCurve.volumeMultiplier(3, 11, 3, 11, true, 100) == 1f, "no boost at custom anchor"); + check(LiquidSoundBalanceCurve.volumeMultiplier(7, 14, 7, 7, true, 50) == 1.5f, "rear endpoint gets selected boost"); + check(LiquidSoundBalanceCurve.volumeMultiplier(7, 0, 7, 7, true, 50) == 1.5f, "front endpoint gets selected boost"); + check(LiquidSoundBalanceCurve.volumeMultiplier(0, 0, 7, 7, true, 50) == 1.5f, "corners never exceed selected boost"); + check(LiquidSoundBalanceCurve.volumeMultiplier(8, 8, 7, 7, true, 50) > + LiquidSoundBalanceCurve.volumeMultiplier(8, 7, 7, 7, true, 50), "diagonal distance increases compensation"); + check(LiquidSoundBalanceCurve.volumeMultiplier(0, 14, 7, 7, false, 100) == 1f, "disabled compensation is neutral"); + check(LiquidSoundBalanceCurve.volumeMultiplier(-1, 14, 7, 7, true, 100) == 1f, "unknown actual position cannot boost"); + check(LiquidSoundBalanceCurve.volumeMultiplier(0, 14, 7, 7, true, 0) == 1f, "zero slider cannot boost"); + for (int step = 0; step < 7; step++) { + check(LiquidSoundBalanceCurve.volumeMultiplier(7, 7 + step, 7, 7, true, 50) < + LiquidSoundBalanceCurve.volumeMultiplier(7, 8 + step, 7, 7, true, 50), "boost grows with distance"); + } + check(LiquidSoundBalanceCurve.targetFader(0f, 1f, 100) == 0, "stationary has no longitudinal force"); + check(LiquidSoundBalanceCurve.targetFader(0.2f, 1f, 100) == 0, "small fluctuations ignored"); + check(LiquidSoundBalanceCurve.targetFader(1f, 1f, 100) > 0, "acceleration moves rearward"); + check(LiquidSoundBalanceCurve.targetFader(-1f, 1f, 100) < 0, "braking moves forward"); + check(LiquidSoundBalanceCurve.targetFader(20f, 1f, 100) == 7, "full movement limited to seven steps"); + check(LiquidSoundBalanceCurve.targetFader(20f, 1f, 0) == 0, "zero power disables movement"); + check(LiquidSoundBalanceCurve.targetFader(Float.NaN, 1f, 100) == 0, "invalid acceleration ignored"); + check(LiquidSoundBalanceCurve.positionForOffset(0) == 7, "default OEM center is seven"); + check(LiquidSoundBalanceCurve.positionForOffset(3, 0) == 3, "custom anchor is preserved"); + check(LiquidSoundBalanceCurve.positionForOffset(3, -7) == 0, "custom anchor clips at left edge"); + check(LiquidSoundBalanceCurve.positionForOffset(12, 7) == 14, "custom anchor clips at right edge"); + check(LiquidSoundBalanceCurve.positionForOffset(Integer.MIN_VALUE) == 0, "negative overflow avoided"); + check(LiquidSoundBalanceCurve.positionForOffset(Integer.MAX_VALUE) == 14, "positive overflow avoided"); + + float gentle = LiquidSoundBalanceCurve.lateralAcceleration(30f, 10f, false); + float faster = LiquidSoundBalanceCurve.lateralAcceleration(60f, 10f, false); + check(gentle > 0f, "positive-left steering pushes audio right"); + check(Math.abs(faster - 4f * gentle) < 0.001f, "cornering force scales with speed squared"); + check(LiquidSoundBalanceCurve.lateralAcceleration(30f, 20f, false) > gentle, "tighter turn increases force"); + check(LiquidSoundBalanceCurve.lateralAcceleration(30f, -10f, false) == -gentle, "right turn pushes audio left"); + check(LiquidSoundBalanceCurve.lateralAcceleration(30f, 10f, true) == -gentle, "direction calibration reverses sign"); + check(LiquidSoundBalanceCurve.lateralAcceleration(0f, 500f, false) == 0f, "parked steering causes no sway"); + check(LiquidSoundBalanceCurve.lateralAcceleration(90f, 0f, false) == 0f, "straight cruising causes no sway"); + check(LiquidSoundBalanceCurve.lateralAcceleration(90f, Float.NaN, false) == 0f, "missing steering is neutral"); + check(LiquidSoundBalanceCurve.lateralAcceleration(90f, 65535f, false) == 0f, "invalid steering sentinel ignored"); + check(LiquidSoundBalanceCurve.lateralAcceleration(Float.POSITIVE_INFINITY, 20f, false) == 0f, "invalid speed ignored"); + + LiquidSoundBalanceMotion motion = new LiquidSoundBalanceMotion(); + advance(motion, 0f, 60f, 30f, true, true, 7, 7, 40); + check(motion.balance(7) > 7, "steady left turn maintains outward X displacement without accelerating"); + check(motion.fader(7) == 7, "cornering does not move Y"); + int sustained = motion.balance(7); + advance(motion, 0f, 60f, 30f, true, true, 7, 7, 40); + check(motion.balance(7) == sustained, "steady turn does not oscillate on a timer"); + advance(motion, 0f, 60f, -30f, true, true, 7, 7, 40); + check(motion.balance(7) < 7, "opposite turn changes outward direction"); + advance(motion, 0f, 60f, Float.NaN, true, true, 7, 7, 1); + check(motion.balance(7) == 7, "lost steering immediately locks X to anchor"); + advance(motion, 5f, 60f, 0f, true, true, 7, 7, 40); + check(motion.balance(7) == 7 && motion.fader(7) > 7, "straight acceleration only moves Y"); + advance(motion, -5f, 60f, 30f, false, true, 3, 10, 40); + check(motion.balance(3) == 3 && motion.fader(10) < 10, "disabled sway locks custom X while braking moves Y"); + + for (int anchor = 0; anchor <= 14; anchor++) { + for (boolean bounce : new boolean[] {false, true}) { + motion.reset(); + advance(motion, 20f, 100f, 500f, true, bounce, anchor, 14 - anchor, 30); + advance(motion, -20f, 100f, -500f, true, bounce, anchor, 14 - anchor, 30); + advance(motion, 0f, 0f, 0f, true, bounce, anchor, 14 - anchor, 100); + check(motion.balance(anchor) == anchor, "X settles exactly at every custom anchor"); + check(motion.fader(14 - anchor) == 14 - anchor, "Y settles exactly at every custom anchor"); + } + } + motion.reset(); + advance(motion, 4f, 60f, 30f, true, true, 4, 9, 20); + motion.update(4f, 60f, 30f, 1f, 0, true, false, true, 4, 9, 0.1f); + check(motion.balance(4) == 4 && motion.fader(9) == 9, "zero power resets both axes immediately"); + advance(motion, 4f, 60f, 30f, true, true, 4, 9, 20); + motion.update(4f, 60f, 30f, 1f, 100, true, false, true, 4, 9, 5f); + check(motion.balance(4) == 4 && motion.fader(9) == 9, "long polling gap clears stale momentum"); + for (boolean bounce : new boolean[] {false, true}) { + motion.reset(); + advance(motion, 2f, 60f, 0f, false, bounce, 7, 7, 50); + boolean crossedAnchor = false; + for (int index = 0; index < 80; index++) { + advance(motion, 0f, 60f, 0f, false, bounce, 7, 7, 1); + crossedAnchor |= motion.fader(7) < 7; + } + check(crossedAnchor == bounce, "only bounce mode rebounds across the anchor"); + } + motion.reset(); + for (int index = 0; index < 100; index++) { + motion.update(20f, 100f, 520f, 1f, 30, true, false, true, 3, 3, 0.1f); + check(Math.abs(motion.balance(3) - 3) <= 2 && Math.abs(motion.fader(3) - 3) <= 2, + "spring overshoot respects the selected power limit"); + } + System.out.println("LiquidSoundBalanceCurveTest: OK"); + } +} diff --git a/tests/PluginMarketplaceTest.java b/tests/PluginMarketplaceTest.java new file mode 100644 index 0000000..e1348af --- /dev/null +++ b/tests/PluginMarketplaceTest.java @@ -0,0 +1,14 @@ +import cloud.molberg.mgutility.plugin.*; +import java.util.*; + +public final class PluginMarketplaceTest { + public static void main(String[] args) throws Exception { + PluginMarketplace marketplace = new PluginMarketplace(); + final PluginRepository repo = new PluginRepository("test", "Test", "https://example.test/index.json", true, false); + marketplace.addRepository(repo); + marketplace.refresh(new PluginMarketplace.RepositoryClient() { public PluginRepositoryIndex fetch(PluginRepository r) { return new PluginRepositoryIndex(1, Arrays.asList(new PluginCatalogEntry("demo", "Demo", "1.0.0", "", "https://example.test/demo.apk", "", "", ""), new PluginCatalogEntry("demo", "Demo", "2.0.0", "", "https://example.test/demo.apk", "", "", ""))); } }); + if (marketplace.available("1.0.0").size() != 1 || !"2.0.0".equals(marketplace.available("1.0.0").get(0).version)) throw new AssertionError("version selection"); + if (!PluginSignatureVerifier.matches("hello".getBytes("UTF-8"), PluginSignatureVerifier.sha256("hello".getBytes("UTF-8")))) throw new AssertionError("checksum"); + System.out.println("PluginMarketplaceTest: OK"); + } +} diff --git a/tests/PluginSdkTest.java b/tests/PluginSdkTest.java new file mode 100644 index 0000000..461f914 --- /dev/null +++ b/tests/PluginSdkTest.java @@ -0,0 +1,28 @@ +import cloud.molberg.mgutility.sdk.*; +import cloud.molberg.mgutility.plugin.*; + +public final class PluginSdkTest { + public static void main(String[] args) { + PluginManifest m = PluginManifestParser.parse("{\"schema\":1,\"id\":\"demo.plugin\",\"name\":\"Demo\",\"versionName\":\"1.2.0\",\"entryPoint\":\"Demo\",\"permissions\":[\"audio\"],\"capabilities\":[\"AUDIO_PLAYBACK\",\"DASHBOARD\"]}"); + if (!"demo.plugin".equals(m.id) || m.permissions.size() != 1) throw new AssertionError("manifest parse"); + if (!m.requests(PluginCapability.AUDIO_PLAYBACK) || m.requests(PluginCapability.KEY_REMAP)) throw new AssertionError("manifest capabilities"); + boolean rejected = false; + try { PluginManifestParser.parse("{\"schema\":99,\"id\":\"demo.plugin\",\"entry\":\"Demo\"}"); } + catch (IllegalArgumentException expected) { rejected = true; } + if (!rejected) throw new AssertionError("manifest schema validation"); + InMemoryContributionRegistry contributions = new InMemoryContributionRegistry(); + contributions.register(new Contribution("tile", Contribution.Type.HOME_TILE, "Tile", "", null)); + if (contributions.all().size() != 1) throw new AssertionError("contribution registry"); + if (!new VersionRange("1.0.0", "2.0.0").contains("1.4.1")) throw new AssertionError("version range"); + final int[] events = {0}; + InMemoryHookRegistry hooks = new InMemoryHookRegistry(); + InMemoryHookRegistry.Listener listener = new InMemoryHookRegistry.Listener() { public void onEvent(String hook, Object payload) { events[0]++; } }; + hooks.subscribe("vehicle.data", listener); hooks.publish("vehicle.data", null); hooks.unsubscribe("vehicle.data", listener); hooks.publish("vehicle.data", null); + if (events[0] != 1) throw new AssertionError("hook registry"); + final int[] typed = {0}; + hooks.subscribe(PluginHook.SPEED_CHANGED, new HookRegistry.TypedListener() { public void onEvent(PluginHook hook, HookEvent event) { if (event.getDouble("speedKph", -1) == 42.5) typed[0]++; } }); + java.util.Map speed = new java.util.HashMap(); speed.put("speedKph", 42.5); hooks.publish(HookEvent.now(PluginHook.SPEED_CHANGED, speed)); + if (typed[0] != 1 || PluginHook.fromId("vehicle.speed_changed") != PluginHook.SPEED_CHANGED) throw new AssertionError("typed hooks"); + System.out.println("PluginSdkTest: OK"); + } +} diff --git a/tests/PushToTalkPressTest.java b/tests/PushToTalkPressTest.java new file mode 100644 index 0000000..9193ac3 --- /dev/null +++ b/tests/PushToTalkPressTest.java @@ -0,0 +1,35 @@ +package cloud.molberg.mgutility; + +public final class PushToTalkPressTest { + public static void main(String[] args) { + PushToTalkPress press = new PushToTalkPress(); + require(!press.end(1, 42, 120, 100), "Ignore orphan release"); + require(press.begin(1, 42, 120, 100, 0), "Start on initial down"); + require(!press.begin(1, 42, 120, 100, 0), "Duplicate down must not restart recording"); + require(!press.begin(1, 42, 120, 100, 1), "Repeat must not restart recording"); + require(press.matches(1, 42, 120, 100), "Repeat remains consumed"); + require(!press.end(2, 42, 120, 100), "Other input device cannot release"); + require(!press.end(1, 43, 121, 100), "Other key cannot release"); + require(!press.end(1, 42, 120, 99), "Stale release cannot end current press"); + require(press.end(1, 0, 120, 100), "OEM unknown keycode release matches actual scan code"); + require(!press.end(1, 42, 120, 100), "Submit only once"); + require(press.begin(1, 42, 120, 200, 0), "Next turn starts immediately"); + require(press.end(1, 42, 0, 200), "Release with omitted scan code matches actual key"); + require(press.begin(1, 0, 120, 300, 0), "Unknown key down is supported"); + require(press.end(1, 42, 120, 300), "Mapped keycode can change on up"); + require(!press.begin(1, 42, 120, 400, 2), "Orphan repeat cannot start"); + require(press.begin(1, 42, 120, 500, 0), "Start before cancellation"); + press.clear(); + require(!press.end(1, 42, 120, 500), "Cancelled press cannot submit"); + require(press.begin(1, 42, 120, 600, 0), "Restart after cancellation"); + require(!press.begin(2, 42, 120, 700, 0), "Other device cannot replace a held key"); + require(press.begin(1, 42, 120, 800, 0), "Recover when previous release was lost"); + require(!press.end(1, 42, 120, 600), "Delayed old release cannot submit new turn"); + require(press.end(1, 42, 120, 800), "Recovered turn releases normally"); + System.out.println("PushToTalkPressTest: OK"); + } + + private static void require(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tests/VehiclePowerOffControllerTest.java b/tests/VehiclePowerOffControllerTest.java new file mode 100644 index 0000000..458fd4a --- /dev/null +++ b/tests/VehiclePowerOffControllerTest.java @@ -0,0 +1,104 @@ +package cloud.molberg.mgutility; + +public final class VehiclePowerOffControllerTest { + private static final class FakeTransport implements VehiclePowerOffController.Transport { + boolean compatible = true; + int gear = 1; + int gearAfterSpeed = 1; + float speed; + boolean accepted = true; + boolean failRead; + boolean failSend; + int reads; + int writes; + + @Override public boolean isCompatible() { reads++; return compatible; } + @Override public int getGear() { + reads++; + if (failRead) throw new IllegalStateException("Disconnected"); + return gear; + } + @Override public float getSpeed() { reads++; gear = gearAfterSpeed; return speed; } + @Override public boolean sendPowerOff() { + writes++; + if (failSend) throw new IllegalStateException("Disconnected during send"); + return accepted; + } + } + + public static void main(String[] args) throws Exception { + FakeTransport transport = new FakeTransport(); + VehiclePowerOffController controller = new VehiclePowerOffController(transport); + check(transport.reads == 0 && transport.writes == 0, "Construction must not access the car"); + expect(VehiclePowerOffController.Result.CANCELLED, controller.request(false)); + check(transport.reads == 0 && transport.writes == 0, "Cancellation must not access the car"); + expect(VehiclePowerOffController.Result.REQUEST_SENT, controller.request(true)); + check(transport.writes == 1, "Confirmed stationary Park sends exactly once"); + expect(VehiclePowerOffController.Result.ALREADY_REQUESTED, controller.request(true)); + check(transport.writes == 1, "Duplicate confirmation must not resend"); + + expect(VehiclePowerOffController.Result.UNSUPPORTED, new VehiclePowerOffController(null).request(true)); + transport = new FakeTransport(); + transport.compatible = false; + blocked(transport, VehiclePowerOffController.Result.UNSUPPORTED); + for (int gear : new int[] { -1, 0, 2, 3, 4, 255 }) { + transport = new FakeTransport(); + transport.gear = gear; + blocked(transport, VehiclePowerOffController.Result.NOT_PARKED); + } + for (float speed : new float[] { Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, + -1f, -0.01f, 0.01f, 1f, 100f }) { + transport = new FakeTransport(); + transport.speed = speed; + blocked(transport, VehiclePowerOffController.Result.NOT_STATIONARY); + } + transport = new FakeTransport(); + transport.gearAfterSpeed = 4; + blocked(transport, VehiclePowerOffController.Result.NOT_PARKED); + transport = new FakeTransport(); + transport.failRead = true; + blocked(transport, VehiclePowerOffController.Result.FAILED); + + for (boolean throwOnSend : new boolean[] { false, true }) { + transport = new FakeTransport(); + transport.accepted = false; + transport.failSend = throwOnSend; + controller = new VehiclePowerOffController(transport); + expect(VehiclePowerOffController.Result.FAILED, controller.request(true)); + expect(VehiclePowerOffController.Result.ALREADY_REQUESTED, controller.request(true)); + check(transport.writes == 1, "Uncertain delivery must not retry"); + } + + transport = new FakeTransport(); + controller = new VehiclePowerOffController(transport); + transport.gear = 4; + expect(VehiclePowerOffController.Result.NOT_PARKED, controller.request(true)); + transport.gear = 1; + expect(VehiclePowerOffController.Result.REQUEST_SENT, controller.request(true)); + check(transport.writes == 1, "A new confirmation rereads live state after a blocked attempt"); + + final FakeTransport concurrentTransport = new FakeTransport(); + final VehiclePowerOffController concurrentController = new VehiclePowerOffController(concurrentTransport); + Runnable request = new Runnable() { + @Override public void run() { concurrentController.request(true); } + }; + Thread first = new Thread(request); + Thread second = new Thread(request); + first.start(); second.start(); first.join(); second.join(); + check(concurrentTransport.writes == 1, "Concurrent confirmations must not duplicate writes"); + System.out.println("VehiclePowerOffControllerTest: OK"); + } + + private static void blocked(FakeTransport transport, VehiclePowerOffController.Result expected) { + expect(expected, new VehiclePowerOffController(transport).request(true)); + check(transport.writes == 0, "Blocked state must never send a power request"); + } + + private static void expect(VehiclePowerOffController.Result expected, VehiclePowerOffController.Result actual) { + check(expected == actual, "Expected " + expected + ", got " + actual); + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tests/VehiclePowerOffGatewayTest.java b/tests/VehiclePowerOffGatewayTest.java new file mode 100644 index 0000000..600c53f --- /dev/null +++ b/tests/VehiclePowerOffGatewayTest.java @@ -0,0 +1,92 @@ +package cloud.molberg.mgutility; + +import android.os.IBinder; +import android.os.Parcel; + +public final class VehiclePowerOffGatewayTest { + private static final class FakeService implements IBinder { + final String token; + String descriptor; + int gear = 1; + float speed; + int writes; + boolean available = true; + boolean accepted = true; + + FakeService(String token) { this.token = token; descriptor = token; } + @Override public String getInterfaceDescriptor() { return descriptor; } + @Override public boolean transact(int code, Parcel data, Parcel reply, int flags) { + check(token.equals(data.readString()), "Interface token must match OEM ABI"); + if (!available) return false; + if (VehicleSettingsGateway.SETTING_TOKEN.equals(token)) { + check(code == 0xad, "Only the OEM power-off transaction may be sent"); + check(flags == IBinder.FLAG_ONEWAY && reply == null, "Power request must be one-way without reply"); + check(data.readInt() == 2, "OEM power-off payload must be integer 2"); + writes++; + return accepted; + } + check(flags == 0 && reply != null, "Telemetry must be synchronous"); + reply.writeNoException(); + if (code == 0x05) reply.writeInt(gear); + else if (code == 0x03) reply.writeFloat(speed); + else throw new AssertionError("Unexpected telemetry transaction: " + code); + return true; + } + } + + private static VehicleSettingsGateway gateway(final FakeService setting, final FakeService condition) { + return new VehicleSettingsGateway(new IBinder() { + @Override public String getInterfaceDescriptor() { return VehicleSettingsGateway.HUB_TOKEN; } + @Override public boolean transact(int code, Parcel data, Parcel reply, int flags) { + check(code == 1 && flags == 0, "Hub lookup transaction"); + check(VehicleSettingsGateway.HUB_TOKEN.equals(data.readString()), "Hub token"); + String service = data.readString(); + reply.writeNoException(); + reply.writeStrongBinder("vehiclesetting".equals(service) ? setting + : "vehiclecondition".equals(service) ? condition : null); + return true; + } + }); + } + + public static void main(String[] args) { + FakeService setting = new FakeService(VehicleSettingsGateway.SETTING_TOKEN); + FakeService condition = new FakeService(VehicleSettingsGateway.CONDITION_TOKEN); + VehicleSettingsGateway gateway = gateway(setting, condition); + String version = VehiclePowerOffController.SUPPORTED_SERVICE_VERSION; + expect(VehiclePowerOffController.Result.CANCELLED, gateway.powerOffController(version).request(false)); + for (String unsupported : new String[] { null, "", "mg4", "2022", "VehicleSettingsService.44042" }) { + expect(VehiclePowerOffController.Result.UNSUPPORTED, gateway.powerOffController(unsupported).request(true)); + } + setting.descriptor = "unknown"; + expect(VehiclePowerOffController.Result.UNSUPPORTED, gateway.powerOffController(version).request(true)); + setting.descriptor = setting.token; + condition.descriptor = "unknown"; + expect(VehiclePowerOffController.Result.UNSUPPORTED, gateway.powerOffController(version).request(true)); + condition.descriptor = condition.token; + condition.available = false; + expect(VehiclePowerOffController.Result.NOT_PARKED, gateway.powerOffController(version).request(true)); + condition.available = true; + condition.speed = Float.NaN; + expect(VehiclePowerOffController.Result.NOT_STATIONARY, gateway.powerOffController(version).request(true)); + check(setting.writes == 0, "Blocked/cancelled requests never reach the setter"); + condition.speed = 0f; + VehiclePowerOffController controller = gateway.powerOffController(version); + expect(VehiclePowerOffController.Result.REQUEST_SENT, controller.request(true)); + expect(VehiclePowerOffController.Result.ALREADY_REQUESTED, controller.request(true)); + check(setting.writes == 1, "Exactly one correctly encoded request"); + setting.accepted = false; + expect(VehiclePowerOffController.Result.FAILED, gateway.powerOffController(version).request(true)); + expect(VehiclePowerOffController.Result.UNSUPPORTED, gateway(null, condition).powerOffController(version).request(true)); + expect(VehiclePowerOffController.Result.UNSUPPORTED, gateway(setting, null).powerOffController(version).request(true)); + System.out.println("VehiclePowerOffGatewayTest: OK"); + } + + private static void expect(VehiclePowerOffController.Result expected, VehiclePowerOffController.Result actual) { + check(expected == actual, "Expected " + expected + ", got " + actual); + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tests/VehicleSettingsCoordinatorTest.java b/tests/VehicleSettingsCoordinatorTest.java index ab9b617..25e328d 100644 --- a/tests/VehicleSettingsCoordinatorTest.java +++ b/tests/VehicleSettingsCoordinatorTest.java @@ -62,12 +62,31 @@ public final class VehicleSettingsCoordinatorTest { List partialResults = partialCoordinator.applyStartup("partial"); check(partialResults.size() == 2 && partial.writes == 2, "failed setting does not block independent setting"); - Car moving = new Car(); moving.applyQueued = true; moving.speed = 2f; - VehicleSettingsApplyCoordinator blocked = new VehicleSettingsApplyCoordinator(fresh, moving, VehicleSettingsProfile.known()); - check(blocked.applyStartup("moving-check").size() == 2 && moving.writes == 0, "moving vehicle produces no writes"); + Store movingStore = new Store(); + restore(movingStore, "drive_mode", 4); restore(movingStore, "regenerative_level", 2); + Car moving = new Car(); moving.applyQueued = true; moving.speed = 50f; moving.gear = 4; + moving.current.put("drive_mode", 3); moving.current.put("regenerative_level", 1); + VehicleSettingsApplyCoordinator movingCoordinator = new VehicleSettingsApplyCoordinator(movingStore, moving, VehicleSettingsProfile.known()); + List movingResults = movingCoordinator.applyStartup("moving-check"); + check(movingResults.size() == 2 && moving.writes == 2, "startup writes while in gear and moving"); + for (VehicleSettingsApplyCoordinator.Result result : movingResults) + check(result.status == VehicleSettingsApplyCoordinator.Status.VERIFIED, "moving startup read-back matches"); + check(movingCoordinator.applyStartup("moving-check").isEmpty() && moving.writes == 2, + "moving startup still deduplicates the ignition session"); + moving.current.put("drive_mode", 3); moving.current.put("regenerative_level", 1); + List movingManual = movingCoordinator.applyStartupNow(); + check(movingManual.size() == 2 && moving.writes == 4, "manual startup writes while in gear and moving"); + for (VehicleSettingsApplyCoordinator.Result result : movingManual) + check(result.status == VehicleSettingsApplyCoordinator.Status.VERIFIED, "moving manual read-back matches"); + moving.gear = -1; moving.speed = Float.NaN; + moving.current.put("drive_mode", 3); moving.current.put("regenerative_level", 1); + check(movingCoordinator.applyStartup("missing-motion").size() == 2 && moving.writes == 6, + "startup does not depend on gear or speed telemetry"); Car unknownState = new Car(); unknownState.ignition = -1; VehicleSettingsApplyCoordinator unknownStateCoordinator = new VehicleSettingsApplyCoordinator(fresh, unknownState, VehicleSettingsProfile.known()); check(unknownStateCoordinator.applyStartup("unknown-state").size() == 2 && unknownState.writes == 0, "unknown ignition produces no writes"); + check(unknownStateCoordinator.applyStartupNow().size() == 2 && unknownState.writes == 0, + "manual startup still requires ignition readiness"); Car experimental = new Car(); experimental.applyQueued = true; experimental.current.put("regenerative_level", 2); Store experimentalStore = new Store(); experimentalStore.ack = VehicleSettingsProfile.MG4_LUXURY_2022 + ":1"; diff --git a/tests/audio-stubs/android/content/Context.java b/tests/audio-stubs/android/content/Context.java new file mode 100644 index 0000000..aec91e3 --- /dev/null +++ b/tests/audio-stubs/android/content/Context.java @@ -0,0 +1,35 @@ +package android.content; + +import java.util.HashMap; +import java.util.Map; + +public class Context { + public static final int MODE_PRIVATE = 0; + public static final String AUDIO_SERVICE = "audio"; + private final Map preferences = new HashMap<>(); + + public Context getApplicationContext() { return this; } + public Object getSystemService(String name) { return null; } + public SharedPreferences getSharedPreferences(String name, int mode) { + if (!preferences.containsKey(name)) preferences.put(name, new MemoryPreferences()); + return preferences.get(name); + } + + private static final class MemoryPreferences implements SharedPreferences, SharedPreferences.Editor { + private final Map values = new HashMap<>(); + public boolean getBoolean(String key, boolean fallback) { + return values.containsKey(key) ? (Boolean) values.get(key) : fallback; + } + public int getInt(String key, int fallback) { + return values.containsKey(key) ? (Integer) values.get(key) : fallback; + } + public float getFloat(String key, float fallback) { + return values.containsKey(key) ? (Float) values.get(key) : fallback; + } + public SharedPreferences.Editor edit() { return this; } + public SharedPreferences.Editor putBoolean(String key, boolean value) { values.put(key, value); return this; } + public SharedPreferences.Editor putInt(String key, int value) { values.put(key, value); return this; } + public SharedPreferences.Editor putFloat(String key, float value) { values.put(key, value); return this; } + public void apply() { } + } +} diff --git a/tests/audio-stubs/android/content/SharedPreferences.java b/tests/audio-stubs/android/content/SharedPreferences.java new file mode 100644 index 0000000..5e19ae3 --- /dev/null +++ b/tests/audio-stubs/android/content/SharedPreferences.java @@ -0,0 +1,15 @@ +package android.content; + +public interface SharedPreferences { + boolean getBoolean(String key, boolean fallback); + int getInt(String key, int fallback); + float getFloat(String key, float fallback); + Editor edit(); + + interface Editor { + Editor putBoolean(String key, boolean value); + Editor putInt(String key, int value); + Editor putFloat(String key, float value); + void apply(); + } +} diff --git a/tests/audio-stubs/android/media/AudioManager.java b/tests/audio-stubs/android/media/AudioManager.java new file mode 100644 index 0000000..98d9517 --- /dev/null +++ b/tests/audio-stubs/android/media/AudioManager.java @@ -0,0 +1,9 @@ +package android.media; + +public class AudioManager { + public static final int STREAM_MUSIC = 3; + public int getStreamMaxVolume(int stream) { return 20; } + public int getStreamMinVolume(int stream) { return 0; } + public int getStreamVolume(int stream) { return 10; } + public void setStreamVolume(int stream, int volume, int flags) { } +} diff --git a/tests/audio-stubs/android/os/Build.java b/tests/audio-stubs/android/os/Build.java new file mode 100644 index 0000000..b40d21c --- /dev/null +++ b/tests/audio-stubs/android/os/Build.java @@ -0,0 +1,7 @@ +package android.os; + +public final class Build { + public static final class VERSION { + public static final int SDK_INT = 28; + } +} diff --git a/tests/audio-stubs/android/os/SystemClock.java b/tests/audio-stubs/android/os/SystemClock.java new file mode 100644 index 0000000..ac90ef6 --- /dev/null +++ b/tests/audio-stubs/android/os/SystemClock.java @@ -0,0 +1,6 @@ +package android.os; + +public final class SystemClock { + public static long now = 10000L; + public static long elapsedRealtime() { return now; } +} diff --git a/tests/audio-stubs/cloud/molberg/mgutility/MgServiceBridge.java b/tests/audio-stubs/cloud/molberg/mgutility/MgServiceBridge.java new file mode 100644 index 0000000..b4e1866 --- /dev/null +++ b/tests/audio-stubs/cloud/molberg/mgutility/MgServiceBridge.java @@ -0,0 +1,21 @@ +package cloud.molberg.mgutility; + +import android.content.Context; + +final class MgServiceBridge { + static final int VOL_TYPE_MEDIA = 0; + private static final MgServiceBridge INSTANCE = new MgServiceBridge(); + int volume = 10; + boolean failWrites; + boolean failReads; + static MgServiceBridge get() { return INSTANCE; } + void ensureBound(Context context) { } + int getVolume(int type) { return failReads ? -1 : volume; } + int getMinVolume(int type) { return 0; } + int getMaxVolume(int type) { return 20; } + boolean setVolume(int type, int value) { + if (failWrites) return false; + volume = value; + return true; + } +} diff --git a/tests/run_hermes_tests.sh b/tests/run_hermes_tests.sh new file mode 100644 index 0000000..7645f8a --- /dev/null +++ b/tests/run_hermes_tests.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +SDK=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/opt/android-sdk}} +ANDROID_JAR=$(find "$SDK/platforms" -name android.jar -type f | sort -V | tail -n 1) +AAR="$ROOT/vendor/sherpa-onnx/sherpa-onnx-1.13.8.aar" +KOTLIN_STDLIB="$ROOT/vendor/sherpa-onnx/kotlin-stdlib-2.0.21.jar" +OUT=$(mktemp -d) +trap 'rm -rf "$OUT"' EXIT +if [ -f "$AAR" ]; then + unzip -q -o "$AAR" 'classes.jar' -d "$OUT/vendor" + mkdir -p "$OUT/sherpa-classes" + (cd "$OUT/sherpa-classes" && unzip -q -o "$OUT/vendor/classes.jar") + SHERPA_CP="$OUT/sherpa-classes:$KOTLIN_STDLIB" +else + SHERPA_CP="" +fi +javac -source 8 -target 8 -cp "$ANDROID_JAR:$SHERPA_CP" -d "$OUT" \ + "$ROOT/src/cloud/molberg/mgutility/HermesConfig.java" \ + "$ROOT/src/cloud/molberg/mgutility/HermesTranscriptionClient.java" \ + "$ROOT/tests/HermesTranscriptionClientTest.java" +java -cp "$OUT:$ANDROID_JAR" cloud.molberg.mgutility.HermesTranscriptionClientTest \ No newline at end of file diff --git a/tests/run_tests.sh b/tests/run_tests.sh index c4bcd3e..5bfa71e 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -4,16 +4,55 @@ ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) OUT=$(mktemp -d) trap 'rm -rf "$OUT"' EXIT javac -source 8 -target 8 -d "$OUT" \ + "$ROOT/src/cloud/molberg/mgutility/PushToTalkPress.java" "$ROOT/tests/PushToTalkPressTest.java" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsCatalog.java" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsProfile.java" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java" \ + "$ROOT/src/cloud/molberg/mgutility/VehiclePowerOffController.java" "$ROOT/tests/VehiclePowerOffControllerTest.java" \ "$ROOT/src/cloud/molberg/mgutility/SpeedAudioCurve.java" \ + "$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceCurve.java" \ + "$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceMotion.java" \ "$ROOT/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java" \ "$ROOT/tests/VehicleSettingsCatalogTest.java" "$ROOT/tests/VehicleSettingsCoordinatorTest.java" \ - "$ROOT/tests/SpeedAudioCurveTest.java" "$ROOT/tests/AdaptiveAudioCurveTest.java" "$ROOT/src/cloud/molberg/mgutility/BrightnessSchedule.java" \ - "$ROOT/tests/BrightnessScheduleTest.java" + "$ROOT/tests/SpeedAudioCurveTest.java" "$ROOT/tests/AdaptiveAudioCurveTest.java" "$ROOT/tests/LiquidSoundBalanceCurveTest.java" "$ROOT/src/cloud/molberg/mgutility/BrightnessSchedule.java" \ + "$ROOT/tests/BrightnessScheduleTest.java" \ + "$ROOT/src/cloud/molberg/mgutility/CampingModePolicy.java" "$ROOT/tests/CampingModePolicyTest.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/Plugin.java" "$ROOT/src/cloud/molberg/mgutility/sdk/PluginContext.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/ScopedPreferences.java" "$ROOT/src/cloud/molberg/mgutility/sdk/PluginLogger.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginCapability.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/Contribution.java" "$ROOT/src/cloud/molberg/mgutility/sdk/ContributionRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/HookRegistry.java" "$ROOT/src/cloud/molberg/mgutility/sdk/InMemoryContributionRegistry.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginHook.java" "$ROOT/src/cloud/molberg/mgutility/sdk/HookEvent.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/InMemoryHookRegistry.java" "$ROOT/src/cloud/molberg/mgutility/sdk/VersionRange.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginCapability.java" \ + "$ROOT/src/cloud/molberg/mgutility/sdk/PluginManifest.java" "$ROOT/src/cloud/molberg/mgutility/sdk/PluginManifestParser.java" \ + "$ROOT/src/cloud/molberg/mgutility/plugin/PluginRepository.java" "$ROOT/src/cloud/molberg/mgutility/plugin/PluginCatalogEntry.java" \ + "$ROOT/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndex.java" "$ROOT/src/cloud/molberg/mgutility/plugin/PluginMarketplace.java" \ + "$ROOT/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java" "$ROOT/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java" \ + "$ROOT/tests/PluginSdkTest.java" "$ROOT/tests/PluginMarketplaceTest.java" java -cp "$OUT" VehicleSettingsCatalogTest +java -cp "$OUT" cloud.molberg.mgutility.PushToTalkPressTest java -cp "$OUT" VehicleSettingsCoordinatorTest +java -cp "$OUT" cloud.molberg.mgutility.VehiclePowerOffControllerTest java -cp "$OUT" SpeedAudioCurveTest java -cp "$OUT" AdaptiveAudioCurveTest +java -cp "$OUT" LiquidSoundBalanceCurveTest java -cp "$OUT" BrightnessScheduleTest +java -cp "$OUT" cloud.molberg.mgutility.CampingModePolicyTest +java -cp "$OUT" PluginSdkTest +java -cp "$OUT" PluginMarketplaceTest +mkdir -p "$OUT/vehicle-power" +javac -source 8 -target 8 -cp "$OUT" -d "$OUT/vehicle-power" \ + $(find "$ROOT/tests/vehicle-power-stubs" -name '*.java') \ + "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsGateway.java" \ + "$ROOT/tests/VehiclePowerOffGatewayTest.java" +java -cp "$OUT/vehicle-power:$OUT" cloud.molberg.mgutility.VehiclePowerOffGatewayTest +mkdir -p "$OUT/audio" +javac -source 8 -target 8 -d "$OUT/audio" \ + $(find "$ROOT/tests/audio-stubs" -name '*.java') \ + "$ROOT/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java" \ + "$ROOT/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java" \ + "$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceCurve.java" \ + "$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java" \ + "$ROOT/tests/LiquidAudioIntegrationTest.java" +java -cp "$OUT/audio" cloud.molberg.mgutility.LiquidAudioIntegrationTest diff --git a/tests/vehicle-power-stubs/android/os/IBinder.java b/tests/vehicle-power-stubs/android/os/IBinder.java new file mode 100644 index 0000000..2f0851d --- /dev/null +++ b/tests/vehicle-power-stubs/android/os/IBinder.java @@ -0,0 +1,7 @@ +package android.os; + +public interface IBinder { + int FLAG_ONEWAY = 1; + String getInterfaceDescriptor(); + boolean transact(int code, Parcel data, Parcel reply, int flags); +} diff --git a/tests/vehicle-power-stubs/android/os/Parcel.java b/tests/vehicle-power-stubs/android/os/Parcel.java new file mode 100644 index 0000000..562b71a --- /dev/null +++ b/tests/vehicle-power-stubs/android/os/Parcel.java @@ -0,0 +1,24 @@ +package android.os; + +import java.util.ArrayList; + +public final class Parcel { + private final ArrayList values = new ArrayList(); + private int position; + + public static Parcel obtain() { return new Parcel(); } + public void recycle() { values.clear(); } + public void writeInterfaceToken(String token) { writeString(token); } + public void writeString(String value) { values.add(value); } + public String readString() { return (String) values.get(position++); } + public void writeInt(int value) { values.add(value); } + public int readInt() { return (Integer) values.get(position++); } + public void writeFloat(float value) { values.add(value); } + public float readFloat() { return (Float) values.get(position++); } + public void writeStrongBinder(IBinder binder) { values.add(binder); } + public IBinder readStrongBinder() { return (IBinder) values.get(position++); } + public void writeNoException() { writeInt(0); } + public void readException() { + if (readInt() != 0) throw new IllegalStateException("Remote exception"); + } +} diff --git a/vendor/sherpa-onnx/kotlin-stdlib-2.0.21.jar b/vendor/sherpa-onnx/kotlin-stdlib-2.0.21.jar new file mode 100644 index 0000000..9b7f2a8 Binary files /dev/null and b/vendor/sherpa-onnx/kotlin-stdlib-2.0.21.jar differ diff --git a/vendor/sherpa-onnx/sherpa-onnx-1.13.8.aar b/vendor/sherpa-onnx/sherpa-onnx-1.13.8.aar new file mode 100644 index 0000000..6e7e7be Binary files /dev/null and b/vendor/sherpa-onnx/sherpa-onnx-1.13.8.aar differ