Might fix some bugs?

This commit is contained in:
huangyuhui 2016-02-05 17:03:25 +08:00
parent d4dccd1391
commit 27a013450e
68 changed files with 931 additions and 384 deletions

View File

@ -26,6 +26,9 @@ import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
@ -44,14 +47,12 @@ import org.jackhuang.hellominecraft.util.Utils;
*/
public final class Launcher {
public static void println(String s) {
System.out.println(s);
}
static final Logger LOGGER = LogManager.getLogManager().getLogger(Launcher.class.getName());
static String classPath = "", proxyHost = "", proxyPort = "", proxyUsername = "", proxyPassword = "";
public static void main(String[] args) {
println("*** " + Main.makeTitle() + " ***");
LOGGER.log(Level.INFO, "*** {0} ***", Main.makeTitle());
boolean showInfo = false;
String mainClass = "net.minecraft.client.Minecraft";
@ -91,7 +92,7 @@ public final class Launcher {
try {
File logFile = new File("hmclmc.log");
if (!logFile.exists() && !logFile.createNewFile())
println("Failed to create log file");
LOGGER.info("Failed to create log file");
else {
FileOutputStream tc = new FileOutputStream(logFile);
DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
@ -100,13 +101,12 @@ public final class Launcher {
System.setErr(new LauncherPrintStream(err));
}
} catch (IOException e) {
println("Failed to add log file appender.");
e.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to add log file appender.", e);
}
println("Arguments: {\n" + StrUtils.parseParams(" ", args, "\n") + "\n}");
println("Main Class: " + mainClass);
println("Class Path: {\n" + StrUtils.parseParams(" ", tokenized, "\n") + "\n}");
LOGGER.log(Level.INFO, "Arguments: '{'\n{0}\n'}'", StrUtils.parseParams(" ", args, "\n"));
LOGGER.log(Level.INFO, "Main Class: {0}", mainClass);
LOGGER.log(Level.INFO, "Class Path: '{'\n{0}\n'}'", StrUtils.parseParams(" ", tokenized, "\n"));
SwingUtilities.invokeLater(() -> LogWindow.INSTANCE.setVisible(true));
}
@ -133,8 +133,7 @@ public final class Launcher {
urls[j] = new File(tokenized[j]).toURI().toURL();
} catch (Throwable e) {
MessageBox.Show(C.i18n("crash.main_class_not_found"));
println("Failed to get classpath.");
e.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to get classpath.", e);
return;
}
@ -145,12 +144,11 @@ public final class Launcher {
minecraftMain = ucl.loadClass(mainClass).getMethod("main", String[].class);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException t) {
MessageBox.Show(C.i18n("crash.main_class_not_found"));
println("Minecraft main class not found.");
t.printStackTrace();
LOGGER.log(Level.SEVERE, "Minecraft main class not found.", t);
return;
}
println("*** Launching Game ***");
LOGGER.info("*** Launching Game ***");
int flag = 0;
try {
@ -168,7 +166,7 @@ public final class Launcher {
flag = 1;
}
println("*** Game Exited ***");
LOGGER.info("*** Game Exited ***");
try {
Utils.shutdownForcely(flag);
} catch (Exception e) {

View File

@ -26,6 +26,8 @@ import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
@ -67,7 +69,7 @@ public final class Main implements Runnable {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
return new X509Certificate[0];
}
};
private static final HostnameVerifier HNV = (hostname, session) -> true;
@ -111,7 +113,9 @@ public final class Main implements Runnable {
}
public static final Main INSTANCE = new Main();
public static HelloMinecraftLookAndFeel LOOK_AND_FEEL;
private static HelloMinecraftLookAndFeel LOOK_AND_FEEL;
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
@SuppressWarnings({ "CallToPrintStackTrace", "UseSpecificCatch" })
public static void main(String[] args) throws IOException {
@ -126,12 +130,11 @@ public final class Main implements Runnable {
try {
File file = new File("hmcl.log");
if (!file.exists())
file.createNewFile();
if (!file.exists() && !file.createNewFile())
HMCLog.warn("Failed to create log file " + file);
Configuration.DEFAULT.appenders.add(new ConsoleAppender("File", new DefaultLayout(), true, new FileOutputStream(file), true));
} catch (IOException ex) {
System.err.println("Failed to add log appender File because an error occurred while creating or opening hmcl.log");
ex.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to add log appender File because an error occurred while creating or opening hmcl.log", ex);
}
HMCLog.log("*** " + Main.makeTitle() + " ***");
@ -170,7 +173,7 @@ public final class Main implements Runnable {
}
try {
PluginManager.NOW_PLUGIN.showUI();
PluginManager.plugin().showUI();
} catch (Throwable t) {
new CrashReporter(false).uncaughtException(Thread.currentThread(), t);
System.exit(1);

View File

@ -26,7 +26,7 @@ import org.jackhuang.hellominecraft.launcher.setting.DefaultPlugin;
*/
public class PluginManager {
public static IPlugin NOW_PLUGIN = new DefaultPlugin();
private static IPlugin NOW_PLUGIN = new DefaultPlugin();
public static void getServerPlugin() {
try {
@ -40,4 +40,8 @@ public class PluginManager {
}
}
public static IPlugin plugin() {
return NOW_PLUGIN;
}
}

View File

@ -80,11 +80,11 @@ public final class MCUtils {
return gameDir;
}
public static String profile = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static final String PROFILE = "{\"selectedProfile\": \"(Default)\",\"profiles\": {\"(Default)\": {\"name\": \"(Default)\"}},\"clientToken\": \"88888888-8888-8888-8888-888888888888\"}";
public static void tryWriteProfile(File gameDir) throws IOException {
File file = new File(gameDir, "launcher_profiles.json");
if (!file.exists())
FileUtils.writeStringToFile(file, profile);
FileUtils.writeStringToFile(file, PROFILE);
}
}

View File

@ -109,7 +109,7 @@ public class ModInfo implements Comparable<ModInfo> {
private static ModInfo getForgeModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException {
ModInfo i = new ModInfo();
i.location = f;
List<ModInfo> m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), TYPE);
List<ModInfo> m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry), "UTF-8"), TYPE);
if (m != null && m.size() > 0) {
i = m.get(0);
i.location = f;
@ -118,7 +118,7 @@ public class ModInfo implements Comparable<ModInfo> {
}
private static ModInfo getLiteLoaderModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException {
ModInfo m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), ModInfo.class);
ModInfo m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry), "UTF-8"), ModInfo.class);
if (m == null)
m = new ModInfo();
m.location = f;

View File

@ -26,6 +26,19 @@ public class AssetsObject {
private String hash;
private long size;
public AssetsObject(String hash, long size) {
this.hash = hash;
this.size = size;
}
public void setHash(String hash) {
this.hash = hash;
}
public void setSize(long size) {
this.size = size;
}
public AssetsObject() {
}

View File

@ -24,6 +24,58 @@ package org.jackhuang.hellominecraft.launcher.core.asset;
public class Contents {
public String key, eTag, lastModified, storageClass;
public Contents() {
}
public Contents(String key, String eTag, String lastModified, String storageClass, long size) {
this();
this.key = key;
this.eTag = eTag;
this.lastModified = lastModified;
this.storageClass = storageClass;
this.size = size;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String geteTag() {
return eTag;
}
public void seteTag(String eTag) {
this.eTag = eTag;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
public String getStorageClass() {
return storageClass;
}
public void setStorageClass(String storageClass) {
this.storageClass = storageClass;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public long size;
}

View File

@ -97,7 +97,7 @@ public abstract class IAssetsHandler {
@Override
public void executeTask() {
if (assetsDownloadURLs == null || assetsLocalNames == null)
if (assetsDownloadURLs == null || assetsLocalNames == null || contents == null)
throw new IllegalStateException(C.i18n("assets.not_refreshed"));
int max = assetsDownloadURLs.size();
al = new ArrayList<>();
@ -106,8 +106,8 @@ public abstract class IAssetsHandler {
String mark = assetsDownloadURLs.get(i);
String url = u + mark;
File location = assetsLocalNames.get(i);
if (!location.getParentFile().exists())
location.getParentFile().mkdirs();
if (!location.getParentFile().exists() && !location.getParentFile().mkdirs())
HMCLog.warn("Failed to make directories: " + location.getParent());
if (location.isDirectory())
continue;
boolean need = true;
@ -116,7 +116,7 @@ public abstract class IAssetsHandler {
FileInputStream fis = new FileInputStream(location);
String sha = DigestUtils.sha1Hex(NetUtils.getBytesFromStream(fis));
IOUtils.closeQuietly(fis);
if (contents.get(i).eTag.equals(sha)) {
if (contents.get(i).geteTag().equals(sha)) {
hasDownloaded++;
HMCLog.log("File " + assetsLocalNames.get(i) + " has downloaded successfully, skipped downloading.");
if (ppl != null)

View File

@ -24,6 +24,7 @@ import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftAssetService;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftService;
import org.jackhuang.hellominecraft.launcher.core.version.MinecraftVersion;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
import org.jackhuang.hellominecraft.util.tasks.download.FileDownloadTask;
@ -71,22 +72,24 @@ public class MinecraftAssetService extends IMinecraftAssetService {
String aurl = service.getDownloadType().getProvider().getIndexesDownloadURL();
File assetsLocation = getAssets();
assetsLocation.mkdirs();
if (!assetsLocation.exists() && !assetsLocation.mkdirs())
HMCLog.warn("Failed to make directories: " + assetsLocation);
File assetsIndex = new File(assetsLocation, "indexes/" + assetsId + ".json");
File renamed = null;
if (assetsIndex.exists()) {
renamed = new File(assetsLocation, "indexes/" + assetsId + "-renamed.json");
assetsIndex.renameTo(renamed);
if (assetsIndex.renameTo(renamed))
HMCLog.warn("Failed to rename " + assetsIndex + " to " + renamed);
}
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(aurl + assetsId + ".json", IOUtils.tryGetCanonicalFile(assetsIndex)).setTag(assetsId + ".json"))
.start()) {
if (renamed != null)
renamed.delete();
if (renamed != null && !renamed.delete())
HMCLog.warn("Failed to delete " + renamed + ", maybe you should do it.");
return true;
}
if (renamed != null)
renamed.renameTo(assetsIndex);
if (renamed != null && !renamed.renameTo(assetsIndex))
HMCLog.warn("Failed to rename " + renamed + " to " + assetsIndex);
return false;
}

View File

@ -21,6 +21,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import org.jackhuang.hellominecraft.util.code.DigestUtils;
/**
@ -41,7 +42,7 @@ public final class BestLogin extends IAuthenticator {
Socket socket = new Socket("auth.zhh0000zhh.com", 8);
OutputStream os = socket.getOutputStream();
os.write(request.length());
os.write(request.getBytes());
os.write(request.getBytes(Charset.forName("UTF-8")));
UserProfileProvider lr = new UserProfileProvider();
@ -64,13 +65,17 @@ public final class BestLogin extends IAuthenticator {
throw new AuthenticationException("server reloading.");
case 0:
byte[] b = new byte[64];
is.read(b, 0, b.length);
String[] ss = new String(b).split(":");
int x = is.read(b, 0, b.length);
if (x != -1)
throw new AuthenticationException("server response does not follow the protocol.");
String[] ss = new String(b, Charset.forName("UTF-8")).split(":");
lr.setUserName(info.username);
lr.setUserId(ss[1]);
lr.setSession(ss[0]);
lr.setAccessToken(ss[0]);
break;
default:
break;
}
lr.setUserType("Legacy");
return lr;
@ -95,7 +100,7 @@ public final class BestLogin extends IAuthenticator {
}
@Override
public void logout() {
public void logOut() {
}
}

View File

@ -33,7 +33,7 @@ public abstract class IAuthenticator {
public static final List<IAuthenticator> LOGINS = new ArrayList<>();
static {
PluginManager.NOW_PLUGIN.onRegisterAuthenticators(LOGINS::add);
PluginManager.plugin().onRegisterAuthenticators(LOGINS::add);
}
protected String clientToken, username;
@ -42,6 +42,10 @@ public abstract class IAuthenticator {
this.clientToken = clientToken;
}
public String getClientToken() {
return clientToken;
}
/**
* Login Method
*
@ -81,7 +85,7 @@ public abstract class IAuthenticator {
public abstract UserProfileProvider loginBySettings() throws AuthenticationException;
public abstract void logout();
public abstract void logOut();
public Map onSaveSettings() {
HashMap m = new HashMap();
@ -95,11 +99,11 @@ public abstract class IAuthenticator {
username = (String) m.get("IAuthenticator_UserName");
}
public String getUsername() {
public String getUserName() {
return username;
}
public void setUsername(String s) {
public void setUserName(String s) {
username = s;
}
}

View File

@ -98,7 +98,7 @@ public final class OfflineAuthenticator extends IAuthenticator {
}
@Override
public void logout() {
public void logOut() {
}
}

View File

@ -20,6 +20,7 @@ package org.jackhuang.hellominecraft.launcher.core.auth;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.code.DigestUtils;
import org.jackhuang.hellominecraft.util.NetUtils;
import org.jackhuang.hellominecraft.util.lang.SupportedLocales;
import org.jackhuang.hellominecraft.util.ui.Selector;
/**
@ -47,7 +48,7 @@ public final class SkinmeAuthenticator extends IAuthenticator {
if (info.username == null || !info.username.contains("@"))
throw new AuthenticationException(C.i18n("login.not_email"));
try {
String usr = info.username.toLowerCase();
String usr = info.username.toLowerCase(SupportedLocales.NOW_LOCALE.self);
String pwd = info.password;
String str = DigestUtils.sha1Hex(usr);
@ -120,7 +121,7 @@ public final class SkinmeAuthenticator extends IAuthenticator {
}
@Override
public void logout() {
public void logOut() {
}
}

View File

@ -57,7 +57,7 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
if (!ua.isLoggedIn())
ua.setPassword(pwd);
ua.setUsername(usr);
ua.setUserName(usr);
ua.logIn();
if (!ua.isLoggedIn())
throw new AuthenticationException(C.i18n("login.wrong_password"));
@ -136,7 +136,7 @@ public final class YggdrasilAuthenticator extends IAuthenticator {
}
@Override
public void logout() {
public void logOut() {
ua.logOut();
}
}

View File

@ -21,9 +21,49 @@ import java.util.HashMap;
public class AuthenticationRequest {
public HashMap<String, Object> agent;
public String username, password, clientToken;
public boolean requestUser = true;
private HashMap<String, Object> agent;
private String username, password, clientToken;
private boolean requestUser = true;
public HashMap<String, Object> getAgent() {
return agent;
}
public void setAgent(HashMap<String, Object> agent) {
this.agent = agent;
}
public String getUserName() {
return username;
}
public void setUserName(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getClientToken() {
return clientToken;
}
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
public boolean isRequestUser() {
return requestUser;
}
public void setRequestUser(boolean requestUser) {
this.requestUser = requestUser;
}
public AuthenticationRequest(String username, String password, String clientToken) {
agent = new HashMap<>();

View File

@ -73,6 +73,8 @@ public class GameProfile {
@Override
public GameProfile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!(json instanceof JsonObject))
throw new JsonParseException("The json element is not a JsonObject.");
JsonObject object = (JsonObject) json;
UUID id = object.has("id") ? (UUID) context.deserialize(object.get("id"), UUID.class) : null;
String name = object.has("name") ? object.getAsJsonPrimitive("name").getAsString() : null;

View File

@ -35,6 +35,8 @@ import org.jackhuang.hellominecraft.util.logging.HMCLog;
public class PropertyMap extends HashMap<String, Property> {
private static final long serialVersionUID = 362498820763181265L;
public List<Map<String, String>> list() {
List<Map<String, String>> properties = new ArrayList<>();
for (Property profileProperty : values()) {

View File

@ -19,13 +19,46 @@ package org.jackhuang.hellominecraft.launcher.core.auth.yggdrasil;
public class RefreshRequest {
public String clientToken;
public String accessToken;
public GameProfile selectedProfile;
public boolean requestUser = true;
private String clientToken;
private String accessToken;
private GameProfile selectedProfile;
private boolean requestUser = true;
public RefreshRequest(String accessToken, String clientToken) {
this.clientToken = clientToken;
this.accessToken = accessToken;
}
public String getClientToken() {
return clientToken;
}
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public GameProfile getSelectedProfile() {
return selectedProfile;
}
public void setSelectedProfile(GameProfile selectedProfile) {
this.selectedProfile = selectedProfile;
}
public boolean isRequestUser() {
return requestUser;
}
public void setRequestUser(boolean requestUser) {
this.requestUser = requestUser;
}
}

View File

@ -19,6 +19,31 @@ package org.jackhuang.hellominecraft.launcher.core.auth.yggdrasil;
public class User {
public String id;
public PropertyMap properties;
private String id;
private PropertyMap properties;
public User() {
}
public User(String id, PropertyMap properties) {
this.id = id;
this.properties = properties;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public PropertyMap getProperties() {
return properties;
}
public void setProperties(PropertyMap properties) {
this.properties = properties;
}
}

View File

@ -67,7 +67,7 @@ public class YggdrasilAuthentication {
}
// <editor-fold defaultstate="collapsed" desc="Get/Set">
public void setUsername(String username) {
public void setUserName(String username) {
if ((isLoggedIn()) && (canPlayOnline()))
throw new IllegalStateException("Cannot change username while logged in & online");
@ -96,7 +96,7 @@ public class YggdrasilAuthentication {
}
public GameProfile[] getAvailableProfiles() {
return profiles;
return profiles.clone();
}
public String getAuthenticatedToken() {
@ -154,7 +154,7 @@ public class YggdrasilAuthentication {
throw new AuthenticationException(C.i18n("login.changed_client_token"));
User user = response.user;
userid = user != null && user.id != null ? user.id : username;
userid = user != null && user.getId() != null ? user.getId() : username;
isOnline = true;
profiles = response.availableProfiles;
@ -162,8 +162,8 @@ public class YggdrasilAuthentication {
userProperties.clear();
this.accessToken = response.accessToken;
if (user != null && user.properties != null)
userProperties.putAll(user.properties);
if (user != null && user.getProperties() != null)
userProperties.putAll(user.getProperties());
} catch (IOException | IllegalStateException | JsonParseException e) {
throw new AuthenticationException(C.i18n("login.failed.connect_authentication_server"), e);
}
@ -185,7 +185,7 @@ public class YggdrasilAuthentication {
public void loadFromStorage(Map<String, Object> credentials) {
logOut();
setUsername((String) credentials.get(STORAGE_KEY_USER_NAME));
setUserName((String) credentials.get(STORAGE_KEY_USER_NAME));
if (credentials.containsKey(STORAGE_KEY_USER_ID))
userid = (String) credentials.get(STORAGE_KEY_USER_ID);

View File

@ -76,9 +76,12 @@ public class MinecraftDownloadService extends IMinecraftDownloadService {
File vpath = new File(service.baseDirectory(), "versions/" + id);
File mvt = new File(vpath, id + ".json");
File mvj = new File(vpath, id + ".jar");
vpath.mkdirs();
mvt.delete();
mvj.delete();
if (!vpath.exists() && !vpath.mkdirs())
HMCLog.warn("Failed to make directories: " + vpath);
if (mvt.exists() && !mvt.delete())
HMCLog.warn("Failed to delete " + mvt);
if (mvj.exists() && !mvj.delete())
HMCLog.warn("Failed to delete " + mvj);
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json"))
@ -101,20 +104,23 @@ public class MinecraftDownloadService extends IMinecraftDownloadService {
File mvv = new File(vpath, id + ".jar"), moved = null;
if (mvv.exists()) {
moved = new File(vpath, id + "-renamed.jar");
mvv.renameTo(moved);
if (!mvv.renameTo(moved))
HMCLog.warn("Failed to rename " + mvv + " to " + moved);
}
File mvt = new File(vpath, id + ".jar");
vpath.mkdirs();
if (!vpath.exists() && !vpath.mkdirs())
HMCLog.warn("Failed to make version folder " + vpath);
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".jar", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".jar"))
.start()) {
if (moved != null)
moved.delete();
if (moved != null && moved.exists() && !moved.delete())
HMCLog.warn("Failed to delete " + moved);
return true;
} else {
mvt.delete();
if (moved != null)
moved.renameTo(mvt);
if (mvt.exists() && !mvt.delete())
HMCLog.warn("Failed to delete game jar " + mvt);
if (moved != null && moved.exists() && !moved.renameTo(mvt))
HMCLog.warn("Failed to rename " + moved + " to " + mvt);
return false;
}
}
@ -132,20 +138,23 @@ public class MinecraftDownloadService extends IMinecraftDownloadService {
File mvv = new File(vpath, id + ".json"), moved = null;
if (mvv.exists()) {
moved = new File(vpath, id + "-renamed.json");
mvv.renameTo(moved);
if (!mvv.renameTo(moved))
HMCLog.warn("Failed to rename " + mvv + " to " + moved);
}
File mvt = new File(vpath, id + ".json");
vpath.mkdirs();
if (!vpath.exists() && !vpath.mkdirs())
HMCLog.warn("Failed to make version folder " + vpath);
if (TaskWindow.getInstance()
.addTask(new FileDownloadTask(vurl + id + ".json", IOUtils.tryGetCanonicalFile(mvt)).setTag(id + ".json"))
.start()) {
if (moved != null)
moved.delete();
if (moved != null && moved.exists() && !moved.delete())
HMCLog.warn("Failed to delete " + moved);
return true;
} else {
mvt.delete();
if (moved != null)
moved.renameTo(mvt);
if (mvt.exists() && !mvt.delete())
HMCLog.warn("Failed to delete minecraft version json" + mvt);
if (moved != null && moved.exists() && !moved.renameTo(mvt))
HMCLog.warn("Failed to rename " + moved + " to " + mvt);
return false;
}
}
@ -157,7 +166,7 @@ public class MinecraftDownloadService extends IMinecraftDownloadService {
protected void work() throws Exception {
MinecraftRemoteVersions r = C.GSON.fromJson(NetUtils.get(service.getDownloadType().getProvider().getVersionsListDownloadURL()), MinecraftRemoteVersions.class);
if (r != null && r.versions != null)
publish(r.versions.toArray(new MinecraftRemoteVersion[0]));
publish(r.versions.toArray(new MinecraftRemoteVersion[r.versions.size()]));
}
};
}

View File

@ -17,9 +17,11 @@
*/
package org.jackhuang.hellominecraft.launcher.core.install;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import org.jackhuang.hellominecraft.util.func.Consumer;
/**
@ -84,9 +86,29 @@ public abstract class InstallerVersionList implements Consumer<String[]> {
public int compareTo(InstallerVersion o) {
return selfVersion.compareTo(o.selfVersion);
}
@Override
public int hashCode() {
return selfVersion.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final InstallerVersion other = (InstallerVersion) obj;
return Objects.equals(this.selfVersion, other.selfVersion);
}
}
public static class InstallerVersionComparator implements Comparator<InstallerVersion> {
public static class InstallerVersionComparator implements Comparator<InstallerVersion>, Serializable {
private static final long serialVersionUID = 3276198781795213723L;
public static final InstallerVersionComparator INSTANCE = new InstallerVersionComparator();

View File

@ -17,6 +17,7 @@
*/
package org.jackhuang.hellominecraft.launcher.core.install;
import java.io.Serializable;
import java.util.Comparator;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList.InstallerVersion;
@ -24,10 +25,12 @@ import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList.I
*
* @author huangyuhui
*/
public class InstallerVersionNewerComparator implements Comparator<InstallerVersion> {
public class InstallerVersionNewerComparator implements Comparator<InstallerVersion>, Serializable {
private static final long serialVersionUID = 14758562453742645L;
@Override
public int compare(InstallerVersion o1, InstallerVersion o2) {
return -o1.compareTo(o2);
return o2.compareTo(o1);
}
}

View File

@ -65,7 +65,7 @@ public final class MinecraftInstallerService extends IMinecraftInstallerService
if (v.installer != null)
TaskWindow.getInstance()
.addTask(new FileDownloadTask(service.getDownloadType().getProvider().getParsedLibraryDownloadURL(v.installer), filepath).setTag("forge"))
.addTask(new ForgeInstaller(service, filepath, v))
.addTask(new ForgeInstaller(service, filepath))
.start();
}
};

View File

@ -20,6 +20,7 @@ package org.jackhuang.hellominecraft.launcher.core.install;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.system.Compressor;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
@ -40,7 +41,8 @@ public class PackMinecraftInstaller {
public void install() throws IOException {
File file = new File(IOUtils.currentDir(), "HMCL-MERGE-TEMP");
file.mkdirs();
if (!file.exists() && !file.mkdirs())
HMCLog.warn("Failed to make directories: " + file);
for (String src1 : src)
Compressor.unzip(new File(src1), file);
Compressor.zip(file.getAbsolutePath(), dest.getAbsolutePath());

View File

@ -27,7 +27,6 @@ import java.util.zip.ZipFile;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.launcher.core.service.IMinecraftService;
import org.jackhuang.hellominecraft.launcher.core.install.InstallerVersionList.InstallerVersion;
import org.jackhuang.hellominecraft.util.tasks.Task;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.NetUtils;
@ -43,62 +42,51 @@ public class ForgeInstaller extends Task {
public File gameDir;
public File forgeInstaller;
public IMinecraftService mp;
public InstallerVersion installerVersion;
public ForgeInstaller(IMinecraftService mp, File forgeInstaller, InstallerVersion installerVersion) {
public ForgeInstaller(IMinecraftService mp, File forgeInstaller) {
this.gameDir = mp.baseDirectory();
this.forgeInstaller = forgeInstaller;
this.mp = mp;
this.installerVersion = installerVersion;
}
@Override
public void executeTask() throws Exception {
HMCLog.log("Extracting install profiles...");
ZipFile zipFile = new ZipFile(forgeInstaller);
ZipEntry entry = zipFile.getEntry("install_profile.json");
String content = NetUtils.getStreamContent(zipFile.getInputStream(entry));
InstallProfile profile = C.GSON.fromJson(content, InstallProfile.class);
File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft);
if (!from.exists())
if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) {
if (!mp.version().install(profile.install.minecraft, null))
try (ZipFile zipFile = new ZipFile(forgeInstaller)) {
ZipEntry entry = zipFile.getEntry("install_profile.json");
String content = NetUtils.getStreamContent(zipFile.getInputStream(entry));
InstallProfile profile = C.GSON.fromJson(content, InstallProfile.class);
File from = new File(gameDir, "versions" + File.separator + profile.install.getMinecraft());
if (!from.exists())
if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) {
if (!mp.version().install(profile.install.getMinecraft(), null))
throw new IllegalStateException(C.i18n("install.no_version"));
} else
throw new IllegalStateException(C.i18n("install.no_version"));
} else
throw new IllegalStateException(C.i18n("install.no_version"));
File to = new File(gameDir, "versions" + File.separator + profile.install.target);
to.mkdirs();
HMCLog.log("Copying jar..." + profile.install.minecraft + ".jar to " + profile.install.target + ".jar");
FileUtils.copyFile(new File(from, profile.install.minecraft + ".jar"),
new File(to, profile.install.target + ".jar"));
HMCLog.log("Creating new version profile..." + profile.install.target + ".json");
/*
* for (MinecraftLibrary library : profile.versionInfo.libraries)
* if (library.name.startsWith("net.minecraftforge:forge:"))
* library.url = installerVersion.universal;
*/
FileUtils.write(new File(to, profile.install.target + ".json"), C.GSON.toJson(profile.versionInfo));
HMCLog.log("Extracting universal forge pack..." + profile.install.filePath);
entry = zipFile.getEntry(profile.install.filePath);
InputStream is = zipFile.getInputStream(entry);
MinecraftLibrary forge = new MinecraftLibrary(profile.install.path);
forge.init();
File file = new File(gameDir, "libraries/" + forge.formatted);
file.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int c;
while ((c = is.read()) != -1)
bos.write((byte) c);
File to = new File(gameDir, "versions" + File.separator + profile.install.getTarget());
if (!to.exists() && !to.mkdirs())
HMCLog.warn("Failed to make new version folder " + to);
HMCLog.log("Copying jar..." + profile.install.getMinecraft() + ".jar to " + profile.install.getTarget() + ".jar");
FileUtils.copyFile(new File(from, profile.install.getMinecraft() + ".jar"),
new File(to, profile.install.getTarget() + ".jar"));
HMCLog.log("Creating new version profile..." + profile.install.getTarget() + ".json");
FileUtils.write(new File(to, profile.install.getTarget() + ".json"), C.GSON.toJson(profile.versionInfo));
HMCLog.log("Extracting universal forge pack..." + profile.install.getFilePath());
entry = zipFile.getEntry(profile.install.getFilePath());
InputStream is = zipFile.getInputStream(entry);
MinecraftLibrary forge = new MinecraftLibrary(profile.install.getPath());
forge.init();
File file = new File(gameDir, "libraries/" + forge.formatted);
if (file.getParentFile().mkdirs())
HMCLog.warn("Failed to make library directory " + file.getParent());
try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int c;
while ((c = is.read()) != -1)
bos.write((byte) c);
}
mp.version().refreshVersions();
}
mp.version().refreshVersions();
}
@Override

View File

@ -23,13 +23,102 @@ package org.jackhuang.hellominecraft.launcher.core.install.forge;
*/
public class Install {
public String profileName;
public String target;
public String path;
public String version;
public String filePath;
public String welcome;
public String minecraft;
public String mirrorList;
public String logo;
private String profileName;
private String target;
private String path;
private String version;
private String filePath;
private String welcome;
private String minecraft;
private String mirrorList;
private String logo;
public Install() {
}
public Install(String profileName, String target, String path, String version, String filePath, String welcome, String minecraft, String mirrorList, String logo) {
this();
this.profileName = profileName;
this.target = target;
this.path = path;
this.version = version;
this.filePath = filePath;
this.welcome = welcome;
this.minecraft = minecraft;
this.mirrorList = mirrorList;
this.logo = logo;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getWelcome() {
return welcome;
}
public void setWelcome(String welcome) {
this.welcome = welcome;
}
public String getMinecraft() {
return minecraft;
}
public void setMinecraft(String minecraft) {
this.minecraft = minecraft;
}
public String getMirrorList() {
return mirrorList;
}
public void setMirrorList(String mirrorList) {
this.mirrorList = mirrorList;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
}

View File

@ -27,4 +27,65 @@ public class MinecraftForgeVersion {
public int build;
public double modified;
public String[][] files;
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getMCVersion() {
return mcversion;
}
public void setMCVersion(String mcversion) {
this.mcversion = mcversion;
}
public String getJobver() {
return jobver;
}
public void setJobver(String jobver) {
this.jobver = jobver;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getBuild() {
return build;
}
public void setBuild(int build) {
this.build = build;
}
public double getModified() {
return modified;
}
public void setModified(double modified) {
this.modified = modified;
}
public MinecraftForgeVersion() {
}
public MinecraftForgeVersion(String branch, String mcversion, String jobver, String version, int build, double modified) {
this.branch = branch;
this.mcversion = mcversion;
this.jobver = jobver;
this.version = version;
this.build = build;
this.modified = modified;
}
}

View File

@ -35,7 +35,7 @@ import org.jackhuang.hellominecraft.util.NetUtils;
*/
public class MinecraftForgeVersionList extends InstallerVersionList {
private static MinecraftForgeVersionList instance;
private static volatile MinecraftForgeVersionList instance;
public static MinecraftForgeVersionList getInstance() {
if (instance == null)
@ -81,6 +81,8 @@ public class MinecraftForgeVersionList extends InstallerVersionList {
case "changelog":
iv.changelog = url;
break;
default:
break;
}
}
if (StrUtils.isBlank(iv.installer) || StrUtils.isBlank(iv.universal))

View File

@ -75,7 +75,8 @@ public class LiteLoaderInstaller extends Task implements PreviousResultRegistrar
mv.mainClass = "net.minecraft.launchwrapper.Launch";
mv.minecraftArguments += " --tweakClass " + version.tweakClass;
File folder = new File(service.baseDirectory(), "versions/" + mv.id);
folder.mkdirs();
if (!folder.exists() && folder.mkdirs())
HMCLog.warn("Failed to create new liteloader version " + folder);
File json = new File(folder, mv.id + ".json");
HMCLog.log("Creating new version profile..." + mv.id + ".json");
FileUtils.write(json, C.GSON.toJson(mv));

View File

@ -110,6 +110,7 @@ public class LiteLoaderVersionList extends InstallerVersionList {
public LiteLoaderInstallerVersion(String selfVersion, String mcVersion) {
super(selfVersion, mcVersion);
}
}
}

View File

@ -23,5 +23,39 @@ package org.jackhuang.hellominecraft.launcher.core.install.liteloader;
*/
public class LiteLoaderVersionsMeta {
public String description, authors, url;
private String description, authors, url;
public LiteLoaderVersionsMeta() {
}
public LiteLoaderVersionsMeta(String description, String authors, String url) {
this();
this.description = description;
this.authors = authors;
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

View File

@ -29,6 +29,7 @@ import org.jackhuang.hellominecraft.util.tasks.communication.PreviousResultRegis
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.launcher.core.version.MinecraftLibrary;
import org.jackhuang.hellominecraft.launcher.core.version.MinecraftVersion;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
/**
*
@ -65,15 +66,18 @@ public class OptiFineInstaller extends Task implements PreviousResultRegistrar<F
FileUtils.copyFile(installer, new File(service.baseDirectory(), "libraries/optifine/OptiFine/" + selfId + "/OptiFine-" + selfId + ".jar"));
mv.id += "-" + selfId;
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"));
try (ZipFile zipFile = new ZipFile(installer)) {
if (zipFile.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";
}
mv.minecraftArguments += " --tweakClass optifine.OptiFineTweaker";
}
File loc = new File(service.baseDirectory(), "versions/" + mv.id);
loc.mkdirs();
if (!loc.exists() && loc.mkdirs())
HMCLog.warn("Failed to make directories: " + loc);
File json = new File(loc, mv.id + ".json");
FileUtils.writeStringToFile(json, C.GSON.toJson(mv, MinecraftVersion.class));

View File

@ -23,5 +23,45 @@ package org.jackhuang.hellominecraft.launcher.core.install.optifine;
*/
public class OptiFineVersion {
public String dl, ver, date, mirror, mcver;
private String dl, ver, date, mirror, mcver;
public String getDownloadLink() {
return dl;
}
public void setDownloadLink(String dl) {
this.dl = dl;
}
public String getVersion() {
return ver;
}
public void setVersion(String ver) {
this.ver = ver;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMirror() {
return mirror;
}
public void setMirror(String mirror) {
this.mirror = mirror;
}
public String getMCVersion() {
return mcver;
}
public void setMCVersion(String mcver) {
this.mcver = mcver;
}
}

View File

@ -65,19 +65,19 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
return;
root = C.GSON.fromJson(s, TYPE);
for (OptiFineVersion v : root) {
v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/");
v.setMirror(v.getMirror().replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"));
if (StrUtils.isBlank(v.mcver)) {
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*) HD");
Matcher m = p.matcher(v.ver);
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.mcver = m.group(1);
v.setMCVersion(m.group(1));
}
InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver));
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
List<InstallerVersion> al = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver));
String url = "http://bmclapi.bangbang93.com/optifine/" + iv.selfVersion.replace(" ", "%20");
iv.installer = iv.universal = v.mirror;
List<InstallerVersion> al = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
//String url = "http://bmclapi.bangbang93.com/optifine/" + iv.selfVersion.replace(" ", "%20");
iv.installer = iv.universal = v.getMirror();
al.add(iv);
versions.add(iv);
}

View File

@ -71,7 +71,7 @@ public class OptiFineVersionList extends InstallerVersionList {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(content.getBytes()));
Document doc = db.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));
Element r = doc.getDocumentElement();
NodeList tables = r.getElementsByTagName("table");
for (int i = 0; i < tables.getLength(); i++) {
@ -84,26 +84,26 @@ public class OptiFineVersionList extends InstallerVersionList {
for (int j = 0; j < downloadLine.getLength(); j++) {
Element td = (Element) downloadLine.item(j);
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineMirror"))
v.mirror = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
v.setMirror(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDownload"))
v.dl = ((Element) td.getElementsByTagName("a").item(0)).getAttribute("href");
v.setDownloadLink(((Element) td.getElementsByTagName("a").item(0)).getAttribute("href"));
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineDate"))
v.date = td.getTextContent();
v.setDate(td.getTextContent());
if (StrUtils.startsWith(td.getAttribute("class"), "downloadLineFile"))
v.ver = td.getTextContent();
v.setVersion(td.getTextContent());
}
if (StrUtils.isBlank(v.mcver)) {
if (StrUtils.isBlank(v.getMCVersion())) {
Pattern p = Pattern.compile("OptiFine (.*?) ");
Matcher m = p.matcher(v.ver);
Matcher m = p.matcher(v.getVersion());
while (m.find())
v.mcver = StrUtils.formatVersion(m.group(1));
v.setMCVersion(StrUtils.formatVersion(m.group(1)));
}
InstallerVersion iv = new InstallerVersion(v.ver, StrUtils.formatVersion(v.mcver));
iv.installer = iv.universal = v.mirror;
InstallerVersion iv = new InstallerVersion(v.getVersion(), StrUtils.formatVersion(v.getMCVersion()));
iv.installer = iv.universal = v.getMirror();
root.add(v);
versions.add(iv);
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.mcver));
List<InstallerVersion> ivl = ArrayUtils.tryGetMapWithList(versionMap, StrUtils.formatVersion(v.getMCVersion()));
ivl.add(iv);
}
}

View File

@ -57,9 +57,9 @@ public class DefaultGameLauncher extends GameLauncher {
for (int i = 0; i < value.decompressFiles.length; i++)
try {
String[] rules = value.extractRules[i];
Compressor.unzip(value.decompressFiles[i], value.decompressTo, t -> !StrUtils.startsWithOne(rules, t), false);
Compressor.unzip(value.decompressFiles[i], value.getDecompressTo(), t -> !StrUtils.startsWithOne(rules, t), false);
} 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.getDecompressTo(), ex);
}
return true;
});

View File

@ -84,7 +84,7 @@ public class GameLauncher {
result = login.loginBySettings();
if (result == null)
throw new AuthenticationException("Result can not be null.");
PluginManager.NOW_PLUGIN.onProcessingLoginResult(result);
PluginManager.plugin().onProcessingLoginResult(result);
loader = service.launch(options, result);
@ -150,8 +150,8 @@ public class GameLauncher {
service.version().onLaunch();
boolean isWin = OS.os() == OS.WINDOWS;
File f = new File(launcherName + (isWin ? ".bat" : ".sh"));
if (!f.exists())
f.createNewFile();
if (!f.exists() && !f.createNewFile())
HMCLog.warn("Failed to create " + f);
BufferedWriter writer;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), System.getProperty("sun.jnu.encoding", "UTF-8")));

View File

@ -32,7 +32,6 @@ import org.jackhuang.hellominecraft.util.system.IOUtils;
import org.jackhuang.hellominecraft.launcher.core.asset.AssetsIndex;
import org.jackhuang.hellominecraft.launcher.core.asset.AssetsObject;
import org.jackhuang.hellominecraft.launcher.core.asset.IAssetsHandler;
import org.jackhuang.hellominecraft.launcher.core.download.DownloadType;
import org.jackhuang.hellominecraft.util.system.OS;
import org.jackhuang.hellominecraft.launcher.core.version.MinecraftLibrary;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
@ -46,29 +45,25 @@ import org.jackhuang.hellominecraft.util.StrUtils;
*/
public class MinecraftLoader extends AbstractMinecraftLoader {
DownloadType dt;
String text;
public MinecraftLoader(LaunchOptions p, IMinecraftService provider, UserProfileProvider lr) throws GameException {
super(p, provider, p.getLaunchVersion(), lr);
}
@Override
protected void makeSelf(List<String> res) throws GameException {
String library = options.isCanceledWrapper() ? "" : "-cp=";
StringBuilder library = new StringBuilder(options.isCanceledWrapper() ? "" : "-cp=");
for (MinecraftLibrary l : version.libraries) {
l.init();
if (l.allow() && !l.isRequiredToUnzip())
library += l.getFilePath(gameDir).getAbsolutePath() + File.pathSeparator;
library.append(l.getFilePath(gameDir).getAbsolutePath()).append(File.pathSeparator);
}
File f = version.getJar(service.baseDirectory());
if (!f.exists())
throw new GameException("Minecraft jar does not exists");
library += IOUtils.tryGetCanonicalFilePath(f) + File.pathSeparator;
library = library.substring(0, library.length() - File.pathSeparator.length());
library.append(IOUtils.tryGetCanonicalFilePath(f)).append(File.pathSeparator);
if (options.isCanceledWrapper())
res.add("-cp");
res.add(library);
res.add(library.toString().substring(0, library.length() - File.pathSeparator.length()));
String mainClass = version.mainClass;
res.add((options.isCanceledWrapper() ? "" : "-mainClass=") + mainClass);

View File

@ -59,19 +59,14 @@ public class MinecraftModService extends IMinecraftModService {
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()) {
if (ModInfo.isFileMod(f))
mods.add(ModInfo.readModInfo(f));
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);
}
if (ModInfo.isFileMod(ff))
mods.add(ModInfo.readModInfo(ff));
}
Collections.sort(mods);
modCache.put(id, mods);
@ -84,9 +79,8 @@ public class MinecraftModService extends IMinecraftModService {
if (!ModInfo.isFileMod(f))
return false;
File modsFolder = service.version().getRunDirectory(id, "mods");
if (modsFolder == null)
return false;
modsFolder.mkdirs();
if (!modsFolder.exists() && !modsFolder.mkdirs())
HMCLog.warn("Failed to make directories: " + modsFolder);
File newf = new File(modsFolder, f.getName());
FileUtils.copyFile(f, newf);
ModInfo i = ModInfo.readModInfo(f);
@ -103,10 +97,12 @@ public class MinecraftModService extends IMinecraftModService {
if (rows.length == 0)
return;
for (Object r : rows)
if (r instanceof ModInfo)
((ModInfo) r).location.delete();
else if (r instanceof Number)
getMods(id).get(((Number) r).intValue()).location.delete();
if (r instanceof ModInfo) {
if (!((ModInfo) r).location.delete())
HMCLog.warn("Failed to delete mod" + r);
} else if (r instanceof Number)
if (!getMods(id).get(((Number) r).intValue()).location.delete())
HMCLog.warn("Failed to delete mod " + r + ", maybe not a file?");
recacheMods(id);
}

View File

@ -72,17 +72,22 @@ public final class ModpackManager {
if (newFile.isDirectory())
FileUtils.deleteDirectory(newFile);
else if (newFile.isFile())
newFile.delete();
oldFile.renameTo(newFile);
if (!newFile.delete())
HMCLog.warn("Failed to delete file " + newFile);
if (!oldFile.renameTo(newFile))
HMCLog.warn("Failed to rename " + oldFile + " to " + newFile);
}
File preVersion = new File(versions, id), preVersionRenamed = null;
if (preVersion.exists()) {
HMCLog.log("Backing up the game");
String preId = id + "-" + System.currentTimeMillis();
preVersion.renameTo(preVersionRenamed = new File(versions, preId));
new File(preVersionRenamed, id + ".json").renameTo(new File(preVersionRenamed, preId + ".json"));
new File(preVersionRenamed, id + ".jar").renameTo(new File(preVersionRenamed, preId + ".jar"));
if (!preVersion.renameTo(preVersionRenamed = new File(versions, preId)))
HMCLog.warn("Failed to rename pre-version folder " + preVersion + " to a temp folder " + preVersionRenamed);
if (!new File(preVersionRenamed, id + ".json").renameTo(new File(preVersionRenamed, preId + ".json")))
HMCLog.warn("Failed to rename pre json to new json");
if (!new File(preVersionRenamed, id + ".jar").renameTo(new File(preVersionRenamed, preId + ".jar")))
HMCLog.warn("Failed to rename pre jar to new jar");
}
try {
@ -96,7 +101,8 @@ public final class ModpackManager {
if (b.get() < 1)
throw new FileNotFoundException(C.i18n("modpack.incorrect_format.no_json"));
File nowFile = new File(versions, id);
oldFile.renameTo(nowFile);
if (oldFile.exists() && !oldFile.renameTo(nowFile))
HMCLog.warn("Failed to rename incorrect json " + oldFile + " to " + nowFile);
File json = new File(nowFile, "pack.json");
MinecraftVersion mv = C.GSON.fromJson(FileUtils.readFileToString(json), MinecraftVersion.class);
@ -106,7 +112,8 @@ public final class ModpackManager {
c.add(service.download().downloadMinecraftJarTo(mv.jar, new File(nowFile, id + ".jar")));
mv.jar = null;
FileUtils.writeStringToFile(json, C.GSON.toJson(mv));
json.renameTo(new File(nowFile, id + ".json"));
if (!json.renameTo(new File(nowFile, id + ".json")))
HMCLog.warn("Failed to rename pack.json to new id");
if (preVersionRenamed != null) {
HMCLog.log("Restoring saves");

View File

@ -27,11 +27,19 @@ public class DecompressLibraryJob {
public File[] decompressFiles;
public String[][] extractRules;
public File decompressTo;
private File decompressTo;
public DecompressLibraryJob(File[] decompressFiles, String[][] extractRules, File decompressTo) {
this.decompressFiles = decompressFiles;
this.extractRules = extractRules;
this.decompressFiles = decompressFiles.clone();
this.extractRules = extractRules.clone();
this.decompressTo = decompressTo;
}
public File getDecompressTo() {
return decompressTo;
}
public void setDecompressTo(File decompressTo) {
this.decompressTo = decompressTo;
}

View File

@ -17,21 +17,30 @@
*/
package org.jackhuang.hellominecraft.launcher.core.version;
import java.util.Arrays;
/**
*
* @author huangyuhui
*/
public class Extract extends Object implements Cloneable {
public class Extract implements Cloneable {
String[] exclude;
public String[] exclude;
public Extract(String[] exclude) {
this();
this.exclude = exclude.clone();
}
public Extract() {
}
@Override
protected Object clone() {
Extract e = new Extract();
e.exclude = exclude == null ? null : Arrays.copyOf(exclude, exclude.length);
return e;
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
throw new InternalError(ex);
}
}
}

View File

@ -59,7 +59,12 @@ public abstract class IMinecraftLibrary implements Cloneable {
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
throw new InternalError(ex);
}
}
}

View File

@ -19,7 +19,6 @@ package org.jackhuang.hellominecraft.launcher.core.version;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.jackhuang.hellominecraft.launcher.core.download.DownloadType;
import org.jackhuang.hellominecraft.util.system.OS;
import org.jackhuang.hellominecraft.util.system.Platform;
@ -33,8 +32,6 @@ public class MinecraftLibrary extends IMinecraftLibrary {
public ArrayList<Rules> rules;
public String url, formatted = null;
//public boolean serverreq=true, clientreq=true;
public String[] checksums;
public Natives natives;
public Extract extract;
@ -42,17 +39,16 @@ public class MinecraftLibrary extends IMinecraftLibrary {
super(name);
}
public MinecraftLibrary(ArrayList<Rules> rules, String url, String[] checksums, Natives natives, String name, Extract extract) {
public MinecraftLibrary(ArrayList<Rules> rules, String url, Natives natives, String name, Extract extract) {
super(name);
this.rules = rules == null ? null : (ArrayList<Rules>) rules.clone();
this.url = url;
this.checksums = checksums == null ? null : Arrays.copyOf(checksums, checksums.length);
this.natives = natives == null ? null : (Natives) natives.clone();
this.extract = extract == null ? null : (Extract) extract.clone();
}
@Override
public Object clone() throws CloneNotSupportedException {
public Object clone() {
MinecraftLibrary ml = (MinecraftLibrary) super.clone();
ml.extract = (Extract) ml.extract.clone();
ml.natives = (Natives) ml.natives.clone();
@ -72,12 +68,12 @@ public class MinecraftLibrary extends IMinecraftLibrary {
flag = true;
else
for (Rules r : rules)
if (r.action.equals("disallow")) {
if (r.os != null && (StrUtils.isBlank(r.os.getName()) || r.os.getName().equalsIgnoreCase(OS.os().toString()))) {
if ("disallow".equals(r.getAction())) {
if (r.getOS() != null && (StrUtils.isBlank(r.getOS().getName()) || r.getOS().getName().equalsIgnoreCase(OS.os().toString()))) {
flag = false;
break;
}
} else if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.getName()) || r.os.getName().equalsIgnoreCase(OS.os().toString()))))
} else if (r.getOS() == null || (r.getOS() != null && (StrUtils.isBlank(r.getOS().getName()) || r.getOS().getName().equalsIgnoreCase(OS.os().toString()))))
flag = true;
return flag;
}
@ -89,11 +85,11 @@ public class MinecraftLibrary extends IMinecraftLibrary {
private String getNative() {
switch (OS.os()) {
case WINDOWS:
return formatArch(natives.windows);
return formatArch(natives.getWindows());
case OSX:
return formatArch(natives.osx);
return formatArch(natives.getOsx());
default:
return formatArch(natives.linux);
return formatArch(natives.getLinux());
}
}

View File

@ -51,7 +51,7 @@ public class MinecraftOldLibrary extends MinecraftLibrary {
@Override
public Object clone() {
return new MinecraftOldLibrary(name);
return super.clone();
}
@Override

View File

@ -39,7 +39,7 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
public int minimumLauncherVersion;
public boolean hidden;
public List<MinecraftLibrary> libraries;
public ArrayList<MinecraftLibrary> libraries;
public MinecraftVersion() {
}
@ -70,7 +70,13 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
@Override
public Object clone() {
return new MinecraftVersion(minecraftArguments, mainClass, time, id, type, processArguments, releaseTime, assets, jar, inheritsFrom, runDir, minimumLauncherVersion, libraries, hidden);
try {
MinecraftVersion mv = (MinecraftVersion) super.clone();
mv.libraries = (ArrayList<MinecraftLibrary>) mv.libraries.clone();
return mv;
} catch (CloneNotSupportedException ex) {
throw new InternalError();
}
}
public MinecraftVersion resolve(IMinecraftProvider provider) throws GameException {
@ -127,6 +133,6 @@ public class MinecraftVersion implements Cloneable, Comparable<MinecraftVersion>
@Override
public int compareTo(MinecraftVersion o) {
return id.compareTo(((MinecraftVersion) o).id);
return id.compareTo(o.id);
}
}

View File

@ -104,7 +104,8 @@ public class MinecraftVersionManager extends IMinecraftProvider {
if (ask) {
HMCLog.warn("Found not matched filenames version: " + id + ", json: " + jsons[0].getName());
if (MessageBox.Show(String.format(C.i18n("launcher.versions_json_not_matched"), id, jsons[0].getName()), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
jsons[0].renameTo(new File(jsons[0].getParent(), id + ".json"));
if (!jsons[0].renameTo(new File(jsons[0].getParent(), id + ".json")))
HMCLog.warn("Failed to rename version json " + jsons[0]);
}
if (!jsonFile.exists()) {
if (MessageBox.Show(C.i18n("launcher.versions_json_not_matched_cannot_auto_completion", id), MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION)
@ -173,13 +174,15 @@ public class MinecraftVersionManager extends IMinecraftProvider {
mcVersion.id = to;
FileUtils.writeQuietly(fromJson, C.GSON.toJson(mcVersion));
File toDir = versionRoot(to);
versionRoot(from).renameTo(toDir);
if (!versionRoot(from).renameTo(toDir))
HMCLog.warn("MinecraftVersionManager.RenameVersion: Failed to rename version root " + from + " to " + to);
File toJson = new File(toDir, to + ".json");
File toJar = new File(toDir, to + ".jar");
new File(toDir, from + ".json").renameTo(toJson);
if (new File(toDir, from + ".json").renameTo(toJson))
HMCLog.warn("MinecraftVersionManager.RenameVersion: Failed to rename json");
File newJar = new File(toDir, from + ".jar");
if (newJar.exists())
newJar.renameTo(toJar);
if (newJar.exists() && !newJar.renameTo(toJar))
HMCLog.warn("Failed to rename pre jar " + newJar + " to new jar " + toJar);
return true;
} catch (IOException | JsonSyntaxException e) {
HMCLog.warn("Failed to rename " + from + " to " + to + ", the json of this Minecraft is malformed.", e);
@ -227,7 +230,7 @@ public class MinecraftVersionManager extends IMinecraftProvider {
extractRules.add(l.getDecompressExtractRules());
}
}
return new DecompressLibraryJob(unzippings.toArray(new File[0]), extractRules.toArray(new String[0][]), getDecompressNativesToLocation(v));
return new DecompressLibraryJob(unzippings.toArray(new File[unzippings.size()]), extractRules.toArray(new String[extractRules.size()][]), getDecompressNativesToLocation(v));
}
@Override
@ -261,8 +264,8 @@ public class MinecraftVersionManager extends IMinecraftProvider {
@Override
public boolean onLaunch() {
File resourcePacks = getResourcePacks();
if (!resourcePacks.exists())
resourcePacks.mkdirs();
if (!resourcePacks.exists() && !resourcePacks.mkdirs())
HMCLog.warn("Failed to make resourcePacks: " + resourcePacks);
return true;
}
@ -276,7 +279,8 @@ public class MinecraftVersionManager extends IMinecraftProvider {
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();
if (!new File(f, str).delete())
HMCLog.warn("Failed to delete " + str);
}
}
@ -285,7 +289,7 @@ public class MinecraftVersionManager extends IMinecraftProvider {
}
private void downloadModpack(String url) throws IOException {
public void downloadModpack(String url) throws IOException {
File tmp = File.createTempFile("hmcl", ".zip");
TaskWindow.getInstance().addTask(new FileDownloadTask(url, tmp)).addTask(new DecompressTask(tmp, service.baseDirectory())).start();
}

View File

@ -23,10 +23,39 @@ package org.jackhuang.hellominecraft.launcher.core.version;
*/
public class Natives implements Cloneable {
public String windows, osx, linux;
private String windows, osx, linux;
public String getWindows() {
return windows;
}
public void setWindows(String windows) {
this.windows = windows;
}
public String getOsx() {
return osx;
}
public void setOsx(String osx) {
this.osx = osx;
}
public String getLinux() {
return linux;
}
public void setLinux(String linux) {
this.linux = linux;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
@SuppressWarnings("CloneDeclaresCloneNotSupported")
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
throw new InternalError(ex);
}
}
}

View File

@ -23,6 +23,32 @@ package org.jackhuang.hellominecraft.launcher.core.version;
*/
public class Rules {
public String action;
public OS os;
private String action;
private OS os;
public Rules() {
}
public Rules(String action, OS os) {
this();
this.action = action;
this.os = os;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public OS getOS() {
return os;
}
public void setOS(OS os) {
this.os = os;
}
}

View File

@ -177,6 +177,7 @@ public final class Config {
@SerializedName("configurations")
private TreeMap<String, Profile> configurations;
@SerializedName("auth")
@SuppressWarnings("FieldMayBeFinal")
private Map<String, Map> auth;
public Config() {

View File

@ -44,7 +44,6 @@ import org.jackhuang.hellominecraft.util.system.FileUtils;
*/
public class DefaultMinecraftService extends IMinecraftService {
File base;
Profile p;
final Map<String, VersionSetting> versionSettings = new HashMap<>();

View File

@ -35,9 +35,9 @@ import org.jackhuang.hellominecraft.util.func.Consumer;
*/
public class DefaultPlugin implements IPlugin {
protected static YggdrasilAuthenticator YGGDRASIL_LOGIN;
protected static OfflineAuthenticator OFFLINE_LOGIN;
protected static SkinmeAuthenticator SKINME_LOGIN;
YggdrasilAuthenticator YGGDRASIL_LOGIN = null;
OfflineAuthenticator OFFLINE_LOGIN = null;
SkinmeAuthenticator SKINME_LOGIN = null;
@Override
public IMinecraftService provideMinecraftService(Profile profile) {

View File

@ -62,14 +62,14 @@ public class HMCLGameLauncher {
}
final IAuthenticator l = IAuthenticator.LOGINS.get(Settings.getInstance().getLoginType());
final LoginInfo li = new LoginInfo(l.getUsername(), l.isLoggedIn() || !l.hasPassword() ? null : passwordIfNeeded);
final LoginInfo li = new LoginInfo(l.getUserName(), l.isLoggedIn() || !l.hasPassword() ? null : passwordIfNeeded);
new Thread() {
@Override
public void run() {
Thread.currentThread().setName("Game Launcher");
try {
LaunchOptions options = profile.getSelectedVersionSetting().createLaunchOptions(profile.getCanonicalGameDirFile());
PluginManager.NOW_PLUGIN.onProcessingLaunchOptions(options);
PluginManager.plugin().onProcessingLaunchOptions(options);
DefaultGameLauncher gl = new DefaultGameLauncher(options, profile.service(), li, l);
gl.setTag(profile.getSelectedVersionSetting().getLauncherVisibility());
gl.successEvent.register(() -> isLaunching = false);

View File

@ -57,7 +57,7 @@ public final class Profile {
public IMinecraftService service() {
if (service == null)
service = PluginManager.NOW_PLUGIN.provideMinecraftService(this);
service = PluginManager.plugin().provideMinecraftService(this);
return service;
}

View File

@ -60,6 +60,10 @@ public class AnimatedPanel extends JPanel implements Selectable {
@Override
public void paint(Graphics g) {
if (!(g instanceof Graphics2D)) {
super.paint(g);
return;
}
double pgs = 1 - Math.sin(Math.PI / 2 / ANIMATION_LENGTH * offsetX);
if (Math.abs(ANIMATION_LENGTH - offsetX) < 0.1) {
super.paint(g);

View File

@ -27,7 +27,7 @@ import org.jackhuang.hellominecraft.util.ui.SwingUtils;
*
* @author huangyuhui
*/
public class GameDownloadPanel extends AnimatedPanel implements Selectable {
public class GameDownloadPanel extends AnimatedPanel {
GameSettingsPanel gsp;

View File

@ -1294,22 +1294,27 @@ public final class GameSettingsPanel extends AnimatedPanel implements DropTarget
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Mods">
private boolean reloadingMods = false;
private final Object modLock = new Object();
private synchronized void reloadMods() {
if (reloadingMods)
return;
reloadingMods = true;
DefaultTableModel model = SwingUtils.clearDefaultTable(lstExternalMods);
new OverridableSwingWorker<List<ModInfo>>() {
@Override
protected void work() throws Exception {
publish(getProfile().service().mod().recacheMods(getProfile().getSelectedVersion()));
}
}.reg(t -> {
for (ModInfo x : t)
model.addRow(new Object[] { x.isActive(), x, x.version });
reloadingMods = false;
}).execute();
private void reloadMods() {
synchronized (modLock) {
if (reloadingMods)
return;
reloadingMods = true;
DefaultTableModel model = SwingUtils.clearDefaultTable(lstExternalMods);
new OverridableSwingWorker<List<ModInfo>>() {
@Override
protected void work() throws Exception {
publish(getProfile().service().mod().recacheMods(getProfile().getSelectedVersion()));
}
}.reg(t -> {
synchronized (modLock) {
for (ModInfo x : t)
model.addRow(new Object[] { x.isActive(), x, x.version });
reloadingMods = false;
}
}).execute();
}
}
// </editor-fold>

View File

@ -36,7 +36,7 @@ import org.jackhuang.hellominecraft.util.ui.SwingUtils;
*
* @author huangyuhui
*/
public class InstallerPanel extends AnimatedPanel implements Selectable {
public class InstallerPanel extends AnimatedPanel {
GameSettingsPanel gsp;
@ -118,8 +118,8 @@ public class InstallerPanel extends AnimatedPanel implements Selectable {
refreshVersions();
}//GEN-LAST:event_btnRefreshActionPerformed
List<InstallerVersionList.InstallerVersion> versions;
InstallerVersionList list;
transient List<InstallerVersionList.InstallerVersion> versions;
transient InstallerVersionList list;
InstallerType id;
void refreshVersions() {
@ -129,11 +129,11 @@ public class InstallerPanel extends AnimatedPanel implements Selectable {
loadVersions();
}
public InstallerVersionList.InstallerVersion getVersion(int idx) {
public synchronized InstallerVersionList.InstallerVersion getVersion(int idx) {
return versions.get(idx);
}
void downloadSelectedRow() {
synchronized void downloadSelectedRow() {
int idx = lstInstallers.getSelectedRow();
if (versions == null || idx < 0 || idx >= versions.size()) {
MessageBox.Show(C.i18n("install.not_refreshed"));

View File

@ -237,29 +237,7 @@ public final class MainFrame extends DraggableFrame {
windowTitle = new JLabel(defaultTitle);
windowTitle.setForeground(BasicColors.COLOR_WHITE_TEXT);
windowTitle.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
Settings.UPDATE_CHECKER.checkOutdate();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
windowTitle.addMouseListener(MouseListenerImpl.INSTANCE);
header.add(windowTitle);
header.add(Box.createHorizontalGlue());
header.add(rightHeaderPanel);
@ -388,7 +366,7 @@ public final class MainFrame extends DraggableFrame {
public static void showMainFrame() {
IAuthenticator l = Settings.getInstance().getAuthenticator();
if (StrUtils.isBlank(l.getUsername()))
if (StrUtils.isBlank(l.getUserName()))
SwingUtilities.invokeLater(() -> MainFrame.INSTANCE.showMessage(C.i18n("ui.message.first_load")));
if (l.hasPassword() && !l.isLoggedIn())
SwingUtilities.invokeLater(() -> MainFrame.INSTANCE.showMessage(C.i18n("ui.message.enter_password")));
@ -454,4 +432,30 @@ public final class MainFrame extends DraggableFrame {
}
}
private static class MouseListenerImpl implements MouseListener {
public static final MouseListenerImpl INSTANCE = new MouseListenerImpl();
@Override
public void mouseClicked(MouseEvent e) {
Settings.UPDATE_CHECKER.checkOutdate();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
}

View File

@ -302,7 +302,7 @@ public class MainPagePanel extends AnimatedPanel {
private void txtPlayerNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPlayerNameFocusLost
IAuthenticator l = Settings.getInstance().getAuthenticator();
l.setUsername(txtPlayerName.getText());
l.setUserName(txtPlayerName.getText());
}//GEN-LAST:event_txtPlayerNameFocusLost
private void cboLoginModeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboLoginModeItemStateChanged
@ -342,7 +342,7 @@ public class MainPagePanel extends AnimatedPanel {
IAuthenticator l = Settings.getInstance().getAuthenticator();
CardLayout cl = (CardLayout) pnlPassword.getLayout();
if (l.isLoggedIn())
l.logout();
l.logOut();
cl.first(pnlPassword);
pnlPassword.repaint();
}//GEN-LAST:event_btnLogoutActionPerformed
@ -350,7 +350,7 @@ public class MainPagePanel extends AnimatedPanel {
private void txtPlayerNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPlayerNameKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
IAuthenticator l = Settings.getInstance().getAuthenticator();
l.setUsername(txtPlayerName.getText());
l.setUserName(txtPlayerName.getText());
if (!l.hasPassword())
runGame();
else if (!l.isLoggedIn())
@ -583,7 +583,7 @@ public class MainPagePanel extends AnimatedPanel {
cl.last(pnlPassword);
else
cl.first(pnlPassword);
String username = l.getUsername();
String username = l.getUserName();
if (username == null)
username = "";
txtPlayerName.setText(username);

View File

@ -35,9 +35,9 @@ import org.jackhuang.hellominecraft.util.ui.wizard.spi.WizardController;
*/
public class ModpackFileSelectionPanel extends javax.swing.JPanel {
private final WizardController controller;
private transient final WizardController controller;
private final Map wizardData;
private final BiFunction<String, Boolean, Integer> blackList;
private transient final BiFunction<String, Boolean, Integer> blackList;
private final Set<String> bannedFiles = new HashSet<>();
/**

View File

@ -33,7 +33,7 @@ public class ModpackInitializationPanel extends javax.swing.JPanel {
public static final String KEY_GAME_VERSION = "gameVersion";
public static final String KEY_MODPACK_LOCATION = "modpackLocation";
private final WizardController controller;
private final transient WizardController controller;
private final Map wizardData;
/**

View File

@ -22,6 +22,9 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
@ -39,6 +42,8 @@ import org.jackhuang.hellominecraft.util.ui.LogWindow;
*/
public class CrashReporter implements Thread.UncaughtExceptionHandler {
private static final Logger LOGGER = LogManager.getLogManager().getLogger(CrashReporter.class.getName());
boolean enableLogger = false;
public CrashReporter(boolean enableLogger) {
@ -50,35 +55,35 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
if (s.contains("MessageBox") || s.contains("AWTError"))
return false;
else if (s.contains("JFileChooser") || s.contains("JceSecurityManager")) {
System.out.println("Is not your operating system installed completely? ");
LOGGER.severe("Is not your operating system installed completely? ");
return false;
}
if (s.contains("sun.awt.shell.Win32ShellFolder2") || s.contains("UnsatisfiedLinkError")) {
System.out.println(C.i18n("crash.user_fault"));
LOGGER.severe(C.i18n("crash.user_fault"));
try {
showMessage(C.i18n("crash.user_fault"));
} catch (Throwable t) {
t.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to show message", t);
}
return false;
} else if (s.contains("java.awt.HeadlessException")) {
System.out.println(C.i18n("crash.headless"));
LOGGER.severe(C.i18n("crash.headless"));
try {
showMessage(C.i18n("crash.headless"));
} catch (Throwable t) {
t.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to show message", t);
}
return false;
} else if (s.contains("java.lang.NoClassDefFoundError") || s.contains("java.lang.VerifyError") || s.contains("java.lang.NoSuchMethodError") || s.contains("java.lang.IncompatibleClassChangeError") || s.contains("java.lang.ClassFormatError")) {
System.out.println(C.i18n("crash.NoClassDefFound"));
LOGGER.severe(C.i18n("crash.NoClassDefFound"));
try {
showMessage(C.i18n("crash.NoClassDefFound"));
} catch (Throwable t) {
t.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to show message", t);
}
return false;
} else if (s.contains("java.lang.OutOfMemoryError")) {
System.out.println("FUCKING MEMORY LIMIT!");
LOGGER.severe("FUCKING MEMORY LIMIT!");
return false;
}
return true;
@ -111,8 +116,8 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
reportToServer(text, s);
}
} catch (Throwable ex) {
showMessage(e.getMessage() + "\n" + ex.getMessage());
ex.printStackTrace();
LOGGER.log(Level.SEVERE, "Failed to caught exception", ex);
LOGGER.log(Level.SEVERE, "There is the original exception", e);
}
}
@ -120,8 +125,7 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
try {
MessageBox.Show(s, "ERROR", MessageBox.ERROR_MESSAGE);
} catch (Throwable e) {
System.err.println("ERROR: " + s);
e.printStackTrace();
LOGGER.log(Level.SEVERE, "ERROR", e);
}
}
@ -131,19 +135,15 @@ public class CrashReporter implements Thread.UncaughtExceptionHandler {
if (THROWABLE_SET.contains(stacktrace))
return;
THROWABLE_SET.add(stacktrace);
new Thread() {
@Override
public void run() {
HashMap<String, String> map = new HashMap<>();
map.put("CrashReport", text);
try {
System.out.println(NetUtils.post(NetUtils.constantURL("http://huangyuhui.duapp.com/crash.php"), map));
} catch (IOException ex) {
System.out.println("Failed to send post request to HMCL server.");
ex.printStackTrace();
}
new Thread(() -> {
HashMap<String, String> map = new HashMap<>();
map.put("CrashReport", text);
try {
NetUtils.post(NetUtils.constantURL("http://huangyuhui.duapp.com/crash.php"), map);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Failed to post HMCL server.", ex);
}
}.start();
}).start();
}
}

View File

@ -18,6 +18,7 @@
package org.jackhuang.hellominecraft.launcher.util;
import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.lang.SupportedLocales;
/**
* Give the advice to solve the Minecraft crashing.
@ -31,7 +32,7 @@ public final class MinecraftCrashAdvicer {
}
public static String getAdvice(String trace, boolean selfCrash) {
trace = trace.toLowerCase();
trace = trace.toLowerCase(SupportedLocales.NOW_LOCALE.self);
if (trace.contains("pixel format not accelerated"))
return C.i18n("crash.advice.LWJGLException");
else if (trace.contains("unsupportedclassversionrrror"))

View File

@ -26,7 +26,7 @@ import java.util.ArrayList;
*/
public class ModpackUpdater {
ModpackInfo info;
private ModpackInfo info;
public ModpackUpdater(File baseFolder, ModpackInfo info) {
this.info = info;
@ -36,6 +36,14 @@ public class ModpackUpdater {
}
public ModpackInfo getInfo() {
return info;
}
public void setInfo(ModpackInfo info) {
this.info = info;
}
public static class ModpackInfo {
ArrayList<ModpackFolder> folders;

View File

@ -25,6 +25,8 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -45,7 +47,6 @@ import org.jackhuang.hellominecraft.util.MessageBox;
import org.jackhuang.hellominecraft.util.UpdateChecker;
import org.jackhuang.hellominecraft.util.Utils;
import org.jackhuang.hellominecraft.util.VersionNumber;
import org.jackhuang.hellominecraft.util.func.Consumer;
import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
import org.jackhuang.hellominecraft.util.system.OS;
@ -68,18 +69,21 @@ public class AppDataUpgrader extends IUpgrader {
String j = m.get("loc");
if (j != null) {
File jar = new File(j);
if (jar.exists()) {
JarFile jarFile = new JarFile(jar);
String mainClass = jarFile.getManifest().getMainAttributes().getValue("Main-Class");
if (mainClass != null) {
ArrayList<String> al = new ArrayList<>(Arrays.asList(args));
al.add("notfound");
new URLClassLoader(new URL[] { jar.toURI().toURL() },
URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass)
.getMethod("main", String[].class).invoke(null, new Object[] { al.toArray(new String[0]) });
return true;
if (jar.exists())
try (JarFile jarFile = new JarFile(jar)) {
String mainClass = jarFile.getManifest().getMainAttributes().getValue("Main-Class");
if (mainClass != null) {
ArrayList<String> al = new ArrayList<>(Arrays.asList(args));
al.add("notfound");
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
new URLClassLoader(new URL[] { jar.toURI().toURL() },
URLClassLoader.getSystemClassLoader().getParent()).loadClass(mainClass)
.getMethod("main", String[].class).invoke(null, new Object[] { al.toArray(new String[0]) });
return null;
});
return true;
}
}
}
}
}
}
@ -91,36 +95,33 @@ public class AppDataUpgrader extends IUpgrader {
@Override
public boolean call(Object sender, final VersionNumber number) {
((UpdateChecker) sender).requestDownloadLink().reg(new Consumer<Map<String, String>>() {
@Override
public void accept(Map<String, String> map) {
if (map != null && map.containsKey("pack"))
try {
if (TaskWindow.getInstance().addTask(new AppDataUpgraderTask(map.get("pack"), number.version)).start()) {
new ProcessBuilder(new String[] { IOUtils.getJavaDir(), "-jar", AppDataUpgraderTask.getSelf(number.version).getAbsolutePath() }).directory(new File(".")).start();
System.exit(0);
}
} catch (IOException ex) {
HMCLog.err("Failed to create upgrader", ex);
}
if (MessageBox.Show(C.i18n("update.newest_version") + number.firstVer + "." + number.secondVer + "." + number.thirdVer + "\n"
+ C.i18n("update.should_open_link"),
MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
String url = C.URL_PUBLISH;
if (map != null)
if (map.containsKey(OS.os().checked_name))
url = map.get(OS.os().checked_name);
else if (map.containsKey(OS.UNKOWN.checked_name))
url = map.get(OS.UNKOWN.checked_name);
if (url == null)
url = C.URL_PUBLISH;
try {
java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException | IOException e) {
HMCLog.warn("Failed to browse uri: " + url, e);
Utils.setClipborad(url);
MessageBox.Show(C.i18n("update.no_browser"));
((UpdateChecker) sender).requestDownloadLink().reg(map -> {
if (map != null && map.containsKey("pack"))
try {
if (TaskWindow.getInstance().addTask(new AppDataUpgraderTask(map.get("pack"), number.version)).start()) {
new ProcessBuilder(new String[] { IOUtils.getJavaDir(), "-jar", AppDataUpgraderTask.getSelf(number.version).getAbsolutePath() }).directory(new File(".")).start();
System.exit(0);
}
} catch (IOException ex) {
HMCLog.err("Failed to create upgrader", ex);
}
if (MessageBox.Show(C.i18n("update.newest_version") + number.firstVer + "." + number.secondVer + "." + number.thirdVer + "\n"
+ C.i18n("update.should_open_link"),
MessageBox.YES_NO_OPTION) == MessageBox.YES_OPTION) {
String url = C.URL_PUBLISH;
if (map != null)
if (map.containsKey(OS.os().checked_name))
url = map.get(OS.os().checked_name);
else if (map.containsKey(OS.UNKOWN.checked_name))
url = map.get(OS.UNKOWN.checked_name);
if (url == null)
url = C.URL_PUBLISH;
try {
java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (URISyntaxException | IOException e) {
HMCLog.warn("Failed to browse uri: " + url, e);
Utils.setClipborad(url);
MessageBox.Show(C.i18n("update.no_browser"));
}
}
}).execute();
@ -154,12 +155,13 @@ public class AppDataUpgrader extends IUpgrader {
public void executeTask() throws Exception {
HashMap<String, String> json = new HashMap<>();
File f = getSelf(newestVersion);
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.getParentFile().exists() && !f.getParentFile().mkdirs())
HMCLog.warn("Failed to make directories: " + f.getParent());
for (int i = 0; f.exists(); i++)
f = new File(BASE_FOLDER, "HMCL-" + newestVersion + (i > 0 ? "-" + i : "") + ".jar");
f.createNewFile();
if (!f.createNewFile())
HMCLog.warn("Failed to create new file: " + f);
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(f))) {
Pack200.newUnpacker().unpack(new GZIPInputStream(new FileInputStream(tempFile)), jos);

View File

@ -19,6 +19,7 @@ package org.jackhuang.hellominecraft.util.version;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.jackhuang.hellominecraft.util.C;
@ -29,7 +30,7 @@ import org.jackhuang.hellominecraft.util.NetUtils;
/**
* @author huangyuhui
*/
public class MinecraftVersionRequest {
public class MinecraftVersionRequest implements Serializable {
public static final int UNKOWN = 0, INVALID = 1, INVALID_JAR = 2,
MODIFIED = 3, OK = 4, NOT_FOUND = 5, UNREADABLE = 6, NOT_FILE = 7;