used findbugs

This commit is contained in:
huangyuhui
2016-02-05 13:10:22 +08:00
parent cd972f5945
commit d4dccd1391
39 changed files with 388 additions and 427 deletions

View File

@@ -19,6 +19,7 @@ package org.jackhuang.hellominecraft.launcher;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.PasswordAuthentication; import java.net.PasswordAuthentication;
@@ -89,14 +90,16 @@ public final class Launcher {
}); });
try { try {
File logFile = new File("hmclmc.log"); File logFile = new File("hmclmc.log");
if (!logFile.exists()) if (!logFile.exists() && !logFile.createNewFile())
logFile.createNewFile(); println("Failed to create log file");
FileOutputStream tc = new FileOutputStream(logFile); else {
DoubleOutputStream out = new DoubleOutputStream(tc, System.out); FileOutputStream tc = new FileOutputStream(logFile);
System.setOut(new LauncherPrintStream(out)); DoubleOutputStream out = new DoubleOutputStream(tc, System.out);
DoubleOutputStream err = new DoubleOutputStream(tc, System.err); System.setOut(new LauncherPrintStream(out));
System.setErr(new LauncherPrintStream(err)); DoubleOutputStream err = new DoubleOutputStream(tc, System.err);
} catch (Exception e) { System.setErr(new LauncherPrintStream(err));
}
} catch (IOException e) {
println("Failed to add log file appender."); println("Failed to add log file appender.");
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -22,6 +22,7 @@ import com.google.gson.reflect.TypeToken;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List; import java.util.List;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
@@ -56,7 +57,7 @@ public class ModInfo implements Comparable<ModInfo> {
@Override @Override
public int compareTo(ModInfo o) { public int compareTo(ModInfo o) {
return getFileName().toLowerCase().compareTo(o.getFileName().toLowerCase()); return getFileName().compareToIgnoreCase(o.getFileName());
} }
public String getName() { public String getName() {
@@ -102,12 +103,13 @@ public class ModInfo implements Comparable<ModInfo> {
return name.endsWith(".zip") || name.endsWith(".jar") || name.endsWith("litemod"); return name.endsWith(".zip") || name.endsWith(".jar") || name.endsWith("litemod");
} }
private static final Type TYPE = new TypeToken<List<ModInfo>>() {
}.getType();
private static ModInfo getForgeModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException { private static ModInfo getForgeModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException {
ModInfo i = new ModInfo(); ModInfo i = new ModInfo();
i.location = f; i.location = f;
List<ModInfo> m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), List<ModInfo> m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), TYPE);
new TypeToken<List<ModInfo>>() {
}.getType());
if (m != null && m.size() > 0) { if (m != null && m.size() > 0) {
i = m.get(0); i = m.get(0);
i.location = f; i.location = f;
@@ -116,8 +118,7 @@ public class ModInfo implements Comparable<ModInfo> {
} }
private static ModInfo getLiteLoaderModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException { private static ModInfo getLiteLoaderModInfo(File f, ZipFile jar, ZipEntry entry) throws IOException {
ModInfo m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), ModInfo m = C.GSON.fromJson(new InputStreamReader(jar.getInputStream(entry)), ModInfo.class);
ModInfo.class);
if (m == null) if (m == null)
m = new ModInfo(); m = new ModInfo();
m.location = f; m.location = f;

View File

@@ -29,8 +29,8 @@ import java.util.Set;
public class AssetsIndex { public class AssetsIndex {
public static final String DEFAULT_ASSET_NAME = "legacy"; public static final String DEFAULT_ASSET_NAME = "legacy";
private Map<String, AssetsObject> objects; public Map<String, AssetsObject> objects;
private boolean virtual; public boolean virtual;
public AssetsIndex() { public AssetsIndex() {
this.objects = new LinkedHashMap(); this.objects = new LinkedHashMap();

View File

@@ -97,7 +97,7 @@ public abstract class IAssetsHandler {
@Override @Override
public void executeTask() { public void executeTask() {
if (assetsDownloadURLs == null) if (assetsDownloadURLs == null || assetsLocalNames == null)
throw new IllegalStateException(C.i18n("assets.not_refreshed")); throw new IllegalStateException(C.i18n("assets.not_refreshed"));
int max = assetsDownloadURLs.size(); int max = assetsDownloadURLs.size();
al = new ArrayList<>(); al = new ArrayList<>();

View File

@@ -25,6 +25,7 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import org.jackhuang.hellominecraft.util.StrUtils; import org.jackhuang.hellominecraft.util.StrUtils;
@@ -46,9 +47,16 @@ public class GameProfile {
return id != null && StrUtils.isNotBlank(name); return id != null && StrUtils.isNotBlank(name);
} }
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.id);
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
System.out.println("hello?");
if (this == o) if (this == o)
return true; return true;
if (o == null || getClass() != o.getClass()) if (o == null || getClass() != o.getClass())

View File

@@ -51,6 +51,7 @@ public class PropertyMap extends HashMap<String, Property> {
for (Map<String, String> propertyMap : list) { for (Map<String, String> propertyMap : list) {
String name = propertyMap.get("name"); String name = propertyMap.get("name");
String value = propertyMap.get("value"); String value = propertyMap.get("value");
put(name, new Property(name, value));
} }
} catch (Throwable t) { } catch (Throwable t) {
HMCLog.warn("Failed to deserialize properties", t); HMCLog.warn("Failed to deserialize properties", t);
@@ -76,6 +77,7 @@ public class PropertyMap extends HashMap<String, Property> {
JsonObject object = (JsonObject) element; JsonObject object = (JsonObject) element;
String name = object.getAsJsonPrimitive("name").getAsString(); String name = object.getAsJsonPrimitive("name").getAsString();
String value = object.getAsJsonPrimitive("value").getAsString(); String value = object.getAsJsonPrimitive("value").getAsString();
result.put(name, new Property(name, value));
} }
return result; return result;
@@ -101,10 +103,10 @@ public class PropertyMap extends HashMap<String, Property> {
@Override @Override
public JsonElement serialize(PropertyMap src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(PropertyMap src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject(); JsonObject result = new JsonObject();
for (String key : src.keySet()) { for (PropertyMap.Entry<String, Property> entry : src.entrySet()) {
JsonArray values = new JsonArray(); JsonArray values = new JsonArray();
values.add(new JsonPrimitive(src.get(key).value)); values.add(new JsonPrimitive(entry.getValue().value));
result.add(key, values); result.add(entry.getKey(), values);
} }
return result; return result;
} }

View File

@@ -37,7 +37,7 @@ import org.jackhuang.hellominecraft.util.StrUtils;
*/ */
public class LiteLoaderVersionList extends InstallerVersionList { public class LiteLoaderVersionList extends InstallerVersionList {
private static LiteLoaderVersionList instance; private static volatile LiteLoaderVersionList instance = null;
public static LiteLoaderVersionList getInstance() { public static LiteLoaderVersionList getInstance() {
if (instance == null) if (instance == null)

View File

@@ -18,6 +18,7 @@
package org.jackhuang.hellominecraft.launcher.core.install.optifine.bmcl; package org.jackhuang.hellominecraft.launcher.core.install.optifine.bmcl;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@@ -50,6 +51,9 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
public Map<String, List<InstallerVersion>> versionMap; public Map<String, List<InstallerVersion>> versionMap;
public List<InstallerVersion> versions; public List<InstallerVersion> versions;
private static final Type TYPE = new TypeToken<ArrayList<OptiFineVersion>>() {
}.getType();
@Override @Override
public void refreshList(String[] needed) throws Exception { public void refreshList(String[] needed) throws Exception {
String s = NetUtils.get("http://bmclapi.bangbang93.com/optifine/versionlist"); String s = NetUtils.get("http://bmclapi.bangbang93.com/optifine/versionlist");
@@ -59,8 +63,7 @@ public class OptiFineBMCLVersionList extends InstallerVersionList {
if (s == null) if (s == null)
return; return;
root = C.GSON.fromJson(s, new TypeToken<ArrayList<OptiFineVersion>>() { root = C.GSON.fromJson(s, TYPE);
}.getType());
for (OptiFineVersion v : root) { for (OptiFineVersion v : root) {
v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/"); v.mirror = v.mirror.replace("http://optifine.net/http://optifine.net/", "http://optifine.net/");

View File

@@ -118,7 +118,7 @@ public class GameLauncher {
if (StrUtils.isNotBlank(options.getPrecalledCommand())) { if (StrUtils.isNotBlank(options.getPrecalledCommand())) {
Process p = Runtime.getRuntime().exec(options.getPrecalledCommand()); Process p = Runtime.getRuntime().exec(options.getPrecalledCommand());
try { try {
if (p != null && p.isAlive()) if (p.isAlive())
p.waitFor(); p.waitFor();
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
HMCLog.warn("Failed to invoke precalled command", ex); HMCLog.warn("Failed to invoke precalled command", ex);

View File

@@ -144,32 +144,26 @@ public final class ModpackManager {
* &lt; String, Boolean, Boolean &gt;: Folder/File name, Is Directory, * &lt; String, Boolean, Boolean &gt;: Folder/File name, Is Directory,
* Return 0: non blocked, 1: non shown, 2: suggested, checked. * Return 0: non blocked, 1: non shown, 2: suggested, checked.
*/ */
public static final BiFunction<String, Boolean, Integer> MODPACK_PREDICATE = new BiFunction<String, Boolean, Integer>() { public static final BiFunction<String, Boolean, Integer> MODPACK_PREDICATE = (String x, Boolean y) -> {
@Override if (ModpackManager.MODPACK_BLACK_LIST_PREDICATE.apply(x, y))
public Integer apply(String x, Boolean y) { return 1;
if (ModpackManager.MODPACK_BLACK_LIST_PREDICATE.apply(x, y)) if (ModpackManager.MODPACK_SUGGESTED_BLACK_LIST_PREDICATE.apply(x, y))
return 1; return 2;
if (ModpackManager.MODPACK_SUGGESTED_BLACK_LIST_PREDICATE.apply(x, y)) return 0;
return 2;
return 0;
}
}; };
public static final BiFunction<String, Boolean, Boolean> MODPACK_BLACK_LIST_PREDICATE = modpackPredicateMaker(MODPACK_BLACK_LIST); public static final BiFunction<String, Boolean, Boolean> MODPACK_BLACK_LIST_PREDICATE = modpackPredicateMaker(MODPACK_BLACK_LIST);
public static final BiFunction<String, Boolean, Boolean> MODPACK_SUGGESTED_BLACK_LIST_PREDICATE = modpackPredicateMaker(MODPACK_SUGGESTED_BLACK_LIST); public static final BiFunction<String, Boolean, Boolean> MODPACK_SUGGESTED_BLACK_LIST_PREDICATE = modpackPredicateMaker(MODPACK_SUGGESTED_BLACK_LIST);
private static BiFunction<String, Boolean, Boolean> modpackPredicateMaker(final List<String> l) { private static BiFunction<String, Boolean, Boolean> modpackPredicateMaker(final List<String> l) {
return new BiFunction<String, Boolean, Boolean>() { return (String x, Boolean y) -> {
@Override for (String s : l)
public Boolean apply(String x, Boolean y) { if (y) {
for (String s : l) if (x.startsWith(s + "/"))
if (y) {
if (x.startsWith(s + "/"))
return true;
} else if (x.equals(s))
return true; return true;
return false; } else if (x.equals(s))
} return true;
return false;
}; };
} }
@@ -193,17 +187,14 @@ public final class ModpackManager {
ZipEngine zip = null; ZipEngine zip = null;
try { try {
zip = new ZipEngine(output); zip = new ZipEngine(output);
zip.putDirectory(provider.getRunDirectory(version), new BiFunction<String, Boolean, String>() { zip.putDirectory(provider.getRunDirectory(version), (String x, Boolean y) -> {
@Override for (String s : b)
public String apply(String x, Boolean y) { if (y) {
for (String s : b) if (x.startsWith(s + "/"))
if (y) {
if (x.startsWith(s + "/"))
return null;
} else if (x.equals(s))
return null; return null;
return "minecraft/" + x; } else if (x.equals(s))
} return null;
return "minecraft/" + x;
}); });
MinecraftVersion mv = provider.getVersionById(version).resolve(provider); MinecraftVersion mv = provider.getVersionById(version).resolve(provider);

View File

@@ -59,5 +59,7 @@ public abstract class IMinecraftLibrary implements Cloneable {
} }
@Override @Override
public abstract Object clone(); public Object clone() throws CloneNotSupportedException {
return super.clone();
}
} }

View File

@@ -52,8 +52,12 @@ public class MinecraftLibrary extends IMinecraftLibrary {
} }
@Override @Override
public Object clone() { public Object clone() throws CloneNotSupportedException {
return new MinecraftLibrary(rules, url, checksums, natives, name, extract); MinecraftLibrary ml = (MinecraftLibrary) super.clone();
ml.extract = (Extract) ml.extract.clone();
ml.natives = (Natives) ml.natives.clone();
ml.rules = (ArrayList<Rules>) ml.rules.clone();
return ml;
} }
/** /**
@@ -69,11 +73,11 @@ public class MinecraftLibrary extends IMinecraftLibrary {
else else
for (Rules r : rules) for (Rules r : rules)
if (r.action.equals("disallow")) { if (r.action.equals("disallow")) {
if (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString()))) { if (r.os != null && (StrUtils.isBlank(r.os.getName()) || r.os.getName().equalsIgnoreCase(OS.os().toString()))) {
flag = false; flag = false;
break; break;
} }
} else if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.name) || r.os.name.equalsIgnoreCase(OS.os().toString())))) } else if (r.os == null || (r.os != null && (StrUtils.isBlank(r.os.getName()) || r.os.getName().equalsIgnoreCase(OS.os().toString()))))
flag = true; flag = true;
return flag; return flag;
} }
@@ -83,13 +87,14 @@ public class MinecraftLibrary extends IMinecraftLibrary {
} }
private String getNative() { private String getNative() {
OS os = OS.os(); switch (OS.os()) {
if (os == OS.WINDOWS) case WINDOWS:
return formatArch(natives.windows); return formatArch(natives.windows);
else if (os == OS.OSX) case OSX:
return formatArch(natives.osx); return formatArch(natives.osx);
else default:
return formatArch(natives.linux); return formatArch(natives.linux);
}
} }
@Override @Override

View File

@@ -26,11 +26,7 @@ public class Natives implements Cloneable {
public String windows, osx, linux; public String windows, osx, linux;
@Override @Override
protected Object clone() { protected Object clone() throws CloneNotSupportedException {
Natives n = new Natives(); return super.clone();
n.windows = windows;
n.osx = osx;
n.linux = linux;
return n;
} }
} }

View File

@@ -23,5 +23,21 @@ package org.jackhuang.hellominecraft.launcher.core.version;
*/ */
public class OS { public class OS {
public String version, name; private String version, name;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} }

View File

@@ -19,7 +19,6 @@ package org.jackhuang.hellominecraft.launcher.ui;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import org.jackhuang.hellominecraft.util.C; import org.jackhuang.hellominecraft.util.C;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.MessageBox; import org.jackhuang.hellominecraft.util.MessageBox;
import org.jackhuang.hellominecraft.util.StrUtils; import org.jackhuang.hellominecraft.util.StrUtils;
import org.jackhuang.hellominecraft.util.ui.SwingUtils; import org.jackhuang.hellominecraft.util.ui.SwingUtils;

View File

@@ -22,7 +22,6 @@ import java.awt.Dimension;
import java.awt.Font; import java.awt.Font;
import java.awt.event.ItemEvent; import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import javax.swing.JFileChooser; import javax.swing.JFileChooser;
@@ -45,7 +44,6 @@ import org.jackhuang.hellominecraft.lookandfeel.GraphicsUtils;
import org.jackhuang.hellominecraft.util.Event; import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton; import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton;
import org.jackhuang.hellominecraft.util.system.FileUtils; import org.jackhuang.hellominecraft.util.system.FileUtils;
import org.jackhuang.hellominecraft.util.system.IOUtils;
import org.jackhuang.hellominecraft.util.system.JavaProcessMonitor; import org.jackhuang.hellominecraft.util.system.JavaProcessMonitor;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow; import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
import org.jackhuang.hellominecraft.util.ui.LogWindow; import org.jackhuang.hellominecraft.util.ui.LogWindow;
@@ -86,9 +84,9 @@ public class MainPagePanel extends AnimatedPanel {
pnlMore.setBackground(GraphicsUtils.getWebColorWithAlpha("FFFFFF7F")); pnlMore.setBackground(GraphicsUtils.getWebColorWithAlpha("FFFFFF7F"));
pnlMore.setOpaque(true); pnlMore.setOpaque(true);
prepareAuths();
Settings.getInstance().authChangedEvent.register(onAuthChanged); Settings.getInstance().authChangedEvent.register(onAuthChanged);
prepareAuths();
} }
/** /**
@@ -464,7 +462,7 @@ public class MainPagePanel extends AnimatedPanel {
void runGame() { void runGame() {
MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching")); MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching"));
getProfile().launcher().genLaunchCode(value -> { getProfile().launcher().genLaunchCode(value -> {
value.successEvent.register(new LaunchFinisher()); value.successEvent.register(launchFinisher);
value.successEvent.register(this::prepareAuths); value.successEvent.register(this::prepareAuths);
}, this::failed, txtPassword.getText()); }, this::failed, txtPassword.getText());
} }
@@ -472,7 +470,7 @@ public class MainPagePanel extends AnimatedPanel {
void makeLaunchScript() { void makeLaunchScript() {
MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching")); MainFrame.INSTANCE.showMessage(C.i18n("ui.message.launching"));
getProfile().launcher().genLaunchCode(value -> { getProfile().launcher().genLaunchCode(value -> {
value.successEvent.register(new LaunchScriptFinisher()); value.successEvent.register(launchScriptFinisher);
value.successEvent.register(this::prepareAuths); value.successEvent.register(this::prepareAuths);
}, this::failed, txtPassword.getText()); }, this::failed, txtPassword.getText());
} }
@@ -483,68 +481,59 @@ public class MainPagePanel extends AnimatedPanel {
MainFrame.INSTANCE.closeMessage(); MainFrame.INSTANCE.closeMessage();
} }
public class LaunchFinisher implements Event<List<String>> { final Event<List<String>> launchFinisher = (sender, str) -> {
final GameLauncher obj = (GameLauncher) sender;
@Override obj.launchEvent.register(p -> {
public boolean call(Object sender, List<String> str) { if ((LauncherVisibility) obj.getTag() == LauncherVisibility.CLOSE && !LogWindow.INSTANCE.isVisible()) {
final GameLauncher obj = (GameLauncher) sender; HMCLog.log("Without the option of keeping the launcher visible, this application will exit and will NOT catch game logs, but you can turn on \"Debug Mode\".");
obj.launchEvent.register(p -> { System.exit(0);
if ((LauncherVisibility) obj.getTag() == LauncherVisibility.CLOSE && !LogWindow.INSTANCE.isVisible()) { } else if ((LauncherVisibility) obj.getTag() == LauncherVisibility.KEEP)
MainFrame.INSTANCE.closeMessage();
else {
if (LogWindow.INSTANCE.isVisible())
LogWindow.INSTANCE.setExit(() -> true);
MainFrame.INSTANCE.dispose();
}
JavaProcessMonitor jpm = new JavaProcessMonitor(p);
jpm.applicationExitedAbnormallyEvent.register(t -> {
HMCLog.err("The game exited abnormally, exit code: " + t);
MessageBox.Show(C.i18n("launch.exited_abnormally") + ", exit code: " + t);
});
jpm.jvmLaunchFailedEvent.register(t -> {
HMCLog.err("Cannot create jvm, exit code: " + t);
MessageBox.Show(C.i18n("launch.cannot_create_jvm") + ", exit code: " + t);
});
jpm.stoppedEvent.register(() -> {
if ((LauncherVisibility) obj.getTag() != LauncherVisibility.KEEP && !LogWindow.INSTANCE.isVisible()) {
HMCLog.log("Without the option of keeping the launcher visible, this application will exit and will NOT catch game logs, but you can turn on \"Debug Mode\"."); HMCLog.log("Without the option of keeping the launcher visible, this application will exit and will NOT catch game logs, but you can turn on \"Debug Mode\".");
System.exit(0); System.exit(0);
} else if ((LauncherVisibility) obj.getTag() == LauncherVisibility.KEEP)
MainFrame.INSTANCE.closeMessage();
else {
if (LogWindow.INSTANCE.isVisible())
LogWindow.INSTANCE.setExit(() -> true);
MainFrame.INSTANCE.dispose();
} }
JavaProcessMonitor jpm = new JavaProcessMonitor(p);
jpm.applicationExitedAbnormallyEvent.register(t -> {
HMCLog.err("The game exited abnormally, exit code: " + t);
MessageBox.Show(C.i18n("launch.exited_abnormally") + ", exit code: " + t);
});
jpm.jvmLaunchFailedEvent.register(t -> {
HMCLog.err("Cannot create jvm, exit code: " + t);
MessageBox.Show(C.i18n("launch.cannot_create_jvm") + ", exit code: " + t);
});
jpm.stoppedEvent.register(() -> {
if ((LauncherVisibility) obj.getTag() != LauncherVisibility.KEEP && !LogWindow.INSTANCE.isVisible()) {
HMCLog.log("Without the option of keeping the launcher visible, this application will exit and will NOT catch game logs, but you can turn on \"Debug Mode\".");
System.exit(0);
}
});
jpm.start();
}); });
try { jpm.start();
obj.launch(str); });
} catch (IOException e) { try {
failed(C.i18n("launch.failed_creating_process") + "\n" + e.getMessage()); obj.launch(str);
HMCLog.err("Failed to launch when creating a new process.", e); } catch (IOException e) {
} failed(C.i18n("launch.failed_creating_process") + "\n" + e.getMessage());
return true; HMCLog.err("Failed to launch when creating a new process.", e);
} }
} return true;
};
public class LaunchScriptFinisher implements Event<List<String>> { final Event<List<String>> launchScriptFinisher = (sender, str) -> {
boolean flag = false;
@Override try {
public boolean call(Object sender, List str) { String s = JOptionPane.showInputDialog(C.i18n("mainwindow.enter_script_name"));
boolean flag = false; if (s != null)
try { MessageBox.Show(C.i18n("mainwindow.make_launch_succeed") + " " + ((GameLauncher) sender).makeLauncher(s, str).getAbsolutePath());
String s = JOptionPane.showInputDialog(C.i18n("mainwindow.enter_script_name")); flag = true;
if (s != null) } catch (IOException ex) {
MessageBox.Show(C.i18n("mainwindow.make_launch_succeed") + " " + ((GameLauncher) sender).makeLauncher(s, str).getAbsolutePath()); MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed"));
flag = true; HMCLog.err("Failed to create script file.", ex);
} catch (IOException ex) {
MessageBox.Show(C.i18n("mainwindow.make_launch_script_failed"));
HMCLog.err("Failed to create script file.", ex);
}
MainFrame.INSTANCE.closeMessage();
return flag;
} }
MainFrame.INSTANCE.closeMessage();
} return flag;
};
public Profile getProfile() { public Profile getProfile() {
return Settings.getProfile((String) cboProfiles.getSelectedItem()); return Settings.getProfile((String) cboProfiles.getSelectedItem());

View File

@@ -130,8 +130,12 @@ public final class NewProfileWindow extends javax.swing.JDialog {
Profile newProfile = new Profile(Settings.getProfile(cboProfiles.getSelectedItem().toString())); Profile newProfile = new Profile(Settings.getProfile(cboProfiles.getSelectedItem().toString()));
newProfile.setName(txtNewProfileName.getText()); newProfile.setName(txtNewProfileName.getText());
Settings.trySetProfile(newProfile); Settings.trySetProfile(newProfile);
break;
case 27: case 27:
this.dispose(); this.dispose();
break;
default:
break;
} }
}//GEN-LAST:event_txtNewProfileNameKeyTyped }//GEN-LAST:event_txtNewProfileNameKeyTyped

View File

@@ -84,7 +84,7 @@ public class AppDataUpgrader extends IUpgrader {
} }
} }
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); HMCLog.err("Failed to execute newer version application", t);
} }
return false; return false;
} }

View File

@@ -18,8 +18,6 @@
package org.jackhuang.hellominecraft.launcher.util.upgrade; package org.jackhuang.hellominecraft.launcher.util.upgrade;
import org.jackhuang.hellominecraft.util.Event; import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.util.Event;
import org.jackhuang.hellominecraft.util.VersionNumber;
import org.jackhuang.hellominecraft.util.VersionNumber; import org.jackhuang.hellominecraft.util.VersionNumber;
/** /**

View File

@@ -19,8 +19,6 @@ package org.jackhuang.hellominecraft.launcher.util.upgrade;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jackhuang.hellominecraft.util.logging.HMCLog; import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.tasks.TaskWindow; import org.jackhuang.hellominecraft.util.tasks.TaskWindow;
import org.jackhuang.hellominecraft.util.tasks.download.FileDownloadTask; import org.jackhuang.hellominecraft.util.tasks.download.FileDownloadTask;

View File

@@ -18,10 +18,8 @@
package org.jackhuang.hellominecraft.util; package org.jackhuang.hellominecraft.util;
import org.jackhuang.hellominecraft.util.lang.SupportedLocales; import org.jackhuang.hellominecraft.util.lang.SupportedLocales;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import java.util.ResourceBundle;
/** /**
* *

View File

@@ -72,9 +72,7 @@ public class Pair<K, V> implements Map.Entry<K, V> {
final Pair<?, ?> other = (Pair<?, ?>) obj; final Pair<?, ?> other = (Pair<?, ?>) obj;
if (!Objects.equals(this.key, other.key)) if (!Objects.equals(this.key, other.key))
return false; return false;
if (!Objects.equals(this.value, other.value)) return Objects.equals(this.value, other.value);
return false;
return true;
} }
} }

View File

@@ -41,13 +41,13 @@ public class Base64 {
val |= (0xFF & (int) data[i + 2]); val |= (0xFF & (int) data[i + 2]);
quad = true; quad = true;
} }
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; out[index + 3] = ALPHABET[(quad ? (val & 0x3F) : 64)];
val >>= 6; val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; out[index + 2] = ALPHABET[(trip ? (val & 0x3F) : 64)];
val >>= 6; val >>= 6;
out[index + 1] = alphabet[val & 0x3F]; out[index + 1] = ALPHABET[val & 0x3F];
val >>= 6; val >>= 6;
out[index + 0] = alphabet[val & 0x3F]; out[index + 0] = ALPHABET[val & 0x3F];
} }
return out; return out;
} }
@@ -71,7 +71,7 @@ public class Base64 {
int accum = 0; int accum = 0;
int index = 0; int index = 0;
for (int ix = 0; ix < data.length; ix++) { for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] & 0xFF]; int value = CODES[data[ix] & 0xFF];
if (value >= 0) { if (value >= 0) {
accum <<= 6; accum <<= 6;
shift += 6; shift += 6;
@@ -86,20 +86,20 @@ public class Base64 {
throw new Error("miscalculated data length!"); throw new Error("miscalculated data length!");
return out; return out;
} }
private static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray(); .toCharArray();
private static final byte[] codes = new byte[256]; private static final byte[] CODES = new byte[256];
static { static {
for (int i = 0; i < 256; i++) for (int i = 0; i < 256; i++)
codes[i] = -1; CODES[i] = -1;
for (int i = 'A'; i <= 'Z'; i++) for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A'); CODES[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++) for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a'); CODES[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++) for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0'); CODES[i] = (byte) (52 + i - '0');
codes['+'] = 62; CODES['+'] = 62;
codes['/'] = 63; CODES['/'] = 63;
} }
} }

View File

@@ -25,34 +25,34 @@ import org.jackhuang.hellominecraft.util.logging.logger.Logger;
*/ */
public class HMCLog { public class HMCLog {
private static final Logger logger = new Logger("Hello Minecraft!"); private static final Logger LOGGER = new Logger("Hello Minecraft!");
public static void log(String message) { public static void log(String message) {
logger.info(message); LOGGER.info(message);
} }
public static void warn(String message) { public static void warn(String message) {
logger.warn(message); LOGGER.warn(message);
} }
public static void debug(String message) { public static void debug(String message) {
logger.debug(message); LOGGER.debug(message);
} }
public static void warn(String msg, Throwable t) { public static void warn(String msg, Throwable t) {
logger.warn(msg, t); LOGGER.warn(msg, t);
} }
public static void debug(String msg, Throwable t) { public static void debug(String msg, Throwable t) {
logger.debug(msg, t); LOGGER.debug(msg, t);
} }
public static void err(String msg) { public static void err(String msg) {
logger.error(msg); LOGGER.error(msg);
} }
public static void err(String msg, Throwable t) { public static void err(String msg, Throwable t) {
logger.error(msg, t); LOGGER.error(msg, t);
} }
} }

View File

@@ -60,18 +60,29 @@ public enum Level {
if (m.find()) { if (m.find()) {
// New style logs from log4j // New style logs from log4j
String levelStr = m.group("level"); String levelStr = m.group("level");
if ("INFO".equals(levelStr)) if (null != levelStr)
level = INFO; switch (levelStr) {
else if ("WARN".equals(levelStr)) case "INFO":
level = WARN; level = INFO;
else if ("ERROR".equals(levelStr)) break;
level = ERROR; case "WARN":
else if ("FATAL".equals(levelStr)) level = WARN;
level = FATAL; break;
else if ("TRACE".equals(levelStr)) case "ERROR":
level = TRACE; level = ERROR;
else if ("DEBUG".equals(levelStr)) break;
level = DEBUG; case "FATAL":
level = FATAL;
break;
case "TRACE":
level = TRACE;
break;
case "DEBUG":
level = DEBUG;
break;
default:
break;
}
} else { } else {
if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]") if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]")
|| line.contains("[FINER]") || line.contains("[FINEST]")) || line.contains("[FINER]") || line.contains("[FINEST]"))

View File

@@ -51,7 +51,7 @@ public class Logger extends AbstractLogger {
this.config = new PrivateConfig(this.config, level); this.config = new PrivateConfig(this.config, level);
} }
public Level getLevel() { public synchronized Level getLevel() {
return this.config.level; return this.config.level;
} }

View File

@@ -26,7 +26,6 @@ import java.io.InputStreamReader;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import org.jackhuang.hellominecraft.util.logging.HMCLog; import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.StrUtils;
/** /**
* @author huangyuhui * @author huangyuhui
@@ -85,7 +84,7 @@ public enum OS {
BufferedReader br = new BufferedReader(new InputStreamReader( BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file))); new FileInputStream(file)));
long[] result = new long[4]; long[] result = new long[4];
String str = null; String str;
StringTokenizer token; StringTokenizer token;
while ((str = br.readLine()) != null) { while ((str = br.readLine()) != null) {
token = new StringTokenizer(str); token = new StringTokenizer(str);

View File

@@ -21,7 +21,6 @@ import java.io.OutputStream;
import java.util.Timer; import java.util.Timer;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import org.jackhuang.hellominecraft.util.logging.Level; import org.jackhuang.hellominecraft.util.logging.Level;
import org.jackhuang.hellominecraft.util.ui.LogWindow;
/** /**
* *

View File

@@ -21,9 +21,7 @@ import java.awt.Color;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Graphics; import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.ColorUIResource;
public class CheckBoxTreeLabel extends JLabel { public class CheckBoxTreeLabel extends JLabel {

View File

@@ -198,23 +198,20 @@ public class NavButtonManager implements ActionListener {
final boolean enableNext = nextStep != null && canContinue && problem == null && !isDeferredResult; final boolean enableNext = nextStep != null && canContinue && problem == null && !isDeferredResult;
final boolean enablePrevious = wizard.getPreviousStep() != null && !isDeferredResult; final boolean enablePrevious = wizard.getPreviousStep() != null && !isDeferredResult;
final Runnable runnable = new Runnable() { final Runnable runnable = () -> {
@Override next.setEnabled(enableNext);
public void run() { prev.setEnabled(enablePrevious);
next.setEnabled(enableNext); finish.setEnabled(enableFinish);
prev.setEnabled(enablePrevious); JRootPane root = next.getRootPane();
finish.setEnabled(enableFinish); if (root != null)
JRootPane root = next.getRootPane(); if (next.isEnabled())
if (root != null) root.setDefaultButton(next);
if (next.isEnabled()) else if (finish.isEnabled())
root.setDefaultButton(next); root.setDefaultButton(finish);
else if (finish.isEnabled()) else if (prev.isEnabled())
root.setDefaultButton(finish); root.setDefaultButton(prev);
else if (prev.isEnabled()) else
root.setDefaultButton(prev); root.setDefaultButton(null);
else
root.setDefaultButton(null);
}
}; };
if (EventQueue.isDispatchThread()) if (EventQueue.isDispatchThread())
@@ -265,21 +262,18 @@ public class NavButtonManager implements ActionListener {
} }
void deferredResultFailed(final boolean canGoBack) { void deferredResultFailed(final boolean canGoBack) {
final Runnable runnable = new Runnable() { final Runnable runnable = () -> {
@Override if (!canGoBack)
public void run() { getCancel().setText(getCloseString());
if (!canGoBack) getPrev().setEnabled(true);
getCancel().setText(getCloseString()); getNext().setEnabled(false);
getPrev().setEnabled(true); getCancel().setEnabled(true);
getNext().setEnabled(false); getFinish().setEnabled(false);
getCancel().setEnabled(true);
getFinish().setEnabled(false);
if (NAME_CLOSE.equals(deferredStatus)) { if (NAME_CLOSE.equals(deferredStatus)) {
// no action // no action
} else } else
deferredStatus = DEFERRED_FAILED + deferredStatus; deferredStatus = DEFERRED_FAILED + deferredStatus;
}
}; };
if (EventQueue.isDispatchThread()) if (EventQueue.isDispatchThread())
runnable.run(); runnable.run();
@@ -601,25 +595,22 @@ public class NavButtonManager implements ActionListener {
} }
public void navigabilityChanged(final Wizard wizard) { public void navigabilityChanged(final Wizard wizard) {
final Runnable runnable = new Runnable() { final Runnable runnable = () -> {
@Override if (wizard.isBusy()) {
public void run() { next.setEnabled(false);
if (wizard.isBusy()) { prev.setEnabled(false);
next.setEnabled(false); finish.setEnabled(false);
prev.setEnabled(false); cancel.setEnabled(false);
finish.setEnabled(false); parent.getOuterPanel().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
cancel.setEnabled(false); wasBusy = true;
parent.getOuterPanel().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); return;
wasBusy = true; } else if (wasBusy) {
return; cancel.setEnabled(true);
} else if (wasBusy) { parent.getOuterPanel().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
cancel.setEnabled(true);
parent.getOuterPanel().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
configureNavigationButtons(wizard, prev, next, finish);
parent.updateProblem();
} }
configureNavigationButtons(wizard, prev, next, finish);
parent.updateProblem();
}; };
if (EventQueue.isDispatchThread()) if (EventQueue.isDispatchThread())
runnable.run(); runnable.run();

View File

@@ -150,14 +150,10 @@ final class Util {
try { try {
m.setAccessible(true); m.setAccessible(true);
result = (String) m.invoke(null, (Object[]) null); result = (String) m.invoke(null, (Object[]) null);
} catch (InvocationTargetException ite) { } catch (InvocationTargetException | IllegalAccessException ite) {
throw new IllegalArgumentException("Could not invoke " throw new IllegalArgumentException("Could not invoke "
+ "public static String " + clazz.getName() + "public static String " + clazz.getName()
+ ".getDescription() - make sure it exists."); + ".getDescription() - make sure it exists.", ite);
} catch (IllegalAccessException iae) {
throw new IllegalArgumentException("Could not invoke "
+ "public static String " + clazz.getName()
+ ".getDescription() - make sure it exists.");
} }
return result; return result;
} }

View File

@@ -54,9 +54,7 @@ public abstract class WizardPanelNavResult extends DeferredWizardResult {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof WPNRimmediate && ((WPNRimmediate) o).value == value) return o instanceof WPNRimmediate && ((WPNRimmediate) o).value == value;
return true;
return false;
} }
public int hashCode() { public int hashCode() {

View File

@@ -17,6 +17,8 @@
*/ */
package org.jackhuang.hellominecraft.svrmgr.install.cauldron; package org.jackhuang.hellominecraft.svrmgr.install.cauldron;
import java.util.Arrays;
/** /**
* *
* @author huangyuhui * @author huangyuhui
@@ -29,6 +31,6 @@ public class ForgeVersion {
@Override @Override
public String toString() { public String toString() {
return "ForgeVersion{" + "vername=" + vername + ", ver=" + ver + ", mcver=" + mcver + ", releasetime=" + releasetime + ", changelog=" + changelog + ", installer=" + installer + ", javadoc=" + javadoc + ", src=" + src + ", universal=" + universal + ", userdev=" + userdev + ", typeint=" + typeint + '}'; return "ForgeVersion{" + "vername=" + vername + ", ver=" + ver + ", mcver=" + mcver + ", releasetime=" + releasetime + ", changelog=" + changelog + ", installer=" + Arrays.toString(installer) + ", javadoc=" + Arrays.toString(javadoc) + ", src=" + Arrays.toString(src) + ", universal=" + universal + ", userdev=" + userdev + ", typeint=" + typeint + '}';
} }
} }

View File

@@ -38,9 +38,7 @@ public class ServerChecker {
} }
if (file.getEntry("org/bukkit/craftbukkit/Main.class") != null) if (file.getEntry("org/bukkit/craftbukkit/Main.class") != null)
return true; return true;
if (file.getEntry("net/minecraft/server/MinecraftServer.class") != null) return file.getEntry("net/minecraft/server/MinecraftServer.class") != null;
return true;
return false;
} }
} }

View File

@@ -70,7 +70,7 @@ public abstract class PlayerList<T extends BasePlayer> {
public void initByText(String s) { public void initByText(String s) {
String[] lines = s.split("\n"); String[] lines = s.split("\n");
op = new HashSet<T>(); op = new HashSet<>();
for (String l : lines) { for (String l : lines) {
if (l.startsWith("#")) if (l.startsWith("#"))
continue; continue;
@@ -86,17 +86,7 @@ public abstract class PlayerList<T extends BasePlayer> {
} }
public void initByBoth(File txt, File json) { public void initByBoth(File txt, File json) {
HashSet<T> player = new HashSet<T>(); HashSet<T> player = new HashSet<>();
/*op = null;
if(json.exists()) {
try {
initByJson(FileUtils.readFileToStringIgnoreFileNotFound(json));
if(op != null)
player.addAll(op);
} catch(IOException e) {
HMCLLog.warn("Failed to load playerlist by json", e);
}
}*/
op = null; op = null;
if (txt.exists()) if (txt.exists())
try { try {

View File

@@ -18,11 +18,9 @@ package org.jackhuang.hellominecraft.lookandfeel;
import java.awt.Color; import java.awt.Color;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.util.Map; import java.util.Map;
import javax.swing.UIDefaults; import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.synth.SynthLookAndFeel; import javax.swing.plaf.synth.SynthLookAndFeel;
import org.jackhuang.hellominecraft.util.logging.HMCLog; import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.NetUtils; import org.jackhuang.hellominecraft.util.NetUtils;

View File

@@ -42,22 +42,22 @@ import org.jackhuang.hellominecraft.lookandfeel.comp.ConstomButton;
public class ButtonPainter extends SynthPainter { public class ButtonPainter extends SynthPainter {
private static final String DEFAULT_NORMAL = "D5D5D5"; private static final String DEFAULT_NORMAL = "D5D5D5";
private static final Color[] DEFAULT_NORMAL_FG = new Color[]{ private static final Color[] DEFAULT_NORMAL_FG = new Color[] {
GraphicsUtils.getWebColor(DEFAULT_NORMAL), GraphicsUtils.getWebColor(DEFAULT_NORMAL),
GraphicsUtils.getWebColor(DEFAULT_NORMAL) GraphicsUtils.getWebColor(DEFAULT_NORMAL)
}; };
private static final String DEFAULT_PRELIGHT = "A9A9A9"; private static final String DEFAULT_PRELIGHT = "A9A9A9";
private static final Color[] DEFAULT_PRELIGHT_FG = new Color[]{ private static final Color[] DEFAULT_PRELIGHT_FG = new Color[] {
GraphicsUtils.getWebColor(DEFAULT_PRELIGHT), GraphicsUtils.getWebColor(DEFAULT_PRELIGHT),
GraphicsUtils.getWebColor(DEFAULT_PRELIGHT) GraphicsUtils.getWebColor(DEFAULT_PRELIGHT)
}; };
private static final String DEFAULT_ACTIVE = "222222"; private static final String DEFAULT_ACTIVE = "222222";
private static final Color[] DEFAULT_ACTIVE_FG = new Color[]{ private static final Color[] DEFAULT_ACTIVE_FG = new Color[] {
GraphicsUtils.getWebColor(DEFAULT_ACTIVE), GraphicsUtils.getWebColor(DEFAULT_ACTIVE),
GraphicsUtils.getWebColor(DEFAULT_ACTIVE) GraphicsUtils.getWebColor(DEFAULT_ACTIVE)
}; };
private static final Color[] DISABLED_BG = new Color[]{ private static final Color[] DISABLED_BG = new Color[] {
GraphicsUtils.getWebColor("E3EFE9"), GraphicsUtils.getWebColor("E3EFE9"),
GraphicsUtils.getMidWebColor("E3EFE9", "DFE2E6"), GraphicsUtils.getMidWebColor("E3EFE9", "DFE2E6"),
GraphicsUtils.getWebColor("DFE2E6"), GraphicsUtils.getWebColor("DFE2E6"),
@@ -68,7 +68,7 @@ public class ButtonPainter extends SynthPainter {
GraphicsUtils.getWebColor("D8DBE1"), GraphicsUtils.getWebColor("D8DBE1"),
GraphicsUtils.getWebColor("DADDE3") GraphicsUtils.getWebColor("DADDE3")
}; };
private static final Color[] DISABLED_FG = new Color[]{ private static final Color[] DISABLED_FG = new Color[] {
GraphicsUtils.getWebColor("C9CCD2"), GraphicsUtils.getWebColor("C9CCD2"),
GraphicsUtils.getWebColor("C9CCD2"), GraphicsUtils.getWebColor("C9CCD2"),
GraphicsUtils.getWebColor("BCBFC5"), GraphicsUtils.getWebColor("BCBFC5"),
@@ -79,18 +79,12 @@ public class ButtonPainter extends SynthPainter {
if (System.currentTimeMillis() > c.lastDrawTime) { if (System.currentTimeMillis() > c.lastDrawTime) {
c.lastDrawTime = System.currentTimeMillis(); c.lastDrawTime = System.currentTimeMillis();
c.drawPercent += add; c.drawPercent += add;
if (c.drawPercent > 100 && add > 0) { if (c.drawPercent > 100 && add > 0)
c.drawPercent = 100; c.drawPercent = 100;
} else if (c.drawPercent < 0 && add < 0) { else if (c.drawPercent < 0 && add < 0)
c.drawPercent = 0; c.drawPercent = 0;
} else { else
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(c::updateUI);
@Override
public void run() {
c.updateUI();
}
});
}
} }
return true; return true;
} }
@@ -103,98 +97,84 @@ public class ButtonPainter extends SynthPainter {
Graphics2D g2 = (Graphics2D) g.create(); Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] fg, bg; Color[] fg, bg;
if ((context.getComponentState() & SynthConstants.DEFAULT) != 0) { if ((context.getComponentState() & SynthConstants.DEFAULT) != 0)
if ((context.getComponentState() & SynthConstants.PRESSED) != 0) { if ((context.getComponentState() & SynthConstants.PRESSED) != 0)
if (context.getComponent() instanceof ConstomButton) { if (context.getComponent() instanceof ConstomButton) {
ConstomButton c = (ConstomButton) context.getComponent(); ConstomButton c = (ConstomButton) context.getComponent();
fg = new Color[]{c.activeFg, c.activeFg}; fg = new Color[] { c.activeFg, c.activeFg };
bg = new Color[]{c.activeFg, c.activeFg}; bg = new Color[] { c.activeFg, c.activeFg };
} else { } else {
fg = DEFAULT_ACTIVE_FG; fg = DEFAULT_ACTIVE_FG;
bg = DEFAULT_ACTIVE_FG; bg = DEFAULT_ACTIVE_FG;
} }
} else if ((context.getComponentState() & SynthConstants.DISABLED) != 0) { else if ((context.getComponentState() & SynthConstants.DISABLED) != 0)
return; return; //fg = DISABLED_FG;
//fg = DISABLED_FG; //bg = DISABLED_BG;
//bg = DISABLED_BG; else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0)
} else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0) {
if (context.getComponent() instanceof ConstomButton) { if (context.getComponent() instanceof ConstomButton) {
final ConstomButton c = (ConstomButton) context.getComponent(); final ConstomButton c = (ConstomButton) context.getComponent();
if (!processCustomButton(c, 1)) { if (!processCustomButton(c, 1))
return; return;
}
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent); Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent); Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[]{fgs, fgs}; fg = new Color[] { fgs, fgs };
bg = new Color[]{bgs, bgs}; bg = new Color[] { bgs, bgs };
} else { } else {
fg = DEFAULT_PRELIGHT_FG; fg = DEFAULT_PRELIGHT_FG;
bg = DEFAULT_PRELIGHT_FG; bg = DEFAULT_PRELIGHT_FG;
} }
else if (context.getComponent() instanceof ConstomButton) {
final ConstomButton c = (ConstomButton) context.getComponent();
if (!processCustomButton(c, -1))
return;
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[] { fgs, fgs };
bg = new Color[] { bgs, bgs };
} else { } else {
if (context.getComponent() instanceof ConstomButton) { fg = DEFAULT_NORMAL_FG;
final ConstomButton c = (ConstomButton) context.getComponent(); bg = DEFAULT_NORMAL_FG;
if (!processCustomButton(c, -1)) {
return;
}
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[]{fgs, fgs};
bg = new Color[]{bgs, bgs};
} else {
fg = DEFAULT_NORMAL_FG;
bg = DEFAULT_NORMAL_FG;
}
} }
} else { else if ((context.getComponentState() & SynthConstants.PRESSED) != 0)
if ((context.getComponentState() & SynthConstants.PRESSED) != 0) { if (context.getComponent() instanceof ConstomButton) {
if (context.getComponent() instanceof ConstomButton) { ConstomButton c = (ConstomButton) context.getComponent();
ConstomButton c = (ConstomButton) context.getComponent(); fg = new Color[] { c.activeFg, c.activeFg };
fg = new Color[]{c.activeFg, c.activeFg}; bg = new Color[] { c.activeFg, c.activeFg };
bg = new Color[]{c.activeFg, c.activeFg}; } else {
} else { fg = DEFAULT_ACTIVE_FG;
fg = DEFAULT_ACTIVE_FG; bg = DEFAULT_ACTIVE_FG;
bg = DEFAULT_ACTIVE_FG; }
} else if ((context.getComponentState() & SynthConstants.DISABLED) != 0)
} else if ((context.getComponentState() & SynthConstants.DISABLED) != 0) { return; //fg = DISABLED_FG;
//bg = DISABLED_BG;
else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0)
if (context.getComponent() instanceof ConstomButton) {
final ConstomButton c = (ConstomButton) context.getComponent();
if (!processCustomButton(c, 1))
return;
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[] { fgs, fgs };
bg = new Color[] { bgs, bgs };
} else if (context.getComponent() instanceof ConstomButton) {
ConstomButton c = (ConstomButton) context.getComponent();
fg = new Color[] { c.prelightFg, c.prelightFg };
bg = new Color[] { c.prelightBg, c.prelightBg };
} else {
fg = DEFAULT_PRELIGHT_FG;
bg = DEFAULT_PRELIGHT_FG;
}
else if (context.getComponent() instanceof ConstomButton) {
final ConstomButton c = (ConstomButton) context.getComponent();
if (!processCustomButton(c, -1))
return; return;
//fg = DISABLED_FG; Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
//bg = DISABLED_BG; Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
} else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0) { fg = new Color[] { fgs, fgs };
if (context.getComponent() instanceof ConstomButton) { bg = new Color[] { bgs, bgs };
final ConstomButton c = (ConstomButton) context.getComponent(); } else {
if (!processCustomButton(c, 1)) { fg = DEFAULT_NORMAL_FG;
return; bg = DEFAULT_NORMAL_FG;
}
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[]{fgs, fgs};
bg = new Color[]{bgs, bgs};
} else {
if (context.getComponent() instanceof ConstomButton) {
ConstomButton c = (ConstomButton) context.getComponent();
fg = new Color[]{c.prelightFg, c.prelightFg};
bg = new Color[]{c.prelightBg, c.prelightBg};
} else {
fg = DEFAULT_PRELIGHT_FG;
bg = DEFAULT_PRELIGHT_FG;
}
}
} else {
if (context.getComponent() instanceof ConstomButton) {
final ConstomButton c = (ConstomButton) context.getComponent();
if (!processCustomButton(c, -1)) {
return;
}
Color fgs = GraphicsUtils.getMidWebColor(c.normalFg, c.prelightFg, c.drawPercent);
Color bgs = GraphicsUtils.getMidWebColor(c.normalBg, c.prelightBg, c.drawPercent);
fg = new Color[]{fgs, fgs};
bg = new Color[]{bgs, bgs};
} else {
fg = DEFAULT_NORMAL_FG;
bg = DEFAULT_NORMAL_FG;
}
}
} }
/*w = w - 2; /*w = w - 2;
h = h - 2; h = h - 2;
@@ -222,7 +202,7 @@ public class ButtonPainter extends SynthPainter {
Graphics2D g2 = (Graphics2D) g.create(); Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] fg, bg; Color[] fg, bg;
if ((context.getComponentState() & SynthConstants.DEFAULT) != 0) { if ((context.getComponentState() & SynthConstants.DEFAULT) != 0)
if ((context.getComponentState() & SynthConstants.PRESSED) != 0 || (context.getComponentState() & SynthConstants.SELECTED) != 0) { if ((context.getComponentState() & SynthConstants.PRESSED) != 0 || (context.getComponentState() & SynthConstants.SELECTED) != 0) {
fg = DEFAULT_ACTIVE_FG; fg = DEFAULT_ACTIVE_FG;
bg = DEFAULT_ACTIVE_FG; bg = DEFAULT_ACTIVE_FG;
@@ -236,20 +216,18 @@ public class ButtonPainter extends SynthPainter {
fg = DEFAULT_NORMAL_FG; fg = DEFAULT_NORMAL_FG;
bg = DEFAULT_NORMAL_FG; bg = DEFAULT_NORMAL_FG;
} }
else if ((context.getComponentState() & SynthConstants.PRESSED) != 0 || (context.getComponentState() & SynthConstants.SELECTED) != 0) {
fg = DEFAULT_ACTIVE_FG;
bg = DEFAULT_ACTIVE_FG;
} else if ((context.getComponentState() & SynthConstants.DISABLED) != 0) {
fg = DISABLED_FG;
bg = DISABLED_BG;
} else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0) {
fg = DEFAULT_PRELIGHT_FG;
bg = DEFAULT_PRELIGHT_FG;
} else { } else {
if ((context.getComponentState() & SynthConstants.PRESSED) != 0 || (context.getComponentState() & SynthConstants.SELECTED) != 0) { fg = DEFAULT_NORMAL_FG;
fg = DEFAULT_ACTIVE_FG; bg = DEFAULT_NORMAL_FG;
bg = DEFAULT_ACTIVE_FG;
} else if ((context.getComponentState() & SynthConstants.DISABLED) != 0) {
fg = DISABLED_FG;
bg = DISABLED_BG;
} else if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0) {
fg = DEFAULT_PRELIGHT_FG;
bg = DEFAULT_PRELIGHT_FG;
} else {
fg = DEFAULT_NORMAL_FG;
bg = DEFAULT_NORMAL_FG;
}
} }
g2.setColor(fg[0]); g2.setColor(fg[0]);
Rectangle2D fgshape = new Rectangle2D.Float(x, y, w, h); Rectangle2D fgshape = new Rectangle2D.Float(x, y, w, h);

View File

@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Lesser General Public * You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package org.jackhuang.hellominecraft.lookandfeel.painter; package org.jackhuang.hellominecraft.lookandfeel.painter;
import javax.swing.plaf.synth.SynthContext; import javax.swing.plaf.synth.SynthContext;
@@ -37,12 +37,13 @@ public class TextFieldPainter extends SynthPainter {
private boolean fill = true; private boolean fill = true;
private static final Color disabled = GraphicsUtils.getWebColor("F3F3F3"), private static final Color DISABLED = GraphicsUtils.getWebColor("F3F3F3"),
normal = GraphicsUtils.getWebColor("CCCCCC"), NORMAL = GraphicsUtils.getWebColor("CCCCCC"),
focused = GraphicsUtils.getWebColor("000000"), FOCUSED = GraphicsUtils.getWebColor("000000"),
over = GraphicsUtils.getWebColor("7F7F7F"); OVER = GraphicsUtils.getWebColor("7F7F7F");
public TextFieldPainter() {} public TextFieldPainter() {
}
public TextFieldPainter(boolean fill) { public TextFieldPainter(boolean fill) {
this.fill = fill; this.fill = fill;
@@ -55,16 +56,15 @@ public class TextFieldPainter extends SynthPainter {
g.setColor(Color.WHITE); g.setColor(Color.WHITE);
g.fillRect(x, y, w, h); g.fillRect(x, y, w, h);
} }
Color color = null; Color color;
if((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0) { if ((context.getComponentState() & SynthConstants.MOUSE_OVER) != 0)
color = over; color = OVER;
} else if((context.getComponentState() & SynthConstants.DISABLED) != 0) { else if ((context.getComponentState() & SynthConstants.DISABLED) != 0)
color = disabled; color = DISABLED;
} else if((context.getComponentState() & SynthConstants.FOCUSED) != 0) { else if ((context.getComponentState() & SynthConstants.FOCUSED) != 0)
color = focused; color = FOCUSED;
} else { else
color = normal; color = NORMAL;
}
g.setColor(color); g.setColor(color);
g.drawLine(x, y, x + w, y); g.drawLine(x, y, x + w, y);
g.drawLine(x, y, x, y + w); g.drawLine(x, y, x, y + w);

View File

@@ -27,10 +27,10 @@ import java.awt.event.MouseEvent;
*/ */
public class ComboBoxUI extends BasicComboBoxUI implements MouseListener { public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
private static final BufferedImage combo_normal = loadImage("combo_normal.png"); private static final BufferedImage COMBO_NORMAL = loadImage("combo_normal.png");
private static final BufferedImage combo_over = loadImage("combo_over.png"); private static final BufferedImage COMBO_OVER = loadImage("combo_over.png");
private static final BufferedImage combo_pressed = loadImage("combo_pressed.png"); private static final BufferedImage COMBO_PRESSED = loadImage("combo_pressed.png");
private static final BufferedImage combo_disabled = loadImage("combo_disabled.png"); private static final BufferedImage COMBO_DISABLED = loadImage("combo_disabled.png");
private static final Dimension BTN_SIZE = new Dimension(17, 20); private static final Dimension BTN_SIZE = new Dimension(17, 20);
private final Dimension btnSize = new Dimension(BTN_SIZE); private final Dimension btnSize = new Dimension(BTN_SIZE);
@@ -39,6 +39,7 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
* method that all UI deligates must have. * method that all UI deligates must have.
* *
* @param c The component that the UI is for * @param c The component that the UI is for
*
* @return a new instance of NimbusComboBoxUI * @return a new instance of NimbusComboBoxUI
*/ */
public static ComponentUI createUI(JComponent c) { public static ComponentUI createUI(JComponent c) {
@@ -66,13 +67,13 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
/** /**
* The minumum size is the size of the display area plus insets plus the * The minumum size is the size of the display area plus insets plus the
* button. * button.
*
* @return the size yeah. * @return the size yeah.
*/ */
@Override @Override
public Dimension getMinimumSize(JComponent c) { public Dimension getMinimumSize(JComponent c) {
if (!isMinimumSizeDirty) { if (!isMinimumSizeDirty)
return new Dimension(cachedMinimumSize); return new Dimension(cachedMinimumSize);
}
Dimension size = getDisplaySize(); Dimension size = getDisplaySize();
Insets insets = getInsets(); Insets insets = getInsets();
btnSize.height = size.height = Math.max(size.height, BTN_SIZE.height); btnSize.height = size.height = Math.max(size.height, BTN_SIZE.height);
@@ -92,17 +93,16 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
@Override @Override
protected void paintComponent(Graphics g) { protected void paintComponent(Graphics g) {
if (comboBox.isEditable()) { if (comboBox.isEditable()) {
BufferedImage img = combo_normal; BufferedImage img = COMBO_NORMAL;
if (mouseDown) { if (mouseDown)
img = combo_pressed; img = COMBO_PRESSED;
} else if (!comboBox.isEnabled()) { else if (!comboBox.isEnabled())
img = combo_normal; img = COMBO_NORMAL;
} else if (mouseInside) { else if (mouseInside)
img = combo_over; img = COMBO_OVER;
}
g.drawImage(img, g.drawImage(img,
0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(),
0, 0, img.getWidth(), img.getHeight(), comboBox); 0, 0, img.getWidth(), img.getHeight(), comboBox);
} }
} }
}; };
@@ -125,32 +125,30 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
((JComponent) renderer).setForeground(comboBox.getForeground()); ((JComponent) renderer).setForeground(comboBox.getForeground());
} }
paintCurrentValue(g, rectangleForCurrentValue(), false); paintCurrentValue(g, rectangleForCurrentValue(), false);
if (renderer instanceof JComponent) { if (renderer instanceof JComponent)
((JComponent) renderer).setOpaque(true); ((JComponent) renderer).setOpaque(true);
}
} }
} }
@Override @Override
public void paintCurrentValueBackground(Graphics g, Rectangle bounds, boolean hasFocus) { public void paintCurrentValueBackground(Graphics g, Rectangle bounds, boolean hasFocus) {
if (!comboBox.isEditable()) { if (!comboBox.isEditable()) {
BufferedImage img = combo_normal; BufferedImage img = COMBO_NORMAL;
if (!comboBox.isEnabled()) { if (!comboBox.isEnabled())
img = combo_disabled; img = COMBO_DISABLED;
} else if (mouseDown) { else if (mouseDown)
img = combo_pressed; img = COMBO_PRESSED;
} else if (mouseInside) { else if (mouseInside)
img = combo_over; img = COMBO_OVER;
}
g.drawImage(img, g.drawImage(img,
bounds.x, bounds.y, bounds.x + 4, bounds.y + bounds.height, bounds.x, bounds.y, bounds.x + 4, bounds.y + bounds.height,
0, 0, 1, 26, comboBox); 0, 0, 1, 26, comboBox);
g.drawImage(img, g.drawImage(img,
bounds.x + 1, bounds.y, bounds.x + bounds.width - 25, bounds.y + bounds.height, bounds.x + 1, bounds.y, bounds.x + bounds.width - 25, bounds.y + bounds.height,
1, 0, 3, 26, comboBox); 1, 0, 3, 26, comboBox);
g.drawImage(img, g.drawImage(img,
bounds.x + bounds.width - 25, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height, bounds.x + bounds.width - 25, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height,
4, 0, 29, 26, comboBox); 4, 0, 29, 26, comboBox);
} else { } else {
/*g.setColor(Color.WHITE); /*g.setColor(Color.WHITE);
g.fillRect(bounds.x, bounds.y, bounds.width - btnSize.width, bounds.height - 1); g.fillRect(bounds.x, bounds.y, bounds.width - btnSize.width, bounds.height - 1);
@@ -194,9 +192,8 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
@Override @Override
public void mouseEntered(MouseEvent e) { public void mouseEntered(MouseEvent e) {
if (comboBox.isEditable()) { if (comboBox.isEditable()) {
if (e.getComponent() == arrowButton) { if (e.getComponent() == arrowButton)
mouseInside = true; mouseInside = true;
}
} else { } else {
mouseInside = true; mouseInside = true;
comboBox.repaint(); comboBox.repaint();
@@ -206,9 +203,8 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
@Override @Override
public void mouseExited(MouseEvent e) { public void mouseExited(MouseEvent e) {
if (comboBox.isEditable()) { if (comboBox.isEditable()) {
if (e.getComponent() == arrowButton) { if (e.getComponent() == arrowButton)
mouseInside = false; mouseInside = false;
}
} else { } else {
mouseInside = false; mouseInside = false;
comboBox.repaint(); comboBox.repaint();
@@ -218,9 +214,8 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
@Override @Override
public void mousePressed(MouseEvent e) { public void mousePressed(MouseEvent e) {
if (comboBox.isEditable()) { if (comboBox.isEditable()) {
if (e.getComponent() == arrowButton) { if (e.getComponent() == arrowButton)
mouseDown = true; mouseDown = true;
}
} else { } else {
mouseDown = true; mouseDown = true;
comboBox.repaint(); comboBox.repaint();
@@ -230,9 +225,8 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
@Override @Override
public void mouseReleased(MouseEvent e) { public void mouseReleased(MouseEvent e) {
if (comboBox.isEditable()) { if (comboBox.isEditable()) {
if (e.getComponent() == arrowButton) { if (e.getComponent() == arrowButton)
mouseDown = false; mouseDown = false;
}
} else { } else {
mouseDown = false; mouseDown = false;
comboBox.repaint(); comboBox.repaint();
@@ -269,16 +263,14 @@ public class ComboBoxUI extends BasicComboBoxUI implements MouseListener {
Insets insets = getInsets(); Insets insets = getInsets();
Rectangle cvb; Rectangle cvb;
if (arrowButton != null) { if (arrowButton != null)
if (cb.getComponentOrientation().isLeftToRight()) { if (cb.getComponentOrientation().isLeftToRight())
arrowButton.setBounds(width - (insets.right + btnSize.width), arrowButton.setBounds(width - (insets.right + btnSize.width),
insets.top, insets.top,
btnSize.width, btnSize.height); btnSize.width, btnSize.height);
} else { else
arrowButton.setBounds(insets.left, insets.top, arrowButton.setBounds(insets.left, insets.top,
btnSize.width, btnSize.height); btnSize.width, btnSize.height);
}
}
if (editor != null) { if (editor != null) {
cvb = rectangleForCurrentValue(); cvb = rectangleForCurrentValue();
editor.setBounds(cvb.x, cvb.y, cvb.width, cvb.height); editor.setBounds(cvb.x, cvb.y, cvb.width, cvb.height);