Reconstruct codes.

This commit is contained in:
huanghongxun
2015-12-03 20:11:52 +08:00
parent b6cb5f0bee
commit f0212ea4eb
33 changed files with 636 additions and 418 deletions

View File

@@ -256,7 +256,7 @@ public final class Main implements Runnable {
} }
public static void invokeUpdate() { public static void invokeUpdate() {
MainFrame.instance.invokeUpdate(); MainFrame.INSTANCE.invokeUpdate();
} }
public static ImageIcon getIcon(String path) { public static ImageIcon getIcon(String path) {

View File

@@ -0,0 +1,36 @@
/*
* 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.launcher.launch;
import java.io.File;
import java.util.List;
import org.jackhuang.hellominecraft.launcher.utils.ModInfo;
/**
*
* @author huangyuhui
*/
public interface IMinecraftModService {
List<ModInfo> getMods();
List<ModInfo> recacheMods();
boolean addMod(File f);
void removeMod(int[] index);
}

View File

@@ -22,8 +22,8 @@ import java.util.List;
import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider; import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider;
import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType; import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
import org.jackhuang.hellominecraft.launcher.settings.Profile; import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.utils.ModInfo;
import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion; import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
import org.jackhuang.hellominecraft.utils.StrUtils;
/** /**
* Provide everything of the Minecraft of a Profile. * Provide everything of the Minecraft of a Profile.
@@ -47,6 +47,10 @@ public abstract class IMinecraftProvider {
* @return the run directory * @return the run directory
*/ */
public abstract File getRunDirectory(String id); public abstract File getRunDirectory(String id);
public File getRunDirectory(String id, String subFolder) {
return new File(getRunDirectory(getSelectedMinecraftVersion().id), subFolder);
}
/** /**
* Get the libraries that need to download. * Get the libraries that need to download.
@@ -57,13 +61,11 @@ public abstract class IMinecraftProvider {
*/ */
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 open(String version, String folder); public abstract void open(String version, String folder);
public abstract File getAssets(); public abstract File getAssets();
public abstract List<ModInfo> listMods(); public abstract IMinecraftModService getModService();
/** /**
* Returns the thing like ".minecraft/resourcepacks". * Returns the thing like ".minecraft/resourcepacks".
@@ -158,6 +160,26 @@ public abstract class IMinecraftProvider {
* @return the Minecraft json instance * @return the Minecraft json instance
*/ */
public abstract MinecraftVersion getVersionById(String id); public abstract MinecraftVersion getVersionById(String id);
public MinecraftVersion getSelectedVersion() {
return profile.getSelectedMinecraftVersion();
}
public MinecraftVersion getSelectedMinecraftVersion() {
if (StrUtils.isBlank(profile.getSelectedMinecraftVersionName())) {
MinecraftVersion v = getOneVersion();
if (v == null)
return null;
profile.setSelectedMinecraftVersion(v.id);
return v;
}
MinecraftVersion v = getVersionById(profile.getSelectedMinecraftVersionName());
if (v == null)
v = getOneVersion();
if (v != null)
profile.setSelectedMinecraftVersion(v.id);
return v;
}
/** /**
* getVersions().size() * getVersions().size()
@@ -170,6 +192,11 @@ public abstract class IMinecraftProvider {
* Refind the versions in this profile. * Refind the versions in this profile.
*/ */
public abstract void refreshVersions(); public abstract void refreshVersions();
/**
* Clean redundancy files.
*/
public abstract void cleanFolder();
/** /**
* Install a new version to this profile. * Install a new version to this profile.

View File

@@ -37,11 +37,11 @@ public class LaunchFinisher implements Event<List<String>> {
if (obj.getProfile().getLauncherVisibility() == LauncherVisibility.CLOSE && !LogWindow.instance.isVisible()) if (obj.getProfile().getLauncherVisibility() == LauncherVisibility.CLOSE && !LogWindow.instance.isVisible())
System.exit(0); System.exit(0);
else if (obj.getProfile().getLauncherVisibility() == LauncherVisibility.KEEP) else if (obj.getProfile().getLauncherVisibility() == LauncherVisibility.KEEP)
MainFrame.instance.closeMessage(); MainFrame.INSTANCE.closeMessage();
else { else {
if (LogWindow.instance.isVisible()) if (LogWindow.instance.isVisible())
LogWindow.instance.setExit(TrueFunction.instance); LogWindow.instance.setExit(TrueFunction.instance);
MainFrame.instance.dispose(); MainFrame.INSTANCE.dispose();
} }
JavaProcessMonitor jpm = new JavaProcessMonitor(p); JavaProcessMonitor jpm = new JavaProcessMonitor(p);
jpm.stoppedEvent.register((sender3, t) -> { jpm.stoppedEvent.register((sender3, t) -> {

View File

@@ -43,7 +43,7 @@ public class LaunchScriptFinisher implements Event<List<String>> {
MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed")); MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed"));
HMCLog.err("Failed to create script file.", ex); HMCLog.err("Failed to create script file.", ex);
} }
MainFrame.instance.closeMessage(); MainFrame.INSTANCE.closeMessage();
return flag; return flag;
} }

View File

@@ -46,36 +46,31 @@ public class LibraryDownloadTask extends FileDownloadTask {
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Throwable {
try { File packFile = new File(job.path.getParentFile(), job.path.getName() + ".pack.xz");
File packFile = new File(job.path.getParentFile(), job.path.getName() + ".pack.xz"); if (job.name.contains("typesafe")) {
if (job.name.contains("typesafe") && download(new URL(job.url + ".pack.xz"), packFile)) { download(new URL(job.url + ".pack.xz"), packFile);
unpackLibrary(job.path, packFile); unpackLibrary(job.path, packFile);
packFile.delete(); packFile.delete();
return true; } else {
} else { if (job.name.startsWith("net.minecraftforge:forge:")) {
if (job.name.startsWith("net.minecraftforge:forge:")) { String[] s = job.name.split(":");
String[] s = job.name.split(":"); if (s.length == 3)
if (s.length == 3) job.url = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/" + s[2] + "/forge-" + s[2] + "-universal.jar";
job.url = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/" + s[2] + "/forge-" + s[2] + "-universal.jar";
}
if (job.name.startsWith("com.mumfrey:liteloader:")) {
String[] s = job.name.split(":");
if (s.length == 3 && s[2].length() > 3)
job.url = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + s[2].substring(0, s[2].length() - 3) + "/liteloader-" + s[2] + ".jar";
}
return download(new URL(job.url), job.path);
} }
} catch (Exception ex) { if (job.name.startsWith("com.mumfrey:liteloader:")) {
setFailReason(ex); String[] s = job.name.split(":");
return false; if (s.length == 3 && s[2].length() > 3)
job.url = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + s[2].substring(0, s[2].length() - 3) + "/liteloader-" + s[2] + ".jar";
}
download(new URL(job.url), job.path);
} }
} }
boolean download(URL url, File filePath) { void download(URL url, File filePath) throws Throwable {
this.url = url; this.url = url;
this.filePath = filePath; this.filePath = filePath;
return super.executeTask(); super.executeTask();
} }
@SuppressWarnings("UnusedAssignment") @SuppressWarnings("UnusedAssignment")

View File

@@ -20,7 +20,9 @@ import java.io.File;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftProvider; import org.jackhuang.hellominecraft.launcher.launch.IMinecraftProvider;
import org.jackhuang.hellominecraft.utils.system.IOUtils; import org.jackhuang.hellominecraft.utils.system.IOUtils;
import org.jackhuang.hellominecraft.launcher.utils.MCUtils; import org.jackhuang.hellominecraft.launcher.utils.MCUtils;
import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerService;
import org.jackhuang.hellominecraft.launcher.version.GameDirType; import org.jackhuang.hellominecraft.launcher.version.GameDirType;
import org.jackhuang.hellominecraft.launcher.version.MinecraftService;
import org.jackhuang.hellominecraft.utils.StrUtils; import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.Utils; import org.jackhuang.hellominecraft.utils.Utils;
import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion; import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
@@ -94,13 +96,17 @@ public final class Profile {
minecraftProvider = new MinecraftVersionManager(this); minecraftProvider = new MinecraftVersionManager(this);
return minecraftProvider; return minecraftProvider;
} }
public String getSelectedMinecraftVersionName() {
return selectedMinecraftVersion;
}
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; setSelectedMinecraftVersion(v.id);
return v; return v;
} }
MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion); MinecraftVersion v = getMinecraftProvider().getVersionById(selectedMinecraftVersion);
@@ -111,6 +117,10 @@ public final class Profile {
return v; return v;
} }
public void setSelectedMinecraftVersion(String selectedMinecraftVersion) {
this.selectedMinecraftVersion = selectedMinecraftVersion;
}
public String getGameDir() { public String getGameDir() {
if (StrUtils.isBlank(gameDir)) if (StrUtils.isBlank(gameDir))
gameDir = MCUtils.getInitGameDir().getPath(); gameDir = MCUtils.getInitGameDir().getPath();
@@ -187,7 +197,7 @@ public final class Profile {
public File getFolder(String folder) { public File getFolder(String folder) {
if (getSelectedMinecraftVersion() == null) if (getSelectedMinecraftVersion() == null)
return new File(getCanonicalGameDirFile(), folder); return new File(getCanonicalGameDirFile(), folder);
return new File(getMinecraftProvider().getRunDirectory(getSelectedMinecraftVersion().id), folder); return getMinecraftProvider().getRunDirectory(getSelectedMinecraftVersion().id, folder);
} }
public String getName() { public String getName() {
@@ -198,10 +208,6 @@ public final class Profile {
this.name = name; this.name = name;
} }
public void setSelectedMinecraftVersion(String selectedMinecraftVersion) {
this.selectedMinecraftVersion = selectedMinecraftVersion;
}
public String getJavaArgs() { public String getJavaArgs() {
if (StrUtils.isBlank(javaArgs)) if (StrUtils.isBlank(javaArgs))
return ""; return "";
@@ -351,4 +357,14 @@ public final class Profile {
public void checkFormat() { public void checkFormat() {
gameDir = gameDir.replace('/', OS.os().fileSeparator).replace('\\', OS.os().fileSeparator); gameDir = gameDir.replace('/', OS.os().fileSeparator).replace('\\', OS.os().fileSeparator);
} }
final InstallerService is = new InstallerService(this);
public InstallerService getInstallerService() {
return is;
}
final MinecraftService ms = new MinecraftService(this);
public MinecraftService getMinecraftService() {
return ms;
}
} }

View File

@@ -27,6 +27,7 @@ import java.util.zip.ZipFile;
import org.jackhuang.hellominecraft.C; import org.jackhuang.hellominecraft.C;
import org.jackhuang.hellominecraft.HMCLog; import org.jackhuang.hellominecraft.HMCLog;
import org.jackhuang.hellominecraft.utils.StrUtils; import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.Utils;
import org.jackhuang.hellominecraft.utils.system.FileUtils; import org.jackhuang.hellominecraft.utils.system.FileUtils;
/** /**
@@ -43,6 +44,21 @@ public class ModInfo implements Comparable<ModInfo> {
return !location.getName().endsWith(".disabled"); return !location.getName().endsWith(".disabled");
} }
public void reverseModState() {
File f = location, newf;
if (f.getName().endsWith(".disabled"))
newf = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - ".disabled".length()));
else
newf = new File(f.getParentFile(), f.getName() + ".disabled");
if (f.renameTo(newf))
location = newf;
}
public void showURL() {
if (url != null)
Utils.openLink(url);
}
@Override @Override
public int compareTo(ModInfo o) { public int compareTo(ModInfo o) {
return getFileName().toLowerCase().compareTo(o.getFileName().toLowerCase()); return getFileName().toLowerCase().compareTo(o.getFileName().toLowerCase());
@@ -51,13 +67,14 @@ public class ModInfo implements Comparable<ModInfo> {
public String getName() { public String getName() {
return name == null ? FileUtils.removeExtension(location.getName()) : name; return name == null ? FileUtils.removeExtension(location.getName()) : name;
} }
public String getAuthor() { public String getAuthor() {
if (authorList != null && authorList.length > 0) if (authorList != null && authorList.length > 0)
return StrUtils.parseParams("", authorList, ", "); return StrUtils.parseParams("", authorList, ", ");
else if (StrUtils.isNotBlank(author)) else if (StrUtils.isNotBlank(author))
return author; return author;
else return "Unknown"; else
return "Unknown";
} }
@Override @Override

View File

@@ -95,11 +95,9 @@ public abstract class IAssetsHandler {
} }
@Override @Override
public boolean executeTask() { public void executeTask() {
if (assetsDownloadURLs == null) { if (assetsDownloadURLs == null)
setFailReason(new RuntimeException(C.i18n("assets.not_refreshed"))); throw new IllegalStateException(C.i18n("assets.not_refreshed"));
return false;
}
int max = assetsDownloadURLs.size(); int max = assetsDownloadURLs.size();
al = new ArrayList<>(); al = new ArrayList<>();
int hasDownloaded = 0; int hasDownloaded = 0;
@@ -132,7 +130,6 @@ public abstract class IAssetsHandler {
if (need) if (need)
al.add(new FileDownloadTask(url, location).setTag(mark)); al.add(new FileDownloadTask(url, location).setTag(mark));
} }
return true;
} }
@Override @Override

View File

@@ -0,0 +1,88 @@
/*
* 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.launcher.utils.installers;
import java.io.File;
import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.settings.Settings;
import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionList.InstallerVersion;
import org.jackhuang.hellominecraft.launcher.utils.installers.forge.ForgeInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.liteloader.LiteLoaderInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.liteloader.LiteLoaderVersionList;
import org.jackhuang.hellominecraft.launcher.utils.installers.optifine.OptiFineInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.optifine.vanilla.OptiFineDownloadFormatter;
import org.jackhuang.hellominecraft.tasks.Task;
import org.jackhuang.hellominecraft.tasks.TaskInfo;
import org.jackhuang.hellominecraft.tasks.TaskWindow;
import org.jackhuang.hellominecraft.tasks.download.FileDownloadTask;
import org.jackhuang.hellominecraft.utils.system.IOUtils;
/**
*
* @author huangyuhui
*/
public final class InstallerService {
Profile p;
public InstallerService(Profile p) {
this.p = p;
}
public Task downloadForge(InstallerVersion v) {
return new TaskInfo("OptiFine Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "forge-installer.jar");
if (v.installer != null)
TaskWindow.getInstance()
.addTask(new FileDownloadTask(Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(v.installer), filepath).setTag("forge"))
.addTask(new ForgeInstaller(p.getMinecraftProvider(), filepath, v))
.start();
}
};
}
public Task downloadOptifine(InstallerVersion v) {
return new TaskInfo("OptiFine Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "optifine-installer.jar");
if (v.installer != null) {
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
TaskWindow.getInstance().addTask(task)
.addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.addTask(new OptiFineInstaller(p, v.selfVersion, filepath))
.start();
}
}
};
}
public Task downloadLiteLoader(InstallerVersion v) {
return new TaskInfo("OptiFine Downloader") {
@Override
public void executeTask() {
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "liteloader-universal.jar");
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(v.universal, filepath).setTag("LiteLoader");
TaskWindow.getInstance()
.addTask(task).addTask(new LiteLoaderInstaller(p, (LiteLoaderVersionList.LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.start();
}
};
}
}

View File

@@ -55,57 +55,47 @@ public class ForgeInstaller extends Task {
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
try { HMCLog.log("Extracting install profiles...");
HMCLog.log("Extracting install profiles...");
ZipFile zipFile = new ZipFile(forgeInstaller); ZipFile zipFile = new ZipFile(forgeInstaller);
ZipEntry entry = zipFile.getEntry("install_profile.json"); ZipEntry entry = zipFile.getEntry("install_profile.json");
String content = NetUtils.getStreamContent(zipFile.getInputStream(entry)); String content = NetUtils.getStreamContent(zipFile.getInputStream(entry));
InstallProfile profile = C.gsonPrettyPrinting.fromJson(content, InstallProfile.class); InstallProfile profile = C.gsonPrettyPrinting.fromJson(content, InstallProfile.class);
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"))); throw new IllegalStateException(C.i18n("install.no_version"));
} else } else
setFailReason(new RuntimeException(C.i18n("install.no_version"))); throw new IllegalStateException(C.i18n("install.no_version"));
return false;
}
File to = new File(gameDir, "versions" + File.separator + profile.install.target); File to = new File(gameDir, "versions" + File.separator + profile.install.target);
to.mkdirs(); to.mkdirs();
HMCLog.log("Copying jar..." + profile.install.minecraft + ".jar to " + profile.install.target + ".jar"); HMCLog.log("Copying jar..." + profile.install.minecraft + ".jar to " + profile.install.target + ".jar");
FileUtils.copyFile(new File(from, profile.install.minecraft + ".jar"), FileUtils.copyFile(new File(from, profile.install.minecraft + ".jar"),
new File(to, profile.install.target + ".jar")); new File(to, profile.install.target + ".jar"));
HMCLog.log("Creating new version profile..." + profile.install.target + ".json"); HMCLog.log("Creating new version profile..." + profile.install.target + ".json");
/*for (MinecraftLibrary library : profile.versionInfo.libraries) /*for (MinecraftLibrary library : profile.versionInfo.libraries)
if (library.name.startsWith("net.minecraftforge:forge:")) if (library.name.startsWith("net.minecraftforge:forge:"))
library.url = installerVersion.universal;*/ library.url = installerVersion.universal;*/
FileUtils.write(new File(to, profile.install.target + ".json"), C.gsonPrettyPrinting.toJson(profile.versionInfo)); FileUtils.write(new File(to, profile.install.target + ".json"), C.gsonPrettyPrinting.toJson(profile.versionInfo));
HMCLog.log("Extracting universal forge pack..." + profile.install.filePath); HMCLog.log("Extracting universal forge pack..." + profile.install.filePath);
entry = zipFile.getEntry(profile.install.filePath); entry = zipFile.getEntry(profile.install.filePath);
InputStream is = zipFile.getInputStream(entry); InputStream is = zipFile.getInputStream(entry);
MinecraftLibrary forge = new MinecraftLibrary(profile.install.path); MinecraftLibrary forge = new MinecraftLibrary(profile.install.path);
forge.init(); forge.init();
File file = new File(gameDir, "libraries/" + forge.formatted); File file = new File(gameDir, "libraries/" + forge.formatted);
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream(file)) { try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
BufferedOutputStream bos = new BufferedOutputStream(fos); int c;
int c; while ((c = is.read()) != -1)
while ((c = is.read()) != -1) bos.write((byte) c);
bos.write((byte) c);
bos.close();
}
return true;
} catch (IOException | JsonSyntaxException e) {
setFailReason(e);
return false;
} }
} }

