From 9577871b46e5601436b3b69476820326d15b098e Mon Sep 17 00:00:00 2001 From: Lynxifyy <297587416+Lynxifyy@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:36:22 +0000 Subject: [PATCH 1/5] feat(curseforge): browse by section and show each project's own picture The tab did nothing until a query was typed: nothing called the API on entry. It now browses on first visit, and the section chips are the API's own Minecraft Bedrock classes (Addons 4984, Texture Packs 6929, Scripts 6940, Maps 6913, Skins 6925, read from /v1/categories?gameId=78022) instead of an unfiltered mixture. Every section asks for total downloads descending and the list is re-sorted on the client, so a row cannot read out of order. The result row drew a hardcoded CurseForge mark in place of the project's picture, which made every texture pack look identical. It draws logo.thumbnailUrl through the existing avatar cache and keeps the mark only as the fallback. --- .../core/curseforge/CurseForgeBrowser.java | 15 ++- .../core/curseforge/CurseForgeClient.java | 20 +++- .../launcher/ui/activities/MainActivity.java | 6 +- .../ui/compose/caramel/CaramelModels.kt | 3 + .../ui/compose/caramel/CurseForgeSections.kt | 45 +++++++++ .../caramel/launcher/CaramelCurseForgeTab.kt | 94 +++++++++++++++---- .../caramel/launcher/CaramelLauncherHost.kt | 7 +- .../caramel/launcher/CaramelLauncherScreen.kt | 2 +- app/src/main/res/values-es/strings.xml | 6 ++ app/src/main/res/values-fr/strings.xml | 6 ++ app/src/main/res/values-hi/strings.xml | 6 ++ app/src/main/res/values-id/strings.xml | 6 ++ app/src/main/res/values-ja/strings.xml | 6 ++ app/src/main/res/values-pt/strings.xml | 6 ++ app/src/main/res/values-ru/strings.xml | 6 ++ app/src/main/res/values-tr/strings.xml | 6 ++ app/src/main/res/values-vi/strings.xml | 6 ++ app/src/main/res/values-zh-rCN/strings.xml | 6 ++ app/src/main/res/values/strings.xml | 6 ++ .../core/curseforge/CurseForgeSectionsTest.kt | 68 ++++++++++++++ scripts/apply_translations.py | 1 + ...nslations_caramel_curseforge_sections.json | 82 ++++++++++++++++ 22 files changed, 377 insertions(+), 32 deletions(-) create mode 100644 app/src/main/java/org/chimeramc/client/ui/compose/caramel/CurseForgeSections.kt create mode 100644 app/src/test/java/org/chimeramc/client/core/curseforge/CurseForgeSectionsTest.kt create mode 100644 scripts/translations_caramel_curseforge_sections.json 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 callback) { - if (!requireKey(callback)) return; + /** + * The search URL for one page, built without touching the network so the parameters that decide + * what a section shows are unit-tested rather than assumed. + */ + static HttpUrl searchUrl(String query, int classId, String version, int index, int pageSize, + String sortField, String sortOrder) { HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/v1/mods/search").newBuilder(); urlBuilder.addQueryParameter("gameId", String.valueOf(GAME_ID_MINECRAFT)); urlBuilder.addQueryParameter("sortField", sortField != null ? sortField : SORT_POPULARITY); @@ -115,8 +117,16 @@ public void searchContent(String query, int classId, String version, int index, if (version != null && !version.isEmpty() && !"All".equals(version)) { urlBuilder.addQueryParameter("gameVersion", version); } + return urlBuilder.build(); + } - Request request = authedRequest(urlBuilder.build().toString()).build(); + public void searchContent(String query, int classId, String version, int index, int pageSize, + String sortField, String sortOrder, + CurseForgeCallback callback) { + if (!requireKey(callback)) return; + Request request = authedRequest( + searchUrl(query, classId, version, index, pageSize, sortField, sortOrder).toString()) + .build(); client.newCall(request).enqueue(new Callback() { @Override diff --git a/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java b/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java index cb9a3e26d..8316f82c6 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java +++ b/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java @@ -1496,13 +1496,15 @@ private String queryDisplayName(Uri uri) { } @Override - public void searchCurseForge(String query) { + public void searchCurseForge(String query, int classId) { mutateState(s -> { s.setCurseForgeQuery(query == null ? "" : query); + s.setCurseForgeSection(org.chimeramc.client.ui.compose.caramel.CurseForgeSection + .Companion.forClassId(classId)); s.setCurseForgeBusy(true); s.setCurseForgeStatus(getString(R.string.caramel_curseforge_searching)); }); - CurseForgeBrowser.search(this, query, new CurseForgeBrowser.SearchListener() { + CurseForgeBrowser.search(this, query, classId, new CurseForgeBrowser.SearchListener() { @Override public void onResults(List items) { mutateState(s -> { diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt index b9d5202ea..e839d05c2 100644 --- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt @@ -436,6 +436,9 @@ class CaramelLauncherState { /** True once a search has run, so the empty state can tell "not searched" from "no matches". */ var curseForgeSearched by mutableStateOf(false) + /** The catalogue section the tab is browsing; [CurseForgeSection.ALL] until one is picked. */ + var curseForgeSection by mutableStateOf(CurseForgeSection.ALL) + // --- Update check --------------------------------------------------------------------- } diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CurseForgeSections.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CurseForgeSections.kt new file mode 100644 index 000000000..6c32bda1f --- /dev/null +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CurseForgeSections.kt @@ -0,0 +1,45 @@ +package org.chimeramc.client.ui.compose.caramel + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import org.chimeramc.client.R + +/** + * The catalogue sections the CurseForge tab browses, in the order the tab shows them. + * + *

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): List = + items.sortedByDescending { it.downloads } diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt index af3cf0d60..b7c050764 100644 --- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt @@ -1,5 +1,6 @@ package org.chimeramc.client.ui.compose.caramel.launcher +import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -16,6 +17,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Download @@ -23,19 +25,29 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import org.chimeramc.client.R +import org.chimeramc.client.ui.compose.caramel.CaramelAvatarLoader +import org.chimeramc.client.ui.compose.caramel.CurseForgeSection +import org.chimeramc.client.ui.compose.caramel.FilterChip import org.chimeramc.client.ui.compose.caramel.C import org.chimeramc.client.ui.compose.caramel.CaramelCurseForgeItem import org.chimeramc.client.ui.compose.caramel.CaramelLauncherState @@ -49,12 +61,15 @@ import org.chimeramc.client.ui.compose.caramel.sp_ import java.util.Locale /** - * The CurseForge tab: search the public CurseForge catalogue and import what it returns. + * The CurseForge tab: browse or search the public CurseForge catalogue and import what it returns. * *

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.toList(), 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(initialValue = null, url) { + value = if (CaramelAvatarLoader.isLoadable(url)) { + withContext(Dispatchers.IO) { CaramelAvatarLoader.load(context, url) } + } else null + }.value + 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, + ) { + if (bitmap != null) { + Image( + bitmap = bitmap.asImageBitmap(), + contentDescription = null, + modifier = Modifier.size(52.dp).clip(RoundedCornerShape(13.dp)), + contentScale = ContentScale.Crop, + ) + } else { + Image( + painterResource(R.drawable.ic_brand_curseforge), + contentDescription = null, + modifier = Modifier.size(28.dp), + ) + } + } +} + /** "1.2M", "34.5k", "912": a download count a person can read at a glance. */ private fun formatCount(value: Long): String { if (value >= 1_000_000L) return String.format(Locale.ROOT, "%.1fM", value / 1_000_000.0) 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..8bf2013b3 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) diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2b9c4e017..a52aebb91 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1560,4 +1560,10 @@ La migración debe completarse antes de continuar con CaramelClient. Última versión: %1$s Modo desarrollador Muestra opciones avanzadas, incluida la clave de API de CurseForge. + Todos + Complementos + Paquetes de texturas + Scripts + Mapas + Skins diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 29f35e421..d4645d191 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1560,4 +1560,10 @@ La migration doit être terminée avant de continuer avec CaramelClient.Dernière version : %1$s Mode développeur Affiche des options avancées, dont la clé d\'API CurseForge. + Tous + Extensions + Packs de textures + Scripts + Cartes + Skins \ No newline at end of file diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 94e5557c9..04abfd497 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1588,4 +1588,10 @@ CaramelClient जारी रखने से पहले माइग्र नवीनतम रिलीज़: %1$s डेवलपर मोड उन्नत विकल्प दिखाता है, जिसमें CurseForge API कुंजी भी शामिल है। + सभी + ऐड-ऑन + टेक्सचर पैक + स्क्रिप्ट + मानचित्र + स्किन \ No newline at end of file diff --git a/app/src/main/res/values-id/strings.xml b/app/src/main/res/values-id/strings.xml index 4561dce27..c2d5726b6 100644 --- a/app/src/main/res/values-id/strings.xml +++ b/app/src/main/res/values-id/strings.xml @@ -1584,4 +1584,10 @@ Migrasi harus selesai sebelum CaramelClient dapat melanjutkan. Rilis terbaru: %1$s Mode pengembang Menampilkan opsi lanjutan, termasuk kunci API CurseForge. + Semua + Add-on + Paket Tekstur + Skrip + Peta + Skin \ No newline at end of file diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f9e609c35..2b743ed21 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1557,4 +1557,10 @@ CaramelClient を続行するには移行を完了する必要があります。 最新リリース: %1$s 開発者モード CurseForge API キーを含む詳細オプションを表示します。 + すべて + アドオン + テクスチャパック + スクリプト + マップ + スキン \ No newline at end of file diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index deb7a30a5..b7d0587d9 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1560,4 +1560,10 @@ A migração deve ser concluída antes que o CaramelClient continue. Versão mais recente: %1$s Modo desenvolvedor Mostra opções avançadas, incluindo a chave de API do CurseForge. + Todos + Complementos + Pacotes de textura + Scripts + Mapas + Skins \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e2dc30f3b..78d726b80 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1599,4 +1599,10 @@ Последняя версия: %1$s Режим разработчика Показывает дополнительные параметры, включая ключ API CurseForge. + Все + Дополнения + Наборы текстур + Скрипты + Карты + Скины \ No newline at end of file diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 7ebc682ed..08d84b1c1 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1587,4 +1587,10 @@ CaramelClient\'ın devam edebilmesi için taşımanın tamamlanması gerekiyor.< En yeni sürüm: %1$s Geliştirici modu CurseForge API anahtarı dahil gelişmiş seçenekleri gösterir. + Tümü + Eklentiler + Doku Paketleri + Betikler + Haritalar + Skinler \ No newline at end of file diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 465575189..72ce664c9 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1590,4 +1590,10 @@ Quá trình chuyển đổi phải hoàn tất trước khi CaramelClient có th Bản phát hành mới nhất: %1$s Chế độ nhà phát triển Hiện các tùy chọn nâng cao, gồm khóa API CurseForge. + Tất cả + Tiện ích + Gói kết cấu + Tập lệnh + Bản đồ + Skin \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e29beefce..b6a30945e 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1581,4 +1581,10 @@ 最新版本:%1$s 开发者模式 显示高级选项,包括 CurseForge API 密钥。 + 全部 + 附加内容 + 材质包 + 脚本 + 地图 + 皮肤 \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 72f24a10b..6f4e2351e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2901,6 +2901,12 @@ CaramelClient must complete the migration before continuing. Nothing found No project matched that search. Try a shorter query or a different spelling. %1$s downloads + All + Add-ons + Texture packs + Scripts + Maps + Skins Diagnostics The build, the device and the instance store, as text you can share Build diff --git a/app/src/test/java/org/chimeramc/client/core/curseforge/CurseForgeSectionsTest.kt b/app/src/test/java/org/chimeramc/client/core/curseforge/CurseForgeSectionsTest.kt new file mode 100644 index 000000000..929ce304a --- /dev/null +++ b/app/src/test/java/org/chimeramc/client/core/curseforge/CurseForgeSectionsTest.kt @@ -0,0 +1,68 @@ +package org.chimeramc.client.core.curseforge + +import org.chimeramc.client.ui.compose.caramel.CaramelCurseForgeItem +import org.chimeramc.client.ui.compose.caramel.CurseForgeSection +import org.chimeramc.client.ui.compose.caramel.sortedByDownloads +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The browse contract of the CurseForge tab: which class each section asks for, and the ranking. + * + *

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/scripts/apply_translations.py b/scripts/apply_translations.py index f8c05764b..c454b7e5d 100644 --- a/scripts/apply_translations.py +++ b/scripts/apply_translations.py @@ -60,6 +60,7 @@ ROOT / "scripts/translations_caramel_about.json", ROOT / "scripts/translations_caramel_loaders.json", ROOT / "scripts/translations_caramel_splash.json", + ROOT / "scripts/translations_caramel_curseforge_sections.json", ] STRING_RE = re.compile(r']*)>(.*?)', re.S) diff --git a/scripts/translations_caramel_curseforge_sections.json b/scripts/translations_caramel_curseforge_sections.json new file mode 100644 index 000000000..92df18383 --- /dev/null +++ b/scripts/translations_caramel_curseforge_sections.json @@ -0,0 +1,82 @@ +{ + "es": { + "caramel_curseforge_section_all": "Todos", + "caramel_curseforge_section_addons": "Complementos", + "caramel_curseforge_section_texture_packs": "Paquetes de texturas", + "caramel_curseforge_section_scripts": "Scripts", + "caramel_curseforge_section_maps": "Mapas", + "caramel_curseforge_section_skins": "Skins" + }, + "fr": { + "caramel_curseforge_section_all": "Tous", + "caramel_curseforge_section_addons": "Extensions", + "caramel_curseforge_section_texture_packs": "Packs de textures", + "caramel_curseforge_section_scripts": "Scripts", + "caramel_curseforge_section_maps": "Cartes", + "caramel_curseforge_section_skins": "Skins" + }, + "hi": { + "caramel_curseforge_section_all": "सभी", + "caramel_curseforge_section_addons": "ऐड-ऑन", + "caramel_curseforge_section_texture_packs": "टेक्सचर पैक", + "caramel_curseforge_section_scripts": "स्क्रिप्ट", + "caramel_curseforge_section_maps": "मानचित्र", + "caramel_curseforge_section_skins": "स्किन" + }, + "id": { + "caramel_curseforge_section_all": "Semua", + "caramel_curseforge_section_addons": "Add-on", + "caramel_curseforge_section_texture_packs": "Paket Tekstur", + "caramel_curseforge_section_scripts": "Skrip", + "caramel_curseforge_section_maps": "Peta", + "caramel_curseforge_section_skins": "Skin" + }, + "ja": { + "caramel_curseforge_section_all": "すべて", + "caramel_curseforge_section_addons": "アドオン", + "caramel_curseforge_section_texture_packs": "テクスチャパック", + "caramel_curseforge_section_scripts": "スクリプト", + "caramel_curseforge_section_maps": "マップ", + "caramel_curseforge_section_skins": "スキン" + }, + "pt": { + "caramel_curseforge_section_all": "Todos", + "caramel_curseforge_section_addons": "Complementos", + "caramel_curseforge_section_texture_packs": "Pacotes de textura", + "caramel_curseforge_section_scripts": "Scripts", + "caramel_curseforge_section_maps": "Mapas", + "caramel_curseforge_section_skins": "Skins" + }, + "ru": { + "caramel_curseforge_section_all": "Все", + "caramel_curseforge_section_addons": "Дополнения", + "caramel_curseforge_section_texture_packs": "Наборы текстур", + "caramel_curseforge_section_scripts": "Скрипты", + "caramel_curseforge_section_maps": "Карты", + "caramel_curseforge_section_skins": "Скины" + }, + "tr": { + "caramel_curseforge_section_all": "Tümü", + "caramel_curseforge_section_addons": "Eklentiler", + "caramel_curseforge_section_texture_packs": "Doku Paketleri", + "caramel_curseforge_section_scripts": "Betikler", + "caramel_curseforge_section_maps": "Haritalar", + "caramel_curseforge_section_skins": "Skinler" + }, + "vi": { + "caramel_curseforge_section_all": "Tất cả", + "caramel_curseforge_section_addons": "Tiện ích", + "caramel_curseforge_section_texture_packs": "Gói kết cấu", + "caramel_curseforge_section_scripts": "Tập lệnh", + "caramel_curseforge_section_maps": "Bản đồ", + "caramel_curseforge_section_skins": "Skin" + }, + "zh-rCN": { + "caramel_curseforge_section_all": "全部", + "caramel_curseforge_section_addons": "附加内容", + "caramel_curseforge_section_texture_packs": "材质包", + "caramel_curseforge_section_scripts": "脚本", + "caramel_curseforge_section_maps": "地图", + "caramel_curseforge_section_skins": "皮肤" + } +} From 32deaed17c4f6537ce088554a905ddff664245fa Mon Sep 17 00:00:00 2001 From: Lynxifyy <297587416+Lynxifyy@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:40:27 +0000 Subject: [PATCH 2/5] fix(import): install XAPK and zip packages, and show the import's progress The importer only worked for a bare .apk. An .xapk unpacks its APKs at the root and its OBB under Android/obb/, but the installer only reads apk/ and obb/, so an XAPK produced an empty instance that appeared in the list and refused to launch. ImportedPackageLayout now collects the parts wherever the archive put them, makes the largest APK base.apk and keeps the splits, so both layouts install. A .zip is accepted too, and the picker's own subtitle stops promising a zip the importer used to reject. Archive entries that point outside the import directory (../, an absolute path, a Windows separator) are skipped instead of being written, which was an arbitrary-write path. Importing now shows a modal progress ring with the percentage in the pixel face. It was writing to busyMessage, which only the sign-in dialog reads, so the import looked frozen. --- .../core/versions/ImportedPackageLayout.java | 203 ++++++++++++++++++ .../core/versions/VersionManager.java | 87 ++++---- .../launcher/ui/activities/MainActivity.java | 28 ++- .../ui/compose/caramel/CaramelModels.kt | 3 + .../caramel/launcher/CaramelImportProgress.kt | 68 ++++++ .../caramel/launcher/CaramelLauncherScreen.kt | 1 + app/src/main/res/values-es/strings.xml | 4 + app/src/main/res/values-fr/strings.xml | 4 + app/src/main/res/values-hi/strings.xml | 4 + app/src/main/res/values-id/strings.xml | 4 + app/src/main/res/values-ja/strings.xml | 4 + app/src/main/res/values-pt/strings.xml | 4 + app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values-tr/strings.xml | 4 + app/src/main/res/values-vi/strings.xml | 4 + app/src/main/res/values-zh-rCN/strings.xml | 4 + app/src/main/res/values/strings.xml | 6 +- .../versions/ImportedPackageLayoutTest.java | 145 +++++++++++++ scripts/apply_translations.py | 1 + .../translations_caramel_import_progress.json | 72 +++++++ 20 files changed, 607 insertions(+), 47 deletions(-) create mode 100644 app/src/main/java/org/chimeramc/client/launcher/core/versions/ImportedPackageLayout.java create mode 100644 app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelImportProgress.kt create mode 100644 app/src/test/java/org/chimeramc/client/core/versions/ImportedPackageLayoutTest.java create mode 100644 scripts/translations_caramel_import_progress.json 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//main..obb} and {@code manifest.json} at the root, or all of it inside + * one folder. The installer only reads {@code apk/} and {@code obb/}, so an archive imported as an + * empty instance: it appeared in the list and refused to launch. + * + *

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 apks = new ArrayList<>(); + List obbs = new ArrayList<>(); + List manifests = new ArrayList<>(); + collect(root, 0, apks, obbs, manifests); + + apks.removeIf(file -> APK_DIR.equals(file.getParentFile() == null + ? "" : file.getParentFile().getName()) && BASE_APK.equals(file.getName())); + result.apks = apks.size(); + result.obbs = obbs.size(); + result.manifest = !manifests.isEmpty(); + + File apkDir = new File(root, APK_DIR); + File obbDir = new File(root, OBB_DIR); + if (!apks.isEmpty()) ensureDir(apkDir); + if (!obbs.isEmpty()) ensureDir(obbDir); + + File base = largest(apks); + for (File apk : apks) { + String targetName = apk.equals(base) ? BASE_APK : apk.getName(); + move(apk, new File(apkDir, targetName)); + } + for (File obb : obbs) { + move(obb, new File(obbDir, obb.getName())); + } + for (File manifest : manifests) { + File target = new File(root, MANIFEST); + if (!target.equals(manifest)) move(manifest, target); + } + + File existingBase = new File(apkDir, BASE_APK); + result.hasBase = existingBase.isFile() && existingBase.length() > 0; + return result; + } + + private static void collect(File dir, int depth, List apks, List obbs, + List manifests) { + if (depth > MAX_DEPTH) return; + File[] children = dir.listFiles(); + if (children == null) return; + for (File child : children) { + if (child.isDirectory()) { + collect(child, depth + 1, apks, obbs, manifests); + continue; + } + String name = child.getName().toLowerCase(java.util.Locale.ROOT); + if (name.endsWith(".apk")) { + apks.add(child); + } else if (name.endsWith(".obb")) { + obbs.add(child); + } else if (MANIFEST.equals(name)) { + manifests.add(child); + } + } + } + + private static File largest(List files) { + File best = null; + for (File file : files) { + if (best == null || file.length() > best.length()) best = file; + } + return best; + } + + private static void ensureDir(File dir) throws IOException { + if (!dir.isDirectory() && !dir.mkdirs()) { + throw new IOException("could not create " + dir.getName()); + } + } + + private static void move(File source, File target) throws IOException { + if (source.equals(target)) return; + File parent = target.getParentFile(); + if (parent != null) ensureDir(parent); + try (FileInputStream in = new FileInputStream(source); + FileOutputStream out = new FileOutputStream(target)) { + byte[] buffer = new byte[8192]; + int read; + while ((read = in.read(buffer)) > 0) { + out.write(buffer, 0, read); + } + } + if (!source.delete()) { + // A leftover copy is harmless: the installer reads the moved one. + source.deleteOnExit(); + } + } +} diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java b/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java index 313b44336..d79a6f323 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java +++ b/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java @@ -1318,13 +1318,12 @@ public interface VersionCallback { public void importGameFile(File gameFile, VersionCallback callback) { AppExecutors.run(AppExecutors.Kind.DISK, "version-import", () -> { try { - String fileName = gameFile.getName().toLowerCase(); - - if (fileName.endsWith(".xapk") || fileName.endsWith(".apk")) { - extractAndSplit(gameFile, callback); - } else { - callback.onError("Unsupported file format. Please use .apk or .xapk files."); + ImportedPackageLayout.Kind kind = ImportedPackageLayout.detect(gameFile); + if (kind == ImportedPackageLayout.Kind.UNKNOWN) { + callback.onError(context.getString(R.string.caramel_import_instance_unsupported)); + return; } + extractAndSplit(gameFile, kind, callback); } catch (Exception e) { AppLog.error(TAG, "Importing the game file failed", e); callback.onError(UserFacingError.shortReasonForText(context, "Import failed", e.getMessage())); @@ -1332,62 +1331,73 @@ public void importGameFile(File gameFile, VersionCallback callback) { }); } - private void extractAndSplit(File gameFile, VersionCallback callback) throws IOException { + private void extractAndSplit(File gameFile, ImportedPackageLayout.Kind kind, + VersionCallback callback) throws IOException { String versionId = java.util.UUID.randomUUID().toString(); File baseDir = LauncherStorage.getMinecraftRoot(context); File versionDir = new File(baseDir, versionId); File tempDir = new File(context.getCacheDir(), "temp_extract_" + versionId); - - // Clean temp directory + deleteDir(tempDir); tempDir.mkdirs(); - + callback.onProgress(10); - - // Extract XAPK/APK contents - if (gameFile.getName().endsWith(".xapk")) { - extractXapk(gameFile, tempDir, callback); + + if (kind == ImportedPackageLayout.Kind.ARCHIVE) { + extractArchive(gameFile, tempDir, callback); } else { - // Single APK - create simple structure - File apkDir = new File(tempDir, "apk"); + File apkDir = new File(tempDir, ImportedPackageLayout.APK_DIR); apkDir.mkdirs(); - copyFile(gameFile, new File(apkDir, "base.apk")); - - // Extract version info - String versionName = getApkVersionName(gameFile); - saveVersionMetadata(versionId, versionName, gameFile.length(), versionDir); + copyFile(gameFile, new File(apkDir, ImportedPackageLayout.BASE_APK)); } - + callback.onProgress(50); - - // Split and organize files into sandboxed directories + + // An XAPK keeps its APKs at the root and its OBB under Android/obb/; an exported instance + // may nest everything one folder down. Both are collected into the layout the installer reads. + ImportedPackageLayout.Result layout = ImportedPackageLayout.normalise(tempDir); + if (!layout.installable()) { + deleteDir(tempDir); + callback.onError(context.getString(R.string.caramel_import_instance_empty)); + return; + } + + File baseApk = new File(tempDir, ImportedPackageLayout.APK_DIR + "/" + + ImportedPackageLayout.BASE_APK); + saveVersionMetadata(versionId, getApkVersionName(baseApk), gameFile.length(), versionDir); + splitIntoSandbox(tempDir, versionDir, callback); - + callback.onProgress(90); - - // Mark as available by creating a custom version entry + createCustomVersionFromImport(versionId, versionDir); - + callback.onProgress(100); callback.onSuccess(versionId); - - // Cleanup temp + deleteDir(tempDir); } - private void extractXapk(File xapkFile, File outputDir, VersionCallback callback) throws IOException { - try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(xapkFile)))) { + private void extractArchive(File archive, File outputDir, VersionCallback callback) throws IOException { + try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)))) { ZipEntry entry; - int totalEntries = countEntries(xapkFile); + int totalEntries = Math.max(1, countEntries(archive)); int processed = 0; - + while ((entry = zis.getNextEntry()) != null) { + if (ImportedPackageLayout.isUnsafeEntry(entry.getName())) { + AppLog.warnOnce(TAG, "import-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 { - outputFile.getParentFile().mkdirs(); + File parent = outputFile.getParentFile(); + if (parent != null) parent.mkdirs(); try (FileOutputStream fos = new FileOutputStream(outputFile)) { byte[] buffer = new byte[BUFFER_SIZE]; int len; @@ -1396,16 +1406,15 @@ private void extractXapk(File xapkFile, File outputDir, VersionCallback callback } } } - + processed++; int progress = 10 + (processed * 40 / totalEntries); callback.onProgress(progress); - + zis.closeEntry(); } } } - private int countEntries(File zipFile) throws IOException { int count = 0; try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)))) { diff --git a/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java b/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java index 8316f82c6..e2d837b93 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java +++ b/app/src/main/java/org/chimeramc/client/launcher/ui/activities/MainActivity.java @@ -1428,12 +1428,15 @@ public void importInstance() { /** Copies the picked package into the cache, then hands it to the version importer. */ private void importInstanceFrom(Uri uri) { if (versionManager == null) return; - mutateState(s -> s.setBusyMessage(getString(R.string.caramel_import_instance_progress, 0))); + mutateState(s -> { + s.setBusyMessage(getString(R.string.caramel_import_instance_progress, 0)); + s.setImportProgress(0); + }); AppExecutors.run(AppExecutors.Kind.DISK, "instance-import-copy", () -> { File copied = null; try { String name = queryDisplayName(uri); - if (name == null || name.isEmpty()) name = "instance.xapk"; + if (name == null || name.isEmpty()) name = "instance.apk"; File dir = new File(getCacheDir(), "instance-import"); if (!dir.exists() && !dir.mkdirs()) throw new java.io.IOException("no cache directory"); copied = new File(dir, name); @@ -1449,7 +1452,10 @@ private void importInstanceFrom(Uri uri) { @Override public void onSuccess(String versionId) { runOnUiThread(() -> { - mutateState(s -> s.setBusyMessage("")); + mutateState(s -> { + s.setBusyMessage(""); + s.setImportProgress(-1); + }); toast(getString(R.string.caramel_import_instance_done, versionId)); refreshState(); }); @@ -1458,21 +1464,29 @@ public void onSuccess(String versionId) { @Override public void onError(String error) { runOnUiThread(() -> { - mutateState(s -> s.setBusyMessage("")); + mutateState(s -> { + s.setBusyMessage(""); + s.setImportProgress(-1); + }); toastWarning(getString(R.string.caramel_import_instance_failed, error)); }); } @Override public void onProgress(int percent) { - runOnUiThread(() -> mutateState(s -> - s.setBusyMessage(getString(R.string.caramel_import_instance_progress, percent)))); + runOnUiThread(() -> mutateState(s -> { + s.setBusyMessage(getString(R.string.caramel_import_instance_progress, percent)); + s.setImportProgress(percent); + })); } }); } catch (Throwable t) { AppLog.warnOnce(TAG, "instance-import", "Copying the picked package failed", t); runOnUiThread(() -> { - mutateState(s -> s.setBusyMessage("")); + mutateState(s -> { + s.setBusyMessage(""); + s.setImportProgress(-1); + }); toastWarning(getString(R.string.caramel_import_instance_failed, t.getMessage() == null ? "" : t.getMessage())); }); diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt index e839d05c2..e0154d829 100644 --- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/CaramelModels.kt @@ -303,6 +303,9 @@ class CaramelLauncherState { /** A status line shown while a long action (sign-in, repair) is running; empty when idle. */ var busyMessage by mutableStateOf("") + /** Import progress, 0-100, or -1 when no instance import is running. */ + var importProgress by mutableStateOf(-1) + /** The Microsoft device code shown in the add-account modal, empty when no sign-in is running. */ var deviceCode by mutableStateOf("") diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelImportProgress.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelImportProgress.kt new file mode 100644 index 000000000..456a6d71d --- /dev/null +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelImportProgress.kt @@ -0,0 +1,68 @@ +package org.chimeramc.client.ui.compose.caramel.launcher + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import org.chimeramc.client.R +import org.chimeramc.client.ui.compose.caramel.C +import org.chimeramc.client.ui.compose.caramel.CaramelModal +import org.chimeramc.client.ui.compose.caramel.CaramelLauncherState +import org.chimeramc.client.ui.compose.caramel.T +import org.chimeramc.client.ui.compose.caramel.sp_ + +/** + * The import dialog: a progress ring, the percentage in the pixel face, and the file being read. + * + *

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/CaramelLauncherScreen.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelLauncherScreen.kt index 8bf2013b3..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 @@ -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/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a52aebb91..dfb8bdb06 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1566,4 +1566,8 @@ La migración debe completarse antes de continuar con CaramelClient. Scripts Mapas Skins + Importando instancia + Mantén el launcher abierto hasta que termine. + Ese archivo no es un paquete .apk, .xapk o .zip. + Ese paquete no contiene un base.apk. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index d4645d191..024803660 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1566,4 +1566,8 @@ La migration doit être terminée avant de continuer avec CaramelClient.Scripts Cartes Skins + Importation de l\'instance + Gardez le launcher ouvert jusqu\'à la fin. + Ce fichier n\'est pas un paquet .apk, .xapk ou .zip. + Ce paquet ne contient pas de base.apk. \ No newline at end of file diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 04abfd497..0da3ebc5f 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1594,4 +1594,8 @@ CaramelClient जारी रखने से पहले माइग्र स्क्रिप्ट मानचित्र स्किन + इंस्टेंस आयात हो रहा है + पूरा होने तक लॉन्चर खुला रखें। + यह फ़ाइल .apk, .xapk या .zip पैकेज नहीं है। + इस पैकेज में base.apk नहीं है। \ No newline at end of file diff --git a/app/src/main/res/values-id/strings.xml b/app/src/main/res/values-id/strings.xml index c2d5726b6..9c8becca6 100644 --- a/app/src/main/res/values-id/strings.xml +++ b/app/src/main/res/values-id/strings.xml @@ -1590,4 +1590,8 @@ Migrasi harus selesai sebelum CaramelClient dapat melanjutkan. Skrip Peta Skin + Mengimpor instans + Biarkan launcher terbuka sampai selesai. + Berkas itu bukan paket .apk, .xapk, atau .zip. + Paket itu tidak berisi base.apk. \ No newline at end of file diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 2b743ed21..33bf29b23 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1563,4 +1563,8 @@ CaramelClient を続行するには移行を完了する必要があります。 スクリプト マップ スキン + インスタンスをインポート中 + 完了するまでランチャーを開いたままにしてください。 + このファイルは .apk、.xapk、.zip のパッケージではありません。 + このパッケージには base.apk が含まれていません。 \ No newline at end of file diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index b7d0587d9..426a103b8 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1566,4 +1566,8 @@ A migração deve ser concluída antes que o CaramelClient continue. Scripts Mapas Skins + Importando instância + Mantenha o launcher aberto até terminar. + Esse arquivo não é um pacote .apk, .xapk ou .zip. + Esse pacote não contém um base.apk. \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 78d726b80..d118ec860 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1605,4 +1605,8 @@ Скрипты Карты Скины + Импорт экземпляра + Не закрывайте лаунчер до завершения. + Этот файл не является пакетом .apk, .xapk или .zip. + В этом пакете нет base.apk. \ No newline at end of file diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 08d84b1c1..9ec8d32bd 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1593,4 +1593,8 @@ CaramelClient\'ın devam edebilmesi için taşımanın tamamlanması gerekiyor.< Betikler Haritalar Skinler + Örnek içe aktarılıyor + Bitene kadar başlatıcıyı açık tutun. + Bu dosya bir .apk, .xapk veya .zip paketi değil. + Bu pakette base.apk yok. \ No newline at end of file diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 72ce664c9..7c09e94e0 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1596,4 +1596,8 @@ Quá trình chuyển đổi phải hoàn tất trước khi CaramelClient có th Tập lệnh Bản đồ Skin + Đang nhập phiên bản + Giữ trình khởi chạy mở cho đến khi xong. + Tệp đó không phải gói .apk, .xapk hoặc .zip. + Gói đó không có base.apk. \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index b6a30945e..c4ede65ac 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1587,4 +1587,8 @@ 脚本 地图 皮肤 + 正在导入实例 + 请保持启动器打开直到完成。 + 该文件不是 .apk、.xapk 或 .zip 包。 + 该包中没有 base.apk。 \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6f4e2351e..d9d3f9cbc 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2881,7 +2881,11 @@ CaramelClient must complete the migration before continuing. This preloader option is still in development. Ask one of the lead developers for more information. Skip Import instance - Import a .zip or a folder from this device + Import an .apk, .xapk or .zip from this device + Importing instance + Keep the launcher open until this finishes. + That file is not an .apk, .xapk or .zip package. + That package has no base.apk inside it. Importing instance… %1$d%% Imported instance %1$s Import failed: %1$s diff --git a/app/src/test/java/org/chimeramc/client/core/versions/ImportedPackageLayoutTest.java b/app/src/test/java/org/chimeramc/client/core/versions/ImportedPackageLayoutTest.java new file mode 100644 index 000000000..dc6ded35c --- /dev/null +++ b/app/src/test/java/org/chimeramc/client/core/versions/ImportedPackageLayoutTest.java @@ -0,0 +1,145 @@ +package org.chimeramc.client.core.versions; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * The layout rules that decide whether an imported package launches. + * + *

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/scripts/apply_translations.py b/scripts/apply_translations.py index c454b7e5d..d5b77f6fd 100644 --- a/scripts/apply_translations.py +++ b/scripts/apply_translations.py @@ -61,6 +61,7 @@ ROOT / "scripts/translations_caramel_loaders.json", ROOT / "scripts/translations_caramel_splash.json", ROOT / "scripts/translations_caramel_curseforge_sections.json", + ROOT / "scripts/translations_caramel_import_progress.json", ] STRING_RE = re.compile(r']*)>(.*?)', re.S) diff --git a/scripts/translations_caramel_import_progress.json b/scripts/translations_caramel_import_progress.json new file mode 100644 index 000000000..7ff249781 --- /dev/null +++ b/scripts/translations_caramel_import_progress.json @@ -0,0 +1,72 @@ +{ + "es": { + "caramel_import_instance_sub": "Importa un .apk, .xapk o .zip desde este dispositivo", + "caramel_import_instance_title": "Importando instancia", + "caramel_import_instance_wait": "Mantén el launcher abierto hasta que termine.", + "caramel_import_instance_unsupported": "Ese archivo no es un paquete .apk, .xapk o .zip.", + "caramel_import_instance_empty": "Ese paquete no contiene un base.apk." + }, + "fr": { + "caramel_import_instance_sub": "Importez un .apk, .xapk ou .zip depuis cet appareil", + "caramel_import_instance_title": "Importation de l'instance", + "caramel_import_instance_wait": "Gardez le launcher ouvert jusqu'à la fin.", + "caramel_import_instance_unsupported": "Ce fichier n'est pas un paquet .apk, .xapk ou .zip.", + "caramel_import_instance_empty": "Ce paquet ne contient pas de base.apk." + }, + "hi": { + "caramel_import_instance_sub": "इस डिवाइस से .apk, .xapk या .zip आयात करें", + "caramel_import_instance_title": "इंस्टेंस आयात हो रहा है", + "caramel_import_instance_wait": "पूरा होने तक लॉन्चर खुला रखें।", + "caramel_import_instance_unsupported": "यह फ़ाइल .apk, .xapk या .zip पैकेज नहीं है।", + "caramel_import_instance_empty": "इस पैकेज में base.apk नहीं है।" + }, + "id": { + "caramel_import_instance_sub": "Impor .apk, .xapk, atau .zip dari perangkat ini", + "caramel_import_instance_title": "Mengimpor instans", + "caramel_import_instance_wait": "Biarkan launcher terbuka sampai selesai.", + "caramel_import_instance_unsupported": "Berkas itu bukan paket .apk, .xapk, atau .zip.", + "caramel_import_instance_empty": "Paket itu tidak berisi base.apk." + }, + "ja": { + "caramel_import_instance_sub": "この端末から .apk、.xapk、.zip をインポート", + "caramel_import_instance_title": "インスタンスをインポート中", + "caramel_import_instance_wait": "完了するまでランチャーを開いたままにしてください。", + "caramel_import_instance_unsupported": "このファイルは .apk、.xapk、.zip のパッケージではありません。", + "caramel_import_instance_empty": "このパッケージには base.apk が含まれていません。" + }, + "pt": { + "caramel_import_instance_sub": "Importe um .apk, .xapk ou .zip deste dispositivo", + "caramel_import_instance_title": "Importando instância", + "caramel_import_instance_wait": "Mantenha o launcher aberto até terminar.", + "caramel_import_instance_unsupported": "Esse arquivo não é um pacote .apk, .xapk ou .zip.", + "caramel_import_instance_empty": "Esse pacote não contém um base.apk." + }, + "ru": { + "caramel_import_instance_sub": "Импортируйте .apk, .xapk или .zip с этого устройства", + "caramel_import_instance_title": "Импорт экземпляра", + "caramel_import_instance_wait": "Не закрывайте лаунчер до завершения.", + "caramel_import_instance_unsupported": "Этот файл не является пакетом .apk, .xapk или .zip.", + "caramel_import_instance_empty": "В этом пакете нет base.apk." + }, + "tr": { + "caramel_import_instance_sub": "Bu cihazdan .apk, .xapk veya .zip içe aktar", + "caramel_import_instance_title": "Örnek içe aktarılıyor", + "caramel_import_instance_wait": "Bitene kadar başlatıcıyı açık tutun.", + "caramel_import_instance_unsupported": "Bu dosya bir .apk, .xapk veya .zip paketi değil.", + "caramel_import_instance_empty": "Bu pakette base.apk yok." + }, + "vi": { + "caramel_import_instance_sub": "Nhập .apk, .xapk hoặc .zip từ thiết bị này", + "caramel_import_instance_title": "Đang nhập phiên bản", + "caramel_import_instance_wait": "Giữ trình khởi chạy mở cho đến khi xong.", + "caramel_import_instance_unsupported": "Tệp đó không phải gói .apk, .xapk hoặc .zip.", + "caramel_import_instance_empty": "Gói đó không có base.apk." + }, + "zh-rCN": { + "caramel_import_instance_sub": "从此设备导入 .apk、.xapk 或 .zip", + "caramel_import_instance_title": "正在导入实例", + "caramel_import_instance_wait": "请保持启动器打开直到完成。", + "caramel_import_instance_unsupported": "该文件不是 .apk、.xapk 或 .zip 包。", + "caramel_import_instance_empty": "该包中没有 base.apk。" + } +} From 289b3d15ca037154a044690290c07c317babde70 Mon Sep 17 00:00:00 2001 From: Lynxifyy <297587416+Lynxifyy@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:42:47 +0000 Subject: [PATCH 3/5] feat(mod-menu): give the in-game button a plain handle instead of the brand mark The floating button wore the Caramel apple, so it named the client in every screenshot it appeared in. It now draws a three-bar handle: still obviously a menu, no longer a logo. ModMenuButtonIconTest pins the choice and the properties the glyph needs to stay legible on any game scene (a vector, visible strokes, one flat white). --- .../inbuilt/overlay/ModMenuButtonOverlay.java | 15 ++- app/src/main/res/drawable/mod_menu_handle.xml | 28 ++++++ .../overlay/ModMenuButtonIconTest.java | 96 +++++++++++++++++++ 3 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 app/src/main/res/drawable/mod_menu_handle.xml create mode 100644 app/src/test/java/org/chimeramc/client/core/mods/inbuilt/overlay/ModMenuButtonIconTest.java diff --git a/app/src/main/java/org/chimeramc/client/launcher/core/mods/inbuilt/overlay/ModMenuButtonOverlay.java b/app/src/main/java/org/chimeramc/client/launcher/core/mods/inbuilt/overlay/ModMenuButtonOverlay.java index cbbc7338a..ef867f2b6 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/core/mods/inbuilt/overlay/ModMenuButtonOverlay.java +++ b/app/src/main/java/org/chimeramc/client/launcher/core/mods/inbuilt/overlay/ModMenuButtonOverlay.java @@ -11,8 +11,7 @@ * *

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/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 @@ + + + + + + + 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 found = new ArrayList<>(); + while (colours.find()) found.add(colours.group().toUpperCase()); + assertFalse("the handle states no colour", found.isEmpty()); + for (String colour : found) { + assertTrue("the handle must stay flat white, found " + colour, + colour.equals("#FFFFFFFF")); + } + } +} From e8a64227c32df5a26923072038ba2033b2662d49 Mon Sep 17 00:00:00 2001 From: Lynxifyy <297587416+Lynxifyy@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:46:55 +0000 Subject: [PATCH 4/5] fix(build): keep the version manager under its size budget and the tab at API 28 VersionManager crossed its file-size baseline once import grew, so the archive unpacking moved to ArchiveExtractor; the tab used Stream.toList, which the API-28 gate rejects. --- .../core/versions/ArchiveExtractor.java | 78 +++++++++++++++++++ .../core/versions/VersionManager.java | 49 +----------- .../caramel/launcher/CaramelCurseForgeTab.kt | 2 +- 3 files changed, 80 insertions(+), 49 deletions(-) create mode 100644 app/src/main/java/org/chimeramc/client/launcher/core/versions/ArchiveExtractor.java 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/VersionManager.java b/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java index d79a6f323..3c5e61938 100644 --- a/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java +++ b/app/src/main/java/org/chimeramc/client/launcher/core/versions/VersionManager.java @@ -1344,7 +1344,7 @@ private void extractAndSplit(File gameFile, ImportedPackageLayout.Kind kind, callback.onProgress(10); if (kind == ImportedPackageLayout.Kind.ARCHIVE) { - extractArchive(gameFile, tempDir, callback); + ArchiveExtractor.extract(gameFile, tempDir, callback::onProgress); } else { File apkDir = new File(tempDir, ImportedPackageLayout.APK_DIR); apkDir.mkdirs(); @@ -1378,53 +1378,6 @@ private void extractAndSplit(File gameFile, ImportedPackageLayout.Kind kind, deleteDir(tempDir); } - private void extractArchive(File archive, File outputDir, VersionCallback callback) throws IOException { - try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)))) { - ZipEntry entry; - int totalEntries = Math.max(1, countEntries(archive)); - int processed = 0; - - while ((entry = zis.getNextEntry()) != null) { - if (ImportedPackageLayout.isUnsafeEntry(entry.getName())) { - AppLog.warnOnce(TAG, "import-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 fos = new FileOutputStream(outputFile)) { - byte[] buffer = new byte[BUFFER_SIZE]; - int len; - while ((len = zis.read(buffer)) > 0) { - fos.write(buffer, 0, len); - } - } - } - - processed++; - int progress = 10 + (processed * 40 / totalEntries); - callback.onProgress(progress); - - zis.closeEntry(); - } - } - } - private 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; - } private void splitIntoSandbox(File sourceDir, File versionDir, VersionCallback callback) { // Create sandboxed directory structure diff --git a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt index b7c050764..ef85283a8 100644 --- a/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt +++ b/app/src/main/java/org/chimeramc/client/ui/compose/caramel/launcher/CaramelCurseForgeTab.kt @@ -90,7 +90,7 @@ fun CaramelCurseForgeScreen( } 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.toList(), key = { it.name }) { section -> + items(CurseForgeSection.entries, key = { it.name }) { section -> FilterChip( section.label(), state.curseForgeSection == section, From fa51f4852db688d9e6f375e722f8e3f461d82f34 Mon Sep 17 00:00:00 2001 From: Lynxifyy <297587416+Lynxifyy@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:02:18 +0000 Subject: [PATCH 5/5] docs(agents): record the CurseForge browse contract and the package import layout Both bugs came from a contract nobody had written down: the CurseForge tab only searched on demand, and the importer assumed every package already had the installer's layout. --- AGENTS.md | 1 + docs/agents/caramel-curseforge-tab.md | 8 ++++++++ .../agents/installations-tab-pluggable-package-sources.md | 6 ++++++ 3 files changed, 15 insertions(+) create mode 100644 docs/agents/caramel-curseforge-tab.md 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/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//`, so nothing was moved: the instance was registered, appeared in the list, and had no APK to boot. `ImportedPackageLayout.normalise` collects every APK/OBB/manifest wherever the archive put it (up to four folders deep, so an exported instance nested in one folder works too), makes the **largest** APK `base.apk`, and keeps the splits under their own names. It is idempotent, so running it on an already-correct tree is safe. `ImportedPackageLayoutTest` builds both trees on a real temporary directory. +- **Archive entries are checked before they are written.** `ArchiveExtractor` skips any entry whose name resolves outside the scratch directory (`../`, a leading `/`, a Windows `\`) — the previous code joined the entry name to the output directory and wrote it, which is a write anywhere the app can reach. `ImportedPackageLayout.isUnsafeEntry` is the rule and is unit-tested on its own. +- **The import has a progress dialog now.** Progress used to be written to `busyMessage`, which only the sign-in dialog reads, so a multi-minute import looked like a frozen launcher. `state.importProgress` (-1 when idle) drives `CaramelImportProgressModal`: a ring, the percentage in Press Start 2P, and a line saying to keep the launcher open. It cannot be dismissed from the outside, because the import runs on a disk executor and a dismissed dialog would be a lie about what is happening. +- `VersionManager` hit its `FileSizeBudgetTest` baseline while this shipped, which is why the unpacking lives in `ArchiveExtractor` rather than inline: the budget is a one-way ratchet, so the fix is to split, never to raise the number.