Reconstruct the codes.

This commit is contained in:
huanghongxun
2015-07-11 17:34:25 +08:00
parent 0be056ac04
commit 2b63d46ffd
113 changed files with 1281 additions and 1343 deletions

View File

@@ -153,11 +153,9 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
res.add(args.length > 1 ? args[1] : "25565"); res.add(args.length > 1 ? args[1] : "25565");
} }
if (v.isFullscreen()) if (v.isFullscreen()) res.add("--fullscreen");
res.add("--fullscreen");
if (v.isDebug() && !v.isCanceledWrapper()) if (v.isDebug() && !v.isCanceledWrapper()) res.add("-debug");
res.add("-debug");
if (StrUtils.isNotBlank(v.getMinecraftArgs())) if (StrUtils.isNotBlank(v.getMinecraftArgs()))
res.addAll(Arrays.asList(v.getMinecraftArgs().split(" "))); res.addAll(Arrays.asList(v.getMinecraftArgs().split(" ")));
@@ -172,6 +170,7 @@ public abstract class AbstractMinecraftLoader implements IMinecraftLoader {
* <li>main class</li> * <li>main class</li>
* <li>minecraft arguments</li> * <li>minecraft arguments</li>
* </ul> * </ul>
*
* @param list the command list you shoud edit. * @param list the command list you shoud edit.
*/ */
protected abstract void makeSelf(List<String> list); protected abstract void makeSelf(List<String> list);

View File

@@ -57,17 +57,12 @@ public class DefaultGameLauncher extends GameLauncher {
return flag; return flag;
}); });
decompressNativesEvent.register((sender, value) -> { decompressNativesEvent.register((sender, value) -> {
//boolean flag = true;
for (int i = 0; i < value.decompressFiles.length; i++) for (int i = 0; i < value.decompressFiles.length; i++)
try { try {
Compressor.unzip(value.decompressFiles[i], value.decompressTo, value.extractRules[i]); Compressor.unzip(value.decompressFiles[i], value.decompressTo, value.extractRules[i]);
} catch (IOException ex) { } catch (IOException ex) {
HMCLog.err("Unable to decompress library file: " + value.decompressFiles[i] + " to " + value.decompressTo, ex); HMCLog.err("Unable to decompress library file: " + value.decompressFiles[i] + " to " + value.decompressTo, ex);
//flag = false;
} }
/*if(!flag)
if(MessageBox.Show(C.i18n("launch.not_finished_decompressing_natives"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
flag = true;*/
return true; return true;
}); });
} }

View File

