Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
* <p>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,
Expand All @@ -68,7 +75,7 @@ public void onSuccess(ContentSearchResponse result) {
rows.add(toItem(content));
}
}
main(() -> listener.onResults(rows));
main(() -> listener.onResults(CurseForgeSectionsKt.sortedByDownloads(rows)));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ContentSearchResponse> 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);
Expand All @@ -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<ContentSearchResponse> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
*
* <p>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 {

Expand All @@ -25,9 +24,19 @@ protected String getModId() {
return ModIds.MOD_MENU;
}

/**
* The drawable the floating button wears.
*
* <p>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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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;
}
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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 <em>own</em> layout — {@code base.apk}, {@code split_config.*.apk},
* {@code Android/obb/<pkg>/main.<n>.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.
*
* <p>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.
*
* <p>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.
*
* <p>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}.
*
* <p>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<File> apks = new ArrayList<>();
List<File> obbs = new ArrayList<>();
List<File> 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<File> apks, List<File> obbs,
List<File> 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<File> 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();
}
}
}
Loading
Loading