View File

@@ -50,41 +50,32 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
if (profile == null || profile.getSelectedMinecraftVersion() == null) { if (profile == null || profile.getSelectedMinecraftVersion() == null)
setFailReason(new RuntimeException(C.i18n("install.no_version"))); throw new IllegalStateException(C.i18n("install.no_version"));
return false;
}
if (pre.size() != 1 && installer == null) if (pre.size() != 1 && installer == null)
throw new IllegalStateException("No registered previous task."); throw new IllegalStateException("No registered previous task.");
if (installer == null) if (installer == null)
installer = pre.get(pre.size() - 1).getResult(); installer = pre.get(pre.size() - 1).getResult();
try { MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone();
MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone(); mv.inheritsFrom = mv.id;
mv.inheritsFrom = mv.id; mv.jar = mv.jar == null ? mv.id : mv.jar;
mv.jar = mv.jar == null ? mv.id : mv.jar; mv.libraries = new ArrayList(Arrays.asList(version.libraries));
mv.libraries = new ArrayList(Arrays.asList(version.libraries));
MinecraftLibrary ml = new MinecraftLibrary("com.mumfrey:liteloader:" + version.selfVersion); MinecraftLibrary ml = new MinecraftLibrary("com.mumfrey:liteloader:" + version.selfVersion);
//ml.url = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + version.mcVersion + "/liteloader-" + version.selfVersion + ".jar"; //ml.url = "http://dl.liteloader.com/versions/com/mumfrey/liteloader/" + version.mcVersion + "/liteloader-" + version.selfVersion + ".jar";
mv.libraries.add(0, ml); mv.libraries.add(0, ml);
FileUtils.copyFile(installer, new File(profile.getCanonicalGameDir(), "libraries/com/mumfrey/liteloader/" + version.selfVersion + "/liteloader-" + version.selfVersion + ".jar")); FileUtils.copyFile(installer, new File(profile.getCanonicalGameDir(), "libraries/com/mumfrey/liteloader/" + version.selfVersion + "/liteloader-" + version.selfVersion + ".jar"));
mv.id += "-LiteLoader" + version.selfVersion; mv.id += "-LiteLoader" + version.selfVersion;
mv.mainClass = "net.minecraft.launchwrapper.Launch"; mv.mainClass = "net.minecraft.launchwrapper.Launch";
mv.minecraftArguments += " --tweakClass " + version.tweakClass; mv.minecraftArguments += " --tweakClass " + version.tweakClass;
File folder = new File(profile.getCanonicalGameDir(), "versions/" + mv.id); File folder = new File(profile.getCanonicalGameDir(), "versions/" + mv.id);
folder.mkdirs(); folder.mkdirs();
File json = new File(folder, mv.id + ".json"); File json = new File(folder, mv.id + ".json");
HMCLog.log("Creating new version profile..." + mv.id + ".json"); HMCLog.log("Creating new version profile..." + mv.id + ".json");
FileUtils.write(json, C.gsonPrettyPrinting.toJson(mv)); FileUtils.write(json, C.gsonPrettyPrinting.toJson(mv));
return true;
} catch (Exception e) {
setFailReason(e);
return false;
}
} }
@Override @Override