@@ -104,8 +104,14 @@ public class GameLauncher {
File file = provider.getDecompressNativesToLocation(); File file = provider.getDecompressNativesToLocation();
if (file != null) FileUtils.cleanDirectoryQuietly(file); if (file != null) FileUtils.cleanDirectoryQuietly(file);
if(!downloadLibrariesEvent.execute(provider.getDownloadLibraries(downloadType))) { failEvent.execute(C.i18n("launch.failed")); return null; } if (!downloadLibrariesEvent.execute(provider.getDownloadLibraries(downloadType))) {
if(!decompressNativesEvent.execute(provider.getDecompressLibraries())) { failEvent.execute(C.i18n("launch.failed")); return null; } failEvent.execute(C.i18n("launch.failed"));
return null;
}
if (!decompressNativesEvent.execute(provider.getDecompressLibraries())) {
failEvent.execute(C.i18n("launch.failed"));
return null;
}
successEvent.execute(loader.makeLaunchingCommand()); successEvent.execute(loader.makeLaunchingCommand());
return loader; return loader;
} }
@@ -185,6 +191,7 @@ public class GameLauncher {
} }
public static class DecompressLibraryJob { public static class DecompressLibraryJob {
File[] decompressFiles; File[] decompressFiles;
String[][] extractRules; String[][] extractRules;
File decompressTo; File decompressTo;

View File

@@ -23,5 +23,6 @@ import java.util.List;
* @author huangyuhui * @author huangyuhui
*/ */
public interface IMinecraftLoader { public interface IMinecraftLoader {
List<String> makeLaunchingCommand(); List<String> makeLaunchingCommand();
} }

View File

@@ -29,6 +29,7 @@ import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class IMinecraftProvider { public abstract class IMinecraftProvider {
Profile profile; Profile profile;
public IMinecraftProvider(Profile profile) { public IMinecraftProvider(Profile profile) {
@@ -36,18 +37,28 @@ public abstract class IMinecraftProvider {
} }
public abstract File getRunDirectory(String id); public abstract File getRunDirectory(String id);
public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type); public abstract List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType type);
public abstract void openSelf(String version); public abstract void openSelf(String version);
public abstract void open(String version, String folder); public abstract void open(String version, String folder);
public abstract File getAssets(); public abstract File getAssets();
public abstract File getResourcePacks(); public abstract File getResourcePacks();
public abstract GameLauncher.DecompressLibraryJob getDecompressLibraries(); public abstract GameLauncher.DecompressLibraryJob getDecompressLibraries();
public abstract File getDecompressNativesToLocation(); public abstract File getDecompressNativesToLocation();
public abstract File getMinecraftJar(); public abstract File getMinecraftJar();
public abstract File getBaseFolder(); public abstract File getBaseFolder();
/** /**
* Launch * Launch
*
* @param p player informations, including username & auth_token * @param p player informations, including username & auth_token
* @param type according to the class name 233 * @param type according to the class name 233
* @return what you want * @return what you want
@@ -57,14 +68,21 @@ public abstract class IMinecraftProvider {
// Versions // Versions
public abstract boolean renameVersion(String from, String to); public abstract boolean renameVersion(String from, String to);
public abstract boolean removeVersionFromDisk(String a); public abstract boolean removeVersionFromDisk(String a);
public abstract boolean refreshJson(String a); public abstract boolean refreshJson(String a);
public abstract boolean refreshAssetsIndex(String a); public abstract boolean refreshAssetsIndex(String a);
public abstract MinecraftVersion getOneVersion(); public abstract MinecraftVersion getOneVersion();
public abstract Collection<MinecraftVersion> getVersions(); public abstract Collection<MinecraftVersion> getVersions();
public abstract MinecraftVersion getVersionById(String id); public abstract MinecraftVersion getVersionById(String id);
public abstract int getVersionCount(); public abstract int getVersionCount();
public abstract void refreshVersions(); public abstract void refreshVersions();
public abstract boolean install(String version, DownloadType type); public abstract boolean install(String version, DownloadType type);

View File

@@ -31,25 +31,24 @@ public final class MinecraftCrashAdvicer {
public static String getAdvice(String trace, boolean selfCrash) { public static String getAdvice(String trace, boolean selfCrash) {
trace = trace.toLowerCase(); trace = trace.toLowerCase();
if(trace.contains("pixel format not accelerated")) { if (trace.contains("pixel format not accelerated"))
return C.i18n("crash.advice.LWJGLException"); return C.i18n("crash.advice.LWJGLException");
} else if (trace.contains("unsupportedclassversionrrror")) { else if (trace.contains("unsupportedclassversionrrror"))
return C.i18n("crash.advice.UnsupportedClassVersionError"); return C.i18n("crash.advice.UnsupportedClassVersionError");
} else if (trace.contains("concurrentmodificationexception")) { else if (trace.contains("concurrentmodificationexception"))
return C.i18n("crash.advice.ConcurrentModificationException"); return C.i18n("crash.advice.ConcurrentModificationException");
} else if (trace.contains("securityexception")) { else if (trace.contains("securityexception"))
return C.i18n("crash.advice.SecurityException"); return C.i18n("crash.advice.SecurityException");
} else if (trace.contains("nosuchfieldexception") || trace.contains("nosuchfielderror")) { else if (trace.contains("nosuchfieldexception") || trace.contains("nosuchfielderror"))
return C.i18n("crash.advice.NoSuchFieldError"); return C.i18n("crash.advice.NoSuchFieldError");
} else if (trace.contains("outofmemory") || trace.contains("out of memory")) { else if (trace.contains("outofmemory") || trace.contains("out of memory"))
return C.i18n("crash.advice.OutOfMemoryError"); return C.i18n("crash.advice.OutOfMemoryError");
} else if (trace.contains("noclassdeffounderror") || trace.contains("classnotfoundexception")) { else if (trace.contains("noclassdeffounderror") || trace.contains("classnotfoundexception"))
return C.i18n("crash.advice.ClassNotFoundException"); return C.i18n("crash.advice.ClassNotFoundException");
} else if (trace.contains("no lwjgl in java.library.path")) { else if (trace.contains("no lwjgl in java.library.path"))
return C.i18n("crash.advice.no_lwjgl"); return C.i18n("crash.advice.no_lwjgl");
} else if (trace.contains("opengl") || trace.contains("openal")) { else if (trace.contains("opengl") || trace.contains("openal"))
return C.i18n("crash.advice.OpenGL"); return C.i18n("crash.advice.OpenGL");
}
return C.i18n(selfCrash ? "crash.advice.no" : "crash.advice.otherwise"); return C.i18n(selfCrash ? "crash.advice.no" : "crash.advice.otherwise");
} }

View File

@@ -31,6 +31,7 @@ import org.jackhuang.hellominecraft.utils.system.OS;
* @author huangyuhui * @author huangyuhui
*/ */
public final class Config { public final class Config {
@SerializedName("last") @SerializedName("last")
private String last; private String last;
@SerializedName("bgpath") @SerializedName("bgpath")
@@ -153,8 +154,7 @@ public final class Config {
@SerializedName("yggdrasil") @SerializedName("yggdrasil")
private Map yggdrasil; private Map yggdrasil;
public Config() public Config() {
{
clientToken = UUID.randomUUID().toString(); clientToken = UUID.randomUUID().toString();
username = ""; username = "";
logintype = downloadtype = 0; logintype = downloadtype = 0;

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.settings;
* @author huangyuhui * @author huangyuhui
*/ */
public enum LauncherVisibility { public enum LauncherVisibility {
CLOSE, CLOSE,
HIDE, HIDE,
KEEP KEEP

View File

@@ -67,9 +67,7 @@ public final class Profile {
public Profile(Profile v) { public Profile(Profile v) {
this(); this();
if (v == null) { if (v == null) return;
return;
}
name = v.name; name = v.name;
gameDir = v.gameDir; gameDir = v.gameDir;
maxMemory = v.maxMemory; maxMemory = v.maxMemory;
@@ -97,9 +95,7 @@ public final class Profile {
public MinecraftVersion getSelectedMinecraftVersion() { public MinecraftVersion getSelectedMinecraftVersion() {
if (StrUtils.isBlank(selectedMinecraftVersion)) { if (StrUtils.isBlank(selectedMinecraftVersion)) {
MinecraftVersion v = getMinecraftProvider().getOneVersion(); MinecraftVersion v = getMinecraftProvider().getOneVersion();
if (v == null) { if (v == null) return null;
return null;
}
selectedMinecraftVersion = v.id; selectedMinecraftVersion = v.id;
return v; return v;
} }
@@ -110,9 +106,7 @@ public final class Profile {
} }
public String getGameDir() { public String getGameDir() {
if (StrUtils.isBlank(gameDir)) { if (StrUtils.isBlank(gameDir)) gameDir = MCUtils.getInitGameDir().getPath();
gameDir = MCUtils.getInitGameDir().getPath();
}
return IOUtils.addSeparator(gameDir); return IOUtils.addSeparator(gameDir);
} }
@@ -135,9 +129,8 @@ public final class Profile {
} }
public String getJavaDir() { public String getJavaDir() {
if (StrUtils.isBlank(javaDir)) { if (StrUtils.isBlank(javaDir))
javaDir = IOUtils.getJavaDir(); javaDir = IOUtils.getJavaDir();
}
return javaDir; return javaDir;
} }

View File

@@ -61,9 +61,8 @@ public final class Settings {
if (!getVersions().containsKey(DEFAULT_PROFILE)) if (!getVersions().containsKey(DEFAULT_PROFILE))
getVersions().put(DEFAULT_PROFILE, new Profile()); getVersions().put(DEFAULT_PROFILE, new Profile());
for(Profile e : getVersions().values()) { for (Profile e : getVersions().values())
e.checkFormat(); e.checkFormat();
}
UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer), UPDATE_CHECKER = new UpdateChecker(new VersionNumber(Main.firstVer, Main.secondVer, Main.thirdVer),
"hmcl", settings.isCheckUpdate(), () -> Main.invokeUpdate()); "hmcl", settings.isCheckUpdate(), () -> Main.invokeUpdate());

View File

@@ -84,8 +84,8 @@ public final class MCUtils {
String ver = new String(tmp, i, j - i, "ASCII"); String ver = new String(tmp, i, j - i, "ASCII");
r.version = ver; r.version = ver;
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ? r.type = file.getEntry("META-INF/MANIFEST.MF") == null
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -134,8 +134,8 @@ public final class MCUtils {
k++; k++;
r.version = new String(tmp, k, i - k + 1); r.version = new String(tmp, k, i - k + 1);
} }
r.type = file.getEntry("META-INF/MANIFEST.MF") == null ? r.type = file.getEntry("META-INF/MANIFEST.MF") == null
MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK; ? MinecraftVersionRequest.Modified : MinecraftVersionRequest.OK;
return r; return r;
} }
@@ -297,6 +297,7 @@ public final class MCUtils {
} }
public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}"; public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static void tryWriteProfile(File gameDir) throws IOException { public static void tryWriteProfile(File gameDir) throws IOException {
File file = new File(gameDir, "launcher_profiles.json"); File file = new File(gameDir, "launcher_profiles.json");
if (!file.exists()) if (!file.exists())

View File

@@ -54,23 +54,18 @@ public class AssetsLoader extends Thread {
for (int i = 0; i < contents.getLength(); i++) { for (int i = 0; i < contents.getLength(); i++) {
Node result = contents.item(i); Node result = contents.item(i);
if (result.getNodeType() == Node.ELEMENT_NODE) { if (result.getNodeType() == Node.ELEMENT_NODE) {
if (result.getNodeName().equalsIgnoreCase("Key")) { if (result.getNodeName().equalsIgnoreCase("Key"))
ret.key = result.getTextContent(); ret.key = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("ETag"))
if (result.getNodeName().equalsIgnoreCase("ETag")) {
ret.eTag = result.getTextContent(); ret.eTag = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("LastModified"))
if (result.getNodeName().equalsIgnoreCase("LastModified")) {
ret.lastModified = result.getTextContent(); ret.lastModified = result.getTextContent();
} if (result.getNodeName().equalsIgnoreCase("Size"))
if (result.getNodeName().equalsIgnoreCase("Size")) {
ret.size = MathUtils.parseInt(result.getTextContent(), 0); ret.size = MathUtils.parseInt(result.getTextContent(), 0);
} if (result.getNodeName().equalsIgnoreCase("StorageClass"))
if (result.getNodeName().equalsIgnoreCase("StorageClass")) {
ret.storageClass = result.getTextContent(); ret.storageClass = result.getTextContent();
} }
} }
}
return ret; return ret;
} }

View File

@@ -62,8 +62,8 @@ public class AssetsMojangOldLoader extends IAssetsHandler {
public boolean isVersionAllowed(String formattedVersion) { public boolean isVersionAllowed(String formattedVersion) {
VersionNumber r = VersionNumber.check(formattedVersion); VersionNumber r = VersionNumber.check(formattedVersion);
if (r == null) return false; if (r == null) return false;
return VersionNumber.check("1.7.2").compareTo(r) >= 0 && return VersionNumber.check("1.7.2").compareTo(r) >= 0
VersionNumber.check("1.6.0").compareTo(r) <= 0; && VersionNumber.check("1.6.0").compareTo(r) <= 0;
} }
@Override @Override

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.assets;
* @author huangyuhui * @author huangyuhui
*/ */
public class AssetsObject { public class AssetsObject {
private String hash; private String hash;
private long size; private long size;

View File

@@ -62,7 +62,6 @@ public abstract class IAssetsHandler {
static { static {
assetsHandlers.add(new AssetsMojangLoader(C.i18n("assets.list.1_7_3_after"))); assetsHandlers.add(new AssetsMojangLoader(C.i18n("assets.list.1_7_3_after")));
//assetsHandlers.add(new AssetsMojangOldLoader(C.i18n("assets.list.1_6")));
} }
/** /**

View File

@@ -30,7 +30,6 @@ public abstract class IAuthenticator {
public static final YggdrasilAuthenticator yggdrasilLogin; public static final YggdrasilAuthenticator yggdrasilLogin;
public static final OfflineAuthenticator offlineLogin; public static final OfflineAuthenticator offlineLogin;
public static final SkinmeAuthenticator skinmeLogin; public static final SkinmeAuthenticator skinmeLogin;
//public static final BestLogin bestLogin;
public static final List<IAuthenticator> logins; public static final List<IAuthenticator> logins;
@@ -40,11 +39,10 @@ public abstract class IAuthenticator {
logins.add(offlineLogin = new OfflineAuthenticator(clientToken)); logins.add(offlineLogin = new OfflineAuthenticator(clientToken));
logins.add(yggdrasilLogin = new YggdrasilAuthenticator(clientToken)); logins.add(yggdrasilLogin = new YggdrasilAuthenticator(clientToken));
logins.add(skinmeLogin = new SkinmeAuthenticator(clientToken)); logins.add(skinmeLogin = new SkinmeAuthenticator(clientToken));
//logins.add(bestLogin = new BestLogin(clientToken));
yggdrasilLogin.onLoadSettings(Settings.getInstance().getYggdrasilConfig()); yggdrasilLogin.onLoadSettings(Settings.getInstance().getYggdrasilConfig());
Runtime.getRuntime().addShutdownHook(new Thread(() -> Runtime.getRuntime().addShutdownHook(new Thread(()
Settings.getInstance().setYggdrasilConfig(yggdrasilLogin.onSaveSettings()) -> Settings.getInstance().setYggdrasilConfig(yggdrasilLogin.onSaveSettings())
)); ));
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.auth;
* @author huangyuhui * @author huangyuhui
*/ */
public final class LoginInfo { public final class LoginInfo {
public String username, password; public String username, password;
public LoginInfo(String username, String password) { public LoginInfo(String username, String password) {

View File

@@ -23,6 +23,7 @@ import org.jackhuang.hellominecraft.C;
* @author huangyuhui * @author huangyuhui
*/ */
public enum DownloadType { public enum DownloadType {
Mojang(C.i18n("download.mojang"), new MojangDownloadProvider()), Mojang(C.i18n("download.mojang"), new MojangDownloadProvider()),
BMCL(C.i18n("download.BMCL"), new BMCLAPIDownloadProvider()); BMCL(C.i18n("download.BMCL"), new BMCLAPIDownloadProvider());

View File

@@ -23,14 +23,24 @@ import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionLi
* @author huangyuhui * @author huangyuhui
*/ */
public interface IDownloadProvider { public interface IDownloadProvider {
InstallerVersionList getInstallerByType(String type); InstallerVersionList getInstallerByType(String type);
InstallerVersionList getForgeInstaller(); InstallerVersionList getForgeInstaller();
InstallerVersionList getLiteLoaderInstaller(); InstallerVersionList getLiteLoaderInstaller();
InstallerVersionList getOptiFineInstaller(); InstallerVersionList getOptiFineInstaller();
String getLibraryDownloadURL(); String getLibraryDownloadURL();
String getVersionsDownloadURL(); String getVersionsDownloadURL();
String getIndexesDownloadURL(); String getIndexesDownloadURL();
String getVersionsListDownloadURL(); String getVersionsListDownloadURL();
String getAssetsDownloadURL(); String getAssetsDownloadURL();
boolean isAllowedToUseSelfURL(); boolean isAllowedToUseSelfURL();
} }

View File

@@ -25,6 +25,7 @@ import org.jackhuang.hellominecraft.launcher.utils.installers.forge.Install;
* @author huangyuhui * @author huangyuhui
*/ */
public class InstallProfile { public class InstallProfile {
@SerializedName("install") @SerializedName("install")
public Install install; public Install install;
@SerializedName("versionInfo") @SerializedName("versionInfo")

View File

@@ -25,16 +25,21 @@ import org.jackhuang.hellominecraft.utils.functions.Consumer;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class InstallerVersionList implements Consumer<String[]> { public abstract class InstallerVersionList implements Consumer<String[]> {
/** /**
* Refresh installer versions list from the downloaded content. * Refresh installer versions list from the downloaded content.
*
* @param versions Minecraft versions you need to refresh * @param versions Minecraft versions you need to refresh
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
public abstract void refreshList(String[] versions) throws Exception; public abstract void refreshList(String[] versions) throws Exception;
public abstract String getName(); public abstract String getName();
public abstract List<InstallerVersion> getVersions(String mcVersion); public abstract List<InstallerVersion> getVersions(String mcVersion);
public static class InstallerVersion implements Comparable<InstallerVersion> { public static class InstallerVersion implements Comparable<InstallerVersion> {
public String selfVersion, mcVersion; public String selfVersion, mcVersion;
public String installer, universal; public String installer, universal;
public String changelog; public String changelog;
@@ -51,7 +56,9 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
} }
public static class InstallerVersionComparator implements Comparator<InstallerVersion> { public static class InstallerVersionComparator implements Comparator<InstallerVersion> {
public static final InstallerVersionComparator INSTANCE = new InstallerVersionComparator(); public static final InstallerVersionComparator INSTANCE = new InstallerVersionComparator();
@Override @Override
public int compare(InstallerVersion o1, InstallerVersion o2) { public int compare(InstallerVersion o1, InstallerVersion o2) {
return o2.compareTo(o1); return o2.compareTo(o1);

View File

@@ -66,12 +66,10 @@ public class ForgeInstaller extends Task {
File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft); File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft);
if (!from.exists()) { if (!from.exists()) {
if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) {
if(!mp.install(profile.install.minecraft, Settings.getInstance().getDownloadSource())) { if (!mp.install(profile.install.minecraft, Settings.getInstance().getDownloadSource()))
setFailReason(new RuntimeException(C.i18n("install.no_version"))); setFailReason(new RuntimeException(C.i18n("install.no_version")));
} } else
} else {
setFailReason(new RuntimeException(C.i18n("install.no_version"))); setFailReason(new RuntimeException(C.i18n("install.no_version")));
}
return false; return false;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge;
* @author huangyuhui * @author huangyuhui
*/ */
public class Install { public class Install {
public String profileName; public String profileName;
public String target; public String target;
public String path; public String path;

View File

@@ -58,12 +58,12 @@ public class ForgeBMCLVersionList extends InstallerVersionList {
if (versionMap.containsKey(x)) continue; if (versionMap.containsKey(x)) continue;
String s = NetUtils.doGet("http://bmclapi2.bangbang93.com/forge/minecraft/" + x); String s = NetUtils.doGet("http://bmclapi2.bangbang93.com/forge/minecraft/" + x);
if (s == null) { if (s == null)
continue; continue;
}
try { try {
root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>(){}.getType()); root = C.gson.fromJson(s, new TypeToken<ArrayList<ForgeVersion>>() {
}.getType());
for (ForgeVersion v : root) { for (ForgeVersion v : root) {
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft)); InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.minecraft));

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge.bmcl;
* @author huangyuhui * @author huangyuhui
*/ */
public class ForgeVersion { public class ForgeVersion {
public String time, minecraft, version, _id, __v; public String time, minecraft, version, _id, __v;
public Downloads downloads; public Downloads downloads;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.forge.vanilla;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersion { public class MinecraftForgeVersion {
public String branch, mcversion, jobver, version; public String branch, mcversion, jobver, version;
public int build; public int build;
public double modified; public double modified;

View File

@@ -32,7 +32,9 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersionList extends InstallerVersionList { public class MinecraftForgeVersionList extends InstallerVersionList {
private static MinecraftForgeVersionList instance; private static MinecraftForgeVersionList instance;
public static MinecraftForgeVersionList getInstance() { public static MinecraftForgeVersionList getInstance() {
if (instance == null) if (instance == null)
instance = new MinecraftForgeVersionList(); instance = new MinecraftForgeVersionList();
@@ -50,34 +52,36 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
root = C.gson.fromJson(s, MinecraftForgeVersionRoot.class); root = C.gson.fromJson(s, MinecraftForgeVersionRoot.class);
versionMap = new HashMap<String, List<InstallerVersion>>(); versionMap = new HashMap<>();
versions = new ArrayList<InstallerVersion>(); versions = new ArrayList<>();
for (Map.Entry<String, int[]> arr : root.mcversion.entrySet()) { for (Map.Entry<String, int[]> arr : root.mcversion.entrySet()) {
String mcver = StrUtils.formatVersion(arr.getKey()); String mcver = StrUtils.formatVersion(arr.getKey());
ArrayList<InstallerVersion> al = new ArrayList<InstallerVersion>(); ArrayList<InstallerVersion> al = new ArrayList<>();
for (int num : arr.getValue()) { for (int num : arr.getValue()) {
MinecraftForgeVersion v = root.number.get(num); MinecraftForgeVersion v = root.number.get(num);
InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion)); InstallerVersion iv = new InstallerVersion(v.version, StrUtils.formatVersion(v.mcversion));
for (String[] f : v.files) { for (String[] f : v.files) {
String ver = v.mcversion + "-" + v.version; String ver = v.mcversion + "-" + v.version;
if(!StrUtils.isBlank(v.branch)) { if (!StrUtils.isBlank(v.branch))
ver = ver + "-" + v.branch; ver = ver + "-" + v.branch;
}
String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0]; String filename = root.artifact + "-" + ver + "-" + f[1] + "." + f[0];
String url = root.webpath + "/" + ver + "/" + filename; String url = root.webpath + "/" + ver + "/" + filename;
if(f[1].equals("installer")) { switch (f[1]) {
case "installer":
iv.installer = url; iv.installer = url;
} else if(f[1].equals("universal")) { break;
case "universal":
iv.universal = url; iv.universal = url;
} else if(f[1].equals("changelog")) { break;
case "changelog":
iv.changelog = url; iv.changelog = url;
break;
} }
} }
if(StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal)) { if (StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal))
continue; continue;
}
Collections.sort(al, new InstallerVersionNewerComparator()); Collections.sort(al, new InstallerVersionNewerComparator());
al.add(iv); al.add(iv);
versions.add(iv); versions.add(iv);

View File

@@ -23,6 +23,7 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftForgeVersionRoot { public class MinecraftForgeVersionRoot {
public String artifact, webpath, adfly, homepage, name; public String artifact, webpath, adfly, homepage, name;
public Map<String, int[]> branches, mcversion; public Map<String, int[]> branches, mcversion;
public Map<String, Integer> promos; public Map<String, Integer> promos;

View File

@@ -92,6 +92,7 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrat
} }
ArrayList<PreviousResult<File>> pre = new ArrayList<>(); ArrayList<PreviousResult<File>> pre = new ArrayList<>();
@Override @Override
public Task registerPreviousResult(PreviousResult pr) { public Task registerPreviousResult(PreviousResult pr) {
pre.add(pr); pre.add(pr);

View File

@@ -23,5 +23,6 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderMCVersions { public class LiteLoaderMCVersions {
public Map<String, Map<String, LiteLoaderVersion>> artefacts; public Map<String, Map<String, LiteLoaderVersion>> artefacts;
} }

View File

@@ -23,6 +23,7 @@ import org.jackhuang.hellominecraft.launcher.version.MinecraftLibrary;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersion { public class LiteLoaderVersion {
public String tweakClass, file, version, md5, timestamp; public String tweakClass, file, version, md5, timestamp;
public MinecraftLibrary[] libraries; public MinecraftLibrary[] libraries;
} }

View File

@@ -35,11 +35,12 @@ import org.jackhuang.hellominecraft.utils.StrUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionList extends InstallerVersionList { public class LiteLoaderVersionList extends InstallerVersionList {
private static LiteLoaderVersionList instance; private static LiteLoaderVersionList instance;
public static LiteLoaderVersionList getInstance() { public static LiteLoaderVersionList getInstance() {
if(instance == null) { if (instance == null)
instance = new LiteLoaderVersionList(); instance = new LiteLoaderVersionList();
}
return instance; return instance;
} }
@@ -94,6 +95,7 @@ public class LiteLoaderVersionList extends InstallerVersionList {
} }
public static class LiteLoaderInstallerVersion extends InstallerVersion { public static class LiteLoaderInstallerVersion extends InstallerVersion {
public MinecraftLibrary[] libraries; public MinecraftLibrary[] libraries;
public String tweakClass; public String tweakClass;

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.launcher.utils.installers.liteloader;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionsMeta { public class LiteLoaderVersionsMeta {
public String description, authors, url; public String description, authors, url;
} }

View File

@@ -23,6 +23,7 @@ import java.util.Map;
* @author huangyuhui * @author huangyuhui
*/ */
public class LiteLoaderVersionsRoot { public class LiteLoaderVersionsRoot {
public Map<String, LiteLoaderMCVersions> versions; public Map<String, LiteLoaderMCVersions> versions;
public LiteLoaderVersionsMeta meta; public LiteLoaderVersionsMeta meta;
} }

View File

@@ -28,6 +28,7 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
* @author huangyuhui * @author huangyuhui
*/ */
public class OptiFineDownloadFormatter extends Task implements PreviousResult<String> { public class OptiFineDownloadFormatter extends Task implements PreviousResult<String> {
String url, result; String url, result;
public OptiFineDownloadFormatter(String url) { public OptiFineDownloadFormatter(String url) {

View File

@@ -44,14 +44,15 @@ import org.xml.sax.SAXException;
* @author huangyuhui * @author huangyuhui
*/ */
public class OptiFineVersionList extends InstallerVersionList { public class OptiFineVersionList extends InstallerVersionList {
private static OptiFineVersionList instance; private static OptiFineVersionList instance;
public static OptiFineVersionList getInstance() { public static OptiFineVersionList getInstance() {
if (null == instance) if (null == instance)
instance = new OptiFineVersionList(); instance = new OptiFineVersionList();
return instance; return instance;
} }
public ArrayList<OptiFineVersion> root = new ArrayList(); public ArrayList<OptiFineVersion> root = new ArrayList();
public Map<String, List<InstallerVersion>> versionMap; public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions; public List<InstallerVersion> versions;
@@ -80,19 +81,15 @@ public class OptiFineVersionList extends InstallerVersionList {
OptiFineVersion v = new OptiFineVersion(); OptiFineVersion v = new OptiFineVersion();
for (int j = 0; j < downloadLine.getLength(); j++) { for (int j = 0; j < downloadLine.getLength(); j++) {
Element td = (Element) downloadLine.item(j); Element td = (Element) downloadLine.item(j);
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror")) { if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror"))
v.mirror = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"); v.mirror = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
} if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload"))
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload")) {
v.dl = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"); v.dl = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
} if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate"))
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate")) {
v.date = td.getTextContent(); v.date = td.getTextContent();
} if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile"))
if(StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile")) {
v.ver = td.getTextContent(); v.ver = td.getTextContent();
} }
}
if (StrUtils.isBlank(v.mcver)) { if (StrUtils.isBlank(v.mcver)) {
Pattern p = Pattern.compile("OptiFine (.*?) "); Pattern p = Pattern.compile("OptiFine (.*?) ");
Matcher m = p.matcher(v.ver); Matcher m = p.matcher(v.ver);
@@ -103,7 +100,6 @@ public class OptiFineVersionList extends InstallerVersionList {
root.add(v); root.add(v);
versions.add(iv); versions.add(iv);
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver)); List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver));
ivl.add(iv); ivl.add(iv);
} }

View File

@@ -23,6 +23,7 @@ import java.util.Arrays;
* @author huangyuhui * @author huangyuhui
*/ */
public class Extract extends Object implements Cloneable { public class Extract extends Object implements Cloneable {
String[] exclude; String[] exclude;
@Override @Override
@@ -32,5 +33,4 @@ public class Extract extends Object implements Cloneable {
return e; return e;
} }
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public enum GameDirType { public enum GameDirType {
ROOT_FOLDER, ROOT_FOLDER,
VERSION_FOLDER; VERSION_FOLDER;
} }

View File

@@ -26,15 +26,21 @@ import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
public abstract class IMinecraftLibrary implements Cloneable { public abstract class IMinecraftLibrary implements Cloneable {
public String name; public String name;
public IMinecraftLibrary(String name) { public IMinecraftLibrary(String name) {
this.name = name; this.name = name;
} }
public abstract boolean isRequiredToUnzip(); public abstract boolean isRequiredToUnzip();
public abstract String[] getDecompressExtractRules(); public abstract String[] getDecompressExtractRules();
public abstract void init(); public abstract void init();
public abstract boolean allow(); public abstract boolean allow();
public abstract File getFilePath(File gameDir); public abstract File getFilePath(File gameDir);
public abstract String getDownloadURL(String urlBase, DownloadType downloadType); public abstract String getDownloadURL(String urlBase, DownloadType downloadType);
@Override @Override

View File

@@ -63,22 +63,18 @@ public class MinecraftLibrary extends IMinecraftLibrary {
@Override @Override
public boolean allow() { public boolean allow() {
boolean flag = false; boolean flag = false;
if (rules == null || rules.isEmpty()) { if (rules == null || rules.isEmpty())
flag = true; flag = true;
} else { else
for (Rules r : rules) { for (Rules r : rules)
if (r.action.equals("disallow")) { if (r.action.equals("disallow")) {
if (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))) { if (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))) {
flag = false; flag = false;
break; break;
} }
} else { } else
if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString())))) { if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))))
flag = true; flag = true;
}
}
}
}
return flag; return flag;
} }
@@ -88,14 +84,13 @@ public class MinecraftLibrary extends IMinecraftLibrary {
private String getNative() { private String getNative() {
OS os = OS.os(); OS os = OS.os();
if (os == OS.WINDOWS) { if (os == OS.WINDOWS)
return formatArch(natives.windows); return formatArch(natives.windows);
} else if (os == OS.OSX) { else if (os == OS.OSX)
return formatArch(natives.osx); return formatArch(natives.osx);
} else { else
return formatArch(natives.linux); return formatArch(natives.linux);
} }
}
@Override @Override
public boolean isRequiredToUnzip() { public boolean isRequiredToUnzip() {
@@ -108,10 +103,10 @@ public class MinecraftLibrary extends IMinecraftLibrary {
String[] s = str.split(":"); String[] s = str.split(":");
str = s[0]; str = s[0];
str = str.replace('.', File.separatorChar); str = str.replace('.', File.separatorChar);
if (natives == null) { if (natives == null)
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + ".jar"; + File.separator + s[1] + '-' + s[2] + ".jar";
} else { else {
str += File.separator + s[1] + File.separator + s[2] str += File.separator + s[1] + File.separator + s[2]
+ File.separator + s[1] + '-' + s[2] + '-'; + File.separator + s[1] + '-' + s[2] + '-';
str += getNative(); str += getNative();

View File

@@ -59,11 +59,10 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
if (libraries == null) this.libraries = new ArrayList<>(); if (libraries == null) this.libraries = new ArrayList<>();
else { else {
this.libraries = new ArrayList<>(libraries.size()); this.libraries = new ArrayList<>(libraries.size());
for (IMinecraftLibrary library : libraries) { for (IMinecraftLibrary library : libraries)
this.libraries.add((MinecraftLibrary) library.clone()); this.libraries.add((MinecraftLibrary) library.clone());
} }
} }
}
@Override @Override
public Object clone() { public Object clone() {
@@ -75,12 +74,10 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
} }
protected MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) { protected MinecraftVersion resolve(IMinecraftProvider manager, Set<String> resolvedSoFar, DownloadType sourceType) {
if (inheritsFrom == null) { if (inheritsFrom == null)
return this; return this;
} if (!resolvedSoFar.add(id))
if (!resolvedSoFar.add(id)) {
throw new IllegalStateException("Circular dependency detected."); throw new IllegalStateException("Circular dependency detected.");
}
MinecraftVersion parent = manager.getVersionById(inheritsFrom); MinecraftVersion parent = manager.getVersionById(inheritsFrom);
if (parent == null) { if (parent == null) {

View File

@@ -118,12 +118,10 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
if (StrUtils.formatVersion(id) == null) { if (StrUtils.formatVersion(id) == null) {
if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
FileUtils.deleteDirectoryQuietly(dir); FileUtils.deleteDirectoryQuietly(dir);
} else if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_needs_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { } else if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_needs_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
if (!refreshJson(id)) { if (!refreshJson(id))
if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
FileUtils.deleteDirectoryQuietly(dir); FileUtils.deleteDirectoryQuietly(dir);
}
}
continue; continue;
} }
MinecraftVersion mcVersion; MinecraftVersion mcVersion;
@@ -226,7 +224,7 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) { public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) {
ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>(); ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>();
MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource()); MinecraftVersion v = profile.getSelectedMinecraftVersion().resolve(this, Settings.getInstance().getDownloadSource());
if(v.libraries != null) { if (v.libraries != null)
for (IMinecraftLibrary l : v.libraries) { for (IMinecraftLibrary l : v.libraries) {
l.init(); l.init();
if (l.allow()) { if (l.allow()) {
@@ -239,7 +237,6 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
} }
} }
} }
}
return downloadLibraries; return downloadLibraries;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class Natives implements Cloneable { public class Natives implements Cloneable {
public String windows, osx, linux; public String windows, osx, linux;
@Override @Override

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class OS { public class OS {
public String version, name; public String version, name;
} }

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.launcher.version;
* @author huangyuhui * @author huangyuhui
*/ */
public class Rules { public class Rules {
public String action; public String action;
public OS os; public OS os;
} }

View File

@@ -63,10 +63,9 @@ public class DraggableFrame extends JFrame
@Override @Override
public void mouseDragged(MouseEvent e) { public void mouseDragged(MouseEvent e) {
if ((e.getModifiersEx() & 0x400) != 0) { if ((e.getModifiersEx() & 0x400) != 0)
setLocation(e.getXOnScreen() - this.dragGripX, e.getYOnScreen() - this.dragGripY); setLocation(e.getXOnScreen() - this.dragGripX, e.getYOnScreen() - this.dragGripY);
} }
}
@Override @Override
public void mouseMoved(MouseEvent e) { public void mouseMoved(MouseEvent e) {

View File

@@ -48,7 +48,7 @@ public class HeaderTab extends JLabel
return this.isActive; return this.isActive;
} }
public void setIsActive(boolean isActive) { public final void setIsActive(boolean isActive) {
this.isActive = isActive; this.isActive = isActive;
setOpaque(isActive); setOpaque(isActive);

View File

@@ -259,9 +259,8 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
fc.setDialogTitle(C.i18n("launcher.choose_bgpath")); fc.setDialogTitle(C.i18n("launcher.choose_bgpath"));
fc.setMultiSelectionEnabled(false); fc.setMultiSelectionEnabled(false);
fc.showOpenDialog(this); fc.showOpenDialog(this);
if (fc.getSelectedFile() == null) { if (fc.getSelectedFile() == null)
return; return;
}
try { try {
String path = fc.getSelectedFile().getCanonicalPath(); String path = fc.getSelectedFile().getCanonicalPath();
path = IOUtils.removeLastSeparator(path); path = IOUtils.removeLastSeparator(path);

View File

@@ -86,7 +86,6 @@ public final class MainFrame extends DraggableFrame {
if (enableShadow) if (enableShadow)
try { try {
//AWTUtilities.setWindowOpaque(this, false);
setBackground(new Color(0, 0, 0, 0)); setBackground(new Color(0, 0, 0, 0));
getRootPane().setBorder(border = new DropShadowBorder(borderColor, 4)); getRootPane().setBorder(border = new DropShadowBorder(borderColor, 4));
} catch (Throwable ex) { } catch (Throwable ex) {

View File

@@ -25,13 +25,13 @@ import java.util.ResourceBundle;
* @author huangyuhui * @author huangyuhui
*/ */
public final class C { public final class C {
public static final Gson gsonPrettyPrinting = new GsonBuilder().setPrettyPrinting().create(); public static final Gson gsonPrettyPrinting = new GsonBuilder().setPrettyPrinting().create();
public static final Gson gson = new Gson(); public static final Gson gson = new Gson();
public static final ResourceBundle I18N = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N"); public static final ResourceBundle I18N = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N");
//http://repo1.maven.org/maven2 //http://repo1.maven.org/maven2
public static final String URL_PUBLISH = "http://www.mcbbs.net/thread-142335-1-1.html"; public static final String URL_PUBLISH = "http://www.mcbbs.net/thread-142335-1-1.html";
public static final String URL_TIEBA = "http://tieba.baidu.com/f?kw=hellominecraftlauncher"; public static final String URL_TIEBA = "http://tieba.baidu.com/f?kw=hellominecraftlauncher";
public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues"; public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues";
@@ -44,7 +44,8 @@ public final class C {
public static final String URL_FORGE_LIST = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json"; public static final String URL_FORGE_LIST = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json";
public static final String URL_LITELOADER_LIST = "http://dl.liteloader.com/versions/versions.json"; public static final String URL_LITELOADER_LIST = "http://dl.liteloader.com/versions/versions.json";
private C(){} private C() {
}
public static String i18n(String a, Object... format) { public static String i18n(String a, Object... format) {
try { try {

View File

@@ -18,7 +18,6 @@ package org.jackhuang.hellominecraft;
import org.jackhuang.hellominecraft.logging.logger.Logger; import org.jackhuang.hellominecraft.logging.logger.Logger;
/** /**
* *
* @author huangyuhui * @author huangyuhui

View File

@@ -21,18 +21,24 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public interface DoingDoneListener<K> { public interface DoingDoneListener<K> {
/** /**
* Task done. * Task done.
*
* @param k * @param k
*/ */
void onDone(K k); void onDone(K k);
/** /**
* Before task executing. * Before task executing.
*
* @param k * @param k
*/ */
void onDoing(K k); void onDoing(K k);
/** /**
* Task failed. * Task failed.
*
* @param k * @param k
*/ */
void onFailed(K k); void onFailed(K k);

View File

@@ -24,6 +24,7 @@ import java.util.HashSet;
* @author huangyuhui * @author huangyuhui
*/ */
public class ParallelTask extends Task { public class ParallelTask extends Task {
Collection<Task> dependsTask = new HashSet<>(); Collection<Task> dependsTask = new HashSet<>();
@Override @Override

View File

@@ -21,6 +21,7 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public abstract class ProgressProvider { public abstract class ProgressProvider {
protected ProgressProviderListener ppl; protected ProgressProviderListener ppl;
public ProgressProvider setProgressProviderListener(ProgressProviderListener p) { public ProgressProvider setProgressProviderListener(ProgressProviderListener p) {

View File

@@ -21,7 +21,10 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public interface ProgressProviderListener { public interface ProgressProviderListener {
void setProgress(int prog, int max); void setProgress(int prog, int max);
void setStatus(String sta); void setStatus(String sta);
void onProgressProviderDone(); void onProgressProviderDone();
} }

View File

@@ -26,25 +26,33 @@ public abstract class Task extends ProgressProvider {
/** /**
* Run in a new thread(packed in TaskList). * Run in a new thread(packed in TaskList).
*
* @return is task finished sucessfully. * @return is task finished sucessfully.
*/ */
public abstract boolean executeTask(); public abstract boolean executeTask();
/** /**
* if this func returns false, TaskList will force abort the thread. * if this func returns false, TaskList will force abort the thread. run in
* run in main thread. * main thread.
*
* @return is aborted. * @return is aborted.
*/ */
public boolean abort() { return false; } public boolean abort() {
return false;
}
public Throwable getFailReason() { return failReason; } public Throwable getFailReason() {
return failReason;
}
protected Throwable failReason = null; protected Throwable failReason = null;
protected void setFailReason(Throwable s) { protected void setFailReason(Throwable s) {
failReason = s; failReason = s;
} }
protected String tag; protected String tag;
protected boolean parallelExecuting; protected boolean parallelExecuting;
public Task setTag(String tag) { public Task setTag(String tag) {
this.tag = tag; this.tag = tag;
return this; return this;
@@ -60,6 +68,11 @@ public abstract class Task extends ProgressProvider {
public abstract String getInfo(); public abstract String getInfo();
public Collection<Task> getDependTasks() { return null; } public Collection<Task> getDependTasks() {
public Collection<Task> getAfterTasks() { return null; } return null;
}
public Collection<Task> getAfterTasks() {
return null;
}
} }

View File

@@ -87,9 +87,8 @@ public class TaskList extends Thread {
static final Set<Task> taskPool = Collections.synchronizedSet(new HashSet<Task>()); static final Set<Task> taskPool = Collections.synchronizedSet(new HashSet<Task>());
private void processTasks(Collection<Task> c) { private void processTasks(Collection<Task> c) {
if (c == null) { if (c == null)
return; return;
}
this.totTask += c.size(); this.totTask += c.size();
Set<InvokeThread> runningThread = Collections.synchronizedSet(new HashSet<InvokeThread>()); Set<InvokeThread> runningThread = Collections.synchronizedSet(new HashSet<InvokeThread>());
for (Task t2 : c) { for (Task t2 : c) {
@@ -99,41 +98,36 @@ public class TaskList extends Thread {
runningThread.add(thread); runningThread.add(thread);
thread.start(); thread.start();
} }
while (!runningThread.isEmpty()) { while (!runningThread.isEmpty())
try { try {
if (this.isInterrupted()) return; if (this.isInterrupted()) return;
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
HMCLog.warn("Failed to sleep task thread", ex); HMCLog.warn("Failed to sleep task thread", ex);
} }
}
} }
private void executeTask(Task t) { private void executeTask(Task t) {
if (!shouldContinue || t == null) { if (!shouldContinue || t == null)
return; return;
}
processTasks(t.getDependTasks()); processTasks(t.getDependTasks());
HMCLog.log("Executing task: " + t.getInfo()); HMCLog.log("Executing task: " + t.getInfo());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onDoing(t); d.onDoing(t);
}
if (t.executeTask()) { if (t.executeTask()) {
HMCLog.log("Task finished: " + t.getInfo()); HMCLog.log("Task finished: " + t.getInfo());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onDone(t); d.onDone(t);
}
processTasks(t.getAfterTasks()); processTasks(t.getAfterTasks());
} else { } else {
HMCLog.err("Task failed: " + t.getInfo(), t.getFailReason()); HMCLog.err("Task failed: " + t.getInfo(), t.getFailReason());
for (DoingDoneListener<Task> d : taskListener) { for (DoingDoneListener<Task> d : taskListener)
d.onFailed(t); d.onFailed(t);
} }
} }
}
@Override @Override
public void run() { public void run() {

View File

@@ -21,7 +21,9 @@ package org.jackhuang.hellominecraft.tasks;
* @author huangyuhui * @author huangyuhui
*/ */
public class TaskRunnable extends TaskInfo { public class TaskRunnable extends TaskInfo {
private final Runnable r; private final Runnable r;
public TaskRunnable(String info, Runnable r) { public TaskRunnable(String info, Runnable r) {
super(info); super(info);
this.r = r; this.r = r;

View File

@@ -230,7 +230,7 @@ public class TaskWindow extends javax.swing.JDialog
@Override @Override
public void onFailed(Task task) { public void onFailed(Task task) {
failReasons.add(task.getInfo() + ": " + (task.getFailReason() == null ? "No exception" : task.getFailReason().getLocalizedMessage())); failReasons.add(task.getInfo() + ": " + (null == task.getFailReason() ? "No exception" : task.getFailReason().getLocalizedMessage()));
pgsTotal.setMaximum(taskList.taskCount()); pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1); pgsTotal.setValue(pgsTotal.getValue() + 1);
SwingUtils.replaceLast(lstDownload, task.getFailReason()); SwingUtils.replaceLast(lstDownload, task.getFailReason());

View File

@@ -22,6 +22,7 @@ package org.jackhuang.hellominecraft.tasks.communication;
* @param <T> the type of result. * @param <T> the type of result.
*/ */
public class DefaultPreviousResult<T> implements PreviousResult<T> { public class DefaultPreviousResult<T> implements PreviousResult<T> {
T a; T a;
public DefaultPreviousResult(T a) { public DefaultPreviousResult(T a) {

View File

@@ -43,17 +43,13 @@ public class ArrayUtils {
} }
public static <T> int indexOf(T[] array, T valueToFind, int startIndex) { public static <T> int indexOf(T[] array, T valueToFind, int startIndex) {
if (array == null) { if (array == null)
return -1; return -1;
} if (startIndex < 0)
if (startIndex < 0) {
startIndex = 0; startIndex = 0;
} for (int i = startIndex; i < array.length; i++)
for (int i = startIndex; i < array.length; i++) { if (valueToFind.equals(array[i]))
if (valueToFind.equals(array[i])) {
return i; return i;
}
}
return -1; return -1;
} }
@@ -62,26 +58,22 @@ public class ArrayUtils {
} }
public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) { public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) {
if (array == null) { if (array == null)
return -1; return -1;
} if (startIndex < 0)
if (startIndex < 0) {
return -1; return -1;
} if (startIndex >= array.length)
if (startIndex >= array.length) {
startIndex = array.length - 1; startIndex = array.length - 1;
} for (int i = startIndex; i >= 0; i--)
for (int i = startIndex; i >= 0; i--) { if (valueToFind.equals(array[i]))
if (valueToFind.equals(array[i])) {
return i; return i;
}
}
return -1; return -1;
} }
public static ArrayList merge(List a, List b) { public static ArrayList merge(List a, List b) {
ArrayList al = new ArrayList(a.size() + b.size()); ArrayList al = new ArrayList(a.size() + b.size());
al.addAll(a); al.addAll(b); al.addAll(a);
al.addAll(b);
return al; return al;
} }
@@ -101,16 +93,14 @@ public class ArrayUtils {
for (int i = 0; i < a.length - b.length; i++) { for (int i = 0; i < a.length - b.length; i++) {
int j = 1; int j = 1;
for (int k = 0; k < b.length; k++) { for (int k = 0; k < b.length; k++) {
if (b[k].equals(a[(i + k)])) { if (b[k].equals(a[(i + k)]))
continue; continue;
}
j = 0; j = 0;
break; break;
} }
if (j != 0) { if (j != 0)
return i; return i;
} }
}
return -1; return -1;
} }
@@ -118,16 +108,14 @@ public class ArrayUtils {
for (int i = 0; i < a.length - b.length; i++) { for (int i = 0; i < a.length - b.length; i++) {
int j = 1; int j = 1;
for (int k = 0; k < b.length; k++) { for (int k = 0; k < b.length; k++) {
if (b[k] == a[(i + k)]) { if (b[k] == a[(i + k)])
continue; continue;
}
j = 0; j = 0;
break; break;
} }
if (j != 0) { if (j != 0)
return i; return i;
} }
}
return -1; return -1;
} }
} }

View File

@@ -27,13 +27,16 @@ import java.util.Iterator;
* @author huangyuhui * @author huangyuhui
*/ */
public final class CollectionUtils { public final class CollectionUtils {
public static <T> void forEach(Collection<T> coll, Consumer<T> p) { public static <T> void forEach(Collection<T> coll, Consumer<T> p) {
for (T t : coll) p.accept(t); for (T t : coll) p.accept(t);
} }
public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) { public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) {
ArrayList<T> newColl = new ArrayList<>(); ArrayList<T> newColl = new ArrayList<>();
forEach(coll, t -> { if(p.apply(t)) newColl.add(t); }); forEach(coll, t -> {
if (p.apply(t)) newColl.add(t);
});
return newColl; return newColl;
} }

View File

@@ -41,62 +41,49 @@ public class DoubleOutputStream extends OutputStream {
@Override @Override
public final void write(byte[] arr, int off, int len) throws IOException { public final void write(byte[] arr, int off, int len) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(arr, off, len); this.a.write(arr, off, len);
} if (this.b != null)
if (this.b != null) {
this.b.write(arr, off, len); this.b.write(arr, off, len);
} if (this.c)
if (this.c) {
flush(); flush();
} }
}
@Override @Override
public final void write(byte[] paramArrayOfByte) throws IOException { public final void write(byte[] paramArrayOfByte) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(paramArrayOfByte); this.a.write(paramArrayOfByte);
} if (this.b != null)
if (this.b != null) {
this.b.write(paramArrayOfByte); this.b.write(paramArrayOfByte);
} if (this.c)
if (this.c) {
flush(); flush();
} }
}
@Override @Override
public final void write(int paramInt) throws IOException { public final void write(int paramInt) throws IOException {
if (this.a != null) { if (this.a != null)
this.a.write(paramInt); this.a.write(paramInt);
} if (this.b != null)
if (this.b != null) {
this.b.write(paramInt); this.b.write(paramInt);
} if (this.c)
if (this.c) {
flush(); flush();
} }
}
@Override @Override
public final void close() throws IOException { public final void close() throws IOException {
flush(); flush();
if (this.a != null) { if (this.a != null)
this.a.close(); this.a.close();
} if (this.b != null)
if (this.b != null) {
this.b.close(); this.b.close();
} }
}
@Override @Override
public final void flush() throws IOException { public final void flush() throws IOException {
if (this.a != null) { if (this.a != null)
this.a.flush(); this.a.flush();
} if (this.b != null)
if (this.b != null) {
this.b.flush(); this.b.flush();
} }
} }
}

View File

@@ -22,5 +22,6 @@ package org.jackhuang.hellominecraft.utils;
* @param <T> EventArgs * @param <T> EventArgs
*/ */
public interface Event<T> { public interface Event<T> {
boolean call(Object sender, T t); boolean call(Object sender, T t);
} }

View File

@@ -24,6 +24,7 @@ import java.util.HashSet;
* @param <T> EventArgs * @param <T> EventArgs
*/ */
public class EventHandler<T> { public class EventHandler<T> {
HashSet<Event<T>> handlers; HashSet<Event<T>> handlers;
Object sender; Object sender;

View File

@@ -37,10 +37,9 @@ public class LauncherPrintStream extends PrintStream {
public final void println(String paramString) { public final void println(String paramString) {
super.println(paramString); super.println(paramString);
for (Consumer<String> a1 : printListeners) { for (Consumer<String> a1 : printListeners)
a1.accept(paramString); a1.accept(paramString);
} }
}
public final void addPrintListener(Consumer<String> paraml) { public final void addPrintListener(Consumer<String> paraml) {
this.printListeners.add(paraml); this.printListeners.add(paraml);

View File

@@ -39,9 +39,8 @@ public final class NetUtils {
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
byte[] arrayOfByte1 = new byte[1024]; byte[] arrayOfByte1 = new byte[1024];
int i; int i;
while ((i = is.read(arrayOfByte1)) >= 0) { while ((i = is.read(arrayOfByte1)) >= 0)
localByteArrayOutputStream.write(arrayOfByte1, 0, i); localByteArrayOutputStream.write(arrayOfByte1, 0, i);
}
is.close(); is.close();
return localByteArrayOutputStream.toByteArray(); return localByteArrayOutputStream.toByteArray();
} }
@@ -56,10 +55,9 @@ public final class NetUtils {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding))) {
result = ""; result = "";
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null)
result += line + "\n"; result += line + "\n";
} }
}
if (result.length() < 1) return ""; if (result.length() < 1) return "";
else return result.substring(0, result.length() - 1); else return result.substring(0, result.length() - 1);
} }
@@ -85,16 +83,15 @@ public final class NetUtils {
public static String sendGetRequest(String endpoint, public static String sendGetRequest(String endpoint,
String requestParameters) { String requestParameters) {
String result = null; String result = null;
if (endpoint.startsWith("http://")) { if (endpoint.startsWith("http://"))
// Send a GET request to the servlet // Send a GET request to the servlet
try { try {
// Construct data // Construct data
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
// Send data // Send data
String urlStr = endpoint; String urlStr = endpoint;
if (requestParameters != null && requestParameters.length() > 0) { if (requestParameters != null && requestParameters.length() > 0)
urlStr += "?" + requestParameters; urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr); URL url = new URL(urlStr);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
@@ -110,7 +107,6 @@ public final class NetUtils {
} catch (Exception e) { } catch (Exception e) {
HMCLog.warn("Failed to send get request.", e); HMCLog.warn("Failed to send get request.", e);
} }
}
return result; return result;
} }
@@ -176,9 +172,8 @@ public final class NetUtils {
public static URL concatenateURL(URL url, String query) { public static URL concatenateURL(URL url, String query) {
try { try {
if ((url.getQuery() != null) && (url.getQuery().length() > 0)) { if ((url.getQuery() != null) && (url.getQuery().length() > 0))
return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("&").append(query).toString()); return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("&").append(query).toString());
}
return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("?").append(query).toString()); return new URL(url.getProtocol(), url.getHost(), url.getPort(), new StringBuilder().append(url.getFile()).append("?").append(query).toString());
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex); throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex);

View File

@@ -25,6 +25,7 @@ import java.util.Map;
* @param <V> V Type * @param <V> V Type
*/ */
public class Pair<K, V> implements Map.Entry<K, V> { public class Pair<K, V> implements Map.Entry<K, V> {
public K key; public K key;
public V value; public V value;

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2013 huangyuhui <huanghongxun2008@126.com>
*
* 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 2 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.
*/
package org.jackhuang.hellominecraft.utils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author huangyuhui
*/
public class ReflectUtils {
public static Set<? extends Class<?>> getClasses(Class c) {
HashSet set = new HashSet();
set.addAll(Arrays.asList(c.getInterfaces()));
while(c != Object.class) {
set.add(c);
c = c.getSuperclass();
}
return set;
}
}

View File

@@ -32,6 +32,14 @@ import org.jackhuang.hellominecraft.HMCLog;
*/ */
public class SwingUtils { public class SwingUtils {
/**
* Make DefaultTableModel by overriding getColumnClass and isCellEditable of DefaultTableModel.
*
* @param titleA The title of each column.
* @param typesA The type of each column value.
* @param canEditA Is column editable?
* @return
*/
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) { public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
return new javax.swing.table.DefaultTableModel( return new javax.swing.table.DefaultTableModel(
new Object[][]{}, new Object[][]{},
@@ -51,6 +59,10 @@ public class SwingUtils {
}; };
} }
/**
* Open URL by java.awt.Desktop
* @param link
*/
public static void openLink(URI link) { public static void openLink(URI link) {
try { try {
java.awt.Desktop.getDesktop().browse(link); java.awt.Desktop.getDesktop().browse(link);
@@ -59,20 +71,38 @@ public class SwingUtils {
} }
} }
/**
* Move the cursor to the end of TextArea.
* @param tf the TextArea
*/
public static void moveEnd(JTextArea tf) { public static void moveEnd(JTextArea tf) {
int position = tf.getText().length(); int position = tf.getText().length();
tf.setCaretPosition(position); tf.setCaretPosition(position);
} }
/**
* Move the cursor to the end of ScrollPane.
* @param pane the ScrollPane
*/
public static void moveEnd(JScrollPane pane) { public static void moveEnd(JScrollPane pane) {
JScrollBar bar = pane.getVerticalScrollBar(); JScrollBar bar = pane.getVerticalScrollBar();
bar.setValue(bar.getMaximum()); bar.setValue(bar.getMaximum());
} }
/**
* Get the DefaultListModel from JList.
* @param list
* @return Forcely Type casted to DefaultListModel
*/
public static DefaultListModel getDefaultListModel(JList list) { public static DefaultListModel getDefaultListModel(JList list) {
return (DefaultListModel) list.getModel(); return (DefaultListModel) list.getModel();
} }
/**
* Append new element to JList
* @param list the JList
* @param element the Element
*/
public static void appendLast(JList list, Object element) { public static void appendLast(JList list, Object element) {
getDefaultListModel(list).addElement(element); getDefaultListModel(list).addElement(element);
} }
@@ -86,11 +116,14 @@ public class SwingUtils {
list.setModel(new DefaultListModel()); list.setModel(new DefaultListModel());
} }
/**
* Clear the JTable
* @param table JTable with DefaultTableModel.
*/
public static void clearDefaultTable(JTable table) { public static void clearDefaultTable(JTable table) {
DefaultTableModel model = (DefaultTableModel) table.getModel(); DefaultTableModel model = (DefaultTableModel) table.getModel();
while(model.getRowCount() > 0) { while (model.getRowCount() > 0)
model.removeRow(0); model.removeRow(0);
}
table.updateUI(); table.updateUI();
} }

View File

@@ -26,6 +26,7 @@ import org.jackhuang.hellominecraft.HMCLog;
* @author huangyuhui * @author huangyuhui
*/ */
public final class UpdateChecker extends Thread { public final class UpdateChecker extends Thread {
public static boolean OUT_DATED = false; public static boolean OUT_DATED = false;
public VersionNumber base; public VersionNumber base;
public String type; public String type;
@@ -53,25 +54,22 @@ public final class UpdateChecker extends Thread {
return; return;
} }
value = VersionNumber.check(version); value = VersionNumber.check(version);
if (!continueUpdate) { if (!continueUpdate)
return; return;
}
process(false); process(false);
} }
public void process(boolean showMessage) { public void process(boolean showMessage) {
if (value == null) { if (value == null) {
HMCLog.warn("Failed to check update..."); HMCLog.warn("Failed to check update...");
if(showMessage) { if (showMessage)
MessageBox.Show(C.i18n("update.failed")); MessageBox.Show(C.i18n("update.failed"));
} } else
} else {
if (VersionNumber.isOlder(base, value)) { if (VersionNumber.isOlder(base, value)) {
OUT_DATED = true; OUT_DATED = true;
dl.onDone(); dl.onDone();
} }
} }
}
public VersionNumber getNewVersion() { public VersionNumber getNewVersion() {
return value; return value;

View File

@@ -46,6 +46,7 @@ import org.jackhuang.hellominecraft.HMCLog;
public final class Utils { public final class Utils {
private static final GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting(); private static final GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
public static GsonBuilder getDefaultGsonBuilder() { public static GsonBuilder getDefaultGsonBuilder() {
return gsonBuilder; return gsonBuilder;
} }
@@ -53,13 +54,12 @@ public final class Utils {
public static String[] getURL() { public static String[] getURL() {
URL[] urls = ((URLClassLoader) Utils.class.getClassLoader()).getURLs(); URL[] urls = ((URLClassLoader) Utils.class.getClassLoader()).getURLs();
String[] urlStrings = new String[urls.length]; String[] urlStrings = new String[urls.length];
for (int i = 0; i < urlStrings.length; i++) { for (int i = 0; i < urlStrings.length; i++)
try { try {
urlStrings[i] = URLDecoder.decode(urls[i].getPath(), "UTF-8"); urlStrings[i] = URLDecoder.decode(urls[i].getPath(), "UTF-8");
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
HMCLog.warn("Unsupported UTF-8 encoding", ex); HMCLog.warn("Unsupported UTF-8 encoding", ex);
} }
}
return urlStrings; return urlStrings;
} }
@@ -163,7 +163,7 @@ public final class Utils {
if (!loaded) { if (!loaded) {
File backgroundImageFile = new File("background.jpg"); File backgroundImageFile = new File("background.jpg");
if (backgroundImageFile.exists()) { if (backgroundImageFile.exists()) {
loaded = true; //loaded = true;
background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT)); background = new ImageIcon(Toolkit.getDefaultToolkit().getImage(backgroundImageFile.getAbsolutePath()).getScaledInstance(width, height, Image.SCALE_DEFAULT));
HMCLog.log("Prepared background image in background.jpg."); HMCLog.log("Prepared background image in background.jpg.");
} }

View File

@@ -27,16 +27,16 @@ public final class VersionNumber implements Comparable<VersionNumber> {
public byte firstVer, secondVer, thirdVer; public byte firstVer, secondVer, thirdVer;
public VersionNumber(byte a, byte b, byte c) { public VersionNumber(byte a, byte b, byte c) {
firstVer = a; secondVer = b; thirdVer = c; firstVer = a;
secondVer = b;
thirdVer = c;
} }
public static VersionNumber check(String data) { public static VersionNumber check(String data) {
while (!data.isEmpty() && ((data.charAt(0) < '0' || data.charAt(0) > '9') && data.charAt(0) != '.')) { while (!data.isEmpty() && ((data.charAt(0) < '0' || data.charAt(0) > '9') && data.charAt(0) != '.'))
data = data.substring(1); data = data.substring(1);
} if (data.isEmpty())
if (data.isEmpty()) {
return null; return null;
}
VersionNumber ur; VersionNumber ur;
String[] ver = data.split("\\."); String[] ver = data.split("\\.");
if (ver.length == 3) { if (ver.length == 3) {
@@ -55,17 +55,14 @@ public final class VersionNumber implements Comparable<VersionNumber> {
} }
public static boolean isOlder(VersionNumber a, VersionNumber b) { public static boolean isOlder(VersionNumber a, VersionNumber b) {
if (a.firstVer < b.firstVer) { if (a.firstVer < b.firstVer)
return true; return true;
} else if (a.firstVer == b.firstVer) { else if (a.firstVer == b.firstVer)
if (a.secondVer < b.secondVer) { if (a.secondVer < b.secondVer)
return true; return true;
} else if (a.secondVer == b.secondVer) { else if (a.secondVer == b.secondVer)
if (a.thirdVer < b.thirdVer) { if (a.thirdVer < b.thirdVer)
return true; return true;
}
}
}
return false; return false;
} }

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.code; package org.jackhuang.hellominecraft.utils.code;
import org.jackhuang.hellominecraft.utils.code.Hex;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.MessageDigest; import java.security.MessageDigest;

View File

@@ -20,5 +20,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface BiConsumer<V, V2> { public interface BiConsumer<V, V2> {
void onDone(V value, V2 value2); void onDone(V value, V2 value2);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface BiFunction<A, B, C> { public interface BiFunction<A, B, C> {
C apply(A a, B b); C apply(A a, B b);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Consumer<T> { public interface Consumer<T> {
void accept(T t); void accept(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Function<T, R> { public interface Function<T, R> {
R apply(T t); R apply(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface NonConsumer { public interface NonConsumer {
void onDone(); void onDone();
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface NonFunction<T> { public interface NonFunction<T> {
T onDone(); T onDone();
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface Predicate<T> { public interface Predicate<T> {
boolean apply(T t); boolean apply(T t);
} }

View File

@@ -21,5 +21,6 @@ package org.jackhuang.hellominecraft.utils.functions;
* @author huangyuhui * @author huangyuhui
*/ */
public interface TriConsumer<V1, V2, V3> { public interface TriConsumer<V1, V2, V3> {
void onDone(V1 v1, V2 v2, V3 v3); void onDone(V1 v1, V2 v2, V3 v3);
} }

View File

@@ -52,11 +52,10 @@ public class Compressor {
BufferedOutputStream bos = new BufferedOutputStream(os); BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) { try (ZipOutputStream zos = new ZipOutputStream(bos)) {
String basePath; String basePath;
if (sourceDir.isDirectory()) { if (sourceDir.isDirectory())
basePath = sourceDir.getPath(); basePath = sourceDir.getPath();
} else {//直接压缩单个文件时,取父目录 else//直接压缩单个文件时,取父目录
basePath = sourceDir.getParent(); basePath = sourceDir.getParent();
}
zipFile(sourceDir, basePath, zos); zipFile(sourceDir, basePath, zos);
zos.closeEntry(); zos.closeEntry();
} }
@@ -72,22 +71,21 @@ public class Compressor {
private static void zipFile(File source, String basePath, private static void zipFile(File source, String basePath,
ZipOutputStream zos) throws IOException { ZipOutputStream zos) throws IOException {
File[] files; File[] files;
if (source.isDirectory()) { if (source.isDirectory())
files = source.listFiles(); files = source.listFiles();
} else { else {
files = new File[1]; files = new File[1];
files[0] = source; files[0] = source;
} }
String pathName;//存相对路径(相对于待压缩的根目录) String pathName;//存相对路径(相对于待压缩的根目录)
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int length; int length;
for (File file : files) { for (File file : files)
if (file.isDirectory()) { if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) pathName = file.getPath().substring(basePath.length() + 1)
+ "/"; + "/";
if (file.getName().toLowerCase().contains("meta-inf")) { if (file.getName().toLowerCase().contains("meta-inf"))
continue; continue;
}
zos.putNextEntry(new ZipEntry(pathName)); zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos); zipFile(file, basePath, zos);
} else { } else {
@@ -95,13 +93,11 @@ public class Compressor {
try (InputStream is = new FileInputStream(file)) { try (InputStream is = new FileInputStream(file)) {
BufferedInputStream bis = new BufferedInputStream(is); BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName)); zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) { while ((length = bis.read(buf)) > 0)
zos.write(buf, 0, length); zos.write(buf, 0, length);
} }
} }
} }
}
}
public static void unzip(String zipFileName, String extPlace) throws IOException { public static void unzip(String zipFileName, String extPlace) throws IOException {
unzip(new File(zipFileName), new File(extPlace)); unzip(new File(zipFileName), new File(extPlace));
@@ -142,15 +138,13 @@ public class Compressor {
strtemp = strPath + File.separator + gbkPath; strtemp = strPath + File.separator + gbkPath;
//建目录 //建目录
String strsubdir = gbkPath; String strsubdir = gbkPath;
for (int i = 0; i < strsubdir.length(); i++) { for (int i = 0; i < strsubdir.length(); i++)
if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) { if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
String temp = strPath + File.separator + strsubdir.substring(0, i); String temp = strPath + File.separator + strsubdir.substring(0, i);
File subdir = new File(temp); File subdir = new File(temp);
if (!subdir.exists()) { if (!subdir.exists())
subdir.mkdir(); subdir.mkdir();
} }
}
}
try (FileOutputStream fos = new FileOutputStream(strtemp); BufferedOutputStream bos = new BufferedOutputStream(fos)) { try (FileOutputStream fos = new FileOutputStream(strtemp); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int c; int c;
while ((c = bis.read()) != -1) while ((c = bis.read()) != -1)

View File

@@ -37,13 +37,11 @@ public class FileUtils {
public static void deleteDirectory(File directory) public static void deleteDirectory(File directory)
throws IOException { throws IOException {
if (!directory.exists()) { if (!directory.exists())
return; return;
}
if (!isSymlink(directory)) { if (!isSymlink(directory))
cleanDirectory(directory); cleanDirectory(directory);
}
if (!directory.delete()) { if (!directory.delete()) {
String message = "Unable to delete directory " + directory + "."; String message = "Unable to delete directory " + directory + ".";
@@ -87,34 +85,30 @@ public class FileUtils {
} }
File[] files = directory.listFiles(); File[] files = directory.listFiles();
if (files == null) { if (files == null)
throw new IOException("Failed to list contents of " + directory); throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null; IOException exception = null;
for (File file : files) { for (File file : files)
try { try {
forceDelete(file); forceDelete(file);
} catch (IOException ioe) { } catch (IOException ioe) {
exception = ioe; exception = ioe;
} }
}
if (null != exception) { if (null != exception)
throw exception; throw exception;
} }
}
public static void forceDelete(File file) public static void forceDelete(File file)
throws IOException { throws IOException {
if (file.isDirectory()) { if (file.isDirectory())
deleteDirectory(file); deleteDirectory(file);
} else { else {
boolean filePresent = file.exists(); boolean filePresent = file.exists();
if (!file.delete()) { if (!file.delete()) {
if (!filePresent) { if (!filePresent)
throw new FileNotFoundException("File does not exist: " + file); throw new FileNotFoundException("File does not exist: " + file);
}
String message = "Unable to delete file: " + file; String message = "Unable to delete file: " + file;
throw new IOException(message); throw new IOException(message);
@@ -124,16 +118,14 @@ public class FileUtils {
public static boolean isSymlink(File file) public static boolean isSymlink(File file)
throws IOException { throws IOException {
if (file == null) { if (file == null)
throw new NullPointerException("File must not be null"); throw new NullPointerException("File must not be null");
} if (File.separatorChar == '\\')
if (File.separatorChar == '\\') {
return false; return false;
}
File fileInCanonicalDir; File fileInCanonicalDir;
if (file.getParent() == null) { if (file.getParent() == null)
fileInCanonicalDir = file; fileInCanonicalDir = file;
} else { else {
File canonicalDir = file.getParentFile().getCanonicalFile(); File canonicalDir = file.getParentFile().getCanonicalFile();
fileInCanonicalDir = new File(canonicalDir, file.getName()); fileInCanonicalDir = new File(canonicalDir, file.getName());
} }
@@ -158,21 +150,16 @@ public class FileUtils {
public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcDir == null) { if (srcDir == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
} if (destDir == null)
if (destDir == null) {
throw new NullPointerException("Destination must not be null"); throw new NullPointerException("Destination must not be null");
} if (!srcDir.exists())
if (!srcDir.exists()) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
} if (!srcDir.isDirectory())
if (!srcDir.isDirectory()) {
throw new IOException("Source '" + srcDir + "' exists but is not a directory"); throw new IOException("Source '" + srcDir + "' exists but is not a directory");
} if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath()))
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
}
List exclusionList = null; List exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
@@ -191,36 +178,29 @@ public class FileUtils {
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList) private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList)
throws IOException { throws IOException {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null) { if (srcFiles == null)
throw new IOException("Failed to list contents of " + srcDir); throw new IOException("Failed to list contents of " + srcDir);
}
if (destDir.exists()) { if (destDir.exists()) {
if (!destDir.isDirectory()) { if (!destDir.isDirectory())
throw new IOException("Destination '" + destDir + "' exists but is not a directory"); throw new IOException("Destination '" + destDir + "' exists but is not a directory");
} } else if ((!destDir.mkdirs()) && (!destDir.isDirectory()))
} else if ((!destDir.mkdirs()) && (!destDir.isDirectory())) {
throw new IOException("Destination '" + destDir + "' directory cannot be created"); throw new IOException("Destination '" + destDir + "' directory cannot be created");
}
if (!destDir.canWrite()) { if (!destDir.canWrite())
throw new IOException("Destination '" + destDir + "' cannot be written to"); throw new IOException("Destination '" + destDir + "' cannot be written to");
}
for (File srcFile : srcFiles) { for (File srcFile : srcFiles) {
File dstFile = new File(destDir, srcFile.getName()); File dstFile = new File(destDir, srcFile.getName());
if ((exclusionList == null) || (!exclusionList.contains(srcFile.getCanonicalPath()))) { if ((exclusionList == null) || (!exclusionList.contains(srcFile.getCanonicalPath())))
if (srcFile.isDirectory()) { if (srcFile.isDirectory())
doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList); doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
} else { else
doCopyFile(srcFile, dstFile, preserveFileDate); doCopyFile(srcFile, dstFile, preserveFileDate);
}
}
} }
if (preserveFileDate) { if (preserveFileDate)
destDir.setLastModified(srcDir.lastModified()); destDir.setLastModified(srcDir.lastModified());
} }
}
public static String readFileToString(File file) public static String readFileToString(File file)
throws IOException { throws IOException {
@@ -256,38 +236,30 @@ public class FileUtils {
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) public static void copyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if (srcFile == null) { if (srcFile == null)
throw new NullPointerException("Source must not be null"); throw new NullPointerException("Source must not be null");
} if (destFile == null)
if (destFile == null) {
throw new NullPointerException("Destination must not be null"); throw new NullPointerException("Destination must not be null");
} if (!srcFile.exists())
if (!srcFile.exists()) {
throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
} if (srcFile.isDirectory())
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' exists but is a directory"); throw new IOException("Source '" + srcFile + "' exists but is a directory");
} if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath()))
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
}
File parentFile = destFile.getParentFile(); File parentFile = destFile.getParentFile();
if ((parentFile != null) if ((parentFile != null)
&& (!parentFile.mkdirs()) && (!parentFile.isDirectory())) { && (!parentFile.mkdirs()) && (!parentFile.isDirectory()))
throw new IOException("Destination '" + parentFile + "' directory cannot be created"); throw new IOException("Destination '" + parentFile + "' directory cannot be created");
}
if ((destFile.exists()) && (!destFile.canWrite())) { if ((destFile.exists()) && (!destFile.canWrite()))
throw new IOException("Destination '" + destFile + "' exists but is read-only"); throw new IOException("Destination '" + destFile + "' exists but is read-only");
}
doCopyFile(srcFile, destFile, preserveFileDate); doCopyFile(srcFile, destFile, preserveFileDate);
} }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException { throws IOException {
if ((destFile.exists()) && (destFile.isDirectory())) { if ((destFile.exists()) && (destFile.isDirectory()))
throw new IOException("Destination '" + destFile + "' exists but is a directory"); throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null; FileInputStream fis = null;
FileOutputStream fos = null; FileOutputStream fos = null;
@@ -312,37 +284,32 @@ public class FileUtils {
IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fis);
} }
if (srcFile.length() != destFile.length()) { if (srcFile.length() != destFile.length())
throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
}
if (preserveFileDate) { if (preserveFileDate)
destFile.setLastModified(srcFile.lastModified()); destFile.setLastModified(srcFile.lastModified());
} }
}
public static int indexOfLastSeparator(String filename) { public static int indexOfLastSeparator(String filename) {
if (filename == null) { if (filename == null)
return -1; return -1;
}
int lastUnixPos = filename.lastIndexOf(47); int lastUnixPos = filename.lastIndexOf(47);
int lastWindowsPos = filename.lastIndexOf(92); int lastWindowsPos = filename.lastIndexOf(92);
return Math.max(lastUnixPos, lastWindowsPos); return Math.max(lastUnixPos, lastWindowsPos);
} }
public static int indexOfExtension(String filename) { public static int indexOfExtension(String filename) {
if (filename == null) { if (filename == null)
return -1; return -1;
}
int extensionPos = filename.lastIndexOf(46); int extensionPos = filename.lastIndexOf(46);
int lastSeparator = indexOfLastSeparator(filename); int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos ? -1 : extensionPos; return lastSeparator > extensionPos ? -1 : extensionPos;
} }
public static String getName(String filename) { public static String getName(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
}
int index = indexOfLastSeparator(filename); int index = indexOfLastSeparator(filename);
return filename.substring(index + 1); return filename.substring(index + 1);
} }
@@ -352,24 +319,20 @@ public class FileUtils {
} }
public static String getExtension(String filename) { public static String getExtension(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
}
int index = indexOfExtension(filename); int index = indexOfExtension(filename);
if (index == -1) { if (index == -1)
return ""; return "";
}
return filename.substring(index + 1); return filename.substring(index + 1);
} }
public static String removeExtension(String filename) { public static String removeExtension(String filename) {
if (filename == null) { if (filename == null)
return null; return null;
}
int index = indexOfExtension(filename); int index = indexOfExtension(filename);
if (index == -1) { if (index == -1)
return filename; return filename;
}
return filename.substring(0, index); return filename.substring(0, index);
} }
@@ -427,15 +390,12 @@ public class FileUtils {
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canRead())
if (!file.canRead()) {
throw new IOException("File '" + file + "' cannot be read"); throw new IOException("File '" + file + "' cannot be read");
} } else
} else {
throw new FileNotFoundException("File '" + file + "' does not exist"); throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file); return new FileInputStream(file);
} }
@@ -447,18 +407,15 @@ public class FileUtils {
public static FileOutputStream openOutputStream(File file, boolean append) public static FileOutputStream openOutputStream(File file, boolean append)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canWrite())
if (!file.canWrite()) {
throw new IOException("File '" + file + "' cannot be written to"); throw new IOException("File '" + file + "' cannot be written to");
}
} else { } else {
File parent = file.getParentFile(); File parent = file.getParentFile();
if ((parent != null) if ((parent != null)
&& (!parent.mkdirs()) && (!parent.isDirectory())) { && (!parent.mkdirs()) && (!parent.isDirectory()))
throw new IOException("Directory '" + parent + "' could not be created"); throw new IOException("Directory '" + parent + "' could not be created");
}
file.createNewFile(); file.createNewFile();
} }

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.system; package org.jackhuang.hellominecraft.utils.system;
import org.jackhuang.hellominecraft.utils.system.OS;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.Closeable; import java.io.Closeable;
import java.io.File; import java.io.File;
@@ -43,15 +42,13 @@ import org.jackhuang.hellominecraft.HMCLog;
public class IOUtils { public class IOUtils {
public static String addSeparator(String path) { public static String addSeparator(String path) {
if (path == null || path.trim().length() == 0) { if (path == null || path.trim().length() == 0)
return ""; return "";
} if (isSeparator(path.charAt(path.length() - 1)))
if (isSeparator(path.charAt(path.length() - 1))) {
return path; return path;
} else { else
return path + File.separatorChar; return path + File.separatorChar;
} }
}
public static boolean isSeparator(char ch) { public static boolean isSeparator(char ch) {
return ch == File.separatorChar || ch == '/' || ch == '\\'; return ch == File.separatorChar || ch == '/' || ch == '\\';
@@ -60,21 +57,18 @@ public class IOUtils {
public static String removeLastSeparator(String dir) { public static String removeLastSeparator(String dir) {
String t = dir.trim(); String t = dir.trim();
char ch = t.charAt(t.length() - 1); char ch = t.charAt(t.length() - 1);
if (isSeparator(ch)) { if (isSeparator(ch))
return t.substring(0, t.length() - 1); return t.substring(0, t.length() - 1);
}
return t; return t;
} }
public static String extractLastDirectory(String dir) { public static String extractLastDirectory(String dir) {
String t = removeLastSeparator(dir); String t = removeLastSeparator(dir);
int i = t.length() - 1; int i = t.length() - 1;
while (i >= 0 && !isSeparator(dir.charAt(i))) { while (i >= 0 && !isSeparator(dir.charAt(i)))
i--; i--;
} if (i < 0)
if (i < 0) {
return t; return t;
}
return t.substring(i + 1, (t.length() - i) + (i + 1) - 1); return t.substring(i + 1, (t.length() - i) + (i + 1) - 1);
} }
@@ -83,12 +77,10 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isFile()) { if (f1[i].isFile())
arr.add(f1[i].getName()); arr.add(f1[i].getName());
} }
}
}
return arr; return arr;
} }
@@ -97,12 +89,10 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isFile()) { if (f1[i].isFile())
arr.add(addSeparator(f.getAbsolutePath()) + f1[i].getName()); arr.add(addSeparator(f.getAbsolutePath()) + f1[i].getName());
} }
}
}
return arr; return arr;
} }
@@ -111,12 +101,10 @@ public class IOUtils {
if (f.isDirectory()) { if (f.isDirectory()) {
File[] f1 = f.listFiles(); File[] f1 = f.listFiles();
int len = f1.length; int len = f1.length;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++)
if (f1[i].isDirectory()) { if (f1[i].isDirectory())
arr.add(f1[i].getName()); arr.add(f1[i].getName());
} }
}
}
return arr; return arr;
} }
@@ -152,9 +140,8 @@ public class IOUtils {
for (int i = 0; i < macs.length; i++) { for (int i = 0; i < macs.length; i++) {
mac = Integer.toHexString(macs[i] & 0xFF); mac = Integer.toHexString(macs[i] & 0xFF);
if (mac.length() == 1) { if (mac.length() == 1)
mac = '0' + mac; mac = '0' + mac;
}
sb.append(mac).append("-"); sb.append(mac).append("-");
} }
@@ -179,12 +166,11 @@ public class IOUtils {
public static String getJavaDir() { public static String getJavaDir() {
String path = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar; String path = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar;
path = addSeparator(path); path = addSeparator(path);
if (OS.os() == OS.WINDOWS && new File(path + "javaw.exe").isFile()) { if (OS.os() == OS.WINDOWS && new File(path + "javaw.exe").isFile())
return path + "javaw.exe"; return path + "javaw.exe";
} else { else
return path + "java"; return path + "java";
} }
}
public static byte[] readFully(InputStream stream) throws IOException { public static byte[] readFully(InputStream stream) throws IOException {
byte[] data = new byte[4096]; byte[] data = new byte[4096];
@@ -192,9 +178,8 @@ public class IOUtils {
int len; int len;
do { do {
len = stream.read(data); len = stream.read(data);
if (len <= 0) { if (len <= 0)
continue; continue;
}
entryBuffer.write(data, 0, len); entryBuffer.write(data, 0, len);
} while (len != -1); } while (len != -1);
@@ -219,39 +204,33 @@ public class IOUtils {
public static void closeQuietly(Closeable closeable) { public static void closeQuietly(Closeable closeable) {
try { try {
if (closeable != null) { if (closeable != null)
closeable.close(); closeable.close();
}
} catch (IOException ioe) { } catch (IOException ioe) {
} }
} }
public static void write(byte[] data, OutputStream output) public static void write(byte[] data, OutputStream output)
throws IOException { throws IOException {
if (data != null) { if (data != null)
output.write(data); output.write(data);
} }
}
public static void write(String data, OutputStream output, String encoding) public static void write(String data, OutputStream output, String encoding)
throws IOException { throws IOException {
if (data != null) { if (data != null)
output.write(data.getBytes(encoding)); output.write(data.getBytes(encoding));
} }
}
public static FileInputStream openInputStream(File file) public static FileInputStream openInputStream(File file)
throws IOException { throws IOException {
if (file.exists()) { if (file.exists()) {
if (file.isDirectory()) { if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory"); throw new IOException("File '" + file + "' exists but is a directory");
} if (!file.canRead())
if (!file.canRead()) {
throw new IOException("File '" + file + "' cannot be read"); throw new IOException("File '" + file + "' cannot be read");
} } else
} else {
throw new FileNotFoundException("File '" + file + "' does not exist"); throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file); return new FileInputStream(file);
} }

View File

@@ -16,7 +16,6 @@
*/ */
package org.jackhuang.hellominecraft.utils.system; package org.jackhuang.hellominecraft.utils.system;
import org.jackhuang.hellominecraft.utils.system.ProcessManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;

View File

@@ -113,14 +113,10 @@ public final class JdkVersion {
private static int parseVersion(String javaVersion) { private static int parseVersion(String javaVersion) {
if (StrUtils.isBlank(javaVersion)) return UNKOWN; if (StrUtils.isBlank(javaVersion)) return UNKOWN;
int a = UNKOWN; int a = UNKOWN;
if (javaVersion.contains("1.9.")) if (javaVersion.contains("1.9.")) a = JAVA_19;
a = JAVA_19; else if (javaVersion.contains("1.8.")) a = JAVA_18;
else if (javaVersion.contains("1.8.")) else if (javaVersion.contains("1.7.")) a = JAVA_17;
a = JAVA_18; else if (javaVersion.contains("1.6.")) a = JAVA_16;
else if (javaVersion.contains("1.7."))
a = JAVA_17;
else if (javaVersion.contains("1.6."))
a = JAVA_16;
return a; return a;
} }

View File

@@ -22,8 +22,8 @@ import org.jackhuang.hellominecraft.C;
/** /**
* @author huangyuhui * @author huangyuhui
*/ */
public class MessageBox public class MessageBox {
{
private static String Title = C.i18n("message.info"); private static String Title = C.i18n("message.info");
/** /**
* Buttons: OK * Buttons: OK
@@ -84,15 +84,14 @@ public class MessageBox
/** /**
* Show MsgBox with title and options * Show MsgBox with title and options
*
* @param Msg The Message * @param Msg The Message
* @param Title The title of MsgBox. * @param Title The title of MsgBox.
* @param Option The type of MsgBox. * @param Option The type of MsgBox.
* @return user operation. * @return user operation.
*/ */
public static int Show(String Msg, String Title, int Option) public static int Show(String Msg, String Title, int Option) {
{ switch (Option) {
switch(Option)
{
case YES_NO_OPTION: case YES_NO_OPTION:
case YES_NO_CANCEL_OPTION: case YES_NO_CANCEL_OPTION:
case OK_CANCEL_OPTION: case OK_CANCEL_OPTION:
@@ -105,22 +104,22 @@ public class MessageBox
/** /**
* Show MsgBox with options * Show MsgBox with options
*
* @param Msg The Message * @param Msg The Message
* @param Option The type of MsgBox. * @param Option The type of MsgBox.
* @return User Operation * @return User Operation
*/ */
public static int Show(String Msg, int Option) public static int Show(String Msg, int Option) {
{
return Show(Msg, Title, Option); return Show(Msg, Title, Option);
} }
/** /**
* Show Default MsgBox * Show Default MsgBox
*
* @param Msg The Message * @param Msg The Message
* @return User Operation * @return User Operation
*/ */
public static int Show(String Msg) public static int Show(String Msg) {
{
return Show(Msg, Title, INFORMATION_MESSAGE); return Show(Msg, Title, INFORMATION_MESSAGE);
} }
} }

View File

@@ -39,24 +39,18 @@ public enum OS {
public static OS os() { public static OS os() {
String str; String str;
if ((str = System.getProperty("os.name").toLowerCase()) if ((str = System.getProperty("os.name").toLowerCase())
.contains("win")) { .contains("win"))
return OS.WINDOWS; return OS.WINDOWS;
} if (str.contains("mac"))
if (str.contains("mac")) {
return OS.OSX; return OS.OSX;
} if (str.contains("solaris"))
if (str.contains("solaris")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("sunos"))
if (str.contains("sunos")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("linux"))
if (str.contains("linux")) {
return OS.LINUX; return OS.LINUX;
} if (str.contains("unix"))
if (str.contains("unix")) {
return OS.LINUX; return OS.LINUX;
}
return OS.UNKOWN; return OS.UNKOWN;
} }

View File

@@ -31,9 +31,8 @@ public class ProcessManager {
} }
public void stopAllProcesses() { public void stopAllProcesses() {
for(JavaProcess jp : gameProcesses) { for (JavaProcess jp : gameProcesses)
jp.stop(); jp.stop();
}
gameProcesses.clear(); gameProcesses.clear();
} }

View File

@@ -49,22 +49,20 @@ public class ProcessThread extends Thread {
public void run() { public void run() {
InputStream in = null; InputStream in = null;
BufferedReader br = null; BufferedReader br = null;
if (enableReading) { if (enableReading)
in = readError ? p.getRawProcess().getErrorStream() : p.getRawProcess().getInputStream(); in = readError ? p.getRawProcess().getErrorStream() : p.getRawProcess().getInputStream();
}
try { try {
if (enableReading) { if (enableReading)
try { try {
br = new BufferedReader(new InputStreamReader(in, System.getProperty("sun.jnu.encoding", "UTF-8"))); br = new BufferedReader(new InputStreamReader(in, System.getProperty("sun.jnu.encoding", "UTF-8")));
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex); HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex);
br = new BufferedReader(new InputStreamReader(in)); br = new BufferedReader(new InputStreamReader(in));
} }
}
String line; String line;
while (p.isRunning()) { while (p.isRunning())
if (enableReading) { if (enableReading)
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
printlnEvent.execute(line); printlnEvent.execute(line);
if (readError) { if (readError) {
@@ -75,14 +73,12 @@ public class ProcessThread extends Thread {
p.getStdOutLines().add(line); p.getStdOutLines().add(line);
} }
} }
} else { else
try { try {
Thread.sleep(1); Thread.sleep(1);
} catch (Exception e) { } catch (Exception e) {
} }
} if (enableReading)
}
if (enableReading) {
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
printlnEvent.execute(line); printlnEvent.execute(line);
if (readError) { if (readError) {
@@ -93,7 +89,6 @@ public class ProcessThread extends Thread {
p.getStdOutLines().add(line); p.getStdOutLines().add(line);
} }
} }
}
stopEvent.execute(p); stopEvent.execute(p);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@@ -22,6 +22,7 @@ import org.jackhuang.hellominecraft.C;
* @author huangyuhui * @author huangyuhui
*/ */
public class MinecraftVersionRequest { public class MinecraftVersionRequest {
public static final int Unkown = 0, Invaild = 1, InvaildJar = 2, public static final int Unkown = 0, Invaild = 1, InvaildJar = 2,
Modified = 3, OK = 4, NotFound = 5, NotReadable = 6, NotAFile = 7; Modified = 3, OK = 4, NotFound = 5, NotReadable = 6, NotAFile = 7;
public int type; public int type;

View File

@@ -18,9 +18,11 @@ package org.jackhuang.hellominecraft.views;
/** /**
* The frame given to choose things. * The frame given to choose things.
*
* @author huangyuhui * @author huangyuhui
*/ */
public class Selector extends javax.swing.JDialog { public class Selector extends javax.swing.JDialog {
String[] selList; String[] selList;
String msg; String msg;
/** /**

View File

@@ -46,9 +46,8 @@ public class TintablePanel extends JPanel {
} }
public void setOverIcon(ImageIcon image) { public void setOverIcon(ImageIcon image) {
if (this.overIcon != null) { if (this.overIcon != null)
remove(this.overIcon); remove(this.overIcon);
}
this.overIcon = new JLabel(image); this.overIcon = new JLabel(image);
this.overIcon.setVisible(false); this.overIcon.setVisible(false);