diff --git a/README.md b/README.md index 6737fb7..3685039 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ rough edges, and expect performance to vary a lot between devices - see compatibility layer, running on Vulkan through Google's Dawn. **An OpenGL ES fallback.** Some phones ship a Vulkan driver too broken to start -the game at all. The launcher's **Graphics...** screen can switch the renderer +the game at all. The launcher's **Settings > Graphics** can switch the renderer to OpenGL ES for those devices. It is slower than Vulkan by nature - OpenGL only lets one thread talk to the GPU, so shaders compile on the render thread and the multithreaded graphics path is unavailable - so leave it on Automatic unless @@ -75,10 +75,40 @@ restart, which the menu does for you. **Vertical mode (experimental).** Play upright like Mario Kart Tour: the race fills the tall screen, the race HUD moves to the corners and the touch controls -get their own layout. Launcher > Graphics > Vertical mode. +get their own layout. Launcher > Settings > Graphics > Vertical mode. **Save import and export.** Bring your profile over from a Wii NAND backup or -Dolphin (`rksys.dat`), or copy it out, from the launcher's **Save data**. +Dolphin (`rksys.dat`), or copy it out, from the launcher's **Settings > Save data**. + +**A launcher built around the game.** Home, Mods, Rooms, Ranks, Profile and +Settings pages, upright with a tab bar on a phone and sideways with a navigation +rail on tablets and handhelds. **Settings > Launcher orientation** picks Automatic, +Portrait or Landscape. Long jobs (installing Retro Rewind, downloading a mod, +importing a game pack) show their progress in a task bar that follows you from +page to page. + +**Mods from inside the app.** Browse GameBanana's Mario Kart Wii mods and install +one with a tap (`.zip`, `.7z` and `.rar`, including RAR5), or import an archive you +already have. Turn mods on and off and drag them into priority order: the higher +mod wins when two change the same file. Turned-on mods load when you press Play (a +game that's already running restarts so the change takes) and apply to both Mario +Kart Wii and Retro Rewind. For Retro Rewind they're also laid out in its own +`Patches` folder the way the Wheel Wizard PC tool does it, so mods built on its +loose archive overrides (files like `Name.race.szs`) work too. + +**Rooms and Ranks.** Every public Retro WFC room, live: the track being raced, +who's in it with their Miis and VR, the room's average VR and whether it's open. +Ranks has the top 100 players by VR, and each player has a page with their rank and +a 7-day VR chart. Tap anyone to copy their friend code or add them as a friend. +Joining a room still happens inside the game. + +**Profile and Mii editor.** Licenses from your saves (Mii, friend code, VR and BR, +races and wins, friends), and an editor for every part of every Mii where each shape +is picked from pictures of your own Mii wearing it. Make, duplicate and delete Miis, +and import or export single Miis (`.rcd`) or the whole Mii file. Every change is +checked, written with the correct checksum, and the previous file is kept next to it +as a `.bak`. The pictures come from Nintendo's online Mii renderer; **Settings > Mii +pictures** turns that off and draws simple offline ones instead. **Picture settings.** Brightness, contrast and saturation in the Display settings. @@ -158,7 +188,7 @@ a phone, and the honest summary is: - **Android 10 (API 29) or newer**, on a 64-bit ARM (`arm64-v8a`) chip. There is no 32-bit or x86 build. - A working Vulkan driver for the best experience. Devices without one can fall back to OpenGL ES - from the launcher's **Graphics...** screen. + from the launcher's **Settings > Graphics**. - Enough free storage for the extracted game data (a few GB) plus headroom during the one-time extraction step. - A clean, unmodified **PAL `RMCP01`** disc image of Mario Kart Wii (.iso or .wbfs), dumped by you. @@ -186,7 +216,7 @@ all stay. **Optional: a game pack.** On your PC, unpack DriftDroid Builder, open `DriftDroidBuilder.exe` (Linux: `DriftDroidBuilder`), choose your disc image, pick Android and press **Start**. It takes 30 minutes to a couple of hours and makes `output/DriftDroid-GamePack-.zip`. Copy it to the -phone and tap **Import Game Pack...**: the app then uses that game code, for example a newer Retro +phone and open **Settings > Import game pack**: the app then uses that game code, for example a newer Retro Rewind. A game pack fits one app version, so make a new one with the matching builder. DriftDroid Builder also makes the **Switch** version (`DriftDroid.nro` and `RetroRewind.nro`); that @@ -336,8 +366,8 @@ No - this is an active, personal work-in-progress fork. It's playable start to f performance work, device compatibility and bug fixing are ongoing. **It won't start / the screen stays black.** -Most often a Vulkan driver the device can't actually deliver on. Open the launcher, tap -**Graphics...**, choose **OpenGL ES**, and try again. Report it either way - which renderer worked +Most often a Vulkan driver the device can't actually deliver on. Open the launcher, go to +**Settings > Graphics**, choose **OpenGL ES**, and try again. Report it either way - which renderer worked is exactly the information that's useful. **It runs at 60 fps and then gets slower.** @@ -351,7 +381,7 @@ the frames. It applies from the next race. **Retro Rewind crashes when I open Retro WFC or a menu after updating.** Most likely a mod that replaces Retro Rewind's own files and was made for an older Retro Rewind. -Turn your mods off in **Mods...** and try again; if that fixes it, the mod needs a version made +Turn your mods off on the **Mods** page and try again; if that fixes it, the mod needs a version made for the Retro Rewind you have now. **Characters or menu icons are stretched across the screen.** @@ -360,7 +390,7 @@ GPUs; if you still see it, set **Fix stretched graphics (Snapdragon)** in the se **Everything**, or try a different GPU driver (next question). **Can I use a different GPU driver?** -On Snapdragon phones, yes: **Graphics...** -> **GPU driver...** installs an AdrenoTools driver +On Snapdragon phones, yes: **Settings > Graphics** -> **GPU driver...** installs an AdrenoTools driver package such as Turnip. DriftDroid does not ship drivers; where to get them and how to check which one is active is in [`docs/android-gpu-compatibility.md`](docs/android-gpu-compatibility.md). @@ -421,6 +451,17 @@ position-tracked). steering calibration curve were directly modeled on, and the source of several GX command processor fixes, the in-app updater, and the phone vibration fallback and vibration strength setting this fork carries. +- **[Wheel Wizard](https://github.com/TeamWheelWizard/WheelWizard)** by Team Wheel Wizard - the PC + tool whose features the launcher brings to Android, and the reference for its Retro WFC and + GameBanana API use, the Mii renderer encoding, the save-file and Mii-file layouts, and friend-code + math. +- **Retro WFC**, whose public API powers Rooms and Ranks, and + **[GameBanana](https://gamebanana.com/games/5896)** and the mod authors whose work the Mods page + lists. +- **[libarchive](https://www.libarchive.org/)** (BSD) through + **[libarchive-android](https://github.com/zhanghai/libarchive-android)** (Apache 2.0) - unpacking + `.7z` and `.rar` mods. +- **Material Design icons** by Google (Apache 2.0) in the launcher. - **App icon**: a 3D render made for this project in Blender. The kart is **"Kart" by [absence_art](https://sketchfab.com/absence_art)** on Sketchfab (), licensed diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index d8ffcbc..fe58f6d 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -143,6 +143,22 @@ load time, at `android/app/src/main/java/org/libsdl/app/`. Taken unmodified from source tree pinned below (`android-project/app/src/main/java/org/libsdl/app/`). Source: . +### Material Design icons - Apache-2.0 + +The launcher's icons (`android/app/src/main/kotlin/com/driftdroid/android/ui/Icons.kt`) are path data +from Google's Material Design icons, Copyright Google LLC, licensed under the Apache License 2.0. +Source: . + +### libarchive-android 1.1.4 - Apache-2.0, with libarchive - BSD + +The Android app's mod installer unpacks `.7z` and `.rar` archives with libarchive, through the +`me.zhanghai.android.libarchive:library:1.1.4` JNI wrapper (fetched from Maven Central by Gradle and +packaged into the APK as `libarchive-jni.so`). The wrapper is Copyright 2023 Google LLC, licensed +under the Apache License 2.0. libarchive is Copyright Tim Kientzle and the libarchive contributors, +licensed under the 2-clause BSD license; the native library also contains the compression libraries +it is built with, each under its own license as listed by the wrapper project. +Sources: , . + --- ## Fetched at build time and redistributed in release builds diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9f7f7e2..c00f3d7 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -81,4 +81,11 @@ dependencies { implementation("androidx.documentfile:documentfile:1.0.1") implementation("com.google.android.material:material:1.12.0") implementation("androidx.recyclerview:recyclerview:1.3.2") + // libarchive for mod downloads: GameBanana's Mario Kart Wii mods come as .zip, .7z and RAR5 .rar, + // and RAR5 has no pure-Java reader. BSD-licensed libarchive behind an Apache-2.0 JNI wrapper. + implementation("me.zhanghai.android.libarchive:library:1.1.4") + + testImplementation("junit:junit:4.13.2") + // Android's org.json is a stub in local unit tests; this is the real implementation. + testImplementation("org.json:json:20240303") } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 26e5b43..0aea144 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -35,10 +35,11 @@ + + android:exported="true"> diff --git a/android/app/src/main/kotlin/com/driftdroid/android/LauncherOrientation.kt b/android/app/src/main/kotlin/com/driftdroid/android/LauncherOrientation.kt new file mode 100644 index 0000000..1d1ee8a --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/LauncherOrientation.kt @@ -0,0 +1,96 @@ +package com.driftdroid.android + +import android.app.Activity +import android.content.Context +import android.content.pm.ActivityInfo +import android.graphics.Point +import android.os.Build +import android.view.Surface +import com.driftdroid.android.ui.DriftSheet +import kotlin.math.max +import kotlin.math.min + +/** + * Which way up the launcher stands. Automatic puts phones in portrait - held in one hand, the + * pages are lists - and tablets and gaming handhelds in landscape, where the screen is held that + * way anyway and a rail beside the content uses the width. The game itself is always landscape. + */ +internal object LauncherOrientation { + enum class Mode(val label: String) { AUTO("Automatic"), PORTRAIT("Portrait"), LANDSCAPE("Landscape") } + + private const val PREFS = "launcher" + private const val KEY = "orientation" + + fun mode(context: Context): Mode = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) + ?.let { name -> Mode.values().firstOrNull { it.name == name } } ?: Mode.AUTO + + fun setMode(context: Context, mode: Mode) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, mode.name).apply() + } + + /** The requestedOrientation for [activity] under the saved mode. */ + fun requested(activity: Activity): Int { + val landscape = + when (mode(activity)) { + Mode.PORTRAIT -> false + Mode.LANDSCAPE -> true + Mode.AUTO -> deviceWantsLandscape(activity) + } + return if (landscape) ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE else ActivityInfo.SCREEN_ORIENTATION_PORTRAIT + } + + /** + * A tablet or a handheld: its screen is wider than tall when held the natural way (handhelds + * and most tablets), it is tablet-sized (600dp+ on its short side), or it is too square for a + * portrait column to pay off (4:3 and 1:1 handhelds, an unfolded foldable). A phone is none + * of these: tall, narrow and portrait by nature. + */ + fun deviceWantsLandscape(activity: Activity): Boolean { + val (w, h) = displaySize(activity) + @Suppress("DEPRECATION") + val rotation = activity.windowManager.defaultDisplay.rotation + val sideways = rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270 + val naturalWidth = if (sideways) h else w + val naturalHeight = if (sideways) w else h + if (naturalWidth > naturalHeight) return true + if (activity.resources.configuration.smallestScreenWidthDp >= 600) return true + val ratio = max(w, h).toFloat() / min(w, h).coerceAtLeast(1) + return ratio < 1.6f + } + + private fun displaySize(activity: Activity): Pair = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val bounds = activity.windowManager.maximumWindowMetrics.bounds + bounds.width() to bounds.height() + } else { + val size = Point() + @Suppress("DEPRECATION") + activity.windowManager.defaultDisplay.getRealSize(size) + size.x to size.y + } + + /** The Settings sheet: three choices, applied at once. */ + fun show(activity: Activity, onChanged: () -> Unit = {}) { + val current = mode(activity) + val sheet = DriftSheet(activity, T("Launcher orientation"), T("The game itself always plays in landscape")) + val auto = if (deviceWantsLandscape(activity)) T("landscape") else T("portrait") + for (option in Mode.values()) { + val detail = + when (option) { + Mode.AUTO -> T("Portrait on phones, landscape on tablets and handhelds. This device: %s").format(auto) + Mode.PORTRAIT -> T("Always upright") + Mode.LANDSCAPE -> T("Always sideways, like the game") + } + sheet.radio(option.label, detail, option == current) { + sheet.dismiss() + if (option != current) { + setMode(activity, option) + onChanged() + activity.requestedOrientation = requested(activity) + } + } + } + sheet.show() + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/MainActivity.kt b/android/app/src/main/kotlin/com/driftdroid/android/MainActivity.kt index 2025bea..f7cd31d 100644 --- a/android/app/src/main/kotlin/com/driftdroid/android/MainActivity.kt +++ b/android/app/src/main/kotlin/com/driftdroid/android/MainActivity.kt @@ -165,7 +165,25 @@ class MainActivity : SDLActivity() { restartIntoProduct(resolvedProduct) return } + // Same for mods: the running game read its overlay roots once, at DVD init, and never + // looks again. A mod installed, switched on or off, or reordered in the launcher since + // then would silently not apply when Play just resumed this session - restart clean so + // the new set is the one the game starts with. + ModManager.prepareEnabledPacks(this) + val overlayRoots = ModManager.enabledOverlayRoots(this) + if (sLoadedProduct != null && sLoadedOverlayRoots != overlayRoots) { + restartIntoProduct(resolvedProduct) + return + } + val freshStart = sLoadedProduct == null sLoadedProduct = resolvedProduct + sLoadedOverlayRoots = overlayRoots + // Retro Rewind also takes mods through its own Patches folder (loose archive overrides + // and all) - laid out now, before the game reads anything, and only on a fresh start: a + // session that is merely resumed already has its files open. + if (freshStart && resolvedProduct == PRODUCT_RETRO_REWIND) { + runCatching { ModManager.syncRetroRewindPatches(this, File(filesDir, RETRO_REWIND_STAGING_SUBDIR)) } + } // Vertical mode: upright screen, read by aurora's window setup (SDL_HINT_ORIENTATIONS) from // this variable, so it has to be set before the native side starts. val vertical = VerticalMode.isEnabled(this) @@ -206,7 +224,7 @@ class MainActivity : SDLActivity() { if (resolvedProduct == PRODUCT_RETRO_REWIND) { nativeSetRetroRewindRoot(File(filesDir, RETRO_REWIND_STAGING_SUBDIR).absolutePath) } - for (root in ModManager.enabledOverlayRoots(this)) { + for (root in overlayRoots) { nativeAddOverlayRoot(root) } // Only ever used as a FIRST-RUN default (native side only writes it when no explicit @@ -663,6 +681,17 @@ class MainActivity : SDLActivity() { // instances within the same still-alive process. private var sLoadedProduct: String? = null + /** True once a game has started in this process; the launcher warns before editing saves + * or Miis then, since the still-loaded game may write its own copy back over them. */ + val isGameLoaded: Boolean get() = sLoadedProduct != null + + // The mod folders (in priority order) the loaded game started with. + private var sLoadedOverlayRoots: List? = null + + /** The game is loaded but the launcher's mods have changed since: Play restarts it. */ + fun modsChangedSinceLoad(context: android.content.Context): Boolean = + sLoadedProduct != null && sLoadedOverlayRoots != ModManager.enabledOverlayRoots(context) + // Staging path for the Retro Rewind asset pack (tracks/textures - distinct from Code.pul, // which only carries the mod's patched game LOGIC and is already compiled into // libGameCombined.so). Populated by ModePickerActivity's folder-import flow, mirroring how diff --git a/android/app/src/main/kotlin/com/driftdroid/android/MiiDatabaseEditor.kt b/android/app/src/main/kotlin/com/driftdroid/android/MiiDatabaseEditor.kt deleted file mode 100644 index aa49121..0000000 --- a/android/app/src/main/kotlin/com/driftdroid/android/MiiDatabaseEditor.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.driftdroid.android - -/** - * Inserts one standalone Mii record (the 74-byte "Mii Data" exchange format - offsets confirmed - * by decoding a real .rcd export byte-for-byte: name at 0x02..0x15 in UTF-16BE, creator name in - * the last 20 bytes ending exactly at byte 74) into an existing RFL_DB.dat, rather than requiring - * the player to already have a full replacement database. - * - * Container layout (RFL_DB.dat's "My Miis" table) confirmed against SuperFromND/rfl_mii_extractor - * (github.com/SuperFromND/rfl_mii_extractor/blob/main/src/main.go), a working, independent - * open-source RFL_DB.dat parser: 4-byte header, then exactly 100 Mii slots of 74 bytes each - * starting at offset 4 - the same 74-byte record layout as the standalone exchange format, just - * packed back-to-back with no per-slot wrapper. - */ -internal object MiiDatabaseEditor { - const val MII_RECORD_BYTES = 74 - const val DATABASE_BYTES = 779_968 - - private const val TABLE_HEADER_BYTES = 4 - private const val SLOT_COUNT = 100 - private const val MAGIC = "RNOD" - // Same offset/algorithm as KartPad's KartPadMiiStorage.isValidDatabase - CRC-16/CCITT-XMODEM - // (poly 0x1021, no reflection) over every byte before this offset, stored big-endian here. - private const val CRC_OFFSET = 0x1F1DE - - sealed class Result { - data class Success(val database: ByteArray, val slotIndex: Int) : Result() - data class Failure(val message: String) : Result() - } - - fun isValidMiiRecord(record: ByteArray): Boolean = - record.size == MII_RECORD_BYTES && record.any { it != 0.toByte() } - - fun isValidDatabase(database: ByteArray): Boolean { - if (database.size != DATABASE_BYTES) return false - if (String(database, 0, 4, Charsets.US_ASCII) != MAGIC) return false - val stored = ((database[CRC_OFFSET].toInt() and 0xff) shl 8) or (database[CRC_OFFSET + 1].toInt() and 0xff) - return stored == crc16(database, CRC_OFFSET) - } - - /** Finds the first empty (all-zero) "My Miis" slot and writes [record] into it, then - * recomputes and rewrites the whole-database CRC so the result stays a genuinely valid - * database - not just one that happens to work in our own runtime. Does not mutate the input - * array; returns a new one. */ - fun insertMii(database: ByteArray, record: ByteArray): Result { - if (!isValidMiiRecord(record)) { - return Result.Failure("that doesn't look like a valid single-Mii (.rcd) file") - } - if (!isValidDatabase(database)) { - return Result.Failure("the existing Mii database failed validation - it may be corrupt") - } - - val updated = database.copyOf() - var freeSlot = -1 - for (slot in 0 until SLOT_COUNT) { - val offset = TABLE_HEADER_BYTES + slot * MII_RECORD_BYTES - var empty = true - for (i in 0 until MII_RECORD_BYTES) { - if (updated[offset + i] != 0.toByte()) { - empty = false - break - } - } - if (empty) { - freeSlot = slot - break - } - } - if (freeSlot < 0) { - return Result.Failure("no free Mii slot - all 100 \"My Miis\" slots are already used") - } - - val offset = TABLE_HEADER_BYTES + freeSlot * MII_RECORD_BYTES - System.arraycopy(record, 0, updated, offset, MII_RECORD_BYTES) - - val newCrc = crc16(updated, CRC_OFFSET) - updated[CRC_OFFSET] = ((newCrc shr 8) and 0xff).toByte() - updated[CRC_OFFSET + 1] = (newCrc and 0xff).toByte() - - return Result.Success(updated, freeSlot) - } - - private fun crc16(data: ByteArray, length: Int): Int { - var crc = 0 - for (index in 0 until length) { - crc = crc xor ((data[index].toInt() and 0xff) shl 8) - repeat(8) { - crc = - if ((crc and 0x8000) != 0) { - (crc shl 1) xor 0x1021 - } else { - crc shl 1 - } - crc = crc and 0xffff - } - } - return crc - } -} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ModManager.kt b/android/app/src/main/kotlin/com/driftdroid/android/ModManager.kt index a68aec0..5d4d591 100644 --- a/android/app/src/main/kotlin/com/driftdroid/android/ModManager.kt +++ b/android/app/src/main/kotlin/com/driftdroid/android/ModManager.kt @@ -1,51 +1,83 @@ package com.driftdroid.android -import android.app.Activity -import android.content.Intent +import android.content.Context import android.net.Uri -import android.view.MotionEvent -import android.view.View -import android.view.ViewGroup -import android.widget.LinearLayout -import android.widget.TextView -import androidx.recyclerview.widget.ItemTouchHelper -import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView -import com.driftdroid.android.ui.DriftSheet -import com.driftdroid.android.ui.DriftUi -import com.driftdroid.android.ui.PillSwitch +import android.provider.OpenableColumns +import com.driftdroid.android.mods.ArchiveExtractor +import com.driftdroid.android.mods.RetroRewindPatches +import com.driftdroid.android.mods.RiivolutionChoices +import org.json.JSONObject import java.io.File -import java.util.zip.ZipInputStream /** - * User-imported Riivolution-shaped mods (e.g. GameBanana downloads: a riivolution folder with an - * XML file in it, plus a folder of replacement .brres/.szs files) - covers texture packs, UI - * skins, and character/vehicle model swaps alike, since none of this is texture-specific: it's - * the same generic disc-file-replacement pipeline Retro Rewind's own custom tracks use. Each mod - * lives in its own subdirectory of [packsDir] (still named "TexturePacks" on disk - renaming it - * would orphan whatever's already imported there for existing installs, and it's an internal - * implementation detail the user never sees), registered as an extra DVD overlay root (see - * nativeAddOverlayRoot / android_jni_bridge.cpp's g_androidOverlayRoots) exactly like Retro - * Rewind's own install already is. The actual file-serve pipeline (RiivoDiscoverRoots -> + * User-installed mods: Riivolution-shaped packs (a riivolution folder with an XML file in it, plus + * replacement files) or plain loose files such as most GameBanana downloads - covers texture packs, + * UI skins, character/vehicle model swaps and custom tracks alike, since none of this is + * texture-specific: it's the same generic disc-file-replacement pipeline Retro Rewind's own custom + * tracks use. Each mod lives in its own subdirectory of [packsDir] (still named "TexturePacks" on + * disk - renaming it would orphan whatever's already imported there for existing installs, and + * it's an internal implementation detail the user never sees), registered as an extra DVD overlay + * root (see nativeAddOverlayRoot / android_jni_bridge.cpp's g_androidOverlayRoots) exactly like + * Retro Rewind's own install already is. The actual file-serve pipeline (RiivoDiscoverRoots -> * ScanOverlayRoot -> RegisterFileEntry, runtime/src/hle/storage) needs no changes for this - it - * never distinguishes where an overlay root's files came from or what kind of file they replace. + * never distinguishes where an overlay root's files came from, and a root with no XML has its + * files matched to disc files by name (dvd.cpp's ApplyFolderByNameMapping). * * Mods are only picked up at the next app launch (same limitation as Retro Rewind: nothing here - * can hot-swap which files the running guest fiber is reading from), so enable/disable/import all - * just edit files on disk and tell the user to restart. + * can hot-swap which files the running guest fiber is reading from), so enable/disable/install all + * just edit files on disk. The Mods page in the launcher is the UI for all of this. */ object ModManager { private const val DISABLED_MARKER = ".disabled" private const val ORDER_FILE = ".mod_order" + private const val META_FILE = ".driftdroid_mod.json" + + /** Where a mod came from, kept next to its files. Only GameBanana installs have most fields. */ + data class Meta( + val source: String, + val gameBananaId: Int?, + val title: String, + val author: String?, + val version: String?, + val thumbnailUrl: String?, + val fileName: String?, + val installedAt: Long, + ) { + fun toJson(): JSONObject = + JSONObject() + .put("source", source) + .put("gamebananaId", gameBananaId ?: JSONObject.NULL) + .put("title", title) + .put("author", author ?: JSONObject.NULL) + .put("version", version ?: JSONObject.NULL) + .put("thumbnailUrl", thumbnailUrl ?: JSONObject.NULL) + .put("fileName", fileName ?: JSONObject.NULL) + .put("installedAt", installedAt) + + companion object { + fun fromJson(o: JSONObject): Meta = + Meta( + source = o.optString("source", "file"), + gameBananaId = if (o.isNull("gamebananaId")) null else o.optInt("gamebananaId"), + title = o.optString("title"), + author = if (o.isNull("author")) null else o.optString("author"), + version = if (o.isNull("version")) null else o.optString("version"), + thumbnailUrl = if (o.isNull("thumbnailUrl")) null else o.optString("thumbnailUrl"), + fileName = if (o.isNull("fileName")) null else o.optString("fileName"), + installedAt = o.optLong("installedAt"), + ) + } + } - data class Pack(val dir: File, val enabled: Boolean) { + data class Pack(val dir: File, val enabled: Boolean, val meta: Meta?) { val name: String get() = dir.name + val title: String get() = meta?.title?.takeIf { it.isNotBlank() } ?: dir.name } - fun packsDir(activity: Activity): File = File(activity.filesDir, "WiiCompiled/TexturePacks") + fun packsDir(context: Context): File = File(context.filesDir, "WiiCompiled/TexturePacks") - private fun orderFile(activity: Activity): File = File(packsDir(activity), ORDER_FILE) + private fun orderFile(context: Context): File = File(packsDir(context), ORDER_FILE) // Priority order, top (index 0) wins: dvd.cpp applies discovered overlay roots in REVERSE // (overlays.rbegin()..rend(), "the explicitly configured root outranks the mod manifest"), @@ -54,305 +86,155 @@ object ModManager { // Persisted as a flat, newline-separated list of folder names (not the packs' own file // contents) since order needs to survive across imports/deletes independent of what's // actually installed at any given moment. - fun installedPacks(activity: Activity): List { - val root = packsDir(activity) + fun installedPacks(context: Context): List { + val root = packsDir(context) val dirs = root.listFiles { f -> f.isDirectory } ?: return emptyList() val byName = dirs.associateBy { it.name } - val saved = orderFile(activity).takeIf { it.isFile }?.readLines().orEmpty() + val saved = orderFile(context).takeIf { it.isFile }?.readLines().orEmpty() val ordered = mutableListOf() for (name in saved) { byName[name]?.let { ordered.add(it) } } val remaining = dirs.filter { it.name !in saved }.sortedBy { it.name.lowercase() } ordered.addAll(remaining) - return ordered.map { Pack(it, enabled = !File(it, DISABLED_MARKER).exists()) } + return ordered.map { Pack(it, enabled = !File(it, DISABLED_MARKER).exists(), meta = readMeta(it)) } } + private fun readMeta(dir: File): Meta? = + runCatching { Meta.fromJson(JSONObject(File(dir, META_FILE).readText())) }.getOrNull() + /** Persists a new priority order - top of the list (index 0) wins, matching * [installedPacks]'s convention above. */ - fun setOrder(activity: Activity, orderedNames: List) { - orderFile(activity).writeText(orderedNames.joinToString("\n")) + fun setOrder(context: Context, orderedNames: List) { + packsDir(context).mkdirs() + orderFile(context).writeText(orderedNames.joinToString("\n")) } /** Called from MainActivity right before super.onCreate(), same timing rule as * nativeSetRetroRewindRoot - RuntimeRiivolution::Overlays() caches this list on first use, * which happens later during DVD init, but never re-reads it after. */ - fun enabledOverlayRoots(activity: Activity): List = - installedPacks(activity).filter { it.enabled }.map { it.dir.absolutePath } + fun enabledOverlayRoots(context: Context): List = + installedPacks(context).filter { it.enabled }.map { it.dir.absolutePath } + + /** Readies every turned-on mod for the game - see [RiivolutionChoices] and + * [RetroRewindPatches.addRegionTwins]. Called just before the + * game starts, so mods installed by an earlier version of the app get it too. */ + fun prepareEnabledPacks(context: Context) { + for (pack in installedPacks(context)) { + if (!pack.enabled) continue + runCatching { RiivolutionChoices.ensure(pack.dir) } + runCatching { RetroRewindPatches.addRegionTwins(pack.dir) } + } + } + + /** Lays the turned-on mods out in Retro Rewind's own Patches folder - see [RetroRewindPatches]. + * Called as Retro Rewind starts fresh, before the game reads its files. */ + fun syncRetroRewindPatches(context: Context, retroRewindRoot: File) { + val packs = installedPacks(context).filter { it.enabled }.map { it.dir } + RetroRewindPatches.sync(packs, File(retroRewindRoot, "Patches")) + } fun setEnabled(pack: Pack, enabled: Boolean) { val marker = File(pack.dir, DISABLED_MARKER) if (enabled) marker.delete() else marker.createNewFile() } - fun delete(pack: Pack) { + fun delete(context: Context, pack: Pack) { pack.dir.deleteRecursively() + setOrder(context, installedPacks(context).map { it.name }) } - // --- Import --- + /** GameBanana mod ids that are installed right now. */ + fun installedGameBananaIds(context: Context): Set = + installedPacks(context).mapNotNull { it.meta?.gameBananaId }.toSet() - /** Extracts a zip (Zip-Slip guarded, same pattern as RetroRewindInstallService) into a fresh - * subdirectory of [packsDir] named after the mod, on a background thread. [onDone] runs on - * the UI thread with an error message, or null on success. */ - fun importZip(activity: Activity, source: Uri, packName: String, onDone: (String?) -> Unit) { - val safeName = packName.trim().ifEmpty { "Mod" }.replace(Regex("[^A-Za-z0-9 _-]"), "_") - Thread { - val error = runCatching { extractZip(activity, source, safeName) } - .fold(onSuccess = { it }, onFailure = { it.message ?: "unknown error" }) - activity.runOnUiThread { onDone(error) } - }.start() - } + // --- Install --- - private fun extractZip(activity: Activity, source: Uri, safeName: String): String? { - val root = packsDir(activity) + /** + * Unpacks [archive] (.zip, .7z or .rar) into a new mod folder named after [meta]'s title and + * puts it at the top of the list, so it wins over older mods that replace the same files. + * Slow: call from a background thread. Throws with a readable message. + */ + fun installArchive(context: Context, archive: File, meta: Meta, onFile: (Int) -> Unit = {}): Pack { + val root = packsDir(context) root.mkdirs() - var dest = File(root, safeName) - var suffix = 2 - while (dest.exists()) { - dest = File(root, "$safeName ($suffix)") - suffix++ - } - val scratch = File(activity.cacheDir, "mod_import_scratch") + // Unpacked next to the packs, not in cacheDir: a folder moved out of cacheDir keeps its + // cache group, and Android would then count the installed mod as clearable cache. + val scratchRoot = File(context.filesDir, ".mod_install") + val scratch = File(scratchRoot, System.nanoTime().toString()) scratch.deleteRecursively() - scratch.mkdirs() - val scratchCanonical = scratch.canonicalFile try { - val stream = activity.contentResolver.openInputStream(source) - ?: return "couldn't open the selected file" - stream.use { input -> - ZipInputStream(input).use { zip -> - var entry = zip.nextEntry - var any = false - while (entry != null) { - val outFile = File(scratch, entry.name) - if (!outFile.canonicalPath.startsWith(scratchCanonical.path + File.separator) && - outFile.canonicalPath != scratchCanonical.path - ) { - return "archive contains an unsafe file path" - } - if (entry.isDirectory) { - outFile.mkdirs() - } else { - outFile.parentFile?.mkdirs() - outFile.outputStream().use { output -> zip.copyTo(output) } - any = true - } - zip.closeEntry() - entry = zip.nextEntry - } - if (!any) return "archive was empty" - } - } - } catch (e: Exception) { - return e.message ?: "extraction failed" - } - - // A GameBanana zip commonly wraps its actual riivolution/ folder one level deep (a single - // top-level folder named after the mod) - unwrap that one level so `dest` itself becomes - // the overlay root riivolution.cpp expects (its riivolution/*.xml at the top). - val resolved = resolveOverlayRoot(scratch) - if (!resolved.renameTo(dest)) { - resolved.copyRecursively(dest, overwrite = true) - } - scratch.deleteRecursively() - return null - } - - private fun resolveOverlayRoot(extracted: File): File { - if (File(extracted, "riivolution").isDirectory) return extracted - val children = extracted.listFiles { f -> f.isDirectory } ?: return extracted - if (children.size == 1 && File(children[0], "riivolution").isDirectory) return children[0] - return extracted - } - - // --- UI --- - - const val REQUEST_CODE_PICK_ZIP = 9821 - - fun startPickZip(activity: Activity) { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "*/*" - activity.startActivityForResult(intent, REQUEST_CODE_PICK_ZIP) - } - - /** Call from the activity's onActivityResult for [REQUEST_CODE_PICK_ZIP]. */ - fun onZipPicked(activity: Activity, uri: Uri?) { - if (uri == null) return - val sheet = DriftSheet(activity, T("Name this mod"), compact = true) - val nameInput = sheet.textField("Mod name") - sheet.button("Cancel") { sheet.dismiss() } - sheet.button("Import", DriftUi.Style.PRIMARY) { - val name = nameInput.text?.toString().orEmpty() - sheet.dismiss() - val progress = DriftSheet(activity, T("Importing mod..."), compact = true) - progress.progress() - progress.dialog.setCancelable(false) - progress.show() - importZip(activity, uri, name) { error -> - progress.dismiss() - if (error != null) { - DriftSheet.message(activity, "Import failed", error) - } else { - showManagerDialog(activity) - } + ArchiveExtractor.extract(archive, scratch, onFile) + // A GameBanana archive commonly wraps everything in one top-level folder named after + // the mod - unwrap it so `dest` itself becomes the overlay root riivolution.cpp + // expects (its riivolution/*.xml at the top). A loose-file mod works either way. + val resolved = resolveOverlayRoot(scratch) + val dest = uniqueDir(root, safeFolderName(meta.title)) + if (!resolved.renameTo(dest)) { + resolved.copyRecursively(dest, overwrite = true) } + File(dest, META_FILE).writeText(meta.toJson().toString()) + RiivolutionChoices.ensure(dest) + RetroRewindPatches.addRegionTwins(dest) + val order = installedPacks(context).map { it.name }.filter { it != dest.name } + setOrder(context, listOf(dest.name) + order) + return Pack(dest, enabled = true, meta = meta) + } finally { + scratch.deleteRecursively() + scratchRoot.delete() // only goes when empty, so a parallel install's folder stays } - sheet.show() } - // The dialog currently on screen, if any. Every refresh (after import/delete/toggle) used to - // build and show a brand-new AlertDialog on top of whichever one was already showing, rather - // than replacing it - confirmed directly: importing a mod left the freshly updated dialog - // stacked ON TOP of the still-open, stale pre-import one, so closing it (which looked like - // "close the dialog") actually just revealed the stale copy underneath, making the import look - // like it never took effect until the user backed out and reopened the whole thing fresh. - private var currentDialog: DriftSheet? = null - - /** Lists installed mods with on/off switches, drag handles and delete, and an Import button. - * Restart-required note matches the same limitation Retro Rewind's own install/update flow - * already has. */ - fun showManagerDialog(activity: Activity) { - currentDialog?.dismiss() - val dp: (Int) -> Int = { (it * activity.resources.displayMetrics.density).toInt() } - val sheet = DriftSheet(activity, "Mods") - sheet.note( - "Turned-on mods load the next time you start a race. Drag ≡ to reorder: a mod higher in " + - "the list wins when two replace the same file.", - ) - val packs = installedPacks(activity) - if (packs.isEmpty()) { - sheet.note("No mods yet. Import one from a .zip (for example a GameBanana download).") - } else { - val recyclerView = RecyclerView(activity) - recyclerView.layoutManager = LinearLayoutManager(activity) - recyclerView.overScrollMode = View.OVER_SCROLL_NEVER - val adapter = PackAdapter(activity, packs.toMutableList()) - recyclerView.adapter = adapter - val itemTouchHelper = ItemTouchHelper(DragCallback(adapter)) - itemTouchHelper.attachToRecyclerView(recyclerView) - adapter.dragStarter = { holder -> itemTouchHelper.startDrag(holder) } - // Bounded height: the list scrolls inside the sheet instead of growing past the screen. - recyclerView.layoutParams = - LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(minOf(packs.size, 5) * 64)) - sheet.custom(recyclerView) + /** Installs a .zip/.7z/.rar the player picked with the system file picker. */ + fun importFile(context: Context, source: Uri, title: String, onFile: (Int) -> Unit = {}): Pack { + val fileName = displayName(context, source) ?: "mod.zip" + val copy = File(context.cacheDir, "mod_import_${System.nanoTime()}") + try { + val input = context.contentResolver.openInputStream(source) ?: throw IllegalStateException("couldn't open the picked file") + input.use { stream -> copy.outputStream().use { stream.copyTo(it, 1 shl 16) } } + val meta = + Meta( + source = "file", + gameBananaId = null, + title = title.trim().ifEmpty { fileName.substringBeforeLast('.') }, + author = null, + version = null, + thumbnailUrl = null, + fileName = fileName, + installedAt = System.currentTimeMillis(), + ) + return installArchive(context, copy, meta, onFile) + } finally { + copy.delete() } - sheet.button("Import .zip") { startPickZip(activity) } - sheet.button("Done", DriftUi.Style.PRIMARY) { sheet.dismiss() } - sheet.onDismiss = { if (currentDialog === sheet) currentDialog = null } - sheet.show() - currentDialog = sheet } - // Drag-to-reorder priority: a dedicated "≡" handle per row starts the drag (rather than - // enabling ItemTouchHelper's default long-press-anywhere) so long-pressing the checkbox or - // Delete button doesn't fight with their own touch handling. Order is persisted (setOrder) - // as soon as a drag ends, not deferred to dialog close, so it survives even if the user backs - // out with the system back button rather than tapping Close. - private class PackAdapter(private val activity: Activity, val items: MutableList) : - RecyclerView.Adapter() { - - var dragStarter: ((RecyclerView.ViewHolder) -> Unit)? = null - - class VH(val row: LinearLayout, val handle: TextView, val name: TextView, val toggle: PillSwitch, val deleteButton: TextView) : - RecyclerView.ViewHolder(row) - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { - val dp: (Int) -> Int = { (it * activity.resources.displayMetrics.density).toInt() } - val row = LinearLayout(activity) - row.orientation = LinearLayout.HORIZONTAL - row.gravity = android.view.Gravity.CENTER_VERTICAL - row.setPadding(dp(6), 0, dp(12), 0) - row.background = DriftUi.pressable(activity, DriftUi.ROW) - row.layoutParams = - RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(58)).apply { bottomMargin = dp(6) } - - val handle = TextView(activity) - handle.text = "≡" - handle.textSize = 22f - handle.setTextColor(DriftUi.MUTED) - handle.setPadding(dp(10), 0, dp(12), 0) - row.addView(handle) - - val name = TextView(activity) - name.textSize = 16f - name.setTextColor(DriftUi.TEXT) - name.isSingleLine = true - name.ellipsize = android.text.TextUtils.TruncateAt.END - row.addView(name, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) - - val toggle = PillSwitch(activity) - row.addView(toggle, LinearLayout.LayoutParams(dp(52), dp(30)).apply { marginStart = dp(10) }) - - val deleteButton = DriftUi.button(activity, "Delete", DriftUi.Style.DANGER) {} - deleteButton.textSize = 13f - deleteButton.minHeight = dp(38) - row.addView(deleteButton, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp(38)).apply { marginStart = dp(10) }) - - return VH(row, handle, name, toggle, deleteButton) - } - - override fun getItemCount(): Int = items.size - - override fun onBindViewHolder(holder: VH, position: Int) { - val pack = items[position] - holder.name.text = pack.name - holder.toggle.isOn = pack.enabled - holder.row.setOnClickListener { - holder.toggle.isOn = !holder.toggle.isOn - setEnabled(pack, holder.toggle.isOn) + fun displayName(context: Context, uri: Uri): String? = + runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null } + }.getOrNull() - holder.handle.setOnTouchListener { _, event -> - if (event.action == MotionEvent.ACTION_DOWN) { - dragStarter?.invoke(holder) - } - false - } - - holder.deleteButton.setOnClickListener { - DriftSheet.confirm(activity, T("Delete \"%s\"?").format(pack.name), "The mod's files are removed from the app.", "Delete", danger = true) { - val index = items.indexOf(pack) - if (index >= 0) { - items.removeAt(index) - notifyItemRemoved(index) - delete(pack) - setOrder(activity, items.map { it.name }) - } - } - } - } + private fun safeFolderName(title: String): String = + title.trim().replace(Regex("[^A-Za-z0-9 _().-]"), "_").trim('.', ' ').take(60).ifEmpty { "Mod" } - fun moveItem(from: Int, to: Int) { - val moved = items.removeAt(from) - items.add(to, moved) - notifyItemMoved(from, to) - } - - fun persistOrder() { - setOrder(activity, items.map { it.name }) + private fun uniqueDir(root: File, name: String): File { + var dest = File(root, name) + var suffix = 2 + while (dest.exists()) { + dest = File(root, "$name ($suffix)") + suffix++ } + return dest } - private class DragCallback(private val adapter: PackAdapter) : - ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { - - override fun isLongPressDragEnabled(): Boolean = false - - override fun onMove( - recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder, - ): Boolean { - adapter.moveItem(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) - return true - } - - override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { - super.clearView(recyclerView, viewHolder) - adapter.persistOrder() - } - - override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} + private fun resolveOverlayRoot(extracted: File): File { + if (File(extracted, "riivolution").isDirectory) return extracted + val children = extracted.listFiles() ?: return extracted + val dirs = children.filter { it.isDirectory } + if (dirs.size == 1 && children.size == 1) return dirs[0] + if (dirs.size == 1 && File(dirs[0], "riivolution").isDirectory) return dirs[0] + return extracted } } diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ModePickerActivity.kt b/android/app/src/main/kotlin/com/driftdroid/android/ModePickerActivity.kt index 7823b2f..385721a 100644 --- a/android/app/src/main/kotlin/com/driftdroid/android/ModePickerActivity.kt +++ b/android/app/src/main/kotlin/com/driftdroid/android/ModePickerActivity.kt @@ -1,41 +1,53 @@ package com.driftdroid.android import android.app.Activity -import android.content.BroadcastReceiver import android.content.Context import android.content.Intent -import android.content.IntentFilter -import android.content.pm.PackageInstaller -import android.graphics.Color -import android.graphics.Typeface -import android.graphics.drawable.Drawable -import android.graphics.drawable.GradientDrawable -import android.graphics.drawable.LayerDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.provider.OpenableColumns -import android.provider.Settings import android.view.Gravity -import android.view.MotionEvent import android.view.View import android.view.ViewGroup -import android.view.ViewOutlineProvider -import android.widget.Button +import android.view.WindowInsets +import android.view.WindowInsetsController +import android.view.WindowManager +import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.ProgressBar +import android.widget.ScrollView import android.widget.TextView import androidx.documentfile.provider.DocumentFile +import com.driftdroid.android.launcher.HomePage +import com.driftdroid.android.launcher.LeaderboardPage +import com.driftdroid.android.launcher.ModsPage +import com.driftdroid.android.launcher.Page +import com.driftdroid.android.launcher.ProfilePage +import com.driftdroid.android.launcher.RoomsPage +import com.driftdroid.android.launcher.SettingsPage +import com.driftdroid.android.launcher.Tab +import com.driftdroid.android.mods.ModInstallJob +import com.driftdroid.android.net.Http import com.driftdroid.android.ui.DriftSheet import com.driftdroid.android.ui.DriftUi +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.IconDrawable +import com.driftdroid.android.ui.LauncherBackground +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages +import com.driftdroid.android.ui.SheetPalette +import com.driftdroid.android.ui.SheetThemed +import com.driftdroid.android.ui.SlantDrawable import java.io.File import java.io.RandomAccessFile import java.text.SimpleDateFormat import java.util.Date import java.util.Locale +import java.util.concurrent.Executors import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream @@ -46,440 +58,678 @@ import java.util.zip.ZipOutputStream * running game has a supported way to reset and switch profiles live - MainActivity.EXTRA_PRODUCT * tells it which one nativeSetActiveProduct() should select. * + * It is also the home of everything around the game: Home, Mods, Rooms, Ranks, Profile and + * Settings (the pages in com.driftdroid.android.launcher), behind a bottom tab bar on a phone held + * upright or a navigation rail on a tablet or handheld held sideways (LauncherOrientation picks + * which). A header carries the page's title and actions, detail pages are pushed on top with a back + * arrow, and a task bar for long jobs (Retro Rewind installs, mod downloads, imports) keeps + * following a job across pages. + * * Retro Rewind's pack (tracks/textures, ~2GB - distinct from Code.pul, which only carries the - * mod's patched game LOGIC and is already compiled into libGameCombined.so) is never bundled or - * downloaded by this app, matching how the PC version works: WiiCompiled.Setup's - * RetroRewindSource.cs only ever resolves a folder the user already has (normally obtained via the - * separate Wheel Wizard tool) - it never packages or downloads it itself. This picker offers two - * ways to hand over a copy the user already obtained: the .zip file exactly as downloaded (most - * people will only ever have this - extracted first, matching how someone who downloaded Retro - * Rewind normally has it), or an already-extracted folder for anyone who prefers that. + * mod's patched game LOGIC and is already compiled into libGameCombined.so) is downloaded from + * Retro Rewind's own server by RetroRewindInstallService, or taken from a copy the player already + * has: the .zip file exactly as downloaded, or an already-extracted folder. + * + * File pickers and anything else that hands Android's own UI the screen stay here rather than in + * the in-game sidebar: launching one while a live game session's GPU surface is running lost the + * WebGPU/Vulkan surface on-device ("QueuePresent failed with VK_ERROR_SURFACE_LOST_KHR") and + * crashed the game. No such surface exists on this screen. */ -class ModePickerActivity : Activity() { - - private lateinit var root: LinearLayout - private lateinit var baseButton: Button - private lateinit var retroButton: Button - private lateinit var retroMenuButton: Button - private lateinit var statusText: TextView - private lateinit var progressBar: ProgressBar - private lateinit var diagnosticsButton: Button - private lateinit var graphicsButton: Button - private lateinit var iconButton: Button - private lateinit var languageButton: Button - private lateinit var serverSettingsButton: Button - private lateinit var modsButton: Button - private lateinit var miiDataButton: Button +class ModePickerActivity : Activity(), SheetThemed { + + override val sheetPalette: SheetPalette get() = SheetPalette.LAUNCHER + private val mainHandler = Handler(Looper.getMainLooper()) + private val background = Executors.newCachedThreadPool { r -> Thread(r, "launcher-work").apply { isDaemon = true } } + + /** Phone layout: one column with a bottom tab bar, instead of a rail beside the pages. */ + internal var compact = false + private set + + private val navItems = HashMap() + private var rail: View? = null + private lateinit var backButton: View + private lateinit var settingsButton: View + private lateinit var titleView: TextView + private lateinit var subtitleView: TextView + private lateinit var titlesBox: View + private lateinit var brandBox: LinearLayout + private lateinit var brandArt: ImageView + private lateinit var actionsBox: LinearLayout + private lateinit var pageHost: FrameLayout + private lateinit var taskBar: LinearLayout + private lateinit var taskTitle: TextView + private lateinit var taskDetail: TextView + private lateinit var taskProgress: ProgressBar + private lateinit var taskCancel: View + private lateinit var snack: LinearLayout + private lateinit var snackEdge: View + private lateinit var snackText: TextView + + private val tabPages = HashMap() + private val stack = ArrayList() + private val actionViews = HashMap>() + private var currentTab = Tab.HOME + private var previousTab = Tab.HOME + private var shown: Page? = null + private var paused = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // Portrait on phones, landscape on tablets and handhelds, or the player's choice. When this + // turns the screen, Android starts the Activity again the right way up straight away. + requestedOrientation = LauncherOrientation.requested(this) I18n.init(this) - buildUi() + Http.userAgent = "DriftDroid/${appVersionName()} (Android ${Build.VERSION.RELEASE})" + RemoteImages.init(this) + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN) + // Draw the backdrop under a camera cutout too (no black band beside or above it); the + // shell keeps its content clear of the cutout itself. + window.attributes = window.attributes.apply { + layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.setDecorFitsSystemWindows(false) + compact = Lx.isCompact(this) + buildShell() + val tab = savedInstanceState?.getString(STATE_TAB)?.let { name -> Tab.values().firstOrNull { it.name == name } } ?: Tab.HOME + navigate(tab) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putString(STATE_TAB, currentTab.name) } override fun onResume() { super.onResume() - refreshChannelButtons() + hideSystemBars() + // Coming back from the game or a picker: the page refreshes what may have changed. + if (paused) currentPage()?.let { if (it === shown) it.onShow() } + paused = false // An install may still be running in RetroRewindInstallService from a previous instance // of this Activity (e.g. this one is a fresh recreation after Android reclaimed the old // one while backgrounded) - pick up its live progress instead of showing an idle screen // over a copy that's actually still going. - if (RetroRewindInstallStatus.running) { - beginImportUi(RetroRewindInstallStatus.label) - startStatusPolling() - } + if (RetroRewindInstallStatus.running) trackingRetroInstall = true + if (ModInstallJob.running) watchModInstall() + startTaskPolling() } override fun onPause() { super.onPause() - stopStatusPolling() + paused = true + stopTaskPolling() + shown?.onHide() } - private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() - - /** A rounded "channel" tile background, Wii Menu channel style. */ - private fun channelDrawable(topColor: Int, bottomColor: Int, radius: Float): GradientDrawable = - GradientDrawable( - GradientDrawable.Orientation.TOP_BOTTOM, - intArrayOf(topColor, bottomColor), - ).also { it.cornerRadius = radius } - - private fun styleChannelButton( - button: Button, - topColor: Int, - bottomColor: Int, - radius: Float = dp(18).toFloat(), - ) { - button.background = channelDrawable(topColor, bottomColor, radius) - button.setTextColor(Color.WHITE) - button.typeface = Typeface.DEFAULT_BOLD - button.isAllCaps = false - button.setShadowLayer(3f, 0f, 2f, Color.argb(140, 0, 0, 0)) - button.stateListAnimator = null - button.elevation = dp(4).toFloat() - addPressBounce(button) + override fun onDestroy() { + super.onDestroy() + (stack + tabPages.values).forEach { it.onClose() } } - /** - * Custom channel art (a full banner image, already carrying its own logo/text) as a button's - * background, clipped to rounded corners via the view's outline rather than baked into the - * image itself - the source banners are plain rectangles at 1120x256 (= 280x64dp at 4x/xxxhdpi, - * matching buttonParams exactly, so the image stretches to fill with no cropping needed). - */ - private fun styleImageButton( - button: Button, - drawableRes: Int, - locked: Boolean, - lockedLabel: String, - radius: Float = dp(18).toFloat(), - ) { - val art = androidx.core.content.ContextCompat.getDrawable(this, drawableRes)!!.mutate() - button.background = - if (locked) { - // A dark scrim over the banner art (rather than editing the art itself) both - // signals "locked" Wii-channel style and naturally dims the banner's own baked-in - // title text underneath the "Install..." label drawn on top, so the two don't - // compete for attention. - val scrim = GradientDrawable() - scrim.setColor(Color.argb(175, 0, 0, 0)) - scrim.cornerRadius = radius - LayerDrawable(arrayOf(art, scrim)) + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) hideSystemBars() + } + + /** Full screen like the game itself; a swipe from the edge brings the system bars back briefly. */ + private fun hideSystemBars() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + window.insetsController?.let { + it.hide(WindowInsets.Type.systemBars()) + it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + } + } else { + // Android 10 has no WindowInsetsController. + @Suppress("DEPRECATION") + window.decorView.systemUiVisibility = + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or + View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + } + } + + @Deprecated("Deprecated in Java") + override fun onBackPressed() { + when { + stack.isNotEmpty() -> back() + currentTab == Tab.SETTINGS && compact -> navigate(previousTab) + currentTab != Tab.HOME -> navigate(Tab.HOME) + else -> @Suppress("DEPRECATION") super.onBackPressed() + } + } + + private fun dp(value: Float): Int = Lx.dp(this, value) + + // --- Shell --- + + /** One destination in the tab bar or rail: its icon on a slanted green plate when picked, and a label. */ + private inner class NavItem(val tab: Tab) { + val root: LinearLayout = Lx.vbox(this@ModePickerActivity) + private val icon = ImageView(this@ModePickerActivity) + private val label = Lx.text(this@ModePickerActivity, T(tab.label).uppercase(), 10.5f, Lx.FAINT, Lx.CONDENSED, 1) + + init { + root.gravity = Gravity.CENTER + val p = dp(15f) + icon.setPadding(p, dp(4f), p, dp(4f)) + root.addView(icon, Lx.lp(this@ModePickerActivity, 56f, 30f)) + label.letterSpacing = 0.08f + root.addView(label, Lx.lp(this@ModePickerActivity, -2f, -2f, top = 4f)) + root.background = Lx.pressable(this@ModePickerActivity, android.graphics.Color.TRANSPARENT, 8f) + root.contentDescription = T(tab.label) + root.setOnClickListener { + UiSounds.playClick(this@ModePickerActivity) + navigate(tab) + } + } + + fun paint(selected: Boolean) { + icon.setImageDrawable(IconDrawable(tab.icon, if (selected) Lx.ACCENT_TEXT else Lx.MUTED)) + icon.background = if (selected) SlantDrawable(Lx.ACCENT, 0, 0f, dp(3f).toFloat()) else null + label.setTextColor(if (selected) Lx.TEXT else Lx.FAINT) + root.isSelected = selected + } + } + + private fun buildShell() { + val root = FrameLayout(this) + root.background = LauncherBackground(compact) + + pageHost = FrameLayout(this) + val header = buildHeader() + if (compact) { + val column = Lx.vbox(this) + column.addView(header) + column.addView(pageHost, Lx.lp(this, -1f, 0f, 1f)) + val bar = Lx.hbox(this, Gravity.CENTER) + bar.setBackgroundColor(Lx.BAR) + for (tab in Tab.values().filter { it != Tab.SETTINGS }) { + val item = NavItem(tab) + navItems[tab] = item + bar.addView(item.root, Lx.lp(this, 0f, -1f, 1f)) + } + column.addView(Lx.divider(this)) + column.addView(bar, Lx.lp(this, -1f, BOTTOM_BAR_DP)) + root.addView(column, Lx.match()) + } else { + val row = Lx.hbox(this, Gravity.TOP) + val rail = Lx.vbox(this) + rail.gravity = Gravity.CENTER_HORIZONTAL + // A phone held sideways is only ~400dp tall: tighter items so all six and the icon fit + // without the rail scrolling Settings out of sight. + val short = resources.configuration.screenHeightDp < 480 + rail.setPadding(0, dp(if (short) 6f else 12f), 0, dp(if (short) 6f else 12f)) + val mark = ImageView(this) + mark.setImageResource(R.mipmap.ic_launcher) + mark.contentDescription = getString(R.string.app_name) + rail.addView(mark, Lx.lp(this, if (short) 42f else 56f, if (short) 42f else 56f, bottom = if (short) 4f else 10f)) + for (tab in Tab.values()) { + val item = NavItem(tab) + navItems[tab] = item + if (tab == Tab.SETTINGS) rail.addView(View(this), LinearLayout.LayoutParams(1, 0, 1f)) + rail.addView(item.root, Lx.lp(this, 80f, if (short) 56f else 62f, bottom = if (short) 0f else 2f)) + } + val railScroll = ScrollView(this) + railScroll.isVerticalScrollBarEnabled = false + railScroll.isFillViewport = true + railScroll.setBackgroundColor(Lx.BAR) + railScroll.addView(rail, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + row.addView(railScroll, LinearLayout.LayoutParams(dp(RAIL_DP), ViewGroup.LayoutParams.MATCH_PARENT)) + row.addView(View(this).apply { setBackgroundColor(Lx.LINE) }, LinearLayout.LayoutParams(dp(1f), ViewGroup.LayoutParams.MATCH_PARENT)) + val main = Lx.vbox(this) + main.addView(header) + main.addView(pageHost, Lx.lp(this, -1f, 0f, 1f)) + row.addView(main, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f)) + root.addView(row, Lx.match()) + this.rail = railScroll + } + + buildTaskBar(root) + buildSnack(root) + // Keep content clear of a camera cutout. Sideways, a cutout on the rail's side widens the + // rail instead, so the rail runs right to the screen's edge. + root.setOnApplyWindowInsetsListener { view, insets -> + val cutout = insets.displayCutout + val left = cutout?.safeInsetLeft ?: 0 + val railView = rail + if (railView != null) { + railView.setPadding(left, 0, 0, 0) + railView.layoutParams = railView.layoutParams.apply { width = dp(RAIL_DP) + left } + view.setPadding(0, cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) } else { - art + view.setPadding(left, cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) } - button.text = if (locked) lockedLabel else "" - button.setTextColor(Color.WHITE) - button.typeface = Typeface.DEFAULT_BOLD - button.textSize = 16f - button.isAllCaps = false - button.setShadowLayer(3f, 0f, 2f, Color.argb(200, 0, 0, 0)) - button.stateListAnimator = null - button.elevation = dp(4).toFloat() - button.clipToOutline = true - button.outlineProvider = - object : ViewOutlineProvider() { - override fun getOutline(view: View, outline: android.graphics.Outline) { - outline.setRoundRect(0, 0, view.width, view.height, radius) + insets + } + setContentView(root) + } + + private fun buildHeader(): View { + val header = Lx.hbox(this) + header.setPadding(dp(if (compact) 8f else 16f), dp(8f), dp(if (compact) 8f else 20f), dp(8f)) + header.minimumHeight = dp(if (compact) 60f else 72f) + backButton = Lx.iconButton(this, Icon.BACK, "Back", Lx.TEXT, android.graphics.Color.TRANSPARENT, 44f) { goBack() } + header.addView(backButton, Lx.lp(this, 44f, 44f, end = 4f)) + + // Home's header is the brand: the app icon (the rail already shows it in landscape) and the wordmark. + brandBox = Lx.hbox(this) + if (compact) { + val mark = ImageView(this) + mark.setImageResource(R.mipmap.ic_launcher) + brandBox.addView(mark, Lx.lp(this, 44f, 44f, end = 6f)) + } + brandArt = ImageView(this) + brandArt.scaleType = ImageView.ScaleType.FIT_START + brandArt.adjustViewBounds = true + brandBox.addView(brandArt, Lx.lp(this, -2f, if (compact) 30f else 40f)) + header.addView(brandBox, Lx.lp(this, 0f, -2f, 1f, start = if (compact) 4f else 8f)) + + val titles = Lx.vbox(this) + titleView = Lx.display(this, "", if (compact) 23f else 27f, Lx.TEXT, 1) + subtitleView = Lx.caption(this, "", Lx.MUTED, 1) + titles.addView(titleView) + titles.addView(subtitleView, Lx.lp(this, top = 3f)) + titlesBox = titles + header.addView(titles, Lx.lp(this, 0f, -2f, 1f, start = 8f, end = 8f)) + + actionsBox = Lx.hbox(this) + header.addView(actionsBox) + settingsButton = Lx.iconButton(this, Icon.SETTINGS, "Settings", Lx.MUTED, android.graphics.Color.TRANSPARENT, 44f) { + UiSounds.playClick(this) + navigate(Tab.SETTINGS) + } + header.addView(settingsButton, Lx.lp(this, 44f, 44f, start = 4f)) + return header + } + + private fun buildTaskBar(root: FrameLayout) { + taskBar = Lx.hbox(this) + taskBar.background = Lx.rounded(this, Lx.SURFACE_HI, 8f) + Lx.clipRounded(taskBar, 8f) + taskBar.elevation = dp(10f).toFloat() + taskBar.addView(View(this).apply { setBackgroundColor(Lx.ACCENT) }, LinearLayout.LayoutParams(dp(4f), ViewGroup.LayoutParams.MATCH_PARENT)) + val taskText = Lx.vbox(this) + taskTitle = Lx.text(this, "", 14.5f, Lx.TEXT, Lx.CONDENSED, 1) + taskDetail = Lx.caption(this, "", Lx.MUTED, 2) + taskProgress = Lx.progressBar(this) + taskText.addView(taskTitle) + taskText.addView(taskDetail, Lx.lp(this, top = 3f)) + taskText.addView(taskProgress, Lx.lp(this, -1f, 6f, top = 8f)) + taskBar.addView(taskText, Lx.lp(this, 0f, -2f, 1f, start = 14f, top = 12f, end = 8f, bottom = 12f)) + taskCancel = Lx.iconButton(this, Icon.CLOSE, "Cancel", Lx.MUTED, android.graphics.Color.TRANSPARENT, 40f) { ModInstallJob.cancel() } + taskBar.addView(taskCancel, Lx.lp(this, 40f, 40f, end = 6f)) + taskBar.visibility = View.GONE + val params = + if (compact) { + FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM).apply { + setMargins(dp(12f), 0, dp(12f), dp(BOTTOM_BAR_DP + 10f)) + } + } else { + FrameLayout.LayoutParams(dp(380f), ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM or Gravity.END).apply { + setMargins(0, 0, dp(20f), dp(18f)) } } - addPressBounce(button) + root.addView(taskBar, params) } - /** - * The little "press in, spring back" wiggle every Wii Menu channel does when tapped - - * squishes non-uniformly (width in more than height) rather than a plain uniform scale, and - * overshoots slightly past 1.0 on release before settling - the actual difference between - * "shrinks and grows back" (mechanical) and "liquid"/gel-like motion is in that asymmetry and - * overshoot, not just easing curve choice. Purely a touch-feedback animation (returns false so - * the real click listener still fires), not a gate on the click itself. - */ - private fun addPressBounce(view: View) { - val overshoot = android.view.animation.OvershootInterpolator(3.5f) - view.setOnTouchListener { v, event -> - when (event.action) { - MotionEvent.ACTION_DOWN -> - v.animate().scaleX(0.92f).scaleY(0.95f).setDuration(90) - .setInterpolator(android.view.animation.DecelerateInterpolator()).start() - // Sound plays on an actual completed tap only, not ACTION_CANCEL (a drag that - // left the view, or the touch getting reassigned elsewhere) - both still spring - // the view back visually, but a canceled touch never counted as a "click" and - // shouldn't sound like one either. - MotionEvent.ACTION_UP -> { - v.animate().scaleX(1f).scaleY(1f).setDuration(260).setInterpolator(overshoot).start() - UiSounds.playClick(v.context) - } - MotionEvent.ACTION_CANCEL -> - v.animate().scaleX(1f).scaleY(1f).setDuration(260).setInterpolator(overshoot).start() + private fun buildSnack(root: FrameLayout) { + snack = Lx.hbox(this) + snack.background = Lx.rounded(this, 0xF51E2229.toInt(), 8f) + Lx.clipRounded(snack, 8f) + snack.elevation = dp(12f).toFloat() + snackEdge = View(this) + snack.addView(snackEdge, LinearLayout.LayoutParams(dp(4f), ViewGroup.LayoutParams.MATCH_PARENT)) + snackText = Lx.text(this, "", 14f, Lx.TEXT, Lx.MEDIUM, 3) + snackText.setLineSpacing(0f, 1.15f) + snack.addView(snackText, Lx.lp(this, -2f, -2f, start = 14f, top = 12f, end = 16f, bottom = 12f)) + snack.visibility = View.GONE + root.addView(snack, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL).apply { + if (compact) setMargins(dp(16f), 0, dp(16f), dp(BOTTOM_BAR_DP + 12f)) else setMargins(dp(RAIL_DP + 24f), 0, dp(24f), dp(22f)) + }) + } + + private fun pageFor(tab: Tab): Page = + tabPages.getOrPut(tab) { + when (tab) { + Tab.HOME -> HomePage(this) + Tab.MODS -> ModsPage(this) + Tab.ROOMS -> RoomsPage(this) + Tab.RANKS -> LeaderboardPage(this) + Tab.PROFILE -> ProfilePage(this) + Tab.SETTINGS -> SettingsPage(this) } - false } + + private fun currentPage(): Page? = stack.lastOrNull() ?: tabPages[currentTab] + + internal fun isShowing(page: Page): Boolean = shown === page && !isFinishing + + /** Switches to a top-level page, closing any detail pages that were open. */ + internal fun navigate(tab: Tab) { + while (stack.isNotEmpty()) stack.removeAt(stack.size - 1).also { if (it === shown) it.onHide() }.onClose() + if (tab != currentTab && currentTab != Tab.SETTINGS) previousTab = currentTab + currentTab = tab + for ((t, item) in navItems) item.paint(t == tab) + show(pageFor(tab)) } - private fun buildUi() { - root = LinearLayout(this) - root.orientation = LinearLayout.VERTICAL - root.gravity = Gravity.CENTER - val pad = dp(24) - root.setPadding(pad, pad, pad, pad) - - val title = ImageView(this) - title.setImageResource(R.drawable.driftdroid_logo) - title.adjustViewBounds = true - val titleParams = LinearLayout.LayoutParams(dp(240), ViewGroup.LayoutParams.WRAP_CONTENT) - title.layoutParams = titleParams - title.setPadding(0, dp(8), 0, 0) - - val subtitle = TextView(this) - subtitle.text = T("Kart Channel") - subtitle.setTextColor(Color.argb(230, 0xDD, 0xDD, 0xDD)) - subtitle.textSize = 14f - subtitle.gravity = Gravity.CENTER - subtitle.setPadding(0, dp(2), 0, dp(28)) - - baseButton = Button(this) - baseButton.setOnClickListener { launchProduct(MainActivity.PRODUCT_BASE) } - - retroButton = Button(this) - retroButton.setOnClickListener { - if (packWithoutRetroRewind()) { - DriftSheet.message( - this, - "Retro Rewind isn't in your game pack", - "Your game pack was made without Retro Rewind. To play it, run DriftDroid Builder again " + - "with \"Retro Rewind\" ticked and import the new game pack.", - ) - } else if (isRetroRewindInstalled()) { - launchRetroRewindOrUpdate() - } else { - showInstallRetroRewindDialog() + /** Pushes a detail page on top of the current one. */ + internal fun open(page: Page) { + stack.add(page) + show(page) + } + + /** The header's back arrow: a detail page closes; Settings (opened from the gear) returns to where it was opened. */ + private fun goBack() { + if (stack.isNotEmpty()) back() else if (currentTab == Tab.SETTINGS) navigate(previousTab) + } + + /** Closes the top detail page. [force] skips the page's own say (unsaved changes, say). */ + internal fun back(force: Boolean = false) { + val top = stack.lastOrNull() ?: return + if (!force && top.onBack()) return + stack.removeAt(stack.size - 1) + top.onHide() + top.onClose() + actionViews.remove(top) + show(currentPage() ?: pageFor(currentTab)) + } + + private fun show(page: Page) { + val previous = shown + if (previous != null && previous !== page && (previous in stack || tabPages.containsValue(previous))) previous.onHide() + shown = page + pageHost.removeAllViews() + val view = page.view + (view.parent as? ViewGroup)?.removeView(view) + pageHost.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + val detail = stack.isNotEmpty() + // Detail pages slide in from the side; top-level pages rise a little. + view.alpha = 0f + view.translationX = if (detail && page === stack.last()) dp(16f).toFloat() else 0f + view.translationY = if (detail) 0f else dp(8f).toFloat() + view.animate().alpha(1f).translationX(0f).translationY(0f).setDuration(170).start() + backButton.visibility = if (detail || (compact && currentTab == Tab.SETTINGS)) View.VISIBLE else View.GONE + settingsButton.visibility = if (compact && !detail && currentTab != Tab.SETTINGS) View.VISIBLE else View.GONE + actionsBox.removeAllViews() + for (action in actionViews.getOrPut(page) { page.actions() }) { + (action.parent as? ViewGroup)?.removeView(action) + actionsBox.addView(action) + } + refreshHeader(page) + page.onShow() + } + + internal fun refreshHeader(page: Page) { + if (page !== shown) return + titleView.text = page.title + val sub = page.subtitle + subtitleView.text = sub ?: "" + subtitleView.visibility = if (sub.isNullOrEmpty()) View.GONE else View.VISIBLE + val art = page.headerArt + if (art != null) brandArt.setImageResource(art) + brandBox.contentDescription = page.title + brandBox.visibility = if (art != null) View.VISIBLE else View.GONE + titlesBox.visibility = if (art != null) View.GONE else View.VISIBLE + } + + /** Tells every open page that [what] changed. */ + internal fun broadcast(what: Page.Data) { + (tabPages.values + stack).forEach { it.onDataChanged(what) } + shown?.let { refreshHeader(it) } + } + + private val hideSnack = Runnable { snack.animate().alpha(0f).translationY(dp(8f).toFloat()).setDuration(200).withEndAction { snack.visibility = View.GONE }.start() } + + /** A short message over the bottom of the screen, edged in the colour of what it reports. */ + internal fun toast(message: String, tone: Lx.Tone = Lx.Tone.INFO) { + val color = + when (tone) { + Lx.Tone.PRIMARY -> Lx.ACCENT + Lx.Tone.DANGER -> Lx.DANGER + else -> Lx.CYAN } + snackText.text = message + snackEdge.setBackgroundColor(color) + snack.visibility = View.VISIBLE + snack.alpha = 0f + snack.translationY = dp(8f).toFloat() + snack.animate().alpha(1f).translationY(0f).setDuration(160).start() + mainHandler.removeCallbacks(hideSnack) + mainHandler.postDelayed(hideSnack, if (tone == Lx.Tone.DANGER) 6000L else 3800L) + } + + /** Runs [task] off the main thread and hands its result back on it (unless the screen is gone). */ + internal fun work(task: () -> T, done: (Result) -> Unit) { + background.execute { + val result = runCatching(task) + mainHandler.post { if (!isDestroyed) done(result) } } + } - val buttonParams = LinearLayout.LayoutParams(dp(280), dp(64)) - buttonParams.topMargin = dp(14) - - retroMenuButton = Button(this) - retroMenuButton.text = "⋮" // vertical ellipsis ("3 dots") - retroMenuButton.textSize = 18f - retroMenuButton.setOnClickListener { showRetroRewindMenuDialog() } - styleChannelButton(retroMenuButton, Color.rgb(0xF2, 0x5C, 0x4C), Color.rgb(0xD1, 0x2A, 0x1E), dp(14).toFloat()) - - val retroRowParams = - LinearLayout.LayoutParams(dp(280), dp(64)) - retroRowParams.topMargin = dp(14) - val retroRow = LinearLayout(this) - retroRow.orientation = LinearLayout.HORIZONTAL - val retroButtonParams = - LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f) - val retroMenuButtonParams = - LinearLayout.LayoutParams(dp(56), ViewGroup.LayoutParams.MATCH_PARENT) - retroMenuButtonParams.marginStart = dp(8) - retroRow.addView(retroButton, retroButtonParams) - retroRow.addView(retroMenuButton, retroMenuButtonParams) - - progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal) - progressBar.max = 1000 - progressBar.visibility = View.GONE - val progressParams = LinearLayout.LayoutParams(dp(280), ViewGroup.LayoutParams.WRAP_CONTENT) - progressParams.topMargin = dp(14) - - statusText = TextView(this) - statusText.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - statusText.textSize = 13f - statusText.gravity = Gravity.CENTER - statusText.setPadding(0, dp(16), 0, 0) - - - diagnosticsButton = Button(this) - diagnosticsButton.text = T("Export Diagnostics") - diagnosticsButton.textSize = 11f - diagnosticsButton.setOnClickListener { launchDiagnosticsExportPicker() } - val diagnosticsButtonParams = - LinearLayout.LayoutParams(dp(260), dp(40)) - diagnosticsButtonParams.topMargin = dp(24) - styleChannelButton( - diagnosticsButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - diagnosticsButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - diagnosticsButton.setShadowLayer(0f, 0f, 0f, 0) - - serverSettingsButton = Button(this) - serverSettingsButton.text = T("Experimental Server Settings...") - serverSettingsButton.textSize = 11f - serverSettingsButton.setOnClickListener { PrivateServerSettings.show(this) } - val serverSettingsButtonParams = - LinearLayout.LayoutParams(dp(260), dp(40)) - serverSettingsButtonParams.topMargin = dp(8) - styleChannelButton( - serverSettingsButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - serverSettingsButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - serverSettingsButton.setShadowLayer(0f, 0f, 0f, 0) - - // Renderer choice lives here because a device with no working Vulkan driver crashes before - // the in-game settings exist (GitHub issue #3). - graphicsButton = Button(this) - graphicsButton.text = T("Graphics...") - graphicsButton.textSize = 11f - graphicsButton.setOnClickListener { GraphicsSettings.show(this) } - val graphicsButtonParams = - LinearLayout.LayoutParams(dp(260), dp(40)) - graphicsButtonParams.topMargin = dp(8) - styleChannelButton( - graphicsButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - graphicsButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - graphicsButton.setShadowLayer(0f, 0f, 0f, 0) - - // Custom home-screen shortcut icon. Lives here rather than in the in-game sidebar because - // it opens the gallery picker, which must not run over a live game surface (see the - // Mods... button below for the crash that caused). - iconButton = Button(this) - iconButton.text = T("App icon...") - iconButton.textSize = 11f - iconButton.setOnClickListener { IconSettings.show(this) } - val iconButtonParams = - LinearLayout.LayoutParams(dp(260), dp(40)) - iconButtonParams.topMargin = dp(8) - styleChannelButton( - iconButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - iconButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - iconButton.setShadowLayer(0f, 0f, 0f, 0) - - languageButton = Button(this) - languageButton.text = T("Language...") - languageButton.textSize = 11f - languageButton.setOnClickListener { LanguageSettings.show(this) } - val languageButtonParams = LinearLayout.LayoutParams(dp(260), dp(40)) - languageButtonParams.topMargin = dp(8) - styleChannelButton( - languageButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - languageButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - languageButton.setShadowLayer(0f, 0f, 0f, 0) - - // Import/manage from here, not from the in-game settings sidebar - launching Android's - // file picker while a live game session's GPU surface is running lost the WebGPU/Vulkan - // surface on-device ("QueuePresent failed with VK_ERROR_SURFACE_LOST_KHR") and crashed - // the game. No such surface exists yet on this screen, so it's safe here - same reasoning - // as why Retro Rewind's own install flow only ever runs from this Activity. - modsButton = Button(this) - modsButton.text = T("Mods...") - modsButton.textSize = 11f - modsButton.setOnClickListener { ModManager.showManagerDialog(this) } - val modsButtonParams = - LinearLayout.LayoutParams(dp(260), dp(40)) - modsButtonParams.topMargin = dp(8) - styleChannelButton( - modsButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - modsButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - modsButton.setShadowLayer(0f, 0f, 0f, 0) - - val gamePackButton = Button(this) - gamePackButton.text = T("Import Game Pack...") - gamePackButton.textSize = 11f - gamePackButton.setOnClickListener { launchGamePackPicker() } - val gamePackButtonParams = LinearLayout.LayoutParams(dp(260), dp(40)) - gamePackButtonParams.topMargin = dp(8) - styleChannelButton( - gamePackButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - gamePackButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - gamePackButton.setShadowLayer(0f, 0f, 0f, 0) - - // GitHub issue #14: bring a save over from a Wii NAND backup or Dolphin, or copy it out. - val saveDataButton = Button(this) - saveDataButton.text = T("Save Data...") - saveDataButton.textSize = 11f - saveDataButton.setOnClickListener { SaveData.showDialog(this) } - val saveDataButtonParams = LinearLayout.LayoutParams(dp(260), dp(40)) - saveDataButtonParams.topMargin = dp(8) - styleChannelButton( - saveDataButton, - Color.rgb(0x5A, 0x5A, 0x5A), - Color.rgb(0x3A, 0x3A, 0x3A), - dp(12).toFloat(), - ) - saveDataButton.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - saveDataButton.setShadowLayer(0f, 0f, 0f, 0) - - // A square channel-style tile, same idea as baseButton/retroButton but square (96dp, - // matching the eventual custom Mii icon art) rather than a wide banner - Mii Data isn't a - // product to launch, but it's frequent enough (importing/exporting Miis) to earn its own - // channel rather than living in the pale utility-button stack below. - miiDataButton = Button(this) - miiDataButton.setOnClickListener { showMiiDataMenuDialog() } - val miiDataButtonParams = LinearLayout.LayoutParams(dp(96), dp(96)) - miiDataButtonParams.topMargin = dp(14) - styleImageButton( - miiDataButton, - R.drawable.channel_mii_data, - locked = false, - lockedLabel = "", - radius = dp(20).toFloat(), - ) + /** A job long enough to show in the task bar: [task] can report a line of progress as it goes. */ + internal fun task(label: String, task: ((String) -> Unit) -> T, done: (Result) -> Unit) { + val job = LocalTask(label) + localTasks.add(job) + startTaskPolling() + background.execute { + val result = runCatching { task { job.detail = it } } + mainHandler.post { + localTasks.remove(job) + paintTaskBar() + if (!isDestroyed) done(result) + } + } + } - root.addView(title) - root.addView(subtitle) - root.addView(baseButton, buttonParams) - root.addView(retroRow, retroRowParams) - root.addView(miiDataButton, miiDataButtonParams) - root.addView(progressBar, progressParams) - root.addView(statusText) - root.addView(diagnosticsButton, diagnosticsButtonParams) - root.addView(graphicsButton, graphicsButtonParams) - root.addView(iconButton, iconButtonParams) - root.addView(languageButton, languageButtonParams) - root.addView(serverSettingsButton, serverSettingsButtonParams) - root.addView(modsButton, modsButtonParams) - root.addView(saveDataButton, saveDataButtonParams) - root.addView(gamePackButton, gamePackButtonParams) - - // The picker has grown past what fits on-screen in landscape on some phones - confirmed - // directly on-device: the two lowest buttons (server settings, Mii data) were laid out - // fine but simply extended below the visible screen with no way to reach them, since a - // LinearLayout doesn't scroll on its own. A ScrollView guarantees every control stays - // reachable regardless of screen height/font scale, at the cost of no longer being - // perfectly vertically centered when everything DOES fit - worth it for correctness. - val scroll = android.widget.ScrollView(this) - scroll.background = ScrollingCheckerboardDrawable(this) - scroll.addView( - root, - ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT), - ) - setContentView(scroll) - refreshChannelButtons() + internal fun isGameLoaded(): Boolean = MainActivity.isGameLoaded + + /** Runs [block], after a warning when the game is still loaded and could overwrite the change. */ + internal fun guardGameRunning(block: () -> Unit) { + if (!isGameLoaded()) { + block() + return + } + DriftSheet.confirm( + this, + "The game is still open", + "It's running in the background and may write its own copy of this file back when it saves. To be safe, " + + "close DriftDroid from Recents, reopen it and make the change then.", + "Change it anyway", + cancelLabel = "Not now", + ) { block() } } - private fun refreshChannelButtons() { - val romInstalled = isRomImported() - styleImageButton(baseButton, R.drawable.channel_mkwii, locked = !romInstalled, lockedLabel = "Install with ISO/WBFS") - - val retroInstalled = isRetroRewindInstalled() - val notInPack = packWithoutRetroRewind() - styleImageButton( - retroButton, - R.drawable.channel_retro_rewind, - locked = !retroInstalled || notInPack, - lockedLabel = if (notInPack) T("NOT IN GAME PACK") else "INSTALL", - ) - // Nothing to update or delete until a copy is actually installed. - retroMenuButton.visibility = if (retroInstalled) View.VISIBLE else View.GONE + // --- Pickers for pages --- + + private var pendingOpen: ((Uri?) -> Unit)? = null + private var pendingCreate: ((Uri?) -> Unit)? = null + + internal fun openDocument(callback: (Uri?) -> Unit) { + pendingOpen = callback + val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) + intent.addCategory(Intent.CATEGORY_OPENABLE) + // Not restricted by MIME type: many file managers hand files over with a generic or + // missing type, so each caller checks the file itself. + intent.type = "*/*" + startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT) + } + + internal fun createDocument(mime: String, name: String, callback: (Uri?) -> Unit) { + pendingCreate = callback + val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) + intent.addCategory(Intent.CATEGORY_OPENABLE) + intent.type = mime + intent.putExtra(Intent.EXTRA_TITLE, name) + startActivityForResult(intent, REQUEST_CODE_CREATE_DOCUMENT) } + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + val uri = if (resultCode == RESULT_OK) data?.data else null + when (requestCode) { + REQUEST_CODE_OPEN_DOCUMENT -> pendingOpen.also { pendingOpen = null }?.invoke(uri) + REQUEST_CODE_CREATE_DOCUMENT -> pendingCreate.also { pendingCreate = null }?.invoke(uri) + REQUEST_CODE_PICK_RETRO_REWIND_FOLDER -> handleFolderPicked(data?.data) + REQUEST_CODE_PICK_RETRO_REWIND_ZIP -> handleZipPicked(data?.data) + SaveData.REQUEST_CODE_EXPORT -> SaveData.onExportDestinationPicked(this, data?.data) + SaveData.REQUEST_CODE_IMPORT -> SaveData.onImportSourcePicked(this, data?.data) + GpuDriverSettings.REQUEST_CODE_PICK_ZIP -> GpuDriverSettings.onZipPicked(this, data?.data) + IconSettings.REQUEST_CODE_PICK_IMAGE -> IconSettings.onImagePicked(this, data?.data) + } + } + + // --- Task bar --- + + private class LocalTask(val label: String) { + @Volatile var detail: String = "" + } + + private val localTasks = ArrayList() + private var trackingRetroInstall = false + private var pendingRetroLabel: String? = null + private var watchingModInstall = false + private var seenModFinishes = ModInstallJob.finishedCount + private var taskPoller: Runnable? = null + + internal fun watchModInstall() { + if (!watchingModInstall) seenModFinishes = ModInstallJob.finishedCount + watchingModInstall = true + startTaskPolling() + } + + private fun startTaskPolling() { + if (taskPoller != null) return + val poller = + object : Runnable { + override fun run() { + pollTasks() + if (trackingRetroInstall || watchingModInstall || localTasks.isNotEmpty()) { + mainHandler.postDelayed(this, 400) + } else { + taskPoller = null + } + } + } + taskPoller = poller + mainHandler.post(poller) + } + + private fun stopTaskPolling() { + taskPoller?.let { mainHandler.removeCallbacks(it) } + taskPoller = null + } + + private fun pollTasks() { + if (trackingRetroInstall && RetroRewindInstallStatus.finished && !RetroRewindInstallStatus.running) { + trackingRetroInstall = false + pendingRetroLabel = null + finishRetroInstall(RetroRewindInstallStatus.error, RetroRewindInstallStatus.filesDone) + } + if (watchingModInstall && !ModInstallJob.running && ModInstallJob.finishedCount != seenModFinishes) { + watchingModInstall = false + seenModFinishes = ModInstallJob.finishedCount + if (ModInstallJob.stage == ModInstallJob.Stage.DONE) { + toast(T("Installed \"%s\". It loads the next time you start the game.").format(ModInstallJob.title), Lx.Tone.PRIMARY) + } else if (ModInstallJob.error != "cancelled") { + toast(T("Couldn't install \"%s\": %s").format(ModInstallJob.title, ModInstallJob.error ?: "unknown error"), Lx.Tone.DANGER) + } + broadcast(Page.Data.MODS) + } + paintTaskBar() + } + + private fun paintTaskBar() { + val local = localTasks.lastOrNull() + when { + trackingRetroInstall -> { + val total = RetroRewindInstallStatus.totalBytes + taskTitle.text = T("Retro Rewind") + taskDetail.text = + when { + !RetroRewindInstallStatus.running -> pendingRetroLabel ?: T("Starting...") + total > 0 -> T("%s... %s of %s").format(RetroRewindInstallStatus.label, Lx.fileSize(RetroRewindInstallStatus.downloadedBytes), Lx.fileSize(total)) + else -> T("%s... %s files done").format(RetroRewindInstallStatus.label, RetroRewindInstallStatus.filesDone) + } + setProgress(if (total > 0) RetroRewindInstallStatus.downloadedBytes.toFloat() / total else -1f) + taskCancel.visibility = View.GONE + taskBar.visibility = View.VISIBLE + } + ModInstallJob.running -> { + taskTitle.text = ModInstallJob.title + val total = ModInstallJob.bytesTotal + if (ModInstallJob.stage == ModInstallJob.Stage.DOWNLOADING) { + taskDetail.text = + if (total > 0) T("Downloading... %s of %s").format(Lx.fileSize(ModInstallJob.bytesDone), Lx.fileSize(total)) + else T("Downloading... %s").format(Lx.fileSize(ModInstallJob.bytesDone)) + setProgress(if (total > 0) ModInstallJob.bytesDone.toFloat() / total else -1f) + taskCancel.visibility = View.VISIBLE + } else { + taskDetail.text = T("Unpacking... %s files").format(ModInstallJob.filesUnpacked) + setProgress(-1f) + taskCancel.visibility = View.GONE + } + taskBar.visibility = View.VISIBLE + } + local != null -> { + taskTitle.text = local.label + taskDetail.text = local.detail.ifEmpty { T("Working...") } + setProgress(-1f) + taskCancel.visibility = View.GONE + taskBar.visibility = View.VISIBLE + } + else -> taskBar.visibility = View.GONE + } + } + + private fun setProgress(fraction: Float) { + if (fraction < 0f) { + taskProgress.isIndeterminate = true + } else { + taskProgress.isIndeterminate = false + taskProgress.progress = (fraction.coerceIn(0f, 1f) * 1000).toInt() + } + } + + // --- The games --- + + internal fun isRomImported(): Boolean = + com.driftdroid.android.rom.RomImportOverlay.isRomAlreadyImported(File(filesDir, "WiiCompiled/DiscData")) + + internal fun isRetroRewindInstalled(): Boolean = File(retroRewindRoot(), "Binaries/Code.pul").isFile + + internal fun retroRewindVersion(): String? = RetroRewindCatalog.installedVersion(retroRewindRoot()) + /** A game pack is in and it was built without Retro Rewind. */ - private fun packWithoutRetroRewind(): Boolean = + internal fun packWithoutRetroRewind(): Boolean = GamePack.state(this) == GamePack.State.Ready && !GamePack.hasRetroRewind(this) - private fun isRomImported(): Boolean = - com.driftdroid.android.rom.RomImportOverlay.isRomAlreadyImported(File(filesDir, "WiiCompiled/DiscData")) + private fun retroRewindRoot(): File = File(filesDir, MainActivity.RETRO_REWIND_STAGING_SUBDIR) + + /** Plays the original game. Without the disc's data yet, MainActivity asks for the image first. */ + internal fun playBase() { + UiSounds.playClick(this) + launchProduct(MainActivity.PRODUCT_BASE) + } - private fun showRetroRewindMenuDialog() { - val sheet = DriftSheet(this, "Retro Rewind", RetroRewindCatalog.installedVersion(retroRewindRoot())?.let { T("Installed: %s").format(it) }) + internal fun playRetroRewind() { + UiSounds.playClick(this) + if (packWithoutRetroRewind()) { + DriftSheet.message( + this, + "Retro Rewind isn't in your game pack", + "Your game pack was made without Retro Rewind. To play it, run DriftDroid Builder again " + + "with \"Retro Rewind\" ticked and import the new game pack.", + ) + } else if (isRetroRewindInstalled()) { + launchRetroRewindOrUpdate() + } else { + showInstallRetroRewindDialog() + } + } + + internal fun showRetroRewindMenu() { + val sheet = DriftSheet(this, "Retro Rewind", retroRewindVersion()?.let { T("Installed: %s").format(it) }) sheet.action("Check for updates", "Downloads only what changed") { sheet.dismiss() startDeltaUpdate() @@ -505,17 +755,11 @@ class ModePickerActivity : Activity() { danger = true, ) { retroRewindRoot().deleteRecursively() - refreshChannelButtons() - statusText.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - statusText.text = T("Retro Rewind deleted.") + broadcast(Page.Data.INSTALL) + toast(T("Retro Rewind deleted.")) } } - private fun isRetroRewindInstalled(): Boolean = - File(retroRewindRoot(), "Binaries/Code.pul").isFile - - private fun retroRewindRoot(): File = File(filesDir, MainActivity.RETRO_REWIND_STAGING_SUBDIR) - /** * Starts Retro Rewind - unless the installed copy holds game code this build isn't compiled * for, which is what an install made by an older DriftDroid looks like after the app has been @@ -525,24 +769,18 @@ class ModePickerActivity : Activity() { */ private fun launchRetroRewindOrUpdate() { val root = retroRewindRoot() - retroButton.isEnabled = false - Thread { - val supported = RetroRewindCatalog.isSupportedCodePul(RetroRewindCatalog.installedCodePulSha256(root)) - mainHandler.post { - retroButton.isEnabled = true - if (isFinishing || isDestroyed) return@post - if (supported) { - launchProduct(MainActivity.PRODUCT_RETRO_REWIND) - } else { - val installed = RetroRewindCatalog.installedVersion(root) - beginImportUi( - T("Retro Rewind %s needs updating for this version of DriftDroid - updating it now...").format(installed ?: ""), - ) - RetroRewindInstallService.startDeltaUpdate(this) - startStatusPolling() - } + work({ RetroRewindCatalog.isSupportedCodePul(RetroRewindCatalog.installedCodePulSha256(root)) }) { result -> + if (isFinishing) return@work + if (result.getOrDefault(false)) { + launchProduct(MainActivity.PRODUCT_RETRO_REWIND) + } else { + val installed = RetroRewindCatalog.installedVersion(root) + beginRetroInstall( + T("Retro Rewind %s needs updating for this version of DriftDroid - updating it now...").format(installed ?: ""), + ) + RetroRewindInstallService.startDeltaUpdate(this) } - }.start() + } } private fun launchProduct(product: String) { @@ -569,7 +807,8 @@ class ModePickerActivity : Activity() { ) sheet.action("Download it", "About 1.9 GB. Wi-Fi recommended") { sheet.dismiss() - startLatestInstall() + beginRetroInstall(T("Checking for the newest Retro Rewind...")) + RetroRewindInstallService.startLatestInstall(this) } sheet.action("Pick a .zip I have", "The file exactly as downloaded") { sheet.dismiss() @@ -582,26 +821,39 @@ class ModePickerActivity : Activity() { sheet.show() } - private fun startDownloadInstall() { - beginImportUi(T("Downloading Retro Rewind %s...").format(RetroRewindRelease.VERSION)) - RetroRewindInstallService.startDownloadInstall(this) - startStatusPolling() - } - - /** Installs whatever the live release catalog says is newest AND runnable on this build, - * rather than only ever the release that was current when the app was compiled. */ - private fun startLatestInstall() { - beginImportUi(T("Checking for the newest Retro Rewind...")) - RetroRewindInstallService.startLatestInstall(this) - startStatusPolling() - } - /** Applies the mod's own small per-version update archives to the existing install - a few MB * rather than another ~1.9GB. */ private fun startDeltaUpdate() { - beginImportUi(T("Checking for Retro Rewind updates...")) + beginRetroInstall(T("Checking for Retro Rewind updates...")) RetroRewindInstallService.startDeltaUpdate(this) - startStatusPolling() + } + + /** The install itself runs in [RetroRewindInstallService] (a foreground service that outlives + * this Activity); the task bar follows [RetroRewindInstallStatus] until it finishes. */ + private fun beginRetroInstall(label: String) { + pendingRetroLabel = label + trackingRetroInstall = true + // A finished flag left over from an earlier run must not end this one before it starts. + RetroRewindInstallStatus.finished = false + broadcast(Page.Data.INSTALL) + startTaskPolling() + } + + private fun finishRetroInstall(error: String?, filesCount: Int) { + if (error == null) { + toast(RetroRewindInstallStatus.successMessage ?: T("Retro Rewind installed (%s files).").format(filesCount), Lx.Tone.PRIMARY) + } else { + // Leave no half-copied install behind - isRetroRewindInstalled() only checks for + // Code.pul, and a partial copy that happened to include it would then look + // "installed" while actually missing tracks/assets. Only when the install really was + // being rebuilt, though: a refused version or an update check that couldn't finish + // has not touched the working install, and deleting it then cost the player 1.9GB. + if (RetroRewindInstallStatus.installIncomplete) { + retroRewindRoot().deleteRecursively() + } + DriftSheet.message(this, "Retro Rewind", T("Install failed: %s").format(error)) + } + broadcast(Page.Data.INSTALL) } private fun launchRetroRewindFolderPicker() { @@ -622,181 +874,80 @@ class ModePickerActivity : Activity() { intent.addCategory(Intent.CATEGORY_OPENABLE) // Not restricted to "application/zip": many file managers/browsers hand a downloaded zip // over with a generic or missing MIME type - the extension check on the picked file (see - // onActivityResult) is the real gate, same reasoning as RomImportOverlay's ISO/WBFS picker. + // handleZipPicked) is the real gate, same reasoning as RomImportOverlay's ISO/WBFS picker. intent.type = "*/*" startActivityForResult(intent, REQUEST_CODE_PICK_RETRO_REWIND_ZIP) } - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { - super.onActivityResult(requestCode, resultCode, data) - when (requestCode) { - REQUEST_CODE_PICK_RETRO_REWIND_FOLDER -> handleFolderPicked(data?.data) - REQUEST_CODE_PICK_RETRO_REWIND_ZIP -> handleZipPicked(data?.data) - REQUEST_CODE_EXPORT_DIAGNOSTICS -> handleDiagnosticsDestinationPicked(data?.data) - REQUEST_CODE_EXPORT_MII_DATA -> handleMiiExportDestinationPicked(data?.data) - REQUEST_CODE_IMPORT_MII_DATA -> handleMiiImportSourcePicked(data?.data) - REQUEST_CODE_IMPORT_SINGLE_MII -> handleSingleMiiSourcePicked(data?.data) - ModManager.REQUEST_CODE_PICK_ZIP -> ModManager.onZipPicked(this, data?.data) - REQUEST_CODE_IMPORT_GAME_PACK -> handleGamePackPicked(data?.data) - SaveData.REQUEST_CODE_EXPORT -> SaveData.onExportDestinationPicked(this, data?.data) - SaveData.REQUEST_CODE_IMPORT -> SaveData.onImportSourcePicked(this, data?.data) - GpuDriverSettings.REQUEST_CODE_PICK_ZIP -> GpuDriverSettings.onZipPicked(this, data?.data) - IconSettings.REQUEST_CODE_PICK_IMAGE -> IconSettings.onImagePicked(this, data?.data) - } - } - - /** - * The Mii Channel's own database (RFL_DB.dat, distinct from RFL_Res.dat - the read-only face - * resource seeded from the ISO by nand_fs.cpp's SeedFaceLibResource, never written by the - * player) - lives at NAND/shared2/menu/FaceLib/RFL_DB.dat under filesDir/WiiCompiled, since - * ApplicationDataDirectory() / "NAND" (nand_path.h) resolves to that same directory on - * Android. A fixed-size file (779968 bytes, the standard RFL database size on real Wii/Wii - * consoles) - checked before import so a wrong/corrupt file can't silently wedge the Mii - * Channel, with the previous database always backed up first regardless. - */ - private fun miiDatabaseFile(): File = - File(filesDir, "WiiCompiled/NAND/shared2/menu/FaceLib/RFL_DB.dat") - - private fun showMiiDataMenuDialog() { - val sheet = DriftSheet(this, "Mii data", T("The Miis in the Mii Channel")) - sheet.note("Start Mario Kart Wii at least once first: that makes the Mii file.") - sheet.action("Export all Miis", "Saves RFL_DB.dat where you choose") { - sheet.dismiss() - launchMiiExportPicker() - } - sheet.action("Replace all Miis", "From an RFL_DB.dat file. The current one is backed up") { - sheet.dismiss() - launchMiiImportPicker() + private fun handleFolderPicked(treeUri: Uri?) { + if (treeUri == null) return + // Best-effort: the transient grant this Activity already holds is enough to run the copy + // (the service is the same UID, same process), so a provider that refuses to persist is + // not a reason to fail the import - and must never be a reason to crash. + try { + contentResolver.takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } catch (_: SecurityException) { } - sheet.action("Add one Mii", "From a .rcd file, into a free slot") { - sheet.dismiss() - launchSingleMiiImportPicker() + val picked = DocumentFile.fromTreeUri(this, treeUri) + if (picked == null) { + toast(T("Couldn't open that folder - try picking it again."), Lx.Tone.DANGER) + return } - sheet.show() - } - - private fun launchSingleMiiImportPicker() { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "*/*" - startActivityForResult(intent, REQUEST_CODE_IMPORT_SINGLE_MII) - } - - private fun handleSingleMiiSourcePicked(source: Uri?) { - if (source == null) return - insertSingleMii(source) - } - - /** - * Inserts one standalone Mii (.rcd, the 74-byte Wii Mii exchange format) into a free slot in - * the existing database - see MiiDatabaseEditor.kt for the format details and where they came - * from. Backs up the current database first, same as the whole-database Replace path. - */ - private fun insertSingleMii(source: Uri) { - try { - val size = queryFileSize(source) - if (size >= 0 && size != MiiDatabaseEditor.MII_RECORD_BYTES.toLong()) { - throw IllegalArgumentException( - "not a single-Mii file (expected ${MiiDatabaseEditor.MII_RECORD_BYTES} bytes, got $size)", + // Walking a SAF tree means a content-provider round trip per entry, which on a big folder + // on slow storage is far too slow for the main thread (an ANR reads to the player exactly + // like a crash). Resolve off-thread, then come back to the UI. + task(T("Checking the selected folder..."), { resolveRetroRewind6(picked) }) { result -> + val resolved = result.getOrNull() + if (resolved == null) { + DriftSheet.message( + this, + "Retro Rewind", + T("That folder doesn't contain RetroRewind6/Binaries/Code.pul - pick the folder you extracted Retro Rewind into (or the RetroRewind6 folder itself)."), ) + return@task } - val record = - contentResolver.openInputStream(source)?.use { it.readBytes() } - ?: throw IllegalStateException("couldn't open the picked file") - - val dbFile = miiDatabaseFile() - if (!dbFile.isFile) { - throw IllegalStateException("no existing Mii database - start Mario Kart Wii once first") - } - val database = dbFile.readBytes() - - when (val result = MiiDatabaseEditor.insertMii(database, record)) { - is MiiDatabaseEditor.Result.Failure -> throw IllegalStateException(result.message) - is MiiDatabaseEditor.Result.Success -> { - val backup = File(dbFile.parentFile, "RFL_DB.dat.bak") - dbFile.copyTo(backup, overwrite = true) - dbFile.writeBytes(result.database) - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = T("Mii added to slot %s of 100.").format(result.slotIndex + 1) - } - } - } catch (e: Exception) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Mii import failed: %s").format(e.message ?: "unknown error") + beginRetroInstall(T("Copying Retro Rewind files - this can take a while for ~2GB...")) + RetroRewindInstallService.startFolderInstall(this, resolved.uri) } } - private fun launchMiiExportPicker() { - if (!miiDatabaseFile().isFile) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("No Mii database yet - start Mario Kart Wii once first.") + private fun handleZipPicked(uri: Uri?) { + if (uri == null) return + val name = queryDisplayName(uri) ?: uri.lastPathSegment ?: "selected file" + if (!name.substringAfterLast('.', "").equals("zip", ignoreCase = true)) { + toast(T("\"%s\" isn't a .zip file - pick the Retro Rewind archive you downloaded.").format(name), Lx.Tone.DANGER) return } - val stamp = SimpleDateFormat("yyyy-MM-dd_HHmmss", Locale.US).format(Date()) - val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "application/octet-stream" - intent.putExtra(Intent.EXTRA_TITLE, "DriftDroid-Mii-$stamp.dat") - startActivityForResult(intent, REQUEST_CODE_EXPORT_MII_DATA) + beginRetroInstall(T("Extracting \"%s\" - this can take a while for ~2GB...").format(name)) + RetroRewindInstallService.startZipInstall(this, uri, name) } - private fun handleMiiExportDestinationPicked(destination: Uri?) { - if (destination == null) return + private fun queryDisplayName(uri: Uri): String? = try { - contentResolver.openOutputStream(destination)?.use { output -> - miiDatabaseFile().inputStream().use { input -> input.copyTo(output) } - } ?: throw IllegalStateException("couldn't open the chosen destination") - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = T("Mii data exported.") - } catch (e: Exception) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Mii export failed: %s").format(e.message ?: "unknown error") + contentResolver.query(uri, null, null, null, null)?.use { cursor -> + val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null + } + } catch (_: Exception) { + null } - } - private fun launchMiiImportPicker() { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "*/*" - startActivityForResult(intent, REQUEST_CODE_IMPORT_MII_DATA) - } - - private fun handleMiiImportSourcePicked(source: Uri?) { - if (source == null) return - DriftSheet.confirm( - this, - "Replace all Miis?", - "Every Mii in the Mii Channel is replaced with the picked file's Miis. The current ones are " + - "backed up first (RFL_DB.dat.bak) in case this goes wrong.", - "Replace", - danger = true, - ) { importMiiDatabase(source) } - } - - private fun importMiiDatabase(source: Uri): Unit = - try { - val picked = - contentResolver.openInputStream(source)?.use { it.readBytes() } - ?: throw IllegalStateException("couldn't open the picked file") - // Real CRC-16 validation (matches KartPad's own check), not just a size comparison - - // catches a corrupted-but-right-size file that a size-only check would wave through. - if (!MiiDatabaseEditor.isValidDatabase(picked)) { - throw IllegalArgumentException("that doesn't look like a valid Mii database file") - } - val dest = miiDatabaseFile() - if (!dest.isFile) { - throw IllegalStateException("no existing Mii database - start Mario Kart Wii once first") + /** Mirrors the PC installer's RetroRewindSource.ResolveRetroRewind6: accept either the + * RetroRewind6 folder itself, its parent, or a one-level-deeper wrapper folder. */ + private fun resolveRetroRewind6(picked: DocumentFile): DocumentFile? { + val candidates = mutableListOf(picked) + picked.findFile("RetroRewind6")?.let { candidates.add(it) } + for (child in picked.listFiles()) { + if (child.isDirectory) { + child.findFile("RetroRewind6")?.let { candidates.add(it) } } - val backup = File(dest.parentFile, "RFL_DB.dat.bak") - dest.copyTo(backup, overwrite = true) - dest.writeBytes(picked) - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = T("Mii data replaced (previous copy saved as RFL_DB.dat.bak).") - Unit - } catch (e: Exception) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Mii import failed: %s").format(e.message ?: "unknown error") } + return candidates.firstOrNull { candidate -> + candidate.findFile("Binaries")?.findFile("Code.pul")?.isFile == true + } + } + + // --- Game pack --- private fun showGamePackNeededDialog(wrongVersion: Boolean) { val message = @@ -813,39 +964,30 @@ class ModePickerActivity : Activity() { } sheet.button("Import game pack", DriftUi.Style.PRIMARY) { sheet.dismiss() - launchGamePackPicker() + importGamePack() } sheet.show() } - private fun launchGamePackPicker() { - val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "*/*" - startActivityForResult(intent, REQUEST_CODE_IMPORT_GAME_PACK) - } - - private fun handleGamePackPicked(source: Uri?) { - if (source == null) return - statusText.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - statusText.text = T("Importing the game pack...") - Thread { - val error = - GamePack.import(this, source) { bytes -> - mainHandler.post { statusText.text = T("Importing the game pack... %s MB").format(bytes / (1 shl 20)) } - } - mainHandler.post { + internal fun importGamePack() { + openDocument { source -> + if (source == null) return@openDocument + task(T("Importing the game pack..."), { progress -> + GamePack.import(this, source) { bytes -> progress(T("%s MB").format(bytes / (1 shl 20))) } + }) { result -> + val error = result.getOrElse { it.message ?: "unknown error" } if (error == null) { - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = T("Game pack imported. You can play now.") + toast(T("Game pack imported. You can play now."), Lx.Tone.PRIMARY) + broadcast(Page.Data.INSTALL) } else { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Game pack import failed: %s").format(error) + DriftSheet.message(this, "Game pack", T("Game pack import failed: %s").format(error)) } } - }.start() + } } + // --- Diagnostics --- + /** * Bundles the runtime's own log files (see android_jni_bridge.cpp's freopen() of * stdout/stderr, and main.cpp's per-run Logs/__pid/console.log folders - @@ -854,33 +996,16 @@ class ModePickerActivity : Activity() { * so troubleshooting doesn't require a USB cable and `adb shell run-as ... cat` - the only way * this app's logs have been readable until now. */ - private fun launchDiagnosticsExportPicker() { + internal fun exportDiagnostics() { val stamp = SimpleDateFormat("yyyy-MM-dd_HHmmss", Locale.US).format(Date()) - val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) - intent.addCategory(Intent.CATEGORY_OPENABLE) - intent.type = "application/zip" - intent.putExtra(Intent.EXTRA_TITLE, "DriftDroid-diagnostics-$stamp.zip") - startActivityForResult(intent, REQUEST_CODE_EXPORT_DIAGNOSTICS) - } - - private fun handleDiagnosticsDestinationPicked(destination: Uri?) { - if (destination == null) return - statusText.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - statusText.text = T("Exporting diagnostics...") - val thread = - Thread { - val error = writeDiagnosticsZip(destination) - mainHandler.post { - if (error == null) { - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = T("Diagnostics exported.") - } else { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Diagnostics export failed: %s").format(error) - } - } + createDocument("application/zip", "DriftDroid-diagnostics-$stamp.zip") { destination -> + if (destination == null) return@createDocument + task(T("Exporting diagnostics..."), { writeDiagnosticsZip(destination) }) { result -> + val error = result.getOrElse { it.message ?: "unknown error" } + if (error == null) toast(T("Diagnostics exported."), Lx.Tone.PRIMARY) + else toast(T("Diagnostics export failed: %s").format(error), Lx.Tone.DANGER) } - thread.start() + } } private fun writeDiagnosticsZip(destination: Uri): String? { @@ -904,9 +1029,9 @@ class ModePickerActivity : Activity() { zip.putNextEntry(ZipEntry("README.txt")) zip.write( buildString { - appendLine("DriftDroid runtime diagnostics - review before sharing.") - appendLine("Device: ${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}") - appendLine("API level: ${android.os.Build.VERSION.SDK_INT}") + appendLine("${getString(R.string.app_name)} runtime diagnostics - review before sharing.") + appendLine("Device: ${Build.MANUFACTURER} ${Build.MODEL}") + appendLine("API level: ${Build.VERSION.SDK_INT}") appendLine("App version: ${appVersionName()}") appendLine("Memory: ${totalMemoryMiB()} MiB") appendLine("Each log is truncated to its last $MAX_LOG_FILE_BYTES bytes.") @@ -955,7 +1080,7 @@ class ModePickerActivity : Activity() { } } - private fun appVersionName(): String = + internal fun appVersionName(): String = try { packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown" } catch (_: Exception) { @@ -1037,273 +1162,16 @@ class ModePickerActivity : Activity() { } } - private fun handleFolderPicked(treeUri: Uri?) { - if (treeUri == null) return - // Best-effort: the transient grant this Activity already holds is enough to run the copy - // (the service is the same UID, same process), so a provider that refuses to persist is - // not a reason to fail the import - and must never be a reason to crash. - try { - contentResolver.takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION) - } catch (_: SecurityException) { - } - val picked = DocumentFile.fromTreeUri(this, treeUri) - if (picked == null) { - showImportError(T("Couldn't open that folder - try picking it again.")) - return - } - // Walking a SAF tree means a content-provider round trip per entry, which on a big folder - // on slow storage is far too slow for the main thread (an ANR reads to the player exactly - // like the crash above). Resolve off-thread, then come back to the UI. - beginImportUi(T("Checking the selected folder...")) - Thread { - val resolved = - try { - resolveRetroRewind6(picked) - } catch (_: Exception) { - null - } - mainHandler.post { - if (isFinishing || isDestroyed) return@post - if (resolved == null) { - endImportUi() - showImportError( - T("That folder doesn't contain RetroRewind6/Binaries/Code.pul - pick the folder you extracted Retro Rewind into (or the RetroRewind6 folder itself)."), - ) - return@post - } - statusText.text = T("Copying Retro Rewind files - this can take a while for ~2GB...") - RetroRewindInstallService.startFolderInstall(this, resolved.uri) - startStatusPolling() - } - }.start() - } - - private fun showImportError(message: String) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = message - } - - private fun handleZipPicked(uri: Uri?) { - if (uri == null) return - val name = queryDisplayName(uri) ?: uri.lastPathSegment ?: "selected file" - if (!name.substringAfterLast('.', "").equals("zip", ignoreCase = true)) { - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = "\"$name\" isn't a .zip file - pick the Retro Rewind archive you downloaded." - return - } - beginImportUi(T("Extracting \"%s\" - this can take a while for ~2GB...").format(name)) - RetroRewindInstallService.startZipInstall(this, uri, name) - startStatusPolling() - } - - private fun queryDisplayName(uri: Uri): String? = - try { - contentResolver.query(uri, null, null, null, null)?.use { cursor -> - val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) - if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null - } - } catch (_: Exception) { - null - } - - /** Mirrors the PC installer's RetroRewindSource.ResolveRetroRewind6: accept either the - * RetroRewind6 folder itself, its parent, or a one-level-deeper wrapper folder. */ - private fun resolveRetroRewind6(picked: DocumentFile): DocumentFile? { - val candidates = mutableListOf(picked) - picked.findFile("RetroRewind6")?.let { candidates.add(it) } - for (child in picked.listFiles()) { - if (child.isDirectory) { - child.findFile("RetroRewind6")?.let { candidates.add(it) } - } - } - return candidates.firstOrNull { candidate -> - candidate.findFile("Binaries")?.findFile("Code.pul")?.isFile == true - } - } - - private fun beginImportUi(statusMessage: String) { - baseButton.isEnabled = false - retroButton.isEnabled = false - progressBar.visibility = View.VISIBLE - // Indeterminate (spinning), not a 0-100% fill: neither the folder-copy nor the zip-extract - // path knows the total file/byte count up front without a slow pre-scan, so a fixed - // progress value just sat frozen at 0% the whole time - confirmed directly as "no progress - // bar... which is weird" (it was there, just never moving, so it looked broken/absent). - // The file-count text next to it already gives a live sense of movement. - progressBar.isIndeterminate = true - statusText.setTextColor(Color.rgb(0xDD, 0xDD, 0xDD)) - statusText.text = statusMessage - } - - /** Puts the buttons/progress bar back without writing any status text - for bailing out of an - * import before the service was ever started (the caller sets its own message). */ - private fun endImportUi() { - progressBar.isIndeterminate = false - progressBar.visibility = View.GONE - baseButton.isEnabled = true - retroButton.isEnabled = true - } - - private fun finishImportUi(error: String?, filesCount: Int) { - endImportUi() - if (error == null) { - statusText.setTextColor(Color.rgb(20, 140, 60)) - statusText.text = - RetroRewindInstallStatus.successMessage ?: T("Retro Rewind installed (%s files).").format(filesCount) - refreshChannelButtons() - } else { - // Leave no half-copied install behind - isRetroRewindInstalled() only checks for - // Code.pul, and a partial copy that happened to include it would then look - // "installed" while actually missing tracks/assets. Only when the install really was - // being rebuilt, though: a refused version or an update check that couldn't finish - // has not touched the working install, and deleting it then cost the player 1.9GB. - if (RetroRewindInstallStatus.installIncomplete) { - retroRewindRoot().deleteRecursively() - } - refreshChannelButtons() - statusText.setTextColor(Color.rgb(190, 30, 30)) - statusText.text = T("Install failed: %s").format(error) - } - } - - /** - * The actual copy/extract now runs in [RetroRewindInstallService], a foreground service that - * outlives this Activity's lifecycle (see the service's own doc comment for why - short - * version: a plain background Thread here died whenever Android reclaimed this Activity's - * process while backgrounded, losing the whole ~2GB copy). This just reflects - * [RetroRewindInstallStatus] into the UI, polling rather than needing a callback since a - * brand new Activity instance (post-recreation) can start polling and pick up exactly where - * an old, now-gone instance left off. - */ - private var statusPoller: Runnable? = null - - private fun startStatusPolling() { - if (statusPoller != null) return - val poller = - object : Runnable { - override fun run() { - if (RetroRewindInstallStatus.finished) { - statusPoller = null - finishImportUi(RetroRewindInstallStatus.error, RetroRewindInstallStatus.filesDone) - return - } - val totalBytes = RetroRewindInstallStatus.totalBytes - statusText.text = - if (totalBytes > 0) { - val doneMb = RetroRewindInstallStatus.downloadedBytes / (1024 * 1024) - val totalMb = totalBytes / (1024 * 1024) - "${RetroRewindInstallStatus.label}... ${doneMb}MB / ${totalMb}MB" - } else { - "${RetroRewindInstallStatus.label}... ${RetroRewindInstallStatus.filesDone} files done" - } - mainHandler.postDelayed(this, 500) - } - } - statusPoller = poller - mainHandler.post(poller) - } - - private fun stopStatusPolling() { - statusPoller?.let { mainHandler.removeCallbacks(it) } - statusPoller = null - } - - private fun queryFileSize(uri: Uri): Long = - try { - contentResolver.query(uri, null, null, null, null)?.use { cursor -> - val index = cursor.getColumnIndex(OpenableColumns.SIZE) - if (index >= 0 && cursor.moveToFirst() && !cursor.isNull(index)) cursor.getLong(index) else -1L - } ?: -1L - } catch (_: Exception) { - -1L - } - companion object { + private const val STATE_TAB = "tab" + private const val BOTTOM_BAR_DP = 66f + private const val RAIL_DP = 88f private const val REQUEST_CODE_PICK_RETRO_REWIND_FOLDER = 0x52520000 // "RR" private const val REQUEST_CODE_PICK_RETRO_REWIND_ZIP = 0x52520001 - private const val REQUEST_CODE_EXPORT_DIAGNOSTICS = 0x52520002 + private const val REQUEST_CODE_OPEN_DOCUMENT = 0x4C4E0001 // "LN" + private const val REQUEST_CODE_CREATE_DOCUMENT = 0x4C4E0002 private const val MAX_LOG_FILES = 12 private const val MAX_LOG_FILE_BYTES = 4L * 1024 * 1024 private const val MAX_EXIT_REASONS = 10 - private const val REQUEST_CODE_IMPORT_GAME_PACK = 0x47500000 // "GP" - private const val REQUEST_CODE_EXPORT_MII_DATA = 0x52520003 - private const val REQUEST_CODE_IMPORT_MII_DATA = 0x52520004 - private const val REQUEST_CODE_IMPORT_SINGLE_MII = 0x52520005 - } -} - -/** - * A gray checkerboard wallpaper, tiled and drifting diagonally forever - replaces the earlier sky - * gradient background. A Drawable (not a View) so it can just be dropped in as `view.background`; - * animates itself via Drawable.scheduleSelf, which only works because setting a Drawable as a - * View's background makes that View its Drawable.Callback automatically (no manual wiring needed, - * and it stops scheduling redraws on its own once the View is gone/detached). - */ -private class ScrollingCheckerboardDrawable(context: android.content.Context) : Drawable() { - private val tilePx = (28 * context.resources.displayMetrics.density).toInt().coerceAtLeast(8) - private val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG) - private val shader: android.graphics.BitmapShader - private val localMatrix = android.graphics.Matrix() - private var offsetPx = 0f - private var lastFrameUptimeMs = android.os.SystemClock.uptimeMillis() - private var started = false - - init { - val size = tilePx * 2 - val bitmap = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888) - val canvas = android.graphics.Canvas(bitmap) - val light = android.graphics.Paint().apply { color = Color.rgb(0x3A, 0x3A, 0x3A) } - val dark = android.graphics.Paint().apply { color = Color.rgb(0x22, 0x22, 0x22) } - val t = tilePx.toFloat() - val s = size.toFloat() - canvas.drawRect(0f, 0f, t, t, light) - canvas.drawRect(t, 0f, s, t, dark) - canvas.drawRect(0f, t, t, s, dark) - canvas.drawRect(t, t, s, s, light) - shader = android.graphics.BitmapShader( - bitmap, android.graphics.Shader.TileMode.REPEAT, android.graphics.Shader.TileMode.REPEAT, - ) - paint.shader = shader - } - - private val tick = - object : Runnable { - override fun run() { - val now = android.os.SystemClock.uptimeMillis() - val deltaMs = (now - lastFrameUptimeMs).coerceIn(0, 100) - lastFrameUptimeMs = now - offsetPx += deltaMs * SPEED_PX_PER_MS - invalidateSelf() - scheduleSelf(this, now + FRAME_INTERVAL_MS) - } - } - - override fun draw(canvas: android.graphics.Canvas) { - localMatrix.setTranslate(offsetPx, offsetPx * 0.6f) - shader.setLocalMatrix(localMatrix) - canvas.drawRect(bounds, paint) - // First draw() (right after the background is actually attached/visible) is what starts - // the animation loop, once - scheduling from init{} instead would need scheduleSelf's - // Callback (set by View.setBackground) that doesn't exist yet at construction time; after - // this, `tick` reschedules itself, so draw() must NOT also reschedule on every frame (that - // would stack a second, independent chain of ticks on top of tick's own, each triggering - // more invalidateSelf() calls than the last - confirmed this exact mistake in an earlier - // draft, caught before it shipped). - if (!started) { - started = true - lastFrameUptimeMs = android.os.SystemClock.uptimeMillis() - scheduleSelf(tick, lastFrameUptimeMs + FRAME_INTERVAL_MS) - } - } - - override fun setAlpha(alpha: Int) {} - - override fun setColorFilter(colorFilter: android.graphics.ColorFilter?) {} - - override fun getOpacity(): Int = android.graphics.PixelFormat.OPAQUE - - companion object { - private const val FRAME_INTERVAL_MS = 32L // ~30fps - plenty smooth for a slow drift - private const val SPEED_PX_PER_MS = 0.006f // slow: one tile crossed roughly every 9s } } diff --git a/android/app/src/main/kotlin/com/driftdroid/android/SaveData.kt b/android/app/src/main/kotlin/com/driftdroid/android/SaveData.kt index 119b26c..0a29f69 100644 --- a/android/app/src/main/kotlin/com/driftdroid/android/SaveData.kt +++ b/android/app/src/main/kotlin/com/driftdroid/android/SaveData.kt @@ -28,7 +28,7 @@ internal object SaveData { /** "RKSD" header, then a CRC-32 of the first 0x27FFC bytes stored big-endian at 0x27FFC. */ private const val CHECKSUM_OFFSET = 0x27FFC - private enum class Game(val label: String, val relativePath: String) { + internal enum class Game(val label: String, val relativePath: String) { MarioKartWii("Mario Kart Wii", "WiiCompiled/NAND/title/00010004/524d4350/data/rksys.dat"), RetroRewind("Retro Rewind", "WiiCompiled/riivolution/save/RetroWFC/RMCP/rksys.dat"), } diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/HomePage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/HomePage.kt new file mode 100644 index 0000000..89ea4ed --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/HomePage.kt @@ -0,0 +1,282 @@ +package com.driftdroid.android.launcher + +import android.graphics.ColorMatrix +import android.graphics.ColorMatrixColorFilter +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import com.driftdroid.android.ModManager +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.R +import com.driftdroid.android.RetroRewindInstallStatus +import com.driftdroid.android.SaveData +import com.driftdroid.android.T +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.online.RetroWfc +import com.driftdroid.android.profile.SaveFile +import com.driftdroid.android.ui.AspectImageView +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx + +/** The first page: the start grid (the two games, ready to play or to install) and a glance trackside. */ +internal class HomePage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Home") + override val headerArt: Int get() = R.drawable.driftdroid_logo + + private lateinit var baseCard: GameCard + private lateinit var retroCard: GameCard + private lateinit var onlineTile: Tile + private lateinit var racerTile: Tile + private lateinit var modsTile: Tile + private var lastRoomsFetch = 0L + + override fun build(): View { + val column = Lx.vbox(context) + column.setPadding(gutter, dp(4f), gutter, dp(28f)) + + column.addView(Lx.section(context, "Start grid"), Lx.lp(context, bottom = 12f)) + baseCard = GameCard(R.drawable.channel_mkwii, T("Mario Kart Wii")) + retroCard = GameCard(R.drawable.channel_retro_rewind, T("Retro Rewind")) + if (compact) { + column.addView(retroCard.root) + column.addView(baseCard.root, Lx.lp(context, top = 12f)) + } else { + val games = Lx.hbox(context, Gravity.TOP) + games.addView(retroCard.root, Lx.lp(context, 0f, -2f, 1f, end = 8f)) + games.addView(baseCard.root, Lx.lp(context, 0f, -2f, 1f, start = 8f)) + column.addView(games) + } + + column.addView(Lx.section(context, "Trackside"), Lx.lp(context, top = 28f, bottom = 12f)) + onlineTile = Tile(Icon.PUBLIC, T("Online now")) { host.navigate(Tab.ROOMS) } + racerTile = Tile(Icon.FACE, T("Your racer")) { host.navigate(Tab.PROFILE) } + modsTile = Tile(Icon.EXTENSION, T("Mods")) { host.navigate(Tab.MODS) } + if (compact) { + // One panel of rows on a phone; three tiles side by side when there's room. + val panel = Lx.panel(context, 0f) + panel.addView(onlineTile.root) + panel.addView(Lx.divider(context, 70f)) + panel.addView(racerTile.root) + panel.addView(Lx.divider(context, 70f)) + panel.addView(modsTile.root) + column.addView(panel) + } else { + val tiles = Lx.hbox(context, Gravity.TOP) + tiles.addView(onlineTile.root, Lx.lp(context, 0f, -1f, 1f, end = 6f)) + tiles.addView(racerTile.root, Lx.lp(context, 0f, -1f, 1f, start = 6f, end = 6f)) + tiles.addView(modsTile.root, Lx.lp(context, 0f, -1f, 1f, start = 6f)) + column.addView(tiles) + } + + val scroll = ScrollView(context) + scroll.isFillViewport = true + scroll.addView(column, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + return scroll + } + + override fun onShow() { + refresh() + if (System.currentTimeMillis() - lastRoomsFetch > 60_000) fetchRooms() + } + + override fun onDataChanged(what: Data) { + if (what == Data.ROOMS) refreshOnline() else refresh() + } + + private fun fetchRooms() { + lastRoomsFetch = System.currentTimeMillis() + host.work({ RetroWfc.fetchRooms() }) { result -> + if (result.isSuccess) refreshOnline() else onlineTile.set("—", T("Retro WFC is unreachable right now")) + } + } + + fun refresh() { + refreshGames() + refreshOnline() + refreshRacer() + refreshMods() + } + + private fun refreshGames() { + val romReady = host.isRomImported() + val busy = RetroRewindInstallStatus.running + baseCard.set( + ready = romReady, + status = if (romReady) T("Ready") else T("Needs your disc image (.iso or .wbfs)"), + primaryLabel = if (romReady) "Play" else "Install with ISO/WBFS", + primaryIcon = if (romReady) Icon.PLAY else Icon.FOLDER, + primaryEnabled = !busy, + onPrimary = { host.playBase() }, + menu = null, + ) + + val retroInstalled = host.isRetroRewindInstalled() + val notInPack = host.packWithoutRetroRewind() + val version = host.retroRewindVersion() + val playable = retroInstalled && !notInPack + val status = + when { + busy -> RetroRewindInstallStatus.label.ifBlank { T("Installing...") } + notInPack -> T("Not in your game pack") + retroInstalled -> if (version != null) T("Ready · version %s").format(version) else T("Ready") + else -> T("300+ tracks, free. About 1.9 GB") + } + retroCard.set( + ready = playable && !busy, + status = status, + primaryLabel = if (playable) "Play" else "Install", + primaryIcon = if (playable) Icon.PLAY else Icon.DOWNLOAD, + primaryEnabled = !busy, + onPrimary = { host.playRetroRewind() }, + menu = if (retroInstalled && !busy) ({ host.showRetroRewindMenu() }) else null, + ) + } + + private fun refreshOnline() { + val rooms = RetroWfc.lastRooms + if (rooms == null) { + onlineTile.set("…", T("Checking Retro WFC")) + return + } + onlineTile.set(Lx.number(rooms.totalPlayers), T("racers in %s rooms").format(rooms.activeRooms.size)) + } + + private fun refreshRacer() { + host.work({ + val save = SaveFile.load(context, SaveData.Game.RetroRewind) ?: SaveFile.load(context, SaveData.Game.MarioKartWii) + save?.licenses?.firstOrNull() + }) { result -> + val license = result.getOrNull() + if (license == null) { + racerTile.set(T("No license"), T("Play once to make one")) + racerTile.showMii(null) + } else { + racerTile.set(license.displayName, if (license.isOnline) T("%s VR").format(Lx.number(license.vr)) else T("Offline license")) + racerTile.showMii(license.mii) + } + } + } + + private fun refreshMods() { + val packs = ModManager.installedPacks(context) + val on = packs.count { it.enabled } + modsTile.set( + if (packs.isEmpty()) "0" else Lx.number(on), + if (packs.isEmpty()) T("Browse GameBanana") else T("on, of %s installed").format(packs.size), + ) + } + + /** A game: its banner, a dot for its state, and the one thing to do next on a slanted plate. */ + private inner class GameCard(art: Int, name: String) { + val root: LinearLayout = Lx.vbox(context) + private val banner = AspectImageView(context, 1120f / 256f) + private val statusRow = Lx.status(context, "", Lx.MUTED) + private val actions = Lx.hbox(context) + + init { + root.background = Lx.rounded(context, Lx.SURFACE, 8f) + Lx.clipRounded(root, 8f) + banner.scaleType = ImageView.ScaleType.FIT_XY + banner.setImageResource(art) + root.addView(banner) + val body = Lx.vbox(context) + body.setPadding(dp(16f), dp(14f), dp(16f), dp(16f)) + body.addView(Lx.display(context, name, 21f)) + body.addView(statusRow, Lx.lp(context, top = 6f)) + body.addView(actions, Lx.lp(context, top = 14f)) + root.addView(body) + } + + fun set( + ready: Boolean, + status: String, + primaryLabel: String, + primaryIcon: Icon, + primaryEnabled: Boolean, + onPrimary: () -> Unit, + menu: (() -> Unit)?, + ) { + // Not playable yet: the banner fades to grey rather than hiding behind a black veil. + banner.colorFilter = if (ready) null else ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0.15f) }) + banner.alpha = if (ready) 1f else 0.55f + statusRow.getChildAt(0).background = Lx.rounded(context, if (ready) Lx.ACCENT else Lx.AMBER, 4f) + (statusRow.getChildAt(1) as TextView).apply { + text = status + setTextColor(if (ready) Lx.TEXT else Lx.MUTED) + } + actions.removeAllViews() + val tone = if (primaryIcon == Icon.PLAY) Lx.Tone.PRIMARY else Lx.Tone.SECONDARY + val primary = Lx.button(context, primaryLabel, tone, primaryIcon) { onPrimary() } + Lx.setEnabled(primary, primaryEnabled) + actions.addView(primary, Lx.lp(context, 0f, -2f, 1f)) + if (menu != null) { + actions.addView(Lx.iconButton(context, Icon.MORE_VERT, "More", Lx.TEXT, Lx.SURFACE_HI, 46f) { menu() }, Lx.lp(context, 46f, 46f, start = 8f)) + } + } + } + + /** A glance at another page - a row on a phone, a tile beside its neighbours otherwise. Tapping goes there. */ + private inner class Tile(icon: Icon, label: String, onClick: () -> Unit) { + val root: LinearLayout + private val value = Lx.display(context, "", if (compact) 21f else 26f) + private val detail = Lx.caption(context, "", Lx.MUTED, 2) + private val iconView = Lx.iconView(context, icon, Lx.MUTED, 24f) + private val mii = ImageView(context) + + init { + mii.visibility = View.GONE + if (compact) { + root = Lx.hbox(context) + root.background = Lx.pressable(context, android.graphics.Color.TRANSPARENT, 8f) + root.setPadding(dp(16f), dp(12f), dp(12f), dp(12f)) + val lead = FrameLayout(context) + lead.addView(iconView, FrameLayout.LayoutParams(dp(24f), dp(24f), Gravity.CENTER)) + lead.addView(mii, FrameLayout.LayoutParams(dp(42f), dp(42f), Gravity.CENTER)) + root.addView(lead, Lx.lp(context, 42f, 42f)) + val column = Lx.vbox(context) + column.addView(Lx.label(context, label)) + val line = Lx.hbox(context, Gravity.BOTTOM) + line.addView(value) + line.addView(detail, Lx.lp(context, 0f, -2f, 1f, start = 8f, bottom = 2f)) + column.addView(line, Lx.lp(context, top = 4f)) + root.addView(column, Lx.lp(context, 0f, -2f, 1f, start = 12f, end = 8f)) + root.addView(Lx.iconView(context, Icon.CHEVRON, Lx.FAINT, 20f)) + } else { + root = Lx.vbox(context) + root.background = Lx.pressable(context, Lx.SURFACE, 8f) + root.setPadding(dp(16f), dp(14f), dp(16f), dp(16f)) + val top = Lx.hbox(context) + top.addView(iconView) + top.addView(mii, Lx.lp(context, 30f, 30f)) + top.addView(Lx.label(context, label), Lx.lp(context, 0f, -2f, 1f, start = 10f)) + top.addView(Lx.iconView(context, Icon.CHEVRON, Lx.FAINT, 18f)) + root.addView(top) + root.addView(value, Lx.lp(context, top = 14f)) + root.addView(detail, Lx.lp(context, top = 4f)) + } + root.setOnClickListener { onClick() } + } + + fun set(main: String, line: String) { + value.text = main + detail.text = line + } + + fun showMii(m: Mii?) { + if (m != null) { + iconView.visibility = View.GONE + mii.visibility = View.VISIBLE + MiiImages.bind(mii, m) + } else { + iconView.visibility = View.VISIBLE + mii.visibility = View.GONE + } + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/LeaderboardPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/LeaderboardPage.kt new file mode 100644 index 0000000..0c26cf1 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/LeaderboardPage.kt @@ -0,0 +1,436 @@ +package com.driftdroid.android.launcher + +import android.annotation.SuppressLint +import android.content.Context +import android.content.Intent +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF +import android.net.Uri +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.T +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.mii.MiiStudio +import com.driftdroid.android.net.Http +import com.driftdroid.android.online.RetroWfc +import com.driftdroid.android.profile.FriendCode +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx + +/** Retro WFC's top 100 by VR, with a podium for the top three. */ +internal class LeaderboardPage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Leaderboard") + override val subtitle: String get() = T("Top 100 on Retro WFC by VR") + + private lateinit var frame: FrameLayout + private val adapter = Adapter() + private var players: List = emptyList() + private var loaded = false + + // A friend-code lookup: in the header on a wide screen, at the top of the page on a phone. + override fun actions(): List { + val refresh = Lx.iconButton(context, Icon.REFRESH, "Refresh", Lx.MUTED, android.graphics.Color.TRANSPARENT, 44f) { load(true) } + if (compact) return listOf(refresh) + val box = lookupBox() + box.layoutParams = LinearLayout.LayoutParams(dp(260f), ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginEnd = dp(8f) } + return listOf(box, refresh) + } + + private fun lookupBox(): View = + Lx.searchField(context, "Look up a friend code", { text -> + if (text.isBlank()) return@searchField + val code = FriendCode.normalize(text) + if (code == null) host.toast(T("That isn't a valid friend code."), Lx.Tone.DANGER) else host.open(PlayerPage(host, code, null, null)) + }).first + + override fun build(): View { + frame = FrameLayout(context) + if (!compact) return frame + val column = Lx.vbox(context) + column.addView(lookupBox(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + marginStart = gutter + marginEnd = gutter + bottomMargin = dp(8f) + }) + column.addView(frame, Lx.lp(context, -1f, 0f, 1f)) + return column + } + + override fun onShow() { + if (!loaded) load(false) + } + + private fun load(force: Boolean) { + frame.removeAllViews() + frame.addView(Lx.loading(context, "Loading the leaderboard..."), match()) + host.work({ RetroWfc.fetchTop(100, force) }) { result -> + frame.removeAllViews() + result.fold( + onSuccess = { + loaded = true + players = it.sortedBy { p -> p.rank ?: Int.MAX_VALUE } + val list = RecyclerView(context) + list.layoutManager = LinearLayoutManager(context) + list.adapter = adapter + list.clipToPadding = false + list.setPadding(gutter, dp(4f), gutter, dp(96f)) + adapter.notifyDataSetChanged() + frame.addView(list, match()) + }, + onFailure = { + frame.addView( + Lx.emptyState(context, Icon.WARNING, "Retro WFC didn't answer", T("Check your connection and try again (%s).").format(Http.describe(it)), "Try again") { load(true) }, + match(), + ) + }, + ) + } + } + + private fun match() = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + + private fun medal(rank: Int?): Int = + when (rank) { + 1 -> Lx.GOLD + 2 -> Lx.SILVER + 3 -> Lx.BRONZE + else -> Lx.MUTED + } + + private fun openPlayer(p: RetroWfc.Ranked) = host.open(PlayerPage(host, p.friendCode, p.displayName, p.mii)) + + private inner class Adapter : RecyclerView.Adapter() { + private val podium get() = players.size >= 3 + + override fun getItemCount() = if (players.isEmpty()) 0 else if (podium) players.size - 2 else players.size + + override fun getItemViewType(position: Int) = if (podium && position == 0) 0 else 1 + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = + if (viewType == 0) { + object : RecyclerView.ViewHolder(Lx.hbox(context, Gravity.BOTTOM).apply { + layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = dp(14f) } + }) {} + } else { + val row = PlayerRow(context) + // The position as a slanted number plate, like a kart's. + val rank = Lx.plateBadge(context, "", Lx.SURFACE_HI, Lx.MUTED, 13f) + row.lead.addView(rank, Lx.lp(context, 48f, 26f, end = 8f)) + object : RecyclerView.ViewHolder(row) {} + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (getItemViewType(position) == 0) { + val box = holder.itemView as LinearLayout + box.removeAllViews() + for (index in intArrayOf(1, 0, 2)) { + box.addView(podiumCard(players[index], index == 0), Lx.lp(context, 0f, -2f, 1f, start = 5f, end = 5f)) + } + return + } + val player = players[if (podium) position + 2 else position] + val row = holder.itemView as PlayerRow + ((row.lead.getChildAt(0)) as android.widget.TextView).apply { + text = "P${player.rank ?: (position + 1)}" + val medal = player.rank != null && player.rank <= 3 + setTextColor(if (medal) Lx.BG else Lx.MUTED) + background = com.driftdroid.android.ui.SlantDrawable(if (medal) medal(player.rank) else Lx.SURFACE_HI, 0, 0f, dp(2f).toFloat()) + } + val seen = player.lastSeen?.let { T("seen %s").format(Lx.ago(it)) } + row.bind(player.mii, player.displayName, listOfNotNull(player.friendCode.ifBlank { null }, seen).joinToString(" · ")) + row.setValue(T("%s VR").format(Lx.number(player.vr)), Lx.AMBER, if (player.vr24h != 0) T("%s today").format(Lx.signed(player.vr24h)) else null) + row.setOnClickListener { openPlayer(player) } + } + } + + private fun podiumCard(player: RetroWfc.Ranked, first: Boolean): View { + val color = medal(player.rank) + val card = Lx.vbox(context) + card.gravity = Gravity.CENTER_HORIZONTAL + card.background = Lx.pressable(context, Lx.SURFACE, 8f) + card.setPadding(dp(8f), dp(if (first) 18f else 12f), dp(8f), dp(14f)) + // The podium step: a medal-coloured bar along the top of the card. + card.foreground = android.graphics.drawable.LayerDrawable(arrayOf(Lx.rounded(context, color, 0f))).apply { + setLayerGravity(0, Gravity.TOP or Gravity.FILL_HORIZONTAL) + setLayerHeight(0, dp(3f)) + } + Lx.clipRounded(card, 8f) + card.addView(Lx.plateBadge(context, "P${player.rank ?: "?"}", color, Lx.BG, if (first) 15f else 13f), Lx.lp(context, -2f, -2f)) + val mii = ImageView(context) + MiiImages.bind(mii, player.mii, MiiStudio.Size.LARGE) + val size = if (first) (if (compact) 72f else 88f) else (if (compact) 58f else 70f) + card.addView(mii, Lx.lp(context, size, size, top = 8f)) + card.addView(Lx.text(context, player.displayName, 14.5f, Lx.TEXT, Lx.MEDIUM, 1).apply { gravity = Gravity.CENTER }, Lx.lp(context, -2f, -2f, top = 8f)) + card.addView(Lx.display(context, Lx.number(player.vr), if (first) 22f else 18f, Lx.AMBER), Lx.lp(context, -2f, -2f, top = 4f)) + card.addView(Lx.label(context, if (player.vrWeek != 0) T("%s this week").format(Lx.signed(player.vrWeek)) else T("VR")), Lx.lp(context, -2f, -2f, top = 3f)) + card.setOnClickListener { openPlayer(player) } + return card + } +} + +/** One player's Retro WFC profile: rank, VR and how it moved over the last week. */ +internal class PlayerPage( + host: ModePickerActivity, + private val friendCode: String, + private val knownName: String?, + private val knownMii: Mii?, +) : Page(host) { + override val title: String get() = profile?.displayName ?: knownName ?: friendCode + override val subtitle: String get() = friendCode + + private var profile: RetroWfc.Ranked? = null + private lateinit var frame: FrameLayout + + override fun actions(): List = + listOf( + Lx.iconButton(context, Icon.OPEN_IN_NEW, "Open on rwfc.net") { + runCatching { host.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://rwfc.net/player/${friendCode.filter { it.isDigit() }}"))) } + }, + ) + + override fun build(): View { + frame = FrameLayout(context) + load() + return frame + } + + private fun load() { + frame.removeAllViews() + frame.addView(Lx.loading(context, "Loading the profile..."), match()) + host.work({ + val p = RetroWfc.fetchPlayer(friendCode) + val history = runCatching { RetroWfc.fetchHistory(friendCode, 7) }.getOrDefault(emptyList()) + p to history + }) { result -> + frame.removeAllViews() + result.fold( + onSuccess = { (p, history) -> + profile = p + refreshHeader() + frame.addView(content(p, history), match()) + }, + onFailure = { error -> + val notFound = (error as? Http.HttpException)?.code == 404 + frame.addView( + if (notFound) { + Lx.emptyState(context, Icon.PERSON, "Not on the leaderboard", "This friend code hasn't raced on Retro WFC yet, or not recently.") + } else { + Lx.emptyState(context, Icon.WARNING, "Couldn't load this player", T("Retro WFC didn't answer (%s).").format(Http.describe(error)), "Try again") { load() } + }, + match(), + ) + }, + ) + } + } + + private fun match() = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + + private fun content(p: RetroWfc.Ranked, history: List): View { + // Who: Mii, name, code, rank plate and the two things to do with them. + val left = Lx.panel(context, 18f) + left.gravity = Gravity.CENTER_HORIZONTAL + val mii = ImageView(context) + MiiImages.bind(mii, p.mii ?: knownMii, MiiStudio.Size.LARGE) + left.addView(mii, Lx.lp(context, 120f, 120f)) + left.addView(Lx.display(context, p.displayName, 23f).apply { gravity = Gravity.CENTER }, Lx.lp(context, -2f, -2f, top = 10f)) + left.addView(Lx.caption(context, p.friendCode), Lx.lp(context, -2f, -2f, top = 4f)) + val badges = Lx.hbox(context) + p.rank?.let { badges.addView(Lx.plateBadge(context, "P$it", if (it <= 3) medalColor(it) else Lx.SURFACE_HI, if (it <= 3) Lx.BG else Lx.TEXT, 13f), Lx.lp(context, -2f, -2f, end = 8f)) } + p.vehiclePreference?.let { badges.addView(Lx.badge(context, if (it.equals("bike", true)) T("Bikes") else if (it.equals("kart", true)) T("Karts") else it, Lx.CYAN)) } + left.addView(badges, Lx.lp(context, -2f, -2f, top = 12f)) + p.lastSeen?.let { left.addView(Lx.caption(context, T("Last seen %s").format(Lx.ago(it)), Lx.FAINT), Lx.lp(context, -2f, -2f, top = 10f)) } + left.addView( + Lx.button(context, "Add as a friend", Lx.Tone.PRIMARY, Icon.PERSON_ADD) { PlayerActions.addFriend(host, p.friendCode, p.mii ?: knownMii, p.vr, null) }, + Lx.lp(context, -1f, -2f, top = 16f), + ) + left.addView(Lx.button(context, "Copy friend code", Lx.Tone.SECONDARY, Icon.COPY) { PlayerActions.copy(host, p.friendCode) }, Lx.lp(context, -1f, -2f, top = 8f)) + + // How: VR now and how it moved, then the week as a line. + val right = Lx.vbox(context) + val stats = Lx.panel(context, 16f) + val statRow = Lx.hbox(context, Gravity.TOP) + fun stat(value: String, label: String, color: Int) = statRow.addView(Lx.stat(context, value, label, color, if (compact) 20f else 24f), Lx.lp(context, 0f, -2f, 1f)) + stat(Lx.number(p.vr), "VR", Lx.AMBER) + stat(Lx.signed(p.vr24h), "24 hours", Lx.TEXT) + stat(Lx.signed(p.vrWeek), "7 days", Lx.TEXT) + stat(Lx.signed(p.vrMonth), "30 days", Lx.TEXT) + stats.addView(statRow) + right.addView(stats) + + val chartPanel = Lx.panel(context, 16f) + chartPanel.addView(Lx.section(context, "VR, last 7 days")) + if (history.size >= 2) { + chartPanel.addView(Lx.caption(context, T("Touch the line to read any point"), Lx.FAINT), Lx.lp(context, top = 6f)) + chartPanel.addView(VrChart(context, history), Lx.lp(context, -1f, 200f, top = 12f)) + } else { + chartPanel.addView(Lx.body(context, T("No VR changes in the last 7 days.")), Lx.lp(context, top = 10f)) + } + right.addView(chartPanel, Lx.lp(context, top = 12f)) + + val content: LinearLayout + if (compact) { + content = Lx.vbox(context) + content.addView(left) + content.addView(right, Lx.lp(context, top = 12f)) + } else { + content = Lx.hbox(context, Gravity.TOP) + content.addView(left, Lx.lp(context, 260f, -2f, end = 16f)) + content.addView(right, Lx.lp(context, 0f, -2f, 1f)) + } + content.setPadding(gutter, dp(4f), gutter, dp(96f)) + val scroll = ScrollView(context) + scroll.addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + return scroll + } + + private fun medalColor(rank: Int): Int = + when (rank) { + 1 -> Lx.GOLD + 2 -> Lx.SILVER + else -> Lx.BRONZE + } +} + +/** + * One player's VR over time: a single 2dp line on one axis with recessive gridlines, the latest + * value marked and labelled at the end, and touch-to-read for any other point. The line colour is + * a deeper step of the app green, checked for lightness and contrast against the card surface. + */ +@SuppressLint("ViewConstructor") +internal class VrChart(context: Context, private val points: List) : View(context) { + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = LINE_COLOR + style = Paint.Style.STROKE + strokeWidth = Lx.dp(context, 2f).toFloat() + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + } + private val grid = Paint().apply { + color = Lx.alpha(Lx.LINE, 0.8f) + strokeWidth = Lx.dp(context, 1f).toFloat() + } + private val dot = Paint(Paint.ANTI_ALIAS_FLAG) + private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = Lx.dp(context, 11f).toFloat() + color = Lx.FAINT + } + private val value = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textSize = Lx.dp(context, 12f).toFloat() + color = Lx.TEXT + typeface = Lx.BOLD + } + private val path = Path() + private val box = RectF() + private var touched = -1 + + private val minVr = points.minOf { it.totalVr } + private val maxVr = points.maxOf { it.totalVr } + private val t0 = points.first().time + private val t1 = points.last().time + + init { + contentDescription = + T("VR went from %s to %s over the last 7 days").format(Lx.number(points.first().totalVr), Lx.number(points.last().totalVr)) + } + + private val left get() = Lx.dp(context, 52f).toFloat() + private val right get() = width - Lx.dp(context, 64f).toFloat() + private val top get() = Lx.dp(context, 10f).toFloat() + private val bottom get() = height - Lx.dp(context, 22f).toFloat() + + private fun x(time: Long) = if (t1 == t0) (left + right) / 2 else left + (right - left) * ((time - t0).toFloat() / (t1 - t0)) + + private fun y(vr: Int): Float { + val span = (maxVr - minVr).coerceAtLeast(1) + // A little headroom so the line never sits on the frame. + val pad = span * 0.1f + return bottom - (bottom - top) * ((vr - minVr + pad) / (span + 2 * pad)) + } + + override fun onDraw(canvas: Canvas) { + // Three recessive gridlines with their values on the one axis. + for (i in 0..2) { + val vr = minVr + (maxVr - minVr) * i / 2 + val gy = y(vr) + canvas.drawLine(left, gy, right, gy, grid) + val text = Lx.number(vr) + canvas.drawText(text, left - Lx.dp(context, 8f) - label.measureText(text), gy + label.textSize / 3, label) + } + val format = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT) + canvas.drawText(format.format(java.util.Date(t0)), left, height.toFloat() - Lx.dp(context, 4f), label) + val endDate = format.format(java.util.Date(t1)) + canvas.drawText(endDate, right - label.measureText(endDate), height.toFloat() - Lx.dp(context, 4f), label) + + path.reset() + points.forEachIndexed { i, p -> + if (i == 0) path.moveTo(x(p.time), y(p.totalVr)) else path.lineTo(x(p.time), y(p.totalVr)) + } + canvas.drawPath(path, line) + + val last = points.last() + drawMarker(canvas, x(last.time), y(last.totalVr)) + canvas.drawText(Lx.number(last.totalVr), x(last.time) + Lx.dp(context, 10f), y(last.totalVr) + value.textSize / 3, value) + + if (touched in points.indices) { + val p = points[touched] + val px = x(p.time) + val py = y(p.totalVr) + grid.color = Lx.MUTED + canvas.drawLine(px, top, px, bottom, grid) + grid.color = Lx.alpha(Lx.LINE, 0.8f) + drawMarker(canvas, px, py) + val time = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT, java.text.DateFormat.SHORT).format(java.util.Date(p.time)) + val text = "$time · ${Lx.number(p.totalVr)} VR" + val w = value.measureText(text) + Lx.dp(context, 16f) + val h = Lx.dp(context, 26f).toFloat() + val bx = (px - w / 2).coerceIn(0f, width - w) + val by = (py - h - Lx.dp(context, 12f)).coerceAtLeast(0f) + box.set(bx, by, bx + w, by + h) + dot.color = Lx.SURFACE_HI + canvas.drawRoundRect(box, h / 2, h / 2, dot) + canvas.drawText(text, bx + Lx.dp(context, 8f), by + h / 2 + value.textSize / 3, value) + } + } + + /** An 8dp dot in the line colour, ringed with the surface so it reads over the line. */ + private fun drawMarker(canvas: Canvas, cx: Float, cy: Float) { + dot.color = Lx.SURFACE + canvas.drawCircle(cx, cy, Lx.dp(context, 6f).toFloat(), dot) + dot.color = LINE_COLOR + canvas.drawCircle(cx, cy, Lx.dp(context, 4f).toFloat(), dot) + } + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { + parent?.requestDisallowInterceptTouchEvent(true) + touched = points.indices.minByOrNull { kotlin.math.abs(x(points[it].time) - event.x) } ?: -1 + invalidate() + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + touched = -1 + invalidate() + } + } + return true + } + + companion object { + /** Validated with the dataviz palette checker against the dark card surface. */ + const val LINE_COLOR = 0xFF4BA63A.toInt() + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/MiiEditorPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/MiiEditorPage.kt new file mode 100644 index 0000000..82894c8 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/MiiEditorPage.kt @@ -0,0 +1,535 @@ +package com.driftdroid.android.launcher + +import android.os.Handler +import android.os.Looper +import android.text.Editable +import android.text.TextWatcher +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.T +import com.driftdroid.android.mii.BodyFigure +import com.driftdroid.android.mii.FocusImageView +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiDatabase +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.mii.MiiStudio +import com.driftdroid.android.mii.PartFocus +import com.driftdroid.android.mii.PartTile +import com.driftdroid.android.profile.SaveFile +import com.driftdroid.android.ui.DriftSheet +import com.driftdroid.android.ui.GridBox +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.IconDrawable +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages +import com.driftdroid.android.ui.TabStrip +import java.io.IOException +import kotlin.random.Random +import kotlin.reflect.KMutableProperty1 + +/** + * Edits one Mii, or makes a new one: every part of the Wii Mii format, grouped like the Mii + * Channel's own tabs, with a live picture. Each part is picked from pictures of this Mii wearing + * it - zoomed onto the eyes for eyes, the mouth for mouths - and height and weight show on a full + * body and on a figure measured against an average Mii. Saving writes that one slot of the Mii + * file back (with a backup), and renames any license that races as this Mii. + */ +internal class MiiEditorPage( + host: ModePickerActivity, + private val slot: Int?, + private val original: Mii?, +) : Page(host) { + private val mii: Mii = original?.copy() ?: Mii.blank() + private var dirty = false + private var saving = false + private val handler = Handler(Looper.getMainLooper()) + private val repaint = Runnable { repaint() } + + override val title: String get() = if (original == null) T("New Mii") else T("Edit %s").format(original.displayName) + override val subtitle: String + get() = when { + saving -> T("Saving...") + dirty -> T("Unsaved changes") + slot != null -> T("Slot %s of 100").format(slot + 1) + else -> T("Not saved yet") + } + + private lateinit var preview: ImageView + private lateinit var nameView: TextView + private lateinit var creatorView: TextView + private lateinit var controls: LinearLayout + private lateinit var scroll: ScrollView + private lateinit var tabStrip: TabStrip + + /** What the open tab needs redrawn after a change: its part pictures, the body views. */ + private val refreshers = ArrayList<() -> Unit>() + + private val tabs: List Unit>> = + listOf( + "Info" to ::infoTab, + "Body" to ::bodyTab, + "Face" to ::faceTab, + "Hair" to ::hairTab, + "Eyebrows" to ::browTab, + "Eyes" to ::eyeTab, + "Nose" to ::noseTab, + "Mouth" to ::mouthTab, + "Glasses" to ::glassesTab, + "Facial hair" to ::facialHairTab, + "Mole" to ::moleTab, + ) + + override fun actions(): List = listOf(Lx.button(context, "Save", Lx.Tone.PRIMARY, Icon.CHECK, compact = true) { save() }) + + override fun build(): View { + preview = ImageView(context) + nameView = Lx.display(context, "", if (compact) 22f else 24f) + creatorView = Lx.caption(context, "", Lx.MUTED, 1) + tabStrip = TabStrip(context, tabs.map { it.first }, fill = false) { selectTab(it) } + controls = Lx.vbox(context) + controls.setPadding(gutter, dp(4f), gutter, dp(32f)) + scroll = ScrollView(context) + scroll.addView(controls, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + + val root: View + if (compact) { + // Phone: the Mii stays in view at the top while the parts scroll under it. + val column = Lx.vbox(context) + val head = Lx.hbox(context) + head.setPadding(gutter, 0, gutter, dp(8f)) + preview.background = Lx.rounded(context, Lx.SURFACE, 8f) + head.addView(preview, Lx.lp(context, 108f, 108f)) + val names = Lx.vbox(context) + names.addView(nameView) + names.addView(creatorView, Lx.lp(context, top = 4f)) + names.addView(Lx.caption(context, T("Tap a picture to pick that part"), Lx.FAINT, 2), Lx.lp(context, top = 10f)) + head.addView(names, Lx.lp(context, 0f, -2f, 1f, start = 16f)) + column.addView(head) + column.addView(tabStrip.view, Lx.lp(context).apply { marginStart = dp(4f) }) + column.addView(Lx.divider(context)) + column.addView(scroll, Lx.lp(context, -1f, 0f, 1f)) + root = column + } else { + val row = Lx.hbox(context, Gravity.TOP) + val left = Lx.panel(context, 18f) + left.gravity = Gravity.CENTER_HORIZONTAL + left.addView(preview, Lx.lp(context, 190f, 190f)) + left.addView(nameView.apply { gravity = Gravity.CENTER }, Lx.lp(context, -2f, -2f, top = 12f)) + left.addView(creatorView, Lx.lp(context, -2f, -2f, top = 4f)) + left.addView(Lx.caption(context, T("Tap a picture to pick that part"), Lx.FAINT, 2).apply { gravity = Gravity.CENTER }, Lx.lp(context, -2f, -2f, top = 14f)) + row.addView(ScrollView(context).apply { addView(left) }, Lx.lp(context, 250f, -2f, start = 24f, end = 4f)) + val right = Lx.vbox(context) + right.addView(tabStrip.view, Lx.lp(context).apply { marginStart = dp(10f) }) + right.addView(Lx.divider(context)) + right.addView(scroll, Lx.lp(context, -1f, 0f, 1f)) + row.addView(right, Lx.lp(context, 0f, -1f, 1f)) + root = row + } + selectTab(0) + tabStrip.select(0) + paintPreview() + return root + } + + override fun onBack(): Boolean { + if (!dirty) return false + leave() + return true + } + + override fun onClose() = handler.removeCallbacks(repaint) + + override fun onDataChanged(what: Data) { + // Mii pictures turned on or off in Settings. + if (what == Data.MIIS && ::controls.isInitialized) repaint() + } + + private fun leave() { + if (!dirty) { + host.back(force = true) + return + } + DriftSheet.confirm(host, "Discard your changes?", "Your changes to this Mii haven't been saved.", "Discard", danger = true, cancelLabel = "Keep editing") { + dirty = false + host.back(force = true) + } + } + + private fun selectTab(index: Int) { + refreshers.clear() + controls.removeAllViews() + tabs[index].second() + scroll.scrollTo(0, 0) + } + + private fun changed() { + dirty = true + nameView.text = mii.displayName + refreshHeader() + handler.removeCallbacks(repaint) + handler.postDelayed(repaint, 350) + } + + private fun repaint() { + paintPreview() + refreshers.forEach { it() } + } + + private fun paintPreview() { + nameView.text = mii.displayName + creatorView.text = mii.creatorName.takeIf { it.isNotBlank() }?.let { T("by %s").format(it) } ?: T("No creator name") + MiiImages.bind(preview, mii.copy(), MiiStudio.Size.LARGE) + } + + // --- Control builders --- + + private fun section(label: String) { + controls.addView(Lx.section(context, label), Lx.lp(context, top = if (controls.childCount == 0) 14f else 26f, bottom = 12f)) + } + + /** + * A part's shapes as pictures: the Mii wearing each one, cropped to [focus]. [neutral] puts the + * part back to its standard size and place in those pictures, so moving a slider doesn't make + * every picture download again - the pictures compare shapes; the sliders place them. + */ + private fun shapes( + label: String, + count: Int, + prop: KMutableProperty1, + focus: PartFocus, + noneFirst: Boolean = false, + neutral: (Mii) -> Unit = {}, + ) { + section(label) + val grid = GridBox(context, dp(if (compact) 72f else 84f), dp(8f)) + val tiles = ArrayList() + for (i in 0 until count) { + val none = noneFirst && i == 0 + val tile = PartTile(context, if (none) "—" else (if (noneFirst) i else i + 1).toString(), if (none) T("None") else null) + tile.contentDescription = if (none) T("%s: none").format(T(label)) else T("%s %s").format(T(label), if (noneFirst) i else i + 1) + tile.setOnClickListener { + prop.set(mii, i) + tiles.forEachIndexed { j, t -> t.setPicked(j == i) } + changed() + } + tiles += tile + grid.addView(tile) + } + fun paint() { + val online = MiiImages.onlineEnabled(context) + val base = mii.copy().also(neutral) + val current = prop.get(mii) + tiles.forEachIndexed { i, tile -> + val variant = base.copy() + prop.set(variant, i) + tile.show(variant, focus, online) + tile.setPicked(i == current) + } + } + paint() + refreshers += { paint() } + controls.addView(grid) + if (!MiiImages.onlineEnabled(context)) { + controls.addView( + Lx.caption(context, T("Turn on Mii pictures in Settings to see each shape instead of its number."), Lx.FAINT, 2), + Lx.lp(context, top = 8f), + ) + } + } + + private fun colors(label: String, palette: IntArray, prop: KMutableProperty1, names: List? = null) { + section(label) + val grid = GridBox(context, dp(44f), dp(10f)) + val swatches = ArrayList() + fun paint() { + val current = prop.get(mii) + swatches.forEachIndexed { i, s -> + val on = i == current + s.background = Lx.rounded(context, palette[i], 8f, if (on) Lx.TEXT else Lx.alpha(Lx.TEXT, 0.12f), if (on) 3f else 1f) + s.getChildAt(0).visibility = if (on) View.VISIBLE else View.GONE + } + } + palette.forEachIndexed { i, color -> + val swatch = FrameLayout(context) + val check = ImageView(context) + // A dark tick on light colours, a light one on dark colours. + val light = android.graphics.Color.luminance(color) > 0.45f + check.setImageDrawable(IconDrawable(Icon.CHECK, if (light) Lx.BG else Lx.TEXT)) + swatch.addView(check, FrameLayout.LayoutParams(dp(20f), dp(20f), Gravity.CENTER)) + swatch.contentDescription = names?.getOrNull(i)?.let { T(it) } ?: T("Colour %s").format(i + 1) + swatch.setOnClickListener { + prop.set(mii, i) + paint() + changed() + } + swatches += swatch + grid.addView(swatch) + } + paint() + controls.addView(grid) + } + + private fun slider( + label: String, + min: Int, + max: Int, + prop: KMutableProperty1, + ends: Pair? = null, + format: (Int) -> String = { it.toString() }, + onMove: () -> Unit = {}, + ) { + controls.addView( + Lx.slider(context, label, min, max, prop.get(mii), format, ends?.let { T(it.first) to T(it.second) }) { + prop.set(mii, it) + onMove() + changed() + }, + ) + } + + private fun toggle(label: String, detail: String?, get: () -> Boolean, set: (Boolean) -> Unit) { + controls.addView( + Lx.toggleRow(context, label, detail, get()) { + set(it) + changed() + }, + ) + } + + private fun choice(label: String, options: List, get: () -> Int, set: (Int) -> Unit) { + section(label) + val row = Lx.hbox(context) + val chips = ArrayList() + options.forEachIndexed { i, option -> + val chip = Lx.chip(context, option, get() == i) { + set(i) + chips.forEachIndexed { j, c -> Lx.paintChip(c, j == i) } + changed() + } + chips += chip + row.addView(chip, Lx.lp(context, 0f, 42f, 1f, end = if (i < options.size - 1) 8f else 0f)) + } + controls.addView(row) + } + + private fun field(label: String, hint: String, get: () -> String, set: (String) -> Unit) { + section(label) + val input = Lx.textField(context, hint, get(), Mii.NAME_CHARS) + input.addTextChangedListener( + object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} + + override fun afterTextChanged(s: Editable?) { + val text = s?.toString().orEmpty() + if (text != get()) { + set(text) + changed() + } + } + }, + ) + controls.addView(input) + } + + // Words for the ends of the placement sliders. On a Mii a bigger "height" number sits lower. + private val sizeEnds = "Smaller" to "Bigger" + private val upDown = "Higher" to "Lower" + private val spacingEnds = "Closer" to "Further apart" + + // --- Tabs --- + + private fun infoTab() { + field("Name", "Up to 10 characters", { mii.name }, { mii.name = it }) + field("Made by", "Creator's name", { mii.creatorName }, { mii.creatorName = it }) + choice("Gender", listOf("Boy", "Girl"), { if (mii.isGirl) 1 else 0 }, { mii.isGirl = it == 1 }) + colors("Favorite colour", Mii.FAVORITE_COLORS, Mii::favoriteColor, Mii.FAVORITE_COLOR_NAMES) + section("Birthday") + slider("Month", 0, 12, Mii::birthMonth, format = { if (it == 0) T("Not set") else monthName(it) }) + slider("Day", 0, 31, Mii::birthDay, format = { if (it == 0) T("Not set") else it.toString() }) + section("More") + toggle("Favorite", "Marked as a favorite in the Mii Channel", { mii.isFavorite }, { mii.isFavorite = it }) + toggle("Allow copying and mingling", "Lets this Mii travel to other consoles", { !mii.mingleOff }, { mii.mingleOff = !it }) + } + + private fun monthName(month: Int): String = + java.text.DateFormatSymbols.getInstance().months.getOrNull(month - 1)?.takeIf { it.isNotBlank() } ?: month.toString() + + /** Height and weight: Nintendo's full-body picture beside a figure measured against an average Mii. */ + private fun bodyTab() { + section("Build") + val panel = Lx.panel(context, 12f) + val pictures = Lx.hbox(context, Gravity.BOTTOM) + val online = MiiImages.onlineEnabled(context) + // The renderer leaves a lot of room around a full body; crop in a little so the Mii reads. + val body = FocusImageView(context) + body.focus = PartFocus(0.5f, 0.54f, 1.3f) + val figure = BodyFigure(context) + figure.set(mii) + if (online) { + val column = Lx.vbox(context) + column.gravity = Gravity.CENTER_HORIZONTAL + column.addView(body, Lx.lp(context, -1f, 0f, 1f)) + column.addView(Lx.label(context, "Your Mii"), Lx.lp(context, -2f, -2f, top = 8f)) + pictures.addView(column, Lx.lp(context, 0f, -1f, 1f, end = 6f)) + } + val figureColumn = Lx.vbox(context) + figureColumn.gravity = Gravity.CENTER_HORIZONTAL + figureColumn.addView(figure, Lx.lp(context, -1f, 0f, 1f)) + figureColumn.addView(Lx.label(context, "Against average"), Lx.lp(context, -2f, -2f, top = 8f)) + pictures.addView(figureColumn, Lx.lp(context, 0f, -1f, 1f, start = if (online) 6f else 0f)) + panel.addView(pictures, Lx.lp(context, -1f, if (compact) 240f else 280f)) + controls.addView(panel) + + fun paintBody() { + if (online) RemoteImages.bind(body, MiiStudio.imageUrl(mii.copy(), MiiStudio.Size.LARGE, body = true), dp(240f), null) + } + paintBody() + refreshers += { paintBody() } + + slider("Height", 0, 127, Mii::height, "Short" to "Tall") { figure.set(mii) } + slider("Weight", 0, 127, Mii::weight, "Slim" to "Heavy") { figure.set(mii) } + controls.addView( + Lx.caption(context, T("The dashed outline is an average Mii (64 and 64). Your Mii's shirt is its favorite colour."), Lx.FAINT, 3), + Lx.lp(context, top = 6f), + ) + } + + private fun faceTab() { + shapes("Face shape", 8, Mii::faceShape, PartFocus(0.5f, 0.56f, 1.15f)) + colors("Skin tone", Mii.SKIN_COLORS, Mii::skinColor) + shapes("Features and makeup", 12, Mii::facialFeature, PartFocus(0.5f, 0.6f, 1.35f), noneFirst = true) + } + + private fun hairTab() { + shapes("Hairstyle", 72, Mii::hairType, PartFocus.WHOLE) + colors("Hair colour", Mii.HAIR_COLORS, Mii::hairColor) + section("Parting") + toggle("Flip hairstyle", "Mirrors the parting", { mii.hairFlipped }, { mii.hairFlipped = it }) + } + + private fun browTab() { + shapes("Eyebrows", 24, Mii::browType, PartFocus(0.5f, 0.45f, 2.8f)) { it.browSize = 4; it.browVertical = 10; it.browSpacing = 2 } + colors("Colour", Mii.HAIR_COLORS, Mii::browColor) + section("Placement") + slider("Size", 0, 8, Mii::browSize, sizeEnds) + slider("Angle", 0, 11, Mii::browRotation) + slider("Height", 3, 18, Mii::browVertical, upDown) + slider("Spacing", 0, 12, Mii::browSpacing, spacingEnds) + } + + private fun eyeTab() { + shapes("Eyes", 48, Mii::eyeType, PartFocus(0.5f, 0.505f, 2.8f)) { it.eyeSize = 4; it.eyeVertical = 12; it.eyeSpacing = 2; it.eyeRotation = 4 } + colors("Colour", Mii.EYE_COLORS, Mii::eyeColor) + section("Placement") + slider("Size", 0, 7, Mii::eyeSize, sizeEnds) + slider("Angle", 0, 7, Mii::eyeRotation) + slider("Height", 0, 18, Mii::eyeVertical, upDown) + slider("Spacing", 0, 12, Mii::eyeSpacing, spacingEnds) + } + + private fun noseTab() { + shapes("Nose", 12, Mii::noseType, PartFocus(0.5f, 0.575f, 3.0f)) { it.noseSize = 4; it.noseVertical = 9 } + section("Placement") + slider("Size", 0, 8, Mii::noseSize, sizeEnds) + slider("Height", 0, 18, Mii::noseVertical, upDown) + } + + private fun mouthTab() { + shapes("Mouth", 24, Mii::lipType, PartFocus(0.5f, 0.69f, 2.8f)) { it.lipSize = 4; it.lipVertical = 13 } + colors("Colour", Mii.LIP_COLORS, Mii::lipColor) + section("Placement") + slider("Size", 0, 8, Mii::lipSize, sizeEnds) + slider("Height", 0, 18, Mii::lipVertical, upDown) + } + + private fun glassesTab() { + shapes("Glasses", 9, Mii::glassesType, PartFocus(0.5f, 0.505f, 1.9f), noneFirst = true) { it.glassesSize = 4; it.glassesVertical = 10 } + colors("Colour", Mii.GLASSES_COLORS, Mii::glassesColor) + section("Placement") + slider("Size", 0, 7, Mii::glassesSize, sizeEnds) + slider("Height", 0, 20, Mii::glassesVertical, upDown) + } + + private fun facialHairTab() { + shapes("Mustache", 4, Mii::mustacheType, PartFocus(0.5f, 0.64f, 2.5f), noneFirst = true) { it.mustacheSize = 4; it.mustacheVertical = 10 } + shapes("Beard", 4, Mii::beardType, PartFocus(0.5f, 0.68f, 1.3f), noneFirst = true) + colors("Colour", Mii.HAIR_COLORS, Mii::facialHairColor) + section("Mustache placement") + slider("Size", 0, 8, Mii::mustacheSize, sizeEnds) + slider("Height", 0, 16, Mii::mustacheVertical, upDown) + } + + private fun moleTab() { + section("Mole") + toggle("Show a mole", null, { mii.moleOn }, { mii.moleOn = it }) + slider("Size", 0, 8, Mii::moleSize, sizeEnds) + slider("Height", 0, 30, Mii::moleVertical, upDown) + slider("Across", 0, 16, Mii::moleHorizontal) + } + + // --- Saving --- + + private fun save() { + if (saving) return + if (mii.name.isBlank()) { + host.toast(T("Give the Mii a name first."), Lx.Tone.INFO) + tabStrip.select(0) + selectTab(0) + return + } + host.guardGameRunning { + saving = true + refreshHeader() + val result = mii.copy() + host.work({ write(result) }) { outcome -> + saving = false + outcome.fold( + onSuccess = { + dirty = false + host.toast(T("%s saved.").format(result.displayName), Lx.Tone.PRIMARY) + host.broadcast(Data.MIIS) + host.broadcast(Data.SAVES) + host.back(force = true) + }, + onFailure = { + refreshHeader() + host.toast(T("Couldn't save: %s").format(it.message ?: "unknown error"), Lx.Tone.DANGER) + }, + ) + } + } + } + + /** Runs off the main thread. */ + private fun write(result: Mii) { + val snapshot = MiiDatabase.load(context) ?: throw IOException("there's no Mii file yet - start Mario Kart Wii once first") + if (slot == null || original == null) { + result.miiId = Mii.newMiiId(snapshot.slots.map { it.mii.miiId }.toSet()) + result.systemId = snapshot.systemId ?: (Random.nextLong(1, 0xFFFFFFFFL)) + val free = MiiDatabase.firstFreeSlot(snapshot.bytes) + if (free < 0) throw IOException("all 100 Mii slots are in use - delete one first") + MiiDatabase.save(context, MiiDatabase.withSlot(snapshot.bytes, free, result)) + return + } + val current = snapshot.slots.firstOrNull { it.index == slot } + if (current == null || current.mii.miiId != original.miiId) { + throw IOException("the Mii file changed while you were editing - reopen this Mii and try again") + } + MiiDatabase.save(context, MiiDatabase.withSlot(snapshot.bytes, slot, result)) + // Licenses keep their own copy of the name; keep them matching the Mii. + if (result.name != original.name) { + for ((game, license) in SaveFile.licensesUsing(context, result.miiId)) { + runCatching { SaveFile.setLicenseMii(context, game, license.index, result) } + } + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModDetailPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModDetailPage.kt new file mode 100644 index 0000000..2d55bce --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModDetailPage.kt @@ -0,0 +1,249 @@ +package com.driftdroid.android.launcher + +import android.content.Intent +import android.net.Uri +import android.text.Html +import android.text.method.LinkMovementMethod +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.PagerSnapHelper +import androidx.recyclerview.widget.RecyclerView +import com.driftdroid.android.ModManager +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.T +import com.driftdroid.android.mods.GameBanana +import com.driftdroid.android.mods.ModInstallJob +import com.driftdroid.android.net.Http +import com.driftdroid.android.ui.AspectFrame +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages + +/** One GameBanana mod: screenshots, details, and its files with an Install button each. Stacked in one column on a phone. */ +internal class ModDetailPage(host: ModePickerActivity, private val summary: GameBanana.ModSummary) : Page(host) { + override val title: String get() = summary.name + override val subtitle: String get() = listOf(summary.author, summary.category).filter { it.isNotBlank() }.joinToString(" · ") + + private lateinit var frame: FrameLayout + private var details: GameBanana.ModDetails? = null + private val fileButtons = ArrayList>() + + override fun actions(): List = + listOf( + Lx.iconButton(context, Icon.OPEN_IN_NEW, "Open on GameBanana", Lx.MUTED, android.graphics.Color.TRANSPARENT, 44f) { + runCatching { host.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(summary.profileUrl))) } + }, + ) + + override fun build(): View { + frame = FrameLayout(context) + load() + return frame + } + + override fun onDataChanged(what: Data) { + if (what == Data.MODS || what == Data.INSTALL) paintFileButtons() + } + + private fun load() { + frame.removeAllViews() + frame.addView(Lx.loading(context, "Loading the mod..."), match()) + host.work({ GameBanana.details(summary.id) }) { result -> + frame.removeAllViews() + result.fold( + onSuccess = { + details = it + frame.addView(content(it), match()) + }, + onFailure = { + frame.addView( + Lx.emptyState(context, Icon.WARNING, "Couldn't load this mod", T("GameBanana didn't answer (%s).").format(Http.describe(it)), "Try again") { load() }, + match(), + ) + }, + ) + } + } + + private fun match() = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + + private fun content(mod: GameBanana.ModDetails): View { + val column = Lx.vbox(context) + column.setPadding(gutter, dp(4f), gutter, dp(96f)) + + val side = Lx.vbox(context) + side.addView(Lx.display(context, mod.summary.name, if (compact) 22f else 25f, Lx.TEXT, 3)) + val by = Lx.caption(context, listOf(mod.summary.author.takeIf { it.isNotBlank() }?.let { T("by %s").format(it) }, mod.summary.category.ifBlank { null }).filterNotNull().joinToString(" · ")) + side.addView(by, Lx.lp(context, top = 6f)) + + val badges = Lx.hbox(context) + mod.version?.let { badges.addView(Lx.badge(context, "v$it", Lx.CYAN), Lx.lp(context, -2f, -2f, end = 6f)) } + if (mod.summary.id in ModManager.installedGameBananaIds(context)) badges.addView(Lx.plateBadge(context, T("Installed").uppercase(), Lx.ACCENT, Lx.ACCENT_TEXT, 11f)) + if (badges.childCount > 0) side.addView(badges, Lx.lp(context, top = 10f)) + + val stats = Lx.hbox(context) + stats.addView(Lx.stat(context, Lx.number(mod.summary.likes), "likes", Lx.TEXT, 20f), Lx.lp(context, 0f, -2f, 1f)) + stats.addView(Lx.stat(context, Lx.number(mod.summary.views), "views", Lx.TEXT, 20f), Lx.lp(context, 0f, -2f, 1f)) + stats.addView(Lx.stat(context, Lx.number(mod.downloads), "downloads", Lx.TEXT, 20f), Lx.lp(context, 0f, -2f, 1f)) + side.addView(stats, Lx.lp(context, top = 18f)) + + side.addView(Lx.section(context, "Files"), Lx.lp(context, top = 24f, bottom = 10f)) + fileButtons.clear() + if (mod.files.isEmpty()) { + side.addView(Lx.body(context, T("This mod has no files to download here. Its GameBanana page may link to them."))) + } + for (file in mod.files) side.addView(fileRow(file), Lx.lp(context, bottom = 8f)) + paintFileButtons() + side.addView( + Lx.caption(context, T("Installed mods load the next time you start the game. Manage them under Installed."), Lx.FAINT, 3), + Lx.lp(context, top = 4f), + ) + + if (compact) { + column.addView(gallery(mod)) + column.addView(side, Lx.lp(context, top = 16f)) + } else { + val top = Lx.hbox(context, Gravity.TOP) + top.addView(gallery(mod), Lx.lp(context, 0f, -2f, 1.15f, end = 24f)) + top.addView(side, Lx.lp(context, 0f, -2f, 1f)) + column.addView(top) + } + + val text = description(mod.html) + if (text.isNotBlank()) { + column.addView(Lx.section(context, "About this mod"), Lx.lp(context, top = 28f, bottom = 10f)) + val panel = Lx.panel(context, 18f) + val body = Lx.body(context, text, Lx.TEXT) + body.setLinkTextColor(Lx.CYAN) + body.movementMethod = LinkMovementMethod.getInstance() + panel.addView(body) + column.addView(panel) + } + + val scroll = ScrollView(context) + scroll.addView(column, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + return scroll + } + + /** The screenshots, swiped through one at a time. */ + private fun gallery(mod: GameBanana.ModDetails): View { + val box = Lx.vbox(context) + val shots = mod.screenshots.ifEmpty { listOfNotNull(mod.summary.thumbnailUrl) } + val counter = Lx.label(context, "") + val list = RecyclerView(context) + list.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) + list.adapter = + object : RecyclerView.Adapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val frame = AspectFrame(context, 16f / 10f) + // MATCH_PARENT in a horizontal list: each screenshot is exactly one page wide. + frame.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) + val image = ImageView(context) + image.scaleType = ImageView.ScaleType.CENTER_CROP + image.setBackgroundColor(Lx.SURFACE_HI) + frame.addView(image, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + return object : RecyclerView.ViewHolder(frame) {} + } + + override fun getItemCount() = shots.size + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val image = (holder.itemView as FrameLayout).getChildAt(0) as ImageView + RemoteImages.bind(image, shots[position], dp(530f), null) + } + } + PagerSnapHelper().attachToRecyclerView(list) + fun paintCounter() { + val position = (list.layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition() + counter.text = if (shots.size > 1 && position >= 0) T("%s / %s · swipe for more").format(position + 1, shots.size).uppercase() else "" + } + list.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + if (newState == RecyclerView.SCROLL_STATE_IDLE) paintCounter() + } + }, + ) + val clip = FrameLayout(context) + clip.background = Lx.rounded(context, Lx.SURFACE, 8f) + Lx.clipRounded(clip, 8f) + clip.addView(list, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + if (shots.isEmpty()) { + val empty = AspectFrame(context, 16f / 10f) + empty.addView(Lx.iconView(context, Icon.IMAGE, Lx.FAINT, 40f), FrameLayout.LayoutParams(dp(40f), dp(40f), Gravity.CENTER)) + clip.addView(empty) + } + box.addView(clip) + box.addView(counter, Lx.lp(context, top = 8f)) + list.post { paintCounter() } + return box + } + + private fun fileRow(file: GameBanana.ModFile): View { + val row = Lx.hbox(context) + row.background = Lx.rounded(context, Lx.SURFACE, 8f) + row.setPadding(dp(14f), dp(12f), dp(12f), dp(12f)) + row.addView(Lx.iconView(context, if (file.isArchive) Icon.FOLDER else Icon.INFO, if (file.isArchive) Lx.MUTED else Lx.FAINT, 22f)) + val column = Lx.vbox(context) + column.addView(Lx.text(context, file.name, 14.5f, Lx.TEXT, Lx.MEDIUM, 2)) + val detail = + listOfNotNull(Lx.fileSize(file.size).takeIf { file.size > 0 }, file.description?.takeIf { it.isNotBlank() }) + .joinToString(" · ") + .ifEmpty { file.extension.uppercase() } + column.addView(Lx.caption(context, detail, Lx.MUTED, 2), Lx.lp(context, top = 3f)) + row.addView(column, Lx.lp(context, 0f, -2f, 1f, start = 14f, end = 8f)) + val actions = Lx.hbox(context) + row.addView(actions) + fileButtons += file to actions + return row + } + + /** Install / Installing... / Install again / can't, depending on what's going on. */ + private fun paintFileButtons() { + val mod = details ?: return + val installed = mod.summary.id in ModManager.installedGameBananaIds(context) + val busy = ModInstallJob.running + val thisBusy = busy && ModInstallJob.modId == mod.summary.id + for ((file, actions) in fileButtons) { + actions.removeAllViews() + if (!file.isArchive) { + actions.addView(Lx.badge(context, T(".%s not supported").format(file.extension.ifEmpty { "?" }), Lx.FAINT)) + continue + } + val label = + when { + thisBusy -> "Installing..." + installed -> "Install again" + else -> "Install" + } + val button = Lx.button(context, label, if (installed) Lx.Tone.SECONDARY else Lx.Tone.PRIMARY, Icon.DOWNLOAD, compact = true) { install(mod, file) } + Lx.setEnabled(button, !busy) + actions.addView(button) + } + } + + private fun install(mod: GameBanana.ModDetails, file: GameBanana.ModFile) { + if (!ModInstallJob.start(context, mod, file)) { + host.toast(T("Another mod is still installing. Try again when it's done."), Lx.Tone.INFO) + return + } + host.watchModInstall() + paintFileButtons() + } + + /** GameBanana's HTML description as styled text, without the pictures (they'd show as boxes). */ + private fun description(html: String): CharSequence { + if (html.isBlank()) return "" + val cleaned = html + .replace(Regex("(?is)]*>"), "") + .replace(Regex("(?is)"), "") + .replace(Regex("(?is)"), "") + return Html.fromHtml(cleaned, Html.FROM_HTML_MODE_COMPACT).trim() + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModsPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModsPage.kt new file mode 100644 index 0000000..d144f96 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ModsPage.kt @@ -0,0 +1,563 @@ +package com.driftdroid.android.launcher + +import android.content.Intent +import android.net.Uri +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.driftdroid.android.ModManager +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.T +import com.driftdroid.android.mods.GameBanana +import com.driftdroid.android.net.Http +import com.driftdroid.android.ui.AspectFrame +import com.driftdroid.android.ui.DriftSheet +import com.driftdroid.android.ui.DriftUi +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.IconDrawable +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages +import com.driftdroid.android.ui.Switch +import com.driftdroid.android.ui.TabStrip + +/** + * Mods: what's installed (on/off, priority by drag, delete, import a file you have) and a browser + * for GameBanana's Mario Kart Wii mods that installs with one tap - the mod browser and "My Stuff" + * manager WheelWizard has on PC, for the phone. + */ +internal class ModsPage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Mods") + override val subtitle: String + get() = if (browsing) T("Mario Kart Wii mods on GameBanana") else T("Turned-on mods load the next time you start the game") + + private var browsing = false + private lateinit var tabs: TabStrip + private lateinit var installedBar: View + private lateinit var installedSummary: TextView + private lateinit var browseBar: View + private lateinit var searchField: EditText + private val categoryChips = ArrayList() + private lateinit var content: FrameLayout + + // Installed + private lateinit var installedList: RecyclerView + private val installedAdapter = InstalledAdapter() + private lateinit var installedEmpty: View + + // Browse + private lateinit var browseList: RecyclerView + private val browseAdapter = BrowseAdapter() + private lateinit var browseState: FrameLayout + private var category = 0 + private var query = "" + private var page = 0 + private var complete = false + private var loading = false + private var generation = 0 + private var installedIds: Set = emptySet() + + override fun build(): View { + val root = Lx.vbox(context) + + tabs = TabStrip(context, listOf("Installed", "Browse GameBanana"), fill = compact) { showTab(it == 1) } + root.addView(tabs.view, Lx.lp(context).apply { marginStart = if (compact) 0 else gutter - dp(10f) }) + root.addView(Lx.divider(context)) + + // Installed: how many are on, and a way in for a file the player already has. + val iBar = Lx.hbox(context) + installedSummary = Lx.caption(context, "", Lx.MUTED, 2) + iBar.addView(installedSummary, Lx.lp(context, 0f, -2f, 1f, end = 12f)) + iBar.addView(Lx.button(context, "Import a file", Lx.Tone.GHOST, Icon.UPLOAD, compact = true) { importFile() }) + installedBar = iBar + + // Browse: search and categories. + val bBar = Lx.vbox(context) + val (box, field) = Lx.searchField(context, "Search mods", { startQuery(it) }) + searchField = field + val chips = Lx.hbox(context) + GameBanana.CATEGORIES.forEachIndexed { index, cat -> + val chip = Lx.chip(context, cat.label, index == 0) { selectCategory(index) } + categoryChips += chip + chips.addView(chip, Lx.lp(context, -2f, -2f, end = 8f)) + } + val chipScroll = HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + addView(chips) + } + if (compact) { + bBar.addView(box) + bBar.addView(chipScroll, Lx.lp(context, top = 10f)) + } else { + val line = Lx.hbox(context) + line.addView(chipScroll, Lx.lp(context, 0f, -2f, 1f, end = 12f)) + line.addView(box, Lx.lp(context, 300f, -2f)) + bBar.addView(line) + } + browseBar = bBar + + val bars = FrameLayout(context) + bars.setPadding(gutter, dp(12f), gutter, dp(4f)) + bars.addView(installedBar) + bars.addView(browseBar) + root.addView(bars) + + content = FrameLayout(context) + root.addView(content, Lx.lp(context, -1f, 0f, 1f, top = 8f)) + + // Installed + installedList = RecyclerView(context) + installedList.layoutManager = LinearLayoutManager(context) + installedList.adapter = installedAdapter + installedList.clipToPadding = false + installedList.setPadding(gutter, 0, gutter, dp(96f)) + val touch = ItemTouchHelper(DragCallback()) + touch.attachToRecyclerView(installedList) + installedAdapter.dragStarter = { touch.startDrag(it) } + installedEmpty = + Lx.emptyState( + context, Icon.EXTENSION, "No mods yet", + "Browse GameBanana and install one with a tap, or import a .zip, .7z or .rar you already have.", + "Browse mods", + ) { selectTab(true) } + content.addView(installedList, Lx.match()) + content.addView(installedEmpty, Lx.match()) + + // Browse + browseList = RecyclerView(context) + val grid = GridLayoutManager(context, 2) + grid.spanSizeLookup = + object : GridLayoutManager.SpanSizeLookup() { + override fun getSpanSize(position: Int) = if (browseAdapter.getItemViewType(position) == FOOTER) grid.spanCount else 1 + } + browseList.layoutManager = grid + browseList.adapter = browseAdapter + browseList.clipToPadding = false + val inner = gutter - dp(5f) + browseList.setPadding(inner, 0, inner, dp(96f)) + browseList.addOnLayoutChangeListener { v, left, _, right, _, oldLeft, _, oldRight, _ -> + if (right - left != oldRight - oldLeft) { + val spans = ((right - left) / dp(176f)).coerceIn(2, 6) + if (grid.spanCount != spans) v.post { grid.spanCount = spans } + } + } + browseList.addOnScrollListener( + object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + if (dy > 0 && grid.findLastVisibleItemPosition() >= browseAdapter.itemCount - 6) loadMore() + } + }, + ) + browseState = FrameLayout(context) + content.addView(browseList, Lx.match()) + content.addView(browseState, Lx.match()) + + selectTab(false) + return root + } + + override fun onShow() { + refreshInstalled() + } + + override fun onDataChanged(what: Data) { + if (what == Data.MODS) refreshInstalled() + } + + private fun selectTab(browse: Boolean) { + tabs.select(if (browse) 1 else 0) + showTab(browse) + } + + fun showTab(browse: Boolean) { + browsing = browse + installedBar.visibility = if (browse) View.GONE else View.VISIBLE + browseBar.visibility = if (browse) View.VISIBLE else View.GONE + installedList.visibility = View.GONE + installedEmpty.visibility = View.GONE + browseList.visibility = if (browse) View.VISIBLE else View.GONE + browseState.visibility = if (browse) View.VISIBLE else View.GONE + if (browse) { + if (browseAdapter.mods.isEmpty() && !loading) startQuery(query) + } else { + refreshInstalled() + } + refreshHeader() + } + + // --- Installed --- + + private fun refreshInstalled() { + val packs = ModManager.installedPacks(context) + installedIds = packs.mapNotNull { it.meta?.gameBananaId }.toSet() + tabs.setLabel(0, if (packs.isEmpty()) T("Installed") else T("Installed (%s)").format(packs.size)) + val on = packs.count { it.enabled } + installedSummary.text = + when { + packs.isEmpty() -> T("Mods you install show here") + packs.size == 1 -> T("%s of 1 on").format(on) + else -> T("%s of %s on · drag to set which wins").format(on, packs.size) + } + installedAdapter.items = packs.toMutableList() + installedAdapter.notifyDataSetChanged() + browseAdapter.notifyDataSetChanged() + if (!browsing) { + installedList.visibility = if (packs.isEmpty()) View.GONE else View.VISIBLE + installedEmpty.visibility = if (packs.isEmpty()) View.VISIBLE else View.GONE + } + } + + private fun importFile() { + host.openDocument { uri -> + if (uri == null) return@openDocument + val fileName = ModManager.displayName(context, uri) ?: "mod" + val extension = fileName.substringAfterLast('.', "").lowercase() + if (extension !in GameBanana.ARCHIVE_EXTENSIONS) { + host.toast(T("\"%s\" isn't a .zip, .7z or .rar file.").format(fileName), Lx.Tone.DANGER) + return@openDocument + } + val sheet = DriftSheet(host, T("Name this mod"), compact = true) + val field = sheet.textField("Mod name", fileName.substringBeforeLast('.')) + sheet.button("Cancel") { sheet.dismiss() } + sheet.button("Install", DriftUi.Style.PRIMARY) { + val name = field.text.toString() + sheet.dismiss() + host.task(T("Installing \"%s\"...").format(name), { progress -> + ModManager.importFile(context, uri, name) { count -> progress(T("%s files unpacked").format(count)) } + }) { result -> + result.fold( + onSuccess = { + host.toast(T("Installed \"%s\". It loads the next time you start the game.").format(it.title), Lx.Tone.PRIMARY) + host.broadcast(Data.MODS) + }, + onFailure = { host.toast(T("Couldn't install it: %s").format(it.message ?: "unknown error"), Lx.Tone.DANGER) }, + ) + } + } + sheet.show() + } + } + + private fun showPackMenu(pack: ModManager.Pack) { + val sheet = DriftSheet(host, pack.title, pack.meta?.author?.let { T("by %s").format(it) }) + val id = pack.meta?.gameBananaId + if (id != null) { + sheet.action("Open on GameBanana", "See its page, comments and updates") { + sheet.dismiss() + runCatching { host.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://gamebanana.com/mods/$id"))) } + } + } + sheet.action("Delete", "Removes the mod's files from the app") { + sheet.dismiss() + DriftSheet.confirm(host, T("Delete \"%s\"?").format(pack.title), "The mod's files are removed from the app.", "Delete", danger = true) { + ModManager.delete(context, pack) + host.broadcast(Data.MODS) + } + } + sheet.show() + } + + /** Installed mods as rows: priority number and handle, picture, name, on/off, menu. First in the list wins. */ + private inner class InstalledAdapter : RecyclerView.Adapter() { + var items: MutableList = mutableListOf() + var dragStarter: ((RecyclerView.ViewHolder) -> Unit)? = null + + inner class Holder( + val row: LinearLayout, + val handle: LinearLayout, + val order: TextView, + val thumb: ImageView, + val name: TextView, + val detail: TextView, + val toggle: Switch, + val more: ImageView, + ) : RecyclerView.ViewHolder(row) + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val row = Lx.hbox(context) + row.background = Lx.pressable(context, Lx.SURFACE, 8f) + row.setPadding(dp(4f), dp(10f), dp(6f), dp(10f)) + row.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = dp(8f) } + val handle = Lx.vbox(context) + handle.gravity = Gravity.CENTER + val order = Lx.display(context, "", 13f, Lx.MUTED) + handle.addView(order) + handle.addView(Lx.iconView(context, Icon.DRAG, Lx.FAINT, 18f), Lx.lp(context, 18f, 18f, top = 2f)) + handle.contentDescription = T("Drag to reorder") + row.addView(handle, Lx.lp(context, 34f, 48f)) + val thumb = ImageView(context) + thumb.scaleType = ImageView.ScaleType.CENTER_CROP + thumb.background = Lx.rounded(context, Lx.SURFACE_HI, 6f) + Lx.clipRounded(thumb, 6f) + row.addView(thumb, Lx.lp(context, if (compact) 64f else 80f, if (compact) 40f else 48f, start = 2f)) + val column = Lx.vbox(context) + val name = Lx.text(context, "", 15f, Lx.TEXT, Lx.MEDIUM, 2) + val detail = Lx.caption(context, "", Lx.MUTED, 1) + column.addView(name) + column.addView(detail, Lx.lp(context, top = 4f)) + row.addView(column, Lx.lp(context, 0f, -2f, 1f, start = 12f, end = 4f)) + val toggle = Switch(context) + row.addView(toggle, Lx.switchLp(context)) + val more = Lx.iconButton(context, Icon.MORE_VERT, "More", Lx.MUTED, android.graphics.Color.TRANSPARENT, 40f) {} + row.addView(more, Lx.lp(context, 40f, 40f, start = 2f)) + return Holder(row, handle, order, thumb, name, detail, toggle, more) + } + + override fun getItemCount() = items.size + + override fun onBindViewHolder(holder: Holder, position: Int) { + val pack = items[position] + holder.order.text = (position + 1).toString() + holder.name.text = pack.title + val meta = pack.meta + holder.detail.text = + when { + meta?.gameBananaId != null -> listOfNotNull(meta.author, Lx.ago(meta.installedAt)).filter { it.isNotBlank() }.joinToString(" · ") + meta != null -> listOfNotNull(meta.fileName, Lx.ago(meta.installedAt)).filter { it.isNotBlank() }.joinToString(" · ") + else -> T("Imported mod") + } + paintOn(holder, pack.enabled) + RemoteImages.bind(holder.thumb, meta?.thumbnailUrl, dp(80f), IconDrawable(Icon.EXTENSION, Lx.FAINT)) + holder.thumb.scaleType = if (meta?.thumbnailUrl != null) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.CENTER_INSIDE + if (meta?.thumbnailUrl == null) holder.thumb.setPadding(dp(20f), dp(8f), dp(20f), dp(8f)) else holder.thumb.setPadding(0, 0, 0, 0) + holder.row.setOnClickListener { + val index = holder.bindingAdapterPosition + val current = items.getOrNull(index) ?: return@setOnClickListener + val on = !holder.toggle.isOn + paintOn(holder, on) + ModManager.setEnabled(current, on) + items[index] = current.copy(enabled = on) + refreshSummary() + } + holder.more.setOnClickListener { items.getOrNull(holder.bindingAdapterPosition)?.let { showPackMenu(it) } } + holder.handle.setOnTouchListener { _, event -> + if (event.action == MotionEvent.ACTION_DOWN) dragStarter?.invoke(holder) + false + } + } + + private fun paintOn(holder: Holder, on: Boolean) { + holder.toggle.isOn = on + holder.thumb.alpha = if (on) 1f else 0.4f + holder.name.setTextColor(if (on) Lx.TEXT else Lx.MUTED) + } + + fun move(from: Int, to: Int) { + val moved = items.removeAt(from) + items.add(to, moved) + notifyItemMoved(from, to) + } + } + + private fun refreshSummary() { + val packs = installedAdapter.items + val on = packs.count { it.enabled } + installedSummary.text = if (packs.size == 1) T("%s of 1 on").format(on) else T("%s of %s on · drag to set which wins").format(on, packs.size) + } + + // Drag to reorder by the handle only, so a long press on the switch doesn't start a drag. The + // order is saved the moment a drag ends, and the priority numbers follow. + private inner class DragCallback : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { + override fun isLongPressDragEnabled() = false + + override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { + installedAdapter.move(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) + return true + } + + override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { + super.clearView(recyclerView, viewHolder) + ModManager.setOrder(context, installedAdapter.items.map { it.name }) + recyclerView.post { installedAdapter.notifyItemRangeChanged(0, installedAdapter.itemCount) } + } + + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} + } + + // --- Browse --- + + private fun selectCategory(index: Int) { + category = index + categoryChips.forEachIndexed { i, chip -> Lx.paintChip(chip, i == index) } + startQuery(searchField.text.toString()) + } + + private fun startQuery(text: String) { + query = text.trim() + generation++ + page = 0 + complete = false + loading = false + browseAdapter.mods.clear() + browseAdapter.footer = Footer.NONE + browseAdapter.notifyDataSetChanged() + showBrowseState(Lx.loading(context, "Loading mods...")) + loadMore() + } + + private fun loadMore() { + if (loading || complete) return + loading = true + val wanted = page + 1 + val token = generation + val cat = GameBanana.CATEGORIES[category] + val text = query + if (browseAdapter.mods.isNotEmpty()) { + browseAdapter.footer = Footer.LOADING + browseAdapter.notifyItemChanged(browseAdapter.itemCount - 1) + } + host.work({ + if (text.isEmpty()) GameBanana.list(cat.id, wanted) else GameBanana.search(text, wanted, cat) + }) { result -> + if (token != generation) return@work + loading = false + result.fold( + onSuccess = { list -> + page = wanted + complete = list.complete || list.mods.isEmpty() && text.isEmpty() + val known = browseAdapter.mods.map { it.id }.toHashSet() + val fresh = list.mods.filter { known.add(it.id) } + browseAdapter.mods.addAll(fresh) + browseAdapter.footer = if (complete) Footer.END else Footer.NONE + browseAdapter.notifyDataSetChanged() + if (browseAdapter.mods.isEmpty() && (complete || list.mods.isEmpty())) { + complete = true + showBrowseState( + Lx.emptyState( + context, Icon.SEARCH, "Nothing found", + if (text.isEmpty()) "There are no mods in this category yet." else T("No mods match \"%s\".").format(text), + ), + ) + } else { + showBrowseState(null) + // A search filtered down to a few results may not fill the screen: keep going. + if (fresh.size < 6 && !complete) browseList.post { loadMore() } + } + }, + onFailure = { error -> + if (browseAdapter.mods.isEmpty()) { + showBrowseState( + Lx.emptyState(context, Icon.WARNING, "GameBanana didn't answer", T("Check your connection and try again (%s).").format(Http.describe(error)), "Try again") { + startQuery(query) + }, + ) + } else { + browseAdapter.footer = Footer.ERROR + browseAdapter.notifyItemChanged(browseAdapter.itemCount - 1) + } + }, + ) + } + } + + private fun showBrowseState(view: View?) { + browseState.removeAllViews() + if (view != null) browseState.addView(view, Lx.match()) + browseState.visibility = if (view != null && browsing) View.VISIBLE else View.GONE + } + + /** GameBanana mods as picture cards; one already installed carries a green slanted plate. */ + private inner class BrowseAdapter : RecyclerView.Adapter() { + val mods = ArrayList() + var footer = Footer.NONE + + inner class Card( + val root: LinearLayout, + val image: ImageView, + val badge: TextView, + val name: TextView, + val author: TextView, + val likes: TextView, + val views: TextView, + ) : RecyclerView.ViewHolder(root) + + inner class FooterHolder(val root: FrameLayout) : RecyclerView.ViewHolder(root) + + override fun getItemViewType(position: Int) = if (position >= mods.size) FOOTER else CARD + + override fun getItemCount() = mods.size + if (footer == Footer.NONE) 0 else 1 + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + if (viewType == FOOTER) { + val frame = FrameLayout(context) + frame.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(64f)) + return FooterHolder(frame) + } + val root = Lx.vbox(context) + root.background = Lx.pressable(context, Lx.SURFACE, 8f) + Lx.clipRounded(root, 8f) + root.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(5f), dp(5f), dp(5f), dp(5f)) + } + val frame = AspectFrame(context, 16f / 10f) + val image = ImageView(context) + image.scaleType = ImageView.ScaleType.CENTER_CROP + image.setBackgroundColor(Lx.SURFACE_HI) + frame.addView(image, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + val badge = Lx.plateBadge(context, T("Installed").uppercase(), Lx.ACCENT, Lx.ACCENT_TEXT, 11f) + frame.addView(badge, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + gravity = Gravity.TOP or Gravity.START + setMargins(dp(8f), dp(8f), 0, 0) + }) + root.addView(frame) + val body = Lx.vbox(context) + body.setPadding(dp(12f), dp(10f), dp(12f), dp(12f)) + val name = Lx.text(context, "", 14f, Lx.TEXT, Lx.MEDIUM, 2) + name.minLines = 2 + name.setLineSpacing(0f, 1.1f) + body.addView(name) + val author = Lx.caption(context, "", Lx.MUTED, 1) + body.addView(author, Lx.lp(context, top = 6f)) + val stats = Lx.hbox(context) + stats.addView(Lx.iconView(context, Icon.THUMB_UP, Lx.FAINT, 13f)) + val likes = Lx.caption(context, "", Lx.FAINT) + stats.addView(likes, Lx.lp(context, -2f, -2f, start = 5f, end = 12f)) + stats.addView(Lx.iconView(context, Icon.VISIBILITY, Lx.FAINT, 13f)) + val views = Lx.caption(context, "", Lx.FAINT) + stats.addView(views, Lx.lp(context, -2f, -2f, start = 5f)) + body.addView(stats, Lx.lp(context, top = 8f)) + root.addView(body) + return Card(root, image, badge, name, author, likes, views) + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + if (holder is FooterHolder) { + holder.root.removeAllViews() + val view: View = + when (footer) { + Footer.LOADING, Footer.NONE -> Lx.spinner(context, 28f) + Footer.END -> Lx.label(context, "That's everything") + Footer.ERROR -> Lx.button(context, "Couldn't load more - try again", Lx.Tone.GHOST, Icon.REFRESH, compact = true) { loadMore() } + } + holder.root.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)) + return + } + val card = holder as Card + val mod = mods[position] + card.name.text = mod.name + card.author.text = listOf(mod.author, mod.category).filter { it.isNotBlank() }.joinToString(" · ") + card.likes.text = Lx.number(mod.likes) + card.views.text = Lx.number(mod.views) + card.badge.visibility = if (mod.id in installedIds) View.VISIBLE else View.GONE + RemoteImages.bind(card.image, mod.previewUrl ?: mod.thumbnailUrl, dp(240f), null) + card.root.setOnClickListener { host.open(ModDetailPage(host, mod)) } + } + } + + private enum class Footer { NONE, LOADING, END, ERROR } + + private companion object { + const val CARD = 0 + const val FOOTER = 1 + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/Page.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/Page.kt new file mode 100644 index 0000000..df7b283 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/Page.kt @@ -0,0 +1,66 @@ +package com.driftdroid.android.launcher + +import android.content.Context +import android.view.View +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx + +/** The launcher's top-level pages, in tab-bar and rail order. On a phone Settings sits behind the header's gear instead. */ +internal enum class Tab(val label: String, val icon: Icon) { + HOME("Home", Icon.HOME), + MODS("Mods", Icon.EXTENSION), + ROOMS("Rooms", Icon.PUBLIC), + RANKS("Ranks", Icon.TROPHY), + PROFILE("Profile", Icon.FACE), + SETTINGS("Settings", Icon.SETTINGS), +} + +/** + * One screen of the launcher. The top-level pages sit behind the tab bar (or rail); detail pages + * (a mod, a room, a player, the Mii editor) are pushed on top of them with a back arrow. The shell + * ([ModePickerActivity]) owns the header, the back stack, toasts and the task bar. A page lays + * itself out for [compact] - one column on a phone held upright - or side by side. + */ +internal abstract class Page(val host: ModePickerActivity) { + enum class Data { MODS, MIIS, SAVES, ROOMS, INSTALL } + + val context: Context get() = host + + abstract val title: String + open val subtitle: String? get() = null + + /** A picture (drawable id) the header shows instead of the title and subtitle - Home's wordmark. */ + open val headerArt: Int? get() = null + + private var built: View? = null + val view: View get() = built ?: build().also { built = it } + + protected abstract fun build(): View + + /** Buttons for the header's right-hand side. Built once per page. */ + open fun actions(): List = emptyList() + + open fun onShow() {} + + open fun onHide() {} + + /** The page was popped off the stack for good. */ + open fun onClose() {} + + /** Something this page may show changed (a mod installed, a Mii saved, rooms refreshed...). */ + open fun onDataChanged(what: Data) {} + + /** Back was pressed while this page is on top. Return true to keep the page open. */ + open fun onBack(): Boolean = false + + /** Phone held upright: one column, controls stacked, search boxes in the page instead of the header. */ + val compact: Boolean get() = host.compact + + /** The page's side margin in pixels. */ + protected val gutter: Int get() = Lx.gutter(context) + + protected fun dp(value: Float): Int = Lx.dp(context, value) + + protected fun refreshHeader() = host.refreshHeader(this) +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/ProfilePage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ProfilePage.kt new file mode 100644 index 0000000..99737c4 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/ProfilePage.kt @@ -0,0 +1,454 @@ +package com.driftdroid.android.launcher + +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.HorizontalScrollView +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.SaveData +import com.driftdroid.android.T +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiDatabase +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.mii.MiiStudio +import com.driftdroid.android.profile.SaveFile +import com.driftdroid.android.ui.DriftSheet +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.TabStrip +import java.io.IOException +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * The player's side of things: their licenses (Mii, friend code, VR/BR, friend list) from each + * save, and every Mii in the Mii file with an editor - WheelWizard's profile and Mii pages. + */ +internal class ProfilePage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Profile") + override val subtitle: String + get() = if (showingMiis) T("The Miis your licenses race as") else T("Licenses, ratings and friends from your saves") + + private var showingMiis = false + private var game = SaveData.Game.RetroRewind + private var selectedLicense = 0 + private lateinit var tabs: TabStrip + private lateinit var tools: LinearLayout + private lateinit var body: FrameLayout + private val gameChips = HashMap() + + override fun build(): View { + val root = Lx.vbox(context) + tabs = TabStrip(context, listOf("Licenses", "Miis"), fill = compact) { showTab(it == 1) } + root.addView(tabs.view, Lx.lp(context).apply { marginStart = if (compact) 0 else gutter - dp(10f) }) + root.addView(Lx.divider(context)) + // The tab's own tools: which game's licenses, or what to do with Miis. + tools = Lx.hbox(context) + root.addView(HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + setPadding(gutter, dp(12f), gutter, 0) + clipToPadding = false + addView(tools) + }) + if (host.isGameLoaded()) { + val warn = Lx.hbox(context) + warn.background = Lx.rounded(context, Lx.alpha(Lx.AMBER, 0.12f), 8f) + warn.setPadding(dp(14f), dp(10f), dp(14f), dp(10f)) + warn.addView(Lx.iconView(context, Icon.WARNING, Lx.AMBER, 18f)) + warn.addView( + Lx.caption(context, T("The game is still open in the background and may overwrite changes made here when it saves. Close DriftDroid from Recents and reopen it first to be safe."), Lx.TEXT, 4), + Lx.lp(context, 0f, -2f, 1f, start = 12f), + ) + root.addView(warn, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + marginStart = gutter + marginEnd = gutter + topMargin = dp(12f) + }) + } + body = FrameLayout(context) + root.addView(body, Lx.lp(context, -1f, 0f, 1f, top = 12f)) + tabs.select(0) + showTab(false) + return root + } + + override fun onShow() = reload() + + override fun onDataChanged(what: Data) { + if (what == Data.MIIS || what == Data.SAVES) reload() + } + + private fun showTab(miis: Boolean) { + showingMiis = miis + tools.removeAllViews() + if (miis) { + tools.addView(Lx.button(context, "New Mii", Lx.Tone.PRIMARY, Icon.ADD, compact = true) { host.open(MiiEditorPage(host, null, null)) }, Lx.lp(context, -2f, -2f, end = 8f)) + tools.addView(Lx.button(context, "Import", Lx.Tone.GHOST, Icon.UPLOAD, compact = true) { importMii() }, Lx.lp(context, -2f, -2f, end = 8f)) + tools.addView(Lx.button(context, "Export all", Lx.Tone.GHOST, Icon.DOWNLOAD, compact = true) { exportAll() }) + } else { + for (g in listOf(SaveData.Game.RetroRewind, SaveData.Game.MarioKartWii)) { + val chip = Lx.chip(context, g.label, g == game) { selectGame(g) } + gameChips[g] = chip + tools.addView(chip, Lx.lp(context, -2f, -2f, end = 8f)) + } + } + refreshHeader() + reload() + } + + private fun selectGame(g: SaveData.Game) { + game = g + selectedLicense = 0 + gameChips.forEach { (k, chip) -> Lx.paintChip(chip, k == g) } + reload() + } + + private fun reload() { + if (!::body.isInitialized) return + if (showingMiis) loadMiis() else loadLicenses() + } + + private fun setBody(view: View) { + body.removeAllViews() + body.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + } + + // --- Licenses --- + + private fun loadLicenses() { + val wanted = game + host.work({ SaveFile.load(context, wanted) to MiiDatabase.load(context) }) { result -> + if (showingMiis || game != wanted) return@work + val (save, miis) = result.getOrNull() ?: (null to null) + if (save == null || save.licenses.isEmpty()) { + setBody(Lx.emptyState(context, Icon.FLAG, T("No %s save yet").format(wanted.label), "Play it once and make a license - it'll show up here with its friend code, ratings and friends.")) + return@work + } + selectedLicense = selectedLicense.coerceIn(0, save.licenses.size - 1) + setBody(licensesView(save, miis)) + } + } + + private fun licensesView(save: SaveFile.Save, miis: MiiDatabase.Snapshot?): View { + val column = Lx.vbox(context) + column.setPadding(0, 0, 0, dp(96f)) + val cards = Lx.hbox(context, Gravity.TOP) + save.licenses.forEachIndexed { i, license -> + cards.addView(licenseCard(license, i == selectedLicense) { + selectedLicense = i + setBody(licensesView(save, miis)) + }, Lx.lp(context, if (compact) 250f else 270f, -2f, end = 10f)) + } + column.addView(HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + setPadding(gutter, 0, gutter, 0) + clipToPadding = false + addView(cards) + }) + + val license = save.licenses[selectedLicense] + val inner = Lx.vbox(context) + inner.setPadding(gutter, 0, gutter, 0) + val actions = Lx.hbox(context) + if (license.isOnline) { + actions.addView(Lx.button(context, "Copy friend code", Lx.Tone.GHOST, Icon.COPY, compact = true) { PlayerActions.copy(host, license.friendCode) }, Lx.lp(context, -2f, -2f, end = 8f)) + } + actions.addView(Lx.button(context, "Change Mii", Lx.Tone.GHOST, Icon.FACE, compact = true) { changeMii(save.game, license, miis) }) + inner.addView(actions, Lx.lp(context, top = 14f)) + inner.addView(Lx.section(context, T("Friends · %s of 30").format(license.friends.size)), Lx.lp(context, top = 24f, bottom = 10f)) + + if (license.friends.isEmpty()) { + inner.addView( + Lx.panel(context, 18f).apply { + addView(Lx.body(context, T("No friends on this license yet. Add people from Rooms or Ranks - they'll show as pending until they add you back."))) + }, + ) + } + for (friend in license.friends) { + val row = PlayerRow(context) + row.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = dp(6f) } + row.bind(friend.mii, friend.displayName, friend.friendCode) + if (friend.pending) row.badges.addView(Lx.badge(context, "Pending", Lx.AMBER)) + row.setValue(T("%s VR").format(Lx.number(friend.vr)), Lx.AMBER, T("%s wins · %s losses").format(friend.wins, friend.losses)) + row.setOnClickListener { friendMenu(save.game, license, friend) } + inner.addView(row) + } + column.addView(inner) + val scroll = ScrollView(context) + scroll.addView(column, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + return scroll + } + + private fun licenseCard(license: SaveFile.License, selected: Boolean, onClick: () -> Unit): View { + // A racing license: the one being shown is outlined green; the others are a tap away. + val card = Lx.vbox(context) + card.background = Lx.pressable(context, if (selected) Lx.SURFACE_HI else Lx.SURFACE, 8f, if (selected) Lx.ACCENT else 0) + card.setPadding(dp(16f), dp(14f), dp(16f), dp(16f)) + card.setOnClickListener { onClick() } + card.isSelected = selected + val top = Lx.hbox(context) + val mii = ImageView(context) + MiiImages.bind(mii, license.mii, MiiStudio.Size.LARGE) + top.addView(mii, Lx.lp(context, 58f, 58f)) + val names = Lx.vbox(context) + names.addView(Lx.display(context, license.displayName, 20f)) + names.addView(Lx.caption(context, if (license.isOnline) license.friendCode else T("Not online yet"), Lx.MUTED), Lx.lp(context, top = 4f)) + top.addView(names, Lx.lp(context, 0f, -2f, 1f, start = 12f)) + card.addView(top) + val stats = Lx.hbox(context) + stats.addView(Lx.stat(context, Lx.number(license.vr), "VR", Lx.AMBER, 22f), Lx.lp(context, 0f, -2f, 1f)) + stats.addView(Lx.stat(context, Lx.number(license.br), "BR", Lx.TEXT, 22f), Lx.lp(context, 0f, -2f, 1f)) + stats.addView(Lx.stat(context, Lx.number(license.wins), "wins", Lx.TEXT, 22f), Lx.lp(context, 0f, -2f, 1f)) + card.addView(stats, Lx.lp(context, top = 16f)) + card.addView(Lx.caption(context, T("%s races").format(Lx.number(license.races)), Lx.FAINT), Lx.lp(context, top = 10f)) + return card + } + + private fun friendMenu(game: SaveData.Game, license: SaveFile.License, friend: SaveFile.Friend) { + val sheet = DriftSheet(host, friend.displayName, friend.friendCode) + if (friend.friendCode.isNotBlank()) { + sheet.action("Copy friend code", friend.friendCode) { + sheet.dismiss() + PlayerActions.copy(host, friend.friendCode) + } + sheet.action("Profile and VR history", "From the Retro WFC leaderboard") { + sheet.dismiss() + host.open(PlayerPage(host, friend.friendCode, friend.displayName, friend.mii)) + } + } + sheet.action("Remove friend", T("Takes them off %s's list").format(license.displayName)) { + sheet.dismiss() + DriftSheet.confirm(host, T("Remove %s?").format(friend.displayName), "They're taken off this license's friend list. The save is backed up first (rksys.dat.bak).", "Remove", danger = true) { + host.guardGameRunning { + host.work({ SaveFile.removeFriend(context, game, license.index, friend.profileId) }) { result -> + result.fold( + onSuccess = { host.broadcast(Data.SAVES) }, + onFailure = { host.toast(T("Couldn't remove them: %s").format(it.message ?: "unknown error"), Lx.Tone.DANGER) }, + ) + } + } + } + } + sheet.show() + } + + private fun changeMii(game: SaveData.Game, license: SaveFile.License, miis: MiiDatabase.Snapshot?) { + if (miis == null || miis.slots.isEmpty()) { + host.toast(T("There are no Miis to pick from yet."), Lx.Tone.INFO) + return + } + val sheet = DriftSheet(host, T("Race as which Mii?"), license.displayName) + val rows = ArrayList() + miis.slots.forEach { slot -> + rows += sheet.radio(slot.mii.displayName, slot.mii.creatorName.ifBlank { null }?.let { T("by %s").format(it) }, slot.mii.miiId == license.miiId) { + sheet.dismiss() + if (slot.mii.miiId == license.miiId) return@radio + host.guardGameRunning { + host.work({ SaveFile.setLicenseMii(context, game, license.index, slot.mii) }) { result -> + result.fold( + onSuccess = { + host.toast(T("%s now races as %s.").format(license.displayName, slot.mii.displayName), Lx.Tone.PRIMARY) + host.broadcast(Data.SAVES) + }, + onFailure = { host.toast(T("Couldn't change the Mii: %s").format(it.message ?: "unknown error"), Lx.Tone.DANGER) }, + ) + } + } + } + } + sheet.show() + } + + // --- Miis --- + + private fun loadMiis() { + host.work({ + val snapshot = MiiDatabase.load(context) + val used = + SaveData.Game.values().flatMap { g -> SaveFile.load(context, g)?.licenses.orEmpty() }.map { it.miiId }.toSet() + snapshot to used + }) { result -> + if (!showingMiis) return@work + val (snapshot, used) = result.getOrNull() ?: (null to emptySet()) + if (snapshot == null) { + val exists = MiiDatabase.exists(context) + setBody( + Lx.emptyState( + context, Icon.FACE, + if (exists) "The Mii file couldn't be read" else "No Mii file yet", + if (exists) "It failed its own check, so DriftDroid won't touch it. Import a good RFL_DB.dat to replace it." else "Start Mario Kart Wii once - the game makes the Mii file the first time it runs.", + ), + ) + return@work + } + if (snapshot.slots.isEmpty()) { + setBody(Lx.emptyState(context, Icon.FACE, "No Miis yet", "Make one here, or import a .rcd Mii file.", "New Mii") { host.open(MiiEditorPage(host, null, null)) }) + return@work + } + val list = RecyclerView(context) + val grid = GridLayoutManager(context, 5) + list.layoutManager = grid + list.clipToPadding = false + val inner = gutter - dp(5f) + list.setPadding(inner, 0, inner, dp(96f)) + list.addOnLayoutChangeListener { v, left, _, right, _, oldLeft, _, oldRight, _ -> + if (right - left != oldRight - oldLeft) { + val spans = ((right - left) / dp(112f)).coerceIn(3, 10) + if (grid.spanCount != spans) v.post { grid.spanCount = spans } + } + } + list.adapter = MiiAdapter(snapshot.slots, used) + val column = Lx.vbox(context) + column.addView(Lx.label(context, T("%s of 100 slots used · hold one for more").format(snapshot.slots.size)), Lx.lp(context, start = gutter / context.resources.displayMetrics.density, bottom = 8f)) + column.addView(list, Lx.lp(context, -1f, 0f, 1f)) + setBody(column) + } + } + + private inner class MiiAdapter(val slots: List, val used: Set) : RecyclerView.Adapter() { + override fun getItemCount() = slots.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val tile = Lx.vbox(context) + tile.gravity = Gravity.CENTER_HORIZONTAL + tile.background = Lx.pressable(context, Lx.SURFACE, 8f) + tile.setPadding(dp(6f), dp(10f), dp(6f), dp(12f)) + tile.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(5f), dp(5f), dp(5f), dp(5f)) + } + return object : RecyclerView.ViewHolder(tile) {} + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val slot = slots[position] + val tile = holder.itemView as LinearLayout + tile.removeAllViews() + val image = ImageView(context) + MiiImages.bind(image, slot.mii) + tile.addView(image, Lx.lp(context, 72f, 72f)) + val name = Lx.hbox(context, Gravity.CENTER) + if (slot.mii.isFavorite) name.addView(Lx.iconView(context, Icon.STAR, Lx.AMBER, 13f), Lx.lp(context, 13f, 13f, end = 4f)) + name.addView(Lx.text(context, slot.mii.displayName, 13.5f, Lx.TEXT, Lx.MEDIUM, 1)) + tile.addView(name, Lx.lp(context, -2f, -2f, top = 8f)) + val badge = if (slot.mii.miiId in used) Lx.badge(context, "License", Lx.ACCENT) else Lx.caption(context, slot.mii.creatorName.ifBlank { " " }, Lx.FAINT) + tile.addView(badge, Lx.lp(context, -2f, -2f, top = 5f)) + tile.setOnClickListener { host.open(MiiEditorPage(host, slot.index, slot.mii)) } + tile.setOnLongClickListener { + miiMenu(slot, slot.mii.miiId in used) + true + } + } + } + + private fun miiMenu(slot: MiiDatabase.Slot, inUse: Boolean) { + val sheet = DriftSheet(host, slot.mii.displayName, T("Slot %s").format(slot.index + 1)) + sheet.action("Edit", null) { + sheet.dismiss() + host.open(MiiEditorPage(host, slot.index, slot.mii)) + } + sheet.action("Duplicate", "Makes an editable copy") { + sheet.dismiss() + writeMiis { + val snapshot = MiiDatabase.load(context) ?: throw IOException("the Mii file is gone") + MiiDatabase.add(context, MiiDatabase.adopt(snapshot, slot.mii)) + } + } + sheet.action("Export as .rcd", "One Mii, for another Wii, Dolphin or a friend") { + sheet.dismiss() + host.createDocument("application/octet-stream", "${slot.mii.displayName.replace(Regex("[^A-Za-z0-9 _-]"), "_")}.rcd") { uri -> + if (uri == null) return@createDocument + host.work({ host.contentResolver.openOutputStream(uri)?.use { it.write(slot.mii.data) } ?: throw IOException("couldn't open the destination") }) { result -> + host.toast(if (result.isSuccess) T("Mii exported.") else T("Export failed: %s").format(result.exceptionOrNull()?.message), if (result.isSuccess) Lx.Tone.PRIMARY else Lx.Tone.DANGER) + } + } + } + sheet.action("Delete", if (inUse) T("A license races as this Mii - pick another for it first") else T("Frees the slot")) { + sheet.dismiss() + if (inUse) { + host.toast(T("A license still uses this Mii. Change that license's Mii first."), Lx.Tone.INFO) + return@action + } + DriftSheet.confirm(host, T("Delete %s?").format(slot.mii.displayName), "The Mii is removed from the Mii file. A backup of the file is kept (RFL_DB.dat.bak).", "Delete", danger = true) { + writeMiis { + val snapshot = MiiDatabase.load(context) ?: throw IOException("the Mii file is gone") + val current = snapshot.slots.firstOrNull { it.index == slot.index } + if (current?.mii?.miiId != slot.mii.miiId) throw IOException("the Mii file changed - reopen this page and try again") + MiiDatabase.save(context, MiiDatabase.withSlot(snapshot.bytes, slot.index, null)) + } + } + } + sheet.show() + } + + /** Runs a Mii file change off the main thread, then refreshes everything that shows Miis. */ + private fun writeMiis(change: () -> Unit) { + host.guardGameRunning { + host.work({ change() }) { result -> + result.fold( + onSuccess = { host.broadcast(Data.MIIS) }, + onFailure = { host.toast(it.message ?: T("Something went wrong"), Lx.Tone.DANGER) }, + ) + } + } + } + + /** A single .rcd Mii goes into a free slot; a whole RFL_DB.dat replaces the file (after asking). */ + private fun importMii() { + host.openDocument { uri -> + if (uri == null) return@openDocument + host.work({ host.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: throw IOException("couldn't open the file") }) { result -> + val bytes = result.getOrElse { + host.toast(T("Couldn't read that file: %s").format(it.message), Lx.Tone.DANGER) + return@work + } + when { + bytes.size == Mii.RECORD_BYTES -> { + val mii = Mii.fromBytes(bytes) + if (mii == null) { + host.toast(T("That Mii file is empty."), Lx.Tone.DANGER) + return@work + } + writeMiis { + val snapshot = MiiDatabase.load(context) ?: throw IOException("there's no Mii file yet - start Mario Kart Wii once first") + val slot = MiiDatabase.add(context, MiiDatabase.adopt(snapshot, mii)) + host.runOnUiThread { host.toast(T("%s added to slot %s.").format(mii.displayName, slot + 1), Lx.Tone.PRIMARY) } + } + } + bytes.size == MiiDatabase.DATABASE_BYTES -> { + if (!MiiDatabase.isValid(bytes)) { + host.toast(T("That Mii database failed its check - it may be damaged."), Lx.Tone.DANGER) + return@work + } + DriftSheet.confirm(host, "Replace all Miis?", "Every Mii is replaced with the ones in the picked file. The current file is backed up first (RFL_DB.dat.bak).", "Replace", danger = true) { + writeMiis { MiiDatabase.save(context, bytes) } + } + } + else -> host.toast(T("That isn't a Mii (.rcd, 74 bytes) or a Mii database (RFL_DB.dat)."), Lx.Tone.DANGER) + } + } + } + } + + private fun exportAll() { + val file = MiiDatabase.file(context) + if (!file.isFile) { + host.toast(T("No Mii file yet - start Mario Kart Wii once first."), Lx.Tone.INFO) + return + } + val stamp = SimpleDateFormat("yyyy-MM-dd_HHmmss", Locale.US).format(Date()) + host.createDocument("application/octet-stream", "DriftDroid-Mii-$stamp.dat") { uri -> + if (uri == null) return@createDocument + host.work({ host.contentResolver.openOutputStream(uri)?.use { out -> file.inputStream().use { it.copyTo(out) } } ?: throw IOException("couldn't open the destination") }) { result -> + host.toast(if (result.isSuccess) T("Mii file exported.") else T("Export failed: %s").format(result.exceptionOrNull()?.message), if (result.isSuccess) Lx.Tone.PRIMARY else Lx.Tone.DANGER) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/RoomsPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/RoomsPage.kt new file mode 100644 index 0000000..23071b8 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/RoomsPage.kt @@ -0,0 +1,461 @@ +package com.driftdroid.android.launcher + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.SaveData +import com.driftdroid.android.T +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.net.Http +import com.driftdroid.android.online.RetroWfc +import com.driftdroid.android.profile.FriendCode +import com.driftdroid.android.profile.SaveFile +import com.driftdroid.android.ui.DriftSheet +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx + +private const val POLL_MS = 40_000L + +/** Who's racing on Retro WFC right now, room by room - refreshed every 40 seconds while open. */ +internal class RoomsPage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Rooms") + override val subtitle: String + get() { + val status = RetroWfc.lastRooms ?: return T("Live from Retro WFC") + return T("%s racers in %s rooms · updated %s").format( + Lx.number(status.totalPlayers), status.activeRooms.size, Lx.ago(status.fetchedAt), + ) + } + + private val handler = Handler(Looper.getMainLooper()) + private val poll = Runnable { fetch() } + private lateinit var frame: FrameLayout + private lateinit var grid: RecyclerView + private lateinit var results: RecyclerView + private lateinit var state: FrameLayout + private val roomAdapter = RoomAdapter() + private val resultAdapter = PlayerAdapter() + private var query = "" + private var fetching = false + private var lastError: Throwable? = null + + // On a phone the search box sits at the top of the page; on a wide screen it fits in the header. + override fun actions(): List { + val refresh = Lx.iconButton(context, Icon.REFRESH, "Refresh", Lx.MUTED, android.graphics.Color.TRANSPARENT, 44f) { fetch() } + if (compact) return listOf(refresh) + val box = searchBox() + box.layoutParams = LinearLayout.LayoutParams(dp(260f), ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginEnd = dp(8f) } + return listOf(box, refresh) + } + + private fun searchBox(): View = Lx.searchField(context, "Find a player", { applyQuery(it) }, { applyQuery(it) }).first + + override fun build(): View { + frame = FrameLayout(context) + val inner = gutter - dp(6f) + frame.setPadding(inner, 0, inner, 0) + grid = RecyclerView(context) + val layout = GridLayoutManager(context, 2) + grid.layoutManager = layout + grid.adapter = roomAdapter + grid.clipToPadding = false + grid.setPadding(0, dp(4f), 0, dp(96f)) + grid.addOnLayoutChangeListener { v, left, _, right, _, oldLeft, _, oldRight, _ -> + if (right - left != oldRight - oldLeft) { + val spans = ((right - left) / dp(300f)).coerceIn(1, 4) + if (layout.spanCount != spans) v.post { layout.spanCount = spans } + } + } + results = RecyclerView(context) + results.layoutManager = LinearLayoutManager(context) + results.adapter = resultAdapter + results.clipToPadding = false + results.setPadding(dp(6f), dp(4f), dp(6f), dp(96f)) + state = FrameLayout(context) + frame.addView(grid, match()) + frame.addView(results, match()) + frame.addView(state, match()) + render() + if (!compact) return frame + val column = Lx.vbox(context) + column.addView(searchBox(), LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + marginStart = gutter + marginEnd = gutter + bottomMargin = dp(8f) + }) + column.addView(frame, Lx.lp(context, -1f, 0f, 1f)) + return column + } + + private fun match() = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + + override fun onShow() { + val last = RetroWfc.lastRooms + if (last == null || System.currentTimeMillis() - last.fetchedAt > 15_000) fetch() else schedule() + render() + } + + override fun onHide() = handler.removeCallbacks(poll) + + override fun onClose() = handler.removeCallbacks(poll) + + override fun onDataChanged(what: Data) { + if (what == Data.ROOMS) render() + } + + private fun schedule() { + handler.removeCallbacks(poll) + handler.postDelayed(poll, POLL_MS) + } + + private fun fetch() { + if (fetching) return + fetching = true + handler.removeCallbacks(poll) + host.work({ RetroWfc.fetchRooms() }) { result -> + fetching = false + lastError = result.exceptionOrNull() + host.broadcast(Data.ROOMS) + refreshHeader() + render() + if (host.isShowing(this)) schedule() + } + } + + private fun applyQuery(text: String) { + query = text.trim() + render() + } + + private fun render() { + if (!::frame.isInitialized) return + val status = RetroWfc.lastRooms + state.removeAllViews() + grid.visibility = View.GONE + results.visibility = View.GONE + state.visibility = View.VISIBLE + when { + status == null && lastError == null -> state.addView(Lx.loading(context, "Asking Retro WFC who's online..."), match()) + status == null -> + state.addView( + Lx.emptyState(context, Icon.WARNING, "Retro WFC didn't answer", T("Check your connection and try again (%s).").format(Http.describe(lastError!!)), "Try again") { fetch() }, + match(), + ) + query.isNotEmpty() -> { + val q = query.lowercase() + val hits = + status.rooms.flatMap { room -> room.players.map { room to it } } + .filter { (_, p) -> p.displayName.lowercase().contains(q) || p.friendCode.contains(q) } + resultAdapter.items = hits + resultAdapter.notifyDataSetChanged() + if (hits.isEmpty()) { + state.addView(Lx.emptyState(context, Icon.SEARCH, "Nobody by that name", T("No one online matches \"%s\" right now.").format(query)), match()) + } else { + state.visibility = View.GONE + results.visibility = View.VISIBLE + } + } + status.activeRooms.isEmpty() -> { + state.addView( + Lx.emptyState(context, Icon.PUBLIC, "Nobody's racing right now", "Rooms show up here the moment people start racing. Check back soon.", "Refresh") { fetch() }, + match(), + ) + } + else -> { + roomAdapter.rooms = status.activeRooms + roomAdapter.notifyDataSetChanged() + state.visibility = View.GONE + grid.visibility = View.VISIBLE + } + } + } + + private inner class RoomAdapter : RecyclerView.Adapter() { + var rooms: List = emptyList() + + override fun getItemCount() = rooms.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val card = Lx.vbox(context) + card.background = Lx.pressable(context, Lx.SURFACE, 8f) + card.setPadding(dp(16f), dp(14f), dp(16f), dp(14f)) + card.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(6f), dp(6f), dp(6f), dp(6f)) + } + return object : RecyclerView.ViewHolder(card) {} + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val room = rooms[position] + val card = holder.itemView as LinearLayout + card.removeAllViews() + val top = Lx.hbox(context) + top.addView(Lx.label(context, room.label), Lx.lp(context, 0f, -2f, 1f)) + top.addView(if (room.isJoinable) Lx.status(context, T("Open"), Lx.ACCENT, Lx.TEXT) else Lx.status(context, T("Full or racing"), Lx.FAINT, Lx.MUTED)) + card.addView(top) + val track = room.race?.trackName?.takeIf { it.isNotBlank() } + card.addView(Lx.display(context, track ?: T("Between races"), 20f), Lx.lp(context, top = 10f)) + val line = + listOfNotNull( + room.race?.takeIf { it.number > 0 }?.let { T("Race %s").format(it.number) }, + room.createdAt?.let { T("open since %s").format(Lx.ago(it)) }, + ).joinToString(" · ") + card.addView(Lx.caption(context, line, Lx.MUTED), Lx.lp(context, top = 4f)) + card.addView(miiStrip(context, room.players.map { it.mii }, 7), Lx.lp(context, top = 14f)) + val bottom = Lx.hbox(context, Gravity.BOTTOM) + bottom.addView(Lx.display(context, room.players.size.toString(), 18f)) + bottom.addView(Lx.label(context, "/ 12 racers"), Lx.lp(context, -2f, -2f, start = 5f, bottom = 2f)) + bottom.addView(Lx.spring(context)) + room.averageVr?.let { + bottom.addView(Lx.display(context, Lx.number(it), 18f, Lx.AMBER)) + bottom.addView(Lx.label(context, "avg VR"), Lx.lp(context, -2f, -2f, start = 5f, bottom = 2f)) + } + card.addView(bottom, Lx.lp(context, top = 14f)) + card.setOnClickListener { host.open(RoomDetailPage(host, room)) } + } + } + + private inner class PlayerAdapter : RecyclerView.Adapter() { + var items: List> = emptyList() + + override fun getItemCount() = items.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = object : RecyclerView.ViewHolder(PlayerRow(context)) {} + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val (room, player) = items[position] + val row = holder.itemView as PlayerRow + row.bind(player.mii, player.displayName, listOf(player.friendCode, room.label).filter { it.isNotBlank() }.joinToString(" · ")) + row.setValue(player.vr?.let { T("%s VR").format(Lx.number(it)) }, Lx.AMBER) + row.setOnClickListener { host.open(RoomDetailPage(host, room)) } + } + } +} + +/** One room's players, with who's hosting and everyone's rating. */ +internal class RoomDetailPage(host: ModePickerActivity, private var room: RetroWfc.Room) : Page(host) { + override val title: String get() = room.race?.trackName?.takeIf { it.isNotBlank() } ?: room.label + override val subtitle: String + get() = listOfNotNull(room.label, T("%s players").format(room.players.size), room.averageVr?.let { T("avg %s VR").format(Lx.number(it)) }, if (closed) T("closed") else null) + .joinToString(" · ") + + private val handler = Handler(Looper.getMainLooper()) + private val poll = Runnable { fetch() } + private var closed = false + private val adapter = Adapter() + + override fun actions(): List = listOf(Lx.iconButton(context, Icon.REFRESH, "Refresh", Lx.MUTED, android.graphics.Color.TRANSPARENT, 44f) { fetch() }) + + override fun build(): View { + val list = RecyclerView(context) + list.layoutManager = LinearLayoutManager(context) + list.adapter = adapter + list.clipToPadding = false + list.setPadding(gutter, dp(4f), gutter, dp(96f)) + return list + } + + override fun onShow() = schedule() + + override fun onHide() = handler.removeCallbacks(poll) + + override fun onClose() = handler.removeCallbacks(poll) + + override fun onDataChanged(what: Data) { + if (what != Data.ROOMS) return + val status = RetroWfc.lastRooms ?: return + // A room id can stand for several rooms after a split; pick the one sharing the most players. + val mine = room.players.map { it.pid }.toSet() + val match = status.rooms.filter { it.id == room.id }.maxByOrNull { r -> r.players.count { it.pid in mine } } + if (match == null || match.players.isEmpty()) { + closed = true + } else { + closed = false + room = match + } + adapter.notifyDataSetChanged() + refreshHeader() + } + + private fun schedule() { + handler.removeCallbacks(poll) + handler.postDelayed(poll, POLL_MS) + } + + private fun fetch() { + handler.removeCallbacks(poll) + host.work({ RetroWfc.fetchRooms() }) { result -> + if (result.isSuccess) host.broadcast(Data.ROOMS) else host.toast(T("Couldn't refresh: %s").format(Http.describe(result.exceptionOrNull()!!)), Lx.Tone.DANGER) + if (host.isShowing(this)) schedule() + } + } + + private inner class Adapter : RecyclerView.Adapter() { + override fun getItemCount() = room.players.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = object : RecyclerView.ViewHolder(PlayerRow(context)) {} + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val player = room.players.sortedByDescending { it.vr ?: 0 }[position] + val row = holder.itemView as PlayerRow + row.bind(player.mii, player.displayName, player.friendCode.ifBlank { T("No friend code") }) + row.badges.removeAllViews() + if (player.isOpenHost) row.badges.addView(Lx.badge(context, "Open host", Lx.CYAN)) + val values = listOfNotNull(player.vr?.let { T("%s VR").format(Lx.number(it)) }, player.br?.let { T("%s BR").format(Lx.number(it)) }) + row.setValue(values.firstOrNull(), Lx.AMBER, values.getOrNull(1)) + row.setOnClickListener { PlayerActions.show(host, player.displayName, player.friendCode, player.mii, player.vr, player.br) } + } + } +} + +/** A Mii, a name and a line under it, with an optional value on the right. Used by every list of people. */ +internal class PlayerRow(context: Context) : LinearLayout(context) { + val mii = ImageView(context) + private val name = Lx.text(context, "", 15f, Lx.TEXT, Lx.MEDIUM, 1) + private val detail = Lx.caption(context, "", Lx.MUTED, 1) + val badges = Lx.hbox(context) + // A rating is never cut short: the name beside it gives way instead. + private val value = Lx.display(context, "", 16f, Lx.AMBER).apply { ellipsize = null } + private val value2 = Lx.caption(context, "", Lx.MUTED, 1) + val lead = Lx.hbox(context) + + init { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + background = Lx.pressable(context, Lx.SURFACE, 8f) + setPadding(Lx.dp(context, 10f), Lx.dp(context, 8f), Lx.dp(context, 16f), Lx.dp(context, 8f)) + layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = Lx.dp(context, 6f) } + addView(lead) + mii.background = Lx.rounded(context, Lx.SURFACE_HI, 6f) + addView(mii, Lx.lp(context, 46f, 46f)) + val column = Lx.vbox(context) + val top = Lx.hbox(context) + top.addView(name, Lx.lp(context, -2f, -2f, end = 8f)) + top.addView(badges) + column.addView(top) + column.addView(detail, Lx.lp(context, top = 3f)) + addView(column, Lx.lp(context, 0f, -2f, 1f, start = 12f, end = 8f)) + val right = Lx.vbox(context) + right.gravity = Gravity.END + value.gravity = Gravity.END + value2.gravity = Gravity.END + right.addView(value) + right.addView(value2, Lx.lp(context, -2f, -2f, top = 2f)) + addView(right) + } + + fun bind(m: Mii?, title: String, line: String) { + MiiImages.bind(mii, m) + name.text = title + detail.text = line + } + + fun setValue(main: String?, color: Int, second: String? = null) { + value.text = main ?: "" + value.setTextColor(color) + value2.text = second ?: "" + value2.visibility = if (second.isNullOrEmpty()) View.GONE else View.VISIBLE + } +} + +/** Up to [max] Mii faces overlapping in a row, with "+N" for the rest. */ +internal fun miiStrip(context: Context, miis: List, max: Int): View { + val row = Lx.hbox(context) + val size = Lx.dp(context, 32f) + miis.take(max).forEachIndexed { i, mii -> + val view = ImageView(context) + view.background = Lx.rounded(context, Lx.SURFACE_HI, 16f, Lx.SURFACE, 2f) + MiiImages.bind(view, mii) + row.addView(view, LinearLayout.LayoutParams(size, size).apply { if (i > 0) marginStart = -Lx.dp(context, 8f) }) + } + if (miis.size > max) { + row.addView(Lx.display(context, "+${miis.size - max}", 14f, Lx.MUTED), Lx.lp(context, -2f, -2f, start = 8f)) + } + return row +} + +/** What can be done with another player from anywhere in the launcher. */ +internal object PlayerActions { + fun show(host: ModePickerActivity, name: String, friendCode: String, mii: Mii?, vr: Int?, br: Int?) { + val code = FriendCode.normalize(friendCode) + val sheet = DriftSheet(host, name, code ?: T("No friend code")) + if (code != null) { + sheet.action("Copy friend code", code) { + sheet.dismiss() + copy(host, code) + } + sheet.action("Add as a friend", "Puts them on a license's friend list") { + sheet.dismiss() + addFriend(host, code, mii, vr, br) + } + sheet.action("Profile and VR history", "From the Retro WFC leaderboard") { + sheet.dismiss() + host.open(PlayerPage(host, code, name, mii)) + } + } else { + sheet.note("This player has no friend code to show.") + } + sheet.show() + } + + fun copy(host: ModePickerActivity, text: String) { + (host.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager)?.setPrimaryClip(ClipData.newPlainText("Friend code", text)) + host.toast(T("Friend code copied."), Lx.Tone.PRIMARY) + } + + /** Adds [code] to one of the player's licenses, asking which when there's more than one. */ + fun addFriend(host: ModePickerActivity, code: String, mii: Mii?, vr: Int?, br: Int?) { + if (mii == null) { + host.toast(T("Retro WFC didn't send this player's Mii, so they can't be added from here."), Lx.Tone.DANGER) + return + } + host.work({ + SaveData.Game.values().sortedBy { if (it == SaveData.Game.RetroRewind) 0 else 1 } + .flatMap { game -> SaveFile.load(host, game)?.licenses?.filter { it.isOnline }?.map { game to it }.orEmpty() } + }) { result -> + val licenses = result.getOrNull().orEmpty() + when { + licenses.isEmpty() -> host.toast(T("There's no license with a friend code yet - play online once first."), Lx.Tone.DANGER) + licenses.size == 1 -> confirmAdd(host, licenses[0].first, licenses[0].second, code, mii, vr, br) + else -> { + val sheet = DriftSheet(host, T("Add to which license?")) + for ((game, license) in licenses) { + sheet.action(license.displayName, T("%s · %s friends").format(game.label, license.friends.size)) { + sheet.dismiss() + confirmAdd(host, game, license, code, mii, vr, br) + } + } + sheet.show() + } + } + } + } + + private fun confirmAdd(host: ModePickerActivity, game: SaveData.Game, license: SaveFile.License, code: String, mii: Mii, vr: Int?, br: Int?) { + host.guardGameRunning { + host.work({ SaveFile.addFriend(host, game, license.index, code, mii, vr, br) }) { result -> + result.fold( + onSuccess = { + host.toast(T("Added %s to %s. They show as pending until they add you back.").format(mii.displayName, license.displayName), Lx.Tone.PRIMARY) + host.broadcast(Page.Data.SAVES) + }, + onFailure = { host.toast(T("Couldn't add them: %s").format(it.message ?: "unknown error"), Lx.Tone.DANGER) }, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/launcher/SettingsPage.kt b/android/app/src/main/kotlin/com/driftdroid/android/launcher/SettingsPage.kt new file mode 100644 index 0000000..f87ac55 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/launcher/SettingsPage.kt @@ -0,0 +1,117 @@ +package com.driftdroid.android.launcher + +import android.content.Intent +import android.net.Uri +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import android.widget.ScrollView +import com.driftdroid.android.GraphicsSettings +import com.driftdroid.android.IconSettings +import com.driftdroid.android.LanguageSettings +import com.driftdroid.android.LauncherOrientation +import com.driftdroid.android.ModePickerActivity +import com.driftdroid.android.PrivateServerSettings +import com.driftdroid.android.R +import com.driftdroid.android.SaveData +import com.driftdroid.android.T +import com.driftdroid.android.mii.MiiImages +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.Switch + +/** Settings, in groups: the game, this launcher, and where things come from. */ +internal class SettingsPage(host: ModePickerActivity) : Page(host) { + override val title: String get() = T("Settings") + override val subtitle: String get() = "${host.getString(R.string.app_name)} ${host.appVersionName()}" + + override fun build(): View { + val game = group("Game") { + row(Icon.TUNE, "Graphics", "Renderer, vertical mode and GPU driver") { GraphicsSettings.show(host) } + row(Icon.TRANSLATE, "Language", "For these screens and the game's menus") { LanguageSettings.show(host) } + row(Icon.SAVE, "Save data", "Import or export your licenses, unlocks and ghosts") { SaveData.showDialog(host) } + row(Icon.FOLDER, "Import game pack", "Game code made by DriftDroid Builder on a PC") { host.importGamePack() } + row(Icon.SERVER, "Experimental server", "Only for people who run their own server") { PrivateServerSettings.show(host) } + } + val launcher = group("Launcher") { + row(Icon.SCREEN_ROTATION, "Launcher orientation", orientationDetail()) { LauncherOrientation.show(host) } + val switch = Switch(context) + switch.isOn = MiiImages.onlineEnabled(context) + switch.layoutParams = Lx.switchLp(context) + add( + Lx.settingsRow(context, Icon.FACE, "Mii pictures", "Draw Miis with Nintendo's online Mii renderer. Off: simple offline drawings", Lx.MUTED, switch) { + switch.isOn = !switch.isOn + MiiImages.setOnlineEnabled(context, switch.isOn) + host.broadcast(Data.MIIS) + }, + ) + row(Icon.IMAGE, "App icon", "Put a shortcut with your own picture on the home screen") { IconSettings.show(host) } + row(Icon.BUG, "Export diagnostics", "Logs to attach to a bug report - review before sharing") { host.exportDiagnostics() } + } + val about = group("About") { + row(Icon.OPEN_IN_NEW, "DriftDroid on GitHub", "Source code, bug reports and DriftDroid Builder") { open("https://github.com/dorPXP/driftdroid") } + row(Icon.PUBLIC, "Retro WFC", "The online service behind Rooms and Ranks") { open("https://rwfc.net") } + row(Icon.EXTENSION, "GameBanana", "Where the mods in the Mods browser come from") { open("https://gamebanana.com/games/5896") } + } + val note = + Lx.caption( + context, + T("Online pages use Retro WFC's and GameBanana's public APIs, the same ones the Wheel Wizard tool uses on PC. No Nintendo code or game data is included or downloaded."), + Lx.FAINT, + 5, + ).apply { setLineSpacing(0f, 1.2f) } + + val content: LinearLayout + if (compact) { + content = Lx.vbox(context) + content.addView(game) + content.addView(launcher) + content.addView(about) + content.addView(note, Lx.lp(context, start = 4f, top = 4f, end = 4f)) + } else { + content = Lx.hbox(context, Gravity.TOP) + val left = Lx.vbox(context) + left.addView(game) + left.addView(launcher) + val right = Lx.vbox(context) + right.addView(about) + right.addView(note, Lx.lp(context, start = 4f, top = 4f, end = 4f)) + content.addView(left, Lx.lp(context, 0f, -2f, 1f, end = 10f)) + content.addView(right, Lx.lp(context, 0f, -2f, 1f, start = 10f)) + } + content.setPadding(gutter, dp(4f), gutter, dp(28f)) + val scroll = ScrollView(context) + scroll.addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + return scroll + } + + private fun orientationDetail(): String { + val mode = LauncherOrientation.mode(context) + return if (mode == LauncherOrientation.Mode.AUTO) T("Automatic: portrait on phones, landscape on tablets and handhelds") else T(mode.label) + } + + private fun open(url: String) { + runCatching { host.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } + } + + /** A labelled group: rows on one panel, hairlines between them. */ + private fun group(label: String, fill: Group.() -> Unit): View { + val box = Lx.vbox(context) + box.addView(Lx.section(context, label), Lx.lp(context, bottom = 10f)) + val panel = Lx.panel(context, 0f) + Group(panel).fill() + box.addView(panel) + box.layoutParams = Lx.lp(context, bottom = 22f) + return box + } + + private inner class Group(private val panel: LinearLayout) { + fun add(row: View) { + if (panel.childCount > 0) panel.addView(Lx.divider(context, 54f)) + panel.addView(row) + } + + fun row(icon: Icon, title: String, detail: String, onClick: () -> Unit) = add(Lx.settingsRow(context, icon, title, detail, Lx.MUTED, null, onClick)) + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mii/Mii.kt b/android/app/src/main/kotlin/com/driftdroid/android/mii/Mii.kt new file mode 100644 index 0000000..fe24114 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mii/Mii.kt @@ -0,0 +1,262 @@ +package com.driftdroid.android.mii + +/** + * One Wii Mii: the 74-byte record the Mii Channel keeps in RFL_DB.dat, that rksys.dat embeds for + * friends, that .rcd files hold on their own and that Retro WFC hands out base64-encoded. + * + * The record itself is the state. Every property reads and writes its own bits in [data], so a + * Mii that is opened and saved again keeps every bit nothing here knows about (Nintendo left a + * few unused ones between fields) exactly as it was. Bit layout from WheelWizard's MiiSerializer + * (github.com/TeamWheelWizard/WheelWizard), which matches wiibrew's Mii data documentation. + */ +internal class Mii(val data: ByteArray) { + init { + require(data.size == RECORD_BYTES) { "a Mii is $RECORD_BYTES bytes, not ${data.size}" } + } + + fun copy(): Mii = Mii(data.copyOf()) + + var isGirl: Boolean by flag(Field(0x00, 2, 14, 1)) + var birthMonth: Int by int(Field(0x00, 2, 10, 4), 0, 12) + var birthDay: Int by int(Field(0x00, 2, 5, 5), 0, 31) + var favoriteColor: Int by int(Field(0x00, 2, 1, 4), 0, FAVORITE_COLORS.size - 1) + var isFavorite: Boolean by flag(Field(0x00, 2, 0, 1)) + + var name: String + get() = readName(NAME_OFFSET) + set(value) = writeName(NAME_OFFSET, value) + + var height: Int + get() = data[0x16].toInt() and 0xFF + set(value) { + data[0x16] = value.coerceIn(0, 127).toByte() + } + + var weight: Int + get() = data[0x17].toInt() and 0xFF + set(value) { + data[0x17] = value.coerceIn(0, 127).toByte() + } + + /** The "avatar id" a license points at. Stored unsigned; kept in a Long so it never goes negative. */ + var miiId: Long + get() = readU32(0x18) + set(value) = writeU32(0x18, value) + + /** The "client id" of the console that made this Mii. */ + var systemId: Long + get() = readU32(0x1C) + set(value) = writeU32(0x1C, value) + + var faceShape: Int by int(Field(0x20, 2, 13, 3), 0, 7) + var skinColor: Int by int(Field(0x20, 2, 10, 3), 0, SKIN_COLORS.size - 1) + var facialFeature: Int by int(Field(0x20, 2, 6, 4), 0, 11) + var mingleOff: Boolean by flag(Field(0x20, 2, 2, 1)) + + var hairType: Int by int(Field(0x22, 2, 9, 7), 0, 71) + var hairColor: Int by int(Field(0x22, 2, 6, 3), 0, HAIR_COLORS.size - 1) + var hairFlipped: Boolean by flag(Field(0x22, 2, 5, 1)) + + var browType: Int by int(Field(0x24, 4, 27, 5), 0, 23) + var browRotation: Int by int(Field(0x24, 4, 22, 4), 0, 11) + var browColor: Int by int(Field(0x24, 4, 13, 3), 0, HAIR_COLORS.size - 1) + var browSize: Int by int(Field(0x24, 4, 9, 4), 0, 8) + var browVertical: Int by int(Field(0x24, 4, 4, 5), 3, 18) + var browSpacing: Int by int(Field(0x24, 4, 0, 4), 0, 12) + + var eyeType: Int by int(Field(0x28, 4, 26, 6), 0, 47) + var eyeRotation: Int by int(Field(0x28, 4, 21, 3), 0, 7) + var eyeVertical: Int by int(Field(0x28, 4, 16, 5), 0, 18) + var eyeColor: Int by int(Field(0x28, 4, 13, 3), 0, EYE_COLORS.size - 1) + var eyeSize: Int by int(Field(0x28, 4, 9, 3), 0, 7) + var eyeSpacing: Int by int(Field(0x28, 4, 5, 4), 0, 12) + + var noseType: Int by int(Field(0x2C, 2, 12, 4), 0, 11) + var noseSize: Int by int(Field(0x2C, 2, 8, 4), 0, 8) + var noseVertical: Int by int(Field(0x2C, 2, 3, 5), 0, 18) + + var lipType: Int by int(Field(0x2E, 2, 11, 5), 0, 23) + var lipColor: Int by int(Field(0x2E, 2, 9, 2), 0, LIP_COLORS.size - 1) + var lipSize: Int by int(Field(0x2E, 2, 5, 4), 0, 8) + var lipVertical: Int by int(Field(0x2E, 2, 0, 5), 0, 18) + + var glassesType: Int by int(Field(0x30, 2, 12, 4), 0, 8) + var glassesColor: Int by int(Field(0x30, 2, 9, 3), 0, GLASSES_COLORS.size - 1) + var glassesSize: Int by int(Field(0x30, 2, 5, 3), 0, 7) + var glassesVertical: Int by int(Field(0x30, 2, 0, 5), 0, 20) + + var mustacheType: Int by int(Field(0x32, 2, 14, 2), 0, 3) + var beardType: Int by int(Field(0x32, 2, 12, 2), 0, 3) + var facialHairColor: Int by int(Field(0x32, 2, 9, 3), 0, HAIR_COLORS.size - 1) + var mustacheSize: Int by int(Field(0x32, 2, 5, 4), 0, 8) + var mustacheVertical: Int by int(Field(0x32, 2, 0, 5), 0, 16) + + var moleOn: Boolean by flag(Field(0x34, 2, 15, 1)) + var moleSize: Int by int(Field(0x34, 2, 11, 4), 0, 8) + var moleVertical: Int by int(Field(0x34, 2, 6, 5), 0, 30) + var moleHorizontal: Int by int(Field(0x34, 2, 1, 5), 0, 16) + + var creatorName: String + get() = readName(CREATOR_OFFSET) + set(value) = writeName(CREATOR_OFFSET, value) + + /** Name for display: never blank, so a list row always has something to show. */ + val displayName: String get() = name.ifBlank { "Mii" } + + // --- Bit access --- + + class Field(val offset: Int, val bytes: Int, val shift: Int, val width: Int) { + val mask: Long get() = (1L shl width) - 1 + } + + fun get(field: Field): Int { + val word = readWord(field.offset, field.bytes) + return ((word shr field.shift) and field.mask).toInt() + } + + fun set(field: Field, value: Int) { + val word = readWord(field.offset, field.bytes) + val cleared = word and (field.mask shl field.shift).inv() + writeWord(field.offset, field.bytes, cleared or ((value.toLong() and field.mask) shl field.shift)) + } + + private fun readWord(offset: Int, bytes: Int): Long { + var word = 0L + for (i in 0 until bytes) word = (word shl 8) or (data[offset + i].toLong() and 0xFF) + return word + } + + private fun writeWord(offset: Int, bytes: Int, word: Long) { + for (i in 0 until bytes) data[offset + i] = (word shr (8 * (bytes - 1 - i))).toByte() + } + + private fun readU32(offset: Int): Long = readWord(offset, 4) + + private fun writeU32(offset: Int, value: Long) = writeWord(offset, 4, value and 0xFFFFFFFFL) + + private fun readName(offset: Int): String { + val chars = StringBuilder() + for (i in 0 until NAME_CHARS) { + val c = ((data[offset + i * 2].toInt() and 0xFF) shl 8) or (data[offset + i * 2 + 1].toInt() and 0xFF) + if (c == 0) break + chars.append(c.toChar()) + } + return chars.toString() + } + + private fun writeName(offset: Int, value: String) { + val clipped = value.take(NAME_CHARS) + for (i in 0 until NAME_CHARS) { + val c = if (i < clipped.length) clipped[i].code else 0 + data[offset + i * 2] = (c shr 8).toByte() + data[offset + i * 2 + 1] = c.toByte() + } + } + + private fun flag(field: Field) = + object : kotlin.properties.ReadWriteProperty { + override fun getValue(thisRef: Mii, property: kotlin.reflect.KProperty<*>) = get(field) != 0 + + override fun setValue(thisRef: Mii, property: kotlin.reflect.KProperty<*>, value: Boolean) = + set(field, if (value) 1 else 0) + } + + private fun int(field: Field, min: Int, max: Int) = + object : kotlin.properties.ReadWriteProperty { + override fun getValue(thisRef: Mii, property: kotlin.reflect.KProperty<*>) = get(field) + + override fun setValue(thisRef: Mii, property: kotlin.reflect.KProperty<*>, value: Int) = + set(field, value.coerceIn(min, max)) + } + + companion object { + const val RECORD_BYTES = 74 + const val NAME_CHARS = 10 + private const val NAME_OFFSET = 0x02 + private const val CREATOR_OFFSET = 0x36 + + /** A Mii from raw bytes, or null when they are empty (an unused slot) or not a Mii. */ + fun fromBytes(bytes: ByteArray?): Mii? { + if (bytes == null || bytes.size != RECORD_BYTES) return null + if (bytes.all { it == 0.toByte() } || bytes.all { it == 0xFF.toByte() }) return null + return Mii(bytes.copyOf()) + } + + fun fromBase64(text: String?): Mii? = + if (text.isNullOrBlank()) null else runCatching { fromBytes(java.util.Base64.getDecoder().decode(text.trim())) }.getOrNull() + + /** A plain, centred starting point for a new Mii: every part in a mid-range position. */ + fun blank(): Mii { + val mii = Mii(ByteArray(RECORD_BYTES)) + mii.name = "New Mii" + mii.height = 64 + mii.weight = 64 + mii.faceShape = 5 + mii.hairType = 33 + mii.hairColor = 1 + mii.browType = 6 + mii.browSize = 4 + mii.browVertical = 10 + mii.browSpacing = 2 + mii.browColor = 1 + mii.eyeType = 2 + mii.eyeRotation = 4 + mii.eyeVertical = 12 + mii.eyeSize = 4 + mii.eyeSpacing = 2 + mii.noseType = 1 + mii.noseSize = 4 + mii.noseVertical = 9 + mii.lipType = 23 + mii.lipSize = 4 + mii.lipVertical = 13 + mii.glassesSize = 4 + mii.glassesVertical = 10 + mii.mustacheSize = 4 + mii.mustacheVertical = 10 + mii.moleSize = 4 + mii.moleVertical = 20 + mii.moleHorizontal = 2 + mii.favoriteColor = 5 + return mii + } + + /** + * A fresh avatar id, the way a Wii makes one: a counter of 4-second ticks since 2006-01-01 + * in the low 29 bits, under the 0b100 "normal Mii" prefix. [taken] avoids handing out an id + * already in the database when several are made within one tick. + */ + fun newMiiId(taken: Set, nowMillis: Long = System.currentTimeMillis()): Long { + val epoch2006 = 1_136_073_600_000L + var counter = ((nowMillis - epoch2006) / 4000L).coerceAtLeast(0) + while (true) { + val id = (0b100L shl 29) or (counter and 0x1FFFFFFFL) + if (id !in taken) return id + counter++ + } + } + + // Display colours. Mii palettes are fixed indices; these RGB values are the ones + // WheelWizard's editor uses (MiiColorMappings.cs). + val FAVORITE_COLORS = + intArrayOf( + 0xFFFC2114.toInt(), 0xFFFF771B.toInt(), 0xFFFFED21.toInt(), 0xFF8FF01F.toInt(), + 0xFF008232.toInt(), 0xFF0A50B8.toInt(), 0xFF47BAE1.toInt(), 0xFFFF627E.toInt(), + 0xFF8A2AB0.toInt(), 0xFF573E17.toInt(), 0xFFFFFFFA.toInt(), 0xFF181818.toInt(), + ) + val FAVORITE_COLOR_NAMES = + listOf("Red", "Orange", "Yellow", "Light green", "Green", "Blue", "Light blue", "Pink", "Purple", "Brown", "White", "Black") + val SKIN_COLORS = + intArrayOf(0xFFFFD39D.toInt(), 0xFFFFB963.toInt(), 0xFFDE7B3D.toInt(), 0xFFFFAB80.toInt(), 0xFFC85327.toInt(), 0xFF752E17.toInt()) + val HAIR_COLORS = + intArrayOf( + 0xFF1A1A1A.toInt(), 0xFF562D1B.toInt(), 0xFF782515.toInt(), 0xFF9D4A20.toInt(), + 0xFF988B8C.toInt(), 0xFF684E1B.toInt(), 0xFFAB6A24.toInt(), 0xFFFFB757.toInt(), + ) + val EYE_COLORS = + intArrayOf(0xFF1A1A1A.toInt(), 0xFF6B7280.toInt(), 0xFF96482D.toInt(), 0xFFA59837.toInt(), 0xFF555DC3.toInt(), 0xFF488F64.toInt()) + val LIP_COLORS = intArrayOf(0xFFD8643A.toInt(), 0xFFE0261E.toInt(), 0xFFF0605A.toInt()) + val GLASSES_COLORS = + intArrayOf(0xFF909090.toInt(), 0xFFCA9366.toInt(), 0xFFFF574D.toInt(), 0xFF7B87BD.toInt(), 0xFFFFAF47.toInt(), 0xFFDCC5BE.toInt()) + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiDatabase.kt b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiDatabase.kt new file mode 100644 index 0000000..f2a50de --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiDatabase.kt @@ -0,0 +1,140 @@ +package com.driftdroid.android.mii + +import android.content.Context +import java.io.File +import java.io.IOException + +/** + * The Mii Channel's database, RFL_DB.dat, as the game keeps it in the emulated NAND + * (filesDir/WiiCompiled/NAND/shared2/menu/FaceLib - ApplicationDataDirectory() / "NAND" on Android). + * Not to be confused with RFL_Res.dat, the read-only face resource seeded from the disc. + * + * Layout confirmed against SuperFromND/rfl_mii_extractor and WheelWizard's MiiRepositoryService: + * a fixed 779,968-byte file starting "RNOD", then 100 "My Miis" slots of 74 bytes each from offset + * 4 (an all-zero slot is free), and a CRC-16/CCITT-XMODEM of everything before 0x1F1DE stored + * big-endian at 0x1F1DE. Every write recomputes that CRC, so the result is a genuinely valid + * database rather than one only our runtime would accept, and keeps the previous file as + * RFL_DB.dat.bak. + */ +internal object MiiDatabase { + const val DATABASE_BYTES = 779_968 + const val SLOT_COUNT = 100 + private const val TABLE_OFFSET = 4 + private const val MAGIC = "RNOD" + private const val CRC_OFFSET = 0x1F1DE + + class Slot(val index: Int, val mii: Mii) + + /** One read of the file: its bytes, and the Miis in it with their slot numbers. */ + class Snapshot(val bytes: ByteArray) { + val slots: List = + (0 until SLOT_COUNT).mapNotNull { index -> Mii.fromBytes(record(bytes, index))?.let { Slot(index, it) } } + + fun byMiiId(id: Long): Slot? = slots.firstOrNull { it.mii.miiId == id } + + val freeSlots: Int get() = SLOT_COUNT - slots.size + + /** The console id most Miis here were made with, for new Miis to count as this console's. */ + val systemId: Long? + get() = slots.map { it.mii.systemId }.filter { it != 0L }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key + } + + fun file(context: Context): File = File(context.filesDir, "WiiCompiled/NAND/shared2/menu/FaceLib/RFL_DB.dat") + + fun exists(context: Context): Boolean = file(context).isFile + + /** The current database, or null when there is none yet or it fails validation. */ + fun load(context: Context): Snapshot? { + val file = file(context) + if (!file.isFile) return null + val bytes = runCatching { file.readBytes() }.getOrNull() ?: return null + return if (isValid(bytes)) Snapshot(bytes) else null + } + + fun isValid(bytes: ByteArray): Boolean { + if (bytes.size != DATABASE_BYTES) return false + if (String(bytes, 0, 4, Charsets.US_ASCII) != MAGIC) return false + val stored = ((bytes[CRC_OFFSET].toInt() and 0xFF) shl 8) or (bytes[CRC_OFFSET + 1].toInt() and 0xFF) + return stored == crc16(bytes, 0, CRC_OFFSET) + } + + private fun record(bytes: ByteArray, index: Int): ByteArray { + val offset = TABLE_OFFSET + index * Mii.RECORD_BYTES + return bytes.copyOfRange(offset, offset + Mii.RECORD_BYTES) + } + + /** [bytes] with slot [index] set to [mii] (or cleared for null), CRC fixed. A new array. */ + fun withSlot(bytes: ByteArray, index: Int, mii: Mii?): ByteArray { + require(index in 0 until SLOT_COUNT) + val updated = bytes.copyOf() + val offset = TABLE_OFFSET + index * Mii.RECORD_BYTES + if (mii == null) { + java.util.Arrays.fill(updated, offset, offset + Mii.RECORD_BYTES, 0) + } else { + System.arraycopy(mii.data, 0, updated, offset, Mii.RECORD_BYTES) + } + fixCrc(updated) + return updated + } + + fun firstFreeSlot(bytes: ByteArray): Int = + (0 until SLOT_COUNT).firstOrNull { index -> + val offset = TABLE_OFFSET + index * Mii.RECORD_BYTES + (offset until offset + Mii.RECORD_BYTES).all { bytes[it] == 0.toByte() } + } ?: -1 + + /** Writes [bytes] as the new database (validated first), keeping the old one as a backup. */ + fun save(context: Context, bytes: ByteArray) { + if (!isValid(bytes)) throw IOException("the Mii data failed its own check, so nothing was written") + val dest = file(context) + val dir = dest.parentFile ?: throw IOException("no Mii folder") + dir.mkdirs() + if (dest.isFile) dest.copyTo(File(dir, "RFL_DB.dat.bak"), overwrite = true) + val temporary = File(dir, "RFL_DB.dat.saving") + temporary.writeBytes(bytes) + if (!temporary.renameTo(dest)) { + temporary.delete() + throw IOException("couldn't replace the Mii file") + } + } + + /** Adds [mii] into the first free slot of the current database. Returns the slot number. */ + fun add(context: Context, mii: Mii): Int { + val snapshot = load(context) ?: throw IOException("there's no Mii file yet - start Mario Kart Wii once first") + val slot = firstFreeSlot(snapshot.bytes) + if (slot < 0) throw IOException("all 100 Mii slots are in use - delete one first") + save(context, withSlot(snapshot.bytes, slot, mii)) + return slot + } + + /** + * Prepares a Mii that came from somewhere else (a file, a friend, Retro WFC) for this console: + * a fresh avatar id so it can't clash with one already here, and this console's id so the Mii + * Channel treats it as an editable Mii rather than a foreign one. + */ + fun adopt(snapshot: Snapshot, mii: Mii): Mii { + val copy = mii.copy() + copy.miiId = Mii.newMiiId(snapshot.slots.map { it.mii.miiId }.toSet()) + snapshot.systemId?.let { copy.systemId = it } + return copy + } + + fun fixCrc(bytes: ByteArray) { + val crc = crc16(bytes, 0, CRC_OFFSET) + bytes[CRC_OFFSET] = (crc shr 8).toByte() + bytes[CRC_OFFSET + 1] = crc.toByte() + } + + /** CRC-16/CCITT-XMODEM: polynomial 0x1021, initial 0, no reflection. */ + fun crc16(data: ByteArray, start: Int, length: Int): Int { + var crc = 0 + for (index in start until start + length) { + crc = crc xor ((data[index].toInt() and 0xFF) shl 8) + repeat(8) { + crc = if ((crc and 0x8000) != 0) (crc shl 1) xor 0x1021 else crc shl 1 + crc = crc and 0xFFFF + } + } + return crc + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiImages.kt b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiImages.kt new file mode 100644 index 0000000..49d583a --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiImages.kt @@ -0,0 +1,125 @@ +package com.driftdroid.android.mii + +import android.content.Context +import android.graphics.Canvas +import android.graphics.ColorFilter +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.RectF +import android.graphics.drawable.Drawable +import android.widget.ImageView +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages + +/** + * A Mii's face in an ImageView: Nintendo's renderer when it's allowed and reachable, and a simple + * drawing of the Mii's colours ([MiiAvatarDrawable]) while it loads, offline, or when the player + * has turned the online pictures off in Settings. + */ +internal object MiiImages { + private const val PREFS = "launcher" + private const val KEY_ONLINE = "mii_pictures_online" + + fun onlineEnabled(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_ONLINE, true) + + fun setOnlineEnabled(context: Context, enabled: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_ONLINE, enabled).apply() + } + + fun bind(view: ImageView, mii: Mii?, size: MiiStudio.Size = MiiStudio.Size.SMALL) { + view.scaleType = ImageView.ScaleType.FIT_CENTER + val fallback = MiiAvatarDrawable(mii) + if (mii == null || !onlineEnabled(view.context)) { + RemoteImages.clear(view) + view.setImageDrawable(fallback) + return + } + RemoteImages.bind(view, MiiStudio.imageUrl(mii, size), size.px, fallback) + } +} + +/** + * An offline stand-in for a Mii's picture, drawn from its own data: skin tone, hair colour, + * eye colour, glasses and facial hair on a disc of its favourite colour. Deliberately simple - it + * only has to tell Miis apart until the real picture arrives. + */ +internal class MiiAvatarDrawable(mii: Mii?) : Drawable() { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + private val favorite = mii?.let { Mii.FAVORITE_COLORS[it.favoriteColor.coerceIn(0, Mii.FAVORITE_COLORS.size - 1)] } ?: Lx.FAINT + private val skin = mii?.let { Mii.SKIN_COLORS[it.skinColor.coerceIn(0, Mii.SKIN_COLORS.size - 1)] } ?: Lx.SURFACE_HI + private val hair = mii?.let { Mii.HAIR_COLORS[it.hairColor.coerceIn(0, Mii.HAIR_COLORS.size - 1)] } ?: Lx.LINE + private val eyes = mii?.let { Mii.EYE_COLORS[it.eyeColor.coerceIn(0, Mii.EYE_COLORS.size - 1)] } ?: Lx.FAINT + private val glasses = mii?.let { if (it.glassesType > 0) Mii.GLASSES_COLORS[it.glassesColor.coerceIn(0, Mii.GLASSES_COLORS.size - 1)] else 0 } ?: 0 + private val facialHair = mii?.let { if (it.mustacheType > 0 || it.beardType > 0) Mii.HAIR_COLORS[it.facialHairColor.coerceIn(0, 7)] else 0 } ?: 0 + private val wide = mii?.let { 0.30f + it.faceShape * 0.006f } ?: 0.3f + private val blank = mii == null + private val oval = RectF() + + override fun draw(canvas: Canvas) { + val b = bounds + val size = minOf(b.width(), b.height()).toFloat() + val cx = b.exactCenterX() + val cy = b.exactCenterY() + paint.style = Paint.Style.FILL + paint.color = Lx.alpha(favorite, 0.28f) + canvas.drawCircle(cx, cy, size / 2f, paint) + if (blank) { + paint.color = Lx.alpha(Lx.TEXT, 0.25f) + canvas.drawCircle(cx, cy - size * 0.08f, size * 0.16f, paint) + oval.set(cx - size * 0.27f, cy + size * 0.12f, cx + size * 0.27f, cy + size * 0.5f) + canvas.drawOval(oval, paint) + return + } + // Hair behind the face. + paint.color = hair + oval.set(cx - size * (wide + 0.04f), cy - size * 0.36f, cx + size * (wide + 0.04f), cy + size * 0.18f) + canvas.drawOval(oval, paint) + // Face. + paint.color = skin + oval.set(cx - size * wide, cy - size * 0.27f, cx + size * wide, cy + size * 0.36f) + canvas.drawOval(oval, paint) + // Fringe. + paint.color = hair + oval.set(cx - size * (wide + 0.02f), cy - size * 0.37f, cx + size * (wide + 0.02f), cy - size * 0.06f) + canvas.drawArc(oval, 180f, 180f, true, paint) + // Eyes. + paint.color = eyes + val eyeY = cy + size * 0.03f + canvas.drawCircle(cx - size * 0.11f, eyeY, size * 0.035f, paint) + canvas.drawCircle(cx + size * 0.11f, eyeY, size * 0.035f, paint) + if (glasses != 0) { + paint.style = Paint.Style.STROKE + paint.strokeWidth = size * 0.025f + paint.color = glasses + canvas.drawCircle(cx - size * 0.11f, eyeY, size * 0.075f, paint) + canvas.drawCircle(cx + size * 0.11f, eyeY, size * 0.075f, paint) + paint.style = Paint.Style.FILL + } + // Mouth, or facial hair. + if (facialHair != 0) { + paint.color = facialHair + oval.set(cx - size * 0.12f, cy + size * 0.14f, cx + size * 0.12f, cy + size * 0.22f) + canvas.drawOval(oval, paint) + } else { + paint.style = Paint.Style.STROKE + paint.strokeWidth = size * 0.022f + paint.strokeCap = Paint.Cap.ROUND + paint.color = 0xFF9C3B2B.toInt() + oval.set(cx - size * 0.08f, cy + size * 0.1f, cx + size * 0.08f, cy + size * 0.2f) + canvas.drawArc(oval, 20f, 140f, false, paint) + paint.style = Paint.Style.FILL + } + } + + override fun setAlpha(alpha: Int) { + paint.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + paint.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiPreviews.kt b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiPreviews.kt new file mode 100644 index 0000000..864482c --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiPreviews.kt @@ -0,0 +1,236 @@ +package com.driftdroid.android.mii + +import android.content.Context +import android.graphics.Canvas +import android.graphics.ColorFilter +import android.graphics.DashPathEffect +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.RectF +import android.graphics.drawable.Drawable +import android.view.Gravity +import android.view.View +import android.widget.FrameLayout +import android.widget.ImageView +import com.driftdroid.android.ui.Icon +import com.driftdroid.android.ui.IconDrawable +import com.driftdroid.android.ui.Lx +import com.driftdroid.android.ui.RemoteImages +import kotlin.math.max + +/** + * Where a Mii part sits in the renderer's face picture, and how far to zoom in on it, so a picker + * tile shows the eyes as eyes rather than a whole head with a dot in it. Fractions of the picture. + */ +internal class PartFocus(val x: Float, val y: Float, val zoom: Float) { + companion object { + val WHOLE = PartFocus(0.5f, 0.5f, 1f) + } +} + +/** An ImageView that crops its picture around a [PartFocus] instead of fitting it whole. */ +internal class FocusImageView(context: Context) : ImageView(context) { + var focus: PartFocus = PartFocus.WHOLE + set(value) { + field = value + updateMatrix() + } + private val crop = Matrix() + + override fun setImageDrawable(drawable: Drawable?) { + super.setImageDrawable(drawable) + updateMatrix() + } + + override fun setFrame(l: Int, t: Int, r: Int, b: Int): Boolean { + val changed = super.setFrame(l, t, r, b) + updateMatrix() + return changed + } + + private fun updateMatrix() { + val d = drawable + val dw = d?.intrinsicWidth ?: -1 + val dh = d?.intrinsicHeight ?: -1 + if (d == null || dw <= 0 || dh <= 0 || width == 0 || height == 0) { + // A drawn placeholder without a size of its own just fills the tile. + if (scaleType != ScaleType.FIT_XY) scaleType = ScaleType.FIT_XY + return + } + if (scaleType != ScaleType.MATRIX) scaleType = ScaleType.MATRIX + val scale = max(width.toFloat() / dw, height.toFloat() / dh) * focus.zoom + val tx = (width / 2f - focus.x * dw * scale).coerceIn(width - dw * scale, 0f) + val ty = (height / 2f - focus.y * dh * scale).coerceIn(height - dh * scale, 0f) + crop.setScale(scale, scale) + crop.postTranslate(tx, ty) + imageMatrix = crop + } +} + +/** + * One choice in a Mii part picker: the Mii as it would look with that part, zoomed onto the part, + * outlined green when it's the current one. Offline (or with Mii pictures turned off) it falls + * back to the part's number. + */ +internal class PartTile(context: Context, number: String, caption: String? = null) : FrameLayout(context) { + private val image = FocusImageView(context) + private val placeholder = NumberDrawable(number) + private val check = ImageView(context) + + init { + background = Lx.pressable(context, Lx.SURFACE_HI, 8f) + Lx.clipRounded(this, 8f) + addView(image, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + if (caption != null) { + // "None" says so in words: a face without glasses doesn't explain itself. + val label = Lx.label(context, caption, Lx.TEXT, 10f) + label.gravity = Gravity.CENTER + label.setPadding(0, Lx.dp(context, 3f), 0, Lx.dp(context, 3f)) + label.setBackgroundColor(Lx.alpha(Lx.BG, 0.72f)) + addView(label, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)) + } + check.setImageDrawable(IconDrawable(Icon.CHECK, Lx.ACCENT_TEXT)) + val p = Lx.dp(context, 2f) + check.setPadding(p, p, p, p) + check.background = Lx.rounded(context, Lx.ACCENT, 4f) + check.visibility = View.GONE + addView(check, LayoutParams(Lx.dp(context, 18f), Lx.dp(context, 18f), Gravity.TOP or Gravity.END).apply { + setMargins(0, Lx.dp(context, 4f), Lx.dp(context, 4f), 0) + }) + contentDescription = number + } + + fun setPicked(picked: Boolean) { + foreground = if (picked) Lx.rounded(context, 0, 8f, Lx.ACCENT, 2.5f) else null + check.visibility = if (picked) View.VISIBLE else View.GONE + isSelected = picked + } + + /** Shows [mii] cropped to [focus]; [online] false shows the number only. */ + fun show(mii: Mii, focus: PartFocus, online: Boolean) { + image.focus = focus + if (!online) { + RemoteImages.clear(image) + image.setImageDrawable(placeholder) + return + } + // Ask for enough pixels that the zoomed crop is still sharp. + val size = if (focus.zoom > 1.4f) MiiStudio.Size.XL else MiiStudio.Size.LARGE + val target = (Lx.dp(context, 80f) * focus.zoom).toInt().coerceAtMost(size.px) + RemoteImages.bind(image, MiiStudio.imageUrl(mii, size), target, placeholder) + } +} + +/** A part's number, drawn quietly in the middle of its tile until (or instead of) its picture. */ +private class NumberDrawable(private val text: String) : Drawable() { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Lx.FAINT + typeface = Lx.DISPLAY + textAlign = Paint.Align.CENTER + } + + override fun draw(canvas: Canvas) { + val b = bounds + paint.textSize = b.height() * 0.3f + canvas.drawText(text, b.exactCenterX(), b.exactCenterY() + paint.textSize * 0.35f, paint) + } + + override fun setAlpha(alpha: Int) { + paint.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + paint.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT +} + +/** + * Height and weight at a glance: the Mii as a simple figure in its favourite-colour shirt, drawn + * over the dashed outline of an average Mii (both 64), so "taller" and "heavier" read against + * something. It follows the sliders instantly and works offline. + */ +internal class BodyFigure(context: Context) : View(context) { + private var heightValue = 64 + private var weightValue = 64 + private var shirt = Lx.ACCENT + private var skin = Mii.SKIN_COLORS[0] + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val ghost = Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + color = Lx.FAINT + strokeWidth = Lx.dp(context, 1.5f).toFloat() + pathEffect = DashPathEffect(floatArrayOf(Lx.dp(context, 4f).toFloat(), Lx.dp(context, 3f).toFloat()), 0f) + } + private val ground = Paint().apply { + color = Lx.LINE + strokeWidth = Lx.dp(context, 1f).toFloat() + } + private val rect = RectF() + + fun set(mii: Mii) { + heightValue = mii.height + weightValue = mii.weight + shirt = Mii.FAVORITE_COLORS[mii.favoriteColor.coerceIn(0, Mii.FAVORITE_COLORS.size - 1)] + skin = Mii.SKIN_COLORS[mii.skinColor.coerceIn(0, Mii.SKIN_COLORS.size - 1)] + contentDescription = "Height $heightValue of 127, weight $weightValue of 127" + invalidate() + } + + override fun onDraw(canvas: Canvas) { + val pad = Lx.dp(context, 10f).toFloat() + val baseline = height - pad + val unit = (height - pad * 2) / 1.34f + canvas.drawLine(pad, baseline, width - pad, baseline, ground) + drawFigure(canvas, width / 2f, baseline, unit, 64, 64, null) + drawFigure(canvas, width / 2f, baseline, unit, heightValue, weightValue, fill) + } + + /** Head, torso, arms and legs, standing on [baseline]; [paint] null draws the dashed outline. */ + private fun drawFigure(canvas: Canvas, cx: Float, baseline: Float, unit: Float, h: Int, w: Int, paint: Paint?) { + val tall = 0.72f + 0.5f * (h / 127f) + val wide = 0.7f + 0.75f * (w / 127f) + val legH = 0.38f * unit * tall + val legW = 0.12f * unit * wide + val gap = 0.03f * unit + val torsoH = 0.42f * unit * tall + val torsoW = 0.36f * unit * wide + val armW = 0.09f * unit * wide + val armH = 0.34f * unit * tall + val head = 0.17f * unit + val torsoTop = baseline - legH - torsoH + val r = 0.06f * unit + + fun part(l: Float, t: Float, rr: Float, b: Float, color: Int, radius: Float) { + rect.set(l, t, rr, b) + if (paint == null) { + canvas.drawRoundRect(rect, radius, radius, ghost) + } else { + paint.color = color + canvas.drawRoundRect(rect, radius, radius, paint) + } + } + // Legs, in the dark trousers every Mii wears. + part(cx - gap / 2 - legW, baseline - legH, cx - gap / 2, baseline, 0xFF3A3F47.toInt(), r) + part(cx + gap / 2, baseline - legH, cx + gap / 2 + legW, baseline, 0xFF3A3F47.toInt(), r) + // Arms either side, hands in skin tone at the ends. + val armTop = torsoTop + 0.04f * unit + part(cx - torsoW / 2 - armW - 0.01f * unit, armTop, cx - torsoW / 2 - 0.01f * unit, armTop + armH, shirt, armW / 2) + part(cx + torsoW / 2 + 0.01f * unit, armTop, cx + torsoW / 2 + armW + 0.01f * unit, armTop + armH, shirt, armW / 2) + if (paint != null) { + paint.color = skin + canvas.drawCircle(cx - torsoW / 2 - armW / 2 - 0.01f * unit, armTop + armH, armW * 0.62f, paint) + canvas.drawCircle(cx + torsoW / 2 + armW / 2 + 0.01f * unit, armTop + armH, armW * 0.62f, paint) + } + part(cx - torsoW / 2, torsoTop, cx + torsoW / 2, baseline - legH + 0.02f * unit, shirt, r * 1.4f) + // Head: the same size whatever the build, as on a real Mii. + val headY = torsoTop - head + 0.02f * unit + if (paint == null) canvas.drawCircle(cx, headY, head, ghost) else { + paint.color = skin + canvas.drawCircle(cx, headY, head, paint) + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiStudio.kt b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiStudio.kt new file mode 100644 index 0000000..5e85dcf --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mii/MiiStudio.kt @@ -0,0 +1,105 @@ +package com.driftdroid.android.mii + +/** + * Pictures of Miis from Nintendo's public Mii renderer (studio.mii.nintendo.com), the same one + * WheelWizard used for its Mii faces before it grew its own 3D renderer. + * + * The renderer takes the Mii in "studio" form: 46 bytes in a different order and with different + * colour numbering from the Wii record, then lightly obfuscated into hex. The mapping is a port of + * WheelWizard's MiiStudioDataSerializer.GenerateStudioDataArray (Wii branch). + */ +internal object MiiStudio { + const val HOST = "studio.mii.nintendo.com" + + enum class Size(val px: Int) { SMALL(128), LARGE(270), XL(512) } + + fun imageUrl(mii: Mii, size: Size = Size.SMALL, body: Boolean = false): String = + "https://$HOST/miis/image.png?data=${encode(mii)}" + + "&type=${if (body) "all_body" else "face"}&expression=normal&width=${size.px}&bgColor=FFFFFF00" + + /** The renderer's `data=` value for [mii]. */ + fun encode(mii: Mii): String { + val studio = studioBytes(mii) + val out = StringBuilder(2 + studio.size * 2).append("00") + var previous = 0 + for (b in studio) { + val value = (7 + ((b.toInt() and 0xFF) xor previous)) and 0xFF + previous = value + out.append(HEX[value shr 4]).append(HEX[value and 0xF]) + } + return out.toString() + } + + private val HEX = "0123456789abcdef".toCharArray() + private val MAKEUP = intArrayOf(0, 1, 6, 9, 0, 0, 0, 0, 0, 10, 0, 0) + private val WRINKLES = intArrayOf(0, 0, 0, 0, 5, 2, 3, 7, 8, 0, 9, 11) + + fun studioBytes(mii: Mii): ByteArray { + val s = IntArray(46) + s[0x16] = if (mii.isGirl) 1 else 0 + s[0x15] = mii.favoriteColor + s[0x1E] = mii.height + s[0x02] = mii.weight + + s[0x13] = mii.faceShape + s[0x11] = mii.skinColor + val feature = mii.facialFeature + s[0x14] = WRINKLES.getOrElse(feature) { 0 } + s[0x12] = MAKEUP.getOrElse(feature) { 0 } + + s[0x1D] = mii.hairType + s[0x1B] = hairColor(mii.hairColor) + s[0x1C] = if (mii.hairFlipped) 1 else 0 + + s[0x0E] = mii.browType + s[0x0C] = mii.browRotation + s[0x0B] = hairColor(mii.browColor) + s[0x0D] = mii.browSize + s[0x0A] = 3 + s[0x10] = mii.browVertical + s[0x0F] = mii.browSpacing + + s[0x07] = mii.eyeType + s[0x05] = mii.eyeRotation + s[0x09] = mii.eyeVertical + s[0x04] = mii.eyeColor + 8 + s[0x06] = mii.eyeSize + s[0x03] = 3 + s[0x08] = mii.eyeSpacing + + s[0x2C] = mii.noseType + s[0x2B] = mii.noseSize + s[0x2D] = mii.noseVertical + + s[0x26] = mii.lipType + s[0x24] = mii.lipColor + 19 + s[0x25] = mii.lipSize + s[0x23] = 3 + s[0x27] = mii.lipVertical + + s[0x29] = mii.mustacheType + s[0x01] = mii.beardType + s[0x00] = hairColor(mii.facialHairColor) + s[0x28] = mii.mustacheSize + s[0x2A] = mii.mustacheVertical + + s[0x19] = mii.glassesType + s[0x17] = + when (val color = mii.glassesColor) { + 0 -> 8 + in 1..5 -> color + 13 + else -> 0 + } + s[0x18] = mii.glassesSize + s[0x1A] = mii.glassesVertical + + s[0x20] = if (mii.moleOn) 1 else 0 + s[0x1F] = mii.moleSize + s[0x22] = mii.moleVertical + s[0x21] = mii.moleHorizontal + return ByteArray(s.size) { s[it].toByte() } + } + + /** Wii hair colour 0 (black) is studio colour 8; the rest keep their number. */ + private fun hairColor(wii: Int): Int = if (wii == 0) 8 else wii +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mods/ArchiveExtractor.kt b/android/app/src/main/kotlin/com/driftdroid/android/mods/ArchiveExtractor.kt new file mode 100644 index 0000000..d5c1e01 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mods/ArchiveExtractor.kt @@ -0,0 +1,147 @@ +package com.driftdroid.android.mods + +import android.os.ParcelFileDescriptor +import me.zhanghai.android.libarchive.Archive +import me.zhanghai.android.libarchive.ArchiveEntry +import me.zhanghai.android.libarchive.ArchiveException +import java.io.File +import java.io.IOException +import java.util.zip.ZipFile + +/** + * Unpacks a mod archive into a folder. Mario Kart Wii mods on GameBanana come as .zip (most), + * .rar (nearly always RAR5) and .7z; zip goes through java.util.zip, and everything else - or a + * zip java.util.zip can't read - through libarchive. + * + * Every entry is checked to land inside [extract]'s destination (no "../" escapes, no absolute + * paths), and the unpacked total is capped so a hostile archive can't fill the phone. + */ +internal object ArchiveExtractor { + enum class Format { ZIP, SEVEN_ZIP, RAR, UNKNOWN } + + private const val MAX_TOTAL_BYTES = 6L shl 30 + private const val MAX_ENTRIES = 50_000 + + fun sniff(file: File): Format { + val head = ByteArray(8) + val n = runCatching { file.inputStream().use { it.read(head) } }.getOrDefault(0) + if (n < 4) return Format.UNKNOWN + fun at(vararg bytes: Int) = bytes.withIndex().all { (i, b) -> i < n && (head[i].toInt() and 0xFF) == b } + return when { + at(0x50, 0x4B, 0x03, 0x04) || at(0x50, 0x4B, 0x05, 0x06) -> Format.ZIP + at(0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> Format.SEVEN_ZIP + at(0x52, 0x61, 0x72, 0x21, 0x1A, 0x07) -> Format.RAR + else -> Format.UNKNOWN + } + } + + /** Unpacks [archive] into [destination] (created if needed). Throws with a readable message. */ + fun extract(archive: File, destination: File, onFile: (Int) -> Unit = {}) { + destination.mkdirs() + when (sniff(archive)) { + Format.ZIP -> + try { + extractZip(archive, destination, onFile) + } catch (e: Exception) { + // Some zips (unusual compression, broken central directories) only libarchive reads. + destination.listFiles()?.forEach { it.deleteRecursively() } + extractWithLibarchive(archive, destination, onFile) + } + Format.SEVEN_ZIP, Format.RAR -> extractWithLibarchive(archive, destination, onFile) + Format.UNKNOWN -> throw IOException("that isn't a .zip, .7z or .rar archive") + } + if (destination.walkTopDown().none { it.isFile }) throw IOException("the archive was empty") + } + + private fun extractZip(archive: File, destination: File, onFile: (Int) -> Unit) { + var total = 0L + var count = 0 + ZipFile(archive).use { zip -> + val entries = zip.entries() + while (entries.hasMoreElements()) { + val entry = entries.nextElement() + val target = safeTarget(destination, entry.name) ?: continue + if (entry.isDirectory) { + target.mkdirs() + continue + } + if (++count > MAX_ENTRIES) throw IOException("the archive has too many files") + target.parentFile?.mkdirs() + zip.getInputStream(entry).use { input -> + target.outputStream().use { output -> + val buffer = ByteArray(1 shl 16) + while (true) { + val n = input.read(buffer) + if (n < 0) break + total += n + if (total > MAX_TOTAL_BYTES) throw IOException("the archive unpacks to more than 6 GB") + output.write(buffer, 0, n) + } + } + } + onFile(count) + } + } + } + + private fun extractWithLibarchive(archive: File, destination: File, onFile: (Int) -> Unit) { + val handle = + try { + Archive.readNew() + } catch (e: Throwable) { + throw IOException("this phone can't open .7z or .rar files (${e.message})") + } + var total = 0L + var count = 0 + try { + Archive.readSupportFilterAll(handle) + Archive.readSupportFormatAll(handle) + Archive.readOpenFileName(handle, archive.absolutePath.toByteArray(), 1L shl 16) + while (true) { + val entry = + try { + Archive.readNextHeader(handle) + } catch (e: ArchiveException) { + if (e.code == Archive.ERRNO_EOF) 0L else throw e + } + if (entry == 0L) break + val name = ArchiveEntry.pathnameUtf8(entry) ?: ArchiveEntry.pathname(entry)?.toString(Charsets.ISO_8859_1) + val target = name?.let { safeTarget(destination, it) } + val type = ArchiveEntry.filetype(entry) + when { + target == null -> Archive.readDataSkip(handle) + type == ArchiveEntry.AE_IFDIR -> target.mkdirs() + type == ArchiveEntry.AE_IFREG -> { + if (ArchiveEntry.isEncrypted(entry)) throw IOException("the archive is password-protected") + if (++count > MAX_ENTRIES) throw IOException("the archive has too many files") + if (ArchiveEntry.sizeIsSet(entry)) { + total += ArchiveEntry.size(entry) + if (total > MAX_TOTAL_BYTES) throw IOException("the archive unpacks to more than 6 GB") + } + target.parentFile?.mkdirs() + ParcelFileDescriptor.open( + target, + ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_TRUNCATE, + ).use { Archive.readDataIntoFd(handle, it.fd) } + onFile(count) + } + // Links, devices and the like have no place in a mod. + else -> Archive.readDataSkip(handle) + } + } + } catch (e: ArchiveException) { + throw IOException(e.message?.takeIf { it.isNotBlank() } ?: "the archive couldn't be read", e) + } finally { + runCatching { Archive.readFree(handle) } + } + } + + /** Where [entryName] goes under [root], or null if it would land outside it. */ + fun safeTarget(root: File, entryName: String): File? { + val clean = entryName.replace('\\', '/').trimStart('/') + if (clean.isEmpty() || clean.split('/').any { it == ".." }) return null + val target = File(root, clean) + val rootPath = root.canonicalPath + File.separator + return if (target.canonicalPath.startsWith(rootPath)) target else null + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mods/GameBanana.kt b/android/app/src/main/kotlin/com/driftdroid/android/mods/GameBanana.kt new file mode 100644 index 0000000..b73fead --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mods/GameBanana.kt @@ -0,0 +1,156 @@ +package com.driftdroid.android.mods + +import com.driftdroid.android.net.Http +import org.json.JSONArray +import org.json.JSONObject +import java.net.URLEncoder + +/** + * GameBanana's public API (apiv12) for Mario Kart Wii (game 5896): the mod browser's listings, + * search and mod pages. The same endpoints WheelWizard's mod browser uses (IGameBananaApi.cs). + */ +internal object GameBanana { + const val GAME_ID = 5896 + private const val API = "https://gamebanana.com/apiv12" + // Downloads redirect to files.gamebanana.com or numbered caches (filecache53.gamebanana.com...). + val HOSTS = setOf("gamebanana.com", "*.gamebanana.com") + const val PAGE_SIZE = 20 + + /** A browser tab. [rootName] is how search results name the same category. */ + class Category(val id: Int?, val label: String, val rootName: String?) + + // Mario Kart Wii's category tree: gamebanana.com/games/cattree/5896 + val CATEGORIES = + listOf( + Category(null, "All", null), + Category(10080, "Skins", "Skins"), + Category(799, "Tracks", "Tracks"), + Category(2083, "UI", "UI"), + Category(4152, "Other", "Other/Misc"), + ) + + class ModSummary( + val id: Int, + val name: String, + val author: String, + val category: String, + val thumbnailUrl: String?, + /** The same first screenshot at 530px wide, for big cards. */ + val previewUrl: String?, + val likes: Int, + val views: Int, + val addedAt: Long, + ) { + val profileUrl: String get() = "https://gamebanana.com/mods/$id" + } + + class ListPage(val mods: List, val total: Int, val complete: Boolean) + + class ModFile(val id: Int, val name: String, val size: Long, val downloadUrl: String, val description: String?) { + val extension: String get() = name.substringAfterLast('.', "").lowercase() + val isArchive: Boolean get() = extension in ARCHIVE_EXTENSIONS + } + + class ModDetails( + val summary: ModSummary, + val html: String, + val version: String?, + val downloads: Int, + val screenshots: List, + val files: List, + val updatedAt: Long?, + ) + + val ARCHIVE_EXTENSIONS = setOf("zip", "7z", "rar") + + // --- Fetching (call off the main thread) --- + + fun list(categoryId: Int?, page: Int): ListPage { + val filter = if (categoryId != null) "&_aFilters%5BGeneric_Category%5D=$categoryId" else "" + val url = "$API/Mod/Index?_aFilters%5BGeneric_Game%5D=$GAME_ID$filter&_nPage=$page&_nPerpage=$PAGE_SIZE" + return parseList(Http.getText(url, HOSTS)) + } + + /** Full-text search. GameBanana ignores the category filter here, so [category] is applied to + * the results instead (WheelWizard does the same). */ + fun search(query: String, page: Int, category: Category?): ListPage { + val q = URLEncoder.encode(query.trim(), "UTF-8") + val url = "$API/Util/Search/Results?_sSearchString=$q&_idGameRow=$GAME_ID&_sModelName=Mod&_nPage=$page" + val result = parseList(Http.getText(url, HOSTS)) + val root = category?.rootName ?: return result + return ListPage(result.mods.filter { it.category.equals(root, ignoreCase = true) }, result.total, result.complete) + } + + fun details(id: Int): ModDetails = parseDetails(JSONObject(Http.getText("$API/Mod/$id/ProfilePage", HOSTS))) + + // --- Parsing (pure, unit-tested) --- + + fun parseList(json: String): ListPage { + val root = JSONObject(json) + val meta = root.optJSONObject("_aMetadata") + val records = root.optJSONArray("_aRecords") ?: JSONArray() + val mods = ArrayList() + for (i in 0 until records.length()) { + val o = records.optJSONObject(i) ?: continue + if (o.str("_sModelName")?.equals("Mod", ignoreCase = true) == false) continue + mods += parseSummary(o) + } + val total = meta?.optInt("_nRecordCount", mods.size) ?: mods.size + val complete = meta?.optBoolean("_bIsComplete", records.length() == 0) ?: true + return ListPage(mods, total, complete || records.length() == 0) + } + + private fun parseSummary(o: JSONObject): ModSummary { + val images = images(o) + return ModSummary( + id = o.optInt("_idRow"), + name = o.str("_sName") ?: "Untitled", + author = o.optJSONObject("_aSubmitter")?.str("_sName") ?: "", + category = (o.optJSONObject("_aRootCategory") ?: o.optJSONObject("_aCategory"))?.str("_sName") ?: "", + thumbnailUrl = images.firstOrNull()?.let { it.url(it.file220 ?: it.file) }, + previewUrl = images.firstOrNull()?.let { it.url(it.file530 ?: it.file) }, + likes = o.optInt("_nLikeCount"), + views = o.optInt("_nViewCount"), + addedAt = o.optLong("_tsDateAdded") * 1000, + ) + } + + fun parseDetails(o: JSONObject): ModDetails { + val files = ArrayList() + val array = o.optJSONArray("_aFiles") ?: JSONArray() + for (i in 0 until array.length()) { + val f = array.optJSONObject(i) ?: continue + val url = f.str("_sDownloadUrl") ?: continue + files += ModFile(f.optInt("_idRow"), f.str("_sFile") ?: "file", f.optLong("_nFilesize"), url, f.str("_sDescription")) + } + val updated = o.optLong("_tsDateUpdated").takeIf { it > 0 } ?: o.optLong("_tsDateModified").takeIf { it > 0 } + return ModDetails( + summary = parseSummary(o), + html = o.str("_sText") ?: "", + version = o.str("_sVersion"), + downloads = o.optInt("_nDownloadCount"), + screenshots = images(o).map { it.url(it.file530 ?: it.file) }, + files = files, + updatedAt = updated?.times(1000), + ) + } + + private class Image(val base: String, val file: String, val file220: String?, val file530: String?) { + fun url(name: String) = "$base/$name" + } + + private fun images(o: JSONObject): List { + val array = o.optJSONObject("_aPreviewMedia")?.optJSONArray("_aImages") ?: return emptyList() + val list = ArrayList() + for (i in 0 until array.length()) { + val image = array.optJSONObject(i) ?: continue + val base = image.str("_sBaseUrl") ?: continue + val file = image.str("_sFile") ?: continue + if (!Http.isAllowed("$base/$file", HOSTS)) continue + list += Image(base, file, image.str("_sFile220"), image.str("_sFile530")) + } + return list + } + + private fun JSONObject.str(key: String): String? = if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mods/ModInstallJob.kt b/android/app/src/main/kotlin/com/driftdroid/android/mods/ModInstallJob.kt new file mode 100644 index 0000000..6cd21e9 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mods/ModInstallJob.kt @@ -0,0 +1,100 @@ +package com.driftdroid.android.mods + +import android.content.Context +import com.driftdroid.android.ModManager +import com.driftdroid.android.net.Http +import java.io.File + +/** + * Downloads one file of a GameBanana mod and installs it with [ModManager.installArchive] - the + * "no moving files around by hand" path. One at a time; the launcher's task bar polls the fields + * below (same pattern as RetroRewindInstallStatus), so a recreated Activity picks a running + * install straight back up. + */ +internal object ModInstallJob { + enum class Stage { IDLE, DOWNLOADING, UNPACKING, DONE, FAILED } + + @Volatile var stage: Stage = Stage.IDLE + private set + @Volatile var title: String = "" + private set + @Volatile var modId: Int = 0 + private set + @Volatile var bytesDone: Long = 0 + private set + @Volatile var bytesTotal: Long = 0 + private set + @Volatile var filesUnpacked: Int = 0 + private set + @Volatile var error: String? = null + private set + + /** Goes up by one every time a job finishes, so pollers can tell a new result from an old one. */ + @Volatile var finishedCount: Int = 0 + private set + + @Volatile private var cancelRequested = false + + val running: Boolean get() = stage == Stage.DOWNLOADING || stage == Stage.UNPACKING + + /** Starts installing [file] of [mod]. False when another install is still running. */ + @Synchronized + fun start(context: Context, mod: GameBanana.ModDetails, file: GameBanana.ModFile): Boolean { + if (running) return false + val app = context.applicationContext + title = mod.summary.name + modId = mod.summary.id + bytesDone = 0 + bytesTotal = file.size + filesUnpacked = 0 + error = null + cancelRequested = false + stage = Stage.DOWNLOADING + Thread({ run(app, mod, file) }, "mod-install").start() + return true + } + + fun cancel() { + cancelRequested = true + } + + private fun run(context: Context, mod: GameBanana.ModDetails, file: GameBanana.ModFile) { + val downloads = File(context.cacheDir, "mod_downloads") + val archive = File(downloads, "${file.id}.${file.extension.ifEmpty { "bin" }}") + try { + // A little over what GameBanana lists, so a slightly re-uploaded file still fits; never + // more than 4 GB. + val limit = if (file.size > 0) (file.size + file.size / 4 + (8L shl 20)).coerceAtMost(4L shl 30) else 4L shl 30 + Http.download(file.downloadUrl, GameBanana.HOSTS, archive, limit, { cancelRequested }) { done, total -> + bytesDone = done + if (total > 0) bytesTotal = total + } + if (cancelRequested) throw Http.CancelledException() + stage = Stage.UNPACKING + val meta = + ModManager.Meta( + source = "gamebanana", + gameBananaId = mod.summary.id, + title = mod.summary.name, + author = mod.summary.author.ifBlank { null }, + version = mod.version, + thumbnailUrl = mod.summary.thumbnailUrl, + fileName = file.name, + installedAt = System.currentTimeMillis(), + ) + ModManager.installArchive(context, archive, meta) { filesUnpacked = it } + finish(Stage.DONE, null) + } catch (e: Throwable) { + finish(Stage.FAILED, Http.describe(e)) + } finally { + archive.delete() + File(archive.path + ".part").delete() + } + } + + private fun finish(result: Stage, message: String?) { + error = message + stage = result + finishedCount++ + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mods/RetroRewindPatches.kt b/android/app/src/main/kotlin/com/driftdroid/android/mods/RetroRewindPatches.kt new file mode 100644 index 0000000..6ee108b --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mods/RetroRewindPatches.kt @@ -0,0 +1,114 @@ +package com.driftdroid.android.mods + +import java.io.File +import java.nio.file.Files + +/** + * Mods for Retro Rewind the way Retro Rewind itself takes them, which is how the Wheel Wizard PC + * tool installs them: every turned-on mod's files, flattened into RetroRewind6/Patches. Retro + * Rewind's XML maps that folder onto the disc as /patches, and its own code (Pulsar, compiled into + * the game here) applies what it finds there - including "loose archive overrides", files named + * like `Name.race.szs` that are merged into the game's archive of that name rather than replacing + * a whole file. GameBanana's Retro Rewind UI mods are built for exactly this and do nothing as a + * plain file swap. + * + * Mirrors Wheel Wizard's ModsLaunchService: the top mod wins a clash of names, and archive + * overrides carry their mod's place in the list as a numeric prefix so Pulsar can settle clashes + * inside an archive. Files are hard-linked, not copied, so the folder costs no space, and only + * files this app placed (listed in a manifest beside the folder) are ever removed from it. + */ +internal object RetroRewindPatches { + private const val MANIFEST = ".driftdroid_patches.txt" + + /** + * Makes [patchesDir] hold exactly the files of [packs] (turned-on mod folders, highest priority + * first). Riivolution-shaped packs are skipped: their XML places their files itself. Returns + * the names now in place. + */ + fun sync(packs: List, patchesDir: File): Set { + val wanted = LinkedHashMap>() // lower-case name -> (name, source) + // Lowest priority first, so a higher mod's file of the same name replaces it. + for (index in packs.indices.reversed()) { + val pack = packs[index] + if (isRiivolutionPack(pack)) continue + pack.walkTopDown() + .onEnter { dir -> dir == pack || !(dir.name.startsWith(".") || dir.name.equals("__MACOSX", ignoreCase = true)) } + .filter { it.isFile && !it.name.startsWith(".") } + .forEach { file -> + val name = if (isArchiveOverride(file.name)) "$index.${stripPriority(file.name)}" else file.name + wanted[name.lowercase()] = name to file + } + } + + patchesDir.mkdirs() + val manifest = File(patchesDir.parentFile, MANIFEST) + val placedBefore = manifest.takeIf { it.isFile }?.readLines()?.filter { it.isNotBlank() }.orEmpty() + for (old in placedBefore) { + if (old.lowercase() !in wanted) File(patchesDir, old).delete() + } + val placed = LinkedHashSet() + for ((name, source) in wanted.values) { + val dest = File(patchesDir, name) + if (!sameFile(source, dest)) { + dest.delete() + link(source, dest) + } + placed += name + } + manifest.writeText(placed.joinToString("\n")) + return placed + } + + /** + * Gives every US-English UI archive in [dir] (`Race_U.szs`) a European-English twin + * (`Race_E.szs`), unless the mod already has one: the app only plays the PAL disc, which + * reads the _E files, and most GameBanana UI mods are made on the US version. Returns how many + * twins were made. + */ + fun addRegionTwins(dir: File): Int { + var made = 0 + dir.walkTopDown() + .filter { it.isFile && US_ENGLISH.matches(it.name) } + .toList() + .forEach { file -> + val twin = File(file.parentFile, file.name.dropLast("_U.szs".length) + "_E.szs") + val existing = file.parentFile?.listFiles()?.any { it.name.equals(twin.name, ignoreCase = true) } == true + if (!existing) { + link(file, twin) + made++ + } + } + return made + } + + /** `Name.race.szs`: a file Pulsar merges into an archive, recognisable by the tag before .szs. */ + fun isArchiveOverride(fileName: String): Boolean { + if (!fileName.endsWith(".szs", ignoreCase = true)) return false + val stem = fileName.dropLast(4) + val tag = stem.lastIndexOf('.') + return tag > 0 && tag + 1 < stem.length + } + + /** "3.Name.race.szs" -> "Name.race.szs", so a re-numbered mod isn't numbered twice. */ + fun stripPriority(fileName: String): String { + val digits = fileName.takeWhile { it.isDigit() }.length + return if (digits > 0 && digits < fileName.length && fileName[digits] == '.') fileName.substring(digits + 1) else fileName + } + + private fun isRiivolutionPack(pack: File): Boolean = + File(pack, "riivolution").listFiles()?.any { it.isFile && it.name.endsWith(".xml", ignoreCase = true) } == true + + private fun sameFile(a: File, b: File): Boolean = + b.exists() && runCatching { Files.isSameFile(a.toPath(), b.toPath()) }.getOrDefault(false) + + /** A hard link when the filesystem allows it (no extra space), a copy otherwise. */ + private fun link(source: File, dest: File) { + try { + Files.createLink(dest.toPath(), source.toPath()) + } catch (_: Exception) { + source.copyTo(dest, overwrite = true) + } + } + + private val US_ENGLISH = Regex("^[^.]+_U\\.szs$", RegexOption.IGNORE_CASE) +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/mods/RiivolutionChoices.kt b/android/app/src/main/kotlin/com/driftdroid/android/mods/RiivolutionChoices.kt new file mode 100644 index 0000000..963e135 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/mods/RiivolutionChoices.kt @@ -0,0 +1,90 @@ +package com.driftdroid.android.mods + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.w3c.dom.Element + +/** + * Riivolution-shaped mods (XML files in a riivolution folder, next to their replacement files) describe what they + * change as options, and Riivolution starts every option on choice 0, "Disabled", unless the XML + * says otherwise - the player turns them on in Riivolution's menu on a Wii, or in Dolphin. The + * game's loader here (runtime/src/hle/storage/riivolution.cpp) has no such menu: it reads the + * remembered choices from riivolution/config/.xml in the mod's folder, the same file Dolphin + * and the Wii keep them in. Without that file an installed pack applies nothing at all. + * + * So each pack gets that file, with every option switched on at its first choice (or at the XML's + * own default when it names one). A file that is already there - choices someone made elsewhere - + * is left alone. + */ +internal object RiivolutionChoices { + /** Only PAL Mario Kart Wii (RMCP01) discs are accepted, so only its config is read. */ + private const val GAME_ID4 = "RMCP" + + fun configFile(root: File): File = File(root, "riivolution/config/$GAME_ID4.xml") + + /** Writes the config for the pack at [root] if it has Riivolution XMLs and no config yet. True when written. */ + fun ensure(root: File): Boolean { + val xmls = + File(root, "riivolution").listFiles { f -> f.isFile && f.name.endsWith(".xml", ignoreCase = true) } + ?.sortedBy { it.name.lowercase() } + .orEmpty() + if (xmls.isEmpty()) return false + val config = configFile(root) + if (config.exists()) return false + val choices = LinkedHashMap() + for (xml in xmls) runCatching { choices.putAll(choicesFor(xml.readText())) } + if (choices.isEmpty()) return false + config.parentFile?.mkdirs() + config.writeText(render(choices)) + return true + } + + /** + * Every option in one Riivolution XML, keyed the way the loader (and Dolphin) looks them up - + * the option's id, or its section's name followed by its own name when it has none - mapped + * to the choice to use: the XML's default if it picks one, else the first choice. + */ + fun choicesFor(xml: String): Map { + val factory = DocumentBuilderFactory.newInstance() + factory.isExpandEntityReferences = false + runCatching { factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) } + val document = factory.newDocumentBuilder().parse(xml.byteInputStream()) + val result = LinkedHashMap() + val sections = document.getElementsByTagName("section") + for (i in 0 until sections.length) { + val section = sections.item(i) as? Element ?: continue + if ((section.parentNode as? Element)?.tagName != "options") continue + val sectionName = section.getAttribute("name") + for (option in section.childElements("option")) { + val choiceCount = option.childElements("choice").size + if (choiceCount == 0) continue + val id = option.getAttribute("id").ifEmpty { sectionName + option.getAttribute("name") } + if (id.isEmpty()) continue + val default = option.getAttribute("default").toIntOrNull() ?: 0 + result[id] = if (default in 1..choiceCount) default else 1 + } + } + return result + } + + fun render(choices: Map): String = + buildString { + append("\n") + append("\n") + for ((id, choice) in choices) append(" \n") + } + + private fun Element.childElements(tag: String): List { + val out = ArrayList() + val nodes = childNodes + for (i in 0 until nodes.length) { + val node = nodes.item(i) + if (node is Element && node.tagName == tag) out += node + } + return out + } + + private fun escape(text: String): String = + text.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">") +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/net/Http.kt b/android/app/src/main/kotlin/com/driftdroid/android/net/Http.kt new file mode 100644 index 0000000..6967049 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/net/Http.kt @@ -0,0 +1,177 @@ +package com.driftdroid.android.net + +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL + +/** + * The launcher's one way onto the internet, for the online pages (Retro WFC rooms and leaderboard, + * GameBanana mods, Mii pictures). + * + * Every request names the hosts it may talk to, and redirects are followed by hand so each hop is + * checked against that list too (HttpURLConnection would follow one anywhere, and silently drops + * HTTPS-to-HTTPS cross-host redirects). HTTPS only, and a response can never deliver more than the + * caller's limit, whatever its headers claim. Same rules as RetroRewindCatalog.openStream. + */ +internal object Http { + @Volatile var userAgent: String = "DriftDroid (Android)" + + class HttpException(val code: Int) : IOException("the server answered HTTP $code") + + class CancelledException : IOException("cancelled") + + private const val MAX_REDIRECTS = 5 + private const val CONNECT_TIMEOUT_MS = 15_000 + private const val READ_TIMEOUT_MS = 30_000 + + /** HTTPS to one of [hosts]; an entry like "*.example.com" allows any subdomain of it (GameBanana + * hands downloads to numbered mirrors such as filecache53.gamebanana.com). */ + fun isAllowed(url: String, hosts: Set): Boolean = + try { + val parsed = URL(url) + val host = parsed.host.lowercase() + parsed.protocol == "https" && + (host in hosts || hosts.any { it.startsWith("*.") && host.endsWith(it.substring(1)) }) + } catch (_: Exception) { + false + } + + /** An open response body. Close it (use {}) to release the connection. */ + class Response internal constructor( + val stream: InputStream, + val contentLength: Long, + private val connection: HttpURLConnection, + ) : java.io.Closeable { + override fun close() { + try { + stream.close() + } finally { + connection.disconnect() + } + } + } + + fun open(url: String, hosts: Set, maxBytes: Long, accept: String? = null): Response { + var current = url + repeat(MAX_REDIRECTS + 1) { + if (!isAllowed(current, hosts)) throw IOException("refusing to connect to ${hostOf(current)}") + val connection = (URL(current).openConnection() as HttpURLConnection).apply { + connectTimeout = CONNECT_TIMEOUT_MS + readTimeout = READ_TIMEOUT_MS + instanceFollowRedirects = false + setRequestProperty("User-Agent", userAgent) + if (accept != null) setRequestProperty("Accept", accept) + } + val code = + try { + connection.responseCode + } catch (e: IOException) { + connection.disconnect() + throw e + } + if (code in 300..399) { + val location = connection.getHeaderField("Location") + connection.disconnect() + current = URL(URL(current), location ?: throw IOException("redirect with no Location")).toString() + return@repeat + } + if (code != HttpURLConnection.HTTP_OK) { + connection.disconnect() + throw HttpException(code) + } + val declared = connection.contentLengthLong + if (declared > maxBytes) { + connection.disconnect() + throw IOException("the response is larger than expected") + } + return Response(Bounded(connection.inputStream, maxBytes), declared, connection) + } + throw IOException("too many redirects") + } + + fun getBytes(url: String, hosts: Set, maxBytes: Long = 8L shl 20, accept: String? = null): ByteArray = + open(url, hosts, maxBytes, accept).use { it.stream.readBytes() } + + fun getText(url: String, hosts: Set, maxBytes: Long = 8L shl 20): String = + getBytes(url, hosts, maxBytes, "application/json").toString(Charsets.UTF_8) + + /** + * Streams [url] into [destination] (through a .part file, so a broken download never looks + * finished). [onProgress] gets (bytes so far, total or -1) a few times a second at most; + * [cancelled] is checked between reads. + */ + fun download( + url: String, + hosts: Set, + destination: File, + maxBytes: Long, + cancelled: () -> Boolean = { false }, + onProgress: (Long, Long) -> Unit = { _, _ -> }, + ) { + destination.parentFile?.mkdirs() + val part = File(destination.path + ".part") + try { + open(url, hosts, maxBytes).use { response -> + part.outputStream().buffered(1 shl 16).use { out -> + val buffer = ByteArray(1 shl 16) + var done = 0L + var lastReport = 0L + while (true) { + if (cancelled()) throw CancelledException() + val n = response.stream.read(buffer) + if (n < 0) break + out.write(buffer, 0, n) + done += n + val now = System.currentTimeMillis() + if (now - lastReport > 200) { + lastReport = now + onProgress(done, response.contentLength) + } + } + onProgress(done, response.contentLength) + if (response.contentLength > 0 && done != response.contentLength) { + throw IOException("the download stopped early") + } + } + } + if (destination.exists()) destination.delete() + if (!part.renameTo(destination)) throw IOException("couldn't store the download") + } catch (e: Exception) { + part.delete() + throw e + } + } + + fun hostOf(url: String): String = runCatching { URL(url).host }.getOrDefault(url) + + /** A short, human reason for a failed request. */ + fun describe(error: Throwable): String = + when (error) { + is HttpException -> error.message ?: "server error" + is java.net.UnknownHostException -> "no internet connection" + is java.net.SocketTimeoutException -> "the server took too long to answer" + is javax.net.ssl.SSLException -> "a secure connection couldn't be made" + is CancelledException -> "cancelled" + else -> error.message ?: "network error" + } + + private class Bounded(private val delegate: InputStream, private val limit: Long) : InputStream() { + private var read = 0L + + private fun count(n: Int): Int { + if (n > 0) { + read += n + if (read > limit) throw IOException("the response is larger than expected") + } + return n + } + + override fun read(): Int = delegate.read().also { if (it >= 0) count(1) } + + override fun read(b: ByteArray, off: Int, len: Int): Int = count(delegate.read(b, off, len)) + + override fun close() = delegate.close() + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/online/RetroWfc.kt b/android/app/src/main/kotlin/com/driftdroid/android/online/RetroWfc.kt new file mode 100644 index 0000000..9251f7b --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/online/RetroWfc.kt @@ -0,0 +1,249 @@ +package com.driftdroid.android.online + +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.net.Http +import org.json.JSONArray +import org.json.JSONObject + +/** + * Retro WFC's public API (rwfc.net), the online service Retro Rewind plays on: who is racing in + * which room right now, and the VR leaderboard. The same endpoints WheelWizard's Rooms and + * Leaderboard pages read (its IRwfcApi.cs). + * + * Read-only. Nothing here talks to the game servers themselves or can join a room; that only + * happens inside the game. + */ +internal object RetroWfc { + const val HOST = "rwfc.net" + private val HOSTS = setOf(HOST) + private const val API = "https://$HOST/api" + + class Player( + val pid: String, + val name: String, + val friendCode: String, + val vr: Int?, + val br: Int?, + val isOpenHost: Boolean, + val miiData: String?, + val connectionMap: List, + ) { + val mii: Mii? by lazy { Mii.fromBase64(miiData) } + val displayName: String get() = name.ifBlank { mii?.displayName ?: "Player" } + } + + class Race(val number: Int, val course: Int, val trackName: String?) + + class Room( + val id: String, + val type: String, + val roomType: String?, + val createdAt: Long?, + val rk: String?, + val players: List, + val averageVr: Int?, + val race: Race?, + val isPublic: Boolean, + val isJoinable: Boolean, + ) { + /** What the room is, for a person: "Retro Tracks", "Private room"... */ + val label: String + get() = roomType?.takeIf { it.isNotBlank() } ?: when { + !isPublic || type.equals("private", ignoreCase = true) -> "Private room" + type.equals("anybody", ignoreCase = true) -> "Worldwide" + else -> type.replaceFirstChar { it.uppercase() } + } + } + + class RoomStatus(val rooms: List, val totalPlayers: Int, val fetchedAt: Long) { + val activeRooms: List get() = rooms.filter { it.players.isNotEmpty() } + } + + class Ranked( + val pid: String, + val name: String, + val friendCode: String, + val vr: Int, + val rank: Int?, + val lastSeen: Long?, + val vr24h: Int, + val vrWeek: Int, + val vrMonth: Int, + val miiData: String?, + val vehiclePreference: String?, + ) { + val mii: Mii? by lazy { Mii.fromBase64(miiData) } + val displayName: String get() = name.ifBlank { mii?.displayName ?: "Player" } + } + + class VrPoint(val time: Long, val totalVr: Int) + + // --- Fetching (call off the main thread) --- + + @Volatile var lastRooms: RoomStatus? = null + private set + + fun fetchRooms(): RoomStatus = + parseRooms(Http.getText("$API/roomstatus", HOSTS), System.currentTimeMillis()).also { lastRooms = it } + + @Volatile private var cachedTop: Pair>? = null + + /** The top [limit] players, kept for 90 seconds (the leaderboard only moves after races). */ + fun fetchTop(limit: Int = 100, force: Boolean = false): List { + val cached = cachedTop + if (!force && cached != null && System.currentTimeMillis() - cached.first < 90_000 && cached.second.size >= limit) { + return cached.second.take(limit) + } + val bounded = limit.coerceIn(1, 200) + val list = parseLeaderboard(Http.getText("$API/leaderboard/top/$bounded", HOSTS)) + cachedTop = System.currentTimeMillis() to list + return list + } + + fun fetchPlayer(friendCode: String): Ranked = + parseRanked(JSONObject(Http.getText("$API/leaderboard/player/${friendCode.trim()}", HOSTS))) + + fun fetchHistory(friendCode: String, days: Int = 7): List = + parseHistory(Http.getText("$API/leaderboard/player/${friendCode.trim()}/history?days=$days", HOSTS)) + + // --- Parsing (pure, unit-tested) --- + + fun parseRooms(json: String, now: Long): RoomStatus { + val root = JSONObject(json) + val rooms = ArrayList() + val array = root.optJSONArray("rooms") ?: JSONArray() + for (i in 0 until array.length()) { + val o = array.optJSONObject(i) ?: continue + if (o.optBoolean("isSuspended") || o.optBoolean("suspend")) continue + val players = ArrayList() + val playerArray = o.optJSONArray("players") ?: JSONArray() + for (j in 0 until playerArray.length()) { + val p = playerArray.optJSONObject(j) ?: continue + if (p.optBoolean("isSuspended")) continue + val mii = p.optJSONObject("mii") + val map = p.optJSONArray("connectionMap") + players += + Player( + pid = p.str("pid") ?: "", + name = p.str("name") ?: mii?.str("name") ?: "", + friendCode = p.str("friendCode") ?: "", + vr = p.int("vr"), + br = p.int("br"), + isOpenHost = p.optBoolean("isOpenHost"), + miiData = mii?.str("data"), + connectionMap = if (map == null) emptyList() else List(map.length()) { map.optString(it) }, + ) + } + val race = o.optJSONObject("race") + val base = + Room( + id = o.str("id") ?: "", + type = o.str("type") ?: "", + roomType = o.str("roomType"), + createdAt = parseTime(o.str("created")), + rk = o.str("rk"), + players = players, + averageVr = o.int("averageVR"), + race = race?.let { Race(it.optInt("num"), it.optInt("course"), it.str("trackName")) }, + isPublic = o.optBoolean("isPublic", true), + isJoinable = o.optBoolean("isJoinable", false), + ) + rooms.addAll(splitMergedRoom(base)) + } + rooms.sortWith(compareByDescending { it.players.size }.thenBy { it.id }) + val total = root.int("totalPlayers") ?: rooms.sumOf { it.players.size } + return RoomStatus(rooms, total, now) + } + + /** + * The server sometimes reports two groups of players that can't see each other as one room. + * Their connection maps give it away: split the room into the groups that are connected both + * ways. A port of WheelWizard's LiveRoomsService.SplitMergedRooms (from kevinvg207's rr-rooms). + */ + fun splitMergedRoom(room: Room): List { + val n = room.players.size + if (n < 2) return listOf(room) + val adjacency = Array(n) { HashSet() } + var anyEdge = false + for (i in 0 until n) { + val map = room.players[i].connectionMap + if (map.isEmpty()) continue + val includesSelf = map.size == n + if (!includesSelf && map.size != n - 1) continue + for (j in map.indices) { + if (map[j].firstOrNull()?.let { it == '0' } != false) continue + if (includesSelf && j == i) continue + val other = if (includesSelf) j else if (j >= i) j + 1 else j + if (other in 0 until n) { + adjacency[i].add(other) + anyEdge = true + } + } + } + if (!anyEdge) return listOf(room) + val seen = BooleanArray(n) + val groups = ArrayList>() + for (start in 0 until n) { + if (seen[start]) continue + val group = ArrayList() + val stack = ArrayDeque().apply { addLast(start) } + while (stack.isNotEmpty()) { + val u = stack.removeLast() + if (seen[u]) continue + seen[u] = true + group.add(u) + for (v in adjacency[u]) if (u in adjacency[v] && !seen[v]) stack.addLast(v) + } + groups.add(group.sorted()) + } + if (groups.size <= 1) return listOf(room) + return groups.map { group -> + Room( + room.id, room.type, room.roomType, room.createdAt, room.rk, + group.map { room.players[it] }, null, room.race, room.isPublic, room.isJoinable, + ) + } + } + + fun parseLeaderboard(json: String): List { + val array = JSONArray(json) + return List(array.length()) { parseRanked(array.getJSONObject(it)) } + } + + fun parseRanked(o: JSONObject): Ranked { + val stats = o.optJSONObject("vrStats") + return Ranked( + pid = o.str("pid") ?: "", + name = o.str("name") ?: "", + friendCode = o.str("friendCode") ?: "", + vr = o.int("vr") ?: 0, + rank = o.int("rank") ?: o.int("activeRank"), + lastSeen = parseTime(o.str("lastSeen")), + vr24h = stats?.int("last24Hours") ?: 0, + vrWeek = stats?.int("lastWeek") ?: 0, + vrMonth = stats?.int("lastMonth") ?: 0, + miiData = o.str("miiData"), + vehiclePreference = o.str("vehiclePreference"), + ) + } + + fun parseHistory(json: String): List { + val array = JSONObject(json).optJSONArray("history") ?: return emptyList() + val points = ArrayList(array.length()) + for (i in 0 until array.length()) { + val o = array.optJSONObject(i) ?: continue + val time = parseTime(o.str("date")) ?: continue + points += VrPoint(time, o.int("totalVR") ?: continue) + } + return points.sortedBy { it.time } + } + + /** "2026-09-13T18:56:58.4018284Z" in epoch milliseconds, or null. */ + fun parseTime(text: String?): Long? = + if (text.isNullOrBlank()) null else runCatching { java.time.Instant.parse(text).toEpochMilli() }.getOrNull() + + // org.json returns the text "null" for a JSON null from optString; these treat it as missing. + private fun JSONObject.str(key: String): String? = if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() } + + private fun JSONObject.int(key: String): Int? = if (isNull(key)) null else (opt(key) as? Number)?.toInt() +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/profile/FriendCode.kt b/android/app/src/main/kotlin/com/driftdroid/android/profile/FriendCode.kt new file mode 100644 index 0000000..5c0d02e --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/profile/FriendCode.kt @@ -0,0 +1,49 @@ +package com.driftdroid.android.profile + +import java.security.MessageDigest + +/** + * Mario Kart Wii friend codes. A friend code is a 32-bit profile id with a 7-bit checksum on top: + * the first byte of MD5(profile id little-endian + "JCMR"), shifted right by one. Same math as + * WheelWizard's FriendCode.cs and the game's own DWC library. + */ +internal object FriendCode { + private val GAME_ID_REVERSED = byteArrayOf('J'.code.toByte(), 'C'.code.toByte(), 'M'.code.toByte(), 'R'.code.toByte()) + + /** The friend code number for [profileId], or 0 for profile id 0 (no license). */ + fun fromProfileId(profileId: Long): Long { + val pid = profileId and 0xFFFFFFFFL + if (pid == 0L) return 0 + val input = byteArrayOf(pid.toByte(), (pid shr 8).toByte(), (pid shr 16).toByte(), (pid shr 24).toByte()) + GAME_ID_REVERSED + val checksum = (MessageDigest.getInstance("MD5").digest(input)[0].toInt() and 0xFF) shr 1 + return (checksum.toLong() shl 32) or pid + } + + /** "1234-5678-9012" for [profileId], or "" when there is no license. */ + fun format(profileId: Long): String = formatNumber(fromProfileId(profileId)) + + fun formatNumber(code: Long): String { + if (code <= 0) return "" + val digits = code.toString().padStart(12, '0') + return "${digits.substring(0, 4)}-${digits.substring(4, 8)}-${digits.substring(8, 12)}" + } + + /** + * The profile id behind a typed or listed friend code, or 0 if it isn't 12 digits or its + * checksum doesn't match (a typo, almost always). + */ + fun toProfileId(friendCode: String?): Long { + val digits = friendCode?.filter { it.isDigit() } ?: return 0 + if (digits.length != 12) return 0 + val code = digits.toLongOrNull() ?: return 0 + val pid = code and 0xFFFFFFFFL + if (pid == 0L) return 0 + return if (fromProfileId(pid) == code) pid else 0 + } + + /** The canonical "1234-5678-9012" form of a typed code, or null if it isn't a real one. */ + fun normalize(friendCode: String?): String? { + val pid = toProfileId(friendCode) + return if (pid == 0L) null else format(pid) + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/profile/SaveFile.kt b/android/app/src/main/kotlin/com/driftdroid/android/profile/SaveFile.kt new file mode 100644 index 0000000..76b38fb --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/profile/SaveFile.kt @@ -0,0 +1,324 @@ +package com.driftdroid.android.profile + +import android.content.Context +import com.driftdroid.android.SaveData +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiDatabase +import java.io.File +import java.io.IOException +import java.nio.ByteBuffer +import java.util.zip.CRC32 + +/** + * The licenses inside a Mario Kart Wii save (rksys.dat): each one's Mii, friend code, VR/BR, + * race counts and friend roster, and the few edits the Profile page makes to them (add or remove a + * friend, give a license another Mii). + * + * Offsets from wiki.tockdom.com/wiki/Rksys.dat by way of WheelWizard's GameLicenseService.cs. + * Every write re-validates the file, fixes its CRC-32 (at 0x27FFC, over everything before it), + * keeps the previous save as rksys.dat.bak and swaps the new one in, so a failure can never leave + * a half-written save behind. + */ +internal object SaveFile { + private const val SAVE_BYTES = 0x2BC000 + private const val LICENSE_COUNT = 4 + private const val LICENSE_OFFSET = 0x08 + private const val LICENSE_BYTES = 0x8CC0 + private const val CHECKSUM_OFFSET = 0x27FFC + private const val FRIEND_COUNT = 30 + private const val FRIEND_OFFSET = 0x56D0 + private const val FRIEND_BYTES = 0x1C0 + private const val FRIEND_EXTRA_OFFSET = 0x8B50 + private const val FRIEND_EXTRA_BYTES = 0x0C + private const val FRIEND_ADDED = 0x0001 + private const val FRIEND_KEY = 0x10 + private const val DEFAULT_RATING = 5000 + + class Friend( + val slot: Int, + val profileId: Long, + val friendCode: String, + val mii: Mii?, + val vr: Int, + val br: Int, + val wins: Int, + val losses: Int, + val pending: Boolean, + ) { + val displayName: String get() = mii?.displayName ?: friendCode + } + + class License( + val index: Int, + val name: String, + val miiId: Long, + val profileId: Long, + val friendCode: String, + val vr: Int, + val br: Int, + val races: Long, + val wins: Long, + val friends: List, + /** The license's Mii from the Mii file, when it's still there. */ + val mii: Mii?, + ) { + val displayName: String get() = name.ifBlank { mii?.displayName ?: "License ${index + 1}" } + val isOnline: Boolean get() = profileId != 0L + } + + class Save(val game: SaveData.Game, val licenses: List) + + fun file(context: Context, game: SaveData.Game): File = File(context.filesDir, game.relativePath) + + /** The licenses in [game]'s save, or null when there's no usable save yet. */ + fun load(context: Context, game: SaveData.Game): Save? { + val bytes = runCatching { file(context, game).takeIf { it.isFile }?.readBytes() }.getOrNull() ?: return null + if (SaveData.validate(bytes) != null) return null + val ratings = if (game == SaveData.Game.RetroRewind) RrRatings.load(context) else emptyMap() + return parse(bytes, game, MiiDatabase.load(context), ratings) + } + + /** The licenses in an already-validated save. */ + fun parse(bytes: ByteArray, game: SaveData.Game, miis: MiiDatabase.Snapshot?, ratings: Map>): Save = + Save(game, (0 until LICENSE_COUNT).mapNotNull { parseLicense(bytes, it, game, miis, ratings) }) + + private fun base(index: Int) = LICENSE_OFFSET + index * LICENSE_BYTES + + private fun parseLicense( + bytes: ByteArray, + index: Int, + game: SaveData.Game, + miis: MiiDatabase.Snapshot?, + ratings: Map>, + ): License? { + val base = base(index) + if (String(bytes, base, 4, Charsets.US_ASCII) != "RKPD") return null + val name = utf16(bytes, base + 0x14, 10) + val miiId = u32(bytes, base + 0x28) + if (name.isBlank() && miiId == 0L) return null + val profileId = u32(bytes, base + 0x5C) + var vr = u16(bytes, base + 0xB0) + var br = u16(bytes, base + 0xB2) + // Retro Rewind keeps its real, uncapped rating outside rksys.dat (RRRating.pul) in VR/100. + ratings[profileId]?.let { (ratingVr, ratingBr) -> + vr = Math.round(ratingVr * 100) + br = Math.round(ratingBr * 100) + } + val friends = + (0 until FRIEND_COUNT).mapNotNull { slot -> parseFriend(bytes, base, slot, game) } + return License( + index = index, + name = name, + miiId = miiId, + profileId = profileId, + friendCode = FriendCode.format(profileId), + vr = vr, + br = br, + races = u32(bytes, base + 0xB4), + wins = u32(bytes, base + 0xDC), + friends = friends, + mii = miis?.byMiiId(miiId)?.mii, + ) + } + + private fun parseFriend(bytes: ByteArray, base: Int, slot: Int, game: SaveData.Game): Friend? { + val offset = base + FRIEND_OFFSET + slot * FRIEND_BYTES + val miiBytes = bytes.copyOfRange(offset + 0x1A, offset + 0x1A + Mii.RECORD_BYTES) + if (miiBytes.all { it == 0.toByte() }) return null + val profileId = u32(bytes, offset + 0x04) + val state = u16(bytes, offset + 0x10) and 0x3 + val control = bytes[base + FRIEND_EXTRA_OFFSET + slot * FRIEND_EXTRA_BYTES + 2].toInt() and 0xFF + return Friend( + slot = slot, + profileId = profileId, + friendCode = FriendCode.format(profileId), + mii = Mii.fromBytes(miiBytes), + vr = friendRating(u16(bytes, offset + 0x16), game), + br = friendRating(u16(bytes, offset + 0x18), game), + wins = u16(bytes, offset + 0x14), + losses = u16(bytes, offset + 0x12), + pending = state == FRIEND_ADDED && (control == FRIEND_KEY || control == 0), + ) + } + + /** Retro Rewind stores a friend's rating in hundreds (29,367 VR as 293); 5000 is the default. */ + private fun friendRating(stored: Int, game: SaveData.Game): Int = + if (game != SaveData.Game.RetroRewind || stored == DEFAULT_RATING || stored > 10_000) stored else stored * 100 + + private fun storedFriendRating(points: Int, game: SaveData.Game): Int = + if (game == SaveData.Game.RetroRewind) (points.coerceIn(0, 1_000_000) / 100) else points.coerceIn(0, 9999) + + // --- Edits --- + + /** Adds [friendCode] (with [mii] as its picture) to license [index]'s friend roster. */ + fun addFriend(context: Context, game: SaveData.Game, index: Int, friendCode: String, mii: Mii, vr: Int?, br: Int?) = + edit(context, game) { applyAddFriend(it, game, index, friendCode, mii, vr, br) } + + fun applyAddFriend(bytes: ByteArray, game: SaveData.Game, index: Int, friendCode: String, mii: Mii, vr: Int?, br: Int?) { + run { + val base = base(index) + if (String(bytes, base, 4, Charsets.US_ASCII) != "RKPD") throw IOException("that license is empty") + val profileId = FriendCode.toProfileId(friendCode) + if (profileId == 0L) throw IOException("that isn't a valid friend code") + if (profileId == u32(bytes, base + 0x5C)) throw IOException("that's this license's own friend code") + val slots = 0 until FRIEND_COUNT + if (slots.any { u32(bytes, base + FRIEND_OFFSET + it * FRIEND_BYTES + 0x04) == profileId }) { + throw IOException("they're already on this license's friend list") + } + val slot = + slots.firstOrNull { s -> + val o = base + FRIEND_OFFSET + s * FRIEND_BYTES + u32(bytes, o + 0x04) == 0L && (u16(bytes, o + 0x10) and 0x3) == 0 && + (o + 0x1A until o + 0x1A + Mii.RECORD_BYTES).all { bytes[it] == 0.toByte() } + } ?: throw IOException("the friend list is full (30 friends)") + val main = base + FRIEND_OFFSET + slot * FRIEND_BYTES + val extra = base + FRIEND_EXTRA_OFFSET + slot * FRIEND_EXTRA_BYTES + java.util.Arrays.fill(bytes, main, main + FRIEND_BYTES, 0) + java.util.Arrays.fill(bytes, extra, extra + FRIEND_EXTRA_BYTES, 0) + val code = FriendCode.fromProfileId(profileId) + putU32(bytes, main, code ushr 32) + putU32(bytes, main + 0x04, profileId) + putU16(bytes, main + 0x10, FRIEND_ADDED) + putU16(bytes, main + 0x16, storedFriendRating(vr ?: DEFAULT_RATING, game)) + putU16(bytes, main + 0x18, storedFriendRating(br ?: DEFAULT_RATING, game)) + System.arraycopy(mii.data, 0, bytes, main + 0x1A, Mii.RECORD_BYTES) + putU16(bytes, main + 0x64, MiiDatabase.crc16(mii.data, 0, Mii.RECORD_BYTES)) + bytes[main + 0x66] = slot.toByte() + bytes[main + 0x67] = 0 + bytes[main + 0x68] = 0xFF.toByte() + bytes[main + 0x69] = 0xFF.toByte() + for (i in 0 until 10) putU32(bytes, main + 0x70 + i * 8, 0xFFFFFFFFL) + // A one-sided request: the friend shows as pending until they add this license back. + bytes[extra + 0x2] = FRIEND_KEY.toByte() + putU32(bytes, extra + 0x4, profileId) + } + } + + fun removeFriend(context: Context, game: SaveData.Game, index: Int, profileId: Long) = + edit(context, game) { applyRemoveFriend(it, index, profileId) } + + fun applyRemoveFriend(bytes: ByteArray, index: Int, profileId: Long) { + run { + val base = base(index) + val slot = + (0 until FRIEND_COUNT).firstOrNull { u32(bytes, base + FRIEND_OFFSET + it * FRIEND_BYTES + 0x04) == profileId } + ?: throw IOException("that friend isn't on this license") + val main = base + FRIEND_OFFSET + slot * FRIEND_BYTES + val extra = base + FRIEND_EXTRA_OFFSET + slot * FRIEND_EXTRA_BYTES + java.util.Arrays.fill(bytes, main, main + FRIEND_BYTES, 0) + java.util.Arrays.fill(bytes, extra, extra + FRIEND_EXTRA_BYTES, 0) + } + } + + /** Points license [index] at [mii] (which must be in the Mii file) and renames it to match. */ + fun setLicenseMii(context: Context, game: SaveData.Game, index: Int, mii: Mii) = + edit(context, game) { applySetLicenseMii(it, index, mii) } + + fun applySetLicenseMii(bytes: ByteArray, index: Int, mii: Mii) { + run { + val base = base(index) + if (String(bytes, base, 4, Charsets.US_ASCII) != "RKPD") throw IOException("that license is empty") + putU32(bytes, base + 0x28, mii.miiId) + putU32(bytes, base + 0x2C, mii.systemId) + val name = mii.name.take(10) + for (i in 0 until 10) { + val c = if (i < name.length) name[i].code else 0 + bytes[base + 0x14 + i * 2] = (c shr 8).toByte() + bytes[base + 0x15 + i * 2] = c.toByte() + } + } + } + + /** Which licenses (by index) use the Mii with avatar id [miiId], across both saves. */ + fun licensesUsing(context: Context, miiId: Long): List> = + SaveData.Game.values().flatMap { game -> + load(context, game)?.licenses?.filter { it.miiId == miiId }?.map { game to it }.orEmpty() + } + + private fun edit(context: Context, game: SaveData.Game, change: (ByteArray) -> Unit) { + val dest = file(context, game) + if (!dest.isFile) throw IOException("there's no ${game.label} save yet - play it once first") + val bytes = dest.readBytes() + SaveData.validate(bytes)?.let { throw IOException(it) } + change(bytes) + fixChecksum(bytes) + SaveData.validate(bytes)?.let { throw IOException(it) } + val dir = dest.parentFile ?: throw IOException("no save folder") + dest.copyTo(File(dir, "rksys.dat.bak"), overwrite = true) + val temporary = File(dir, "rksys.dat.saving") + temporary.writeBytes(bytes) + if (!temporary.renameTo(dest)) { + temporary.delete() + throw IOException("couldn't replace the save file") + } + } + + fun fixChecksum(bytes: ByteArray) { + val crc = CRC32() + crc.update(bytes, 0, CHECKSUM_OFFSET) + ByteBuffer.wrap(bytes, CHECKSUM_OFFSET, 4).putInt(crc.value.toInt()) + } + + // --- Big-endian helpers --- + + private fun u16(b: ByteArray, o: Int): Int = ((b[o].toInt() and 0xFF) shl 8) or (b[o + 1].toInt() and 0xFF) + + private fun u32(b: ByteArray, o: Int): Long = + ((b[o].toLong() and 0xFF) shl 24) or ((b[o + 1].toLong() and 0xFF) shl 16) or + ((b[o + 2].toLong() and 0xFF) shl 8) or (b[o + 3].toLong() and 0xFF) + + private fun putU16(b: ByteArray, o: Int, v: Int) { + b[o] = (v shr 8).toByte() + b[o + 1] = v.toByte() + } + + private fun putU32(b: ByteArray, o: Int, v: Long) { + b[o] = (v shr 24).toByte() + b[o + 1] = (v shr 16).toByte() + b[o + 2] = (v shr 8).toByte() + b[o + 3] = v.toByte() + } + + private fun utf16(b: ByteArray, o: Int, chars: Int): String { + val out = StringBuilder() + for (i in 0 until chars) { + val c = u16(b, o + i * 2) + if (c == 0) break + out.append(c.toChar()) + } + return out.toString() + } + + /** + * Retro Rewind's own rating file, RRRating.pul ("RRRT", version 1, 100 entries of profile id, + * VR and BR as floats in hundreds, and flags). Format from WheelWizard's RrRatingReader. + */ + object RrRatings { + private val CANDIDATES = + listOf( + "WiiCompiled/NAND/shared2/Pulsar/RetroRewind6/RRRating.pul", + "WiiCompiled/riivolution/save/RetroWFC/RRRating.pul", + ) + + fun load(context: Context): Map> { + val bytes = CANDIDATES.asSequence().map { File(context.filesDir, it) }.firstOrNull { it.isFile } + ?.let { runCatching { it.readBytes() }.getOrNull() } ?: return emptyMap() + return parse(bytes) + } + + fun parse(bytes: ByteArray): Map> { + if (bytes.size < 8 + 16 * 100) return emptyMap() + val buffer = ByteBuffer.wrap(bytes) + if (buffer.getInt(0) != 0x52525254 || buffer.getShort(4).toInt() != 1) return emptyMap() + val count = buffer.getShort(6).toInt().coerceIn(0, (bytes.size - 8) / 16) + val result = HashMap>() + for (i in 0 until count) { + val o = 8 + i * 16 + val pid = buffer.getInt(o).toLong() and 0xFFFFFFFFL + val flags = buffer.getInt(o + 12) + if (pid != 0L && (flags and 1) != 0) result[pid] = buffer.getFloat(o + 4) to buffer.getFloat(o + 8) + } + return result + } + } +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ui/DriftSheet.kt b/android/app/src/main/kotlin/com/driftdroid/android/ui/DriftSheet.kt index 709aba0..e5529d3 100644 --- a/android/app/src/main/kotlin/com/driftdroid/android/ui/DriftSheet.kt +++ b/android/app/src/main/kotlin/com/driftdroid/android/ui/DriftSheet.kt @@ -112,8 +112,88 @@ internal object DriftUi { } } +/** + * The colours a [DriftSheet] draws with. In game it is the native settings drawer's ([GAME]); a + * screen with a look of its own - the launcher - hands sheets its palette by being [SheetThemed]. + */ +class SheetPalette internal constructor( + val panel: Int, + val row: Int, + val rowStrong: Int, + val line: Int, + val text: Int, + val muted: Int, + val accent: Int, + val accentText: Int, + val focus: Int, + val trackOff: Int, + val knobOff: Int, + val danger: Int, + val radiusDp: Float, + val panelRadiusDp: Float, + /** Footer buttons as the launcher's slanted plates instead of the drawer's pills. */ + val plates: Boolean, +) { + internal fun pressable(context: Context, color: Int, radiusDp: Float = this.radiusDp): Drawable = + DriftUi.pressable(context, color, min(radiusDp, if (plates) this.radiusDp else radiusDp)) + + internal fun button(context: Context, text: String, style: DriftUi.Style, onClick: () -> Unit): TextView { + if (!plates) return DriftUi.button(context, text, style, onClick) + val (fill, ink) = + when (style) { + DriftUi.Style.PRIMARY -> accent to accentText + DriftUi.Style.SECONDARY -> rowStrong to this.text + DriftUi.Style.DANGER -> Lx.alpha(danger, 0.16f) to danger + } + return TextView(context).apply { + this.text = text.uppercase() + textSize = 15f + typeface = Lx.CONDENSED + letterSpacing = 0.04f + gravity = Gravity.CENTER + isSingleLine = true + minHeight = DriftUi.dp(context, 46f) + setPadding(DriftUi.dp(context, 18f), 0, DriftUi.dp(context, 18f), 0) + background = Lx.plate(context, fill) + setTextColor(ink) + setOnClickListener { onClick() } + } + } + + internal fun styleField(field: EditText) { + if (!plates) return DriftUi.styleField(field) + field.setTextColor(text) + field.setHintTextColor(muted) + field.textSize = 16f + field.background = Lx.fieldBackground(field.context) + field.setPadding(DriftUi.dp(field.context, 14f), DriftUi.dp(field.context, 12f), DriftUi.dp(field.context, 14f), DriftUi.dp(field.context, 12f)) + } + + companion object { + val GAME = + SheetPalette( + DriftUi.PANEL, DriftUi.ROW, DriftUi.ROW_STRONG, DriftUi.LINE, DriftUi.TEXT, DriftUi.MUTED, DriftUi.ACCENT, + DriftUi.ACCENT_TEXT, DriftUi.FOCUS, DriftUi.TRACK_OFF, DriftUi.KNOB_OFF, DriftUi.DANGER, 12f, 20f, false, + ) + + val LAUNCHER = + SheetPalette( + Lx.SURFACE, Lx.SURFACE_HI, 0xFF292E36.toInt(), Lx.LINE, Lx.TEXT, Lx.MUTED, Lx.ACCENT, + Lx.ACCENT_TEXT, Lx.MUTED, Lx.LINE, Lx.MUTED, Lx.DANGER, 8f, 14f, true, + ) + + internal fun of(activity: Activity): SheetPalette = (activity as? SheetThemed)?.sheetPalette ?: GAME + } +} + +/** A screen whose sheets should wear its own colours rather than the in-game drawer's. */ +interface SheetThemed { + val sheetPalette: SheetPalette +} + /** The drawer's on/off switch: green track with the knob on the right when on. */ internal class PillSwitch(context: Context) : View(context) { + var palette: SheetPalette = SheetPalette.GAME var isOn = false set(value) { field = value @@ -125,15 +205,16 @@ internal class PillSwitch(context: Context) : View(context) { val w = width.toFloat() val h = height.toFloat() val r = h / 2f - paint.color = if (isOn) DriftUi.ACCENT else DriftUi.TRACK_OFF + paint.color = if (isOn) palette.accent else palette.trackOff canvas.drawRoundRect(0f, 0f, w, h, r, r, paint) - paint.color = if (isOn) Color.WHITE else DriftUi.KNOB_OFF + paint.color = if (isOn) Color.WHITE else palette.knobOff canvas.drawCircle(if (isOn) w - r else r, r, r * 0.74f, paint) } } /** The check circle of a [DriftSheet.radio] row. */ internal class RadioMark(context: Context) : View(context) { + var palette: SheetPalette = SheetPalette.GAME var picked = false set(value) { field = value @@ -151,7 +232,7 @@ internal class RadioMark(context: Context) : View(context) { val stroke = DriftUi.dp(context, 2f).toFloat() paint.style = Paint.Style.STROKE paint.strokeWidth = stroke - paint.color = if (picked) DriftUi.ACCENT else DriftUi.MUTED + paint.color = if (picked) palette.accent else palette.muted canvas.drawCircle(r, r, r - stroke, paint) if (picked) { paint.style = Paint.Style.FILL @@ -192,6 +273,7 @@ internal class DriftSheet( ) { enum class Dock { AUTO, START, END, TOP, BOTTOM } + private val pal = SheetPalette.of(activity) private val portrait = activity.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT private val dock = when (dock) { @@ -219,10 +301,10 @@ internal class DriftSheet( val (_, screenH) = screenSize() val root = LinearLayout(activity) root.orientation = LinearLayout.VERTICAL - val radius = dp(20f).toFloat() + val radius = dp(pal.panelRadiusDp).toFloat() root.background = GradientDrawable().apply { - setColor(DriftUi.PANEL) - setStroke(dp(1.5f), DriftUi.LINE) + setColor(pal.panel) + setStroke(dp(1.5f), pal.line) cornerRadii = when (this@DriftSheet.dock) { Dock.BOTTOM -> floatArrayOf(radius, radius, radius, radius, 0f, 0f, 0f, 0f) @@ -242,12 +324,12 @@ internal class DriftSheet( titles.addView( TextView(activity).apply { text = T(title) - setTextColor(DriftUi.TEXT) + setTextColor(pal.text) textSize = 21f typeface = Typeface.DEFAULT_BOLD }, ) - subtitleView.setTextColor(DriftUi.MUTED) + subtitleView.setTextColor(pal.muted) subtitleView.textSize = 14f subtitleView.visibility = View.GONE titles.addView(subtitleView) @@ -258,8 +340,8 @@ internal class DriftSheet( text = "✕" textSize = 18f gravity = Gravity.CENTER - setTextColor(DriftUi.MUTED) - background = DriftUi.pressable(activity, DriftUi.ROW, 22f) + setTextColor(pal.muted) + background = pal.pressable(activity, pal.row, 22f) contentDescription = "Close" setOnClickListener { dismiss() } }, @@ -271,7 +353,7 @@ internal class DriftSheet( root.addView( View(activity).apply { background = GradientDrawable().apply { - setColor(DriftUi.LINE) + setColor(pal.line) cornerRadius = dp(3f).toFloat() } }, @@ -282,7 +364,7 @@ internal class DriftSheet( ) } root.addView(header) - root.addView(View(activity).apply { setBackgroundColor(DriftUi.LINE) }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1.5f))) + root.addView(View(activity).apply { setBackgroundColor(pal.line) }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(1.5f))) body.orientation = LinearLayout.VERTICAL body.setPadding(dp(16f), dp(12f), dp(16f), dp(8f)) @@ -336,7 +418,7 @@ internal class DriftSheet( gravity = Gravity.CENTER_VERTICAL minimumHeight = dp(58f) setPadding(dp(16f), dp(10f), dp(14f), dp(10f)) - background = DriftUi.pressable(activity, DriftUi.ROW) + background = pal.pressable(activity, pal.row) } private fun labelColumn(label: String, detail: String?): LinearLayout { @@ -345,7 +427,7 @@ internal class DriftSheet( column.addView( TextView(activity).apply { text = T(label) - setTextColor(DriftUi.TEXT) + setTextColor(pal.text) textSize = 16f }, ) @@ -353,7 +435,7 @@ internal class DriftSheet( column.addView( TextView(activity).apply { text = T(detail) - setTextColor(DriftUi.MUTED) + setTextColor(pal.muted) textSize = 13f setPadding(0, dp(2f), 0, 0) }, @@ -366,7 +448,7 @@ internal class DriftSheet( body.addView( TextView(activity).apply { this.text = T(text).uppercase() - setTextColor(DriftUi.FOCUS) + setTextColor(pal.focus) textSize = 12f typeface = Typeface.DEFAULT_BOLD letterSpacing = 0.08f @@ -378,7 +460,7 @@ internal class DriftSheet( fun note(text: String): TextView = TextView(activity).apply { this.text = T(text) - setTextColor(DriftUi.MUTED) + setTextColor(pal.muted) textSize = 14f setLineSpacing(0f, 1.15f) setPadding(dp(4f), dp(2f), dp(4f), dp(10f)) @@ -389,6 +471,7 @@ internal class DriftSheet( val row = rowBase() row.addView(labelColumn(label, detail), LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) val pill = PillSwitch(activity) + pill.palette = pal pill.isOn = checked row.addView(pill, LinearLayout.LayoutParams(dp(52f), dp(30f)).apply { marginStart = dp(12f) }) row.setOnClickListener { @@ -407,7 +490,7 @@ internal class DriftSheet( trailing ?: TextView(activity).apply { text = "›" textSize = 24f - setTextColor(DriftUi.MUTED) + setTextColor(pal.muted) setPadding(dp(12f), 0, dp(2f), dp(2f)) }, ) @@ -422,8 +505,8 @@ internal class DriftSheet( card.orientation = LinearLayout.VERTICAL card.setPadding(dp(16f), dp(12f), dp(12f), dp(12f)) card.background = GradientDrawable().apply { - setColor(DriftUi.ROW) - cornerRadius = dp(12f).toFloat() + setColor(pal.row) + cornerRadius = dp(pal.radiusDp).toFloat() } card.addView(labelColumn(label, detail)) val pills = LinearLayout(activity) @@ -432,8 +515,8 @@ internal class DriftSheet( fun paint(current: Int) { pillViews.forEachIndexed { index, view -> val on = index == current - view.background = DriftUi.pressable(activity, if (on) DriftUi.ACCENT else DriftUi.ROW_STRONG, 10f) - view.setTextColor(if (on) DriftUi.ACCENT_TEXT else DriftUi.TEXT) + view.background = pal.pressable(activity, if (on) pal.accent else pal.rowStrong, 10f) + view.setTextColor(if (on) pal.accentText else pal.text) } } options.forEachIndexed { index, option -> @@ -494,22 +577,22 @@ internal class DriftSheet( card.orientation = LinearLayout.VERTICAL card.setPadding(dp(16f), dp(12f), dp(8f), dp(6f)) card.background = GradientDrawable().apply { - setColor(DriftUi.ROW) - cornerRadius = dp(12f).toFloat() + setColor(pal.row) + cornerRadius = dp(pal.radiusDp).toFloat() } val top = LinearLayout(activity) top.orientation = LinearLayout.HORIZONTAL top.addView( TextView(activity).apply { text = label - setTextColor(DriftUi.TEXT) + setTextColor(pal.text) textSize = 16f }, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f), ) val valueView = TextView(activity).apply { text = format(value) - setTextColor(DriftUi.TEXT) + setTextColor(pal.text) textSize = 15f typeface = Typeface.DEFAULT_BOLD setPadding(0, 0, dp(8f), 0) @@ -519,8 +602,8 @@ internal class DriftSheet( val seek = SeekBar(activity) seek.max = steps seek.progress = (((value - min) / (max - min)) * steps).toInt().coerceIn(0, steps) - seek.progressTintList = ColorStateList.valueOf(DriftUi.ACCENT) - seek.progressBackgroundTintList = ColorStateList.valueOf(DriftUi.TRACK_OFF) + seek.progressTintList = ColorStateList.valueOf(pal.accent) + seek.progressBackgroundTintList = ColorStateList.valueOf(pal.trackOff) seek.thumbTintList = ColorStateList.valueOf(Color.WHITE) seek.setPadding(dp(8f), dp(12f), dp(16f), dp(12f)) seek.setOnSeekBarChangeListener( @@ -547,7 +630,7 @@ internal class DriftSheet( field.setText(initial) field.isSingleLine = true field.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES - DriftUi.styleField(field) + pal.styleField(field) addRow(field) field.setSelection(field.text.length) return field @@ -559,6 +642,7 @@ internal class DriftSheet( * [setPicked] when one is tapped). */ fun radio(label: String, detail: String? = null, picked: Boolean, onClick: () -> Unit): LinearLayout { val mark = RadioMark(activity) + mark.palette = pal mark.picked = picked val row = action(label, detail, mark, onClick) (mark.layoutParams as? LinearLayout.LayoutParams)?.marginStart = dp(12f) @@ -575,9 +659,9 @@ internal class DriftSheet( val bar = android.widget.ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal) bar.max = 1000 bar.isIndeterminate = true - bar.progressTintList = ColorStateList.valueOf(DriftUi.ACCENT) - bar.progressBackgroundTintList = ColorStateList.valueOf(DriftUi.TRACK_OFF) - bar.indeterminateTintList = ColorStateList.valueOf(DriftUi.ACCENT) + bar.progressTintList = ColorStateList.valueOf(pal.accent) + bar.progressBackgroundTintList = ColorStateList.valueOf(pal.trackOff) + bar.indeterminateTintList = ColorStateList.valueOf(pal.accent) addRow(bar) return bar } @@ -618,7 +702,7 @@ internal class DriftSheet( /** A footer button. Buttons share the footer's width equally. */ fun button(text: String, style: DriftUi.Style = DriftUi.Style.SECONDARY, onClick: () -> Unit): TextView { - val view = DriftUi.button(activity, T(text), style, onClick) + val view = pal.button(activity, T(text), style, onClick) footer.visibility = View.VISIBLE footer.addView( view, @@ -651,7 +735,11 @@ internal class DriftSheet( window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN) window.attributes = window.attributes.apply { layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + // The system bars are hidden, so the sheet sits on the screen's real edge rather than + // above where the navigation bar would be (which left a strip of the page under it). + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) fitInsetsTypes = 0 } + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) window.setDecorFitsSystemWindows(false) window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) if (sideDock) { val width = (screenW * 0.40f).toInt().coerceIn(min(dp(340f), screenW), (screenW * 0.62f).toInt().coerceAtLeast(dp(340f))) @@ -669,9 +757,12 @@ internal class DriftSheet( dialog.show() @Suppress("DEPRECATION") window.decorView.systemUiVisibility = activity.window.decorView.systemUiVisibility - window.insetsController?.let { - it.hide(WindowInsets.Type.systemBars()) - it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + // WindowInsetsController is Android 11+; on Android 10 the copied flags above do the job. + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { + window.insetsController?.let { + it.hide(WindowInsets.Type.systemBars()) + it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + } } window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) } diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ui/Icons.kt b/android/app/src/main/kotlin/com/driftdroid/android/ui/Icons.kt new file mode 100644 index 0000000..a98f70a --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/ui/Icons.kt @@ -0,0 +1,197 @@ +package com.driftdroid.android.ui + +import android.graphics.Canvas +import android.graphics.ColorFilter +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Path +import android.graphics.PixelFormat +import android.graphics.drawable.Drawable + +/** Material Design icons (Apache 2.0), as 24x24 path data, for the launcher. */ +internal enum class Icon(val path: String) { + HOME("M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z"), + EXTENSION( + "M20.5,11H19V7c0,-1.1 -0.9,-2 -2,-2h-4V3.5C13,2.12 11.88,1 10.5,1S8,2.12 8,3.5V5H4c-1.1,0 -1.99,0.9 -1.99,2v3.8H3.5" + + "c1.49,0 2.7,1.21 2.7,2.7s-1.21,2.7 -2.7,2.7H2V20c0,1.1 0.9,2 2,2h3.8v-1.5c0,-1.49 1.21,-2.7 2.7,-2.7 1.49,0 2.7,1.21 " + + "2.7,2.7V22H17c1.1,0 2,-0.9 2,-2v-4h1.5c1.38,0 2.5,-1.12 2.5,-2.5S21.88,11 20.5,11z", + ), + PUBLIC( + "M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM11,19.93c-3.95,-0.49 -7,-3.85 -7,-7.93 " + + "0,-0.62 0.08,-1.21 0.21,-1.79L9,15v1c0,1.1 0.9,2 2,2v1.93zM17.9,17.39c-0.26,-0.81 -1,-1.39 -1.9,-1.39h-1v-3" + + "c0,-0.55 -0.45,-1 -1,-1H8v-2h2c0.55,0 1,-0.45 1,-1V7h2c1.1,0 2,-0.9 2,-2v-0.41c2.93,1.19 5,4.06 5,7.41 0,2.08 " + + "-0.8,3.97 -2.1,5.39z", + ), + TROPHY( + "M19,5h-2V3H7v2H5C3.9,5 3,5.9 3,7v1c0,2.55 1.92,4.63 4.39,4.94c0.63,1.5 1.98,2.63 3.61,2.96V19H7v2h10v-2h-4v-3.1" + + "c1.63,-0.33 2.98,-1.46 3.61,-2.96C19.08,12.63 21,10.55 21,8V7C21,5.9 20.1,5 19,5zM5,8V7h2v3.82C5.84,10.4 5,9.3 5,8z" + + "M19,8c0,1.3 -0.84,2.4 -2,2.82V7h2V8z", + ), + FACE( + "M9,11.75c-0.69,0 -1.25,0.56 -1.25,1.25s0.56,1.25 1.25,1.25 1.25,-0.56 1.25,-1.25 -0.56,-1.25 -1.25,-1.25z" + + "M15,11.75c-0.69,0 -1.25,0.56 -1.25,1.25s0.56,1.25 1.25,1.25 1.25,-0.56 1.25,-1.25 -0.56,-1.25 -1.25,-1.25z" + + "M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8 0,-0.29 0.02,-0.58 " + + "0.05,-0.86 2.36,-1.05 4.23,-2.98 5.21,-5.37C11.07,8.33 14.05,10 17.42,10c0.78,0 1.53,-0.09 2.25,-0.26 0.21,0.71 " + + "0.33,1.47 0.33,2.26 0,4.41 -3.59,8 -8,8z", + ), + SETTINGS( + "M19.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94c0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 " + + "0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81" + + "c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29" + + "L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 " + + "4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22" + + "l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41" + + "l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 " + + "-0.12,-0.61L19.14,12.94zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6s3.6,1.62 3.6,3.6S13.98,15.6 12,15.6z", + ), + PLAY("M8,5v14l11,-7z"), + DOWNLOAD("M19,9h-4V3H9v6H5l7,7 7,-7zM5,18v2h14v-2H5z"), + UPLOAD("M9,16h6v-6h4l-7,-7 -7,7h4zM5,18h14v2H5z"), + REFRESH( + "M17.65,6.35C16.2,4.9 14.21,4 12,4c-4.42,0 -7.99,3.58 -7.99,8s3.57,8 7.99,8c3.73,0 6.84,-2.55 7.73,-6h-2.08" + + "c-0.82,2.33 -3.04,4 -5.65,4 -3.31,0 -6,-2.69 -6,-6s2.69,-6 6,-6c1.66,0 3.14,0.69 4.22,1.78L13,11h7V4l-2.35,2.35z", + ), + BACK("M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"), + CLOSE("M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z"), + EDIT( + "M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34" + + "c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83 3.75,3.75 1.83,-1.83z", + ), + DELETE("M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"), + ADD("M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"), + SEARCH( + "M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16" + + "c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 " + + "14,7.01 14,9.5 11.99,14 9.5,14z", + ), + PEOPLE( + "M16,11c1.66,0 2.99,-1.34 2.99,-3S17.66,5 16,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zM8,11c1.66,0 2.99,-1.34 2.99,-3" + + "S9.66,5 8,5C6.34,5 5,6.34 5,8s1.34,3 3,3zM8,13c-2.33,0 -7,1.17 -7,3.5V19h14v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z" + + "M16,13c-0.29,0 -0.62,0.02 -0.97,0.05 1.16,0.84 1.97,1.97 1.97,3.45V19h6v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z", + ), + PERSON("M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"), + PERSON_ADD( + "M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10V7H4v3H1v2h3v3h2v-3h3v-2H6zM15,14" + + "c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z", + ), + THUMB_UP( + "M1,21h4V9H1v12zM23,10c0,-1.1 -0.9,-2 -2,-2h-6.31l0.95,-4.57 0.03,-0.32c0,-0.41 -0.17,-0.79 -0.44,-1.06L14.17,1 " + + "7.59,7.59C7.22,7.95 7,8.45 7,9v10c0,1.1 0.9,2 2,2h9c0.83,0 1.54,-0.5 1.84,-1.22l3.02,-7.05c0.09,-0.23 0.14,-0.47 " + + "0.14,-0.73v-2z", + ), + VISIBILITY( + "M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17" + + "c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 " + + "-1.34,-3 -3,-3z", + ), + COPY( + "M16,1H4c-1.1,0 -2,0.9 -2,2v14h2V3h12V1zM19,5H8c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h11c1.1,0 2,-0.9 2,-2V7" + + "c0,-1.1 -0.9,-2 -2,-2zM19,21H8V7h11v14z", + ), + OPEN_IN_NEW( + "M19,19H5V5h7V3H5c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2v-7h-2v7zM14,3v2h3.59l-9.83,9.83 " + + "1.41,1.41L19,6.41V10h2V3h-7z", + ), + DRAG("M20,9H4v2h16V9zM4,15h16v-2H4v2z"), + MORE_VERT( + "M12,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 " + + "-0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z", + ), + CHECK("M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"), + INFO("M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2V7h2v2z"), + WARNING("M1,21h22L12,2 1,21zM13,18h-2v-2h2v2zM13,14h-2v-4h2v4z"), + STAR("M12,17.27L18.18,21l-1.64,-7.03L22,9.24l-7.19,-0.61L12,2 9.19,8.63 2,9.24l5.46,4.73L5.82,21z"), + FOLDER("M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z"), + TUNE( + "M3,17v2h6v-2H3zM3,5v2h10V5H3zM13,21v-2h8v-2h-8v-2h-2v6h2zM7,9v2H3v2h4v2h2V9H7zM21,13v-2H11v2h10zM15,9h2V7h4V5h-4V3" + + "h-2v6z", + ), + TRANSLATE( + "M12.87,15.07l-2.54,-2.51 0.03,-0.03c1.74,-1.94 2.98,-4.17 3.71,-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5,7.92 " + + "10.44,9.75 9,11.35 8.07,10.32 7.3,9.19 6.69,8h-2c0.73,1.63 1.73,3.17 2.98,4.56l-5.09,5.02L4,19l5,-5 3.11,3.11 " + + "0.76,-2.04zM18.5,10h-2L12,22h2l1.12,-3h4.75L21,22h2l-4.5,-12zM15.88,17l1.62,-4.33L19.12,17h-3.24z", + ), + IMAGE( + "M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01" + + "L14.5,12l4.5,6H5l3.5,-4.5z", + ), + SAVE( + "M17,3H5c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2V7l-4,-4zM12,19c-1.66,0 -3,-1.34 -3,-3" + + "s1.34,-3 3,-3 3,1.34 3,3 -1.34,3 -3,3zM15,9H5V5h10v4z", + ), + SERVER( + "M20,13H4c-0.55,0 -1,0.45 -1,1v6c0,0.55 0.45,1 1,1h16c0.55,0 1,-0.45 1,-1v-6c0,-0.55 -0.45,-1 -1,-1zM7,19" + + "c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2zM20,3H4c-0.55,0 -1,0.45 -1,1v6c0,0.55 0.45,1 1,1h16" + + "c0.55,0 1,-0.45 1,-1V4c0,-0.55 -0.45,-1 -1,-1zM7,9c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2z", + ), + BUG( + "M20,8h-2.81c-0.45,-0.78 -1.07,-1.45 -1.82,-1.96L17,4.41 15.59,3l-2.17,2.17C12.96,5.06 12.49,5 12,5" + + "c-0.49,0 -0.96,0.06 -1.41,0.17L8.41,3 7,4.41l1.62,1.63C7.88,6.55 7.26,7.22 6.81,8H4v2h2.09c-0.05,0.33 -0.09,0.66 " + + "-0.09,1v1H4v2h2v1c0,0.34 0.04,0.67 0.09,1H4v2h2.81c1.04,1.79 2.97,3 5.19,3s4.15,-1.21 5.19,-3H20v-2h-2.09" + + "c0.05,-0.33 0.09,-0.66 0.09,-1v-1h2v-2h-2v-1c0,-0.34 -0.04,-0.67 -0.09,-1H20V8zM14,16h-4v-2h4v2zM14,12h-4v-2h4v2z", + ), + GAMEPAD( + "M21,6H3c-1.1,0 -2,0.9 -2,2v8c0,1.1 0.9,2 2,2h18c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2zM11,13H8v3H6v-3H3v-2h3V8" + + "h2v3h3v2zM15.5,15c-0.83,0 -1.5,-0.67 -1.5,-1.5s0.67,-1.5 1.5,-1.5 1.5,0.67 1.5,1.5 -0.67,1.5 -1.5,1.5zM19.5,12" + + "c-0.83,0 -1.5,-0.67 -1.5,-1.5S18.67,9 19.5,9 21,9.67 21,10.5 20.33,12 19.5,12z", + ), + FLAG("M14.4,6L14,4H5v17h2v-7h5.6l0.4,2h7V6z"), + CLOCK( + "M11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8" + + "s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8zM12.5,7H11v6l5.25,3.15 0.75,-1.23 -4.5,-2.67z", + ), + CHEVRON("M10,6L8.59,7.41 13.17,12l-4.58,4.59L10,18l6,-6z"), + SCREEN_ROTATION( + "M16.48,2.52c3.27,1.55 5.61,4.72 5.97,8.48h1.5C23.44,4.84 18.29,0 12,0l-0.66,0.03 3.81,3.81 1.33,-1.32zM10.23,1.75" + + "c-0.59,-0.59 -1.54,-0.59 -2.12,0L1.75,8.11c-0.59,0.59 -0.59,1.54 0,2.12l12.02,12.02c0.59,0.59 1.54,0.59 2.12,0" + + "l6.36,-6.36c0.59,-0.59 0.59,-1.54 0,-2.12L10.23,1.75zM14.83,21.19L2.81,9.17l6.36,-6.36 12.02,12.02 -6.36,6.36z" + + "M7.52,21.48C4.25,19.94 1.91,16.76 1.55,13H0.05C0.56,19.16 5.71,24 12,24l0.66,-0.03 -3.81,-3.81 -1.33,1.32z", + ), + ; + + /** Parsed once; null if the path data can't be read (then the icon just draws nothing). */ + val parsed: Path? by lazy { runCatching { androidx.core.graphics.PathParser.createPathFromPathData(path) }.getOrNull() } +} + +/** An [Icon] as a tinted Drawable that scales to whatever bounds it gets. */ +internal class IconDrawable(private val icon: Icon, color: Int) : Drawable() { + private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + this.color = color + style = Paint.Style.FILL + } + private val scaled = Path() + private val matrix = Matrix() + + var color: Int + get() = paint.color + set(value) { + paint.color = value + invalidateSelf() + } + + override fun onBoundsChange(bounds: android.graphics.Rect) { + super.onBoundsChange(bounds) + val source = icon.parsed ?: return + val scale = minOf(bounds.width(), bounds.height()) / 24f + matrix.setScale(scale, scale) + matrix.postTranslate(bounds.left + (bounds.width() - 24 * scale) / 2f, bounds.top + (bounds.height() - 24 * scale) / 2f) + source.transform(matrix, scaled) + } + + override fun draw(canvas: Canvas) { + if (icon.parsed != null) canvas.drawPath(scaled, paint) + } + + override fun setAlpha(alpha: Int) { + paint.alpha = alpha + invalidateSelf() + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + paint.colorFilter = colorFilter + invalidateSelf() + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ui/Lx.kt b/android/app/src/main/kotlin/com/driftdroid/android/ui/Lx.kt new file mode 100644 index 0000000..8b1cd37 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/ui/Lx.kt @@ -0,0 +1,893 @@ +package com.driftdroid.android.ui + +import android.content.Context +import android.content.res.ColorStateList +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.ColorFilter +import android.graphics.CornerPathEffect +import android.graphics.Paint +import android.graphics.Path +import android.graphics.PixelFormat +import android.graphics.Rect +import android.graphics.Typeface +import android.graphics.drawable.Drawable +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.RippleDrawable +import android.graphics.drawable.StateListDrawable +import android.text.Editable +import android.text.InputType +import android.text.TextUtils +import android.text.TextWatcher +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.SeekBar +import android.widget.TextView +import com.driftdroid.android.T +import java.text.NumberFormat +import kotlin.math.max +import kotlin.math.tan + +/** + * The launcher's look, "pit lane": dark asphalt neutrals, the kart's Android green as the one "go" + * colour (play, on, selected), amber for ratings, cyan for links, and condensed italic type for + * titles and numbers, like a race timing screen. Its signature is the slanted plate - primary + * buttons, rank numbers and the selected-tab marker are parallelograms - and everything else stays + * flat: panels without outlines, rows with hairlines, no cards inside cards. + */ +internal object Lx { + // Asphalt neutrals, darkest to lightest. + const val BG = 0xFF0C0E11.toInt() + const val BAR = 0xFF111418.toInt() + const val SURFACE_LO = 0xFF121519.toInt() + const val SURFACE = 0xFF171A1F.toInt() + const val SURFACE_HI = 0xFF20242B.toInt() + const val LINE = 0xFF2A2F37.toInt() + const val TEXT = 0xFFF1F3F6.toInt() + const val MUTED = 0xFFA3ABB7.toInt() + const val FAINT = 0xFF77808C.toInt() + + // Signals. Green is reserved for "go": the main action, things that are on, the current tab. + const val ACCENT = 0xFF3DDC84.toInt() + const val ACCENT_TEXT = 0xFF04210F.toInt() + const val AMBER = 0xFFFFB547.toInt() + const val CYAN = 0xFF5CC8FF.toInt() + const val DANGER = 0xFFFF5A5F.toInt() + const val VIOLET = 0xFFB69CFF.toInt() + const val GOLD = 0xFFFFC94A.toInt() + const val SILVER = 0xFFCDD3DC.toInt() + const val BRONZE = 0xFFE0955A.toInt() + + /** Titles, big numbers and plates: condensed, bold, leaning forward. */ + val DISPLAY: Typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD_ITALIC) + /** Labels and tabs: condensed bold, upright. */ + val CONDENSED: Typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD) + val MEDIUM: Typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) + val BOLD: Typeface = Typeface.DEFAULT_BOLD + + /** How far plates lean: the top edge sits this many degrees ahead of the bottom. */ + const val SLANT_DEGREES = 12f + + fun dp(context: Context, value: Float): Int = + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.resources.displayMetrics).toInt() + + fun alpha(color: Int, fraction: Float): Int = (color and 0x00FFFFFF) or ((fraction.coerceIn(0f, 1f) * 255).toInt() shl 24) + + /** Phone-sized width: one column, bottom tab bar, controls stacked instead of side by side. */ + fun isCompact(context: Context): Boolean = context.resources.configuration.screenWidthDp < 600 + + /** The side margin pages use. */ + fun gutter(context: Context): Int = dp(context, if (isCompact(context)) 16f else 24f) + + // --- Shapes --- + + fun rounded(context: Context, color: Int, radiusDp: Float, strokeColor: Int = 0, strokeDp: Float = 1f): GradientDrawable = + GradientDrawable().apply { + setColor(color) + cornerRadius = dp(context, radiusDp).toFloat() + if (strokeColor != 0) setStroke(dp(context, strokeDp).coerceAtLeast(1), strokeColor) + } + + /** A rounded fill that ripples when pressed and lights up when focused by a gamepad. */ + fun pressable(context: Context, color: Int, radiusDp: Float = 8f, strokeColor: Int = 0): Drawable { + val shape = rounded(context, color, radiusDp, strokeColor) + val mask = rounded(context, Color.WHITE, radiusDp) + return RippleDrawable(ColorStateList.valueOf(0x2EFFFFFF), shape, mask) + } + + /** A slanted plate that ripples. */ + fun plate(context: Context, fill: Int, stroke: Int = 0): Drawable { + val shape = SlantDrawable(fill, stroke, dp(context, 1.5f).toFloat(), dp(context, 3f).toFloat()) + val mask = SlantDrawable(Color.WHITE, 0, 0f, dp(context, 3f).toFloat()) + return RippleDrawable(ColorStateList.valueOf(0x33FFFFFF), shape, mask) + } + + /** A flat panel: the one surface level content sits on. No outline, small corners. */ + fun panel(context: Context, padDp: Float = 16f, color: Int = SURFACE): LinearLayout = + LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + background = rounded(context, color, 8f) + val p = dp(context, padDp) + setPadding(p, p, p, p) + } + + /** Clips a view (and its children, such as a banner image) to rounded corners. */ + fun clipRounded(view: View, radiusDp: Float) { + val radius = dp(view.context, radiusDp).toFloat() + view.clipToOutline = true + view.outlineProvider = + object : android.view.ViewOutlineProvider() { + override fun getOutline(v: View, outline: android.graphics.Outline) { + outline.setRoundRect(0, 0, v.width, v.height, radius) + } + } + } + + // --- Text --- + + fun text( + context: Context, + value: CharSequence, + sizeSp: Float, + color: Int = TEXT, + face: Typeface = Typeface.DEFAULT, + maxLines: Int = 0, + ): TextView = + TextView(context).apply { + text = value + textSize = sizeSp + setTextColor(color) + typeface = face + includeFontPadding = false + if (maxLines > 0) { + this.maxLines = maxLines + ellipsize = TextUtils.TruncateAt.END + } + } + + /** Condensed italic for a title or a big number; figures are tabular so counts don't jitter. */ + fun display(context: Context, value: CharSequence, sizeSp: Float, color: Int = TEXT, maxLines: Int = 1): TextView = + text(context, value, sizeSp, color, DISPLAY, maxLines).apply { + fontFeatureSettings = "tnum" + // Italic glyphs lean past the advance width TextView measures; room so the last one isn't shaved. + setPadding(0, 0, (sizeSp * 0.12f * resources.displayMetrics.scaledDensity).toInt(), 0) + } + + fun heading(context: Context, value: String, maxLines: Int = 1) = text(context, value, 16f, TEXT, BOLD, maxLines) + + fun body(context: Context, value: CharSequence, color: Int = MUTED) = + text(context, value, 14f, color).apply { setLineSpacing(0f, 1.25f) } + + fun caption(context: Context, value: CharSequence, color: Int = MUTED, maxLines: Int = 1) = + text(context, value, 12.5f, color, Typeface.DEFAULT, maxLines) + + /** A small upright all-caps label. */ + fun label(context: Context, value: String, color: Int = FAINT, sizeSp: Float = 11f) = + text(context, T(value).uppercase(), sizeSp, color, CONDENSED, 1).apply { letterSpacing = 0.12f } + + /** A section heading: a green slanted tick, then the label. */ + fun section(context: Context, value: String, trailing: View? = null): LinearLayout = + hbox(context).apply { + addView(View(context).apply { background = SlantDrawable(ACCENT, 0, 0f, 0f) }, lp(context, 10f, 12f, end = 8f)) + addView(label(context, value, MUTED, 12f), lp(context, 0f, -2f, 1f)) + if (trailing != null) addView(trailing) + } + + /** A big number with a small label under it. */ + fun stat(context: Context, value: String, label: String, color: Int = TEXT, sizeSp: Float = 24f): LinearLayout = + vbox(context).apply { + addView(display(context, value, sizeSp, color)) + addView(label(context, label), lp(context, -2f, -2f, top = 4f)) + } + + // --- Controls --- + + enum class Tone { PRIMARY, SECONDARY, GHOST, DANGER, INFO } + + /** A slanted plate button with an optional leading icon. */ + fun button( + context: Context, + label: String, + tone: Tone = Tone.SECONDARY, + icon: Icon? = null, + compact: Boolean = false, + onClick: () -> Unit, + ): LinearLayout { + val (fill, stroke, ink) = + when (tone) { + Tone.PRIMARY -> Triple(ACCENT, 0, ACCENT_TEXT) + Tone.SECONDARY -> Triple(SURFACE_HI, 0, TEXT) + Tone.GHOST -> Triple(Color.TRANSPARENT, LINE, MUTED) + Tone.DANGER -> Triple(alpha(DANGER, 0.14f), 0, DANGER) + Tone.INFO -> Triple(Color.TRANSPARENT, alpha(CYAN, 0.6f), CYAN) + } + return hbox(context, Gravity.CENTER).apply { + minimumHeight = dp(context, if (compact) 36f else 46f) + val h = dp(context, if (compact) 16f else 22f) + setPadding(h, 0, h, 0) + background = plate(context, fill, stroke) + isClickable = true + isFocusable = true + if (icon != null) { + addView( + ImageView(context).apply { setImageDrawable(IconDrawable(icon, ink)) }, + LinearLayout.LayoutParams(dp(context, 18f), dp(context, 18f)).apply { marginEnd = dp(context, 8f) }, + ) + } + addView(text(context, T(label).uppercase(), if (compact) 13f else 15f, ink, CONDENSED, 1).apply { letterSpacing = 0.04f }) + setOnClickListener { onClick() } + contentDescription = T(label) + } + } + + fun setEnabled(view: View, enabled: Boolean) { + view.isEnabled = enabled + view.alpha = if (enabled) 1f else 0.4f + } + + /** A square icon-only button. */ + fun iconButton( + context: Context, + icon: Icon, + description: String, + tint: Int = TEXT, + fill: Int = SURFACE_HI, + sizeDp: Float = 40f, + onClick: () -> Unit, + ): ImageView = + ImageView(context).apply { + setImageDrawable(IconDrawable(icon, tint)) + val p = dp(context, sizeDp * 0.25f) + setPadding(p, p, p, p) + background = pressable(context, fill, 8f) + contentDescription = T(description) + layoutParams = LinearLayout.LayoutParams(dp(context, sizeDp), dp(context, sizeDp)) + setOnClickListener { onClick() } + } + + fun iconView(context: Context, icon: Icon, tint: Int, sizeDp: Float): ImageView = + ImageView(context).apply { + setImageDrawable(IconDrawable(icon, tint)) + layoutParams = LinearLayout.LayoutParams(dp(context, sizeDp), dp(context, sizeDp)) + } + + /** A filter chip: outlined when off, solid white when on (green is kept for "go"). */ + fun chip(context: Context, label: String, selected: Boolean, onClick: () -> Unit): TextView = + text(context, T(label), 13.5f, TEXT, MEDIUM, 1).apply { + gravity = Gravity.CENTER + minHeight = dp(context, 34f) + setPadding(dp(context, 14f), 0, dp(context, 14f), 0) + paintChip(this, selected) + setOnClickListener { onClick() } + } + + fun paintChip(chip: TextView, selected: Boolean) { + val context = chip.context + chip.background = pressable(context, if (selected) TEXT else Color.TRANSPARENT, 6f, if (selected) 0 else LINE) + chip.setTextColor(if (selected) BG else MUTED) + chip.isSelected = selected + } + + /** A short coloured label: state, version, "Pending". */ + fun badge(context: Context, label: String, color: Int): TextView = + text(context, T(label).uppercase(), 10.5f, color, CONDENSED, 1).apply { + letterSpacing = 0.08f + setPadding(dp(context, 7f), dp(context, 3f), dp(context, 7f), dp(context, 3f)) + background = rounded(context, alpha(color, 0.15f), 3f) + } + + /** A slanted number plate: ranks, "Installed". */ + fun plateBadge(context: Context, label: String, fill: Int, ink: Int, sizeSp: Float = 12f): TextView = + text(context, label, sizeSp, ink, DISPLAY, 1).apply { + fontFeatureSettings = "tnum" + gravity = Gravity.CENTER + setPadding(dp(context, 9f), dp(context, 3f), dp(context, 10f), dp(context, 3f)) + background = SlantDrawable(fill, 0, 0f, dp(context, 2f).toFloat()) + } + + /** A dot and a line of text: "● Ready", "● Open". */ + fun status(context: Context, value: String, color: Int, textColor: Int = color): LinearLayout = + hbox(context).apply { + addView(View(context).apply { background = rounded(context, color, 4f) }, lp(context, 7f, 7f, end = 7f)) + addView(caption(context, value, textColor, 2), lp(context, 0f, -2f, 1f)) + } + + fun divider(context: Context, insetDp: Float = 0f): View = + View(context).apply { + setBackgroundColor(LINE) + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(context, 1f)).apply { marginStart = dp(context, insetDp) } + } + + fun spinner(context: Context, sizeDp: Float = 32f): ProgressBar = + ProgressBar(context).apply { + isIndeterminate = true + indeterminateTintList = ColorStateList.valueOf(ACCENT) + layoutParams = LinearLayout.LayoutParams(dp(context, sizeDp), dp(context, sizeDp)) + } + + fun progressBar(context: Context): ProgressBar = + ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal).apply { + max = 1000 + progressTintList = ColorStateList.valueOf(ACCENT) + progressBackgroundTintList = ColorStateList.valueOf(LINE) + indeterminateTintList = ColorStateList.valueOf(ACCENT) + } + + /** The look of every text box: a dark well that outlines green while it has focus. */ + fun fieldBackground(context: Context): Drawable = + StateListDrawable().apply { + addState(intArrayOf(android.R.attr.state_focused), rounded(context, SURFACE_LO, 6f, ACCENT, 1.5f)) + addState(intArrayOf(), rounded(context, SURFACE_LO, 6f, LINE)) + } + + /** A search box. [onSearch] runs on the keyboard's search key; [onChange] on every edit. */ + fun searchField( + context: Context, + hint: String, + onSearch: (String) -> Unit, + onChange: ((String) -> Unit)? = null, + ): Pair { + val box = hbox(context) + box.background = rounded(context, SURFACE_LO, 6f, LINE) + box.setPadding(dp(context, 12f), 0, dp(context, 4f), 0) + box.minimumHeight = dp(context, 42f) + box.addView(iconView(context, Icon.SEARCH, FAINT, 18f)) + val field = EditText(context) + field.hint = T(hint) + field.setHintTextColor(FAINT) + field.setTextColor(TEXT) + field.textSize = 14.5f + field.background = null + field.isSingleLine = true + field.inputType = InputType.TYPE_CLASS_TEXT + field.imeOptions = EditorInfo.IME_ACTION_SEARCH or EditorInfo.IME_FLAG_NO_EXTRACT_UI + field.setPadding(dp(context, 10f), dp(context, 8f), dp(context, 4f), dp(context, 8f)) + field.setOnFocusChangeListener { _, focused -> + box.background = rounded(context, SURFACE_LO, 6f, if (focused) ACCENT else LINE, if (focused) 1.5f else 1f) + } + field.setOnEditorActionListener { v, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) { + hideKeyboard(v) + onSearch(field.text.toString()) + true + } else { + false + } + } + if (onChange != null) { + field.addTextChangedListener( + object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} + + override fun afterTextChanged(s: Editable?) = onChange(s?.toString().orEmpty()) + }, + ) + } + box.addView(field, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + box.addView( + iconButton(context, Icon.CLOSE, "Clear", FAINT, Color.TRANSPARENT, 34f) { + field.setText("") + onSearch("") + }, + ) + return box to field + } + + fun hideKeyboard(view: View) { + (view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(view.windowToken, 0) + view.clearFocus() + } + + fun textField(context: Context, hint: String, initial: String = "", maxChars: Int = 0): EditText = + EditText(context).apply { + this.hint = T(hint) + setText(initial) + isSingleLine = true + inputType = InputType.TYPE_CLASS_TEXT + imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_ACTION_DONE + if (maxChars > 0) filters = arrayOf(android.text.InputFilter.LengthFilter(maxChars)) + setTextColor(TEXT) + setHintTextColor(FAINT) + textSize = 15f + background = fieldBackground(context) + setPadding(dp(context, 14f), dp(context, 12f), dp(context, 14f), dp(context, 12f)) + } + + /** An icon, a title and a message, with an optional button: empty lists, errors, offline. */ + fun emptyState( + context: Context, + icon: Icon, + title: String, + message: String, + actionLabel: String? = null, + action: (() -> Unit)? = null, + ): LinearLayout = + vbox(context).apply { + gravity = Gravity.CENTER + val p = dp(context, 28f) + setPadding(p, p, p, p) + addView(iconView(context, icon, FAINT, 40f)) + addView(display(context, T(title), 21f, TEXT, 2).apply { gravity = Gravity.CENTER }, lp(context, -2f, -2f, top = 14f, bottom = 8f)) + addView(body(context, T(message)).apply { gravity = Gravity.CENTER; maxWidth = dp(context, 380f) }) + if (actionLabel != null && action != null) { + addView(button(context, actionLabel, Tone.PRIMARY, onClick = action), lp(context, -2f, -2f, top = 18f)) + } + } + + /** A centred spinner with a line under it. */ + fun loading(context: Context, message: String = "Loading..."): LinearLayout = + vbox(context).apply { + gravity = Gravity.CENTER + addView(spinner(context, 34f)) + addView(caption(context, T(message)).apply { setPadding(0, dp(context, 12f), 0, 0) }) + } + + /** A list row: icon, title, detail, then [trailing] or a chevron. Flat; a panel groups them. */ + fun settingsRow( + context: Context, + icon: Icon, + title: String, + detail: String?, + color: Int = MUTED, + trailing: View? = null, + onClick: (() -> Unit)?, + ): LinearLayout = + hbox(context).apply { + minimumHeight = dp(context, 64f) + setPadding(dp(context, 16f), dp(context, 10f), dp(context, 12f), dp(context, 10f)) + background = pressable(context, Color.TRANSPARENT, 8f) + addView(iconView(context, icon, color, 22f)) + val column = vbox(context) + column.setPadding(dp(context, 16f), 0, dp(context, 8f), 0) + column.addView(text(context, T(title), 15.5f, TEXT, MEDIUM, 2)) + if (!detail.isNullOrEmpty()) column.addView(caption(context, T(detail), MUTED, 3).apply { setPadding(0, dp(context, 4f), 0, 0); setLineSpacing(0f, 1.15f) }) + addView(column, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + if (trailing != null) { + addView(trailing) + } else if (onClick != null) { + addView(iconView(context, Icon.CHEVRON, FAINT, 20f)) + } + if (onClick != null) setOnClickListener { onClick() } else isClickable = false + } + + /** A labelled slider over [min]..[max] showing [format] of its value, with optional words for its two ends. */ + fun slider( + context: Context, + label: String, + min: Int, + max: Int, + value: Int, + format: (Int) -> String = { it.toString() }, + ends: Pair? = null, + onChange: (Int) -> Unit, + ): LinearLayout = + vbox(context).apply { + setPadding(0, dp(context, 8f), 0, dp(context, 4f)) + val top = hbox(context) + top.addView(text(context, T(label), 14.5f, TEXT, MEDIUM, 1), LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + val valueView = display(context, format(value), 16f, TEXT) + top.addView(valueView) + addView(top) + val seek = SeekBar(context) + seek.max = max - min + seek.progress = (value - min).coerceIn(0, max - min) + seek.progressTintList = ColorStateList.valueOf(ACCENT) + seek.progressBackgroundTintList = ColorStateList.valueOf(LINE) + seek.thumbTintList = ColorStateList.valueOf(TEXT) + seek.setPadding(dp(context, 6f), dp(context, 12f), dp(context, 6f), dp(context, 8f)) + seek.setOnSeekBarChangeListener( + object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) { + if (!fromUser) return + valueView.text = format(min + progress) + onChange(min + progress) + } + + override fun onStartTrackingTouch(bar: SeekBar) {} + + override fun onStopTrackingTouch(bar: SeekBar) {} + }, + ) + addView(seek, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) + if (ends != null) { + val row = hbox(context) + row.addView(label(context, ends.first), lp(context, 0f, -2f, 1f)) + row.addView(label(context, ends.second)) + addView(row, lp(context, start = 6f, end = 6f)) + } + } + + /** A label with an on/off switch at the end; the whole row toggles. */ + fun toggleRow(context: Context, label: String, detail: String?, checked: Boolean, onChange: (Boolean) -> Unit): LinearLayout = + hbox(context).apply { + minimumHeight = dp(context, 56f) + setPadding(0, dp(context, 6f), 0, dp(context, 6f)) + val column = vbox(context) + column.addView(text(context, T(label), 14.5f, TEXT, MEDIUM, 2)) + if (!detail.isNullOrEmpty()) column.addView(caption(context, T(detail), MUTED, 2).apply { setPadding(0, dp(context, 3f), 0, 0) }) + addView(column, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + val switch = Switch(context) + switch.isOn = checked + addView(switch, switchLp(context)) + background = pressable(context, Color.TRANSPARENT, 8f) + setOnClickListener { + switch.isOn = !switch.isOn + onChange(switch.isOn) + } + } + + fun switchLp(context: Context): LinearLayout.LayoutParams = + LinearLayout.LayoutParams(dp(context, 46f), dp(context, 26f)).apply { marginStart = dp(context, 12f) } + + // --- Layout helpers --- + + fun hbox(context: Context, gravity: Int = Gravity.CENTER_VERTICAL): LinearLayout = + LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + this.gravity = gravity + } + + fun vbox(context: Context): LinearLayout = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL } + + fun space(context: Context, widthDp: Float = 0f, heightDp: Float = 0f): View = + View(context).apply { layoutParams = LinearLayout.LayoutParams(dp(context, widthDp), dp(context, heightDp)) } + + /** A flexible space that pushes what follows to the end of a row. */ + fun spring(context: Context): View = View(context).apply { layoutParams = LinearLayout.LayoutParams(0, 1, 1f) } + + fun lp( + context: Context, + widthDp: Float = -1f, + heightDp: Float = -2f, + weight: Float = 0f, + start: Float = 0f, + top: Float = 0f, + end: Float = 0f, + bottom: Float = 0f, + ): LinearLayout.LayoutParams { + fun size(v: Float) = + when (v) { + -1f -> ViewGroup.LayoutParams.MATCH_PARENT + -2f -> ViewGroup.LayoutParams.WRAP_CONTENT + else -> dp(context, v) + } + return LinearLayout.LayoutParams(size(widthDp), size(heightDp), weight).apply { + marginStart = dp(context, start) + topMargin = dp(context, top) + marginEnd = dp(context, end) + bottomMargin = dp(context, bottom) + } + } + + fun match(): FrameLayout.LayoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + + // --- Formatting --- + + fun number(value: Long): String = NumberFormat.getIntegerInstance().format(value) + + fun number(value: Int): String = number(value.toLong()) + + fun signed(value: Int): String = (if (value > 0) "+" else "") + number(value) + + fun fileSize(bytes: Long): String = + when { + bytes >= 1L shl 30 -> String.format("%.1f GB", bytes / (1L shl 30).toDouble()) + bytes >= 1L shl 20 -> String.format("%.1f MB", bytes / (1L shl 20).toDouble()) + bytes >= 1L shl 10 -> String.format("%.0f KB", bytes / (1L shl 10).toDouble()) + else -> "$bytes B" + } + + /** "just now", "5 min ago", "3 h ago", "2 days ago". */ + fun ago(timeMs: Long?, now: Long = System.currentTimeMillis()): String { + if (timeMs == null || timeMs <= 0) return "" + val seconds = max(0L, (now - timeMs) / 1000) + return when { + seconds < 60 -> T("just now") + seconds < 3600 -> T("%s min ago").format(seconds / 60) + seconds < 86_400 -> T("%s h ago").format(seconds / 3600) + seconds < 86_400 * 60 -> T("%s days ago").format(seconds / 86_400) + else -> java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).format(java.util.Date(timeMs)) + } + } +} + +/** + * A parallelogram leaning forward by [Lx.SLANT_DEGREES]: the launcher's plate shape. The slant is + * taken out of the bounds' own width, so text padded by about a third of the height clears it. + */ +internal class SlantDrawable( + private val fill: Int, + private val stroke: Int, + private val strokeWidth: Float, + cornerRadius: Float, +) : Drawable() { + private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = fill + style = Paint.Style.FILL + if (cornerRadius > 0f) pathEffect = CornerPathEffect(cornerRadius) + } + private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = stroke + style = Paint.Style.STROKE + this.strokeWidth = strokeWidth + if (cornerRadius > 0f) pathEffect = CornerPathEffect(cornerRadius) + } + private val path = Path() + + override fun onBoundsChange(bounds: Rect) { + super.onBoundsChange(bounds) + val inset = if (stroke != 0) strokeWidth / 2f else 0f + val l = bounds.left + inset + val r = bounds.right - inset + val t = bounds.top + inset + val b = bounds.bottom - inset + val lean = ((b - t) * tan(Math.toRadians(Lx.SLANT_DEGREES.toDouble())).toFloat()).coerceAtMost((r - l) / 3f) + path.reset() + path.moveTo(l + lean, t) + path.lineTo(r, t) + path.lineTo(r - lean, b) + path.lineTo(l, b) + path.close() + } + + override fun draw(canvas: Canvas) { + if (Color.alpha(fill) > 0) canvas.drawPath(path, fillPaint) + if (stroke != 0) canvas.drawPath(path, strokePaint) + } + + override fun setAlpha(alpha: Int) { + fillPaint.alpha = alpha + strokePaint.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + fillPaint.colorFilter = colorFilter + strokePaint.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT +} + +/** + * Text tabs, the picked one in white over a slanted green underline. [fill] spreads them across + * the width (two or three tabs); otherwise they keep their own width and scroll sideways. + */ +internal class TabStrip(context: Context, labels: List, fill: Boolean, private val onSelect: (Int) -> Unit) { + private val tabs = ArrayList() + private val scroller: android.widget.HorizontalScrollView? + val view: View + var selected = -1 + private set + + init { + val row = Lx.hbox(context) + labels.forEachIndexed { i, label -> + val tab = Lx.text(context, T(label).uppercase(), 13f, Lx.MUTED, Lx.CONDENSED, 1) + tab.letterSpacing = 0.08f + tab.gravity = Gravity.CENTER + val p = Lx.dp(context, 14f) + tab.setPadding(p, 0, p, 0) + tab.setOnClickListener { + if (selected != i) { + select(i) + onSelect(i) + } + } + tabs += tab + row.addView(tab, if (fill) Lx.lp(context, 0f, 46f, 1f) else Lx.lp(context, -2f, 46f)) + } + if (fill) { + scroller = null + view = row + } else { + scroller = android.widget.HorizontalScrollView(context).apply { + isHorizontalScrollBarEnabled = false + addView(row) + } + view = scroller + } + } + + fun select(index: Int) { + selected = index + tabs.forEachIndexed { i, tab -> + val on = i == index + tab.setTextColor(if (on) Lx.TEXT else Lx.MUTED) + tab.background = if (on) underline(tab.context) else Lx.pressable(tab.context, Color.TRANSPARENT, 6f) + tab.isSelected = on + } + val tab = tabs.getOrNull(index) ?: return + scroller?.post { scroller.smoothScrollTo((tab.left - (scroller.width - tab.width) / 2).coerceAtLeast(0), 0) } + } + + fun setLabel(index: Int, label: String) { + tabs.getOrNull(index)?.text = label.uppercase() + } + + private fun underline(context: Context): Drawable { + val bar = SlantDrawable(Lx.ACCENT, 0, 0f, 0f) + val layers = android.graphics.drawable.LayerDrawable(arrayOf(Lx.pressable(context, Color.TRANSPARENT, 6f), bar)) + layers.setLayerGravity(1, Gravity.BOTTOM or Gravity.FILL_HORIZONTAL) + layers.setLayerHeight(1, Lx.dp(context, 3f)) + layers.setLayerInsetLeft(1, Lx.dp(context, 10f)) + layers.setLayerInsetRight(1, Lx.dp(context, 10f)) + return layers + } +} + +/** The launcher's on/off switch: a squared track that turns green, its knob riding to the end. */ +internal class Switch(context: Context) : View(context) { + var isOn = false + set(value) { + field = value + invalidate() + } + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + + override fun onDraw(canvas: Canvas) { + val w = width.toFloat() + val h = height.toFloat() + val r = Lx.dp(context, 6f).toFloat() + paint.color = if (isOn) Lx.ACCENT else Lx.LINE + canvas.drawRoundRect(0f, 0f, w, h, r, r, paint) + val pad = Lx.dp(context, 3f).toFloat() + val knob = h - pad * 2 + val x = if (isOn) w - pad - knob else pad + paint.color = if (isOn) Lx.ACCENT_TEXT else Lx.MUTED + canvas.drawRoundRect(x, pad, x + knob, pad + knob, r - pad / 2, r - pad / 2, paint) + } +} + +/** A ViewGroup that lays its children out left to right and wraps onto new lines. */ +internal class FlowLayout(context: Context, private val gapPx: Int = Lx.dp(context, 8f)) : ViewGroup(context) { + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val maxWidth = MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight + val unbounded = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED + var x = 0 + var y = 0 + var lineHeight = 0 + var widest = 0 + for (i in 0 until childCount) { + val child = getChildAt(i) + if (child.visibility == GONE) continue + measureChild(child, MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), heightMeasureSpec) + if (!unbounded && x > 0 && x + child.measuredWidth > maxWidth) { + x = 0 + y += lineHeight + gapPx + lineHeight = 0 + } + x += child.measuredWidth + gapPx + widest = max(widest, x - gapPx) + lineHeight = max(lineHeight, child.measuredHeight) + } + val width = if (unbounded) widest else maxWidth + setMeasuredDimension(width + paddingLeft + paddingRight, resolveSize(y + lineHeight + paddingTop + paddingBottom, heightMeasureSpec)) + } + + override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { + val maxWidth = r - l - paddingLeft - paddingRight + var x = 0 + var y = 0 + var lineHeight = 0 + for (i in 0 until childCount) { + val child = getChildAt(i) + if (child.visibility == GONE) continue + if (x > 0 && x + child.measuredWidth > maxWidth) { + x = 0 + y += lineHeight + gapPx + lineHeight = 0 + } + child.layout(paddingLeft + x, paddingTop + y, paddingLeft + x + child.measuredWidth, paddingTop + y + child.measuredHeight) + x += child.measuredWidth + gapPx + lineHeight = max(lineHeight, child.measuredHeight) + } + } +} + +/** + * Equal cells, as many per row as fit [minCellPx] - the Mii part pickers and colour rows, which + * sit inside a scrolling column where a RecyclerView grid would fight the scroll. + */ +internal class GridBox(context: Context, private val minCellPx: Int, private val gapPx: Int, private val ratio: Float = 1f) : ViewGroup(context) { + private var columns = 1 + private var cell = 0 + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight + columns = max(1, (width + gapPx) / (minCellPx + gapPx)) + cell = (width - gapPx * (columns - 1)) / columns + val cellHeight = (cell / ratio).toInt() + val spec = MeasureSpec.makeMeasureSpec(cell, MeasureSpec.EXACTLY) + val hSpec = MeasureSpec.makeMeasureSpec(cellHeight, MeasureSpec.EXACTLY) + var visible = 0 + for (i in 0 until childCount) { + val child = getChildAt(i) + if (child.visibility == GONE) continue + child.measure(spec, hSpec) + visible++ + } + val rows = (visible + columns - 1) / columns + val height = rows * cellHeight + max(0, rows - 1) * gapPx + paddingTop + paddingBottom + setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height) + } + + override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { + val cellHeight = (cell / ratio).toInt() + var index = 0 + for (i in 0 until childCount) { + val child = getChildAt(i) + if (child.visibility == GONE) continue + val col = index % columns + val row = index / columns + val x = paddingLeft + col * (cell + gapPx) + val y = paddingTop + row * (cellHeight + gapPx) + child.layout(x, y, x + cell, y + cellHeight) + index++ + } + } +} + +/** An ImageView that keeps a fixed width:height ratio, sized from its width. */ +internal class AspectImageView(context: Context, private val ratio: Float) : ImageView(context) { + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + setMeasuredDimension(width, (width / ratio).toInt()) + } +} + +/** A FrameLayout that is always as tall as it is wide times [ratio]. */ +internal class AspectFrame(context: Context, private val ratio: Float) : FrameLayout(context) { + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + super.onMeasure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec((width / ratio).toInt(), MeasureSpec.EXACTLY), + ) + } +} + +/** + * The launcher's backdrop: flat asphalt with three faint slanted stripes in the top corner - the + * kart's speed lines, quiet enough to sit behind any page. Static, so it costs nothing. + */ +internal class LauncherBackground(private val compact: Boolean) : Drawable() { + private val stripe = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + + override fun draw(canvas: Canvas) { + canvas.drawColor(Lx.BG) + val b = bounds + val unit = (if (compact) b.width() else b.height()) * 0.09f + val lean = unit * 2.2f + for (i in 0 until 3) { + stripe.color = Lx.alpha(Lx.ACCENT, 0.045f - i * 0.012f) + val x = b.right - unit * (1.6f + i * 1.25f) + path.reset() + path.moveTo(x, b.top.toFloat()) + path.lineTo(x + unit * 0.8f, b.top.toFloat()) + path.lineTo(x + unit * 0.8f - lean, b.top + unit * 5.5f) + path.lineTo(x - lean, b.top + unit * 5.5f) + path.close() + canvas.drawPath(path, stripe) + } + } + + override fun setAlpha(alpha: Int) {} + + override fun setColorFilter(colorFilter: ColorFilter?) {} + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.OPAQUE +} diff --git a/android/app/src/main/kotlin/com/driftdroid/android/ui/RemoteImages.kt b/android/app/src/main/kotlin/com/driftdroid/android/ui/RemoteImages.kt new file mode 100644 index 0000000..62cce22 --- /dev/null +++ b/android/app/src/main/kotlin/com/driftdroid/android/ui/RemoteImages.kt @@ -0,0 +1,142 @@ +package com.driftdroid.android.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.drawable.Drawable +import android.os.Handler +import android.os.Looper +import android.util.LruCache +import android.widget.ImageView +import com.driftdroid.android.mii.MiiStudio +import com.driftdroid.android.mods.GameBanana +import com.driftdroid.android.net.Http +import java.io.File +import java.security.MessageDigest +import java.util.WeakHashMap +import java.util.concurrent.Executors + +/** + * Pictures from the internet for the launcher's lists: GameBanana screenshots and Mii faces. + * A small memory cache in front of a disk cache (cacheDir, so Android can reclaim it), four + * download threads, and at most one request per picture however many rows ask for it. Rows that + * get recycled while their picture is loading never receive someone else's. + */ +internal object RemoteImages { + private val HOSTS = GameBanana.HOSTS + MiiStudio.HOST + private const val DISK_LIMIT_BYTES = 48L shl 20 + private const val MAX_IMAGE_BYTES = 6L shl 20 + private const val RETRY_AFTER_MS = 120_000L + + private val main = Handler(Looper.getMainLooper()) + private val pool = Executors.newFixedThreadPool(4) { r -> Thread(r, "remote-images").apply { isDaemon = true } } + private val memory = + object : LruCache((Runtime.getRuntime().maxMemory() / 10 / 1024).toInt()) { + override fun sizeOf(key: String, value: Bitmap) = value.byteCount / 1024 + } + private val waiting = HashMap Unit>>() + private val failedAt = HashMap() + private val bound = WeakHashMap() + @Volatile private var diskDir: File? = null + + fun init(context: Context) { + if (diskDir != null) return + val dir = File(context.cacheDir, "remote-images") + dir.mkdirs() + diskDir = dir + pool.execute { trim(dir) } + } + + /** Shows [url] in [view] (after [placeholder] while it loads). Main thread only. */ + fun bind(view: ImageView, url: String?, targetPx: Int, placeholder: Drawable?) { + if (url == null) { + bound.remove(view) + view.setImageDrawable(placeholder) + return + } + val key = "$targetPx|$url" + if (bound[view] == key && view.drawable != null && view.drawable !== placeholder) return + bound[view] = key + val cached = memory.get(key) + if (cached != null) { + view.setImageBitmap(cached) + return + } + view.setImageDrawable(placeholder) + load(url, targetPx) { bitmap -> + if (bitmap != null && bound[view] == key) { + view.alpha = 0f + view.setImageBitmap(bitmap) + view.animate().alpha(1f).setDuration(160).start() + } + } + } + + /** Forgets what [view] was showing, so a late picture can't land in it. */ + fun clear(view: ImageView) { + bound.remove(view) + } + + /** Fetches [url] scaled down to about [targetPx]; [done] runs on the main thread. */ + fun load(url: String, targetPx: Int, done: (Bitmap?) -> Unit) { + val key = "$targetPx|$url" + memory.get(key)?.let { + done(it) + return + } + val failed = failedAt[key] + if (failed != null && System.currentTimeMillis() - failed < RETRY_AFTER_MS) { + done(null) + return + } + val list = waiting[key] + if (list != null) { + list.add(done) + return + } + waiting[key] = mutableListOf(done) + pool.execute { + val bitmap = runCatching { fetch(url, targetPx) }.getOrNull() + main.post { + if (bitmap != null) memory.put(key, bitmap) else failedAt[key] = System.currentTimeMillis() + waiting.remove(key)?.forEach { it(bitmap) } + } + } + } + + private fun fetch(url: String, targetPx: Int): Bitmap? { + val dir = diskDir + val file = dir?.let { File(it, sha1(url)) } + val bytes = + if (file != null && file.isFile) { + file.setLastModified(System.currentTimeMillis()) + file.readBytes() + } else { + val downloaded = Http.getBytes(url, HOSTS, MAX_IMAGE_BYTES, "image/*") + if (file != null) runCatching { file.writeBytes(downloaded) } + downloaded + } + return decode(bytes, targetPx) + } + + private fun decode(bytes: ByteArray, targetPx: Int): Bitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0) return null + var sample = 1 + while (bounds.outWidth / (sample * 2) >= targetPx && bounds.outHeight / (sample * 2) >= targetPx / 2) sample *= 2 + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) + } + + private fun trim(dir: File) { + val files = dir.listFiles()?.sortedByDescending { it.lastModified() } ?: return + var total = 0L + for (file in files) { + total += file.length() + if (total > DISK_LIMIT_BYTES) file.delete() + } + } + + private fun sha1(text: String): String = + MessageDigest.getInstance("SHA-1").digest(text.toByteArray()).joinToString("") { "%02x".format(it) } +} diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml index 1fdb0c8..62c6d8a 100644 --- a/android/app/src/main/res/values/colors.xml +++ b/android/app/src/main/res/values/colors.xml @@ -4,4 +4,6 @@ #F07C1E #35C3F0 #2A2A2A + + #0C0E11 diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml index 2da2298..e6f3ac5 100644 --- a/android/app/src/main/res/values/themes.xml +++ b/android/app/src/main/res/values/themes.xml @@ -8,10 +8,11 @@ @android:color/white @color/wii_orange @android:color/white - - @color/driftdroid_gray_dark - @color/driftdroid_gray_dark + + @color/launcher_bg + @color/launcher_bg + @color/launcher_bg false diff --git a/android/app/src/test/kotlin/com/driftdroid/android/MiiAndFriendCodeTest.kt b/android/app/src/test/kotlin/com/driftdroid/android/MiiAndFriendCodeTest.kt new file mode 100644 index 0000000..a126120 --- /dev/null +++ b/android/app/src/test/kotlin/com/driftdroid/android/MiiAndFriendCodeTest.kt @@ -0,0 +1,92 @@ +package com.driftdroid.android + +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiStudio +import com.driftdroid.android.profile.FriendCode +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class MiiAndFriendCodeTest { + // A public Mii as Retro WFC's /api/roomstatus lists it (player "aubrey."). + private val roomMii = "wA4AYQB1AGIAcgBlAHkALgAAAAAAAEMngAAAAAAAAAAAPXnAmbkGoniLqFgURnyNAIoAioVUAAAAAAAAAAAAAAAAAAAAAAAAAAA=" + + @Test + fun friendCodesMatchRetroWfc() { + // Profile id / friend code pairs exactly as Retro WFC's API reports them. + assertEquals("4123-1699-9123", FriendCode.format(138707)) + assertEquals("3137-3137-3137", FriendCode.format(198760529)) + assertEquals("0001-0010-0100", FriendCode.format(100100100)) + assertEquals(138707L, FriendCode.toProfileId("4123 1699 9123")) + assertEquals(0L, FriendCode.toProfileId("4123-1699-9124")) + assertEquals(0L, FriendCode.toProfileId("123")) + assertEquals("", FriendCode.format(0)) + assertNull(FriendCode.normalize("0000-0000-0000")) + } + + @Test + fun decodesARealMii() { + val mii = Mii.fromBase64(roomMii) + assertNotNull(mii) + assertEquals("aubrey.", mii!!.name) + assertTrue(mii.isGirl) + } + + @Test + fun editingOneFieldLeavesEveryOtherBitAlone() { + val original = Mii.fromBase64(roomMii)!! + val edited = original.copy() + val before = edited.hairColor + edited.hairColor = (before + 1) % Mii.HAIR_COLORS.size + edited.hairColor = before + assertArrayEquals(original.data, edited.data) + + edited.eyeType = 47 + assertEquals(47, edited.eyeType) + assertEquals(original.eyeColor, edited.eyeColor) + assertEquals(original.eyeSpacing, edited.eyeSpacing) + assertEquals(original.browType, edited.browType) + edited.eyeType = 99 // clamped to the editor's range + assertEquals(47, edited.eyeType) + } + + @Test + fun namesRoundTrip() { + val mii = Mii.blank() + mii.name = "Zoë☆12345678" + assertEquals("Zoë☆123456", mii.name) + mii.creatorName = "" + assertEquals("", mii.creatorName) + } + + @Test + fun emptySlotsAreNotMiis() { + assertNull(Mii.fromBytes(ByteArray(Mii.RECORD_BYTES))) + assertNull(Mii.fromBytes(ByteArray(Mii.RECORD_BYTES) { 0xFF.toByte() })) + assertNull(Mii.fromBytes(ByteArray(10))) + } + + @Test + fun newMiiIdsAreUniqueAndNormal() { + val now = 1_760_000_000_000L + val first = Mii.newMiiId(emptySet(), now) + val second = Mii.newMiiId(setOf(first), now) + assertTrue(first != second) + assertEquals(0b100L, first shr 29) + } + + @Test + fun studioDataHasTheRendererShape() { + val mii = Mii.fromBase64(roomMii)!! + val encoded = MiiStudio.encode(mii) + assertEquals(94, encoded.length) + assertTrue(encoded.startsWith("00")) + // Written out so the URL can be checked against the live renderer by hand. + File("build/test-out").mkdirs() + File("build/test-out/studio_url.txt").writeText(MiiStudio.imageUrl(mii, MiiStudio.Size.LARGE) + "\n") + } +} diff --git a/android/app/src/test/kotlin/com/driftdroid/android/OnlineAndSaveFormatsTest.kt b/android/app/src/test/kotlin/com/driftdroid/android/OnlineAndSaveFormatsTest.kt new file mode 100644 index 0000000..66460da --- /dev/null +++ b/android/app/src/test/kotlin/com/driftdroid/android/OnlineAndSaveFormatsTest.kt @@ -0,0 +1,315 @@ +package com.driftdroid.android + +import com.driftdroid.android.mii.Mii +import com.driftdroid.android.mii.MiiDatabase +import com.driftdroid.android.mods.ArchiveExtractor +import com.driftdroid.android.mods.GameBanana +import com.driftdroid.android.online.RetroWfc +import com.driftdroid.android.profile.FriendCode +import com.driftdroid.android.profile.SaveFile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.io.File +import java.nio.ByteBuffer +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +/** Synthetic data only: the shapes of the real responses and files, none of anyone's details. */ +class OnlineAndSaveFormatsTest { + private val sampleMii: Mii = + Mii.blank().apply { + name = "Tester" + miiId = 0x80001234L + systemId = 0x11223344L + } + + // --- Retro WFC --- + + @Test + fun parsesRoomsAndSkipsNullsAndSuspensions() { + val json = + """ + {"rooms":[ + {"id":"AAAAAA","type":"anybody","roomType":"Retro Tracks","created":"2026-01-01T10:00:00.1234567Z","rk":"vs_10", + "averageVR":12000,"isPublic":true,"isJoinable":true,"race":{"num":5,"course":300,"cc":2,"trackName":"Test Track"}, + "players":[ + {"pid":"1","name":"One","friendCode":"0000-0000-0001","vr":15000,"br":null,"isOpenHost":true, + "mii":{"data":"${java.util.Base64.getEncoder().encodeToString(sampleMii.data)}","name":"One"},"connectionMap":["1"]}, + {"pid":"2","name":"Two","friendCode":"0000-0000-0002","vr":9000,"isSuspended":false,"connectionMap":["1"]}, + {"pid":"3","name":"Banned","isSuspended":true} + ]}, + {"id":"BBBBBB","type":"private","roomType":null,"created":null,"isPublic":false,"players":[]}, + {"id":"CCCCCC","type":"anybody","isSuspended":true,"players":[{"pid":"9"}]} + ],"totalPlayers":2} + """.trimIndent() + val status = RetroWfc.parseRooms(json, 42L) + assertEquals(2, status.rooms.size) + assertEquals(2, status.totalPlayers) + val room = status.rooms[0] + assertEquals("Retro Tracks", room.label) + assertEquals("Test Track", room.race?.trackName) + assertEquals(2, room.players.size) + assertNull(room.players[0].br) + assertEquals("Tester", room.players[0].mii?.name) + assertEquals("Private room", status.rooms[1].label) + assertEquals(1, status.activeRooms.size) + assertNotNull(room.createdAt) + } + + @Test + fun splitsRoomsWhosePlayersCannotSeeEachOther() { + fun player(id: String, map: List) = RetroWfc.Player(id, id, "", null, null, false, null, map) + // Players 0-1 see each other, 2-3 see each other, nobody across: two rooms reported as one. + val merged = + RetroWfc.Room( + "R", "anybody", null, null, null, + listOf( + player("a", listOf("0", "1", "0", "0")), + player("b", listOf("1", "0", "0", "0")), + player("c", listOf("0", "0", "0", "1")), + player("d", listOf("0", "0", "1", "0")), + ), + null, null, true, true, + ) + val parts = RetroWfc.splitMergedRoom(merged) + assertEquals(2, parts.size) + assertEquals(listOf("a", "b"), parts[0].players.map { it.pid }) + assertEquals(listOf("c", "d"), parts[1].players.map { it.pid }) + // No connection info: left alone. + val unknown = RetroWfc.Room("R", "anybody", null, null, null, listOf(player("a", emptyList()), player("b", emptyList())), null, null, true, true) + assertEquals(1, RetroWfc.splitMergedRoom(unknown).size) + } + + @Test + fun parsesLeaderboardAndHistory() { + val top = + RetroWfc.parseLeaderboard( + """[{"pid":"5","name":"Fast","friendCode":"1111-2222-3333","vr":200000,"rank":1,"lastSeen":"2026-02-01T00:00:00Z", + "vrStats":{"last24Hours":-50,"lastWeek":300,"lastMonth":900},"miiData":null,"vehiclePreference":"bike"}]""", + ) + assertEquals(1, top.size) + assertEquals(200000, top[0].vr) + assertEquals(-50, top[0].vr24h) + assertNull(top[0].mii) + assertEquals("bike", top[0].vehiclePreference) + val history = + RetroWfc.parseHistory( + """{"history":[{"date":"2026-02-02T00:00:00Z","totalVR":110},{"date":"2026-02-01T00:00:00Z","totalVR":100},{"date":"bad","totalVR":1}]}""", + ) + assertEquals(listOf(100, 110), history.map { it.totalVr }) + assertNull(RetroWfc.parseTime("not a date")) + } + + // --- GameBanana --- + + @Test + fun parsesGameBananaListingsAndDetails() { + val list = + GameBanana.parseList( + """{"_aMetadata":{"_nRecordCount":2,"_nPerpage":20,"_bIsComplete":true},"_aRecords":[ + {"_idRow":10,"_sModelName":"Mod","_sName":"Skin","_aSubmitter":{"_sName":"Maker"},"_aRootCategory":{"_sName":"Skins"}, + "_aPreviewMedia":{"_aImages":[{"_sBaseUrl":"https://images.gamebanana.com/img/ss/mods","_sFile":"a.jpg","_sFile220":"220-90_a.jpg"}]}, + "_nLikeCount":3,"_nViewCount":40,"_tsDateAdded":1700000000}, + {"_idRow":11,"_sModelName":"Question","_sName":"Not a mod"}]}""", + ) + assertTrue(list.complete) + assertEquals(1, list.mods.size) + val mod = list.mods[0] + assertEquals("https://images.gamebanana.com/img/ss/mods/220-90_a.jpg", mod.thumbnailUrl) + assertEquals(1_700_000_000_000L, mod.addedAt) + + val details = + GameBanana.parseDetails( + org.json.JSONObject( + """{"_idRow":10,"_sName":"Skin","_sText":"Hi","_sVersion":"1.2","_nDownloadCount":7, + "_aSubmitter":{"_sName":"Maker"},"_aCategory":{"_sName":"Mario"}, + "_aPreviewMedia":{"_aImages":[{"_sBaseUrl":"https://images.gamebanana.com/img/ss/mods","_sFile":"a.jpg","_sFile530":"530-90_a.jpg"}, + {"_sBaseUrl":"https://evil.example.com","_sFile":"x.jpg"}]}, + "_aFiles":[{"_idRow":99,"_sFile":"skin.rar","_nFilesize":1234,"_sDownloadUrl":"https://gamebanana.com/dl/99"}, + {"_idRow":98,"_sFile":"readme.txt","_nFilesize":10,"_sDownloadUrl":"https://gamebanana.com/dl/98"}]}""", + ), + ) + assertEquals(listOf("https://images.gamebanana.com/img/ss/mods/530-90_a.jpg"), details.screenshots) + assertEquals(2, details.files.size) + assertTrue(details.files[0].isArchive) + assertFalse(details.files[1].isArchive) + assertEquals("1.2", details.version) + } + + @Test + fun downloadsMayOnlyGoToGameBananaOverHttps() { + val hosts = GameBanana.HOSTS + assertTrue(com.driftdroid.android.net.Http.isAllowed("https://gamebanana.com/dl/1", hosts)) + assertTrue(com.driftdroid.android.net.Http.isAllowed("https://filecache53.gamebanana.com/mods/x.rar", hosts)) + assertTrue(com.driftdroid.android.net.Http.isAllowed("https://images.gamebanana.com/img/a.jpg", hosts)) + assertFalse(com.driftdroid.android.net.Http.isAllowed("http://files.gamebanana.com/mods/x.rar", hosts)) + assertFalse(com.driftdroid.android.net.Http.isAllowed("https://evilgamebanana.com/x.rar", hosts)) + assertFalse(com.driftdroid.android.net.Http.isAllowed("https://gamebanana.com.evil.example/x.rar", hosts)) + } + + // --- Mii database --- + + private fun emptyDatabase(): ByteArray { + val db = ByteArray(MiiDatabase.DATABASE_BYTES) + "RNOD".toByteArray().copyInto(db) + MiiDatabase.fixCrc(db) + return db + } + + @Test + fun miiDatabaseSlotsKeepItValid() { + val db = emptyDatabase() + assertTrue(MiiDatabase.isValid(db)) + assertEquals(0, MiiDatabase.firstFreeSlot(db)) + val withOne = MiiDatabase.withSlot(db, 0, sampleMii) + assertTrue(MiiDatabase.isValid(withOne)) + assertEquals(1, MiiDatabase.firstFreeSlot(withOne)) + val snapshot = MiiDatabase.Snapshot(withOne) + assertEquals("Tester", snapshot.byMiiId(0x80001234L)?.mii?.name) + assertEquals(0x11223344L, snapshot.systemId) + val cleared = MiiDatabase.withSlot(withOne, 0, null) + assertTrue(MiiDatabase.isValid(cleared)) + assertEquals(0, MiiDatabase.Snapshot(cleared).slots.size) + // A flipped byte is caught. + val broken = withOne.copyOf() + broken[100] = (broken[100] + 1).toByte() + assertFalse(MiiDatabase.isValid(broken)) + } + + @Test + fun adoptedMiisGetAFreshIdAndThisConsole() { + val snapshot = MiiDatabase.Snapshot(MiiDatabase.withSlot(emptyDatabase(), 0, sampleMii)) + val visitor = sampleMii.copy().apply { systemId = 0x99999999L } + val adopted = MiiDatabase.adopt(snapshot, visitor) + assertTrue(adopted.miiId != sampleMii.miiId) + assertEquals(0x11223344L, adopted.systemId) + assertEquals("Tester", adopted.name) + } + + // --- Save file --- + + private fun syntheticSave(profileId: Long): ByteArray { + val save = ByteArray(0x2BC000) + "RKSD0006".toByteArray().copyInto(save) + val base = 0x08 + "RKPD".toByteArray().copyInto(save, base) + val name = "Racer" + name.forEachIndexed { i, c -> + save[base + 0x14 + i * 2] = (c.code shr 8).toByte() + save[base + 0x15 + i * 2] = c.code.toByte() + } + ByteBuffer.wrap(save).putInt(base + 0x28, sampleMii.miiId.toInt()) + ByteBuffer.wrap(save).putInt(base + 0x5C, profileId.toInt()) + ByteBuffer.wrap(save).putShort(base + 0xB0, 7000.toShort()) + ByteBuffer.wrap(save).putInt(base + 0xB4, 12) + SaveFile.fixChecksum(save) + return save + } + + @Test + fun readsLicensesAndEditsFriendsSafely() { + val save = syntheticSave(100100100) + assertNull(SaveData.validate(save)) + val miis = MiiDatabase.Snapshot(MiiDatabase.withSlot(emptyDatabase(), 0, sampleMii)) + val parsed = SaveFile.parse(save, SaveData.Game.MarioKartWii, miis, emptyMap()) + assertEquals(1, parsed.licenses.size) + val license = parsed.licenses[0] + assertEquals("Racer", license.name) + assertEquals("0001-0010-0100", license.friendCode) + assertEquals(7000, license.vr) + assertEquals(12L, license.races) + assertEquals("Tester", license.mii?.name) + + val friendCode = FriendCode.format(138707) + SaveFile.applyAddFriend(save, SaveData.Game.RetroRewind, 0, friendCode, sampleMii, 143211, null) + SaveFile.fixChecksum(save) + assertNull(SaveData.validate(save)) + val withFriend = SaveFile.parse(save, SaveData.Game.RetroRewind, null, emptyMap()).licenses[0].friends + assertEquals(1, withFriend.size) + assertEquals(friendCode, withFriend[0].friendCode) + assertTrue(withFriend[0].pending) + assertEquals(143200, withFriend[0].vr) // stored in hundreds + assertEquals(5000, withFriend[0].br) + + try { + SaveFile.applyAddFriend(save, SaveData.Game.RetroRewind, 0, friendCode, sampleMii, null, null) + fail("a duplicate friend must be refused") + } catch (_: java.io.IOException) { + } + try { + SaveFile.applyAddFriend(save, SaveData.Game.RetroRewind, 0, "0001-0010-0100", sampleMii, null, null) + fail("a license's own code must be refused") + } catch (_: java.io.IOException) { + } + + SaveFile.applyRemoveFriend(save, 0, 138707) + assertEquals(0, SaveFile.parse(save, SaveData.Game.RetroRewind, null, emptyMap()).licenses[0].friends.size) + + val other = sampleMii.copy().apply { + name = "Renamed" + miiId = 0x80005678L + } + SaveFile.applySetLicenseMii(save, 0, other) + val renamed = SaveFile.parse(save, SaveData.Game.MarioKartWii, null, emptyMap()).licenses[0] + assertEquals("Renamed", renamed.name) + assertEquals(0x80005678L, renamed.miiId) + } + + @Test + fun readsRetroRewindRatings() { + val bytes = ByteArray(8 + 16 * 100) + val b = ByteBuffer.wrap(bytes) + b.putInt(0, 0x52525254).putShort(4, 1).putShort(6, 100) + b.putInt(8, 138707).putFloat(12, 1432.95f).putFloat(16, 50f).putInt(20, 1) + b.putInt(24, 5).putFloat(28, 1f).putFloat(32, 1f).putInt(36, 0) // no data flag: ignored + val ratings = SaveFile.RrRatings.parse(bytes) + assertEquals(1, ratings.size) + assertEquals(1432.95f, ratings[138707L]!!.first, 0.001f) + assertTrue(SaveFile.RrRatings.parse(ByteArray(10)).isEmpty()) + } + + // --- Archives --- + + @Test + fun archiveEntriesCannotEscape() { + val root = File("build/test-out/archive-root").canonicalFile + root.mkdirs() + assertNull(ArchiveExtractor.safeTarget(root, "../evil.szs")) + assertNull(ArchiveExtractor.safeTarget(root, "a/../../evil.szs")) + assertNull(ArchiveExtractor.safeTarget(root, "")) + assertEquals(File(root, "Race/Course/x.szs").canonicalPath, ArchiveExtractor.safeTarget(root, "/Race\\Course/x.szs")!!.canonicalPath) + } + + @Test + fun unpacksAZipAndKnowsTheFormats() { + val dir = File("build/test-out/zip-test") + dir.deleteRecursively() + dir.mkdirs() + val zip = File(dir, "mod.zip") + ZipOutputStream(zip.outputStream()).use { out -> + out.putNextEntry(ZipEntry("My Mod/Race_E.szs")) + out.write(byteArrayOf(1, 2, 3)) + out.closeEntry() + out.putNextEntry(ZipEntry("../outside.txt")) + out.write(byteArrayOf(9)) + out.closeEntry() + } + assertEquals(ArchiveExtractor.Format.ZIP, ArchiveExtractor.sniff(zip)) + val dest = File(dir, "out") + ArchiveExtractor.extract(zip, dest) + assertTrue(File(dest, "My Mod/Race_E.szs").isFile) + assertFalse(File(dir, "outside.txt").exists()) + + val rar = File(dir, "x.rar").apply { writeBytes(byteArrayOf(0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00)) } + assertEquals(ArchiveExtractor.Format.RAR, ArchiveExtractor.sniff(rar)) + val sevenZip = File(dir, "x.7z").apply { writeBytes(byteArrayOf(0x37, 0x7A, 0xBC.toByte(), 0xAF.toByte(), 0x27, 0x1C, 0, 3)) } + assertEquals(ArchiveExtractor.Format.SEVEN_ZIP, ArchiveExtractor.sniff(sevenZip)) + val text = File(dir, "x.txt").apply { writeText("hello") } + assertEquals(ArchiveExtractor.Format.UNKNOWN, ArchiveExtractor.sniff(text)) + } +} diff --git a/android/app/src/test/kotlin/com/driftdroid/android/RetroRewindPatchesTest.kt b/android/app/src/test/kotlin/com/driftdroid/android/RetroRewindPatchesTest.kt new file mode 100644 index 0000000..ca74335 --- /dev/null +++ b/android/app/src/test/kotlin/com/driftdroid/android/RetroRewindPatchesTest.kt @@ -0,0 +1,94 @@ +package com.driftdroid.android + +import com.driftdroid.android.mods.RetroRewindPatches +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RetroRewindPatchesTest { + private fun withTemp(block: (File) -> Unit) { + val root = Files.createTempDirectory("rrpatches").toFile() + try { + block(root) + } finally { + root.deleteRecursively() + } + } + + private fun file(dir: File, path: String, text: String = path): File = + File(dir, path).apply { + parentFile.mkdirs() + writeText(text) + } + + @Test + fun archiveOverridesAreRecognisedTheWayWheelWizardDoes() { + assertTrue(RetroRewindPatches.isArchiveOverride("SteamDeckButtonPrompts.race.szs")) + assertFalse(RetroRewindPatches.isArchiveOverride("Race_U.szs")) + assertFalse(RetroRewindPatches.isArchiveOverride(".race.szs")) + assertFalse(RetroRewindPatches.isArchiveOverride("wr.brres")) + assertEquals("Name.race.szs", RetroRewindPatches.stripPriority("12.Name.race.szs")) + assertEquals("Name.race.szs", RetroRewindPatches.stripPriority("Name.race.szs")) + } + + @Test + fun enabledModsAreFlattenedTopMostWinningWithNumberedOverrides() = + withTemp { root -> + val top = File(root, "mods/Top") + val lower = File(root, "mods/Lower") + file(top, "race/la_kart-wr.szs", "top") + file(top, "Prompts.race.szs", "top override") + file(top, ".driftdroid_mod.json") + file(lower, "deep/folder/la_kart-wr.szs", "lower") + file(lower, "Prompts.race.szs", "lower override") + file(lower, "__MACOSX/._junk.szs") + val riivo = File(root, "mods/Riivo") + file(riivo, "riivolution/pack.xml", "") + file(riivo, "Pack/la_kart-wr.szs", "riivolution") + + val patches = File(root, "RetroRewind6/Patches") + val placed = RetroRewindPatches.sync(listOf(top, riivo, lower), patches) + + assertEquals(setOf("la_kart-wr.szs", "0.Prompts.race.szs", "2.Prompts.race.szs"), placed) + // A plain file clash: the top mod's copy is the one in place. + assertEquals("top", File(patches, "la_kart-wr.szs").readText()) + // Archive overrides from both mods stay, each numbered by its mod's place. + assertEquals("top override", File(patches, "0.Prompts.race.szs").readText()) + assertEquals("lower override", File(patches, "2.Prompts.race.szs").readText()) + } + + @Test + fun turningModsOffRemovesOnlyWhatTheAppPutThere() = + withTemp { root -> + val mod = File(root, "mods/Mod") + file(mod, "Mod.race.szs") + val patches = File(root, "RetroRewind6/Patches") + file(patches, "SomeoneElses.szs", "keep me") + RetroRewindPatches.sync(listOf(mod), patches) + assertTrue(File(patches, "0.Mod.race.szs").isFile) + + RetroRewindPatches.sync(emptyList(), patches) + assertFalse(File(patches, "0.Mod.race.szs").exists()) + assertEquals("keep me", File(patches, "SomeoneElses.szs").readText()) + } + + @Test + fun usEnglishUiArchivesGetAEuropeanTwin() = + withTemp { root -> + file(root, "Race_U.szs", "us race") + file(root, "MenuSingle_U.szs", "us menu") + file(root, "MenuSingle_E.szs", "pal menu") + file(root, "Prompts.race_u.szs", "override") + + assertEquals(1, RetroRewindPatches.addRegionTwins(root)) + assertEquals("us race", File(root, "Race_E.szs").readText()) + // The mod's own PAL file is never replaced, and archive overrides keep their names. + assertEquals("pal menu", File(root, "MenuSingle_E.szs").readText()) + assertFalse(File(root, "Prompts.race_e.szs").exists()) + // Running again makes nothing new. + assertEquals(0, RetroRewindPatches.addRegionTwins(root)) + } +} diff --git a/android/app/src/test/kotlin/com/driftdroid/android/RiivolutionChoicesTest.kt b/android/app/src/test/kotlin/com/driftdroid/android/RiivolutionChoicesTest.kt new file mode 100644 index 0000000..280428b --- /dev/null +++ b/android/app/src/test/kotlin/com/driftdroid/android/RiivolutionChoicesTest.kt @@ -0,0 +1,75 @@ +package com.driftdroid.android + +import com.driftdroid.android.mods.RiivolutionChoices +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RiivolutionChoicesTest { + private val xml = + """ + + + +
+ + +
+
+ +
+ """.trimIndent() + + @Test + fun optionsAreTurnedOnAtTheirFirstChoiceOrTheirOwnDefault() { + val choices = RiivolutionChoices.choicesFor(xml) + // No id: Dolphin's key is the section's name followed by the option's name. + assertEquals(1, choices["CharactersBaby Rosalina"]) + assertEquals(2, choices["karts"]) + assertFalse("an option without choices has nothing to turn on", choices.containsKey("CharactersNothing to pick")) + } + + @Test + fun configIsWrittenOnceInTheFormatTheLoaderReads() { + val root = Files.createTempDirectory("riivo").toFile() + try { + File(root, "riivolution").mkdirs() + File(root, "riivolution/mod.xml").writeText(xml) + assertTrue(RiivolutionChoices.ensure(root)) + val config = RiivolutionChoices.configFile(root) + assertEquals(File(root, "riivolution/config/RMCP.xml"), config) + val text = config.readText() + assertTrue(text.contains("")) + assertTrue(text.contains("