entry : unusedResources.entrySet()) {
+ table.addTableItem(new UnusedFileTableItem(entry.getValue()));
}
table.tableComplete();
resultFrame = new ChildFrame("Result", true);
@@ -206,7 +172,7 @@ public void run() {
panel.add(bopen);
panel.add(bopennew);
panel.add(bsave);
- JLabel count = new JLabel(table.getRowCount() + " unused " + checkType + "s found", SwingConstants.CENTER);
+ JLabel count = new JLabel(table.getRowCount() + " unused resources found", SwingConstants.CENTER);
count.setFont(count.getFont().deriveFont(count.getFont().getSize() + 2.0f));
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.getViewport().setBackground(table.getBackground());
@@ -280,11 +246,9 @@ private void checkDialog(DlgResource dialog) {
checkCode(compiler.getCode(), type);
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
- } else if (checkType.equalsIgnoreCase("WAV") && (entry instanceof State || entry instanceof Transition)) {
+ } else if (checkTypes.contains("WAV") && (entry instanceof State || entry instanceof Transition)) {
for (final StructEntry e : ((AbstractStruct) entry).getFlatFields()) {
if (e instanceof StringRef) {
checkSound((StringRef) e);
@@ -298,9 +262,7 @@ private void checkScript(BcsResource script) {
try {
checkCode(script.getCode(), ScriptType.BCS);
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
@@ -308,7 +270,7 @@ private void checkStruct(AbstractStruct struct) {
for (final StructEntry entry : struct.getFlatFields()) {
if (entry instanceof ResourceRef) {
checkResourceRef((ResourceRef) entry);
- } else if (checkType.equalsIgnoreCase("WAV") && entry instanceof StringRef) {
+ } else if (checkTypes.contains("WAV") && entry instanceof StringRef) {
checkSound((StringRef) entry);
}
}
@@ -317,7 +279,9 @@ private void checkStruct(AbstractStruct struct) {
private void checkTextfile(PlainTextResource text) {
final Matcher m = RESREF_PATTERN.matcher(text.getText());
while (m.find()) {
- removeEntries(m.group() + '.' + checkType);
+ for (final String checkType : checkTypes) {
+ removeEntries(m.group() + '.' + checkType);
+ }
}
}
@@ -338,13 +302,16 @@ private void checkCode(String compiledCode, ScriptType type) throws Exception {
synchronized (unusedResources) {
for (final ResourceEntry entry : decompiler.getResourcesUsed()) {
- unusedResources.remove(entry);
+ unusedResources.remove(entry.getResourceName());
+ }
+ for (final int strref : decompiler.getStringRefsUsed()) {
+ checkSound(strref);
}
}
}
/**
- * If type (a.k.a. extension) of the resource equals to the {@link #checkType type of checking resources}, removes
+ * If type (a.k.a. extension) of the resource equals to the {@link #checkTypes} type of checking resources, removes
* specified resource name from {@link #unusedResources}, otherwise do nothing.
*
* This method can be called from several threads
@@ -352,7 +319,8 @@ private void checkCode(String compiledCode, ScriptType type) throws Exception {
* @param ref Reference to the resource for checking
*/
private void checkResourceRef(ResourceRef ref) {
- if (checkType.equalsIgnoreCase(ref.getType())) {
+ final String type = ref.getType().toUpperCase();
+ if (checkTypes.contains(type)) {
removeEntries(ref.getResourceName());
}
}
@@ -366,9 +334,22 @@ private void checkResourceRef(ResourceRef ref) {
* @param ref Reference to entry in string table that contains sound file name
*/
private void checkSound(StringRef ref) {
- final int index = ref.getValue();
- if (index >= 0) {
- final String wav = StringTable.getSoundResource(index);
+ if (ref != null) {
+ checkSound(ref.getValue());
+ }
+ }
+
+ /**
+ * If string reference has the associated sound, removes this sound from {@link #unusedResources}, otherwise do
+ * nothing.
+ *
+ * This method can be called from several threads
+ *
+ * @param ref Reference to entry in string table that contains sound file name
+ */
+ private void checkSound(int strref) {
+ if (strref >= 0) {
+ final String wav = StringTable.getSoundResource(strref);
if (!wav.isEmpty()) {
removeEntries(wav + ".WAV");
}
@@ -384,12 +365,7 @@ private void checkSound(StringRef ref) {
*/
private void removeEntries(String name) {
synchronized (unusedResources) {
- for (final Iterator it = unusedResources.iterator(); it.hasNext();) {
- if (it.next().getResourceName().equalsIgnoreCase(name)) {
- it.remove();
- break;
- }
- }
+ unusedResources.remove(name);
}
}
diff --git a/src/org/infinity/check/ScriptChecker.java b/src/org/infinity/check/ScriptChecker.java
index 096dc2b99..7f43d1256 100644
--- a/src/org/infinity/check/ScriptChecker.java
+++ b/src/org/infinity/check/ScriptChecker.java
@@ -42,6 +42,7 @@
import org.infinity.resource.bcs.ScriptMessage;
import org.infinity.resource.key.ResourceEntry;
import org.infinity.search.AbstractSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/** Performs checking {@link BcsResource BCS} & {@code BS} resources. */
@@ -227,22 +228,20 @@ protected Runnable newWorker(ResourceEntry entry) {
final Compiler compiler = new Compiler(decompiler.decompile());
compiler.compile();
- synchronized (errorTable) {
+ synchronized (this) {
for (final ScriptMessage sm : compiler.getErrors()) {
errorTable.addTableItem(
new ScriptErrorsTableLine(entry, sm.getLine(), sm.getMessage(), ScriptErrorsTableLine.Type.ERROR));
}
}
- synchronized (warningTable) {
+ synchronized (this) {
for (final ScriptMessage sm : compiler.getWarnings()) {
warningTable.addTableItem(
new ScriptErrorsTableLine(entry, sm.getLine(), sm.getMessage(), ScriptErrorsTableLine.Type.WARNING));
}
}
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
advanceProgress();
};
diff --git a/src/org/infinity/check/StringDuplicatesChecker.java b/src/org/infinity/check/StringDuplicatesChecker.java
index a056bda03..5d5c0686b 100644
--- a/src/org/infinity/check/StringDuplicatesChecker.java
+++ b/src/org/infinity/check/StringDuplicatesChecker.java
@@ -14,7 +14,6 @@
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -227,23 +226,13 @@ public StringSet() {
/** Registers the specified strref in the string set. */
public void register(int strref) {
final String s = getInternalString(strref);
- List list = strings.get(s);
- if (list == null) {
- list = new ArrayList<>();
- strings.put(s, list);
- }
+ List list = strings.computeIfAbsent(s, k -> new ArrayList<>());
list.add(strref);
}
/** Removes all entries without duplicates. */
public void cleanup() {
- final Iterator>> iter = strings.entrySet().iterator();
- while (iter.hasNext()) {
- final Map.Entry> entry = iter.next();
- if (entry.getValue().size() < 2) {
- iter.remove();
- }
- }
+ strings.entrySet().removeIf(entry -> entry.getValue().size() < 2);
}
/** Returns the number of duplicate string instances. */
@@ -271,7 +260,6 @@ private String getInternalString(int strref) {
/**
* Returns a normalized version of the given string.
- *
* A {@code null} string reference returns an empty string. Otherwise, whitespace is trimmed from the given string.
*
* @param s String to normalize.
diff --git a/src/org/infinity/check/StringSoundsChecker.java b/src/org/infinity/check/StringSoundsChecker.java
index df67786c1..cf0639225 100644
--- a/src/org/infinity/check/StringSoundsChecker.java
+++ b/src/org/infinity/check/StringSoundsChecker.java
@@ -148,8 +148,8 @@ public void run() {
new Class>[] { Integer.class, String.class, String.class },
new Integer[] { 25, 600, 50 });
List list = stringMap.get(StringTable.Type.MALE);
- for (int i = 0, size = list.size(); i < size; i++) {
- table.addTableItem(new StringSoundsItem(list.get(i), StringTable.Type.MALE));
+ for (Integer integer : list) {
+ table.addTableItem(new StringSoundsItem(integer, StringTable.Type.MALE));
}
// Female string table is presented in a separate tab, if available
@@ -158,8 +158,8 @@ public void run() {
new Class>[] { Integer.class, String.class, String.class },
new Integer[] { 25, 600, 50 });
list = stringMap.get(StringTable.Type.FEMALE);
- for (int i = 0, size = list.size(); i < size; i++) {
- tableFemale.addTableItem(new StringSoundsItem(list.get(i), StringTable.Type.FEMALE));
+ for (Integer integer : list) {
+ tableFemale.addTableItem(new StringSoundsItem(integer, StringTable.Type.FEMALE));
}
}
diff --git a/src/org/infinity/check/StringUseChecker.java b/src/org/infinity/check/StringUseChecker.java
index 93623347c..95d8aed57 100644
--- a/src/org/infinity/check/StringUseChecker.java
+++ b/src/org/infinity/check/StringUseChecker.java
@@ -55,6 +55,7 @@
import org.infinity.search.SearchClient;
import org.infinity.search.SearchMaster;
import org.infinity.search.StringReferenceSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.LuaEntry;
import org.infinity.util.LuaParser;
import org.infinity.util.Misc;
@@ -375,9 +376,7 @@ private void checkDialog(DlgResource dialog) {
checkCode(compiler.getCode(), type);
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
}
@@ -387,9 +386,7 @@ private void checkScript(BcsResource script) {
try {
checkCode(script.getCode(), ScriptType.BCS);
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
@@ -516,7 +513,7 @@ private void updateStringUsed(long strref) {
if (strref >= 0 && strref < Integer.MAX_VALUE) {
final int index = StringTable.getTranslatedIndex((int)strref);
if (index >= 0 && index < strUsed.length && !strUsed[index]) {
- synchronized (strUsed) {
+ synchronized (this) {
strUsed[index] = true;
}
}
@@ -550,7 +547,7 @@ private void checkBestiaryLua() {
}
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -572,6 +569,7 @@ private Number toNumber(String s) {
}
retVal = Long.parseLong(s, radix);
} catch (Exception e) {
+ Logger.trace(e);
}
}
diff --git a/src/org/infinity/check/StringValidationChecker.java b/src/org/infinity/check/StringValidationChecker.java
index c5dff6629..1c51c4f31 100644
--- a/src/org/infinity/check/StringValidationChecker.java
+++ b/src/org/infinity/check/StringValidationChecker.java
@@ -52,6 +52,7 @@
import org.infinity.resource.key.FileResourceEntry;
import org.infinity.resource.key.ResourceEntry;
import org.infinity.search.AbstractSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
import org.infinity.util.io.StreamUtils;
@@ -82,9 +83,7 @@ public void run() {
final Path path = Profile.getProperty(key);
if (path != null) {
final ResourceEntry entry = new FileResourceEntry(path);
- if (entry != null) {
- files.add(entry);
- }
+ files.add(entry);
}
}
@@ -257,17 +256,13 @@ protected Runnable newWorker(ResourceEntry entry) {
try {
validateInput(decoder, inBuf, outBuf, entry, idx, isFemale);
} catch (IllegalStateException | CoderMalfunctionError e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
decoder.reset();
}
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
advanceProgress();
@@ -302,7 +297,7 @@ private void validateInputUnicode(CharsetDecoder decoder, ByteBuffer inBuf, Char
while (lenString > 0) {
final CoderResult cr = decoder.decode(inBuf, outBuf, true);
if (cr.isError()) {
- synchronized (table) {
+ synchronized (this) {
final String text = StringTable.getStringRef(isFemale ? StringTable.Type.FEMALE : StringTable.Type.MALE,
strref);
final String infoBytes = (cr.length() == 1) ? " byte" : " bytes";
@@ -350,7 +345,7 @@ private void validateInputAnsi(CharsetDecoder decoder, ByteBuffer inBuf, CharBuf
final char ch1 = textAnsi.charAt(ofs);
final char ch2 = textUtf8.charAt(ofs);
if (ch1 != ch2) {
- synchronized(table) {
+ synchronized(this) {
final String msg = "Possible encoding error found at offset " + ofs;
table.addTableItem(new StringErrorTableItem(entry, strref, textAnsi, msg));
isError = true;
@@ -359,7 +354,7 @@ private void validateInputAnsi(CharsetDecoder decoder, ByteBuffer inBuf, CharBuf
}
if (!isError && textAnsi.length() > textUtf8.length()) {
- synchronized (table) {
+ synchronized (this) {
final String msg = "Possible encoding error found at offset " + textUtf8.length();
table.addTableItem(new StringErrorTableItem(entry, strref, textAnsi, msg));
}
@@ -435,8 +430,6 @@ public Object getObjectAt(int columnIndex) {
switch (columnIndex) {
case 0:
return resource;
- case 1:
- return strref;
case 2:
return text;
case 3:
diff --git a/src/org/infinity/check/StrrefIndexChecker.java b/src/org/infinity/check/StrrefIndexChecker.java
index 18c9edc9c..390ebf19f 100644
--- a/src/org/infinity/check/StrrefIndexChecker.java
+++ b/src/org/infinity/check/StrrefIndexChecker.java
@@ -48,6 +48,7 @@
import org.infinity.resource.key.ResourceEntry;
import org.infinity.resource.text.PlainTextResource;
import org.infinity.search.StringReferenceSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
import org.infinity.util.Table2da;
@@ -60,7 +61,7 @@ public class StrrefIndexChecker extends AbstractChecker implements ListSelection
private final JButton bsave = new JButton("Save...", Icons.ICON_SAVE_16.getIcon());
/** List of the {@link StrrefEntry} objects. */
- private SortableTable table;
+ private final SortableTable table;
public StrrefIndexChecker() {
super("Find illegal strrefs", StringReferenceSearcher.FILE_TYPES);
@@ -217,9 +218,7 @@ private void checkDialog(DlgResource dialog) {
}
}
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
}
@@ -254,9 +253,7 @@ private void checkScript(BcsResource script) {
}
}
} catch (Exception e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
@@ -285,10 +282,9 @@ private void checkText(PlainTextResource text) {
}
final String[] lines = text.getText().split("\r?\n");
- for (int i = 0; i < lines.length; i++) {
- final Matcher matcher = StringReferenceSearcher.NUMBER_PATTERN.matcher(lines[i]);
+ for (int line = 0; line < lines.length; line++) {
+ final Matcher matcher = StringReferenceSearcher.NUMBER_PATTERN.matcher(lines[line]);
while (matcher.find()) {
- final int line = i;
final int pos = matcher.start();
final int len = matcher.end() - pos;
try {
@@ -302,9 +298,7 @@ private void checkText(PlainTextResource text) {
}
}
} catch (NumberFormatException e) {
- synchronized (System.err) {
- e.printStackTrace();
- }
+ Logger.error(e);
}
}
}
@@ -324,6 +318,7 @@ private void check2da(Table2da array) {
}
}
} catch (NumberFormatException e) {
+ Logger.trace(e);
}
// checking table content
@@ -341,6 +336,7 @@ private void check2da(Table2da array) {
}
}
} catch (NumberFormatException e) {
+ Logger.trace(e);
}
}
}
diff --git a/src/org/infinity/check/StructChecker.java b/src/org/infinity/check/StructChecker.java
index 320639028..9b50d5259 100644
--- a/src/org/infinity/check/StructChecker.java
+++ b/src/org/infinity/check/StructChecker.java
@@ -12,7 +12,6 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
@@ -55,6 +54,7 @@
import org.infinity.resource.sto.ItemSale11;
import org.infinity.resource.wed.Overlay;
import org.infinity.resource.wed.Tilemap;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
@@ -326,15 +326,15 @@ private void search(ResourceEntry entry, AbstractStruct struct) {
if (entry.getExtension().equalsIgnoreCase("WED")) {
List list = getWedCorruption(entry, struct);
synchronized (table) {
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- table.addTableItem(iter.next());
+ for (Corruption corruption : list) {
+ table.addTableItem(corruption);
}
}
} else if (entry.getExtension().equalsIgnoreCase("STO")) {
List list = getStoCorruption(entry, struct);
synchronized (table) {
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- table.addTableItem(iter.next());
+ for (Corruption corruption : list) {
+ table.addTableItem(corruption);
}
}
}
@@ -385,7 +385,7 @@ private List getWedCorruption(ResourceEntry entry, AbstractStruct st
if (overlay == null) {
continue;
}
- int width = ((IsNumeric) overlay.getAttribute(ovlOfs + 0, false)).getValue();
+ int width = ((IsNumeric) overlay.getAttribute(ovlOfs, false)).getValue();
int height = ((IsNumeric) overlay.getAttribute(ovlOfs + 2, false)).getValue();
String tisName = ((IsReference) overlay.getAttribute(ovlOfs + 4, false)).getResourceName();
int tileStartOfs = ((IsNumeric) overlay.getAttribute(ovlOfs + 16, false)).getValue();
@@ -397,7 +397,7 @@ private List getWedCorruption(ResourceEntry entry, AbstractStruct st
// checking Overlay fields
boolean skip = false;
if (width <= 0) {
- list.add(new Corruption(entry, ovlOfs + 0, String.format("Overlay %d: Tileset width is <= 0", ovlIdx)));
+ list.add(new Corruption(entry, ovlOfs, String.format("Overlay %d: Tileset width is <= 0", ovlIdx)));
skip = true;
}
if (height <= 0) {
@@ -447,20 +447,20 @@ private List getWedCorruption(ResourceEntry entry, AbstractStruct st
}
// checking indices
for (int i = 0; i < numTiles; i++) {
- Tilemap tile = mapTiles.get(Integer.valueOf(i));
+ Tilemap tile = mapTiles.get(i);
if (tile != null) {
int tileOfs = tile.getOffset();
int tileIdx = (tileOfs - tileStartOfs) / tileSize;
- int tileIdxPri = ((IsNumeric) tile.getAttribute(tileOfs + 0, false)).getValue();
+ int tileIdxPri = ((IsNumeric) tile.getAttribute(tileOfs, false)).getValue();
int tileCountPri = ((IsNumeric) tile.getAttribute(tileOfs + 2, false)).getValue();
int tileIdxSec = ((IsNumeric) tile.getAttribute(tileOfs + 4, false)).getValue();
IsNumeric tileFlag = (IsNumeric) tile.getAttribute(tileOfs + 6, false);
int tileFlagValue = tileFlag.getValue();
for (int j = tileIdxPri, count = tileIdxPri + tileCountPri; j < count; j++) {
- Integer tileLookupIndex = mapIndices.get(Integer.valueOf(j));
+ Integer tileLookupIndex = mapIndices.get(j);
if (tileLookupIndex != null) {
if (tileLookupIndex >= tisInfo[0]) {
- list.add(new Corruption(entry, tileOfs + 0,
+ list.add(new Corruption(entry, tileOfs,
String.format("Overlay %d/Tilemap %d: Primary tile index %d " + "out of range [0..%d]", ovlIdx,
tileIdx, j, tisInfo[0] - 1)));
}
@@ -498,7 +498,7 @@ private void showInViewer(Corruption corruption, boolean newWindow) {
try {
((AbstractStruct) res).getViewer().selectEntry(offset);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
} else {
@@ -512,7 +512,7 @@ private void showInViewer(Corruption corruption, boolean newWindow) {
try {
((AbstractStruct) res).getViewer().selectEntry(offset);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
} else {
@@ -522,7 +522,7 @@ private void showInViewer(Corruption corruption, boolean newWindow) {
try {
((AbstractStruct) viewable).getViewer().selectEntry(offset);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
});
@@ -594,7 +594,7 @@ public StructInfo(String sig, String[] ver) {
/** Returns whether the signatures matches the signature of the current structure definition. */
public boolean isSignature(String sig) {
- return (sig != null) ? signature.equals(sig) : false;
+ return signature.equals(sig);
}
/** Returns whether the specified version is supported by the current structure definition. */
diff --git a/src/org/infinity/datatype/AbstractBitmap.java b/src/org/infinity/datatype/AbstractBitmap.java
index d0aed501b..0ef1a3f49 100644
--- a/src/org/infinity/datatype/AbstractBitmap.java
+++ b/src/org/infinity/datatype/AbstractBitmap.java
@@ -88,10 +88,10 @@ public class AbstractBitmap extends Datatype implements Editable, IsNumeric {
private final TreeMap itemMap;
private final List buttonList;
+ private final JButton bUpdate;
private BiFunction formatter;
private TextListPanel> list;
- private JButton bUpdate;
private long value;
private boolean signed;
private boolean sortByName;
@@ -311,9 +311,8 @@ public boolean equals(Object o) {
// taking care of signedness
long mask = (1L << (getSize() * 8)) - 1L;
- boolean retVal = ((value & mask) == (other.value & mask));
- return retVal;
+ return ((value & mask) == (other.value & mask));
}
/** Returns the TextListPanel control used by this datatype. */
@@ -348,7 +347,7 @@ public Long getSelectedValue() {
* @return the data object associated with the numeric value, {@code null} otherwise.
*/
public T getDataOf(long value) {
- return itemMap.get(Long.valueOf(value));
+ return itemMap.get(value);
}
/**
@@ -359,7 +358,7 @@ public T getDataOf(long value) {
*/
public String toString(long value) {
Long number = value;
- T data = itemMap.get(Long.valueOf(value));
+ T data = itemMap.get(value);
return formatter.apply(number, data);
}
@@ -474,7 +473,6 @@ protected void listItemChanged() {
* Helper method: returns the specified number in hexadecimal notation.
*
* @param value the value to return as hexadecimal representation.
- * @param size size of the value in bytes.
* @return String containing hexadecimal notation of the specified value.
*/
protected String getHexValue(long value) {
diff --git a/src/org/infinity/datatype/AreResourceRef.java b/src/org/infinity/datatype/AreResourceRef.java
index f2dd49478..0107b7758 100644
--- a/src/org/infinity/datatype/AreResourceRef.java
+++ b/src/org/infinity/datatype/AreResourceRef.java
@@ -47,8 +47,8 @@ public AreResourceRef(ByteBuffer buffer, int offset, String name, AreResource ar
}
// ResourceEntry entry = ResourceFactory.getInstance().getResourceEntry(getResourceName());
// if (!isLegalEntry(entry)) {
-// System.out.println("Illegal: " + entry + " from " + entry.getActualFile());
-// System.out.println("In: " + are.getResourceEntry() + " from " + are.getResourceEntry().getActualFile());
+// Logger.info("Illegal: {} from {}", entry, entry.getActualFile());
+// Logger.info("In: {} from {}", are.getResourceEntry(), are.getResourceEntry().getActualFile());
// }
}
diff --git a/src/org/infinity/datatype/Bestiary.java b/src/org/infinity/datatype/Bestiary.java
index 75fbc89aa..b5678de8f 100644
--- a/src/org/infinity/datatype/Bestiary.java
+++ b/src/org/infinity/datatype/Bestiary.java
@@ -65,6 +65,7 @@
import org.infinity.util.IniMapCache;
import org.infinity.util.IniMapEntry;
import org.infinity.util.IniMapSection;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
@@ -809,18 +810,17 @@ private static List readCreatures() {
private static List readCreatures(String filename, IniMap ini) {
final IniMapSection init = ini.getSection("init");
if (init == null) {
- System.err.println(filename + ": [init] section not found in the file. Creatures not loaded");
+ Logger.warn("{}: [init] section not found in the file. Creatures not loaded", filename);
return Collections.emptyList();
}
final IniMapEntry entry = init.getEntry("beastcount");
if (entry == null) {
- System.err.println(filename + ": \"beastcount\" key in [init] section not found. Creatures not loaded");
+ Logger.warn("{}: \"beastcount\" key in [init] section not found. Creatures not loaded", filename);
return Collections.emptyList();
}
final Integer count = entry.getIntValue();
if (count == null) {
- System.err.println(filename + ": \"beastcount\" key in [init] section: expected integer buf found "
- + entry.getValue() + ". Creatures not loaded");
+ Logger.warn("{}: \"beastcount\" key in [init] section: expected integer but found {}. Creatures not loaded.", filename, entry.getValue());
return Collections.emptyList();
}
@@ -833,8 +833,7 @@ private static List readCreatures(String filename, IniMap ini) {
continue;
}
if (i < 0 || i >= 256) {
- System.err.println(
- filename + ": invalid creature number " + i + ", expected number in range [0; 256]. Creature skipped");
+ Logger.warn("{}: invalid creature number {}, expected number in range [0; 256]. Creature skipped.", filename, i);
continue;
}
result.ensureCapacity(i);
diff --git a/src/org/infinity/datatype/ColorPicker.java b/src/org/infinity/datatype/ColorPicker.java
index de9ec9a39..75a474029 100644
--- a/src/org/infinity/datatype/ColorPicker.java
+++ b/src/org/infinity/datatype/ColorPicker.java
@@ -37,6 +37,7 @@
import org.infinity.icon.Icons;
import org.infinity.resource.AbstractStruct;
import org.infinity.resource.graphics.ColorConvert;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/**
@@ -150,7 +151,7 @@ public JComponent edit(ActionListener container) {
tfBri = new JTextField(4); // range: [0..100]
tfBri.addFocusListener(this);
- JLabel lHue2 = new JLabel("\u00B0");
+ JLabel lHue2 = new JLabel("°");
JLabel lSat2 = new JLabel("%");
JLabel lBri2 = new JLabel("%");
@@ -541,6 +542,7 @@ private int validateNumberInput(JTextField tf, int oldVal, int min, int max) {
oldVal = max;
}
} catch (NumberFormatException nfe) {
+ Logger.trace(nfe);
}
tf.setText(Integer.toString(oldVal));
}
diff --git a/src/org/infinity/datatype/ColorValue.java b/src/org/infinity/datatype/ColorValue.java
index 31fdcb377..bebf7ab72 100644
--- a/src/org/infinity/datatype/ColorValue.java
+++ b/src/org/infinity/datatype/ColorValue.java
@@ -58,6 +58,7 @@
import org.infinity.util.IdsMap;
import org.infinity.util.IdsMapCache;
import org.infinity.util.IdsMapEntry;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.Table2da;
import org.infinity.util.Table2daCache;
@@ -282,7 +283,7 @@ public boolean equals(Object obj) {
* Returns the name associated with the specified color entry. Returns {@code null} if no name is available.
*/
public String getColorName(int index) {
- String retVal = randomColors.get(Integer.valueOf(index));
+ String retVal = randomColors.get(index);
if (retVal == null) {
retVal = lookupColorName(colorMap, index, true);
}
@@ -421,7 +422,7 @@ private void initEntries(int defaultWidth, int defaultHeight) {
for (int idx = 0; idx <= maxValue; idx++) {
BufferedImage range;
- if (!colorValue.randomColors.containsKey(Integer.valueOf(idx)) && idx < image.getHeight()) {
+ if (!colorValue.randomColors.containsKey(idx) && idx < image.getHeight()) {
// fixed color
range = getFixedColor(image, idx, defaultWidth, defaultHeight);
} else {
@@ -431,7 +432,7 @@ private void initEntries(int defaultWidth, int defaultHeight) {
colors.add(range);
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -463,7 +464,7 @@ private BufferedImage getVirtualColor(int index, int width, int height) {
BufferedImage retVal = null;
Color invalidColor = new Color(0xe0e0e0);
- boolean isRandom = colorValue.randomColors.containsKey(Integer.valueOf(index));
+ boolean isRandom = colorValue.randomColors.containsKey(index);
retVal = new BufferedImage(12 * width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = retVal.createGraphics();
try {
diff --git a/src/org/infinity/datatype/Datatype.java b/src/org/infinity/datatype/Datatype.java
index f37d35e03..aa357fb52 100644
--- a/src/org/infinity/datatype/Datatype.java
+++ b/src/org/infinity/datatype/Datatype.java
@@ -17,6 +17,7 @@
import org.infinity.resource.AbstractStruct;
import org.infinity.resource.StructEntry;
+import org.infinity.util.Logger;
import org.infinity.util.io.ByteBufferOutputStream;
import org.infinity.util.io.StreamUtils;
@@ -152,7 +153,7 @@ public ByteBuffer getDataBuffer() {
try (ByteBufferOutputStream bbos = new ByteBufferOutputStream(bb)) {
write(bbos);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
bb.position(0);
return bb;
diff --git a/src/org/infinity/datatype/DecNumber.java b/src/org/infinity/datatype/DecNumber.java
index 9bb9d38e9..5fa670c7c 100644
--- a/src/org/infinity/datatype/DecNumber.java
+++ b/src/org/infinity/datatype/DecNumber.java
@@ -12,6 +12,7 @@
import java.util.Objects;
import org.infinity.resource.AbstractStruct;
+import org.infinity.util.Logger;
/**
* Field that represents numerical value which is usually edited in a decimal mode.
@@ -25,8 +26,9 @@
*
*/
public class DecNumber extends Datatype implements InlineEditable, IsNumeric {
+ private final boolean signed;
+
private long number;
- private boolean signed;
public DecNumber(ByteBuffer buffer, int offset, int length, String name) {
this(buffer, offset, length, name, true);
@@ -52,7 +54,7 @@ public boolean update(Object value) {
}
return true;
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
@@ -93,7 +95,7 @@ public int read(ByteBuffer buffer, int offset) {
if (signed) {
number = buffer.getInt();
} else {
- number = buffer.getInt() & 0xffffffff;
+ number = buffer.getInt() & 0xffffffffL;
}
break;
default:
@@ -173,7 +175,7 @@ public static long parseNumber(Object value, int size, boolean negativeAllowed,
if (value instanceof IsTextual) {
s = ((IsTextual) value).getText();
} else {
- s = (value != null) ? value.toString() : "";
+ s = value.toString();
}
s = s.toLowerCase(Locale.ENGLISH);
diff --git a/src/org/infinity/datatype/Editable.java b/src/org/infinity/datatype/Editable.java
index 860d799c0..0282559b2 100644
--- a/src/org/infinity/datatype/Editable.java
+++ b/src/org/infinity/datatype/Editable.java
@@ -20,7 +20,7 @@ public interface Editable extends StructEntry {
/**
* Used to create and setup editor for this object.
*
- * @param container
+ * @param container {@link ActionListener} of the parent structure that contains this {@code Editable} instance.
* @return Component that will be used to edit this object. Must not be {@code null}
*/
JComponent edit(ActionListener container);
diff --git a/src/org/infinity/datatype/EffectType.java b/src/org/infinity/datatype/EffectType.java
index 89f5e4795..6dc7962a3 100644
--- a/src/org/infinity/datatype/EffectType.java
+++ b/src/org/infinity/datatype/EffectType.java
@@ -12,6 +12,7 @@
import org.infinity.resource.AbstractStruct;
import org.infinity.resource.StructEntry;
import org.infinity.resource.effects.BaseOpcode;
+import org.infinity.util.Logger;
public final class EffectType extends Bitmap implements UpdateListener {
// EffectType-specific field labels
@@ -42,7 +43,7 @@ public boolean updateValue(AbstractStruct struct) {
struct.addFields(this, list);
return true;
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
@@ -56,7 +57,7 @@ public boolean valueUpdated(UpdateEvent event) {
try {
return BaseOpcode.updateOpcode(event.getStructure());
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
@@ -80,7 +81,7 @@ public int readAttributes(ByteBuffer buffer, int off, List list) {
try {
off = BaseOpcode.makeEffectStruct(getValue(), this, buffer, off, list, isV1);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
attrLength = off - attrLength;
return off;
diff --git a/src/org/infinity/datatype/Flag.java b/src/org/infinity/datatype/Flag.java
index 8005e50fe..42b860a2c 100644
--- a/src/org/infinity/datatype/Flag.java
+++ b/src/org/infinity/datatype/Flag.java
@@ -182,7 +182,7 @@ public int read(ByteBuffer buffer, int offset) {
value = buffer.getShort() & 0xffff;
break;
case 4:
- value = buffer.getInt() & 0xffffffff;
+ value = buffer.getInt() & 0xffffffffL;
break;
default:
throw new IllegalArgumentException();
diff --git a/src/org/infinity/datatype/FloatNumber.java b/src/org/infinity/datatype/FloatNumber.java
index 0514391c4..c39d2b02a 100644
--- a/src/org/infinity/datatype/FloatNumber.java
+++ b/src/org/infinity/datatype/FloatNumber.java
@@ -11,6 +11,7 @@
import java.util.Objects;
import org.infinity.resource.AbstractStruct;
+import org.infinity.util.Logger;
import org.infinity.util.io.StreamUtils;
/**
@@ -51,7 +52,7 @@ public boolean update(Object value) {
return true;
} catch (NumberFormatException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
diff --git a/src/org/infinity/datatype/HexNumber.java b/src/org/infinity/datatype/HexNumber.java
index 4fa09c440..3fe9e959c 100644
--- a/src/org/infinity/datatype/HexNumber.java
+++ b/src/org/infinity/datatype/HexNumber.java
@@ -6,6 +6,8 @@
import java.nio.ByteBuffer;
+import org.infinity.util.Logger;
+
public class HexNumber extends DecNumber {
public HexNumber(ByteBuffer buffer, int offset, int length, String desc) {
super(buffer, offset, length, desc);
@@ -19,7 +21,7 @@ public boolean update(Object value) {
setValue((int) DecNumber.parseNumber(value, getSize(), true, true));
return true;
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
diff --git a/src/org/infinity/datatype/IdsBitmap.java b/src/org/infinity/datatype/IdsBitmap.java
index 786aaaf50..9dc2a539f 100644
--- a/src/org/infinity/datatype/IdsBitmap.java
+++ b/src/org/infinity/datatype/IdsBitmap.java
@@ -6,6 +6,8 @@
import java.awt.event.ActionListener;
import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Locale;
import java.util.TreeMap;
import java.util.function.BiFunction;
@@ -25,6 +27,8 @@ public class IdsBitmap extends AbstractBitmap {
}
};
+ private static final HashMap> MAP_CACHE = new HashMap<>();
+
public IdsBitmap(ByteBuffer buffer, int offset, int length, String name, String resource) {
this(buffer, offset, length, name, resource, true, false, false);
}
@@ -63,8 +67,22 @@ public void addIdsMapEntry(IdsMapEntry entry) {
getBitmap().putIfAbsent(entry.getID(), entry);
}
+ public static void clearCache() {
+ MAP_CACHE.clear();
+ }
+
private static TreeMap createResourceList(String resource) {
TreeMap retVal = null;
+ if (resource == null) {
+ return retVal;
+ }
+
+ resource = resource.trim().toUpperCase(Locale.ENGLISH);
+ retVal = MAP_CACHE.get(resource);
+ if (retVal != null) {
+ return retVal;
+ }
+
IdsMap idsMap = IdsMapCache.get(resource);
if (idsMap != null) {
retVal = new TreeMap<>();
@@ -81,6 +99,8 @@ private static TreeMap createResourceList(String resource) {
retVal.put(0L, new IdsMapEntry(0L, "NONE"));
}
}
+
+ MAP_CACHE.put(resource, retVal);
}
return retVal;
}
diff --git a/src/org/infinity/datatype/ItemTypeBitmap.java b/src/org/infinity/datatype/ItemTypeBitmap.java
new file mode 100644
index 000000000..909050206
--- /dev/null
+++ b/src/org/infinity/datatype/ItemTypeBitmap.java
@@ -0,0 +1,140 @@
+// Near Infinity - An Infinity Engine Browser and Editor
+// Copyright (C) 2001 Jon Olav Hauglid
+// See LICENSE.txt for license information
+
+package org.infinity.datatype;
+
+import java.nio.ByteBuffer;
+import java.util.Locale;
+import java.util.TreeMap;
+
+import org.infinity.resource.Profile;
+import org.infinity.resource.ResourceFactory;
+import org.infinity.util.IdsMap;
+import org.infinity.util.IdsMapCache;
+import org.infinity.util.IdsMapEntry;
+import org.infinity.util.Logger;
+import org.infinity.util.Misc;
+import org.infinity.util.Table2da;
+import org.infinity.util.Table2daCache;
+
+/**
+ * Specialized {@link HashBitmap} that uses a mix of hardcoded entries and custom entries from ITEMTYPE.2DA
+ * if available.
+ */
+public class ItemTypeBitmap extends HashBitmap {
+ private static final String TABLE_NAME = "ITEMTYPE.2DA";
+
+ public static final String[] CATEGORIES_ARRAY = { "Miscellaneous", "Amulets and necklaces", "Armor",
+ "Belts and girdles", "Boots", "Arrows", "Bracers and gauntlets", "Headgear", "Keys", "Potions", "Rings",
+ "Scrolls", "Shields", "Food", "Bullets", "Bows", "Daggers", "Maces", "Slings", "Small swords", "Large swords",
+ "Hammers", "Morning stars", "Flails", "Darts", "Axes", "Quarterstaves", "Crossbows", "Hand-to-hand weapons",
+ "Spears", "Halberds", "Bolts", "Cloaks and robes", "Gold pieces", "Gems", "Wands", "Containers", "Books",
+ "Familiars", "Tattoos", "Lenses", "Bucklers", "Candles", "Child bodies", "Clubs", "Female bodies", "Keys (old)",
+ "Large shields", "Male bodies", "Medium shields", "Notes", "Rods", "Skulls", "Small shields", "Spider bodies",
+ "Telescopes", "Bottles", "Greatswords", "Bags", "Furs and pelts", "Leather armor", "Studded leather",
+ "Chain mail", "Splint mail", "Plate mail", "Full plate", "Hide armor", "Robes", "Scale mail", "Bastard swords",
+ "Scarves", "Rations", "Hats", "Gloves", "Eyeballs", "Earrings", "Teeth", "Bracelets" };
+
+ public static final String[] CATEGORIES11_ARRAY = { "Miscellaneous", "Amulets and necklaces", "Armor",
+ "Belts and girdles", "Boots", "Arrows", "Bracers and gauntlets", "Headgear", "Keys", "Potions", "Rings",
+ "Scrolls", "Shields", "Spells", "Bullets", "Bows", "Daggers", "Maces", "Slings", "Small swords", "Large swords",
+ "Hammers", "Morning stars", "Flails", "Darts", "Axes", "Quarterstaves", "Crossbows", "Hand-to-hand weapons",
+ "Greatswords", "Halberds", "Bolts", "Cloaks and robes", "Copper commons", "Gems", "Wands", "Eyeballs",
+ "Bracelets", "Earrings", "Tattoos", "Lenses", "Teeth" };
+
+ private static TreeMap CATEGORIES = null;
+
+ public ItemTypeBitmap(ByteBuffer buffer, int offset, int length, String name) {
+ super(buffer, offset, length, name, getItemCategories(), false, false);
+ }
+
+ /**
+ * Returns a list of available item categories. List entries depend on the detected game and may include
+ * static and dynamic elements.
+ *
+ * @return Map of strings with item categories.
+ */
+ public static TreeMap getItemCategories() {
+ synchronized (TABLE_NAME) {
+ if (Profile.isEnhancedEdition() && !Table2daCache.isCached(TABLE_NAME)) {
+ CATEGORIES = null;
+ }
+ if (CATEGORIES == null) {
+ CATEGORIES = buildCategories();
+ }
+ }
+ return CATEGORIES;
+ }
+
+ /** Rebuilds the list of item categories. */
+ private static TreeMap buildCategories() {
+ final TreeMap retVal = new TreeMap<>();
+ if (Profile.isEnhancedEdition() && ResourceFactory.resourceExists(TABLE_NAME)) {
+ final IdsMap slots = IdsMapCache.get("SLOTS.IDS");
+ final Table2da table = Table2daCache.get(TABLE_NAME);
+ final String baseName = "Extra category ";
+ int baseIndex = 1;
+ for (int row = 0, count = table.getRowCount(); row < count; row++) {
+ final String idxValue = table.get(row, 0);
+ final int radix = idxValue.startsWith("0x") ? 16 : 10;
+ String catName = "";
+ try {
+ int idx = Integer.parseInt(idxValue, radix);
+ if (idx >= 0 && idx < CATEGORIES_ARRAY.length) {
+ // looking up hardcoded category name
+ catName = CATEGORIES_ARRAY[idx];
+ } else {
+ // generating custom category name
+ catName = baseName + baseIndex;
+ baseIndex++;
+ }
+
+ // adding slot restriction if available
+ int slot = Misc.toNumber(table.get(row, 3), -1);
+ if (slot >= 0) {
+ final IdsMapEntry slotEntry = slots.get(slot);
+ if (slotEntry != null) {
+ final String slotName = beautifyString(slotEntry.getSymbol(), "SLOT");
+ if (slotName != null && !slotName.isEmpty()) {
+ catName = catName + " [" + slotName + " slot" + "]";
+ }
+ }
+ }
+
+ retVal.put((long) idx, catName);
+ } catch (NumberFormatException e) {
+ // skip entry with log message
+ Logger.warn("{}: Invalid index at row={} (value={})", TABLE_NAME, row, idxValue);
+ }
+ }
+ } else if (Profile.getEngine() == Profile.Engine.PST) {
+ // PST
+ for (long idx = 0, count = CATEGORIES11_ARRAY.length; idx < count; idx++) {
+ retVal.put(idx, CATEGORIES11_ARRAY[(int) idx]);
+ }
+ } else {
+ // Any non-EE games except PST
+ for (long idx = 0, count = CATEGORIES_ARRAY.length; idx < count; idx++) {
+ retVal.put(idx, CATEGORIES_ARRAY[(int) idx]);
+ }
+ }
+
+ return retVal;
+ }
+
+ private static String beautifyString(String s, String removedPrefix) {
+ String retVal = s;
+ if (retVal != null) {
+ retVal = retVal.replaceFirst(removedPrefix + "_?", "");
+ final String[] words = retVal.split("[ _]+");
+ for (int i = 0; i < words.length; i++) {
+ words[i] = words[i].charAt(0) + words[i].substring(1).toLowerCase(Locale.ENGLISH);
+ }
+ retVal = String.join(" ", words);
+ retVal = retVal.replaceFirst("(\\D)(\\d)", "$1 $2");
+ retVal = retVal.trim();
+ }
+ return retVal;
+ }
+}
diff --git a/src/org/infinity/datatype/MultiNumber.java b/src/org/infinity/datatype/MultiNumber.java
index 7d6111de9..f58f44876 100644
--- a/src/org/infinity/datatype/MultiNumber.java
+++ b/src/org/infinity/datatype/MultiNumber.java
@@ -31,6 +31,7 @@
import org.infinity.gui.ViewerUtil;
import org.infinity.gui.menu.BrowserMenuBar;
import org.infinity.resource.AbstractStruct;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/**
@@ -137,7 +138,7 @@ public JComponent edit(ActionListener container) {
// making "Attribute" column wider
tValues.getColumnModel().getColumn(0).setPreferredWidth(dim.width * 3 / 4);
- tValues.getColumnModel().getColumn(1).setPreferredWidth(dim.width * 1 / 4);
+ tValues.getColumnModel().getColumn(1).setPreferredWidth(dim.width / 4);
tValues.changeSelection(0, 1, false, false);
@@ -309,7 +310,7 @@ public static int bitRangeAsNumber(int data, int bits, int pos, boolean signed)
}
int retVal = (data >> pos) & ((1 << bits) - 1);
if (signed && (retVal & (1 << (bits - 1))) != 0) {
- retVal |= -1 & ~((1 << bits) - 1);
+ retVal |= -(1 << bits);
}
return retVal;
}
@@ -333,7 +334,7 @@ private static class ValueTableModel extends AbstractTableModel {
private final int bits;
private final int numValues;
- private boolean signed;
+ private final boolean signed;
public ValueTableModel(int value, int bits, int numValues, String[] labels, boolean signed) {
if (bits < 1) {
@@ -390,10 +391,10 @@ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
} else {
newVal = Math.min((1 << bits) - 1, Math.max(0, newVal));
}
- data[VALUE][rowIndex] = Integer.valueOf(newVal);
+ data[VALUE][rowIndex] = newVal;
fireTableCellUpdated(rowIndex, columnIndex);
} catch (NumberFormatException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -407,7 +408,7 @@ public boolean isCellEditable(int rowIndex, int columnIndex) {
@Override
public Class> getColumnClass(int columnIndex) {
if (columnIndex >= 0 && columnIndex < 2) {
- return getValueAt(0, columnIndex).getClass();
+ return Objects.requireNonNull(getValueAt(0, columnIndex)).getClass();
} else {
return Object.class;
}
diff --git a/src/org/infinity/datatype/PriTypeBitmap.java b/src/org/infinity/datatype/PriTypeBitmap.java
index 0637c4d97..53425a4f2 100644
--- a/src/org/infinity/datatype/PriTypeBitmap.java
+++ b/src/org/infinity/datatype/PriTypeBitmap.java
@@ -43,7 +43,7 @@ public static String getTableName() {
public static String[] getTypeArray() {
final TreeMap map = getTypeTable();
- return map.values().toArray(new String[map.size()]);
+ return map.values().toArray(new String[0]);
}
private static synchronized TreeMap getTypeTable() {
@@ -53,9 +53,8 @@ private static synchronized TreeMap getTypeTable() {
Table2da table = Table2daCache.get(TABLE_NAME);
if (table != null) {
for (int row = 0, size = table.getRowCount(); row < size; row++) {
- long id = row;
String label = table.get(row, 0).toUpperCase(Locale.ENGLISH);
- TYPE_MAP.put(id, label);
+ TYPE_MAP.put((long) row, label);
}
if (TYPE_MAP.size() == 10) {
// XXX: Doesn't appear to be listed in unmodded games
diff --git a/src/org/infinity/datatype/Readable.java b/src/org/infinity/datatype/Readable.java
index c25b62aea..596cb08fa 100644
--- a/src/org/infinity/datatype/Readable.java
+++ b/src/org/infinity/datatype/Readable.java
@@ -13,7 +13,7 @@ public interface Readable {
* @param buffer The {@link ByteBuffer} to read from.
* @param offset The start offset within the buffer.
* @return The first index after the processed data.
- * @throws Exception
+ * @throws Exception if an exception occurs.
*/
int read(ByteBuffer buffer, int offset) throws Exception;
}
diff --git a/src/org/infinity/datatype/ResourceBitmap.java b/src/org/infinity/datatype/ResourceBitmap.java
index 249ffdc25..26ee90e29 100644
--- a/src/org/infinity/datatype/ResourceBitmap.java
+++ b/src/org/infinity/datatype/ResourceBitmap.java
@@ -99,7 +99,7 @@ public ResourceBitmap(ByteBuffer buffer, int offset, int length, String name, Li
if (curEntry == null) {
curEntry = getDataOf(0L);
}
- if (curEntry == null && resources != null && resources.size() > 0) {
+ if (curEntry == null && resources != null && !resources.isEmpty()) {
curEntry = resources.get(0);
}
this.bView = new JButton("View/Edit", Icons.ICON_ZOOM_16.getIcon());
@@ -181,7 +181,7 @@ public static final class RefEntry implements Comparable {
private final String searchString;
/** Cached textual output for {@link #toString()} method. */
- private String desc;
+ private final String desc;
public RefEntry(long value, String ref) {
this(value, ref, null, null);
diff --git a/src/org/infinity/datatype/ResourceRef.java b/src/org/infinity/datatype/ResourceRef.java
index a7d10e2d1..970ebc53d 100644
--- a/src/org/infinity/datatype/ResourceRef.java
+++ b/src/org/infinity/datatype/ResourceRef.java
@@ -44,6 +44,7 @@
import org.infinity.resource.ResourceFactory;
import org.infinity.resource.key.ResourceEntry;
import org.infinity.resource.sound.SoundResource;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.io.StreamUtils;
@@ -162,7 +163,7 @@ public JComponent edit(final ActionListener container) {
}
}
addExtraEntries(values);
- Collections.sort(values, IGNORE_CASE_EXT_COMPARATOR);
+ values.sort(IGNORE_CASE_EXT_COMPARATOR);
boolean showIcons = BrowserMenuBar.getInstance().getOptions().showResourceListIcons() &&
Arrays.stream(types).anyMatch(s -> ICON_EXTENSIONS.contains(s.toUpperCase()));
list = new TextListPanel<>(values, false, showIcons);
@@ -429,7 +430,7 @@ private void closeResource(Resource resource) {
try {
((Closeable) resource).close();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
diff --git a/src/org/infinity/datatype/SecTypeBitmap.java b/src/org/infinity/datatype/SecTypeBitmap.java
index b0cd1faee..b72c36a69 100644
--- a/src/org/infinity/datatype/SecTypeBitmap.java
+++ b/src/org/infinity/datatype/SecTypeBitmap.java
@@ -32,7 +32,7 @@ public static String getTableName() {
public static String[] getTypeArray() {
final TreeMap map = getTypeTable();
- return map.values().toArray(new String[map.size()]);
+ return map.values().toArray(new String[0]);
}
private static synchronized TreeMap getTypeTable() {
@@ -42,9 +42,8 @@ private static synchronized TreeMap getTypeTable() {
Table2da table = Table2daCache.get(TABLE_NAME);
if (table != null) {
for (int row = 0, size = table.getRowCount(); row < size; row++) {
- long id = row;
String label = table.get(row, 0).toUpperCase(Locale.ENGLISH);
- TYPE_MAP.put(id, label);
+ TYPE_MAP.put((long) row, label);
}
}
} else {
diff --git a/src/org/infinity/datatype/SpellProtType.java b/src/org/infinity/datatype/SpellProtType.java
index 5668cd10d..730e17623 100644
--- a/src/org/infinity/datatype/SpellProtType.java
+++ b/src/org/infinity/datatype/SpellProtType.java
@@ -18,6 +18,7 @@
import org.infinity.util.IdsMap;
import org.infinity.util.IdsMapCache;
import org.infinity.util.IdsMapEntry;
+import org.infinity.util.Logger;
import org.infinity.util.Table2da;
import org.infinity.util.Table2daCache;
@@ -195,7 +196,7 @@ public String getIdsFile() {
Table2da table = Table2daCache.get(TABLE_NAME);
if (table != null) {
int id = toNumber(table.get(value, 1), -1);
- String retVal = STAT_IDS.get(Long.valueOf(id));
+ String retVal = STAT_IDS.get((long) id);
if (retVal != null) {
return retVal;
}
@@ -292,7 +293,7 @@ public static String getIdsFile(int value) {
boolean isCustom = (-1 == toNumber(table.get(value, 2), 0));
if (isCustom) {
int id = toNumber(table.get(value, 1), -1);
- String retVal = STAT_IDS.get(Long.valueOf(id));
+ String retVal = STAT_IDS.get((long) id);
if (retVal != null) {
return retVal;
}
@@ -546,6 +547,7 @@ private static int toNumber(String value, int defValue) {
retVal = Integer.parseInt(value);
}
} catch (NumberFormatException e) {
+ Logger.trace(e);
}
}
return retVal;
diff --git a/src/org/infinity/datatype/StringRef.java b/src/org/infinity/datatype/StringRef.java
index 66a25136b..df32702e4 100644
--- a/src/org/infinity/datatype/StringRef.java
+++ b/src/org/infinity/datatype/StringRef.java
@@ -51,6 +51,7 @@
import org.infinity.resource.sav.SavResourceEntry;
import org.infinity.resource.to.TohResource;
import org.infinity.search.StringReferenceSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
import org.infinity.util.io.FileManager;
@@ -202,7 +203,7 @@ public void mouseClicked(MouseEvent e) {
JTextField edit = (JTextField) e.getSource();
// Invoke later to circumvent content validation (may not work correctly on every platform)
if (e.getClickCount() == 2) {
- SwingUtilities.invokeLater(() -> edit.selectAll());
+ SwingUtilities.invokeLater(edit::selectAll);
} else {
SwingUtilities.invokeLater(() -> edit.setCaretPosition(edit.viewToModel(e.getPoint())));
}
@@ -474,7 +475,7 @@ private String getStringRef(int strref, StringTable.Format fmt) {
}
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
} else {
// load TOH/TOT directly
diff --git a/src/org/infinity/datatype/Summon2daBitmap.java b/src/org/infinity/datatype/Summon2daBitmap.java
index a8a35c576..961986306 100644
--- a/src/org/infinity/datatype/Summon2daBitmap.java
+++ b/src/org/infinity/datatype/Summon2daBitmap.java
@@ -9,6 +9,7 @@
import java.util.TreeMap;
import org.infinity.resource.ResourceFactory;
+import org.infinity.util.Logger;
import org.infinity.util.Table2da;
import org.infinity.util.Table2daCache;
@@ -38,10 +39,10 @@ private static synchronized TreeMap getSummonTable() {
String resref = table.get(row, 1).toUpperCase(Locale.ENGLISH) + ".2DA";
SUMMON_MAP.put(id, resref);
if (!ResourceFactory.resourceExists(resref)) {
- System.err.println("Resource does not exist: " + resref);
+ Logger.warn("Resource does not exist: {}", resref);
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
diff --git a/src/org/infinity/datatype/TextEdit.java b/src/org/infinity/datatype/TextEdit.java
index b4e21edf4..75565c78c 100644
--- a/src/org/infinity/datatype/TextEdit.java
+++ b/src/org/infinity/datatype/TextEdit.java
@@ -199,17 +199,15 @@ public boolean equals(Object obj) {
public ByteBuffer toBuffer() {
if (text != null) {
byte[] buf = eolConvert(text).getBytes();
- if (buf != null) {
- int imax = Math.min(buf.length, buffer.limit());
- buffer.position(0);
- buffer.put(buf, 0, imax);
- while (buffer.remaining() > 0) {
- buffer.put((byte) 0);
- }
- if (terminateString) {
- buffer.position(buffer.position() - 1);
- buffer.put((byte) 0);
- }
+ int imax = Math.min(buf.length, buffer.limit());
+ buffer.position(0);
+ buffer.put(buf, 0, imax);
+ while (buffer.remaining() > 0) {
+ buffer.put((byte) 0);
+ }
+ if (terminateString) {
+ buffer.position(buffer.position() - 1);
+ buffer.put((byte) 0);
}
buffer.position(0);
}
@@ -256,7 +254,7 @@ public void setEditable(boolean edit) {
}
private String eolConvert(String s) {
- if (s != null && s.length() > 0) {
+ if (s != null && !s.isEmpty()) {
return s.replaceAll("(\r\n|\n)", EOL.get(eolType));
} else {
return s;
@@ -264,7 +262,7 @@ private String eolConvert(String s) {
}
private String eolConvert(String s, String eol) {
- if (s != null && s.length() > 0 && eol != null && eol.length() > 0) {
+ if (s != null && !s.isEmpty() && eol != null && !eol.isEmpty()) {
return s.replaceAll("(\r\n|\n)", eol);
} else {
return s;
@@ -283,13 +281,13 @@ private void setValue(String newValue) {
// Ensures a size limit on byte level
private class FixedDocument extends RSyntaxDocument {
- private int maxLength;
- private RTextArea textArea;
+ private final int maxLength;
+ private final RTextArea textArea;
FixedDocument(RTextArea text, int length) {
super(null);
textArea = text;
- maxLength = length >= 0 ? length : 0;
+ maxLength = Math.max(length, 0);
}
@Override
diff --git a/src/org/infinity/datatype/Unknown.java b/src/org/infinity/datatype/Unknown.java
index d776fbb01..ed3006be1 100644
--- a/src/org/infinity/datatype/Unknown.java
+++ b/src/org/infinity/datatype/Unknown.java
@@ -96,8 +96,7 @@ public JComponent edit(ActionListener container) {
panel.setPreferredSize(Misc.getScaledDimension(DIM_BROAD));
return panel;
} else {
- JPanel panel = new JPanel();
- return panel;
+ return new JPanel();
}
}
diff --git a/src/org/infinity/datatype/UnknownDecimal.java b/src/org/infinity/datatype/UnknownDecimal.java
index 21fc2c810..20ea48301 100644
--- a/src/org/infinity/datatype/UnknownDecimal.java
+++ b/src/org/infinity/datatype/UnknownDecimal.java
@@ -8,6 +8,7 @@
import java.nio.ByteBuffer;
import org.infinity.resource.AbstractStruct;
+import org.infinity.util.Logger;
/**
* Field that represents binary data in decimal format in their editor.
@@ -31,7 +32,7 @@ public UnknownDecimal(ByteBuffer buffer, int offset, int length, String name) {
public boolean updateValue(AbstractStruct struct) {
String value = textArea.getText().trim();
value = value.replaceAll("\r?\n", " ") + ' ';
- byte newdata[] = new byte[buffer.limit()];
+ byte[] newdata = new byte[buffer.limit()];
int counter = 0;
try {
int index = value.indexOf(' ');
@@ -50,7 +51,7 @@ public boolean updateValue(AbstractStruct struct) {
return true;
}
} catch (NumberFormatException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
diff --git a/src/org/infinity/datatype/UnsignHexNumber.java b/src/org/infinity/datatype/UnsignHexNumber.java
new file mode 100644
index 000000000..505ea9a72
--- /dev/null
+++ b/src/org/infinity/datatype/UnsignHexNumber.java
@@ -0,0 +1,35 @@
+// Near Infinity - An Infinity Engine Browser and Editor
+// Copyright (C) 2001 Jon Olav Hauglid
+// See LICENSE.txt for license information
+
+package org.infinity.datatype;
+
+import java.nio.ByteBuffer;
+
+import org.infinity.util.Logger;
+
+public class UnsignHexNumber extends UnsignDecNumber {
+ public UnsignHexNumber(ByteBuffer buffer, int offset, int length, String desc) {
+ super(buffer, offset, length, desc);
+ }
+
+ // --------------------- Begin Interface InlineEditable ---------------------
+
+ @Override
+ public boolean update(Object value) {
+ try {
+ setValue(UnsignDecNumber.parseNumber(value, getSize(), false, true));
+ return true;
+ } catch (Exception e) {
+ Logger.error(e);
+ }
+ return false;
+ }
+
+ // --------------------- End Interface InlineEditable ---------------------
+
+ @Override
+ public String toString() {
+ return Long.toHexString(getLongValue() & 0xffffffffL) + " h";
+ }
+}
diff --git a/src/org/infinity/gui/BIFFEditor.java b/src/org/infinity/gui/BIFFEditor.java
index 4907afd66..a78a85fb7 100644
--- a/src/org/infinity/gui/BIFFEditor.java
+++ b/src/org/infinity/gui/BIFFEditor.java
@@ -42,6 +42,7 @@
import org.infinity.resource.key.BIFFWriter;
import org.infinity.resource.key.FileResourceEntry;
import org.infinity.resource.key.ResourceEntry;
+import org.infinity.util.Logger;
import org.infinity.util.io.FileEx;
import org.infinity.util.io.FileManager;
import org.infinity.util.io.StreamUtils;
@@ -121,7 +122,7 @@ public void run() {
progress.setProgress(2, false);
JOptionPane.showMessageDialog(editframe, "Error while extracting files from " + bifentry, "Error",
JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
blocker.setBlocked(false);
return;
}
@@ -147,7 +148,7 @@ public void run() {
} catch (Exception e) {
progress.setProgress(3, false);
JOptionPane.showMessageDialog(editframe, "Error while saving " + bifentry, "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
blocker.setBlocked(false);
return;
}
@@ -159,7 +160,7 @@ public void run() {
try {
Files.delete(file);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -182,7 +183,7 @@ public void run() {
} catch (IOException e) {
progress.setProgress(6, false);
JOptionPane.showMessageDialog(editframe, "Error while saving keyfile", "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
ResourceFactory.getResourceTreeModel().sort();
blocker.setBlocked(false);
diff --git a/src/org/infinity/gui/BIFFEditorTable.java b/src/org/infinity/gui/BIFFEditorTable.java
index f1f766bc4..b4fa3401e 100644
--- a/src/org/infinity/gui/BIFFEditorTable.java
+++ b/src/org/infinity/gui/BIFFEditorTable.java
@@ -13,7 +13,6 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
@@ -157,7 +156,7 @@ public void moveSelectedTo(BIFFEditorTable other) {
public BifEditorTableLine[] getSelectedValues() {
final BifEditorTableLine[] selected = new BifEditorTableLine[table.getSelectedRowCount()];
- int isel[] = table.getSelectedRows();
+ int[] isel = table.getSelectedRows();
for (int i = 0; i < isel.length; i++) {
selected[i] = tablemodel.get(isel[i]);
}
@@ -223,7 +222,7 @@ private boolean add(BifEditorTableLine line) {
entries.add(line);
return true;
} else if (line.state == State.BIF) {
- String options[] = { "Keep updated", "Overwrite updated", "Cancel" };
+ String[] options = { "Keep updated", "Overwrite updated", "Cancel" };
int choice = JOptionPane.showOptionDialog(parent, "An updated version of this file already exists.",
"Updated version exists", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
@@ -321,7 +320,7 @@ public String getColumnName(int i) {
}
public void sort() {
- Collections.sort(entries, this);
+ entries.sort(this);
}
@Override
diff --git a/src/org/infinity/gui/BcsDropFrame.java b/src/org/infinity/gui/BcsDropFrame.java
index 93f1d2bd4..aba81824f 100644
--- a/src/org/infinity/gui/BcsDropFrame.java
+++ b/src/org/infinity/gui/BcsDropFrame.java
@@ -60,6 +60,7 @@
import org.infinity.resource.bcs.ScriptMessage;
import org.infinity.resource.bcs.ScriptType;
import org.infinity.resource.key.FileResourceEntry;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.io.FileEx;
import org.infinity.util.io.FileManager;
@@ -242,7 +243,7 @@ private SortedSet compileFile(Path file) {
line = br.readLine();
}
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
return null;
}
Compiler compiler = new Compiler(source.toString());
@@ -269,7 +270,7 @@ private SortedSet compileFile(Path file) {
try (BufferedWriter bw = Files.newBufferedWriter(output)) {
bw.write(compiled);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
return null;
}
}
@@ -285,7 +286,7 @@ private boolean decompileFile(Path file) {
line = br.readLine();
}
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
return false;
}
String filename = file.getFileName().toString();
@@ -302,7 +303,7 @@ private boolean decompileFile(Path file) {
bw.write(decompiler.getSource().replaceAll("\r?\n", Misc.LINE_SEPARATOR));
bw.newLine();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
return false;
}
return true;
@@ -322,7 +323,7 @@ private void filesDropped(Component component, List files) {
files.add(p.toFile());
}
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
} else if (file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BAF")) {
SortedSet errors = compileFile(file);
@@ -352,7 +353,7 @@ private void filesDropped(Component component, List files) {
files.add(p.toFile());
}
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
} else if (file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BCS")
|| file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BS")) {
@@ -407,7 +408,7 @@ public void drop(DropTargetDropEvent event) {
event.acceptDrop(DnDConstants.ACTION_COPY);
files = (List) event.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
event.dropComplete(false);
return;
}
diff --git a/src/org/infinity/gui/BookmarkEditor.java b/src/org/infinity/gui/BookmarkEditor.java
index fdcf106ff..185945e28 100644
--- a/src/org/infinity/gui/BookmarkEditor.java
+++ b/src/org/infinity/gui/BookmarkEditor.java
@@ -52,6 +52,7 @@
import org.infinity.NearInfinity;
import org.infinity.gui.menu.Bookmark;
import org.infinity.resource.Profile;
+import org.infinity.util.Logger;
import org.infinity.util.Platform;
import org.infinity.util.SimpleListModel;
import org.infinity.util.io.FileManager;
@@ -288,7 +289,7 @@ private void initData(List bookmarks) {
}
}
- int platformIdx = Math.max(cbPlatformModel.getIndexOf(Platform.getPlatform()), 0);
+ int platformIdx = Math.max(cbPlatformModel.getIndexOf(Platform.OS.getCurrentOS()), 0);
cbPlatform.setSelectedIndex(platformIdx);
for (int idx = 0; idx < cbPlatformModel.getSize(); idx++) {
listBinPathModels.put(cbPlatformModel.getElementAt(idx), new DefaultListModel());
@@ -298,8 +299,8 @@ private void initData(List bookmarks) {
cbPlatform.addItemListener(this);
if (listBookmarks != null) {
- for (Iterator iter = listBookmarks.iterator(); iter.hasNext();) {
- modelEntries.addElement(iter.next());
+ for (Bookmark listBookmark : listBookmarks) {
+ modelEntries.addElement(listBookmark);
}
if (!modelEntries.isEmpty()) {
listEntries.setSelectedIndex(0);
@@ -512,18 +513,15 @@ public boolean accept(File f) {
}
};
}
- if (exeFilter != null) {
- fc.addChoosableFileFilter(exeFilter);
- }
+ fc.addChoosableFileFilter(exeFilter);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
- if (exeFilter != null) {
- fc.setFileFilter(exeFilter);
- }
+ fc.setFileFilter(exeFilter);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
Path path = fc.getSelectedFile().toPath();
try {
path = Profile.getGameRoot().relativize(path);
} catch (IllegalArgumentException ex) {
+ Logger.trace(ex);
}
DefaultListModel model = getBinPathModel();
boolean exists = false;
diff --git a/src/org/infinity/gui/ButtonPanel.java b/src/org/infinity/gui/ButtonPanel.java
index c3e44b94f..1c9bf084f 100644
--- a/src/org/infinity/gui/ButtonPanel.java
+++ b/src/org/infinity/gui/ButtonPanel.java
@@ -429,7 +429,7 @@ private int getControlIndex(JComponent comp) {
// -------------------------- INNER CLASSES --------------------------
- private class Entry {
+ private static class Entry {
private final JComponent component;
private final Control type;
diff --git a/src/org/infinity/gui/ButtonPopupMenu.java b/src/org/infinity/gui/ButtonPopupMenu.java
index d8adadfc7..ca29cdcee 100644
--- a/src/org/infinity/gui/ButtonPopupMenu.java
+++ b/src/org/infinity/gui/ButtonPopupMenu.java
@@ -241,7 +241,7 @@ public void setMenuItems(List menuItems, boolean sorted) {
List preparedList;
if (sorted) {
preparedList = new ArrayList<>(menuItems);
- Collections.sort(preparedList, MENU_ITEM_COMPARATOR);
+ preparedList.sort(MENU_ITEM_COMPARATOR);
} else {
preparedList = menuItems;
}
@@ -428,7 +428,7 @@ public void mouseReleased(MouseEvent e) {
}
} else {
menu.setVisible(false);
- Component components[] = menu.getComponents();
+ Component[] components = menu.getComponents();
for (final Component component : components) {
if (component instanceof JMenuItem) {
JMenuItem item = (JMenuItem) component;
diff --git a/src/org/infinity/gui/ButtonPopupWindow.java b/src/org/infinity/gui/ButtonPopupWindow.java
index ad6eab55d..bfb2d4ae2 100644
--- a/src/org/infinity/gui/ButtonPopupWindow.java
+++ b/src/org/infinity/gui/ButtonPopupWindow.java
@@ -138,7 +138,7 @@ public ButtonPopupWindow(String text, Icon icon, Component content, Align align)
/** Adds a new PopupWindowListener to this component. */
public void addPopupWindowListener(PopupWindowListener listener) {
if (listener != null) {
- if (listeners.indexOf(listener) < 0) {
+ if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
@@ -416,7 +416,7 @@ private void hideWindow() {
private PopupWindow getParentPopupWindow(PopupWindow wnd) {
if (wnd != null) {
Window parent = SwingUtilities.getWindowAncestor(wnd.getButton());
- if (parent != null && parent instanceof PopupWindow) {
+ if (parent instanceof PopupWindow) {
return (PopupWindow) parent;
}
}
@@ -460,8 +460,10 @@ public ButtonPopupListener() {
@Override
public void mousePressed(MouseEvent event) {
- if (event.getSource() instanceof ButtonPopupWindow && event.getButton() == MouseEvent.BUTTON1
- && !event.isPopupTrigger() && event.getComponent().isEnabled() && window != null) {
+ if (event.getSource() instanceof ButtonPopupWindow &&
+ event.getButton() == MouseEvent.BUTTON1 &&
+ !event.isPopupTrigger() &&
+ event.getComponent().isEnabled()) {
displayWindow(!window.isVisible());
}
}
diff --git a/src/org/infinity/gui/ChildFrame.java b/src/org/infinity/gui/ChildFrame.java
index b2d2ddb85..e98c0214b 100644
--- a/src/org/infinity/gui/ChildFrame.java
+++ b/src/org/infinity/gui/ChildFrame.java
@@ -34,6 +34,7 @@
import org.infinity.resource.Viewable;
import org.infinity.resource.ViewableContainer;
import org.infinity.resource.graphics.BamResource;
+import org.infinity.util.Logger;
public class ChildFrame extends JFrame {
private static final List WINDOWS = new ArrayList<>();
@@ -190,7 +191,7 @@ public void actionPerformed(ActionEvent e) {
return;
}
} catch (Exception e2) {
- e2.printStackTrace();
+ Logger.error(e2);
return;
}
WINDOWS.remove(ChildFrame.this);
@@ -338,7 +339,7 @@ private static void closeWindow(ChildFrame frame, WindowEvent event) {
}
frame.dispose();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
diff --git a/src/org/infinity/gui/ChooseBIFFrame.java b/src/org/infinity/gui/ChooseBIFFrame.java
index ecafd399f..cdba830c7 100644
--- a/src/org/infinity/gui/ChooseBIFFrame.java
+++ b/src/org/infinity/gui/ChooseBIFFrame.java
@@ -29,6 +29,7 @@
import org.infinity.resource.ResourceFactory;
import org.infinity.resource.key.AbstractBIFFReader;
import org.infinity.resource.key.BIFFEntry;
+import org.infinity.util.Logger;
final class ChooseBIFFrame extends ChildFrame implements ActionListener {
private final BIFFEditor editor;
@@ -211,7 +212,7 @@ public void actionPerformed(ActionEvent event) {
close();
editor.makeEditor(entry, file.getType());
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
diff --git a/src/org/infinity/gui/ColorGrid.java b/src/org/infinity/gui/ColorGrid.java
index 3bd11f962..9efcf982b 100644
--- a/src/org/infinity/gui/ColorGrid.java
+++ b/src/org/infinity/gui/ColorGrid.java
@@ -108,7 +108,7 @@ public ColorGrid(int colorCount, Collection colors) {
*/
public void addActionListener(ActionListener l) {
if (l != null) {
- if (listActionListeners.indexOf(l) < 0) {
+ if (!listActionListeners.contains(l)) {
listActionListeners.add(l);
}
}
@@ -139,7 +139,7 @@ public void removeActionListener(ActionListener l) {
*/
public void addMouseOverListener(MouseOverListener l) {
if (l != null) {
- if (listMouseOverListeners.indexOf(l) < 0) {
+ if (!listMouseOverListeners.contains(l)) {
listMouseOverListeners.add(l);
}
}
@@ -170,7 +170,7 @@ public void removeMouseOverListener(MouseOverListener l) {
*/
public void addChangeListener(ChangeListener l) {
if (l != null) {
- if (listChangeListeners.indexOf(l) < 0) {
+ if (!listChangeListeners.contains(l)) {
listChangeListeners.add(l);
}
}
@@ -442,7 +442,7 @@ public Color[] getSelectedColors() {
/** Returns whether the specified color entry index is currently selected. */
public boolean isSelectedIndex(int index) {
if (index >= 0 && index < getColorCount()) {
- int idx = listSelection.indexOf(Integer.valueOf(index));
+ int idx = listSelection.indexOf(index);
return (idx >= 0);
}
return false;
@@ -491,7 +491,7 @@ public void setSelectedIndices(int[] indices) {
if (indices != null) {
for (int index : indices) {
if (index >= 0 && index < getColorCount()) {
- int idx = listSelection.indexOf(Integer.valueOf(index));
+ int idx = listSelection.indexOf(index);
if (idx < 0) {
listSelection.add(index);
}
@@ -522,7 +522,7 @@ public void addSelectedIndices(int[] indices) {
if (indices != null) {
for (int index : indices) {
if (index >= 0 && index < getColorCount()) {
- int idx = listSelection.indexOf(Integer.valueOf(index));
+ int idx = listSelection.indexOf(index);
if (idx < 0) {
listSelection.add(index);
}
@@ -547,7 +547,7 @@ public void removeSelectedIndices(int[] indices) {
if (indices != null) {
for (int index : indices) {
if (index >= 0 && index < getColorCount()) {
- int idx = listSelection.indexOf(Integer.valueOf(index));
+ int idx = listSelection.indexOf(index);
if (idx >= 0) {
listSelection.remove(idx);
}
@@ -609,8 +609,7 @@ private static TexturePaint createBackgroundPattern() {
BufferedImage buf = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
int[] raster = ((DataBufferInt) buf.getRaster().getDataBuffer()).getData();
System.arraycopy(checker, 0, raster, 0, checker.length);
- TexturePaint tp = new TexturePaint(buf, new Rectangle(0, 0, 8, 8));
- return tp;
+ return new TexturePaint(buf, new Rectangle(0, 0, 8, 8));
}
// First-time initializations
@@ -908,8 +907,8 @@ public interface MouseOverListener extends EventListener {
}
/** MouseOverEvent is used to notify listeners that the mouse has been placed over a specific color entry. */
- public class MouseOverEvent extends EventObject {
- private int index;
+ public static class MouseOverEvent extends EventObject {
+ private final int index;
/**
* Constructs a MouseOverEvent.
diff --git a/src/org/infinity/gui/DebugConsole.java b/src/org/infinity/gui/DebugConsole.java
index fea613db0..f72d9c87e 100644
--- a/src/org/infinity/gui/DebugConsole.java
+++ b/src/org/infinity/gui/DebugConsole.java
@@ -26,6 +26,7 @@
import org.infinity.gui.menu.BrowserMenuBar;
import org.infinity.icon.Icons;
import org.infinity.resource.Profile;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.io.FileEx;
@@ -78,7 +79,7 @@ public void actionPerformed(ActionEvent event) {
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path output = chooser.getSelectedFile().toPath();
if (FileEx.create(output).exists()) {
- String options[] = { "Overwrite", "Cancel" };
+ String[] options = { "Overwrite", "Cancel" };
if (JOptionPane.showOptionDialog(this, output + " exists. Overwrite?", "Save debug log",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) {
return;
@@ -104,7 +105,7 @@ public void actionPerformed(ActionEvent event) {
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error while saving " + output, "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
}
} else if (event.getSource() == cbExtraInfo) {
diff --git a/src/org/infinity/gui/FixedFocusTraversalPolicy.java b/src/org/infinity/gui/FixedFocusTraversalPolicy.java
index be859ce0b..1a71d680a 100644
--- a/src/org/infinity/gui/FixedFocusTraversalPolicy.java
+++ b/src/org/infinity/gui/FixedFocusTraversalPolicy.java
@@ -68,11 +68,7 @@ public void setComponents(Component[] list) {
public void setDefaultComponent(Component c) {
if (c != null) {
int idx = order.indexOf(c);
- if (idx >= 0) {
- defaultIndex = idx;
- } else {
- defaultIndex = 0;
- }
+ defaultIndex = Math.max(idx, 0);
} else {
defaultIndex = 0;
}
diff --git a/src/org/infinity/gui/FontChooser.java b/src/org/infinity/gui/FontChooser.java
index c644a13fd..7feea6b9e 100644
--- a/src/org/infinity/gui/FontChooser.java
+++ b/src/org/infinity/gui/FontChooser.java
@@ -48,10 +48,9 @@
import javax.swing.text.JTextComponent;
import javax.swing.text.Position;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
-//import org.infinity.util.Misc;
-
/**
* The {@code FontChooser} class is a swing component for font selection. This class has {@code FileChooser} like APIs.
* The following code pops up a font chooser dialog.
@@ -61,11 +60,11 @@
* int result = fontChooser.showDialog(parent);
* if (result == FontChooser.OK_OPTION) {
* Font font = fontChooser.getSelectedFont();
- * System.out.println("Selected Font : " + font);
+ * Logger.info("Selected Font : {}", font);
* }
*
*
- * Based on JFontChooser (http://osdn.jp/projects/jfontchooser/)
+ * Based on JFontChooser.
**/
public class FontChooser extends JComponent {
// class variables
@@ -204,7 +203,7 @@ public JList getFontStyleList() {
fontStyleList.addListSelectionListener(new ListSelectionHandler(getFontStyleTextField()));
fontStyleList.setSelectedIndex(0);
fontStyleList.setFont(Misc.getScaledFont(DEFAULT_FONT));
- fontStyleList.setPrototypeCellValue(fontStyleList.getModel().getElementAt(0).toString());
+ fontStyleList.setPrototypeCellValue(fontStyleList.getModel().getElementAt(0));
fontStyleList.setFocusable(false);
}
return fontStyleList;
@@ -230,8 +229,7 @@ public JList getFontSizeList() {
* @see #setSelectedFontFamily
**/
public String getSelectedFontFamily() {
- String fontName = getFontFamilyList().getSelectedValue();
- return fontName;
+ return getFontFamilyList().getSelectedValue();
}
/**
@@ -282,8 +280,7 @@ public int getSelectedFontSize() {
* @see java.awt.Font
**/
public Font getSelectedFont() {
- Font font = new Font(getSelectedFontFamily(), getSelectedFontStyle(), getSelectedFontSize());
- return font;
+ return new Font(getSelectedFontFamily(), getSelectedFontStyle(), getSelectedFontSize());
}
/**
@@ -392,7 +389,7 @@ public void windowClosing(WindowEvent e) {
// -------------------------- INNER CLASSES --------------------------
protected class ListSelectionHandler implements ListSelectionListener {
- private JTextComponent textComponent;
+ private final JTextComponent textComponent;
ListSelectionHandler(JTextComponent textComponent) {
this.textComponent = textComponent;
@@ -417,7 +414,7 @@ public void valueChanged(ListSelectionEvent e) {
}
protected class TextFieldFocusHandlerForTextSelection extends FocusAdapter {
- private JTextComponent textComponent;
+ private final JTextComponent textComponent;
public TextFieldFocusHandlerForTextSelection(JTextComponent textComponent) {
this.textComponent = textComponent;
@@ -435,8 +432,8 @@ public void focusLost(FocusEvent e) {
}
}
- protected class TextFieldKeyHandlerForListSelectionUpDown extends KeyAdapter {
- private JList targetList;
+ protected static class TextFieldKeyHandlerForListSelectionUpDown extends KeyAdapter {
+ private final JList targetList;
public TextFieldKeyHandlerForListSelectionUpDown(JList list) {
this.targetList = list;
@@ -467,7 +464,7 @@ public void keyPressed(KeyEvent e) {
}
}
- protected class ListSearchTextFieldDocumentHandler implements DocumentListener {
+ protected static class ListSearchTextFieldDocumentHandler implements DocumentListener {
JList targetList;
public ListSearchTextFieldDocumentHandler(JList targetList) {
@@ -495,10 +492,10 @@ private void update(DocumentEvent event) {
Document doc = event.getDocument();
newValue = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
- e.printStackTrace();
+ Logger.error(e);
}
- if (newValue.length() > 0) {
+ if (!newValue.isEmpty()) {
int index = targetList.getNextMatch(newValue, 0, Position.Bias.Forward);
if (index < 0) {
index = 0;
@@ -515,7 +512,7 @@ private void update(DocumentEvent event) {
}
public class ListSelector implements Runnable {
- private int index;
+ private final int index;
public ListSelector(int index) {
this.index = index;
@@ -530,7 +527,7 @@ public void run() {
protected class DialogOKAction extends AbstractAction {
protected static final String ACTION_NAME = "OK";
- private JDialog dialog;
+ private final JDialog dialog;
protected DialogOKAction(JDialog dialog) {
this.dialog = dialog;
@@ -548,7 +545,7 @@ public void actionPerformed(ActionEvent e) {
protected class DialogCancelAction extends AbstractAction {
protected static final String ACTION_NAME = "Cancel";
- private JDialog dialog;
+ private final JDialog dialog;
protected DialogCancelAction(JDialog dialog) {
this.dialog = dialog;
diff --git a/src/org/infinity/gui/GameProperties.java b/src/org/infinity/gui/GameProperties.java
index 35786ae05..3ff1849ee 100644
--- a/src/org/infinity/gui/GameProperties.java
+++ b/src/org/infinity/gui/GameProperties.java
@@ -20,7 +20,6 @@
import java.awt.event.FocusListener;
import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
@@ -285,7 +284,7 @@ private void init() {
}
}
- Collections.sort(listTypes, (o1, o2) -> o1.getText().compareToIgnoreCase(o2.getText()));
+ listTypes.sort((o1, o2) -> o1.getText().compareToIgnoreCase(o2.getText()));
// setting preferred size to fit all entries
int itemsPerRow = pFixed.getPreferredSize().width / (maxWidth + flow.getHgap());
@@ -355,7 +354,7 @@ private void init() {
// Returns the name of the language specified by the given language code
private static String getLanguageName(String langCode) {
if (langCode != null && langCode.matches("[a-z]{2}_[A-Z]{2}")) {
- String lang[] = langCode.split("_");
+ String[] lang = langCode.split("_");
if (lang.length >= 2) {
String name = (new Locale(lang[0], lang[1])).getDisplayLanguage();
if (name != null && !name.isEmpty()) {
diff --git a/src/org/infinity/gui/IdsBrowser.java b/src/org/infinity/gui/IdsBrowser.java
index deb5b3959..8be6f1ba0 100644
--- a/src/org/infinity/gui/IdsBrowser.java
+++ b/src/org/infinity/gui/IdsBrowser.java
@@ -39,7 +39,7 @@ public IdsBrowser() {
setIconImage(Icons.ICON_HISTORY_16.getIcon().getImage());
List resList = ResourceFactory.getResources("IDS");
- idsfiles = new JComboBox<>(resList.toArray(new ResourceEntry[resList.size()]));
+ idsfiles = new JComboBox<>(resList.toArray(new ResourceEntry[0]));
idsfiles.setEditable(false);
idsfiles.setSelectedIndex(0);
idsfiles.addActionListener(this);
@@ -108,7 +108,7 @@ public void refreshList() {
private void insertString(String s) {
Viewable viewable = NearInfinity.getInstance().getViewable();
- if (viewable == null || !(viewable instanceof BcsResource)) {
+ if (!(viewable instanceof BcsResource)) {
JOptionPane.showMessageDialog(this, "No script displayed in the main window", "Error", JOptionPane.ERROR_MESSAGE);
} else {
((BcsResource) viewable).insertString(s);
diff --git a/src/org/infinity/gui/InfinityAmp.java b/src/org/infinity/gui/InfinityAmp.java
index 6a627f6ae..0ca2de71d 100644
--- a/src/org/infinity/gui/InfinityAmp.java
+++ b/src/org/infinity/gui/InfinityAmp.java
@@ -37,6 +37,7 @@
import org.infinity.resource.mus.Entry;
import org.infinity.resource.sound.AudioBuffer;
import org.infinity.resource.sound.AudioPlayer;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.SimpleListModel;
import org.infinity.util.io.StreamUtils;
@@ -155,7 +156,7 @@ public void actionPerformed(ActionEvent event) {
keepPlaying = false;
player.stopPlay();
} else if (event.getSource() == bAdd) {
- int indices[] = allMusList.getSelectedIndices();
+ int[] indices = allMusList.getSelectedIndices();
for (final int index : indices) {
selectedMusModel.addElement(allMusModel.get(index));
}
@@ -167,7 +168,7 @@ public void actionPerformed(ActionEvent event) {
if (index >= 0) {
selectedMusList.addSelectionInterval(index, index);
}
- bPlay.setEnabled(selectedMusModel.size() > 0);
+ bPlay.setEnabled(!selectedMusModel.isEmpty());
} else if (event.getSource() == bUp) {
int index = selectedMusList.getSelectedIndex();
ResourceEntry o = selectedMusModel.remove(index);
@@ -284,7 +285,7 @@ private void playMus(ResourceEntry musEntry) {
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error accessing " + musEntry + '\n' + e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
}
}
diff --git a/src/org/infinity/gui/InfinityTextArea.java b/src/org/infinity/gui/InfinityTextArea.java
index 30df0a300..cad8d7697 100644
--- a/src/org/infinity/gui/InfinityTextArea.java
+++ b/src/org/infinity/gui/InfinityTextArea.java
@@ -43,6 +43,7 @@
import org.infinity.resource.text.modes.MenuTokenMaker;
import org.infinity.resource.text.modes.TLKTokenMaker;
import org.infinity.resource.text.modes.WeiDULogTokenMaker;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/**
@@ -88,7 +89,7 @@ public String getStyle() {
/** Available color schemes for use when enabling syntax highlighting. */
public enum Scheme {
/** Disables any color scheme. */
- NONE("None", () -> getNoneScheme()),
+ NONE("None", InfinityTextArea::getNoneScheme),
/** The default color scheme. */
DEFAULT("Default", () -> SCHEME_DEFAULT),
/** Color scheme based on Notepad++'s Obsidian scheme. */
@@ -396,13 +397,11 @@ public static void applyExtendedSettings(RSyntaxTextArea edit, Language language
if (schemePath != null) {
try (InputStream is = ClassLoader.getSystemResourceAsStream(schemePath)) {
Theme theme = Theme.load(is);
- if (theme != null) {
- theme.apply(edit);
- }
+ theme.apply(edit);
} catch (NullPointerException e) {
// ignore
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -525,17 +524,17 @@ public void addGutterIcon(int line, Icon icon, String msg) {
/** Get information about the gutter icon at the specified line. */
public GutterIcon getGutterIconInfo(int line) {
- return gutterIcons.get(Integer.valueOf(line));
+ return gutterIcons.get(line);
}
/** Returns whether the gutter icon at the specified line is currently applied. */
public boolean isGutterIconActive(int line) {
- return gutterIconsActive.containsKey(Integer.valueOf(line));
+ return gutterIconsActive.containsKey(line);
}
/** Removes the gutter icon from the specified line. */
public void removeGutterIcon(int line) {
- if (gutterIcons.remove(Integer.valueOf(line)) != null) {
+ if (gutterIcons.remove(line) != null) {
refreshGutterIcon(line);
}
}
@@ -576,6 +575,7 @@ protected Point getVisibleLineRange(Point range) {
range.x = startLine;
range.y = endLine;
} catch (BadLocationException e) {
+ Logger.trace(e);
}
}
@@ -594,6 +594,7 @@ private void refreshGutterIcon(int line) {
GutterIconInfo info = getScrollPane().getGutter().addLineTrackingIcon(item.line, item.icon, item.message);
gutterIconsActive.put(key, info);
} catch (BadLocationException e) {
+ Logger.trace(e);
}
}
}
@@ -627,6 +628,7 @@ private void refreshGutterIcons() {
GutterIconInfo info = gutter.addLineTrackingIcon(item.line, item.icon, item.message);
gutterIconsActive.put(item.line, info);
} catch (BadLocationException e) {
+ Logger.trace(e);
}
}
}
diff --git a/src/org/infinity/gui/LinkButton.java b/src/org/infinity/gui/LinkButton.java
index b2b554e2c..67e27d055 100644
--- a/src/org/infinity/gui/LinkButton.java
+++ b/src/org/infinity/gui/LinkButton.java
@@ -22,6 +22,7 @@
import org.infinity.resource.ResourceFactory;
import org.infinity.resource.key.ResourceEntry;
import org.infinity.updater.Utils;
+import org.infinity.util.Logger;
/**
* A JLabel-based control which supports either internal game resources or external URLs.
@@ -214,7 +215,7 @@ public void actionPerformed(ActionEvent e) {
try {
Utils.openWebPage(new URL(getUrl()));
} catch (Exception ex) {
- ex.printStackTrace();
+ Logger.error(ex);
JOptionPane.showMessageDialog(((LinkButton) e.getSource()).getTopLevelAncestor(),
"Error opening link in browser.", "Error", JOptionPane.ERROR_MESSAGE);
}
diff --git a/src/org/infinity/gui/NewChrSettings.java b/src/org/infinity/gui/NewChrSettings.java
index 68566b62f..b1dd81bd6 100644
--- a/src/org/infinity/gui/NewChrSettings.java
+++ b/src/org/infinity/gui/NewChrSettings.java
@@ -20,8 +20,9 @@
import javax.swing.text.PlainDocument;
public final class NewChrSettings extends NewAbstractSettings {
+ private final ChrConfig config;
+
private JTextField tfName;
- private ChrConfig config;
public NewChrSettings(Window parent) {
super(parent, "CHR settings");
@@ -100,7 +101,7 @@ private void initDialog(Window parent) {
// -------------------------- INNER CLASSES --------------------------
- public class ChrConfig {
+ public static class ChrConfig {
private String name; // field at offset 0x08
public ChrConfig() {
@@ -125,14 +126,14 @@ private void setName(String newName) {
}
// Ensures a size limit on byte level
- private class FixedDocument extends PlainDocument {
- private int maxLength;
- private JTextField textField;
+ private static class FixedDocument extends PlainDocument {
+ private final int maxLength;
+ private final JTextField textField;
FixedDocument(JTextField text, int length) {
super();
textField = text;
- maxLength = length >= 0 ? length : 0;
+ maxLength = Math.max(length, 0);
}
@Override
diff --git a/src/org/infinity/gui/NewProSettings.java b/src/org/infinity/gui/NewProSettings.java
index 989013395..aac60b526 100644
--- a/src/org/infinity/gui/NewProSettings.java
+++ b/src/org/infinity/gui/NewProSettings.java
@@ -19,8 +19,9 @@
public final class NewProSettings extends NewAbstractSettings {
private static final String[] PRO_DESC = { "1 - No BAM", "2 - Single target", "3 - Area of effect" };
+ private final ProConfig config;
+
private JComboBox cbType;
- private ProConfig config;
public NewProSettings(Window parent) {
super(parent, "PRO settings");
@@ -98,7 +99,7 @@ private void initDialog(Window parent) {
// -------------------------- INNER CLASSES --------------------------
- public class ProConfig {
+ public static class ProConfig {
private int proType; // field at offset 0x08
public ProConfig() {
diff --git a/src/org/infinity/gui/NewResSettings.java b/src/org/infinity/gui/NewResSettings.java
index 45101de96..af5395504 100644
--- a/src/org/infinity/gui/NewResSettings.java
+++ b/src/org/infinity/gui/NewResSettings.java
@@ -91,8 +91,9 @@ private enum GameType {
private GameType gameType; // 0=unknown, 1=BG2, 2=IWD, 3=IWD2
private int lastStrref;
+ private final ResConfig config;
+
private InfinityTextArea taText;
- private ResConfig config;
public NewResSettings(Window parent) {
super(parent, "Biography settings");
@@ -265,7 +266,7 @@ public void keyTyped(KeyEvent event) {
// -------------------------- INNER CLASSES --------------------------
- public class ResConfig {
+ public static class ResConfig {
private String desc; // field at offset 0x08
public ResConfig() {
diff --git a/src/org/infinity/gui/OpenFileFrame.java b/src/org/infinity/gui/OpenFileFrame.java
index d794d8dbf..f03396511 100644
--- a/src/org/infinity/gui/OpenFileFrame.java
+++ b/src/org/infinity/gui/OpenFileFrame.java
@@ -46,6 +46,7 @@
import org.infinity.resource.ResourceFactory;
import org.infinity.resource.key.FileResourceEntry;
import org.infinity.resource.key.ResourceEntry;
+import org.infinity.util.Logger;
import org.infinity.util.io.FileEx;
import org.infinity.util.io.FileManager;
@@ -82,17 +83,17 @@ public OpenFileFrame() {
tfExternalName.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
- bOpenNew.setEnabled(rbInternal.isSelected() || tfExternalName.getText().length() > 0);
+ bOpenNew.setEnabled(rbInternal.isSelected() || !tfExternalName.getText().isEmpty());
}
@Override
public void removeUpdate(DocumentEvent e) {
- bOpenNew.setEnabled(rbInternal.isSelected() || tfExternalName.getText().length() > 0);
+ bOpenNew.setEnabled(rbInternal.isSelected() || !tfExternalName.getText().isEmpty());
}
@Override
public void changedUpdate(DocumentEvent e) {
- bOpenNew.setEnabled(rbInternal.isSelected() || tfExternalName.getText().length() > 0);
+ bOpenNew.setEnabled(rbInternal.isSelected() || !tfExternalName.getText().isEmpty());
}
});
lpInternal = new TextListPanel<>(new ArrayList<>(ResourceFactory.getResourceTreeModel().getResourceEntries()));
@@ -191,7 +192,7 @@ public void mouseClicked(MouseEvent event) {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == rbExternal) {
bOpen.setEnabled(false);
- bOpenNew.setEnabled(tfExternalName.getText().length() > 0);
+ bOpenNew.setEnabled(!tfExternalName.getText().isEmpty());
lpInternal.setEnabled(false);
tfExternalName.setEnabled(true);
bExternalBrowse.setEnabled(true);
@@ -275,7 +276,7 @@ public void drop(DropTargetDropEvent event) {
event.acceptDrop(DnDConstants.ACTION_COPY);
files = (List) event.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
event.dropComplete(false);
return;
}
diff --git a/src/org/infinity/gui/OpenResourceDialog.java b/src/org/infinity/gui/OpenResourceDialog.java
index 78c17fa6c..d377ab36b 100644
--- a/src/org/infinity/gui/OpenResourceDialog.java
+++ b/src/org/infinity/gui/OpenResourceDialog.java
@@ -48,6 +48,7 @@
import org.infinity.resource.ResourceFactory;
import org.infinity.resource.key.ResourceEntry;
import org.infinity.util.DataString;
+import org.infinity.util.Logger;
import org.infinity.util.SimpleListModel;
/**
@@ -134,6 +135,7 @@ public void insertUpdate(DocumentEvent e) {
setSearchLock(true);
updateListSelection(searchDoc.getText(0, searchDoc.getLength()));
} catch (BadLocationException ble) {
+ Logger.trace(ble);
} finally {
setSearchLock(false);
}
@@ -147,6 +149,7 @@ public void removeUpdate(DocumentEvent e) {
setSearchLock(true);
updateListSelection(searchDoc.getText(0, searchDoc.getLength()));
} catch (BadLocationException ble) {
+ Logger.trace(ble);
} finally {
setSearchLock(false);
}
@@ -160,6 +163,7 @@ public void changedUpdate(DocumentEvent e) {
setSearchLock(true);
updateListSelection(searchDoc.getText(0, searchDoc.getLength()));
} catch (BadLocationException ble) {
+ Logger.trace(ble);
} finally {
setSearchLock(false);
}
@@ -239,7 +243,7 @@ private void acceptDialog() {
setVisible(false);
List entries = list.getSelectedValuesList();
if (entries != null) {
- result = entries.toArray(new ResourceEntry[entries.size()]);
+ result = entries.toArray(new ResourceEntry[0]);
} else {
result = new ResourceEntry[0];
}
@@ -290,7 +294,7 @@ private void updateList(List entries) {
listModel.clear();
if (entries != null) {
listModel.addAll(entries);
- if (listModel.size() > 0) {
+ if (!listModel.isEmpty()) {
list.setSelectedIndex(0);
list.ensureIndexIsVisible(0);
list.requestFocusInWindow();
@@ -347,11 +351,7 @@ private void updateListSelection(String search) {
String entry = (entries.length > 0) ? entries[0] : "";
int idx = getClosestIndex(entry);
list.setSelectedIndex(idx);
- if (idx >= 0) {
- list.ensureIndexIsVisible(idx);
- } else {
- list.ensureIndexIsVisible(0);
- }
+ list.ensureIndexIsVisible(Math.max(idx, 0));
}
}
diff --git a/src/org/infinity/gui/PreferencesDialog.java b/src/org/infinity/gui/PreferencesDialog.java
index a11c3ddc9..8ab566f67 100644
--- a/src/org/infinity/gui/PreferencesDialog.java
+++ b/src/org/infinity/gui/PreferencesDialog.java
@@ -74,6 +74,7 @@
import org.infinity.AppOption;
import org.infinity.NearInfinity;
import org.infinity.gui.menu.BrowserMenuBar;
+import org.infinity.gui.menu.LogLevel;
import org.infinity.gui.menu.OptionsMenuItem;
import org.infinity.gui.menu.OptionsMenuItem.CharsetInfo;
import org.infinity.gui.menu.OverrideMode;
@@ -88,6 +89,7 @@
import org.infinity.gui.options.OptionGroupBox;
import org.infinity.icon.Icons;
import org.infinity.resource.Profile;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/**
@@ -227,6 +229,11 @@ public String toString() {
+ "Java Runtime, and available memory on the main panel while no game resource is opened "
+ "in the main panel.",
AppOption.SHOW_SYS_INFO),
+ OptionCheckBox.create(AppOption.SHOW_MEM_STATUS.getName(), AppOption.SHOW_MEM_STATUS.getLabel(),
+ "With this option enabled the current memory usage will be shown in the status bar of the Near Infinity "
+ + "main window. This value is updated in regular intervals."
+ + "Note: Changing this option requires a restart of Near Infinity to be effective.
",
+ AppOption.SHOW_MEM_STATUS),
OptionCheckBox.create(AppOption.OPEN_BOOKMARKS_PROMPT.getName(), AppOption.OPEN_BOOKMARKS_PROMPT.getLabel(),
"With this option enabled a confirmation dialog is shown whenever you try to load a bookmarked game."
+ "Note: This option can also be changed in the confirmation dialog of the "
@@ -472,6 +479,19 @@ public String toString() {
),
OptionCategory.create(Category.VISUAL_OPTIONS,
OptionGroup.createDefault(
+ OptionGroupBox.create(AppOption.APP_LOG_LEVEL.getName(), AppOption.APP_LOG_LEVEL.getLabel(),
+ "Specify the minimum severity level for log messages to be shown in the debug console."
+ + "
" + LogLevel.TRACE + ": (Not recommended) Log messages for all "
+ + "unexpected and many expected results which is only useful for developers.
"
+ + "
" + LogLevel.DEBUG + ": Log messages for diagnostic purposes which can be "
+ + "relevant for troubleshooting issues with the application.
"
+ + "
" + LogLevel.INFO + ": Log helpful information as well as warnings and "
+ + "errors.
"
+ + "
" + LogLevel.WARN + ": Log only warnings and errors. Choose this option to "
+ + "reduce the amount of messages without losing relevant information.
"
+ + "
" + LogLevel.ERROR + ": Log only error messages.
"
+ + "
" + LogLevel.OFF + ": This option disables logging completely.
",
+ LogLevel.INFO.ordinal(), LogLevel.values(), AppOption.APP_LOG_LEVEL),
OptionGroupBox.create(AppOption.SHOW_RES_REF.getName(), AppOption.SHOW_RES_REF.getLabel(),
"Choose how resources should be displayed in resource lists.", ResRefMode.RefName.ordinal(),
ResRefMode.values(), AppOption.SHOW_RES_REF),
@@ -1380,7 +1400,7 @@ private void globalFontSizeOnAccept(OptionGroupBox gb) {
gb.getOption().setValue(-size);
}
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1403,7 +1423,7 @@ private boolean globalFontSizeOnSelect(OptionGroupBox gb) {
int minFontSize = Arrays.stream(fontSizes).filter(i -> i > 0).min().orElse(0);
int maxFontSize = Arrays.stream(fontSizes).max().orElse(0);
String ret = JOptionPane.showInputDialog(NearInfinity.getInstance(),
- String.format("Enter font size in percent (%d - %d):", minFontSize, maxFontSize), Integer.valueOf(size));
+ String.format("Enter font size in percent (%d - %d):", minFontSize, maxFontSize), size);
if (ret == null) {
selectMatchingGlobalFontSize(gb, size);
return true;
@@ -1431,7 +1451,7 @@ private boolean globalFontSizeOnSelect(OptionGroupBox gb) {
return true;
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return true;
@@ -1463,7 +1483,7 @@ private void lookAndFeelClassOnInit(OptionGroupBox gb) {
label = ((LookAndFeel) o).getName();
}
} catch (Exception e) {
-// e.printStackTrace();
+// Logger.error(e);
}
if (label == null) {
@@ -1484,7 +1504,7 @@ private void lookAndFeelClassOnInit(OptionGroupBox gb) {
// need to track item index separately in case that a L&F class is not accessible
curIdx++;
} catch (Exception e) {
-// e.printStackTrace();
+// Logger.error(e);
}
}
@@ -1504,7 +1524,7 @@ private void lookAndFeelClassOnAccept(OptionGroupBox gb) {
final DataItem item = (DataItem) gb.getItem(gb.getSelectedIndex());
gb.getOption().setValue(item.getData().getClassName());
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1555,9 +1575,9 @@ private void textFontOnAccept(OptionGroupBox gb) {
AppOption.TEXT_FONT_SIZE.setValue(font.getSize());
AppOption.TEXT_FONT_STYLE.setValue(font.getStyle());
}
- gb.getOption().setValue(Integer.valueOf(index));
+ gb.getOption().setValue(index);
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1583,7 +1603,7 @@ private boolean textFontOnSelect(OptionGroupBox gb) {
}
}
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return true;
@@ -1642,7 +1662,7 @@ private void tlkCharsetTypeOnAccept(OptionGroupBox gb) {
gb.getOption().setValue(item.getData());
}
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1652,6 +1672,7 @@ private boolean tlkCharsetTypeOnSelect(OptionGroupBox gb) {
final DataItem> item = (DataItem>) gb.getItem(gb.getSelectedIndex());
return item.getData() != null;
} catch (IndexOutOfBoundsException e) {
+ Logger.trace(e);
}
return false;
}
@@ -1704,7 +1725,7 @@ private void gameLanguagesOnAccept(OptionGroupBox gb) {
languageDefinitions = OptionsMenuItem.updateGameLanguages(languageDefinitions, Profile.getGame(), langCode);
gb.getOption().setValue(languageDefinitions);
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -1768,7 +1789,7 @@ private void uiScaleFactorOnAccept(OptionGroupBox gb) {
final DataItem item = (DataItem) gb.getItem(gb.getSelectedIndex());
gb.getOption().setValue(item.getData());
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1790,8 +1811,7 @@ private boolean uiScaleFactorOnSelect(OptionGroupBox gb) {
int minUiScale = Arrays.stream(scaleFactors).filter(i -> i > 0).min().orElse(0) / 2;
int maxUiScale = Arrays.stream(scaleFactors).max().orElse(0);
String ret = JOptionPane.showInputDialog(NearInfinity.getInstance(),
- String.format("Enter UI scaling factor in percent (%d - %d):", minUiScale, maxUiScale),
- Integer.valueOf(factor));
+ String.format("Enter UI scaling factor in percent (%d - %d):", minUiScale, maxUiScale), factor);
if (ret == null) {
selectMatchingUiScaleFactor(gb, factor);
return true;
@@ -1819,7 +1839,7 @@ private boolean uiScaleFactorOnSelect(OptionGroupBox gb) {
return true;
} catch (IndexOutOfBoundsException e) {
- e.printStackTrace();
+ Logger.error(e);
}
return false;
}
@@ -1860,11 +1880,9 @@ private void selectMatchingGlobalFontSize(OptionGroupBox gb, int percent) {
private void setUiScaleFactorEnabled(boolean enabled) {
OptionBase o = optionRoot.findOption(NearInfinity.APP_UI_SCALE_FACTOR);
if (o instanceof OptionGroupBox) {
- if (o instanceof OptionGroupBox) {
- final OptionGroupBox uiScaleFactor = (OptionGroupBox) o;
- uiScaleFactor.getUiComboBox().setEnabled(enabled);
- uiScaleFactor.getUiLabel().setEnabled(enabled);
- }
+ final OptionGroupBox uiScaleFactor = (OptionGroupBox) o;
+ uiScaleFactor.getUiComboBox().setEnabled(enabled);
+ uiScaleFactor.getUiLabel().setEnabled(enabled);
}
}
@@ -2027,7 +2045,7 @@ public Component getListCellRendererComponent(JList> list, Object value, int i
if (fontInfo != null && fontInfo.getData() instanceof Font) {
final Font oldFont = label.getFont();
final Font newFont = (Font) fontInfo.getData();
- label.setFont(Misc.getScaledFont(newFont.deriveFont(oldFont.getSize())));
+ label.setFont(Misc.getScaledFont(newFont.deriveFont(oldFont.getSize2D())));
label.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
diff --git a/src/org/infinity/gui/QuickSearch.java b/src/org/infinity/gui/QuickSearch.java
index 98a83c87a..f37fa24d1 100644
--- a/src/org/infinity/gui/QuickSearch.java
+++ b/src/org/infinity/gui/QuickSearch.java
@@ -12,7 +12,6 @@
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
-import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.SortedSet;
@@ -39,6 +38,7 @@
import org.infinity.resource.key.ResourceEntry;
import org.infinity.resource.key.ResourceTreeFolder;
import org.infinity.resource.key.ResourceTreeModel;
+import org.infinity.util.Logger;
import org.infinity.util.MapTree;
import org.infinity.util.Misc;
@@ -171,7 +171,7 @@ public void popupWindowWillBecomeInvisible(PopupWindowEvent event) {
cbSearch = new WideComboBox<>();
cbSearch.setRenderer(new QuickListCellRenderer());
- cbSearch.setFormatter(item -> QuickListCellRenderer.getFormattedValue(item));
+ cbSearch.setFormatter(QuickListCellRenderer::getFormattedValue);
cbSearch.setPreferredSize(Misc.getPrototypeSize(cbSearch, "WWWWWWWW.WWWW")); // space for at least 8.4 characters
cbSearch.setEditable(true);
tcEdit = (JTextComponent) cbSearch.getEditor().getEditorComponent();
@@ -269,9 +269,7 @@ private void generateRootNode() {
ResourceTreeModel model = tree.getModel();
if (model != null) {
SortedSet entries = generateResourceList(model.getRoot(), null);
- if (entries != null) {
- list.addAll(entries);
- }
+ list.addAll(entries);
}
}
@@ -390,10 +388,10 @@ public void run() {
cbSearch.hidePopup(); // XXX: work-around to force visual update of file list
cbModel.removeAllElements();
- if (!keyword.isEmpty() && node != null && node.getValue() != null) {
+ if (!keyword.isEmpty() && node.getValue() != null) {
List list = node.getValue();
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- cbModel.addElement(iter.next());
+ for (ResourceEntry resourceEntry : list) {
+ cbModel.addElement(resourceEntry);
}
}
@@ -423,6 +421,7 @@ public void run() {
try {
monitor.wait();
} catch (InterruptedException e) {
+ Logger.trace(e);
}
}
}
diff --git a/src/org/infinity/gui/ResourceChooser.java b/src/org/infinity/gui/ResourceChooser.java
index 651907193..f057e3a8c 100644
--- a/src/org/infinity/gui/ResourceChooser.java
+++ b/src/org/infinity/gui/ResourceChooser.java
@@ -322,7 +322,7 @@ public void windowClosing(WindowEvent e) {
private class DialogOkAction extends AbstractAction implements ListSelectionListener {
public static final String ACTION_NAME = "OK";
- private JDialog dialog;
+ private final JDialog dialog;
public DialogOkAction(JDialog dialog) {
this.dialog = dialog;
@@ -348,7 +348,7 @@ public void valueChanged(ListSelectionEvent e) {
private class DialogCancelAction extends AbstractAction {
public static final String ACTION_NAME = "Cancel";
- private JDialog dialog;
+ private final JDialog dialog;
public DialogCancelAction(JDialog dialog) {
this.dialog = dialog;
diff --git a/src/org/infinity/gui/ResourceTree.java b/src/org/infinity/gui/ResourceTree.java
index 5049c8d32..43e97ca4b 100644
--- a/src/org/infinity/gui/ResourceTree.java
+++ b/src/org/infinity/gui/ResourceTree.java
@@ -68,6 +68,7 @@
import org.infinity.resource.key.ResourceTreeFolder;
import org.infinity.resource.key.ResourceTreeModel;
import org.infinity.util.IconCache;
+import org.infinity.util.Logger;
import org.infinity.util.Operation;
import org.infinity.util.io.FileEx;
import org.infinity.util.io.FileManager;
@@ -302,7 +303,7 @@ public static void renameResource(FileResourceEntry entry) {
} catch (IOException e) {
JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error renaming file \"" + filename + "\"!", "Error",
JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
return;
}
// ResourceFactory.getResourceTreeModel().resourceEntryChanged(entry);
@@ -323,7 +324,7 @@ public static void deleteResource(ResourceEntry entry) {
try {
Files.delete(bakFile);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
try {
@@ -331,10 +332,10 @@ public static void deleteResource(ResourceEntry entry) {
} catch (IOException e) {
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
"Error deleting file \"" + entry.getResourceName() + "\"!", "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
} else if (entry instanceof BIFFResourceEntry) {
- String options[] = { "Delete", "Cancel" };
+ String[] options = { "Delete", "Cancel" };
if (JOptionPane.showOptionDialog(NearInfinity.getInstance(),
"Are you sure you want to delete the " + "override file " + entry + '?', "Delete file",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) {
@@ -346,7 +347,7 @@ public static void deleteResource(ResourceEntry entry) {
try {
Files.delete(bakFile);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
try {
@@ -354,7 +355,7 @@ public static void deleteResource(ResourceEntry entry) {
} catch (IOException e) {
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
"Error deleting file \"" + entry.getResourceName() + "\"!", "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -376,8 +377,7 @@ public static void restoreResource(ResourceEntry entry) {
// .bak available -> restore .bak version
Path curFile = getCurrentFile(entry);
Path tmpFile = getTempFile(curFile);
- if (curFile != null && FileEx.create(curFile).isFile() && bakFile != null
- && FileEx.create(bakFile).isFile()) {
+ if (curFile != null && FileEx.create(curFile).isFile() && FileEx.create(bakFile).isFile()) {
try {
Files.move(curFile, tmpFile);
try {
@@ -385,7 +385,7 @@ public static void restoreResource(ResourceEntry entry) {
try {
Files.delete(tmpFile);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Backup has been restored successfully.",
"Restore backup", JOptionPane.INFORMATION_MESSAGE);
@@ -401,11 +401,11 @@ public static void restoreResource(ResourceEntry entry) {
+ String.format("Please manually rename the file \"%s\" into \"%s\", located in \n + \"%s\"",
tmpName, curName, path),
"Critical Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
return;
}
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
@@ -420,7 +420,7 @@ public static void restoreResource(ResourceEntry entry) {
} catch (IOException e) {
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
"Error removing file \"" + entry + "\" from override folder!", "Error", JOptionPane.ERROR_MESSAGE);
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -442,7 +442,7 @@ public static void createZipFile(Path path) {
JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Zip file created.", "Information",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.error(e);
wb.setBlocked(false);
JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error while creating zip file.", "Error",
JOptionPane.ERROR_MESSAGE);
@@ -540,10 +540,8 @@ private final class TreeExpandListener implements TreeExpansionListener, TreeWil
public TreeExpandListener(JTree tree) {
this.tree = Objects.requireNonNull(tree);
this.expanding = false;
- if (this.tree != null) {
- this.tree.addTreeWillExpandListener(this);
- this.tree.addTreeExpansionListener(this);
- }
+ this.tree.addTreeWillExpandListener(this);
+ this.tree.addTreeExpansionListener(this);
}
@Override
@@ -727,13 +725,13 @@ public void actionPerformed(ActionEvent event) {
new ViewFrame(NearInfinity.getInstance(), res);
}
} catch (NullPointerException e) {
- System.err.println("Does not exist in BIFF: " + node);
+ Logger.warn("Does not exist in BIFF: {}", node);
JOptionPane.showMessageDialog(NearInfinity.getInstance(),
"Does not exist in BIFF: " + node, "Error", JOptionPane.ERROR_MESSAGE);
}
} else if (event.getSource() == miReference && node != null) {
Resource res = ResourceFactory.getResource(node);
- if (res != null && res instanceof Referenceable) {
+ if (res instanceof Referenceable) {
if (((Referenceable) res).isReferenceable()) {
((Referenceable) res).searchReferences(NearInfinity.getInstance());
} else {
diff --git a/src/org/infinity/gui/ScriptTextArea.java b/src/org/infinity/gui/ScriptTextArea.java
index 9e2dfa144..980b8e8a9 100644
--- a/src/org/infinity/gui/ScriptTextArea.java
+++ b/src/org/infinity/gui/ScriptTextArea.java
@@ -43,6 +43,7 @@
import org.infinity.resource.text.modes.BCSTokenMaker;
import org.infinity.util.CreMapCache;
import org.infinity.util.IdsMapCache;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
/**
@@ -73,8 +74,8 @@ private enum IconType {
// Special popup menu for interactive resource references
private final ScriptPopupMenu menu = new ScriptPopupMenu();
- private Signatures triggers;
- private Signatures actions;
+ private final Signatures triggers;
+ private final Signatures actions;
/**
* Constructs a new script text area with BCS language settings.
@@ -150,9 +151,7 @@ protected void paintComponent(Graphics g) {
SortedMap map = tokenMap.subMap(offsetMin, offsetMax);
// processing interactive tokens of visible area
- Iterator iter = map.keySet().iterator();
- while (iter.hasNext()) {
- Integer key = iter.next();
+ for (Integer key : map.keySet()) {
InteractiveToken itoken = map.get(key);
if (itoken.isLink() && !itoken.isSilent()) {
@@ -174,6 +173,7 @@ protected void paintComponent(Graphics g) {
g2d.setStroke(oldStroke);
g2d.setColor(oldColor);
} catch (BadLocationException ble) {
+ Logger.trace(ble);
}
}
}
@@ -194,10 +194,8 @@ public String getToolTipText(MouseEvent e) {
int ofsMin = getLineStartOffset(line);
int ofsMax = getLineEndOffset(line);
SortedMap map = tokenMap.subMap(ofsMin, ofsMax);
- Iterator iter = map.values().iterator();
- while (iter.hasNext()) {
- InteractiveToken itoken = iter.next();
+ for (InteractiveToken itoken : map.values()) {
if (itoken.isTooltip()) {
if (offset >= itoken.position && offset < itoken.position + itoken.length) {
retVal = itoken.tooltip;
@@ -206,6 +204,7 @@ public String getToolTipText(MouseEvent e) {
}
}
} catch (BadLocationException ble) {
+ Logger.trace(ble);
} finally {
tokenMapLock.unlock();
}
@@ -325,9 +324,7 @@ private void handlePopup(MouseEvent e) {
SortedMap map = tokenMap.subMap(minOffset, maxOffset);
- Iterator iter = map.values().iterator();
- while (iter.hasNext()) {
- InteractiveToken token = iter.next();
+ for (InteractiveToken token : map.values()) {
// generate list of resource links
menu.clearResEntries();
if (token.isLink()) {
@@ -341,6 +338,7 @@ private void handlePopup(MouseEvent e) {
}
}
} catch (BadLocationException ble) {
+ Logger.trace(ble);
} finally {
tokenMapLock.unlock();
}
@@ -370,6 +368,7 @@ private void updateInteractiveTokens(boolean reset) {
iter.remove();
}
} catch (BadLocationException ble) {
+ Logger.trace(ble);
}
}
@@ -382,6 +381,7 @@ private void updateInteractiveTokens(boolean reset) {
iter.remove();
}
} catch (BadLocationException ble) {
+ Logger.trace(ble);
}
}
@@ -424,6 +424,7 @@ private void updateInteractiveTokens(boolean reset) {
}
}
} catch (BadLocationException ble) {
+ Logger.trace(ble);
}
} finally {
tokenMapLock.unlock();
@@ -482,7 +483,7 @@ private InteractiveToken updateSymbolToken(Token token) {
Long value = IdsMapCache.getIdsValue(idsRef, token.getLexeme(), null);
if (value != null) {
retVal = new InteractiveToken(token.getOffset(), token.length(),
- idsRef + ": " + value.longValue() + " (0x" + Long.toHexString(value) + ")",
+ idsRef + ": " + value + " (0x" + Long.toHexString(value) + ")",
ResourceFactory.getResourceEntry(idsRef), getForegroundForToken(token));
}
}
@@ -503,7 +504,7 @@ private InteractiveToken updateStringToken(Token token) {
String delim = "\"~%";
int v1 = delim.indexOf(value.charAt(0));
int v2 = delim.indexOf(value.charAt(value.length() - 1));
- if (v1 > -1 && v2 > -1 && v1 == v2) {
+ if (v2 > -1 && v1 == v2) {
value = value.substring(1, value.length() - 1);
}
}
@@ -542,6 +543,7 @@ private InteractiveToken updateStringToken(Token token) {
resList.add(ResourceFactory.getResourceEntry(resRef));
}
} catch (NumberFormatException e) {
+ Logger.trace(e);
}
if (res != null) {
if (i > 0) {
diff --git a/src/org/infinity/gui/ScrollPopupMenu.java b/src/org/infinity/gui/ScrollPopupMenu.java
index 36b2c5a8e..4a66c691e 100644
--- a/src/org/infinity/gui/ScrollPopupMenu.java
+++ b/src/org/infinity/gui/ScrollPopupMenu.java
@@ -209,7 +209,7 @@ private void clearModified() {
// -------------------------- INNER CLASSES --------------------------
- protected class ScrollPopupMenuLayout implements LayoutManager {
+ protected static class ScrollPopupMenuLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {
}
diff --git a/src/org/infinity/gui/SortableTable.java b/src/org/infinity/gui/SortableTable.java
index b1be0ec35..595d4c233 100644
--- a/src/org/infinity/gui/SortableTable.java
+++ b/src/org/infinity/gui/SortableTable.java
@@ -14,7 +14,6 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -35,6 +34,7 @@
import org.infinity.icon.Icons;
import org.infinity.resource.Profile;
import org.infinity.util.ArrayUtil;
+import org.infinity.util.Logger;
import org.infinity.util.io.FileEx;
public final class SortableTable extends JTable implements MouseListener {
@@ -129,7 +129,7 @@ private void saveResult(Component parent, String dialogTitle, String header) {
} catch (IOException ex) {
JOptionPane.showMessageDialog(parent, "Error while saving " + output + " (details in the trace)", "Error",
JOptionPane.ERROR_MESSAGE);
- ex.printStackTrace();
+ Logger.error(ex);
}
}
}
@@ -143,9 +143,7 @@ private void saveResult(Component parent, String dialogTitle, String header) {
*/
public void ensureIndexIsVisible(int index) {
Rectangle rect = getCellRect(index, 0, true);
- if (rect != null) {
- scrollRectToVisible(rect);
- }
+ scrollRectToVisible(rect);
}
@Override
@@ -239,12 +237,12 @@ public void sort() {
if (!tableItems.isEmpty()) {
final Object item = tableItems.get(0).getObjectAt(sortByColumn);
if (item != null && !getColumnClass(sortByColumn).isAssignableFrom(item.getClass())) {
- System.err.printf("Incompatible item type at column %d: expected %s, found %s\n",
+ Logger.warn("Incompatible item type at column {}: expected {}, found {}",
sortByColumn, getColumnClass(sortByColumn).getSimpleName(), item.getClass().getSimpleName());
}
}
- Collections.sort(tableItems, this);
+ tableItems.sort(this);
fireTableChangedEvent();
}
diff --git a/src/org/infinity/gui/StandardDialogs.java b/src/org/infinity/gui/StandardDialogs.java
index 05cbf42f1..7a511546f 100644
--- a/src/org/infinity/gui/StandardDialogs.java
+++ b/src/org/infinity/gui/StandardDialogs.java
@@ -232,7 +232,7 @@ private static Object createMessageObject(Object message, Object newItem) {
/** Ensures a valid result object for confirmation dialogs. */
private static Couple getDialogResult(int result, JCheckBox cbOption) {
- return Couple.with(result, cbOption != null ? cbOption.isSelected() : false);
+ return Couple.with(result, cbOption != null && cbOption.isSelected());
}
// -------------------------- INNER CLASSES --------------------------
diff --git a/src/org/infinity/gui/StatusBar.java b/src/org/infinity/gui/StatusBar.java
index 7f81ac270..0feabd123 100644
--- a/src/org/infinity/gui/StatusBar.java
+++ b/src/org/infinity/gui/StatusBar.java
@@ -4,32 +4,69 @@
package org.infinity.gui;
-import java.awt.BorderLayout;
import java.awt.Dimension;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.function.Function;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
+import javax.swing.JProgressBar;
import javax.swing.JTextArea;
+import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
-public final class StatusBar extends JPanel implements CaretListener {
+import org.infinity.gui.menu.BrowserMenuBar;
+
+public final class StatusBar extends JPanel implements CaretListener, ActionListener {
private final JLabel messageLabel = new JLabel();
private final JLabel cursorLabel = new JLabel();
+ private final JProgressBar memoryProgress = new JProgressBar(JProgressBar.HORIZONTAL);
+ private final Timer updateTimer = new Timer(2000, this);
public StatusBar() {
- super(new BorderLayout(3, 0));
+ super(new GridBagLayout());
+ setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
+
messageLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1),
BorderFactory.createLineBorder(UIManager.getColor("controlShadow"))));
cursorLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1),
BorderFactory.createLineBorder(UIManager.getColor("controlShadow"))));
cursorLabel.setPreferredSize(new Dimension(120, cursorLabel.getPreferredSize().height));
- add(messageLabel, BorderLayout.CENTER);
- add(cursorLabel, BorderLayout.EAST);
- setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ cursorLabel.setMinimumSize(cursorLabel.getPreferredSize());
+
+ if (BrowserMenuBar.getInstance().getOptions().showMemStatus()) {
+ memoryProgress.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1),
+ BorderFactory.createLineBorder(UIManager.getColor("controlShadow"))));
+ memoryProgress.setStringPainted(true);
+ memoryProgress.setMinimumSize(memoryProgress.getPreferredSize());
+ }
+
+ final GridBagConstraints c = new GridBagConstraints();
+ ViewerUtil.setGBC(c, 0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH,
+ new Insets(0, 0, 0, 0), 0, 0);
+ add(messageLabel, c);
+ ViewerUtil.setGBC(c, 1, 0, 1, 1, 0.0, 1.0, GridBagConstraints.LINE_START, GridBagConstraints.VERTICAL,
+ new Insets(0, 3, 0, 0), 0, 0);
+ add(cursorLabel, c);
+
+ if (BrowserMenuBar.getInstance().getOptions().showMemStatus()) {
+ ViewerUtil.setGBC(c, 2, 0, 1, 1, 0.0, 1.0, GridBagConstraints.LINE_START, GridBagConstraints.VERTICAL,
+ new Insets(0, 3, 0, 0), 0, 0);
+ add(memoryProgress, c);
+
+ updateMemoryProgress();
+ updateTimer.setInitialDelay(updateTimer.getDelay());
+ updateTimer.setRepeats(true);
+ updateTimer.start();
+ }
}
// --------------------- Begin Interface CaretListener ---------------------
@@ -50,13 +87,24 @@ public void caretUpdate(CaretEvent event) {
// --------------------- End Interface CaretListener ---------------------
+ // --------------------- Begin Interface ActionListener ---------------------
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == updateTimer) {
+ updateMemoryProgress();
+ }
+ }
+
+ // --------------------- End Interface ActionListener ---------------------
+
public void setCursorText(String text) {
cursorLabel.setText(' ' + text);
}
public String getCursorText() {
String text = cursorLabel.getText();
- if (text.length() > 0) {
+ if (!text.isEmpty()) {
return text.substring(1);
} else {
return "";
@@ -70,10 +118,44 @@ public void setMessage(String msg) {
public String getMessage() {
String text = messageLabel.getText();
- if (text.length() > 0) {
+ if (!text.isEmpty()) {
return text.substring(1);
} else {
return "";
}
}
+
+ /**
+ * Calculates currently used memory and updates the {@link JProgressBar} element.
+ */
+ private void updateMemoryProgress() {
+ // using non-linear scaling for better resolution in lower memory ranges
+ final Function logScaled = value -> (int) Math.pow(Math.log(value / 1024.0), 6.0);
+
+ final Runtime rt = Runtime.getRuntime();
+
+ // total memory available to the VM
+ final long maxMemory = rt.maxMemory();
+ memoryProgress.setMaximum(logScaled.apply(maxMemory));
+
+ // used memory
+ final long usedMemory = rt.totalMemory() - rt.freeMemory();
+ final int value = Math.min(Math.max(logScaled.apply(usedMemory), 0), memoryProgress.getMaximum());
+ memoryProgress.setValue(value);
+
+ final long usedMemoryMB = usedMemory / (1024L * 1024L);
+ if (usedMemoryMB >= 1024L) {
+ final double usedMemoryGB = usedMemoryMB / 1024.0;
+ memoryProgress.setString(String.format("%.2f GB", usedMemoryGB));
+ } else {
+ memoryProgress.setString(usedMemoryMB + " MB");
+ }
+
+ // updating tooltip
+ final long maxMemoryMB = maxMemory / (1024L * 1024L);
+ final double usedMemoryPercent = (double) usedMemory / (double) maxMemory * 100.0;
+ final String msg = String.format("Memory used by Near Infinity: %d MB of %d MB (%.1f %%)",
+ usedMemoryMB, maxMemoryMB, usedMemoryPercent);
+ memoryProgress.setToolTipText(msg);
+ }
}
diff --git a/src/org/infinity/gui/StringEditor.java b/src/org/infinity/gui/StringEditor.java
index 469209310..60fc85b6b 100644
--- a/src/org/infinity/gui/StringEditor.java
+++ b/src/org/infinity/gui/StringEditor.java
@@ -57,6 +57,7 @@
import org.infinity.search.SearchClient;
import org.infinity.search.SearchMaster;
import org.infinity.search.StringReferenceSearcher;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StringTable;
import org.infinity.util.io.FileEx;
@@ -143,7 +144,7 @@ protected Void doInBackground() throws Exception {
worker.execute();
worker.get();
} catch (InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -595,15 +596,20 @@ private void updateTableItem(int row) {
StringTable.StringEntry entry = getSelectedEntry();
if (cellName != null && cellValue != null && entry != null) {
String name = cellName.toString();
- if (StringEditor.TLK_FLAGS.equals(name)) {
- entry.setFlags((short) ((IsNumeric) cellValue).getValue());
- } else if (StringEditor.TLK_SOUND.equals(name)) {
- ResourceRef ref = (ResourceRef) cellValue;
- entry.setSoundRef(ref.isEmpty() ? "" : ref.getText());
- } else if (StringEditor.TLK_VOLUME.equals(name)) {
- entry.setVolume(((IsNumeric) cellValue).getValue());
- } else if (StringEditor.TLK_PITCH.equals(name)) {
- entry.setPitch(((IsNumeric) cellValue).getValue());
+ switch (name) {
+ case StringEditor.TLK_FLAGS:
+ entry.setFlags((short) ((IsNumeric) cellValue).getValue());
+ break;
+ case StringEditor.TLK_SOUND:
+ ResourceRef ref = (ResourceRef) cellValue;
+ entry.setSoundRef(ref.isEmpty() ? "" : ref.getText());
+ break;
+ case StringEditor.TLK_VOLUME:
+ entry.setVolume(((IsNumeric) cellValue).getValue());
+ break;
+ case StringEditor.TLK_PITCH:
+ entry.setPitch(((IsNumeric) cellValue).getValue());
+ break;
}
updateModifiedUI(getSelectedDialogType());
}
@@ -745,7 +751,7 @@ private void save(boolean interactive) {
JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
} finally {
bSync.setEnabled(isSync);
bAdd.setEnabled(isAdd);
@@ -818,7 +824,8 @@ protected Void doInBackground() throws Exception {
WindowBlocker blocker = new WindowBlocker(StringEditor.this);
try {
blocker.setBlocked(true);
- showEntry(addEntry(new StringTable.StringEntry(null), new StringTable.StringEntry(null), true));
+ showEntry(addEntry(new StringTable.StringEntry(null, StringTable.FLAGS_DEFAULT),
+ new StringTable.StringEntry(null, StringTable.FLAGS_DEFAULT), true));
} finally {
blocker.setBlocked(false);
}
diff --git a/src/org/infinity/gui/StringLookup.java b/src/org/infinity/gui/StringLookup.java
index 25c95f24f..fbf06b06f 100644
--- a/src/org/infinity/gui/StringLookup.java
+++ b/src/org/infinity/gui/StringLookup.java
@@ -54,7 +54,7 @@ public StringLookup() {
Center.center(this, NearInfinity.getInstance().getBounds());
// pre-caching string table to significantly reduce search time
- new Thread(() -> StringTable.ensureFullyLoaded()).start();
+ new Thread(StringTable::ensureFullyLoaded).start();
}
// --------------------- Begin Interface SearchClient ---------------------
diff --git a/src/org/infinity/gui/StructCellEditor.java b/src/org/infinity/gui/StructCellEditor.java
index 8a7cf7981..a0cd633ec 100644
--- a/src/org/infinity/gui/StructCellEditor.java
+++ b/src/org/infinity/gui/StructCellEditor.java
@@ -35,7 +35,7 @@ public class StructCellEditor extends AbstractCellEditor implements TableCellEdi
protected InlineEditable editorComponent;
/**
- * An integer specifying the number of clicks needed to start editing. Even if {@codeclickCountToStart} is defined as
+ * An integer specifying the number of clicks needed to start editing. Even if {@code clickCountToStart} is defined as
* zero, it will not initiate until a click occurs.
*/
protected int clickCountToStart;
diff --git a/src/org/infinity/gui/StructViewer.java b/src/org/infinity/gui/StructViewer.java
index 518d9b2d2..d79eea0a9 100644
--- a/src/org/infinity/gui/StructViewer.java
+++ b/src/org/infinity/gui/StructViewer.java
@@ -68,7 +68,6 @@
import org.infinity.datatype.Editable;
import org.infinity.datatype.EffectType;
import org.infinity.datatype.Flag;
-import org.infinity.datatype.HexNumber;
import org.infinity.datatype.InlineEditable;
import org.infinity.datatype.IsNumeric;
import org.infinity.datatype.IsReference;
@@ -82,6 +81,8 @@
import org.infinity.datatype.Unknown;
import org.infinity.datatype.UnknownBinary;
import org.infinity.datatype.UnknownDecimal;
+import org.infinity.datatype.UnsignDecNumber;
+import org.infinity.datatype.UnsignHexNumber;
import org.infinity.gui.menu.BrowserMenuBar;
import org.infinity.gui.menu.ViewMode;
import org.infinity.icon.Icons;
@@ -105,6 +106,7 @@
import org.infinity.search.DialogStateReferenceSearcher;
import org.infinity.search.advanced.AdvancedSearch;
import org.infinity.search.advanced.SearchOptions;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
import org.infinity.util.StructClipboard;
import org.infinity.util.io.ByteBufferOutputStream;
@@ -129,6 +131,7 @@ public final class StructViewer extends JPanel implements ListSelectionListener,
public static final String CMD_TOBIN = "ToBin";
public static final String CMD_TODEC = "ToDec";
public static final String CMD_TOINT = "ToInt";
+ public static final String CMD_TOUINT = "ToUint";
public static final String CMD_TOHEXINT = "ToHexInt";
public static final String CMD_TOFLAGS = "ToFlags";
public static final String CMD_TORESLIST = "ToResList";
@@ -163,7 +166,8 @@ public final class StructViewer extends JPanel implements ListSelectionListener,
private final JMenuItem miToString = createMenuItem(CMD_TOSTRING, "Edit as string", Icons.ICON_REFRESH_16.getIcon(), this);
private final JMenuItem miToBin = createMenuItem(CMD_TOBIN, "Edit as binary data", Icons.ICON_REFRESH_16.getIcon(), this);
private final JMenuItem miToDec = createMenuItem(CMD_TODEC, "Edit as decimal data", Icons.ICON_REFRESH_16.getIcon(), this);
- private final JMenuItem miToInt = createMenuItem(CMD_TOINT, "Edit as number", Icons.ICON_REFRESH_16.getIcon(), this);
+ private final JMenuItem miToInt = createMenuItem(CMD_TOINT, "Edit as signed number", Icons.ICON_REFRESH_16.getIcon(), this);
+ private final JMenuItem miToUint = createMenuItem(CMD_TOUINT, "Edit as unsigned number", Icons.ICON_REFRESH_16.getIcon(), this);
private final JMenuItem miToHexInt = createMenuItem(CMD_TOHEXINT, "Edit as hexadecimal number", Icons.ICON_REFRESH_16.getIcon(), this);
private final JMenuItem miToFlags = createMenuItem(CMD_TOFLAGS, "Edit as bit field", Icons.ICON_REFRESH_16.getIcon(), this);
private final JMenuItem miReset = createMenuItem(CMD_RESET, "Reset field type", Icons.ICON_REFRESH_16.getIcon(), this);
@@ -288,6 +292,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
popupmenu.add(miToBin);
popupmenu.add(miToDec);
popupmenu.add(miToInt);
+ popupmenu.add(miToUint);
popupmenu.add(miToHexInt);
popupmenu.add(miToFlags);
popupmenu.add(miToResref);
@@ -312,6 +317,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
miToBin.setEnabled(false);
miToDec.setEnabled(false);
miToInt.setEnabled(false);
+ miToUint.setEnabled(false);
miToHexInt.setEnabled(false);
miToFlags.setEnabled(false);
miToResref.setEnabled(false);
@@ -376,7 +382,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
bRemove.addActionListener(this);
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -386,7 +392,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
miFindAttribute = new JMenuItem("selected attribute");
miFindAttribute.setEnabled(false);
miFindReferences = new JMenuItem("references to this file");
- miFindReferences.setEnabled(struct instanceof Resource && struct.getParent() == null);
+ miFindReferences.setEnabled(struct.getParent() == null);
miFindStateReferences = new JMenuItem("references to this state");
miFindStateReferences.setEnabled(false);
miFindRefToItem = new JMenuItem("references to selected item in this file");
@@ -523,7 +529,7 @@ public void actionPerformed(ActionEvent event) {
try {
struct.removeDatatype((AddRemovable) entry, true);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -547,7 +553,7 @@ public void actionPerformed(ActionEvent event) {
try {
pj.print();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -600,6 +606,8 @@ public void actionPerformed(ActionEvent event) {
convertAttribute(min, miToDec);
} else if (CMD_TOINT.equals(cmd)) {
convertAttribute(min, miToInt);
+ } else if (CMD_TOUINT.equals(cmd)) {
+ convertAttribute(min, miToUint);
} else if (CMD_TOHEXINT.equals(cmd)) {
convertAttribute(min, miToHexInt);
} else if (CMD_TOFLAGS.equals(cmd)) {
@@ -660,14 +668,19 @@ public void itemStateChanged(ItemEvent event) {
AddRemovable toadd = (AddRemovable) item.getClientProperty("prototype");
try {
toadd = ((HasChildStructs) struct).confirmAddEntry(toadd);
- if (toadd != null) {
+ } catch (Exception e) {
+ JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ if (toadd != null) {
+ try {
toadd = (AddRemovable) toadd.clone();
+ int index = struct.addDatatype(toadd);
+ table.getSelectionModel().setSelectionInterval(index, index);
+ table.scrollRectToVisible(table.getCellRect(index, 1, true));
+ } catch (Exception e) {
+ Logger.error(e);
}
- int index = struct.addDatatype(toadd);
- table.getSelectionModel().setSelectionInterval(index, index);
- table.scrollRectToVisible(table.getCellRect(index, 1, true));
- } catch (Exception e) {
- e.printStackTrace();
}
} else if (src == buttonPanel.getControlByType(ButtonPanel.Control.FIND_MENU)) {
final JMenuItem item = ((ButtonPopupMenu) src).getSelectedItem();
@@ -716,6 +729,7 @@ public void valueChanged(ListSelectionEvent event) {
miToBin.setEnabled(false);
miToDec.setEnabled(false);
miToInt.setEnabled(false);
+ miToUint.setEnabled(false);
miToHexInt.setEnabled(false);
miToFlags.setEnabled(false);
miToResref.setEnabled(false);
@@ -758,31 +772,32 @@ public void valueChanged(ListSelectionEvent event) {
miFindStateReferences.setEnabled(selected instanceof State);
}
final boolean isDataType = (selected instanceof Datatype);
- final boolean isReadable = (selected instanceof Readable);
- miToHex.setEnabled(isDataType && isReadable
+ miToHex.setEnabled(isDataType
&& !(selected instanceof Unknown || selected instanceof SectionCount || selected instanceof AbstractCode));
if (!miToHex.isEnabled() && (selected instanceof UnknownBinary || selected instanceof UnknownDecimal)) {
miToHex.setEnabled(true);
}
- miToBin.setEnabled(isDataType && isReadable && !(selected instanceof UnknownBinary
+ miToBin.setEnabled(isDataType && !(selected instanceof UnknownBinary
|| selected instanceof SectionCount || selected instanceof AbstractCode));
- miToDec.setEnabled(isDataType && isReadable && !(selected instanceof UnknownDecimal
+ miToDec.setEnabled(isDataType && !(selected instanceof UnknownDecimal
|| selected instanceof SectionCount || selected instanceof AbstractCode));
miToInt.setEnabled(
- isDataType && isReadable && ((Datatype) selected).getSize() <= 4 && !(selected instanceof SectionCount
+ isDataType && ((Datatype) selected).getSize() <= 4 && !(selected instanceof SectionCount
|| selected instanceof SectionOffset || selected instanceof AbstractCode));
- miToHexInt.setEnabled(isDataType && isReadable && ((Datatype) selected).getSize() <= 4
- && !(selected instanceof HexNumber || selected instanceof SectionCount || selected instanceof SectionOffset
- || selected instanceof AbstractCode));
- miToFlags.setEnabled(isDataType && isReadable && ((Datatype) selected).getSize() <= 4
+ miToUint.setEnabled(
+ isDataType && ((Datatype) selected).getSize() <= 4 && !(selected instanceof SectionCount
+ || selected instanceof SectionOffset || selected instanceof AbstractCode));
+ miToHexInt.setEnabled(isDataType && ((Datatype) selected).getSize() <= 4
+ && !(selected instanceof UnsignHexNumber || selected instanceof SectionCount ||
+ selected instanceof SectionOffset || selected instanceof AbstractCode));
+ miToFlags.setEnabled(isDataType && ((Datatype) selected).getSize() <= 4
&& !(selected instanceof Flag || selected instanceof SectionCount || selected instanceof SectionOffset
|| selected instanceof AbstractCode));
miToResref.setEnabled(
- isDataType && isReadable && selected instanceof IsTextual && ((Datatype) selected).getSize() == 8);
- miToString.setEnabled(isDataType && isReadable
- && (selected instanceof Unknown || selected instanceof ResourceRef || selected instanceof TextBitmap)
- && !(selected instanceof AbstractCode));
- miReset.setEnabled(isDataType && isReadable && getCachedStructEntry(((Datatype) selected).getOffset()) != null
+ isDataType && selected instanceof IsTextual && ((Datatype) selected).getSize() == 8);
+ miToString.setEnabled(isDataType && (selected instanceof Unknown || selected instanceof ResourceRef
+ || selected instanceof TextBitmap));
+ miReset.setEnabled(isDataType && getCachedStructEntry(((Datatype) selected).getOffset()) != null
&& !(selected instanceof AbstractCode));
miAddToAdvSearch.setEnabled(!(selected instanceof AbstractStruct || selected instanceof Unknown));
miGotoOffset.setEnabled(selected instanceof SectionOffset || selected instanceof SectionCount);
@@ -961,7 +976,7 @@ public void close() {
try {
((Closeable) c).close();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
}
@@ -1186,8 +1201,10 @@ private void convertAttribute(int index, JMenuItem menuitem) {
newentry = new UnknownDecimal(bb, 0, entry.getSize(), entry.getName());
} else if (menuitem == miToInt) {
newentry = new DecNumber(bb, 0, entry.getSize(), entry.getName());
+ } else if (menuitem == miToUint) {
+ newentry = new UnsignDecNumber(bb, 0, entry.getSize(), entry.getName());
} else if (menuitem == miToHexInt) {
- newentry = new HexNumber(bb, 0, entry.getSize(), entry.getName());
+ newentry = new UnsignHexNumber(bb, 0, entry.getSize(), entry.getName());
} else if (menuitem == miToFlags) {
newentry = new Flag(bb, 0, entry.getSize(), entry.getName(), null);
} else if (CMD_TORESLIST.equals(menuitem.getActionCommand())) {
@@ -1209,7 +1226,7 @@ private void convertAttribute(int index, JMenuItem menuitem) {
table.getSelectionModel().removeSelectionInterval(index, index);
table.getSelectionModel().addSelectionInterval(index, index);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.error(e);
}
}
@@ -1258,24 +1275,24 @@ private void selectSubEntry(AbstractStruct subStruct, StructEntry structEntry) {
/** Caches the given StructEntry object. */
private void setCachedStructEntry(StructEntry struct) {
if (struct != null) {
- if (!entryMap.containsKey(Integer.valueOf(struct.getOffset()))) {
+ if (!entryMap.containsKey(struct.getOffset())) {
entryMap.put(struct.getOffset(), struct);
}
}
}
private StructEntry getCachedStructEntry(int offset) {
- return entryMap.get(Integer.valueOf(offset));
+ return entryMap.get(offset);
}
/** Removes the StructEntry object at the given offset and returns it. */
private StructEntry removeCachedStructEntry(int offset) {
- return entryMap.remove(Integer.valueOf(offset));
+ return entryMap.remove(offset);
}
/** Indicates whether the given StructEntry object is equal to the cached object. */
private boolean isCachedStructEntry(int offset) {
- return entryMap.containsKey(Integer.valueOf(offset));
+ return entryMap.containsKey(offset);
}
/** Recycles existing ViewFrame constructs if possible. */
@@ -1437,7 +1454,7 @@ private void addToAdvancedSearch(StructEntry entry) {
while (root.getParent() != null) {
root = root.getParent();
}
- if (root == null || root.getResourceEntry() == null) {
+ if (root.getResourceEntry() == null) {
return;
}
@@ -1582,7 +1599,7 @@ private void appendKeyChar(char ch) {
/** Removes the last charcater from the search string. */
private void removeKeyChar() {
synchronized (timer) {
- if (currentKey.length() > 0) {
+ if (!currentKey.isEmpty()) {
currentKey = currentKey.substring(0, currentKey.length() - 1);
}
}
diff --git a/src/org/infinity/gui/TextListPanel.java b/src/org/infinity/gui/TextListPanel.java
index e749f5de6..3ac858da0 100644
--- a/src/org/infinity/gui/TextListPanel.java
+++ b/src/org/infinity/gui/TextListPanel.java
@@ -15,7 +15,6 @@
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.FileNotFoundException;
-import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -49,6 +48,7 @@
import org.infinity.resource.key.ResourceEntry;
import org.infinity.util.FilteredListModel;
import org.infinity.util.IconCache;
+import org.infinity.util.Logger;
import org.infinity.util.Misc;
public class TextListPanel extends JPanel
@@ -180,6 +180,7 @@ public void actionPerformed(ActionEvent e) {
try {
item = listmodel.get(idx);
} catch (Exception ex) {
+ Logger.trace(ex);
}
if (item == null || !item.toString().equals(tfield.getText())) {
selectClosest(tfield.getText());
@@ -246,7 +247,7 @@ public void setSelectedValue(E value, boolean shouldScroll) {
public void setValues(List extends E> values) {
if (this.sortValues) {
- Collections.sort(values, Misc.getIgnoreCaseComparator());
+ values.sort(Misc.getIgnoreCaseComparator());
}
listmodel.baseClear();
listmodel.baseAddAll(values);
@@ -292,7 +293,7 @@ private void ensurePreferredComponentWidth(JComponent c, boolean includeScrollBa
double w1 = fm.getStringBounds(e1.toString(), g).getWidth();
double w2 = fm.getStringBounds(e2.toString(), g).getWidth();
return (int) (w1 - w2);
- }).get();
+ }).orElse(null);
if (item != null) {
int cw = (int) fm.getStringBounds(item.toString(), g).getWidth();
cw += c.getInsets().left;
diff --git a/src/org/infinity/gui/TileGrid.java b/src/org/infinity/gui/TileGrid.java
index 3ebd2be40..54c641cbe 100644
--- a/src/org/infinity/gui/TileGrid.java
+++ b/src/org/infinity/gui/TileGrid.java
@@ -269,7 +269,7 @@ public void addImage(List images) {
throw new NullPointerException();
}
- if (images.size() > 0) {
+ if (!images.isEmpty()) {
int startIndex = imageList.size();
imageList.addAll(images);
updateTileList(startIndex, images.size());
@@ -327,7 +327,7 @@ public void insertImage(int index, List images) {
throw new IndexOutOfBoundsException("Index out of bounds: " + index);
}
- if (images.size() > 0) {
+ if (!images.isEmpty()) {
imageList.addAll(index, images);
updateTileList(index, imageList.size() - index);
validate();
@@ -384,7 +384,7 @@ public void replaceImage(int index, List images) {
throw new IndexOutOfBoundsException("Index out of bounds: " + index);
}
- if (images.size() > 0) {
+ if (!images.isEmpty()) {
int count = 0;
ListIterator iterSrc = images.listIterator(index);
ListIterator iterDst = images.listIterator(index);
@@ -461,9 +461,7 @@ public void clearImages() {
public int findImage(Image image) {
if (image != null) {
int idx = 0;
- ListIterator iter = imageList.listIterator();
- while (iter.hasNext()) {
- Image listImage = iter.next();
+ for (Image listImage : imageList) {
if (listImage.equals(image)) {
return idx;
}
@@ -749,9 +747,8 @@ private void updateTileLayout() {
root.removeAll();
// 2. re-add tiles, depending on ordering
- ListIterator iter = tileList.listIterator();
- while (iter.hasNext()) {
- root.add(iter.next());
+ for (TileLabel tileLabel : tileList) {
+ root.add(tileLabel);
}
}
@@ -780,17 +777,13 @@ private void updateTileIcons(boolean visible) {
if (visible != bShowIcons) {
bShowIcons = visible;
if (bShowIcons) {
- ListIterator iterSrc = imageList.listIterator();
- ListIterator iterDst = tileList.listIterator();
- while (iterDst.hasNext()) {
+ final ListIterator iterSrc = imageList.listIterator();
+ for (TileLabel tileLabel : tileList) {
Image image = iterSrc.hasNext() ? iterSrc.next() : null;
- TileLabel label = iterDst.next();
- label.setImage(image);
+ tileLabel.setImage(image);
}
} else {
- ListIterator iter = tileList.listIterator();
- while (iter.hasNext()) {
- TileLabel label = iter.next();
+ for (TileLabel label : tileList) {
label.setImage(null);
}
}
@@ -841,7 +834,7 @@ private int locationToIndex(Point location) {
// -------------------------- INNER CLASSES --------------------------
// Adding grid support to RenderCanvas
- private class TileLabel extends RenderCanvas {
+ private static class TileLabel extends RenderCanvas {
private Color gridColor;
private boolean showGrid;
diff --git a/src/org/infinity/gui/ToolTipTableCellRenderer.java b/src/org/infinity/gui/ToolTipTableCellRenderer.java
index 4ff1bfc29..d988e74d6 100644
--- a/src/org/infinity/gui/ToolTipTableCellRenderer.java
+++ b/src/org/infinity/gui/ToolTipTableCellRenderer.java
@@ -55,7 +55,7 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole
if (delta == -1) {
delta = string.length();
}
- sb.append(string.substring(index, Math.min(delta, string.length())));
+ sb.append(string, index, Math.min(delta, string.length()));
index = delta;
}
sb.append("