diff --git a/AGENTS.md b/AGENTS.md index af13fbeb6..b2cfd6402 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ file is missing from the index. - [Splash screen (ui.activities.SplashActivity + core.splash + drawable-nodpi/splash_bg_*)](docs/agents/splash-screen.md) - [Launch tab layout & news removal](docs/agents/launch-tab-layout-news-removal.md) - [Mod Hub (org.chimeramc.client.ui.activities.ModHubActivity + core.modrinth + core.downloads)](docs/agents/mod-hub.md) +- [CurseForge tab (CaramelCurseForgeTab + CurseForgeSections + core.curseforge)](docs/agents/caramel-curseforge-tab.md) - [Controller illustrations (ui.views.ControllerIllustrationView)](docs/agents/controller-illustrations-ui-views-controllerillustrationview.md) - [Mod load diagnostics & crash-loop safe mode (core.mods.ModLoadDiagnostics + ModSafeMode)](docs/agents/mod-load-diagnostics-crash-loop-safe-mode.md) - [Per-instance mod sets & the hero "N active" stat (core.mods.ModManager + MainActivity)](docs/agents/per-instance-mod-sets-the-hero-n-active-stat.md) diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeBrowser.java b/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeBrowser.java index 2005327d9..8a182be6d 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeBrowser.java +++ b/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeBrowser.java @@ -7,6 +7,7 @@ import org.chimeramc.client.core.curseforge.models.ContentFile; import org.chimeramc.client.core.curseforge.models.ContentSearchResponse; import org.chimeramc.client.ui.compose.caramel.CaramelCurseForgeItem; +import org.chimeramc.client.ui.compose.caramel.CurseForgeSectionsKt; import org.chimeramc.client.util.AppExecutors; import org.chimeramc.client.util.AppLog; import org.chimeramc.client.util.MainThread; @@ -49,11 +50,17 @@ public interface DownloadListener { void onError(String message); } - /** Searches by free text, newest-download ranking, and reports a mapped list. */ - public static void search(Context context, String query, SearchListener listener) { + /** + * Browses or searches one catalogue section and reports a mapped list. + * + *
An empty [query] is a browse, not an error: it is what the tab shows before anyone types
+ * anything. [classId] is the section's CurseForge class, with 0 meaning "every section" — the
+ * same convention {@link CurseForgeClient#searchContent} uses.
+ */
+ public static void search(Context context, String query, int classId, SearchListener listener) {
CurseForgeClient.getInstance(context).searchContent(
query == null ? "" : query,
- 0,
+ classId,
null,
0,
PAGE_SIZE,
@@ -68,7 +75,7 @@ public void onSuccess(ContentSearchResponse result) {
rows.add(toItem(content));
}
}
- main(() -> listener.onResults(rows));
+ main(() -> listener.onResults(CurseForgeSectionsKt.sortedByDownloads(rows)));
}
@Override
diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeClient.java b/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeClient.java
index 661fa28c0..f8c9a4cee 100644
--- a/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeClient.java
+++ b/app/src/main/java/org/chimeramc/client/launcher/core/curseforge/CurseForgeClient.java
@@ -95,10 +95,12 @@ private static IOException describeFailure(Response response) {
return new IOException("Unexpected response from CurseForge: HTTP " + code);
}
- public void searchContent(String query, int classId, String version, int index, int pageSize,
- String sortField, String sortOrder,
- CurseForgeCallback The menu itself is drawn natively (Dear ImGui), and until this button existed the only way to
* open it was the keyboard or controller bind — a phone with neither had no entry point at all, and
- * the "Open the Mod Menu" description had nothing to describe. The glyph is the Caramel apple, the
- * same mark the launcher wears, so the button reads as the client's own.
+ * the "Open the Mod Menu" description had nothing to describe.
*/
public class ModMenuButtonOverlay extends BaseOverlayButton {
@@ -25,9 +24,19 @@ protected String getModId() {
return ModIds.MOD_MENU;
}
+ /**
+ * The drawable the floating button wears.
+ *
+ * A plain three-bar handle, not the client's apple: the button sits on top of the game and
+ * every screenshot, and the brand mark there announced the client rather than the menu.
+ */
+ static int iconResource() {
+ return R.drawable.mod_menu_handle;
+ }
+
@Override
protected int getIconResource() {
- return R.drawable.mod_menu_icon;
+ return iconResource();
}
@Override
diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/versions/ArchiveExtractor.java b/app/src/main/java/org/chimeramc/client/launcher/core/versions/ArchiveExtractor.java
new file mode 100644
index 000000000..93a368cf8
--- /dev/null
+++ b/app/src/main/java/org/chimeramc/client/launcher/core/versions/ArchiveExtractor.java
@@ -0,0 +1,78 @@
+package org.chimeramc.client.core.versions;
+
+import org.chimeramc.client.util.AppLog;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.function.IntConsumer;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+/**
+ * Unpacks a game package (XAPK, APK-as-zip or instance zip) into a scratch directory.
+ *
+ * Split out of {@code VersionManager} so the one part of an import that parses hostile input —
+ * an archive from anywhere on the device — is small enough to read in one sitting. Entries that
+ * resolve outside the output directory are skipped rather than written, so a crafted name such as
+ * {@code ../../files/x.apk} cannot place a file outside the app's own scratch space.
+ */
+final class ArchiveExtractor {
+
+ private static final String TAG = "ArchiveExtractor";
+ private static final int BUFFER_SIZE = 8192;
+
+ private ArchiveExtractor() {
+ }
+
+ /** Reports 10 to 50 percent, the share of the import this step owns. */
+ static void extract(File archive, File outputDir, IntConsumer onProgress) throws IOException {
+ try (ZipInputStream zis = new ZipInputStream(
+ new BufferedInputStream(new FileInputStream(archive)))) {
+ int totalEntries = Math.max(1, countEntries(archive));
+ int processed = 0;
+ ZipEntry entry;
+
+ while ((entry = zis.getNextEntry()) != null) {
+ if (ImportedPackageLayout.isUnsafeEntry(entry.getName())) {
+ AppLog.warnOnce(TAG, "unsafe-entry",
+ "Skipped an archive entry that points outside the import directory", null);
+ zis.closeEntry();
+ continue;
+ }
+ File outputFile = new File(outputDir, entry.getName());
+ if (entry.isDirectory()) {
+ outputFile.mkdirs();
+ } else {
+ File parent = outputFile.getParentFile();
+ if (parent != null) parent.mkdirs();
+ try (FileOutputStream out = new FileOutputStream(outputFile)) {
+ byte[] buffer = new byte[BUFFER_SIZE];
+ int len;
+ while ((len = zis.read(buffer)) > 0) {
+ out.write(buffer, 0, len);
+ }
+ }
+ }
+
+ processed++;
+ onProgress.accept(10 + (processed * 40 / totalEntries));
+ zis.closeEntry();
+ }
+ }
+ }
+
+ private static int countEntries(File zipFile) throws IOException {
+ int count = 0;
+ try (ZipInputStream zis = new ZipInputStream(
+ new BufferedInputStream(new FileInputStream(zipFile)))) {
+ while (zis.getNextEntry() != null) {
+ count++;
+ zis.closeEntry();
+ }
+ }
+ return count;
+ }
+}
diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/versions/ImportedPackageLayout.java b/app/src/main/java/org/chimeramc/client/launcher/core/versions/ImportedPackageLayout.java
new file mode 100644
index 000000000..dacda9ca3
--- /dev/null
+++ b/app/src/main/java/org/chimeramc/client/launcher/core/versions/ImportedPackageLayout.java
@@ -0,0 +1,203 @@
+package org.chimeramc.client.core.versions;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Turns an unpacked game package into the shape {@code VersionManager} installs.
+ *
+ * Two package layouts reach the importer and only one used to work. A single {@code .apk} was
+ * copied to {@code apk/base.apk}; an {@code .xapk} (or a {@code .zip} an instance was exported to)
+ * unpacks to its own layout — {@code base.apk}, {@code split_config.*.apk},
+ * {@code Android/obb/ This class collects the parts wherever they were extracted and puts them where the installer
+ * looks. It is plain {@code java.io} so the layout rules are unit-tested against a real directory
+ * tree rather than a device.
+ */
+public final class ImportedPackageLayout {
+
+ public static final String APK_DIR = "apk";
+ public static final String OBB_DIR = "obb";
+ public static final String BASE_APK = "base.apk";
+ public static final String MANIFEST = "manifest.json";
+
+ /** How deep to look for the parts. An exported instance nests at most two folders deep. */
+ private static final int MAX_DEPTH = 4;
+
+ private ImportedPackageLayout() {
+ }
+
+ /** What a picked file is. */
+ public enum Kind {
+ /** A single installable package. */
+ APK,
+ /** A zip container: an XAPK, or an exported instance folder. */
+ ARCHIVE,
+ /** Neither, by name or by signature. */
+ UNKNOWN,
+ }
+
+ /** The outcome of {@link #normalise(File)}, for the caller's error message and its logging. */
+ public static final class Result {
+ public int apks;
+ public int obbs;
+ public boolean manifest;
+ public boolean hasBase;
+
+ /** Whether the package is complete enough to install. */
+ public boolean installable() {
+ return hasBase;
+ }
+ }
+
+ /**
+ * Decides what {@code file} is from its name and its first bytes.
+ *
+ * The extension alone is not enough: a {@code .zip} can hold a game, and an APK renamed to
+ * {@code .zip} is still an APK to the package manager. Both are zip containers, so the only
+ * distinction that matters here is "one package" versus "a container to unpack".
+ */
+ public static Kind detect(File file) {
+ if (file == null || !file.isFile()) return Kind.UNKNOWN;
+ String name = file.getName().toLowerCase(java.util.Locale.ROOT);
+ if (name.endsWith(".apk")) return Kind.APK;
+ if (name.endsWith(".xapk") || name.endsWith(".zip") || name.endsWith(".apks")) {
+ return hasZipSignature(file) ? Kind.ARCHIVE : Kind.UNKNOWN;
+ }
+ return hasZipSignature(file) ? Kind.ARCHIVE : Kind.UNKNOWN;
+ }
+
+ /** A zip starts with "PK\3\4"; an empty zip only has the end record, which is not an install. */
+ static boolean hasZipSignature(File file) {
+ try (FileInputStream in = new FileInputStream(file)) {
+ byte[] head = new byte[4];
+ int read = in.read(head);
+ return read == 4 && head[0] == 'P' && head[1] == 'K' && head[2] == 3 && head[3] == 4;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Whether a zip entry would be written outside the directory it is extracted into.
+ *
+ * An entry named {@code ../../files/…} escapes the target once joined, which is a write
+ * anywhere the app can reach. The name is checked rather than the joined path so a Windows-style
+ * separator cannot slip past either.
+ */
+ public static boolean isUnsafeEntry(String entryName) {
+ if (entryName == null || entryName.isEmpty()) return true;
+ String normalised = entryName.replace('\\', '/');
+ if (normalised.startsWith("/")) return true;
+ for (String segment : normalised.split("/")) {
+ if ("..".equals(segment)) return true;
+ }
+ return false;
+ }
+
+ /**
+ * Moves every APK, OBB and manifest found under {@code root} into {@code apk/}, {@code obb/}
+ * and {@code root/manifest.json}.
+ *
+ * The largest APK becomes {@code base.apk} because that is the one the launcher boots; the
+ * others keep their names so a split is still recognisable. An already-correct layout is left
+ * alone, so this is safe to run twice.
+ */
+ public static Result normalise(File root) throws IOException {
+ Result result = new Result();
+ if (root == null || !root.isDirectory()) return result;
+
+ List The class ids are the API's own for Minecraft Bedrock (`gameId` 78022), read from
+ * `/v1/categories?gameId=78022`: the entries with `isClass = true` are Addons 4984, Maps 6913,
+ * Skins 6925, Texture Packs 6929 and Scripts 6940. They are not guesses — a wrong id would return
+ * another game's catalogue or nothing at all.
+ *
+ * [ALL] carries id 0, which the client omits from the request, so it means "no class filter".
+ * Bedrock content predates classes in some listings, and this is the section that shows it.
+ */
+enum class CurseForgeSection(val classId: Int, private val labelRes: Int) {
+ ALL(0, R.string.caramel_curseforge_section_all),
+ ADDONS(4984, R.string.caramel_curseforge_section_addons),
+ TEXTURE_PACKS(6929, R.string.caramel_curseforge_section_texture_packs),
+ SCRIPTS(6940, R.string.caramel_curseforge_section_scripts),
+ MAPS(6913, R.string.caramel_curseforge_section_maps),
+ SKINS(6925, R.string.caramel_curseforge_section_skins),
+ ;
+
+ @Composable
+ fun label(): String = stringResource(labelRes)
+
+ companion object {
+ /** The section for [classId], or [ALL] for an id this build does not know. */
+ fun forClassId(classId: Int): CurseForgeSection =
+ entries.firstOrNull { it.classId == classId } ?: ALL
+ }
+}
+
+/**
+ * Sorts [items] by downloads, highest first, keeping the API's order for equal counts.
+ *
+ * The request already asks for total downloads, descending, so this is a second guard:
+ * the section list is what a person reads top to bottom, and a row out of order reads as a bug in
+ * the section rather than in the ranking. Pure, so the ordering rule is unit-tested.
+ */
+fun sortedByDownloads(items: List CurseForge needs an API key, but not from the user: the client ships its own default key and
- * only exposes the key field under Developer mode. The search itself is a plain text query — no
- * class filter — because Bedrock content is spread across several CurseForge categories and a
- * filter would hide the very add-ons this tab exists for.
+ * only exposes the key field under Developer mode.
+ *
+ * The tab opens on a listing rather than on an empty page: an empty query is a browse, and the
+ * section chips ([CurseForgeSection]) are the API's own Bedrock classes, so Add-ons and Texture
+ * Packs each show their own catalogue instead of an unfiltered mixture. Results are ranked by
+ * downloads, and the ranking is applied again on the client so a row can never read out of order.
*
* A result is downloadable only when the API returned a file with a URL. The button is disabled
* otherwise rather than downloading nothing.
@@ -62,16 +77,32 @@ import java.util.Locale
@Composable
fun CaramelCurseForgeScreen(
state: CaramelLauncherState,
- onSearch: (String) -> Unit,
+ onBrowse: (CurseForgeSection, String) -> Unit,
onDownload: (CaramelCurseForgeItem) -> Unit,
) {
var query by remember { mutableStateOf(state.curseForgeQuery) }
+ // The first visit shows the catalogue instead of an empty page; later visits keep whatever is
+ // already on screen so switching tabs does not restart the listing.
+ LaunchedEffect(state.curseForgeSection) {
+ if (!state.curseForgeSearched && state.curseForgeResults.isEmpty() && !state.curseForgeBusy) {
+ onBrowse(state.curseForgeSection, "")
+ }
+ }
CaramelPage(stringResource(R.string.caramel_curseforge_title), stringResource(R.string.caramel_curseforge_sub)) {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
+ items(CurseForgeSection.entries, key = { it.name }) { section ->
+ FilterChip(
+ section.label(),
+ state.curseForgeSection == section,
+ { if (state.curseForgeSection != section) onBrowse(section, query.trim()) },
+ )
+ }
+ }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
SearchField(query, { query = it }, stringResource(R.string.caramel_curseforge_search_hint), Modifier.width(360.dp))
PrimaryButton(
stringResource(R.string.caramel_curseforge_search),
- { onSearch(query.trim()) },
+ { onBrowse(state.curseForgeSection, query.trim()) },
Modifier.width(150.dp),
tone = Tone.Caramel,
icon = Icons.Rounded.Download,
@@ -132,18 +163,7 @@ private fun CurseForgeRow(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
- Box(
- Modifier.size(52.dp).clip(RoundedCornerShape(13.dp))
- .background(C.Orange.copy(0.16f))
- .border(1.dp, C.Orange.copy(0.5f), RoundedCornerShape(13.dp)),
- Alignment.Center,
- ) {
- Image(
- painterResource(R.drawable.ic_brand_curseforge),
- contentDescription = null,
- modifier = Modifier.size(28.dp),
- )
- }
+ CurseForgeThumb(item.logoUrl)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
@@ -185,6 +205,44 @@ private fun CurseForgeRow(
}
}
+/**
+ * A project's own picture, with the CurseForge mark only as the fallback.
+ *
+ * Every search result carries `logo.thumbnailUrl`; showing a generic mark in its place is what
+ * made two different texture packs look identical. The image is fetched off the main thread through
+ * the same bounded cache the account avatar uses, so scrolling a listing does not re-download.
+ */
+@Composable
+private fun CurseForgeThumb(url: String) {
+ val context = LocalContext.current
+ val bitmap = produceState Importing copies a whole game package and can take a minute on a phone, so it needs a modal
+ * that cannot be dismissed by tapping outside it and that says how far along it is. The percentage
+ * is drawn in Press Start 2P — the same face the splash uses — because it reads as a game loading
+ * screen rather than as a system dialog.
+ *
+ * [CaramelLauncherState.importProgress] is -1 when nothing is importing, which is the only state
+ * that hides the dialog.
+ */
+@Composable
+fun CaramelImportProgressModal(state: CaramelLauncherState) {
+ if (state.importProgress < 0) return
+ val percent = state.importProgress.coerceIn(0, 100)
+ CaramelModal(true, {}, Modifier.size(360.dp, 260.dp)) {
+ Column(
+ Modifier.fillMaxWidth().size(360.dp, 260.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center,
+ ) {
+ CircularProgressIndicator(
+ progress = { percent / 100f },
+ color = C.Caramel,
+ trackColor = C.sheen(0.12f),
+ strokeWidth = 6.dp,
+ modifier = Modifier.size(96.dp),
+ )
+ Text(
+ "$percent%",
+ style = T.Display.copy(
+ fontFamily = FontFamily(Font(R.font.pressstart2p)),
+ fontSize = 26.sp_,
+ ),
+ )
+ Text(
+ stringResource(R.string.caramel_import_instance_title),
+ style = T.Label,
+ )
+ Text(
+ stringResource(R.string.caramel_import_instance_wait),
+ style = T.Caption,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherHost.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherHost.kt
index a0afd1aaf..f1b4ba020 100644
--- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherHost.kt
+++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherHost.kt
@@ -78,8 +78,11 @@ object CaramelLauncherHost {
fun setInstanceLaunchVertical(enabled: Boolean)
/** Toggles the in-game resource-pack changer for this instance. */
fun setInstancePackChanger(enabled: Boolean)
- /** Runs a CurseForge search for [query] and publishes the results into the state. */
- fun searchCurseForge(query: String)
+ /**
+ * Browses [classId] (0 for every section) with [query], publishing the results into the
+ * state. An empty query is the tab's default listing, not an error.
+ */
+ fun searchCurseForge(query: String, classId: Int)
/** Downloads [item]'s newest file and imports it into the selected instance. */
fun downloadCurseForge(item: CaramelCurseForgeItem)
fun quit()
diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherScreen.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherScreen.kt
index de26bc81f..434fe3ab1 100644
--- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherScreen.kt
+++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherScreen.kt
@@ -53,7 +53,7 @@ fun CaramelLauncherScreen(
CaramelTab.News -> CaramelNewsScreen(state)
CaramelTab.CurseForge -> CaramelCurseForgeScreen(
state,
- onSearch = actions::searchCurseForge,
+ onBrowse = { section, query -> actions.searchCurseForge(query, section.classId) },
onDownload = actions::downloadCurseForge,
)
CaramelTab.Store -> CaramelStoreScreen(state)
@@ -82,6 +82,7 @@ fun CaramelLauncherScreen(
CaramelAddServerModal(state, actions)
CaramelInstanceSettingsModal(state, actions)
CaramelWebModal(state)
+ CaramelImportProgressModal(state)
CaramelToast(state)
}
}
diff --git a/app/src/main/res/drawable/mod_menu_handle.xml b/app/src/main/res/drawable/mod_menu_handle.xml
new file mode 100644
index 000000000..1c5acf1ba
--- /dev/null
+++ b/app/src/main/res/drawable/mod_menu_handle.xml
@@ -0,0 +1,28 @@
+
+
+ The class ids are the ones the live API reports for `gameId=78022` (`isClass = true`):
+ * Addons 4984, Maps 6913, Skins 6925, Texture Packs 6929, Scripts 6940. A transposed digit does not
+ * fail loudly — it returns an empty or unrelated section — so they are pinned here.
+ */
+class CurseForgeSectionsTest {
+
+ @Test
+ fun `each section asks for the API's own Bedrock class`() {
+ assertEquals(0, CurseForgeSection.ALL.classId)
+ assertEquals(4984, CurseForgeSection.ADDONS.classId)
+ assertEquals(6929, CurseForgeSection.TEXTURE_PACKS.classId)
+ assertEquals(6940, CurseForgeSection.SCRIPTS.classId)
+ assertEquals(6913, CurseForgeSection.MAPS.classId)
+ assertEquals(6925, CurseForgeSection.SKINS.classId)
+ }
+
+ @Test
+ fun `a class id round-trips and an unknown one falls back to All`() {
+ for (section in CurseForgeSection.entries) {
+ assertEquals(section, CurseForgeSection.forClassId(section.classId))
+ }
+ assertEquals(CurseForgeSection.ALL, CurseForgeSection.forClassId(12345))
+ }
+
+ @Test
+ fun `the browse URL carries the section and the download ranking`() {
+ val url = CurseForgeClient.searchUrl(
+ "", CurseForgeSection.TEXTURE_PACKS.classId, null, 0, 30,
+ CurseForgeClient.SORT_TOTAL_DOWNLOADS, "desc",
+ )
+ assertEquals("78022", url.queryParameter("gameId"))
+ assertEquals("6929", url.queryParameter("classId"))
+ assertEquals("6", url.queryParameter("sortField"))
+ assertEquals("desc", url.queryParameter("sortOrder"))
+ assertNull("an empty query is a browse, not a filter", url.queryParameter("searchFilter"))
+ }
+
+ @Test
+ fun `All sends no class filter and a query becomes a searchFilter`() {
+ val url = CurseForgeClient.searchUrl(
+ "bed wars", CurseForgeSection.ALL.classId, null, 0, 30,
+ CurseForgeClient.SORT_TOTAL_DOWNLOADS, "desc",
+ )
+ assertNull(url.queryParameter("classId"))
+ assertEquals("bed wars", url.queryParameter("searchFilter"))
+ }
+
+ @Test
+ fun `results are ranked by downloads, highest first`() {
+ val rows = listOf(item(1, 10), item(2, 900), item(3, 5_000), item(4, 900))
+ assertEquals(listOf(3, 2, 4, 1), sortedByDownloads(rows).map { it.id })
+ }
+
+ private fun item(id: Int, downloads: Long) =
+ CaramelCurseForgeItem(id, "name-$id", "", "", downloads, "https://media.forgecdn.net/x.png")
+}
diff --git a/app/src/test/java/org/chimeramc/client/core/mods/inbuilt/overlay/ModMenuButtonIconTest.java b/app/src/test/java/org/chimeramc/client/core/mods/inbuilt/overlay/ModMenuButtonIconTest.java
new file mode 100644
index 000000000..ec3952f7a
--- /dev/null
+++ b/app/src/test/java/org/chimeramc/client/core/mods/inbuilt/overlay/ModMenuButtonIconTest.java
@@ -0,0 +1,96 @@
+package org.chimeramc.client.core.mods.inbuilt.overlay;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.chimeramc.client.R;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+
+/**
+ * The in-game menu button's glyph.
+ *
+ * The button floats over the game and lands in every screenshot, so its icon decides whether the
+ * client announces itself. It wore the Caramel apple; it now wears a plain handle. These tests pin
+ * that choice and the three properties the handle needs to be legible on an arbitrary game scene:
+ * it is a vector, it draws something, and it is a single flat white so it survives any backdrop.
+ */
+public class ModMenuButtonIconTest {
+
+ private static final String ANDROID_NS = "http://schemas.android.com/apk/res/android";
+
+ private static final String HANDLE_NAME = "app/src/main/res/drawable/mod_menu_handle.xml";
+
+ /** The module's working directory differs between the IDE and Gradle, so walk up to the repo. */
+ private static Path handle() throws java.io.IOException {
+ Path dir = Paths.get("").toAbsolutePath();
+ for (int i = 0; i < 6 && dir != null; i++) {
+ Path candidate = dir.resolve(HANDLE_NAME);
+ if (Files.exists(candidate)) return candidate;
+ dir = dir.getParent();
+ }
+ throw new IllegalStateException("could not find " + HANDLE_NAME);
+ }
+
+ @Test
+ public void theButtonDoesNotWearTheClientsBrandMark() {
+ assertNotEquals("the floating button must not use the apple again",
+ R.drawable.mod_menu_icon, ModMenuButtonOverlay.iconResource());
+ assertEquals(R.drawable.mod_menu_handle, ModMenuButtonOverlay.iconResource());
+ }
+
+ @Test
+ public void theHandleIsAVectorWithVisibleStrokes() throws Exception {
+ Path handle = handle();
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ Document document = factory.newDocumentBuilder().parse(handle.toFile());
+ Element root = document.getDocumentElement();
+ assertEquals("vector", root.getTagName());
+
+ NodeList paths = root.getElementsByTagName("path");
+ assertTrue("a handle needs at least the three bars, found " + paths.getLength(),
+ paths.getLength() >= 3);
+ for (int i = 0; i < paths.getLength(); i++) {
+ Element path = (Element) paths.item(i);
+ String data = android(path, "pathData");
+ assertTrue("path " + i + " draws nothing", data.startsWith("M"));
+ assertTrue("path " + i + " has no width", !android(path, "strokeWidth").isEmpty());
+ assertTrue("path " + i + " has no colour",
+ !android(path, "strokeColor").isEmpty() || !android(path, "fillColor").isEmpty());
+ }
+ }
+
+ /** The vector attributes are in the android namespace, so a plain getAttribute returns "". */
+ private static String android(Element element, String name) {
+ String value = element.getAttributeNS(ANDROID_NS, name);
+ return value.isEmpty() ? element.getAttribute(name) : value;
+ }
+
+ @Test
+ public void everyColourIsOpaqueWhite() throws Exception {
+ String xml = new String(Files.readAllBytes(handle()), java.nio.charset.StandardCharsets.UTF_8);
+ Matcher colours = Pattern.compile("#[0-9A-Fa-f]{6,8}").matcher(xml);
+ List A real XAPK keeps {@code base.apk}, its splits and {@code manifest.json} at the root and the
+ * OBB under {@code Android/obb/}. The installer only reads {@code apk/} and {@code obb/}, so before
+ * this step an XAPK became an empty instance: it showed in the list and refused to launch. These
+ * tests build that tree on disk and check where each part ends up.
+ */
+public class ImportedPackageLayoutTest {
+
+ @Rule
+ public TemporaryFolder folder = new TemporaryFolder();
+
+ @Test
+ public void anXapkRootIsCollectedIntoTheInstallerLayout() throws IOException {
+ File root = folder.newFolder("extracted");
+ File base = write(new File(root, "base.apk"), 4096);
+ File split = write(new File(root, "split_config.arm64_v8a.apk"), 1024);
+ File obb = write(new File(root, "Android/obb/com.mojang.minecraftpe/main.118.com.mojang.minecraftpe.obb"), 64);
+ write(new File(root, "manifest.json"), 32);
+ long baseLen = base.length();
+ long splitLen = split.length();
+ long obbLen = obb.length();
+
+ ImportedPackageLayout.Result result = ImportedPackageLayout.normalise(root);
+
+ assertTrue(result.installable());
+ assertEquals(1, result.obbs);
+ assertTrue(result.manifest);
+ File apkDir = new File(root, "apk");
+ assertEquals(baseLen, new File(apkDir, "base.apk").length());
+ assertEquals(splitLen, new File(apkDir, "split_config.arm64_v8a.apk").length());
+ assertEquals(obbLen, new File(root, "obb/main.118.com.mojang.minecraftpe.obb").length());
+ assertTrue(new File(root, "manifest.json").isFile());
+ }
+
+ @Test
+ public void anInstanceNestedOneFolderDownStillFindsItsBaseApk() throws IOException {
+ File root = folder.newFolder("nested");
+ write(new File(root, "MyInstance/game.apk"), 2048);
+ write(new File(root, "MyInstance/obb/main.1.obb"), 16);
+
+ ImportedPackageLayout.Result result = ImportedPackageLayout.normalise(root);
+
+ assertTrue(result.installable());
+ assertTrue(new File(root, "apk/base.apk").isFile());
+ assertTrue(new File(root, "obb/main.1.obb").isFile());
+ }
+
+ @Test
+ public void theLargestApkIsTheBaseAndTheOthersStayRecognisable() throws IOException {
+ File root = folder.newFolder("splits");
+ write(new File(root, "tiny.apk"), 100);
+ write(new File(root, "the-real-one.apk"), 9000);
+
+ ImportedPackageLayout.normalise(root);
+
+ assertEquals(9000, new File(root, "apk/base.apk").length());
+ assertEquals(100, new File(root, "apk/tiny.apk").length());
+ }
+
+ @Test
+ public void normaliseIsSafeToRunTwice() throws IOException {
+ File root = folder.newFolder("twice");
+ write(new File(root, "base.apk"), 512);
+ ImportedPackageLayout.normalise(root);
+ ImportedPackageLayout.Result second = ImportedPackageLayout.normalise(root);
+
+ assertTrue(second.installable());
+ assertTrue(new File(root, "apk/base.apk").isFile());
+ }
+
+ @Test
+ public void aPackageWithNoApkIsNotInstallable() throws IOException {
+ File root = folder.newFolder("empty");
+ write(new File(root, "readme.txt"), 10);
+
+ ImportedPackageLayout.Result result = ImportedPackageLayout.normalise(root);
+
+ assertFalse(result.installable());
+ assertEquals(0, result.apks);
+ }
+
+ @Test
+ public void theKindComesFromContentAsWellAsTheName() throws IOException {
+ File apk = write(folder.newFile("game.apk"), 8);
+ File zip = zip(folder.newFile("instance.zip"));
+ File renamed = zip(folder.newFile("game.bin"));
+ File text = write(folder.newFile("notes.txt"), 8);
+
+ assertEquals(ImportedPackageLayout.Kind.APK, ImportedPackageLayout.detect(apk));
+ assertEquals(ImportedPackageLayout.Kind.ARCHIVE, ImportedPackageLayout.detect(zip));
+ assertEquals("a zip renamed still opens", ImportedPackageLayout.Kind.ARCHIVE,
+ ImportedPackageLayout.detect(renamed));
+ assertEquals(ImportedPackageLayout.Kind.UNKNOWN, ImportedPackageLayout.detect(text));
+ }
+
+ @Test
+ public void entriesThatEscapeTheImportDirectoryAreRejected() {
+ assertTrue(ImportedPackageLayout.isUnsafeEntry("../files/x.apk"));
+ assertTrue(ImportedPackageLayout.isUnsafeEntry("a/../../b"));
+ assertTrue(ImportedPackageLayout.isUnsafeEntry("..\\windows\\x"));
+ assertTrue(ImportedPackageLayout.isUnsafeEntry("/absolute/path"));
+ assertFalse(ImportedPackageLayout.isUnsafeEntry("base.apk"));
+ assertFalse(ImportedPackageLayout.isUnsafeEntry("Android/obb/pkg/main.1.obb"));
+ assertFalse(ImportedPackageLayout.isUnsafeEntry("two..dots.apk"));
+ }
+
+ private static File write(File file, int bytes) throws IOException {
+ File parent = file.getParentFile();
+ if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
+ throw new IOException("could not create " + parent);
+ }
+ try (FileOutputStream out = new FileOutputStream(file)) {
+ out.write(new byte[bytes]);
+ }
+ return file;
+ }
+
+ private static File zip(File file) throws IOException {
+ try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) {
+ zos.putNextEntry(new ZipEntry("base.apk"));
+ zos.write("not-a-real-apk".getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ }
+ return file;
+ }
+}
diff --git a/docs/agents/caramel-curseforge-tab.md b/docs/agents/caramel-curseforge-tab.md
new file mode 100644
index 000000000..ec4073d6e
--- /dev/null
+++ b/docs/agents/caramel-curseforge-tab.md
@@ -0,0 +1,8 @@
+## CurseForge tab (CaramelCurseForgeTab + CurseForgeSections + core.curseforge)
+- **The tab must browse before it is asked to.** For two releases the CurseForge screen was blank on entry: it only called the API from the Search button, so a first-time visitor saw an empty page and concluded the tab was broken. `LaunchedEffect(state.curseForgeSection)` now runs the default listing when nothing has been searched and nothing is on screen. Do not "simplify" it back into the search button, and keep the guard (`curseForgeSearched` / results / busy) or every recomposition re-fires the request.
+- **An empty query is a browse, not an error.** `CurseForgeClient.searchUrl` only adds `searchFilter` when the query is non-empty, and `classId` only when it is above zero. `CurseForgeSectionsTest` pins both, because a stray `searchFilter=` returns nothing and looks exactly like "CurseForge has no content".
+- **Sections are the API's own Bedrock classes, read from the live catalogue** (`GET /v1/categories?gameId=78022`): Add-ons `4984` (subcategories Maps / Texture Packs / Skins / Players / Mobs / Data Packs / PvP / Realistic / Simplistic / Miscellaneous / Themed), Maps `6913`, Skins `6925`, Texture Packs `6929`, Scripts `6940`. A transposed digit does not fail loudly — it returns an empty or unrelated section — so `CurseForgeSectionsTest` pins every id.
+- **Sorting is requested and then applied again.** Everything asks for `sortField=6` (total downloads) descending, and `sortedByDownloads` re-sorts the page before it reaches the list. The API is asked for the ranking; the client does not trust the order it gets back. The sort is stable, so equal download counts keep the API's order instead of jumping between recompositions.
+- **A result row shows the project's own picture.** `logo.thumbnailUrl` (e.g. `https://media.forgecdn.net/avatars/thumbnails/...`) goes through `CaramelAvatarLoader`, the same bounded cache the account avatar uses, so scrolling a listing does not re-download. The CurseForge mark is the fallback for a project with no logo — it must not be drawn in place of one, which is what made every texture pack look like the same card.
+- **The key is not the user's problem.** `BuildConfig.CURSEFORGE_API_KEY` has a default; the key field is only reachable from Developer mode (`CurseForgeKeyStore` holds a device override). `CurseForgeClient.describeFailure` maps 401/403/429 to something a person can act on rather than the raw status.
+- **Downloadable means a file URL came back.** `CaramelCurseForgeItem.downloadable = downloadUrl.isNotEmpty()`; the row disables Download otherwise instead of starting an empty transfer.
diff --git a/docs/agents/installations-tab-pluggable-package-sources.md b/docs/agents/installations-tab-pluggable-package-sources.md
index 569626fbe..0bebc62a1 100644
--- a/docs/agents/installations-tab-pluggable-package-sources.md
+++ b/docs/agents/installations-tab-pluggable-package-sources.md
@@ -19,3 +19,9 @@
- `uniqueVersionName` picks a name no existing instance uses, because the import pipeline deletes the target directory before extracting: importing onto an existing name silently destroys that instance. This is also what makes "Reinstall" create a second copy instead of overwriting the first.
- **`McpedlSourceTest` pins the extraction rules against markup shaped like the live pages** (index cards, the three-row variant table, the scripted form response), and `installations_source_warning` is a format string taking the active source's host. The parser was also verified against the real captured HTML: 15 versions, correct release/beta flags, `armv7a` flagged 32-bit, and the resolved `file.mcpedl.org` URL. Fixtures must keep mirroring the real shapes тАФ a hand-written fixture that only resembles them can pass while the live selectors are wrong.
- Lint: `lintDebug` **passes and is a CI gate**. `app/lint.xml` promotes `ContentDescription`, `LabelFor`, `TouchTargetSizeCheck` and `NewApi` to errors and captures the pre-existing backlog in `app/lint-baseline.xml`, so the step fails only on a new offender. `MissingTranslation` is deliberately **off** (the locale backlog is ~13k rows; `TranslationCoverageTest` is the ratchet that fails on a *new* untranslated string), and the style-only checks (`UnknownNullness`, `SyntheticAccessor`, `DuplicateStrings`, `UnusedIds`, `TypographyQuotes`, `SelectableText`, `DefaultLocale`, `Rtl*`) are ignored so the baseline stays small. After intentionally changing a flagged area, regenerate with `./gradlew :app:updateLintBaseline` and review the diff.
+
+- **"Import instance" accepts an .apk, an .xapk and a .zip, and the subtitle used to promise a zip the importer rejected.** `VersionManager.importGameFile` only took `.apk`/`.xapk` by extension; anything else failed with *"Unsupported file format"*, so the button's own description ("Import a .zip") led straight into an error. `ImportedPackageLayout.detect` now decides by name **and** zip signature, so a package renamed on the way through a file provider still opens.
+- **The archive's own layout is not the installer's layout — this is why an imported XAPK never launched.** `extractAndSplit` copies a bare APK to `apk/base.apk`, and `splitIntoSandbox` only reads `apk/`, `obb/` and `manifest.json`. A real XAPK unpacks `base.apk`, `split_config.*.apk` and `manifest.json` at the **root** with the OBB under `Android/obb/