View File

@@ -17,7 +17,6 @@
package org.jackhuang.hellominecraft.launcher.utils.installers.optifine; package org.jackhuang.hellominecraft.launcher.utils.installers.optifine;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import org.jackhuang.hellominecraft.C; import org.jackhuang.hellominecraft.C;
@@ -50,37 +49,28 @@ public class OptiFineInstaller extends Task implements PreviousResultRegistrar<F
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
if (profile == null || profile.getSelectedMinecraftVersion() == null) { if (profile == null || profile.getSelectedMinecraftVersion() == null)
setFailReason(new RuntimeException(C.i18n("install.no_version"))); throw new Exception(C.i18n("install.no_version"));
return false;
}
MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone(); MinecraftVersion mv = (MinecraftVersion) profile.getSelectedMinecraftVersion().clone();
mv.inheritsFrom = mv.id;
mv.jar = mv.jar == null ? mv.id : mv.jar;
mv.libraries.clear();
mv.libraries.add(0, new MinecraftLibrary("optifine:OptiFine:" + version));
FileUtils.copyFile(installer, new File(profile.getCanonicalGameDir(), "libraries/optifine/OptiFine/" + version + "/OptiFine-" + version + ".jar"));
try { mv.id += "-" + version;
mv.inheritsFrom = mv.id; if (new ZipFile(installer).getEntry("optifine/OptiFineTweaker.class") != null) {
mv.jar = mv.jar == null ? mv.id : mv.jar; if (!mv.mainClass.startsWith("net.minecraft.launchwrapper.")) {
mv.libraries.clear(); mv.mainClass = "net.minecraft.launchwrapper.Launch";
mv.libraries.add(0, new MinecraftLibrary("optifine:OptiFine:" + version)); mv.libraries.add(1, new MinecraftLibrary("net.minecraft:launchwrapper:1.7"));
FileUtils.copyFile(installer, new File(profile.getCanonicalGameDir(), "libraries/optifine/OptiFine/" + version + "/OptiFine-" + version + ".jar"));
mv.id += "-" + version;
if (new ZipFile(installer).getEntry("optifine/OptiFineTweaker.class") != null) {
if (!mv.mainClass.startsWith("net.minecraft.launchwrapper.")) {
mv.mainClass = "net.minecraft.launchwrapper.Launch";
mv.libraries.add(1, new MinecraftLibrary("net.minecraft:launchwrapper:1.7"));
}
mv.minecraftArguments += " --tweakClass optifine.OptiFineTweaker";
} }
File loc = new File(profile.getCanonicalGameDir(), "versions/" + mv.id); mv.minecraftArguments += " --tweakClass optifine.OptiFineTweaker";
loc.mkdirs();
File json = new File(loc, mv.id + ".json");
FileUtils.writeStringToFile(json, C.gsonPrettyPrinting.toJson(mv, MinecraftVersion.class));
} catch (IOException ex) {
setFailReason(ex);
return false;
} }
return true; File loc = new File(profile.getCanonicalGameDir(), "versions/" + mv.id);
loc.mkdirs();
File json = new File(loc, mv.id + ".json");
FileUtils.writeStringToFile(json, C.gsonPrettyPrinting.toJson(mv, MinecraftVersion.class));
} }
@Override @Override

View File

@@ -36,19 +36,13 @@ public class OptiFineDownloadFormatter extends Task implements PreviousResult<St
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
try { String content = NetUtils.get(url);
String content = NetUtils.get(url); Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\"");
Pattern p = Pattern.compile("\"downloadx\\?f=OptiFine(.*)\""); Matcher m = p.matcher(content);
Matcher m = p.matcher(content); while (m.find())
while (m.find()) result = m.group(1);
result = m.group(1); result = "http://optifine.net/downloadx?f=OptiFine" + result;
result = "http://optifine.net/downloadx?f=OptiFine" + result;
return true;
} catch (Exception ex) {
setFailReason(ex);
return false;
}
} }
@Override @Override

View File

@@ -60,29 +60,23 @@ public class Upgrader extends Task {
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
HashMap<String, String> json = new HashMap<>(); HashMap<String, String> json = new HashMap<>();
File f = getSelf(newestVersion); File f = getSelf(newestVersion);
try { if (!f.getParentFile().exists())
if (!f.getParentFile().exists()) f.getParentFile().mkdirs();
f.getParentFile().mkdirs();
for (int i = 0; f.exists(); i++) for (int i = 0; f.exists(); i++)
f = new File(BASE_FOLDER, "HMCL-" + newestVersion + (i > 0 ? "-" + i : "") + ".jar"); f = new File(BASE_FOLDER, "HMCL-" + newestVersion + (i > 0 ? "-" + i : "") + ".jar");
f.createNewFile(); f.createNewFile();
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) { try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) {
Pack200.newUnpacker().unpack(new XZInputStream(new FileInputStream(tempFile)), jos); Pack200.newUnpacker().unpack(new XZInputStream(new FileInputStream(tempFile)), jos);
}
json.put("ver", newestVersion);
json.put("loc", f.getAbsolutePath());
String result = C.gson.toJson(json);
FileUtils.write(HMCL_VER_FILE, result);
return true;
} catch (IOException e) {
setFailReason(e);
return false;
} }
json.put("ver", newestVersion);
json.put("loc", f.getAbsolutePath());
String result = C.gson.toJson(json);
FileUtils.write(HMCL_VER_FILE, result);
} }
@Override @Override

View File

