diff --git a/HMCLBoot/src/main/java/org/jackhuang/hmcl/Main.java b/HMCLBoot/src/main/java/org/jackhuang/hmcl/Main.java index 457dbe8148..71eae3d5a9 100644 --- a/HMCLBoot/src/main/java/org/jackhuang/hmcl/Main.java +++ b/HMCLBoot/src/main/java/org/jackhuang/hmcl/Main.java @@ -20,6 +20,13 @@ import org.jackhuang.hmcl.util.SwingUtils; import javax.swing.*; +import java.net.URISyntaxException; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.CodeSource; +import java.security.ProtectionDomain; import java.util.ResourceBundle; /** @@ -104,15 +111,41 @@ static void showErrorAndExit(String[] args) { private static void checkDirectoryPath() { String currentDir = System.getProperty("user.dir", ""); + + Path jarPath = getThisJarPath(); if (currentDir.contains("!")) { SwingUtils.initLookAndFeel(); System.err.println("The current working path contains an exclamation mark: " + currentDir); // No Chinese translation because both Swing and JavaFX cannot render Chinese character properly when exclamation mark exists in the path. - SwingUtils.showErrorDialog("Exclamation mark(!) is not allowed in the path where HMCL is in.\n" + "The path is " + currentDir); + SwingUtils.showErrorDialog("Exclamation mark(!) is not allowed in the working path.\n" + "The path is " + currentDir); + System.exit(1); + } else if (jarPath != null && jarPath.toString().contains("!")) { + SwingUtils.initLookAndFeel(); + System.err.println("The jar path contains an exclamation mark: " + jarPath); + // No Chinese translation because both Swing and JavaFX cannot render Chinese character properly when exclamation mark exists in the path. + SwingUtils.showErrorDialog("Exclamation mark(!) is not allowed in the path where HMCL is in.\n" + "The path is " + jarPath); System.exit(1); } } + private static Path getThisJarPath() { + ProtectionDomain protectionDomain = Main.class.getProtectionDomain(); + if (protectionDomain == null) return null; + + CodeSource codeSource = protectionDomain.getCodeSource(); + + if (codeSource == null) return null; + + Path path; + try { + path = Paths.get(codeSource.getLocation().toURI()).toAbsolutePath(); + } catch (FileSystemNotFoundException | IllegalArgumentException | URISyntaxException e) { + path = null; + } + return (path != null && Files.isRegularFile(path)) ? path : null; + + } + public static void main(String[] args) throws Throwable { checkDirectoryPath(); if (getJavaFeatureVersion(System.getProperty("java.version")) >= MINIMUM_JAVA_VERSION) {