Compare commits

...
47 Commits
Author SHA1 Message Date
Glavo 24fd2cf521 Fix #4409: 修复导出的历史日志文件为空的问题 (#4411) 2025-09-07 22:31:44 +08:00
Glavo 68dbe6945b 优化语言设置中简体/繁体中文选项的显示方式 (#4410) 2025-09-07 21:06:26 +08:00
Glavo c3352d2b73 优化游戏下载界面 (#4405) 2025-09-07 16:33:49 +08:00
小宇 55a7169e21 Fix MultiMC modpack update not applying configuration overrides (#4382) 2025-09-07 15:53:47 +08:00
Glavo 50080ab875 修复地支中的「丑」被误写为「醜」的问题 (#4404) 2025-09-07 15:51:21 +08:00
GlavoandCopilot 5697cbd251 使用 Gradle 自动更新文档内容 (#4403)
Co-authored-by: Copilot <[email protected]>
2025-09-07 15:47:17 +08:00
Glavo 86ad055f8f 修复 Config 的序列化问题 (#4402) 2025-09-06 17:46:43 +08:00
+1 4883c3897b 文言翻译优化 (#4387)
Co-authored-by: 0xis-cn <[email protected]>
Co-authored-by: BeiDou114514 <[email protected]>
Co-authored-by: Furina-de-zh-Hant <[email protected]>
Co-authored-by: Kaohaaa <[email protected]>
Co-authored-by: 365KW <[email protected]>
Co-authored-by: Andypsl8 <[email protected]>
Co-authored-by: Au0727 <[email protected]>
Co-authored-by: threwd <[email protected]>
Co-authored-by: vinds476283 <[email protected]>
Co-authored-by: Glavo <[email protected]>
2025-09-06 17:38:11 +08:00
Glavo 09c17fc85b 优化 checkTranslations Task (#4396) 2025-09-06 15:41:38 +08:00
Glavo fe59f495f6 优化地区判断逻辑 (#4401) 2025-09-06 15:40:37 +08:00
Glavo 9a475c2e92 更新 PLATFORM.md (#4399) 2025-09-06 02:13:24 +08:00
Glavo 8cd8a389b9 将 README.md 移动至 docs 文件夹中 (#4398) 2025-09-06 02:06:30 +08:00
Glavo 9cc45bc66a 将 README.md 翻译至更多语言 (#4397) 2025-09-06 01:41:36 +08:00
Glavo ea0b65be2e 在 README 中声明对 FreeBSD 的支持 (#4395) 2025-09-05 21:13:38 +08:00
GlavoandCopilot f4a8e3d1a6 重构 Config (#4394)
Co-authored-by: Copilot <[email protected]>
2025-09-05 20:24:01 +08:00
Glavo 7576bf6a01 在 LocaleUtils 中添加更多工具方法 (#4390) 2025-09-04 15:51:17 +08:00
3gf8jv4dv 3d63523f25 chore(l10n): change translation from 版本 to 实例 in zh-cn for term INSTANCE (#4376) 2025-09-04 15:35:31 +08:00
Glavo dbfd6c7599 更新文档结构 (#4389) 2025-09-04 10:59:59 +08:00
Glavo ed6c7387bc Update microsoft_auth.html (#4388) 2025-09-03 23:48:52 +08:00
Glavo 6ab216dcb6 增强本地化支持 (#4379) 2025-09-03 21:55:20 +08:00
GlavoandCopilot b38076f847 Fix #4377: 修复离线账户换肤功能使用无效 CSL API 导致启动失败的问题 (#4386)
Co-authored-by: Copilot <[email protected]>
2025-09-03 20:16:10 +08:00
Glavo 16816d8490 修复 Linux 平台上无法正确为安装了 Cleanroom 的游戏版本选择 Java 的问题 (#4385) 2025-09-03 16:56:47 +08:00
e8813fe153 feat: Cleanroom 自动安装 (#4272)
Co-authored-by: Zkitefly <[email protected]>
Co-authored-by: Glavo <[email protected]>
2025-09-03 15:50:57 +08:00
Glavo ce24e4e622 修复连续点击两次返回按钮时会最大化窗口的问题 (#4384) 2025-09-03 15:34:59 +08:00
Glavo 10e5e7bc9c 优化 Minecraft Wiki 跳转功能 (#4372) 2025-09-01 23:13:20 +08:00
Glavo 28b222e3dd 优化中文适配 (#4370) 2025-09-01 21:01:59 +08:00
Glavo 86085031f6 优化自动切换游戏语言功能 (#4353) 2025-08-31 14:57:23 +08:00
Glavo 30f47704f1 更新文言文翻译 (#4364) 2025-08-31 12:18:34 +08:00
Glavo 82e0cd1ca1 Fix #3669: 修复首次打开子页面时切换动画丢失的问题 (#4365) 2025-08-31 12:11:13 +08:00
Wulian233andGlavo 5374127241 修改部分文言条目 (#4359)
Co-authored-by: Glavo <[email protected]>
2025-08-31 00:59:14 +08:00
Glavo df489c0cfe 添加乌克兰语支持 (#4363) 2025-08-31 00:48:22 +08:00
BANERandGlavo d83f6106f5 Add I18N_uk.properties (#4346)
Co-authored-by: Glavo <[email protected]>
2025-08-31 00:33:16 +08:00
Glavo b7361c8da4 优化语言设置 (#4362) 2025-08-31 00:18:25 +08:00
Glavo 73531dbf60 优化文言文翻译 (#4361) 2025-08-30 22:21:45 +08:00
Andypsl8 5af6858d4c 更新文言文翻译 (#4356) 2025-08-30 02:06:33 +08:00
Glavo 1a3b473356 Fix #3076: 修复无法识别部分简体中文环境的问题 (#4350) 2025-08-29 20:31:05 +08:00
Glavo 67e4dddda1 添加文言文支持 (#4348) 2025-08-29 14:42:10 +08:00
Glavo 55816032b7 启动游戏时隐藏 GameAssetDownloadTask (#4349) 2025-08-29 12:25:49 +08:00
Glavo b9fd0e50a7 为迁移至 Java 17 做准备 (#4311) 2025-08-28 20:43:03 +08:00
Glavo 71d54955ad 修复 TaskListPane.StatusChangeListener 持有 ListCell 的强引用的问题 (#4347) 2025-08-28 20:21:55 +08:00
Burning_TNTandGlavo d34dc82db6 Feature: Decompress legacy HMCL log files while exporting. (#4342)
Co-authored-by: Glavo <[email protected]>
2025-08-27 21:44:33 +08:00
Glavo 73214ad599 不对回环地址应用代理 (#4338) 2025-08-27 21:43:54 +08:00
Wulian233 1ddb73595d 修复世界管理页面不支持显示极限模式的问题 (#4321) 2025-08-27 21:41:52 +08:00
Glavo f9ee9c8592 更严格地检测文件名合法性 (#4341) 2025-08-27 20:10:52 +08:00
Burning_TNT 0fdfc945c3 Fix: IJ support (#4343) 2025-08-26 22:43:26 +08:00
YuChuXi 97219c951e 游戏崩溃窗口中增加对拍照的提醒 (#4294) 2025-08-26 21:54:42 +08:00
Glavo 64cc64095d 增加 TaskListPane 中任务条目之间的间距 (#4340) 2025-08-26 21:51:59 +08:00
91 changed files with 7969 additions and 1099 deletions

No files matched your search

+15 -3
View File
@@ -1,3 +1,4 @@
import org.jackhuang.hmcl.gradle.CheckTranslations
import org.jackhuang.hmcl.gradle.mod.ParseModDataTask
import java.net.URI
import java.nio.file.FileSystems
@@ -298,9 +299,9 @@ fun parseToolOptions(options: String?): MutableList<String> {
tasks.withType<JavaExec> {
if (name != "run") {
jvmArgs(addOpens.map { "--add-opens=$it=ALL-UNNAMED" })
if (javaVersion >= JavaVersion.VERSION_24) {
jvmArgs("--enable-native-access=ALL-UNNAMED")
}
// if (javaVersion >= JavaVersion.VERSION_24) {
// jvmArgs("--enable-native-access=ALL-UNNAMED")
// }
}
}
@@ -332,6 +333,17 @@ tasks.register<JavaExec>("run") {
}
}
// Check Translations
tasks.register<CheckTranslations>("checkTranslations") {
val dir = layout.projectDirectory.dir("src/main/resources/assets/lang")
englishFile.set(dir.file("I18N.properties"))
simplifiedChineseFile.set(dir.file("I18N_zh_CN.properties"))
traditionalChineseFile.set(dir.file("I18N_zh.properties"))
classicalChineseFile.set(dir.file("I18N_lzh.properties"))
}
// mcmod data
tasks.register<ParseModDataTask>("parseModData") {
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

@@ -19,10 +19,13 @@ package org.jackhuang.hmcl;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.util.platform.Architecture;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.EnumSet;
/**
* Stores metadata about this application.
@@ -38,6 +41,10 @@ public final class Metadata {
public static final String TITLE = NAME + " " + VERSION;
public static final String FULL_TITLE = FULL_NAME + " v" + VERSION;
public static final int MINIMUM_REQUIRED_JAVA_VERSION = 11;
public static final int MINIMUM_SUPPORTED_JAVA_VERSION = 17;
public static final int RECOMMENDED_JAVA_VERSION = 21;
public static final String PUBLISH_URL = "https://hmcl.huangyuhui.net";
public static final String ABOUT_URL = PUBLISH_URL + "/about";
public static final String DOWNLOAD_URL = PUBLISH_URL + "/download";
@@ -94,4 +101,30 @@ public final class Metadata {
return !isStable() && !isDev();
}
public static @Nullable String getSuggestedJavaDownloadLink() {
if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX && Architecture.SYSTEM_ARCH == Architecture.LOONGARCH64_OW)
return "https://www.loongnix.cn/zh/api/java/downloads-jdk21/index.html";
else {
EnumSet<Architecture> supportedArchitectures;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS)
supportedArchitectures = EnumSet.of(Architecture.X86_64, Architecture.X86, Architecture.ARM64);
else if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX)
supportedArchitectures = EnumSet.of(
Architecture.X86_64, Architecture.X86,
Architecture.ARM64, Architecture.ARM32,
Architecture.RISCV64, Architecture.LOONGARCH64
);
else if (OperatingSystem.CURRENT_OS == OperatingSystem.MACOS)
supportedArchitectures = EnumSet.of(Architecture.X86_64, Architecture.ARM64);
else
supportedArchitectures = EnumSet.noneOf(Architecture.class);
if (supportedArchitectures.contains(Architecture.SYSTEM_ARCH))
return String.format("https://docs.hmcl.net/downloads/%s/%s.html",
OperatingSystem.CURRENT_OS.getCheckedName(),
Architecture.SYSTEM_ARCH.getCheckedName()
);
else
return null;
}
}
}
@@ -21,15 +21,18 @@ import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.auth.AuthInfo;
import org.jackhuang.hmcl.launch.DefaultLauncher;
import org.jackhuang.hmcl.launch.ProcessListener;
import org.jackhuang.hmcl.util.i18n.I18n;
import org.jackhuang.hmcl.util.i18n.LocaleUtils;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.platform.ManagedProcess;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
/**
@@ -58,61 +61,86 @@ public final class HMCLGameLauncher extends DefaultLauncher {
}
private void generateOptionsTxt() {
File optionsFile = new File(repository.getRunDirectory(version.getId()), "options.txt");
File configFolder = new File(repository.getRunDirectory(version.getId()), "config");
if (optionsFile.exists()) {
if (config().isDisableAutoGameOptions())
return;
}
if (configFolder.isDirectory()) {
if (findFiles(configFolder, "options.txt")) {
return;
Path runDir = repository.getRunDirectory(version.getId()).toPath();
Path optionsFile = runDir.resolve("options.txt");
Path configFolder = runDir.resolve("config");
if (Files.exists(optionsFile))
return;
if (Files.isDirectory(configFolder)) {
try (Stream<Path> stream = Files.walk(configFolder, 2, FileVisitOption.FOLLOW_LINKS)) {
if (stream.anyMatch(file -> "options.txt".equals(FileUtils.getName(file))))
return;
} catch (IOException e) {
LOG.warning("Failed to visit config folder", e);
}
}
if (!I18n.isUseChinese()) {
Locale locale = Locale.getDefault();
if (LocaleUtils.isEnglish(locale))
return;
}
String lang;
/*
1.0- :没有语言选项,遇到这些版本时不设置
1.1 ~ 5 :zh_CN 时正常,zh_cn 时崩溃(最后两位字母必须大写,否则将会 NPE 崩溃)
1.6 ~ 10 :zh_CN 时正常,zh_cn 时自动切换为英文
1.11 ~ 12:zh_cn 时正常,zh_CN 时虽然显示了中文但语言设置会错误地显示选择英文
1.13+ :zh_cn 时正常,zh_CN 时自动切换为英文
* 1.0 : No language option, do not set for these versions
* 1.1 ~ 1.5 : zh_CN works fine, zh_cn will crash (the last two letters must be uppercase, otherwise it will cause an NPE crash)
* 1.6 ~ 1.10 : zh_CN works fine, zh_cn will automatically switch to English
* 1.11 ~ 1.12 : zh_cn works fine, zh_CN will display Chinese but the language setting will incorrectly show English as selected
* 1.13+ : zh_cn works fine, zh_CN will automatically switch to English
*/
GameVersionNumber gameVersion = GameVersionNumber.asGameVersion(repository.getGameVersion(version));
if (gameVersion.compareTo("1.1") < 0) {
lang = null;
} else if (gameVersion.compareTo("1.11") < 0) {
lang = "zh_CN";
} else {
lang = "zh_cn";
}
if (gameVersion.compareTo("1.1") < 0)
return;
if (lang != null) {
try {
FileUtils.writeText(optionsFile, String.format("lang:%s\n", lang));
} catch (IOException e) {
LOG.warning("Unable to generate options.txt", e);
}
String lang = normalizedLanguageTag(locale, gameVersion);
if (lang.isEmpty())
return;
if (gameVersion.compareTo("1.11") >= 0)
lang = lang.toLowerCase(Locale.ROOT);
try {
Files.createDirectories(optionsFile.getParent());
Files.writeString(optionsFile, String.format("lang:%s\n", lang));
} catch (IOException e) {
LOG.warning("Unable to generate options.txt", e);
}
}
private boolean findFiles(File folder, String fileName) {
File[] fs = folder.listFiles();
if (fs != null) {
for (File f : fs) {
if (f.isDirectory())
if (f.listFiles((dir, name) -> name.equals(fileName)) != null)
return true;
if (f.getName().equals(fileName))
return true;
}
private static String normalizedLanguageTag(Locale locale, GameVersionNumber gameVersion) {
String language = locale.getLanguage();
String region = locale.getCountry();
switch (language) {
case "ru":
return "ru_RU";
case "uk":
return "uk_UA";
case "es":
return "es_ES";
case "ja":
return "ja_JP";
case "lzh":
return gameVersion.compareTo("1.16") >= 0
? "lzh"
: "";
case "zh":
default:
if (LocaleUtils.isChinese(locale)) {
String script = LocaleUtils.getScript(locale);
if ("Hant".equals(script)) {
if ((region.equals("HK") || region.equals("MO") && gameVersion.compareTo("1.16") >= 0))
return "zh_HK";
return "zh_TW";
}
return "zh_CN";
}
return "";
}
return false;
}
@Override
@@ -314,6 +314,8 @@ public class HMCLGameRepository extends DefaultGameRepository {
return VersionIconType.FABRIC.getIcon();
else if (libraryAnalyzer.has(LibraryAnalyzer.LibraryType.FORGE))
return VersionIconType.FORGE.getIcon();
else if (libraryAnalyzer.has(LibraryAnalyzer.LibraryType.CLEANROOM))
return VersionIconType.CLEANROOM.getIcon();
else if (libraryAnalyzer.has(LibraryAnalyzer.LibraryType.NEO_FORGE))
return VersionIconType.NEO_FORGE.getIcon();
else if (libraryAnalyzer.has(LibraryAnalyzer.LibraryType.QUILT))
@@ -452,7 +452,9 @@ public final class LauncherHelper {
return result;
} else {
GameJavaVersion gameJavaVersion;
if (violatedMandatoryConstraints.contains(JavaVersionConstraint.GAME_JSON))
if (violatedMandatoryConstraints.contains(JavaVersionConstraint.CLEANROOM_JAVA_21))
gameJavaVersion = GameJavaVersion.JAVA_21;
else if (violatedMandatoryConstraints.contains(JavaVersionConstraint.GAME_JSON))
gameJavaVersion = version.getJavaVersion();
else if (violatedMandatoryConstraints.contains(JavaVersionConstraint.VANILLA))
gameJavaVersion = GameJavaVersion.getMinimumJavaVersion(gameVersion);
@@ -542,6 +544,9 @@ public final class LauncherHelper {
case MODDED_JAVA_21:
suggestions.add(i18n("launch.advice.modded_java", 21, gameVersion));
break;
case CLEANROOM_JAVA_21:
suggestions.add(i18n("launch.advice.cleanroom"));
break;
case VANILLA_JAVA_8_51:
suggestions.add(i18n("launch.advice.java8_51_1_13"));
break;
@@ -236,7 +236,11 @@ public final class ModpackHelper {
if (provider == null) {
throw new UnsupportedModpackException();
}
return provider.createUpdateTask(profile.getDependency(), name, zipFile, modpack);
if (modpack.getManifest() instanceof MultiMCInstanceConfiguration)
return provider.createUpdateTask(profile.getDependency(), name, zipFile, modpack)
.thenComposeAsync(() -> createMultiMCPostUpdateTask(profile, (MultiMCInstanceConfiguration) modpack.getManifest(), name));
else
return provider.createUpdateTask(profile.getDependency(), name, zipFile, modpack);
}
public static void toVersionSetting(MultiMCInstanceConfiguration c, VersionSetting vs) {
@@ -276,6 +280,24 @@ public final class ModpackHelper {
}
}
private static void applyCommandAndJvmSettings(MultiMCInstanceConfiguration c, VersionSetting vs) {
if (c.isOverrideCommands()) {
vs.setWrapper(Lang.nonNull(c.getWrapperCommand(), ""));
vs.setPreLaunchCommand(Lang.nonNull(c.getPreLaunchCommand(), ""));
}
if (c.isOverrideJavaArgs()) {
vs.setJavaArgs(Lang.nonNull(c.getJvmArgs(), ""));
}
}
private static Task<Void> createMultiMCPostUpdateTask(Profile profile, MultiMCInstanceConfiguration manifest, String version) {
return Task.runAsync(Schedulers.javafx(), () -> {
VersionSetting vs = Objects.requireNonNull(profile.getRepository().specializeVersionSetting(version));
ModpackHelper.applyCommandAndJvmSettings(manifest, vs);
});
}
private static Task<Void> createMultiMCPostInstallTask(Profile profile, MultiMCInstanceConfiguration manifest, String version) {
return Task.runAsync(Schedulers.javafx(), () -> {
VersionSetting vs = Objects.requireNonNull(profile.getRepository().specializeVersionSetting(version));
@@ -30,6 +30,7 @@ import org.jackhuang.hmcl.util.io.NetworkUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@@ -103,6 +104,7 @@ public final class OAuthServer extends NanoHTTPD implements OAuth.Session {
String html;
try {
html = IOUtils.readFullyAsString(OAuthServer.class.getResourceAsStream("/assets/microsoft_auth.html"))
.replace("%lang%", Locale.getDefault().toLanguageTag())
.replace("%close-page%", i18n("account.methods.microsoft.close_page"));
} catch (IOException e) {
LOG.error("Failed to load html", e);
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,8 @@ import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.text.Font;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.util.Lazy;
import org.jackhuang.hmcl.util.i18n.I18n;
import org.jackhuang.hmcl.util.i18n.LocaleUtils;
import org.jackhuang.hmcl.util.io.JarUtils;
import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jackhuang.hmcl.util.platform.SystemUtils;
@@ -32,8 +34,7 @@ import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.Objects;
import java.util.*;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
@@ -50,7 +51,21 @@ public final class FontManager {
public static final double DEFAULT_FONT_SIZE = 12.0f;
private static final Lazy<Font> DEFAULT_FONT = new Lazy<>(() -> {
Font font = tryLoadDefaultFont(Metadata.HMCL_CURRENT_DIRECTORY);
Font font;
// Recommended
font = tryLoadLocalizedFont(Metadata.HMCL_CURRENT_DIRECTORY.resolve("font"));
if (font != null)
return font;
font = tryLoadLocalizedFont(Metadata.HMCL_GLOBAL_DIRECTORY.resolve("font"));
if (font != null)
return font;
// Legacy
font = tryLoadDefaultFont(Metadata.HMCL_CURRENT_DIRECTORY);
if (font != null)
return font;
@@ -69,10 +84,12 @@ public final class FontManager {
return font;
}
// Default
String fcMatchPattern;
if (OperatingSystem.CURRENT_OS.isLinuxOrBSD()
&& Locale.getDefault() != Locale.ROOT
&& !"en".equals(Locale.getDefault().getLanguage()))
return findByFcMatch();
&& !(fcMatchPattern = I18n.getLocale().getFcMatchPattern()).isEmpty())
return findByFcMatch(fcMatchPattern);
else
return null;
});
@@ -108,6 +125,7 @@ public final class FontManager {
for (String extension : FONT_EXTENSIONS) {
Path path = dir.resolve("font." + extension);
if (Files.isRegularFile(path)) {
LOG.info("Load font file: " + path);
try {
Font font = Font.loadFont(path.toUri().toURL().toExternalForm(), DEFAULT_FONT_SIZE);
if (font != null) {
@@ -123,16 +141,47 @@ public final class FontManager {
return null;
}
public static Font findByFcMatch() {
private static Font tryLoadLocalizedFont(Path dir) {
Map<String, Map<String, Path>> fontFiles = LocaleUtils.findAllLocalizedFiles(dir, "font", Set.of(FONT_EXTENSIONS));
if (fontFiles.isEmpty())
return null;
List<Locale> candidateLocales = I18n.getLocale().getCandidateLocales();
for (Locale locale : candidateLocales) {
Map<String, Path> extToFiles = fontFiles.get(LocaleUtils.toLanguageKey(locale));
if (extToFiles != null) {
for (String ext : FONT_EXTENSIONS) {
Path fontFile = extToFiles.get(ext);
if (fontFile != null) {
LOG.info("Load font file: " + fontFile);
try {
Font font = Font.loadFont(
fontFile.toAbsolutePath().normalize().toUri().toURL().toExternalForm(),
DEFAULT_FONT_SIZE);
if (font != null)
return font;
} catch (MalformedURLException ignored) {
}
LOG.warning("Failed to load font " + fontFile);
}
}
}
}
return null;
}
public static Font findByFcMatch(String pattern) {
Path fcMatch = SystemUtils.which("fc-match");
if (fcMatch == null)
return null;
try {
String result = SystemUtils.run(fcMatch.toString(),
":lang=" + Locale.getDefault().toLanguageTag(),
pattern,
"--format", "%{family}\\n%{file}").trim();
String[] results = result.split("\\n");
if (results.length != 2 || results[0].isEmpty() || results[1].isEmpty()) {
LOG.warning("Unexpected output from fc-match: " + result);
@@ -148,6 +197,7 @@ public final class FontManager {
return null;
}
LOG.info("Load font file: " + path);
Font[] fonts = Font.loadFonts(file.toUri().toURL().toExternalForm(), DEFAULT_FONT_SIZE);
if (fonts == null) {
LOG.warning("Failed to load font from " + path);
@@ -19,22 +19,28 @@ package org.jackhuang.hmcl.setting;
import javafx.beans.InvalidationListener;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.NetworkUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.net.*;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
public final class ProxyManager {
private static final ProxySelector NO_PROXY = new SimpleProxySelector(Proxy.NO_PROXY);
private static final ProxySelector SYSTEM_DEFAULT = Objects.requireNonNullElse(ProxySelector.getDefault(), NO_PROXY);
private static final SimpleProxySelector NO_PROXY = new SimpleProxySelector(Proxy.NO_PROXY);
private static final ProxySelector SYSTEM_DEFAULT;
static {
ProxySelector systemProxySelector = ProxySelector.getDefault();
SYSTEM_DEFAULT = systemProxySelector != null
? new ProxySelectorWrapper(systemProxySelector)
: NO_PROXY;
}
private static volatile @NotNull ProxySelector defaultProxySelector = SYSTEM_DEFAULT;
private static volatile @Nullable SimpleAuthenticator defaultAuthenticator = null;
@@ -51,7 +57,7 @@ public final class ProxyManager {
LOG.warning("Illegal proxy port: " + port);
return NO_PROXY;
} else {
return new SimpleProxySelector(new Proxy(proxyType, new InetSocketAddress(host, port)));
return new ProxySelectorWrapper(new SimpleProxySelector(new Proxy(proxyType, new InetSocketAddress(host, port))));
}
} else {
return ProxyManager.SYSTEM_DEFAULT;
@@ -106,15 +112,41 @@ public final class ProxyManager {
config().proxyPassProperty().addListener(updateAuthenticator);
}
private static final class SimpleProxySelector extends ProxySelector {
private static abstract class AbstractProxySelector extends ProxySelector {
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
if (uri == null || sa == null || ioe == null) {
throw new IllegalArgumentException("Arguments can't be null.");
}
}
}
private static final class SimpleProxySelector extends AbstractProxySelector {
private final List<Proxy> proxies;
SimpleProxySelector(Proxy proxy) {
this(Collections.singletonList(proxy));
this.proxies = List.of(proxy);
}
SimpleProxySelector(List<Proxy> proxies) {
this.proxies = proxies;
@Override
public List<Proxy> select(URI uri) {
if (uri == null)
throw new IllegalArgumentException("URI can't be null.");
return proxies;
}
@Override
public String toString() {
return "SimpleProxySelector" + proxies;
}
}
/// Wraps another ProxySelector to avoid using proxy for loopback addresses.
private static final class ProxySelectorWrapper extends AbstractProxySelector {
private final ProxySelector source;
ProxySelectorWrapper(ProxySelector source) {
this.source = source;
}
@Override
@@ -122,19 +154,10 @@ public final class ProxyManager {
if (uri == null)
throw new IllegalArgumentException("URI can't be null.");
return proxies;
}
if (NetworkUtils.isLoopbackAddress(uri))
return NO_PROXY.proxies;
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
if (uri == null || sa == null || ioe == null) {
throw new IllegalArgumentException("Arguments can't be null.");
}
}
@Override
public String toString() {
return "SimpleProxySelector" + proxies;
return source.select(uri);
}
}
@@ -34,7 +34,8 @@ public enum VersionIconType {
NEO_FORGE("/assets/img/neoforge.png"),
FURNACE("/assets/img/furnace.png"),
QUILT("/assets/img/quilt.png"),
APRIL_FOOLS("/assets/img/april_fools.png");
APRIL_FOOLS("/assets/img/april_fools.png"),
CLEANROOM("/assets/img/cleanroom.png");
// Please append new items at last
@@ -42,6 +42,7 @@ import org.jackhuang.hmcl.Launcher;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.game.ModpackHelper;
import org.jackhuang.hmcl.java.JavaManager;
import org.jackhuang.hmcl.java.JavaRuntime;
import org.jackhuang.hmcl.setting.*;
import org.jackhuang.hmcl.task.Task;
import org.jackhuang.hmcl.task.TaskExecutor;
@@ -325,6 +326,27 @@ public final class Controllers {
}
}
if (JavaRuntime.CURRENT_VERSION < Metadata.MINIMUM_SUPPORTED_JAVA_VERSION) {
Number shownTipVersion = null;
try {
shownTipVersion = (Number) config().getShownTips().get(JAVA_VERSION_TIP);
} catch (ClassCastException e) {
LOG.warning("Invalid type for shown tips key: " + JAVA_VERSION_TIP, e);
}
if (shownTipVersion == null || shownTipVersion.intValue() < Metadata.MINIMUM_SUPPORTED_JAVA_VERSION) {
MessageDialogPane.Builder builder = new MessageDialogPane.Builder(i18n("fatal.deprecated_java_version"), null, MessageType.WARNING);
String downloadLink = Metadata.getSuggestedJavaDownloadLink();
if (downloadLink != null)
builder.addHyperLink(
i18n("fatal.deprecated_java_version.download_link", Metadata.RECOMMENDED_JAVA_VERSION),
downloadLink
);
Controllers.dialog(builder
.ok(() -> config().getShownTips().put(JAVA_VERSION_TIP, Metadata.MINIMUM_SUPPORTED_JAVA_VERSION))
.build());
}
}
if (globalConfig().getAgreementVersion() < 1) {
JFXDialogLayout agreementPane = new JFXDialogLayout();
agreementPane.setHeading(new Label(i18n("launcher.agreement")));
@@ -52,6 +52,7 @@ import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;
import javafx.util.StringConverter;
import org.jackhuang.hmcl.setting.Theme;
import org.jackhuang.hmcl.task.CacheFileTask;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.task.Task;
@@ -1159,6 +1160,13 @@ public final class FXUtils {
return button;
}
public static JFXButton newToggleButton4(SVG icon) {
JFXButton button = new JFXButton();
button.getStyleClass().add("toggle-icon4");
button.setGraphic(icon.createIcon(Theme.blackFill(), -1));
return button;
}
public static Label truncatedLabel(String text, int limit) {
Label label = new Label();
if (text.length() <= limit) {
@@ -138,6 +138,9 @@ public class InstallerItem extends Control {
case "forge":
iconType = VersionIconType.FORGE;
break;
case "cleanroom":
iconType = VersionIconType.CLEANROOM;
break;
case "liteloader":
iconType = VersionIconType.CHICKEN;
break;
@@ -232,6 +235,7 @@ public class InstallerItem extends Control {
InstallerItem fabric = new InstallerItem(FABRIC, style);
InstallerItem fabricApi = new InstallerItem(FABRIC_API, style);
InstallerItem forge = new InstallerItem(FORGE, style);
InstallerItem cleanroom = new InstallerItem(CLEANROOM, style);
InstallerItem neoForge = new InstallerItem(NEO_FORGE, style);
InstallerItem liteLoader = new InstallerItem(LITELOADER, style);
InstallerItem optiFine = new InstallerItem(OPTIFINE, style);
@@ -239,11 +243,11 @@ public class InstallerItem extends Control {
InstallerItem quiltApi = new InstallerItem(QUILT_API, style);
Map<InstallerItem, Set<InstallerItem>> incompatibleMap = new HashMap<>();
mutualIncompatible(incompatibleMap, forge, fabric, quilt, neoForge);
addIncompatibles(incompatibleMap, liteLoader, fabric, quilt, neoForge);
addIncompatibles(incompatibleMap, optiFine, fabric, quilt, neoForge);
addIncompatibles(incompatibleMap, fabricApi, forge, quiltApi, neoForge, liteLoader, optiFine);
addIncompatibles(incompatibleMap, quiltApi, forge, fabric, fabricApi, neoForge, liteLoader, optiFine);
mutualIncompatible(incompatibleMap, forge, fabric, quilt, neoForge, cleanroom);
addIncompatibles(incompatibleMap, liteLoader, fabric, quilt, neoForge, cleanroom);
addIncompatibles(incompatibleMap, optiFine, fabric, quilt, neoForge, cleanroom);
addIncompatibles(incompatibleMap, fabricApi, forge, quiltApi, neoForge, liteLoader, optiFine, cleanroom);
addIncompatibles(incompatibleMap, quiltApi, forge, fabric, fabricApi, neoForge, liteLoader, optiFine, cleanroom);
for (Map.Entry<InstallerItem, Set<InstallerItem>> entry : incompatibleMap.entrySet()) {
InstallerItem item = entry.getKey();
@@ -277,7 +281,7 @@ public class InstallerItem extends Control {
game.versionProperty.set(new InstalledState(gameVersion, false, false));
}
InstallerItem[] all = {game, forge, neoForge, liteLoader, optiFine, fabric, fabricApi, quilt, quiltApi};
InstallerItem[] all = {game, forge, neoForge, liteLoader, optiFine, fabric, fabricApi, quilt, quiltApi, cleanroom};
for (InstallerItem item : all) {
if (!item.resolvedStateProperty.isBound()) {
@@ -293,6 +297,8 @@ public class InstallerItem extends Control {
if (gameVersion == null) {
this.libraries = all;
} else if (gameVersion.equals("1.12.2")) {
this.libraries = new InstallerItem[]{game, forge, cleanroom, liteLoader, optiFine};
} else if (GameVersionNumber.compare(gameVersion, "1.13") < 0) {
this.libraries = new InstallerItem[]{game, forge, liteLoader, optiFine};
} else {
@@ -41,6 +41,7 @@ import org.jackhuang.hmcl.ui.construct.AdvancedListItem;
import org.jackhuang.hmcl.ui.construct.ClassTitle;
import org.jackhuang.hmcl.ui.decorator.DecoratorAnimatedPage;
import org.jackhuang.hmcl.ui.decorator.DecoratorPage;
import org.jackhuang.hmcl.util.i18n.LocaleUtils;
import org.jackhuang.hmcl.util.io.NetworkUtils;
import org.jackhuang.hmcl.util.javafx.BindingMapping;
import org.jackhuang.hmcl.util.javafx.MappedObservableList;
@@ -49,8 +50,9 @@ import org.jackhuang.hmcl.util.platform.OperatingSystem;
import org.jackhuang.hmcl.util.platform.windows.Kernel32;
import org.jackhuang.hmcl.util.platform.windows.WinConstants;
import java.time.Duration;
import java.time.ZoneId;
import java.util.Arrays;
import java.time.ZonedDateTime;
import java.util.Locale;
import static org.jackhuang.hmcl.setting.ConfigHolder.globalConfig;
@@ -63,27 +65,22 @@ public final class AccountListPage extends DecoratorAnimatedPage implements Deco
static final BooleanProperty RESTRICTED = new SimpleBooleanProperty(true);
private static boolean isExemptedRegion() {
String zoneId = ZoneId.systemDefault().getId();
if (Arrays.asList(
"Asia/Shanghai",
// Although Asia/Beijing is not a legal name, Deepin uses it
"Asia/Beijing",
"Asia/Chongqing",
"Asia/Chungking",
"Asia/Harbin"
).contains(zoneId))
if ("Asia/Shanghai".equals(ZoneId.systemDefault().getId()))
return true;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && NativeUtils.USE_JNA) {
Kernel32 kernel32 = Kernel32.INSTANCE;
// https://learn.microsoft.com/windows/win32/intl/table-of-geographical-locations
if (kernel32 != null && kernel32.GetUserGeoID(WinConstants.GEOCLASS_NATION) == 45) // China
// Check if the time zone is UTC+8
if (ZonedDateTime.now().getOffset().getTotalSeconds() == Duration.ofHours(8).toSeconds()) {
if ("CN".equals(LocaleUtils.SYSTEM_DEFAULT.getCountry()))
return true;
} else if (OperatingSystem.CURRENT_OS == OperatingSystem.LINUX && "GMT+08:00".equals(zoneId))
// Some Linux distributions may use invalid time zone ids (e.g., Asia/Beijing)
// Java may not be able to resolve this name and use GMT+08:00 instead.
return true;
if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && NativeUtils.USE_JNA) {
Kernel32 kernel32 = Kernel32.INSTANCE;
// https://learn.microsoft.com/windows/win32/intl/table-of-geographical-locations
if (kernel32 != null && kernel32.GetUserGeoID(WinConstants.GEOCLASS_NATION) == 45) // China
return true;
}
}
return false;
}
@@ -30,8 +30,7 @@ public class TransitionPane extends StackPane implements AnimationHandler {
private Duration duration;
private Node previousNode, currentNode;
{
currentNode = getChildren().stream().findFirst().orElse(null);
public TransitionPane() {
FXUtils.setOverflowHidden(this);
}
@@ -91,8 +90,12 @@ public class TransitionPane extends StackPane implements AnimationHandler {
private void updateContent(Node newView) {
if (getWidth() > 0 && getHeight() > 0) {
previousNode = currentNode;
if (previousNode == null)
previousNode = EMPTY_PANE;
if (previousNode == null) {
if (getChildren().isEmpty())
previousNode = EMPTY_PANE;
else
previousNode = getChildren().get(0);
}
} else
previousNode = EMPTY_PANE;
@@ -33,6 +33,7 @@ import javafx.scene.control.ListCell;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import org.jackhuang.hmcl.download.cleanroom.CleanroomInstallTask;
import org.jackhuang.hmcl.download.fabric.FabricAPIInstallTask;
import org.jackhuang.hmcl.download.fabric.FabricInstallTask;
import org.jackhuang.hmcl.download.forge.ForgeNewInstallTask;
@@ -164,6 +165,8 @@ public final class TaskListPane extends StackPane {
if (task.getInheritedStage() != null && task.getInheritedStage().startsWith("hmcl.install.game"))
return;
task.setName(i18n("install.installer.install", i18n("install.installer.game")));
} else if (task instanceof CleanroomInstallTask) {
task.setName(i18n("install.installer.install", i18n("install.installer.cleanroom")));
} else if (task instanceof ForgeNewInstallTask || task instanceof ForgeOldInstallTask) {
task.setName(i18n("install.installer.install", i18n("install.installer.forge")));
} else if (task instanceof NeoForgeInstallTask || task instanceof NeoForgeOldInstallTask) {
@@ -279,10 +282,10 @@ public final class TaskListPane extends StackPane {
private final JFXProgressBar bar = new JFXProgressBar();
private WeakReference<StageNode> prevStageNodeRef;
private ChangeListener<StageNode.Status> statusChangeListener;
private StatusChangeListener statusChangeListener;
private Cell() {
setPadding(Insets.EMPTY);
setPadding(new Insets(0, 0, 4, 0));
prefWidthProperty().bind(cellWidth);
@@ -364,32 +367,32 @@ public final class TaskListPane extends StackPane {
pane.setBottom(null);
}
}
}
private final class StatusChangeListener implements ChangeListener<StageNode.Status>, WeakListener {
private static final class StatusChangeListener implements ChangeListener<StageNode.Status>, WeakListener {
private final WeakReference<Cell> cellRef;
private final WeakReference<Cell> cellRef;
private StatusChangeListener(Cell cell) {
this.cellRef = new WeakReference<>(cell);
}
@Override
public boolean wasGarbageCollected() {
return cellRef.get() == null;
}
@Override
public void changed(ObservableValue<? extends StageNode.Status> observable,
StageNode.Status oldValue,
StageNode.Status newValue) {
Cell cell = cellRef.get();
if (cell == null) {
if (observable != null)
observable.removeListener(this);
return;
}
cell.updateLeftIcon(newValue);
private StatusChangeListener(Cell cell) {
this.cellRef = new WeakReference<>(cell);
}
@Override
public boolean wasGarbageCollected() {
return cellRef.get() == null;
}
@Override
public void changed(ObservableValue<? extends StageNode.Status> observable,
StageNode.Status oldValue,
StageNode.Status newValue) {
Cell cell = cellRef.get();
if (cell == null) {
if (observable != null)
observable.removeListener(this);
return;
}
cell.updateLeftIcon(newValue);
}
}
@@ -439,6 +442,7 @@ public final class TaskListPane extends StackPane {
case "hmcl.install.libraries": message = i18n("libraries.download"); break;
case "hmcl.install.game": message = i18n("install.installer.install", i18n("install.installer.game") + " " + stageValue); break;
case "hmcl.install.forge": message = i18n("install.installer.install", i18n("install.installer.forge") + " " + stageValue); break;
case "hmcl.install.cleanroom": message = i18n("install.installer.install", i18n("install.installer.cleanroom") + " " + stageValue); break;
case "hmcl.install.neoforge": message = i18n("install.installer.install", i18n("install.installer.neoforge") + " " + stageValue); break;
case "hmcl.install.liteloader": message = i18n("install.installer.install", i18n("install.installer.liteloader") + " " + stageValue); break;
case "hmcl.install.optifine": message = i18n("install.installer.install", i18n("install.installer.optifine") + " " + stageValue); break;
@@ -55,7 +55,9 @@ public class DecoratorSkin extends SkinBase<Decorator> {
private final Stage primaryStage;
private final TransitionPane navBarPane;
@SuppressWarnings("FieldCanBeLocal")
private final InvalidationListener onWindowsStatusChange;
private final EventHandler<MouseEvent> onTitleBarDoubleClick;
private double mouseInitX, mouseInitY, stageInitX, stageInitY, stageInitWidth, stageInitHeight;
@@ -104,6 +106,12 @@ public class DecoratorSkin extends SkinBase<Decorator> {
root.addEventFilter(MouseEvent.MOUSE_MOVED, onMouseMoved);
}
};
onTitleBarDoubleClick = event -> {
if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
primaryStage.setMaximized(!primaryStage.isMaximized());
event.consume();
}
};
WeakInvalidationListener weakOnWindowsStatusChange = new WeakInvalidationListener(onWindowsStatusChange);
primaryStage.iconifiedProperty().addListener(weakOnWindowsStatusChange);
primaryStage.maximizedProperty().addListener(weakOnWindowsStatusChange);
@@ -111,6 +119,7 @@ public class DecoratorSkin extends SkinBase<Decorator> {
onWindowsStatusChange.invalidated(null);
} else {
onWindowsStatusChange = null;
onTitleBarDoubleClick = null;
root.addEventFilter(MouseEvent.MOUSE_RELEASED, onMouseReleased);
root.addEventFilter(MouseEvent.MOUSE_DRAGGED, onMouseDragged);
root.addEventFilter(MouseEvent.MOUSE_MOVED, onMouseMoved);
@@ -188,16 +197,6 @@ public class DecoratorSkin extends SkinBase<Decorator> {
BorderPane titleBar = new BorderPane();
titleContainer.getChildren().add(titleBar);
// https://github.com/HMCL-dev/HMCL/issues/4290
if (OperatingSystem.CURRENT_OS != OperatingSystem.MACOS) {
titleBar.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
primaryStage.setMaximized(!primaryStage.isMaximized());
event.consume();
}
});
}
Rectangle buttonsContainerPlaceHolder = new Rectangle();
{
navBarPane = new TransitionPane();
@@ -324,6 +323,8 @@ public class DecoratorSkin extends SkinBase<Decorator> {
BorderPane.setAlignment(titleNode, Pos.CENTER_LEFT);
BorderPane.setMargin(titleNode, new Insets(0, 0, 0, 8));
}
if (onTitleBarDoubleClick != null)
center.setOnMouseClicked(onTitleBarDoubleClick);
navBar.setCenter(center);
if (canRefresh) {
@@ -130,6 +130,9 @@ public class InstallersPage extends AbstractInstallersPage {
case NEO_FORGE:
loaderName = i18n("install.installer.neoforge");
break;
case CLEANROOM:
loaderName = i18n("install.installer.cleanroom");
break;
case FABRIC:
loaderName = i18n("install.installer.fabric");
break;
@@ -19,18 +19,20 @@ package org.jackhuang.hmcl.ui.download;
import com.jfoenix.controls.*;
import javafx.beans.InvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import org.jackhuang.hmcl.download.DownloadProvider;
import org.jackhuang.hmcl.download.RemoteVersion;
import org.jackhuang.hmcl.download.VersionList;
import org.jackhuang.hmcl.download.cleanroom.CleanroomRemoteVersion;
import org.jackhuang.hmcl.download.fabric.FabricAPIRemoteVersion;
import org.jackhuang.hmcl.download.fabric.FabricRemoteVersion;
import org.jackhuang.hmcl.download.forge.ForgeRemoteVersion;
@@ -40,7 +42,6 @@ import org.jackhuang.hmcl.download.neoforge.NeoForgeRemoteVersion;
import org.jackhuang.hmcl.download.optifine.OptiFineRemoteVersion;
import org.jackhuang.hmcl.download.quilt.QuiltAPIRemoteVersion;
import org.jackhuang.hmcl.download.quilt.QuiltRemoteVersion;
import org.jackhuang.hmcl.setting.Theme;
import org.jackhuang.hmcl.setting.VersionIconType;
import org.jackhuang.hmcl.task.Schedulers;
import org.jackhuang.hmcl.task.Task;
@@ -72,17 +73,23 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
private final String libraryId;
private final String title;
private final Navigation navigation;
private final DownloadProvider downloadProvider;
private final VersionList<?> versionList;
private final Runnable callback;
private final ObservableList<RemoteVersion> versions = FXCollections.observableArrayList();
private final ObjectProperty<Status> status = new SimpleObjectProperty<>(Status.LOADING);
public VersionsPage(Navigation navigation, String title, String gameVersion, DownloadProvider downloadProvider, String libraryId, Runnable callback) {
public VersionsPage(Navigation navigation,
String title, String gameVersion,
DownloadProvider downloadProvider,
String libraryId,
Runnable callback) {
this.title = title;
this.gameVersion = gameVersion;
this.libraryId = libraryId;
this.navigation = navigation;
this.downloadProvider = downloadProvider;
this.versionList = downloadProvider.getVersionListById(libraryId);
this.callback = callback;
@@ -129,10 +136,6 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
navigation.onPrev(true);
}
private void onSponsor() {
FXUtils.openLink("https://bmclapidoc.bangbang93.com");
}
private enum Status {
LOADING,
FAILED,
@@ -148,22 +151,61 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
}
private static class RemoteVersionListCell extends ListCell<RemoteVersion> {
private final IconedTwoLineListItem content = new IconedTwoLineListItem();
private final RipplerContainer ripplerContainer = new RipplerContainer(content);
private final VersionsPage control;
private final TwoLineListItem twoLineListItem = new TwoLineListItem();
private final ImageView imageView = new ImageView();
private final StackPane pane = new StackPane();
private final Holder<RemoteVersionListCell> lastCell;
RemoteVersionListCell(Holder<RemoteVersionListCell> lastCell, String libraryId) {
RemoteVersionListCell(Holder<RemoteVersionListCell> lastCell, VersionsPage control) {
this.lastCell = lastCell;
if ("game".equals(libraryId)) {
content.getExternalLinkButton().setGraphic(SVG.GLOBE_BOOK.createIcon(Theme.blackFill(), -1));
FXUtils.installFastTooltip(content.getExternalLinkButton(), i18n("wiki.tooltip"));
this.control = control;
HBox hbox = new HBox(16);
HBox.setHgrow(twoLineListItem, Priority.ALWAYS);
hbox.setAlignment(Pos.CENTER);
HBox actions = new HBox(8);
actions.setAlignment(Pos.CENTER);
{
if ("game".equals(control.libraryId)) {
JFXButton wikiButton = newToggleButton4(SVG.GLOBE_BOOK);
wikiButton.setOnAction(event -> onOpenWiki());
FXUtils.installFastTooltip(wikiButton, i18n("wiki.tooltip"));
actions.getChildren().add(wikiButton);
}
JFXButton actionButton = newToggleButton4(SVG.ARROW_FORWARD);
actionButton.setOnAction(e -> onAction());
actions.getChildren().add(actionButton);
}
hbox.getChildren().setAll(imageView, twoLineListItem, actions);
pane.getStyleClass().add("md-list-cell");
StackPane.setMargin(content, new Insets(10, 16, 10, 16));
pane.getChildren().setAll(ripplerContainer);
StackPane.setMargin(hbox, new Insets(10, 16, 10, 16));
pane.getChildren().setAll(new RipplerContainer(hbox));
FXUtils.onClicked(this, this::onAction);
}
private void onAction() {
RemoteVersion item = getItem();
if (item == null)
return;
control.navigation.getSettings().put(control.libraryId, item);
control.callback.run();
}
private void onOpenWiki() {
RemoteVersion item = getItem();
if (!(item instanceof GameRemoteVersion))
return;
FXUtils.openLink(I18n.getWikiLink((GameRemoteVersion) item));
}
@Override
@@ -181,38 +223,34 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
}
setGraphic(pane);
content.setTitle(remoteVersion.getSelfVersion());
twoLineListItem.setTitle(I18n.getDisplaySelfVersion(remoteVersion));
if (remoteVersion.getReleaseDate() != null) {
content.setSubtitle(I18n.formatDateTime(remoteVersion.getReleaseDate()));
twoLineListItem.setSubtitle(I18n.formatDateTime(remoteVersion.getReleaseDate()));
} else {
content.setSubtitle(null);
twoLineListItem.setSubtitle(null);
}
if (remoteVersion instanceof GameRemoteVersion) {
RemoteVersion.Type versionType = remoteVersion.getVersionType();
String wikiSuffix = getWikiUrlSuffix(remoteVersion.getGameVersion());
switch (versionType) {
case RELEASE:
content.getTags().setAll(i18n("version.game.release"));
content.setImage(VersionIconType.GRASS.getIcon());
content.setExternalLink(i18n("wiki.version.game", wikiSuffix));
twoLineListItem.getTags().setAll(i18n("version.game.release"));
imageView.setImage(VersionIconType.GRASS.getIcon());
break;
case PENDING:
case SNAPSHOT:
if (versionType == RemoteVersion.Type.SNAPSHOT
&& GameVersionNumber.asGameVersion(remoteVersion.getGameVersion()).isAprilFools()) {
content.getTags().setAll(i18n("version.game.april_fools"));
content.setImage(VersionIconType.APRIL_FOOLS.getIcon());
twoLineListItem.getTags().setAll(i18n("version.game.april_fools"));
imageView.setImage(VersionIconType.APRIL_FOOLS.getIcon());
} else {
content.getTags().setAll(i18n("version.game.snapshot"));
content.setImage(VersionIconType.COMMAND.getIcon());
twoLineListItem.getTags().setAll(i18n("version.game.snapshot"));
imageView.setImage(VersionIconType.COMMAND.getIcon());
}
content.setExternalLink(i18n("wiki.version.game", wikiSuffix));
break;
default:
content.getTags().setAll(i18n("version.game.old"));
content.setImage(VersionIconType.CRAFT_TABLE.getIcon());
content.setExternalLink(i18n("wiki.version.game", wikiSuffix));
twoLineListItem.getTags().setAll(i18n("version.game.old"));
imageView.setImage(VersionIconType.CRAFT_TABLE.getIcon());
break;
}
} else {
@@ -223,6 +261,8 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
iconType = VersionIconType.OPTIFINE;
else if (remoteVersion instanceof ForgeRemoteVersion)
iconType = VersionIconType.FORGE;
else if (remoteVersion instanceof CleanroomRemoteVersion)
iconType = VersionIconType.CLEANROOM;
else if (remoteVersion instanceof NeoForgeRemoteVersion)
iconType = VersionIconType.NEO_FORGE;
else if (remoteVersion instanceof FabricRemoteVersion || remoteVersion instanceof FabricAPIRemoteVersion)
@@ -230,85 +270,15 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
else if (remoteVersion instanceof QuiltRemoteVersion || remoteVersion instanceof QuiltAPIRemoteVersion)
iconType = VersionIconType.QUILT;
else
iconType = null;
iconType = VersionIconType.COMMAND;
content.setImage(iconType != null ? iconType.getIcon() : null);
if (content.getSubtitle() == null)
content.setSubtitle(remoteVersion.getGameVersion());
imageView.setImage(iconType.getIcon());
if (twoLineListItem.getSubtitle() == null)
twoLineListItem.setSubtitle(remoteVersion.getGameVersion());
else
content.getTags().setAll(remoteVersion.getGameVersion());
content.setExternalLink(null);
twoLineListItem.getTags().setAll(remoteVersion.getGameVersion());
}
}
private String getWikiUrlSuffix(String gameVersion) {
String id = gameVersion.toLowerCase(Locale.ROOT);
switch (id) {
case "0.30-1":
case "0.30-2":
case "c0.30_01c":
return i18n("wiki.version.game.search", "Classic_0.30");
case "in-20100206-2103":
return i18n("wiki.version.game.search", "Indev_20100206");
case "inf-20100630-1":
return i18n("wiki.version.game.search", "Infdev_20100630");
case "inf-20100630-2":
return i18n("wiki.version.game.search", "Alpha_v1.0.0");
case "1.19_deep_dark_experimental_snapshot-1":
return "1.19-exp1";
case "in-20100130":
return i18n("wiki.version.game.search", "Indev_0.31_20100130");
case "b1.6-tb3":
return i18n("wiki.version.game.search", "Beta_1.6_Test_Build_3");
case "1.14_combat-212796":
return i18n("wiki.version.game.search", "1.14.3_-_Combat_Test");
case "1.14_combat-0":
return i18n("wiki.version.game.search", "Combat_Test_2");
case "1.14_combat-3":
return i18n("wiki.version.game.search", "Combat_Test_3");
case "1_15_combat-1":
return i18n("wiki.version.game.search", "Combat_Test_4");
case "1_15_combat-6":
return i18n("wiki.version.game.search", "Combat_Test_5");
case "1_16_combat-0":
return i18n("wiki.version.game.search", "Combat_Test_6");
case "1_16_combat-1":
return i18n("wiki.version.game.search", "Combat_Test_7");
case "1_16_combat-2":
return i18n("wiki.version.game.search", "Combat_Test_7b");
case "1_16_combat-3":
return i18n("wiki.version.game.search", "Combat_Test_7c");
case "1_16_combat-4":
return i18n("wiki.version.game.search", "Combat_Test_8");
case "1_16_combat-5":
return i18n("wiki.version.game.search", "Combat_Test_8b");
case "1_16_combat-6":
return i18n("wiki.version.game.search", "Combat_Test_8c");
}
if (id.startsWith("1.0.0-rc2")) return "RC2";
if (id.startsWith("2.0")) return i18n("wiki.version.game.search", "2.0");
if (id.startsWith("b1.8-pre1")) return "Beta_1.8-pre1";
if (id.startsWith("b1.1-")) return i18n("wiki.version.game.search", "Beta_1.1");
if (id.startsWith("a1.1.0")) return "Alpha_v1.1.0";
if (id.startsWith("a1.0.14")) return "Alpha_v1.0.14";
if (id.startsWith("a1.0.13_01")) return "Alpha_v1.0.13_01";
if (id.startsWith("in-20100214")) return i18n("wiki.version.game.search", "Indev_20100214");
if (id.contains("experimental-snapshot")) {
return id.replace("_experimental-snapshot-", "-exp");
}
if (id.startsWith("inf-")) return id.replace("inf-", "Infdev_");
if (id.startsWith("in-")) return id.replace("in-", "Indev_");
if (id.startsWith("rd-")) return "pre-Classic_" + id;
if (id.startsWith("b")) return id.replace("b", "Beta_");
if (id.startsWith("a")) return id.replace("a", "Alpha_v");
if (id.startsWith("c")) return id.replace("c", "Classic_").replace("st", "SURVIVAL_TEST");
return i18n("wiki.version.game.search", id);
}
}
private static final class VersionsPageSkin extends SkinBase<VersionsPage> {
@@ -424,14 +394,7 @@ public final class VersionsPage extends Control implements WizardPage, Refreshab
control.versions.addListener((InvalidationListener) o -> updateList());
Holder<RemoteVersionListCell> lastCell = new Holder<>();
list.setCellFactory(listView -> new RemoteVersionListCell(lastCell, control.libraryId));
FXUtils.onClicked(list, () -> {
if (list.getSelectionModel().getSelectedIndex() < 0)
return;
control.navigation.getSettings().put(control.libraryId, list.getSelectionModel().getSelectedItem());
control.callback.run();
});
list.setCellFactory(listView -> new RemoteVersionListCell(lastCell, control));
ComponentList.setVgrow(list, Priority.ALWAYS);
@@ -35,9 +35,12 @@ import org.jackhuang.hmcl.upgrade.UpdateHandler;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.i18n.Locales;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.IOUtils;
import org.tukaani.xz.XZInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -45,14 +48,15 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.util.Lang.thread;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
import static org.jackhuang.hmcl.util.javafx.ExtendedProperties.selectedItemPropertyFor;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
public final class SettingsPage extends SettingsView {
@@ -64,6 +68,8 @@ public final class SettingsPage extends SettingsView {
// ==== Languages ====
cboLanguage.getItems().setAll(Locales.LOCALES);
selectedItemPropertyFor(cboLanguage).bindBidirectional(config().localizationProperty());
disableAutoGameOptionsPane.selectedProperty().bindBidirectional(config().disableAutoGameOptionsProperty());
// ====
fileCommonLocation.selectedDataProperty().bindBidirectional(config().commonDirTypeProperty());
@@ -124,6 +130,42 @@ public final class SettingsPage extends SettingsView {
UpdateHandler.updateFrom(target);
}
/// This method guarantees to close both `input` and the current zip entry.
///
/// If no exception occurs, this method returns `true`;
/// If an exception occurs while reading from `input`, this method returns `false`;
/// If an exception occurs while writing to `output`, this method will throw it as is.
private static boolean exportLogFile(ZipOutputStream output,
Path file, // For logging
String entryName,
InputStream input,
byte[] buffer) throws IOException {
//noinspection TryFinallyCanBeTryWithResources
try {
output.putNextEntry(new ZipEntry(entryName));
int read;
while (true) {
try {
read = input.read(buffer);
if (read <= 0)
return true;
} catch (Throwable ex) {
LOG.warning("Failed to decompress log file " + file, ex);
return false;
}
output.write(buffer, 0, read);
}
} finally {
try {
input.close();
} catch (Throwable ex) {
LOG.warning("Failed to close log file " + file, ex);
}
output.closeEntry();
}
}
@Override
protected void onExportLogs() {
thread(() -> {
@@ -143,17 +185,53 @@ public final class SettingsPage extends SettingsView {
outputFile = Metadata.CURRENT_DIRECTORY.resolve(nameBase + ".zip");
LOG.info("Exporting latest logs to " + outputFile);
byte[] buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE];
try (var os = Files.newOutputStream(outputFile);
var zos = new ZipOutputStream(os)) {
for (Path path : recentLogFiles) {
String zipEntryName = path.getFileName().toString();
zos.putNextEntry(new ZipEntry(zipEntryName));
Files.copy(path, zos);
zos.closeEntry();
String fileName = FileUtils.getName(path);
String extension = StringUtils.substringAfterLast(fileName, '.');
if ("gz".equals(extension) || "xz".equals(extension)) {
// If an exception occurs while decompressing the input file, we should
// ensure the input file and the current zip entry are closed,
// then copy the compressed file content as-is into a new entry in the zip file.
InputStream input = null;
try {
input = Files.newInputStream(path);
input = "gz".equals(extension)
? new GZIPInputStream(input)
: new XZInputStream(input);
} catch (Throwable ex) {
LOG.warning("Failed to open log file " + path, ex);
IOUtils.closeQuietly(input, ex);
input = null;
}
String entryName = StringUtils.substringBeforeLast(fileName, ".");
if (input != null && exportLogFile(zos, path, entryName, input, buffer))
continue;
}
// Copy the log file content as-is into a new entry in the zip file.
// If an exception occurs while decompressing the input file, we should
// ensure the input file and the current zip entry are closed.
InputStream input;
try {
input = Files.newInputStream(path);
} catch (Throwable ex) {
LOG.warning("Failed to open log file " + path, ex);
continue;
}
exportLogFile(zos, path, fileName, input, buffer);
}
zos.putNextEntry(new ZipEntry("latest.log"));
zos.putNextEntry(new ZipEntry("hmcl-latest.log"));
LOG.exportLogs(zos);
zos.closeEntry();
}
@@ -37,6 +37,7 @@ import org.jackhuang.hmcl.ui.SVG;
import org.jackhuang.hmcl.ui.construct.ComponentList;
import org.jackhuang.hmcl.ui.construct.ComponentSublist;
import org.jackhuang.hmcl.ui.construct.MultiFileItem;
import org.jackhuang.hmcl.ui.construct.OptionToggleButton;
import org.jackhuang.hmcl.util.i18n.I18n;
import org.jackhuang.hmcl.util.i18n.Locales.SupportedLocale;
@@ -49,6 +50,7 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG;
public abstract class SettingsView extends StackPane {
protected final JFXComboBox<SupportedLocale> cboLanguage;
protected final OptionToggleButton disableAutoGameOptionsPane;
protected final MultiFileItem<EnumCommonDirectory> fileCommonLocation;
protected final ComponentSublist fileCommonLocationSublist;
protected final Label lblUpdate;
@@ -177,14 +179,30 @@ public abstract class SettingsView extends StackPane {
BorderPane.setAlignment(left, Pos.CENTER_LEFT);
languagePane.setLeft(left);
SupportedLocale currentLocale = I18n.getLocale();
cboLanguage = new JFXComboBox<>();
cboLanguage.setConverter(stringConverter(I18n::getName));
cboLanguage.setConverter(stringConverter(locale -> {
if (locale.isDefault())
return locale.getDisplayName(currentLocale);
else if (locale.isSameLanguage(currentLocale))
return locale.getDisplayName(locale);
else
return locale.getDisplayName(currentLocale) + " - " + locale.getDisplayName(locale);
}));
FXUtils.setLimitWidth(cboLanguage, 300);
languagePane.setRight(cboLanguage);
settingsPane.getContent().add(languagePane);
}
{
disableAutoGameOptionsPane = new OptionToggleButton();
disableAutoGameOptionsPane.setTitle(i18n("settings.launcher.disable_auto_game_options"));
settingsPane.getContent().add(disableAutoGameOptionsPane);
}
{
BorderPane debugPane = new BorderPane();
@@ -407,6 +407,9 @@ public class DownloadPage extends Control implements DecoratorPage {
case FORGE:
content.getTags().add(i18n("install.installer.forge"));
break;
case CLEANROOM:
content.getTags().add(i18n("install.installer.cleanroom"));
break;
case NEO_FORGED:
content.getTags().add(i18n("install.installer.neoforge"));
break;
@@ -76,7 +76,7 @@ public class InstallerListPage extends ListPageBase<InstallerItem> implements Ve
InstallerItem.InstallerItemGroup group = new InstallerItem.InstallerItemGroup(gameVersion, InstallerItem.Style.LIST_ITEM);
// Conventional libraries: game, fabric, forge, neoforge, liteloader, optifine
// Conventional libraries: game, fabric, forge, cleanroom, neoforge, liteloader, optifine
for (InstallerItem item : group.getLibraries()) {
String libraryId = item.getLibraryId();
@@ -424,6 +424,9 @@ class ModListPageSkin extends SkinBase<ModListPage> {
case FORGE:
loaderName = i18n("install.installer.forge");
break;
case CLEANROOM:
loaderName = i18n("install.installer.cleanroom");
break;
case NEO_FORGED:
loaderName = i18n("install.installer.neoforge");
break;
@@ -550,6 +553,9 @@ class ModListPageSkin extends SkinBase<ModListPage> {
case FORGE:
content.getTags().add(i18n("install.installer.forge"));
break;
case CLEANROOM:
content.getTags().add(i18n("install.installer.cleanroom"));
break;
case NEO_FORGED:
content.getTags().add(i18n("install.installer.neoforge"));
break;
@@ -65,6 +65,7 @@ public class VersionIconDialog extends DialogPane {
createIcon(VersionIconType.CRAFT_TABLE),
createIcon(VersionIconType.FABRIC),
createIcon(VersionIconType.FORGE),
createIcon(VersionIconType.CLEANROOM),
createIcon(VersionIconType.NEO_FORGE),
createIcon(VersionIconType.FURNACE),
createIcon(VersionIconType.QUILT)
@@ -361,14 +361,27 @@ public final class WorldInfoPage extends SpinnerPane {
playerGameTypePane.setRight(gameTypeBox);
Tag tag = player.get("playerGameType");
Tag hardcoreTag = dataTag.get("hardcore");
boolean isHardcore = hardcoreTag instanceof ByteTag && ((ByteTag) hardcoreTag).getValue() == 1;
if (tag instanceof IntTag) {
IntTag intTag = (IntTag) tag;
GameType gameType = GameType.of(intTag.getValue());
GameType gameType = GameType.of(intTag.getValue(), isHardcore);
if (gameType != null) {
gameTypeBox.setValue(gameType);
gameTypeBox.valueProperty().addListener((o, oldValue, newValue) -> {
if (newValue != null) {
intTag.setValue(newValue.ordinal());
if (newValue == GameType.HARDCORE) {
intTag.setValue(0); // survival (hardcore worlds are survival+hardcore flag)
if (hardcoreTag instanceof ByteTag) {
((ByteTag) hardcoreTag).setValue((byte) 1);
}
} else {
intTag.setValue(newValue.ordinal());
if (hardcoreTag instanceof ByteTag) {
((ByteTag) hardcoreTag).setValue((byte) 0);
}
}
saveLevelDat();
}
});
@@ -606,12 +619,13 @@ public final class WorldInfoPage extends SpinnerPane {
}
private enum GameType {
SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR;
SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR, HARDCORE;
static final ObservableList<GameType> items = FXCollections.observableList(Arrays.asList(values()));
static GameType of(int d) {
return d >= 0 && d <= items.size() ? items.get(d) : null;
static GameType of(int d, boolean hardcore) {
if (hardcore && d == 0) return HARDCORE; // hardcore + survival
return d >= 0 && d < 4 ? items.get(d) : null;
}
@Override
@@ -17,70 +17,100 @@
*/
package org.jackhuang.hmcl.util.i18n;
import org.jackhuang.hmcl.download.RemoteVersion;
import org.jackhuang.hmcl.download.game.GameRemoteVersion;
import org.jackhuang.hmcl.util.i18n.Locales.SupportedLocale;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import org.jetbrains.annotations.Nullable;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
public final class I18n {
private I18n() {
}
private static volatile SupportedLocale locale = Locales.DEFAULT;
private static volatile ResourceBundle resourceBundle = locale.getResourceBundle();
private static volatile DateTimeFormatter dateTimeFormatter;
public static void setLocale(SupportedLocale locale) {
I18n.locale = locale;
resourceBundle = locale.getResourceBundle();
dateTimeFormatter = null;
}
public static SupportedLocale getLocale() {
return locale;
}
public static boolean isUseChinese() {
return locale.getLocale() == Locale.CHINA;
return LocaleUtils.isChinese(locale.getLocale());
}
public static ResourceBundle getResourceBundle() {
return resourceBundle;
}
public static String getName(SupportedLocale locale) {
return locale == Locales.DEFAULT ? resourceBundle.getString("lang.default") : locale.getResourceBundle().getString("lang");
return locale.getResourceBundle();
}
public static String i18n(String key, Object... formatArgs) {
try {
return String.format(getResourceBundle().getString(key), formatArgs);
} catch (MissingResourceException e) {
LOG.error("Cannot find key " + key + " in resource bundle", e);
} catch (IllegalFormatException e) {
LOG.error("Illegal format string, key=" + key + ", args=" + Arrays.toString(formatArgs), e);
}
return key + Arrays.toString(formatArgs);
return locale.i18n(key, formatArgs);
}
public static String i18n(String key) {
try {
return getResourceBundle().getString(key);
} catch (MissingResourceException e) {
LOG.error("Cannot find key " + key + " in resource bundle", e);
return key;
}
return locale.i18n(key);
}
public static String formatDateTime(TemporalAccessor time) {
DateTimeFormatter formatter = dateTimeFormatter;
if (formatter == null) {
formatter = dateTimeFormatter = DateTimeFormatter.ofPattern(getResourceBundle().getString("datetime.format")).withZone(ZoneId.systemDefault());
}
return locale.formatDateTime(time);
}
return formatter.format(time);
public static String getDisplaySelfVersion(RemoteVersion version) {
if (locale.getLocale().getLanguage().equals("lzh")) {
if (version instanceof GameRemoteVersion)
return WenyanUtils.translateGameVersion(GameVersionNumber.asGameVersion(version.getSelfVersion()));
else
return WenyanUtils.translateGenericVersion(version.getSelfVersion());
}
return version.getSelfVersion();
}
/// Find the builtin localized resource with given name and suffix.
///
/// For example, if the current locale is `zh-CN`, when calling `getBuiltinResource("assets.lang.foo", "json")`,
/// this method will look for the following built-in resources in order:
///
/// - `assets/lang/foo_zh_Hans_CN.json`
/// - `assets/lang/foo_zh_Hans.json`
/// - `assets/lang/foo_zh_CN.json`
/// - `assets/lang/foo_zh.json`
/// - `assets/lang/foo.json`
///
/// This method will return the first found resource;
/// if none of the above resources exist, it returns `null`.
public static @Nullable URL getBuiltinResource(String name, String suffix) {
var control = DefaultResourceBundleControl.INSTANCE;
var classLoader = I18n.class.getClassLoader();
for (Locale locale : locale.getCandidateLocales()) {
String resourceName = control.toResourceName(control.toBundleName(name, locale), suffix);
URL input = classLoader.getResource(resourceName);
if (input != null)
return input;
}
return null;
}
/// @see [#getBuiltinResource(String, String) ]
public static @Nullable InputStream getBuiltinResourceAsStream(String name, String suffix) {
URL resource = getBuiltinResource(name, suffix);
try {
return resource != null ? resource.openStream() : null;
} catch (IOException e) {
return null;
}
}
public static String getWikiLink(GameRemoteVersion remoteVersion) {
return MinecraftWiki.getWikiLink(locale, remoteVersion);
}
public static boolean hasKey(String key) {
@@ -20,115 +20,231 @@ package org.jackhuang.hmcl.util.i18n;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.jackhuang.hmcl.util.Lang;
import org.jackhuang.hmcl.util.StringUtils;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
public final class Locales {
private Locales() {
}
public static final SupportedLocale DEFAULT = new SupportedLocale(Locale.getDefault());
private static Locale getDefaultLocale() {
String language = System.getenv("HMCL_LANGUAGE");
if (StringUtils.isNotBlank(language))
return Locale.forLanguageTag(language);
else
return LocaleUtils.SYSTEM_DEFAULT;
}
public static final SupportedLocale DEFAULT = new SupportedLocale("def", getDefaultLocale()) {
@Override
public boolean isDefault() {
return true;
}
};
/**
* English
*/
public static final SupportedLocale EN = new SupportedLocale(Locale.ROOT);
public static final SupportedLocale EN = new SupportedLocale("en", Locale.ENGLISH);
/**
* Spanish
*/
public static final SupportedLocale ES = new SupportedLocale(Locale.forLanguageTag("es"));
public static final SupportedLocale ES = new SupportedLocale("es", Locale.forLanguageTag("es"));
/**
* Russian
*/
public static final SupportedLocale RU = new SupportedLocale(Locale.forLanguageTag("ru"));
public static final SupportedLocale RU = new SupportedLocale("ru", Locale.forLanguageTag("ru"));
/**
* Ukrainian
*/
public static final SupportedLocale UK = new SupportedLocale("uk", Locale.forLanguageTag("uk"));
/**
* Japanese
*/
public static final SupportedLocale JA = new SupportedLocale(Locale.JAPANESE);
public static final SupportedLocale JA = new SupportedLocale("ja", Locale.JAPANESE);
/**
* Traditional Chinese
* Chinese (Simplified)
*/
public static final SupportedLocale ZH = new SupportedLocale(Locale.TRADITIONAL_CHINESE);
public static final SupportedLocale ZH_HANS = new SupportedLocale("zh_CN", LocaleUtils.LOCALE_ZH_HANS);
/**
* Simplified Chinese
* Chinese (Traditional)
*/
public static final SupportedLocale ZH_CN = new SupportedLocale(Locale.SIMPLIFIED_CHINESE);
public static final SupportedLocale ZH_HANT = new SupportedLocale("zh", LocaleUtils.LOCALE_ZH_HANT);
public static final List<SupportedLocale> LOCALES = Lang.immutableListOf(DEFAULT, EN, ES, JA, RU, ZH_CN, ZH);
/**
* Wenyan (Classical Chinese)
*/
public static final SupportedLocale WENYAN = new SupportedLocale("lzh", Locale.forLanguageTag("lzh"));
public static final List<SupportedLocale> LOCALES = List.of(DEFAULT, EN, ES, JA, RU, UK, ZH_HANS, ZH_HANT, WENYAN);
public static SupportedLocale getLocaleByName(String name) {
if (name == null) return DEFAULT;
switch (name.toLowerCase(Locale.ROOT)) {
case "en":
return EN;
case "es":
return ES;
case "ja":
return JA;
case "ru":
return RU;
case "zh":
return ZH;
case "zh_cn":
return ZH_CN;
default:
return DEFAULT;
}
}
public static String getNameByLocale(SupportedLocale locale) {
if (locale == EN) return "en";
else if (locale == ES) return "es";
else if (locale == RU) return "ru";
else if (locale == JA) return "ja";
else if (locale == ZH) return "zh";
else if (locale == ZH_CN) return "zh_CN";
else if (locale == DEFAULT) return "def";
else throw new IllegalArgumentException("Unknown locale: " + locale);
for (SupportedLocale locale : LOCALES) {
if (locale.getName().equalsIgnoreCase(name))
return locale;
}
return DEFAULT;
}
@JsonAdapter(SupportedLocale.TypeAdapter.class)
public static final class SupportedLocale {
public static class SupportedLocale {
private final String name;
private final Locale locale;
private ResourceBundle resourceBundle;
private DateTimeFormatter dateTimeFormatter;
private List<Locale> candidateLocales;
SupportedLocale(Locale locale) {
SupportedLocale(String name, Locale locale) {
this.name = name;
this.locale = locale;
}
public boolean isDefault() {
return false;
}
public String getName() {
return name;
}
public Locale getLocale() {
return locale;
}
public ResourceBundle getResourceBundle() {
ResourceBundle bundle = resourceBundle;
public String getDisplayName(SupportedLocale inLocale) {
if (inLocale.locale.getLanguage().equals("lzh"))
inLocale = ZH_HANT;
if (resourceBundle == null) {
if (this != DEFAULT && this.locale == DEFAULT.locale) {
bundle = DEFAULT.getResourceBundle();
} else {
bundle = ResourceBundle.getBundle("assets.lang.I18N", locale);
if (isDefault()) {
try {
return inLocale.getResourceBundle().getString("lang.default");
} catch (Throwable e) {
LOG.warning("Failed to get localized name for default locale", e);
return "Default";
}
resourceBundle = bundle;
}
if (this.locale.getLanguage().equals("lzh")) {
if (LocaleUtils.isChinese(inLocale.locale))
return "文言";
String name = locale.getDisplayName(inLocale.getLocale());
return name.equals("lzh") || name.equals("Literary Chinese")
? "Chinese (Classical)"
: name;
}
return locale.getDisplayName(inLocale.getLocale());
}
public ResourceBundle getResourceBundle() {
ResourceBundle bundle = resourceBundle;
if (resourceBundle == null)
resourceBundle = bundle = ResourceBundle.getBundle("assets.lang.I18N", locale,
DefaultResourceBundleControl.INSTANCE);
return bundle;
}
public List<Locale> getCandidateLocales() {
if (candidateLocales == null)
candidateLocales = List.copyOf(LocaleUtils.getCandidateLocales(locale));
return candidateLocales;
}
public String i18n(String key, Object... formatArgs) {
try {
return String.format(getResourceBundle().getString(key), formatArgs);
} catch (MissingResourceException e) {
LOG.error("Cannot find key " + key + " in resource bundle", e);
} catch (IllegalFormatException e) {
LOG.error("Illegal format string, key=" + key + ", args=" + Arrays.toString(formatArgs), e);
}
return key + Arrays.toString(formatArgs);
}
public String i18n(String key) {
try {
return getResourceBundle().getString(key);
} catch (MissingResourceException e) {
LOG.error("Cannot find key " + key + " in resource bundle", e);
return key;
}
}
public String formatDateTime(TemporalAccessor time) {
DateTimeFormatter formatter = dateTimeFormatter;
if (formatter == null) {
if (locale.getLanguage().equals("lzh"))
return WenyanUtils.formatDateTime(time);
formatter = dateTimeFormatter = DateTimeFormatter.ofPattern(getResourceBundle().getString("datetime.format"))
.withZone(ZoneId.systemDefault());
}
return formatter.format(time);
}
public String getFcMatchPattern() {
String language = locale.getLanguage();
String region = locale.getCountry();
if (LocaleUtils.isEnglish(locale))
return "";
if (LocaleUtils.isChinese(locale)) {
String lang;
String charset;
String script = LocaleUtils.getScript(locale);
switch (script) {
case "Hans":
lang = region.equals("SG") || region.equals("MY")
? "zh-" + region
: "zh-CN";
charset = "0x6e38,0x620f";
break;
case "Hant":
lang = region.equals("HK") || region.equals("MO")
? "zh-" + region
: "zh-TW";
charset = "0x904a,0x6232";
break;
default:
return "";
}
return ":lang=" + lang + ":charset=" + charset;
}
return region.isEmpty() ? language : language + "-" + region;
}
public boolean isSameLanguage(SupportedLocale other) {
return (this.getLocale().getLanguage().equals(other.getLocale().getLanguage()))
|| (LocaleUtils.isChinese(this.getLocale()) && LocaleUtils.isChinese(other.getLocale()));
}
public static final class TypeAdapter extends com.google.gson.TypeAdapter<SupportedLocale> {
@Override
public void write(JsonWriter out, SupportedLocale value) throws IOException {
out.value(getNameByLocale(value));
out.value(value.getName());
}
@Override
@@ -137,4 +253,5 @@ public final class Locales {
}
}
}
}
@@ -0,0 +1,185 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import org.jackhuang.hmcl.download.game.GameRemoteVersion;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import java.util.Locale;
import java.util.regex.Pattern;
public final class MinecraftWiki {
private static final Pattern SNAPSHOT_PATTERN = Pattern.compile("^[0-9]{2}w[0-9]{2}.+$");
public static String getWikiLink(Locales.SupportedLocale locale, GameRemoteVersion version) {
String wikiVersion = version.getSelfVersion();
var gameVersion = GameVersionNumber.asGameVersion(wikiVersion);
if (locale.getLocale().getLanguage().equals("lzh")) {
String translatedVersion;
if (wikiVersion.startsWith("2.0"))
translatedVersion = "二點〇";
else if (wikiVersion.startsWith("1.0.0-rc2"))
translatedVersion = WenyanUtils.translateGameVersion(GameVersionNumber.asGameVersion("1.0.0-rc2"));
else
translatedVersion = WenyanUtils.translateGameVersion(gameVersion);
if (translatedVersion.equals(gameVersion.toString()) || gameVersion instanceof GameVersionNumber.Old) {
return getWikiLink(Locales.ZH_HANT, version);
} else if (SNAPSHOT_PATTERN.matcher(wikiVersion).matches()) {
return locale.i18n("wiki.version.game.snapshot", translatedVersion);
} else {
return locale.i18n("wiki.version.game", translatedVersion);
}
}
String variantSuffix;
if (LocaleUtils.isChinese(locale.getLocale())) {
if (!"Hant".equals(LocaleUtils.getScript(locale.getLocale()))) {
variantSuffix = "?variant=zh-cn";
} else {
String region = locale.getLocale().getCountry();
variantSuffix = region.equals("HK") || region.equals("MO")
? "?variant=zh-hk"
: "?variant=zh-tw";
}
} else
variantSuffix = "";
replace:
if (gameVersion instanceof GameVersionNumber.Release) {
if (wikiVersion.startsWith("1.0")) {
if (wikiVersion.equals("1.0"))
wikiVersion = "1.0.0";
else if (wikiVersion.startsWith("1.0.0-rc2"))
wikiVersion = "1.0.0-rc2";
}
} else if (gameVersion instanceof GameVersionNumber.Snapshot) {
return locale.i18n("wiki.version.game.snapshot", wikiVersion) + variantSuffix;
} else {
if (wikiVersion.length() >= 6 && wikiVersion.charAt(2) == 'w') {
// Starting from 2020, all April Fools' versions follow this pattern
if (SNAPSHOT_PATTERN.matcher(wikiVersion).matches()) {
if (wikiVersion.equals("22w13oneblockatatime"))
wikiVersion = "22w13oneBlockAtATime";
return locale.i18n("wiki.version.game.snapshot", wikiVersion) + variantSuffix;
}
}
String lower = wikiVersion.toLowerCase(Locale.ROOT);
switch (lower) {
case "0.30-1":
case "0.30-2":
case "c0.30_01c":
wikiVersion = "Classic_0.30";
break replace;
case "in-20100206-2103":
wikiVersion = "Indev_20100206";
break replace;
case "inf-20100630-1":
wikiVersion = "Infdev_20100630";
break replace;
case "inf-20100630-2":
wikiVersion = "Alpha_v1.0.0";
break replace;
case "1.19_deep_dark_experimental_snapshot-1":
wikiVersion = "1.19-exp1";
break replace;
case "in-20100130":
wikiVersion = "Indev_0.31_20100130";
break replace;
case "b1.6-tb3":
wikiVersion = "Beta_1.6_Test_Build_3";
break replace;
case "1.14_combat-212796":
wikiVersion = "1.14.3_-_Combat_Test";
break replace;
case "1.14_combat-0":
wikiVersion = "Combat_Test_2";
break replace;
case "1.14_combat-3":
wikiVersion = "Combat_Test_3";
break replace;
case "1_15_combat-1":
wikiVersion = "Combat_Test_4";
break replace;
case "1_15_combat-6":
wikiVersion = "Combat_Test_5";
break replace;
case "1_16_combat-0":
wikiVersion = "Combat_Test_6";
break replace;
case "1_16_combat-1":
wikiVersion = "Combat_Test_7";
break replace;
case "1_16_combat-2":
wikiVersion = "Combat_Test_7b";
break replace;
case "1_16_combat-3":
wikiVersion = "Combat_Test_7c";
break replace;
case "1_16_combat-4":
wikiVersion = "Combat_Test_8";
break replace;
case "1_16_combat-5":
wikiVersion = "Combat_Test_8b";
break replace;
case "1_16_combat-6":
wikiVersion = "Combat_Test_8c";
break replace;
}
if (lower.startsWith("2.0"))
wikiVersion = "2.0";
else if (lower.startsWith("b1.8-pre1"))
wikiVersion = "Beta_1.8-pre1";
else if (lower.startsWith("b1.1-"))
wikiVersion = "Beta_1.1";
else if (lower.startsWith("a1.1.0"))
wikiVersion = "Alpha_v1.1.0";
else if (lower.startsWith("a1.0.14"))
wikiVersion = "Alpha_v1.0.14";
else if (lower.startsWith("a1.0.13_01"))
wikiVersion = "Alpha_v1.0.13_01";
else if (lower.startsWith("in-20100214"))
wikiVersion = "Indev_20100214";
else if (lower.contains("experimental-snapshot"))
wikiVersion = lower.replace("_experimental-snapshot-", "-exp");
else if (lower.startsWith("inf-"))
wikiVersion = lower.replace("inf-", "Infdev_");
else if (lower.startsWith("in-"))
wikiVersion = lower.replace("in-", "Indev_");
else if (lower.startsWith("rd-"))
wikiVersion = "pre-Classic_" + lower;
else if (lower.startsWith("b"))
wikiVersion = lower.replace("b", "Beta_");
else if (lower.startsWith("a"))
wikiVersion = lower.replace("a", "Alpha_v");
else if (lower.startsWith("c"))
wikiVersion = lower
.replace("c", "Classic_")
.replace("st", "SURVIVAL_TEST");
}
return locale.i18n("wiki.version.game", wikiVersion) + variantSuffix;
}
private MinecraftWiki() {
}
}
@@ -0,0 +1,212 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAccessor;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Glavo
*/
public final class WenyanUtils {
private static final String DOT = "點";
private static final String[] NUMBERS = {
"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九",
"十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九",
"廿", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九",
"卅", "卅一", "卅二", "卅三", "卅四", "卅五", "卅六", "卅七", "卅八", "卅九",
"卌", "卌一", "卌二", "卌三", "卌四", "卌五", "卌六", "卌七", "卌八", "卌九",
"五十", "五十一", "五十二", "五十三", "五十四", "五十五", "五十六", "五十七", "五十八", "五十九",
"六十", "六十一", "六十二", "六十三", "六十四", "六十五", "六十六", "六十七", "六十八", "六十九",
};
private static final char[] TIAN_GAN = {'甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'};
private static final char[] DI_ZHI = {'子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'};
private static String digitToString(char digit) {
return digit >= '0' && digit <= '9'
? NUMBERS[digit - '0']
: String.valueOf(digit);
}
private static String numberToString(int number) {
return number >= 0 && number < NUMBERS.length ? NUMBERS[number] : String.valueOf(number);
}
private static void appendDigitByDigit(StringBuilder builder, String number) {
for (int i = 0; i < number.length(); i++) {
builder.append(digitToString(number.charAt(i)));
}
}
private static int mod(int a, int b) {
int r = a % b;
return r >= 0 ? r : r + b;
}
static void appendYear(StringBuilder builder, int year) {
int yearOffset = year - 1984;
builder.append(TIAN_GAN[mod(yearOffset, TIAN_GAN.length)]);
builder.append(DI_ZHI[mod(yearOffset, DI_ZHI.length)]);
}
public static String formatDateTime(TemporalAccessor time) {
LocalDateTime localDateTime;
if (time instanceof Instant)
localDateTime = ((Instant) time).atZone(ZoneId.systemDefault()).toLocalDateTime();
else
localDateTime = LocalDateTime.from(time);
StringBuilder builder = new StringBuilder(16);
appendYear(builder, localDateTime.getYear());
builder.append('年');
builder.append(numberToString(localDateTime.getMonthValue()));
builder.append('月');
builder.append(numberToString(localDateTime.getDayOfMonth()));
builder.append('日');
builder.append(' ');
builder.append(numberToString(localDateTime.getHour()));
builder.append('时');
builder.append(numberToString(localDateTime.getMinute()));
builder.append('分');
builder.append(numberToString(localDateTime.getSecond()));
builder.append('秒');
return builder.toString();
}
public static String translateGameVersion(GameVersionNumber gameVersion) {
if (gameVersion instanceof GameVersionNumber.Release) {
var release = (GameVersionNumber.Release) gameVersion;
StringBuilder builder = new StringBuilder();
appendDigitByDigit(builder, String.valueOf(release.getMajor()));
builder.append(DOT);
appendDigitByDigit(builder, String.valueOf(release.getMinor()));
if (release.getPatch() != 0) {
builder.append(DOT);
appendDigitByDigit(builder, String.valueOf(release.getPatch()));
}
if (release.getEaType() == GameVersionNumber.Release.TYPE_GA) {
// do nothing
} else if (release.getEaType() == GameVersionNumber.Release.TYPE_PRE) {
builder.append("之預");
appendDigitByDigit(builder, release.getEaVersion().toString());
} else if (release.getEaType() == GameVersionNumber.Release.TYPE_RC) {
builder.append("之候");
appendDigitByDigit(builder, release.getEaVersion().toString());
} else {
// Unsupported
return gameVersion.toString();
}
return builder.toString();
} else if (gameVersion instanceof GameVersionNumber.Snapshot) {
var snapshot = (GameVersionNumber.Snapshot) gameVersion;
StringBuilder builder = new StringBuilder();
appendDigitByDigit(builder, String.valueOf(snapshot.getYear()));
builder.append('週');
appendDigitByDigit(builder, String.valueOf(snapshot.getWeek()));
char suffix = snapshot.getSuffix();
if (suffix >= 'a' && (suffix - 'a') < TIAN_GAN.length)
builder.append(TIAN_GAN[suffix - 'a']);
else
builder.append(suffix);
return builder.toString();
} else if (gameVersion instanceof GameVersionNumber.Special) {
String version = gameVersion.toString();
switch (version.toLowerCase(Locale.ROOT)) {
case "2.0":
return "二點〇";
case "2.0_blue":
return "二點〇藍";
case "2.0_red":
return "二點〇赤";
case "2.0_purple":
return "二點〇紫";
case "1.rv-pre1":
return "一點真視之預一";
case "3d shareware v1.34":
return "躍然享件一點三四";
case "20w14infinite":
case "20w14~":
case "20w14∞":
return "二〇週一四宇";
case "22w13oneblockatatime":
return "二二週一三典";
case "23w13a_or_b":
return "二三週一三暨";
case "24w14potato":
return "二四週一四芋";
case "25w14craftmine":
return "二五週一四礦";
default:
return version;
}
} else {
return gameVersion.toString();
}
}
private static final Pattern GENERIC_VERSION_PATTERN =
Pattern.compile("^[0-9]+(\\.[0-9]+)*");
public static String translateGenericVersion(String version) {
Matcher matcher = GENERIC_VERSION_PATTERN.matcher(version);
if (matcher.find()) {
String prefix = matcher.group();
StringBuilder builder = new StringBuilder(version.length());
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (ch >= '0' && ch <= '9')
builder.append(digitToString(ch));
else if (ch == '.')
builder.append(DOT);
else
builder.append(ch);
}
builder.append(version, prefix.length(), version.length());
return builder.toString();
}
return version;
}
private WenyanUtils() {
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

@@ -400,6 +400,16 @@ fatal.apply_update_failure=We are sorry, but Hello Minecraft! Launcher is unable
fatal.apply_update_need_win7=Hello Minecraft! Launcher cannot automatically update on Windows XP/Vista.\n\
\n\
You can update manually by downloading a newer launcher version from %s.
fatal.deprecated_java_version=HMCL will require Java 17 or later to run in the future, but will still support launching games with Java 6~16.\n\
\n\
It is recommended to install the latest version of Java to ensure that HMCL works properly.\n\
\n\
You can continue to keep the old version of Java. HMCL can recognize and manage multiple Java versions and will automatically select the appropriate Java for you based on the game version.
fatal.deprecated_java_version.update=HMCL will require Java 17 or later to run in the future. Please install the latest version of Java to ensure that HMCL can complete the upgrade.\n\
\n\
You can continue to keep the old version of Java.\
HMCL can recognize and manage multiple Java versions and will automatically select the appropriate Java for you based on the game version.
fatal.deprecated_java_version.download_link=Download Java %d
fatal.samba=If you opened Hello Minecraft! Launcher from a Samba network drive, some features might not be working. Please try updating your Java or moving the launcher to another directory.
fatal.illegal_char=Your user path contains an illegal character "=". You will not be able to use authlib-injector or change the skin of your offline account.
fatal.unsupported_platform=Minecraft is not fully supported on your platform yet, so you may experience missing features or even be unable to launch the game.\n\
@@ -437,7 +447,7 @@ folder.screenshots=Screenshots
folder.world=World Directory
game=Games
game.crash.feedback=<b>Please do not share screenshots of this window with others!</b> If you ask for help from others, please click <b>"Export Crash Logs"</b> and send the exported file to others for analysis.
game.crash.feedback=<b>Please do not share screenshots or photos of this interface with others!</b> If you ask for help from others, please click <b>"Export Crash Logs"</b> and send the exported file to others for analysis.
game.crash.info=Crash Info
game.crash.reason=Crash Cause
game.crash.reason.analyzing=Analyzing...
@@ -691,6 +701,7 @@ install.failed.optifine_forge_1.17=For Minecraft 1.17.1, Forge is only compatibl
install.failed.version_mismatch=This loader requires the game version %s, but the installed one is %s.
install.installer.change_version=%s Incompatible
install.installer.choose=Choose Your %s Version
install.installer.cleanroom=Cleanroom
install.installer.depend=Requires %s
install.installer.do_not_install=Do not install
install.installer.fabric=Fabric
@@ -756,13 +767,13 @@ java.installing=Installing Java
java.uninstall=Uninstall Java
java.uninstall.confirm=Are you sure you want to uninstall this Java? This action cannot be undone!
lang=English
lang.default=Use System Locales
launch.advice=%s Do you still want to continue to launch?
launch.advice.multi=The following problems were detected:\n\n%s\n\nThese problems may prevent you from launching the game or affect gaming experience.\nDo you still want to continue to launch?
launch.advice.java.auto=The current Java version is not compatible with the instance.\n\nClick "Yes" to automatically choose the most compatible Java version. Or, you can navigate to "Global/Instance-specific Settings → Java" to choose one yourself.
launch.advice.java.modded_java_7=Minecraft 1.7.2 and previous versions require Java 7 or earlier.
launch.advice.cleanroom=Cleanroom can only be run on Java 21 or later. Please use Java 21 or later versions.
launch.advice.corrected=We have resolved the Java problem. If you still want to use your choice of Java version, you can disable "Do not check JVM compatibility" in "Global/Instance-specific Settings → Advanced Settings".
launch.advice.uncorrected=If you still want to use your choice of Java version, you can disable "Do not check JVM compatibility" in "Global/Instance-specific Settings → Advanced Settings".
launch.advice.different_platform=The 64-bit Java version is recommended for your device, but you have installed a 32-bit one.
@@ -1140,6 +1151,7 @@ world.info.player.food_level=Hunger Level
world.info.player.game_type=Game Mode
world.info.player.game_type.adventure=Adventure
world.info.player.game_type.creative=Creative
world.info.player.game_type.hardcore=Hardcore
world.info.player.game_type.spectator=Spectator
world.info.player.game_type.survival=Survival
world.info.player.health=Health
@@ -1328,6 +1340,7 @@ settings.launcher=Launcher Settings
settings.launcher.appearance=Appearance
settings.launcher.common_path.tooltip=HMCL will put all game assets and dependencies here. If there are existing libraries in the game directory, then HMCL will prefer to use them first.
settings.launcher.debug=Debug
settings.launcher.disable_auto_game_options=Do not switch game language
settings.launcher.download=Download
settings.launcher.download.threads=Threads
settings.launcher.download.threads.auto=Automatically Determine
@@ -1472,8 +1485,8 @@ version.settings=Settings
version.update=Update Modpack
wiki.tooltip=Minecraft Wiki Page
wiki.version.game=https://minecraft.wiki/w/Special:Search?search=%s
wiki.version.game.search=Java_Edition_%s
wiki.version.game=https://minecraft.wiki/w/Java_Edition_%s
wiki.version.game.snapshot=https://minecraft.wiki/w/Java_Edition_%s
wizard.prev=< Prev
wizard.failed=Failed
@@ -402,6 +402,17 @@ fatal.apply_update_failure=Lo sentimos, pero Hello Minecraft! Launcher no puede
fatal.apply_update_need_win7=Hello Minecraft! Launcher no puede actualizarse automáticamente en Windows XP/Vista.\n\
\n\
Puedes actualizar manualmente descargando una versión más reciente del launcher desde %s.
fatal.deprecated_java_version=HMCL requerirá Java 17 o posterior para funcionar en el futuro, pero seguirá siendo compatible con el lanzamiento de juegos con Java 6~16.\n\
\n\
Se recomienda instalar la última versión de Java para garantizar el correcto funcionamiento de HMCL.\n\
\n\
Puedes conservar la versión antigua de Java. HMCL puede reconocer y gestionar varias versiones de Java y elegirá automáticamente la adecuada para usted en función de la versión del juego.
fatal.deprecated_java_version.update=HMCL requerirá Java 17 o posterior para funcionar en el futuro. Por favor, instalar la última versión de Java para asegurarse de que el lanzador puede completar la actualización.\n\
\n\
Puedes conservar la versión antigua de Java.\
HMCL puede reconocer y gestionar varias versiones de Java \
y elegirá automáticamente la adecuada para usted en función de la versión del juego.
fatal.deprecated_java_version.download_link=Descargar Java %d
fatal.samba=Si ha abierto Hello Minecraft! Launcher desde una unidad de red Samba, es posible que algunas funciones no funcionen. Intenta actualizar tu Java o mover el launcher a otro directorio.
fatal.illegal_char=Su ruta de usuario contiene un carácter ilegal «=», por lo que algunas características podrían no funcionar correctamente.\n\
Por ejemplo, no podrá utilizar authlib-injector o cambiar el skin de su cuenta offline.
@@ -440,7 +451,7 @@ folder.screenshots=Capturas de pantalla
folder.world=Directorio del mundo
game=Juegos
game.crash.feedback=<b>¡Por favor, no comparta capturas de pantalla de esta interfaz con otras personas!</b> Si pide ayuda a otras personas, haga clic en <b>Exportar registros de colgado</b> y envíe el archivo exportado a otras personas para que lo analicen.
game.crash.feedback=<b>¡Por favor, no comparta capturas de pantalla o fotos de esta interfaz con otras personas!</b> Si pide ayuda a otras personas, haga clic en <b>Exportar registros de colgado</b> y envíe el archivo exportado a otras personas para que lo analicen.
game.crash.info=Información de colgado
game.crash.reason=Motivo del colgado
game.crash.reason.analyzing=Analizando...
@@ -761,7 +772,6 @@ java.installing=Instalando Java
java.uninstall=Desinstalar Java
java.uninstall.confirm=¿Está seguro de que desea desinstalar este Java? ¡Esta acción no se puede deshacer!
lang=Español
lang.default=Usar idioma del sistema
launch.advice=%s ¿Todavía quieres continuar?
@@ -1472,8 +1482,8 @@ version.settings=Configuración
version.update=Actualizar Modpack
wiki.tooltip=Página de Minecraft Wiki
wiki.version.game=https://es.minecraft.wiki/w/Special:Search?search=%s
wiki.version.game.search=Java_Edition_%s
wiki.version.game=https://es.minecraft.wiki/w/Java_Edition_%s
wiki.version.game.snapshot=https://es.minecraft.wiki/w/Java_Edition_%s
wizard.prev=< Previo
wizard.failed=Falló
@@ -347,7 +347,7 @@ folder.saves=マップ
folder.screenshots=スクリーンショット
game=ゲーム
game.crash.feedback=<b>このインターフェースのスクリーンショットを他の人と共有しないでください。 </b> 他の人に助けを求める場合は、左下隅にあるゲーム クラッシュ情報をクリックしてエクスポートし、エクスポートされたファイルを分析のために他の人に送信してください。
game.crash.feedback=<b>このインターフェースのスクリーンショットや写真を他の人と共有しないでください。</b> 他の人に助けを求める場合は、左下隅にあるゲーム クラッシュ情報をクリックしてエクスポートし、エクスポートされたファイルを分析のために他の人に送信してください。
game.crash.info=ゲームステータス
game.crash.reason=クラッシュアナライザー
game.crash.reason.analyzing=分析中..
@@ -492,7 +492,6 @@ java.install.warning.invalid_character=名前に不正な文字が含まれて
java.uninstall=このJavaをアンインストールする
java.uninstall.confirm=本当にこのJavaをアンインストールしますか?この操作は元に戻せません!
lang=日本語
lang.default=システム言語を使用する
launch.advice.java.auto=現在選択されているJavaVMは、ゲームの要件を満たしていません。適切なJavaVMを選択することを許可しますか?または、ゲーム設定で適切なJavaVMを選択することもできます。
@@ -963,8 +962,8 @@ version.manage.rename.fail=バージョンの名前を変更できませんで
version.settings=設定
version.update=modpackを更新する
wiki.version.game=https://ja.minecraft.wiki/w/Special:Search?search=%s
wiki.version.game.search=Java_Edition_%s
wiki.version.game=https://ja.minecraft.wiki/w/Java_Edition_%s
wiki.version.game.snapshot=https://ja.minecraft.wiki/w/Java_Edition_%s
wizard.prev=< 前へ
wizard.failed=失敗
File diff suppressed because it is too large. Load diff
@@ -400,6 +400,17 @@ fatal.apply_update_failure=Мы сожалеем, лаунчер не смог
Вы можете обновить программу вручную, скачав более новую версию с %s.
fatal.apply_update_need_win7=Лаунчер не может автоматически обновляться на Windows XP/Vista.\n\
Вы можете обновить программу вручную, скачав более новую версию с %s.
fatal.deprecated_java_version=В будущем для работы HMCL потребуется Java 17 или более поздняя версия, однако запуск игр будет поддерживаться и на Java 6~16.\n\
\n\
Рекомендуется установить последнюю версию Java, чтобы обеспечить правильную работу HMCL.\n\
\n\
Вы можете продолжать использовать старую версию Java. HMCL может распознавать и управлять несколькими версиями Java и автоматически выбирать подходящую Java в зависимости от версии игры.
fatal.deprecated_java_version.update=В будущем для работы HMCL потребуется Java 17 или более поздняя версия. Пожалуйста, установить последнюю версию Java, чтобы убедиться, что приложение сможет завершить обновление.\n\
\n\
Вы можете продолжать использовать старую версию Java.\
HMCL может распознавать и управлять несколькими версиями Java \
и автоматически выбирать подходящую Java в зависимости от версии игры.
fatal.deprecated_java_version.download_link=Скачать Java %d
fatal.samba=Если вы пытаетесь открыть лаунчер в общей папке Samba, он может не работать, попробуйте обновить Java или запустить лаунчер из локальной папки.
fatal.illegal_char=Недопустимый символ «=» в пути к папке пользователя. Лаунчер может работать, но некоторые функции не будут работать.\n\
Вы не сможете использовать аккаунт authlib-injector или изменить скин для аккаунта в режиме офлайн.
@@ -438,7 +449,7 @@ folder.screenshots=Снимки экрана
folder.world=Папка мира
game=Игры
game.crash.feedback=<b>Пожалуйста, не делитесь скриншотами этого интерфейса с другими!</b> Если вы просите помощи у других, нажмите <b>«Экспорт журналов с ошибками»</b> и отправьте экспортированный файл другим для анализа.
game.crash.feedback=<b>Пожалуйста, не делитесь с другими скриншотами или фотографиями этого интерфейса.</b> Если вы просите помощи у других, нажмите <b>«Экспорт журналов с ошибками»</b> и отправьте экспортированный файл другим для анализа.
game.crash.info=Сведения об отказе
game.crash.reason=Анализатор сбоев
game.crash.reason.analyzing=Анализирование...
@@ -757,7 +768,6 @@ java.installing=Установка Java
java.uninstall=Удалить Java
java.uninstall.confirm=Вы уверены, что хотите удалить эту Java? Это действие нельзя отменить!
lang=Русский
lang.default=Использовать язык системы
launch.advice=%s Вы все еще хотите продолжить запуск?
@@ -1472,8 +1482,8 @@ version.settings=Настройки
version.update=Обновить модпак
wiki.tooltip=Страница Minecraft Wiki
wiki.version.game=https://ru.minecraft.wiki/w/Special:Search?search=%s
wiki.version.game.search=%s_(Java_Edition)
wiki.version.game=https://ru.minecraft.wiki/w/%s_(Java_Edition)
wiki.version.game.snapshot=https://ru.minecraft.wiki/w/%s_(Java_Edition)
wizard.prev=< Пред.
wizard.failed=Не удалось
File diff suppressed because it is too large. Load diff
@@ -382,6 +382,9 @@ fatal.mac_app_translocation=由於 macOS 的安全機制,Hello Minecraft! Laun
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即將升級完成,請重新開啟 HMCL。
fatal.apply_update_failure=我們很抱歉 Hello Minecraft! Launcher 無法自動完成升級程式,因為出現了一些問題。\n但你依然可以從 %s 處手動下載 HMCL 來完成升級。
fatal.apply_update_need_win7=Hello Minecraft! Launcher 無法在 Windows XP/Vista 上進行自動更新。請從 %s 處手動下載 HMCL 來完成升級。
fatal.deprecated_java_version=HMCL 未來需要 Java 17 或更高版本才能執行,但依然支援使用 Java 6~16 啟動遊戲。建議安裝最新版本的 Java 以確保 HMCL 正常執行。\n你可以繼續保留舊版本 Java。HMCL 能夠識別與管理多個 Java,並會自動根據遊戲版本為你選取合適的 Java。
fatal.deprecated_java_version.update=更高版本的 HMCL 需要 Java 17 或更高版本才能執行,請安裝最新版本的 Java 以確保 HMCL 能夠完成升級。\n你可以繼續保留舊版本 Java。HMCL 能夠識別與管理多個 Java,並會自動根據遊戲版本為你選取合適的 Java。
fatal.deprecated_java_version.download_link=下載 Java %d
fatal.samba=如果您正在透過 Samba 共亯的目錄中開啟 Hello Minecraft! Launcher,啟動器可能無法正常工作,請嘗試更新您的 Java 或在本機目錄內開啟 HMCL。
fatal.illegal_char=由於您的使用者目錄路徑中存在無效字元『=』,您將無法使用外部登入帳戶以及離線登入更換外觀功能。
fatal.unsupported_platform=Minecraft 尚未你您的平臺提供完善支援,所以可能影響遊戲體驗或無法啟動遊戲。\n若無法啟動 Minecraft 1.17 及更高版本,可以嘗試在「(全域/實例特定) 遊戲設定 → 進階設定 → 除錯選項」中將「繪製器」切換為「軟繪製器」,以獲得更好的相容性。
@@ -412,7 +415,7 @@ folder.screenshots=截圖目錄
folder.world=世界目錄
game=遊戲
game.crash.feedback=<b>請不要將本介面截圖給他人!</b>如果你要求助他人,請你點擊左下角「匯出遊戲崩潰資訊」後將匯出的檔案發送給他人以供分析。\n你可以點擊下方的「幫助」前往社群尋求幫助。
game.crash.feedback=<b>請不要將本介面截圖或拍照給他人!</b>如果你要求助他人,請你點擊左下角「匯出遊戲崩潰資訊」後將匯出的檔案發送給他人以供分析。\n你可以點擊下方的「幫助」前往社群尋求幫助。
game.crash.info=遊戲訊息
game.crash.reason=崩潰原因
game.crash.reason.analyzing=分析中……
@@ -507,6 +510,7 @@ install.failed.optifine_forge_1.17=對於 Minecraft 1.17.1 版本,僅 OptiFine
install.failed.version_mismatch=該載入器需要的遊戲版本為 %s,但實際的遊戲版本為 %s。
install.installer.change_version=%s 與目前遊戲不相容,請更換版本
install.installer.choose=選取 %s 版本
install.installer.cleanroom=Cleanroom
install.installer.depend=需要先安裝 %s
install.installer.do_not_install=不安裝
install.installer.fabric=Fabric
@@ -572,13 +576,13 @@ java.installing=安裝 Java
java.uninstall=移除此 Java
java.uninstall.confirm=你確定要移除此 Java 嗎?此操作無法復原!
lang=繁體中文
lang.default=使用系統語言
launch.advice=%s 是否繼續啟動?
launch.advice.multi=檢測到以下問題:\n\n%s\n\n這些問題可能導致遊戲無法正常啟動或影響遊戲體驗,是否繼續啟動?
launch.advice.java.auto=目前選取的 Java 版本不滿足遊戲要求,是否自動選取合適的 Java 版本?\n或者你可以到「(全域/實例特定) 遊戲設定 → 遊戲 Java」中選取一個合適的 Java 版本。
launch.advice.java.modded_java_7=Minecraft 1.7.2 及更低版本需要 Java 7 及更低版本。
launch.advice.cleanroom=Cleanroom 僅支援 Java 21 或更高版本。請使用 Java 21 或最新版本。
launch.advice.corrected=我們已經修正了 Java 版本問題。如果你確實希望使用你自訂的 Java,你可以在「(全域/實例特定) 遊戲設定 → 進階設定」中往下滑,開啟「不檢查 Java 虛擬機與遊戲的相容性」。
launch.advice.uncorrected=如果你確實希望使用你自訂的 Java,你可以在「(全域/實例特定) 遊戲設定 → 進階設定」中往下滑,開啟「不檢查 Java 虛擬機與遊戲的相容性」。
launch.advice.different_platform=你正在使用 32 位元 Java 啟動遊戲。建議更換至 64 位元 Java。
@@ -945,6 +949,7 @@ world.info.player.food_level=饑餓值
world.info.player.game_type=遊戲模式
world.info.player.game_type.adventure=冒險
world.info.player.game_type.creative=創造
world.info.player.game_type.hardcore=極限
world.info.player.game_type.spectator=旁觀者
world.info.player.game_type.survival=生存
world.info.player.health=生命值
@@ -1117,7 +1122,7 @@ settings.game.java_directory.template=%s (%s)
settings.game.management=管理
settings.game.working_directory=執行路徑 (建議使用模組時選取「各實例獨立」。修改後請自行移動相關遊戲檔案,如存檔、模組設定等)
settings.game.working_directory.choose=選取執行目錄
settings.game.working_directory.hint=在「執行路徑」選項中選取「各實例獨立」使目前實例獨立存放設定、存檔、模組等資料。使用模組時建議開啟此選項以避免不同版本模組衝突。修改此選項後需自行移動存檔等檔案。
settings.game.working_directory.hint=在「執行路徑」選項中選取「各實例獨立」使目前實例獨立存放設定、存檔、模組等資料。使用模組時建議開啟此選項以避免不同實例模組衝突。修改此選項後需自行移動存檔等檔案。
settings.icon=遊戲圖示
@@ -1125,6 +1130,7 @@ settings.launcher=啟動器設定
settings.launcher.appearance=外觀
settings.launcher.common_path.tooltip=啟動器將所有遊戲資源及相依元件庫檔案放於此集中管理。如果遊戲目錄內有現成的將不會使用公共庫檔案。
settings.launcher.debug=除錯
settings.launcher.disable_auto_game_options=不自動切換遊戲語言
settings.launcher.download=下載
settings.launcher.download.threads=執行緒數
settings.launcher.download.threads.auto=自動選取執行緒數
@@ -1265,8 +1271,8 @@ version.settings=遊戲設定
version.update=更新模組包
wiki.tooltip=Minecraft Wiki 頁面
wiki.version.game=https://zh.minecraft.wiki/w/Special:Search?search=%s&variant=zh-tw
wiki.version.game.search=Java版%s
wiki.version.game=https://zh.minecraft.wiki/w/Java版%s
wiki.version.game.snapshot=https://zh.minecraft.wiki/w/%s
wizard.prev=< 上一步
wizard.failed=失敗
@@ -183,7 +183,7 @@ archive.version=版本
assets.download=下载资源
assets.download_all=检查资源文件完整性
assets.index.malformed=资源文件的索引文件损坏。你可以在相应版本的“版本管理”页面中,点击左下角“管理 → 更新游戏资源文件”以修复该问题。\n你可以点击右上角帮助按钮进行求助。
assets.index.malformed=资源文件的索引文件损坏。你可以在相应实例的“实例管理”页面中,点击左下角“管理 → 更新游戏资源文件”以修复该问题。\n你可以点击右上角帮助按钮进行求助。
button.cancel=取消
button.change_source=切换下载源
@@ -391,9 +391,12 @@ fatal.mac_app_translocation=由于 macOS 的安全机制,Hello Minecraft! Laun
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即将完成升级,请重新打开 HMCL。\n如遇到问题,你可以访问 https://docs.hmcl.net/help.html 页面寻求帮助。
fatal.apply_update_failure=我们很抱歉 Hello Minecraft! Launcher 无法自动完成升级,因为出现了一些问题。\n但你依可以从 %s 手动下载 HMCL 来完成升级。\n你可以访问 https://docs.hmcl.net/help.html 页面寻求帮助。
fatal.apply_update_need_win7=Hello Minecraft! Launcher 无法在 Windows XP/Vista 上进行自动更新。请从 %s 手动下载 HMCL 来完成升级。
fatal.deprecated_java_version=HMCL 未来需要 Java 17 或更高版本才能运行,但依然支持使用 Java 6~16 启动游戏。建议安装最新版本的 Java 以确保 HMCL 能正常工作。\n你可以继续保留旧版本 Java。HMCL 能够识别与管理多个 Java,并会自动根据游戏版本为你选择合适的 Java。\n你可以访问 https://docs.hmcl.net/help.html 页面寻求帮助。
fatal.deprecated_java_version.update=更高版本的 HMCL 需要 Java 17 或更高版本才能运行,请安装最新版本的 Java 以确保 HMCL 能够完成升级。\n你可以继续保留旧版本 Java。HMCL 能够识别与管理多个 Java,并会自动根据游戏版本为你选择合适的 Java。
fatal.deprecated_java_version.download_link=下载 Java %d
fatal.samba=如果你正在通过 Samba 共享的文件夹中运行 Hello Minecraft! Launcher,启动器可能无法正常工作。请尝试更新你的 Java 或在本地文件夹内运行 HMCL。\n你可以访问 https://docs.hmcl.net/help.html 页面寻求帮助。
fatal.illegal_char=由于你的用户文件夹路径中存在非法字符“=”,你将无法使用外置登录账户以及离线登录更换皮肤功能。\n你可以访问 https://docs.hmcl.net/help.html 页面寻求帮助。
fatal.unsupported_platform=Minecraft 尚未对你的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n若无法启动 Minecraft 1.17 及更高版本,可以尝试在“(全局/版本特定) 游戏设置 → 高级设置 → 调试选项”中将“渲染器”切换为“软渲染器”,以获得更好的兼容性。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
fatal.unsupported_platform=Minecraft 尚未对你的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n若无法启动 Minecraft 1.17 及更高版本,可以尝试在“(全局/实例特定) 游戏设置 → 高级设置 → 调试选项”中将“渲染器”切换为“软渲染器”,以获得更好的兼容性。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
fatal.unsupported_platform.loongarch=Hello Minecraft! Launcher 已为龙芯提供支持。\n如果遇到问题,你可以点击右上角帮助按钮进行求助。
fatal.unsupported_platform.macos_arm64=Hello Minecraft! Launcher 已为 Apple Silicon 平台提供支持。使用 ARM 原生 Java 启动游戏以获得更流畅的游戏体验。\n如果你在游戏中遇到问题,使用 x86-64 架构的 Java 启动游戏可能有更好的兼容性。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
fatal.unsupported_platform.windows_arm64=Hello Minecraft! Launcher 已为 Windows on Arm 平台提供原生支持。如果你在游戏中遇到问题,请尝试使用 x86 架构的 Java 启动游戏。\n如果你正在使用 <b>高通</b> 平台,你可能需要安装 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 兼容包</a> 后才能进行游戏。点击链接前往 Microsoft Store 安装兼容包。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
@@ -410,7 +413,7 @@ feedback.qq_group.statement=欢迎加入 HMCL 用户群,加入后请遵守群
file=文件
folder.config=配置文件夹
folder.game=游戏文件夹
folder.game=实例运行文件夹
folder.logs=日志文件夹
folder.mod=模组文件夹
folder.resourcepacks=资源包文件夹
@@ -421,7 +424,7 @@ folder.screenshots=截图文件夹
folder.world=世界文件夹
game=游戏
game.crash.feedback=<b>请不要将本界面截图给他人!</b>如果你要向他人求助,请你点击左下角<b>“导出游戏崩溃信息”</b>后将导出的文件发送给他人以供分析。\n你可以点击下方的<b>“帮助”</b>前往交流群寻求帮助。
game.crash.feedback=<b>请不要将本界面截图或拍照给他人!</b>如果你要向他人求助,请你点击左下角<b>“导出游戏崩溃信息”</b>后将导出的文件发送给他人以供分析。\n你可以点击下方的<b>“帮助”</b>前往交流群寻求帮助。
game.crash.info=游戏信息
game.crash.reason=崩溃原因
game.crash.reason.analyzing=分析中……
@@ -446,12 +449,12 @@ game.crash.reason.graphics_driver=当前游戏由于显卡驱动问题而崩溃
game.crash.reason.macos_failed_to_find_service_port_for_display=当前游戏由于 Apple Silicon 平台下初始化 OpenGL 窗口失败,无法继续运行。\n对于该问题,HMCL 暂无直接性的解决方案。请你尝试任意打开一个浏览器并全屏,然后再回到 HMCL 启动游戏。在弹出游戏窗口前<b>迅速切回浏览器页面</b>,等待游戏窗口出现后再切回游戏窗口。
game.crash.reason.illegal_access_error=当前游戏由于某些模组的问题,无法继续运行。\n如果你认识“%1$s”,你可以更新或删除对应模组再试。
game.crash.reason.install_mixinbootstrap=当前游戏由于缺失 MixinBootstrap,无法继续运行。\n你可以尝试安装 <a href="https://www.curseforge.com/minecraft/mc-mods/mixinbootstrap">MixinBootstrap</a> 解决该问题。若安装后崩溃,可以尝试在该模组的文件名开头添加半角感叹号 (!) 解决。
game.crash.reason.need_jdk11=当前游戏由于 Java 版本不合适,无法继续运行。\n你需要下载安装 <a href="https://bell-sw.com/pages/downloads/#downloads">Java 11</a>,并在“(全局/版本特定) 游戏设置 → 游戏 Java”中将 Java 设置为 11.x 的版本。
game.crash.reason.jdk_9=当前游戏由于 Java 版本过高,无法继续运行。\n你需要下载安装 <a href="https://bell-sw.com/pages/downloads/#downloads">Java 8</a>,并在“(全局/版本特定) 游戏设置 → 游戏 Java”中将 Java 设置为 1.8.x 的版本。
game.crash.reason.jvm_32bit=当前游戏由于内存分配过大,超过了 32 位 Java 虚拟机内存限制,无法继续运行。\n如果你的电脑是 64 位系统,请下载安装并更换 64 位 Java。<a href="https://bell-sw.com/pages/downloads/#downloads">下载 Java</a>\n如果你的电脑是 32 位系统,你或许可以重新安装 64 位系统,或换一台新电脑。\n或者,你可以在“(全局/版本特定) 游戏设置 → 游戏内存”中关闭“自动分配内存”,并把内存分配值调整为 1024 MiB 或以下。
game.crash.reason.need_jdk11=当前游戏由于 Java 版本不合适,无法继续运行。\n你需要下载安装 <a href="https://bell-sw.com/pages/downloads/#downloads">Java 11</a>,并在“(全局/实例特定) 游戏设置 → 游戏 Java”中将 Java 设置为 11.x 的版本。
game.crash.reason.jdk_9=当前游戏由于 Java 版本过高,无法继续运行。\n你需要下载安装 <a href="https://bell-sw.com/pages/downloads/#downloads">Java 8</a>,并在“(全局/实例特定) 游戏设置 → 游戏 Java”中将 Java 设置为 1.8.x 的版本。
game.crash.reason.jvm_32bit=当前游戏由于内存分配过大,超过了 32 位 Java 虚拟机内存限制,无法继续运行。\n如果你的电脑是 64 位系统,请下载安装并更换 64 位 Java。<a href="https://bell-sw.com/pages/downloads/#downloads">下载 Java</a>\n如果你的电脑是 32 位系统,你或许可以重新安装 64 位系统,或换一台新电脑。\n或者,你可以在“(全局/实例特定) 游戏设置 → 游戏内存”中关闭“自动分配内存”,并把内存分配值调整为 1024 MiB 或以下。
game.crash.reason.loading_crashed_forge=当前游戏由于模组“%1$s (%2$s)”错误,无法继续运行。\n你可以尝试删除或更新该模组以解决问题。
game.crash.reason.loading_crashed_fabric=当前游戏由于模组“%1$s”错误,无法继续运行。\n你可以尝试删除或更新该模组以解决问题。
game.crash.reason.memory_exceeded=当前游戏由于内存分配过大,无法继续运行。\n该问题是由于系统页面文件太小导致的。\n你需要在“(全局/版本特定) 游戏设置”中关闭“自动分配内存”,并将内存分配值调低至游戏能正常启动为止。\n你还可以尝试将虚拟内存设置调整为“自动管理所有驱动器分页文件大小”,<a href="https://docs.hmcl.net/assets/img/hmcl/自动管理所有驱动器分页文件大小.webp">详情</a>。
game.crash.reason.memory_exceeded=当前游戏由于内存分配过大,无法继续运行。\n该问题是由于系统页面文件太小导致的。\n你需要在“(全局/实例特定) 游戏设置”中关闭“自动分配内存”,并将内存分配值调低至游戏能正常启动为止。\n你还可以尝试将虚拟内存设置调整为“自动管理所有驱动器分页文件大小”,<a href="https://docs.hmcl.net/assets/img/hmcl/自动管理所有驱动器分页文件大小.webp">详情</a>。
game.crash.reason.mac_jdk_8u261=当前游戏由于你所使用的 Forge/OptiFine 与 Java 冲突而崩溃。\n请尝试更新 Forge/OptiFine,或使用 Java 8u251 及更早版本启动。
game.crash.reason.mod=当前游戏由于“%1$s”的问题,无法继续运行。\n你可以更新或删除已经安装的“%1$s”再试。
game.crash.reason.mod_resolution=当前游戏由于模组依赖问题,无法继续运行。Fabric 提供了如下信息:\n%1$s
@@ -461,37 +464,37 @@ game.crash.reason.mod_resolution_missing=当前游戏由于缺少前置模组,
game.crash.reason.mod_resolution_missing_minecraft=当前游戏由于模组和 Minecraft 游戏版本不匹配,无法继续运行。\n“%1$s”需要 Minecraft %2$s 才能运行。\n如果你要继续使用你已经安装的模组,你可以选择安装对应的 Minecraft 版本。如果你要继续使用当前 Minecraft 版本,你需要安装对应版本的模组。
game.crash.reason.mod_resolution_mod_version=%1$s (版本号 %2$s)
game.crash.reason.mod_resolution_mod_version.any=%1$s (任意版本)
game.crash.reason.forge_repeat_installation=当前游戏由于 Forge 重复安装,无法继续运行。<a href="https://github.com/HMCL-dev/HMCL/issues/1880">此为已知问题</a>\n建议将日志上传并反馈至 GitHub,以便我们找到更多线索并修复此问题。\n目前你可以在“版本管理 → 自动安装”中卸载 Forge 并重新安装。
game.crash.reason.optifine_repeat_installation=当前游戏由于 OptiFine 重复安装,无法继续运行。\n请删除模组文件夹下的 OptiFine 或前往“版本管理 → 自动安装”卸载安装的 OptiFine。
game.crash.reason.forge_repeat_installation=当前游戏由于 Forge 重复安装,无法继续运行。<a href="https://github.com/HMCL-dev/HMCL/issues/1880">此为已知问题</a>\n建议将日志上传并反馈至 GitHub,以便我们找到更多线索并修复此问题。\n目前你可以在“实例管理 → 自动安装”中卸载 Forge 并重新安装。
game.crash.reason.optifine_repeat_installation=当前游戏由于 OptiFine 重复安装,无法继续运行。\n请删除模组文件夹下的 OptiFine 或前往“实例管理 → 自动安装”卸载安装的 OptiFine。
game.crash.reason.forgemod_resolution=当前游戏由于模组依赖问题,无法继续运行。Forge/NeoForge 提供了如下信息:\n%1$s
game.crash.reason.forge_found_duplicate_mods=当前游戏由于模组重复安装,无法继续运行。Forge/NeoForge 提供了如下信息:\n%1$s
game.crash.reason.modmixin_failure=当前游戏由于某些模组注入失败,无法继续运行。\n这一般代表着该模组存在问题,或与当前环境不兼容。\n你可以查看日志寻找出错模组。
game.crash.reason.night_config_fixes=当前游戏由于 Night Config 库的一些问题,无法继续运行。\n你可以尝试安装 <a href="https://www.curseforge.com/minecraft/mc-mods/night-config-fixes">Night Config Fixes</a> 模组,这或许能帮助你解决这个问题。\n更多详情,可访问该模组的 <a href="https://github.com/Fuzss/nightconfigfixes">GitHub 仓库</a>。
game.crash.reason.forge_error=Forge/NeoForge 可能已经提供了错误信息。\n你可以查看日志,并根据错误报告中的日志信息进行对应处理。\n如果没有看到报错信息,可以查看错误报告了解错误具体是如何发生的。\n%1$s
game.crash.reason.mod_resolution0=当前游戏由于一些模组出现问题,无法继续运行。\n你可以查看日志寻找出错模组。
game.crash.reason.java_version_is_too_high=当前游戏由于 Java 版本过高,无法继续运行。\n请在“(全局/版本特定) 游戏设置 → 游戏 Java”中改用较低版本的 Java,然后再启动游戏。\n如果没有,可以从 <a href="https://www.java.com/download/">java.com (Java 8)</a> 或 <a href="https://bell-sw.com/pages/downloads/#downloads">BellSoft Liberica Full JRE (Java 17)</a> 等平台下载、安装一个 (安装完后需重启启动器)。
game.crash.reason.java_version_is_too_high=当前游戏由于 Java 版本过高,无法继续运行。\n请在“(全局/实例特定) 游戏设置 → 游戏 Java”中改用较低版本的 Java,然后再启动游戏。\n如果没有,可以从 <a href="https://www.java.com/download/">java.com (Java 8)</a> 或 <a href="https://bell-sw.com/pages/downloads/#downloads">BellSoft Liberica Full JRE (Java 17)</a> 等平台下载、安装一个 (安装完后需重启启动器)。
game.crash.reason.mod_name=当前游戏由于模组文件名称问题,无法继续运行。\n模组文件名称应只使用半角的大小写字母 (Aa~Zz)、数字 (0~9)、横线 (-)、下划线 (_)和点 (.)。\n请到模组文件夹中将所有不合规的模组文件名修改为上述合规字符。
game.crash.reason.incomplete_forge_installation=当前游戏由于 Forge/NeoForge 安装不完整,无法继续运行。\n请在“版本管理 → 自动安装”中卸载 Forge 并重新安装。
game.crash.reason.optifine_is_not_compatible_with_forge=当前游戏由于 OptiFine 与当前版本的 Forge 不兼容,导致游戏崩溃。\n点击 <a href="https://zkitefly.github.io/optifine-forge-support-list">此处</a> 查看 OptiFine 所兼容的 Forge 版本,并严格按照对应版本重新安装游戏或在“版本管理 → 自动安装”中更换版本。\n经测试,Forge 版本过高或过低都可能导致崩溃。
game.crash.reason.incomplete_forge_installation=当前游戏由于 Forge/NeoForge 安装不完整,无法继续运行。\n请在“实例管理 → 自动安装”中卸载 Forge 并重新安装。
game.crash.reason.optifine_is_not_compatible_with_forge=当前游戏由于 OptiFine 与当前版本的 Forge 不兼容,导致游戏崩溃。\n点击 <a href="https://zkitefly.github.io/optifine-forge-support-list">此处</a> 查看 OptiFine 所兼容的 Forge 版本,并严格按照对应版本重新安装游戏或在“实例管理 → 自动安装”中更换版本。\n经测试,Forge 版本过高或过低都可能导致崩溃。
game.crash.reason.mod_files_are_decompressed=当前游戏由于模组文件被解压了,无法继续运行。\n请直接把整个模组文件放进模组文件夹中即可。\n解压模组文件会导致游戏出错。请删除模组文件夹中已被解压的模组,然后再启动游戏。
game.crash.reason.shaders_mod=当前游戏由于同时安装了 OptiFine 和 Shaders 模组,无法继续运行。\n由于 OptiFine 已集成 Shaders 模组的功能,所以只需删除 Shaders 模组即可。
game.crash.reason.rtss_forest_sodium=当前游戏由于 RivaTuner Statistics Server (RTSS) 与 Sodium 不兼容,导致游戏崩溃。\n点击 <a href="https://github.com/CaffeineMC/sodium-fabric/wiki/Known-Issues#rtss-incompatible">此处</a> 查看详情。
game.crash.reason.too_many_mods_lead_to_exceeding_the_id_limit=当前游戏由于你所安装的模组过多,超出了游戏的 ID 限制,无法继续运行。\n请尝试安装 <a href="https://www.curseforge.com/minecraft/mc-mods/jeid">JEID</a> 等修复模组,或删除部分大型模组。
game.crash.reason.optifine_causes_the_world_to_fail_to_load=当前游戏可能由于 OptiFine 而无法继续运行。\n该问题只在特定 OptiFine 版本中出现,你可以尝试在“版本管理 → 自动安装”中更换 OptiFine 的版本。
game.crash.reason.optifine_causes_the_world_to_fail_to_load=当前游戏可能由于 OptiFine 而无法继续运行。\n该问题只在特定 OptiFine 版本中出现,你可以尝试在“实例管理 → 自动安装”中更换 OptiFine 的版本。
game.crash.reason.modlauncher_8=当前游戏由于你所使用的 Forge 版本与当前使用的 Java 冲突而崩溃。请尝试更新 Forge 到 36.2.26 或更高版本或换用版本低于 1.8.0.320 的 Java。<a href="https://bell-sw.com/pages/downloads/?version=java-8&package=jre-full">Liberica JDK 8u312+7</a>
game.crash.reason.no_class_def_found_error=当前游戏由于代码不完整,无法继续运行。\n你的游戏可能缺失了某个模组,或者某些模组文件不完整,或者模组与游戏的版本不匹配。\n你可能需要重新安装游戏和模组,或寻求他人帮助。\n缺失:\n%1$s
game.crash.reason.no_such_method_error=当前游戏由于代码不完整,无法继续运行。\n你的游戏可能缺失了某个模组,或者某些模组文件不完整,或者模组与游戏的版本不匹配。\n你可能需要重新安装游戏和模组,或寻求他人帮助。
game.crash.reason.opengl_not_supported=当前游戏由于你的显卡驱动存在问题,无法继续运行。\n原因是 OpenGL 不受支持,你现在是否在远程桌面或者串流模式下?如果是,请直接使用原电脑启动游戏。\n或者尝试升级你的显卡驱动到最新版本后再尝试启动游戏。如果你的电脑同时存在独立显卡和集成显卡,你需要检查游戏是否使用集成显卡启动。如果是,请尝试使用独立显卡启动 HMCL 与游戏。如果仍有问题,你可能需要考虑换一个新显卡或新电脑。
game.crash.reason.openj9=当前游戏无法在 OpenJ9 虚拟机上运行。请你在“(全局/版本特定) 游戏设置 → 游戏 Java”中更换为使用 Hotspot 虚拟机的 Java,并重新启动游戏。如果没有下载安装,你可以在网上自行下载。
game.crash.reason.out_of_memory=当前游戏由于内存不足,无法继续运行。\n这可能是内存分配过小,或者模组数量过多导致的。\n你可以在“(全局/版本特定) 游戏设置 → 游戏内存”中调整内存分配值以允许游戏在更大内存下运行。\n如果仍然出现该错误,你可能需要换一台更好的电脑。
game.crash.reason.openj9=当前游戏无法在 OpenJ9 虚拟机上运行。请你在“(全局/实例特定) 游戏设置 → 游戏 Java”中更换为使用 Hotspot 虚拟机的 Java,并重新启动游戏。如果没有下载安装,你可以在网上自行下载。
game.crash.reason.out_of_memory=当前游戏由于内存不足,无法继续运行。\n这可能是内存分配过小,或者模组数量过多导致的。\n你可以在“(全局/实例特定) 游戏设置 → 游戏内存”中调整内存分配值以允许游戏在更大内存下运行。\n如果仍然出现该错误,你可能需要换一台更好的电脑。
game.crash.reason.resolution_too_high=当前游戏由于资源包/纹理包分辨率过高,无法继续运行。\n你可以更换一个分辨率更低的资源包/纹理包,或者更换一个显存更大的显卡。
game.crash.reason.stacktrace=原因未知。请点击日志按钮查看详细信息。\n下面是一些关键词,其中可能包含模组名称,你可以通过搜索的方式查找有关信息。\n%s
game.crash.reason.too_old_java=当前游戏由于 Java 版本过低,无法继续运行。\n你需要在“(全局/版本特定) 游戏设置 → 游戏 Java”中更换 Java %1$s 或更新版本的 Java,并重新启动游戏。如果没有下载安装,你可以点击 <a href="https://learn.microsoft.com/java/openjdk/download">此处</a> 下载 Microsoft JDK。
game.crash.reason.too_old_java=当前游戏由于 Java 版本过低,无法继续运行。\n你需要在“(全局/实例特定) 游戏设置 → 游戏 Java”中更换 Java %1$s 或更新版本的 Java,并重新启动游戏。如果没有下载安装,你可以点击 <a href="https://learn.microsoft.com/java/openjdk/download">此处</a> 下载 Microsoft JDK。
game.crash.reason.unknown=原因未知。请点击日志按钮查看详细信息。
game.crash.reason.unsatisfied_link_error=当前游戏由于缺少本地库,无法继续运行。\n这些本地库缺失:%1$s。\n如果你在“(全局/版本特定) 游戏设置 → 高级设置”中修改了本地库路径选项,请你修改回默认模式。\n如果你正在使用默认模式,请检查游戏文件夹路径是否只包含英文字母、数字和下划线。\n如果是,那么请检查是否为模组或 HMCL 导致了本地库缺失的问题。如果你确定是 HMCL 引起的,建议你向我们反馈。\n<b>对于 Windows 用户,你还可以尝试在“控制面板 → 时钟和区域 → 区域 → 管理 → 更改系统区域设置”中将“当前系统区域设置”修改为“中文(简体,中国大陆)”,并关闭“Beta 版:使用 Unicode UTF-8 提供全球语言支持”选项;</b>\n<b>或将游戏文件夹路径中的所有非英文字符的名称 (例如中文、空格等) 修改为英文字符。</b>\n如果你确实需要自定义本地库路径,你需要保证其中包含缺失的本地库!
game.crash.reason.unsatisfied_link_error=当前游戏由于缺少本地库,无法继续运行。\n这些本地库缺失:%1$s。\n如果你在“(全局/实例特定) 游戏设置 → 高级设置”中修改了本地库路径选项,请你修改回默认模式。\n如果你正在使用默认模式,请检查游戏文件夹路径是否只包含英文字母、数字和下划线。\n如果是,那么请检查是否为模组或 HMCL 导致了本地库缺失的问题。如果你确定是 HMCL 引起的,建议你向我们反馈。\n<b>对于 Windows 用户,你还可以尝试在“控制面板 → 时钟和区域 → 区域 → 管理 → 更改系统区域设置”中将“当前系统区域设置”修改为“中文(简体,中国大陆)”,并关闭“Beta 版:使用 Unicode UTF-8 提供全球语言支持”选项;</b>\n<b>或将游戏文件夹路径中的所有非英文字符的名称 (例如中文、空格等) 修改为英文字符。</b>\n如果你确实需要自定义本地库路径,你需要保证其中包含缺失的本地库!
game.crash.title=游戏意外退出
game.directory=游戏文件夹路径
game.version=游戏版本
game.version=游戏实例
help=帮助
help.doc=Hello Minecraft! Launcher 帮助文档
@@ -502,7 +505,7 @@ input.number=必须是数字
input.not_empty=必填项
input.url=必须是合法的链接
install=添加游戏
install=添加实例
install.change_version=更换版本
install.change_version.confirm=你确定要将 %s 从 %s 更换成 %s 吗?
install.change_version.process=更换版本
@@ -517,6 +520,7 @@ install.failed.optifine_forge_1.17=对于 Minecraft 1.17.1 版本,仅 OptiFine
install.failed.version_mismatch=该组件需要的游戏版本为 %s,但实际的游戏版本为 %s。
install.installer.change_version=%s 与当前游戏不兼容,请更换版本
install.installer.choose=选择 %s 版本
install.installer.cleanroom=Cleanroom
install.installer.depend=需要先安装 %s
install.installer.do_not_install=不安装
install.installer.fabric=Fabric
@@ -544,8 +548,8 @@ install.modpack=安装整合包
install.modpack.installation=安装整合包
install.name.invalid=名称中包含特殊字符(如 Emoji 表情或中文字符)。\n建议修改名称。名称建议仅包含英文字母、数字和下划线,以防启动游戏时出现问题。是否继续安装?
install.new_game=安装新游戏
install.new_game.already_exists=此版本已经存在,请换一个名字
install.new_game.current_game_version=当前游戏版本
install.new_game.already_exists=此实例已经存在,请换一个名字
install.new_game.current_game_version=当前游戏实例
install.new_game.installation=安装新游戏
install.new_game.malformed=名字不合法
install.select=请选择安装方式
@@ -582,15 +586,15 @@ java.installing=安装 Java
java.uninstall=卸载此 Java
java.uninstall.confirm=你确定要卸载此 Java 吗?此操作无法撤销!
lang=简体中文
lang.default=跟随系统语言
launch.advice=%s 是否继续启动?
launch.advice.multi=检测到以下问题:\n\n%s\n\n这些问题可能导致游戏无法正常启动或影响游戏体验,是否继续启动?\n你可以点击右上角帮助按钮进行求助。
launch.advice.java.auto=当前选择的 Java 版本不满足游戏要求。\n点击“是”即可由 HMCL 来自动选取合适的 Java 版本。\n或者你可以在“(全局/版本特定) 游戏设置 → 游戏 Java”中选择一个合适的 Java 版本。
launch.advice.java.auto=当前选择的 Java 版本不满足游戏要求。\n点击“是”即可由 HMCL 来自动选取合适的 Java 版本。\n或者你可以在“(全局/实例特定) 游戏设置 → 游戏 Java”中选择一个合适的 Java 版本。
launch.advice.java.modded_java_7=Minecraft 1.7.2 及更低版本需要 Java 7 及更低版本。
launch.advice.corrected=我们已经修复了 Java 版本问题。如果你确实希望使用你自定义的 Java,你可以在“(全局/版本特定) 游戏设置 → 高级设置”中往下滑,启用“不检查 Java 虚拟机与游戏的兼容性”。
launch.advice.uncorrected=如果你确实希望使用你自定义的 Java,你可以在“(全局/版本特定) 游戏设置 → 高级设置”中往下滑,启用“不检查 Java 虚拟机与游戏的兼容性”。
launch.advice.cleanroom=Cleanroom 只能在 Java 21 或更高版本上运行。请使用 Java 21 或最新版本。
launch.advice.corrected=我们已经修复了 Java 版本问题。如果你确实希望使用你自定义的 Java,你可以在“(全局/实例特定) 游戏设置 → 高级设置”中往下滑,启用“不检查 Java 虚拟机与游戏的兼容性”。
launch.advice.uncorrected=如果你确实希望使用你自定义的 Java,你可以在“(全局/实例特定) 游戏设置 → 高级设置”中往下滑,启用“不检查 Java 虚拟机与游戏的兼容性”。
launch.advice.different_platform=你正在使用 32 位 Java 启动游戏。建议更换至 64 位 Java。
launch.advice.forge2760_liteloader=Forge 14.23.5.2760 与 LiteLoader 不兼容。请更新 Forge 至 14.23.5.2773 或更高版本。
launch.advice.forge28_2_2_optifine=Forge 28.2.2 及更高版本与 OptiFine 不兼容。请降级 Forge 至 28.2.1 或更低版本。
@@ -608,7 +612,7 @@ launch.advice.vanilla_linux_java_8=对于 Linux x86-64 平台,Minecraft 1.12.2
launch.advice.vanilla_x86.translation=Minecraft 尚未为你的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n你可以在 <a href="https://learn.microsoft.com/java/openjdk/download">这里</a> 下载 <b>x86-64</b> 架构的 Java 以获得更完整的体验。
launch.advice.unknown=由于以下原因,无法继续启动游戏:
launch.failed=启动失败
launch.failed.cannot_create_jvm=无法创建 Java 虚拟机。可能是虚拟机参数有问题。你可以在“(全局/版本特定) 游戏设置 → 高级设置 → Java 虚拟机设置”中移除所有虚拟机参数后,尝试再次启动游戏。
launch.failed.cannot_create_jvm=无法创建 Java 虚拟机。可能是虚拟机参数有问题。你可以在“(全局/实例特定) 游戏设置 → 高级设置 → Java 虚拟机设置”中移除所有虚拟机参数后,尝试再次启动游戏。
launch.failed.creating_process=启动失败。在创建新进程时发生错误,可能是 Java 路径错误。
launch.failed.command_too_long=命令长度超过限制,无法创建批处理脚本。请导出为 PowerShell 脚本。
launch.failed.decompressing_natives=未能解压游戏本地库。
@@ -619,7 +623,7 @@ launch.failed.execution_policy.failed_to_set=设置执行策略失败
launch.failed.execution_policy.hint=当前执行策略阻止你执行 PowerShell 脚本。\n点击“确定”允许当前用户执行本地 PowerShell 脚本,或点击“取消”保持现状。
launch.failed.exited_abnormally=游戏非正常退出。请查看日志文件,或联系他人寻求帮助。
launch.failed.java_version_too_low=你所指定的 Java 版本过低。请重新设置 Java 版本。
launch.failed.no_accepted_java=找不到适合当前游戏使用的 Java。是否使用默认 Java 启动游戏?点击“是”使用默认 Java 继续启动游戏,\n或者在“(全局/版本特定) 游戏设置 → 游戏 Java”中选择一个合适的 Java 版本。\n你可以点击右上角帮助按钮进行求助。
launch.failed.no_accepted_java=找不到适合当前游戏使用的 Java。是否使用默认 Java 启动游戏?点击“是”使用默认 Java 继续启动游戏,\n或者在“(全局/实例特定) 游戏设置 → 游戏 Java”中选择一个合适的 Java 版本。\n你可以点击右上角帮助按钮进行求助。
launch.failed.sigkill=游戏被用户或系统强制终止。
launch.state.dependencies=处理游戏依赖
launch.state.done=启动完成
@@ -749,14 +753,14 @@ modpack.wizard.step.2=文件选择
modpack.wizard.step.2.title=选中你想添加到整合包中的文件或文件夹
modpack.wizard.step.3=整合包类型
modpack.wizard.step.3.title=选择整合包导出类型
modpack.wizard.step.initialization.exported_version=要导出的游戏版本
modpack.wizard.step.initialization.exported_version=要导出的游戏实例
modpack.wizard.step.initialization.force_update=强制升级整合包至最新版本 (需要自建服务器)
modpack.wizard.step.initialization.include_launcher=包含启动器
modpack.wizard.step.initialization.modrinth.info=在整合包创建过程中,启动器将匹配 CurseForge/Modrinth 远程资源替代本地文件(包括模组、资源包和光影包)以缩减整合包体积,并将扩展名为“.disabled”的文件标注为“安装时可选项”。
modpack.wizard.step.initialization.no_create_remote_files=不匹配远程文件
modpack.wizard.step.initialization.save=选择要导出到的游戏整合包位置
modpack.wizard.step.initialization.skip_curseforge_remote_files=不匹配 CurseForge 远程资源
modpack.wizard.step.initialization.warning=在制作整合包前,请你确认你选择的版本可以正常启动,\n并保证你的 Minecraft 是正式版而非快照,\n而且不应当将不允许非官方途径传播的模组、资源 (纹理) 包等纳入整合包。\n整合包会保存你目前的下载源设置。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
modpack.wizard.step.initialization.warning=在制作整合包前,请你确认你选择的实例可以正常启动,\n并保证你的 Minecraft 是正式版而非快照,\n而且不应当将不允许非官方途径传播的模组、资源 (纹理) 包等纳入整合包。\n整合包会保存你目前的下载源设置。\n如遇到问题,你可以点击右上角帮助按钮进行求助。
modpack.wizard.step.initialization.server=点击此处查看有关服务器自动更新整合包的制作教程
modrinth.category.adventure=冒险
@@ -891,7 +895,7 @@ mods.not_modded=你需要先在“自动安装”页面安装 Forge、NeoForge
mods.restore=回退
mods.url=官方页面
mods.update_modpack_mod.warning=更新整合包中的模组可能导致整合包损坏,使整合包无法正常启动。该操作不可逆,确定要更新吗?
mods.install=安装到当前版本
mods.install=安装到当前实例
mods.save_as=下载到本地文件夹
nbt.entries=%s 个条目
@@ -956,6 +960,7 @@ world.info.player.food_level=饥饿值
world.info.player.game_type=游戏模式
world.info.player.game_type.adventure=冒险
world.info.player.game_type.creative=创造
world.info.player.game_type.hardcore=极限
world.info.player.game_type.spectator=旁观者
world.info.player.game_type.survival=生存
world.info.player.health=生命值
@@ -1043,13 +1048,14 @@ settings.advanced.modify=编辑高级设置
settings.advanced.title=高级设置 - %s
settings.advanced.custom_commands=自定义命令
settings.advanced.custom_commands.hint=自定义命令被调用时将包含如下的环境变量:\n\
\ · $INST_NAME: 版本名称;\n\
\ · $INST_ID: 版本名称;\n\
\ · $INST_DIR: 当前版本运行路径;\n\
\ · $INST_NAME: 实例名称;\n\
\ · $INST_ID: 实例名称;\n\
\ · $INST_DIR: 当前实例运行路径;\n\
\ · $INST_MC_DIR: 当前游戏文件夹路径;\n\
\ · $INST_JAVA: 游戏运行使用的 Java 路径;\n\
\ · $INST_FORGE: 若安装了 Forge,将会存在本环境变量;\n\
\ · $INST_NEOFORGE: 若安装了 NeoForge,将会存在本环境变量;\n\
\ · $INST_CLEANROOM: 若安装了 Cleanroom,将会存在本环境变量;\n\
\ · $INST_LITELOADER: 若安装了 LiteLoader,将会存在本环境变量;\n\
\ · $INST_OPTIFINE: 若安装了 OptiFine,将会存在本环境变量;\n\
\ · $INST_FABRIC: 若安装了 Fabric,将会存在本环境变量;\n\
@@ -1059,7 +1065,7 @@ settings.advanced.dont_check_jvm_validity=不检查 Java 虚拟机与游戏的
settings.advanced.dont_patch_natives=不尝试自动替换本地库
settings.advanced.environment_variables=环境变量
settings.advanced.game_dir.default=默认 (".minecraft/")
settings.advanced.game_dir.independent=各版本独立 (存放在 ".minecraft/versions/<版本名>/",除 assets、libraries 外)
settings.advanced.game_dir.independent=各实例独立 (存放在 ".minecraft/versions/<实例名>/",除 assets、libraries 外)
settings.advanced.java_permanent_generation_space=内存永久保存区域
settings.advanced.java_permanent_generation_space.prompt=单位 MiB
settings.advanced.jvm=Java 虚拟机设置
@@ -1078,7 +1084,7 @@ settings.advanced.natives_directory=本地库路径 (LWJGL)
settings.advanced.natives_directory.choose=选择本地库路径
settings.advanced.natives_directory.custom=自定义 (由你提供游戏需要的本地库)
settings.advanced.natives_directory.default=默认 (由启动器提供游戏本地库)
settings.advanced.natives_directory.default.version_id=<版本名称>
settings.advanced.natives_directory.default.version_id=<实例名称>
settings.advanced.natives_directory.hint=本选项提供给 Apple Silicon 等未受游戏官方支持的平台来自定义游戏本地库。如果你不知道本选项的含义,请不要修改本选项,否则会导致游戏无法启动!\n\n如果你要修改本选项,你需要保证自定义文件夹下有游戏所需的本地库文件,如 lwjgl.dll (liblwjgl.so)、openal.dll (libopenal.so) 等文件。启动器不会帮你补全缺少的本地库文件!\n\n注意:指定的本地库文件路径建议只包含英文大小写字母、数字和下划线,否则可能会导致启动游戏失败。
settings.advanced.no_jvm_args=不添加默认的 Java 虚拟机参数
settings.advanced.precall_command=游戏启动前执行命令
@@ -1111,7 +1117,7 @@ settings.custom=自定义
settings.game=游戏设置
settings.game.copy_global=复制全局游戏设置
settings.game.copy_global.copy_all=复制全部
settings.game.copy_global.copy_all.confirm=你确定要覆盖当前版本特定游戏设置吗?此操作无法撤销!
settings.game.copy_global.copy_all.confirm=你确定要覆盖当前实例特定游戏设置吗?此操作无法撤销!
settings.game.current=游戏
settings.game.dimension=游戏窗口分辨率
settings.game.exploration=浏览
@@ -1125,9 +1131,9 @@ settings.game.java_directory.invalid=Java 路径不正确
settings.game.java_directory.version=指定 Java 版本
settings.game.java_directory.template=%s (%s)
settings.game.management=管理
settings.game.working_directory=版本隔离 (建议使用模组时选择“各版本独立”。改后需移动存档、模组等相关游戏文件)
settings.game.working_directory=版本隔离 (建议使用模组时选择“各实例独立”。改后需移动存档、模组等相关游戏文件)
settings.game.working_directory.choose=选择运行文件夹
settings.game.working_directory.hint=在“版本隔离”中选择“各版本独立”使当前版本独立存放设置、存档、模组等数据。使用模组时建议启用此选项以避免不同版本模组冲突。修改此选项后需自行移动存档等文件。
settings.game.working_directory.hint=在“版本隔离”中选择“各实例独立”使当前实例独立存放设置、存档、模组等数据。使用模组时建议启用此选项以避免不同实例模组冲突。修改此选项后需自行移动存档等文件。
settings.icon=游戏图标
@@ -1135,6 +1141,7 @@ settings.launcher=启动器设置
settings.launcher.appearance=外观
settings.launcher.common_path.tooltip=启动器将所有游戏资源及依赖库文件存放于此集中管理。如果游戏文件夹内有现成的将不会使用公共库文件。
settings.launcher.debug=调试
settings.launcher.disable_auto_game_options=不自动切换游戏语言
settings.launcher.download=下载
settings.launcher.download.threads=线程数
settings.launcher.download.threads.auto=自动选择线程数
@@ -1184,13 +1191,13 @@ settings.physical_memory=物理内存大小
settings.show_log=查看日志
settings.tabs.installers=自动安装
settings.take_effect_after_restart=重启后生效
settings.type=版本游戏设置类型
settings.type.global=全局游戏设置 (未启用“版本特定游戏设置”的版本共用此设置)
settings.type=实例游戏设置类型
settings.type.global=全局游戏设置 (未启用“实例特定游戏设置”的实例共用此设置)
settings.type.global.manage=全局游戏设置
settings.type.global.edit=编辑全局游戏设置
settings.type.special.enable=启用版本特定游戏设置 (不影响其他游戏版本)
settings.type.special.edit=编辑版本特定游戏设置
settings.type.special.edit.hint=当前游戏版本“%s”启用了“版本特定游戏设置”,因此本页面选项不对该版本生效。点击链接前往该版本的“游戏设置”页。
settings.type.special.enable=启用实例特定游戏设置 (不影响其他游戏实例)
settings.type.special.edit=编辑实例特定游戏设置
settings.type.special.edit.hint=当前游戏实例“%s”启用了“实例特定游戏设置”,因此本页面选项不对该实例生效。点击链接前往该实例的“游戏设置”页。
sponsor=赞助
sponsor.bmclapi=国内下载源由 BMCLAPI 提供高速下载服务。BMCLAPI 为公益服务,赞助 BMCLAPI 可以帮助作者更好地提供稳定高速的下载服务。[点击此处查阅详细信息]
@@ -1227,11 +1234,11 @@ update.no_browser=无法打开浏览器。网址已经复制到剪贴板,你
update.tooltip=更新
version=游戏
version.name=游戏版本名称
version.cannot_read=读取游戏版本失败,无法进行自动安装
version.empty=没有游戏版本
version.name=游戏实例名称
version.cannot_read=读取游戏实例失败,无法进行自动安装
version.empty=没有游戏实例
version.empty.add=进入下载页安装游戏
version.empty.launch=没有可启动的游戏。点击“确定”将进入“下载”页面。\n你也可以点击 HMCL 主界面左侧的“下载”按钮安装游戏,或在“版本列表”切换游戏文件夹。
version.empty.launch=没有可启动的游戏。点击“确定”将进入“下载”页面。\n你也可以点击 HMCL 主界面左侧的“下载”按钮安装游戏,或在“实例列表”切换游戏文件夹。
version.empty.hint=没有已安装的游戏。\n你可以切换其他游戏文件夹,或者点击此处进入游戏下载页面。
version.game.all=全部
version.game.april_fools=愚人节
@@ -1246,37 +1253,37 @@ version.launch.empty=开始游戏
version.launch.empty.installing=安装游戏
version.launch.empty.tooltip=安装并启动最新正式版游戏
version.launch.test=测试游戏
version.switch=切换版本
version.switch=切换实例
version.launch_script=生成启动脚本
version.launch_script.failed=生成启动脚本失败
version.launch_script.save=保存启动脚本
version.launch_script.success=启动脚本已生成完毕:%s
version.manage=版本列表
version.manage=实例列表
version.manage.clean=清理游戏文件夹
version.manage.clean.tooltip=清理“logs”和“crash-reports”文件夹
version.manage.duplicate=复制游戏版本
version.manage.duplicate=复制游戏实例
version.manage.duplicate.duplicate_save=复制存档
version.manage.duplicate.prompt=请输入新游戏名称
version.manage.duplicate.confirm=新的游戏版本将复制该版本文件夹 (".minecraft/versions/<版本名>") 下的文件,并带有独立的运行文件夹和设置。
version.manage.manage=版本管理
version.manage.manage.title=版本管理 - %1s
version.manage.duplicate.confirm=新的游戏实例将复制该实例文件夹 (".minecraft/versions/<实例名>") 下的文件,并带有独立的运行文件夹和设置。
version.manage.manage=实例管理
version.manage.manage.title=实例管理 - %1s
version.manage.redownload_assets_index=更新游戏资源文件
version.manage.remove=删除该版本
version.manage.remove.confirm.trash=真的要删除版本“%s”吗?你可以在系统的回收站中还原“%s”文件夹来找回该版本。
version.manage.remove.confirm.independent=由于该游戏启用了“(全局/版本特定) 游戏设置 → 版本隔离 → 各版本独立”选项,删除该版本将导致该游戏的存档等数据一同被删除!真的要删除版本“%s”吗?
version.manage.remove=删除该实例
version.manage.remove.confirm.trash=真的要删除实例“%s”吗?你可以在系统的回收站中还原“%s”文件夹来找回该实例。
version.manage.remove.confirm.independent=由于该游戏启用了“(全局/实例特定) 游戏设置 → 版本隔离 → 各实例独立”选项,删除该实例将导致该游戏的存档等数据一同被删除!真的要删除实例“%s”吗?
version.manage.remove_assets=删除所有游戏资源文件
version.manage.remove_libraries=删除所有库文件
version.manage.rename=重命名该版本
version.manage.rename=重命名该实例
version.manage.rename.message=请输入要修改的名称
version.manage.rename.fail=重命名版本失败,可能文件被占用或者名字有特殊字符。
version.manage.rename.fail=重命名实例失败,可能文件被占用或者名字有特殊字符。
version.search=名称
version.search.prompt=输入版本名称进行搜索
version.settings=游戏设置
version.update=更新整合包
wiki.tooltip=Minecraft Wiki 页面
wiki.version.game=https://zh.minecraft.wiki/w/Special:Search?search=%s&variant=zh-cn
wiki.version.game.search=Java版%s
wiki.version.game=https://zh.minecraft.wiki/w/Java版%s
wiki.version.game.snapshot=https://zh.minecraft.wiki/w/%s
wizard.prev=< 上一步
wizard.failed=失败
@@ -16,7 +16,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="%lang%">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
@@ -0,0 +1,42 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Glavo
*/
public final class WenyanUtilsTest {
private static void assertYearToString(String value, int year) {
StringBuilder builder = new StringBuilder(2);
WenyanUtils.appendYear(builder, year);
assertEquals(value, builder.toString());
}
@Test
public void testYearToString() {
assertYearToString("甲子", 1984);
assertYearToString("乙巳", 2025);
assertYearToString("甲子", -2996);
assertYearToString("庚子", 1000);
}
}
+1
View File
@@ -30,4 +30,5 @@ dependencies {
compileOnlyApi(libs.jetbrains.annotations)
testImplementation(libs.jna.platform)
testImplementation(libs.jimfs)
}
@@ -29,7 +29,6 @@ import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import org.jackhuang.hmcl.auth.yggdrasil.YggdrasilService;
import org.jackhuang.hmcl.util.io.HttpRequest;
@@ -58,7 +57,7 @@ public class AuthlibInjectorServer implements Observable {
public static AuthlibInjectorServer locateServer(String url) throws IOException {
try {
url = addHttpsIfMissing(url);
url = NetworkUtils.addHttpsIfMissing(url);
HttpURLConnection conn = NetworkUtils.createHttpConnection(url);
String ali = conn.getHeaderField("x-authlib-injector-api-location");
if (ali != null) {
@@ -85,18 +84,6 @@ public class AuthlibInjectorServer implements Observable {
}
}
private static String addHttpsIfMissing(String url) throws IOException {
if (Pattern.compile("^(?<scheme>[a-zA-Z][a-zA-Z0-9+.-]*)://").matcher(url).find())
return url;
if (url.startsWith("//"))
return "https:" + url;
else if (url.startsWith("/"))
return "https:/" + url;
else
return "https://" + url;
}
private static boolean urlEqualsIgnoreSlash(String a, String b) {
if (!a.endsWith("/"))
a += "/";
@@ -165,7 +165,7 @@ public class Skin {
case CUSTOM_SKIN_LOADER_API:
String realCslApi = type == Type.LITTLE_SKIN
? "https://littleskin.cn/csl"
: StringUtils.removeSuffix(Lang.requireNonNullElse(cslApi, ""), "/");
: NetworkUtils.addHttpsIfMissing(StringUtils.removeSuffix(Lang.requireNonNullElse(cslApi, ""), "/"));
return Task.composeAsync(() -> new GetTask(String.format("%s/%s.json", realCslApi, username)))
.thenComposeAsync(json -> {
SkinJson result = JsonUtils.GSON.fromJson(json, SkinJson.class);
@@ -17,6 +17,7 @@
*/
package org.jackhuang.hmcl.download;
import org.jackhuang.hmcl.download.cleanroom.CleanroomVersionList;
import org.jackhuang.hmcl.download.fabric.FabricAPIVersionList;
import org.jackhuang.hmcl.download.fabric.FabricVersionList;
import org.jackhuang.hmcl.download.forge.ForgeBMCLVersionList;
@@ -43,6 +44,7 @@ public final class BMCLAPIDownloadProvider implements DownloadProvider {
private final FabricVersionList fabric;
private final FabricAPIVersionList fabricApi;
private final ForgeBMCLVersionList forge;
private final CleanroomVersionList cleanroom;
private final NeoForgeBMCLVersionList neoforge;
private final LiteLoaderBMCLVersionList liteLoader;
private final OptiFineBMCLVersionList optifine;
@@ -56,6 +58,7 @@ public final class BMCLAPIDownloadProvider implements DownloadProvider {
this.fabric = new FabricVersionList(this);
this.fabricApi = new FabricAPIVersionList(this);
this.forge = new ForgeBMCLVersionList(apiRoot);
this.cleanroom = new CleanroomVersionList(this);
this.neoforge = new NeoForgeBMCLVersionList(apiRoot);
this.liteLoader = new LiteLoaderBMCLVersionList(this);
this.optifine = new OptiFineBMCLVersionList(apiRoot);
@@ -78,6 +81,8 @@ public final class BMCLAPIDownloadProvider implements DownloadProvider {
pair("https://maven.fabricmc.net", apiRoot + "/maven"),
pair("https://authlib-injector.yushi.moe", apiRoot + "/mirrors/authlib-injector"),
pair("https://repo1.maven.org/maven2", "https://mirrors.cloud.tencent.com/nexus/repository/maven-public"),
pair("https://repo.maven.apache.org/maven2", "https://mirrors.cloud.tencent.com/nexus/repository/maven-public"),
pair("https://hmcl-dev.github.io/metadata/cleanroom", "https://alist.8mi.tech/d/mirror/HMCL-Metadata/Auto/cleanroom"),
pair("https://zkitefly.github.io/unlisted-versions-of-minecraft", "https://alist.8mi.tech/d/mirror/unlisted-versions-of-minecraft/Auto")
// // https://github.com/mcmod-info-mirror/mcim-rust-api
// pair("https://api.modrinth.com", "https://mod.mcimirror.top/modrinth"),
@@ -113,6 +118,8 @@ public final class BMCLAPIDownloadProvider implements DownloadProvider {
return fabricApi;
case "forge":
return forge;
case "cleanroom":
return cleanroom;
case "neoforge":
return neoforge;
case "liteloader":
@@ -85,7 +85,8 @@ public class DefaultDependencyManager extends AbstractDependencyManager {
else
return null;
}).thenComposeAsync(checkPatchCompletionAsync(version, integrityCheck)),
new GameAssetDownloadTask(this, version, GameAssetDownloadTask.DOWNLOAD_INDEX_IF_NECESSARY, integrityCheck),
new GameAssetDownloadTask(this, version, GameAssetDownloadTask.DOWNLOAD_INDEX_IF_NECESSARY, integrityCheck)
.setSignificance(Task.TaskSignificance.MODERATE),
new GameLibrariesTask(this, version, integrityCheck)
);
}
@@ -122,7 +122,7 @@ public final class LibraryAnalyzer implements Iterable<LibraryAnalyzer.LibraryMa
/**
* Remove library by library id
*
* @param libraryId patch id or "forge"/"optifine"/"liteloader"/"fabric"/"quilt"/"neoforge"
* @param libraryId patch id or "forge"/"optifine"/"liteloader"/"fabric"/"quilt"/"neoforge"/"cleanroom"
* @return this
*/
public LibraryAnalyzer removeLibrary(String libraryId) {
@@ -172,6 +172,7 @@ public final class LibraryAnalyzer implements Iterable<LibraryAnalyzer.LibraryMa
String mainClass = resolvedVersion.getMainClass();
return mainClass != null && (LAUNCH_WRAPPER_MAIN.equals(mainClass)
|| mainClass.startsWith("net.minecraftforge")
|| mainClass.startsWith("top.outlands") //Cleanroom
|| mainClass.startsWith("net.fabricmc")
|| mainClass.startsWith("org.quiltmc")
|| mainClass.startsWith("cpw.mods"));
@@ -212,6 +213,7 @@ public final class LibraryAnalyzer implements Iterable<LibraryAnalyzer.LibraryMa
return super.matchLibrary(library, libraries);
}
},
CLEANROOM(true, "cleanroom", "com\\.cleanroommc", "cleanroom", ModLoaderType.CLEANROOM),
NEO_FORGE(true, "neoforge", "net\\.neoforged\\.fancymodloader", "(core|loader)", ModLoaderType.NEO_FORGED) {
private final Pattern NEO_FORGE_VERSION_MATCHER = Pattern.compile("^([0-9.]+)-(?<forge>[0-9.]+)(-([0-9.]+))?$");
@@ -17,6 +17,7 @@
*/
package org.jackhuang.hmcl.download;
import org.jackhuang.hmcl.download.cleanroom.CleanroomVersionList;
import org.jackhuang.hmcl.download.fabric.FabricAPIVersionList;
import org.jackhuang.hmcl.download.fabric.FabricVersionList;
import org.jackhuang.hmcl.download.forge.ForgeVersionList;
@@ -37,6 +38,7 @@ public class MojangDownloadProvider implements DownloadProvider {
private final FabricAPIVersionList fabricApi;
private final ForgeVersionList forge;
private final NeoForgeOfficialVersionList neoforge;
private final CleanroomVersionList cleanroom;
private final LiteLoaderVersionList liteLoader;
private final OptiFineBMCLVersionList optifine;
private final QuiltVersionList quilt;
@@ -51,6 +53,7 @@ public class MojangDownloadProvider implements DownloadProvider {
this.fabricApi = new FabricAPIVersionList(this);
this.forge = new ForgeVersionList(this);
this.neoforge = new NeoForgeOfficialVersionList(this);
this.cleanroom = new CleanroomVersionList(this);
this.liteLoader = new LiteLoaderVersionList(this);
this.optifine = new OptiFineBMCLVersionList(apiRoot);
this.quilt = new QuiltVersionList(this);
@@ -78,6 +81,8 @@ public class MojangDownloadProvider implements DownloadProvider {
return fabricApi;
case "forge":
return forge;
case "cleanroom":
return cleanroom;
case "neoforge":
return neoforge;
case "liteloader":
@@ -0,0 +1,93 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> 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.download.cleanroom;
import org.jackhuang.hmcl.download.DefaultDependencyManager;
import org.jackhuang.hmcl.download.LibraryAnalyzer;
import org.jackhuang.hmcl.download.UnsupportedInstallationException;
import org.jackhuang.hmcl.download.VersionMismatchException;
import org.jackhuang.hmcl.download.forge.ForgeNewInstallTask;
import org.jackhuang.hmcl.game.Version;
import org.jackhuang.hmcl.task.FileDownloadTask;
import org.jackhuang.hmcl.task.Task;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
public final class CleanroomInstallTask extends Task<Version> {
private final DefaultDependencyManager dependencyManager;
private final Version version;
private Path installer;
private final CleanroomRemoteVersion remote;
private FileDownloadTask dependent;
private Task<Version> task;
public CleanroomInstallTask(DefaultDependencyManager dependencyManager, Version version, CleanroomRemoteVersion remoteVersion) {
this.dependencyManager = dependencyManager;
this.version = version;
this.remote = remoteVersion;
setSignificance(TaskSignificance.MODERATE);
}
@Override
public boolean doPreExecute() {
return true;
}
@Override
public void preExecute() throws Exception {
installer = Files.createTempFile("cleanroom-installer", ".jar");
dependent = new FileDownloadTask(
dependencyManager.getDownloadProvider().injectURLsWithCandidates(remote.getUrls()),
installer, null);
dependent.setCacheRepository(dependencyManager.getCacheRepository());
dependent.setCaching(true);
dependent.addIntegrityCheckHandler(FileDownloadTask.ZIP_INTEGRITY_CHECK_HANDLER);
}
@Override
public boolean doPostExecute() {
return true;
}
@Override
public void postExecute() throws Exception {
Files.deleteIfExists(installer);
setResult(task.getResult());
}
@Override
public Collection<Task<?>> getDependents() {
return Collections.singleton(dependent);
}
@Override
public Collection<Task<?>> getDependencies() {
return Collections.singleton(task);
}
@Override
public void execute() throws IOException, VersionMismatchException, UnsupportedInstallationException {
task = new ForgeNewInstallTask(dependencyManager, version, remote.getSelfVersion(), installer).thenApplyAsync((version) -> version.setId(LibraryAnalyzer.LibraryType.CLEANROOM.getPatchId()));
}
}
@@ -0,0 +1,38 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> 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.download.cleanroom;
import org.jackhuang.hmcl.download.DefaultDependencyManager;
import org.jackhuang.hmcl.download.LibraryAnalyzer;
import org.jackhuang.hmcl.download.RemoteVersion;
import org.jackhuang.hmcl.game.Version;
import org.jackhuang.hmcl.task.Task;
import java.time.Instant;
import java.util.List;
public class CleanroomRemoteVersion extends RemoteVersion {
public CleanroomRemoteVersion(String gameVersion, String selfVersion, Instant releaseDate, List<String> url) {
super(LibraryAnalyzer.LibraryType.CLEANROOM.getPatchId(), gameVersion, selfVersion, releaseDate, url);
}
@Override
public Task<Version> getInstallTask(DefaultDependencyManager dependencyManager, Version baseVersion) {
return new CleanroomInstallTask(dependencyManager, baseVersion, this);
}
}
@@ -0,0 +1,69 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2021 huangyuhui <huanghongxun2008@126.com> 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.download.cleanroom;
import org.jackhuang.hmcl.download.DownloadProvider;
import org.jackhuang.hmcl.download.VersionList;
import org.jackhuang.hmcl.task.GetTask;
import org.jackhuang.hmcl.task.Task;
import java.time.Instant;
import java.util.Collections;
public final class CleanroomVersionList extends VersionList<CleanroomRemoteVersion> {
private final DownloadProvider downloadProvider;
private static final String LOADER_LIST_URL = "https://hmcl-dev.github.io/metadata/cleanroom/index.json";
private static final String INSTALLER_URL = "https://hmcl-dev.github.io/metadata/cleanroom/files/cleanroom-%s-installer.jar";
public CleanroomVersionList(DownloadProvider downloadProvider) {
this.downloadProvider = downloadProvider;
}
@Override
public boolean hasType() {
return false;
}
@Override
public Task<?> refreshAsync() {
return Task.allOf(
new GetTask(downloadProvider.injectURLWithCandidates(LOADER_LIST_URL)).thenGetJsonAsync(ReleaseResult[].class)
).thenAcceptAsync(results -> {
lock.writeLock().lock();
try {
versions.clear();
for (ReleaseResult version : results.get(0)) {
versions.put("1.12.2", new CleanroomRemoteVersion(
"1.12.2", version.name, Instant.parse(version.created_at),
Collections.singletonList(
String.format(INSTALLER_URL, version.name)
)
));
}
} finally {
lock.writeLock().unlock();
}
});
}
private static class ReleaseResult {
String name;
String created_at;
}
}
@@ -108,6 +108,14 @@ public enum JavaVersionConstraint {
&& super.appliesToVersionImpl(gameVersionNumber, version, java, analyzer);
}
},
CLEANROOM_JAVA_21(true, GameVersionNumber.between("1.12.2", "1.12.999"), VersionNumber.atLeast("21")) {
@Override
protected boolean appliesToVersionImpl(GameVersionNumber gameVersionNumber, @Nullable Version version,
@Nullable JavaRuntime java, @Nullable LibraryAnalyzer analyzer) {
return analyzer != null && analyzer.has(LibraryAnalyzer.LibraryType.CLEANROOM)
&& super.appliesToVersionImpl(gameVersionNumber, version, java, analyzer);
}
},
// LaunchWrapper<=1.12 will crash because LaunchWrapper assumes the system class loader is an instance of URLClassLoader (Java 8)
LAUNCH_WRAPPER(true, GameVersionNumber.atMost("1.12.999"), VersionNumber.atMost("1.8.999")) {
@Override
@@ -130,7 +138,8 @@ public enum JavaVersionConstraint {
@Nullable JavaRuntime java, @Nullable LibraryAnalyzer analyzer) {
return OperatingSystem.CURRENT_OS == OperatingSystem.LINUX
&& Architecture.SYSTEM_ARCH == Architecture.X86_64
&& (java == null || java.getArchitecture() == Architecture.X86_64);
&& (java == null || java.getArchitecture() == Architecture.X86_64)
&& (analyzer == null || !analyzer.has(LibraryAnalyzer.LibraryType.CLEANROOM));
}
@Override
@@ -26,7 +26,6 @@ import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.gson.UUIDTypeAdapter;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jackhuang.hmcl.util.io.Unzipper;
import org.jackhuang.hmcl.util.platform.Bits;
import org.jackhuang.hmcl.util.platform.*;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
@@ -41,8 +40,8 @@ import java.util.*;
import java.util.function.Supplier;
import static org.jackhuang.hmcl.util.Lang.mapOf;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
import static org.jackhuang.hmcl.util.Pair.pair;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
/**
* @author huangyuhui
@@ -247,6 +246,10 @@ public class DefaultLauncher extends Launcher {
Set<String> classpath = repository.getClasspath(version);
if (analyzer.has(LibraryAnalyzer.LibraryType.CLEANROOM)) {
classpath.removeIf(c -> c.contains("2.9.4-nightly-20150209"));
}
File jar = repository.getVersionJar(version);
if (!jar.exists() || !jar.isFile())
throw new IOException("Minecraft jar does not exist");
@@ -442,7 +445,7 @@ public class DefaultLauncher extends Launcher {
pair("${library_directory}", repository.getLibrariesDirectory(version).getAbsolutePath()),
pair("${classpath_separator}", File.pathSeparator),
pair("${primary_jar}", repository.getVersionJar(version).getAbsolutePath()),
pair("${language}", Locale.getDefault().toString()),
pair("${language}", Locale.getDefault().toLanguageTag()),
// defined by HMCL
// libraries_directory stands for historical reasons here. We don't know the official launcher
@@ -551,6 +554,9 @@ public class DefaultLauncher extends Launcher {
if (analyzer.has(LibraryAnalyzer.LibraryType.FORGE)) {
env.put("INST_FORGE", "1");
}
if (analyzer.has(LibraryAnalyzer.LibraryType.CLEANROOM)) {
env.put("INST_CLEANROOM", "1");
}
if (analyzer.has(LibraryAnalyzer.LibraryType.NEO_FORGE)) {
env.put("INST_NEOFORGE", "1");
}
@@ -20,6 +20,7 @@ package org.jackhuang.hmcl.mod;
public enum ModLoaderType {
UNKNOWN,
FORGE,
CLEANROOM,
NEO_FORGED,
FABRIC,
QUILT,
@@ -91,6 +91,8 @@ public class McbbsModpackExportTask extends Task<Void> {
addons.add(new McbbsModpackManifest.Addon(MINECRAFT.getPatchId(), gameVersion));
analyzer.getVersion(FORGE).ifPresent(forgeVersion ->
addons.add(new McbbsModpackManifest.Addon(FORGE.getPatchId(), forgeVersion)));
analyzer.getVersion(CLEANROOM).ifPresent(cleanroomVersion ->
addons.add(new McbbsModpackManifest.Addon(CLEANROOM.getPatchId(), cleanroomVersion)));
analyzer.getVersion(NEO_FORGE).ifPresent(neoForgeVersion ->
addons.add(new McbbsModpackManifest.Addon(NEO_FORGE.getPatchId(), neoForgeVersion)));
analyzer.getVersion(LITELOADER).ifPresent(liteLoaderVersion ->
@@ -0,0 +1,690 @@
// Copy from GsonTypes
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jackhuang.hmcl.util;
import static com.google.gson.internal.GsonPreconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Properties;
/**
* Static methods for working with types.
*
* @author Bob Lee
* @author Jesse Wilson
*/
@SuppressWarnings("MemberName") // legacy class name
public final class TypeUtils {
static final Type[] EMPTY_TYPE_ARRAY = new Type[]{};
private TypeUtils() {
throw new UnsupportedOperationException();
}
/**
* Returns a new parameterized type, applying {@code typeArguments} to {@code rawType} and
* enclosed by {@code ownerType}.
*
* @return a {@link java.io.Serializable serializable} parameterized type.
*/
public static ParameterizedType newParameterizedTypeWithOwner(
Type ownerType, Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeImpl(ownerType, rawType, typeArguments);
}
/**
* Returns an array type whose elements are all instances of {@code componentType}.
*
* @return a {@link java.io.Serializable serializable} generic array type.
*/
public static GenericArrayType arrayOf(Type componentType) {
return new GenericArrayTypeImpl(componentType);
}
/**
* Returns a type that represents an unknown type that extends {@code bound}. For example, if
* {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
* {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code ?
* extends Object}.
*/
public static WildcardType subtypeOf(Type bound) {
Type[] upperBounds;
if (bound instanceof WildcardType) {
upperBounds = ((WildcardType) bound).getUpperBounds();
} else {
upperBounds = new Type[]{bound};
}
return new WildcardTypeImpl(upperBounds, EMPTY_TYPE_ARRAY);
}
/**
* Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code
* bound} is {@code String.class}, this returns {@code ? super String}.
*/
public static WildcardType supertypeOf(Type bound) {
Type[] lowerBounds;
if (bound instanceof WildcardType) {
lowerBounds = ((WildcardType) bound).getLowerBounds();
} else {
lowerBounds = new Type[]{bound};
}
return new WildcardTypeImpl(new Type[]{Object.class}, lowerBounds);
}
/**
* Returns a type that is functionally equal but not necessarily equal according to {@link
* Object#equals(Object) Object.equals()}. The returned type is {@link java.io.Serializable}.
*/
public static Type canonicalize(Type type) {
if (type instanceof Class) {
Class<?> c = (Class<?>) type;
return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;
} else if (type instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType) type;
return new ParameterizedTypeImpl(
p.getOwnerType(), (Class<?>) p.getRawType(), p.getActualTypeArguments());
} else if (type instanceof GenericArrayType) {
GenericArrayType g = (GenericArrayType) type;
return new GenericArrayTypeImpl(g.getGenericComponentType());
} else if (type instanceof WildcardType) {
WildcardType w = (WildcardType) type;
return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
} else {
// type is either serializable as-is or unsupported
return type;
}
}
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
// type is a normal class.
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// getRawType() returns Type instead of Class; that seems to be an API mistake,
// see https://bugs.openjdk.org/browse/JDK-8250659
Type rawType = parameterizedType.getRawType();
checkArgument(rawType instanceof Class);
return (Class<?>) rawType;
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
} else if (type instanceof TypeVariable) {
// we could use the variable's bounds, but that won't work if there are multiple.
// having a raw type that's more general than necessary is okay
return Object.class;
} else if (type instanceof WildcardType) {
Type[] bounds = ((WildcardType) type).getUpperBounds();
// Currently the JLS only permits one bound for wildcards so using first bound is safe
assert bounds.length == 1;
return getRawType(bounds[0]);
} else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException(
"Expected a Class, ParameterizedType, or GenericArrayType, but <"
+ type
+ "> is of type "
+ className);
}
}
private static boolean equal(Object a, Object b) {
return Objects.equals(a, b);
}
/**
* Returns true if {@code a} and {@code b} are equal.
*/
public static boolean equals(Type a, Type b) {
if (a == b) {
// also handles (a == null && b == null)
return true;
} else if (a instanceof Class) {
// Class already specifies equals().
return a.equals(b);
} else if (a instanceof ParameterizedType) {
if (!(b instanceof ParameterizedType)) {
return false;
}
// TODO: save a .clone() call
ParameterizedType pa = (ParameterizedType) a;
ParameterizedType pb = (ParameterizedType) b;
return equal(pa.getOwnerType(), pb.getOwnerType())
&& pa.getRawType().equals(pb.getRawType())
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
} else if (a instanceof GenericArrayType) {
if (!(b instanceof GenericArrayType)) {
return false;
}
GenericArrayType ga = (GenericArrayType) a;
GenericArrayType gb = (GenericArrayType) b;
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
} else if (a instanceof WildcardType) {
if (!(b instanceof WildcardType)) {
return false;
}
WildcardType wa = (WildcardType) a;
WildcardType wb = (WildcardType) b;
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
} else if (a instanceof TypeVariable) {
if (!(b instanceof TypeVariable)) {
return false;
}
TypeVariable<?> va = (TypeVariable<?>) a;
TypeVariable<?> vb = (TypeVariable<?>) b;
return Objects.equals(va.getGenericDeclaration(), vb.getGenericDeclaration())
&& va.getName().equals(vb.getName());
} else {
// This isn't a type we support. Could be a generic array type, wildcard type, etc.
return false;
}
}
public static String typeToString(Type type) {
return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
/**
* Returns the generic supertype for {@code supertype}. For example, given a class {@code
* IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
* result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
*/
public static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> supertype) {
if (supertype == rawType) {
return context;
}
// we skip searching through interfaces if unknown is an interface
if (supertype.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == supertype) {
return rawType.getGenericInterfaces()[i];
} else if (supertype.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], supertype);
}
}
}
// check our supertypes
if (!rawType.isInterface()) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == supertype) {
return rawType.getGenericSuperclass();
} else if (supertype.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, supertype);
}
rawType = rawSupertype;
}
}
// we can't resolve this further
return supertype;
}
/**
* Returns the generic form of {@code supertype}. For example, if this is {@code
* ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
* Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
*/
public static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
if (context instanceof WildcardType) {
// Wildcards are useless for resolving supertypes. As the upper bound has the same raw type,
// use it instead
Type[] bounds = ((WildcardType) context).getUpperBounds();
// Currently the JLS only permits one bound for wildcards so using first bound is safe
assert bounds.length == 1;
context = bounds[0];
}
checkArgument(supertype.isAssignableFrom(contextRawType));
return resolve(
context, contextRawType, TypeUtils.getGenericSupertype(context, contextRawType, supertype));
}
/**
* Returns the component type of this array type.
*
* @throws ClassCastException if this type is not an array.
*/
public static Type getArrayComponentType(Type array) {
return array instanceof GenericArrayType
? ((GenericArrayType) array).getGenericComponentType()
: ((Class<?>) array).getComponentType();
}
/**
* Returns the element type of this collection type.
*
* @throws IllegalArgumentException if this type is not a collection.
*/
public static Type getCollectionElementType(Type context, Class<?> contextRawType) {
Type collectionType = getSupertype(context, contextRawType, Collection.class);
if (collectionType instanceof ParameterizedType) {
return ((ParameterizedType) collectionType).getActualTypeArguments()[0];
}
return Object.class;
}
/**
* Returns a two element array containing this map's key and value types in positions 0 and 1
* respectively.
*/
public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
/*
* Work around a problem with the declaration of java.util.Properties. That
* class should extend Hashtable<String, String>, but it's declared to
* extend Hashtable<Object, Object>.
*/
if (Properties.class.isAssignableFrom(contextRawType)) {
return new Type[]{String.class, String.class};
}
Type mapType = getSupertype(context, contextRawType, Map.class);
// TODO: strip wildcards?
if (mapType instanceof ParameterizedType) {
ParameterizedType mapParameterizedType = (ParameterizedType) mapType;
return mapParameterizedType.getActualTypeArguments();
}
return new Type[]{Object.class, Object.class};
}
public static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
return resolve(context, contextRawType, toResolve, new HashMap<TypeVariable<?>, Type>());
}
private static Type resolve(
Type context,
Class<?> contextRawType,
Type toResolve,
Map<TypeVariable<?>, Type> visitedTypeVariables) {
// this implementation is made a little more complicated in an attempt to avoid object-creation
TypeVariable<?> resolving = null;
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
Type previouslyResolved = visitedTypeVariables.get(typeVariable);
if (previouslyResolved != null) {
// cannot reduce due to infinite recursion
return (previouslyResolved == Void.TYPE) ? toResolve : previouslyResolved;
}
// Insert a placeholder to mark the fact that we are in the process of resolving this type
visitedTypeVariables.put(typeVariable, Void.TYPE);
if (resolving == null) {
resolving = typeVariable;
}
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
break;
}
} else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
Class<?> original = (Class<?>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType =
resolve(context, contextRawType, componentType, visitedTypeVariables);
toResolve = equal(componentType, newComponentType) ? original : arrayOf(newComponentType);
break;
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType =
resolve(context, contextRawType, componentType, visitedTypeVariables);
toResolve = equal(componentType, newComponentType) ? original : arrayOf(newComponentType);
break;
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
boolean ownerChanged = !equal(newOwnerType, ownerType);
Type[] args = original.getActualTypeArguments();
boolean argsChanged = false;
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument =
resolve(context, contextRawType, args[t], visitedTypeVariables);
if (!equal(resolvedTypeArgument, args[t])) {
if (!argsChanged) {
args = args.clone();
argsChanged = true;
}
args[t] = resolvedTypeArgument;
}
}
toResolve =
ownerChanged || argsChanged
? newParameterizedTypeWithOwner(
newOwnerType, (Class<?>) original.getRawType(), args)
: original;
break;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound =
resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
if (lowerBound != originalLowerBound[0]) {
toResolve = supertypeOf(lowerBound);
break;
}
} else if (originalUpperBound.length == 1) {
Type upperBound =
resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
if (upperBound != originalUpperBound[0]) {
toResolve = subtypeOf(upperBound);
break;
}
}
toResolve = original;
break;
} else {
break;
}
}
// ensure that any in-process resolution gets updated with the final result
if (resolving != null) {
visitedTypeVariables.put(resolving, toResolve);
}
return toResolve;
}
private static Type resolveTypeVariable(
Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
Class<?> declaredByRaw = declaringClassOf(unknown);
// we can't reduce this further
if (declaredByRaw == null) {
return unknown;
}
Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
if (declaredBy instanceof ParameterizedType) {
int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
}
return unknown;
}
private static int indexOf(Object[] array, Object toFind) {
for (int i = 0, length = array.length; i < length; i++) {
if (toFind.equals(array[i])) {
return i;
}
}
throw new NoSuchElementException();
}
/**
* Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
* a class.
*/
private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null;
}
static void checkNotPrimitive(Type type) {
checkArgument(!(type instanceof Class<?>) || !((Class<?>) type).isPrimitive());
}
/**
* Whether an {@linkplain ParameterizedType#getOwnerType() owner type} must be specified when
* constructing a {@link ParameterizedType} for {@code rawType}.
*
* <p>Note that this method might not require an owner type for all cases where Java reflection
* would create parameterized types with owner type.
*/
public static boolean requiresOwnerType(Type rawType) {
if (rawType instanceof Class<?>) {
Class<?> rawTypeAsClass = (Class<?>) rawType;
return !Modifier.isStatic(rawTypeAsClass.getModifiers())
&& rawTypeAsClass.getDeclaringClass() != null;
}
return false;
}
// Here and below we put @SuppressWarnings("serial") on fields of type `Type`. Recent Java
// compilers complain that the declared type is not Serializable. But in this context we go out of
// our way to ensure that the Type in question is either Class (which is serializable) or one of
// the nested Type implementations here (which are also serializable).
private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable {
@SuppressWarnings("serial")
private final Type ownerType;
@SuppressWarnings("serial")
private final Type rawType;
@SuppressWarnings("serial")
private final Type[] typeArguments;
public ParameterizedTypeImpl(Type ownerType, Class<?> rawType, Type... typeArguments) {
requireNonNull(rawType);
if (ownerType == null && requiresOwnerType(rawType)) {
throw new IllegalArgumentException("Must specify owner type for " + rawType);
}
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
this.rawType = canonicalize(rawType);
this.typeArguments = typeArguments.clone();
for (int t = 0, length = this.typeArguments.length; t < length; t++) {
requireNonNull(this.typeArguments[t]);
checkNotPrimitive(this.typeArguments[t]);
this.typeArguments[t] = canonicalize(this.typeArguments[t]);
}
}
@Override
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object other) {
return other instanceof ParameterizedType
&& TypeUtils.equals(this, (ParameterizedType) other);
}
private static int hashCodeOrZero(Object o) {
return o != null ? o.hashCode() : 0;
}
@Override
public int hashCode() {
return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType);
}
@Override
public String toString() {
int length = typeArguments.length;
if (length == 0) {
return typeToString(rawType);
}
StringBuilder stringBuilder = new StringBuilder(30 * (length + 1));
stringBuilder
.append(typeToString(rawType))
.append("<")
.append(typeToString(typeArguments[0]));
for (int i = 1; i < length; i++) {
stringBuilder.append(", ").append(typeToString(typeArguments[i]));
}
return stringBuilder.append(">").toString();
}
private static final long serialVersionUID = 0;
}
private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable {
@SuppressWarnings("serial")
private final Type componentType;
public GenericArrayTypeImpl(Type componentType) {
requireNonNull(componentType);
this.componentType = canonicalize(componentType);
}
@Override
public Type getGenericComponentType() {
return componentType;
}
@Override
public boolean equals(Object o) {
return o instanceof GenericArrayType && TypeUtils.equals(this, (GenericArrayType) o);
}
@Override
public int hashCode() {
return componentType.hashCode();
}
@Override
public String toString() {
return typeToString(componentType) + "[]";
}
private static final long serialVersionUID = 0;
}
/**
* The WildcardType interface supports multiple upper bounds and multiple lower bounds. We only
* support what the target Java version supports - at most one bound, see also
* https://bugs.openjdk.java.net/browse/JDK-8250660. If a lower bound is set, the upper bound must
* be Object.class.
*/
private static final class WildcardTypeImpl implements WildcardType, Serializable {
@SuppressWarnings("serial")
private final Type upperBound;
@SuppressWarnings("serial")
private final Type lowerBound;
public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
checkArgument(lowerBounds.length <= 1);
checkArgument(upperBounds.length == 1);
if (lowerBounds.length == 1) {
requireNonNull(lowerBounds[0]);
checkNotPrimitive(lowerBounds[0]);
checkArgument(upperBounds[0] == Object.class);
this.lowerBound = canonicalize(lowerBounds[0]);
this.upperBound = Object.class;
} else {
requireNonNull(upperBounds[0]);
checkNotPrimitive(upperBounds[0]);
this.lowerBound = null;
this.upperBound = canonicalize(upperBounds[0]);
}
}
@Override
public Type[] getUpperBounds() {
return new Type[]{upperBound};
}
@Override
public Type[] getLowerBounds() {
return lowerBound != null ? new Type[]{lowerBound} : EMPTY_TYPE_ARRAY;
}
@Override
public boolean equals(Object other) {
return other instanceof WildcardType && TypeUtils.equals(this, (WildcardType) other);
}
@Override
public int hashCode() {
// this equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds());
return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode());
}
@Override
public String toString() {
if (lowerBound != null) {
return "? super " + typeToString(lowerBound);
} else if (upperBound == Object.class) {
return "?";
} else {
return "? extends " + typeToString(upperBound);
}
}
private static final long serialVersionUID = 0;
}
}
@@ -0,0 +1,213 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.annotations.SerializedName;
import javafx.beans.Observable;
import javafx.beans.property.ListProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SetProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import org.jackhuang.hmcl.util.TypeUtils;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// @author Glavo
public abstract class ObservableField<T> {
public static <T> ObservableField<T> of(MethodHandles.Lookup lookup, Field field) {
String name;
List<String> alternateNames;
SerializedName serializedName = field.getAnnotation(SerializedName.class);
if (serializedName == null) {
name = field.getName();
alternateNames = List.of();
} else {
name = serializedName.value();
alternateNames = List.of(serializedName.alternate());
}
VarHandle varHandle;
try {
varHandle = lookup.unreflectVarHandle(field);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
if (ObservableList.class.isAssignableFrom(field.getType())) {
Type listType = TypeUtils.getSupertype(field.getGenericType(), field.getType(), List.class);
if (!(listType instanceof ParameterizedType))
throw new IllegalArgumentException("Cannot resolve the list type of " + field.getName());
return new CollectionField<>(name, alternateNames, varHandle, listType, listType);
} else if (ObservableSet.class.isAssignableFrom(field.getType())) {
Type setType = TypeUtils.getSupertype(field.getGenericType(), field.getType(), Set.class);
if (!(setType instanceof ParameterizedType))
throw new IllegalArgumentException("Cannot resolve the set type of " + field.getName());
ParameterizedType listType = TypeUtils.newParameterizedTypeWithOwner(
null,
List.class,
((ParameterizedType) setType).getActualTypeArguments()[0]
);
return new CollectionField<>(name, alternateNames, varHandle, setType, listType);
} else if (ObservableMap.class.isAssignableFrom(field.getType())) {
Type mapType = TypeUtils.getSupertype(field.getGenericType(), field.getType(), Map.class);
if (!(mapType instanceof ParameterizedType))
throw new IllegalArgumentException("Cannot resolve the map type of " + field.getName());
return new MapField<>(name, alternateNames, varHandle, mapType);
} else if (Property.class.isAssignableFrom(field.getType())) {
Type propertyType = TypeUtils.getSupertype(field.getGenericType(), field.getType(), Property.class);
if (!(propertyType instanceof ParameterizedType))
throw new IllegalArgumentException("Cannot resolve the element type of " + field.getName());
Type elementType = ((ParameterizedType) propertyType).getActualTypeArguments()[0];
return new PropertyField<>(name, alternateNames, varHandle, elementType);
} else {
throw new IllegalArgumentException("Field " + field.getName() + " is not a property or observable collection");
}
}
protected final String serializedName;
protected final List<String> alternateNames;
protected final VarHandle varHandle;
private ObservableField(String serializedName, List<String> alternateNames, VarHandle varHandle) {
this.serializedName = serializedName;
this.alternateNames = alternateNames;
this.varHandle = varHandle;
}
public String getSerializedName() {
return serializedName;
}
public List<String> getAlternateNames() {
return alternateNames;
}
public Observable get(T value) {
return (Observable) varHandle.get(value);
}
public abstract JsonElement serialize(T value, JsonSerializationContext context);
public abstract void deserialize(T value, JsonElement element, JsonDeserializationContext context);
private static final class PropertyField<T> extends ObservableField<T> {
private final Type elementType;
PropertyField(String serializedName, List<String> alternate, VarHandle varHandle, Type elementType) {
super(serializedName, alternate, varHandle);
this.elementType = elementType;
}
@Override
public JsonElement serialize(T value, JsonSerializationContext context) {
return context.serialize(((Property<?>) get(value)).getValue(), elementType);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void deserialize(T value, JsonElement element, JsonDeserializationContext context) {
((Property) get(value)).setValue(context.deserialize(element, elementType));
}
}
private static final class CollectionField<T> extends ObservableField<T> {
private final Type collectionType;
/// When deserializing a Set, we first deserialize it into a `List`, then put the elements into the Set.
private final Type listType;
CollectionField(String serializedName, List<String> alternate, VarHandle varHandle,
Type collectionType, Type listType) {
super(serializedName, alternate, varHandle);
this.collectionType = collectionType;
this.listType = listType;
}
@Override
public JsonElement serialize(T value, JsonSerializationContext context) {
return context.serialize(get(value), collectionType);
}
@SuppressWarnings({"unchecked"})
@Override
public void deserialize(T value, JsonElement element, JsonDeserializationContext context) {
List<?> deserialized = context.deserialize(element, listType);
Object fieldValue = get(value);
if (fieldValue instanceof ListProperty) {
((ListProperty<Object>) fieldValue).set(FXCollections.observableList((List<Object>) deserialized));
} else if (fieldValue instanceof ObservableList) {
((ObservableList<Object>) fieldValue).setAll(deserialized);
} else if (fieldValue instanceof SetProperty) {
((SetProperty<Object>) fieldValue).set(FXCollections.observableSet(new HashSet<>(deserialized)));
} else if (fieldValue instanceof ObservableSet) {
ObservableSet<Object> set = (ObservableSet<Object>) fieldValue;
set.clear();
set.addAll(deserialized);
} else {
throw new JsonParseException("Unsupported field type: " + fieldValue.getClass());
}
}
}
private static final class MapField<T> extends ObservableField<T> {
private final Type mapType;
MapField(String serializedName, List<String> alternate, VarHandle varHandle, Type mapType) {
super(serializedName, alternate, varHandle);
this.mapType = mapType;
}
@Override
public JsonElement serialize(T value, JsonSerializationContext context) {
return context.serialize(get(value), mapType);
}
@SuppressWarnings({"unchecked"})
@Override
public void deserialize(T config, JsonElement element, JsonDeserializationContext context) {
Map<Object, Object> deserialized = context.deserialize(element, mapType);
ObservableMap<Object, Object> map = (ObservableMap<Object, Object>) varHandle.get(config);
if (map instanceof MapProperty<?, ?>)
((MapProperty<Object, Object>) map).set(FXCollections.observableMap(deserialized));
else {
map.clear();
map.putAll(deserialized);
}
}
}
}
@@ -0,0 +1,104 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/// Overrides the default behavior of [ResourceBundle.Control], optimizing the candidate list generation logic.
///
/// Compared to the default implementation, [DefaultResourceBundleControl] optimizes the following scenarios:
///
/// - If no language is specified (such as [Locale#ROOT]), `en` is used instead.
/// - For all Chinese locales, if no script is specified, the script (`Hans`/`Hant`/`Latn`) is always inferred based on region and variant.
/// - For all Chinese locales, `zh-CN` is always added to the candidate list. If `zh-Hans` already exists in the candidate list,
/// `zh-CN` is inserted before `zh`; otherwise, it is inserted after `zh`.
/// - For all Traditional Chinese locales, `zh-TW` is always added to the candidate list (before `zh`).
/// - For all Chinese variants (such as `lzh`, `cmn`, `yue`, etc.), a candidate list with the language code replaced by `zh`
/// is added to the end of the candidate list.
///
/// @author Glavo
public class DefaultResourceBundleControl extends ResourceBundle.Control {
public static final DefaultResourceBundleControl INSTANCE = new DefaultResourceBundleControl();
public DefaultResourceBundleControl() {
}
private static List<Locale> ensureEditable(List<Locale> list) {
return list instanceof ArrayList<?>
? list
: new ArrayList<>(list);
}
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
if (locale.getLanguage().isEmpty())
return getCandidateLocales(baseName, Locale.ENGLISH);
if (LocaleUtils.isChinese(locale)) {
String language = locale.getLanguage();
String script = locale.getScript();
if (script.isEmpty()) {
script = LocaleUtils.getScript(locale);
locale = new Locale.Builder()
.setLocale(locale)
.setScript(script)
.build();
}
List<Locale> locales = super.getCandidateLocales("", locale);
if (language.equals("zh")) {
if (locales.contains(LocaleUtils.LOCALE_ZH_HANT) && !locales.contains(Locale.TRADITIONAL_CHINESE)) {
locales = ensureEditable(locales);
int chineseIdx = locales.indexOf(Locale.CHINESE);
if (chineseIdx >= 0)
locales.add(chineseIdx, Locale.TRADITIONAL_CHINESE);
}
if (!locales.contains(Locale.SIMPLIFIED_CHINESE)) {
int chineseIdx = locales.indexOf(Locale.CHINESE);
if (chineseIdx >= 0) {
locales = ensureEditable(locales);
if (locales.contains(LocaleUtils.LOCALE_ZH_HANS))
locales.add(chineseIdx, Locale.SIMPLIFIED_CHINESE);
else
locales.add(chineseIdx + 1, Locale.SIMPLIFIED_CHINESE);
}
}
} else {
locales = ensureEditable(locales);
locales.removeIf(it -> !it.getLanguage().equals(language));
locales.addAll(getCandidateLocales("", new Locale.Builder()
.setLocale(locale)
.setLanguage("zh")
.build()));
}
return locales;
}
return super.getCandidateLocales(baseName, locale);
}
}
@@ -0,0 +1,185 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import org.jackhuang.hmcl.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
/**
* @author Glavo
*/
public final class LocaleUtils {
public static final Locale SYSTEM_DEFAULT = Locale.getDefault();
public static final Locale LOCALE_ZH_HANS = Locale.forLanguageTag("zh-Hans");
public static final Locale LOCALE_ZH_HANT = Locale.forLanguageTag("zh-Hant");
public static final String DEFAULT_LANGUAGE_KEY = "default";
/// Convert a locale to the language key.
///
/// The language key is in the format of BCP 47 language tag.
/// If the locale is the default locale (language is empty), "default" will be returned.
public static String toLanguageKey(Locale locale) {
return locale.getLanguage().isEmpty()
? DEFAULT_LANGUAGE_KEY
: locale.stripExtensions().toLanguageTag();
}
/// Get the script of the locale. If the script is empty and the language is Chinese,
/// the script will be inferred based on the language, the region and the variant.
public static @NotNull String getScript(Locale locale) {
if (locale.getScript().isEmpty()) {
if (isChinese(locale)) {
if (CHINESE_LATN_VARIANTS.contains(locale.getVariant()))
return "Latn";
if (locale.getLanguage().equals("lzh") || CHINESE_TRADITIONAL_REGIONS.contains(locale.getCountry()))
return "Hant";
else
return "Hans";
}
}
return locale.getScript();
}
public static @NotNull List<Locale> getCandidateLocales(Locale locale) {
return DefaultResourceBundleControl.INSTANCE.getCandidateLocales("", locale);
}
public static <T> @Nullable T getByCandidateLocales(Map<String, T> map, List<Locale> candidateLocales) {
for (Locale locale : candidateLocales) {
String key = toLanguageKey(locale);
if (map.containsKey(key))
return map.get(key);
}
return null;
}
/// Find all localized files in the given directory with the given base name and extension.
/// The file name should be in the format of `baseName[_languageTag].ext`.
///
/// @return A map of language key to file path.
public static @NotNull @Unmodifiable Map<String, Path> findAllLocalizedFiles(Path dir, String baseName, String ext) {
if (Files.isDirectory(dir)) {
String suffix = "." + ext;
String defaultName = baseName + suffix;
String noDefaultPrefix = baseName + "_";
try (Stream<Path> list = Files.list(dir)) {
var result = new LinkedHashMap<String, Path>();
list.forEach(file -> {
if (Files.isRegularFile(file)) {
String fileName = file.getFileName().toString();
if (fileName.equals(defaultName)) {
result.put(DEFAULT_LANGUAGE_KEY, file);
} else if (fileName.startsWith(noDefaultPrefix) && fileName.endsWith(suffix)) {
String languageKey = fileName.substring(noDefaultPrefix.length(), fileName.length() - suffix.length())
.replace('_', '-');
if (!languageKey.isEmpty())
result.put(languageKey, file);
}
}
});
return result;
} catch (IOException e) {
LOG.warning("Failed to list files in directory " + dir, e);
}
}
return Map.of();
}
/// Find all localized files in the given directory with the given base name and extensions.
/// The file name should be in the format of `baseName[_languageTag].ext`.
///
/// @return A map of language key to a map of extension to file path.
public static @NotNull @Unmodifiable Map<String, Map<String, Path>> findAllLocalizedFiles(Path dir, String baseName, Collection<String> exts) {
if (Files.isDirectory(dir)) {
try (Stream<Path> list = Files.list(dir)) {
var result = new LinkedHashMap<String, Map<String, Path>>();
list.forEach(file -> {
if (Files.isRegularFile(file)) {
String fileName = file.getFileName().toString();
if (!fileName.startsWith(baseName))
return;
String ext = StringUtils.substringAfterLast(fileName, '.');
if (!exts.contains(ext))
return;
String languageKey;
int defaultFileNameLength = baseName.length() + ext.length() + 1;
if (fileName.length() == defaultFileNameLength)
languageKey = DEFAULT_LANGUAGE_KEY;
else if (fileName.length() > defaultFileNameLength + 1 && fileName.charAt(baseName.length()) == '_')
languageKey = fileName.substring(baseName.length() + 1, fileName.length() - ext.length() - 1)
.replace('_', '-');
else
return;
result.computeIfAbsent(languageKey, key -> new HashMap<>())
.put(ext, file);
}
});
return result;
} catch (IOException e) {
LOG.warning("Failed to list files in directory " + dir, e);
}
}
return Map.of();
}
// ---
public static boolean isEnglish(Locale locale) {
return locale.getLanguage().equals("en") || locale.getLanguage().isEmpty();
}
public static final Set<String> CHINESE_TRADITIONAL_REGIONS = Set.of("TW", "HK", "MO");
public static final Set<String> CHINESE_LATN_VARIANTS = Set.of("pinyin", "wadegile", "tongyong");
public static final Set<String> CHINESE_LANGUAGES = Set.of(
"zh",
"zho", "cmn", "lzh", "cdo", "cjy", "cpx", "czh",
"gan", "hak", "hsn", "mnp", "nan", "wuu", "yue"
);
public static boolean isChinese(Locale locale) {
return CHINESE_LANGUAGES.contains(locale.getLanguage());
}
private LocaleUtils() {
}
}
@@ -0,0 +1,103 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
@JsonAdapter(LocalizedText.Adapter.class)
public final class LocalizedText {
private final @Nullable String value;
private final @Nullable Map<String, String> localizedValues;
public LocalizedText(String value) {
this.value = value;
this.localizedValues = null;
}
public LocalizedText(@NotNull Map<String, String> localizedValues) {
this.value = null;
this.localizedValues = Objects.requireNonNull(localizedValues);
}
public String getText(@NotNull List<Locale> candidates) {
if (localizedValues != null) {
for (Locale locale : candidates) {
String value = localizedValues.get(LocaleUtils.toLanguageKey(locale));
if (value != null)
return value;
}
return null;
} else
return value;
}
static final class Adapter extends TypeAdapter<LocalizedText> {
@Override
public LocalizedText read(JsonReader jsonReader) throws IOException {
JsonToken nextToken = jsonReader.peek();
if (nextToken == JsonToken.NULL) {
return null;
} else if (nextToken == JsonToken.STRING) {
return new LocalizedText(jsonReader.nextString());
} else if (nextToken == JsonToken.BEGIN_OBJECT) {
LinkedHashMap<String, String> localizedValues = new LinkedHashMap<>();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
String value = jsonReader.nextString();
localizedValues.put(name, value);
}
jsonReader.endObject();
return new LocalizedText(localizedValues);
} else {
throw new JsonSyntaxException("Unexpected token " + nextToken);
}
}
@Override
public void write(JsonWriter jsonWriter, LocalizedText localizedText) throws IOException {
if (localizedText == null) {
jsonWriter.nullValue();
} else if (localizedText.localizedValues != null) {
jsonWriter.beginObject();
for (var entry : localizedText.localizedValues.entrySet()) {
jsonWriter.name(entry.getKey());
jsonWriter.value(entry.getValue());
}
jsonWriter.endObject();
} else {
jsonWriter.value(localizedText.value);
}
}
}
}
@@ -18,6 +18,7 @@
package org.jackhuang.hmcl.util.io;
import org.jackhuang.hmcl.util.Pair;
import org.jackhuang.hmcl.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.*;
@@ -45,10 +46,33 @@ public final class NetworkUtils {
private NetworkUtils() {
}
public static boolean isLoopbackAddress(URI uri) {
String host = uri.getHost();
if (StringUtils.isBlank(host))
return false;
try {
InetAddress addr = InetAddress.getByName(host);
return addr.isLoopbackAddress();
} catch (UnknownHostException e) {
return false;
}
}
public static boolean isHttpUri(URI uri) {
return "http".equals(uri.getScheme()) || "https".equals(uri.getScheme());
}
public static String addHttpsIfMissing(String url) {
if (Pattern.compile("^(?<scheme>[a-zA-Z][a-zA-Z0-9+.-]*)://").matcher(url).find())
return url;
if (url.startsWith("//"))
return "https:" + url;
else
return "https://" + url;
}
public static String withQuery(String baseUrl, Map<String, String> params) {
StringBuilder sb = new StringBuilder(baseUrl);
boolean first = true;
@@ -112,7 +136,12 @@ public final class NetworkUtils {
}
public static URLConnection createConnection(URI uri) throws IOException {
URLConnection connection = uri.toURL().openConnection();
URLConnection connection;
try {
connection = uri.toURL().openConnection();
} catch (IllegalArgumentException | MalformedURLException e) {
throw new IOException(e);
}
connection.setConnectTimeout(TIME_OUT);
connection.setReadTimeout(TIME_OUT);
if (connection instanceof HttpURLConnection) {
@@ -0,0 +1,71 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.javafx;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakListener;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
/// @author Glavo
public final class DirtyTracker {
private final Set<Observable> dirty = Collections.newSetFromMap(new IdentityHashMap<>());
private final Listener listener = new Listener(this);
public void track(Observable observable) {
if (!dirty.contains(observable))
observable.addListener(listener);
}
public boolean isDirty(Observable observable) {
return dirty.contains(observable);
}
public void markDirty(Observable observable) {
observable.removeListener(listener);
dirty.add(observable);
}
private static final class Listener implements InvalidationListener, WeakListener {
private final WeakReference<DirtyTracker> trackerReference;
public Listener(DirtyTracker trackerReference) {
this.trackerReference = new WeakReference<>(trackerReference);
}
@Override
public boolean wasGarbageCollected() {
return trackerReference.get() == null;
}
@Override
public void invalidated(Observable observable) {
observable.removeListener(this);
DirtyTracker tracker = trackerReference.get();
if (tracker != null)
tracker.markDirty(observable);
}
}
}
@@ -306,12 +306,39 @@ public enum OperatingSystem {
if (name.isEmpty())
return false;
// . and .. have special meaning on all platforms
if (name.equals("."))
return false;
// \0 and / are forbidden on all platforms
if (name.indexOf('/') != -1 || name.indexOf('\0') != -1)
if (name.equals(".") || name.equals(".."))
return false;
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
int codePoint;
if (Character.isSurrogate(ch)) {
if (!Character.isHighSurrogate(ch))
return false;
if (i == name.length() - 1)
return false;
char ch2 = name.charAt(++i);
if (!Character.isLowSurrogate(ch2))
return false;
codePoint = Character.toCodePoint(ch, ch2);
} else {
codePoint = ch;
}
if (!Character.isValidCodePoint(codePoint)
|| Character.isISOControl(codePoint)
|| codePoint == '/' || codePoint == '\0'
// Unicode replacement character
|| codePoint == 0xfffd
// Not Unicode character
|| codePoint == 0xfffe || codePoint == 0xffff)
return false;
}
if (CURRENT_OS == WINDOWS) { // Windows only
char lastChar = name.charAt(name.length() - 1);
// filenames ending in dot are not valid
@@ -17,6 +17,7 @@
*/
package org.jackhuang.hmcl.util.versioning;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
@@ -135,7 +136,7 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
return value;
}
static final class Old extends GameVersionNumber {
public static final class Old extends GameVersionNumber {
static Old parse(String value) {
Type type;
int prefixLength = 1;
@@ -211,16 +212,16 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
}
}
static final class Release extends GameVersionNumber {
public static final class Release extends GameVersionNumber {
private static final Pattern PATTERN = Pattern.compile("1\\.(?<minor>[0-9]+)(\\.(?<patch>[0-9]+))?((?<eaType>(-[a-zA-Z]+| Pre-Release ))(?<eaVersion>.+))?");
static final int TYPE_GA = Integer.MAX_VALUE;
public static final int TYPE_GA = Integer.MAX_VALUE;
static final int TYPE_UNKNOWN = 0;
static final int TYPE_EXP = 1;
static final int TYPE_PRE = 2;
static final int TYPE_RC = 3;
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_EXP = 1;
public static final int TYPE_PRE = 2;
public static final int TYPE_RC = 3;
static final Release ZERO = new Release("0.0", 0, 0, 0, TYPE_GA, VersionNumber.ZERO);
@@ -259,6 +260,7 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
private final int minor;
private final int patch;
@MagicConstant(intValues = {TYPE_GA, TYPE_UNKNOWN, TYPE_EXP, TYPE_PRE, TYPE_RC})
private final int eaType;
private final VersionNumber eaVersion;
@@ -326,6 +328,26 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
throw new AssertionError(other.getClass());
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
public int getEaType() {
return eaType;
}
public VersionNumber getEaVersion() {
return eaVersion;
}
@Override
public int hashCode() {
return Objects.hash(major, minor, patch, eaType, eaVersion);
@@ -340,7 +362,7 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
}
}
static final class Snapshot extends GameVersionNumber {
public static final class Snapshot extends GameVersionNumber {
static Snapshot parse(String value) {
if (value.length() != 6 || value.charAt(2) != 'w')
throw new IllegalArgumentException(value);
@@ -391,6 +413,18 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
throw new AssertionError(other.getClass());
}
public int getYear() {
return (intValue >> 16) & 0xff;
}
public int getWeek() {
return (intValue >> 8) & 0xff;
}
public char getSuffix() {
return (char) (intValue & 0xff);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -405,7 +439,7 @@ public abstract class GameVersionNumber implements Comparable<GameVersionNumber>
}
}
static final class Special extends GameVersionNumber {
public static final class Special extends GameVersionNumber {
private VersionNumber versionNumber;
private GameVersionNumber prev;
@@ -0,0 +1,177 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.i18n;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Glavo
*/
public final class LocaleUtilsTest {
private static void assertCandidateLocales(String languageTag, List<String> candidateLocales) {
assertEquals(candidateLocales,
LocaleUtils.getCandidateLocales(Locale.forLanguageTag(languageTag))
.stream()
.map(Locale::toLanguageTag)
.collect(Collectors.toList()));
}
@Test
public void testGetCandidateLocales() {
assertCandidateLocales("zh", List.of("zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-CN", List.of("zh-Hans-CN", "zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-SG", List.of("zh-Hans-SG", "zh-Hans", "zh-SG", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-MY", List.of("zh-Hans-MY", "zh-Hans", "zh-MY", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-US", List.of("zh-Hans-US", "zh-Hans", "zh-US", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-TW", List.of("zh-Hant-TW", "zh-Hant", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("zh-HK", List.of("zh-Hant-HK", "zh-Hant", "zh-HK", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("zh-MO", List.of("zh-Hant-MO", "zh-Hant", "zh-MO", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("zh-Hans", List.of("zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-Hant", List.of("zh-Hant", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("zh-Hans-US", List.of("zh-Hans-US", "zh-Hans", "zh-US", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-Hant-CN", List.of("zh-Hant-CN", "zh-Hant", "zh-CN", "zh-TW", "zh", "und"));
assertCandidateLocales("zh-Hans-TW", List.of("zh-Hans-TW", "zh-Hans", "zh-TW", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-Latn", List.of("zh-Latn", "zh", "zh-CN", "und"));
assertCandidateLocales("zh-Latn-CN", List.of("zh-Latn-CN", "zh-Latn", "zh-CN", "zh", "und"));
assertCandidateLocales("zh-pinyin", List.of("zh-Latn-pinyin", "zh-Latn", "zh-pinyin", "zh", "zh-CN", "und"));
assertCandidateLocales("lzh", List.of("lzh-Hant", "lzh", "zh-Hant", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("lzh-Hant", List.of("lzh-Hant", "lzh", "zh-Hant", "zh-TW", "zh", "zh-CN", "und"));
assertCandidateLocales("lzh-Hans", List.of("lzh-Hans", "lzh", "zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("cmn", List.of("cmn-Hans", "cmn", "zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("cmn-Hans", List.of("cmn-Hans", "cmn", "zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("yue", List.of("yue-Hans", "yue", "zh-Hans", "zh-CN", "zh", "und"));
assertCandidateLocales("ja", List.of("ja", "und"));
assertCandidateLocales("ja-JP", List.of("ja-JP", "ja", "und"));
assertCandidateLocales("en", List.of("en", "und"));
assertCandidateLocales("und", List.of("en", "und"));
}
@Test
public void testIsChinese() {
assertTrue(LocaleUtils.isChinese(Locale.CHINESE));
assertTrue(LocaleUtils.isChinese(Locale.SIMPLIFIED_CHINESE));
assertTrue(LocaleUtils.isChinese(Locale.TRADITIONAL_CHINESE));
assertTrue(LocaleUtils.isChinese(LocaleUtils.LOCALE_ZH_HANS));
assertTrue(LocaleUtils.isChinese(LocaleUtils.LOCALE_ZH_HANT));
assertTrue(LocaleUtils.isChinese(Locale.forLanguageTag("lzh")));
assertTrue(LocaleUtils.isChinese(Locale.forLanguageTag("cmn")));
assertTrue(LocaleUtils.isChinese(Locale.forLanguageTag("cmn-Hans")));
assertTrue(LocaleUtils.isChinese(Locale.forLanguageTag("yue")));
assertFalse(LocaleUtils.isChinese(Locale.ROOT));
assertFalse(LocaleUtils.isChinese(Locale.ENGLISH));
assertFalse(LocaleUtils.isChinese(Locale.JAPANESE));
assertFalse(LocaleUtils.isChinese(Locale.forLanguageTag("es")));
assertFalse(LocaleUtils.isChinese(Locale.forLanguageTag("ru")));
assertFalse(LocaleUtils.isChinese(Locale.forLanguageTag("uk")));
}
@Test
public void testGetScript() {
assertEquals("Hans", LocaleUtils.getScript(Locale.CHINESE));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("zh")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("zh-Hans")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("zh-Hans-US")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("zh-SG")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("zh-MY")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("cmn")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("cmn-Hans")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("cmn-CN")));
assertEquals("Hans", LocaleUtils.getScript(Locale.forLanguageTag("lzh-Hans")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("zh-Hant")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("zh-TW")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("zh-HK")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("zh-MO")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("cmn-Hant")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("lzh")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("lzh-Hant")));
assertEquals("Hant", LocaleUtils.getScript(Locale.forLanguageTag("lzh-CN")));
assertEquals("Latn", LocaleUtils.getScript(Locale.forLanguageTag("zh-pinyin")));
}
@Test
public void testFindAllLocalizedFiles() throws IOException {
try (var testFs = Jimfs.newFileSystem(Configuration.unix())) {
Path testDir = testFs.getPath("/test-dir");
Files.createDirectories(testDir);
Files.createFile(testDir.resolve("meow.json"));
Files.createFile(testDir.resolve("meow_zh.json"));
Files.createFile(testDir.resolve("meow_zh_CN.json"));
Files.createFile(testDir.resolve("meow_zh_Hans.json"));
Files.createFile(testDir.resolve("meow_zh_Hans_CN.json"));
Files.createFile(testDir.resolve("meow_en.json"));
Files.createFile(testDir.resolve("meow_en.toml"));
Files.createFile(testDir.resolve("meow_.json"));
Files.createFile(testDir.resolve("meowmeow.json"));
Files.createFile(testDir.resolve("woem.json"));
Files.createFile(testDir.resolve("meow.txt"));
Files.createDirectories(testDir.resolve("subdir"));
Files.createDirectories(testDir.resolve("meow_en_US.json"));
Path notExistsDir = testFs.getPath("/not-exists");
Path emptyDir = testFs.getPath("/empty");
Files.createDirectories(emptyDir);
assertEquals(Map.of(), LocaleUtils.findAllLocalizedFiles(emptyDir, "meow", "json"));
assertEquals(Map.of(), LocaleUtils.findAllLocalizedFiles(emptyDir, "meow", Set.of("json", "toml")));
assertEquals(Map.of(), LocaleUtils.findAllLocalizedFiles(notExistsDir, "meow", "json"));
assertEquals(Map.of(), LocaleUtils.findAllLocalizedFiles(notExistsDir, "meow", Set.of("json", "toml")));
assertEquals(Map.of(
"default", testDir.resolve("meow.json"),
"zh", testDir.resolve("meow_zh.json"),
"zh-CN", testDir.resolve("meow_zh_CN.json"),
"zh-Hans", testDir.resolve("meow_zh_Hans.json"),
"zh-Hans-CN", testDir.resolve("meow_zh_Hans_CN.json"),
"en", testDir.resolve("meow_en.json")
),
LocaleUtils.findAllLocalizedFiles(testDir, "meow", "json"));
assertEquals(Map.of(
"default", Map.of("json", testDir.resolve("meow.json")),
"zh", Map.of("json", testDir.resolve("meow_zh.json")),
"zh-CN", Map.of("json", testDir.resolve("meow_zh_CN.json")),
"zh-Hans", Map.of("json", testDir.resolve("meow_zh_Hans.json")),
"zh-Hans-CN", Map.of("json", testDir.resolve("meow_zh_Hans_CN.json")),
"en", Map.of(
"json", testDir.resolve("meow_en.json"),
"toml", testDir.resolve("meow_en.toml")
)
),
LocaleUtils.findAllLocalizedFiles(testDir, "meow", Set.of("json", "toml")));
}
}
}
@@ -19,17 +19,31 @@ package org.jackhuang.hmcl.util.io;
import org.junit.jupiter.api.Test;
import java.net.URI;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.jackhuang.hmcl.util.io.NetworkUtils.encodeLocation;
import static org.jackhuang.hmcl.util.io.NetworkUtils.getCharsetFromContentType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.jackhuang.hmcl.util.io.NetworkUtils.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Glavo
*/
public class NetworkUtilsTest {
@Test
public void testIsLoopbackAddress() {
assertTrue(isLoopbackAddress(URI.create("https://127.0.0.1/test")));
assertTrue(isLoopbackAddress(URI.create("https://127.0.0.1:8080/test")));
assertTrue(isLoopbackAddress(URI.create("https://localhost/test")));
assertTrue(isLoopbackAddress(URI.create("https://localhost:8080/test")));
assertTrue(isLoopbackAddress(URI.create("https://[::1]/test")));
assertTrue(isLoopbackAddress(URI.create("https://[::1]:8080/test")));
assertFalse(isLoopbackAddress(URI.create("https://www.example.com/test")));
assertFalse(isLoopbackAddress(URI.create("https://www.example.com:8080/test")));
}
@Test
public void testEncodeLocation() {
assertEquals("https://github.com", encodeLocation("https://github.com"));
@@ -0,0 +1,55 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.util.platform;
import org.junit.jupiter.api.Test;
import static org.jackhuang.hmcl.util.platform.OperatingSystem.isNameValid;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Glavo
*/
public final class OperatingSystemTest {
@Test
public void testIsNameValid() {
assertTrue(isNameValid("example"));
assertTrue(isNameValid("example.zip"));
assertTrue(isNameValid("example.tar.gz"));
assertTrue(isNameValid("\uD83D\uDE00"));
assertTrue(isNameValid("a\uD83D\uDE00b"));
assertFalse(isNameValid("."));
assertFalse(isNameValid(".."));
assertFalse(isNameValid("exam\0ple"));
assertFalse(isNameValid("example/0"));
// Test for invalid surrogate pair
assertFalse(isNameValid("\uD83D"));
assertFalse(isNameValid("\uDE00"));
assertFalse(isNameValid("\uDE00\uD83D"));
assertFalse(isNameValid("\uD83D\uD83D"));
assertFalse(isNameValid("a\uD83D"));
assertFalse(isNameValid("a\uDE00"));
assertFalse(isNameValid("a\uDE00\uD83D"));
assertFalse(isNameValid("a\uD83Db"));
assertFalse(isNameValid("a\uDE00b"));
assertFalse(isNameValid("a\uDE00\uD83Db"));
}
}
+7 -52
View File
@@ -1,3 +1,5 @@
import org.jackhuang.hmcl.gradle.docs.UpdateDocuments
plugins {
id("checkstyle")
}
@@ -57,58 +59,11 @@ subprojects {
}
}
tasks.register("checkTranslations") {
doLast {
val hmclLangDir = file("HMCL/src/main/resources/assets/lang")
val en = java.util.Properties().apply {
hmclLangDir.resolve("I18N.properties").bufferedReader().use { load(it) }
}
val zh = java.util.Properties().apply {
hmclLangDir.resolve("I18N_zh.properties").bufferedReader().use { load(it) }
}
val zh_CN = java.util.Properties().apply {
hmclLangDir.resolve("I18N_zh_CN.properties").bufferedReader().use { load(it) }
}
var success = true
zh_CN.forEach {
if (!en.containsKey(it.key)) {
project.logger.warn("I18N.properties missing key '${it.key}'")
success = false
}
}
zh_CN.forEach {
if (!zh.containsKey(it.key)) {
project.logger.warn("I18N_zh.properties missing key '${it.key}'")
success = false
}
}
zh_CN.forEach {
if (it.value.toString().contains("帐户")) {
project.logger.warn("The misspelled '帐户' in '${it.key}' should be replaced by '账户'")
success = false
}
}
zh_CN.forEach {
if (it.value.toString().contains("其它")) {
project.logger.warn("The misspelled '其它' in '${it.key}' should be replaced by '其他'")
success = false
}
}
if (!success) {
throw GradleException("Part of the translation is missing")
}
}
}
org.jackhuang.hmcl.gradle.javafx.JavaFXUtils.register(rootProject)
defaultTasks("clean", "build")
tasks.register<UpdateDocuments>("updateDocuments") {
documentsDir.set(layout.projectDirectory.dir("docs"))
}
+2 -2
View File
@@ -8,6 +8,6 @@ dependencies {
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
@@ -0,0 +1,180 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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;
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.TaskAction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.function.BiConsumer;
/// @author Glavo
public abstract class CheckTranslations extends DefaultTask {
private static final Logger LOGGER = Logging.getLogger(CheckTranslations.class);
@InputFile
public abstract RegularFileProperty getEnglishFile();
@InputFile
public abstract RegularFileProperty getSimplifiedChineseFile();
@InputFile
public abstract RegularFileProperty getTraditionalChineseFile();
@InputFile
public abstract RegularFileProperty getClassicalChineseFile();
@TaskAction
public void run() throws IOException {
Checker checker = new Checker();
var english = new PropertiesFile(getEnglishFile());
var simplifiedChinese = new PropertiesFile(getSimplifiedChineseFile());
var traditionalChinese = new PropertiesFile(getTraditionalChineseFile());
var classicalChinese = new PropertiesFile(getClassicalChineseFile());
simplifiedChinese.forEach((key, value) -> {
checker.checkKeyExists(english, key);
checker.checkKeyExists(traditionalChinese, key);
checker.checkMisspelled(simplifiedChinese, key, value, "账户", "帐户");
checker.checkMisspelled(simplifiedChinese, key, value, "其他", "其它");
});
classicalChinese.forEach((key, value) -> {
checker.checkMisspelled(classicalChinese, key, value, "綫", "線");
checker.checkMisspelled(classicalChinese, key, value, "爲", "為");
checker.checkMisspelled(classicalChinese, key, value, "啟", "啓");
});
checker.check();
}
private static final class PropertiesFile {
final Path path;
final Properties properties = new Properties();
PropertiesFile(RegularFileProperty property) throws IOException {
this(property.getAsFile().get().toPath().toAbsolutePath().normalize());
}
PropertiesFile(Path path) throws IOException {
this.path = path;
try (var reader = Files.newBufferedReader(path)) {
properties.load(reader);
}
}
public String getFileName() {
return path.getFileName().toString();
}
public void forEach(BiConsumer<String, String> consumer) {
properties.forEach((key, value) -> consumer.accept(key.toString(), value.toString()));
}
}
private static final class Checker {
private final Map<PropertiesFile, Map<Class<?>, Set<Problem>>> problems = new LinkedHashMap<>();
private int problemsCount;
public void checkKeyExists(PropertiesFile file, String key) {
if (!file.properties.containsKey(key)) {
onFailure(file, new Problem.MissingKey(key));
}
}
public void checkMisspelled(PropertiesFile file, String key, String value,
String correct, String misspelled) {
if (value.contains(misspelled)) {
onFailure(file, new Problem.Misspelled(correct, misspelled));
}
}
public void onFailure(PropertiesFile file, Problem problem) {
problemsCount++;
problems.computeIfAbsent(file, ignored -> new HashMap<>())
.computeIfAbsent(problem.getClass(), ignored -> new LinkedHashSet<>())
.add(problem);
}
public void check() {
if (problemsCount > 0) {
problems.forEach((file, problems) -> {
problems.values().stream().flatMap(Collection::stream).forEach(problem ->
LOGGER.warn("{}: {}", file.getFileName(), problem.getMessage()));
});
throw new GradleException("Failed to check translations, " + problemsCount + " found problems.");
}
}
}
private static abstract sealed class Problem {
public abstract String getMessage();
private static final class MissingKey extends Problem {
private final String key;
MissingKey(String key) {
this.key = key;
}
@Override
public String getMessage() {
return "missing key '%s'".formatted(key);
}
}
private static final class Misspelled extends Problem {
private final String correct;
private final String misspelled;
Misspelled(String correct, String misspelled) {
this.correct = correct;
this.misspelled = misspelled;
}
@Override
public String getMessage() {
return "misspelled '%s' should be replaced by '%s'".formatted(misspelled, correct);
}
@Override
public int hashCode() {
return misspelled.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Misspelled that && this.misspelled.equals(that.misspelled);
}
}
}
}
@@ -0,0 +1,151 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/// @author Glavo
public record Document(DocumentFileTree directory,
Path file,
String name, DocumentLocale locale,
List<Item> items) {
private static final Pattern MACRO_BEGIN = Pattern.compile(
"<!-- #BEGIN (?<name>\\w+) -->"
);
private static final Pattern MACRO_PROPERTY_LINE = Pattern.compile(
"<!-- #PROPERTY (?<name>\\w+)=(?<value>.*) -->"
);
private static String parsePropertyValue(String value) {
int i = 0;
while (i < value.length()) {
char ch = value.charAt(i);
if (ch == '\\')
break;
i++;
}
if (i == value.length())
return value;
StringBuilder builder = new StringBuilder(value.length());
builder.append(value, 0, i);
for (; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '\\' && i < value.length() - 1) {
char next = value.charAt(++i);
switch (next) {
case 'n' -> builder.append('\n');
case 'r' -> builder.append('\r');
case '\\' -> builder.append('\\');
default -> builder.append(next);
}
} else {
builder.append(ch);
}
}
return builder.toString();
}
static void writePropertyValue(StringBuilder builder, String value) {
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
switch (ch) {
case '\\' -> builder.append("\\\\");
case '\r' -> builder.append("\\r");
case '\n' -> builder.append("\\n");
default -> builder.append(ch);
}
}
}
public static Document load(DocumentFileTree directory, Path file, String name, DocumentLocale locale) throws IOException {
var items = new ArrayList<Item>();
try (var reader = Files.newBufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<!-- #")) {
items.add(new Line(line));
} else {
Matcher matcher = MACRO_BEGIN.matcher(line);
if (!matcher.matches())
throw new IOException("Invalid macro begin line: " + line);
String macroName = matcher.group("name");
String endLine = "<!-- #END " + macroName + " -->";
var properties = new LinkedHashMap<String, List<String>>();
var lines = new ArrayList<String>();
// Handle properties
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<!-- #") || line.equals(endLine))
break;
Matcher propertyMatcher = MACRO_PROPERTY_LINE.matcher(line);
if (propertyMatcher.matches()) {
String propertyName = propertyMatcher.group("name");
String propertyValue = parsePropertyValue(propertyMatcher.group("value"));
properties.computeIfAbsent(propertyName, k -> new ArrayList<>(1))
.add(propertyValue);
} else {
throw new IOException("Invalid macro property line: " + line);
}
}
// Handle lines
if (line != null && !line.equals(endLine)) {
while ((line = reader.readLine()) != null) {
if (line.startsWith("<!-- #"))
break;
lines.add(line);
}
}
if (line == null || !line.equals(endLine))
throw new IOException("Invalid macro end line: " + line);
items.add(new MacroBlock(macroName,
Collections.unmodifiableMap(properties),
Collections.unmodifiableList(lines)));
}
}
}
return new Document(directory, file, name, locale, items);
}
public sealed interface Item {
}
public record MacroBlock(String name, Map<String, List<String>> properties,
List<String> contentLines) implements Item {
}
public record Line(String content) implements Item {
}
}
@@ -0,0 +1,112 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.TreeMap;
/// @author Glavo
public final class DocumentFileTree {
public static DocumentFileTree load(Path dir) throws IOException {
Path documentsDir = dir.toRealPath();
DocumentFileTree rootTree = new DocumentFileTree();
Files.walkFileTree(documentsDir, new SimpleFileVisitor<>() {
@Override
public @NotNull FileVisitResult visitFile(@NotNull Path file, @NotNull BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (fileName.endsWith(".md")) {
DocumentFileTree tree = rootTree.getFileTree(documentsDir.relativize(file.getParent()));
if (tree == null)
throw new AssertionError();
var result = DocumentLocale.parseFileName(fileName.substring(0, fileName.length() - ".md".length()));
tree.getFiles().computeIfAbsent(result.name(), name -> new LocalizedDocument(tree, name))
.getDocuments()
.put(result.locale(), Document.load(tree, file, result.name(), result.locale()));
}
return FileVisitResult.CONTINUE;
}
});
return rootTree;
}
private final @Nullable DocumentFileTree parent;
private final TreeMap<String, DocumentFileTree> children = new TreeMap<>();
private final TreeMap<String, LocalizedDocument> files = new TreeMap<>();
public DocumentFileTree() {
this(null);
}
public DocumentFileTree(@Nullable DocumentFileTree parent) {
this.parent = parent;
}
@Nullable DocumentFileTree getFileTree(Path relativePath) {
if (relativePath.isAbsolute())
throw new IllegalArgumentException(relativePath + " is absolute");
if (relativePath.getNameCount() == 0)
throw new IllegalArgumentException(relativePath + " is empty");
if (relativePath.getNameCount() == 1 && relativePath.getName(0).toString().isEmpty())
return this;
DocumentFileTree current = this;
for (int i = 0; i < relativePath.getNameCount(); i++) {
String name = relativePath.getName(i).toString();
if (name.isEmpty())
throw new IllegalStateException(name + " is empty");
else if (name.equals("."))
continue;
else if (name.equals("..")) {
current = current.parent;
if (current == null)
return null;
} else {
DocumentFileTree finalCurrent = current;
current = current.children.computeIfAbsent(name, ignored -> new DocumentFileTree(finalCurrent));
}
}
return current;
}
public @Nullable DocumentFileTree getParent() {
return parent;
}
public TreeMap<String, DocumentFileTree> getChildren() {
return children;
}
public TreeMap<String, LocalizedDocument> getFiles() {
return files;
}
}
@@ -0,0 +1,118 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import java.util.List;
import java.util.Locale;
/// @author Glavo
public enum DocumentLocale {
ENGLISH(Locale.ENGLISH, "") {
@Override
public List<DocumentLocale> getCandidates() {
return List.of(ENGLISH);
}
},
SIMPLIFIED_CHINESE(Locale.forLanguageTag("zh-Hans"), "zh"),
TRADITIONAL_CHINESE("zh-Hant") {
@Override
public List<DocumentLocale> getCandidates() {
return List.of(TRADITIONAL_CHINESE, SIMPLIFIED_CHINESE, ENGLISH);
}
},
WENYAN("lzh") {
@Override
public String getLanguageDisplayName() {
return TRADITIONAL_CHINESE.getLanguageDisplayName();
}
@Override
public String getSubLanguageDisplayName() {
return "文言";
}
@Override
public List<DocumentLocale> getCandidates() {
return List.of(WENYAN, TRADITIONAL_CHINESE, SIMPLIFIED_CHINESE, ENGLISH);
}
},
JAPANESE("ja"),
SPANISH("es"),
RUSSIAN("ru"),
UKRAINIAN("uk"),
;
public record LocaleAndName(DocumentLocale locale, String name) {
}
public static LocaleAndName parseFileName(String fileNameWithoutExtension) {
for (DocumentLocale locale : values()) {
String suffix = locale.getFileNameSuffix();
if (suffix.isEmpty())
continue;
if (fileNameWithoutExtension.endsWith(suffix))
return new LocaleAndName(locale, fileNameWithoutExtension.substring(0, fileNameWithoutExtension.length() - locale.getFileNameSuffix().length()));
}
return new LocaleAndName(ENGLISH, fileNameWithoutExtension);
}
private final Locale locale;
private final String languageTag;
private final String fileNameSuffix;
DocumentLocale(String languageTag) {
this(Locale.forLanguageTag(languageTag), languageTag);
}
DocumentLocale(Locale locale, String languageTag) {
this.locale = locale;
this.languageTag = languageTag;
this.fileNameSuffix = languageTag.isEmpty() ? "" : "_" + languageTag.replace('-', '_');
}
public String getLanguageDisplayName() {
return locale.getDisplayLanguage(locale);
}
public String getSubLanguageDisplayName() {
boolean hasScript = !locale.getScript().isEmpty();
boolean hasRegion = !locale.getCountry().isEmpty();
if (hasScript && hasRegion)
throw new AssertionError("Unsupported locale: " + locale);
if (hasScript)
return locale.getDisplayScript(locale);
if (hasRegion)
return locale.getDisplayCountry(locale);
return "";
}
public Locale getLocale() {
return locale;
}
public String getFileNameSuffix() {
return fileNameSuffix;
}
public List<DocumentLocale> getCandidates() {
return List.of(this, ENGLISH);
}
}
@@ -0,0 +1,62 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import java.util.EnumMap;
/// @author Glavo
public final class LocalizedDocument {
private final DocumentFileTree directory;
private final String name;
private final EnumMap<DocumentLocale, Document> documents = new EnumMap<>(DocumentLocale.class);
public LocalizedDocument(DocumentFileTree directory, String name) {
this.directory = directory;
this.name = name;
}
public String getName() {
return name;
}
public DocumentFileTree getDirectory() {
return directory;
}
public EnumMap<DocumentLocale, Document> getDocuments() {
return documents;
}
@Override
public boolean equals(Object obj) {
return obj instanceof LocalizedDocument that
&& this.documents.equals(that.documents);
}
@Override
public int hashCode() {
return documents.hashCode();
}
@Override
public String toString() {
return "LocalizedDocument[" +
"files=" + documents + ']';
}
}
@@ -0,0 +1,144 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import javax.print.Doc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
/// @author Glavo
public enum MacroProcessor {
LANGUAGE_SWITCHER {
private static <T> boolean containsIdentity(List<T> list, T element) {
for (T t : list) {
if (t == element)
return true;
}
return false;
}
@Override
public void apply(Document document,
Document.MacroBlock macroBlock,
StringBuilder outputBuilder) throws IOException {
LocalizedDocument localized = document.directory().getFiles().get(document.name());
if (localized == null || localized.getDocuments().isEmpty())
throw new AssertionError("Document " + document.name() + " does not exist");
MacroProcessor.writeBegin(outputBuilder, macroBlock);
if (localized.getDocuments().size() > 1) {
var languageToDocs = new LinkedHashMap<String, List<Document>>();
for (DocumentLocale locale : DocumentLocale.values()) {
Document targetDoc = localized.getDocuments().get(locale);
if (targetDoc != null) {
languageToDocs.computeIfAbsent(locale.getLanguageDisplayName(), name -> new ArrayList<>(1))
.add(targetDoc);
}
}
boolean firstLanguage = true;
for (var entry : languageToDocs.entrySet()) {
if (firstLanguage)
firstLanguage = false;
else
outputBuilder.append(" | ");
String languageName = entry.getKey();
List<Document> targetDocs = entry.getValue();
boolean containsCurrent = containsIdentity(targetDocs, document);
if (targetDocs.size() == 1) {
if (containsCurrent)
outputBuilder.append("**").append(languageName).append("**");
else
outputBuilder.append("[").append(languageName).append("](").append(targetDocs.get(0).file().getFileName()).append(")");
} else {
if (containsCurrent)
outputBuilder.append("**").append(languageName).append("**");
else
outputBuilder.append(languageName);
outputBuilder.append(" (");
boolean isFirst = true;
for (Document targetDoc : targetDocs) {
if (isFirst)
isFirst = false;
else
outputBuilder.append(", ");
String subLanguage = targetDoc.locale().getSubLanguageDisplayName();
if (targetDoc == document) {
outputBuilder.append("**").append(subLanguage).append("**");
} else {
outputBuilder.append('[').append(subLanguage).append("](").append(targetDoc.file().getFileName()).append(")");
}
}
outputBuilder.append(")");
}
}
outputBuilder.append('\n');
}
MacroProcessor.writeEnd(outputBuilder, macroBlock);
}
},
BLOCK {
@Override
public void apply(Document document, Document.MacroBlock macroBlock, StringBuilder outputBuilder) throws IOException {
MacroProcessor.writeBegin(outputBuilder, macroBlock);
MacroProcessor.writeProperties(outputBuilder, macroBlock);
for (String line : macroBlock.contentLines()) {
outputBuilder.append(line).append('\n');
}
MacroProcessor.writeEnd(outputBuilder, macroBlock);
}
};
private static void writeBegin(StringBuilder builder, Document.MacroBlock macroBlock) throws IOException {
builder.append("<!-- #BEGIN ");
builder.append(macroBlock.name());
builder.append(" -->\n");
}
private static void writeEnd(StringBuilder builder, Document.MacroBlock macroBlock) throws IOException {
builder.append("<!-- #END ");
builder.append(macroBlock.name());
builder.append(" -->\n");
}
private static void writeProperties(StringBuilder builder, Document.MacroBlock macroBlock) throws IOException {
macroBlock.properties().forEach((key, values) -> {
for (String value : values) {
builder.append("<!-- #PROPERTY ").append(key).append('=');
Document.writePropertyValue(builder, value);
builder.append(" -->\n");
}
});
}
public abstract void apply(Document document,
Document.MacroBlock macroBlock,
StringBuilder outputBuilder) throws IOException;
}
@@ -0,0 +1,131 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <huanghongxun2008@126.com> 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.docs;
import org.gradle.api.DefaultTask;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.TaskAction;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Pattern;
/// @author Glavo
public abstract class UpdateDocuments extends DefaultTask {
@InputDirectory
public abstract DirectoryProperty getDocumentsDir();
// ---
private static final Pattern LINK_PATTERN = Pattern.compile(
"(?<=]\\()[a-zA-Z0-9_\\-./]+\\.md(?=\\))"
);
private void processLine(StringBuilder outputBuilder, String line, Document document) {
outputBuilder.append(LINK_PATTERN.matcher(line).replaceAll(matchResult -> {
String rawLink = matchResult.group();
String[] splitPath = rawLink.split("/");
if (splitPath.length == 0)
return rawLink;
String fileName = splitPath[splitPath.length - 1];
if (!fileName.endsWith(".md"))
return rawLink;
DocumentFileTree current = document.directory();
for (int i = 0; i < splitPath.length - 1; i++) {
String name = splitPath[i];
switch (name) {
case "" -> {
return rawLink;
}
case "." -> {
continue;
}
case ".." -> {
current = current.getParent();
if (current == null)
return rawLink;
}
default -> {
current = current.getChildren().get(name);
if (current == null)
return rawLink;
}
}
}
DocumentLocale.LocaleAndName currentLocaleAndName = DocumentLocale.parseFileName(fileName.substring(0, fileName.length() - ".md".length()));
LocalizedDocument localizedDocument = current.getFiles().get(currentLocaleAndName.name());
if (localizedDocument != null) {
List<DocumentLocale> candidateLocales = document.locale().getCandidates();
for (DocumentLocale candidateLocale : candidateLocales) {
if (candidateLocale == currentLocaleAndName.locale())
return rawLink;
Document targetDoc = localizedDocument.getDocuments().get(candidateLocale);
if (targetDoc != null) {
splitPath[splitPath.length - 1] = targetDoc.file().getFileName().toString();
return String.join("/", splitPath);
}
}
}
return rawLink;
})).append('\n');
}
private void updateDocument(Document document) throws IOException {
StringBuilder outputBuilder = new StringBuilder(8192);
for (Document.Item item : document.items()) {
if (item instanceof Document.Line line) {
processLine(outputBuilder, line.content(), document);
} else if (item instanceof Document.MacroBlock macro) {
var processor = MacroProcessor.valueOf(macro.name());
processor.apply(document, macro, outputBuilder);
} else
throw new IllegalArgumentException("Unknown item type: " + item.getClass());
}
Files.writeString(document.file(), outputBuilder.toString());
}
private void processDocuments(DocumentFileTree tree) throws IOException {
for (LocalizedDocument localizedDocument : tree.getFiles().values()) {
for (Document document : localizedDocument.getDocuments().values()) {
updateDocument(document);
}
}
for (DocumentFileTree subTree : tree.getChildren().values()) {
processDocuments(subTree);
}
}
@TaskAction
public void run() throws IOException {
Path rootDir = getDocumentsDir().get().getAsFile().toPath();
processDocuments(DocumentFileTree.load(rootDir));
}
}
+4 -2
View File
@@ -1,6 +1,8 @@
# Platform Support Status
**English** | [简体中文](PLATFORM_cn.md) | [繁體中文](PLATFORM_tw.md)
<!-- #BEGIN LANGUAGE_SWITCHER -->
**English** | 中文 ([简体](PLATFORM_zh.md), [繁體](PLATFORM_zh_Hant.md))
<!-- #END LANGUAGE_SWITCHER -->
| | Windows | Linux | macOS | FreeBSD |
|----------------------------|:--------------------------------------------------|:---------------------------|:------------------------------------------------------------------------|:---------------------------|
@@ -35,4 +37,4 @@ Legend:
* `/`: Not applicable.
We have no plans to support these platforms at this time, mainly because we do not have the equipment to test them.
If you can help us adapt, please file a support request via GitHub Issue.
If you can help us adapt, please file a support request via GitHub Issue.
+4 -2
View File
@@ -1,6 +1,8 @@
# 平台支持状态
[English](PLATFORM.md) | **简体中文** | [繁體中文](PLATFORM_tw.md)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](PLATFORM.md) | **中文** (**简体**, [繁體](PLATFORM_zh_Hant.md))
<!-- #END LANGUAGE_SWITCHER -->
| | Windows | Linux | macOS | FreeBSD |
|----------------------------|:--------------------------------------------------|:---------------------------|:-----------------------------------------------------------------------|:--------------------------|
@@ -35,4 +37,4 @@
* `/`: 不支持的平台
我们目前还没有打算支持这些平台,主要是因为我们没有测试这些平台的设备。
如果你能帮助我们进行测试,请通过提交 Issue 提出支持请求。
如果你能帮助我们进行测试,请通过提交 Issue 提出支持请求。
+4 -2
View File
@@ -1,6 +1,8 @@
# 平臺支援狀態
[English](PLATFORM.md) | [简体中文](PLATFORM_cn.md) | **繁體中文**
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](PLATFORM.md) | **中文** ([简体](PLATFORM_zh.md), **繁體**)
<!-- #END LANGUAGE_SWITCHER -->
| | Windows | Linux | macOS | FreeBSD |
|----------------------------|:--------------------------------------------------|:---------------------------|:-----------------------------------------------------------------------|:--------------------------|
@@ -35,4 +37,4 @@
* `/`: 不支援的平臺
我們目前還沒有打算支援這些平臺,主要是因為我們沒有測試這些平臺的裝置。
如果你能幫助我們進行測試,請透過提交 Issue 提出支援請求。
如果你能幫助我們進行測試,請透過提交 Issue 提出支援請求。
+5 -4
View File
@@ -1,4 +1,4 @@
# ⛏ Hello Minecraft! Launcher 💎
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
@@ -6,13 +6,15 @@
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
**English** | [简体中文](README_cn.md) | [繁體中文](README_tw.md)
<!-- #BEGIN LANGUAGE_SWITCHER -->
**English** | 中文 ([简体](README_zh.md), [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | [日本語](README_ja.md) | [español](README_es.md) | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## Introduction
HMCL is an open-source, cross-platform Minecraft launcher that supports Mod Management, Game Customizing, ModLoader Installing (Forge, NeoForge, Fabric, Quilt, LiteLoader, and OptiFine), Modpack Creating, UI Customization, and more.
HMCL has amazing cross-platform capabilities. Not only does it run on different operating systems like Windows, Linux, and macOS, but it also supports various CPU architectures such as x86, ARM, RISC-V, MIPS, and LoongArch. You can easily enjoy Minecraft across different platforms through HMCL.
HMCL has amazing cross-platform capabilities. Not only does it run on different operating systems like Windows, Linux, macOS, and FreeBSD, but it also supports various CPU architectures such as x86, ARM, RISC-V, MIPS, and LoongArch. You can easily enjoy Minecraft across different platforms through HMCL.
For systems and CPU architectures supported by HMCL, please refer to [this table](PLATFORM.md).
@@ -42,7 +44,6 @@ If you want to submit a pull request, here are some requirements:
* IDE: IntelliJ IDEA
* Compiler: Java 17+
* Do NOT modify `gradle` files
### Compilation
+65
View File
@@ -0,0 +1,65 @@
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
![Stars](https://img.shields.io/github/stars/HMCL-dev/HMCL?style=flat)
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | 中文 ([简体](README_zh.md), [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | [日本語](README_ja.md) | **español** | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## Introducción
HMCL es un lanzador de Minecraft de código abierto y multiplataforma que admite la gestión de mods, personalización del juego, instalación de ModLoaders (Forge, NeoForge, Fabric, Quilt, LiteLoader y OptiFine), creación de modpacks, personalización de la interfaz de usuario y más.
HMCL tiene increíbles capacidades multiplataforma. No solo funciona en diferentes sistemas operativos como Windows, Linux, macOS y FreeBSD, sino que también es compatible con varias arquitecturas de CPU como x86, ARM, RISC-V, MIPS y LoongArch. Puedes disfrutar fácilmente de Minecraft en diferentes plataformas a través de HMCL.
Para los sistemas y arquitecturas de CPU compatibles con HMCL, consulta [esta tabla](PLATFORM.md).
## Descarga
Descarga la última versión desde el [sitio web oficial](https://hmcl.huangyuhui.net/download).
También puedes encontrar la última versión de HMCL en [GitHub Releases](https://github.com/HMCL-dev/HMCL/releases).
Aunque no es necesario, se recomienda descargar las versiones solo de los sitios web oficiales mencionados anteriormente.
## Licencia
Consulta [README.md](README.md#license).
## Contribución
Si deseas enviar un pull request, aquí tienes algunos requisitos:
* IDE: IntelliJ IDEA
* Compilador: Java 17+
### Compilación
Simplemente ejecuta el siguiente comando en el directorio raíz del proyecto:
```bash
./gradlew clean build
```
Asegúrate de tener instalado Java 17 o una versión posterior.
## Opciones de JVM (para depuración)
| Parámetro | Descripción |
|---------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| `-Dhmcl.home=<ruta>` | Sobrescribe el directorio de HMCL |
| `-Dhmcl.self_integrity_check.disable=true` | Omite la verificación de integridad propia al buscar actualizaciones |
| `-Dhmcl.bmclapi.override=<url>` | Sobrescribe la raíz de la API del proveedor de descargas BMCLAPI. Por defecto `https://bmclapi2.bangbang93.com` |
| `-Dhmcl.font.override=<familia de fuente>` | Sobrescribe la familia de fuente |
| `-Dhmcl.version.override=<versión>` | Sobrescribe el número de versión |
| `-Dhmcl.update_source.override=<url>` | Sobrescribe la fuente de actualizaciones de HMCL |
| `-Dhmcl.authlibinjector.location=<ruta>` | Usa el authlib-injector especificado (en vez de descargar uno) |
| `-Dhmcl.openjfx.repo=<url del repositorio maven>` | Añade un repositorio Maven personalizado para descargar OpenJFX |
| `-Dhmcl.native.encoding=<codificación>` | Sobrescribe la codificación nativa |
| `-Dhmcl.microsoft.auth.id=<ID de App>` | Sobrescribe el ID de la App OAuth de Microsoft |
| `-Dhmcl.microsoft.auth.secret=<Secreto de App>` | Sobrescribe el secreto de la App OAuth de Microsoft |
| `-Dhmcl.curseforge.apikey=<Clave API>` | Sobrescribe la clave API de CurseForge |
+65
View File
@@ -0,0 +1,65 @@
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
![Stars](https://img.shields.io/github/stars/HMCL-dev/HMCL?style=flat)
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | 中文 ([简体](README_zh.md), [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | **日本語** | [español](README_es.md) | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## 紹介
HMCLはオープンソースでクロスプラットフォーム対応のMinecraftランチャーです。Mod管理、ゲームカスタマイズ、Modローダーのインストール(Forge、NeoForge、Fabric、Quilt、LiteLoader、OptiFine)、Modパック作成、UIカスタマイズなど、さまざまな機能をサポートしています。
HMCLは優れたクロスプラットフォーム性能を持っています。Windows、Linux、macOS、FreeBSDなどの異なるオペレーティングシステムだけでなく、x86、ARM、RISC-V、MIPS、LoongArchなどのさまざまなCPUアーキテクチャにも対応しています。HMCLを使えば、さまざまなプラットフォームでMinecraftを簡単に楽しむことができます。
HMCLが対応しているシステムやCPUアーキテクチャについては、[この表](PLATFORM.md)をご参照ください。
## ダウンロード
最新版は[公式サイト](https://hmcl.huangyuhui.net/download)からダウンロードできます。
また、[GitHub Releases](https://github.com/HMCL-dev/HMCL/releases)でも最新版を入手できます。
必要ではありませんが、上記の公式サイトからのみリリース版をダウンロードすることを推奨します。
## ライセンス
ライセンスについては [README.md](README.md#license) をご参照ください。
## コントリビューション
プルリクエストを送信したい場合、以下の要件を満たしてください。
* IDE:IntelliJ IDEA
* コンパイラ:Java 17以上
### コンパイル方法
プロジェクトのルートディレクトリで次のコマンドを実行してください。
```bash
./gradlew clean build
```
Java 17以上がインストールされていることを確認してください。
## JVMオプション(デバッグ用)
| パラメータ | 説明 |
|----------------------------------------------|-----------------------------------------------------------------------------|
| `-Dhmcl.home=<path>` | HMCLディレクトリを上書きします |
| `-Dhmcl.self_integrity_check.disable=true` | アップデート時の自己整合性チェックをバイパスします |
| `-Dhmcl.bmclapi.override=<url>` | BMCLAPIダウンロードプロバイダーのAPIルートを上書きします。デフォルトは`https://bmclapi2.bangbang93.com`です |
| `-Dhmcl.font.override=<font family>` | フォントファミリーを上書きします |
| `-Dhmcl.version.override=<version>` | バージョン番号を上書きします |
| `-Dhmcl.update_source.override=<url>` | HMCL本体のアップデートソースを上書きします |
| `-Dhmcl.authlibinjector.location=<path>` | 指定したauthlib-injectorを使用します(ダウンロードせずに) |
| `-Dhmcl.openjfx.repo=<maven repository url>` | OpenJFXダウンロード用のカスタムMavenリポジトリを追加します |
| `-Dhmcl.native.encoding=<encoding>` | ネイティブエンコーディングを上書きします |
| `-Dhmcl.microsoft.auth.id=<App ID>` | Microsoft OAuthアプリIDを上書きします |
| `-Dhmcl.microsoft.auth.secret=<App Secret>` | Microsoft OAuthアプリシークレットを上書きします |
| `-Dhmcl.curseforge.apikey=<Api Key>` | CurseForge APIキーを上書きします |
+66
View File
@@ -0,0 +1,66 @@
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
![Stars](https://img.shields.io/github/stars/HMCL-dev/HMCL?style=flat)
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | **中文** ([简体](README_zh.md), [繁體](README_zh_Hant.md), **文言**) | [日本語](README_ja.md) | [español](README_es.md) | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
### 概說
HMCL 者,開源之礦藝啟者也。能理改囊,善於遊戲之自定,且自動安裝諸如 Forge、NeoForge、Fabric、Quilt、LiteLoader、OptiFine 諸改囊,亦可製作改囊集,界面亦可隨意更易。
HMCL 跨域甚廣。無論 Windows、Linux、macOS、FreeBSD 諸常見械綱,抑或 x86、ARM、RISC-V、MIPS、LoongArch 諸大構處理器,皆可運行。
君可憑此,於諸算機間自如遊戲。
若欲詳知 HMCL 於諸算機之支援,請觀[此表](PLATFORM_zh_Hant.md)。
## 下載
請自 [HMCL 官網](https://hmcl.huangyuhui.net/download) 取其最新版。
亦可於 [GitHub Releases](https://github.com/HMCL-dev/HMCL/releases) 得其新者。
雖非強制,然猶勸自官網取之。
## 開源之約
詳見 [README_zh_Hant.md](README_zh_Hant.md#開源協議)。
## 貢獻
若欲獻 Pull Request,須遵下列:
* IDE 用 IntelliJ IDEA
* 編譯器用爪哇十七以上
### 編造
於項目之根目錄,執下列令:
```bash
./gradlew clean build
```
務必保汝已安裝爪哇十七或更高者。
## 爪哇虛機之通弦(以資勘誤)
| 參數 | 解釋 |
|----------------------------------------------|---------------------------------------------------------|
| `-Dhmcl.home=<path>` | 易 HMCL 之用戶目錄 |
| `-Dhmcl.self_integrity_check.disable=true` | 檢查更新時不驗本體之全 |
| `-Dhmcl.bmclapi.override=<url>` | 易 BMCLAPI 之 API 根,預設為 `https://bmclapi2.bangbang93.com` |
| `-Dhmcl.font.override=<font family>` | 易書體 |
| `-Dhmcl.version.override=<version>` | 易版 |
| `-Dhmcl.update_source.override=<url>` | 易 HMCL 之更新所 |
| `-Dhmcl.authlibinjector.location=<path>` | 用所指之 authlib-injector,毋需下載 |
| `-Dhmcl.openjfx.repo=<maven repository url>` | 增 OpenJFX 下載之自定 Maven 庫 |
| `-Dhmcl.native.encoding=<encoding>` | 易本地編碼 |
| `-Dhmcl.microsoft.auth.id=<App ID>` | 易 Microsoft OAuth 之 App ID |
| `-Dhmcl.microsoft.auth.secret=<App Secret>` | 易 Microsoft OAuth 之金鑰 |
| `-Dhmcl.curseforge.apikey=<Api Key>` | 易 CurseForge 之 API 金鑰 |
+65
View File
@@ -0,0 +1,65 @@
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
![Stars](https://img.shields.io/github/stars/HMCL-dev/HMCL?style=flat)
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | 中文 ([简体](README_zh.md), [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | [日本語](README_ja.md) | [español](README_es.md) | **русский** | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## Введение
HMCL — это открытый, кроссплатформенный лаунчер для Minecraft с поддержкой управления модами, настройки игры, установки загрузчиков модов (Forge, NeoForge, Fabric, Quilt, LiteLoader и OptiFine), создания модпаков, настройки интерфейса и многого другого.
HMCL обладает отличной кроссплатформенностью. Он работает не только на различных операционных системах, таких как Windows, Linux, macOS и FreeBSD, но и поддерживает различные архитектуры процессоров: x86, ARM, RISC-V, MIPS и LoongArch. Благодаря HMCL вы можете легко наслаждаться Minecraft на разных платформах.
Список поддерживаемых систем и архитектур процессоров HMCL смотрите в [этой таблице](PLATFORM.md).
## Загрузка
Скачайте последнюю версию с [официального сайта](https://hmcl.huangyuhui.net/download).
Также вы можете найти последнюю версию HMCL в [релизах на GitHub](https://github.com/HMCL-dev/HMCL/releases).
Хотя это не обязательно, рекомендуется скачивать релизы только с указанных выше официальных сайтов.
## Лицензия
См. [README.md](README.md#license).
## Вклад
Если вы хотите отправить pull request, ознакомьтесь с требованиями:
* IDE: IntelliJ IDEA
* Компилятор: Java 17+
### Сборка
Выполните следующую команду в корневой директории проекта:
```bash
./gradlew clean build
```
Убедитесь, что у вас установлена Java 17 или новее.
## Параметры JVM (для отладки)
| Параметр | Описание |
|-----------------------------------------------|---------------------------------------------------------------------------------------------------------------|
| `-Dhmcl.home=<путь>` | Переопределить директорию HMCL |
| `-Dhmcl.self_integrity_check.disable=true` | Отключить проверку целостности при проверке обновлений |
| `-Dhmcl.bmclapi.override=<url>` | Переопределить корневой API-адрес провайдера загрузки BMCLAPI. По умолчанию `https://bmclapi2.bangbang93.com` |
| `-Dhmcl.font.override=<название шрифта>` | Переопределить семейство шрифтов |
| `-Dhmcl.version.override=<версия>` | Переопределить номер версии |
| `-Dhmcl.update_source.override=<url>` | Переопределить источник обновлений для самого HMCL |
| `-Dhmcl.authlibinjector.location=<путь>` | Использовать указанный authlib-injector (вместо загрузки) |
| `-Dhmcl.openjfx.repo=<url репозитория maven>` | Добавить пользовательский Maven-репозиторий для загрузки OpenJFX |
| `-Dhmcl.native.encoding=<кодировка>` | Переопределить нативную кодировку |
| `-Dhmcl.microsoft.auth.id=<App ID>` | Переопределить Microsoft OAuth App ID |
| `-Dhmcl.microsoft.auth.secret=<App Secret>` | Переопределить Microsoft OAuth App Secret |
| `-Dhmcl.curseforge.apikey=<Api Key>` | Переопределить CurseForge API Key |
+65
View File
@@ -0,0 +1,65 @@
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
![Stars](https://img.shields.io/github/stars/HMCL-dev/HMCL?style=flat)
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | 中文 ([简体](README_zh.md), [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | [日本語](README_ja.md) | [español](README_es.md) | [русский](README_ru.md) | **українська**
<!-- #END LANGUAGE_SWITCHER -->
## Вступ
HMCL — це відкритий, кросплатформний лаунчер для Minecraft, який підтримує керування модами, налаштування гри, встановлення модлоадерів (Forge, NeoForge, Fabric, Quilt, LiteLoader та OptiFine), створення модпаків, налаштування інтерфейсу та багато іншого.
HMCL має чудові кросплатформні можливості. Він працює не лише на різних операційних системах, таких як Windows, Linux, macOS і FreeBSD, а й підтримує різні архітектури процесорів, такі як x86, ARM, RISC-V, MIPS і LoongArch. Ви можете легко насолоджуватися Minecraft на різних платформах за допомогою HMCL.
Щодо підтримуваних систем і архітектур процесорів дивіться [цю таблицю](PLATFORM.md).
## Завантаження
Завантажте останню версію з [офіційного сайту](https://hmcl.huangyuhui.net/download).
Також ви можете знайти останню версію HMCL у [релізах GitHub](https://github.com/HMCL-dev/HMCL/releases).
Хоча це не обовʼязково, рекомендується завантажувати релізи лише з офіційних сайтів, зазначених вище.
## Ліцензія
Дивіться [README.md](README.md#license).
## Внесок
Якщо ви хочете надіслати pull request, ознайомтеся з наступними вимогами:
* IDE: IntelliJ IDEA
* Компілятор: Java 17+
### Компіляція
Просто виконайте наступну команду в кореневому каталозі проєкту:
```bash
./gradlew clean build
```
Переконайтеся, що у вас встановлено Java 17 або новішої версії.
## JVM Options (for debugging)
| Parameter | Description |
|----------------------------------------------|-----------------------------------------------------------------------------------------------|
| `-Dhmcl.home=<path>` | Override HMCL directory |
| `-Dhmcl.self_integrity_check.disable=true` | Bypass the self integrity check when checking for updates |
| `-Dhmcl.bmclapi.override=<url>` | Override API Root of BMCLAPI download provider. Defaults to `https://bmclapi2.bangbang93.com` |
| `-Dhmcl.font.override=<font family>` | Override font family |
| `-Dhmcl.version.override=<version>` | Override the version number |
| `-Dhmcl.update_source.override=<url>` | Override the update source for HMCL itself |
| `-Dhmcl.authlibinjector.location=<path>` | Use the specified authlib-injector (instead of downloading one) |
| `-Dhmcl.openjfx.repo=<maven repository url>` | Add custom Maven repository for downloading OpenJFX |
| `-Dhmcl.native.encoding=<encoding>` | Override the native encoding |
| `-Dhmcl.microsoft.auth.id=<App ID>` | Override Microsoft OAuth App ID |
| `-Dhmcl.microsoft.auth.secret=<App Secret>` | Override Microsoft OAuth App Secret |
| `-Dhmcl.curseforge.apikey=<Api Key>` | Override CurseForge API Key |
+6 -5
View File
@@ -1,4 +1,4 @@
# ⛏ Hello Minecraft! Launcher 💎
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
@@ -6,15 +6,17 @@
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
[English](README.md) | **简体中文** | [繁體中文](README_tw.md)
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | **中文** (**简体**, [繁體](README_zh_Hant.md), [文言](README_lzh.md)) | [日本語](README_ja.md) | [español](README_es.md) | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## 简介
HMCL 是一款开源、跨平台的 Minecraft 启动器,支持模组管理、游戏自定义、游戏自动安装 (Forge、NeoForge、Fabric、Quilt、LiteLoader 和 OptiFine)、整合包创建、界面自定义等功能。
HMCL 有着强大的跨平台能力。它不仅支持 Windows、Linux、macOS 等常见的操作系统,同时也支持 x86、ARM、RISC-V、MIPS、LoongArch 等不同的 CPU 架构。你可以使用 HMCL 在不同平台上轻松地游玩 Minecraft。
HMCL 有着强大的跨平台能力。它不仅支持 Windows、Linux、macOS、FreeBSD 等常见的操作系统,同时也支持 x86、ARM、RISC-V、MIPS、LoongArch 等不同的 CPU 架构。你可以使用 HMCL 在不同平台上轻松地游玩 Minecraft。
如果你想要了解 HMCL 对不同平台的支持程度,请参见 [此表格](PLATFORM_cn.md)。
如果你想要了解 HMCL 对不同平台的支持程度,请参见 [此表格](PLATFORM_zh.md)。
## 下载
@@ -42,7 +44,6 @@ HMCL 有着强大的跨平台能力。它不仅支持 Windows、Linux、macOS
* IDE:IntelliJ IDEA
* 编译器:Java 17+
* **不要**修改 `gradle` 相关文件
### 编译
+6 -5
View File
@@ -1,4 +1,4 @@
# ⛏ Hello Minecraft! Launcher 💎
# Hello Minecraft! Launcher
[![Build Status](https://ci.huangyuhui.net/job/HMCL/badge/icon?.svg)](https://ci.huangyuhui.net/job/HMCL)
![Downloads](https://img.shields.io/github/downloads/HMCL-dev/HMCL/total?style=flat)
@@ -6,15 +6,17 @@
[![Discord](https://img.shields.io/discord/995291757799538688.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/jVvC7HfM6U)
[![QQ Group](https://img.shields.io/badge/QQ-HMCL-bright?label=&logo=qq&logoColor=ffffff&color=1EBAFC&labelColor=1DB0EF&logoSize=auto)](https://docs.hmcl.net/groups.html)
[English](README.md) | [简体中文](README_cn.md) | **繁體中文**
<!-- #BEGIN LANGUAGE_SWITCHER -->
[English](README.md) | **中文** ([简体](README_zh.md), **繁體**, [文言](README_lzh.md)) | [日本語](README_ja.md) | [español](README_es.md) | [русский](README_ru.md) | [українська](README_uk.md)
<!-- #END LANGUAGE_SWITCHER -->
## 簡介
HMCL 是一款開源、跨平臺的 Minecraft 啟動器,支援模組管理、遊戲客製化、遊戲自動安裝 (Forge、NeoForge、Fabric、Quilt、LiteLoader 和 OptiFine)、模組包建立、介面客製化等功能。
HMCL 有著強大的跨平臺能力。它不僅支援 Windows、Linux、macOS 等常見的作業系統,同時也支援 x86、ARM、RISC-V、MIPS、LoongArch 等不同的 CPU 架構。你可以使用 HMCL 在不同平臺上輕鬆地遊玩 Minecraft。
HMCL 有著強大的跨平臺能力。它不僅支援 Windows、Linux、macOS、FreeBSD 等常見的作業系統,同時也支援 x86、ARM、RISC-V、MIPS、LoongArch 等不同的 CPU 架構。你可以使用 HMCL 在不同平臺上輕鬆地遊玩 Minecraft。
如果你想要了解 HMCL 對不同平臺的支援程度,請參見 [此表格](PLATFORM_tw.md)。
如果你想要了解 HMCL 對不同平臺的支援程度,請參見 [此表格](PLATFORM_zh_Hant.md)。
## 下載
@@ -42,7 +44,6 @@ HMCL 有著強大的跨平臺能力。它不僅支援 Windows、Linux、macOS
* IDE:IntelliJ IDEA
* 編譯器:Java 17+
* **不要**修改 `gradle` 相關文件
### 編譯
+2
View File
@@ -20,6 +20,7 @@ authlib-injector = "1.2.5"
# testing
junit = "5.13.4"
jimfs = "1.3.0"
# plugins
shadow = "9.0.1"
@@ -48,6 +49,7 @@ authlib-injector = { module = "org.glavo.hmcl:authlib-injector", version.ref = "
# testing
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
jimfs = { module = "com.google.jimfs:jimfs", version.ref = "jimfs" }
[plugins]
shadow = { id = "com.gradleup.shadow", version.ref = "shadow" }