@@ -0,0 +1,109 @@
/*
* 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.launcher.version;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jackhuang.hellominecraft.HMCLog;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftModService;
import org.jackhuang.hellominecraft.launcher.utils.ModInfo;
import org.jackhuang.hellominecraft.utils.system.FileUtils;
/**
*
* @author huangyuhui
*/
public class MinecraftModService implements IMinecraftModService {
MinecraftVersionManager mgr;
public MinecraftModService(MinecraftVersionManager mgr) {
this.mgr = mgr;
}
List<ModInfo> modCache;
@Override
public List<ModInfo> getMods() {
if (modCache == null) return recacheMods();
else return modCache;
}
@Override
public List<ModInfo> recacheMods() {
if (mgr.getSelectedMinecraftVersion() == null)
return modCache = new ArrayList<>();
File modsFolder = mgr.getRunDirectory(mgr.getSelectedMinecraftVersion().id, "mods");
ArrayList<ModInfo> mods = new ArrayList<>();
File[] fs = modsFolder.listFiles();
if (fs != null)
for (File f : fs)
if (ModInfo.isFileMod(f)) {
ModInfo m = ModInfo.readModInfo(f);
if (m != null)
mods.add(m);
} else if (f.isDirectory()) {
File[] ss = f.listFiles();
if (ss != null)
for (File ff : ss)
if (ModInfo.isFileMod(ff)) {
ModInfo m = ModInfo.readModInfo(ff);
if (m != null)
mods.add(m);
}
}
Collections.sort(mods);
return modCache = mods;
}
@Override
public boolean addMod(File f) {
try {
if (mgr.getSelectedMinecraftVersion() == null)
return false;
if (!ModInfo.isFileMod(f))
return false;
File modsFolder = mgr.getRunDirectory(mgr.getSelectedMinecraftVersion().id, "mods");
if (modsFolder == null)
return false;
modsFolder.mkdirs();
File newf = new File(modsFolder, f.getName());
FileUtils.copyFile(f, newf);
ModInfo i = ModInfo.readModInfo(f);
modCache.add(i);
return true;
} catch (IOException ex) {
HMCLog.warn("Failed to copy mod", ex);
return false;
}
}
@Override
public void removeMod(int[] rows) {
Arrays.sort(rows);
for (int idx : rows) {
ModInfo mi = getMods().get(idx);
File f = mi.location;
f.delete();
}
recacheMods();
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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.launcher.version;
import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.settings.Settings;
import org.jackhuang.hellominecraft.launcher.utils.assets.IAssetsHandler;
import org.jackhuang.hellominecraft.tasks.Task;
import org.jackhuang.hellominecraft.tasks.TaskWindow;
/**
*
* @author huangyuhui
*/
public class MinecraftService {
Profile profile;
public MinecraftService(Profile profile) {
this.profile = profile;
}
public Task downloadAssets(String mcVersion) {
return new Task() {
@Override
public void executeTask() throws Throwable {
IAssetsHandler type = IAssetsHandler.ASSETS_HANDLER;
type.getList(profile.getMinecraftProvider().getVersionById(mcVersion), profile.getMinecraftProvider(), (value) -> {
if (value != null)
TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start();
});
}
@Override
public String getInfo() {
return "Download Assets";
}
};
}
}

View File

@@ -21,7 +21,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
@@ -30,6 +29,7 @@ import org.jackhuang.hellominecraft.HMCLog;
import org.jackhuang.hellominecraft.launcher.launch.GameLauncher; import org.jackhuang.hellominecraft.launcher.launch.GameLauncher;
import org.jackhuang.hellominecraft.launcher.launch.GameLauncher.DownloadLibraryJob; import org.jackhuang.hellominecraft.launcher.launch.GameLauncher.DownloadLibraryJob;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftLoader; import org.jackhuang.hellominecraft.launcher.launch.IMinecraftLoader;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftModService;
import org.jackhuang.hellominecraft.launcher.launch.IMinecraftProvider; import org.jackhuang.hellominecraft.launcher.launch.IMinecraftProvider;
import org.jackhuang.hellominecraft.launcher.launch.MinecraftLoader; import org.jackhuang.hellominecraft.launcher.launch.MinecraftLoader;
import org.jackhuang.hellominecraft.utils.system.FileUtils; import org.jackhuang.hellominecraft.utils.system.FileUtils;
@@ -38,7 +38,6 @@ import org.jackhuang.hellominecraft.launcher.utils.auth.UserProfileProvider;
import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType; import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
import org.jackhuang.hellominecraft.launcher.settings.Profile; import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.settings.Settings; import org.jackhuang.hellominecraft.launcher.settings.Settings;
import org.jackhuang.hellominecraft.launcher.utils.ModInfo;
import org.jackhuang.hellominecraft.utils.system.IOUtils; import org.jackhuang.hellominecraft.utils.system.IOUtils;
import org.jackhuang.hellominecraft.utils.system.MessageBox; import org.jackhuang.hellominecraft.utils.system.MessageBox;
import org.jackhuang.hellominecraft.utils.Utils; import org.jackhuang.hellominecraft.utils.Utils;
@@ -224,33 +223,6 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
} }
} }
@Override
public List<ModInfo> listMods() {
if (profile.getSelectedMinecraftVersion() == null)
return new ArrayList<>();
File modsFolder = new File(getRunDirectory(profile.getSelectedMinecraftVersion().id), "mods");
ArrayList<ModInfo> mods = new ArrayList<>();
File[] fs = modsFolder.listFiles();
if (fs != null)
for (File f : fs)
if (ModInfo.isFileMod(f)) {
ModInfo m = ModInfo.readModInfo(f);
if (m != null)
mods.add(m);
} else if (f.isDirectory()) {
File[] ss = f.listFiles();
if (ss != null)
for (File ff : ss)
if (ModInfo.isFileMod(ff)) {
ModInfo m = ModInfo.readModInfo(ff);
if (m != null)
mods.add(m);
}
}
Collections.sort(mods);
return mods;
}
@Override @Override
public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) { public List<GameLauncher.DownloadLibraryJob> getDownloadLibraries(DownloadType downloadType) {
ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>(); ArrayList<DownloadLibraryJob> downloadLibraries = new ArrayList<>();
@@ -273,14 +245,12 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
return downloadLibraries; return downloadLibraries;
} }
@Override
public void openSelf(String mv) {
Utils.openFolder(getRunDirectory(mv));
}
@Override @Override
public void open(String mv, String name) { public void open(String mv, String name) {
Utils.openFolder(new File(getRunDirectory(mv), name)); if (name == null)
Utils.openFolder(getRunDirectory(mv));
else
Utils.openFolder(new File(getRunDirectory(mv), name));
} }
@Override @Override
@@ -348,4 +318,25 @@ public final class MinecraftVersionManager extends IMinecraftProvider {
if (!resourcePacks.exists()) if (!resourcePacks.exists())
resourcePacks.mkdirs(); resourcePacks.mkdirs();
} }
@Override
public void cleanFolder() {
for (MinecraftVersion s : getVersions()) {
FileUtils.deleteDirectoryQuietly(new File(profile.getGameDirFile(), "versions" + File.separator + s.id + File.separator + s.id + "-natives"));
File f = getRunDirectory(s.id);
String[] dir = {"logs", "asm", "NVIDIA", "crash-reports", "server-resource-packs", "natives", "native"};
for (String str : dir)
FileUtils.deleteDirectoryQuietly(new File(f, str));
String[] files = {"output-client.log", "usercache.json", "usernamecache.json", "hmclmc.log"};
for (String str : files)
new File(f, str).delete();
}
}
final MinecraftModService mms = new MinecraftModService(this);
@Override
public IMinecraftModService getModService() {
return mms;
}
} }

View File

