重构 ModTranslations (#6987)
This commit is contained in:
1 parent
0cfc2471a0
commit
4ebbb400ab
21 files changed
+34231
-33242
No files matched your search
+24
-12
@@ -1,4 +1,6 @@
|
||||
import org.jackhuang.hmcl.gradle.TerracottaConfigUpgradeTask
|
||||
import org.jackhuang.hmcl.gradle.addon.FormatJsonFile
|
||||
import org.jackhuang.hmcl.gradle.addon.UpdateAddonProjectInfos
|
||||
import org.jackhuang.hmcl.gradle.ci.GitHubActionUtils
|
||||
import org.jackhuang.hmcl.gradle.ci.JenkinsUtils
|
||||
import org.jackhuang.hmcl.gradle.l10n.CheckTranslations
|
||||
@@ -6,7 +8,6 @@ import org.jackhuang.hmcl.gradle.l10n.CreateLanguageList
|
||||
import org.jackhuang.hmcl.gradle.l10n.CreateLocaleNamesResourceBundle
|
||||
import org.jackhuang.hmcl.gradle.l10n.SyncTranslations
|
||||
import org.jackhuang.hmcl.gradle.l10n.UpsideDownTranslate
|
||||
import org.jackhuang.hmcl.gradle.mod.ParseModDataTask
|
||||
import org.jackhuang.hmcl.gradle.pack.CreateDeb
|
||||
import org.jackhuang.hmcl.gradle.pack.ReleaseType
|
||||
import org.jackhuang.hmcl.gradle.utils.PropertiesUtils
|
||||
@@ -462,21 +463,32 @@ val createLanguageList = tasks.register<CreateLanguageList>("createLanguageList"
|
||||
outputFile.set(generatedDir.map { it.file("languages.json") })
|
||||
}
|
||||
|
||||
val createLocaleNamesResourceBundle = tasks.register<CreateLocaleNamesResourceBundle>("createLocaleNamesResourceBundle") {
|
||||
dependsOn(createLanguageList)
|
||||
val createLocaleNamesResourceBundle =
|
||||
tasks.register<CreateLocaleNamesResourceBundle>("createLocaleNamesResourceBundle") {
|
||||
dependsOn(createLanguageList)
|
||||
|
||||
languagesFile.set(createLanguageList.flatMap { it.outputFile })
|
||||
outputDirectory.set(generatedDir.map { it.dir("generated/LocaleNames") })
|
||||
}
|
||||
languagesFile.set(createLanguageList.flatMap { it.outputFile })
|
||||
outputDirectory.set(generatedDir.map { it.dir("generated/LocaleNames") })
|
||||
}
|
||||
|
||||
// mcmod data
|
||||
|
||||
tasks.register<ParseModDataTask>("parseModData") {
|
||||
inputFile.set(layout.projectDirectory.file("mod.json"))
|
||||
outputFile.set(layout.projectDirectory.file("src/main/resources/assets/mod_data.txt"))
|
||||
tasks.register<FormatJsonFile>("formatModJson") {
|
||||
file.set(layout.projectDirectory.file("mod.json"))
|
||||
}
|
||||
|
||||
tasks.register<ParseModDataTask>("parseModPackData") {
|
||||
inputFile.set(layout.projectDirectory.file("modpack.json"))
|
||||
outputFile.set(layout.projectDirectory.file("src/main/resources/assets/modpack_data.txt"))
|
||||
tasks.register<FormatJsonFile>("formatModpackJson") {
|
||||
file.set(layout.projectDirectory.file("modpack.json"))
|
||||
}
|
||||
|
||||
tasks.register<UpdateAddonProjectInfos>("updateModProjectInfos") {
|
||||
inputFile.set(layout.projectDirectory.file("mod.json"))
|
||||
outputFile.set(layout.projectDirectory.file("src/main/resources/assets/addon/mod.csv"))
|
||||
projectType.set(UpdateAddonProjectInfos.AddonProjectType.MOD)
|
||||
}
|
||||
|
||||
tasks.register<UpdateAddonProjectInfos>("updateModpackProjectInfos") {
|
||||
inputFile.set(layout.projectDirectory.file("modpack.json"))
|
||||
outputFile.set(layout.projectDirectory.file("src/main/resources/assets/addon/modpack.csv"))
|
||||
projectType.set(UpdateAddonProjectInfos.AddonProjectType.MODPACK)
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.addon;
|
||||
|
||||
import org.jackhuang.hmcl.addon.mod.ModProjectInfo;
|
||||
import org.jackhuang.hmcl.modpack.ModpackProjectInfo;
|
||||
import org.jackhuang.hmcl.util.Pair;
|
||||
import org.jackhuang.hmcl.util.StringUtils;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
|
||||
|
||||
/// @author Glavo
|
||||
@NotNullByDefault
|
||||
public abstract class AddonProjectInfoRegistry<I extends AddonProjectInfo> {
|
||||
public static final AddonProjectInfoRegistry<ModProjectInfo> MOD = new AddonProjectInfoRegistry<>(
|
||||
"/assets/addon/mod.csv",
|
||||
32768
|
||||
) {
|
||||
@Override
|
||||
protected int getFieldsCount() {
|
||||
return MOD_IDS_INDEX + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ModProjectInfo parseAddonProjectInfo(String[] fields) throws Exception {
|
||||
return new ModProjectInfo(
|
||||
Integer.parseInt(fields[MCMOD_ID_INDEX]),
|
||||
fields[CURSEFORGE_ID_INDEX],
|
||||
fields[MODRINTH_ID_INDEX],
|
||||
fields[MAIN_NAME_INDEX],
|
||||
fields[SUB_NAME_INDEX],
|
||||
fields[ABBR_NAME_INDEX],
|
||||
fields[MOD_IDS_INDEX]
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/// Provides metadata for modpacks.
|
||||
public static final AddonProjectInfoRegistry<ModpackProjectInfo> MODPACK = new AddonProjectInfoRegistry<>(
|
||||
"/assets/addon/modpack.csv", 2048
|
||||
) {
|
||||
@Override
|
||||
protected int getFieldsCount() {
|
||||
return ABBR_NAME_INDEX + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ModpackProjectInfo parseAddonProjectInfo(String[] fields) {
|
||||
return new ModpackProjectInfo(Integer.parseInt(fields[MCMOD_ID_INDEX]),
|
||||
fields[CURSEFORGE_ID_INDEX], fields[MODRINTH_ID_INDEX],
|
||||
fields[MAIN_NAME_INDEX], fields[SUB_NAME_INDEX], fields[ABBR_NAME_INDEX]);
|
||||
}
|
||||
};
|
||||
|
||||
/// Returns the registry for the addon type, or `null` for null or unsupported types.
|
||||
public static @Nullable AddonProjectInfoRegistry<?> getByAddonType(@Nullable RemoteAddon.Type type) {
|
||||
if (type == null) return null;
|
||||
return switch (type) {
|
||||
case MOD -> MOD;
|
||||
case MODPACK -> MODPACK;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
protected static final int MCMOD_ID_INDEX = 0;
|
||||
protected static final int CURSEFORGE_ID_INDEX = 1;
|
||||
protected static final int MODRINTH_ID_INDEX = 2;
|
||||
protected static final int MAIN_NAME_INDEX = 3;
|
||||
protected static final int SUB_NAME_INDEX = 4;
|
||||
protected static final int ABBR_NAME_INDEX = 5;
|
||||
protected static final int MOD_IDS_INDEX = 6;
|
||||
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
private final String assetsPath;
|
||||
private final int initialCapacity;
|
||||
|
||||
private volatile @Nullable SoftReference<@Unmodifiable List<I>> infosRef;
|
||||
|
||||
/// Softly caches projects indexed by mod ID.
|
||||
private volatile @Nullable SoftReference<@Unmodifiable Map<String, I>> modIdMapRef;
|
||||
|
||||
/// Softly caches projects indexed by cleaned secondary name.
|
||||
private volatile @Nullable SoftReference<@Unmodifiable Map<String, I>> subnameMapRef;
|
||||
|
||||
/// Softly caches projects indexed by CurseForge identifier.
|
||||
private volatile @Nullable SoftReference<@Unmodifiable Map<String, I>> curseForgeMapRef;
|
||||
|
||||
/// Softly caches searchable names in resource and field order.
|
||||
private volatile @Nullable SoftReference<@Unmodifiable List<Pair<String, I>>> keywordsRef;
|
||||
|
||||
/// Creates a registry reading records from the given classpath resource.
|
||||
AddonProjectInfoRegistry(String assetsPath, int initialCapacity) {
|
||||
this.assetsPath = assetsPath;
|
||||
this.initialCapacity = initialCapacity;
|
||||
}
|
||||
|
||||
protected abstract int getFieldsCount();
|
||||
|
||||
protected abstract I parseAddonProjectInfo(String[] fields) throws Exception;
|
||||
|
||||
private @Unmodifiable List<I> loadInfos() throws IOException {
|
||||
@Nullable InputStream inputStream = AddonProjectInfoRegistry.class.getResourceAsStream(assetsPath);
|
||||
if (inputStream == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
try (var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
ArrayList<I> infos = new ArrayList<>(initialCapacity);
|
||||
@Unmodifiable List<I> result = Collections.unmodifiableList(infos);
|
||||
|
||||
int fieldsCount = getFieldsCount();
|
||||
String[] fields = new String[fieldsCount];
|
||||
|
||||
@Nullable StringBuilder fieldBuilder = null;
|
||||
|
||||
@Nullable String line;
|
||||
loop:
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int offset = 0;
|
||||
for (int fieldIndex = 0; fieldIndex < fieldsCount; fieldIndex++) {
|
||||
if (offset > line.length()) {
|
||||
LOG.warning("Invalid line in " + assetsPath + ": " + line);
|
||||
continue loop;
|
||||
}
|
||||
|
||||
int end = line.indexOf(',', offset);
|
||||
if (end < 0)
|
||||
end = line.length();
|
||||
|
||||
|
||||
String field;
|
||||
if (offset == end) {
|
||||
field = "";
|
||||
} else {
|
||||
int cursor = offset;
|
||||
while (cursor < end) {
|
||||
if (line.charAt(cursor) == '\\') {
|
||||
break;
|
||||
} else {
|
||||
cursor++;
|
||||
}
|
||||
}
|
||||
|
||||
if (cursor == end) {
|
||||
field = line.substring(offset, end);
|
||||
} else {
|
||||
if (fieldBuilder == null) {
|
||||
fieldBuilder = new StringBuilder(32);
|
||||
} else {
|
||||
fieldBuilder.setLength(0);
|
||||
}
|
||||
|
||||
fieldBuilder.append(line, offset, cursor);
|
||||
while (cursor < end) {
|
||||
char c = line.charAt(cursor);
|
||||
if (c == '\\') {
|
||||
if (cursor < end - 1) {
|
||||
char next = line.charAt(cursor + 1);
|
||||
switch (next) {
|
||||
case '0' -> {
|
||||
fieldBuilder.append('\0');
|
||||
cursor += 2;
|
||||
}
|
||||
case 'n' -> {
|
||||
fieldBuilder.append('\n');
|
||||
cursor += 2;
|
||||
}
|
||||
case 'r' -> {
|
||||
fieldBuilder.append('\r');
|
||||
cursor += 2;
|
||||
}
|
||||
case 't' -> {
|
||||
fieldBuilder.append('\t');
|
||||
cursor += 2;
|
||||
}
|
||||
case '\\' -> {
|
||||
fieldBuilder.append('\\');
|
||||
cursor += 2;
|
||||
}
|
||||
case 'c' -> {
|
||||
fieldBuilder.append(',');
|
||||
cursor += 2;
|
||||
}
|
||||
case 'u' -> {
|
||||
if (cursor < end - 5) {
|
||||
try {
|
||||
int codePoint = Integer.parseInt(line, cursor + 2, cursor + 6, 16);
|
||||
fieldBuilder.append((char) codePoint);
|
||||
cursor += 6;
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.warning("Invalid line in " + assetsPath + ": " + line);
|
||||
continue loop;
|
||||
}
|
||||
} else {
|
||||
fieldBuilder.append(c);
|
||||
cursor++;
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
LOG.warning("Invalid line in " + assetsPath + ": " + line);
|
||||
continue loop;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fieldBuilder.append(c);
|
||||
cursor++;
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
fieldBuilder.append(c);
|
||||
cursor++;
|
||||
}
|
||||
}
|
||||
field = fieldBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
fields[fieldIndex] = field;
|
||||
offset = end + 1;
|
||||
}
|
||||
|
||||
try {
|
||||
I info = parseAddonProjectInfo(fields);
|
||||
info.setKeepAlive(result);
|
||||
infos.add(info);
|
||||
} catch (Exception e) {
|
||||
LOG.warning("Failed to parse line in " + assetsPath + ": " + line, e);
|
||||
}
|
||||
}
|
||||
|
||||
infos.trimToSize();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an unmodifiable index, rebuilding it after its soft reference is cleared.
|
||||
/// Duplicate keys retain the first project in resource order.
|
||||
private @Unmodifiable Map<String, I> getModIdMap() {
|
||||
@Nullable SoftReference<@Unmodifiable Map<String, I>> reference = this.modIdMapRef;
|
||||
@Unmodifiable Map<String, I> cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
lock.lock();
|
||||
try {
|
||||
reference = this.modIdMapRef;
|
||||
cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
Map<String, I> map = new HashMap<>();
|
||||
for (I info : getInfos()) {
|
||||
if (info instanceof ModProjectInfo mod) {
|
||||
for (String id : mod.getModIds()) {
|
||||
if (!id.isEmpty())
|
||||
map.putIfAbsent(id, info);
|
||||
}
|
||||
}
|
||||
}
|
||||
cached = Collections.unmodifiableMap(map);
|
||||
this.modIdMapRef = new SoftReference<>(cached);
|
||||
return cached;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an unmodifiable index, rebuilding it after its soft reference is cleared.
|
||||
/// Duplicate keys retain the first project in resource order.
|
||||
private @Unmodifiable Map<String, I> getSubnameMap() {
|
||||
@Nullable SoftReference<@Unmodifiable Map<String, I>> reference = this.subnameMapRef;
|
||||
@Unmodifiable Map<String, I> cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
lock.lock();
|
||||
try {
|
||||
reference = this.subnameMapRef;
|
||||
cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
Map<String, I> map = new HashMap<>();
|
||||
for (I info : getInfos()) {
|
||||
String name = cleanSubname(info.subName());
|
||||
if (!name.isEmpty())
|
||||
map.putIfAbsent(name, info);
|
||||
}
|
||||
cached = Collections.unmodifiableMap(map);
|
||||
this.subnameMapRef = new SoftReference<>(cached);
|
||||
return cached;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an unmodifiable index, rebuilding it after its soft reference is cleared.
|
||||
/// Duplicate keys retain the first project in resource order.
|
||||
private @Unmodifiable Map<String, I> getCurseForgeMap() {
|
||||
@Nullable SoftReference<@Unmodifiable Map<String, I>> reference = this.curseForgeMapRef;
|
||||
@Unmodifiable Map<String, I> cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
lock.lock();
|
||||
try {
|
||||
reference = this.curseForgeMapRef;
|
||||
cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
Map<String, I> map = new HashMap<>();
|
||||
for (I info : getInfos()) {
|
||||
String id = info.curseforgeId();
|
||||
if (StringUtils.isNotBlank(id))
|
||||
map.putIfAbsent(id, info);
|
||||
}
|
||||
cached = Collections.unmodifiableMap(map);
|
||||
this.curseForgeMapRef = new SoftReference<>(cached);
|
||||
return cached;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the first project with the exact CurseForge identifier, or `null` if the
|
||||
/// identifier is null, blank or unknown.
|
||||
public @Nullable I getInfoByCurseForgeId(@Nullable String id) {
|
||||
return StringUtils.isBlank(id) ? null : getCurseForgeMap().get(id);
|
||||
}
|
||||
|
||||
/// Finds a project by its cleaned secondary name, falling back to its exact mod ID.
|
||||
/// A name match is accepted only when the ID is blank or belongs to that mod project.
|
||||
/// Null and blank inputs are absent; returns `null` if neither lookup matches.
|
||||
/// Duplicate keys resolve to the first project in resource order.
|
||||
public @Nullable I getInfo(@Nullable String id, @Nullable String subname) {
|
||||
String name = cleanSubname(subname);
|
||||
if (StringUtils.isNotBlank(name)) {
|
||||
@Nullable I info = getSubnameMap().get(name);
|
||||
if (info != null && (StringUtils.isBlank(id)
|
||||
|| info instanceof ModProjectInfo mod && mod.getModIds().contains(id)))
|
||||
return info;
|
||||
}
|
||||
return StringUtils.isBlank(id) ? null : getModIdMap().get(id);
|
||||
}
|
||||
|
||||
private static boolean isSupportedSubnameChar(int ch) {
|
||||
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
|
||||
|| ".+\\".indexOf(ch) >= 0;
|
||||
}
|
||||
|
||||
/// Removes supported separators and pictographs from a secondary name.
|
||||
/// Returns an empty string for null, blank or unsupported names; matching is case-sensitive.
|
||||
private static String cleanSubname(@Nullable String subname) {
|
||||
if (StringUtils.isBlank(subname))
|
||||
return "";
|
||||
|
||||
int offset = 0;
|
||||
while (offset < subname.length()) {
|
||||
int ch = subname.charAt(offset);
|
||||
if (!isSupportedSubnameChar(ch))
|
||||
break;
|
||||
offset++;
|
||||
}
|
||||
|
||||
if (offset == subname.length())
|
||||
return subname;
|
||||
|
||||
StringBuilder builder = new StringBuilder(subname.length());
|
||||
builder.append(subname, 0, offset);
|
||||
|
||||
while (offset < subname.length()) {
|
||||
int ch = subname.codePointAt(offset);
|
||||
if (isSupportedSubnameChar(ch)) {
|
||||
builder.appendCodePoint(ch);
|
||||
} else if (!(Character.isWhitespace(ch)
|
||||
|| "':_-/&()[]{}|,!?~•".indexOf(ch) >= 0
|
||||
|| ch >= 0x1F300 && ch <= 0x1FAFF)) {
|
||||
return "";
|
||||
}
|
||||
offset += Character.charCount(ch);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/// Returns searchable names, rebuilding the index after its soft reference is cleared.
|
||||
private @Unmodifiable List<Pair<String, I>> getKeywords() {
|
||||
@Nullable SoftReference<@Unmodifiable List<Pair<String, I>>> reference = keywordsRef;
|
||||
@Unmodifiable List<Pair<String, I>> cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
lock.lock();
|
||||
try {
|
||||
reference = keywordsRef;
|
||||
cached = reference != null ? reference.get() : null;
|
||||
if (cached != null)
|
||||
return cached;
|
||||
List<Pair<String, I>> keywords = new ArrayList<>();
|
||||
for (I info : getInfos()) {
|
||||
if (!info.mainName().isEmpty())
|
||||
keywords.add(Pair.pair(info.mainName(), info));
|
||||
if (!info.subName().isEmpty())
|
||||
keywords.add(Pair.pair(info.subName(), info));
|
||||
if (!info.abbrName().isEmpty())
|
||||
keywords.add(Pair.pair(info.abbrName(), info));
|
||||
}
|
||||
cached = List.copyOf(keywords);
|
||||
keywordsRef = new SoftReference<>(cached);
|
||||
return cached;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns projects ranked by descending longest common subsequence length after removing
|
||||
/// space characters from the query. Comparison is case-sensitive and uses UTF-16 units.
|
||||
/// Matches require at least one unit and at least query length minus three units.
|
||||
/// Each matching name contributes a result, so projects may occur more than once.
|
||||
/// Ties preserve resource order, then primary name, secondary name and abbreviation order.
|
||||
public @Unmodifiable List<I> search(String query) {
|
||||
query = query.chars().filter(ch -> !Character.isSpaceChar(ch))
|
||||
.collect(StringBuilder::new, (sb, ch) -> sb.append((char) ch), StringBuilder::append).toString();
|
||||
@Unmodifiable List<Pair<String, I>> keywords = getKeywords();
|
||||
int maxLength = keywords.stream().mapToInt(keyword -> keyword.getKey().length()).max().orElse(0);
|
||||
StringUtils.LongestCommonSubsequence lcs = new StringUtils.LongestCommonSubsequence(query.length(), maxLength);
|
||||
List<Pair<Integer, I>> matches = new ArrayList<>();
|
||||
for (Pair<String, I> keyword : keywords) {
|
||||
int score = lcs.calc(query, keyword.getKey());
|
||||
if (score >= Math.max(1, query.length() - 3))
|
||||
matches.add(Pair.pair(score, keyword.getValue()));
|
||||
}
|
||||
return matches.stream().sorted((a, b) -> Integer.compare(b.getKey(), a.getKey()))
|
||||
.map(Pair::getValue).toList();
|
||||
}
|
||||
|
||||
/// Returns cached project metadata, loading it on demand. Missing resources and I/O failures
|
||||
/// produce an empty list; malformed records are skipped. The cache is softly referenced.
|
||||
public @Unmodifiable List<I> getInfos() {
|
||||
@Nullable SoftReference<@Unmodifiable List<I>> infosRef = this.infosRef;
|
||||
@Unmodifiable List<I> infos = infosRef != null ? infosRef.get() : null;
|
||||
if (infos != null)
|
||||
return infos;
|
||||
|
||||
lock.lock();
|
||||
try {
|
||||
infosRef = this.infosRef;
|
||||
infos = infosRef != null ? infosRef.get() : null;
|
||||
if (infos != null)
|
||||
return infos;
|
||||
|
||||
try {
|
||||
infos = loadInfos();
|
||||
} catch (IOException e) {
|
||||
LOG.warning("Failed to load addon project info from " + assetsPath, e);
|
||||
infos = List.of();
|
||||
}
|
||||
this.infosRef = new SoftReference<>(infos);
|
||||
return infos;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,12 @@ package org.jackhuang.hmcl.game;
|
||||
import org.jackhuang.hmcl.download.DownloadProvider;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddon;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddonRepository;
|
||||
import org.jackhuang.hmcl.ui.instances.ModTranslations;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfo;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfoRegistry;
|
||||
import org.jackhuang.hmcl.util.Pair;
|
||||
import org.jackhuang.hmcl.util.StringUtils;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
@@ -51,15 +53,16 @@ public abstract class LocalizedRemoteAddonRepository implements RemoteAddonRepos
|
||||
|
||||
@Override
|
||||
public SearchResult search(DownloadProvider downloadProvider, RemoteAddon.Type type, String gameVersion, Category category, int pageOffset, int pageSize, String searchFilter, SortType sort, SortOrder sortOrder) throws IOException {
|
||||
if (!StringUtils.containsChinese(searchFilter)) {
|
||||
@Nullable AddonProjectInfoRegistry<?> registry = AddonProjectInfoRegistry.getByAddonType(type);
|
||||
if (registry == null || !StringUtils.containsChinese(searchFilter)) {
|
||||
return getBackedRemoteModRepository().search(downloadProvider, type, gameVersion, category, pageOffset, pageSize, searchFilter, sort, sortOrder);
|
||||
}
|
||||
|
||||
Set<String> englishSearchFiltersSet = new LinkedHashSet<>(INITIAL_CAPACITY);
|
||||
|
||||
int count = 0;
|
||||
for (ModTranslations.Mod mod : ModTranslations.getTranslationsByAddonType(type).searchMod(searchFilter)) {
|
||||
String englishSearchFilter = String.join(" ", StringUtils.tokenize(StringUtils.isNotBlank(mod.getSubname()) ? mod.getSubname() : mod.getName()));
|
||||
for (AddonProjectInfo mod : registry.search(searchFilter)) {
|
||||
String englishSearchFilter = String.join(" ", StringUtils.tokenize(StringUtils.isNotBlank(mod.subName()) ? mod.subName() : mod.mainName()));
|
||||
if (StringUtils.isNotBlank(englishSearchFilter)) {
|
||||
englishSearchFiltersSet.add(englishSearchFilter);
|
||||
}
|
||||
@@ -91,8 +94,8 @@ public abstract class LocalizedRemoteAddonRepository implements RemoteAddonRepos
|
||||
continue;
|
||||
}
|
||||
|
||||
ModTranslations.Mod chineseTranslation = ModTranslations.getTranslationsByAddonType(type).getModByCurseForgeId(remoteAddon.slug());
|
||||
if (chineseTranslation != null && !StringUtils.isBlank(chineseTranslation.getName()) && StringUtils.containsChinese(chineseTranslation.getName())) {
|
||||
@Nullable AddonProjectInfo chineseTranslation = registry.getInfoByCurseForgeId(remoteAddon.slug());
|
||||
if (chineseTranslation != null && !StringUtils.isBlank(chineseTranslation.mainName()) && StringUtils.containsChinese(chineseTranslation.mainName())) {
|
||||
searchResultArray[chineseIndex++] = remoteAddon;
|
||||
} else {
|
||||
searchResultArray[englishIndex--] = remoteAddon;
|
||||
@@ -103,11 +106,11 @@ public abstract class LocalizedRemoteAddonRepository implements RemoteAddonRepos
|
||||
|
||||
StringUtils.LevCalculator levCalculator = new StringUtils.LevCalculator();
|
||||
return new SearchResult(Stream.concat(Arrays.stream(searchResultArray, 0, chineseIndex).map(remoteMod -> {
|
||||
ModTranslations.Mod chineseRemoteMod = ModTranslations.getTranslationsByAddonType(type).getModByCurseForgeId(remoteMod.slug());
|
||||
if (chineseRemoteMod == null || StringUtils.isBlank(chineseRemoteMod.getName()) || !StringUtils.containsChinese(chineseRemoteMod.getName())) {
|
||||
@Nullable AddonProjectInfo chineseRemoteMod = registry.getInfoByCurseForgeId(remoteMod.slug());
|
||||
if (chineseRemoteMod == null || StringUtils.isBlank(chineseRemoteMod.mainName()) || !StringUtils.containsChinese(chineseRemoteMod.mainName())) {
|
||||
return Pair.pair(remoteMod, Integer.MAX_VALUE);
|
||||
}
|
||||
String chineseRemoteModName = chineseRemoteMod.getName();
|
||||
String chineseRemoteModName = chineseRemoteMod.mainName();
|
||||
if (searchFilter.isEmpty() || chineseRemoteModName.isEmpty()) {
|
||||
return Pair.pair(remoteMod, Math.max(searchFilter.length(), chineseRemoteModName.length()));
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
import javafx.scene.layout.*;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddon;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfo;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfoRegistry;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddonRepository;
|
||||
import org.jackhuang.hmcl.addon.repository.ModrinthRemoteAddonRepository;
|
||||
import org.jackhuang.hmcl.download.DownloadCandidates;
|
||||
@@ -606,8 +608,9 @@ public class DownloadListPage extends Control implements DecoratorPage {
|
||||
: PADDING
|
||||
);
|
||||
|
||||
ModTranslations.Mod mod = ModTranslations.getTranslationsByAddonType(getSkinnable().type).getModByCurseForgeId(item.slug());
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.getDisplayName() : item.title());
|
||||
@Nullable AddonProjectInfoRegistry<?> registry = AddonProjectInfoRegistry.getByAddonType(getSkinnable().type);
|
||||
@Nullable AddonProjectInfo mod = registry != null ? registry.getInfoByCurseForgeId(item.slug()) : null;
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.displayName() : item.title());
|
||||
String description = item.description();
|
||||
if (description != null) {
|
||||
description = description.replaceAll("\\R", " ");
|
||||
|
||||
@@ -30,6 +30,8 @@ import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.FileChooser;
|
||||
import org.jackhuang.hmcl.addon.AddonLoader;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfo;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfoRegistry;
|
||||
import org.jackhuang.hmcl.download.DownloadProvider;
|
||||
import org.jackhuang.hmcl.game.*;
|
||||
import org.jackhuang.hmcl.addon.mod.ModLoaderType;
|
||||
@@ -65,9 +67,9 @@ public class DownloadPage extends Control implements DecoratorPage {
|
||||
private final BooleanProperty loading = new SimpleBooleanProperty(false);
|
||||
private final BooleanProperty failed = new SimpleBooleanProperty(false);
|
||||
private final RemoteAddonRepository repository;
|
||||
private final ModTranslations translations;
|
||||
private final RemoteAddon addon;
|
||||
private final ModTranslations.Mod mod;
|
||||
/// Localized project metadata, or null when no registry or matching project is available.
|
||||
private final @Nullable AddonProjectInfo mod;
|
||||
private final HMCLGameInstance.Optional instanceReference;
|
||||
private final DownloadCallback callback;
|
||||
private final DownloadListPage page;
|
||||
@@ -80,8 +82,8 @@ public class DownloadPage extends Control implements DecoratorPage {
|
||||
this.repository = page.repository;
|
||||
this.addon = addon;
|
||||
this.type = Objects.requireNonNullElse(addon.type(), page.type);
|
||||
this.translations = ModTranslations.getTranslationsByAddonType(this.type);
|
||||
this.mod = translations.getModByCurseForgeId(addon.slug());
|
||||
@Nullable AddonProjectInfoRegistry<?> registry = AddonProjectInfoRegistry.getByAddonType(this.type);
|
||||
this.mod = registry != null ? registry.getInfoByCurseForgeId(addon.slug()) : null;
|
||||
this.instanceReference = instanceReference;
|
||||
this.callback = callback;
|
||||
loadAddonVersions();
|
||||
@@ -220,8 +222,8 @@ public class DownloadPage extends Control implements DecoratorPage {
|
||||
|
||||
TwoLineListItem content = new TwoLineListItem();
|
||||
HBox.setHgrow(content, Priority.ALWAYS);
|
||||
ModTranslations.Mod mod = getSkinnable().translations.getModByCurseForgeId(getSkinnable().addon.slug());
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.getDisplayName() : getSkinnable().addon.title());
|
||||
@Nullable AddonProjectInfo mod = getSkinnable().mod;
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.displayName() : getSkinnable().addon.title());
|
||||
content.setSubtitle(getSkinnable().addon.description());
|
||||
content.getSubtitleLabel().setWrapText(true);
|
||||
getSkinnable().addon.categories().stream()
|
||||
@@ -231,9 +233,10 @@ public class DownloadPage extends Control implements DecoratorPage {
|
||||
content.getFirstLine().setMinWidth(0);
|
||||
descriptionPane.getChildren().add(content);
|
||||
|
||||
if (getSkinnable().mod != null) {
|
||||
@Nullable String mcmodUrl = mod != null ? mod.mcmodUrl() : null;
|
||||
if (mcmodUrl != null) {
|
||||
JFXHyperlink openMcmodButton = new JFXHyperlink(i18n("mods.mcmod"));
|
||||
openMcmodButton.setExternalLink(getSkinnable().translations.getMcmodUrl(getSkinnable().mod));
|
||||
openMcmodButton.setExternalLink(mcmodUrl);
|
||||
descriptionPane.getChildren().add(openMcmodButton);
|
||||
openMcmodButton.setMinWidth(Region.USE_PREF_SIZE);
|
||||
}
|
||||
@@ -414,8 +417,9 @@ public class DownloadPage extends Control implements DecoratorPage {
|
||||
});
|
||||
setNode(IDX_LEADING, pane);
|
||||
|
||||
ModTranslations.Mod mod = ModTranslations.getTranslationsByAddonType(type).getModByCurseForgeId(addon.slug());
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.getDisplayName() : addon.title());
|
||||
@Nullable AddonProjectInfoRegistry<?> registry = AddonProjectInfoRegistry.getByAddonType(type);
|
||||
@Nullable AddonProjectInfo mod = registry != null ? registry.getInfoByCurseForgeId(addon.slug()) : null;
|
||||
content.setTitle(mod != null && I18n.isUseChinese() ? mod.displayName() : addon.title());
|
||||
content.setSubtitle(addon.description());
|
||||
for (String category : addon.categories()) {
|
||||
if (page.shouldDisplayCategory(category))
|
||||
|
||||
@@ -41,6 +41,8 @@ import javafx.scene.layout.StackPane;
|
||||
import javafx.stage.FileChooser;
|
||||
import javafx.util.Duration;
|
||||
import org.jackhuang.hmcl.addon.AddonLoader;
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfoRegistry;
|
||||
import org.jackhuang.hmcl.addon.mod.ModProjectInfo;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddon;
|
||||
import org.jackhuang.hmcl.addon.RemoteAddonRepository;
|
||||
import org.jackhuang.hmcl.addon.repository.CurseForgeRemoteAddonRepository;
|
||||
@@ -541,7 +543,7 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
|| predicate.test(modInfo.getGameVersion())
|
||||
|| predicate.test(modInfo.getId())
|
||||
|| predicate.test(Objects.toString(modInfo.getModLoaderType()))
|
||||
|| predicate.test((item.getModTranslations() != null ? item.getModTranslations().getDisplayName() : null))) {
|
||||
|| predicate.test((item.getProjectInfo() != null ? item.getProjectInfo().displayName() : null))) {
|
||||
listView.getItems().add(item);
|
||||
}
|
||||
}
|
||||
@@ -553,7 +555,8 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
public static final class ModInfoObject {
|
||||
private final BooleanProperty active;
|
||||
private final LocalModFile localModFile;
|
||||
private final @Nullable ModTranslations.Mod modTranslations;
|
||||
/// Matching project metadata, or null if the local mod cannot be identified.
|
||||
private final @Nullable ModProjectInfo projectInfo;
|
||||
|
||||
private final ItemPropertyAsyncCache<Image, ModInfoObject> iconCache;
|
||||
|
||||
@@ -561,7 +564,7 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
this.localModFile = localModFile;
|
||||
this.active = localModFile.activeProperty();
|
||||
|
||||
this.modTranslations = ModTranslations.MOD.getMod(localModFile.getId(), localModFile.getName());
|
||||
this.projectInfo = AddonProjectInfoRegistry.MOD.getInfo(localModFile.getId(), localModFile.getName());
|
||||
|
||||
this.iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon);
|
||||
}
|
||||
@@ -570,8 +573,9 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
return localModFile;
|
||||
}
|
||||
|
||||
public @Nullable ModTranslations.Mod getModTranslations() {
|
||||
return modTranslations;
|
||||
/// Returns matching project metadata, or null if no project was found.
|
||||
public @Nullable ModProjectInfo getProjectInfo() {
|
||||
return projectInfo;
|
||||
}
|
||||
|
||||
private Image getDefaultIcon() {
|
||||
@@ -621,8 +625,8 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
|
||||
TwoLineListItem title = new TwoLineListItem();
|
||||
title.getTitleLabel().setWrapText(true);
|
||||
if (modInfo.getModTranslations() != null && I18n.isUseChinese())
|
||||
title.setTitle(modInfo.getModTranslations().getDisplayName());
|
||||
if (modInfo.getProjectInfo() != null && I18n.isUseChinese())
|
||||
title.setTitle(modInfo.getProjectInfo().displayName());
|
||||
else
|
||||
title.setTitle(modInfo.getModInfo().getName());
|
||||
|
||||
@@ -694,7 +698,8 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
getActions().add(officialPageButton);
|
||||
}
|
||||
|
||||
if (modInfo.getModTranslations() == null || StringUtils.isBlank(modInfo.getModTranslations().getMcmod())) {
|
||||
@Nullable String mcmodUrl = modInfo.getProjectInfo() != null ? modInfo.getProjectInfo().mcmodUrl() : null;
|
||||
if (mcmodUrl == null) {
|
||||
JFXHyperlink searchButton = new JFXHyperlink(i18n("mods.mcmod.search"));
|
||||
searchButton.setExternalLink(NetworkUtils.withQuery("https://search.mcmod.cn/s", mapOf(
|
||||
pair("key", modInfo.getModInfo().getName()),
|
||||
@@ -704,7 +709,7 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
getActions().add(searchButton);
|
||||
} else {
|
||||
JFXHyperlink mcmodButton = new JFXHyperlink(i18n("mods.mcmod.page"));
|
||||
mcmodButton.setExternalLink(ModTranslations.MOD.getMcmodUrl(modInfo.getModTranslations()));
|
||||
mcmodButton.setExternalLink(mcmodUrl);
|
||||
getActions().add(mcmodButton);
|
||||
}
|
||||
|
||||
@@ -775,15 +780,15 @@ public final class ModListPage extends ListPageBase<ModListPage.ModInfoObject> i
|
||||
content.getTags().clear();
|
||||
|
||||
LocalModFile modInfo = dataItem.getModInfo();
|
||||
ModTranslations.Mod modTranslations = dataItem.getModTranslations();
|
||||
@Nullable ModProjectInfo projectInfo = dataItem.getProjectInfo();
|
||||
|
||||
ModLoaderType modLoaderType = modInfo.getModLoaderType();
|
||||
|
||||
dataItem.iconCache.attachValue(imageContainer.imageProperty(), new WeakReference<>(this.itemProperty()));
|
||||
|
||||
String displayName = modInfo.getName();
|
||||
if (modTranslations != null && I18n.isUseChinese()) {
|
||||
String chineseName = modTranslations.getName();
|
||||
if (projectInfo != null && I18n.isUseChinese()) {
|
||||
String chineseName = projectInfo.mainName();
|
||||
if (StringUtils.containsChinese(chineseName)) {
|
||||
if (StringUtils.containsEmoji(chineseName)) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
@@ -1,353 +0,0 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2021 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.ui.instances;
|
||||
|
||||
import org.jackhuang.hmcl.addon.RemoteAddon;
|
||||
import org.jackhuang.hmcl.util.Pair;
|
||||
import org.jackhuang.hmcl.util.StringUtils;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
|
||||
import static org.jackhuang.hmcl.util.Pair.pair;
|
||||
|
||||
/**
|
||||
* Parser for mod_data.txt
|
||||
*
|
||||
* @see <a href="https://www.mcmod.cn">mcmod.cn</a>
|
||||
*/
|
||||
public enum ModTranslations {
|
||||
MOD("/assets/mod_data.txt") {
|
||||
@Override
|
||||
public String getMcmodUrl(Mod mod) {
|
||||
return String.format("https://www.mcmod.cn/class/%s.html", mod.getMcmod());
|
||||
}
|
||||
},
|
||||
MODPACK("/assets/modpack_data.txt") {
|
||||
@Override
|
||||
public String getMcmodUrl(Mod mod) {
|
||||
return String.format("https://www.mcmod.cn/modpack/%s.html", mod.getMcmod());
|
||||
}
|
||||
},
|
||||
EMPTY("") {
|
||||
@Override
|
||||
public String getMcmodUrl(Mod mod) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
public static ModTranslations getTranslationsByAddonType(@Nullable RemoteAddon.Type type) {
|
||||
if (type == null) return EMPTY;
|
||||
return switch (type) {
|
||||
case MOD -> MOD;
|
||||
case MODPACK -> MODPACK;
|
||||
default -> EMPTY;
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
private static String cleanSubname(String subname) {
|
||||
if (StringUtils.isBlank(subname))
|
||||
return "";
|
||||
|
||||
StringBuilder builder = new StringBuilder(subname.length());
|
||||
for (int i = 0; i < subname.length(); ) {
|
||||
int ch = subname.codePointAt(i);
|
||||
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')
|
||||
|| ".+\\".indexOf(ch) >= 0) {
|
||||
builder.appendCodePoint(ch);
|
||||
} else if (Character.isWhitespace(ch)
|
||||
|| "':_-/&()[]{}|,!?~•".indexOf(ch) >= 0
|
||||
|| ch >= 0x1F300 && ch <= 0x1FAFF) {
|
||||
// Remove these unnecessary characters from subname
|
||||
} else {
|
||||
// The subname contains unsupported characters, so we do not use this subname to match the mod
|
||||
return "";
|
||||
}
|
||||
i += Character.charCount(ch);
|
||||
}
|
||||
return builder.length() == subname.length() ? subname : builder.toString();
|
||||
}
|
||||
|
||||
private final String resourceName;
|
||||
private volatile List<Mod> mods;
|
||||
private volatile Map<String, Mod> modIdMap; // mod id -> mod
|
||||
private volatile Map<String, Mod> subnameMap;
|
||||
private volatile Map<String, Mod> curseForgeMap; // curseforge id -> mod
|
||||
private volatile List<Pair<String, Mod>> keywords;
|
||||
private volatile int maxKeywordLength = -1;
|
||||
|
||||
ModTranslations(String resourceName) {
|
||||
this.resourceName = resourceName;
|
||||
}
|
||||
|
||||
public @NotNull List<Mod> getMods() {
|
||||
List<Mod> mods = this.mods;
|
||||
if (mods != null)
|
||||
return mods;
|
||||
|
||||
synchronized (this) {
|
||||
mods = this.mods;
|
||||
if (mods != null)
|
||||
return mods;
|
||||
|
||||
if (StringUtils.isBlank(resourceName)) {
|
||||
return this.mods = List.of();
|
||||
}
|
||||
|
||||
//noinspection DataFlowIssue
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(
|
||||
ModTranslations.class.getResourceAsStream(resourceName), StandardCharsets.UTF_8))) {
|
||||
return this.mods = reader.lines().filter(line -> !line.startsWith("#")).map(Mod::new).toList();
|
||||
} catch (Exception e) {
|
||||
LOG.warning("Failed to load " + resourceName, e);
|
||||
return this.mods = List.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull Map<String, Mod> getModIdMap() {
|
||||
Map<String, Mod> modIdMap = this.modIdMap;
|
||||
if (modIdMap != null)
|
||||
return modIdMap;
|
||||
synchronized (this) {
|
||||
modIdMap = this.modIdMap;
|
||||
if (modIdMap != null)
|
||||
return modIdMap;
|
||||
|
||||
List<Mod> mods = getMods();
|
||||
modIdMap = new HashMap<>(mods.size());
|
||||
for (Mod mod : mods) {
|
||||
for (String id : mod.getModIds()) {
|
||||
if (StringUtils.isNotBlank(id)) {
|
||||
modIdMap.putIfAbsent(id, mod);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.modIdMap = modIdMap;
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull Map<String, Mod> getSubnameMap() {
|
||||
Map<String, Mod> subnameMap = this.subnameMap;
|
||||
if (subnameMap != null)
|
||||
return subnameMap;
|
||||
synchronized (this) {
|
||||
subnameMap = this.subnameMap;
|
||||
if (subnameMap != null)
|
||||
return subnameMap;
|
||||
|
||||
subnameMap = new HashMap<>();
|
||||
|
||||
List<Mod> mods = getMods();
|
||||
for (Mod mod : mods) {
|
||||
String subname = cleanSubname(mod.getSubname());
|
||||
if (StringUtils.isNotBlank(subname)) {
|
||||
subnameMap.putIfAbsent(subname, mod);
|
||||
}
|
||||
}
|
||||
|
||||
return this.subnameMap = subnameMap;
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull Map<String, Mod> getCurseForgeMap() {
|
||||
Map<String, Mod> curseForgeMap = this.curseForgeMap;
|
||||
if (curseForgeMap != null)
|
||||
return curseForgeMap;
|
||||
|
||||
synchronized (this) {
|
||||
curseForgeMap = this.curseForgeMap;
|
||||
if (curseForgeMap != null)
|
||||
return curseForgeMap;
|
||||
|
||||
List<Mod> mods = getMods();
|
||||
curseForgeMap = new HashMap<>(mods.size());
|
||||
for (Mod mod : mods) {
|
||||
if (StringUtils.isNotBlank(mod.getCurseforge())) {
|
||||
curseForgeMap.putIfAbsent(mod.getCurseforge(), mod);
|
||||
}
|
||||
}
|
||||
|
||||
return this.curseForgeMap = curseForgeMap;
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull List<Pair<String, Mod>> getKeywords() {
|
||||
List<Pair<String, Mod>> keywords = this.keywords;
|
||||
if (keywords != null)
|
||||
return keywords;
|
||||
|
||||
synchronized (this) {
|
||||
keywords = this.keywords;
|
||||
if (keywords != null)
|
||||
return keywords;
|
||||
|
||||
List<Mod> mods = getMods();
|
||||
|
||||
keywords = new ArrayList<>();
|
||||
int maxKeywordLength = -1;
|
||||
for (Mod mod : mods) {
|
||||
if (StringUtils.isNotBlank(mod.getName())) {
|
||||
keywords.add(pair(mod.getName(), mod));
|
||||
maxKeywordLength = Math.max(maxKeywordLength, mod.getName().length());
|
||||
}
|
||||
if (StringUtils.isNotBlank(mod.getSubname())) {
|
||||
keywords.add(pair(mod.getSubname(), mod));
|
||||
maxKeywordLength = Math.max(maxKeywordLength, mod.getSubname().length());
|
||||
}
|
||||
if (StringUtils.isNotBlank(mod.getAbbr())) {
|
||||
keywords.add(pair(mod.getAbbr(), mod));
|
||||
maxKeywordLength = Math.max(maxKeywordLength, mod.getAbbr().length());
|
||||
}
|
||||
}
|
||||
|
||||
this.maxKeywordLength = maxKeywordLength;
|
||||
return this.keywords = keywords;
|
||||
}
|
||||
}
|
||||
|
||||
private int getMaxKeywordLength() {
|
||||
int maxKeywordLength = this.maxKeywordLength;
|
||||
if (maxKeywordLength >= 0)
|
||||
return maxKeywordLength;
|
||||
|
||||
// Ensure maxKeywordLength is initialized
|
||||
getKeywords();
|
||||
return this.maxKeywordLength;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Mod getModByCurseForgeId(String id) {
|
||||
if (StringUtils.isBlank(id)) return null;
|
||||
|
||||
return getCurseForgeMap().get(id);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Mod getMod(String id, String subname) {
|
||||
subname = cleanSubname(subname);
|
||||
if (StringUtils.isNotBlank(subname)) {
|
||||
Mod mod = getSubnameMap().get(subname);
|
||||
if (mod != null && (StringUtils.isBlank(id) || mod.getModIds().contains(id)))
|
||||
return mod;
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(id))
|
||||
return getModIdMap().get(id);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public abstract String getMcmodUrl(Mod mod);
|
||||
|
||||
public List<Mod> searchMod(String query) {
|
||||
StringBuilder newQuery = query.chars()
|
||||
.filter(ch -> !Character.isSpaceChar(ch))
|
||||
.collect(StringBuilder::new, (sb, value) -> sb.append((char) value), StringBuilder::append);
|
||||
query = newQuery.toString();
|
||||
|
||||
StringUtils.LongestCommonSubsequence lcs = new StringUtils.LongestCommonSubsequence(query.length(), getMaxKeywordLength());
|
||||
List<Pair<Integer, Mod>> modList = new ArrayList<>();
|
||||
for (Pair<String, Mod> keyword : getKeywords()) {
|
||||
int value = lcs.calc(query, keyword.getKey());
|
||||
if (value >= Math.max(1, query.length() - 3)) {
|
||||
modList.add(pair(value, keyword.getValue()));
|
||||
}
|
||||
}
|
||||
return modList.stream()
|
||||
.sorted((a, b) -> -a.getKey().compareTo(b.getKey()))
|
||||
.map(Pair::getValue)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static final class Mod {
|
||||
private final String curseforge;
|
||||
private final String mcmod;
|
||||
private final List<String> modIds;
|
||||
private final String name;
|
||||
private final String subname;
|
||||
private final String abbr;
|
||||
|
||||
public Mod(String line) {
|
||||
String[] items = line.split(";", -1);
|
||||
if (items.length != 6) {
|
||||
throw new IllegalArgumentException("Illegal mod data line, 6 items expected " + line);
|
||||
}
|
||||
|
||||
curseforge = items[0];
|
||||
mcmod = items[1];
|
||||
modIds = List.of(items[2].split(","));
|
||||
name = items[3];
|
||||
subname = items[4];
|
||||
abbr = items[5];
|
||||
}
|
||||
|
||||
public Mod(String curseforge, String mcmod, List<String> modIds, String name, String subname, String abbr) {
|
||||
this.curseforge = curseforge;
|
||||
this.mcmod = mcmod;
|
||||
this.modIds = modIds;
|
||||
this.name = name;
|
||||
this.subname = subname;
|
||||
this.abbr = abbr;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (StringUtils.isNotBlank(abbr)) {
|
||||
builder.append("[").append(abbr.trim()).append("] ");
|
||||
}
|
||||
builder.append(name);
|
||||
if (StringUtils.isNotBlank(subname)) {
|
||||
builder.append(" (").append(subname).append(")");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public String getCurseforge() {
|
||||
return curseforge;
|
||||
}
|
||||
|
||||
public String getMcmod() {
|
||||
return mcmod;
|
||||
}
|
||||
|
||||
public List<String> getModIds() {
|
||||
return modIds;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getSubname() {
|
||||
return subname;
|
||||
}
|
||||
|
||||
public String getAbbr() {
|
||||
return abbr;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.addon;
|
||||
|
||||
import org.jackhuang.hmcl.addon.mod.ModProjectInfo;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.ref.Reference;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/// Verifies project lookup, nullable registry selection and reclaimable indices.
|
||||
@NotNullByDefault
|
||||
class AddonProjectInfoRegistryTest {
|
||||
/// Creates an isolated registry backed by deterministic test data.
|
||||
private static AddonProjectInfoRegistry<ModProjectInfo> registry() {
|
||||
return new AddonProjectInfoRegistry<>("/addon/project-info-test.csv", 3) {
|
||||
@Override
|
||||
protected int getFieldsCount() {
|
||||
return 7;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ModProjectInfo parseAddonProjectInfo(String[] fields) {
|
||||
return new ModProjectInfo(Integer.parseInt(fields[0]), fields[1], fields[2],
|
||||
fields[3], fields[4], fields[5], fields[6]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Unsupported types have no registry rather than an empty implementation.
|
||||
@Test
|
||||
void selectsOnlySupportedRegistries() {
|
||||
assertSame(AddonProjectInfoRegistry.MOD, AddonProjectInfoRegistry.getByAddonType(RemoteAddon.Type.MOD));
|
||||
assertSame(AddonProjectInfoRegistry.MODPACK, AddonProjectInfoRegistry.getByAddonType(RemoteAddon.Type.MODPACK));
|
||||
assertNull(AddonProjectInfoRegistry.getByAddonType(null));
|
||||
assertNull(AddonProjectInfoRegistry.getByAddonType(RemoteAddon.Type.RESOURCE_PACK));
|
||||
}
|
||||
|
||||
/// Name matches require a compatible ID; duplicate IDs keep the first entry.
|
||||
@Test
|
||||
void preservesLookupPrecedence() {
|
||||
var registry = registry();
|
||||
var first = registry.getInfos().get(0);
|
||||
var second = registry.getInfos().get(1);
|
||||
assertSame(first, registry.getInfoByCurseForgeId("shared"));
|
||||
assertSame(first, registry.getInfo("shared-id", null));
|
||||
assertSame(second, registry.getInfo(null, "Second_Name!"));
|
||||
assertSame(first, registry.getInfo("first", "Second Name"));
|
||||
assertNull(registry.getInfo("missing", "Second Name"));
|
||||
assertNull(registry.getInfo(null, null));
|
||||
assertNull(registry.getInfoByCurseForgeId(" "));
|
||||
}
|
||||
|
||||
/// Clearing each index reference rebuilds lookups without losing results.
|
||||
@Test
|
||||
void rebuildsClearedIndices() throws ReflectiveOperationException {
|
||||
var registry = registry();
|
||||
var first = registry.getInfos().get(0);
|
||||
assertSame(first, registry.getInfo("first", "First Name"));
|
||||
assertSame(first, registry.getInfo("first", null));
|
||||
assertSame(first, registry.getInfoByCurseForgeId("shared"));
|
||||
var matches = registry.search("First");
|
||||
for (String name : List.of("modIdMapRef", "subnameMapRef", "curseForgeMapRef", "keywordsRef")) {
|
||||
var field = AddonProjectInfoRegistry.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
@Nullable Reference<?> reference = (Reference<?>) field.get(registry);
|
||||
assertNotNull(reference);
|
||||
reference.clear();
|
||||
}
|
||||
assertSame(first, registry.getInfo("first", "First Name"));
|
||||
assertSame(first, registry.getInfo("first", null));
|
||||
assertSame(first, registry.getInfoByCurseForgeId("shared"));
|
||||
assertEquals(matches, registry.search("First"));
|
||||
}
|
||||
|
||||
/// UTF-8 names and escaped commas survive loading; empty searches return no matches.
|
||||
@Test
|
||||
void readsAndDisplaysNames() {
|
||||
var registry = registry();
|
||||
var third = registry.getInfos().get(2);
|
||||
assertEquals("\u673a\u68b0\u52a8\u529b", third.mainName());
|
||||
assertEquals("[EX] \u673a\u68b0\u52a8\u529b (Example, Name)", third.displayName());
|
||||
assertEquals(List.of(third), registry.search("\u673a\u68b0\u52a8\u529b"));
|
||||
assertTrue(registry.search(" ").isEmpty());
|
||||
assertThrows(UnsupportedOperationException.class, () -> registry.search("First").clear());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
1,shared,,First,First Name,FST,first;shared-id
|
||||
2,shared,,Second,Second Name,SND,second;shared-id
|
||||
3,example,,机械动力,Example\c Name, EX ,example
|
||||
|
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.addon;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
/// @author Glavo
|
||||
@NotNullByDefault
|
||||
public abstract class AddonProjectInfo {
|
||||
|
||||
@Range(from = 0, to = Integer.MAX_VALUE)
|
||||
private final int mcmodId;
|
||||
private final String curseforgeId;
|
||||
private final String modrinthId;
|
||||
|
||||
private final String mainName;
|
||||
private final String subName;
|
||||
private final String abbrName;
|
||||
|
||||
/// This field is typically used to keep a reference to the `List<AddonProjectInfo>` that stores this object,
|
||||
/// so that the cached `List<AddonProjectInfo>` is not collected while the `AddonProjectInfo` object itself
|
||||
/// has not yet been collected, which could result in multiple identical `AddonProjectInfo` objects on the heap.
|
||||
@SuppressWarnings({"unused", "FieldCanBeLocal"})
|
||||
private @Nullable Object keepAlive;
|
||||
|
||||
protected AddonProjectInfo(
|
||||
int mcmodId, String curseforgeId, String modrinthId,
|
||||
String mainName, String subName, String abbrName) {
|
||||
if (mainName.isEmpty()) {
|
||||
throw new IllegalArgumentException("main name must not be empty");
|
||||
}
|
||||
|
||||
this.mcmodId = mcmodId;
|
||||
this.curseforgeId = curseforgeId;
|
||||
this.modrinthId = modrinthId;
|
||||
this.mainName = mainName;
|
||||
this.subName = subName;
|
||||
this.abbrName = abbrName;
|
||||
}
|
||||
|
||||
/// Returns the recorded CurseForge identifier, possibly empty.
|
||||
public String curseforgeId() {
|
||||
return curseforgeId;
|
||||
}
|
||||
|
||||
/// Returns the recorded primary name.
|
||||
public String mainName() {
|
||||
return mainName;
|
||||
}
|
||||
|
||||
/// Returns the recorded secondary name, possibly empty.
|
||||
public String subName() {
|
||||
return subName;
|
||||
}
|
||||
|
||||
/// Returns the recorded abbreviation, possibly empty.
|
||||
public String abbrName() {
|
||||
return abbrName;
|
||||
}
|
||||
|
||||
/// Returns the primary name with a nonblank abbreviation in brackets and a nonblank
|
||||
/// secondary name in parentheses. Only the abbreviation is trimmed.
|
||||
public String displayName() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (!abbrName.isBlank())
|
||||
builder.append('[').append(abbrName.trim()).append("] ");
|
||||
builder.append(mainName);
|
||||
if (!subName.isBlank())
|
||||
builder.append(" (").append(subName).append(')');
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public void setKeepAlive(@Nullable Object keepAlive) {
|
||||
this.keepAlive = keepAlive;
|
||||
}
|
||||
|
||||
protected abstract String mcmodClass();
|
||||
|
||||
protected abstract String curseforgeClass();
|
||||
|
||||
protected abstract String modrinthClass();
|
||||
|
||||
public @Nullable String mcmodUrl() {
|
||||
return mcmodId > 0
|
||||
? "https://www.mcmod.cn/" + mcmodClass() + "/" + mcmodId + ".html"
|
||||
: null;
|
||||
}
|
||||
|
||||
public @Nullable String curseforgeUrl() {
|
||||
return !curseforgeId.isEmpty()
|
||||
? "https://www.curseforge.com/minecraft/" + curseforgeClass() + "/" + curseforgeId
|
||||
: null;
|
||||
}
|
||||
|
||||
public @Nullable String modrinthUrl() {
|
||||
return !modrinthId.isEmpty()
|
||||
? "https://modrinth.com/" + modrinthClass() + "/" + modrinthId
|
||||
: null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.addon.mod;
|
||||
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfo;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// @author Glavo
|
||||
@NotNullByDefault
|
||||
public final class ModProjectInfo extends AddonProjectInfo {
|
||||
|
||||
private final @Nullable Object modIds;
|
||||
|
||||
public ModProjectInfo(
|
||||
int mcmodId, String curseforgeId, String modrinthId,
|
||||
String mainName, String subName, String abbrName,
|
||||
String modIds) {
|
||||
super(mcmodId, curseforgeId, modrinthId, mainName, subName, abbrName);
|
||||
|
||||
if (modIds.isEmpty()) {
|
||||
this.modIds = null;
|
||||
} else if (modIds.indexOf(';') < 0) {
|
||||
this.modIds = modIds;
|
||||
} else {
|
||||
this.modIds = List.<String>of(modIds.split(";"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an unmodifiable list of recorded mod IDs, or an empty list if none are recorded.
|
||||
@SuppressWarnings("unchecked")
|
||||
public @Unmodifiable List<String> getModIds() {
|
||||
if (modIds == null)
|
||||
return List.of();
|
||||
if (modIds instanceof String id)
|
||||
return List.of(id);
|
||||
return (List<String>) modIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String mcmodClass() {
|
||||
return "class";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String curseforgeClass() {
|
||||
return "mc-mods";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String modrinthClass() {
|
||||
return "mod";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.modpack;
|
||||
|
||||
import org.jackhuang.hmcl.addon.AddonProjectInfo;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
|
||||
/// @author Glavo
|
||||
@NotNullByDefault
|
||||
public final class ModpackProjectInfo extends AddonProjectInfo {
|
||||
public ModpackProjectInfo(
|
||||
int mcmodId, String curseforgeId, String modrinthId,
|
||||
String mainName, String subName, String abbrName
|
||||
) {
|
||||
super(mcmodId, curseforgeId, modrinthId, mainName, subName, abbrName);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String mcmodClass() {
|
||||
return "modpack";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String curseforgeClass() {
|
||||
return "modpacks";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String modrinthClass() {
|
||||
return "modpack";
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ dependencies {
|
||||
implementation(libs.kala.compress.ar)
|
||||
implementation(libs.weburl)
|
||||
implementation(libs.jsoup)
|
||||
implementation(libs.icu4j)
|
||||
implementation("org.apache.maven:maven-artifact:3.9.16")
|
||||
|
||||
testImplementation(libs.junit.jupiter)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.gradle.addon;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.tasks.InputFile;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.api.tasks.UntrackedTask;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/// Rewrites a JSON source file in its canonical compact representation.
|
||||
@NotNullByDefault
|
||||
@UntrackedTask(because = "Formats a JSON source file in place")
|
||||
public abstract class FormatJsonFile extends DefaultTask {
|
||||
|
||||
/// Returns the JSON source file to rewrite.
|
||||
@InputFile
|
||||
public abstract RegularFileProperty getFile();
|
||||
|
||||
/// Parses and rewrites the configured JSON file if its representation changes.
|
||||
///
|
||||
/// @throws IOException if the file cannot be read or written
|
||||
/// @throws JsonParseException if the file does not contain valid JSON
|
||||
@TaskAction
|
||||
public void run() throws IOException {
|
||||
Path path = getFile().get().getAsFile().toPath();
|
||||
String original = Files.readString(path);
|
||||
|
||||
JsonElement json = JsonParser.parseString(original);
|
||||
String formatted = new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.create()
|
||||
.toJson(json);
|
||||
|
||||
if (!formatted.equals(original)) {
|
||||
Files.writeString(path, formatted);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.gradle.addon;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.annotations.JsonAdapter;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.ibm.icu.lang.UCharacter;
|
||||
import com.ibm.icu.lang.UCharacterCategory;
|
||||
import com.ibm.icu.util.ULocale;
|
||||
import org.glavo.url.WebURL;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.logging.Logger;
|
||||
import org.gradle.api.logging.Logging;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.InputFile;
|
||||
import org.gradle.api.tasks.OutputFile;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.Unmodifiable;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/// Converts mcmod.cn JSON exports into UTF-8 metadata resources for the launcher's addon project registries.
|
||||
@NotNullByDefault
|
||||
public abstract class UpdateAddonProjectInfos extends DefaultTask {
|
||||
|
||||
/// Reports records and optional metadata that cannot be converted.
|
||||
private static final Logger LOGGER = Logging.getLogger(UpdateAddonProjectInfos.class);
|
||||
|
||||
/// Returns the input file property for a UTF-8 JSON array of project records.
|
||||
@InputFile
|
||||
public abstract RegularFileProperty getInputFile();
|
||||
|
||||
/// Returns the output file property. Existing contents are replaced during execution.
|
||||
@OutputFile
|
||||
public abstract RegularFileProperty getOutputFile();
|
||||
|
||||
/// Returns the type of projects to export.
|
||||
@Input
|
||||
public abstract Property<AddonProjectType> getProjectType();
|
||||
|
||||
/// Reads the export and writes the selected project type's metadata.
|
||||
/// Invalid records are skipped where possible, and invalid optional metadata is omitted.
|
||||
/// A failure may leave a partially written output file.
|
||||
///
|
||||
/// @throws Exception if the export cannot be read, converted or written
|
||||
@TaskAction
|
||||
public void run() throws Exception {
|
||||
Path inputFile = getInputFile().getAsFile().get().toPath();
|
||||
Path outputFile = getOutputFile().getAsFile().get().toPath();
|
||||
|
||||
AddonProjectType projectType = getProjectType().get();
|
||||
|
||||
List<AddonInfo> infos;
|
||||
try (var reader = Files.newBufferedReader(inputFile)) {
|
||||
Gson gson = new Gson();
|
||||
infos = gson.fromJson(reader, TypeToken.getParameterized(List.class, AddonInfo.class).getType());
|
||||
}
|
||||
|
||||
Files.createDirectories(outputFile.getParent());
|
||||
try (var writer = new CSVWriter(Files.newBufferedWriter(outputFile))) {
|
||||
writer.writeComment("""
|
||||
|
||||
Hello Minecraft! Launcher
|
||||
Copyright (C) 2026 huangyuhui <[email protected]> and contributors
|
||||
|
||||
mcmod.cn
|
||||
Copyright (C) 2026. All Rights Reserved.
|
||||
|
||||
""");
|
||||
|
||||
Map<String, TreeSet<Integer>> modIdTomcmodId = new HashMap<>();
|
||||
|
||||
for (AddonInfo info : infos) {
|
||||
int mcmodId;
|
||||
|
||||
try {
|
||||
mcmodId = projectType.getMcmodId(info);
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Failed to get the id of mcmod.cn for \"{}\"", info.name.main);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (projectType.shouldSkip(mcmodId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@Nullable String curseforgeId;
|
||||
try {
|
||||
curseforgeId = projectType.getCurseForgeId(info);
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Failed to get the id of CurseForge for \"{}\"", info.name.main);
|
||||
curseforgeId = null;
|
||||
}
|
||||
|
||||
@Nullable String modrinthId;
|
||||
try {
|
||||
modrinthId = projectType.getModrinthId(info);
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Failed to get the id of Modrinth for \"{}\"", info.name.main);
|
||||
modrinthId = null;
|
||||
}
|
||||
|
||||
String mainName = cleanChineseName(info.name.main);
|
||||
String subName = cleanName(info.name.sub);
|
||||
String abbr = cleanName(info.name.abbr);
|
||||
|
||||
if (mainName.isEmpty()) {
|
||||
LOGGER.warn("Mod \"{}\" has empty main name", info.name.main);
|
||||
continue;
|
||||
}
|
||||
|
||||
String modids;
|
||||
if (projectType == AddonProjectType.MOD) {
|
||||
try {
|
||||
Collection<String> idList = cleanModIds(info, mcmodId);
|
||||
|
||||
for (String modid : idList) {
|
||||
modIdTomcmodId.computeIfAbsent(modid, k -> new TreeSet<>()).add(mcmodId);
|
||||
}
|
||||
|
||||
modids = String.join(";", idList);
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Mod \"{}\" has invalid modid list: {}", info.name.main, info.modid);
|
||||
modids = "";
|
||||
}
|
||||
} else {
|
||||
modids = null;
|
||||
}
|
||||
|
||||
// Keep this field order aligned with the runtime project registry parser.
|
||||
writer.writeField(String.valueOf(mcmodId));
|
||||
writer.writeField(curseforgeId);
|
||||
writer.writeField(modrinthId);
|
||||
writer.writeField(mainName);
|
||||
writer.writeField(subName);
|
||||
writer.writeField(abbr);
|
||||
|
||||
if (projectType == AddonProjectType.MOD) {
|
||||
writer.writeField(modids);
|
||||
}
|
||||
|
||||
writer.writeNewLine();
|
||||
}
|
||||
|
||||
modIdTomcmodId.forEach((modid, mcmodIds) -> {
|
||||
if (mcmodIds.size() > 1) {
|
||||
LOGGER.info("Mod id \"{}\" is used by multiple mods: {}", modid, mcmodIds);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes comma-delimited records using backslash escapes instead of quoted CSV fields.
|
||||
/// Closing this writer closes its underlying writer.
|
||||
private static final class CSVWriter implements Closeable {
|
||||
/// Whether the next field omits the leading comma.
|
||||
private boolean firstField = true;
|
||||
/// Destination owned by this writer and closed by [#close()].
|
||||
private final BufferedWriter writer;
|
||||
|
||||
/// Creates a record writer that takes ownership of the supplied destination.
|
||||
private CSVWriter(BufferedWriter writer) {
|
||||
this.writer = writer;
|
||||
}
|
||||
|
||||
/// Closes the underlying writer, flushing its buffered output.
|
||||
///
|
||||
/// @throws IOException if flushing or closing the destination fails
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
writer.close();
|
||||
}
|
||||
|
||||
/// Writes comment lines prefixed with `# `. Must be called at a record boundary.
|
||||
///
|
||||
/// @throws IOException if writing to the destination fails
|
||||
public void writeComment(String comment) throws IOException {
|
||||
for (String line : comment.lines().toList()) {
|
||||
writer.write("# ");
|
||||
writer.write(line);
|
||||
writer.write('\n');
|
||||
}
|
||||
firstField = true;
|
||||
}
|
||||
|
||||
/// Appends a backslash-escaped field with a delimiter when needed.
|
||||
/// Null values produce empty fields. The record is not terminated.
|
||||
///
|
||||
/// @throws IOException if writing to the destination fails
|
||||
public void writeField(@Nullable String field) throws IOException {
|
||||
if (firstField) {
|
||||
firstField = false;
|
||||
} else {
|
||||
writer.write(',');
|
||||
}
|
||||
|
||||
if (field == null || field.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < field.length(); ) {
|
||||
int ch = field.codePointAt(i);
|
||||
|
||||
switch (ch) {
|
||||
case '\0' -> writer.write("\\0");
|
||||
case '\\' -> writer.write("\\\\");
|
||||
case '\n' -> writer.write("\\n");
|
||||
case '\r' -> writer.write("\\r");
|
||||
case '\t' -> writer.write("\\t");
|
||||
case ',' -> writer.write("\\c");
|
||||
default -> {
|
||||
|
||||
boolean needEscape = switch (UCharacter.getType(ch)) {
|
||||
case UCharacterCategory.CONTROL,
|
||||
UCharacterCategory.FORMAT,
|
||||
UCharacterCategory.UNASSIGNED,
|
||||
UCharacterCategory.SURROGATE,
|
||||
UCharacterCategory.PRIVATE_USE,
|
||||
UCharacterCategory.LINE_SEPARATOR,
|
||||
UCharacterCategory.PARAGRAPH_SEPARATOR -> true;
|
||||
default -> false;
|
||||
};
|
||||
|
||||
if (Character.isBmpCodePoint(ch)) {
|
||||
if (needEscape) {
|
||||
writer.write(String.format("\\u%04x", ch));
|
||||
} else {
|
||||
writer.write(ch);
|
||||
}
|
||||
} else {
|
||||
char ch0 = Character.highSurrogate(ch);
|
||||
char ch1 = Character.lowSurrogate(ch);
|
||||
if (needEscape) {
|
||||
// The reader decodes fixed-width UTF-16 escapes, so preserve both surrogate units.
|
||||
writer.write(String.format("\\u%04x\\u%04x", (int) ch0, (int) ch1));
|
||||
} else {
|
||||
writer.write(ch0);
|
||||
writer.write(ch1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i += Character.charCount(ch);
|
||||
}
|
||||
}
|
||||
|
||||
/// Terminates the current record with LF and starts a new record.
|
||||
///
|
||||
/// @throws IOException if writing the separator fails
|
||||
public void writeNewLine() throws IOException {
|
||||
writer.write('\n');
|
||||
firstField = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans an exported name by trimming, removing zero-width spaces and decoding selected HTML entities.
|
||||
private static String cleanName(String name) {
|
||||
// Remove zero-width space (U+200B) characters.
|
||||
name = name.replace("\u200b", "");
|
||||
|
||||
// Remove zero-width non-joiner (U+200C) characters.
|
||||
name = name.replace("\u200c", "");
|
||||
|
||||
// Remove soft hyphen (U+00AD) characters.
|
||||
// TODO: Temporary workaround for https://www.mcmod.cn/class/3084.html
|
||||
name = name.replace("\u00ad", "");
|
||||
|
||||
// Remove left-to-right mark (U+200E) and right-to-left mark (U+200F) characters.
|
||||
// TODO: Temporary workaround for https://www.mcmod.cn/class/7550.html
|
||||
name = name
|
||||
.replace("\u200e", "")
|
||||
.replace("\u200f", "");
|
||||
|
||||
if (name.indexOf('&') >= 0) {
|
||||
// Most string values in the original JSON data contain HTML-escaped characters, such as `&`, `<`, and `>`.
|
||||
name = name
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">");
|
||||
}
|
||||
|
||||
name = name.trim();
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/// Cleans a primary name and normalizes fullwidth parentheses and their spacing.
|
||||
private static String cleanChineseName(String chineseName) {
|
||||
chineseName = cleanName(chineseName);
|
||||
|
||||
if (chineseName.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuilder builder = new StringBuilder(chineseName.length());
|
||||
int[] codePoints = chineseName.codePoints().toArray();
|
||||
for (int i = 0; i < codePoints.length; i++) {
|
||||
int ch = codePoints[i];
|
||||
int prev = i > 0 ? codePoints[i - 1] : 0;
|
||||
|
||||
switch (ch) {
|
||||
case '(' -> {
|
||||
if (Character.isWhitespace(prev) || prev == '!' || prev == '。')
|
||||
builder.append('(');
|
||||
else
|
||||
builder.append(" (");
|
||||
}
|
||||
case ')' -> builder.append(')');
|
||||
default -> builder.appendCodePoint(ch);
|
||||
}
|
||||
}
|
||||
return builder.toString().trim();
|
||||
}
|
||||
|
||||
/// Recognizes accepted mod ID syntax.
|
||||
private static final Pattern MODID_PATTERN = Pattern.compile("^[a-zA-Z0-9._|+' -]+$");
|
||||
/// Explicitly accepted IDs that do not match [#MODID_PATTERN].
|
||||
private static final Set<String> MODID_WHITELIST = Set.of(
|
||||
// https://www.mcmod.cn/class/866.html
|
||||
"<CoFH Tweak>",
|
||||
// https://www.mcmod.cn/class/1780.html
|
||||
"EFFLL (LiteLoader ObjectHolder fix)"
|
||||
);
|
||||
|
||||
/// Returns cleaned, validated mod IDs without duplicates, preserving their original order.
|
||||
///
|
||||
/// @throws GradleException if the mod ID list is null or a cleaned ID is not accepted
|
||||
private static Collection<String> cleanModIds(AddonInfo info, int mcmodId) {
|
||||
if (info.modid() == null) {
|
||||
throw new GradleException("Modid list is null");
|
||||
}
|
||||
|
||||
var result = new LinkedHashSet<String>(info.modid.size());
|
||||
|
||||
for (String modid : info.modid) {
|
||||
String cleanedModid = cleanName(modid.trim());
|
||||
|
||||
// TODO: Temporary workaround, remove this after the modid is fixed
|
||||
cleanedModid = switch (cleanedModid) {
|
||||
// replace non-breaking hyphen (U+2011) with normal hyphen
|
||||
// https://www.mcmod.cn/class/31211.html
|
||||
case "godfall‑trinkets" -> "godfall-trinkets";
|
||||
// https://www.mcmod.cn/class/30575.html
|
||||
case "enchantment-table\"" -> "enchantment-table";
|
||||
// https://www.mcmod.cn/class/28657.html
|
||||
case "斗蛐蛐" -> "mob_battle_plus";
|
||||
// https://www.mcmod.cn/class/4158.html
|
||||
case "morecuriostotemsofundying:" -> "mtca";
|
||||
// https://www.mcmod.cn/class/12820.html
|
||||
case "caves_&_canyons" -> "caves_canyons";
|
||||
// https://www.mcmod.cn/class/30957.html
|
||||
case "minecraft:" -> "moderncontentbackport";
|
||||
default -> cleanedModid;
|
||||
};
|
||||
|
||||
// https://www.mcmod.cn/class/31322.html
|
||||
if (cleanedModid.equals("minecraft")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// https://www.mcmod.cn/class/4.html
|
||||
if (mcmodId == 4 && cleanedModid.equals("kamenridercraft4th")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// https://www.mcmod.cn/class/15744.html
|
||||
if (mcmodId == 15744 && cleanedModid.equals("Fabric API")) {
|
||||
cleanedModid = "impropers3dminimap";
|
||||
}
|
||||
|
||||
// https://www.mcmod.cn/class/26546.html
|
||||
if (mcmodId == 26546 && cleanedModid.equals("swem")) {
|
||||
cleanedModid = "sweconm";
|
||||
}
|
||||
|
||||
if (!MODID_PATTERN.matcher(cleanedModid).matches() && !MODID_WHITELIST.contains(cleanedModid)) {
|
||||
throw new GradleException("Invalid modid: " + modid);
|
||||
}
|
||||
|
||||
result.add(cleanedModid);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Selects project-specific link parsing, exclusion rules and output fields.
|
||||
public enum AddonProjectType {
|
||||
/// Mod projects, excluding Minecraft itself.
|
||||
MOD("class", "mc-mods", "mod") {
|
||||
/// Returns whether the ID identifies Minecraft rather than a mod.
|
||||
@Override
|
||||
public boolean shouldSkip(int mcmodId) {
|
||||
if (mcmodId == 1) {
|
||||
// Should skip the "Minecraft" project, which is the Minecraft game itself, not a mod.
|
||||
// https://www.mcmod.cn/class/1.html
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
},
|
||||
/// Modpack projects.
|
||||
MODPACK("modpack", "modpacks", "modpack");
|
||||
|
||||
/// Recognizes project URLs on mcmod.cn.
|
||||
private final Pattern mcmodUrlPattern;
|
||||
/// CurseForge category for this project type.
|
||||
private final String curseforgeType;
|
||||
|
||||
/// Modrinth category for this project type.
|
||||
private final String modrinthType;
|
||||
|
||||
/// Creates a project type for the specified mcmod.cn path and hosting-platform categories.
|
||||
///
|
||||
/// @param mcmodSlug mcmod.cn path segment used in the canonical URL pattern
|
||||
/// @param curseforgeType CurseForge category accepted during slug extraction
|
||||
/// @param modrinthType Modrinth category accepted during identifier extraction
|
||||
AddonProjectType(
|
||||
String mcmodSlug,
|
||||
String curseforgeType,
|
||||
String modrinthType
|
||||
) {
|
||||
this.mcmodUrlPattern = Pattern.compile("https://www\\.mcmod\\.cn/" + mcmodSlug + "/(?<id>\\d+)\\.html");
|
||||
this.curseforgeType = curseforgeType;
|
||||
this.modrinthType = modrinthType;
|
||||
}
|
||||
|
||||
/// Extracts the project ID from the first mcmod.cn link.
|
||||
///
|
||||
/// @throws GradleException if the URL is not valid for this project type
|
||||
int getMcmodId(AddonInfo info) {
|
||||
String url = info.links.list.get("mcmod").get(0).url();
|
||||
var matcher = mcmodUrlPattern.matcher(url);
|
||||
if (!matcher.matches()) {
|
||||
throw new GradleException("Invalid mcmod.cn URL: " + url);
|
||||
}
|
||||
|
||||
return Integer.parseInt(matcher.group("id"));
|
||||
}
|
||||
|
||||
/// Recognizes CurseForge project paths.
|
||||
private static final Pattern CURSEFORGE_PATH_PATTERNS = Pattern.compile(
|
||||
"^/(?<game>[a-zA-Z-]+)/(?<type>[a-zA-Z0-9-]+)/+(?<id>[\\w-]+)(/(.*?))?$"
|
||||
);
|
||||
|
||||
|
||||
/// Returns a CurseForge project slug for Minecraft and this project type,
|
||||
/// or null if no applicable link is present. No network requests are made.
|
||||
///
|
||||
/// @throws Exception if no suitable link is found and at least one link is invalid
|
||||
@Nullable String getCurseForgeId(AddonInfo info) throws Exception {
|
||||
var links = info.links.list.get("curseforge");
|
||||
|
||||
if (links == null || links.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Exception cause = null;
|
||||
|
||||
for (AddonInfo.Link link : links) {
|
||||
try {
|
||||
WebURL url = WebURL.parse(link.url());
|
||||
|
||||
if (!url.getScheme().equals("https") && !url.getScheme().equals("http")) {
|
||||
throw new GradleException("Invalid CurseForge URL: " + url);
|
||||
}
|
||||
|
||||
switch (Objects.requireNonNull(url.getHost(), "host")) {
|
||||
case "files.xmdhs.com",
|
||||
"edge.forgecdn.net",
|
||||
"minecraft.curseforge.com",
|
||||
"mediafilez.forgecdn.net",
|
||||
// Deprecated domain names
|
||||
"www.curse.com",
|
||||
"mods.curse.com" -> {
|
||||
continue;
|
||||
}
|
||||
case "curseforge.com",
|
||||
"www.curseforge.com",
|
||||
"legacy.curseforge.com",
|
||||
"beta.curseforge.com" -> {
|
||||
String path = url.getPath();
|
||||
|
||||
var matcher = CURSEFORGE_PATH_PATTERNS.matcher(path);
|
||||
if (!matcher.matches()) {
|
||||
throw new GradleException("Invalid CurseForge URL: " + url);
|
||||
}
|
||||
|
||||
String game = matcher.group("game");
|
||||
if (!game.equalsIgnoreCase("minecraft")) {
|
||||
// Ignore minecraft-bedrock and other non-minecraft projects
|
||||
continue;
|
||||
}
|
||||
|
||||
String type = matcher.group("type");
|
||||
if (type.equals(curseforgeType)) {
|
||||
return matcher.group("id");
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
default -> throw new GradleException("Invalid CurseForge URL: " + url);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (cause == null) {
|
||||
cause = e;
|
||||
} else {
|
||||
cause.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cause != null)
|
||||
throw cause;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Recognizes Modrinth project paths.
|
||||
private static final Pattern MODRINTH_PATH_PATTERNS = Pattern.compile(
|
||||
"^/(?<type>[a-zA-Z0-9-]+)/(?<id>[^/]+)(/(.*?))?$"
|
||||
);
|
||||
|
||||
/// Returns a Modrinth project identifier from a link for this project type,
|
||||
/// or null if no applicable link is present. The identifier may be a slug or project ID.
|
||||
/// No network requests are made.
|
||||
///
|
||||
/// @throws Exception if no suitable link is found and at least one link is invalid
|
||||
@Nullable String getModrinthId(AddonInfo info) throws Exception {
|
||||
var links = info.links.list.get("modrinth");
|
||||
|
||||
if (links == null || links.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Exception cause = null;
|
||||
|
||||
for (AddonInfo.Link link : links) {
|
||||
try {
|
||||
WebURL url = WebURL.parse(link.url());
|
||||
|
||||
if (!url.getScheme().equals("https") && !url.getScheme().equals("http")) {
|
||||
throw new GradleException("Invalid Modrinth URL: " + url);
|
||||
}
|
||||
|
||||
switch (Objects.requireNonNull(url.getHost(), "host")) {
|
||||
case "github.com",
|
||||
"cdn.modrinth.com" -> {
|
||||
continue;
|
||||
}
|
||||
case "modrinth.com",
|
||||
"www.modrinth.com" -> {
|
||||
String path = url.getPath();
|
||||
|
||||
var matcher = MODRINTH_PATH_PATTERNS.matcher(path);
|
||||
if (!matcher.matches()) {
|
||||
throw new GradleException("Invalid Modrinth URL: " + url);
|
||||
}
|
||||
|
||||
String type = matcher.group("type");
|
||||
if (!type.equals(modrinthType) && !(this == MOD && type.equals("project"))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return matcher.group("id");
|
||||
}
|
||||
default -> throw new GradleException("Invalid Modrinth URL: " + url);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (cause == null) {
|
||||
cause = e;
|
||||
} else {
|
||||
cause.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cause != null)
|
||||
throw cause;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Returns whether the project identified by the mcmod.cn ID is excluded from output.
|
||||
///
|
||||
/// @implSpec The default implementation returns false.
|
||||
public boolean shouldSkip(int mcmodId) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents one project in the JSON export.
|
||||
///
|
||||
/// @param name primary, secondary and abbreviated project names
|
||||
/// @param modid optional mod IDs decoded from an array or a wrapper object's `list` field
|
||||
/// @param links links grouped by source name
|
||||
private record AddonInfo(
|
||||
AddonInfo.Name name,
|
||||
@JsonAdapter(AddonInfo.ModIdDeserializer.class)
|
||||
@Nullable List<String> modid,
|
||||
Links links
|
||||
) {
|
||||
/// Contains the exported project names before cleanup.
|
||||
///
|
||||
/// @param main primary name
|
||||
/// @param sub secondary name
|
||||
/// @param abbr abbreviation
|
||||
record Name(String main, String sub, String abbr) {
|
||||
}
|
||||
|
||||
/// Contains a source URL and its accompanying text.
|
||||
///
|
||||
/// @param url exported URL, not yet validated
|
||||
/// @param content accompanying text, unused by metadata generation
|
||||
record Link(String url, String content) {
|
||||
}
|
||||
|
||||
/// Groups exported links by source.
|
||||
///
|
||||
/// @param list source names mapped to link lists in export order
|
||||
record Links(@Unmodifiable Map<String, @Unmodifiable List<Link>> list) {
|
||||
}
|
||||
|
||||
/// Decodes mod IDs from either a JSON array or an object's `list` member.
|
||||
public static final class ModIdDeserializer implements JsonDeserializer<List<String>> {
|
||||
/// Generic target type passed to Gson for mod ID arrays.
|
||||
private static final Type STRING_LIST = TypeToken.getParameterized(List.class, String.class).getType();
|
||||
|
||||
/// Decodes a mod ID list, returning null if the list is absent or JSON null.
|
||||
///
|
||||
/// @throws JsonParseException if Gson cannot decode the selected value as a string list
|
||||
/// @throws IllegalStateException if a non-null, non-array value is not a JSON object
|
||||
@Override
|
||||
public @Nullable List<String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
|
||||
if (json.isJsonNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (json.isJsonArray()) {
|
||||
return context.deserialize(json, STRING_LIST);
|
||||
} else {
|
||||
JsonObject jsonObject = json.getAsJsonObject();
|
||||
JsonElement list = jsonObject.get("list");
|
||||
if (list == null) {
|
||||
return null;
|
||||
} else {
|
||||
return context.deserialize(list, STRING_LIST);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
/*
|
||||
* Hello Minecraft! Launcher
|
||||
* Copyright (C) 2025 huangyuhui <[email protected]> and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package org.jackhuang.hmcl.gradle.mod;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.annotations.JsonAdapter;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import org.glavo.url.WebURL;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.logging.Logger;
|
||||
import org.gradle.api.logging.Logging;
|
||||
import org.gradle.api.tasks.InputFile;
|
||||
import org.gradle.api.tasks.OutputFile;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author Glavo
|
||||
*/
|
||||
public abstract class ParseModDataTask extends DefaultTask {
|
||||
|
||||
@InputFile
|
||||
public abstract RegularFileProperty getInputFile();
|
||||
|
||||
@OutputFile
|
||||
public abstract RegularFileProperty getOutputFile();
|
||||
|
||||
private static final Logger LOGGER = Logging.getLogger(ParseModDataTask.class);
|
||||
|
||||
private static final String S = ";";
|
||||
private static final String MOD_SEPARATOR = ",";
|
||||
|
||||
private static final Pattern[] CURSEFORGE_PATTERNS = {
|
||||
Pattern.compile("^/(minecraft|Minecraft|minecraft-bedrock)/(mc-mods|data-packs|modpacks|customization|mc-addons|texture-packs|customization/configuration|addons|scripts|bukkit-plugins)/+(?<modid>[\\w-]+)(/(.*?))?$"),
|
||||
Pattern.compile("^/projects/(?<modid>[\\w-]+)(/(.*?))?$"),
|
||||
Pattern.compile("^/mc-mods/minecraft/(?<modid>[\\w-]+)(/(.*?))?$"),
|
||||
Pattern.compile("^/legacy/mc-mods/minecraft/(\\d+)-(?<modid>[\\w-]+)"),
|
||||
};
|
||||
|
||||
private static String parseName(String name) {
|
||||
return name.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">");
|
||||
}
|
||||
|
||||
private static final Pattern MCMOD_PATTERN =
|
||||
Pattern.compile("^https://www\\.mcmod\\.cn/(class|modpack)/(?<modid>\\d+)\\.html$");
|
||||
|
||||
private static String parseMcMod(String url) {
|
||||
Matcher matcher = MCMOD_PATTERN.matcher(url);
|
||||
if (matcher.matches()) {
|
||||
return matcher.group("modid");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static String cleanChineseName(String chineseName) {
|
||||
if (chineseName == null || chineseName.isBlank())
|
||||
return "";
|
||||
|
||||
chineseName = chineseName.trim();
|
||||
|
||||
StringBuilder builder = new StringBuilder(chineseName.length());
|
||||
int[] codePoints = chineseName.codePoints().toArray();
|
||||
for (int i = 0; i < codePoints.length; i++) {
|
||||
int ch = codePoints[i];
|
||||
int prev = i > 0 ? codePoints[i - 1] : 0;
|
||||
|
||||
switch (ch) {
|
||||
case '(' -> {
|
||||
if (Character.isWhitespace(prev) || prev == '!' || prev == '。')
|
||||
builder.append('(');
|
||||
else
|
||||
builder.append(" (");
|
||||
}
|
||||
case ')' -> builder.append(')');
|
||||
default -> builder.appendCodePoint(ch);
|
||||
}
|
||||
}
|
||||
return builder.toString().trim();
|
||||
}
|
||||
|
||||
private static final Set<String> SKIP = Set.of(
|
||||
"Minecraft",
|
||||
"The Building Game"
|
||||
);
|
||||
|
||||
@TaskAction
|
||||
public void run() throws IOException {
|
||||
Path inputFile = getInputFile().get().getAsFile().toPath().toAbsolutePath();
|
||||
Path outputFile = getOutputFile().get().getAsFile().toPath().toAbsolutePath();
|
||||
|
||||
Files.createDirectories(outputFile.getParent());
|
||||
|
||||
List<ModData> modDatas;
|
||||
try (BufferedReader reader = Files.newBufferedReader(inputFile)) {
|
||||
modDatas = new Gson().fromJson(reader, TypeToken.getParameterized(List.class, ModData.class).getType());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) {
|
||||
writer.write("#\n" +
|
||||
"# Hello Minecraft! Launcher\n" +
|
||||
"# Copyright (C) 2025 huangyuhui <[email protected]> and contributors\n" +
|
||||
"#\n" +
|
||||
"# mcmod.cn\n" +
|
||||
"# Copyright (C) 2025. All Rights Reserved.\n" +
|
||||
"#\n");
|
||||
for (ModData mod : modDatas) {
|
||||
String chineseName = parseName(mod.name.main);
|
||||
String subName = parseName(mod.name.sub);
|
||||
String abbr = parseName(mod.name.abbr);
|
||||
|
||||
chineseName = chineseName == null ? "" : cleanChineseName(chineseName);
|
||||
if (subName == null)
|
||||
subName = "";
|
||||
if (abbr == null)
|
||||
abbr = "";
|
||||
|
||||
if (SKIP.contains(subName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chineseName.contains(S) || subName.contains(S)) {
|
||||
LOGGER.warn("Error chinese name: {}", chineseName);
|
||||
continue;
|
||||
}
|
||||
|
||||
String curseforgeId = "";
|
||||
String mcmodId = "";
|
||||
|
||||
Map<String, List<ModData.Link>> links = mod.links.list;
|
||||
List<ModData.Link> curseforgeLinks = links.get("curseforge");
|
||||
List<ModData.Link> mcmodLinks = links.get("mcmod");
|
||||
|
||||
if (curseforgeLinks != null && !curseforgeLinks.isEmpty()) {
|
||||
boolean reportError = true;
|
||||
|
||||
for (ModData.Link link : curseforgeLinks) {
|
||||
WebURL res = WebURL.parse(link.url);
|
||||
|
||||
if (!"http".equals(res.getScheme()) && !"https".equals(res.getScheme())) {
|
||||
curseforgeId = "";
|
||||
break;
|
||||
}
|
||||
|
||||
if (Set.of(
|
||||
"files.xmdhs.com",
|
||||
"edge.forgecdn.net",
|
||||
"minecraft.curseforge.com",
|
||||
"mediafilez.forgecdn.net"
|
||||
).contains(res.getHost())) {
|
||||
reportError = false;
|
||||
curseforgeId = "";
|
||||
break;
|
||||
}
|
||||
|
||||
for (Pattern pattern : CURSEFORGE_PATTERNS) {
|
||||
Matcher matcher = pattern.matcher(res.getPath());
|
||||
if (matcher.matches()) {
|
||||
curseforgeId = matcher.group("modid");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!curseforgeId.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (curseforgeId.isEmpty() && reportError) {
|
||||
LOGGER.warn("Error curseforge: {}", chineseName);
|
||||
}
|
||||
}
|
||||
|
||||
if (mcmodLinks != null && !mcmodLinks.isEmpty()) {
|
||||
mcmodId = parseMcMod(mcmodLinks.get(0).url);
|
||||
if (mcmodId.isEmpty()) {
|
||||
throw new GradleException("Error mcmod: " + chineseName);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> modId = new ArrayList<>();
|
||||
if (mod.modid != null) {
|
||||
for (String id : mod.modid) {
|
||||
String cleanId = parseName(id.trim());
|
||||
|
||||
if (cleanId.contains(MOD_SEPARATOR) || cleanId.contains(S)) {
|
||||
throw new GradleException("Error modid: " + id);
|
||||
}
|
||||
|
||||
modId.add(cleanId);
|
||||
}
|
||||
}
|
||||
|
||||
String modIds = String.join(MOD_SEPARATOR, modId);
|
||||
|
||||
writer.write(curseforgeId + S + mcmodId + S + modIds + S + chineseName + S + subName + S + abbr + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ModData {
|
||||
|
||||
public Name name;
|
||||
|
||||
@JsonAdapter(ModIdDeserializer.class)
|
||||
public List<String> modid;
|
||||
|
||||
public Links links;
|
||||
|
||||
public static final class Name {
|
||||
public String main;
|
||||
public String sub;
|
||||
public String abbr;
|
||||
}
|
||||
|
||||
public static final class Link {
|
||||
public String url;
|
||||
public String content;
|
||||
}
|
||||
|
||||
public static final class Links {
|
||||
public Map<String, List<Link>> list;
|
||||
}
|
||||
|
||||
public static final class ModIdDeserializer implements JsonDeserializer<List<String>> {
|
||||
private static final Type STRING_LIST = TypeToken.getParameterized(List.class, String.class).getType();
|
||||
|
||||
@Override
|
||||
public List<String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
|
||||
if (json.isJsonNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (json.isJsonArray()) {
|
||||
return context.deserialize(json, STRING_LIST);
|
||||
} else {
|
||||
JsonObject jsonObject = json.getAsJsonObject();
|
||||
JsonElement list = jsonObject.get("list");
|
||||
if (list == null) {
|
||||
return null;
|
||||
} else {
|
||||
return context.deserialize(list, STRING_LIST);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,9 @@ jimfs = "1.3.0"
|
||||
# plugins
|
||||
shadow = "9.6.1"
|
||||
|
||||
# build scripts
|
||||
icu4j = "78.3"
|
||||
|
||||
[libraries]
|
||||
hmclauncher = { module = "org.glavo.hmcl:HMCLauncher", version.ref = "hmclauncher" }
|
||||
jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" }
|
||||
@@ -73,5 +76,8 @@ commonmark-table = { module = "org.commonmark:commonmark-ext-gfm-tables", versio
|
||||
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
|
||||
jimfs = { module = "com.google.jimfs:jimfs", version.ref = "jimfs" }
|
||||
|
||||
# build scripts
|
||||
icu4j = { module = "com.ibm.icu:icu4j", version.ref = "icu4j" }
|
||||
|
||||
[plugins]
|
||||
shadow = { id = "com.gradleup.shadow", version.ref = "shadow" }
|
||||
Reference in new issue
Block a user