@@ -48,14 +48,8 @@ import org.jackhuang.hellominecraft.C;
import org.jackhuang.hellominecraft.HMCLog; import org.jackhuang.hellominecraft.HMCLog;
import org.jackhuang.hellominecraft.launcher.settings.LauncherVisibility; import org.jackhuang.hellominecraft.launcher.settings.LauncherVisibility;
import org.jackhuang.hellominecraft.launcher.utils.MCUtils; import org.jackhuang.hellominecraft.launcher.utils.MCUtils;
import org.jackhuang.hellominecraft.launcher.utils.assets.IAssetsHandler;
import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionList; import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionList;
import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionList.InstallerVersion; import org.jackhuang.hellominecraft.launcher.utils.installers.InstallerVersionList.InstallerVersion;
import org.jackhuang.hellominecraft.launcher.utils.installers.forge.ForgeInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.liteloader.LiteLoaderInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.liteloader.LiteLoaderVersionList.LiteLoaderInstallerVersion;
import org.jackhuang.hellominecraft.launcher.utils.installers.optifine.OptiFineInstaller;
import org.jackhuang.hellominecraft.launcher.utils.installers.optifine.vanilla.OptiFineDownloadFormatter;
import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType; import org.jackhuang.hellominecraft.launcher.utils.download.DownloadType;
import org.jackhuang.hellominecraft.launcher.settings.Profile; import org.jackhuang.hellominecraft.launcher.settings.Profile;
import org.jackhuang.hellominecraft.launcher.settings.Settings; import org.jackhuang.hellominecraft.launcher.settings.Settings;
@@ -64,10 +58,10 @@ import org.jackhuang.hellominecraft.launcher.utils.ModInfo;
import org.jackhuang.hellominecraft.launcher.version.GameDirType; import org.jackhuang.hellominecraft.launcher.version.GameDirType;
import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion; import org.jackhuang.hellominecraft.launcher.version.MinecraftVersion;
import org.jackhuang.hellominecraft.tasks.Task; import org.jackhuang.hellominecraft.tasks.Task;
import org.jackhuang.hellominecraft.tasks.TaskRunnable;
import org.jackhuang.hellominecraft.tasks.TaskRunnableArg1; import org.jackhuang.hellominecraft.tasks.TaskRunnableArg1;
import org.jackhuang.hellominecraft.tasks.TaskWindow; import org.jackhuang.hellominecraft.tasks.TaskWindow;
import org.jackhuang.hellominecraft.tasks.communication.DefaultPreviousResult; import org.jackhuang.hellominecraft.tasks.communication.DefaultPreviousResult;
import org.jackhuang.hellominecraft.tasks.download.FileDownloadTask;
import org.jackhuang.hellominecraft.tasks.download.HTTPGetTask; import org.jackhuang.hellominecraft.tasks.download.HTTPGetTask;
import org.jackhuang.hellominecraft.utils.system.IOUtils; import org.jackhuang.hellominecraft.utils.system.IOUtils;
import org.jackhuang.hellominecraft.utils.system.MessageBox; import org.jackhuang.hellominecraft.utils.system.MessageBox;
@@ -75,8 +69,6 @@ import org.jackhuang.hellominecraft.version.MinecraftVersionRequest;
import org.jackhuang.hellominecraft.utils.system.OS; import org.jackhuang.hellominecraft.utils.system.OS;
import org.jackhuang.hellominecraft.utils.StrUtils; import org.jackhuang.hellominecraft.utils.StrUtils;
import org.jackhuang.hellominecraft.utils.SwingUtils; import org.jackhuang.hellominecraft.utils.SwingUtils;
import org.jackhuang.hellominecraft.utils.Utils;
import org.jackhuang.hellominecraft.utils.system.FileUtils;
import org.jackhuang.hellominecraft.utils.system.Java; import org.jackhuang.hellominecraft.utils.system.Java;
import org.jackhuang.hellominecraft.version.MinecraftRemoteVersion; import org.jackhuang.hellominecraft.version.MinecraftRemoteVersion;
import org.jackhuang.hellominecraft.version.MinecraftRemoteVersions; import org.jackhuang.hellominecraft.version.MinecraftRemoteVersions;
@@ -117,11 +109,7 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
} }
JMenuItem itm; JMenuItem itm;
itm = new JMenuItem(C.i18n("folder.game")); itm = new JMenuItem(C.i18n("folder.game"));
itm.addActionListener((e) -> { itm.addActionListener(new ImplementedActionListener(null));
Profile v = getProfile();
if (v != null)
v.getMinecraftProvider().openSelf(mcVersion);
});
ppmExplore.add(itm); ppmExplore.add(itm);
itm = new JMenuItem(C.i18n("folder.mod")); itm = new JMenuItem(C.i18n("folder.mod"));
itm.addActionListener(new ImplementedActionListener("mods")); itm.addActionListener(new ImplementedActionListener("mods"));
@@ -183,6 +171,7 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
} }
lstExternalMods.getSelectionModel().addListSelectionListener(e -> { lstExternalMods.getSelectionModel().addListSelectionListener(e -> {
int row = lstExternalMods.getSelectedRow(); int row = lstExternalMods.getSelectedRow();
List<ModInfo> mods = profile.getMinecraftProvider().getModService().getMods();
if (mods != null && 0 <= row && row < mods.size()) { if (mods != null && 0 <= row && row < mods.size()) {
ModInfo m = mods.get(row); ModInfo m = mods.get(row);
boolean hasLink = m.url != null; boolean hasLink = m.url != null;
@@ -196,15 +185,9 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
((DefaultTableModel) lstExternalMods.getModel()).addTableModelListener(e -> { ((DefaultTableModel) lstExternalMods.getModel()).addTableModelListener(e -> {
if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 0) { if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 0) {
int row = lstExternalMods.getSelectedRow(); int row = lstExternalMods.getSelectedRow();
if (mods != null && mods.size() > row && row >= 0) { List<ModInfo> mods = profile.getMinecraftProvider().getModService().getMods();
File f = mods.get(row).location, newf; if (mods != null && mods.size() > row && row >= 0)
if (f.getName().endsWith(".disabled")) mods.get(row).reverseModState();
newf = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - ".disabled".length()));
else
newf = new File(f.getParentFile(), f.getName() + ".disabled");
if (f.renameTo(newf))
mods.get(row).location = newf;
}
} }
}); });
tabVersionEdit.addChangeListener(new ChangeListener() { tabVersionEdit.addChangeListener(new ChangeListener() {
@@ -222,26 +205,15 @@ public class GameSettingsPanel extends javax.swing.JPanel implements DropTargetL
} }
}); });
tabInstallers.addChangeListener(new ChangeListener() { tabInstallers.addChangeListener(new ChangeListener() {
boolean a = false, b = false, c = false; boolean refreshed[] = new boolean[] {false, false, false};
InstallerHelper helpers[] = new InstallerHelper[] {forge, optifine, liteloader};
@Override @Override
public void stateChanged(ChangeEvent e) { public void stateChanged(ChangeEvent e) {
switch (tabInstallers.getSelectedIndex()) { int idx = tabInstallers.getSelectedIndex();
case 0: if (0 <= idx && idx < 3 && !refreshed[idx]) {
if (!a) helpers[idx].refreshVersions();
forge.refreshVersions(); refreshed[idx] = true;
a = true;
break;
case 1:
if (!b)
optifine.refreshVersions();
b = true;
break;
case 2:
if (!c)
liteloader.refreshVersions();
c = true;
break;
} }
} }
}); });
@@ -1133,7 +1105,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
if (isLoading) if (isLoading)
return; return;
profile = getProfile(); profile = getProfile();
if (profile == null) return; if (profile == null)
return;
if (profile.getMinecraftProvider().getVersionCount() <= 0) if (profile.getMinecraftProvider().getVersionCount() <= 0)
versionChanged(profile, null); versionChanged(profile, null);
prepare(profile); prepare(profile);
@@ -1161,14 +1134,13 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_btnRemoveProfileActionPerformed }//GEN-LAST:event_btnRemoveProfileActionPerformed
private void cboVersionsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboVersionsItemStateChanged private void cboVersionsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboVersionsItemStateChanged
if (isLoading || evt.getStateChange() != ItemEvent.SELECTED || cboVersions.getSelectedIndex() < 0 || StrUtils.isBlank((String) cboVersions.getSelectedItem()) || getProfile() == null) if (isLoading || evt.getStateChange() != ItemEvent.SELECTED || cboVersions.getSelectedIndex() < 0 || StrUtils.isBlank((String) cboVersions.getSelectedItem()) || getProfile() == null)
return; return;
loadMinecraftVersion((String) cboVersions.getSelectedItem()); String mcv = (String) cboVersions.getSelectedItem();
versionChanged(getProfile(), (String) cboVersions.getSelectedItem()); loadMinecraftVersion(mcv);
versionChanged(getProfile(), mcv);
getProfile().setSelectedMinecraftVersion(cboVersions.getSelectedItem().toString()); getProfile().setSelectedMinecraftVersion(mcv);
cboVersions.setToolTipText(cboVersions.getSelectedItem().toString()); cboVersions.setToolTipText(mcv);
Settings.save(); Settings.save();
}//GEN-LAST:event_cboVersionsItemStateChanged }//GEN-LAST:event_cboVersionsItemStateChanged
@@ -1186,17 +1158,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
MessageBox.Show(C.i18n("install.not_refreshed")); MessageBox.Show(C.i18n("install.not_refreshed"));
return; return;
} }
InstallerVersion v = forge.getVersion(idx); profile.getInstallerService().downloadForge(forge.getVersion(idx)).after(new TaskRunnable(this::refreshVersions)).run();
String url;
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "forge-installer.jar");
if (v.installer != null) {
url = Settings.getInstance().getDownloadSource().getProvider().getParsedLibraryDownloadURL(v.installer);
TaskWindow.getInstance()
.addTask(new FileDownloadTask(url, filepath).setTag("forge"))
.addTask(new ForgeInstaller(profile.getMinecraftProvider(), filepath, v))
.start();
refreshVersions();
}
}//GEN-LAST:event_btnDownloadForgeActionPerformed }//GEN-LAST:event_btnDownloadForgeActionPerformed
private void btnRefreshOptifineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshOptifineActionPerformed private void btnRefreshOptifineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshOptifineActionPerformed
@@ -1209,17 +1171,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
MessageBox.Show(C.i18n("install.not_refreshed")); MessageBox.Show(C.i18n("install.not_refreshed"));
return; return;
} }
InstallerVersion v = optifine.getVersion(idx); profile.getInstallerService().downloadOptifine(optifine.getVersion(idx)).after(new TaskRunnable(this::refreshVersions)).run();
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "optifine-installer.jar");
if (v.installer != null)
SwingUtilities.invokeLater(() -> {
OptiFineDownloadFormatter task = new OptiFineDownloadFormatter(v.installer);
TaskWindow.getInstance().addTask(task)
.addTask(new FileDownloadTask(filepath).registerPreviousResult(task).setTag("optifine"))
.addTask(new OptiFineInstaller(profile, v.selfVersion, filepath))
.start();
refreshVersions();
});
}//GEN-LAST:event_btnDownloadOptifineActionPerformed }//GEN-LAST:event_btnDownloadOptifineActionPerformed
private void btnInstallLiteLoaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInstallLiteLoaderActionPerformed private void btnInstallLiteLoaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInstallLiteLoaderActionPerformed
@@ -1228,15 +1180,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
MessageBox.Show(C.i18n("install.not_refreshed")); MessageBox.Show(C.i18n("install.not_refreshed"));
return; return;
} }
InstallerVersion v = liteloader.getVersion(idx); profile.getInstallerService().downloadLiteLoader(liteloader.getVersion(idx)).after(new TaskRunnable(this::refreshVersions)).run();
String url;
File filepath = IOUtils.tryGetCanonicalFile(IOUtils.currentDirWithSeparator() + "liteloader-universal.jar");
url = v.universal;
FileDownloadTask task = (FileDownloadTask) new FileDownloadTask(url, filepath).setTag("LiteLoader");
TaskWindow.getInstance()
.addTask(task).addTask(new LiteLoaderInstaller(profile, (LiteLoaderInstallerVersion) v).registerPreviousResult(task))
.start();
refreshVersions();
}//GEN-LAST:event_btnInstallLiteLoaderActionPerformed }//GEN-LAST:event_btnInstallLiteLoaderActionPerformed
private void btnRefreshLiteLoaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshLiteLoaderActionPerformed private void btnRefreshLiteLoaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshLiteLoaderActionPerformed
@@ -1320,7 +1264,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_cboLauncherVisibilityFocusLost }//GEN-LAST:event_cboLauncherVisibilityFocusLost
private void btnDownloadAllAssetsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadAllAssetsActionPerformed private void btnDownloadAllAssetsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadAllAssetsActionPerformed
downloadAssets(IAssetsHandler.ASSETS_HANDLER); if (mcVersion != null && profile != null)
profile.getMinecraftService().downloadAssets(mcVersion).run();
}//GEN-LAST:event_btnDownloadAllAssetsActionPerformed }//GEN-LAST:event_btnDownloadAllAssetsActionPerformed
private void txtMaxMemoryFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxMemoryFocusLost private void txtMaxMemoryFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxMemoryFocusLost
@@ -1394,45 +1339,15 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
return; return;
boolean flag = false; boolean flag = false;
for (File f : fc.getSelectedFiles()) for (File f : fc.getSelectedFiles())
if (!addMod(f)) flag |= !profile.getMinecraftProvider().getModService().addMod(f);
flag |= true; reloadMods();
if (flag) if (flag)
MessageBox.Show(C.I18N.getString("mods.failed")); MessageBox.Show(C.I18N.getString("mods.failed"));
}//GEN-LAST:event_btnAddModActionPerformed }//GEN-LAST:event_btnAddModActionPerformed
boolean addMod(File f) {
try {
if (!ModInfo.isFileMod(f) || mods == null)
return false;
File newf = profile.getFolder("mods");
if (newf == null)
return false;
newf.mkdirs();
newf = new File(newf, f.getName());
FileUtils.copyFile(f, newf);
ModInfo i = ModInfo.readModInfo(f);
mods.add(i);
((DefaultTableModel) lstExternalMods.getModel()).addRow(new Object[] {i.isActive(), i.location.getName(), i.version});
return true;
} catch (IOException ex) {
HMCLog.warn("Failed to copy mod", ex);
return false;
}
}
private void btnRemoveModActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveModActionPerformed private void btnRemoveModActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveModActionPerformed
DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel(); profile.getMinecraftProvider().getModService().removeMod(lstExternalMods.getSelectedRows());
int[] rows = lstExternalMods.getSelectedRows(); reloadMods();
Arrays.sort(rows);
int removed = 0;
for (int idx : rows) {
ModInfo mi = mods.get(idx - removed);
File f = mi.location;
mods.remove(idx - removed);
model.removeRow(idx - removed);
removed++;
f.delete();
}
}//GEN-LAST:event_btnRemoveModActionPerformed }//GEN-LAST:event_btnRemoveModActionPerformed
private void lstExternalModsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstExternalModsKeyPressed private void lstExternalModsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lstExternalModsKeyPressed
@@ -1442,11 +1357,8 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
private void lblModInfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblModInfoMouseClicked private void lblModInfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblModInfoMouseClicked
int idx = lstExternalMods.getSelectedRow(); int idx = lstExternalMods.getSelectedRow();
if (idx > 0 && idx < mods.size()) { if (idx > 0 && idx < profile.getMinecraftProvider().getModService().getMods().size())
ModInfo m = mods.get(idx); profile.getMinecraftProvider().getModService().getMods().get(idx).showURL();
if (m.url != null)
Utils.openLink(m.url);
}
}//GEN-LAST:event_lblModInfoMouseClicked }//GEN-LAST:event_lblModInfoMouseClicked
private void btnChoosingGameDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChoosingGameDirActionPerformed private void btnChoosingGameDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChoosingGameDirActionPerformed
@@ -1468,7 +1380,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_btnChoosingGameDirActionPerformed }//GEN-LAST:event_btnChoosingGameDirActionPerformed
private void btnMakeLaunchScriptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMakeLaunchScriptActionPerformed private void btnMakeLaunchScriptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMakeLaunchScriptActionPerformed
MainFrame.instance.mainPanel.btnMakeLaunchCodeActionPerformed(); MainFrame.INSTANCE.mainPanel.btnMakeLaunchCodeActionPerformed();
}//GEN-LAST:event_btnMakeLaunchScriptActionPerformed }//GEN-LAST:event_btnMakeLaunchScriptActionPerformed
private void btnShowLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowLogActionPerformed private void btnShowLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowLogActionPerformed
@@ -1476,15 +1388,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
}//GEN-LAST:event_btnShowLogActionPerformed }//GEN-LAST:event_btnShowLogActionPerformed
private void btnCleanGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanGameActionPerformed private void btnCleanGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanGameActionPerformed
File f = getProfile().getMinecraftProvider().getRunDirectory(mcVersion); profile.getMinecraftProvider().cleanFolder();
String[] dir = {"logs", "asm", "NVIDIA", "crash-reports", "server-resource-packs", "natives", "native"};
for (String s : dir)
FileUtils.deleteDirectoryQuietly(new File(f, s));
String[] files = {"output-client.log", "usercache.json", "usernamecache.json", "hmclmc.log"};
for (String s : files)
new File(f, s).delete();
for (MinecraftVersion s : getProfile().getMinecraftProvider().getVersions())
FileUtils.deleteDirectoryQuietly(new File(getProfile().getGameDirFile(), "versions" + File.separator + s.id + File.separator + s.id + "-natives"));
}//GEN-LAST:event_btnCleanGameActionPerformed }//GEN-LAST:event_btnCleanGameActionPerformed
// </editor-fold> // </editor-fold>
@@ -1601,15 +1505,6 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
// <editor-fold defaultstate="collapsed" desc="Assets"> // <editor-fold defaultstate="collapsed" desc="Assets">
public int assetsType; public int assetsType;
private void downloadAssets(final IAssetsHandler type) {
if (mcVersion == null || profile == null)
return;
type.getList(profile.getMinecraftProvider().getVersionById(mcVersion), profile.getMinecraftProvider(), (value) -> {
if (value != null)
SwingUtilities.invokeLater(() -> TaskWindow.getInstance().addTask(type.getDownloadTask(Settings.getInstance().getDownloadSource().getProvider())).start());
});
}
// </editor-fold> // </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Game Download"> // <editor-fold defaultstate="collapsed" desc="Game Download">
public void refreshDownloads(final DownloadType provider) { public void refreshDownloads(final DownloadType provider) {
@@ -1617,10 +1512,10 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
HTTPGetTask tsk = new HTTPGetTask(provider.getProvider().getVersionsListDownloadURL()); HTTPGetTask tsk = new HTTPGetTask(provider.getProvider().getVersionsListDownloadURL());
@Override @Override
public boolean executeTask() { public void executeTask() {
final MinecraftRemoteVersions v = C.gson.fromJson(tsk.getResult(), MinecraftRemoteVersions.class); final MinecraftRemoteVersions v = C.gson.fromJson(tsk.getResult(), MinecraftRemoteVersions.class);
if (v == null || v.versions == null) if (v == null || v.versions == null)
return true; return;
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel(); DefaultTableModel model = (DefaultTableModel) lstDownloads.getModel();
while (model.getRowCount() > 0) while (model.getRowCount() > 0)
@@ -1630,7 +1525,6 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot") ? C.i18n("versions." + ver.type) : ver.type}); StrUtils.equalsOne(ver.type, "old_beta", "old_alpha", "release", "snapshot") ? C.i18n("versions." + ver.type) : ver.type});
lstDownloads.updateUI(); lstDownloads.updateUI();
}); });
return true;
} }
@Override @Override
@@ -1672,7 +1566,7 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
Transferable tr = dtde.getTransferable(); Transferable tr = dtde.getTransferable();
List<File> files = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor); List<File> files = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : files) for (File file : files)
addMod(file); profile.getMinecraftProvider().getModService().addMod(file);
} catch (Exception ex) { } catch (Exception ex) {
HMCLog.warn("Failed to drop file.", ex); HMCLog.warn("Failed to drop file.", ex);
} }
@@ -1757,19 +1651,18 @@ btnRefreshLiteLoader.addActionListener(new java.awt.event.ActionListener() {
String mcVersion; String mcVersion;
// </editor-fold> // </editor-fold>
// <editor-fold> // <editor-fold defaultstate="collapsed" desc="Mods">
List<ModInfo> mods;
private final Object lockMod = new Object(); private final Object lockMod = new Object();
private void reloadMods() { private void reloadMods() {
new Thread(() -> { new Thread(() -> {
synchronized (lockMod) { synchronized (lockMod) {
mods = profile.getMinecraftProvider().listMods(); profile.getMinecraftProvider().getModService().recacheMods();
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
synchronized (lockMod) { synchronized (lockMod) {
SwingUtils.clearDefaultTable(lstExternalMods); SwingUtils.clearDefaultTable(lstExternalMods);
DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel(); DefaultTableModel model = (DefaultTableModel) lstExternalMods.getModel();
for (ModInfo info : mods) for (ModInfo info : profile.getMinecraftProvider().getModService().getMods())
model.addRow(new Object[] {info.isActive(), info.getFileName(), info.version}); model.addRow(new Object[] {info.isActive(), info.getFileName(), info.version});
} }
}); });

View File

@@ -274,7 +274,7 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
path = IOUtils.removeLastSeparator(path); path = IOUtils.removeLastSeparator(path);
txtBackgroundPath.setText(path); txtBackgroundPath.setText(path);
Settings.getInstance().setBgpath(path); Settings.getInstance().setBgpath(path);
MainFrame.instance.loadBackground(); MainFrame.INSTANCE.loadBackground();
} catch (IOException e) { } catch (IOException e) {
HMCLog.warn("Failed to set background path.", e); HMCLog.warn("Failed to set background path.", e);
MessageBox.Show(C.i18n("ui.label.failed_set") + e.getMessage()); MessageBox.Show(C.i18n("ui.label.failed_set") + e.getMessage());
@@ -283,7 +283,7 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
private void txtBackgroundPathFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtBackgroundPathFocusLost private void txtBackgroundPathFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtBackgroundPathFocusLost
Settings.getInstance().setBgpath(txtBackgroundPath.getText()); Settings.getInstance().setBgpath(txtBackgroundPath.getText());
MainFrame.instance.loadBackground(); MainFrame.INSTANCE.loadBackground();
}//GEN-LAST:event_txtBackgroundPathFocusLost }//GEN-LAST:event_txtBackgroundPathFocusLost
private void btnCheckUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckUpdateActionPerformed private void btnCheckUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckUpdateActionPerformed
@@ -296,8 +296,7 @@ public class LauncherSettingsPanel extends javax.swing.JPanel {
private void cboThemeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboThemeItemStateChanged private void cboThemeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboThemeItemStateChanged
Settings.getInstance().setTheme(cboTheme.getSelectedIndex()); Settings.getInstance().setTheme(cboTheme.getSelectedIndex());
if (MainFrame.instance != null) MainFrame.INSTANCE.reloadColor();
MainFrame.instance.reloadColor();
}//GEN-LAST:event_cboThemeItemStateChanged }//GEN-LAST:event_cboThemeItemStateChanged
private void txtProxyHostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtProxyHostFocusLost private void txtProxyHostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtProxyHostFocusLost

View File

@@ -52,7 +52,7 @@ import org.jackhuang.hellominecraft.views.BasicColors;
*/ */
public final class MainFrame extends DraggableFrame { public final class MainFrame extends DraggableFrame {
public static final MainFrame instance = new MainFrame(); public static final MainFrame INSTANCE = new MainFrame();
HeaderTab mainTab, gameTab, launcherTab; HeaderTab mainTab, gameTab, launcherTab;
TintablePanel centralPanel; TintablePanel centralPanel;
@@ -321,8 +321,8 @@ public final class MainFrame extends DraggableFrame {
} }
public static void showMainFrame(boolean firstLoad) { public static void showMainFrame(boolean firstLoad) {
instance.mainPanel.onShow(firstLoad); INSTANCE.mainPanel.onShow(firstLoad);
instance.show(); INSTANCE.show();
} }
Color borderColor = BasicColors.COLOR_BLUE; Color borderColor = BasicColors.COLOR_BLUE;

View File

@@ -71,9 +71,9 @@ public class MainPagePanel extends javax.swing.JPanel {
this.add(pnlButtons); this.add(pnlButtons);
pnlButtons.setBounds(0, 0, w, h); pnlButtons.setBounds(0, 0, w, h);
this.setSize(new Dimension(deWidth, deHeight)); this.setSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
this.pnlButtons.setLocation(deWidth - pnlButtons.getWidth() - 25, deHeight - pnlButtons.getHeight() - 25); this.pnlButtons.setLocation(DEFAULT_WIDTH - pnlButtons.getWidth() - 25, DEFAULT_HEIGHT - pnlButtons.getHeight() - 25);
pnlMore.setBounds(0, 0, pnlMore.getWidth(), deHeight); pnlMore.setBounds(0, 0, pnlMore.getWidth(), DEFAULT_HEIGHT);
pnlMore.setBackground(GraphicsUtils.getWebColorWithAlpha("FFFFFF7F")); pnlMore.setBackground(GraphicsUtils.getWebColorWithAlpha("FFFFFF7F"));
pnlMore.setOpaque(true); pnlMore.setOpaque(true);
@@ -267,7 +267,7 @@ public class MainPagePanel extends javax.swing.JPanel {
}// </editor-fold>//GEN-END:initComponents }// </editor-fold>//GEN-END:initComponents
private void txtPlayerNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerNameFocusGained private void txtPlayerNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerNameFocusGained
MainFrame.instance.closeMessage(); MainFrame.INSTANCE.closeMessage();
}//GEN-LAST:event_txtPlayerNameFocusGained }//GEN-LAST:event_txtPlayerNameFocusGained
private void txtPlayerNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerNameFocusLost private void txtPlayerNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerNameFocusLost
@@ -318,7 +318,7 @@ public class MainPagePanel extends javax.swing.JPanel {
}//GEN-LAST:event_cboVersionsItemStateChanged }//GEN-LAST:event_cboVersionsItemStateChanged
private void txtPasswordFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasswordFocusGained private void txtPasswordFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasswordFocusGained
MainFrame.instance.closeMessage(); MainFrame.INSTANCE.closeMessage();
}//GEN-LAST:event_txtPasswordFocusGained }//GEN-LAST:event_txtPasswordFocusGained
private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed
@@ -393,7 +393,7 @@ public class MainPagePanel extends javax.swing.JPanel {
gl.failEvent.register((sender, s) -> { gl.failEvent.register((sender, s) -> {
if (s != null) if (s != null)
MessageBox.Show(s); MessageBox.Show(s);
MainFrame.instance.closeMessage(); MainFrame.INSTANCE.closeMessage();
isLaunching = false; isLaunching = false;
return true; return true;
}); });
@@ -448,8 +448,8 @@ public class MainPagePanel extends javax.swing.JPanel {
if (!showedNoVersion) if (!showedNoVersion)
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
if (MessageBox.Show(C.i18n("mainwindow.no_version"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) { if (MessageBox.Show(C.i18n("mainwindow.no_version"), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
MainFrame.instance.selectTab("game"); MainFrame.INSTANCE.selectTab("game");
MainFrame.instance.gamePanel.showGameDownloads(); MainFrame.INSTANCE.gamePanel.showGameDownloads();
} }
showedNoVersion = true; showedNoVersion = true;
}); });
@@ -490,7 +490,7 @@ public class MainPagePanel extends javax.swing.JPanel {
private boolean isLoading = false; private boolean isLoading = false;
private final javax.swing.JPanel pnlButtons; private final javax.swing.JPanel pnlButtons;
private final ConstomButton btnRun; private final ConstomButton btnRun;
private static final int deWidth = 800, deHeight = 480; private static final int DEFAULT_WIDTH = 800, DEFAULT_HEIGHT = 480;
//</editor-fold> //</editor-fold>
class PrepareAuthDoneListener implements Event<List<String>> { class PrepareAuthDoneListener implements Event<List<String>> {
@@ -503,7 +503,7 @@ public class MainPagePanel extends javax.swing.JPanel {
} }
private void btnRunActionPerformed() { private void btnRunActionPerformed() {
MainFrame.instance.showMessage(C.i18n("ui.message.launching")); MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching"));
genLaunchCode(value -> { genLaunchCode(value -> {
value.successEvent.register(new LaunchFinisher()); value.successEvent.register(new LaunchFinisher());
value.successEvent.register(new PrepareAuthDoneListener()); value.successEvent.register(new PrepareAuthDoneListener());
@@ -511,7 +511,7 @@ public class MainPagePanel extends javax.swing.JPanel {
} }
public void btnMakeLaunchCodeActionPerformed() { public void btnMakeLaunchCodeActionPerformed() {
MainFrame.instance.showMessage(C.i18n("ui.message.launching")); MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching"));
genLaunchCode(value -> { genLaunchCode(value -> {
value.successEvent.register(new LaunchScriptFinisher()); value.successEvent.register(new LaunchScriptFinisher());
value.successEvent.register(new PrepareAuthDoneListener()); value.successEvent.register(new PrepareAuthDoneListener());
@@ -520,11 +520,11 @@ public class MainPagePanel extends javax.swing.JPanel {
public void onShow(boolean showLeft) { public void onShow(boolean showLeft) {
if (showLeft) if (showLeft)
SwingUtilities.invokeLater(() -> MainFrame.instance.showMessage(C.i18n("ui.message.first_load"))); SwingUtilities.invokeLater(() -> MainFrame.INSTANCE.showMessage(C.i18n("ui.message.first_load")));
if (cboLoginMode.getSelectedIndex() >= 0 && cboLoginMode.getSelectedIndex() < cboLoginMode.getItemCount()) { if (cboLoginMode.getSelectedIndex() >= 0 && cboLoginMode.getSelectedIndex() < cboLoginMode.getItemCount()) {
IAuthenticator l = IAuthenticator.LOGINS.get(cboLoginMode.getSelectedIndex()); IAuthenticator l = IAuthenticator.LOGINS.get(cboLoginMode.getSelectedIndex());
if (!l.isHidePasswordBox() && !l.isLoggedIn()) if (!l.isHidePasswordBox() && !l.isLoggedIn())
SwingUtilities.invokeLater(() -> MainFrame.instance.showMessage(C.i18n("ui.message.enter_password"))); SwingUtilities.invokeLater(() -> MainFrame.INSTANCE.showMessage(C.i18n("ui.message.enter_password")));
} }
} }

View File

@@ -0,0 +1,31 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.jackhuang.hellominecraft.tasks;
/**
*
* @author huangyuhui
*/
public class DoubleTask extends Task {
Task a, b;
public DoubleTask(Task a, Task b) {
this.a = a;
this.b = b;
}
@Override
public void executeTask() throws Throwable {
a.executeTask(); b.executeTask();
}
@Override
public String getInfo() {
return "Double Task";
}
}

View File

@@ -28,8 +28,7 @@ public class ParallelTask extends Task {
Collection<Task> dependsTask = new HashSet<>(); Collection<Task> dependsTask = new HashSet<>();
@Override @Override
public boolean executeTask() { public void executeTask() {
return true;
} }
@Override @Override

View File

@@ -18,6 +18,7 @@ package org.jackhuang.hellominecraft.tasks;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import org.jackhuang.hellominecraft.HMCLog;
/** /**
* *
@@ -27,10 +28,8 @@ public abstract class Task {
/** /**
* Run in a new thread(packed in TaskList). * Run in a new thread(packed in TaskList).
*
* @return is task finished sucessfully.
*/ */
public abstract boolean executeTask(); public abstract void executeTask() throws Throwable;
/** /**
* if this func returns false, TaskList will force abort the thread. run in * if this func returns false, TaskList will force abort the thread. run in
@@ -101,4 +100,20 @@ public abstract class Task {
ppl = p; ppl = p;
return this; return this;
} }
public Task after(Task t) {
return new DoubleTask(this, t);
}
public Task before(Task t) {
return new DoubleTask(t, this);
}
public void run() {
try {
executeTask();
} catch(Throwable t) {
HMCLog.err("Failed to execute task", t);
}
}
} }

View File

@@ -117,13 +117,14 @@ public class TaskList extends Thread {
for (DoingDoneListener<Task> d : t.getTaskListeners()) for (DoingDoneListener<Task> d : t.getTaskListeners())
d.onDoing(t); d.onDoing(t);
boolean returns = false; boolean flag = true;
try { try {
returns = t.executeTask(); t.executeTask();
} catch (Throwable e) { } catch (Throwable e) {
t.setFailReason(e); t.setFailReason(e);
flag = false;
} }
if (returns) { if (flag) {
HMCLog.log((t.isAborted() ? "Task aborted: " : "Task finished: ") + t.getInfo()); HMCLog.log((t.isAborted() ? "Task aborted: " : "Task finished: ") + t.getInfo());
for (DoingDoneListener<Task> d : taskListener) for (DoingDoneListener<Task> d : taskListener)
d.onDone(t); d.onDone(t);

View File

@@ -29,15 +29,13 @@ public class TaskRunnable extends TaskInfo {
this.r = r; this.r = r;
} }
public TaskRunnable(Runnable r) {
this("TaskRunnable", r);
}
@Override @Override
public boolean executeTask() { public void executeTask() {
try { r.run();
r.run();
return true;
} catch (Throwable t) {
setFailReason(t);
return false;
}
} }
} }

View File

@@ -36,16 +36,10 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
if (al.size() != 1) if (al.size() != 1)
throw new IllegalStateException("the count of args is not one."); throw new IllegalStateException("the count of args is not one.");
try { r.accept(al.get(0).getResult());
r.accept(al.get(0).getResult());
return true;
} catch (Throwable t) {
setFailReason(t);
return false;
}
} }
ArrayList<PreviousResult<T>> al = new ArrayList(); ArrayList<PreviousResult<T>> al = new ArrayList();

View File

@@ -31,9 +31,9 @@ public class ContentGetAndShowTask extends HTTPGetTask implements Event<String>
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
tdtsl.register(this); tdtsl.register(this);
return super.executeTask(); super.executeTask();
} }
String info; String info;

View File

@@ -92,7 +92,7 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
// Download file. // Download file.
@Override @Override
public boolean executeTask() { public void executeTask() throws Throwable {
for (PreviousResult<String> p : al) for (PreviousResult<String> p : al)
this.url = IOUtils.parseURL(p.getResult()); this.url = IOUtils.parseURL(p.getResult());
@@ -113,15 +113,13 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
// Make sure response code is in the 200 range. // Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) { if (connection.getResponseCode() / 100 != 2) {
setFailReason(new NetException(C.i18n("download.not_200") + " " + connection.getResponseCode())); throw new NetException(C.i18n("download.not_200") + " " + connection.getResponseCode());
return false;
} }
// Check for valid content length. // Check for valid content length.
int contentLength = connection.getContentLength(); int contentLength = connection.getContentLength();
if (contentLength < 1) { if (contentLength < 1) {
setFailReason(new NetException("The content length is invalid.")); throw new NetException("The content length is invalid.");
return false;
} }
filePath.getParentFile().mkdirs(); filePath.getParentFile().mkdirs();
@@ -173,17 +171,17 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
} }
if (ppl != null) if (ppl != null)
ppl.onProgressProviderDone(this); ppl.onProgressProviderDone(this);
return true; return;
} catch (Exception e) { } catch (Exception e) {
setFailReason(new NetException(C.i18n("download.failed") + " " + url, e)); setFailReason(new NetException(C.i18n("download.failed") + " " + url, e));
} finally { } finally {
closeFiles(); closeFiles();
} }
} }
return false; if (failReason != null) throw failReason;
} }
public static void download(String url, String file, DownloadListener dl) { public static void download(String url, String file, DownloadListener dl) throws Throwable {
((Task) new FileDownloadTask(url, new File(file)).setProgressProviderListener(dl)).executeTask(); ((Task) new FileDownloadTask(url, new File(file)).setProgressProviderListener(dl)).executeTask();
} }

View File

@@ -50,7 +50,8 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
} }
@Override @Override
public boolean executeTask() { public void executeTask() throws Exception {
Exception t = null;
for (int repeat = 0; repeat < 6; repeat++) { for (int repeat = 0; repeat < 6; repeat++) {
if (repeat > 0) if (repeat > 0)
HMCLog.warn("Failed to download, repeat: " + repeat); HMCLog.warn("Failed to download, repeat: " + repeat);
@@ -65,16 +66,16 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
if (ppl != null) if (ppl != null)
ppl.setProgress(this, ++read, size); ppl.setProgress(this, ++read, size);
if (!shouldContinue) if (!shouldContinue)
return true; return;
} }
result = baos.toString(); result = baos.toString();
tdtsl.execute(result); tdtsl.execute(result);
return true; return;
} catch (Exception ex) { } catch (Exception ex) {
setFailReason(new NetException("Failed to get " + url, ex)); t = new NetException("Failed to get " + url, ex);
} }
} }
return false; if (t != null) throw t;
} }
@Override @Override

View File

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

View File

@@ -3160,7 +3160,7 @@ implements MonitorThread.MonitorThreadListener, Event<Integer> {
} }
@Override @Override
public boolean executeTask() { public void executeTask() {
javax.swing.JTable table = MainWindow.this.lstDownloads; javax.swing.JTable table = MainWindow.this.lstDownloads;
DefaultTableModel model = (DefaultTableModel) table.getModel(); DefaultTableModel model = (DefaultTableModel) table.getModel();
@@ -3173,7 +3173,6 @@ implements MonitorThread.MonitorThreadListener, Event<Integer> {
line[3] = ver.type; line[3] = ver.type;
model.addRow(line); model.addRow(line);
} }
return true;
} }
@Override @Override