diff --git a/.classpath b/.classpath index fb1a79e75..cba48149e 100644 --- a/.classpath +++ b/.classpath @@ -18,6 +18,8 @@ + + diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 07af07995..3f0d71672 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -57,20 +57,28 @@ jobs: - name: Git checkout uses: actions/checkout@v4 - - name: Set up JDK + - name: Set up JDK (windows) + if: startsWith(matrix.os, 'windows-') uses: actions/setup-java@v4 with: java-version: ${{ matrix.java }} distribution: 'temurin' + - name: Set up JDK (macos) + if: startsWith(matrix.os, 'macos-') + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'oracle' + - name: Echo JAVA_HOME (windows) - if: (matrix.os == 'windows-latest') + if: startsWith(matrix.os, 'windows-') run: | echo $env:JAVA_HOME java -version - name: Echo JAVA_HOME (macos) - if: (matrix.os != 'windows-latest') + if: startsWith(matrix.os, 'macos-') run: | echo $JAVA_HOME java -version @@ -90,7 +98,7 @@ jobs: # Building - name: Build portable archive and installer (windows) - if: (matrix.os == 'windows-latest') + if: startsWith(matrix.os, 'windows-') run: | move assets\redistributable\windows\package . move assets\redistributable\windows\build-image.cmd . @@ -108,7 +116,7 @@ jobs: # Validation - name: List built files (windows) - if: (matrix.os == 'windows-latest') + if: startsWith(matrix.os, 'windows-') run: dir - name: List built files (macos) @@ -117,20 +125,20 @@ jobs: # Uploading - name: Upload portable artifact (windows) - if: (matrix.os == 'windows-latest') + if: startsWith(matrix.os, 'windows-') uses: actions/upload-artifact@v4 with: name: portable-windows path: NearInfinity-*.zip - name: Upload exe artifact (windows) - if: (matrix.os == 'windows-latest') + if: startsWith(matrix.os, 'windows-') uses: actions/upload-artifact@v4 with: name: installer-windows path: NearInfinity-*.exe - - name: Upload pkg artifact (macos) + - name: Upload pkg artifact (macos-x86_64) if: (matrix.os == 'macos-13') uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index dd9eb8360..2476b13aa 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,6 @@ jar/NearInfinity.jar *.class /bin /build +/.idea /.settings .vscode/launch.json diff --git a/NearInfinity.iml b/NearInfinity.iml new file mode 100644 index 000000000..c36cf1004 --- /dev/null +++ b/NearInfinity.iml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 455a2ddbe..5e4eb8402 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,8 @@ cd NearInfinity ant ``` -The sources also contain configuration files for the [Eclipse IDE](https://www.eclipse.org/). +The sources also contain configuration files for the [Eclipse IDE](https://www.eclipse.org/) +and [IntelliJ IDEA](https://www.jetbrains.com/idea/download/). It is preferred to use `Apache Ant` for compiling Near Infinity, however. ### Recreate parse tree diff --git a/build.xml b/build.xml index 932571124..271b2e356 100644 --- a/build.xml +++ b/build.xml @@ -5,6 +5,8 @@ + + @@ -31,15 +33,28 @@ deprecation="false" debug="false" debuglevel="lines,vars,source" - classpath="${classpath}:${jorbis.file}:${rsyntaxtextarea.file}:${jhexview.file}:${montemedia.file}:${apng_writer.file}:${json.file}:${commonmark.file}:${flatlaf.file}:${flatlafthemes.file}"> + classpath="${classpath}:${tinylog-api.file}:${tinylog-impl.file}:${jorbis.file}:${rsyntaxtextarea.file}:${jhexview.file}:${montemedia.file}:${apng_writer.file}:${json.file}:${commonmark.file}:${flatlaf.file}:${flatlafthemes.file}"> - - - - - - + + + + + + + + + + + + + + + + + + + @@ -50,6 +65,8 @@ basedir="${build.path}" includes="**/*" level="9"> + + diff --git a/lib/tinylog/license.txt b/lib/tinylog/license.txt new file mode 100644 index 000000000..f433b1a53 --- /dev/null +++ b/lib/tinylog/license.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/lib/tinylog/readme.txt b/lib/tinylog/readme.txt new file mode 100644 index 000000000..cadda4f7a --- /dev/null +++ b/lib/tinylog/readme.txt @@ -0,0 +1,24 @@ +Copyright 2018 Martin Winandy + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +------------------- + Using tinylog +------------------- + +To use tinylog as a logging framework, add tinylog-api.jar and an +implementation such as tinylog-impl.jar to the classpath. + +tinylog-impl.jar is the default implementation for tinylog. There are also +implementations for application and web servers to use their logging +frameworks. Since tinylog 2, multiple implementations can even be used in +parallel. diff --git a/lib/tinylog/tinylog-api-2.7.0-sources.jar b/lib/tinylog/tinylog-api-2.7.0-sources.jar new file mode 100644 index 000000000..8ba31eea1 Binary files /dev/null and b/lib/tinylog/tinylog-api-2.7.0-sources.jar differ diff --git a/lib/tinylog/tinylog-api-2.7.0.jar b/lib/tinylog/tinylog-api-2.7.0.jar new file mode 100644 index 000000000..94c2bdc36 Binary files /dev/null and b/lib/tinylog/tinylog-api-2.7.0.jar differ diff --git a/lib/tinylog/tinylog-impl-2.7.0-sources.jar b/lib/tinylog/tinylog-impl-2.7.0-sources.jar new file mode 100644 index 000000000..a72d47e1c Binary files /dev/null and b/lib/tinylog/tinylog-impl-2.7.0-sources.jar differ diff --git a/lib/tinylog/tinylog-impl-2.7.0.jar b/lib/tinylog/tinylog-impl-2.7.0.jar new file mode 100644 index 000000000..3daf6899c Binary files /dev/null and b/lib/tinylog/tinylog-impl-2.7.0.jar differ diff --git a/src/org/infinity/AppOption.java b/src/org/infinity/AppOption.java index 76f6071d4..d50838b46 100644 --- a/src/org/infinity/AppOption.java +++ b/src/org/infinity/AppOption.java @@ -19,6 +19,7 @@ import java.util.stream.Collectors; import org.infinity.gui.menu.BrowserMenuBar; +import org.infinity.gui.menu.LogLevel; import org.infinity.gui.menu.OptionsMenuItem; import org.infinity.gui.menu.OverrideMode; import org.infinity.gui.menu.ResRefMode; @@ -78,7 +79,7 @@ public class AppOption { if (lang == null || ((String) lang).isEmpty()) { lang = Arrays .stream(Profile.Game.values()) - .filter(g -> Profile.isEnhancedEdition(g)) + .filter(Profile::isEnhancedEdition) .map(g -> g.toString() + "=" + OptionsMenuItem.getDefaultGameLanguage()) .collect(Collectors.joining(";")); } @@ -131,14 +132,14 @@ public class AppOption { /** Menu Options: ShowSysInfo (Boolean, Default: true) */ public static final AppOption SHOW_SYS_INFO = new AppOption(OptionsMenuItem.OPTION_SHOWSYSINFO, "Display System Information at Startup", true); + public static final AppOption SHOW_MEM_STATUS = new AppOption(OptionsMenuItem.OPTION_SHOWMEMSTATUS, + "Display Memory Usage in Status Bar", true); /** Menu Options: OpenBookmarksPrompt (Boolean, Default: true) */ public static final AppOption OPEN_BOOKMARKS_PROMPT = new AppOption(OptionsMenuItem.OPTION_OPENBOOKMARKSPROMPT, "Confirm Opening Bookmarked Gamed", true); /** Menu Options: RememberChildFrameRect (Boolean, Default: false) */ public static final AppOption REMEMBER_CHILD_FRAME_RECT = new AppOption(OptionsMenuItem.OPTION_REMEMBER_CHILDFRAME_RECT, "Remember Last Child Frame Size and Position", false); -// /** Menu Options: MonitorFileChanges (Boolean, Default: false) */ -// public static final AppOption MONITOR_FILE_CHANGES = new AppOption(OptionsMenu.OPTION_MONITORFILECHANGES, "Monitor file changes", false); /** * Menu Options: OptionFixedInternal (Integer, Default: 0). * Note: Used internally to fix incorrect default values after the public release. @@ -284,6 +285,9 @@ public class AppOption { "Show State/Response Numbers", true); // Category: Visual Options + /** Menu Options > Visual Options: AppLogLevel (Integer, Default: Level.INFO) */ + public static final AppOption APP_LOG_LEVEL = new AppOption(NearInfinity.APP_LOG_LEVEL, "Application Log Level", + LogLevel.INFO.ordinal()); /** Menu Options > Visual Options: ShowResRef (Integer, Default: ResRefMode.RefName) */ public static final AppOption SHOW_RES_REF = new AppOption(OptionsMenuItem.OPTION_SHOWRESREF, "Show ResourceRef As", ResRefMode.RefName.ordinal()); @@ -401,12 +405,12 @@ public static AppOption find(String name) { * @return {@code true} if one or more options have been modified, {@code false} otherwise. */ public static boolean isAnyModified() { - return AppOption.getInstances().stream().anyMatch(o -> o.isModified()); + return AppOption.getInstances().stream().anyMatch(AppOption::isModified); } /** Returns a set of all {@code AppOption} that have been modified. */ public static List getModifiedOptions() { - return AppOption.getInstances().stream().filter(o -> o.isModified()).collect(Collectors.toList()); + return AppOption.getInstances().stream().filter(AppOption::isModified).collect(Collectors.toList()); } /** @@ -424,7 +428,7 @@ public static List getOptionsByPrefs(String prefsNode) { /** Discards any changes made to the options and resets them to their initial values. */ public static void revertAll() { - AppOption.getInstances().stream().forEach(o -> o.revert()); + AppOption.getInstances().stream().forEach(AppOption::revert); } /** Writes all options of this enum back to the persistent Preferences storage. */ @@ -442,7 +446,7 @@ public static void storePreferences(Collection collection) { if (collection == null) { collection = AppOption.getInstances(); } - collection.stream().forEach(o -> o.storeValue()); + collection.stream().forEach(AppOption::storeValue); } // /** Used internally to allow only supported types for the generic argument. */ @@ -458,7 +462,7 @@ private static Class validateType(Class classType) throws ClassCastExce return classType; } else { // fail - final String t = (classType != null) ? classType.getSimpleName() : "(null)"; + final String t = classType.getSimpleName(); throw new ClassCastException("Unsupported value type: " + t); } } @@ -466,7 +470,7 @@ private static Class validateType(Class classType) throws ClassCastExce /** Returns a {@link Preferences} instance for the specified node. */ private static Preferences getPrefs(String prefsNode) { if (prefsNode != null) { - return PREFERENCES.computeIfAbsent(prefsNode, s -> Misc.getPrefs(s)); + return PREFERENCES.computeIfAbsent(prefsNode, Misc::getPrefs); } else { return null; } @@ -645,7 +649,7 @@ public Class getValueType() { } /** - * Returns the initial value of the option as set by {@link #setInitialValue(Object)} or {@link #loadValue(Preferences)}. + * Returns the initial value of the option as set by {@link #setInitialValue(Object)} or {@link #loadValue()}. */ public Object getInitialValue() { return initialValue; @@ -754,7 +758,7 @@ public void setValue(Object newValue) { } /** - * Reverts to the initial value as set by {@link #setInitialValue(Object)} or {@link #loadValue(Preferences)}. + * Reverts to the initial value as set by {@link #setInitialValue(Object)} or {@link #loadValue()}. */ public void revert() { this.value = this.initialValue; @@ -883,8 +887,8 @@ public boolean equals(Object obj) { /** Used internally to ensure that the specified value is of the same type as {@link #getDefault()}. */ private Object validate(Object value) throws ClassCastException { value = validator.apply(value); - if ((value == null && validateType(valueType) == valueType) || - (value != null && valueType.isAssignableFrom(validateType(value.getClass())))) { + if (value == null && Objects.equals(validateType(valueType), valueType) || + valueType.isAssignableFrom(validateType(value.getClass()))) { // pass return value; } diff --git a/src/org/infinity/NearInfinity.java b/src/org/infinity/NearInfinity.java index b1efeaca9..42d67b029 100644 --- a/src/org/infinity/NearInfinity.java +++ b/src/org/infinity/NearInfinity.java @@ -9,7 +9,6 @@ import java.awt.Component; import java.awt.Container; import java.awt.Dimension; -import java.awt.Event; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; @@ -27,6 +26,7 @@ import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.event.InputEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; @@ -35,15 +35,14 @@ import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; @@ -74,6 +73,7 @@ import javax.swing.filechooser.FileFilter; import javax.swing.plaf.FontUIResource; +import org.infinity.datatype.IdsBitmap; import org.infinity.datatype.ProRef; import org.infinity.datatype.ResourceRef; import org.infinity.datatype.Song2daBitmap; @@ -124,6 +124,7 @@ import org.infinity.util.IdsMapCache; import org.infinity.util.IniMapCache; import org.infinity.util.LauncherUtils; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.Operation; import org.infinity.util.Platform; @@ -136,7 +137,7 @@ public final class NearInfinity extends JFrame implements ActionListener, ViewableContainer { // the current Near Infinity version - private static final String VERSION = "v2.4-20240424"; + private static final String VERSION = "v2.4-20240914"; // the minimum supported Java version private static final int JAVA_VERSION_MIN = 8; @@ -157,6 +158,7 @@ public final class NearInfinity extends JFrame implements ActionListener, Viewab public static final String OPTION_GLOBAL_FONT_SIZE = "GlobalFontSize"; public static final String APP_UI_SCALE_ENABLED = "AppUiScaleEnabled"; public static final String APP_UI_SCALE_FACTOR = "AppUiScaleFactor"; + public static final String APP_LOG_LEVEL = "AppLogLevel"; private static final String STATUSBAR_TEXT_FMT = "Welcome to Near Infinity! - %s @ %s - %d files available"; @@ -231,10 +233,11 @@ public final class NearInfinity extends JFrame implements ActionListener, Viewab /** Stores table column widths for "Attribute", "Value" and "Offset" */ private final int[] tableColumnWidth = { -1, -1, -1, -1 }; + private final ButtonPopupWindow bpwQuickSearch; + private final JButton btnLaunchGame; + private final JPopupMenu launchMenu; + private Viewable viewable; - private ButtonPopupWindow bpwQuickSearch; - private JButton btnLaunchGame; - private JPopupMenu launchMenu; private int tablePanelHeight; private ProgressMonitor pmProgress; private int progressIndex; @@ -310,7 +313,7 @@ public static void advanceProgress(String note) { } } - public static void main(String args[]) { + public static void main(String[] args) { Profile.Game forcedGame = null; Path gameOverride = null; boolean enableUpdate = true; @@ -370,7 +373,7 @@ public static void main(String args[]) { final LookAndFeel o = lf.getDeclaredConstructor().newInstance(); UIManager.installLookAndFeel(o.getName(), o.getClass().getCanonicalName()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -400,9 +403,6 @@ private NearInfinity(Options options) { // FileDeletionHook provides a way to delete files when the Java Virtual Machine shuts down Runtime.getRuntime().addShutdownHook(FileDeletionHook.getInstance()); - // Migrate preferences from "infinity" to "org.infinity" if needed - migratePreferences("infinity", Preferences.userNodeForPackage(getClass()), true); - // updating relative default font size globally resizeUIFont(AppOption.GLOBAL_FONT_SIZE.getIntValue()); @@ -444,7 +444,7 @@ protected Void doInBackground() throws Exception { try { checkFileAccess(tlkFile); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.this, String.format("Unable to open the game \"%s\".\n" + "The file \"%s\" is locked by another process.", @@ -457,9 +457,6 @@ protected Void doInBackground() throws Exception { BrowserMenuBar.getInstance().gameLoaded(Profile.Game.Unknown, null); CreMapCache.reset(); BaseOpcode.initOpcodes(); -// if (BrowserMenuBar.getInstance().getMonitorFileChanges()) { -// FileWatcher.getInstance().start(); -// } return null; } @@ -470,7 +467,7 @@ protected Void doInBackground() throws Exception { worker.execute(); worker.get(); } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); + Logger.error(e); System.exit(10); } @@ -486,7 +483,7 @@ public void windowClosing(WindowEvent event) { UIManager.setLookAndFeel(info.getClassName()); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } cacheResourceIcons(true); @@ -496,7 +493,7 @@ public void windowClosing(WindowEvent event) { updateWindowTitle(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), - Profile.getGameRoot(), treemodel.size()); + Profile.getGameRoot(), Objects.requireNonNull(treemodel).size()); statusBar.setMessage(msg); tree = new ResourceTree(treemodel); tree.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); @@ -625,12 +622,12 @@ public void popupWindowWillBecomeInvisible(PopupWindowEvent event) { } } } catch (Exception e) { - System.out.println("Failed to check for updates: " + e.getMessage()); + Logger.warn("Failed to check for updates: {}", e.getMessage()); } }).start(); } - SwingUtilities.invokeLater(() -> tree.requestFocusInWindow()); + SwingUtilities.invokeLater(tree::requestFocusInWindow); // Present first-time configuration options SwingUtilities.invokeLater(() -> { @@ -656,7 +653,7 @@ public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals("Open")) { blocker.setBlocked(true); Profile.Game oldGame = Profile.getGame(); - String oldFile = Profile.getChitinKey().toString(); + String oldFile = Objects.requireNonNull(Profile.getChitinKey()).toString(); if (reloadFactory(false)) { if (!removeViewable()) { blocker.setBlocked(false); @@ -666,7 +663,7 @@ public void actionPerformed(ActionEvent event) { ResourceTreeModel treemodel = ResourceFactory.getResourceTreeModel(); updateWindowTitle(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), - Profile.getGameRoot(), treemodel.size()); + Profile.getGameRoot(), Objects.requireNonNull(treemodel).size()); statusBar.setMessage(msg); BrowserMenuBar.getInstance().gameLoaded(oldGame, oldFile); tree.setModel(treemodel); @@ -706,7 +703,7 @@ public void actionPerformed(ActionEvent event) { LookAndFeelInfo info = BrowserMenuBar.getInstance().getOptions().getLookAndFeel(); updateLookAndFeel(info, true); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else if (event.getActionCommand().equals("Collapse")) { try { @@ -793,7 +790,7 @@ public Viewable getViewable() { @Override public void setViewable(Viewable newViewable) { - if (newViewable == null || !(newViewable instanceof Resource)) { + if (!(newViewable instanceof Resource)) { removeViewable(); } else { Resource resource = (Resource) newViewable; @@ -842,7 +839,7 @@ public void openGame(Path keyFile) { try { checkFileAccess(tlkPath); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.this, String.format("The file \"%s\" of the game \"%s\"\nis locked by another process. " + "Reverting to the previous game.", tlkPath.getFileName(), @@ -858,9 +855,9 @@ public void openGame(Path keyFile) { updateWindowTitle(); updateLauncher(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), - Profile.getGameRoot(), treemodel.size()); + Profile.getGameRoot(), Objects.requireNonNull(treemodel).size()); statusBar.setMessage(msg); - BrowserMenuBar.getInstance().gameLoaded(oldGame, oldKeyFile.toString()); + BrowserMenuBar.getInstance().gameLoaded(oldGame, Objects.requireNonNull(oldKeyFile).toString()); tree.setModel(treemodel); containerpanel.removeAll(); containerpanel.add(createJavaInfoPanel(), BorderLayout.CENTER); @@ -898,7 +895,6 @@ public void showResourceEntry(ResourceEntry resourceEntry, Operation doneOperati public void quit() { if (removeViewable()) { - // FileWatcher.getInstance().stop(); ChildFrame.closeWindows(); storePreferences(); clearCache(false); @@ -917,7 +913,7 @@ public void refreshGame() { updateWindowTitle(); updateLauncher(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), - Profile.getGameRoot(), treemodel.size()); + Profile.getGameRoot(), Objects.requireNonNull(treemodel).size()); statusBar.setMessage(msg); statusBar.invalidate(); BrowserMenuBar.getInstance().gameLoaded(null, null); @@ -1031,7 +1027,7 @@ public void updateLauncher() { Bookmark bookmark = BrowserMenuBar.getInstance().getGameMenu().getBookmarkOf(Profile.getChitinKey()); List binPaths = null; if (bookmark != null) { - List list = bookmark.getBinaryPaths(Platform.getPlatform()); + List list = bookmark.getBinaryPaths(Platform.OS.getCurrentOS()); if (list != null && !list.isEmpty()) { binPaths = new ArrayList<>(); for (final String name : list) { @@ -1053,7 +1049,7 @@ public void updateLauncher() { if (binPaths == null || binPaths.isEmpty()) { binPaths = Profile.getGameBinaryPaths(); } - if (binPaths != null && binPaths.isEmpty()) { + if (binPaths.isEmpty()) { binPaths = null; } @@ -1075,7 +1071,7 @@ public void updateLauncher() { btnLaunchGame.setIcon(Icons.ICON_LAUNCH_24.getIcon()); btnLaunchGame.setToolTipText("Launch " + binPaths.get(0).toString()); } else { - String ctrlName = (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.CTRL_MASK) ? "Ctrl" + String ctrlName = (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == InputEvent.CTRL_MASK) ? "Ctrl" : "Command"; btnLaunchGame.setIcon(Icons.ICON_LAUNCH_PLUS_24.getIcon()); btnLaunchGame.setToolTipText("Launch game (launch directly with " + ctrlName + "+Click)"); @@ -1105,8 +1101,9 @@ public boolean preferencesExist() { final Preferences prefs = Preferences.userNodeForPackage(NearInfinity.class); if (prefs != null) { try { - return Arrays.stream(prefs.keys()).anyMatch(k -> k.equals(LAST_GAMEDIR)); + return Arrays.asList(prefs.keys()).contains(LAST_GAMEDIR); } catch (BackingStoreException e) { + Logger.warn(e); } } return false; @@ -1179,8 +1176,6 @@ private static void clearCache(boolean refreshOnly) { if (!refreshOnly) { CharsetDetector.clearCache(); } - DlcManager.close(); - FileManager.reset(); IconCache.clearCache(); IdsMapCache.clearCache(); IniMapCache.clearCache(); @@ -1195,9 +1190,11 @@ private static void clearCache(boolean refreshOnly) { SpriteUtils.clearCache(); ItemInfo.clearCache(); AreResource.clearCache(); + IdsBitmap.clearCache(); Song2daBitmap.resetSonglist(); SpellProtType.resetTypeTable(); Summon2daBitmap.resetSummonTable(); + DlcManager.close(); } private static void showProgress(String msg, int max) { @@ -1262,7 +1259,7 @@ private void storePreferences() { private void setAppIcon() { List list = new ArrayList<>(); for (int i = 4; true; i++) { - final Image icon = Icons.getImage(null, String.format("App%d.png", 1 << i)); + final Image icon = ColorConvert.loadAppImage(Icons.class, String.format("App%d.png", 1 << i)); if (icon != null) { list.add(icon); } else { @@ -1272,70 +1269,6 @@ private void setAppIcon() { setIconImages(list); } - // Migrate preferences from sourceNode to the currently used prefs node if needed. - // Returns true if content of sourceNode has been cloned into the current node. - @Deprecated - private boolean migratePreferences(String sourceNode, Preferences curPrefs, boolean showError) { - boolean retVal = false; - if (sourceNode != null && !sourceNode.isEmpty() && curPrefs != null) { - Preferences prefsOld = null; - boolean isPrefsEmpty = false; - try { - isPrefsEmpty = (curPrefs.keys().length == 0); - sourceNode = sourceNode.trim(); - if (Preferences.userRoot().nodeExists(sourceNode)) { - prefsOld = Preferences.userRoot().node(sourceNode); - } - } catch (Exception e) { - prefsOld = null; - e.printStackTrace(); - } - if (isPrefsEmpty && prefsOld != null && !prefsOld.equals(curPrefs)) { - try { - clonePrefsNode(prefsOld, curPrefs); - retVal = true; - } catch (Exception e) { - retVal = false; - try { - curPrefs.clear(); - } catch (BackingStoreException bse) { - } - e.printStackTrace(); - if (showError) { - JOptionPane.showMessageDialog(this, "Error migrating old Near Infinity settings. Using defaults.", "Error", - JOptionPane.ERROR_MESSAGE); - } - } - } - } - return retVal; - } - - // Duplicates content from prefsOld to prefsNew recursively - @Deprecated - private void clonePrefsNode(Preferences prefsOld, Preferences prefsNew) throws Exception { - if (prefsOld != null && prefsNew != null && !prefsOld.equals(prefsNew)) { - // cloning keys - String[] keyNames = prefsOld.keys(); - if (keyNames != null) { - for (String keyName : keyNames) { - String value = prefsOld.get(keyName, null); - if (value != null) { - prefsNew.put(keyName, value); - } - } - } - - // cloning child nodes - String[] childNames = prefsOld.childrenNames(); - if (childNames != null) { - for (String childName : childNames) { - clonePrefsNode(prefsOld.node(childName), prefsNew.node(childName)); - } - } - } - } - // Enables command-Q on OSX to trigger the window closing callback @SuppressWarnings({ "unchecked", "rawtypes" }) private void enableOSXQuitStrategy() { @@ -1353,7 +1286,7 @@ private void enableOSXQuitStrategy() { method.invoke(instance, closeAllWindows); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); + Logger.error(e); } } @@ -1373,7 +1306,7 @@ private boolean launchGameBinary(Path binPath) { } retVal = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -1386,9 +1319,8 @@ private boolean launchGameBinary(Path binPath) { * @throws IOException if specified path could not be opened for reading. */ private void checkFileAccess(Path path) throws IOException { - if (path != null) { - try (FileChannel ch = FileChannel.open(path, StandardOpenOption.READ)) { - } + if (path != null && !Files.isReadable(path)) { + throw new IOException("Readable check failed: " + path); } } @@ -1396,8 +1328,55 @@ private void checkFileAccess(Path path) throws IOException { * Shows Java Runtime information when there are no components attached to the main view. */ private JPanel createJavaInfoPanel() { + final Color fgColor = Misc.orDefault(UIManager.getColor("Label.foreground"), Color.BLACK); + final Color warningColor = ((fgColor.getRGB() & 0x808080) == 0) + ? new Color(128, 0, 0) // for light UI themes + : new Color(255, 64, 64); // for dark UI themes + + // TODO: Enable deprecation message if 32-bit JRE is detected +// final JLabel archNote; +// if (Platform.IS_32BIT) { +// final String msg = "

" +// + "Support of 32-bit Java Runtime Environments has been deprecated and will be
" +// + "removed completely in a future version.

" +// + "Please upgrade your Java Runtime Environment to 64-bit if possible.
" +// + "Download options can be found on the Near Infinity Wiki page (press F1 to open
" +// + "the Wiki in your browser.)

"; +// archNote = new JLabel(msg); +// archNote.setForeground(warningColor); +// } else { +// archNote = null; +// } + if (!BrowserMenuBar.getInstance().getOptions().showSysInfo()) { - return new JPanel(); + // show only deprecation message + final JPanel infoPanel = new JPanel(); + // TODO: Enable deprecation message if 32-bit JRE is detected (Maybe don't show if SysInfo is disabled?) +// if (archNote != null) { +// final GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); +// final int prefWidth; +// final int minWidth = 400; +// if (gd != null && (AppOption.APP_WINDOW_STATE.getIntValue() & Frame.MAXIMIZED_HORIZ) != 0) { +// prefWidth = Math.max(minWidth, gd.getDisplayMode().getWidth() / 3); +// } else { +// prefWidth = Math.max(minWidth, AppOption.APP_WINDOW_SIZE_X.getIntValue() / 2); +// } +// final int prefHeight; +// final int minHeight = 400; +// if (gd != null && (AppOption.APP_WINDOW_STATE.getIntValue() & Frame.MAXIMIZED_VERT) != 0) { +// prefHeight = Math.max(minHeight, gd.getDisplayMode().getHeight() / 3); +// } else { +// prefHeight = Math.max(minHeight, AppOption.APP_WINDOW_SIZE_Y.getIntValue() / 2); +// } +// +// archNote.setMinimumSize(new Dimension(minWidth, minHeight)); +// archNote.setPreferredSize(new Dimension(prefWidth, prefHeight)); +// infoPanel.setLayout(new GridBagLayout()); +// final GridBagConstraints c = ViewerUtil.setGBC(null, 0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, +// GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); +// infoPanel.add(archNote, c); +// } + return infoPanel; } final List> entries = new ArrayList<>(); @@ -1453,16 +1432,25 @@ private JPanel createJavaInfoPanel() { row++; } + // TODO: Enable deprecation message if 32-bit JRE is detected +// if (archNote != null) { +// c = ViewerUtil.setGBC(c, 0, row, 2, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, +// new Insets(16, 0, 0, 0), 0, 0); +// infoPanel.add(archNote, c); +// row++; +// } + if (memoryMax < 480) { - String message = "
Your Java memory settings may not be sufficient to use all features of Near Infinity.
"; - if (System.getProperty("os.arch").contains("64")) { - message += "Please consider running Near Infinity with improved memory settings."; + String message = "Your Java memory settings may not be sufficient to use all features of Near Infinity.
"; + if (Platform.IS_32BIT) { + message += "Please consider upgrading your Java Runtime Environment to 64-bit or run
" + + "Near Infinity with improved memory settings."; } else { - message += "Please consider upgrading your Java Runtime Environment to 64-bit
or run Near Infinity with improved memory settings."; + message += "Please consider running Near Infinity with improved memory settings."; } - message += "
"; + message += ""; final JLabel infoLabel = new JLabel(message); - infoLabel.setForeground(new Color(0x800000)); + infoLabel.setForeground(warningColor); c = ViewerUtil.setGBC(c, 0, row, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(16, 0, 0, 0), 0, 0); @@ -1485,6 +1473,7 @@ private void cancelCacheResourceIcons() { try { Thread.sleep(10); } catch (InterruptedException e) { + Logger.debug(e); } } iconCacheWorker = null; @@ -1525,7 +1514,7 @@ private void cacheResourceIcons(boolean threaded) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } }; @@ -1540,7 +1529,7 @@ protected Void doInBackground() throws Exception { try { operation.perform(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } setProgress(100); return null; @@ -1602,17 +1591,17 @@ private ConsoleStream(OutputStream out, JTextArea text) { } @Override - public void write(byte buf[], int off, int len) { + public void write(byte[] buf, int off, int len) { super.write(buf, off, len); try { text.append(new String(buf, off, len)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } - private class FileDropTargetListener implements DropTargetListener, Runnable { + private static class FileDropTargetListener implements DropTargetListener, Runnable { private List files; private FileDropTargetListener() { @@ -1645,14 +1634,13 @@ 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); } event.dropComplete(true); if (files != null && files.size() == 1) { Path path = files.get(0).toPath(); - if (path != null && FileEx.create(path).isFile() - && path.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".KEY")) { + if (FileEx.create(path).isFile() && path.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".KEY")) { Path curFile = Profile.getChitinKey(); if (!path.equals(curFile)) { int ret = JOptionPane.showConfirmDialog(NearInfinity.getInstance(), "Open game \"" + path + "\"?", diff --git a/src/org/infinity/check/AbstractChecker.java b/src/org/infinity/check/AbstractChecker.java index b21f07582..2d6bd4d05 100644 --- a/src/org/infinity/check/AbstractChecker.java +++ b/src/org/infinity/check/AbstractChecker.java @@ -92,6 +92,15 @@ protected boolean runCheck(List entries) { return runSearch("Checking", entries); } + /** + * Returns the widget that handles file type selection. + * + * @return {@link FileTypeSelector} instance. + */ + protected FileTypeSelector getSelector() { + return selector; + } + /** * Returns a list of resources for checking. * diff --git a/src/org/infinity/check/BCSIDSChecker.java b/src/org/infinity/check/BCSIDSChecker.java index dd931a119..14037cca1 100644 --- a/src/org/infinity/check/BCSIDSChecker.java +++ b/src/org/infinity/check/BCSIDSChecker.java @@ -40,6 +40,7 @@ import org.infinity.resource.bcs.ScriptType; 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. */ @@ -179,9 +180,7 @@ protected Runnable newWorker(ResourceEntry entry) { try { checkScript(new BcsResource(entry)); } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } advanceProgress(); }; @@ -204,7 +203,7 @@ private void checkScript(BcsResource script) throws Exception { final String error = e.getValue(); if (!error.contains("GTIMES.IDS") && !error.contains("SCROLL.IDS") && !error.contains("SHOUTIDS.IDS") && !error.contains("SPECIFIC.IDS") && !error.contains("TIME.IDS")) { - synchronized (table) { + synchronized (this) { table.addTableItem(new BCSIDSErrorTableLine(script.getResourceEntry(), error, lineNr)); } } diff --git a/src/org/infinity/check/CreInvChecker.java b/src/org/infinity/check/CreInvChecker.java index 23a8aeecf..581698f3b 100644 --- a/src/org/infinity/check/CreInvChecker.java +++ b/src/org/infinity/check/CreInvChecker.java @@ -43,6 +43,7 @@ import org.infinity.resource.cre.Item; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.AbstractSearcher; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** Performs checking {@link CreResource CRE} & {@code CHR} resources. */ @@ -181,9 +182,7 @@ protected Runnable newWorker(ResourceEntry entry) { try { checkCreature(new CreResource(entry)); } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } advanceProgress(); }; @@ -215,7 +214,7 @@ private void checkCreature(CreResource cre) { } // Evaluating results - synchronized (table) { + synchronized (this) { for (final Item item : items) { if (item != null) { table.addTableItem(new CreInvError(cre.getResourceEntry(), item)); diff --git a/src/org/infinity/check/DialogChecker.java b/src/org/infinity/check/DialogChecker.java index 3d0915621..93be5ab4c 100644 --- a/src/org/infinity/check/DialogChecker.java +++ b/src/org/infinity/check/DialogChecker.java @@ -12,7 +12,6 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; -import java.util.Iterator; import java.util.List; import javax.swing.BorderFactory; @@ -47,6 +46,7 @@ import org.infinity.resource.dlg.DlgResource; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.AbstractSearcher; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** Performs checking {@link DlgResource DLG} resources. */ @@ -142,12 +142,7 @@ public void run() { try { final List dlgFiles = ResourceFactory.getResources("DLG"); if (checkOnlyOverride) { - for (Iterator i = dlgFiles.iterator(); i.hasNext();) { - ResourceEntry resourceEntry = i.next(); - if (!resourceEntry.hasOverride()) { - i.remove(); - } - } + dlgFiles.removeIf(resourceEntry -> !resourceEntry.hasOverride()); } final Class[] colClasses = { ResourceEntry.class, String.class, String.class, Integer.class }; @@ -242,9 +237,7 @@ protected Runnable newWorker(ResourceEntry entry) { } } } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } advanceProgress(); }; @@ -260,12 +253,12 @@ private void checkCode(ResourceEntry entry, AbstractCode code) { final ScriptType type = code instanceof Action ? ScriptType.ACTION : ScriptType.TRIGGER; final Compiler compiler = new Compiler(code.getText(), type); compiler.compile(); - synchronized (errorTable) { + synchronized (this) { for (final ScriptMessage sm : compiler.getErrors()) { errorTable.addTableItem(new Problem(entry, code, sm.getLine(), sm.getMessage(), Problem.Type.ERROR)); } } - synchronized (warningTable) { + synchronized (this) { for (final ScriptMessage sm : compiler.getWarnings()) { warningTable.addTableItem(new Problem(entry, code, sm.getLine(), sm.getMessage(), Problem.Type.WARNING)); } diff --git a/src/org/infinity/check/EffectsIndexChecker.java b/src/org/infinity/check/EffectsIndexChecker.java index c8e5bcd94..90255284f 100644 --- a/src/org/infinity/check/EffectsIndexChecker.java +++ b/src/org/infinity/check/EffectsIndexChecker.java @@ -49,8 +49,7 @@ protected Runnable newWorker(ResourceEntry entry) { } private void search(ResourceEntry entry, AbstractStruct struct) { - final int numGlobalEffects = ((IsNumeric) struct.getAttribute(SplResource.SPL_NUM_GLOBAL_EFFECTS)).getValue(); - int expectedEffectsIndex = numGlobalEffects; + int expectedEffectsIndex = ((IsNumeric) struct.getAttribute(SplResource.SPL_NUM_GLOBAL_EFFECTS)).getValue(); for (final StructEntry e : struct.getFields()) { if (e instanceof AbstractAbility) { final AbstractAbility abil = (AbstractAbility) e; diff --git a/src/org/infinity/check/ResourceUseChecker.java b/src/org/infinity/check/ResourceUseChecker.java index 59f24c9ce..9edcd8e00 100644 --- a/src/org/infinity/check/ResourceUseChecker.java +++ b/src/org/infinity/check/ResourceUseChecker.java @@ -7,24 +7,24 @@ import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; -import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; -import java.util.Iterator; +import java.util.HashSet; import java.util.List; +import java.util.Map.Entry; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; import javax.swing.JButton; +import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; -import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; @@ -56,11 +56,11 @@ import org.infinity.resource.dlg.Transition; import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.text.PlainTextResource; -import org.infinity.search.AbstractSearcher; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StringTable; -public final class ResourceUseChecker extends AbstractSearcher +public final class ResourceUseChecker extends AbstractChecker implements Runnable, ListSelectionListener, ActionListener { private static final Pattern RESREF_PATTERN = Pattern.compile("\\w{3,8}"); @@ -70,73 +70,26 @@ public final class ResourceUseChecker extends AbstractSearcher private static final String[] CHECK_TYPES = { "ARE", "BAM", "BCS", "CRE", "DLG", "EFF", "ITM", "PRO", "SPL", "STO", "TIS", "VEF", "VVC", "WAV", "WED" }; - private final ChildFrame selectframe = new ChildFrame("Find unused files", true); - private final JButton bstart = new JButton("Search", Icons.ICON_FIND_16.getIcon()); - private final JButton bcancel = new JButton("Cancel", Icons.ICON_DELETE_16.getIcon()); - private final JRadioButton[] typeButtons = new JRadioButton[CHECK_TYPES.length]; - private final List unusedResources = new ArrayList<>(); + private final TreeMap unusedResources = new TreeMap<>(String::compareToIgnoreCase); + private final HashSet checkTypes = new HashSet<>(CHECK_TYPES.length * 2); private ChildFrame resultFrame; private JButton bopen; private JButton bopennew; private JButton bsave; - private String checkType; /** List of the {@link UnusedFileTableItem} objects. */ private SortableTable table; public ResourceUseChecker(Component parent) { - super(CHECK_MULTI_TYPE_FORMAT, parent); - ButtonGroup bg = new ButtonGroup(); - JPanel radioPanel = new JPanel(new GridLayout(0, 1)); - for (int i = 0; i < typeButtons.length; i++) { - typeButtons[i] = new JRadioButton(CHECK_TYPES[i]); - bg.add(typeButtons[i]); - radioPanel.add(typeButtons[i]); - } - typeButtons[0].setSelected(true); - bstart.setMnemonic('s'); - bcancel.setMnemonic('c'); - bstart.addActionListener(this); - bcancel.addActionListener(this); - selectframe.getRootPane().setDefaultButton(bstart); - selectframe.setIconImage(Icons.ICON_FIND_16.getIcon().getImage()); - radioPanel.setBorder(BorderFactory.createTitledBorder("Select type to search:")); - - JPanel bpanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - bpanel.add(bstart); - bpanel.add(bcancel); - - JPanel mainpanel = new JPanel(new BorderLayout()); - mainpanel.add(radioPanel, BorderLayout.CENTER); - mainpanel.add(bpanel, BorderLayout.SOUTH); - mainpanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); - - JPanel pane = (JPanel) selectframe.getContentPane(); - pane.setLayout(new BorderLayout()); - pane.add(mainpanel, BorderLayout.CENTER); - - selectframe.pack(); - Center.center(selectframe, parent.getBounds()); - selectframe.setVisible(true); + super(CHECK_MULTI_TYPE_FORMAT, CHECK_TYPES); } // --------------------- Begin Interface ActionListener --------------------- @Override public void actionPerformed(ActionEvent event) { - if (event.getSource() == bstart) { - selectframe.setVisible(false); - for (int i = 0; i < typeButtons.length; i++) { - if (typeButtons[i].isSelected()) { - checkType = CHECK_TYPES[i]; - new Thread(this).start(); - return; - } - } - } else if (event.getSource() == bcancel) { - selectframe.setVisible(false); - } else if (event.getSource() == bopen) { + if (event.getSource() == bopen) { int row = table.getSelectedRow(); if (row != -1) { ResourceEntry resourceEntry = (ResourceEntry) table.getValueAt(row, 0); @@ -150,7 +103,9 @@ public void actionPerformed(ActionEvent event) { new ViewFrame(resultFrame, resource); } } else if (event.getSource() == bsave) { - table.saveCheckResult(resultFrame, "Unused " + checkType + " resources"); + table.saveCheckResult(resultFrame, "Unused resources"); + } else { + super.actionPerformed(event); } } @@ -178,19 +133,30 @@ public void run() { files.addAll(ResourceFactory.getResources(fileType)); } - unusedResources.addAll(ResourceFactory.getResources(checkType)); + checkTypes.clear(); + final List typeList = getSelector().getFileTypes(); + for (final JCheckBox cb : typeList) { + if (cb.isSelected()) { + checkTypes.add(cb.getText()); + } + } + + for (final ResourceEntry e : getFiles()) { + unusedResources.put(e.getResourceName(), e); + } + if (runSearch("Searching", files)) { return; } if (unusedResources.isEmpty()) { - JOptionPane.showMessageDialog(NearInfinity.getInstance(), "No unused " + checkType + "s found", "Info", + JOptionPane.showMessageDialog(NearInfinity.getInstance(), "No unused resources found", "Info", JOptionPane.INFORMATION_MESSAGE); } else { table = new SortableTable(new String[] { "File", "Name" }, new Class[] { ResourceEntry.class, String.class }, new Integer[] { 200, 200 }); - for (ResourceEntry entry : unusedResources) { - table.addTableItem(new UnusedFileTableItem(entry)); + for (final Entry 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 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(""); diff --git a/src/org/infinity/gui/UrlBrowser.java b/src/org/infinity/gui/UrlBrowser.java index 031114d8a..adeda9893 100644 --- a/src/org/infinity/gui/UrlBrowser.java +++ b/src/org/infinity/gui/UrlBrowser.java @@ -14,6 +14,7 @@ import org.infinity.NearInfinity; import org.infinity.util.LauncherUtils; +import org.infinity.util.Logger; /** * Browses for the provided URI on mouse clicks @@ -30,7 +31,7 @@ public static boolean openUrl(String url) { LauncherUtils.browse(url); retVal = true; } catch (IOException | URISyntaxException e) { - e.printStackTrace(); + Logger.error(e); showErrorMessage(e.getMessage()); } return retVal; @@ -58,7 +59,7 @@ public void mouseClicked(MouseEvent event) { try { LauncherUtils.browse(url); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); showErrorMessage(e.getMessage()); } } diff --git a/src/org/infinity/gui/ViewerUtil.java b/src/org/infinity/gui/ViewerUtil.java index 0592dabab..cc288f004 100644 --- a/src/org/infinity/gui/ViewerUtil.java +++ b/src/org/infinity/gui/ViewerUtil.java @@ -22,10 +22,10 @@ import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.function.Function; import javax.swing.BorderFactory; @@ -69,6 +69,7 @@ import org.infinity.resource.graphics.MosResource; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.IconCache; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.SimpleListModel; import org.infinity.util.StringTable; @@ -191,31 +192,32 @@ public static void addLabelFieldPair(JPanel panel, JLabel name, JComponent value } public static JLabel makeBamPanel(ResourceRef iconRef, int frameNr) { - ResourceEntry iconEntry = ResourceFactory.getResourceEntry(iconRef.getResourceName()); + final ResourceEntry iconEntry = ResourceFactory.getResourceEntry(iconRef.getResourceName()); if (iconEntry != null) { try { - BamDecoder decoder = BamDecoder.loadBam(iconEntry); - BamControl ctrl = decoder.createControl(); - JLabel label = new JLabel(iconRef.getName(), SwingConstants.CENTER); + final BamDecoder decoder = BamDecoder.loadBam(iconEntry); + final BamControl ctrl = Objects.requireNonNull(decoder).createControl(); + final JLabel label = new JLabel(iconRef.getName(), SwingConstants.CENTER); frameNr = Math.min(frameNr, decoder.frameCount() - 1); label.setIcon(new ImageIcon(decoder.frameGet(ctrl, frameNr))); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setHorizontalTextPosition(SwingConstants.CENTER); return label; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return new JLabel("No " + iconRef.getName().toLowerCase(Locale.ENGLISH), SwingConstants.CENTER); } public static JLabel makeBamPanel(ResourceRef iconRef, int animNr, int frameNr) { - ResourceEntry iconEntry = ResourceFactory.getResourceEntry(iconRef.getResourceName()); + final ResourceEntry iconEntry = ResourceFactory.getResourceEntry(iconRef.getResourceName()); if (iconEntry != null) { try { - BamDecoder decoder = BamDecoder.loadBam(iconEntry); - BamControl ctrl = decoder.createControl(); - JLabel label = new JLabel(iconRef.getName(), SwingConstants.CENTER); + final BamDecoder decoder = BamDecoder.loadBam(iconEntry); + assert decoder != null; + final BamControl ctrl = decoder.createControl(); + final JLabel label = new JLabel(iconRef.getName(), SwingConstants.CENTER); int frameIdx = -1; for (int curAnimIdx = animNr; curAnimIdx >= 0 && frameIdx < 0; curAnimIdx--) { for (int curFrameIdx = frameNr; curFrameIdx >= 0 && frameIdx < 0; curFrameIdx--) { @@ -227,7 +229,39 @@ public static JLabel makeBamPanel(ResourceRef iconRef, int animNr, int frameNr) label.setHorizontalTextPosition(SwingConstants.CENTER); return label; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); + } + } + return new JLabel("No " + iconRef.getName().toLowerCase(Locale.ENGLISH), SwingConstants.CENTER); + } + + // Creates a panel with the biggest graphics (by area) available in the specified BAM resource + public static JLabel makeMaxBamPanel(ResourceRef iconRef) { + ResourceEntry iconEntry = ResourceFactory.getResourceEntry(iconRef.getResourceName()); + if (iconEntry != null) { + try { + final BamDecoder decoder = BamDecoder.loadBam(iconEntry); + int numFrames = Objects.requireNonNull(decoder).frameCount(); + int maxSize = -1; + int frameIdx = -1; + for (int idx = 0; idx < numFrames; idx++) { + final BamDecoder.FrameEntry frameInfo = decoder.getFrameInfo(idx); + int curSize = frameInfo.getWidth() * frameInfo.getHeight(); + if (curSize > maxSize) { + maxSize = curSize; + frameIdx = idx; + } + } + if (frameIdx >= 0) { + final BamControl control = decoder.createControl(); + final JLabel label = new JLabel(iconRef.getName(), SwingConstants.CENTER); + label.setIcon(new ImageIcon(decoder.frameGet(control, frameIdx))); + label.setVerticalTextPosition(SwingConstants.BOTTOM); + label.setHorizontalTextPosition(SwingConstants.CENTER); + return label; + } + } catch (Exception e) { + Logger.error(e); } } return new JLabel("No " + iconRef.getName().toLowerCase(Locale.ENGLISH), SwingConstants.CENTER); @@ -585,7 +619,7 @@ private StructListPanel(String title, AbstractStruct struct, ClassBased on Rob Camick's sources: https://tips4java.wordpress.com/2008/11/06/wrap-layout/

*/ public class WrapLayout extends FlowLayout { public WrapLayout() { diff --git a/src/org/infinity/gui/converter/BamFilterBase.java b/src/org/infinity/gui/converter/BamFilterBase.java index 1315d3f33..c91c3e5cf 100644 --- a/src/org/infinity/gui/converter/BamFilterBase.java +++ b/src/org/infinity/gui/converter/BamFilterBase.java @@ -12,6 +12,7 @@ import javax.swing.event.ChangeListener; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; +import org.infinity.util.Logger; /** * The base class for BAM converter effects filters. @@ -101,17 +102,18 @@ public void close() { * Modifies the specified BufferedImage object to reflect the current settings of the filter.
* Note: For optimization purposes, prevent creating a new BufferedImage object if possible. * - * @param frame The PseudoBamFrameEntry object to modify. + * @param frameIndex Frame index in the global frame list of the current BAM animation. + * @param frame The PseudoBamFrameEntry object to modify. * @return The updated PseudoBamFrameEntry object. */ - public abstract PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry frame); + public abstract PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame); /** * Adds a ChangeListener to the listener list. ChangeListeners will be notified whenever the filter settings change. */ public void addChangeListener(ChangeListener l) { if (l != null) { - if (listChangeListeners.indexOf(l) < 0) { + if (!listChangeListeners.contains(l)) { listChangeListeners.add(l); } } @@ -164,6 +166,7 @@ protected static int decodeNumber(String param, int min, int max, int defValue) return value; } } catch (NumberFormatException e) { + Logger.trace(e); } } return defValue; @@ -178,6 +181,7 @@ protected static double decodeDouble(String param, double min, double max, doubl return value; } } catch (NumberFormatException e) { + Logger.trace(e); } } return defValue; diff --git a/src/org/infinity/gui/converter/BamFilterBaseColor.java b/src/org/infinity/gui/converter/BamFilterBaseColor.java index c1b30bf54..2d46992da 100644 --- a/src/org/infinity/gui/converter/BamFilterBaseColor.java +++ b/src/org/infinity/gui/converter/BamFilterBaseColor.java @@ -117,7 +117,7 @@ public ExcludeColorsPanel(int[] palette) { */ public void addChangeListener(ChangeListener l) { if (l != null) { - if (listChangeListeners.indexOf(l) < 0) { + if (!listChangeListeners.contains(l)) { listChangeListeners.add(l); } } diff --git a/src/org/infinity/gui/converter/BamFilterBaseOutput.java b/src/org/infinity/gui/converter/BamFilterBaseOutput.java index b5c7dc0b9..74d96c46d 100644 --- a/src/org/infinity/gui/converter/BamFilterBaseOutput.java +++ b/src/org/infinity/gui/converter/BamFilterBaseOutput.java @@ -6,9 +6,12 @@ import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; +import java.nio.file.Path; import java.util.Arrays; +import org.infinity.resource.graphics.DxtEncoder; import org.infinity.resource.graphics.PseudoBamDecoder; +import org.infinity.util.Logger; /** * The base class for filters that output the current state of the BAM structure to disk. @@ -53,4 +56,42 @@ public static int[] retrievePalette(PseudoBamDecoder decoder) { } return retVal; } + + /** + * Converts animation data from the specified decoder into the target BAM format and saves it to disk. + * + * @param converter The global {@link ConvertToBam} instance. + * @param outFileName Output path of the resulting BAM file. + * @param decoder {@link PseudoBamDecoder} instance with animation data to convert. + * @return {@code true} if the conversion completed successfully, {@code false} otherwise. + * @throws Exception if an unrecoverable error occurs during the conversion process. + */ + public static boolean convertBam(ConvertToBam converter, Path outFileName, PseudoBamDecoder decoder) + throws Exception { + if (converter != null && outFileName != null && decoder != null) { + if (converter.isBamV1Selected()) { + // convert to BAM v1 + decoder.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, converter.getPaletteDialog().getRleIndex()); + decoder.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, converter.isBamV1Compressed()); + try { + return decoder.exportBamV1(outFileName, converter.getProgressMonitor(), converter.getProgressMonitorStage()); + } catch (Exception e) { + Logger.error(e); + throw e; + } + } else { + // convert to BAM v2 + DxtEncoder.DxtType dxtType = converter.getDxtType(); + int pvrzIndex = converter.getPvrzIndex(); + try { + return decoder.exportBamV2(outFileName, dxtType, pvrzIndex, converter.getProgressMonitor(), + converter.getProgressMonitorStage()); + } catch (Exception e) { + Logger.error(e); + throw e; + } + } + } + return false; + } } diff --git a/src/org/infinity/gui/converter/BamFilterColorBCG.java b/src/org/infinity/gui/converter/BamFilterColorBCG.java index eb9aa9a5c..b851cbbb9 100644 --- a/src/org/infinity/gui/converter/BamFilterColorBCG.java +++ b/src/org/infinity/gui/converter/BamFilterColorBCG.java @@ -66,7 +66,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -80,12 +80,10 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(sliderBrightness.getValue()).append(';'); - sb.append(sliderContrast.getValue()).append(';'); - sb.append(((SpinnerNumberModel) spinnerGamma.getModel()).getNumber().doubleValue()).append(';'); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return String.valueOf(sliderBrightness.getValue()) + ';' + + sliderContrast.getValue() + ';' + + ((SpinnerNumberModel) spinnerGamma.getModel()).getNumber().doubleValue() + ';' + + encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -94,9 +92,9 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.trim().split(";"); - Integer bValue = Integer.MIN_VALUE; - Integer cValue = Integer.MIN_VALUE; - Double gValue = Double.MIN_VALUE; + int bValue = Integer.MIN_VALUE; + int cValue = Integer.MIN_VALUE; + double gValue = Double.MIN_VALUE; int[] indices = null; // parsing configuration data @@ -238,17 +236,17 @@ public void stateChanged(ChangeEvent event) { if (event.getSource() == pExcludeColors) { fireChangeListener(); } else if (event.getSource() == sliderBrightness) { - spinnerBrightness.setValue(Integer.valueOf(sliderBrightness.getValue())); + spinnerBrightness.setValue(sliderBrightness.getValue()); if (!sliderBrightness.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderContrast) { - spinnerContrast.setValue(Integer.valueOf(sliderContrast.getValue())); + spinnerContrast.setValue(sliderContrast.getValue()); if (!sliderContrast.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderGamma) { - spinnerGamma.setValue(Double.valueOf(sliderGamma.getValue() / GAMMA_SCALE_FACTOR)); + spinnerGamma.setValue(sliderGamma.getValue() / GAMMA_SCALE_FACTOR); if (!sliderGamma.getModel().getValueIsAdjusting()) { fireChangeListener(); } @@ -257,7 +255,7 @@ public void stateChanged(ChangeEvent event) { } else if (event.getSource() == spinnerContrast) { sliderContrast.setValue(((Integer) spinnerContrast.getValue())); } else if (event.getSource() == spinnerGamma) { - double v = ((Double) spinnerGamma.getValue()).doubleValue() * GAMMA_SCALE_FACTOR; + double v = (Double) spinnerGamma.getValue() * GAMMA_SCALE_FACTOR; sliderGamma.setValue((int) v); } } @@ -316,7 +314,7 @@ private BufferedImage applyEffect(BufferedImage srcImage) { float gamma2 = 1.0f / ((Double) spinnerGamma.getValue()).floatValue(); for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { // extracting color channels float fa = isPremultiplied ? (float) ((buffer[i] >>> 24) & 0xff) : 255.0f; float fr = ((buffer[i] >>> 16) & 0xff) / fa; diff --git a/src/org/infinity/gui/converter/BamFilterColorBalance.java b/src/org/infinity/gui/converter/BamFilterColorBalance.java index 260161a2b..efe970579 100644 --- a/src/org/infinity/gui/converter/BamFilterColorBalance.java +++ b/src/org/infinity/gui/converter/BamFilterColorBalance.java @@ -64,7 +64,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -78,12 +78,10 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(sliderRed.getValue()).append(';'); - sb.append(sliderGreen.getValue()).append(';'); - sb.append(sliderBlue.getValue()).append(';'); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return String.valueOf(sliderRed.getValue()) + ';' + + sliderGreen.getValue() + ';' + + sliderBlue.getValue() + ';' + + encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -92,9 +90,9 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.trim().split(";"); - Integer redValue = Integer.MIN_VALUE; - Integer greenValue = Integer.MIN_VALUE; - Integer blueValue = Integer.MIN_VALUE; + int redValue = Integer.MIN_VALUE; + int greenValue = Integer.MIN_VALUE; + int blueValue = Integer.MIN_VALUE; int[] indices = null; // parsing configuration data @@ -233,17 +231,17 @@ public void stateChanged(ChangeEvent event) { if (event.getSource() == pExcludeColors) { fireChangeListener(); } else if (event.getSource() == sliderRed) { - spinnerRed.setValue(Integer.valueOf(sliderRed.getValue())); + spinnerRed.setValue(sliderRed.getValue()); if (!sliderRed.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderGreen) { - spinnerGreen.setValue(Integer.valueOf(sliderGreen.getValue())); + spinnerGreen.setValue(sliderGreen.getValue()); if (!sliderGreen.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderBlue) { - spinnerBlue.setValue(Integer.valueOf(sliderBlue.getValue())); + spinnerBlue.setValue(sliderBlue.getValue()); if (!sliderBlue.getModel().getValueIsAdjusting()) { fireChangeListener(); } @@ -305,7 +303,7 @@ private BufferedImage applyEffect(BufferedImage srcImage) { float blue = ((Integer) spinnerBlue.getValue()).floatValue() / 255.0f; for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { // extracting color channels float fa = ((buffer[i] >>> 24) & 0xff) / 255.0f; float fr = (((buffer[i] >>> 16) & 0xff) / 255.0f) / fa; diff --git a/src/org/infinity/gui/converter/BamFilterColorHSL.java b/src/org/infinity/gui/converter/BamFilterColorHSL.java index 531a0e950..f83860178 100644 --- a/src/org/infinity/gui/converter/BamFilterColorHSL.java +++ b/src/org/infinity/gui/converter/BamFilterColorHSL.java @@ -64,7 +64,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -78,12 +78,10 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(sliderHue.getValue()).append(';'); - sb.append(sliderSaturation.getValue()).append(';'); - sb.append(sliderLightness.getValue()).append(';'); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return String.valueOf(sliderHue.getValue()) + ';' + + sliderSaturation.getValue() + ';' + + sliderLightness.getValue() + ';' + + encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -92,9 +90,9 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.trim().split(";"); - Integer hValue = Integer.MIN_VALUE; - Integer sValue = Integer.MIN_VALUE; - Integer lValue = Integer.MIN_VALUE; + int hValue = Integer.MIN_VALUE; + int sValue = Integer.MIN_VALUE; + int lValue = Integer.MIN_VALUE; int[] indices = null; // parsing configuration data @@ -235,17 +233,17 @@ public void stateChanged(ChangeEvent event) { if (event.getSource() == pExcludeColors) { fireChangeListener(); } else if (event.getSource() == sliderHue) { - spinnerHue.setValue(Integer.valueOf(sliderHue.getValue())); + spinnerHue.setValue(sliderHue.getValue()); if (!sliderHue.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderSaturation) { - spinnerSaturation.setValue(Integer.valueOf(sliderSaturation.getValue())); + spinnerSaturation.setValue(sliderSaturation.getValue()); if (!sliderSaturation.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderLightness) { - spinnerLightness.setValue(Integer.valueOf(sliderLightness.getValue())); + spinnerLightness.setValue(sliderLightness.getValue()); if (!sliderLightness.getModel().getValueIsAdjusting()) { fireChangeListener(); } @@ -312,7 +310,7 @@ private BufferedImage applyEffect(BufferedImage srcImage) { float lightness = ((Integer) spinnerLightness.getValue()).floatValue() / 100.0f; for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { // convert RGB -> HSL float fa = isPremultiplied ? (float) ((buffer[i] >>> 24) & 0xff) : 255.0f; float fr = ((buffer[i] >>> 16) & 0xff) / fa; diff --git a/src/org/infinity/gui/converter/BamFilterColorInvert.java b/src/org/infinity/gui/converter/BamFilterColorInvert.java index 8f68f3769..a4cf10fdf 100644 --- a/src/org/infinity/gui/converter/BamFilterColorInvert.java +++ b/src/org/infinity/gui/converter/BamFilterColorInvert.java @@ -53,7 +53,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -67,9 +67,7 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -180,7 +178,7 @@ private BufferedImage applyEffect(BufferedImage srcImage) { } for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { buffer[i] = (buffer[i] & 0xff000000) | (~buffer[i] & 0x00ffffff); } } diff --git a/src/org/infinity/gui/converter/BamFilterColorLab.java b/src/org/infinity/gui/converter/BamFilterColorLab.java index ad359a4e7..d39490a78 100644 --- a/src/org/infinity/gui/converter/BamFilterColorLab.java +++ b/src/org/infinity/gui/converter/BamFilterColorLab.java @@ -68,7 +68,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -82,12 +82,10 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(sliderL.getValue()).append(';'); - sb.append(sliderA.getValue()).append(';'); - sb.append(sliderB.getValue()).append(';'); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return String.valueOf(sliderL.getValue()) + ';' + + sliderA.getValue() + ';' + + sliderB.getValue() + ';' + + encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -96,9 +94,9 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.trim().split(";"); - Integer lValue = Integer.MIN_VALUE; - Integer aValue = Integer.MIN_VALUE; - Integer bValue = Integer.MIN_VALUE; + int lValue = Integer.MIN_VALUE; + int aValue = Integer.MIN_VALUE; + int bValue = Integer.MIN_VALUE; int[] indices = null; // parsing configuration data @@ -234,17 +232,17 @@ public void stateChanged(ChangeEvent event) { if (event.getSource() == pExcludeColors) { fireChangeListener(); } else if (event.getSource() == sliderL) { - spinnerL.setValue(Integer.valueOf(sliderL.getValue())); + spinnerL.setValue(sliderL.getValue()); if (!sliderL.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderA) { - spinnerA.setValue(Integer.valueOf(sliderA.getValue())); + spinnerA.setValue(sliderA.getValue()); if (!sliderA.getModel().getValueIsAdjusting()) { fireChangeListener(); } } else if (event.getSource() == sliderB) { - spinnerB.setValue(Integer.valueOf(sliderB.getValue())); + spinnerB.setValue(sliderB.getValue()); if (!sliderB.getModel().getValueIsAdjusting()) { fireChangeListener(); } @@ -311,7 +309,7 @@ private BufferedImage applyEffect(BufferedImage srcImage) { double labB = ((Integer) spinnerB.getValue()).doubleValue(); for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { // convert RGB -> Lab int fa = isPremultiplied ? (buffer[i] >>> 24) & 0xff : 255; int fr = ((buffer[i] >>> 16) & 0xff) * fa / 255; diff --git a/src/org/infinity/gui/converter/BamFilterColorReplace.java b/src/org/infinity/gui/converter/BamFilterColorReplace.java index cb71073c5..9a1bf2817 100644 --- a/src/org/infinity/gui/converter/BamFilterColorReplace.java +++ b/src/org/infinity/gui/converter/BamFilterColorReplace.java @@ -80,7 +80,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -112,9 +112,7 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeColorList(paletteDialog.getPalette())); - return sb.toString(); + return encodeColorList(paletteDialog.getPalette()); } @Override @@ -275,7 +273,7 @@ public void loadPalette(Path paletteFile) throws Exception { } // fetching palette data - int[] palette = null; + final int[] palette; if ("BM".equals(new String(signature, 0, 2))) { palette = ColorConvert.loadPaletteBMP(paletteFile); } else if (Arrays.equals(Arrays.copyOfRange(signature, 0, 4), new byte[] { (byte) 0x89, 0x50, 0x4e, 0x47 })) { @@ -299,7 +297,7 @@ public void loadPalette(Path paletteFile) throws Exception { } // applying palette - if (palette != null && palette.length > 0) { + if (palette.length > 0) { loadPalette(palette); } else { throw new Exception("No palette found in file " + paletteFile.getFileName()); diff --git a/src/org/infinity/gui/converter/BamFilterColorSwap.java b/src/org/infinity/gui/converter/BamFilterColorSwap.java index 2a54b20cc..d8b8f51af 100644 --- a/src/org/infinity/gui/converter/BamFilterColorSwap.java +++ b/src/org/infinity/gui/converter/BamFilterColorSwap.java @@ -14,6 +14,7 @@ import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.IndexColorModel; +import java.util.Objects; import javax.swing.JComboBox; import javax.swing.JLabel; @@ -88,7 +89,7 @@ public BufferedImage process(BufferedImage frame) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { if (entry != null) { entry.setFrame(applyEffect(entry.getFrame())); } @@ -102,10 +103,8 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(cbSwapType.getSelectedIndex()).append(';'); - sb.append(encodeColorList(pExcludeColors.getSelectedIndices())); - return sb.toString(); + return String.valueOf(cbSwapType.getSelectedIndex()) + ';' + + encodeColorList(pExcludeColors.getSelectedIndices()); } @Override @@ -246,10 +245,10 @@ private BufferedImage applyEffect(BufferedImage srcImage) { // shift contains shift values for r, g, b final SwapType type = (SwapType) cbSwapType.getSelectedItem(); - final int[] shift = type.getShift(); + final int[] shift = Objects.requireNonNull(type).getShift(); for (int i = 0; i < buffer.length; i++) { - if ((cm == null || (cm != null && !pExcludeColors.isSelectedIndex(i))) && (buffer[i] & 0xff000000) != 0) { + if ((cm == null || !pExcludeColors.isSelectedIndex(i)) && (buffer[i] & 0xff000000) != 0) { // extracting color channels int ir = buffer[i] & 0x00ff0000; int ig = buffer[i] & 0x0000ff00; diff --git a/src/org/infinity/gui/converter/BamFilterFactory.java b/src/org/infinity/gui/converter/BamFilterFactory.java index afe2bf65a..483774e0a 100644 --- a/src/org/infinity/gui/converter/BamFilterFactory.java +++ b/src/org/infinity/gui/converter/BamFilterFactory.java @@ -4,50 +4,21 @@ package org.infinity.gui.converter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.infinity.util.Logger; +import org.infinity.util.Misc; +import org.infinity.util.Platform; + public class BamFilterFactory { - private static final List FILTER_INFO_LIST = new ArrayList<>(); - - static { - // Registering individual BAM filters - FILTER_INFO_LIST.add( - new FilterInfo(BamFilterColorBCG.getFilterName(), BamFilterColorBCG.getFilterDesc(), BamFilterColorBCG.class)); - FILTER_INFO_LIST.add( - new FilterInfo(BamFilterColorHSL.getFilterName(), BamFilterColorHSL.getFilterDesc(), BamFilterColorHSL.class)); - FILTER_INFO_LIST.add( - new FilterInfo(BamFilterColorLab.getFilterName(), BamFilterColorLab.getFilterDesc(), BamFilterColorLab.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterColorBalance.getFilterName(), BamFilterColorBalance.getFilterDesc(), - BamFilterColorBalance.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterColorReplace.getFilterName(), BamFilterColorReplace.getFilterDesc(), - BamFilterColorReplace.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterColorSwap.getFilterName(), BamFilterColorSwap.getFilterDesc(), - BamFilterColorSwap.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterColorInvert.getFilterName(), BamFilterColorInvert.getFilterDesc(), - BamFilterColorInvert.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterTransformResize.getFilterName(), - BamFilterTransformResize.getFilterDesc(), BamFilterTransformResize.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterTransformRotate.getFilterName(), - BamFilterTransformRotate.getFilterDesc(), BamFilterTransformRotate.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterTransformMirror.getFilterName(), - BamFilterTransformMirror.getFilterDesc(), BamFilterTransformMirror.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterTransformTrim.getFilterName(), BamFilterTransformTrim.getFilterDesc(), - BamFilterTransformTrim.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterTransformCenter.getFilterName(), - BamFilterTransformCenter.getFilterDesc(), BamFilterTransformCenter.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterOutputDefault.getFilterName(), BamFilterOutputDefault.getFilterDesc(), - BamFilterOutputDefault.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterOutputCombine.getFilterName(), BamFilterOutputCombine.getFilterDesc(), - BamFilterOutputCombine.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterOutputSplitted.getFilterName(), BamFilterOutputSplitted.getFilterDesc(), - BamFilterOutputSplitted.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterOutputImage.getFilterName(), BamFilterOutputImage.getFilterDesc(), - BamFilterOutputImage.class)); - FILTER_INFO_LIST.add(new FilterInfo(BamFilterOutputGif.getFilterName(), BamFilterOutputGif.getFilterDesc(), - BamFilterOutputGif.class)); - } + /** List of registered BAM filters. */ + private static final List FILTER_INFO_LIST = new ArrayList<>(scanFilters()); /** Returns the number of registered BAM filters. */ public static int getFilterInfoSize() { @@ -99,7 +70,7 @@ public static BamFilterBase createInstance(ConvertToBam parent, Class normalizeFilterList(ConvertToBam parent, List< List retList = new ArrayList<>(); List tmpList = new ArrayList<>(); if (filterList != null) { - for (int i = 0; i < filterList.size(); i++) { - if (filterList.get(i) instanceof BamFilterBaseOutput) { - tmpList.add(filterList.get(i)); + for (BamFilterBase bamFilterBase : filterList) { + if (bamFilterBase instanceof BamFilterBaseOutput) { + tmpList.add(bamFilterBase); } else { - retList.add(filterList.get(i)); + retList.add(bamFilterBase); } } } // adding output filters last if (!tmpList.isEmpty()) { - for (int i = 0; i < tmpList.size(); i++) { - retList.add(tmpList.get(i)); - } + retList.addAll(tmpList); } else { retList.add(BamFilterFactory.createInstance(parent, BamFilterOutputDefault.class)); } @@ -135,6 +104,53 @@ public static List normalizeFilterList(ConvertToBam parent, List< return retList; } + /** + * Scans the current application package for available BAM filters and returns them as a sorted list. + * + * @return List of {@link FilterInfo} instances. Returns an empty list if filters could not be determined. + */ + private static List scanFilters() { + final List retVal = new ArrayList<>(); + + try { + final List filterPathList = Misc.getFilesInPackage(BamFilterFactory.class.getPackage().getName()); + for (final Path filterPath : filterPathList) { + // consider only regular Java classes + if (!filterPath.getFileName().toString().endsWith(".class")) { + continue; + } + + final String filterClassName = filterPath.toString().replaceAll("\\.class$", "").replace(Platform.FILE_SEPARATOR, "."); + try { + final Class cls = Class.forName(filterClassName); + if (BamFilterBase.class.isAssignableFrom(cls) && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { + @SuppressWarnings("unchecked") + final Class filterClass = (Class) cls; + try { + final Method nameMethod = filterClass.getMethod("getFilterName"); + final Method descMethod = filterClass.getMethod("getFilterDesc"); + final String filterName = nameMethod.invoke(null).toString(); + final String filterDesc = descMethod.invoke(null).toString(); + retVal.add(new FilterInfo(filterName, filterDesc, filterClass)); + } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) { + Logger.warn(e, "Could not load BAM filter: " + filterClass.getSimpleName()); + } + } + } catch (ExceptionInInitializerError e) { + // should be irrelevant in our case + Logger.trace(e); + } + } + } catch (Exception e) { + Logger.error(e, "Could not load BAM filters"); + retVal.clear(); + } + + retVal.sort((a, b) -> a.getName().compareTo(b.getName())); + + return retVal; + } + // -------------------------- INNER CLASSES -------------------------- public static final class FilterInfo implements Comparable { diff --git a/src/org/infinity/gui/converter/BamFilterOutputCombine.java b/src/org/infinity/gui/converter/BamFilterOutputCombine.java index d9647efbd..c01dc6419 100644 --- a/src/org/infinity/gui/converter/BamFilterOutputCombine.java +++ b/src/org/infinity/gui/converter/BamFilterOutputCombine.java @@ -61,7 +61,7 @@ public boolean setConfiguration(String config) { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry frame) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame) { // does not modify the source image return frame; } diff --git a/src/org/infinity/gui/converter/BamFilterOutputDefault.java b/src/org/infinity/gui/converter/BamFilterOutputDefault.java index 4c0823db1..7e1dec522 100644 --- a/src/org/infinity/gui/converter/BamFilterOutputDefault.java +++ b/src/org/infinity/gui/converter/BamFilterOutputDefault.java @@ -7,14 +7,12 @@ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; -import java.nio.file.Path; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.infinity.gui.ViewerUtil; -import org.infinity.resource.graphics.DxtEncoder; import org.infinity.resource.graphics.PseudoBamDecoder; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; @@ -42,11 +40,11 @@ public BamFilterOutputDefault(ConvertToBam parent) { @Override public boolean process(PseudoBamDecoder decoder) throws Exception { - return applyEffect(decoder); + return BamFilterBaseOutput.convertBam(getConverter(), getConverter().getBamOutput(), decoder); } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { // does not modify the source image return entry; } @@ -74,36 +72,4 @@ protected JPanel loadControls() { return panel; } - - private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { - if (getConverter() != null && decoder != null) { - Path outFile = getConverter().getBamOutput(); - - if (getConverter().isBamV1Selected()) { - // convert to BAM v1 - decoder.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, - Integer.valueOf(getConverter().getPaletteDialog().getRleIndex())); - decoder.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, Boolean.valueOf(getConverter().isBamV1Compressed())); - try { - return decoder.exportBamV1(outFile, getConverter().getProgressMonitor(), - getConverter().getProgressMonitorStage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } else { - // convert to BAM v2 - DxtEncoder.DxtType dxtType = getConverter().getDxtType(); - int pvrzIndex = getConverter().getPvrzIndex(); - try { - return decoder.exportBamV2(outFile, dxtType, pvrzIndex, getConverter().getProgressMonitor(), - getConverter().getProgressMonitorStage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - } - return false; - } } diff --git a/src/org/infinity/gui/converter/BamFilterOutputGif.java b/src/org/infinity/gui/converter/BamFilterOutputGif.java index d7f5255c8..f61d8f7ce 100644 --- a/src/org/infinity/gui/converter/BamFilterOutputGif.java +++ b/src/org/infinity/gui/converter/BamFilterOutputGif.java @@ -78,9 +78,7 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.split(";"); - Integer fps = Integer.MIN_VALUE; - boolean loop = true; - + int fps = Integer.MIN_VALUE; if (params.length > 0) { int min = ((Number) ((SpinnerNumberModel) spinnerFPS.getModel()).getMinimum()).intValue(); int max = ((Number) ((SpinnerNumberModel) spinnerFPS.getModel()).getMaximum()).intValue(); @@ -90,6 +88,7 @@ public boolean setConfiguration(String config) { } } + boolean loop = true; if (params.length > 1) { if (params[1].equalsIgnoreCase("true")) { loop = true; @@ -111,7 +110,7 @@ public boolean setConfiguration(String config) { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry frame) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame) { return frame; } @@ -172,11 +171,11 @@ private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { boolean canvasCheck = true; Dimension dim = new Dimension(decoder.getFrameInfo(0).getWidth(), decoder.getFrameInfo(0).getHeight()); for (int idx = 0; idx < decoder.frameCount(); idx++) { - canvasCheck &= (decoder.getFrameInfo(idx).getWidth() == dim.width); + canvasCheck = (decoder.getFrameInfo(idx).getWidth() == dim.width); if (!canvasCheck) { break; } - canvasCheck &= (decoder.getFrameInfo(idx).getHeight() == dim.height); + canvasCheck = (decoder.getFrameInfo(idx).getHeight() == dim.height); if (!canvasCheck) { break; } diff --git a/src/org/infinity/gui/converter/BamFilterOutputImage.java b/src/org/infinity/gui/converter/BamFilterOutputImage.java index 655f5c2fc..c81b94720 100644 --- a/src/org/infinity/gui/converter/BamFilterOutputImage.java +++ b/src/org/infinity/gui/converter/BamFilterOutputImage.java @@ -31,6 +31,7 @@ import org.infinity.resource.graphics.BamDecoder; import org.infinity.resource.graphics.PseudoBamDecoder; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -64,11 +65,9 @@ public boolean process(PseudoBamDecoder decoder) throws Exception { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(cbImageType.getSelectedIndex()).append(';'); - sb.append(spinnerDigits.getValue()).append(';'); - sb.append(cbTransparent.isSelected()); - return sb.toString(); + return String.valueOf(cbImageType.getSelectedIndex()) + ';' + + spinnerDigits.getValue() + ';' + + cbTransparent.isSelected(); } @Override @@ -77,8 +76,8 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.split(";"); - Integer type = Integer.MIN_VALUE; - Integer digits = Integer.MIN_VALUE; + int type = Integer.MIN_VALUE; + int digits = Integer.MIN_VALUE; boolean t = true; if (params.length > 0) { @@ -121,7 +120,7 @@ public boolean setConfiguration(String config) { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry frame) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame) { return frame; } @@ -245,7 +244,7 @@ private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { throw new IOException(); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Could not export frame " + frameIdx); } image.flush(); diff --git a/src/org/infinity/gui/converter/BamFilterOutputOverlay.java b/src/org/infinity/gui/converter/BamFilterOutputOverlay.java new file mode 100644 index 000000000..ea3523dd7 --- /dev/null +++ b/src/org/infinity/gui/converter/BamFilterOutputOverlay.java @@ -0,0 +1,1459 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.gui.converter; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Graphics2D; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.awt.image.DataBuffer; +import java.awt.image.DataBufferByte; +import java.awt.image.DataBufferInt; +import java.awt.image.IndexColorModel; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeSet; +import java.util.function.BiFunction; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.ListSelectionModel; +import javax.swing.SwingConstants; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; + +import org.infinity.gui.ButtonPopupMenu; +import org.infinity.gui.NewAbstractSettings; +import org.infinity.gui.OpenResourceDialog; +import org.infinity.gui.ViewerUtil; +import org.infinity.icon.Icons; +import org.infinity.resource.Profile; +import org.infinity.resource.ResourceFactory; +import org.infinity.resource.graphics.BamDecoder; +import org.infinity.resource.graphics.BamDecoder.BamControl; +import org.infinity.resource.graphics.BamDecoder.FrameEntry; +import org.infinity.resource.graphics.ColorConvert; +import org.infinity.resource.graphics.PseudoBamDecoder; +import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamControl; +import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamCycleEntry; +import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; +import org.infinity.resource.key.BIFFResourceEntry; +import org.infinity.resource.key.FileResourceEntry; +import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Misc; +import org.infinity.util.Platform; +import org.infinity.util.tuples.Couple; +import org.tinylog.Logger; + +/** + * Output filter: Overlay the current animation with multiple BAM files. + */ +public class BamFilterOutputOverlay extends BamFilterBaseOutput implements ActionListener, ListSelectionListener { + private static final String FILTER_NAME = "Overlay BAM output"; + private static final String FILTER_DESC = "This filter renders all listed BAM files on top of the current " + + "animation on a per frame basis. It can be used to combine BAM animations " + + "that were split into segments because of hardware limitations " + + "(e.g. creature animations.)\n" + + "Overlay BAM files should contain at least as many cycles and cycle frame " + + "entries as the active BAM animation.\n" + + "Note: Output filters will always be processed last."; + + /** + * Controls how BAM animations should be rendered over the source BAM animation. + */ + public enum OverlayMode { + /** Source pixels are only overwritten by non-transparent overlay BAM pixels. */ + NORMAL("Normal", + "Source pixels are only overwritten by non-transparent overlay BAM pixels. Semi-transparent pixels are blended.", + BamFilterOutputOverlay::pixelOpNormal), + /** Source pixels are always overwritten by overlay BAM pixels. */ + FORCED("Forced", + "Source pixels are always overwritten by overlay BAM pixels.", + BamFilterOutputOverlay::pixelOpForced), + /** Only non-transparent source pixels are overwritten by overlay BAM pixels. */ + INCLUSIVE("Inclusive", + "Only non-transparent source pixels are overwritten by overlay BAM pixels. Semi-transparent pixels are blended.", + BamFilterOutputOverlay::pixelOpInclusive), + /** Only transparent source pixels are overwritten by overlay BAM pixels. */ + EXCLUSIVE("Exclusive", + "Only transparent source pixels are overwritten by overlay BAM pixels. Semi-transparent pixels are blended.", + BamFilterOutputOverlay::pixelOpExclusive), + ; + + /** Returns the specified {@link OverlayMode}, or {@link #NORMAL} if {@code mode} is {@code null}. */ + public static OverlayMode getOrDefault(OverlayMode mode) { + return (mode != null) ? mode : NORMAL; + } + + /** + * Returns the {@link OverlayMode} with the specified ordinal value. + * Returns {@link #NORMAL} if the value is out of bounds. + */ + public static OverlayMode getOrDefault(int ordinal) { + if (ordinal >= 0 && ordinal < values().length) { + return values()[ordinal]; + } else { + return NORMAL; + } + } + + private final String name; + private final String desc; + private final OverlayFunc fn; + + OverlayMode(String name, String desc, OverlayFunc fn) { + this.name = name; + this.desc = desc; + this.fn = fn; + } + + /** Returns a short name for the OverlayMode enum. */ + public String getName() { + return name; + } + + /** Returns a more verbose description of the effect the OverlayMode enum produces. */ + public String getDesc() { + return desc; + } + + /** Returns a function that can be used to achieve the desired overlay effect. It works on a per pixel basis. */ + public OverlayFunc getFunction() { + return fn; + } + + @Override + public String toString() { + return getName(); + } + } + + // Cache for overlay BAM resources + private final HashMap bamCache = new HashMap<>(); + + private OverlayTableModel model; + private JTable table; + private JButton bUp; + private JButton bDown; + private JButton bEdit; + private JButton bRemove; + private JMenuItem miAddResource; + private JMenuItem miAddFile; + + public static String getFilterName() { + return FILTER_NAME; + } + + public static String getFilterDesc() { + return FILTER_DESC; + } + + public BamFilterOutputOverlay(ConvertToBam parent) { + super(parent, FILTER_NAME, FILTER_DESC); + } + + @Override + public boolean process(PseudoBamDecoder decoder) throws Exception { + return applyEffect(decoder); + } + + @Override + public String getConfiguration() { + // Format: A concatenation of pairs of BAM resource or file paths and overlay modes + // Note: URI-encode semicolon in path strings: %3B + // Example: res:/bam_resource;0;file:///c:/path/to/bam_file;1;rel:/chitin.key;2;... + final StringBuilder sb = new StringBuilder(); + for (final Couple entry : model) { + try { + final ResourcePath rp = new ResourcePath(entry.getValue0()); + final OverlayMode mode = entry.getValue1(); + if (sb.length() > 0) { + sb.append(';'); + } + sb.append(rp.toString()).append(';').append(mode.ordinal()); + } catch (Exception e) { + Logger.warn(e, "Invalid resource: " + entry); + } + } + return sb.toString(); + } + + @Override + public boolean setConfiguration(String config) { + if (config != null) { + model.clear(); + config = config.trim(); + if (!config.isEmpty()) { + final String[] params = config.split(";"); + for (int i = 0; i < params.length; i+= 2) { + // parsing BAM resource + final ResourceEntry resource; + try { + resource = new ResourcePath(new URI(params[i])).getResourceEntry(); + } catch (URISyntaxException e) { + Logger.error(e, "Invalid filter parameter: " + params[i]); + continue; + } + + // parsing overlay mode + final OverlayMode mode; + if (i + 1 < params.length) { + int modeIdx = Misc.toNumber(params[i + 1], 0); + mode = OverlayMode.getOrDefault(modeIdx); + } else { + mode = OverlayMode.NORMAL; + Logger.warn("No overlay mode specified. Assuming default mode."); + } + + addResource(resource, mode, false); + } + } + return true; + } + return false; + } + + @Override + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame) { + // shortcut + if (model.isEmpty()) { + return frame; + } + + // cycle index and cycle entry index are needed to render the correct overlay BAM frames + int cycleIdx = -1; + int cycleEntryIdx = -1; + final PseudoBamDecoder decoder = getConverter().getBamDecoder(ConvertToBam.BAM_FINAL); + final List cycleList = decoder.getCyclesList(); + for (int i = 0, numCycles = cycleList.size(); i < numCycles; i++) { + final PseudoBamCycleEntry cycle = cycleList.get(i); + for (int j = 0, numCycleEntries = cycle.size(); j < numCycleEntries; j++) { + final int frameIdx = cycle.get(j); + if (frameIdx == frameIndex) { + cycleIdx = i; + cycleEntryIdx = j; + break; + } + } + if (cycleIdx >= 0) { + break; + } + } + +// Logger.debug("Cycle: {}, cycle entry: {}", cycleIdx, cycleEntryIdx); + if (cycleIdx >= 0) { + // perform preview operation + final int[] frameIndices = new int[model.getRowCount()]; + for (int i = 0; i < frameIndices.length; i++) { + final ResourceEntry re = model.get(i).getValue0(); + final BamDecoder ovlDecoder = bamCache.get(re); + if (ovlDecoder != null) { + final BamControl control = ovlDecoder.createControl(); + int ovlFrameIdx = control.cycleGetFrameIndexAbsolute(cycleIdx, cycleEntryIdx); + frameIndices[i] = ovlFrameIdx; + } else { + Logger.warn("No BAM decoder available for overlay resource: " + re); + return frame; + } + } + + try { + return createOverlayFrame(frame, frameIndices); + } catch (Exception e) { + Logger.error(e); + } + } + + return frame; + } + + @Override + protected JPanel loadControls() { + // getting optimal width for "overlay mode" table column + int maxWidth = 0; + final JLabel l = new JLabel(); + for (final OverlayMode mode : OverlayMode.values()) { + final Dimension dim = Misc.getPrototypeSize(l, mode.toString()); + maxWidth = Math.max(maxWidth, dim.width); + } + + model = new OverlayTableModel(); + table = new JTable(model); + table.getSelectionModel().addListSelectionListener(this); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setDragEnabled(false); + + final DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); + tcr.setHorizontalAlignment(SwingConstants.CENTER); + table.getColumnModel().getColumn(1).setCellRenderer(tcr); + table.getColumnModel().getColumn(1).setPreferredWidth(maxWidth + 8); + table.getColumnModel().getColumn(1).setMaxWidth(maxWidth + 8); + + table.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && bEdit.isEnabled()) { + // invoke "Edit" button click + actionPerformed(new ActionEvent(bEdit, ActionEvent.ACTION_PERFORMED, null)); + } + super.mouseClicked(e); + } + }); + + table.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0 && e.getKeyCode() == KeyEvent.VK_A) { + // Ctrl+A + table.selectAll(); + } + } + }); + + final JScrollPane scroll = new JScrollPane(table); + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + bUp = new JButton(Icons.ICON_UP_16.getIcon()); + bUp.setMargin(new Insets(bUp.getInsets().top + 4, 2, bUp.getInsets().bottom + 4, 2)); + bUp.setToolTipText("Move selected list entry up."); + bUp.setEnabled(false); + bUp.addActionListener(this); + + bDown = new JButton(Icons.ICON_DOWN_16.getIcon()); + bDown.setMargin(new Insets(bDown.getInsets().top + 4, 2, bDown.getInsets().bottom + 4, 2)); + bDown.setToolTipText("Move selected list entry down."); + bDown.setEnabled(false); + bDown.addActionListener(this); + + bEdit = new JButton("Edit..."); + bEdit.setToolTipText("Edit overlay mode of the selected list entry."); + bEdit.setEnabled(false); + bEdit.addActionListener(this); + + bRemove = new JButton("Remove"); + bRemove.setToolTipText("Remove the selected BAM resource entry from the list."); + bRemove.setEnabled(false); + bRemove.addActionListener(this); + + miAddResource = new JMenuItem("Add BAM resource..."); + miAddResource.addActionListener(this); + miAddFile = new JMenuItem("Add BAM file..."); + miAddFile.addActionListener(this); + final ButtonPopupMenu bpmAdd = new ButtonPopupMenu("Add", new JMenuItem[]{miAddResource, miAddFile}); + bpmAdd.setIcon(Icons.ICON_ARROW_UP_15.getIcon()); + bpmAdd.setToolTipText("Add a new game resource or external file to the list."); + + final GridBagConstraints c = new GridBagConstraints(); + final JPanel panelRight = new JPanel(new GridBagLayout()); + ViewerUtil.setGBC(c, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0); + panelRight.add(bUp, c); + ViewerUtil.setGBC(c, 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, + new Insets(8, 0, 0, 0), 0, 0); + panelRight.add(bDown, c); + + final JPanel panelBottom = new JPanel(new GridBagLayout()); + ViewerUtil.setGBC(c, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0); + panelBottom.add(bRemove, c); + ViewerUtil.setGBC(c, 1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0); + panelBottom.add(new JPanel(), c); + ViewerUtil.setGBC(c, 2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, + new Insets(0, 0, 0, 0), 0, 0); + panelBottom.add(bEdit, c); + ViewerUtil.setGBC(c, 3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, + new Insets(0, 8, 0, 0), 0, 0); + panelBottom.add(bpmAdd, c); + + final JPanel panelMain = new JPanel(new GridBagLayout()); + ViewerUtil.setGBC(c, 0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0); + panelMain.add(scroll, c); + ViewerUtil.setGBC(c, 1, 0, 1, 1, 0.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.VERTICAL, + new Insets(0, 4, 0, 0), 0, 0); + panelMain.add(panelRight, c); + ViewerUtil.setGBC(c, 0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.HORIZONTAL, + new Insets(8, 0, 0, 0), 0, 0); + panelMain.add(panelBottom, c); + ViewerUtil.setGBC(c, 1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, + new Insets(0, 0, 0, 0), 0, 0); + panelMain.add(new JPanel(), c); + + return panelMain; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == bUp) { + // moving resource entry one position up + if (onMoveUpClicked()) { + fireChangeListener(); + } + } else if (e.getSource() == bDown) { + // moving resource entry one position down + if (onMoveDownClicked()) { + fireChangeListener(); + } + } else if (e.getSource() == bEdit) { + // editing overlay mode of selected entries + if (onEditClicked()) { + fireChangeListener(); + } + } else if (e.getSource() == bRemove) { + // removing overlay resource entry + if (onRemoveClicked()) { + fireChangeListener(); + } + } else if (e.getSource() == miAddFile) { + // adding new external file + if (onAddFileClicked()) { + fireChangeListener(); + } + } else if (e.getSource() == miAddResource) { + // adding new game resource + if (onAddResourceClicked()) { + fireChangeListener(); + } + } + } + + @Override + public void valueChanged(ListSelectionEvent e) { + if (!e.getValueIsAdjusting()) { + // getting selected row(s) + int minIdx = model.getRowCount(); + int maxIdx = -1; + for (final int i : table.getSelectedRows()) { + minIdx = Math.min(minIdx, i); + maxIdx = Math.max(maxIdx, i); + } + final boolean selected = (minIdx != model.getRowCount() && maxIdx != -1); + bEdit.setEnabled(selected); + bRemove.setEnabled(selected); + bUp.setEnabled(selected && minIdx > 0); + bDown.setEnabled(selected && maxIdx < model.getRowCount() - 1); + } + } + + /** Moves all selected table entries one position up (towards start of list). Returns {@code true} if table data has changed. */ + private boolean onMoveUpClicked() { + final int minIndex = Arrays.stream(table.getSelectedRows()).min().orElse(-1); + if (minIndex > 0) { + final int[] indices = table.getSelectedRows(); + for (int index : indices) { + final Couple item = model.remove(index); + model.add(index - 1, item); + } + table.getSelectionModel().clearSelection(); + for (final int index : indices) { + table.getSelectionModel().addSelectionInterval(index - 1, index - 1); + } + return true; + } + return false; + } + + /** Moves all selected table entries one position down (towards end of list). Returns {@code true} if table data has changed. */ + private boolean onMoveDownClicked() { + final int maxIndex = Arrays.stream(table.getSelectedRows()).max().orElse(model.getRowCount()); + if (maxIndex < model.getRowCount() - 1) { + final int[] indices = table.getSelectedRows(); + for (int i = indices.length - 1; i >= 0; i--) { + final Couple item = model.remove(indices[i]); + model.add(indices[i] + 1, item); + } + table.getSelectionModel().clearSelection(); + for (final int index : indices) { + table.getSelectionModel().addSelectionInterval(index + 1, index + 1); + } + return true; + } + return false; + } + + /** Allows the user to adjust the overlay mode for selected table entries. Returns {@code true} if table data has changed. */ + private boolean onEditClicked() { + final EnumSet modes = EnumSet.noneOf(OverlayMode.class); + for (final int rowIdx : table.getSelectedRows()) { + final OverlayMode mode = (OverlayMode) model.getValueAt(rowIdx, 1); + if (mode != null) { + modes.add(mode); + } + } + if (!modes.isEmpty()) { + final OverlayMode mode = (modes.size() == 1) ? modes.iterator().next() : null; + final OverlayModeSelection dlg = new OverlayModeSelection(getConverter(), mode); + if (dlg.isAccepted()) { + final OverlayMode newMode = dlg.getConfig(); + if (newMode != null) { + for (final int rowIdx : table.getSelectedRows()) { + model.set(rowIdx, newMode); + } + return true; + } + } + } + return false; + } + + /** Removes all selected entries from the table. Returns {@code true} if table data has changed. */ + private boolean onRemoveClicked() { + final int[] selectedRows = table.getSelectedRows(); + if (selectedRows.length > 0) { + int maxIdx = -1; + for (int i = selectedRows.length - 1; i >= 0; i--) { + removeResource(selectedRows[i]); + maxIdx = Math.max(maxIdx, selectedRows[i]); + } + if (!model.isEmpty()) { + maxIdx = Math.max(maxIdx, model.getRowCount() - 1); + table.setRowSelectionInterval(maxIdx, maxIdx); + } + return true; + } + return false; + } + + /** Allows the user to add one or more external files to the table. Returns {@code true} if table data has changed. */ + private boolean onAddFileClicked() { + final Path[] files = ConvertToBam.getOpenFileName(getConverter(), "BAM files", null, true, + new FileNameExtensionFilter[] { ConvertToBam.getBamFilter() }, 0); + if (files != null) { + for (final Path file : files) { + final ResourceEntry entry = new FileResourceEntry(file); + try { + if (addResource(entry, null, true)) { + final int rowIdx = model.getRowCount() - 1; + table.setRowSelectionInterval(rowIdx, rowIdx); + } + } catch (NullPointerException npe) { + Logger.warn(npe); + JOptionPane.showMessageDialog(getConverter(), npe.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + return true; + } + return false; + } + + /** Allows the user to add one or more game resources to the table. Returns {@code true} if table data has changed. */ + private boolean onAddResourceClicked() { + final ResourceEntry[] resources = OpenResourceDialog.showOpenDialog(getConverter(), "BAM resources", + new String[] { "BAM" }, true); + if (resources != null) { + for (final ResourceEntry resource : resources) { + try { + if (addResource(resource, null, true)) { + final int rowIdx = model.getRowCount() - 1; + table.setRowSelectionInterval(rowIdx, rowIdx); + } + } catch (NullPointerException npe) { + Logger.warn(npe); + JOptionPane.showMessageDialog(getConverter(), npe.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); + } + } + return true; + } + return false; + } + + /** + * Adds the specified BAM resource to the overlay table. + * + * @param entry {@link ResourceEntry} of the BAM resource to add. + * @param mode {@link OverlayMode} to associate with the BAM resource. Specify {@code null} to use {@link OverlayMode#NORMAL}. + * @param warn Indicates whether a warning dialog should be shown if the BAM resource has an incompatible cycle structure. + * @return {@code true} if the BAM resource was added successfully, {@code false} otherwise. + * @throws NullPointerException if the load operation was cancelled. + */ + private boolean addResource(ResourceEntry entry, OverlayMode mode, boolean warn) { + Objects.requireNonNull(entry, "BAM resource is null"); + if (!bamCache.containsKey(entry)) { + final BamDecoder decoder = BamDecoder.loadBam(entry); + if (decoder == null) { + throw new NullPointerException("Could not load BAM: " + entry); + } + + if (warn) { + if (!isBamCompatible(decoder)) { + final int retVal = JOptionPane.showConfirmDialog(getConverter(), + "Incompatible cycle structure detected. Load anyway?", entry.getResourceName(), JOptionPane.YES_NO_OPTION); + if (retVal != JOptionPane.YES_OPTION) { + return false; + } + } + } + + bamCache.put(entry, decoder); + } + model.add(entry, OverlayMode.getOrDefault(mode)); + return true; + } + + /** + * Removes the BAM resource entry at the specified table row index. + * + * @param rowIndex Table row index of the BAM resource. + * @throws IndexOutOfBoundsException if {@code rowIndex} is negative or greater than or equal to the table size. + */ + private void removeResource(int rowIndex) { + if (rowIndex >= 0) { + final Couple item = model.remove(rowIndex); + bamCache.remove(item.getValue0()); + } + } + + /** + * Determines whether the specified BAM is compatible with the active BAM. + * A BAM is considered compatible if it contains at least as many cycles and every cycle contains at least + * as many frame indices as the active BAM. + * + * @param decoder {@link BamDecoder} instance of a overlay BAM resource. + * @return {@code true} if the BAM resource is compatible, {@code false} otherwise. + */ + private boolean isBamCompatible(BamDecoder decoder) { + final BamControl dstControl = Objects.requireNonNull(decoder).createControl(); + final BamDecoder srcDecoder = getConverter().getBamDecoder(ConvertToBam.BAM_FINAL); + final BamControl srcControl = srcDecoder.createControl(); + + boolean isCompatible = dstControl.cycleCount() >= srcControl.cycleCount(); + for (int i = 0, count = srcControl.cycleCount(); isCompatible && i < count; i++) { + isCompatible = dstControl.cycleFrameCount(i) >= srcControl.cycleFrameCount(i); + } + return isCompatible; + } + + private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { + if (decoder == null) { + return false; + } + + if (model.isEmpty()) { + return BamFilterBaseOutput.convertBam(getConverter(), getConverter().getBamOutput(), decoder); + } + + // mapping: array of source frame indices -> new frame index + final HashMap frameIndexCache = + new HashMap<>(decoder.frameCount() * 4 / 3); + + // initializing BAM controls; controls[0] always refers to the source BAM control + final BamControl[] controls = new BamControl[model.getRowCount() + 1]; + controls[0] = decoder.createControl(); + for (int i = 0; i < model.getRowCount(); i++) { + final ResourceEntry re = model.get(i).getValue0(); + controls[i + 1] = bamCache.get(re).createControl(); + } + // stores new frame indices for each cycle/frame index + final int[][] cycleFrameIndices = new int[controls[0].cycleCount()][]; + + // generating frame index mappings + for (int cycleIdx = 0, numCycles = controls[0].cycleCount(); cycleIdx < numCycles; cycleIdx++) { + cycleFrameIndices[cycleIdx] = new int[controls[0].cycleFrameCount(cycleIdx)]; + for (int frameIdx = 0, numFrames = controls[0].cycleFrameCount(cycleIdx); frameIdx < numFrames; frameIdx++) { + final int[] frames = new int[controls.length]; + for (int i = 0; i < frames.length; i++) { + frames[i] = controls[i].cycleGetFrameIndexAbsolute(cycleIdx, frameIdx); + } + final int newIndex = frameIndexCache.size(); + frameIndexCache.computeIfAbsent(frames, key -> newIndex); + if (frameIndexCache.containsKey(frames)) { + cycleFrameIndices[cycleIdx][frameIdx] = frameIndexCache.get(frames); + } else { + throw new Exception("Unexpected cycle frame index generated for cycle=" + cycleIdx + ", frame index=" + frameIdx); + } + } + } + + // reversing mapping direction to get a sorted set of "frame index -> array of source frame indices" pairs + // this set should contain no gaps between the frame indices + final TreeSet> frameSet = new TreeSet<>((c1, c2) -> c1.getValue0() - c2.getValue0()); + for (final Map.Entry entry : frameIndexCache.entrySet()) { + frameSet.add(Couple.with(entry.getValue(), entry.getKey())); + } + + // generating output BAM + PseudoBamDecoder decoderOut = new PseudoBamDecoder(); + final PseudoBamControl controlOut = decoderOut.createControl(); + // adding global custom options + String[] options = decoder.getOptionNames(); + for (String option : options) { + decoderOut.setOption(option, decoder.getOption(option)); + } + + // generating output frames (outsource actual frame image generation to separate method to reuse it for preview generation) + int prevIndex = -1; + for (final Couple entry : frameSet) { + final int frameIdx = entry.getValue0(); + final int[] srcFrameIndices = entry.getValue1(); + + // adding dummy frames if needed (should not happen) + while (prevIndex + 1 < frameIdx) { + decoderOut.frameAdd(ColorConvert.createCompatibleImage(1, 1, true), new Point()); + prevIndex++; + Logger.warn("Filling frame list gap with dummy entry at index " + prevIndex); + } + + // generating output image and center information + final PseudoBamFrameEntry frameEntry = createOverlayFrame(decoder.getFrameInfo(srcFrameIndices[0]), + Arrays.copyOfRange(srcFrameIndices, 1, srcFrameIndices.length)); + decoderOut.frameAdd(frameEntry.getFrame(), new Point(frameEntry.getCenterX(), frameEntry.getCenterY())); + + prevIndex = frameIdx; + } + + // recreating cycle information + for (int[] cycleFrameIndex : cycleFrameIndices) { + controlOut.cycleAdd(cycleFrameIndex); + } + + if (getConverter().isBamV1Selected()) { + // converting output BAM frames to paletted format + // palette index 1 may have a special meaning: ensure that it doesn't change in the output BAM + final int[] palette = getConverter().getPaletteDialog().getPalette(BamPaletteDialog.TYPE_GENERATED); + final int[] reservedColors; + if (palette != null && palette.length > 1) { + reservedColors = new int[] { palette[1] }; + } else { + reservedColors = new int[0]; + } + decoderOut = convertToPalettedBam(decoderOut, ConvertToBam.getUseAlpha(), ConvertToBam.getTransparencyThreshold(), + reservedColors); + } + + // saving BAM to disk + return BamFilterBaseOutput.convertBam(getConverter(), getConverter().getBamOutput(), decoderOut); + } + + /** + * Composes a new BAM frame from the specified source frame indices. + * + * @param srcFrameEntry {@link PseudoBamFrameEntry} instance of the active BAM animation frame. + * @param overlayFrameIndices Array of BAM frame indices from the overlaid BAM resources. + * @return Fully initialized {@link PseudoBamFrameEntry} of the composed frame. + * @throws Exception if the output frame could not be generated. + */ + private PseudoBamFrameEntry createOverlayFrame(PseudoBamFrameEntry srcFrameEntry, int[] overlayFrameIndices) + throws Exception { + if (srcFrameEntry == null) { + throw new Exception("Source frame entry structure is null"); + } + if (overlayFrameIndices == null) { + throw new Exception("No overlay frame indices specified"); + } + if (overlayFrameIndices.length < model.getRowCount()) { + throw new Exception("Incomplete number of overlay frame indices specified (expected: " + model.getRowCount() + + ", found: " + overlayFrameIndices.length + ")"); + } + + // shortcut + if (model.isEmpty()) { + return srcFrameEntry; + } + + PseudoBamFrameEntry retVal = null; + // preparations + final BamDecoder[] decoders = new BamDecoder[model.getRowCount()]; + final BamControl[] controls = new BamControl[decoders.length]; + for (int i = 0; i < decoders.length; i++) { + final BamDecoder decoder = bamCache.get(model.get(i).getValue0()); + if (decoder == null) { + throw new Exception("Decoder not available for BAM resource at index " + i); + } + decoders[i] = decoder; + controls[i] = decoders[i].createControl(); + } + + // calculating output frame dimension + int left = Integer.MAX_VALUE, top = Integer.MAX_VALUE, right = Integer.MIN_VALUE, bottom = Integer.MIN_VALUE; + int cx = srcFrameEntry.getCenterX(); + int cy = srcFrameEntry.getCenterY(); + left = Math.min(left, (cx < 0) ? cx : -cx); + top = Math.min(top, (cy < 0) ? cy : -cy); + right = Math.max(right, srcFrameEntry.getWidth() - cx); + bottom = Math.max(bottom, srcFrameEntry.getHeight() - cy); + + for (int i = 0; i < decoders.length; i++) { + if (i < overlayFrameIndices.length) { + final FrameEntry frameInfo = decoders[i].getFrameInfo(overlayFrameIndices[i]); + cx = frameInfo.getCenterX(); + cy = frameInfo.getCenterY(); + left = Math.min(left, (cx < 0) ? cx : -cx); + top = Math.min(top, (cy < 0) ? cy : -cy); + right = Math.max(right, frameInfo.getWidth() - cx); + bottom = Math.max(bottom, frameInfo.getHeight() - cy); + } + } + + final int frameWidth = right - left; + final int frameHeight = bottom - top; + final Point center = new Point(-left, -top); + final BufferedImage dstImage = ColorConvert.createCompatibleImage(frameWidth, frameHeight, true); + + // composing frame data + // source BAM frame (simple copy) + Graphics2D g = dstImage.createGraphics(); + try { + g.drawImage(srcFrameEntry.getFrame(), -left - srcFrameEntry.getCenterX(), -top - srcFrameEntry.getCenterY(), null); + } finally { + g.dispose(); + g = null; + } + + // overlay BAM frames + if (decoders.length > 0) { + final BufferedImage srcImage = ColorConvert.createCompatibleImage(frameWidth, frameHeight, true); + final int[] dstBuffer = ((DataBufferInt) dstImage.getRaster().getDataBuffer()).getData(); + for (int i = 0; i < decoders.length; i++) { + final BamDecoder decoder = decoders[i]; + final BamControl control = controls[i]; + final OverlayMode mode = model.get(i).getValue1(); + final FrameEntry info = decoder.getFrameInfo(overlayFrameIndices[i]); + decoder.frameGet(control, overlayFrameIndices[i], srcImage); + final int[] srcBuffer = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData(); + + int x1 = -left -info.getCenterX(); + int y1 = -top - info.getCenterY(); + boolean skip = false; + for (int y = 0, h = info.getHeight(); y < h && !skip; y++) { + for (int x = 0, w = info.getWidth(); x < w && !skip; x++) { + // get dest buffer pixel -> src + final int ofsDestBuffer = (y1 + y) * frameWidth + (x1 + x); + // get overlay frame pixel -> dst + final int ofsSrcBuffer = y * frameWidth + x; + if (ofsDestBuffer >= 0 && ofsDestBuffer < dstBuffer.length && ofsSrcBuffer >= 0 && ofsSrcBuffer < srcBuffer.length) { + // calculate resulting pixel and set it in dest buffer + final int pixel = mode.getFunction().apply(dstBuffer[ofsDestBuffer], srcBuffer[ofsSrcBuffer]); + dstBuffer[ofsDestBuffer] = pixel; + } else { + Logger.debug("decoder={}, frame={}, dstBuffer.length={}, ofsDestBuffer={}, srcBuffer.length={}, ofsSrcBuffer={}", + i, overlayFrameIndices[i], dstBuffer.length, ofsDestBuffer, srcBuffer.length, ofsSrcBuffer); + if (ofsDestBuffer >= 0 && ofsDestBuffer < dstBuffer.length) { + throw new IndexOutOfBoundsException("Destination buffer: offset out of bounds (offset=" + ofsDestBuffer + + ", buffer size=" + dstBuffer.length); + } else { + throw new IndexOutOfBoundsException("Source buffer: offset out of bounds (offset=" + ofsSrcBuffer + + ", buffer size=" + srcBuffer.length); + } + } + } + } + } + } + + retVal = new PseudoBamFrameEntry(dstImage, center.x, center.y); + + return retVal; + } + + /** + * Returns the non-transparent destination pixel. Otherwise the source pixel is returned. + * + * @param src Pixel value of the current animation frame. + * @param dst Pixel value of the overlaid animation frame. + * @return Pixel value of the blend operation. + */ + private static int pixelOpNormal(int src, int dst) { + final int a2 = (dst >> 24) & 0xff; + if (a2 > 0 && a2 < 0xff) { + // performing alpha blending + final int a1 = (src >> 24) & 0xff; + final int r1 = (src >> 16) & 0xff; + final int g1 = (src >> 8) & 0xff; + final int b1 = src & 0xff; + + final int r2 = (dst >> 16) & 0xff; + final int g2 = (dst >> 8) & 0xff; + final int b2 = dst & 0xff; + + final int r = (((r1 * a1) >> 8) + ((r2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int g = (((g1 * a1) >> 8) + ((g2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int b = (((b1 * a1) >> 8) + ((b2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int a = (a1 + ((a2 * (256 - a1)) >> 8)) & 0xff; + return (a << 24) | (r << 16) | (g << 8) | b; + } else { + return ((dst & 0xff000000) != 0) ? dst : src; + } + } + + /** + * Always returns the destination pixel. + * + * @param src Pixel value of the current animation frame. + * @param dst Pixel value of the overlaid animation frame. + * @return Pixel value of the blend operation. + */ + private static int pixelOpForced(int src, int dst) { + return dst; + } + + /** + * Returns the destination pixel if the source pixel is non-transparent. Otherwise the source pixel is returned. + * + * @param src Pixel value of the current animation frame. + * @param dst Pixel value of the overlaid animation frame. + * @return Pixel value of the blend operation. + */ + private static int pixelOpInclusive(int src, int dst) { + final int a1 = (src >> 24) & 0xff; + if (a1 > 0 && a1 < 0xff) { + // performing alpha blending + final int r1 = (src >> 16) & 0xff; + final int g1 = (src >> 8) & 0xff; + final int b1 = src & 0xff; + + final int a2 = (dst >> 24) & 0xff; + final int r2 = (dst >> 16) & 0xff; + final int g2 = (dst >> 8) & 0xff; + final int b2 = dst & 0xff; + + final int r = (((r1 * a1) >> 8) + ((r2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int g = (((g1 * a1) >> 8) + ((g2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int b = (((b1 * a1) >> 8) + ((b2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int a = (a1 + ((a2 * (256 - a1)) >> 8)) & 0xff; + return (a << 24) | (r << 16) | (g << 8) | b; + } else { + return ((src & 0xff000000) != 0) ? dst : src; + } + } + + /** + * Returns the destination pixel if the source pixel is transparent. Otherwise the source pixel is returned. + * + * @param src Pixel value of the current animation frame. + * @param dst Pixel value of the overlaid animation frame. + * @return Pixel value of the blend operation. + */ + private static int pixelOpExclusive(int src, int dst) { + final int a1 = (src >> 24) & 0xff; + if (a1 > 0 && a1 < 0xff) { + // performing alpha blending + final int r1 = (src >> 16) & 0xff; + final int g1 = (src >> 8) & 0xff; + final int b1 = src & 0xff; + + final int a2 = (dst >> 24) & 0xff; + final int r2 = (dst >> 16) & 0xff; + final int g2 = (dst >> 8) & 0xff; + final int b2 = dst & 0xff; + + final int r = (((r1 * a1) >> 8) + ((r2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int g = (((g1 * a1) >> 8) + ((g2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int b = (((b1 * a1) >> 8) + ((b2 * a2 * (256 - a1)) >> 16)) & 0xff; + final int a = (a1 + ((a2 * (256 - a1)) >> 8)) & 0xff; + return (a << 24) | (r << 16) | (g << 8) | b; + } else { + return ((src & 0xff000000) == 0) ? dst : src; + } + } + + // TODO: move method to a more suitable class (e.g. ColorConvert) and make it public + /** + * Returns a {@link PseudoBamDecoder} instance where all frames are fully BAM V1 compatible. Does nothing if the + * decoder is already BAM V1 compatible. + * + * @param decoder {@link PseudoBamDecoder} instance to convert. + * @param useAlpha Specifies whether the generated palette supports alpha values. + * @param transparencyThreshold Threshold to determine whether a color is considered fully transparent. This value is + * only considered if {@code useAlpha} is {@code false}. + * @param reservedColors Optional array of colors that should be assigned to fixed palette indices, starting at + * palette index 1. Magic color "green" is ignored. + * @return {@link PseudoBamDecoder} instance with palette-based frames and the same cycle configuration as the source + * decoder. + * @throws Exception if an unrecoverable error occurs. + */ + private static PseudoBamDecoder convertToPalettedBam(PseudoBamDecoder decoder, boolean useAlpha, + int transparencyThreshold, int... reservedColors) throws Exception { + boolean isPalette = true; + final List framesList = decoder.getFramesList(); + for (int i = 0, size = framesList.size(); isPalette && i < size; i++) { + isPalette = (framesList.get(i).getFrame().getType() == BufferedImage.TYPE_BYTE_INDEXED); + } + + if (isPalette) { + return decoder; + } + + // preparing palette + final LinkedHashMap colorMap = new LinkedHashMap<>(); + for (int frameIdx = 0, frameCount = decoder.frameCount(); frameIdx < frameCount; frameIdx++) { + final PseudoBamFrameEntry info = decoder.getFrameInfo(frameIdx); + PseudoBamDecoder.registerColors(colorMap, info.getFrame(), true); + } + + final int[] subPalette = decoder.createGlobalPalette(colorMap); + final int[] newPalette = new int[256]; + newPalette[0] = 0x0000ff00; + System.arraycopy(subPalette, 0, newPalette, 1, subPalette.length); + + // configuring reserved colors + final double alphaWeight = useAlpha ? 1.0 : 0.0; + if (reservedColors.length > 0) { + int curIndex = 1; + for (final int color : reservedColors) { + if ((color & 0xffffff) != 0x00ff00) { + int idx = ColorConvert.getNearestColor(color, newPalette, alphaWeight, ColorConvert.COLOR_DISTANCE_CIE94, true); + if (idx != curIndex) { + final int tmp = newPalette[idx]; + newPalette[idx] = newPalette[curIndex]; + newPalette[curIndex] = tmp; + curIndex++; + } + } + } + } + + final PseudoBamDecoder newDecoder = new PseudoBamDecoder(); + + // performing color quantization + final HashMap colorCache = new HashMap<>(4096); + for (int i = 1; i < newPalette.length; i++) { + colorCache.put(newPalette[i], (byte) i); + } + final IndexColorModel cm = new IndexColorModel(8, 256, newPalette, 0, useAlpha, 0, DataBuffer.TYPE_BYTE); + for (final PseudoBamFrameEntry frameInfo : framesList) { + final BufferedImage dstImage = new BufferedImage(frameInfo.getWidth(), frameInfo.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, cm); + final byte[] dstBuf = ((DataBufferByte) dstImage.getRaster().getDataBuffer()).getData(); + + final BufferedImage srcImage = frameInfo.getFrame(); + if (srcImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { + // processing palette-based source image + final byte[] srcBuf = ((DataBufferByte) srcImage.getRaster().getDataBuffer()).getData(); + final IndexColorModel srcColorModel = (IndexColorModel) srcImage.getColorModel(); + final int[] srcColors = new int[srcColorModel.getMapSize()]; + srcColorModel.getRGBs(srcColors); + for (int ofs = 0; ofs < srcBuf.length; ofs++) { + final int srcColorIdx = srcBuf[ofs] & 0xff; + final int color = srcColors[(srcColorIdx < srcColors.length) ? srcColorIdx : 0]; + if (!PseudoBamDecoder.isTransparentColor(color, transparencyThreshold)) { + final byte colorIdx = colorCache.computeIfAbsent(color, c -> { + return (byte) ColorConvert.getNearestColor(color, newPalette, alphaWeight, ColorConvert.COLOR_DISTANCE_CIE94); + }); + dstBuf[ofs] = colorIdx; + } + } + } else { + // processing truecolor source image + final int[] srcBuf = ((DataBufferInt) srcImage.getRaster().getDataBuffer()).getData(); + for (int ofs = 0; ofs < srcBuf.length; ofs++) { + final int color = srcBuf[ofs]; + if (!PseudoBamDecoder.isTransparentColor(color, transparencyThreshold)) { + final byte colorIdx = colorCache.computeIfAbsent(color, c -> { + return (byte) ColorConvert.getNearestColor(color, newPalette, alphaWeight, ColorConvert.COLOR_DISTANCE_CIE94); + }); + dstBuf[ofs] = colorIdx; + } + } + } + + // adding frame + final int dstFrameIdx = newDecoder.frameAdd(dstImage, new Point(frameInfo.getCenterX(), frameInfo.getCenterY())); + final PseudoBamFrameEntry dstFrameInfo = newDecoder.getFrameInfo(dstFrameIdx); + dstFrameInfo.setOption(PseudoBamDecoder.OPTION_BOOL_TRANSPARENTGREENFORCED, true); + for (final String option : frameInfo.getOptionNames()) { + dstFrameInfo.setOption(option, frameInfo.getOption(option)); + } + } + + // transfering bam cycles + newDecoder.getCyclesList().addAll(decoder.getCyclesList()); + + return newDecoder; + } + + /** + * Specialization of the {@link BiFunction} interface for combining two source pixels to a destination pixel. + *

The first parameter specifies the pixel of the current animation frame.

+ *

The second parameter specifies the pixel of the overlaid animation frame.

+ *

The resulting pixel value is stored in the output animation frame.

+ *

Pixel format is {@code 0xAARRGGBB}.

+ */ + @FunctionalInterface + public static interface OverlayFunc extends BiFunction { + } + + /** + * Helper class that encodes a BAM resource path into a universal (URI) format. + */ + public static class ResourcePath { + /** + * URI scheme for biffed game resources. The resource path is expected to contain the resource name as root element. + */ + public static final String URI_SCHEME_RESOURCE = "res"; + /** + * URI scheme for relative file path definitions. The path is expected to be relative to the game's root folder. + */ + public static final String URI_SCHEME_RELPATH = "rel"; + + private final URI path; + + /** + * Initializes the {@code ResourcePath} object with the specified resource. + * + * @param entry {@link ResourceEntry} containing the game resource or file path of the BAM resource. + * @throws Exception If the resource location could not be determined. + */ + public ResourcePath(ResourceEntry entry) throws Exception { + Objects.requireNonNull(entry); + if (entry instanceof BIFFResourceEntry) { + this.path = new URI(URI_SCHEME_RESOURCE, "/" + entry.getResourceName(), null); + } else { + final Path resPath = entry.getActualPath(); + if (resPath.startsWith(Profile.getGameRoot())) { + // try to store relative path if possible + final String relPath; + if ("\\".equals(Platform.FILE_SEPARATOR)) { + relPath = Profile.getGameRoot().relativize(resPath).toString().replace('\\', '/'); + } else { + relPath = Profile.getGameRoot().relativize(resPath).toString(); + } + this.path = new URI(URI_SCHEME_RELPATH, "/" + relPath, null); + } else { + this.path = resPath.toUri(); + } + } + } + + /** + * Initializes the {@code ResourcePath} object with the specified {@link URI}. + * + * @param uri {@link URI} instance that defines a resource location. + */ + public ResourcePath(URI uri) { + this.path = Objects.requireNonNull(uri); + } + + /** Returns the {@link URI} of the resource stored inside this object. */ + public URI getURI() { + return path; + } + + /** Returns {@code true} if this object points to a (biffed) game resource. */ + public boolean isResource() { + return URI_SCHEME_RESOURCE.equals(path.getScheme()); + } + + /** Returns {@code true} if this object points to a relative file path. */ + public boolean isRelativePath() { + return URI_SCHEME_RELPATH.equals(path.getScheme()); + } + + /** + * Decodes the ResourceString URI and returns it as a {@link ResourceEntry} object. + * + * @return A {@link ResourceEntry} object with the resource path definition. Returns {@code null} if the resource + * could not be resolved. + * @throws IllegalArgumentException if the object contains an illegal path definition. + * @throws FileSystemNotFoundException if the filesystem does not exist (e.g. a virtual DLC filesystem). + */ + public ResourceEntry getResourceEntry() { + if (isResource()) { + // remove leading slash and decode semicolon + final String resourceName = path.getPath().substring(1).replace("%3B", ";"); + return ResourceFactory.getResourceEntry(resourceName); + } else if (isRelativePath()) { + // remove leading slash and decode semicolon + final String resourceName = path.getPath().substring(1).replace("%3B", ";"); + return new FileResourceEntry(Profile.getGameRoot().resolve(resourceName).normalize()); + } else { + return new FileResourceEntry(Paths.get(path).normalize()); + } + } + + @Override + public int hashCode() { + return Objects.hash(path); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ResourcePath other = (ResourcePath)obj; + return Objects.equals(path, other.path); + } + + /** + * Returns the content of the resource path in URI format. Semicolons inside the URI string are encoded + * to prevent conflicts with the BAM Converter configuration format. + */ + @Override + public String toString() { + return path.toString().replace(";", "%3B"); + } + } + + /** + * Table model for the JTable component of the preview UI with a subset of {@link List} methods. + */ + public static class OverlayTableModel extends AbstractTableModel + implements Iterable> { + private final List> entries = new ArrayList<>(); + + public OverlayTableModel() { + } + + @Override + public int getRowCount() { + return entries.size(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + if (rowIndex < 0 || rowIndex >= entries.size()) { + throw new IndexOutOfBoundsException("Row out of bounds: " + rowIndex); + } + return (columnIndex == 0) ? entries.get(rowIndex).getValue0() : entries.get(rowIndex).getValue1(); + } + + @Override + public String getColumnName(int column) { + return (column == 0) ? "Resource" : "Mode"; + } + + /** Adds a new entry with the specified arguments to the end of the table model. */ + public void add(ResourceEntry resource, OverlayMode mode) { + add(entries.size(), resource, mode); + } + + /** Inserts a new entry with the specified argument at the specified position in the table model. */ + public void add(int index, ResourceEntry resource, OverlayMode mode) { + Objects.requireNonNull(resource); + Objects.requireNonNull(mode); + add(index, Couple.with(resource, mode)); + } + + /** Inserts a new entry at the specified position in the table model. */ + public void add(int index, Couple item) { + Objects.requireNonNull(item); + entries.add(index, item); + fireTableRowsInserted(index, index); + } + + /** Removes all entries from the table model. */ + public void clear() { + final int size = entries.size(); + if (size > 0) { + entries.clear(); + fireTableDataChanged(); + } + } + + /** Returns the content of the entry at the specified position in the table model. */ + public Couple get(int index) { + final Couple entry = entries.get(index); + return Couple.with(entry.getValue0(), entry.getValue1()); + } + + /** Returns {@code true} if the table model contains no entries. */ + public boolean isEmpty() { + return entries.isEmpty(); + } + + /** Returns a read-only iterator over the entries in the table model. */ + @Override + public Iterator> iterator() { + return Collections.unmodifiableList(entries).iterator(); + } + + /** Removes the entry at the specified position in the table model. */ + public Couple remove(int index) { + final Couple retVal = entries.remove(index); + fireTableRowsDeleted(index, index); + return retVal; + } + + /** Replaces the {@link ResourceEntry} of the entry at the specified position in the table model. */ + public ResourceEntry set(int index, ResourceEntry resource) { + Objects.requireNonNull(resource); + final ResourceEntry retVal = entries.get(index).setValue0(resource); + fireTableCellUpdated(index, 0); + return retVal; + } + + /** Replaces the {@link OverlayMode} of the entry at the specified position in the table model. */ + public OverlayMode set(int index, OverlayMode mode) { + Objects.requireNonNull(mode); + final OverlayMode retVal = entries.get(index).setValue1(mode); + fireTableCellUpdated(index, 1); + return retVal; + } + + /** Replaces the content of the entry at the specified position in the table model. */ + public Couple set(int index, ResourceEntry resource, OverlayMode mode) { + Objects.requireNonNull(resource); + Objects.requireNonNull(mode); + final Couple entry = entries.get(index); + final Couple retVal = Couple.with(entry.getValue0(), entry.getValue1()); + entry.setValue0(resource); + entry.setValue1(mode); + fireTableRowsUpdated(index, index); + return retVal; + } + } + + /** + * Interactive dialog for selecting an {@link OverlayMode}. + */ + private static class OverlayModeSelection extends NewAbstractSettings implements ItemListener { + private static final String NO_CHANGE_NAME = "(No change)"; + private static final String NO_CHANGE_DESC = "Keep the current overlay modes for all selected entries."; + + private JComboBox cbMode; + private JTextArea descArea; + + public OverlayModeSelection(Window parent, OverlayMode mode) { + super(parent, "Select Overlay Mode"); + init(mode); + } + + @Override + public OverlayMode getConfig() { + return cbMode.getItemAt(cbMode.getSelectedIndex()); + } + + private void init(OverlayMode mode) { + acceptButton().setText("Select"); + acceptButton().setIcon(Icons.ICON_CHECK_16.getIcon()); + + final JLabel label = new JLabel("Select overlay mode:"); + label.setLabelFor(cbMode); + label.setDisplayedMnemonic(KeyEvent.VK_S); + + final OverlayMode[] items; + if (mode == null) { + items = new OverlayMode[OverlayMode.values().length + 1]; + items[0] = null; + System.arraycopy(OverlayMode.values(), 0, items, 1, OverlayMode.values().length); + } else { + items = OverlayMode.values(); + } + cbMode = new JComboBox<>(items); + cbMode.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, + boolean cellHasFocus) { + final String item = (value != null) ? value.toString() : NO_CHANGE_NAME; + return super.getListCellRendererComponent(list, item, index, isSelected, cellHasFocus); + } + }); + if (mode != null) { + cbMode.setSelectedItem(OverlayMode.getOrDefault(mode)); + } else { + cbMode.setSelectedIndex(0); + } + cbMode.addItemListener(this); + + descArea = new JTextArea(); + descArea.setLineWrap(true); + descArea.setWrapStyleWord(true); + descArea.setEditable(false); + descArea.setBackground(label.getBackground()); + final JScrollPane scroll = new JScrollPane(descArea); + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + scroll.getVerticalScrollBar().setUnitIncrement(16); + scroll.setPreferredSize(new Dimension(label.getPreferredSize().width * 7 / 4, 6 * label.getPreferredSize().height)); + scroll.setMinimumSize(scroll.getPreferredSize()); + updateDesc(cbMode.getItemAt(cbMode.getSelectedIndex())); + + final JPanel panelButtons = new JPanel(new FlowLayout(FlowLayout.TRAILING, 5, 5)); + panelButtons.add(acceptButton()); + panelButtons.add(rejectButton()); + + final GridBagConstraints c = new GridBagConstraints(); + final JPanel panel = new JPanel(new GridBagLayout()); + ViewerUtil.setGBC(c, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, + new Insets(10, 10, 3, 10), 0, 0); + panel.add(label, c); + ViewerUtil.setGBC(c, 0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.HORIZONTAL, + new Insets(0, 10, 10, 10), 0, 0); + panel.add(cbMode, c); + ViewerUtil.setGBC(c, 0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, + new Insets(0, 10, 10, 10), 0, 0); + panel.add(scroll, c); + ViewerUtil.setGBC(c, 0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.LAST_LINE_END, GridBagConstraints.NONE, + new Insets(0, 5, 5, 5), 0, 0); + panel.add(panelButtons, c); + + final Container contentPane = getContentPane(); + contentPane.add(panel); + + pack(); + setMinimumSize(getPreferredSize()); + setLocationRelativeTo(getParent()); + setCancelOnEscape(true); + setVisible(true); + } + + private void updateDesc(OverlayMode mode) { + final String desc = (mode != null) ? mode.getDesc() : NO_CHANGE_DESC; + descArea.setText(desc); + descArea.setCaretPosition(0); + } + + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getItem() instanceof OverlayMode) { + final OverlayMode mode = (OverlayMode) e.getItem(); + updateDesc(mode); + } + } + } +} diff --git a/src/org/infinity/gui/converter/BamFilterOutputSplitted.java b/src/org/infinity/gui/converter/BamFilterOutputSplitted.java index 8782a64ed..ca6969917 100644 --- a/src/org/infinity/gui/converter/BamFilterOutputSplitted.java +++ b/src/org/infinity/gui/converter/BamFilterOutputSplitted.java @@ -16,7 +16,6 @@ import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.IndexColorModel; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -30,7 +29,6 @@ import javax.swing.event.ChangeListener; import org.infinity.gui.ViewerUtil; -import org.infinity.resource.graphics.DxtEncoder; import org.infinity.resource.graphics.PseudoBamDecoder; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; import org.infinity.util.Misc; @@ -72,21 +70,19 @@ public boolean process(PseudoBamDecoder decoder) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { // does not modify the source image return entry; } @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(spinnerSplitX.getValue()).append(';'); - sb.append(spinnerSplitY.getValue()).append(';'); - sb.append(cbSplitAuto.isSelected()).append(';'); - sb.append(cbSuffixDigits.getSelectedIndex()).append(';'); - sb.append(spinnerSuffixStart.getValue()).append(';'); - sb.append(spinnerSuffixStep.getValue()); - return sb.toString(); + return String.valueOf(spinnerSplitX.getValue()) + ';' + + spinnerSplitY.getValue() + ';' + + cbSplitAuto.isSelected() + ';' + + cbSuffixDigits.getSelectedIndex() + ';' + + spinnerSuffixStart.getValue() + ';' + + spinnerSuffixStep.getValue(); } @Override @@ -95,12 +91,12 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.split(";"); - Integer splitX = Integer.MIN_VALUE; - Integer splitY = Integer.MIN_VALUE; + int splitX = Integer.MIN_VALUE; + int splitY = Integer.MIN_VALUE; boolean auto = true; int digits = -1; - Integer start = Integer.MIN_VALUE; - Integer step = Integer.MIN_VALUE; + int start = Integer.MIN_VALUE; + int step = Integer.MIN_VALUE; if (params.length > 0) { int min = ((Number) ((SpinnerNumberModel) spinnerSplitX.getModel()).getMinimum()).intValue(); @@ -184,10 +180,10 @@ protected JPanel loadControls() { JLabel l6 = new JLabel("Start at:"); JLabel l7 = new JLabel("Step by:"); spinnerSplitX = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); - ((SpinnerNumberModel) spinnerSplitX.getModel()).setMaximum(Integer.valueOf(MAX_SPLITS)); + ((SpinnerNumberModel) spinnerSplitX.getModel()).setMaximum(MAX_SPLITS); spinnerSplitX.addChangeListener(this); spinnerSplitY = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); - ((SpinnerNumberModel) spinnerSplitY.getModel()).setMaximum(Integer.valueOf(MAX_SPLITS)); + ((SpinnerNumberModel) spinnerSplitY.getModel()).setMaximum(MAX_SPLITS); spinnerSplitY.addChangeListener(this); cbSplitAuto = new JCheckBox("Split automatically", true); cbSplitAuto.addActionListener(this); @@ -200,10 +196,10 @@ protected JPanel loadControls() { cbSuffixDigits.setSelectedIndex(1); cbSuffixDigits.addActionListener(this); spinnerSuffixStart = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); - ((SpinnerNumberModel) spinnerSuffixStart.getModel()).setMaximum(Integer.valueOf(100000)); + ((SpinnerNumberModel) spinnerSuffixStart.getModel()).setMaximum(100000); spinnerSuffixStart.addChangeListener(this); spinnerSuffixStep = new JSpinner(new SpinnerNumberModel(1, 1, 1000, 1)); - ((SpinnerNumberModel) spinnerSuffixStep.getModel()).setMaximum(Integer.valueOf(10000)); + ((SpinnerNumberModel) spinnerSuffixStep.getModel()).setMaximum(10000); spinnerSuffixStep.addChangeListener(this); JPanel p1 = new JPanel(new GridBagLayout()); @@ -334,8 +330,8 @@ private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { } } } else { - segmentsX = ((Integer) spinnerSplitX.getValue()).intValue() + 1; - segmentsY = ((Integer) spinnerSplitY.getValue()).intValue() + 1; + segmentsX = (Integer) spinnerSplitX.getValue() + 1; + segmentsY = (Integer) spinnerSplitY.getValue() + 1; } // calculating individual splits for each frame @@ -396,7 +392,8 @@ private boolean applyEffect(PseudoBamDecoder decoder) throws Exception { // converting segmented BAM structure int suffix = suffixStart + segIdx * suffixStep; - if (!convertBam(FileManager.resolve(String.format(fmtBamFileName, suffix)), segmentDecoder)) { + if (!BamFilterBaseOutput.convertBam(getConverter(), FileManager.resolve(String.format(fmtBamFileName, suffix)), + segmentDecoder)) { throw new Exception(String.format("Error converting segment %d/%d", segIdx + 1, segmentCount)); } @@ -459,35 +456,4 @@ private PseudoBamFrameEntry createFrameSegment(PseudoBamFrameEntry entry, Rectan } return retVal; } - - // Exports the BAM specified by "decoder" into the filename "outFileName" using global settings - private boolean convertBam(Path outFileName, PseudoBamDecoder decoder) throws Exception { - if (getConverter() != null && outFileName != null && decoder != null) { - if (getConverter().isBamV1Selected()) { - // convert to BAM v1 - decoder.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, - Integer.valueOf(getConverter().getPaletteDialog().getRleIndex())); - decoder.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, Boolean.valueOf(getConverter().isBamV1Compressed())); - try { - return decoder.exportBamV1(outFileName, getConverter().getProgressMonitor(), - getConverter().getProgressMonitorStage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } else { - // convert to BAM v2 - DxtEncoder.DxtType dxtType = getConverter().getDxtType(); - int pvrzIndex = getConverter().getPvrzIndex(); - try { - return decoder.exportBamV2(outFileName, dxtType, pvrzIndex, getConverter().getProgressMonitor(), - getConverter().getProgressMonitorStage()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - } - return false; - } } diff --git a/src/org/infinity/gui/converter/BamFilterTransformCenter.java b/src/org/infinity/gui/converter/BamFilterTransformCenter.java index c08217da8..d661fc777 100644 --- a/src/org/infinity/gui/converter/BamFilterTransformCenter.java +++ b/src/org/infinity/gui/converter/BamFilterTransformCenter.java @@ -62,15 +62,13 @@ public PseudoBamFrameEntry process(PseudoBamFrameEntry frame) throws Exception { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(spinnerLeft.getValue()).append(';'); - sb.append(spinnerTop.getValue()).append(';'); - sb.append(spinnerRight.getValue()).append(';'); - sb.append(spinnerBottom.getValue()).append(';'); - sb.append(cbAdjustCenter.isSelected()).append(';'); - sb.append(spinnerCenterX.getValue()).append(';'); - sb.append(spinnerCenterY.getValue()); - return sb.toString(); + return String.valueOf(spinnerLeft.getValue()) + ';' + + spinnerTop.getValue() + ';' + + spinnerRight.getValue() + ';' + + spinnerBottom.getValue() + ';' + + cbAdjustCenter.isSelected() + ';' + + spinnerCenterX.getValue() + ';' + + spinnerCenterY.getValue(); } @Override @@ -79,12 +77,12 @@ public boolean setConfiguration(String config) { config = config.trim(); if (!config.isEmpty()) { String[] params = config.split(";"); - Integer left = Integer.MIN_VALUE; - Integer top = Integer.MIN_VALUE; - Integer right = Integer.MIN_VALUE; - Integer bottom = Integer.MIN_VALUE; - Integer cx = Integer.MIN_VALUE; - Integer cy = Integer.MIN_VALUE; + int left = Integer.MIN_VALUE; + int top = Integer.MIN_VALUE; + int right = Integer.MIN_VALUE; + int bottom = Integer.MIN_VALUE; + int cx = Integer.MIN_VALUE; + int cy = Integer.MIN_VALUE; boolean a = true; if (params.length > 0) { @@ -177,7 +175,7 @@ public boolean setConfiguration(String config) { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry frame) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry frame) { return applyEffect(frame); } @@ -325,7 +323,7 @@ public static Rectangle getMaxRectangle(PseudoBamDecoder decoder) { /** Returns a frame padded according to the specified rectangle parameter. */ public static BufferedImage padFrame(PseudoBamFrameEntry entry, Rectangle canvasRect) { BufferedImage dstImage = entry.getFrame(); - if (entry != null && canvasRect != null && !canvasRect.isEmpty()) { + if (canvasRect != null && !canvasRect.isEmpty()) { byte[] srcB = null, dstB = null; int[] srcI = null, dstI = null; int transIndex = 0; diff --git a/src/org/infinity/gui/converter/BamFilterTransformMirror.java b/src/org/infinity/gui/converter/BamFilterTransformMirror.java index 5de6f5b35..3bca692fd 100644 --- a/src/org/infinity/gui/converter/BamFilterTransformMirror.java +++ b/src/org/infinity/gui/converter/BamFilterTransformMirror.java @@ -49,17 +49,15 @@ public PseudoBamFrameEntry process(PseudoBamFrameEntry entry) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { return applyEffect(entry); } @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(cbHorizontal.isSelected()).append(';'); - sb.append(cbVertical.isSelected()).append(';'); - sb.append(cbAdjustCenter.isSelected()); - return sb.toString(); + return String.valueOf(cbHorizontal.isSelected()) + ';' + + cbVertical.isSelected() + ';' + + cbAdjustCenter.isSelected(); } @Override diff --git a/src/org/infinity/gui/converter/BamFilterTransformResize.java b/src/org/infinity/gui/converter/BamFilterTransformResize.java index 9b070b8d9..09dfc46bc 100644 --- a/src/org/infinity/gui/converter/BamFilterTransformResize.java +++ b/src/org/infinity/gui/converter/BamFilterTransformResize.java @@ -98,7 +98,7 @@ public PseudoBamFrameEntry process(PseudoBamFrameEntry entry) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { return applyEffect(entry); } @@ -109,14 +109,12 @@ public void updateControls() { @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(cbType.getSelectedIndex()).append(';'); - sb.append(rbScaleBoth.isSelected() ? 0 : 1).append(';'); - sb.append(((SpinnerNumberModel) spinnerFactor.getModel()).getNumber().doubleValue()).append(';'); - sb.append(((SpinnerNumberModel) spinnerFactorX.getModel()).getNumber().doubleValue()).append(';'); - sb.append(((SpinnerNumberModel) spinnerFactorY.getModel()).getNumber().doubleValue()).append(';'); - sb.append(cbAdjustCenter.isSelected()); - return sb.toString(); + return String.valueOf(cbType.getSelectedIndex()) + ';' + + (rbScaleBoth.isSelected() ? 0 : 1) + ';' + + ((SpinnerNumberModel) spinnerFactor.getModel()).getNumber().doubleValue() + ';' + + ((SpinnerNumberModel) spinnerFactorX.getModel()).getNumber().doubleValue() + ';' + + ((SpinnerNumberModel) spinnerFactorY.getModel()).getNumber().doubleValue() + ';' + + cbAdjustCenter.isSelected(); } @Override @@ -126,9 +124,9 @@ public boolean setConfiguration(String config) { if (!config.isEmpty()) { String[] params = config.split(";"); int type = -1; - Double factor = Double.MIN_VALUE; - Double factorX = Double.MIN_VALUE; - Double factorY = Double.MIN_VALUE; + double factor = Double.MIN_VALUE; + double factorX = Double.MIN_VALUE; + double factorY = Double.MIN_VALUE; boolean uniformSelected = true; boolean adjust = true; @@ -438,15 +436,15 @@ private void setFactor(JSpinner spinner, Number current, Number min, Number max, int curI = 0, minI = 0, maxI = 0, stepI = 0; double curD = 0, minD = 0, maxD = 0, stepD = 0; if (isDouble) { - curD = ((Double) current); - minD = ((Double) min); - maxD = ((Double) max); - stepD = ((Double) step); + curD = current.doubleValue(); + minD = min.doubleValue(); + maxD = max.doubleValue(); + stepD = step.doubleValue(); } else { - curI = ((Integer) current); - minI = ((Integer) min); - maxI = ((Integer) max); - stepI = ((Integer) step); + curI = current.intValue(); + minI = min.intValue(); + maxI = max.intValue(); + stepI = step.intValue(); } if (isDouble) { if (snm.getValue() instanceof Integer) { @@ -461,9 +459,9 @@ private void setFactor(JSpinner spinner, Number current, Number min, Number max, } else { if (snm.getValue() instanceof Double) { curI = Math.max(Math.min(curI, maxI), minI); - spinner.setModel(new SpinnerNumberModel(curI, minI, (maxI < 10) ? 10 : maxI, stepI)); + spinner.setModel(new SpinnerNumberModel(curI, minI, Math.max(maxI, 10), stepI)); if (maxI < 10) { - ((SpinnerNumberModel) spinner.getModel()).setMaximum(Integer.valueOf(maxI)); + ((SpinnerNumberModel) spinner.getModel()).setMaximum(maxI); } } else { snm.setMinimum(minI); diff --git a/src/org/infinity/gui/converter/BamFilterTransformRotate.java b/src/org/infinity/gui/converter/BamFilterTransformRotate.java index 888ed1cbd..079b05882 100644 --- a/src/org/infinity/gui/converter/BamFilterTransformRotate.java +++ b/src/org/infinity/gui/converter/BamFilterTransformRotate.java @@ -14,6 +14,7 @@ import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.IndexColorModel; +import java.util.Objects; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; @@ -34,9 +35,9 @@ public class BamFilterTransformRotate extends BamFilterBaseTransform implements private static final String FILTER_DESC = "This filter allows you to rotate each BAM frame by a specified amount."; private enum Angle { - Angle90("90\u00B0"), - Angle180("180\u00B0"), - Angle270("270\u00B0"), + Angle90("90°"), + Angle180("180°"), + Angle270("270°"), ; private final String label; @@ -78,17 +79,15 @@ public PseudoBamFrameEntry process(PseudoBamFrameEntry entry) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { return applyEffect(entry); } @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(rbCW.isSelected() ? 0 : 1).append(';'); - sb.append(cbAngle.getSelectedIndex()).append(';'); - sb.append(cbAdjustCenter.isSelected()); - return sb.toString(); + return String.valueOf(rbCW.isSelected() ? 0 : 1) + ';' + + cbAngle.getSelectedIndex() + ';' + + cbAdjustCenter.isSelected(); } @Override @@ -207,7 +206,7 @@ private PseudoBamFrameEntry applyEffect(PseudoBamFrameEntry entry) { int height = entry.getFrame().getHeight(); BufferedImage dstImage = null; int newWidth, newHeight; - switch ((Angle) cbAngle.getSelectedItem()) { + switch ((Angle) Objects.requireNonNull(cbAngle.getSelectedItem())) { case Angle90: case Angle270: newWidth = height; diff --git a/src/org/infinity/gui/converter/BamFilterTransformTrim.java b/src/org/infinity/gui/converter/BamFilterTransformTrim.java index 1f1d234ea..e9a6a2143 100644 --- a/src/org/infinity/gui/converter/BamFilterTransformTrim.java +++ b/src/org/infinity/gui/converter/BamFilterTransformTrim.java @@ -81,20 +81,18 @@ public PseudoBamFrameEntry process(PseudoBamFrameEntry entry) throws Exception { } @Override - public PseudoBamFrameEntry updatePreview(PseudoBamFrameEntry entry) { + public PseudoBamFrameEntry updatePreview(int frameIndex, PseudoBamFrameEntry entry) { return applyEffect(entry); } @Override public String getConfiguration() { - StringBuilder sb = new StringBuilder(); - sb.append(cbEdges.get(Edge.Top).isSelected()).append(';'); - sb.append(cbEdges.get(Edge.Left).isSelected()).append(';'); - sb.append(cbEdges.get(Edge.Bottom).isSelected()).append(';'); - sb.append(cbEdges.get(Edge.Right).isSelected()).append(';'); - sb.append(((SpinnerNumberModel) spinnerMargin.getModel()).getNumber().intValue()).append(';'); - sb.append(cbAdjustCenter.isSelected()); - return sb.toString(); + return String.valueOf(cbEdges.get(Edge.Top).isSelected()) + ';' + + cbEdges.get(Edge.Left).isSelected() + ';' + + cbEdges.get(Edge.Bottom).isSelected() + ';' + + cbEdges.get(Edge.Right).isSelected() + ';' + + ((SpinnerNumberModel) spinnerMargin.getModel()).getNumber().intValue() + ';' + + cbAdjustCenter.isSelected(); } @Override @@ -104,7 +102,7 @@ public boolean setConfiguration(String config) { if (!config.isEmpty()) { String[] params = config.split(";"); boolean t = true, l = true, b = true, r = true; - Integer margin = Integer.MIN_VALUE; + int margin = Integer.MIN_VALUE; boolean a = true; if (params.length > 0) { @@ -310,8 +308,10 @@ private PseudoBamFrameEntry applyEffect(PseudoBamFrameEntry entry) { // calculating the properties of the resulting image int left = 0, right = width - 1, top = 0, bottom = height - 1; - boolean edgeLeft = !cbEdges.get(Edge.Left).isSelected(), edgeRight = !cbEdges.get(Edge.Right).isSelected(), - edgeTop = !cbEdges.get(Edge.Top).isSelected(), edgeBottom = !cbEdges.get(Edge.Bottom).isSelected(); + boolean edgeLeft = !cbEdges.get(Edge.Left).isSelected(); + boolean edgeRight = !cbEdges.get(Edge.Right).isSelected(); + boolean edgeTop = !cbEdges.get(Edge.Top).isSelected(); + boolean edgeBottom = !cbEdges.get(Edge.Bottom).isSelected(); while ((left < right || top < bottom) && (!edgeLeft || !edgeRight || !edgeTop || !edgeBottom)) { int ofs, step; // checking top edge @@ -404,6 +404,14 @@ private PseudoBamFrameEntry applyEffect(PseudoBamFrameEntry entry) { } } + // preventing empty frames + if (right < left) { + left = right = 0; + } + if (bottom < top) { + top = bottom = 0; + } + // creating new image int margin = ((Integer) spinnerMargin.getValue()); int dstX = 0; diff --git a/src/org/infinity/gui/converter/BamOptionsDialog.java b/src/org/infinity/gui/converter/BamOptionsDialog.java index fc6182169..ed5eccfc2 100644 --- a/src/org/infinity/gui/converter/BamOptionsDialog.java +++ b/src/org/infinity/gui/converter/BamOptionsDialog.java @@ -21,6 +21,7 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.prefs.Preferences; import javax.swing.AbstractAction; @@ -44,6 +45,7 @@ import org.infinity.gui.ViewerUtil; import org.infinity.resource.Profile; import org.infinity.resource.graphics.ColorConvert; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -77,6 +79,7 @@ class BamOptionsDialog extends JDialog implements ActionListener, FocusListener, private static final int DEFAULT_RECENT_SESSIONS_MAX = 10; // Current settings + private static final List recentSessions = new ArrayList<>(); private static boolean settingsLoaded = false; private static int bamVersion = DEFAULT_BAM_VERSION; private static String path = DEFAULT_PATH; @@ -88,7 +91,6 @@ class BamOptionsDialog extends JDialog implements ActionListener, FocusListener, private static boolean compressBam = DEFAULT_COMPRESS_BAM; private static int compressionType = DEFAULT_COMPRESSION_TYPE; private static int pvrzIndex = DEFAULT_PVRZ_INDEX; - private static List recentSessions = new ArrayList<>(); private final ConvertToBam converter; @@ -254,7 +256,7 @@ public static void updateRecentSession(Path session) { if (session != null) { try { session = session.toAbsolutePath(); - for (int idx = 0; idx < recentSessions.size(); idx++) { + for (int idx = recentSessions.size() - 1; idx >= 0; idx--) { if (recentSessions.get(idx).equals(session)) { recentSessions.remove(idx); } @@ -264,7 +266,7 @@ public static void updateRecentSession(Path session) { } recentSessions.add(0, session); } catch (IOError e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -557,12 +559,12 @@ private void setDefaults() { tfPath.setText(DEFAULT_PATH); cbAutoClear.setSelected(DEFAULT_AUTO_CLEAR); cbCloseOnExit.setSelected(DEFAULT_CLOSE_ON_EXIT); - sTransparency.setValue(Integer.valueOf(DEFAULT_TRANSPARENCY_THRESHOLD)); + sTransparency.setValue(DEFAULT_TRANSPARENCY_THRESHOLD); cbUseAlpha.setSelectedIndex(DEFAULT_USE_ALPHA); cbSortPalette.setSelectedItem(DEFAULT_SORT_PALETTE); cbCompressBam.setSelected(DEFAULT_COMPRESS_BAM); cbCompressionType.setSelectedIndex(DEFAULT_COMPRESSION_TYPE); - sPvrzIndex.setValue(Integer.valueOf(DEFAULT_PVRZ_INDEX)); + sPvrzIndex.setValue(DEFAULT_PVRZ_INDEX); } // Fetches the values from the dialog controls @@ -573,7 +575,7 @@ private void updateSettings() { closeOnExit = cbCloseOnExit.isSelected(); transparencyThreshold = (Integer) sTransparency.getValue(); useAlpha = cbUseAlpha.getSelectedIndex(); - sortPalette = cbSortPalette.getSelectedItem().toString(); + sortPalette = Objects.requireNonNull(cbSortPalette.getSelectedItem()).toString(); compressBam = cbCompressBam.isSelected(); compressionType = cbCompressionType.getSelectedIndex(); pvrzIndex = (Integer) sPvrzIndex.getValue(); diff --git a/src/org/infinity/gui/converter/BamPaletteDialog.java b/src/org/infinity/gui/converter/BamPaletteDialog.java index f0862a092..219cc8e38 100644 --- a/src/org/infinity/gui/converter/BamPaletteDialog.java +++ b/src/org/infinity/gui/converter/BamPaletteDialog.java @@ -21,12 +21,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import javax.swing.AbstractAction; @@ -59,7 +54,7 @@ /** * A dialog for managing BAM v1 palette entries. */ -class BamPaletteDialog extends JDialog +public class BamPaletteDialog extends JDialog implements FocusListener, ActionListener, ChangeListener, ColorGrid.MouseOverListener { /** Specifies generated palette type */ public static final int TYPE_GENERATED = 0; @@ -224,9 +219,7 @@ public void setPalette(int type, int[] palette) { if (!isPaletteLocked() || type == TYPE_EXTERNAL) { if (palette != null) { // loading palette data - for (int i = 0; i < palette.length; i++) { - palettes[type][i] = palette[i]; - } + System.arraycopy(palette, 0, palettes[type], 0, palette.length); for (int i = palette.length; i < palettes[type].length; i++) { palettes[type][i] = 0; } @@ -262,7 +255,7 @@ public void loadExternalPalette(int type, Path paletteFile) throws Exception { } // fetching palette data - int[] palette = null; + final int[] palette; if ("BM".equals(new String(signature, 0, 2))) { palette = ColorConvert.loadPaletteBMP(paletteFile); } else if (Arrays.equals(Arrays.copyOfRange(signature, 0, 4), new byte[] { (byte) 0x89, 0x50, 0x4e, 0x47 })) { @@ -281,7 +274,7 @@ public void loadExternalPalette(int type, Path paletteFile) throws Exception { } // applying palette - if (palette != null && palette.length > 0) { + if (palette.length > 0) { System.arraycopy(palette, 0, palettes[type], 0, palette.length); for (int i = palette.length; i < palettes[type].length; i++) { palettes[type][i] = 0xff000000; @@ -351,7 +344,7 @@ public void updateGeneratedPalette() { if (sharedPalette) { // using shared palette as is - System.arraycopy(palette, 0, palettes[TYPE_GENERATED], 0, palette.length); + System.arraycopy(Objects.requireNonNull(palette), 0, palettes[TYPE_GENERATED], 0, palette.length); } else { // creating palette directly from color map without reduction Iterator iter = colorMap.keySet().iterator(); diff --git a/src/org/infinity/gui/converter/ConvertToBam.java b/src/org/infinity/gui/converter/ConvertToBam.java index c5514648f..1b448d6a5 100644 --- a/src/org/infinity/gui/converter/ConvertToBam.java +++ b/src/org/infinity/gui/converter/ConvertToBam.java @@ -50,6 +50,7 @@ import java.util.IllegalFormatException; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Vector; import java.util.function.Consumer; @@ -121,6 +122,7 @@ import org.infinity.util.IniMap; import org.infinity.util.IniMapEntry; import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.SimpleListModel; import org.infinity.util.io.FileEx; @@ -310,6 +312,7 @@ public static int numberValidator(String numberString, int min, int max, int def retVal = max; } } catch (NumberFormatException e) { + Logger.trace(e); } } return retVal; @@ -332,6 +335,7 @@ public static double doubleValidator(String numberString, double min, double max retVal = max; } } catch (NumberFormatException e) { + Logger.trace(e); } } return retVal; @@ -339,28 +343,26 @@ public static double doubleValidator(String numberString, double min, double max /** Returns a list of supported input graphics file formats. */ public static FileNameExtensionFilter[] getGraphicsFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { - new FileNameExtensionFilter("Graphics files (*.bam, *.bmp, *.gif, *.png, *,jpg, *.jpeg)", "bam", "bmp", "gif", - "png", "jpg", "jpeg"), + return new FileNameExtensionFilter[] { + new FileNameExtensionFilter("Graphics files (*.bam, *.bmp, *.gif, *.png, *,jpg, *.jpeg)", + "bam", "bmp", "gif", "png", "jpg", "jpeg"), new FileNameExtensionFilter("BAM files (*.bam)", "bam"), new FileNameExtensionFilter("BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("GIF files (*.gif)", "gif"), new FileNameExtensionFilter("PNG files (*.png)", "png"), new FileNameExtensionFilter("JPEG files (*.jpg, *.jpeg)", "jpg", "jpeg") }; - return filters; } /** Returns a list of supported input file formats containing palettes. */ public static FileNameExtensionFilter[] getPaletteFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { - new FileNameExtensionFilter("Palette from files (*.bam, *.bmp, *.png, *.act, *.pal)", "bam", "bmp", "png", - "act", "pal"), + return new FileNameExtensionFilter[] { + new FileNameExtensionFilter("Palette from files (*.bam, *.bmp, *.png, *.act, *.pal)", + "bam", "bmp", "png", "act", "pal"), new FileNameExtensionFilter("Palette from BAM files (*.bam)", "bam"), new FileNameExtensionFilter("Palette from BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("Palette from PNG files (*.png)", "png"), new FileNameExtensionFilter("Adobe Color Table files (*.act)", "act"), new FileNameExtensionFilter("Microsoft Palette files (*.pal)", "pal"), }; - return filters; } /** Returns a extension filter for BAM files. */ @@ -793,7 +795,7 @@ public void propertyChange(PropertyChangeEvent event) { try { result = workerConvert.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } workerConvert = null; @@ -2081,7 +2083,7 @@ private void updateFrameInfo(int[] indices) { tfFrameHeight.setText(changedHeight ? "" : Integer.toString(initialHeight)); tfFrameCenterX.setText(changedCenterX ? "" : Integer.toString(initialX)); tfFrameCenterY.setText(changedCenterY ? "" : Integer.toString(initialY)); - cbCompressFrame.setSelected(changedCompression ? false : initialState); + cbCompressFrame.setSelected(!changedCompression && initialState); } else { // no frame selected final String zero = "0"; @@ -2232,7 +2234,7 @@ private void updateCyclesAddedFrames(int[] indices) { Arrays.sort(indices); for (final int index : indices) { for (int i = 0; i < modelCycles.getSize(); i++) { - PseudoBamCycleEntry cycle = modelCycles.getElementAt(i); + PseudoBamCycleEntry cycle = Objects.requireNonNull(modelCycles.getElementAt(i)); for (int j = 0; j < cycle.size(); j++) { int idx = cycle.get(j); if (idx >= index) { @@ -2252,7 +2254,7 @@ private void updateCyclesRemovedFrames(int[] indices) { for (int x = indices.length - 1; x >= 0; x--) { int index = indices[x]; for (int i = 0; i < modelCycles.getSize(); i++) { - PseudoBamCycleEntry cycle = modelCycles.getElementAt(i); + PseudoBamCycleEntry cycle = Objects.requireNonNull(modelCycles.getElementAt(i)); int j = 0; while (j < cycle.size()) { int idx = cycle.get(j); @@ -2274,7 +2276,7 @@ private void updateCyclesRemovedFrames(int[] indices) { private void updateCyclesMovedFrames(int index, int shift) { if (index >= 0 && shift != 0) { for (int i = 0; i < modelCycles.getSize(); i++) { - PseudoBamCycleEntry cycle = modelCycles.getElementAt(i); + PseudoBamCycleEntry cycle = Objects.requireNonNull(modelCycles.getElementAt(i)); for (int j = 0; j < cycle.size(); j++) { if (cycle.get(j) == index) { cycle.set(j, cycle.get(j) + shift); @@ -2496,7 +2498,7 @@ public BamDecoder framesAddBam(int listIndex, Path file) { public BamDecoder framesAddBam(int listIndex, ResourceEntry entry) { if (listIndex >= 0 && entry != null && BamDecoder.isValid(entry)) { BamDecoder decoder = BamDecoder.loadBam(entry); - BamDecoder.BamControl control = decoder.createControl(); + BamDecoder.BamControl control = Objects.requireNonNull(decoder).createControl(); control.setMode(BamDecoder.BamControl.Mode.INDIVIDUAL); // preparing palette-specific properties @@ -2569,10 +2571,10 @@ private int framesAddBamFrame(int listIndex, BamDecoder decoder, BamDecoder.BamC } else { fe2.setOption(BAM_FRAME_OPTION_PATH, BAM_FRAME_PATH_BIFF + entry.getResourceName()); } - fe2.setOption(BAM_FRAME_OPTION_SOURCE_INDEX, Integer.valueOf(frameIndex)); + fe2.setOption(BAM_FRAME_OPTION_SOURCE_INDEX, frameIndex); fe2.setOption(PseudoBamDecoder.OPTION_STRING_LABEL, entry.getResourceName() + ":" + frameIndex); - fe2.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, Boolean.valueOf(isCompressed)); - fe2.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, Integer.valueOf(rleIndex)); + fe2.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, isCompressed); + fe2.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, rleIndex); return listIndex; } return -1; @@ -2674,7 +2676,7 @@ private boolean framesAddImage(int listIndex, ResourceEntry entry, int frameInde image = dstImage; } - // Workaround for BAMV1 transparency, see PseudoBamDecoder.OPTION_BOOL_TRANSPARENTGREENFORCED + // Workaround for BAM V1 transparency, see PseudoBamDecoder.OPTION_BOOL_TRANSPARENTGREENFORCED final boolean forceTransparentGreen = image.getType() != BufferedImage.TYPE_BYTE_INDEXED; modelFrames.insert(listIndex + curFrameIdx, image, new Point(), forceTransparentGreen); // setting required extra options @@ -2684,7 +2686,7 @@ private boolean framesAddImage(int listIndex, ResourceEntry entry, int frameInde } else { fe2.setOption(BAM_FRAME_OPTION_PATH, BAM_FRAME_PATH_BIFF + entry.getResourceName()); } - fe2.setOption(BAM_FRAME_OPTION_SOURCE_INDEX, Integer.valueOf(frameIdx)); + fe2.setOption(BAM_FRAME_OPTION_SOURCE_INDEX, frameIdx); if (images.length > 1) { fe2.setOption(PseudoBamDecoder.OPTION_STRING_LABEL, entry.getResourceName() + ":" + frameIdx); } else { @@ -2694,7 +2696,7 @@ private boolean framesAddImage(int listIndex, ResourceEntry entry, int frameInde } } catch (Exception e) { retVal = false; - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -2803,14 +2805,14 @@ public void framesAddFolder(Path path, int insertIndex) { } } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); return; } // adding entries to frames list try { WindowBlocker.blockWindow(this, true); - framesAdd(validFiles.toArray(new Path[validFiles.size()]), insertIndex); + framesAdd(validFiles.toArray(new Path[0]), insertIndex); } finally { WindowBlocker.blockWindow(this, false); } @@ -2914,7 +2916,7 @@ private int framesGetUnusedFramesCount(BitSet framesUsed) { private BitSet framesGetUnusedFrames() { BitSet framesUsed = new BitSet(modelFrames.getSize()); for (int i = 0; i < modelCycles.getSize(); i++) { - PseudoBamCycleEntry cycle = modelCycles.getElementAt(i); + PseudoBamCycleEntry cycle = Objects.requireNonNull(modelCycles.getElementAt(i)); for (int j = 0; j < cycle.size(); j++) { int idx = cycle.get(j); if (idx >= 0) { @@ -3317,10 +3319,11 @@ private void previewSetMode(int mode) { /** Sets a new frame rate. */ private void previewSetFrameRate(double fps) { try { - sPreviewFps.setValue(Double.valueOf(fps)); + sPreviewFps.setValue(fps); currentFps = (Double) sPreviewFps.getValue(); timer.setDelay((int) (1000.0 / currentFps)); } catch (IllegalArgumentException e) { + Logger.trace(e); } } @@ -3425,7 +3428,7 @@ private void previewPrepare(boolean update) { try { updateFilteredBamDecoder(getBamVersion(), false); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -3649,12 +3652,12 @@ private void filterUpdatePreviewFrameIndex() { int max = ((Integer) model.getMaximum()); int cur = ((Integer) model.getValue()); if (max != listFrameEntries.get(BAM_ORIGINAL).size()) { - max = listFrameEntries.get(BAM_ORIGINAL).size(); + max = listFrameEntries.get(BAM_ORIGINAL).size() - 1; if (cur >= max) { cur = Math.max(max - 1, 0); } - model.setMaximum(Integer.valueOf(max)); - model.setValue(Integer.valueOf(cur)); + model.setMaximum(max); + model.setValue(cur); } } @@ -3765,6 +3768,7 @@ private void doWithSelectedListItems(JList list, Consumer> opera try { message = String.format(fmt, selectedCount); } catch (IllegalFormatException e) { + Logger.trace(e); } } @@ -3921,7 +3925,7 @@ private List convert() { try { updateFilteredBamDecoder(getBamVersion(), false); List outList = createOutputFilterList(); - if (outList != null && !outList.isEmpty()) { + if (!outList.isEmpty()) { for (BamFilterBaseOutput element : outList) { // processing output filter if (!element.process(bamDecoderFinal)) { @@ -3933,7 +3937,7 @@ private List convert() { } result.add("Conversion finished successfully."); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add(String.format("Error while exporting BAM files.\n(%s)", e.getMessage())); } @@ -3963,7 +3967,7 @@ private PseudoBamFrameEntry getFilteredBamFrame(int bamVersion, int frameIdx, bo for (int i = 0; i < curFilterIdx; i++) { if (modelFilters.get(i) != null) { BamFilterBase filter = modelFilters.get(i); - entry = filter.updatePreview(entry); + entry = filter.updatePreview(frameIdx, entry); } } entryFilterPreview.setFrame(entry.getFrame()); @@ -3978,7 +3982,7 @@ private PseudoBamFrameEntry getFilteredBamFrame(int bamVersion, int frameIdx, bo entryFilterPreview.getCenterX(), entryFilterPreview.getCenterY()); BamFilterBase filter = modelFilters.get(curFilterIdx); if (filter != null) { - entry = filter.updatePreview(entry); + entry = filter.updatePreview(frameIdx, entry); } } @@ -4009,7 +4013,7 @@ private void updateFilteredBamDecoder(int bamVersion, boolean force) throws Exce } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw e; } } else if (filter instanceof BamFilterBaseTransform) { @@ -4028,16 +4032,16 @@ private void updateFilteredBamDecoder(int bamVersion, boolean force) throws Exce } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw e; } } else if (filter instanceof BamFilterBaseOutput) { // skipping output filter } else { if (filter != null) { - System.err.println(String.format("Skipping unrecognized filter: %s", filter)); + Logger.warn("Skipping unrecognized filter: {}", filter); } else { - System.err.println("Skipping null filter"); + Logger.warn("Skipping null filter"); } } } @@ -4061,9 +4065,7 @@ private List createFilterList(boolean includeOutputFilters) { if (outFilters.isEmpty()) { outFilters.add(BamFilterFactory.createInstance(this, BamFilterOutputDefault.class)); } - for (int i = 0; i < outFilters.size(); i++) { - retVal.add(outFilters.get(i)); - } + retVal.addAll(outFilters); } return retVal; @@ -4105,8 +4107,8 @@ private void updateFinalBamDecoder(int bamVersion) throws Exception { paletteDialog.updateGeneratedPalette(); final int Green = 0x0000ff00; - bamDecoderFinal.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, Integer.valueOf(paletteDialog.getRleIndex())); - bamDecoderFinal.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, Boolean.valueOf(isBamV1Compressed())); + bamDecoderFinal.setOption(PseudoBamDecoder.OPTION_INT_RLEINDEX, paletteDialog.getRleIndex()); + bamDecoderFinal.setOption(PseudoBamDecoder.OPTION_BOOL_COMPRESSED, isBamV1Compressed()); // preparing palette int[] palette = paletteDialog.getPalette(paletteDialog.getPaletteType()); int threshold = getUseAlpha() ? -1 : getTransparencyThreshold(); @@ -4143,7 +4145,7 @@ private void updateFinalBamDecoder(int bamVersion) throws Exception { if (PseudoBamDecoder.isTransparentColor(c, threshold)) { dstBuf[ofs] = (byte) transIndex; } else { - Byte colIdx = colorCache.get(Integer.valueOf(c)); + Byte colIdx = colorCache.get(c); if (colIdx != null) { dstBuf[ofs] = colIdx; } else { @@ -4170,8 +4172,7 @@ private void updateFinalBamDecoder(int bamVersion) throws Exception { } } else { // BAM v2: create truecolored version of each frame - for (int i = 0; i < srcListFrames.size(); i++) { - PseudoBamFrameEntry srcEntry = srcListFrames.get(i); + for (PseudoBamFrameEntry srcEntry : srcListFrames) { BufferedImage dstImage = ColorConvert.toBufferedImage(srcEntry.getFrame(), true, true); PseudoBamFrameEntry dstEntry = new PseudoBamFrameEntry(dstImage, srcEntry.getCenterX(), srcEntry.getCenterY()); @@ -4232,7 +4233,7 @@ private void updateFinalBamFrame(int bamVersion, int frameIdx) { if (PseudoBamDecoder.isTransparentColor(c, threshold)) { dstBuf[ofs] = (byte) transIndex; } else { - Byte colIdx = colorCache.get(Integer.valueOf(c)); + Byte colIdx = colorCache.get(c); if (colIdx != null) { int ci = colIdx.intValue() & 0xff; if (ci >= transIndex) { @@ -4439,6 +4440,7 @@ public boolean importData(TransferSupport support) { return retVal; } catch (Exception e) { + Logger.trace(e); } } @@ -5129,7 +5131,7 @@ public boolean importData(Path session, boolean silent) { /** Loads data from the specified file without user-interaction and optionally without feedback. */ private boolean loadData(Path inFile, boolean silent) { if (inFile != null) { - IniMap ini = new IniMap(new FileResourceEntry(inFile)); + IniMap ini = new IniMap(new FileResourceEntry(inFile), true); try { // checking integrity @@ -5197,7 +5199,7 @@ private boolean loadFrameData(IniMapSection frames) throws Exception { } if (value.startsWith(BAM_FRAME_PATH_BIFF)) { - String resName = value.substring(BAM_FRAME_PATH_BIFF.length(), value.length()); + String resName = value.substring(BAM_FRAME_PATH_BIFF.length()); if (!ResourceFactory.resourceExists(resName)) { throw new Exception("Frame source path not found at line " + (entry.getLine() + 1)); } @@ -5437,7 +5439,7 @@ private boolean applyCenterData(boolean silent) throws Exception { int x = Misc.toNumber(numbers[0].trim(), Integer.MIN_VALUE); int y = Misc.toNumber(numbers[1].trim(), Integer.MIN_VALUE); if (x != Integer.MIN_VALUE && y != Integer.MIN_VALUE) { - PseudoBamFrameEntry bfe = bam.modelFrames.getElementAt(listIndex); + PseudoBamFrameEntry bfe = Objects.requireNonNull(bam.modelFrames.getElementAt(listIndex)); bfe.setCenterX(x); bfe.setCenterY(y); } @@ -5533,7 +5535,7 @@ public Config() { maxIndex = Math.max(maxIndex, idx); } } else if (key.startsWith(KEY_FILTER_CONFIG)) { - final Integer idx = Misc.toNumber(key.substring(KEY_FILTER_CONFIG.length()), -1); + final int idx = Misc.toNumber(key.substring(KEY_FILTER_CONFIG.length()), -1); if (idx >= 0) { String param = entry.getValue().trim(); Config config = filterMap.get(idx); @@ -5657,7 +5659,7 @@ private boolean saveData(Path outFile, boolean silent) { } retVal = true; } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); if (!silent) { JOptionPane.showMessageDialog(bam, "Error exporting BAM session.", "Error", JOptionPane.ERROR_MESSAGE); } diff --git a/src/org/infinity/gui/converter/ConvertToBmp.java b/src/org/infinity/gui/converter/ConvertToBmp.java index 20a24a3a1..da249156e 100644 --- a/src/org/infinity/gui/converter/ConvertToBmp.java +++ b/src/org/infinity/gui/converter/ConvertToBmp.java @@ -54,6 +54,7 @@ import org.infinity.icon.Icons; import org.infinity.resource.Profile; import org.infinity.resource.graphics.ColorConvert; +import org.infinity.util.Logger; import org.infinity.util.SimpleListModel; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -81,12 +82,11 @@ public class ConvertToBmp extends ChildFrame implements ActionListener, FocusLis // Returns a list of supported graphics file formats private static FileNameExtensionFilter[] getGraphicsFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { + return new FileNameExtensionFilter[] { new FileNameExtensionFilter("Graphics files (*.bmp, *.png, *,jpg, *.jpeg)", "bmp", "png", "jpg", "jpeg"), new FileNameExtensionFilter("BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("PNG files (*.png)", "png"), new FileNameExtensionFilter("JPEG files (*.jpg, *.jpeg)", "jpg", "jpeg") }; - return filters; } // returns a selection of files @@ -221,7 +221,7 @@ public void propertyChange(PropertyChangeEvent event) { try { sl = workerConvert.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } workerConvert = null; @@ -443,13 +443,13 @@ private void updateStatus() { private boolean isValidInput(Path file) { boolean result = false; if (file != null) { - try (ImageInputStream iis = ImageIO.createImageInputStream(file.toFile())) { + try (final ImageInputStream iis = ImageIO.createImageInputStream(file.toFile())) { final Iterator readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { result = true; } - iis.close(); } catch (Exception e) { + Logger.trace(e); } } return result; @@ -522,7 +522,7 @@ private void inputAddFolder() { } catch (IOException e) { JOptionPane.showMessageDialog(this, "Unable to read files from the specified folder.", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return; } listInputFiles.setSelectedIndex(idx - 1); @@ -549,7 +549,7 @@ private void inputAddFolder() { private void inputRemove() { int curIdx = Integer.MAX_VALUE; - int indices[] = listInputFiles.getSelectedIndices(); + int[] indices = listInputFiles.getSelectedIndices(); if (indices != null && indices.length > 0) { for (int i = indices.length - 1; i >= 0; i--) { modelInputFiles.remove(indices[i]); @@ -634,7 +634,6 @@ private List convert() { img = ImageIO.read(inFile.toFile()); } catch (Exception e) { failed++; - img = null; } // 2. write BMP output @@ -753,7 +752,7 @@ private boolean writeBMP(Image srcImage, Path file, boolean hasAlpha) { if (!hasAlpha && (pixels[idx] >>> 24) < transThreshold) { pixels[idx] = 0x00ff00; // transparent pixels are translated into RGB(0, 255, 0) } - row[i + 0] = (byte) (pixels[idx] & 0xff); + row[i] = (byte) (pixels[idx] & 0xff); row[i + 1] = (byte) ((pixels[idx] >>> 8) & 0xff); row[i + 2] = (byte) ((pixels[idx] >>> 16) & 0xff); if (hasAlpha) { @@ -768,7 +767,7 @@ private boolean writeBMP(Image srcImage, Path file, boolean hasAlpha) { } return true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return false; diff --git a/src/org/infinity/gui/converter/ConvertToMos.java b/src/org/infinity/gui/converter/ConvertToMos.java index 921b9e900..4c63cc903 100644 --- a/src/org/infinity/gui/converter/ConvertToMos.java +++ b/src/org/infinity/gui/converter/ConvertToMos.java @@ -60,6 +60,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -94,7 +95,6 @@ public class ConvertToMos extends ChildFrame * @param img The source image to convert into a MOS resource. * @param mosFileName The name of the resulting MOS file. * @param compressed If {@code true}, converts into a compressed BAMC file. - * @param fastConvert If {@code true}, uses a fast but less accurate color reduction algorith. * @param result Returns more specific information about the conversion process. Data placed in the first item * indicates success, data in the second item indicates failure. * @param showProgress Specify whether to show a progress monitor (needs a valid 'parent' parameter). @@ -189,7 +189,7 @@ public static boolean convertV1(Component parent, BufferedImage img, String mosF tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte) 255; for (int i = 1; i < 256; i++) { - tilePalette[(i << 2) + 0] = (byte) (palette[i - 1] & 0xff); + tilePalette[(i << 2)] = (byte) (palette[i - 1] & 0xff); tilePalette[(i << 2) + 1] = (byte) ((palette[i - 1] >>> 8) & 0xff); tilePalette[(i << 2) + 2] = (byte) ((palette[i - 1] >>> 16) & 0xff); tilePalette[(i << 2) + 3] = 0; @@ -241,7 +241,7 @@ public static boolean convertV1(Component parent, BufferedImage img, String mosF try (OutputStream os = StreamUtils.getOutputStream(mosFile, true)) { os.write(dst); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add("Error writing TIS file to disk."); return false; @@ -386,7 +386,7 @@ public static boolean convertV2(Component parent, BufferedImage img, String mosF try (OutputStream os = StreamUtils.getOutputStream(mosFile, true)) { os.write(dst); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add("Error writing MOS file to disk."); return false; @@ -413,12 +413,11 @@ public static boolean convertV2(Component parent, BufferedImage img, String mosF // Returns a list of supported graphics file formats private static FileNameExtensionFilter[] getInputFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { + return new FileNameExtensionFilter[] { new FileNameExtensionFilter("Graphics files (*.bmp, *.png, *,jpg, *.jpeg)", "bam", "bmp", "png", "jpg", "jpeg"), new FileNameExtensionFilter("BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("PNG files (*.png)", "png"), new FileNameExtensionFilter("JPEG files (*.jpg, *.jpeg)", "jpg", "jpeg") }; - return filters; } // generates PVRZ textures @@ -496,14 +495,14 @@ private static boolean createPvrzPages(Path path, BufferedImage img, DxtEncoder. try (OutputStream os = StreamUtils.getOutputStream(pvrzFile, true)) { os.write(pvrz); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add(String.format("Error writing PVRZ file \"%s\" to disk.", pvrzFile)); return false; } pvrz = null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add(String.format("Error while generating PVRZ files:\n%s", e.getMessage())); return false; @@ -536,30 +535,30 @@ public void actionPerformed(ActionEvent event) { if (workerConvert == null) { final String msg = "MOS output file already exists. Overwrite?"; Path file = null; - do { - if (tabPane.getSelectedIndex() == 0 && !tfOutputV1.getText().isEmpty()) { - file = FileManager.resolve(tfOutputV1.getText()); - } else if (tabPane.getSelectedIndex() == 1 & !tfOutputV2.getText().isEmpty()) { - file = FileManager.resolve(tfOutputV2.getText()); - } - if (file != null) { - if (!FileEx.create(file).exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, - "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { - file = null; - workerConvert = new SwingWorker, Void>() { - @Override - public List doInBackground() { - return convert(); - } - }; - workerConvert.addPropertyChangeListener(this); - blocker = new WindowBlocker(this); - blocker.setBlocked(true); - workerConvert.execute(); - } + if (tabPane.getSelectedIndex() == 0 && !tfOutputV1.getText().isEmpty()) { + file = FileManager.resolve(tfOutputV1.getText()); + } else if (tabPane.getSelectedIndex() == 1 & !tfOutputV2.getText().isEmpty()) { + file = FileManager.resolve(tfOutputV2.getText()); + } + if (file != null) { + if (FileEx.create(file).isDirectory()) { + JOptionPane.showMessageDialog(this, "Output file cannot be a directory.", "Error", JOptionPane.ERROR_MESSAGE); + } else if (!FileEx.create(file).exists() || + JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE)) { file = null; + workerConvert = new SwingWorker, Void>() { + @Override + public List doInBackground() { + return convert(); + } + }; + workerConvert.addPropertyChangeListener(this); + blocker = new WindowBlocker(this); + blocker.setBlocked(true); + workerConvert.execute(); } - } while (file != null); + } } } else if (event.getSource() == bCancel) { hideWindow(); @@ -614,7 +613,7 @@ public void propertyChange(PropertyChangeEvent event) { try { sl = workerConvert.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } workerConvert = null; @@ -905,6 +904,7 @@ private int getPvrzIndex(Object o) { index = Integer.parseInt(o.toString()); } } catch (Exception e) { + Logger.trace(e); } } return index; @@ -927,8 +927,15 @@ private String getImageFileName(Path path) { fc.setFileFilter(filters[0]); if (Files.isRegularFile(path)) { fc.setSelectedFile(path.toFile()); - } else { - fc.setCurrentDirectory(path.getParent().toFile()); + } else if (!Files.exists(path)) { + // finding existing path + Path curPath = path.getParent(); + while (curPath.getNameCount() > 0 && !Files.exists(curPath)) { + curPath = curPath.getParent(); + } + if (curPath.getNameCount() > 0) { + fc.setCurrentDirectory(curPath.toFile()); + } } int ret = fc.showOpenDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { @@ -946,6 +953,10 @@ private String getMosFileName(Path path) { FileNameExtensionFilter filter = new FileNameExtensionFilter("MOS files (*.mos)", "mos"); fc.addChoosableFileFilter(filter); fc.setFileFilter(filter); + fc.setCurrentDirectory(path.toFile()); + if (!Files.isDirectory(path)) { + fc.setSelectedFile(path.toFile()); + } int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile().toString(); @@ -970,6 +981,7 @@ private List convert() { try { srcImage = ColorConvert.toBufferedImage(ImageIO.read(inFile.toFile()), true); } catch (Exception e) { + Logger.trace(e); } if (srcImage == null) { result.add(null); diff --git a/src/org/infinity/gui/converter/ConvertToPvrz.java b/src/org/infinity/gui/converter/ConvertToPvrz.java index e8bb6210e..48711f73d 100644 --- a/src/org/infinity/gui/converter/ConvertToPvrz.java +++ b/src/org/infinity/gui/converter/ConvertToPvrz.java @@ -27,6 +27,7 @@ import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Vector; import javax.imageio.ImageIO; @@ -55,6 +56,7 @@ import org.infinity.resource.graphics.Compressor; import org.infinity.resource.graphics.DxtEncoder; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.SimpleListModel; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -83,14 +85,13 @@ public class ConvertToPvrz extends ChildFrame implements ActionListener, Propert // Returns a list of supported graphics file formats private static FileNameExtensionFilter[] getInputFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { - new FileNameExtensionFilter("Graphics files (*.bmp, *.png, *,jpg, *.jpeg, *.pvr)", "bam", "bmp", "png", "jpg", - "jpeg", "pvr"), + return new FileNameExtensionFilter[] { + new FileNameExtensionFilter("Graphics files (*.bmp, *.png, *,jpg, *.jpeg, *.pvr)", + "bam", "bmp", "png", "jpg", "jpeg", "pvr"), new FileNameExtensionFilter("BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("PNG files (*.png)", "png"), new FileNameExtensionFilter("JPEG files (*.jpg, *.jpeg)", "jpg", "jpeg"), new FileNameExtensionFilter("PVR files (*.pvr)", "pvr") }; - return filters; } /** @@ -210,7 +211,7 @@ public List doInBackground() { if (dir != null && dir.isDirectory()) { currentDir = dir.toString(); FileNameExtensionFilter[] filters = getInputFilters(); - File[] fileList = dir.listFiles(); + File[] fileList = Objects.requireNonNull(dir.listFiles()); for (final File file : fileList) { for (final FileNameExtensionFilter filter : filters) { if (file != null && file.isFile() && filter.accept(file)) { @@ -276,7 +277,7 @@ public void propertyChange(PropertyChangeEvent event) { try { sl = workerConvert.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } workerConvert = null; @@ -473,7 +474,7 @@ private static boolean isValidGraphicsInput(Path inFile) { boolean result = (inFile != null && FileEx.create(inFile).isFile()); if (result) { Dimension d = ColorConvert.getImageDimension(inFile); - if (d == null || d.width <= 0 || d.width > 1024 || d.height <= 0 || d.height > 1024) { + if (d.width <= 0 || d.width > 1024 || d.height <= 0 || d.height > 1024) { result = false; } } @@ -613,7 +614,7 @@ private List convert() { } catch (IOException e) { bb = null; errors++; - e.printStackTrace(); + Logger.error(e); } if (bb != null) { byte[] buffer = bb.array(); @@ -622,7 +623,7 @@ private List convert() { os.write(output); } catch (Exception e) { errors++; - e.printStackTrace(); + Logger.error(e); } } } else if (isGraphics) { @@ -631,6 +632,7 @@ private List convert() { try { srcImg = ColorConvert.toBufferedImage(ImageIO.read(inFile.toFile()), true); } catch (Exception e) { + Logger.trace(e); } if (srcImg == null) { skippedFiles++; @@ -744,7 +746,7 @@ private List convert() { os.write(pvrz); } catch (Exception e) { errors++; - e.printStackTrace(); + Logger.error(e); } // cleaning up diff --git a/src/org/infinity/gui/converter/ConvertToTis.java b/src/org/infinity/gui/converter/ConvertToTis.java index 49f75dd93..c718ff9f7 100644 --- a/src/org/infinity/gui/converter/ConvertToTis.java +++ b/src/org/infinity/gui/converter/ConvertToTis.java @@ -24,9 +24,9 @@ import java.beans.PropertyChangeListener; import java.io.File; import java.io.OutputStream; +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; @@ -62,6 +62,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -187,7 +188,7 @@ public static boolean convertV1(Component parent, BufferedImage img, String tisF tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte) 255; for (int i = 1; i < 256; i++) { - tilePalette[(i << 2) + 0] = (byte) (palette[i - 1] & 0xff); + tilePalette[(i << 2)] = (byte) (palette[i - 1] & 0xff); tilePalette[(i << 2) + 1] = (byte) ((palette[i - 1] >>> 8) & 0xff); tilePalette[(i << 2) + 2] = (byte) ((palette[i - 1] >>> 16) & 0xff); tilePalette[(i << 2) + 3] = 0; @@ -229,7 +230,7 @@ public static boolean convertV1(Component parent, BufferedImage img, String tisF os.write(dst); } catch (Exception e) { // error handling - e.printStackTrace(); + Logger.error(e); result.add(null); result.add("Error writing TIS file to disk."); return false; @@ -370,7 +371,7 @@ public static boolean convertV2(Component parent, BufferedImage img, String tisF } // writing TIS entries - Collections.sort(entryList, TileEntry.CompareByIndex); + entryList.sort(TileEntry.CompareByIndex); for (int i = 0; i < entryList.size(); i++, dstOfs += 12) { TileEntry entry = entryList.get(i); DynamicArray.putInt(dst, dstOfs, entry.page); @@ -384,7 +385,7 @@ public static boolean convertV2(Component parent, BufferedImage img, String tisF os.write(dst); } catch (Exception e) { // error handling - e.printStackTrace(); + Logger.error(e); result.add(null); result.add("Error writing TIS file to disk."); return false; @@ -421,7 +422,7 @@ public static String createValidTisName(String tisFilename, int tisVersion) { Path outFile = FileManager.resolve(tisFilename).toAbsolutePath(); Path outPath = outFile.getParent(); String outNameBase = outFile.getFileName().toString(); - if (outNameBase == null || outNameBase.isEmpty() || outNameBase.charAt(0) == '.') { + if (outNameBase.isEmpty() || outNameBase.charAt(0) == '.') { outNameBase = "OUTPUT"; } if (outNameBase.lastIndexOf('.') > 0) { @@ -449,12 +450,11 @@ public static String createValidTisName(String tisFilename, int tisVersion) { // Returns a list of supported graphics file formats private static FileNameExtensionFilter[] getInputFilters() { - FileNameExtensionFilter[] filters = new FileNameExtensionFilter[] { + return new FileNameExtensionFilter[] { new FileNameExtensionFilter("Graphics files (*.bmp, *.png, *,jpg, *.jpeg)", "bam", "bmp", "png", "jpg", "jpeg"), new FileNameExtensionFilter("BMP files (*.bmp)", "bmp"), new FileNameExtensionFilter("PNG files (*.png)", "png"), new FileNameExtensionFilter("JPEG files (*.jpg, *.jpeg)", "jpg", "jpeg") }; - return filters; } // generates a PVRZ filename based on the specified parameters @@ -466,8 +466,7 @@ private static String generatePvrzName(String tisFileName, int page) { tisNameBase = tisNameBase.substring(0, tisNameBase.lastIndexOf('.')); } if (Pattern.matches(".{2,7}", tisNameBase)) { - String pvrzName = String.format("%s%s%02d.PVRZ", tisNameBase.substring(0, 1), - tisNameBase.substring(2, tisNameBase.length()), page); + String pvrzName = String.format("%s%s%02d.PVRZ", tisNameBase.charAt(0), tisNameBase.substring(2), page); if (tisPath != null) { return tisPath.resolve(pvrzName).toString(); } else { @@ -538,14 +537,14 @@ public static boolean createPvrzPages(String tisFileName, BufferedImage srcImg, os.write(pvrz); } catch (Exception e) { // critical error - e.printStackTrace(); + Logger.error(e); result.add(null); result.add(String.format("Error writing PVRZ file \"%s\" to disk.", pvrzName)); return false; } pvrz = null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); result.add(null); result.add(String.format("Error while generating PVRZ files:\n%s", e.getMessage())); return false; @@ -578,28 +577,28 @@ public void actionPerformed(ActionEvent event) { if (workerConvert == null) { final String msg = "TIS output file already exists. Overwrite?"; Path file = null; - do { - if (!tfOutput.getText().isEmpty()) { - file = FileManager.resolve(tfOutput.getText()); - } - if (file != null) { - if (!FileEx.create(file).exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, - "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { - file = null; - workerConvert = new SwingWorker, Void>() { - @Override - public List doInBackground() { - return convert(); - } - }; - workerConvert.addPropertyChangeListener(this); - blocker = new WindowBlocker(this); - blocker.setBlocked(true); - workerConvert.execute(); - } + if (!tfOutput.getText().isEmpty()) { + file = FileManager.resolve(tfOutput.getText()); + } + if (file != null) { + if (FileEx.create(file).isDirectory()) { + JOptionPane.showMessageDialog(this, "Output file cannot be a directory.", "Error", JOptionPane.ERROR_MESSAGE); + } else if (!FileEx.create(file).exists() || + JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE)) { file = null; + workerConvert = new SwingWorker, Void>() { + @Override + public List doInBackground() { + return convert(); + } + }; + workerConvert.addPropertyChangeListener(this); + blocker = new WindowBlocker(this); + blocker.setBlocked(true); + workerConvert.execute(); } - } while (file != null); + } } } else if (event.getSource() == bCancel) { hideWindow(); @@ -648,8 +647,11 @@ public List doInBackground() { fileName = createValidTisName(tfInput.getText(), getTisVersion()); } } - fc.setCurrentDirectory(FileManager.resolve(fileName).toFile()); - fc.setSelectedFile(FileManager.resolve(fileName).toFile()); + final Path path = FileManager.resolve(fileName); + fc.setCurrentDirectory(path.toFile()); + if (!Files.isDirectory(path)) { + fc.setSelectedFile(path.toFile()); + } int ret = fc.showSaveDialog(this); while (ret == JFileChooser.APPROVE_OPTION) { currentDir = fc.getSelectedFile().getParent(); @@ -700,7 +702,7 @@ public void propertyChange(PropertyChangeEvent event) { try { sl = workerConvert.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } workerConvert = null; @@ -994,7 +996,7 @@ private int getTisVersion() { // returns number of tiles to convert private int getTileCount() { - return (sTileNum.getValue() > 0) ? sTileNum.getValue() : 0; + return Math.max(sTileNum.getValue(), 0); } private String getInputFile() { @@ -1057,6 +1059,7 @@ private List convert() { try { srcImage = ColorConvert.toBufferedImage(ImageIO.read(inFile.toFile()), true); } catch (Exception e) { + Logger.trace(e); } if (srcImage == null) { ret.add(null); diff --git a/src/org/infinity/gui/hexview/BasicColorMap.java b/src/org/infinity/gui/hexview/BasicColorMap.java index 8576ca987..c6a448968 100644 --- a/src/org/infinity/gui/hexview/BasicColorMap.java +++ b/src/org/infinity/gui/hexview/BasicColorMap.java @@ -188,8 +188,7 @@ public void reset() { for (final StructEntry curEntry : getStruct().getFlatFields()) { List chain = curEntry.getStructChain(); boolean found = false; - for (int i = 0; !found && i < chain.size(); i++) { - final StructEntry e = chain.get(i); + for (final StructEntry e : chain) { Iterator> iter = typeMap.entrySet().iterator(); while (!found && iter.hasNext()) { Map.Entry entry = iter.next(); @@ -213,7 +212,6 @@ public void reset() { } } chain.clear(); - chain = null; } combineColoredBlocks(); @@ -287,7 +285,7 @@ public void setColoredEntry(Coloring color, Class classTy // Returns the cached color for a specific offset. private Color getCachedColor(long offset) { - if (cachedColor.getKey() != Long.valueOf(offset)) { + if (!Objects.equals(cachedColor.getKey(), offset)) { cachedColor.setKey(offset); ColoredBlock cb = findColoredBlock((int) offset); if (cb != null) { @@ -467,10 +465,10 @@ public int getStructureIndex(int offset) { } private static class ColoredBlock implements Comparable, Comparator { - private int offset; - private int size; - private int index; - private Coloring color; + private final int offset; + private final int size; + private final int index; + private final Coloring color; /** Returns a dummy block that can be used as key for search operations. */ public static ColoredBlock getSearchBlock(int offset) { diff --git a/src/org/infinity/gui/hexview/ResourceDataProvider.java b/src/org/infinity/gui/hexview/ResourceDataProvider.java index c460c21d9..9efa8a187 100644 --- a/src/org/infinity/gui/hexview/ResourceDataProvider.java +++ b/src/org/infinity/gui/hexview/ResourceDataProvider.java @@ -9,6 +9,7 @@ import java.util.HashMap; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import tv.porst.jhexview.DataChangedEvent; import tv.porst.jhexview.IDataChangedListener; @@ -36,7 +37,7 @@ public ResourceDataProvider(ResourceEntry entry) { @Override public void addListener(IDataChangedListener listener) { - if (listener != null && listeners.indexOf(listener) < 0) { + if (listener != null && !listeners.contains(listener)) { listeners.add(listener); } } @@ -60,7 +61,7 @@ public byte[] getData(long offset, int length) { } return retVal; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return null; @@ -76,7 +77,7 @@ public int getDataLength() { size = (int) resSize; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return size; @@ -139,11 +140,11 @@ protected void fireDataChanged() { } private boolean isModifiedData(int offset) { - return modifiedMap.containsKey(Integer.valueOf(offset)); + return modifiedMap.containsKey(offset); } private byte getModifiedData(int offset) { - Byte b = modifiedMap.get(Integer.valueOf(offset)); + Byte b = modifiedMap.get(offset); if (b != null) { return b; } else { diff --git a/src/org/infinity/gui/hexview/ResourceMenuCreator.java b/src/org/infinity/gui/hexview/ResourceMenuCreator.java index 8fe0003e0..9dc61b8ad 100644 --- a/src/org/infinity/gui/hexview/ResourceMenuCreator.java +++ b/src/org/infinity/gui/hexview/ResourceMenuCreator.java @@ -7,6 +7,7 @@ import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; @@ -82,7 +83,7 @@ public void actionPerformed(ActionEvent e) { if (curViewer != null) { curViewer.selectEntry(entry.getOffset(), false); } - ViewFrame curFrame = curViewer.getViewFrame((AbstractStruct) entry); + ViewFrame curFrame = Objects.requireNonNull(curViewer).getViewFrame((AbstractStruct) entry); if (curFrame.getViewable() instanceof AbstractStruct) { curViewer = ((AbstractStruct) curFrame.getViewable()).getViewer(); } else { @@ -118,8 +119,7 @@ private List createStructEntries(int offset) { if (!listEntries.isEmpty() && listEntries.get(0) == getStruct()) { listEntries.remove(0); } - for (int i = 0; i < listEntries.size(); i++) { - StructEntry e = listEntries.get(i); + for (StructEntry e : listEntries) { JMenuItem mi = new DataMenuItem(String.format("Go to \"%s\"", e.getName()), null, e); list.add(mi); } diff --git a/src/org/infinity/gui/hexview/StructHexViewer.java b/src/org/infinity/gui/hexview/StructHexViewer.java index 30b35911b..141a78e74 100644 --- a/src/org/infinity/gui/hexview/StructHexViewer.java +++ b/src/org/infinity/gui/hexview/StructHexViewer.java @@ -73,6 +73,7 @@ import org.infinity.resource.dlg.AbstractCode; import org.infinity.resource.key.BIFFResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -411,7 +412,7 @@ private void findPattern(int offset) { offset = getHexView().findAscii(offset, getFindData().getText(), getFindData().isCaseSensitive()); if (offset >= 0) { getHexView().setCurrentOffset(offset); - getHexView().setSelectionLength(getFindData().getText().length() * 2); + getHexView().setSelectionLength(getFindData().getText().length() * 2L); } else { JOptionPane.showMessageDialog(this, "No match found.", "Find", JOptionPane.INFORMATION_MESSAGE); } @@ -420,7 +421,7 @@ private void findPattern(int offset) { offset = getHexView().findHex(offset, getFindData().getBytes()); if (offset >= 0) { getHexView().setCurrentOffset(offset); - getHexView().setSelectionLength(getFindData().getBytes().length * 2); + getHexView().setSelectionLength(getFindData().getBytes().length * 2L); } else { JOptionPane.showMessageDialog(this, "No match found.", "Find", JOptionPane.INFORMATION_MESSAGE); } @@ -487,7 +488,7 @@ private boolean saveResource(Path outFile) { } catch (IOException e) { JOptionPane.showMessageDialog(this, "Unable to create override folder.", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return false; } } @@ -500,7 +501,7 @@ private boolean saveResource(Path outFile) { if (FileEx.create(outPath).exists()) { outPath = outPath.toAbsolutePath(); - String options[] = { "Overwrite", "Cancel" }; + String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(this, outPath + " exists. Overwrite?", "Save resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) == 0) { if (BrowserMenuBar.getInstance().getOptions().backupOnSave()) { @@ -513,7 +514,7 @@ private boolean saveResource(Path outFile) { Files.move(outPath, bakPath); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } else { @@ -538,7 +539,7 @@ private boolean saveResource(Path outFile) { } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error while saving " + getStruct().getResourceEntry().toString(), "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return false; } return true; @@ -707,7 +708,7 @@ private void addComponentToPanel(Component c) { } /** Manages the representation of a single {@link StructEntry} instance. */ - private class StructEntryTableModel extends AbstractTableModel { + private static class StructEntryTableModel extends AbstractTableModel { private final String[] names = { "Name", "Start offset", "Length", "Structure type", "Value" }; private final StructEntry entry; diff --git a/src/org/infinity/gui/hexview/StructuredDataProvider.java b/src/org/infinity/gui/hexview/StructuredDataProvider.java index 15ae9405b..1cef843c3 100644 --- a/src/org/infinity/gui/hexview/StructuredDataProvider.java +++ b/src/org/infinity/gui/hexview/StructuredDataProvider.java @@ -14,6 +14,7 @@ import org.infinity.resource.AbstractStruct; import org.infinity.resource.StructEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; import tv.porst.jhexview.DataChangedEvent; @@ -44,7 +45,7 @@ public StructuredDataProvider(AbstractStruct struct) { @Override public void addListener(IDataChangedListener listener) { - if (listener != null && listeners.indexOf(listener) < 0) { + if (listener != null && !listeners.contains(listener)) { listeners.add(listener); } } @@ -97,7 +98,7 @@ public byte[] getData(long offset, int length) { try { entry.write(os); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } curOfs += entry.getSize(); } @@ -106,7 +107,7 @@ public byte[] getData(long offset, int length) { try { System.arraycopy(os.toByteArray(), (int) offset - startOffset, retVal, 0, length); } catch (ArrayIndexOutOfBoundsException e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -193,7 +194,7 @@ public void setData(long offset, byte[] data) { hasChanged = true; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/gui/layeritem/AbstractLayerItem.java b/src/org/infinity/gui/layeritem/AbstractLayerItem.java index 24a08c1d4..7abf141e7 100644 --- a/src/org/infinity/gui/layeritem/AbstractLayerItem.java +++ b/src/org/infinity/gui/layeritem/AbstractLayerItem.java @@ -78,7 +78,7 @@ public void addActionListener(ActionListener l) { } public ActionListener[] getActionListeners() { - return actionListener.toArray(new ActionListener[actionListener.size()]); + return actionListener.toArray(new ActionListener[0]); } public void removeActionListener(ActionListener l) { diff --git a/src/org/infinity/gui/layeritem/AnimatedLayerItem.java b/src/org/infinity/gui/layeritem/AnimatedLayerItem.java index 359789780..a6d27bed7 100644 --- a/src/org/infinity/gui/layeritem/AnimatedLayerItem.java +++ b/src/org/infinity/gui/layeritem/AnimatedLayerItem.java @@ -273,7 +273,7 @@ public int getFrameWidth(ItemState state) { * Defines the frame width in pixels in the specified state. */ public void setFrameWidth(ItemState state, int width) { - frameInfos[state.ordinal()].setStroke(new BasicStroke(width < 1 ? 1 : width)); + frameInfos[state.ordinal()].setStroke(new BasicStroke(Math.max(width, 1))); updateFrame(); } @@ -545,8 +545,8 @@ private void updatePosition() { /** Stores information about frames around the item. */ private static class FrameInfo { - private static Color DefaultColor = new Color(0, true); - private static BasicStroke DefaultStroke = new BasicStroke(1.0f); + private static final Color DefaultColor = new Color(0, true); + private static final BasicStroke DefaultStroke = new BasicStroke(1.0f); private boolean enabled; private Color color; diff --git a/src/org/infinity/gui/layeritem/IconLayerItem.java b/src/org/infinity/gui/layeritem/IconLayerItem.java index ca7f7373b..89f85083f 100644 --- a/src/org/infinity/gui/layeritem/IconLayerItem.java +++ b/src/org/infinity/gui/layeritem/IconLayerItem.java @@ -35,8 +35,8 @@ public class IconLayerItem extends AbstractLayerItem implements LayerItemListene private final EnumMap images = new EnumMap<>(ItemState.class); private final EnumMap frames = new EnumMap<>(ItemState.class); - private RenderCanvas rcCanvas; - private JLabel label; + private final RenderCanvas rcCanvas; + private final JLabel label; /** * Initialize object with an associated Viewable and an additional text message. @@ -126,7 +126,7 @@ public Image getImage(ItemState state) { if (state == null) { state = ItemState.NORMAL; } - return images.containsKey(state) ? images.get(state) : DEFAULT_IMAGE; + return images.getOrDefault(state, DEFAULT_IMAGE); } /** diff --git a/src/org/infinity/gui/layeritem/LayerItemEvent.java b/src/org/infinity/gui/layeritem/LayerItemEvent.java index 287c87fd7..56a544f8d 100644 --- a/src/org/infinity/gui/layeritem/LayerItemEvent.java +++ b/src/org/infinity/gui/layeritem/LayerItemEvent.java @@ -10,7 +10,7 @@ * Used in AbstractLayerItem and subclasses. */ public class LayerItemEvent extends EventObject { - private String actionCommand; + private final String actionCommand; public LayerItemEvent(Object source, String cmd) { super(source); diff --git a/src/org/infinity/gui/layeritem/ShapedLayerItem.java b/src/org/infinity/gui/layeritem/ShapedLayerItem.java index 117f1b1df..1570bd4a6 100644 --- a/src/org/infinity/gui/layeritem/ShapedLayerItem.java +++ b/src/org/infinity/gui/layeritem/ShapedLayerItem.java @@ -108,7 +108,7 @@ public Color getStrokeColor(ItemState state) { if (state == null) { state = ItemState.NORMAL; } - return strokeColors.containsKey(state) ? strokeColors.get(state) : DEFAULT_COLOR; + return strokeColors.getOrDefault(state, DEFAULT_COLOR); } /** @@ -169,7 +169,7 @@ public Color getFillColor(ItemState state) { if (state == null) { state = ItemState.NORMAL; } - return fillColors.containsKey(state) ? fillColors.get(state) : DEFAULT_COLOR; + return fillColors.getOrDefault(state, DEFAULT_COLOR); } /** diff --git a/src/org/infinity/gui/menu/Bookmark.java b/src/org/infinity/gui/menu/Bookmark.java index f57fba133..0ca844ce2 100644 --- a/src/org/infinity/gui/menu/Bookmark.java +++ b/src/org/infinity/gui/menu/Bookmark.java @@ -114,13 +114,13 @@ public void setHomePath(String hp) { /** Returns a list of available paths to executables for the current platform. */ public List getBinaryPaths() { - return getBinaryPaths(Platform.getPlatform()); + return getBinaryPaths(Platform.OS.getCurrentOS()); } /** Returns a list of available paths to executables for the given platform. */ public List getBinaryPaths(Platform.OS os) { if (os == null) { - os = Platform.getPlatform(); + os = Platform.OS.getCurrentOS(); } return Collections.unmodifiableList(binPaths.getOrDefault(os, new ArrayList(1))); } @@ -130,7 +130,7 @@ public List getBinaryPaths(Platform.OS os) { */ public List setBinaryPaths(Platform.OS os, List pathList) { if (os == null) { - os = Platform.getPlatform(); + os = Platform.OS.getCurrentOS(); } List retVal = binPaths.get(os); @@ -268,7 +268,7 @@ public static String getNameKey(int idx) { /** Returns the Preferences key for a specific BookmarkBinPath for the current platform. */ public static String getBinaryPathKey(int idx) { - return getBinaryPathKey(Platform.getPlatform(), idx); + return getBinaryPathKey(Platform.OS.getCurrentOS(), idx); } /** Returns the Preferences key for a specific BookmarkBinPath for the given platform. */ diff --git a/src/org/infinity/gui/menu/BrowserMenuBar.java b/src/org/infinity/gui/menu/BrowserMenuBar.java index 10208a955..689536ffa 100644 --- a/src/org/infinity/gui/menu/BrowserMenuBar.java +++ b/src/org/infinity/gui/menu/BrowserMenuBar.java @@ -50,7 +50,7 @@ public final class BrowserMenuBar extends JMenuBar implements KeyEventDispatcher private final Preferences prefsGui; private final Preferences prefsProfiles; - /** Returns {@true} if this class has been instantiated. */ + /** Returns {@code true} if this class has been instantiated. */ public static boolean isInstantiated() { return (menuBar != null); } diff --git a/src/org/infinity/gui/menu/FileMenu.java b/src/org/infinity/gui/menu/FileMenu.java index 5b7403984..fc7a6e1ee 100644 --- a/src/org/infinity/gui/menu/FileMenu.java +++ b/src/org/infinity/gui/menu/FileMenu.java @@ -26,6 +26,7 @@ import org.infinity.resource.key.BIFFResourceEntry; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * Handles File menu items for the {@link BrowserMenuBar}. @@ -182,7 +183,7 @@ 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); } diff --git a/src/org/infinity/gui/menu/GameMenu.java b/src/org/infinity/gui/menu/GameMenu.java index e947437ae..545824299 100644 --- a/src/org/infinity/gui/menu/GameMenu.java +++ b/src/org/infinity/gui/menu/GameMenu.java @@ -30,6 +30,7 @@ import org.infinity.icon.Icons; import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; +import org.infinity.util.Logger; import org.infinity.util.Platform; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -316,7 +317,7 @@ public void actionPerformed(ActionEvent event) { try { isEqual = keyFile.equals(Profile.getChitinKey().toAbsolutePath()); } catch (IOError e) { - e.printStackTrace(); + Logger.error(e); } if (!isEqual) { int confirm = JOptionPane.YES_OPTION; diff --git a/src/org/infinity/gui/menu/HelpMenu.java b/src/org/infinity/gui/menu/HelpMenu.java index 548e37f9f..083bf0063 100644 --- a/src/org/infinity/gui/menu/HelpMenu.java +++ b/src/org/infinity/gui/menu/HelpMenu.java @@ -43,6 +43,7 @@ import org.infinity.updater.Updater; import org.infinity.updater.UpdaterSettings; import org.infinity.util.DataString; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.tuples.Couple; @@ -65,6 +66,7 @@ public class HelpMenu extends JMenu implements BrowserSubMenu, ActionListener { private final JMenuItem helpApngWriterLicense; private final JMenuItem helpCommonMarkLicense; private final JMenuItem helpFlatLafLicense; + private final JMenuItem helpTinyLogLicense; private final JMenuItem helpOracleLicense; private final JMenuItem helpUpdateSettings; private final JMenuItem helpUpdateCheck; @@ -118,6 +120,9 @@ public HelpMenu(BrowserMenuBar parent) { helpOracleLicense = BrowserMenuBar.makeMenuItem("Oracle License", KeyEvent.VK_O, Icons.ICON_EDIT_16.getIcon(), -1, this); miscLicenses.add(helpOracleLicense); + helpTinyLogLicense = BrowserMenuBar.makeMenuItem("tinylog License", KeyEvent.VK_T, Icons.ICON_EDIT_16.getIcon(), -1, this); + miscLicenses.add(helpTinyLogLicense); + addSeparator(); helpUpdateSettings = BrowserMenuBar.makeMenuItem("Update settings...", KeyEvent.VK_S, null, -1, this); @@ -187,6 +192,8 @@ public void actionPerformed(ActionEvent event) { displayLicense("org/infinity/commonmark.License.txt", "BSD License"); } else if (event.getSource() == helpOracleLicense) { displayLicense("org/infinity/Oracle.License.txt", "BSD License"); + } else if (event.getSource() == helpTinyLogLicense) { + displayLicense("org/infinity/tinylog.License.txt", "Apache License"); } else if (event.getSource() == helpUpdateSettings) { UpdaterSettings.showDialog(NearInfinity.getInstance()); } else if (event.getSource() == helpUpdateCheck) { @@ -204,7 +211,7 @@ public void actionPerformed(ActionEvent event) { info = null; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Check for updates: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return; @@ -228,7 +235,7 @@ private void displayAbout() { }; // original author final String originalVersion = "From Near Infinity 1.32.1 beta 24"; - final String originalCopyright = "Copyright (\u00A9) 2001-2005 - Jon Olav Hauglid"; + final String originalCopyright = "Copyright (©) 2001-2005 - Jon Olav Hauglid"; // List of various contributors (sorted alphabetically) final List> contributors2 = new ArrayList>() { { @@ -250,13 +257,14 @@ private void displayAbout() { // Third-party copyright messages final List copyThirdPartyText = new ArrayList() { { - add("Most icons (\u00A9) eclipse.org - Common Public License."); - add("RSyntaxTextArea (\u00A9) Fifesoft - Berkeley Software Distribution License."); + add("Most icons (©) eclipse.org - Common Public License."); + add("RSyntaxTextArea (©) Fifesoft - Berkeley Software Distribution License."); add("Monte Media Library by Werner Randelshofer - GNU Lesser General Public License."); - add("JOrbis (\u00A9) JCraft Inc. - GNU Lesser General Public License."); + add("JOrbis (©) JCraft Inc. - GNU Lesser General Public License."); add("JHexView by Sebastian Porst - GNU General Public License."); - add("CommonMark-Java (\u00A9) Atlassian Pty. Ltd. - BSD License."); - add("FlatLaf (\u00A9) FormDev Software GmbH - Apache License."); + add("CommonMark-Java (©) Atlassian Pty. Ltd. - BSD License."); + add("FlatLaf (©) FormDev Software GmbH - Apache License."); + add("tinylog 2 by Martin Winandy - Apache License."); add("APNG Writer by Weoulren - BSD License."); } }; @@ -434,7 +442,7 @@ private void displayLicense(String classPath, String title) { try { tphelp.setPage(ClassLoader.getSystemResource(classPath)); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } JOptionPane.showMessageDialog(NearInfinity.getInstance(), panel, title, JOptionPane.PLAIN_MESSAGE); diff --git a/src/org/infinity/gui/menu/LogLevel.java b/src/org/infinity/gui/menu/LogLevel.java new file mode 100644 index 000000000..6684ce0ca --- /dev/null +++ b/src/org/infinity/gui/menu/LogLevel.java @@ -0,0 +1,41 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.gui.menu; + +import org.tinylog.Level; + +/** Wrapper for the {@link Level} enum from the tinylog logging framework. */ +public enum LogLevel { + TRACE(Level.TRACE, "Trace (fine-grained)"), + DEBUG(Level.DEBUG, "Debug (diagnostic)"), + INFO(Level.INFO, "Information (recommended)"), + WARN(Level.WARN, "Warning"), + ERROR(Level.ERROR, "Error"), + OFF(Level.OFF, "Disabled (not recommended)"), + ; + + private final Level level; + private final String title; + + LogLevel(Level level, String title) { + this.level = level; + this.title = title; + } + + /** Log {@link Level} associated with this enum. */ + public Level getLevel() { + return level; + } + + /** Title of the log level option in the Preferences dialog. */ + public String getTitle() { + return title; + } + + @Override + public String toString() { + return getTitle(); + } +} diff --git a/src/org/infinity/gui/menu/OptionsMenuItem.java b/src/org/infinity/gui/menu/OptionsMenuItem.java index 2a5b4e237..559530130 100644 --- a/src/org/infinity/gui/menu/OptionsMenuItem.java +++ b/src/org/infinity/gui/menu/OptionsMenuItem.java @@ -10,8 +10,6 @@ import java.awt.Font; import java.awt.FontMetrics; import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.nio.charset.Charset; import java.util.ArrayList; @@ -22,7 +20,6 @@ import java.util.List; import java.util.Locale; import java.util.Objects; -import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.JLabel; @@ -50,6 +47,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; import org.infinity.util.CharsetDetector; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StringTable; import org.infinity.util.tuples.Couple; @@ -57,7 +55,7 @@ /** * Handles Option menu items for the {@link BrowserMenuBar}. */ -public class OptionsMenuItem extends JMenuItem implements ActionListener { +public class OptionsMenuItem extends JMenuItem { /** Alignment types available for 2DA resources. */ public enum AutoAlign2da { /** Do not align columns. */ @@ -166,13 +164,13 @@ public String toString() { public static final String OPTION_SHOWCOLOREDSTRUCTURES = "ShowColoredStructures"; public static final String OPTION_SHOWHEXCOLORED = "ShowHexColored"; public static final String OPTION_SHOWSYSINFO = "ShowSysInfo"; + public static final String OPTION_SHOWMEMSTATUS = "ShowMemStatus"; public static final String OPTION_OPENBOOKMARKSPROMPT = "OpenBookmarksPrompt"; public static final String OPTION_REMEMBER_CHILDFRAME_RECT = "RememberChildFrameRect"; public static final String OPTION_AUTOCHECK_BCS = "AutocheckBCS"; public static final String OPTION_AUTOGEN_BCS_COMMENTS = "AutogenBCSComments"; public static final String OPTION_MORECOMPILERWARNINGS = "MoreCompilerWarnings"; -// public static final String OPTION_MONITORFILECHANGES = "MonitorFileChanges"; public static final String OPTION_TEXT_SHOWCURRENTLINE = "TextShowCurrentLine"; public static final String OPTION_TEXT_SHOWLINENUMBERS = "TextShowLineNumbers"; @@ -335,34 +333,32 @@ private static List> extractGameLanguages(String definiti List> list = new ArrayList<>(); if (definition != null && !definition.isEmpty()) { String[] entries = definition.split(";"); - if (entries != null) { - for (final String entry : entries) { - String[] elements = entry.split("="); - if (elements != null && elements.length == 2) { - Profile.Game game = Profile.gameFromString(elements[0]); - if (game != Profile.Game.Unknown) { - String lang = elements[1].trim(); - Couple pair = null; - if (lang.equalsIgnoreCase(LANGUAGE_AUTODETECT)) { - pair = Couple.with(game.toString(), LANGUAGE_AUTODETECT); - } else if (lang.matches("[a-z]{2}_[A-Z]{2}")) { - pair = Couple.with(game.toString(), lang); - } + for (final String entry : entries) { + String[] elements = entry.split("="); + if (elements.length == 2) { + Profile.Game game = Profile.gameFromString(elements[0]); + if (game != Profile.Game.Unknown) { + String lang = elements[1].trim(); + Couple pair = null; + if (lang.equalsIgnoreCase(LANGUAGE_AUTODETECT)) { + pair = Couple.with(game.toString(), LANGUAGE_AUTODETECT); + } else if (lang.matches("[a-z]{2}_[A-Z]{2}")) { + pair = Couple.with(game.toString(), lang); + } - // check if game/language pair is already in the list - if (pair != null) { - for (final Couple curPair : list) { - if (curPair.getValue0().equalsIgnoreCase(pair.getValue0())) { - curPair.setValue1(pair.getValue1()); - pair = null; - break; - } + // check if game/language pair is already in the list + if (pair != null) { + for (final Couple curPair : list) { + if (curPair.getValue0().equalsIgnoreCase(pair.getValue0())) { + curPair.setValue1(pair.getValue1()); + pair = null; + break; } } + } - if (pair != null) { - list.add(pair); - } + if (pair != null) { + list.add(pair); } } } @@ -512,6 +508,11 @@ public boolean showSysInfo() { return AppOption.SHOW_SYS_INFO.getBoolValue(); } + /** Returns whether the current memory consumption is shown in NI's status bar. */ + public boolean showMemStatus() { + return AppOption.SHOW_MEM_STATUS.getBoolValue(); + } + /** Returns whether to show a dialog prompt whenever a bookmarked game is opened. */ public boolean showOpenBookmarksPrompt() { return AppOption.OPEN_BOOKMARKS_PROMPT.getBoolValue(); @@ -809,6 +810,7 @@ public LookAndFeelInfo getLookAndFeel() { info = new LookAndFeelInfo(AppOption.LOOK_AND_FEEL_CLASS.getName(), value); } } catch (Exception e) { + Logger.trace(e); } if (info == null) { @@ -864,16 +866,6 @@ public String getSelectedGameLanguage() { return lang.equalsIgnoreCase(LANGUAGE_AUTODETECT) ? "" : lang; } - /** - * Returns whether file changes in override folders are tracked at real time and reflected in the resource tree. - * - * (not yet implemented) - */ - public boolean getMonitorFileChanges() { -// return optionMonitorFileChanges.isSelected(); - return false; - } - /** Returns defValue if masked bit is clear or value if masked bit is already set. */ public boolean fixOption(int mask, boolean defValue, boolean value) { boolean retVal = value; @@ -886,17 +878,6 @@ public boolean fixOption(int mask, boolean defValue, boolean value) { return retVal; } - @Override - public void actionPerformed(ActionEvent event) { - // if (event.getSource() == optionMonitorFileChanges) { - // if (optionMonitorFileChanges.isSelected()) { - // FileWatcher.getInstance().start(); - // } else { - // FileWatcher.getInstance().stop(); - // } - // } - } - /** Attempts to switch the game language in Enhanced Edition games. */ private void switchGameLanguage(String newLanguage, boolean prompt) { if (newLanguage != null) { @@ -982,6 +963,7 @@ private void applyChanges(Collection options) { lfName = ((LookAndFeel) o).getName(); } } catch (Exception e) { + Logger.trace(e); } final LookAndFeelInfo info = new LookAndFeelInfo(lfName, className); NearInfinity.getInstance().updateLookAndFeel(info, false); @@ -989,7 +971,7 @@ private void applyChanges(Collection options) { refresh = true; restart = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else if (option.equals(AppOption.TEXT_FONT)) { int idx = option.getIntValue(); @@ -1034,56 +1016,52 @@ private void applyChanges(Collection options) { message = "Settings have been applied to Near Infinity."; } - if (sb.length() > 0 || message != null) { - // constructing dialog content pane - JPanel panel = new JPanel(new BorderLayout(8, 8)); + // constructing dialog content pane + JPanel panel = new JPanel(new BorderLayout(8, 8)); - if (sb.length() > 0) { - // constructing list of modified options - JLabel modifiedLabel = new JLabel(String.format("Modified settings (%d):", messages.size()), SwingConstants.LEADING); - panel.add(modifiedLabel, BorderLayout.NORTH); + if (sb.length() > 0) { + // constructing list of modified options + JLabel modifiedLabel = new JLabel(String.format("Modified settings (%d):", messages.size()), SwingConstants.LEADING); + panel.add(modifiedLabel, BorderLayout.NORTH); - // list of modified options - JTextArea textArea = new JTextArea(sb.toString()); + // list of modified options + JTextArea textArea = new JTextArea(sb.toString()); // textArea.setBackground(panel.getBackground()); - textArea.setBackground(Misc.getDefaultColor("Label.background", Color.GRAY)); - textArea.setFont(UIManager.getDefaults().getFont("Label.font")); - textArea.setEditable(false); - textArea.setFocusable(false); - textArea.setBorder(BorderFactory.createEmptyBorder()); - - JScrollPane scroller = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - scroller.setBorder(BorderFactory.createEmptyBorder()); - - panel.add(scroller, BorderLayout.CENTER); - - // limiting number of visible lines - final FontMetrics fm = textArea.getFontMetrics(textArea.getFont()); - int height = Math.min(15, messages.size()) * fm.getHeight() + fm.getHeight() / 2; - final Dimension dim = scroller.getPreferredSize(); - dim.width += UIManager.getInt("ScrollBar.width"); // prevents cut off text - dim.height = height; - scroller.setPreferredSize(dim); - } + textArea.setBackground(Misc.getDefaultColor("Label.background", Color.GRAY)); + textArea.setFont(UIManager.getDefaults().getFont("Label.font")); + textArea.setEditable(false); + textArea.setFocusable(false); + textArea.setBorder(BorderFactory.createEmptyBorder()); + + JScrollPane scroller = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroller.setBorder(BorderFactory.createEmptyBorder()); + + panel.add(scroller, BorderLayout.CENTER); + + // limiting number of visible lines + final FontMetrics fm = textArea.getFontMetrics(textArea.getFont()); + int height = Math.min(15, messages.size()) * fm.getHeight() + fm.getHeight() / 2; + final Dimension dim = scroller.getPreferredSize(); + dim.width += UIManager.getInt("ScrollBar.width"); // prevents cut off text + dim.height = height; + scroller.setPreferredSize(dim); + } - if (message != null) { - JTextPane msgPane = new JTextPane(); - StyledDocument style = msgPane.getStyledDocument(); - SimpleAttributeSet align = new SimpleAttributeSet(); - StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT); - style.setParagraphAttributes(0, style.getLength(), align, false); - msgPane.setBackground(Misc.getDefaultColor("Label.background", Color.GRAY)); - msgPane.setFont(UIManager.getDefaults().getFont("Label.font")); - msgPane.setEditable(false); - msgPane.setFocusable(false); - msgPane.setBorder(BorderFactory.createEmptyBorder()); - msgPane.setText(message); - panel.add(msgPane, BorderLayout.SOUTH); - } + JTextPane msgPane = new JTextPane(); + StyledDocument style = msgPane.getStyledDocument(); + SimpleAttributeSet align = new SimpleAttributeSet(); + StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT); + style.setParagraphAttributes(0, style.getLength(), align, false); + msgPane.setBackground(Misc.getDefaultColor("Label.background", Color.GRAY)); + msgPane.setFont(UIManager.getDefaults().getFont("Label.font")); + msgPane.setEditable(false); + msgPane.setFocusable(false); + msgPane.setBorder(BorderFactory.createEmptyBorder()); + msgPane.setText(message); + panel.add(msgPane, BorderLayout.SOUTH); - JOptionPane.showMessageDialog(NearInfinity.getInstance(), panel, "Settings changed", JOptionPane.INFORMATION_MESSAGE); - } + JOptionPane.showMessageDialog(NearInfinity.getInstance(), panel, "Settings changed", JOptionPane.INFORMATION_MESSAGE); } // -------------------------- INNER CLASSES -------------------------- @@ -1186,9 +1164,9 @@ public String toString() { private void init() { StringBuilder sb = new StringBuilder(); Charset cs = Charset.forName(getId()); - if (cs != null && !cs.aliases().isEmpty()) { + if (!cs.aliases().isEmpty()) { sb.append("Charset aliases: ") - .append(cs.aliases().stream().collect(Collectors.joining(", "))); + .append(String.join(", ", cs.aliases())); } desc = sb.toString(); } diff --git a/src/org/infinity/gui/menu/ToolsMenu.java b/src/org/infinity/gui/menu/ToolsMenu.java index 9765632c9..17dda2f39 100644 --- a/src/org/infinity/gui/menu/ToolsMenu.java +++ b/src/org/infinity/gui/menu/ToolsMenu.java @@ -282,7 +282,7 @@ public ToolsMenu(BrowserMenuBar parent) { // } catch (IOException e) { // JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error writing keyfile", "Error", // JOptionPane.ERROR_MESSAGE); -// e.printStackTrace(); +// Logger.error(e); // } // } // } diff --git a/src/org/infinity/gui/options/OptionCheckBox.java b/src/org/infinity/gui/options/OptionCheckBox.java index 36f263258..4d753da68 100644 --- a/src/org/infinity/gui/options/OptionCheckBox.java +++ b/src/org/infinity/gui/options/OptionCheckBox.java @@ -185,7 +185,7 @@ public void fireOnAccept() { if (getOnAccept() != null) { getOnAccept().accept(this); } else if (getOption() != null && getOption().getDefault() instanceof Boolean) { - getOption().setValue(Boolean.valueOf(getValue())); + getOption().setValue(getValue()); } } diff --git a/src/org/infinity/gui/options/OptionContainerBase.java b/src/org/infinity/gui/options/OptionContainerBase.java index eab01d53e..c7c72677d 100644 --- a/src/org/infinity/gui/options/OptionContainerBase.java +++ b/src/org/infinity/gui/options/OptionContainerBase.java @@ -15,8 +15,8 @@ public abstract class OptionContainerBase extends OptionBase { protected OptionContainerBase(Object id, String label, OptionBase... children) { super(id, label); - for (int i = 0; i < children.length; i++) { - addChild(children[i]); + for (OptionBase child : children) { + addChild(child); } } diff --git a/src/org/infinity/gui/options/OptionGroupBox.java b/src/org/infinity/gui/options/OptionGroupBox.java index 08e7de15d..165d48f69 100644 --- a/src/org/infinity/gui/options/OptionGroupBox.java +++ b/src/org/infinity/gui/options/OptionGroupBox.java @@ -62,8 +62,8 @@ protected OptionGroupBox(Object id, String label, String desc, int selectedIndex super(id, label, desc, option); if (items != null) { - for (int i = 0; i < items.length; i++) { - this.items.add(Objects.requireNonNull(items[i])); + for (Object item : items) { + this.items.add(Objects.requireNonNull(item)); } } @@ -221,7 +221,7 @@ public Function getOnSelect() { /** * Specifies a function that will be executed whenever the user changed the selected item of the associated combobox. * - * @param action {@link Function} instance which is called with this {@code OptionGroupBox} instance as parameter. + * @param select {@link Function} instance which is called with this {@code OptionGroupBox} instance as parameter. * The function should return {@code true} if the current combobox selection state should be retained and * {@code false} if the selection state should be reverted to the previous value. */ @@ -302,7 +302,7 @@ public void fireOnAccept() { if (getOnAccept() != null) { getOnAccept().accept(this); } else if (getOption() != null && getOption().getDefault() instanceof Number) { - getOption().setValue(Integer.valueOf(getSelectedIndex())); + getOption().setValue(getSelectedIndex()); } } diff --git a/src/org/infinity/icon/Icons.java b/src/org/infinity/icon/Icons.java index 29d952ead..5be468cb2 100644 --- a/src/org/infinity/icon/Icons.java +++ b/src/org/infinity/icon/Icons.java @@ -4,13 +4,10 @@ package org.infinity.icon; -import java.awt.Image; -import java.io.IOException; -import java.io.InputStream; - -import javax.imageio.ImageIO; import javax.swing.ImageIcon; +import org.infinity.resource.graphics.ColorConvert; + /** * Provides {@code ImageIcon} instances of selected graphics files. */ @@ -97,7 +94,7 @@ private Icons(String fileName) { /** Returns the {@code ImageIcon} instance of the enum object. */ public ImageIcon getIcon() { if (icon == null) { - icon = getIcon(null, fileName); + icon = ColorConvert.loadAppIcon(Icons.class, fileName); if (icon == null) { throw new NullPointerException("Icon is null"); } @@ -109,67 +106,4 @@ public ImageIcon getIcon() { public String getFileName() { return fileName; } - - /** - * A static method that loads a graphics file from the folder relative to the specified {@code Class} object and - * returns it as an {@code ImageIcon} instance. - * - * @param cls {@code Class} object used to determine the root path within the Java Archive. Specify {@code null} - * to use the current class as root path for the graphics file. - * @param fileName Filename of the graphics file relative to the root path. The following file format are supported: - * BMP, GIF, JPEG PNG and WEBP. - * @return {@code ImageIcon} instance of the graphics file. Returns {@code null} if graphics file could not be loaded. - */ - public static ImageIcon getIcon(Class cls, String fileName) { - ImageIcon retVal = null; - - if (fileName == null) { - return retVal; - } - - if (cls == null) { - cls = Icons.class; - } - - try (InputStream is = cls.getResourceAsStream(fileName)) { - if (is != null) { - Image image = ImageIO.read(is); - retVal = new ImageIcon(image); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return retVal; - } - - /** - * A static method that loads a graphics file from the folder relative to the specified {@code Class} object and - * returns it as an {@code Image} instance. - * - * @param cls {@code Class} object used to to determine the root path within the Java Archive. - * @param fileName Filename of the graphics file relative to the root path. - * @return {@code Image} instance of the graphics file. Returns {@code null} if graphics file could not be loaded. - */ - public static Image getImage(Class cls, String fileName) { - Image retVal = null; - - if (fileName == null) { - return retVal; - } - - if (cls == null) { - cls = Icons.class; - } - - try (InputStream is = cls.getResourceAsStream(fileName)) { - if (is != null) { - retVal = ImageIO.read(is); - } - } catch (IOException e) { - e.printStackTrace(); - } - - return retVal; - } } diff --git a/src/org/infinity/resource/AbstractStruct.java b/src/org/infinity/resource/AbstractStruct.java index 920119d94..dee566504 100644 --- a/src/org/infinity/resource/AbstractStruct.java +++ b/src/org/infinity/resource/AbstractStruct.java @@ -42,6 +42,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.spl.SplResource; import org.infinity.search.ReferenceSearcher; +import org.infinity.util.Logger; import org.infinity.util.io.ByteBufferOutputStream; import org.infinity.util.io.StreamUtils; @@ -296,7 +297,7 @@ public ByteBuffer getDataBuffer() { try (ByteBufferOutputStream bbos = new ByteBufferOutputStream(bb)) { writeFlatFields(bbos); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } bb.position(0); return bb; @@ -378,9 +379,7 @@ public String getColumnName(int columnIndex) { public boolean isCellEditable(int row, int col) { if (col == 1) { Object o = getValueAt(row, col); - if (o instanceof InlineEditable && !(o instanceof Editable)) { - return true; - } + return o instanceof InlineEditable && !(o instanceof Editable); } return false; } @@ -824,6 +823,7 @@ public StructEntry getField(int index) { try { return fields.get(index); } catch (IndexOutOfBoundsException e) { + Logger.trace(e); } return null; } @@ -1006,8 +1006,8 @@ public ByteBuffer removeFromList(StructEntry startFromEntry, int numBytes) throw } } // discard entries - for (int i = endindex - 1; i >= startindex; i--) { - fields.remove(i); + if (endindex > startindex) { + fields.subList(startindex, endindex).clear(); } bb.position(0); return bb; @@ -1221,7 +1221,7 @@ private void fixHoles(ByteBuffer buffer) { Unknown hole = new Unknown(buffer, offset, delta, COMMON_UNUSED_BYTES); fields.add(hole); flatList.add(i, hole); - System.out.println("Hole: " + name + " off: " + Integer.toHexString(offset) + "h len: " + delta); + Logger.warn("Hole: {} off: {} h len: {}", name, Integer.toHexString(offset), delta); i++; } // Using max() as shared data regions may confuse the hole detection algorithm @@ -1229,8 +1229,7 @@ private void fixHoles(ByteBuffer buffer) { } if (endoffset < buffer.limit()) { // Does this break anything? fields.add(new Unknown(buffer, endoffset, buffer.limit() - endoffset, COMMON_UNUSED_BYTES)); - System.out.println( - "Hole: " + name + " off: " + Integer.toHexString(endoffset) + "h len: " + (buffer.limit() - endoffset)); + Logger.warn("Hole: {} off: {} h len: {}", name, Integer.toHexString(endoffset), (buffer.limit() - endoffset)); endoffset = buffer.limit(); } } diff --git a/src/org/infinity/resource/Effect.java b/src/org/infinity/resource/Effect.java index 8c3010779..8606d6918 100644 --- a/src/org/infinity/resource/Effect.java +++ b/src/org/infinity/resource/Effect.java @@ -58,7 +58,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { * @throws Exception */ public Object clone(boolean asV2) throws Exception { - StructEntry retVal = null; + final AbstractStruct retVal; if (asV2) { ByteBuffer src = getDataBuffer().order(ByteOrder.LITTLE_ENDIAN); @@ -114,7 +114,7 @@ public Object clone(boolean asV2) throws Exception { int offset = getOffset(); retVal = new Effect2(null, dst, 0, getName()); retVal.setOffset(offset); - ((AbstractStruct) retVal).realignStructOffsets(); + retVal.realignStructOffsets(); } else { retVal = clone(); } diff --git a/src/org/infinity/resource/Effect2.java b/src/org/infinity/resource/Effect2.java index 2f67f8719..f69d045d0 100644 --- a/src/org/infinity/resource/Effect2.java +++ b/src/org/infinity/resource/Effect2.java @@ -170,7 +170,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { * @throws Exception */ public Object clone(boolean asV1) throws Exception { - StructEntry retVal = null; + final AbstractStruct retVal; if (asV1) { ByteBuffer src = getDataBuffer().order(ByteOrder.LITTLE_ENDIAN); @@ -201,7 +201,7 @@ public Object clone(boolean asV1) throws Exception { int offset = getOffset(); retVal = new Effect(null, dst, 0, getName()); retVal.setOffset(offset); - ((AbstractStruct) retVal).realignStructOffsets(); + retVal.realignStructOffsets(); } else { retVal = clone(); } diff --git a/src/org/infinity/resource/Profile.java b/src/org/infinity/resource/Profile.java index 0a078e4e9..20348e325 100644 --- a/src/org/infinity/resource/Profile.java +++ b/src/org/infinity/resource/Profile.java @@ -16,7 +16,6 @@ import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -51,14 +50,14 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.key.ResourceTreeModel; import org.infinity.util.DataString; +import org.infinity.util.DebugTimer; +import org.infinity.util.Logger; import org.infinity.util.Platform; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; import org.infinity.util.io.DlcManager; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; -import org.infinity.util.io.FileWatcher; -import org.infinity.util.io.FileWatcher.FileWatchEvent; /** * Provides engine- and game-specific properties of the currently opened Infinity Engine game.
@@ -66,7 +65,7 @@ * Properties can be accessed by unique identifiers. The returned property can be of any type defined by the enum * {@link Profile.Type} or {@code null}. */ -public final class Profile implements FileWatcher.FileWatchListener { +public final class Profile { /** Supported data types for properties. */ public enum Type { /** Property data is of type {@link Boolean}. */ @@ -643,7 +642,7 @@ public static Game gameFromString(String gameName) { try { return Enum.valueOf(Game.class, gameName); } catch (IllegalArgumentException e) { - System.err.println("Unknown game type \"" + gameName + "\" specified. Falling back to \"Unknown\"."); + Logger.warn("Unknown game type \"{}\" specified. Falling back to \"Unknown\".", gameName); } } return Game.Unknown; @@ -681,11 +680,12 @@ public static boolean openGame(Path keyFile, String desc) { public static boolean openGame(Path keyFile, String desc, Game forcedGame) { try { closeGame(); + final DebugTimer timer = new DebugTimer(); instance = new Profile(keyFile, desc, forcedGame); - FileWatcher.getInstance().addFileWatchListener(instance); + Logger.info(timer.getTimerFormatted("Initializing game resources")); return true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } closeGame(); return false; @@ -1281,7 +1281,7 @@ public static List getGameBinaries(Game game, Platform.OS os) { game = getGame(); } if (os == null) { - os = Platform.getPlatform(); + os = Platform.OS.getCurrentOS(); } EnumMap> osMap = DEFAULT_GAME_BINARIES.get(game); @@ -1305,7 +1305,7 @@ public static List getGameBinaryPaths(Game game, Platform.OS os) { game = getGame(); } if (os == null) { - os = Platform.getPlatform(); + os = Platform.OS.getCurrentOS(); } List listNames = getGameBinaries(game, os); @@ -1395,6 +1395,7 @@ public void removeListDataListener(ListDataListener l) { try { game = Game.values()[list.getSelectedIndex()]; } catch (Exception e) { + Logger.trace(e); } } @@ -1418,8 +1419,6 @@ private static void closeGame() { PROPERTIES.clear(); addEntry(Key.GET_GAME_TYPE_PREVIOUS, Type.OBJECT, oldGame); initStaticProperties(); - FileWatcher.getInstance().removeFileWatchListener(instance); - FileWatcher.getInstance().reset(); instance = null; } @@ -1715,7 +1714,7 @@ private static String getLuaValue(Path file, String key, String defaultValue, bo } } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -1737,7 +1736,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception { addEntry(Key.GET_GAME_DESC, Type.STRING, desc); } - addEntry(Key.IS_FORCED_GAME, Type.BOOLEAN, Boolean.valueOf(forcedGame != null)); + addEntry(Key.IS_FORCED_GAME, Type.BOOLEAN, forcedGame != null); if (forcedGame != null) { addEntry(Key.GET_GAME_TYPE, Type.OBJECT, forcedGame); } @@ -1956,7 +1955,7 @@ && getLuaValue(FileManager.query(gameRoots, "engine.lua"), "engine_mode", "0", f // initializing list of folders containing BIFF archives List biffDirs = ResourceFactory.getBIFFDirs(); - if (biffDirs != null && !biffDirs.isEmpty()) { + if (!biffDirs.isEmpty()) { addEntry(Key.GET_GAME_BIFF_FOLDERS, Type.LIST, biffDirs); } @@ -2045,8 +2044,7 @@ private void initRootDirs() { addEntry(Key.GET_GAME_DLC_FOLDERS_AVAILABLE, Type.LIST, dlcRoots); // preparing available game root paths - List roots = new ArrayList<>(); - roots.addAll(dlcRoots); + List roots = new ArrayList<>(dlcRoots); roots.add(gameRoot); // process each root separately @@ -2074,10 +2072,6 @@ private void initRootDirs() { listRoots.add(root); }); - listRoots.forEach(path -> { - FileWatcher.getInstance().register(path, false); - }); - addEntry(Key.GET_GAME_ROOT_FOLDERS_AVAILABLE, Type.PATH, listRoots); } @@ -2098,9 +2092,6 @@ private void initExtraFolders() { pathList.addAll(list); }); - // Note: disabled because of issues on Windows systems - // pathList.forEach((path) -> { FileWatcher.getInstance().register(path, true); }); - if (getProperty(Key.GET_GAME_EXTRA_FOLDERS) != null) { updateProperty(Key.GET_GAME_EXTRA_FOLDERS, pathList); } else { @@ -2128,13 +2119,14 @@ private void initOverrides() { try { Files.createDirectory(FileManager.query(gameRoot, getOverrideFolderName().toLowerCase(Locale.ENGLISH))); } catch (Throwable t) { + Logger.trace(t); } } // putting all root folders into a list ordered by priority (highest first) List gameRoots = new ArrayList<>(); gameRoots.add(homeRoot); - dlcRoots.forEach(path -> gameRoots.add(path)); + gameRoots.addAll(dlcRoots); gameRoots.add(gameRoot); // registering override paths @@ -2220,10 +2212,6 @@ private void initOverrides() { } } - list.forEach(path -> { - FileWatcher.getInstance().register(path, false); - }); - addEntry(Key.GET_GAME_OVERRIDE_FOLDERS, Type.LIST, list); } @@ -2436,13 +2424,13 @@ private void initFeatures() { Path exe = FileManager.queryExisting(getGameRoot(), "bgmain.exe"); if (exe != null) { File exeFile = exe.toFile(); - if (exeFile != null && exeFile.length() == 7839790L) { + if (exeFile.length() == 7839790L) { try (RandomAccessFile raf = new RandomAccessFile(exeFile, "r")) { // checking key signatures final int[] sigCheckV1 = { 0x3db6d84, 0xc6004c48, 0x54464958, 0x004141de, 0xf9 }; final int[] sigCheckV2 = { 0x3db6d84, 0x34004c48, 0x54464958, 0x0041412d, 0xf9 }; - long ofs[] = { 0x40742cL, 0x40a8daL, 0x7536e7L, 0x407713L }; - int sig[] = new int[ofs.length + 1]; + long[] ofs = { 0x40742cL, 0x40a8daL, 0x7536e7L, 0x407713L }; + int[] sig = new int[ofs.length + 1]; for (int i = 0; i < ofs.length; i++) { // reading int signatures raf.seek(ofs[i]); @@ -2463,16 +2451,17 @@ private void initFeatures() { isIAv1 = Arrays.equals(sig, sigCheckV1); isIAv2 = Arrays.equals(sig, sigCheckV2); } catch (IOException e) { + Logger.trace(e); } } } } if (isIAv1) { - addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, Integer.valueOf(1)); // v5 or earlier + addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, 1); // v5 or earlier } else if (isIAv2) { - addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, Integer.valueOf(2)); // v6 or later + addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, 2); // v6 or later } else { - addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, Integer.valueOf(0)); // not installed + addEntry(Key.GET_INFINITY_ANIMATIONS, Type.INTEGER, 0); // not installed } // Add campaign-specific extra folders @@ -2572,7 +2561,7 @@ private List initDlc(Path rootDir, Path homeDir) { gameFolders.add(DataString.with("zip", rootDir.resolve("dlc"))); gameFolders.add(DataString.with("zip", rootDir)); } - if (homeDir != null && FileEx.create(homeDir).isDirectory()) { + if (FileEx.create(homeDir).isDirectory()) { gameFolders.add(DataString.with("zip", homeDir)); } @@ -2589,11 +2578,11 @@ private List initDlc(Path rootDir, Path homeDir) { list.add(dlcRoot); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } // DLCs of the same root are sorted alphabetically (in reverse order) if (!list.isEmpty()) { @@ -2651,43 +2640,6 @@ private Path validateDlc(Path file, String ext) throws IOException { } } - // --------------------- Begin Interface FileWatchListener --------------------- - - @Override - public void fileChanged(FileWatchEvent e) { - // System.out.println("Profile.fileChanged(): " + e.getKind().toString() + " - " + e.getPath()); - if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - Path path = e.getPath(); - - if (FileEx.create(path).isDirectory()) { - // Note: skipping extra folders because of issues on Windows systems - // List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); - // if (FileManager.containsPath(path, extraDirs)) { - // FileWatcher.getInstance().register(path, true); - // return; - // } - - // new override folders must be initialized first - initOverrides(); - - // checking if path is an override folder - if (FileManager.isSamePath(path, getOverrideFolders(true))) { - FileWatcher.getInstance().register(path, false); - return; - } - } - } else if (e.getKind() == StandardWatchEventKinds.ENTRY_DELETE) { - Path path = e.getPath(); - - FileWatcher.getInstance().unregister(path, true); - if (FileManager.isSamePath(path, getOverrideFolders(true))) { - initOverrides(); - } - } - } - - // --------------------- End Interface FileWatchListener --------------------- - // -------------------------- INNER CLASSES -------------------------- // Internal definition of a property entry @@ -2735,7 +2687,7 @@ public Object setData(Object newValue) { @Override public String toString() { - return String.format("%d:[%s] = %s", key, type, data); + return String.format("%s:[%s] = %s", key, type, data); } } } diff --git a/src/org/infinity/resource/ResourceFactory.java b/src/org/infinity/resource/ResourceFactory.java index eb9ae616e..3c9a341c3 100644 --- a/src/org/infinity/resource/ResourceFactory.java +++ b/src/org/infinity/resource/ResourceFactory.java @@ -20,7 +20,6 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -86,22 +85,15 @@ import org.infinity.resource.video.WbmResource; import org.infinity.resource.wed.WedResource; import org.infinity.resource.wmp.WmpResource; -import org.infinity.util.CreMapCache; -import org.infinity.util.DynamicArray; -import org.infinity.util.IdsMapCache; -import org.infinity.util.Misc; -import org.infinity.util.StaticSimpleXorDecryptor; +import org.infinity.util.*; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; -import org.infinity.util.io.FileWatcher; -import org.infinity.util.io.FileWatcher.FileWatchEvent; -import org.infinity.util.io.FileWatcher.FileWatchListener; import org.infinity.util.io.StreamUtils; /** * Handles game-specific resource access. */ -public final class ResourceFactory implements FileWatchListener { +public final class ResourceFactory { /** * Name of tree node that contains important game files that not stored in the BIF archives or override folders. */ @@ -112,7 +104,6 @@ public final class ResourceFactory implements FileWatchListener { private JFileChooser fc; private Keyfile keyfile; private ResourceTreeModel treeModel; - private Path pendingSelection; public static Keyfile getKeyfile() { if (getInstance() != null) { @@ -252,9 +243,7 @@ public static Resource getResource(ResourceEntry entry, String forcedExtension) Class cls = getResourceType(entry, forcedExtension); if (cls != null) { Constructor con = cls.getConstructor(ResourceEntry.class); - if (con != null) { - res = con.newInstance(entry); - } + res = con.newInstance(entry); } } catch (Exception e) { if (NearInfinity.getInstance() != null && !BrowserMenuBar.getInstance().getOptions().ignoreReadErrors()) { @@ -264,8 +253,7 @@ public static Resource getResource(ResourceEntry entry, String forcedExtension) final String msg = String.format("Error reading %s @ %s - %s", entry, entry.getActualPath(), e); NearInfinity.getInstance().getStatusBar().setMessage(msg); } - System.err.println("Error reading " + entry); - e.printStackTrace(); + Logger.error(e, "Error reading {}", entry); } return res; } @@ -319,7 +307,7 @@ public static ResourceEntry getResourceIcon(ResourceEntry entry, String forcedEx // forward exception to caller throw e; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -412,7 +400,7 @@ public static Class detectResourceType(ResourceEntry entry) cls = getResourceType(entry, "WBM"); } else if (data.length > 6 && data[3] == 0 && data[4] == 0x78) { // just guessing... cls = getResourceType(entry, "PVRZ"); - } else if (data.length > 4 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47) { + } else if ((data[0] & 0xff) == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47) { cls = getResourceType(entry, "PNG"); } else if (DynamicArray.getInt(data, 0) == 0x00000100) { // wild guess... cls = getResourceType(entry, "TTF"); @@ -423,7 +411,7 @@ public static Class detectResourceType(ResourceEntry entry) throw new Exception(entry.getResourceName() + ": Unable to determine resource type"); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return cls; @@ -434,7 +422,7 @@ public static void exportResource(ResourceEntry entry, Component parent) { try { getInstance().exportResourceInternal(entry, parent, null); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(parent, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } @@ -445,7 +433,7 @@ public static void exportResource(ResourceEntry entry, ByteBuffer buffer, String try { getInstance().exportResourceInternal(entry, buffer, filename, parent, null); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(parent, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } @@ -533,11 +521,9 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search // checking default override folder list if (entry == null) { List extraFolders = Profile.getOverrideFolders(searchExtraDirs); - if (extraFolders != null) { - Path file = FileManager.query(extraFolders, resourceName); - if (file != null && FileEx.create(file).isFile()) { - entry = new FileResourceEntry(file); - } + Path file = FileManager.query(extraFolders, resourceName); + if (file != null && FileEx.create(file).isFile()) { + entry = new FileResourceEntry(file); } } @@ -709,7 +695,7 @@ public static boolean saveResourceAs(Resource resource, Component parent) { /** * If {@code output} is not {@code null}, shows confirmation dialog for saving resource. If user accepts saving then - * resource will be saved if it implements {@link Writable} + * resource will be saved if it implements {@link Writeable} * * @param resource Resource that must be saved * @param entry Entry that represents resource. Must not be {@code null} @@ -731,7 +717,7 @@ public static void closeResource(Resource resource, ResourceEntry entry, JCompon /** * If {@code output} is not {@code null}, shows confirmation dialog for saving resource. If user accepts saving then - * resource will be saved if it implements {@link Writable} + * resource will be saved if it implements {@link Writeable} * * @param resource Resource that must be saved * @param output Path of the saved resource. If {@code null} method do nothing @@ -743,7 +729,7 @@ public static void closeResource(Resource resource, ResourceEntry entry, JCompon */ public static void closeResource(Resource resource, Path output, JComponent parent) throws Exception { if (output != null) { - final String options[] = { "Save changes", "Discard changes", "Cancel" }; + final String[] options = { "Save changes", "Discard changes", "Cancel" }; final int result = JOptionPane.showOptionDialog(parent, "Save changes to " + output + '?', "Resource changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { @@ -769,9 +755,9 @@ public static List getAvailableGameLanguages() { && entry.getFileName().toString().matches("[a-z]{2}_[A-Z]{2}") && FileEx.create(FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME))) .isFile()))) { - dstream.forEach(path -> list.add(path)); + dstream.forEach(list::add); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -807,7 +793,7 @@ public static String autodetectGameLanguage(Path iniFile) { } } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error parsing " + iniFile.getFileName() + ". Using language defaults.", "Error", JOptionPane.ERROR_MESSAGE); @@ -828,8 +814,7 @@ static Path getHomeRoot(boolean allowMissing) { // fallback solution String userPrefix = System.getProperty("user.home"); userPath = null; - String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); - if (osName.contains("windows")) { + if (Platform.IS_WINDOWS) { try { Process p = Runtime.getRuntime().exec( "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); @@ -843,15 +828,15 @@ static Path getHomeRoot(boolean allowMissing) { userPrefix = splitted[splitted.length - 1]; userPath = FileManager.resolve(userPrefix, EE_DIR); } catch (Throwable t) { - t.printStackTrace(); + Logger.error(t); return null; } - } else if (osName.contains("mac") || osName.contains("darwin")) { + } else if (Platform.IS_MACOS) { userPath = FileManager.resolve(FileManager.resolve(userPrefix, "Documents", EE_DIR)); - } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("bsd")) { + } else if (Platform.IS_UNIX) { userPath = FileManager.resolve(FileManager.resolve(userPrefix, ".local", "share", EE_DIR)); } - if (allowMissing || (userPath != null && FileEx.create(userPath).isDirectory())) { + if (userPath != null && FileEx.create(userPath).isDirectory()) { return userPath; } } @@ -871,7 +856,7 @@ static List getBIFFDirs() { } List dlcList = Profile.getProperty(Profile.Key.GET_GAME_DLC_FOLDERS_AVAILABLE); if (dlcList != null) { - dlcList.forEach(path -> dirList.add(path)); + dirList.addAll(dlcList); } dirList.add(Profile.getGameRoot()); } else { @@ -913,7 +898,7 @@ static List getBIFFDirs() { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); dirList.clear(); } } @@ -1002,16 +987,14 @@ private ResourceFactory(Path keyFile) { } loadResourcesInternal(); - FileWatcher.getInstance().addFileWatchListener(this); } catch (Exception e) { JOptionPane.showMessageDialog(null, "No Infinity Engine game found", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } /** Cleans up resources. */ private void close() { - FileWatcher.getInstance().removeFileWatchListener(this); // nothing to do yet... } @@ -1064,7 +1047,7 @@ private Path getExportFileDialogInternal(Component parent, String fileName, bool if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { path = fc.getSelectedFile().toPath(); if (!forceOverwrite && FileEx.create(path).exists()) { - final String options[] = { "Overwrite", "Cancel" }; + final String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(parent, path + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) { path = null; @@ -1085,9 +1068,6 @@ private void exportResourceInternal(ResourceEntry entry, ByteBuffer buffer, Stri // exporting resource if (output != null) { try { - if (output.getFileName().toString().equalsIgnoreCase(entry.getResourceName())) { - setPendingSelection(output); - } try (OutputStream os = StreamUtils.getOutputStream(output, true)) { StreamUtils.writeBytes(os, buffer); } @@ -1096,7 +1076,6 @@ private void exportResourceInternal(ResourceEntry entry, ByteBuffer buffer, Stri JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e) { - setPendingSelection(null); throw new Exception("Error while exporting " + entry); } } @@ -1298,25 +1277,6 @@ private void registerResourceInternal(Path resource, boolean autoselect) { } } - private boolean isPendingSelection(Path path, boolean autoRemove) { - boolean retVal = (pendingSelection == path); - - if (pendingSelection != null && path != null) { - retVal = path.equals(pendingSelection); - if (retVal && autoRemove) { - pendingSelection = null; - } - } - - return retVal; - } - - private void setPendingSelection(Path path) { - if (BrowserMenuBar.isInstantiated() && BrowserMenuBar.getInstance().getOptions().getMonitorFileChanges()) { - pendingSelection = path; - } - } - private void loadResourcesInternal() throws Exception { treeModel = new ResourceTreeModel(); @@ -1365,8 +1325,6 @@ private void loadResourcesInternal() throws Exception { /** * Registers in the resourse tree all special game resources that are not stored in the override folders or BIF * archives - * - * @param folderName Folder in the resource tree under which register files */ private void loadSpecialResources() { final List roots = Profile.getRootFolders(); @@ -1538,7 +1496,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) { } if (FileEx.create(outFile).exists()) { - String options[] = { "Overwrite", "Cancel" }; + String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(NearInfinity.getInstance(), outFile + " exists. Overwrite?", "Confirm overwrite " + outFile, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) { @@ -1553,13 +1511,12 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) { } catch (IOException e) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Could not create " + outPath + ".", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return; } } try { - setPendingSelection(outFile); ByteBuffer bb = entry.getResourceBuffer(); try (OutputStream os = StreamUtils.getOutputStream(outFile, true)) { WritableByteChannel wbc = Channels.newChannel(os); @@ -1578,7 +1535,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) { } catch (Exception e) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error while copying " + entry, "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } @@ -1617,7 +1574,7 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o } catch (IOException e) { JOptionPane.showMessageDialog(parent, "Unable to create override folder.", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return false; } } @@ -1628,13 +1585,13 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o // extra step for saving resources from a read-only medium (such as DLCs) if (!FileManager.isDefaultFileSystem(outPath)) { outPath = Profile.getGameRoot().resolve(outPath.subpath(0, outPath.getNameCount()).toString()); - if (outPath != null && !FileEx.create(outPath.getParent()).exists()) { + if (!FileEx.create(outPath.getParent()).exists()) { try { Files.createDirectories(outPath.getParent()); } catch (IOException e) { JOptionPane.showMessageDialog(parent, "Unable to create folder: " + outPath.getParent(), "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return false; } } @@ -1644,7 +1601,7 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o if (FileEx.create(outPath).exists()) { outPath = outPath.toAbsolutePath(); - String options[] = { "Overwrite", "Cancel" }; + String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(parent, outPath + " exists. Overwrite?", "Save resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) == 0) { if (BrowserMenuBar.getInstance().getOptions().backupOnSave()) { @@ -1657,7 +1614,7 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o Files.move(outPath, bakPath); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } else { @@ -1669,7 +1626,7 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o ((Writeable) resource).write(os); } catch (IOException e) { JOptionPane.showMessageDialog(parent, "Error while saving " + entry, "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return false; } @@ -1694,18 +1651,4 @@ private boolean saveResourceInternal(Resource resource, Component parent, Path o } return true; } - - // --------------------- Begin Interface FileWatchListener --------------------- - - @Override - public void fileChanged(FileWatchEvent e) { - // System.out.println("ResourceFactory.fileChanged(): " + e.getKind().toString() + " - " + e.getPath()); - if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - registerResourceInternal(e.getPath(), isPendingSelection(e.getPath(), true)); - } else if (e.getKind() == StandardWatchEventKinds.ENTRY_DELETE) { - unregisterResourceInternal(e.getPath()); - } - } - - // --------------------- End Interface FileWatchListener --------------------- } diff --git a/src/org/infinity/resource/StructEntry.java b/src/org/infinity/resource/StructEntry.java index d2e0fbf25..caffe1587 100644 --- a/src/org/infinity/resource/StructEntry.java +++ b/src/org/infinity/resource/StructEntry.java @@ -27,7 +27,7 @@ public interface StructEntry extends Comparable, Cloneable, Writeab /** * Returns byte count of serialized value of this object. * - * @return Count of bytes that needed to store this object in it's {@link Writable natural format} + * @return Count of bytes that needed to store this object in it's {@link Writeable natural format} */ int getSize(); diff --git a/src/org/infinity/resource/StructureFactory.java b/src/org/infinity/resource/StructureFactory.java index 104ecc815..ecb852a51 100644 --- a/src/org/infinity/resource/StructureFactory.java +++ b/src/org/infinity/resource/StructureFactory.java @@ -20,6 +20,7 @@ import org.infinity.gui.NewChrSettings; import org.infinity.gui.NewProSettings; import org.infinity.gui.NewResSettings; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.ResourceStructure; import org.infinity.util.io.FileEx; @@ -108,7 +109,7 @@ public void newResource(ResType type, Window parent) { if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { Path outFile = fc.getSelectedFile().toPath(); if (FileEx.create(outFile).exists()) { - final String options[] = { "Overwrite", "Cancel" }; + final String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(parent, outFile + "exists. Overwrite?", title, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) { return; @@ -142,7 +143,7 @@ public void newResource(ResType type, Window parent) { } catch (Exception e) { JOptionPane.showMessageDialog(parent, "Error while creating " + outFile.getFileName(), title, JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } } @@ -491,7 +492,7 @@ private ResourceStructure createRES(Window parent) throws StructureException { if (dlg.isAccepted()) { String text = dlg.getConfig().getText(); final ResourceStructure structRes = new ResourceStructure(); - if (text.length() > 0) { + if (!text.isEmpty()) { structRes.add(ResourceStructure.ID_STRING, text); } @@ -677,7 +678,7 @@ private String extractFileName(String fileName) { // returns filename without extension private String extractFileBase(String fileName) { String name = extractFileName(fileName); - if (name.length() > 0) { + if (!name.isEmpty()) { int idx = name.lastIndexOf('.'); if (idx >= 0) { return name.substring(0, idx); diff --git a/src/org/infinity/resource/are/AreResource.java b/src/org/infinity/resource/are/AreResource.java index 0811c3416..4cd743228 100644 --- a/src/org/infinity/resource/are/AreResource.java +++ b/src/org/infinity/resource/are/AreResource.java @@ -11,6 +11,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; @@ -49,6 +50,7 @@ import org.infinity.resource.wmp.WmpResource; import org.infinity.search.SearchOptions; import org.infinity.util.IdsMapCache; +import org.infinity.util.Logger; import org.infinity.util.LuaEntry; import org.infinity.util.LuaParser; import org.infinity.util.StringTable; @@ -212,7 +214,7 @@ private static void initMapNames(boolean force) { LuaEntry entries = LuaParser.Parse(luaFiles, "cheatAreas\\w*", false); mapNames = createMapNamesFromLua(entries); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else if (ResourceFactory.resourceExists("MAPNAME.2DA")) { // PST map names @@ -265,8 +267,9 @@ private static HashMap createMapNamesFromTable() { int strref = Integer.parseInt(table.get(row, 1)); desc = StringTable.getStringRef(strref); } catch (NumberFormatException e) { + Logger.warn(e); } - if (resref != table.getDefaultValue() && desc != null) { + if (!Objects.equals(resref, table.getDefaultValue()) && desc != null) { retVal.put(resref.toUpperCase(), desc); } } @@ -305,7 +308,7 @@ private static HashMap createMapNamesFromWorldmap() { } if (StringTable.isValidStringRef(strref)) { String name = StringTable.getStringRef(strref); - if (name != null && !name.isEmpty()) { + if (!name.isEmpty()) { retVal.put(resref, name); } } @@ -402,19 +405,33 @@ public void close() throws Exception { public AddRemovable[] getPrototypes() throws Exception { if (Profile.getEngine() == Profile.Engine.PST) { return new AddRemovable[] { new Actor(), new ITEPoint(), new SpawnPoint(), new Entrance(), new Container(), - new Ambient(), new Variable(), new Door(), new Animation(), new TiledObject(), new AutomapNotePST() }; + new Ambient(), new Variable(), new Door(), new Animation(), new TiledObject(), new AutomapNotePST(), + new Song(), new RestSpawn() }; } else if (Profile.getEngine() == Profile.Engine.BG2 || Profile.isEnhancedEdition()) { return new AddRemovable[] { new Actor(), new ITEPoint(), new SpawnPoint(), new Entrance(), new Container(), new Ambient(), new Variable(), new Door(), new Animation(), new TiledObject(), new AutomapNote(), - new ProTrap() }; + new ProTrap(), new Song(), new RestSpawn() }; } else { return new AddRemovable[] { new Actor(), new ITEPoint(), new SpawnPoint(), new Entrance(), new Container(), - new Ambient(), new Variable(), new Door(), new Animation(), new TiledObject() }; + new Ambient(), new Variable(), new Door(), new Animation(), new TiledObject(), new Song(), new RestSpawn() }; } } @Override public AddRemovable confirmAddEntry(AddRemovable entry) throws Exception { + if (entry instanceof Song) { + // only one instance allowed + final IsNumeric songOffset = (IsNumeric) getAttribute(ARE_OFFSET_SONGS); + if (songOffset != null && songOffset.getValue() > 0 && getAttribute(songOffset.getValue(), Song.class) != null) { + throw new Exception(Song.ARE_SONGS + " entry already exists."); + } + } else if (entry instanceof RestSpawn) { + // only one instance allowed + final IsNumeric restOffset = (IsNumeric) getAttribute(ARE_OFFSET_REST_ENCOUNTERS); + if (restOffset != null && restOffset.getValue() > 0 && getAttribute(restOffset.getValue(), RestSpawn.class) != null) { + throw new Exception(RestSpawn.ARE_RESTSPAWN + " entry already exists."); + } + } return entry; } @@ -995,7 +1012,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = are.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -1005,7 +1022,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = SearchOptions.ARE_AreaScript; o = searchOptions.getOption(key); StructEntry struct = are.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchResourceRef(struct, o, false); + retVal = SearchOptions.Utils.matchResourceRef(struct, o, false); } if (retVal) { @@ -1018,7 +1035,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear found |= SearchOptions.Utils.matchResourceRef(struct, o, false); } } - retVal &= found || (o == null); + retVal = found || (o == null); } if (retVal) { @@ -1031,18 +1048,18 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear found |= SearchOptions.Utils.matchResourceRef(struct, o, false); } } - retVal &= found || (o == null); + retVal = found || o == null; } if (retVal) { key = SearchOptions.ARE_Container_Item_Item; o = searchOptions.getOption(key); boolean found = false; - for (Item[] item : items) { - for (int idx2 = 0; idx2 < item.length; idx2++) { - if (item[idx2] != null) { - StructEntry struct = item[idx2].getAttribute(SearchOptions.getResourceName(key), false); - found |= SearchOptions.Utils.matchResourceRef(struct, o, false); + for (final Item[] item : items) { + for (final Item value : item) { + if (value != null) { + StructEntry struct = value.getAttribute(SearchOptions.getResourceName(key), false); + found = SearchOptions.Utils.matchResourceRef(struct, o, false); } if (found) { break; @@ -1052,7 +1069,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } keyList = new String[] { SearchOptions.ARE_Custom1, SearchOptions.ARE_Custom2, SearchOptions.ARE_Custom3, @@ -1061,7 +1078,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(are, o); + retVal = SearchOptions.Utils.matchCustomFilter(are, o); } else { break; } @@ -1069,6 +1086,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.warn(e); } } return false; diff --git a/src/org/infinity/resource/are/RestSpawn.java b/src/org/infinity/resource/are/RestSpawn.java index fd7eb4dd0..34800a22e 100644 --- a/src/org/infinity/resource/are/RestSpawn.java +++ b/src/org/infinity/resource/are/RestSpawn.java @@ -13,9 +13,11 @@ import org.infinity.datatype.TextString; import org.infinity.datatype.Unknown; import org.infinity.resource.AbstractStruct; +import org.infinity.resource.AddRemovable; import org.infinity.resource.Profile; +import org.infinity.util.io.StreamUtils; -public final class RestSpawn extends AbstractStruct { +public final class RestSpawn extends AbstractStruct implements AddRemovable { // ARE/Rest Encounters-specific field labels public static final String ARE_RESTSPAWN = "Rest encounters"; public static final String ARE_RESTSPAWN_NAME = "Name"; @@ -34,10 +36,19 @@ public final class RestSpawn extends AbstractStruct { public static final String ARE_RESTSPAWN_PROBABILITY_DAY_HOUR = "Hourly probability (day)"; public static final String ARE_RESTSPAWN_PROBABILITY_NIGHT_HOUR = "Hourly probability (night)"; + public RestSpawn() throws Exception { + super(null, ARE_RESTSPAWN, StreamUtils.getByteBuffer(228), 0); + } + RestSpawn(AbstractStruct superStruct, ByteBuffer buffer, int offset) throws Exception { super(superStruct, ARE_RESTSPAWN, buffer, offset); } + @Override + public boolean canRemove() { + return false; + } + @Override public int read(ByteBuffer buffer, int offset) throws Exception { final boolean isIWD = (Profile.getEngine() == Profile.Engine.IWD || Profile.getEngine() == Profile.Engine.IWD2); diff --git a/src/org/infinity/resource/are/Song.java b/src/org/infinity/resource/are/Song.java index e32f21caa..268ad6dae 100644 --- a/src/org/infinity/resource/are/Song.java +++ b/src/org/infinity/resource/are/Song.java @@ -14,10 +14,12 @@ import org.infinity.datatype.TableBitmap; import org.infinity.datatype.Unknown; import org.infinity.resource.AbstractStruct; +import org.infinity.resource.AddRemovable; import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; +import org.infinity.util.io.StreamUtils; -public final class Song extends AbstractStruct { // implements AddRemovable +public final class Song extends AbstractStruct implements AddRemovable { // implements AddRemovable // ARE/Songs-specific field labels public static final String ARE_SONGS = "Songs"; public static final String ARE_SONGS_DAY = "Day song"; @@ -38,10 +40,19 @@ public final class Song extends AbstractStruct { // implements AddRemovable public static final String ARE_SONGS_AMBIENT_VOLUME_NIGHT = "Main ambient volume (night)"; public static final String ARE_SONGS_REVERB = "Reverb"; + public Song() throws Exception { + super(null, ARE_SONGS, StreamUtils.getByteBuffer(144), 0); + } + Song(AreResource are, ByteBuffer buffer, int offset) throws Exception { super(are, ARE_SONGS, buffer, offset); } + @Override + public boolean canRemove() { + return false; + } + @Override public int read(ByteBuffer buffer, int offset) throws Exception { addField(new Song2daBitmap(buffer, offset, 4, ARE_SONGS_DAY)); diff --git a/src/org/infinity/resource/are/viewer/AreaViewer.java b/src/org/infinity/resource/are/viewer/AreaViewer.java index c868b2d9c..49cd68307 100644 --- a/src/org/infinity/resource/are/viewer/AreaViewer.java +++ b/src/org/infinity/resource/are/viewer/AreaViewer.java @@ -115,6 +115,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.wed.Overlay; import org.infinity.resource.wed.WedResource; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -209,6 +210,7 @@ public static boolean isValid(AreResource are) { return true; } } catch (Exception e) { + Logger.warn(e); } } } @@ -238,7 +240,7 @@ protected Void doInBackground() throws Exception { try { init(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -695,7 +697,7 @@ private void init() { try { initGuiSettings(); } catch (OutOfMemoryError e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(this, "Not enough memory to load area!", "Error", JOptionPane.ERROR_MESSAGE); throw e; } @@ -1397,7 +1399,7 @@ private boolean updateItemPopup(Point canvasCoords) { int lenPrefix = sb.length(); int lenMsg = item.getToolTipText().length(); if (lenPrefix + lenMsg > MaxLen) { - sb.append(item.getToolTipText().substring(0, MaxLen - lenPrefix)); + sb.append(item.getToolTipText(), 0, MaxLen - lenPrefix); sb.append("..."); } else { sb.append(item.getToolTipText()); @@ -1774,7 +1776,7 @@ private void updateRealActors() { Settings.ShowActorSprites = ViewerConstants.ANIM_SHOW_NONE; } else if (cbLayerRealActor[0].isSelected() && !cbLayerRealActor[1].isSelected()) { Settings.ShowActorSprites = ViewerConstants.ANIM_SHOW_STILL; - } else if (!cbLayerRealActor[0].isSelected() && cbLayerRealActor[1].isSelected()) { + } else if (!cbLayerRealActor[0].isSelected()) { Settings.ShowActorSprites = ViewerConstants.ANIM_SHOW_ANIMATED; } } @@ -1813,7 +1815,7 @@ private void updateRealAnimation() { Settings.ShowRealAnimations = ViewerConstants.ANIM_SHOW_NONE; } else if (cbLayerRealAnimation[0].isSelected() && !cbLayerRealAnimation[1].isSelected()) { Settings.ShowRealAnimations = ViewerConstants.ANIM_SHOW_STILL; - } else if (!cbLayerRealAnimation[0].isSelected() && cbLayerRealAnimation[1].isSelected()) { + } else if (!cbLayerRealAnimation[0].isSelected()) { Settings.ShowRealAnimations = ViewerConstants.ANIM_SHOW_ANIMATED; } } @@ -2100,7 +2102,7 @@ private void updateTreeNode(Component c) { /** Recursive function to find the node containing c. */ private TreeNode getTreeNodeOf(TreeNode node, Component c) { - if (node != null && node instanceof DefaultMutableTreeNode && c != null) { + if (node instanceof DefaultMutableTreeNode && c != null) { if (((DefaultMutableTreeNode) node).getUserObject() == c) { return node; } @@ -2229,7 +2231,7 @@ private void exportMap() { bRet = ImageIO.write(dstImage, "png", os); dstImage.flush(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { releaseProgressMonitor(); WindowBlocker.blockWindow(AreaViewer.this, false); @@ -2402,7 +2404,7 @@ public void actionPerformed(ActionEvent event) { try { setZoomFactor(Settings.ITEM_ZOOM_FACTOR[cbZoomLevel.getSelectedIndex()], previousZoomFactor); } catch (OutOfMemoryError e) { - e.printStackTrace(); + Logger.error(e); cbZoomLevel.hidePopup(); WindowBlocker.blockWindow(AreaViewer.this, false); String msg = "Not enough memory to set selected zoom level.\n" @@ -2554,7 +2556,7 @@ public void mouseWheelMoved(MouseWheelEvent event) { try { setZoomFactor(zoom, previousZoomFactor); } catch (OutOfMemoryError e) { - e.printStackTrace(); + Logger.error(e); cbZoomLevel.hidePopup(); WindowBlocker.blockWindow(AreaViewer.this, false); String msg = "Not enough memory to set selected zoom level.\n" @@ -2592,19 +2594,17 @@ public void stateChanged(ChangeEvent event) { if (event.getSource() == pDayTime) { if (workerLoadMap == null) { // loading map in a separate thread - if (workerLoadMap == null) { - blocker = new WindowBlocker(AreaViewer.this); - blocker.setBlocked(true); - workerLoadMap = new SwingWorker() { - @Override - protected Void doInBackground() throws Exception { - setHour(pDayTime.getHour()); - return null; - } - }; - workerLoadMap.addPropertyChangeListener(this); - workerLoadMap.execute(); - } + blocker = new WindowBlocker(AreaViewer.this); + blocker.setBlocked(true); + workerLoadMap = new SwingWorker() { + @Override + protected Void doInBackground() throws Exception { + setHour(pDayTime.getHour()); + return null; + } + }; + workerLoadMap.addPropertyChangeListener(this); + workerLoadMap.execute(); } } } @@ -2878,7 +2878,7 @@ public boolean closeWed(int dayNight, boolean allowCancel) { } int optionIndex = allowCancel ? 1 : 0; int optionType = allowCancel ? JOptionPane.YES_NO_CANCEL_OPTION : JOptionPane.YES_NO_OPTION; - String options[][] = { { "Save changes", "Discard changes" }, + String[][] options = { { "Save changes", "Discard changes" }, { "Save changes", "Discard changes", "Cancel" } }; int result = JOptionPane.showOptionDialog(parent, "Save changes to " + output + '?', "Resource changed", optionType, JOptionPane.WARNING_MESSAGE, null, options[optionIndex], options[optionIndex][0]); @@ -2918,7 +2918,7 @@ public void reloadWed(int dayNight) { wedItem[dayNight].setVisible(false); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else { wed[dayNight] = wed[ViewerConstants.AREA_DAY]; @@ -2931,7 +2931,7 @@ public void reloadWed(int dayNight) { try { wed[dayNight] = new WedResource(ResourceFactory.getResourceEntry(wedNameNight)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -3130,7 +3130,7 @@ public void removeChangeListener(ChangeListener l) { */ @SuppressWarnings("unused") public ChangeListener[] getChangeListeners() { - return listeners.toArray(new ChangeListener[listeners.size()]); + return listeners.toArray(new ChangeListener[0]); } @Override diff --git a/src/org/infinity/resource/are/viewer/LayerActor.java b/src/org/infinity/resource/are/viewer/LayerActor.java index 7146e8a45..8c0fd0533 100644 --- a/src/org/infinity/resource/are/viewer/LayerActor.java +++ b/src/org/infinity/resource/are/viewer/LayerActor.java @@ -33,6 +33,7 @@ import org.infinity.util.IniMapCache; import org.infinity.util.IniMapEntry; import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; /** * Manages actor layer objects. @@ -83,7 +84,7 @@ protected void loadLayer() { setListeners(obj); objectList.add(obj); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -112,16 +113,16 @@ protected void loadLayer() { if (res instanceof GamResource) { GamResource gamRes = (GamResource) res; List npcList = gamRes.getFields(PartyNPC.class); - for (int i = 0, cnt = npcList.size(); i < cnt; i++) { - PartyNPC npc = (PartyNPC) npcList.get(i); - String area = ((IsTextual) npc.getAttribute(PartyNPC.GAM_NPC_CURRENT_AREA)).getText(); + for (final StructEntry structEntry : npcList) { + final PartyNPC npc = (PartyNPC) structEntry; + final String area = ((IsTextual) npc.getAttribute(PartyNPC.GAM_NPC_CURRENT_AREA)).getText(); if (areEntry.getResourceRef().equalsIgnoreCase(area)) { try { - LayerObjectActor loa = new LayerObjectGlobalActor(gamRes, npc); + final LayerObjectActor loa = new LayerObjectGlobalActor(gamRes, npc); setListeners(loa); objectList.add(loa); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -191,7 +192,7 @@ public Void doInBackground() { progress.setProgress(i + 1); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { progress.close(); if (blocker != null) { diff --git a/src/org/infinity/resource/are/viewer/LayerAnimation.java b/src/org/infinity/resource/are/viewer/LayerAnimation.java index b868fcf5a..f8634d673 100644 --- a/src/org/infinity/resource/are/viewer/LayerAnimation.java +++ b/src/org/infinity/resource/are/viewer/LayerAnimation.java @@ -7,7 +7,6 @@ import static org.infinity.resource.are.AreResource.ARE_NUM_ANIMATIONS; import static org.infinity.resource.are.AreResource.ARE_OFFSET_ANIMATIONS; -import java.util.Collections; import java.util.List; import org.infinity.datatype.Flag; @@ -44,7 +43,7 @@ protected void loadLayer() { a -> new LayerObjectAnimation(parent, a)); // sorting entries (animations not flagged as "draw as background" come first) - Collections.sort(getLayerObjects(), (o1, o2) -> { + getLayerObjects().sort((o1, o2) -> { boolean isBackground1, isBackground2; try { isBackground1 = ((Flag) ((Animation) o1.getViewable()).getAttribute(Animation.ARE_ANIMATION_APPEARANCE)) diff --git a/src/org/infinity/resource/are/viewer/LayerAutomap.java b/src/org/infinity/resource/are/viewer/LayerAutomap.java index 497a7821e..f7e0d6a8b 100644 --- a/src/org/infinity/resource/are/viewer/LayerAutomap.java +++ b/src/org/infinity/resource/are/viewer/LayerAutomap.java @@ -7,10 +7,16 @@ import static org.infinity.resource.are.AreResource.ARE_NUM_AUTOMAP_NOTES; import static org.infinity.resource.are.AreResource.ARE_OFFSET_AUTOMAP_NOTES; +import java.util.List; + import org.infinity.resource.Profile; import org.infinity.resource.are.AreResource; import org.infinity.resource.are.AutomapNote; import org.infinity.resource.are.AutomapNotePST; +import org.infinity.util.IniMap; +import org.infinity.util.IniMapCache; +import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; /** * Manages automap notes layer objects (both PST-specific and generic types). @@ -33,6 +39,10 @@ public boolean isTorment() { @Override protected void loadLayer() { if (isTorment()) { + // loading predefined entries + loadPredefinedAutoNotes(parent); + + // loading user-defined entries loadLayerItems(ARE_OFFSET_AUTOMAP_NOTES, ARE_NUM_AUTOMAP_NOTES, AutomapNotePST.class, n -> new LayerObjectAutomapPST(parent, n)); } else { @@ -46,4 +56,60 @@ public String getAvailability() { int cnt = getLayerObjectCount(); return String.format(AVAILABLE_FMT, cnt); } + + /** + * (PST only) Loads predefined automap note definitions from "AUTONOTE.INI" for the specified map. + * + * @param are Area to load automap notes for. + */ + private void loadPredefinedAutoNotes(AreResource are) { + if (are == null) { + return; + } + + // loading autonote section for this area + final IniMap ini = IniMapCache.get("autonote.ini"); + if (ini != null) { + final String areResref = are.getResourceEntry().getResourceRef(); + IniMapSection iniSection = null; + for (final IniMapSection s : ini) { + if (s.getName().equalsIgnoreCase(areResref)) { + final int count = s.getAsInteger("count", 0); + if (count > 0) { + iniSection = s; + } + break; + } + } + + // loading automap notes + if (iniSection != null) { + final List objectList = getLayerObjects(); + int count = 0; + try { + count = iniSection.getAsInteger("count", 0); + } catch (IllegalArgumentException e) { + Logger.warn(e); + } + final double scale = 32.0 / 3.0; + for (int i = 0; i < count; i++) { + try { + final String keyStrref = "text" + (i + 1); + final String keyX = "xPos" + (i + 1); + final String keyY = "yPos" + (i + 1); + final int strref = iniSection.getAsInteger(keyStrref, -1); + final int x = (int) (iniSection.getAsInteger(keyX, -1) * scale); + final int y = (int) (iniSection.getAsInteger(keyY, -1) * scale); + if (strref >= 0 && x >= 0 && y >= 0) { + final LayerObjectAutomapPSTIni obj = new LayerObjectAutomapPSTIni(iniSection, i); + setListeners(obj); + objectList.add(obj); + } + } catch (IllegalArgumentException e) { + Logger.error(e); + } + } + } + } + } } diff --git a/src/org/infinity/resource/are/viewer/LayerDoor.java b/src/org/infinity/resource/are/viewer/LayerDoor.java index 76785fd05..116afea87 100644 --- a/src/org/infinity/resource/are/viewer/LayerDoor.java +++ b/src/org/infinity/resource/are/viewer/LayerDoor.java @@ -10,6 +10,7 @@ import org.infinity.gui.layeritem.AbstractLayerItem; import org.infinity.resource.are.AreResource; import org.infinity.resource.are.Door; +import org.infinity.util.Logger; /** * Manages door layer objects. @@ -55,13 +56,11 @@ public void setLayerVisible(boolean visible) { items = obj.getLayerItems(ViewerConstants.LAYER_ITEM_ICON); for (final AbstractLayerItem item : items) { - switch (item.getId()) { - case LAYER_ICONS_TARGET: - item.setVisible(isLayerVisible(LAYER_ICONS_TARGET) && isLayerEnabled(LAYER_ICONS_TARGET)); - break; - default: - item.setVisible(false); - System.out.println("Unknown layer id: " + item.getId()); + if (item.getId() == LAYER_ICONS_TARGET) { + item.setVisible(isLayerVisible(LAYER_ICONS_TARGET) && isLayerEnabled(LAYER_ICONS_TARGET)); + } else { + item.setVisible(false); + Logger.info("Unknown layer id: {}", item.getId()); } } }); diff --git a/src/org/infinity/resource/are/viewer/LayerManager.java b/src/org/infinity/resource/are/viewer/LayerManager.java index b2a0dbf86..3d0bb772f 100644 --- a/src/org/infinity/resource/are/viewer/LayerManager.java +++ b/src/org/infinity/resource/are/viewer/LayerManager.java @@ -10,6 +10,7 @@ import org.infinity.resource.are.AreResource; import org.infinity.resource.are.viewer.ViewerConstants.LayerType; import org.infinity.resource.wed.WedResource; +import org.infinity.util.Logger; /** * Manages all layer objects of a single ARE map. @@ -253,7 +254,7 @@ public void setSchedule(int schedule) { */ public boolean isScheduled(LayerObject obj) { if (obj != null) { - return !isScheduleEnabled() || (isScheduleEnabled() && obj.isScheduled(getSchedule())); + return !isScheduleEnabled() || obj.isScheduled(getSchedule()); } return false; } @@ -601,7 +602,7 @@ private void init(AreResource are, WedResource wed, boolean forced) { loadLayer(layer, forced || wedChanged); break; default: - System.err.println(String.format("Unsupported layer type: %s", layer.toString())); + Logger.warn("Unsupported layer type: {}", layer); } } } @@ -753,7 +754,7 @@ private int loadLayer(LayerType layer, boolean forced) { break; } default: - System.err.println(String.format("Unsupported layer type: %s", layer.toString())); + Logger.warn("Unsupported layer type: {}", layer); } } return retVal; diff --git a/src/org/infinity/resource/are/viewer/LayerObjectActor.java b/src/org/infinity/resource/are/viewer/LayerObjectActor.java index 8bfb72f56..ef56b251c 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectActor.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectActor.java @@ -305,7 +305,7 @@ protected static Sequence getMatchingSequence(SpriteDecoder decoder, Sequence[] sequences = Sequence.values(); } - if (decoder == null || sequences.length == 0) { + if (decoder == null) { return retVal; } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAmbient.java b/src/org/infinity/resource/are/viewer/LayerObjectAmbient.java index 8bd53c5a2..c2e028392 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAmbient.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAmbient.java @@ -22,6 +22,7 @@ import org.infinity.resource.are.Ambient; import org.infinity.resource.are.AreResource; import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Ambient Sound and Ambient Sound Range @@ -71,7 +72,7 @@ public LayerObjectAmbient(AreResource parent, Ambient ambient) { msg = ambient.getAttribute(Ambient.ARE_AMBIENT_NAME).toString(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAnimation.java b/src/org/infinity/resource/are/viewer/LayerObjectAnimation.java index b53ec5252..d5049b944 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAnimation.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAnimation.java @@ -27,6 +27,7 @@ import org.infinity.resource.graphics.PseudoBamDecoder; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; /** @@ -169,7 +170,7 @@ public LayerObjectAnimation(AreResource parent, Animation anim) { animation.setStartFrame(skippedFrames); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons @@ -306,7 +307,7 @@ private static int[] getExternalPalette(ResourceRef bmpRef) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return new int[0]; diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAreActor.java b/src/org/infinity/resource/are/viewer/LayerObjectAreActor.java index da664290b..b442bd1b4 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAreActor.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAreActor.java @@ -23,6 +23,7 @@ import org.infinity.resource.are.viewer.icon.ViewerIcons; import org.infinity.resource.cre.CreResource; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Actor @@ -79,7 +80,7 @@ public LayerObjectAreActor(AreResource parent, Actor actor) { ea = ((IsNumeric) cre.getAttribute(CreResource.CRE_ALLEGIANCE)).getValue(); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } this.cre = cre; @@ -142,7 +143,7 @@ public synchronized void loadAnimation() { item.setAnimation(sprite); item.setComposite(Settings.UseActorAccurateBlending ? sprite.getDecoder().getComposite() : null); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java index e17606e29..5568978b8 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java @@ -17,6 +17,7 @@ import org.infinity.resource.are.viewer.icon.ViewerIcons; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.to.TohResource; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; /** @@ -60,7 +61,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomapPST.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomapPST.java index 2e198c240..8463bdbb4 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAutomapPST.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomapPST.java @@ -14,9 +14,10 @@ import org.infinity.resource.are.AreResource; import org.infinity.resource.are.AutomapNotePST; import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.util.Logger; /** - * Handles specific layer type: ARE/Automap Note (PST-specific) + * Handles specific layer type: ARE/Automap Note (PST-specific, user-defined) */ public class LayerObjectAutomapPST extends LayerObject { private static final Image[] ICONS = { ViewerIcons.ICON_ITM_AUTOMAP_1.getIcon().getImage(), @@ -42,7 +43,7 @@ public LayerObjectAutomapPST(AreResource parent, AutomapNotePST note) { location.y = (int) (y.getValue() * MAP_SCALE); msg = note.getAttribute(AutomapNotePST.ARE_AUTOMAP_TEXT).toString(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomapPSTIni.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomapPSTIni.java new file mode 100644 index 000000000..643535e00 --- /dev/null +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomapPSTIni.java @@ -0,0 +1,119 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.resource.are.viewer; + +import java.awt.Image; +import java.awt.Point; +import java.util.Objects; + +import org.infinity.gui.layeritem.AbstractLayerItem; +import org.infinity.gui.layeritem.IconLayerItem; +import org.infinity.resource.ResourceFactory; +import org.infinity.resource.Viewable; +import org.infinity.resource.are.AutomapNotePST; +import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.resource.text.PlainTextResource; +import org.infinity.util.IniMapEntry; +import org.infinity.util.IniMapSection; +import org.infinity.util.StringTable; + +/** + * Handles specific layer type: ARE/Automap Note (PST-specific, predefined) + */ +public class LayerObjectAutomapPSTIni extends LayerObject { + private static final Image[] ICONS = { ViewerIcons.ICON_ITM_AUTOMAP_1.getIcon().getImage(), + ViewerIcons.ICON_ITM_AUTOMAP_2.getIcon().getImage() }; + + private static final Point CENTER = new Point(26, 26); + + private static final double MAP_SCALE = 32.0 / 3.0; // scaling factor for MOS to TIS coordinates + + private static final String AUTONOTE_INI = "autonote.ini"; + + private final Point location = new Point(); + + private final PlainTextResource ini; + private final IniMapSection areData; + private final int noteIndex; + private final IconLayerItem item; + + public LayerObjectAutomapPSTIni(IniMapSection areData, int noteIndex) throws IllegalArgumentException { + super("Automap", AutomapNotePST.class, null); + try { + this.ini = new PlainTextResource(ResourceFactory.getResourceEntry(AUTONOTE_INI)); + } catch (Exception e) { + throw new IllegalArgumentException("Could not load autonote.ini"); + } + this.areData = Objects.requireNonNull(areData); + this.noteIndex = noteIndex; + this.item = initLayerItem(); + } + + @Override + public Viewable getViewable() { + return ini; + } + + @Override + public AbstractLayerItem[] getLayerItems(int type) { + if (type == 0 && item != null) { + return new AbstractLayerItem[] { item }; + } + return new AbstractLayerItem[0]; + } + + @Override + public AbstractLayerItem[] getLayerItems() { + return new AbstractLayerItem[] { item }; + } + + @Override + public void update(double zoomFactor) { + item.setItemLocation((int) (location.x * zoomFactor + (zoomFactor / 2.0)), + (int) (location.y * zoomFactor + (zoomFactor / 2.0))); + } + + private IconLayerItem initLayerItem() throws IllegalArgumentException { + IconLayerItem retVal = null; + + final int count = areData.getAsInteger("count", 0); + if (noteIndex < 0 || noteIndex >= count) { + throw new IllegalArgumentException("Automap note definition out of bounds: index=" + noteIndex + ", count=" + count); + } + + final String keyStrref = "text" + (noteIndex + 1); + final String keyX = "xPos" + (noteIndex + 1); + final String keyY = "yPos" + (noteIndex + 1); + final int strref = areData.getAsInteger(keyStrref, -1); + final int x = (int) (areData.getAsInteger(keyX, -1) * MAP_SCALE); + final int y = (int) (areData.getAsInteger(keyY, -1) * MAP_SCALE); + if (x < 0 || y < 0) { + throw new IllegalArgumentException("Invalid automap note location: x=" + x + ", y=" + y); + } + final String label = StringTable.getStringRef(strref); + + location.x = x; + location.y = y; + + final IniMapEntry areDataEntry = areData.getEntry(keyStrref); + if (areDataEntry != null) { + ini.setHighlightedLine(areDataEntry.getLine() + 1); + } else { + ini.setHighlightedLine(areData.getLine() + 1); + } + + // Using cached icons + final Image[] icons = getIcons(ICONS); + + retVal = new IconLayerItem(ini, label, icons[0], CENTER); + retVal.setLabelEnabled(Settings.ShowLabelMapNotes); + retVal.setName(getCategory()); + retVal.setToolTipText(label); + retVal.setImage(AbstractLayerItem.ItemState.HIGHLIGHTED, icons[1]); + retVal.setVisible(isVisible()); + + return retVal; + } +} diff --git a/src/org/infinity/resource/are/viewer/LayerObjectContainer.java b/src/org/infinity/resource/are/viewer/LayerObjectContainer.java index 1bb11059c..3edc8b6aa 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectContainer.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectContainer.java @@ -21,6 +21,7 @@ import org.infinity.resource.are.Container; import org.infinity.resource.are.viewer.icon.ViewerIcons; import org.infinity.resource.vertex.Vertex; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Container @@ -73,7 +74,7 @@ public LayerObjectContainer(AreResource parent, Container container) { launchPoint.x = ((IsNumeric) container.getAttribute(Container.ARE_CONTAINER_LAUNCH_POINT_X)).getValue(); launchPoint.y = ((IsNumeric) container.getAttribute(Container.ARE_CONTAINER_LAUNCH_POINT_Y)).getValue(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } final Polygon poly = createPolygon(shapeCoords, 1.0); final Rectangle bounds = normalizePolygon(poly); diff --git a/src/org/infinity/resource/are/viewer/LayerObjectDoor.java b/src/org/infinity/resource/are/viewer/LayerObjectDoor.java index aaee4035c..12c88d7aa 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectDoor.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectDoor.java @@ -13,6 +13,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; import org.infinity.datatype.Flag; @@ -27,6 +28,7 @@ import org.infinity.resource.are.viewer.icon.ViewerIcons; import org.infinity.resource.vertex.ClosedVertex; import org.infinity.resource.vertex.OpenVertex; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Door @@ -62,9 +64,9 @@ public LayerObjectDoor(AreResource parent, Door door) { super("Door", Door.class, parent); this.door = door; final DoorInfo doorOpen = new DoorInfo(); - doorMap.put(Integer.valueOf(ViewerConstants.DOOR_OPEN), doorOpen); + doorMap.put(ViewerConstants.DOOR_OPEN, doorOpen); final DoorInfo doorClosed = new DoorInfo(); - doorMap.put(Integer.valueOf(ViewerConstants.DOOR_CLOSED), doorClosed); + doorMap.put(ViewerConstants.DOOR_CLOSED, doorClosed); String name = null; try { String attr = getAttributes(this.door); @@ -88,7 +90,7 @@ public LayerObjectDoor(AreResource parent, Door door) { launchPoint.x = ((IsNumeric) door.getAttribute(Door.ARE_DOOR_LAUNCH_POINT_X)).getValue(); launchPoint.y = ((IsNumeric) door.getAttribute(Door.ARE_DOOR_LAUNCH_POINT_Y)).getValue(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } for (final DoorInfo info: getDoors()) { @@ -273,11 +275,11 @@ private Collection getDoors() { } private Collection getDoorItems() { - return doorMap.values().stream().map(di -> di.getItem()).filter(item -> item != null).collect(Collectors.toList()); + return doorMap.values().stream().map(DoorInfo::getItem).filter(Objects::nonNull).collect(Collectors.toList()); } private DoorInfo getDoor(int id) { - return doorMap.get(Integer.valueOf(id)); + return doorMap.get(id); } // ----------------------------- INNER CLASSES ----------------------------- diff --git a/src/org/infinity/resource/are/viewer/LayerObjectDoorCells.java b/src/org/infinity/resource/are/viewer/LayerObjectDoorCells.java index a94971112..73a3260a4 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectDoorCells.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectDoorCells.java @@ -9,9 +9,11 @@ import java.awt.Polygon; import java.awt.Rectangle; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; import org.infinity.datatype.IsNumeric; @@ -23,6 +25,7 @@ import org.infinity.resource.are.Door; import org.infinity.resource.vertex.ClosedVertexImpeded; import org.infinity.resource.vertex.OpenVertexImpeded; +import org.infinity.util.Logger; /** * Handles specific layer subtype: ARE/Door blocked cells @@ -35,17 +38,16 @@ public class LayerObjectDoorCells extends LayerObject { private final Door door; /** - * @param category - * @param classType * @param parent + * @param door */ public LayerObjectDoorCells(AreResource parent, Door door) { super("Door", Door.class, parent); this.door = door; final DoorInfo doorOpen = new DoorInfo(); - doorMap.put(Integer.valueOf(ViewerConstants.DOOR_OPEN), doorOpen); + doorMap.put(ViewerConstants.DOOR_OPEN, doorOpen); final DoorInfo doorClosed = new DoorInfo(); - doorMap.put(Integer.valueOf(ViewerConstants.DOOR_CLOSED), doorClosed); + doorMap.put(ViewerConstants.DOOR_CLOSED, doorClosed); try { String attr = LayerObjectDoor.getAttributes(this.door); final String name = door.getAttribute(Door.ARE_DOOR_NAME).toString(); @@ -63,7 +65,7 @@ public LayerObjectDoorCells(AreResource parent, Door door) { itemCoords = createCellPolygons(loadVertices(door, cOfs, 0, cNum, ClosedVertexImpeded.class)); doorClosed.setCoords(itemCoords); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } for (final DoorInfo info: getDoors()) { @@ -113,18 +115,14 @@ public AbstractLayerItem[] getLayerItems(int type) { final DoorInfo info = getDoor(ViewerConstants.DOOR_OPEN); if (info != null && info.getCellItems() != null) { final ShapedLayerItem[] items = info.getCellItems(); - for (int i = 0; i < items.length; i++) { - list.add(items[i]); - } + list.addAll(Arrays.asList(items)); } } if (isClosed) { final DoorInfo info = getDoor(ViewerConstants.DOOR_CLOSED); if (info != null && info.getCellItems() != null) { final ShapedLayerItem[] items = info.getCellItems(); - for (int i = 0; i < items.length; i++) { - list.add(items[i]); - } + list.addAll(Arrays.asList(items)); } } @@ -137,9 +135,7 @@ public AbstractLayerItem[] getLayerItems() { for (final AbstractLayerItem[] items : getDoorItems()) { if (items != null) { - for (int i = 0; i < items.length; i++) { - list.add(items[i]); - } + list.addAll(Arrays.asList(items)); } } @@ -168,11 +164,11 @@ private Collection getDoors() { } private Collection getDoorItems() { - return doorMap.values().stream().map(ci -> ci.getCellItems()).filter(cell -> cell != null).collect(Collectors.toList()); + return doorMap.values().stream().map(DoorInfo::getCellItems).filter(Objects::nonNull).collect(Collectors.toList()); } private DoorInfo getDoor(int id) { - return doorMap.get(Integer.valueOf(id)); + return doorMap.get(id); } /** @@ -191,10 +187,10 @@ private Point[][] createCellPolygons(Point[] cells) { if (cells != null && cells.length > 0) { final int cw = 16; // search map cell width, in pixels final int ch = 12; // search map cell height, in pixels - for (int i = 0; i < cells.length; i++) { - final int x = cells[i].x * cw; - final int y = cells[i].y * ch; - polys.add(new Point[] { new Point(x, y), new Point(x + cw, y), new Point(x + cw, y + ch), new Point(x, y + ch) }); + for (Point cell : cells) { + final int x = cell.x * cw; + final int y = cell.y * ch; + polys.add(new Point[]{new Point(x, y), new Point(x + cw, y), new Point(x + cw, y + ch), new Point(x, y + ch)}); } } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectDoorPoly.java b/src/org/infinity/resource/are/viewer/LayerObjectDoorPoly.java index b5430e23c..8f6e6926d 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectDoorPoly.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectDoorPoly.java @@ -23,6 +23,7 @@ import org.infinity.resource.vertex.Vertex; import org.infinity.resource.wed.Door; import org.infinity.resource.wed.WedResource; +import org.infinity.util.Logger; /** * Handles specific layer type: WED/Door Polygon. @@ -63,7 +64,7 @@ public LayerObjectDoorPoly(WedResource parent, Door doorPoly) { // processing closed door polygons fillData(ofsClosed, numClosed, numOpen, info); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); if (info == null) { info = new String[count]; } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectEntrance.java b/src/org/infinity/resource/are/viewer/LayerObjectEntrance.java index 23cbee50a..ad9b73e7c 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectEntrance.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectEntrance.java @@ -15,6 +15,7 @@ import org.infinity.resource.are.AreResource; import org.infinity.resource.are.Entrance; import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Entrance @@ -46,7 +47,7 @@ public LayerObjectEntrance(AreResource parent, Entrance entrance) { final String name = entrance.getAttribute(Entrance.ARE_ENTRANCE_NAME).toString(); msg = String.format("%s (%s)", name, AbstractStruct.OPTION_ORIENTATION[o]); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectGlobalActor.java b/src/org/infinity/resource/are/viewer/LayerObjectGlobalActor.java index 5175c1d19..8516a54ed 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectGlobalActor.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectGlobalActor.java @@ -23,6 +23,7 @@ import org.infinity.resource.gam.GamResource; import org.infinity.resource.gam.PartyNPC; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * Handles specific layer type: global GAM/Actor @@ -119,7 +120,7 @@ public void loadAnimation() { item.setAnimation(sprite); item.setComposite(Settings.UseActorAccurateBlending ? sprite.getDecoder().getComposite() : null); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectIniActor.java b/src/org/infinity/resource/are/viewer/LayerObjectIniActor.java index 2b0a6d639..4801aa3ff 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectIniActor.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectIniActor.java @@ -21,6 +21,7 @@ import org.infinity.resource.text.PlainTextResource; import org.infinity.util.IniMapEntry; import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; /** * Handles specific layer type: INI/Actor @@ -71,7 +72,7 @@ public LayerObjectIniActor(PlainTextResource ini, IniMapSection creData, int cre try { cre = new CreResource(creEntry); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw new IllegalArgumentException(creData.getName() + ": Invalid CRE resource", e); } @@ -151,12 +152,12 @@ private int[] getCreatureLocation() throws IllegalArgumentException { } String[] items = IniMapEntry.splitValues(entryPoint.getValue(), IniMapEntry.REGEX_POSITION); - if (items == null || creIndex >= items.length) { + if (creIndex >= items.length) { throw new IllegalArgumentException(creData.getName() + ": Invalid spawn point index (" + creIndex + ")"); } int[] pos = IniMapEntry.splitPositionValue(items[creIndex]); - if (pos == null || pos.length < 2) { + if (pos.length < 2) { throw new IllegalArgumentException(creData.getName() + ": Invalid spawn point value #" + creIndex); } @@ -179,7 +180,7 @@ public synchronized void loadAnimation() { item.setAnimation(sprite); item.setComposite(Settings.UseActorAccurateBlending ? sprite.getDecoder().getComposite() : null); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/are/viewer/LayerObjectProTrap.java b/src/org/infinity/resource/are/viewer/LayerObjectProTrap.java index 721e7b88d..63c0446f3 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectProTrap.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectProTrap.java @@ -14,6 +14,7 @@ import org.infinity.resource.are.AreResource; import org.infinity.resource.are.ProTrap; import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Projectile Trap @@ -49,7 +50,7 @@ public LayerObjectProTrap(AreResource parent, ProTrap trap) { msg += " (friendly)"; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectRegion.java b/src/org/infinity/resource/are/viewer/LayerObjectRegion.java index 64ad68065..c6a2786c5 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectRegion.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectRegion.java @@ -24,6 +24,7 @@ import org.infinity.resource.are.ITEPoint; import org.infinity.resource.are.viewer.icon.ViewerIcons; import org.infinity.resource.vertex.Vertex; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Region @@ -112,7 +113,7 @@ ITEPoint.TYPE_ARRAY[type], getAttributes(), } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } final Polygon poly = createPolygon(shapeCoords, 1.0); final Rectangle bounds = normalizePolygon(poly); diff --git a/src/org/infinity/resource/are/viewer/LayerObjectSpawnPoint.java b/src/org/infinity/resource/are/viewer/LayerObjectSpawnPoint.java index da58e3381..88b49c8b9 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectSpawnPoint.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectSpawnPoint.java @@ -15,6 +15,7 @@ import org.infinity.resource.are.AreResource; import org.infinity.resource.are.SpawnPoint; import org.infinity.resource.are.viewer.icon.ViewerIcons; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Spawn Point @@ -43,7 +44,7 @@ public LayerObjectSpawnPoint(AreResource parent, SpawnPoint sp) { scheduleFlags = ((Flag) sp.getAttribute(SpawnPoint.ARE_SPAWN_ACTIVE_AT)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } // Using cached icons diff --git a/src/org/infinity/resource/are/viewer/LayerObjectTransition.java b/src/org/infinity/resource/are/viewer/LayerObjectTransition.java index 6d63f86c0..27130eef7 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectTransition.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectTransition.java @@ -13,6 +13,7 @@ import org.infinity.gui.layeritem.ShapedLayerItem; import org.infinity.resource.Viewable; import org.infinity.resource.are.AreResource; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Map transition @@ -46,7 +47,7 @@ public LayerObjectTransition(AreResource parent, AreResource destination, int ed msg = String.format("Transition to %s", ref); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } item = new ShapedLayerItem(destination, msg, null); diff --git a/src/org/infinity/resource/are/viewer/LayerObjectWallPoly.java b/src/org/infinity/resource/are/viewer/LayerObjectWallPoly.java index 148569a1d..9086163ad 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectWallPoly.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectWallPoly.java @@ -17,6 +17,7 @@ import org.infinity.resource.vertex.Vertex; import org.infinity.resource.wed.WallPolygon; import org.infinity.resource.wed.WedResource; +import org.infinity.util.Logger; /** * Handles specific layer type: ARE/Wall Polygon @@ -45,7 +46,7 @@ public LayerObjectWallPoly(WedResource parent, WallPolygon wall) { int startIdx = flags.isFlagSet(2) ? 2 : 0; // skipping first two vertices for "hovering walls" shapeCoords = loadVertices(wall, vOfs, startIdx, vNum - startIdx, Vertex.class); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } final Polygon poly = createPolygon(shapeCoords, 1.0); final Rectangle bounds = normalizePolygon(poly); diff --git a/src/org/infinity/resource/are/viewer/LayerTransition.java b/src/org/infinity/resource/are/viewer/LayerTransition.java index a7c580d94..c6b81ea18 100644 --- a/src/org/infinity/resource/are/viewer/LayerTransition.java +++ b/src/org/infinity/resource/are/viewer/LayerTransition.java @@ -9,6 +9,7 @@ import org.infinity.datatype.ResourceRef; import org.infinity.resource.ResourceFactory; import org.infinity.resource.are.AreResource; +import org.infinity.util.Logger; /** * Manages map transition layer objects. @@ -33,7 +34,7 @@ protected void loadLayer() { setListeners(obj); list.add(obj); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/are/viewer/Settings.java b/src/org/infinity/resource/are/viewer/Settings.java index 1a1686108..801f17367 100644 --- a/src/org/infinity/resource/are/viewer/Settings.java +++ b/src/org/infinity/resource/are/viewer/Settings.java @@ -12,6 +12,7 @@ import org.infinity.resource.are.viewer.ViewerConstants.LayerStackingType; import org.infinity.resource.are.viewer.ViewerConstants.LayerType; +import org.infinity.util.Logger; /** * Manages global area viewer settings. @@ -307,7 +308,7 @@ public static void storeSettings(boolean force) { try { prefs.flush(); } catch (BackingStoreException e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/resource/are/viewer/SettingsDialog.java b/src/org/infinity/resource/are/viewer/SettingsDialog.java index 7c64a29ab..765357fc8 100644 --- a/src/org/infinity/resource/are/viewer/SettingsDialog.java +++ b/src/org/infinity/resource/are/viewer/SettingsDialog.java @@ -224,8 +224,8 @@ private void resetDialogSettings() { cbQualityMap.setSelectedIndex(Settings.getDefaultInterpolationMap()); cbQualityAnim.setSelectedIndex(Settings.getDefaultInterpolationAnim()); - sOverlaysFps.setValue(Double.valueOf(Settings.getDefaultFrameRateOverlays())); - sAnimationsFps.setValue(Double.valueOf(Settings.getDefaultFrameRateAnimations())); + sOverlaysFps.setValue(Settings.getDefaultFrameRateOverlays()); + sAnimationsFps.setValue(Settings.getDefaultFrameRateAnimations()); sMiniMapAlpha.setValue((int) (Settings.getDefaultMiniMapAlpha() * 100.0)); diff --git a/src/org/infinity/resource/are/viewer/SharedResourceCache.java b/src/org/infinity/resource/are/viewer/SharedResourceCache.java index 28d42efae..9eeed2ab6 100644 --- a/src/org/infinity/resource/are/viewer/SharedResourceCache.java +++ b/src/org/infinity/resource/are/viewer/SharedResourceCache.java @@ -6,7 +6,6 @@ import java.util.EnumMap; import java.util.HashMap; -import java.util.Iterator; /** * A global storage class that caches data objects of supported types associated with a unique key. @@ -164,9 +163,7 @@ public static Object getKey(Type type, Object data) { if (type == null) { throw new NullPointerException("type is null"); } - Iterator iter = TABLES.get(type).keySet().iterator(); - while (iter.hasNext()) { - Object key = iter.next(); + for (final Object key : TABLES.get(type).keySet()) { DataWrapper dw = TABLES.get(type).get(key); if ((dw.getData() == null && data == null) || (dw.getData() != null && dw.getData().equals(data))) { return key; @@ -189,10 +186,8 @@ public static int getReferenceCount(Type type, Object key) { if (key == null) { throw new NullPointerException("key is null"); } - if (key != null) { - if (TABLES.get(type).containsKey(key)) { - return TABLES.get(type).get(key).getRefCount(); - } + if (TABLES.get(type).containsKey(key)) { + return TABLES.get(type).get(key).getRefCount(); } return 0; } @@ -205,7 +200,7 @@ private SharedResourceCache() { /** Wrapper for data objects that supports reference counting. */ private static class DataWrapper { - private Object data; + private final Object data; private int refCount; /** diff --git a/src/org/infinity/resource/are/viewer/TilesetChangeEvent.java b/src/org/infinity/resource/are/viewer/TilesetChangeEvent.java index bbcb1cb6d..99d97c4e0 100644 --- a/src/org/infinity/resource/are/viewer/TilesetChangeEvent.java +++ b/src/org/infinity/resource/are/viewer/TilesetChangeEvent.java @@ -7,10 +7,10 @@ import java.util.EventObject; public class TilesetChangeEvent extends EventObject { - private boolean mapChanged; - private boolean appearanceChanged; - private boolean overlayChanged; - private boolean doorStatechanged; + private final boolean mapChanged; + private final boolean appearanceChanged; + private final boolean overlayChanged; + private final boolean doorStatechanged; /** * Constructs a TilesetChangeEvent object. diff --git a/src/org/infinity/resource/are/viewer/TilesetRenderer.java b/src/org/infinity/resource/are/viewer/TilesetRenderer.java index 001a19e79..48e627506 100644 --- a/src/org/infinity/resource/are/viewer/TilesetRenderer.java +++ b/src/org/infinity/resource/are/viewer/TilesetRenderer.java @@ -31,6 +31,7 @@ import org.infinity.resource.wed.Overlay; import org.infinity.resource.wed.Tilemap; import org.infinity.resource.wed.WedResource; +import org.infinity.util.Logger; /** * Specialized renderer for drawing tileset-based graphics data. @@ -121,7 +122,7 @@ public TilesetRenderer(int overlayTransparency, WedResource wed) { */ public void addChangeListener(TilesetChangeListener listener) { if (listener != null) { - if (listChangeListener.indexOf(listener) < 0) { + if (!listChangeListener.contains(listener)) { listChangeListener.add(listener); } } @@ -133,7 +134,7 @@ public void addChangeListener(TilesetChangeListener listener) { * @return All ChangeListeners added or an empty array. */ public TilesetChangeListener[] getChangeListeners() { - return (TilesetChangeListener[]) listChangeListener.toArray(); + return listChangeListener.toArray(new TilesetChangeListener[0]); } /** @@ -725,7 +726,7 @@ private void updateDisplay(boolean forced) { // VolatileImage objects may lose their content under specific circumstances if (!forced && getImage() != null && getImage() instanceof VolatileImage) { - forced |= ((VolatileImage) getImage()).contentsLost(); + forced = ((VolatileImage) getImage()).contentsLost(); } if (hasChangedMap || hasChangedAppearance || forced) { @@ -761,11 +762,11 @@ private boolean hasOverlay(int ovlIdx) { // Draws a grid on the map with the specified parameters private void drawGrid(Graphics g, double gridWidth, double gridHeight, Color color) { if (g == null) { - System.err.println("TilesetRenderer.drawGrid: Graphics argument is null"); + Logger.warn("TilesetRenderer.drawGrid: Graphics argument is null"); return; } if (color == null) { - System.err.println("TilesetRenderer.drawGrid: Color argument is null"); + Logger.warn("TilesetRenderer.drawGrid: Color argument is null"); return; } final double gridWidthZoomed = gridWidth * zoomFactor; @@ -942,7 +943,7 @@ private void drawTileBlended(int[] primaryTile, int[] secondaryTile, int[] overl // draws the specified tile into the target graphics buffer private synchronized void drawTile(Tile tile, boolean isDoorTile) { if (tile != null) { - boolean isDoorClosed = (Profile.getEngine() == Profile.Engine.PST) ? !isClosed : isClosed; + boolean isDoorClosed = (Profile.getEngine() == Profile.Engine.PST) != isClosed; int[] target = ((DataBufferInt) workingTile.getRaster().getDataBuffer()).getData(); if (overlaysEnabled && tile.hasOverlay() && hasOverlay(tile.getOverlayIndex())) { // overlayed tile @@ -965,7 +966,7 @@ private synchronized void drawTile(Tile tile, boolean isDoorTile) { if (tileIdx < listTilesets.get(0).listTileData.size()) { srcSec = listTilesets.get(0).listTileData.get(tileIdx); } else { - System.err.println("Invalid tile index: " + tileIdx + " of " + listTilesets.get(0).listTileData.size()); + Logger.warn("Invalid tile index: {} of {}", tileIdx, listTilesets.get(0).listTileData.size()); } } @@ -1116,7 +1117,7 @@ public Tileset(WedResource wed, Overlay ovl) { public void advanceTileFrame() { if (hasAnimatedTiles) { - listTiles.forEach(tile -> tile.advancePrimaryIndex()); + listTiles.forEach(Tile::advancePrimaryIndex); } } @@ -1156,7 +1157,7 @@ private void init(WedResource wed, Overlay ovl) { decoder.close(); decoder = null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return; } } @@ -1210,8 +1211,7 @@ private void init(WedResource wed, Overlay ovl) { } // grouping overlayed tiles for faster access - for (int i = 0, size = listTiles.size(); i < size; i++) { - Tile tile = listTiles.get(i); + for (Tile tile : listTiles) { if (tile.getFlags() > 0) { listOverlayTiles.add(tile); } @@ -1231,7 +1231,7 @@ private ResourceEntry getTisResource(WedResource wed, Overlay ovl) { if (wed != null && ovl != null) { String tisName = ((ResourceRef) ovl.getAttribute(Overlay.WED_OVERLAY_TILESET)).getResourceName() .toUpperCase(Locale.ENGLISH); - if (tisName == null || "None".equalsIgnoreCase(tisName)) { + if ("None".equalsIgnoreCase(tisName)) { tisName = ""; } if (!tisName.isEmpty()) { @@ -1264,12 +1264,14 @@ private ResourceEntry getTisResource(WedResource wed, Overlay ovl) { // Stores tilemap information only (no graphics data) private static class Tile { - private int tileIdx2; // (start) indices of primary and secondary tiles - private int[] tileIdx; // tile indices for primary and secondary tiles - private int tileCount; // number of primary tiles, currently selected tile + private final int tileIdx2; // (start) indices of primary and secondary tiles + private final int[] tileIdx; // tile indices for primary and secondary tiles + private final int tileCount; // number of primary tiles, currently selected tile private int curTile; // number of primary tiles, currently selected tile - private int x, y, flags; // (x, y) as pixel coordinates, flags defines overlay usage - private boolean isTisV1; + private final int x; // (x, y) as pixel coordinates + private final int y; // (x, y) as pixel coordinates + private final int flags; // flags defines overlay usage + private final boolean isTisV1; public Tile(int x, int y, int tileCount, int[] index, int index2, int flags, boolean isTisV1) { if (tileCount < 0) { @@ -1374,7 +1376,7 @@ public int getOverlayIndex() { private static class DoorInfo { // private String name; // door info structure name // private boolean isClosed; // indicates the door state for the specified list of tile indices - private int[] indices; // list of tilemap indices used for the door + private final int[] indices; // list of tilemap indices used for the door public DoorInfo(String name, boolean isClosed, int[] indices) { // this.name = (name != null) ? name : ""; diff --git a/src/org/infinity/resource/are/viewer/ViewerConstants.java b/src/org/infinity/resource/are/viewer/ViewerConstants.java index b5f52246d..61df2b7e1 100644 --- a/src/org/infinity/resource/are/viewer/ViewerConstants.java +++ b/src/org/infinity/resource/are/viewer/ViewerConstants.java @@ -87,7 +87,7 @@ public String getLabel() { } // Flags that identify the different control sections in the sidebar - public static final int SIDEBAR_VISUALSTATE = 1 << 0; + public static final int SIDEBAR_VISUALSTATE = 1; public static final int SIDEBAR_LAYERS = 1 << 1; public static final int SIDEBAR_MINIMAPS = 1 << 2; @@ -131,7 +131,7 @@ public String getLabel() { public static final int ANIM_SHOW_ANIMATED = 2; // The layer item types used (LayerObjectContainer, LayerObjectDoor, LayerObjectRegion) - public static final int LAYER_ITEM_POLY = 1 << 0; + public static final int LAYER_ITEM_POLY = 1; public static final int LAYER_ITEM_ICON = 1 << 1; public static final int LAYER_ITEM_ANY = LAYER_ITEM_POLY | LAYER_ITEM_ICON; @@ -141,12 +141,12 @@ public String getLabel() { public static final int DOOR_ANY = DOOR_OPEN | DOOR_CLOSED; // The layer item types used (LayerObjectAmbient) - public static final int AMBIENT_ITEM_ICON = 1 << 0; + public static final int AMBIENT_ITEM_ICON = 1; public static final int AMBIENT_ITEM_RANGE = 1 << 1; public static final int AMBIENT_ITEM_ANY = AMBIENT_ITEM_ICON | AMBIENT_ITEM_RANGE; // The ambient sound type - public static final int AMBIENT_TYPE_GLOBAL = 1 << 0; + public static final int AMBIENT_TYPE_GLOBAL = 1; public static final int AMBIENT_TYPE_LOCAL = 1 << 1; public static final int AMBIENT_TYPE_ALL = AMBIENT_TYPE_GLOBAL | AMBIENT_TYPE_LOCAL; diff --git a/src/org/infinity/resource/are/viewer/icon/ViewerIcons.java b/src/org/infinity/resource/are/viewer/icon/ViewerIcons.java index 8511929df..762e5b3f0 100644 --- a/src/org/infinity/resource/are/viewer/icon/ViewerIcons.java +++ b/src/org/infinity/resource/are/viewer/icon/ViewerIcons.java @@ -6,7 +6,7 @@ import javax.swing.ImageIcon; -import org.infinity.icon.Icons; +import org.infinity.resource.graphics.ColorConvert; /** A dummy class used as reference for determining the current package name. */ public enum ViewerIcons { @@ -107,7 +107,7 @@ private ViewerIcons(String fileName) { /** Returns the {@code ImageIcon} instance of the enum object. */ public ImageIcon getIcon() { if (icon == null) { - icon = Icons.getIcon(ViewerIcons.class, fileName); + icon = ColorConvert.loadAppIcon(ViewerIcons.class, fileName); if (icon == null) { throw new NullPointerException("Icon is null"); } diff --git a/src/org/infinity/resource/bcs/BafResource.java b/src/org/infinity/resource/bcs/BafResource.java index a11c32527..483395ce3 100644 --- a/src/org/infinity/resource/bcs/BafResource.java +++ b/src/org/infinity/resource/bcs/BafResource.java @@ -54,6 +54,7 @@ import org.infinity.resource.Writeable; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.TextResourceSearcher; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StaticSimpleXorDecryptor; import org.infinity.util.io.StreamUtils; @@ -76,13 +77,14 @@ public class BafResource implements TextResource, Writeable, Closeable, ItemList private final ButtonPanel bpSource = new ButtonPanel(); private final ButtonPanel bpCode = new ButtonPanel(); + private final String text; + private JTabbedPane tabbedPane; private JMenuItem iFindAll; private JMenuItem iFindThis; private JPanel panel; private InfinityTextArea codeText; private ScriptTextArea sourceText; - private String text; private boolean sourceChanged = false; public BafResource(ResourceEntry entry) throws Exception { @@ -238,6 +240,7 @@ public void highlightText(int linenr, String highlightText) { } highlightText(startOfs, endOfs); } catch (BadLocationException ble) { + Logger.warn(ble); } } @@ -248,6 +251,7 @@ public void highlightText(int startOfs, int endOfs) { sourceText.moveCaretPosition(endOfs); sourceText.getCaret().setSelectionVisible(true); } catch (IllegalArgumentException e) { + Logger.warn(e); } } @@ -374,10 +378,10 @@ private void compile() { sourceText.clearGutterIcons(); bpmErrors.setText("Errors (" + errorMap.size() + ")..."); bpmWarnings.setText("Warnings (" + warningMap.size() + ")..."); - if (errorMap.size() == 0) { + if (errorMap.isEmpty()) { bpmErrors.setEnabled(false); } else { - JMenuItem errorItems[] = new JMenuItem[errorMap.size()]; + JMenuItem[] errorItems = new JMenuItem[errorMap.size()]; int counter = 0; for (final ScriptMessage sm : errorMap) { sourceText.setLineError(sm.getLine(), sm.getMessage(), false); @@ -389,7 +393,7 @@ private void compile() { if (warningMap.isEmpty()) { bpmWarnings.setEnabled(false); } else { - JMenuItem warningItems[] = new JMenuItem[warningMap.size()]; + JMenuItem[] warningItems = new JMenuItem[warningMap.size()]; int counter = 0; for (final ScriptMessage sm : warningMap) { sourceText.setLineWarning(sm.getLine(), sm.getMessage(), false); @@ -403,7 +407,7 @@ private void compile() { try { decompiler.decompile(); Set uses = decompiler.getResourcesUsed(); - JMenuItem usesItems[] = new JMenuItem[uses.size()]; + JMenuItem[] usesItems = new JMenuItem[uses.size()]; int usesIndex = 0; for (final ResourceEntry usesEntry : uses) { if (usesEntry.getSearchString() != null) { @@ -416,7 +420,7 @@ private void compile() { bpmUses.setMenuItems(usesItems); bpmUses.setEnabled(usesItems.length > 0); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -429,11 +433,11 @@ private void decompile() { try { sourceText.setText(decompiler.getSource()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } sourceText.setCaretPosition(0); Set uses = decompiler.getResourcesUsed(); - JMenuItem usesItems[] = new JMenuItem[uses.size()]; + JMenuItem[] usesItems = new JMenuItem[uses.size()]; int usesIndex = 0; for (final ResourceEntry usesEntry : uses) { if (usesEntry.getSearchString() != null) { @@ -454,7 +458,7 @@ private void save(boolean interactive) { final JButton bSaveAs = (JButton) buttonPanel.getControlByType(ButtonPanel.Control.SAVE_AS); final ButtonPopupMenu bpmErrors = (ButtonPopupMenu) bpSource.getControlByType(CTRL_ERRORS); if (bpmErrors.isEnabled()) { - String options[] = { "Save", "Cancel" }; + String[] options = { "Save", "Cancel" }; int result = JOptionPane.showOptionDialog(panel, "Script contains errors. Save anyway?", "Errors found", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (result != 0) { @@ -501,7 +505,7 @@ public String getDescription() { } catch (IOException e) { JOptionPane.showMessageDialog(panel, "Error saving " + chooser.getSelectedFile().toString(), "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/bcs/BcsAction.java b/src/org/infinity/resource/bcs/BcsAction.java index 9d19b8a23..99f81f200 100644 --- a/src/org/infinity/resource/bcs/BcsAction.java +++ b/src/org/infinity/resource/bcs/BcsAction.java @@ -7,6 +7,7 @@ import java.awt.Point; import java.util.Arrays; +import org.infinity.util.Logger; import org.infinity.util.StringBufferStream; /** @@ -340,6 +341,7 @@ private void init(StringBufferStream sbs) throws Exception { } cntNums++; } catch (Exception e) { + Logger.warn(e); } break; case 'S': @@ -352,6 +354,7 @@ private void init(StringBufferStream sbs) throws Exception { } cntStrings++; } catch (Exception e) { + Logger.warn(e); } break; case 'O': @@ -383,7 +386,7 @@ private Signatures.Function[] getSortedFunction(int id, boolean reversed) { retVal = o1.getName().compareTo(o2.getName()); } else if (o1 == null && o2 == null) { retVal = 0; - } else if (o1 != null && o2 == null) { + } else if (o1 != null) { retVal = -1; } else { retVal = 1; diff --git a/src/org/infinity/resource/bcs/BcsObject.java b/src/org/infinity/resource/bcs/BcsObject.java index f340b59b1..df0ef65e5 100644 --- a/src/org/infinity/resource/bcs/BcsObject.java +++ b/src/org/infinity/resource/bcs/BcsObject.java @@ -7,6 +7,7 @@ import java.awt.Rectangle; import org.infinity.resource.Profile; +import org.infinity.util.Logger; import org.infinity.util.StringBufferStream; /** @@ -77,7 +78,7 @@ public static String[] getTargetList(Profile.Engine engine) { public boolean isEmptyTarget() { boolean empty = true; for (long l : target) { - empty &= (l == 0L); + empty = (l == 0L); if (!empty) { break; } @@ -89,7 +90,7 @@ public boolean isEmptyTarget() { public boolean isEmptyIdentifier() { boolean empty = true; for (long l : identifier) { - empty &= (l == 0L); + empty = (l == 0L); if (!empty) { break; } @@ -222,6 +223,7 @@ private void init(StringBufferStream sbs) throws Exception { num[cntNums++] = n; } } catch (Exception e) { + Logger.warn(e); } break; case 'S': @@ -229,6 +231,7 @@ private void init(StringBufferStream sbs) throws Exception { name = parseString(sbs); posName = cnt; } catch (Exception e) { + Logger.warn(e); } break; case 'P': @@ -240,6 +243,7 @@ private void init(StringBufferStream sbs) throws Exception { region.height = r.height; posRect = cnt; } catch (Exception e) { + Logger.warn(e); } break; default: diff --git a/src/org/infinity/resource/bcs/BcsResource.java b/src/org/infinity/resource/bcs/BcsResource.java index 2d39ef827..4be23cc6e 100644 --- a/src/org/infinity/resource/bcs/BcsResource.java +++ b/src/org/infinity/resource/bcs/BcsResource.java @@ -59,6 +59,7 @@ import org.infinity.search.ScriptReferenceSearcher; import org.infinity.search.TextResourceSearcher; import org.infinity.util.IdsMap; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StaticSimpleXorDecryptor; import org.infinity.util.io.StreamUtils; @@ -307,6 +308,8 @@ public final class BcsResource private final ButtonPanel bpDecompile = new ButtonPanel(); private final ButtonPanel bpCompiled = new ButtonPanel(); + private final String text; + private JMenuItem iFindAll; private JMenuItem iFindThis; private JMenuItem iFindUsage; @@ -316,7 +319,6 @@ public final class BcsResource private JTabbedPane tabbedPane; private InfinityTextArea codeText; private ScriptTextArea sourceText; - private String text; private boolean sourceChanged = false; private boolean codeChanged = false; @@ -352,7 +354,7 @@ public void actionPerformed(ActionEvent event) { @Override public void close() throws Exception { if (sourceChanged) { - String options[] = { "Compile & save", "Discard changes", "Cancel" }; + String[] options = { "Compile & save", "Discard changes", "Cancel" }; int result = JOptionPane.showOptionDialog(panel, "Script contains uncompiled changes", "Uncompiled changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { @@ -487,7 +489,7 @@ public String getDescription() { } catch (IOException e) { JOptionPane.showMessageDialog(panel, "Error exporting " + chooser.getSelectedFile().toString(), "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } } else if (bpmExport.getSelectedItem() == iExportScript) { @@ -529,7 +531,7 @@ public String getText() { try { return decompiler.getSource(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return "// Error: " + e.getMessage(); } } @@ -550,6 +552,7 @@ public void highlightText(int linenr, String highlightText) { } highlightText(startOfs, endOfs); } catch (BadLocationException ble) { + Logger.warn(ble); } } @@ -560,6 +563,7 @@ public void highlightText(int startOfs, int endOfs) { sourceText.moveCaretPosition(endOfs - 1); sourceText.getCaret().setSelectionVisible(true); } catch (IllegalArgumentException e) { + Logger.warn(e); } } @@ -697,16 +701,16 @@ private void compile() { bDecompile.setEnabled(false); sourceChanged = false; codeChanged = true; - iExportScript.setEnabled(compiler.getErrors().size() == 0); + iExportScript.setEnabled(compiler.getErrors().isEmpty()); SortedSet errorMap = compiler.getErrors(); SortedSet warningMap = compiler.getWarnings(); sourceText.clearGutterIcons(); bpmErrors.setText("Errors (" + errorMap.size() + ")..."); bpmWarnings.setText("Warnings (" + warningMap.size() + ")..."); - if (errorMap.size() == 0) { + if (errorMap.isEmpty()) { bpmErrors.setEnabled(false); } else { - JMenuItem errorItems[] = new JMenuItem[errorMap.size()]; + JMenuItem[] errorItems = new JMenuItem[errorMap.size()]; int counter = 0; for (final ScriptMessage sm : errorMap) { sourceText.setLineError(sm.getLine(), sm.getMessage(), false); @@ -715,10 +719,10 @@ private void compile() { bpmErrors.setMenuItems(errorItems, false); bpmErrors.setEnabled(true); } - if (warningMap.size() == 0) { + if (warningMap.isEmpty()) { bpmWarnings.setEnabled(false); } else { - JMenuItem warningItems[] = new JMenuItem[warningMap.size()]; + JMenuItem[] warningItems = new JMenuItem[warningMap.size()]; int counter = 0; for (final ScriptMessage sm : warningMap) { sourceText.setLineWarning(sm.getLine(), sm.getMessage(), false); @@ -739,12 +743,12 @@ private void decompile() { try { sourceText.setText(decompiler.getSource()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); sourceText.setText("/*\nError: " + e.getMessage() + "\n*/"); } sourceText.setCaretPosition(0); Set uses = decompiler.getResourcesUsed(); - JMenuItem usesItems[] = new JMenuItem[uses.size()]; + JMenuItem[] usesItems = new JMenuItem[uses.size()]; int usesIndex = 0; for (final ResourceEntry usesEntry : uses) { if (usesEntry.getSearchString() != null) { @@ -766,7 +770,7 @@ private void save(boolean interactive) { final JButton bSaveAs = (JButton) buttonPanel.getControlByType(ButtonPanel.Control.SAVE_AS); final ButtonPopupMenu bpmErrors = (ButtonPopupMenu) bpDecompile.getControlByType(CTRL_ERRORS); if (bpmErrors.isEnabled()) { - String options[] = { "Save", "Cancel" }; + String[] options = { "Save", "Cancel" }; int result = JOptionPane.showOptionDialog(panel, "Script contains errors. Save anyway?", "Errors found", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (result != 0) { diff --git a/src/org/infinity/resource/bcs/BcsStructureBase.java b/src/org/infinity/resource/bcs/BcsStructureBase.java index 6f03a3991..dd3280a13 100644 --- a/src/org/infinity/resource/bcs/BcsStructureBase.java +++ b/src/org/infinity/resource/bcs/BcsStructureBase.java @@ -159,7 +159,7 @@ public String[] setStringParams(Signatures.Function function, String[] strings) if (p.isCombinedString()) { boolean colon = p.isColonSeparatedString(); - if (colon && retVal[dstIndex].length() == 0) { + if (colon && retVal[dstIndex].isEmpty()) { retVal[dstIndex] = ":"; } diff --git a/src/org/infinity/resource/bcs/BcsTrigger.java b/src/org/infinity/resource/bcs/BcsTrigger.java index 79a78ab02..b6a1be7b6 100644 --- a/src/org/infinity/resource/bcs/BcsTrigger.java +++ b/src/org/infinity/resource/bcs/BcsTrigger.java @@ -10,6 +10,7 @@ import java.util.Map; import org.infinity.resource.Profile; +import org.infinity.util.Logger; import org.infinity.util.StringBufferStream; /** @@ -372,6 +373,7 @@ private void init(StringBufferStream sbs) throws Exception { } cntNums++; } catch (Exception e) { + Logger.warn(e); } break; case 'S': @@ -384,6 +386,7 @@ private void init(StringBufferStream sbs) throws Exception { } cntStrings++; } catch (Exception e) { + Logger.warn(e); } break; case 'P': @@ -392,6 +395,7 @@ private void init(StringBufferStream sbs) throws Exception { t7.x = p.x; t7.y = p.y; } catch (Exception e) { + Logger.warn(e); } break; case 'O': @@ -414,7 +418,7 @@ private Signatures.Function[] getSortedFunction(int id) { return o1.getName().compareTo(o2.getName()); } else if (o1 == null && o2 == null) { return 0; - } else if (o1 != null && o2 == null) { + } else if (o1 != null) { return -1; } else { return 1; diff --git a/src/org/infinity/resource/bcs/Compiler.java b/src/org/infinity/resource/bcs/Compiler.java index dc5ae0036..40f865ed7 100644 --- a/src/org/infinity/resource/bcs/Compiler.java +++ b/src/org/infinity/resource/bcs/Compiler.java @@ -24,6 +24,7 @@ import org.infinity.util.BOMStringReader; import org.infinity.util.CreMapCache; import org.infinity.util.IdsMapCache; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -213,6 +214,7 @@ public String compile(ScriptType type) { try { token = parser.getNextToken(); } catch (Throwable t) { + Logger.trace(t); } errors.add(new ScriptMessage(e.getMessage(), token)); } catch (Throwable e) { @@ -399,7 +401,7 @@ private void generateTR(StringBuilder sb, ScriptNode node) { } // setting strings - String[] strings = trigger.setStringParams(node.function, node.strings.toArray(new String[node.strings.size()])); + String[] strings = trigger.setStringParams(node.function, node.strings.toArray(new String[0])); trigger.t4 = strings[0]; trigger.t5 = strings[1]; @@ -545,7 +547,7 @@ private void generateAC(StringBuilder sb, ScriptNode node, BcsObject overrideTar } // handling strings - String[] strings = action.setStringParams(node.function, node.strings.toArray(new String[node.strings.size()])); + String[] strings = action.setStringParams(node.function, node.strings.toArray(new String[0])); action.a8 = strings[0]; action.a9 = strings[1]; @@ -626,7 +628,7 @@ private boolean isOverrideFunction(int code, boolean isTrigger) { paramType = Signatures.Function.Parameter.TYPE_ACTION; } - if (paramType != 0 && func != null) { + if (func != null) { for (int i = 0, cnt = func.getNumParameters(); i < cnt; i++) { if (func.getParameter(i).getType() == paramType) { retVal = true; @@ -729,13 +731,11 @@ private void checkParams(ScriptNode node) { long value = node.numbers.get(nidx); nidx++; String[] types = param.getResourceType(); - if (types.length > 0) { - for (String type : types) { - if (type.equals("TLK")) { - checkStrref(value, node); - } else if (type.equals("SPL")) { - checkSpellCode(value, node); - } + for (String type : types) { + if (type.equals("TLK")) { + checkStrref(value, node); + } else if (type.equals("SPL")) { + checkSpellCode(value, node); } } } @@ -817,10 +817,10 @@ private String generateErrorMessage(ParseException e) { ArrayList expected = new ArrayList<>(); for (int[] element : e.expectedTokenSequences) { String symbol = ""; - for (int j = 0; j < element.length; j++) { - String s = TOKEN_SYMBOL_TO_DESC_MAP.get(e.tokenImage[element[j]]); + for (int offset : element) { + String s = TOKEN_SYMBOL_TO_DESC_MAP.get(e.tokenImage[offset]); if (s == null) { - s = e.tokenImage[element[j]]; + s = e.tokenImage[offset]; } symbol += s + ' '; } diff --git a/src/org/infinity/resource/bcs/Decompiler.java b/src/org/infinity/resource/bcs/Decompiler.java index 7fe4b4419..c4983de39 100644 --- a/src/org/infinity/resource/bcs/Decompiler.java +++ b/src/org/infinity/resource/bcs/Decompiler.java @@ -26,6 +26,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.StringBufferStream; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -732,10 +733,9 @@ private String decompileAction(BcsAction action) throws Exception { if (funcName == null) { funcName = Signatures.Function.ACTION_OVERRIDE_NAME; } - StringBuilder sbOverride = new StringBuilder(); - sbOverride.append(funcName).append('('); - sbOverride.append(decompileObject(override)).append(','); - sb.insert(0, sbOverride.toString()); + String sbOverride = funcName + '(' + + decompileObject(override) + ','; + sb.insert(0, sbOverride); sb.append(')'); } @@ -799,14 +799,12 @@ private String decompileObject(BcsObject object) { // optional: getting region if (!object.isEmptyRect()) { - StringBuilder sbRect = new StringBuilder(); - sbRect.append('['); - sbRect.append(object.region.x).append('.'); - sbRect.append(object.region.y).append('.'); - sbRect.append(object.region.width).append('.'); - sbRect.append(object.region.height); - sbRect.append(']'); - rect = sbRect.toString(); + rect = "[" + + object.region.x + '.' + + object.region.y + '.' + + object.region.width + '.' + + object.region.height + + ']'; } // assembling object string @@ -1056,6 +1054,7 @@ private String generateStringComment(String value, Signatures.Function.Parameter long number = Long.parseLong(snum); result = getNormalizedSymbol(IdsMapCache.getIdsSymbol("SPELL.IDS", number)); } catch (NumberFormatException e) { + Logger.warn(e); } if (result == null) { sb.append("UNKNOWN_").append(snum); diff --git a/src/org/infinity/resource/bcs/ScriptInfo.java b/src/org/infinity/resource/bcs/ScriptInfo.java index 832a4c214..b07b9c697 100644 --- a/src/org/infinity/resource/bcs/ScriptInfo.java +++ b/src/org/infinity/resource/bcs/ScriptInfo.java @@ -328,20 +328,27 @@ public class ScriptInfo { * Maps parameter information returned by the method {@code key(FunctionType ftype, int id, char type, int index)} to * one or more resource types. * - * @param Key A colon-separated list of function type, function id, parameter type (I, S, O or P) and parameter + *

+ * Key A colon-separated list of function type, function id, parameter type (I, S, O or P) and parameter * position.
* Example: {@code "A:7:S:1"} points to the parameter {@code "S:Effect*"} of the action function * {@code "7 CreateCreatureEffect(S:NewObject*,S:Effect*,P:Location*,I:Face*DIR)"}. - * @param Value A colon-separated list of resource types (in upper case) or special keywords (in lower case) + *

+ *

+ * Value A colon-separated list of resource types (in upper case) or special keywords (in lower case) * associated with the parameter. + *

*/ public final Map functionResTypeMap = new HashMap<>(128); /** * Returns number and type of concatenated strings of the specified trigger or action specified by code. * - * @param Key The trigger or action function code. - * @param Value A numeric code: Bit 0: Whether first string parameter consists of two separate strings.
+ *

+ * Key The trigger or action function code. + *

+ *

+ * Value A numeric code: Bit 0: Whether first string parameter consists of two separate strings.
* Bit 4: Whether second string parameter consists of two separate strings.
* Bit 8: Whether first string parameter is separated by fixed-size string (0) or is colon-separated * (1).
@@ -349,6 +356,7 @@ public class ScriptInfo { * (1).
* Bits 16..31: Optional number of expected parameter. This is useful to distinguish functions with * identical code, but different signatures. + *

*/ public final Map functionConcatMap = new HashMap<>(64); @@ -362,8 +370,12 @@ public class ScriptInfo { * Defines which parameter of a function should generate comments. Unlisted functions generate comments for the first * commentable parameter only. * - * @param Key The trigger or action function code. - * @param Value The parameter index. + *

+ * Key The trigger or action function code. + *

+ *

+ * Value The parameter index. + *

*/ public final Map functionParamCommentMap = new HashMap<>(64); @@ -417,10 +429,9 @@ public static ScriptInfo getInfo(Profile.Engine engine) { * Internally used: Create a correctly formatted string for use as key for {@code FUNCTION_RESTYPE}. */ private static String key(Function.FunctionType ftype, int id, char type, int index) { - StringBuilder sb = new StringBuilder(); - sb.append(ftype == Function.FunctionType.TRIGGER ? 'T' : 'A').append(':').append(id).append(':') - .append(Character.toUpperCase(type)).append(':').append(index); - return sb.toString(); + String s = String.valueOf(ftype == Function.FunctionType.TRIGGER ? 'T' : 'A') + ':' + id + ':' + + Character.toUpperCase(type) + ':' + index; + return s; } /** @@ -464,30 +475,44 @@ protected ScriptInfo(String[] objectSpecifierIds, String[] scopes) { SCOPES = scopes; OBJECT_SPECIFIER_IDS = objectSpecifierIds; for (int i = 0; i < OBJECT_SPECIFIER_IDS.length; i++) { - if (OBJECT_SPECIFIER_IDS[i].equals("EA")) { - IDX_OBJECT_EA = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("FACTION")) { - IDX_OBJECT_FACTION = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("TEAM")) { - IDX_OBJECT_TEAM = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("GENERAL")) { - IDX_OBJECT_GENERAL = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("RACE")) { - IDX_OBJECT_RACE = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("CLASS")) { - IDX_OBJECT_CLASS = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("SPECIFIC")) { - IDX_OBJECT_SPECIFIC = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("GENDER")) { - IDX_OBJECT_GENDER = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("ALIGN") || OBJECT_SPECIFIER_IDS[i].equals("ALIGNMNT")) { - IDX_OBJECT_ALIGN = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("SUBRACE")) { - IDX_OBJECT_SUBRACE = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("AVCLASS")) { - IDX_OBJECT_AVCLASS = i; - } else if (OBJECT_SPECIFIER_IDS[i].equals("CLASSMSK")) { - IDX_OBJECT_CLASSMASK = i; + switch (OBJECT_SPECIFIER_IDS[i]) { + case "EA": + IDX_OBJECT_EA = i; + break; + case "FACTION": + IDX_OBJECT_FACTION = i; + break; + case "TEAM": + IDX_OBJECT_TEAM = i; + break; + case "GENERAL": + IDX_OBJECT_GENERAL = i; + break; + case "RACE": + IDX_OBJECT_RACE = i; + break; + case "CLASS": + IDX_OBJECT_CLASS = i; + break; + case "SPECIFIC": + IDX_OBJECT_SPECIFIC = i; + break; + case "GENDER": + IDX_OBJECT_GENDER = i; + break; + case "ALIGN": + case "ALIGNMNT": + IDX_OBJECT_ALIGN = i; + break; + case "SUBRACE": + IDX_OBJECT_SUBRACE = i; + break; + case "AVCLASS": + IDX_OBJECT_AVCLASS = i; + break; + case "CLASSMSK": + IDX_OBJECT_CLASSMASK = i; + break; } } } @@ -609,8 +634,8 @@ public String[] getGlobalScopes() { /** Returns whether the parameter at the specified index may generate comments. */ public boolean isCommentAllowed(int code, int paramIndex) { - if (functionParamCommentMap.containsKey(Integer.valueOf(code))) { - return (paramIndex >= functionParamCommentMap.get(Integer.valueOf(code)).intValue()); + if (functionParamCommentMap.containsKey(code)) { + return (paramIndex >= functionParamCommentMap.get(code)); } else { return true; } @@ -626,7 +651,7 @@ public boolean isCommentAllowed(int code, int paramIndex) { */ public boolean isCombinedString(int code, int position, int numParameters) { boolean retVal = false; - Integer v = functionConcatMap.get(Integer.valueOf(code)); + Integer v = functionConcatMap.get(code); if (v != null) { int numParams = (v >> 16) & 0xffff; if (numParams == 0 || numParameters == 0 || numParams == numParameters) { @@ -656,7 +681,7 @@ public boolean isCombinedString(int code, int position, int numParameters) { */ public boolean isColonSeparatedString(int code, int position, int numParameters) { boolean retVal = false; - Integer v = functionConcatMap.get(Integer.valueOf(code)); + Integer v = functionConcatMap.get(code); if (v != null) { int numParams = (v >> 16) & 0xffff; if (numParams == 0 || numParameters == 0 || numParams == numParameters) { diff --git a/src/org/infinity/resource/bcs/Signatures.java b/src/org/infinity/resource/bcs/Signatures.java index df5d03eac..2852a23ae 100644 --- a/src/org/infinity/resource/bcs/Signatures.java +++ b/src/org/infinity/resource/bcs/Signatures.java @@ -24,7 +24,7 @@ * Manages action and trigger function signatures. */ public class Signatures { - private static HashMap instances = new HashMap<>(); + private static final HashMap INSTANCES = new HashMap<>(); private final TreeMap> functions; private final HashMap functionsByName; @@ -57,7 +57,7 @@ public int getSize() { * Returns the set of functions associated with the specified identifier. Returns {@code null} if not available. */ public Function[] getFunction(int id) { - HashSet set = functions.get(Integer.valueOf(id)); + HashSet set = functions.get(id); if (set != null) { Function[] retVal = new Function[set.size()]; int idx = 0; @@ -101,7 +101,7 @@ public Function getFunction(String name, boolean exact) { * Removes all function signatures from cache. */ public static void clearCache() { - instances.clear(); + INSTANCES.clear(); } /** Convenience method for getting trigger signatures. */ @@ -126,7 +126,7 @@ public static Signatures get(String resource, boolean isTrigger) { Signatures retVal = null; resource = normalizedName(resource); - retVal = instances.get(resource); + retVal = INSTANCES.get(resource); if (retVal == null) { ResourceEntry entry = ResourceFactory.getResourceEntry(resource); if (entry == null) { @@ -143,7 +143,7 @@ public static Signatures get(String resource, boolean isTrigger) { for (String line : lines) { Function f = Function.parse(line, isTrigger); if (f != null) { - HashSet set = retVal.functions.get(Integer.valueOf(f.getId())); + HashSet set = retVal.functions.get(f.getId()); if (set == null) { set = new HashSet<>(8); } @@ -163,7 +163,7 @@ public static Signatures get(String resource, boolean isTrigger) { for (final String line : hardcoded) { Function f = Function.parse(line, isTrigger); if (f != null) { - HashSet set = retVal.functions.get(Integer.valueOf(f.getId())); + HashSet set = retVal.functions.get(f.getId()); if (set == null) { set = new HashSet<>(8); } @@ -173,7 +173,7 @@ public static Signatures get(String resource, boolean isTrigger) { } } - instances.put(resource, retVal); + INSTANCES.put(resource, retVal); } return retVal; } @@ -212,10 +212,10 @@ public static enum FunctionType { public static final String ACTION_OVERRIDE_NAME = "ActionOverride"; private final FunctionType type; // function type + private final ArrayList param; // list of parameter definitions private int id; // function identifier private String name; // function name (without parentheses and parameters) - private ArrayList param; // list of parameter definitions public Function(int id, String name, FunctionType type) { setId(id); @@ -447,11 +447,9 @@ private static Function parse(String line, boolean isTrigger) { if (success) { List paramList = Parameter.parse(params, id, funcType); - if (paramList != null) { - retVal = new Function(id, name, funcType); - for (Parameter p : paramList) { - retVal.addParameter(p); - } + retVal = new Function(id, name, funcType); + for (Parameter p : paramList) { + retVal.addParameter(p); } } @@ -541,7 +539,7 @@ public String getName() { /** Sets parameter name (without trailing asterisk '*'). */ public void setName(String name) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { this.name = ""; } else { int idx = name.indexOf('*'); @@ -556,7 +554,7 @@ public String getIdsRef() { /** Sets lowercased IDS reference. */ public void setIdsRef(String idsRef) { - if (idsRef == null || idsRef.length() == 0) { + if (idsRef == null || idsRef.isEmpty()) { this.idsRef = ""; } else { this.idsRef = idsRef.toLowerCase(Locale.ENGLISH); @@ -694,12 +692,12 @@ private static List parse(String param, int id, FunctionType funcType } } s = m.group(2); - if (s.length() > 0) { + if (!s.isEmpty()) { name = s.replace(" ", ""); } if (m.groupCount() > 2) { s = m.group(3); - if (s.length() > 0) { + if (!s.isEmpty()) { idsRef = s; } } diff --git a/src/org/infinity/resource/chu/Control.java b/src/org/infinity/resource/chu/Control.java index 62fbe8b11..a6cfdd810 100644 --- a/src/org/infinity/resource/chu/Control.java +++ b/src/org/infinity/resource/chu/Control.java @@ -25,7 +25,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.StructEntry; -final class Control extends AbstractStruct { // implements AddRemovable +final public class Control extends AbstractStruct { // implements AddRemovable // CHU/Control-specific field labels public static final String CHU_CONTROL = "Control"; public static final String CHU_CONTROL_OFFSET = "Offset"; diff --git a/src/org/infinity/resource/chu/Viewer.java b/src/org/infinity/resource/chu/Viewer.java index 4d333670f..5e8900559 100644 --- a/src/org/infinity/resource/chu/Viewer.java +++ b/src/org/infinity/resource/chu/Viewer.java @@ -22,10 +22,7 @@ import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; +import java.util.*; import javax.swing.AbstractListModel; import javax.swing.BorderFactory; @@ -62,7 +59,7 @@ import org.infinity.resource.graphics.MosV1Decoder; import org.infinity.util.StringTable; -final class Viewer extends JPanel +final public class Viewer extends JPanel implements ActionListener, TableModelListener, ListSelectionListener, ChangeListener, MouseListener { /** Supported control types. */ public enum ControlType { @@ -154,12 +151,12 @@ public void actionPerformed(ActionEvent e) { if (e.getSource() == cbOutlineControls) { // updating main display Panel p = getSelectedPanel(); - p.repaint(); + Objects.requireNonNull(p).repaint(); rcMain.repaint(); } else if (e.getSource() == cbTransparentPanel) { // updating main display Panel p = getSelectedPanel(); - p.repaint(); + Objects.requireNonNull(p).repaint(); rcMain.repaint(); } } @@ -173,7 +170,7 @@ public void tableChanged(TableModelEvent e) { if (e.getSource() == getResource()) { // updating viewer elements Panel p = getSelectedPanel(); - p.reset(); + Objects.requireNonNull(p).reset(); setPreview(p.getImage()); } } @@ -203,7 +200,7 @@ public void valueChanged(ListSelectionEvent e) { // updating selected control in main window Panel p = getSelectedPanel(); - p.repaint(); + Objects.requireNonNull(p).repaint(); rcMain.repaint(); } } @@ -223,7 +220,7 @@ public void stateChanged(ChangeEvent e) { c.updateState(); c.updateImage(); } - p.repaint(); + Objects.requireNonNull(p).repaint(); rcMain.repaint(); } } @@ -291,22 +288,12 @@ boolean isTransparentBackground() { /** Returns the currently active panel. */ Panel getSelectedPanel() { - Object o = panelsModel.getElementAt(panelsList.getSelectedIndex()); - if (o instanceof Panel) { - return (Panel) o; - } else { - return null; - } + return panelsModel.getElementAt(panelsList.getSelectedIndex()); } /** Returns the currently active control. */ BaseControl getSelectedControl() { - Object o = controlsModel.getElementAt(controlsList.getSelectedIndex()); - if (o instanceof BaseControl) { - return (BaseControl) o; - } else { - return null; - } + return controlsModel.getElementAt(controlsList.getSelectedIndex()); } /** Returns the current properties panel instance. */ @@ -421,7 +408,7 @@ private void initControls() { // ----------------------------- INNER CLASSES ----------------------------- // Data model for the panels list - private class ListPanelsModel extends AbstractListModel { + private static class ListPanelsModel extends AbstractListModel { private final List listPanels = new ArrayList<>(); private final Viewer viewer; @@ -462,7 +449,7 @@ public ChuResource getResource() { } // Data model for the controls list - private class ListControlsModel extends AbstractListModel { + private static class ListControlsModel extends AbstractListModel { private final List listControls = new ArrayList<>(); private final Viewer viewer; @@ -582,7 +569,7 @@ public void actionPerformed(ActionEvent e) { public void addChangeListener(ChangeListener l) { if (l != null) { - if (listeners.indexOf(l) < 0) { + if (!listeners.contains(l)) { listeners.add(l); } } @@ -1024,11 +1011,11 @@ private void updateImage() { } // Common base for control specific classes - private static abstract class BaseControl { + public static abstract class BaseControl { private final Viewer viewer; private final Control control; + private final Color outlinedColor; - private Color outlinedColor; private boolean visible; protected BaseControl(Viewer viewer, Control control, ControlType type) { @@ -1127,12 +1114,10 @@ public Color getOutlinedColor() { @Override public String toString() { if (getResource() != null) { - StringBuilder sb = new StringBuilder("ID: "); - sb.append(getResource().getControlId()); - sb.append(" (Type: "); - sb.append(getControlType(getResource().getControlType()).name()); - sb.append(")"); - return sb.toString(); + return "ID: " + getResource().getControlId() + + " (Type: " + + getControlType(getResource().getControlType()).name() + + ")"; } else { return "(none)"; } @@ -1276,7 +1261,7 @@ protected static Image drawText(String text, BamDecoder fntBam, Color fntColor, int intensity = palette[1] & 0xff; for (int i = 1; i < 255 && isAlpha; i++, intensity--) { int alpha = intensity | (intensity << 8) | (intensity << 16); - isAlpha &= (palette[i] & 0xffffff) == alpha; + isAlpha = (palette[i] & 0xffffff) == alpha; } if (isAlpha) { @@ -1842,43 +1827,41 @@ public void updateImage() { if (isVisible()) { String text = StringTable .getStringRef(((IsNumeric) getResource().getAttribute(Control.CHU_CONTROL_LBL_TEXT)).getValue()); - if (text != null) { - String resName = ((IsReference) getResource().getAttribute(Control.CHU_CONTROL_LBL_FONT)) - .getResourceName(); - resName = resName.toUpperCase(Locale.ENGLISH).replace(".FNT", ".BAM"); - BamDecoder bam = BamDecoder.loadBam(ResourceFactory.getResourceEntry(resName)); - if (bam != null) { - Flag flags = (Flag) getResource().getAttribute(Control.CHU_CONTROL_LBL_FLAGS); - Color col = null; - if (flags.isFlagSet(0)) { - col = new Color( - ((IsNumeric) getResource().getAttribute(Control.CHU_CONTROL_LBL_COLOR_1)).getValue()); + String resName = ((IsReference) getResource().getAttribute(Control.CHU_CONTROL_LBL_FONT)) + .getResourceName(); + resName = resName.toUpperCase(Locale.ENGLISH).replace(".FNT", ".BAM"); + BamDecoder bam = BamDecoder.loadBam(ResourceFactory.getResourceEntry(resName)); + if (bam != null) { + Flag flags = (Flag) getResource().getAttribute(Control.CHU_CONTROL_LBL_FLAGS); + Color col = null; + if (flags.isFlagSet(0)) { + col = new Color( + ((IsNumeric) getResource().getAttribute(Control.CHU_CONTROL_LBL_COLOR_1)).getValue()); + } + Image textImage = drawText(text, bam, col, flags.isFlagSet(1)); + if (textImage != null) { + // calculating text alignment + int srcWidth = textImage.getWidth(null); + int srcHeight = textImage.getHeight(null); + int dstWidth = image.getWidth(); + int dstHeight = image.getHeight(); + int x = 0, y = 0; + if (flags.isFlagSet(3)) { // left + x = 0; + } else if (flags.isFlagSet(4)) { // right + x = dstWidth - srcWidth; + } else { // hcenter + x = (dstWidth - srcWidth) / 2; } - Image textImage = drawText(text, bam, col, flags.isFlagSet(1)); - if (textImage != null) { - // calculating text alignment - int srcWidth = textImage.getWidth(null); - int srcHeight = textImage.getHeight(null); - int dstWidth = image.getWidth(); - int dstHeight = image.getHeight(); - int x = 0, y = 0; - if (flags.isFlagSet(3)) { // left - x = 0; - } else if (flags.isFlagSet(4)) { // right - x = dstWidth - srcWidth; - } else { // hcenter - x = (dstWidth - srcWidth) / 2; - } - if (flags.isFlagSet(5)) { // top - y = 0; - } else if (flags.isFlagSet(7)) { // bottom - y = dstHeight - srcHeight; - } else { // vcenter - y = (dstHeight - srcHeight) / 2; - } - // drawing text - g.drawImage(textImage, x, y, srcWidth, srcHeight, null); + if (flags.isFlagSet(5)) { // top + y = 0; + } else if (flags.isFlagSet(7)) { // bottom + y = dstHeight - srcHeight; + } else { // vcenter + y = (dstHeight - srcHeight) / 2; } + // drawing text + g.drawImage(textImage, x, y, srcWidth, srcHeight, null); } } } diff --git a/src/org/infinity/resource/chu/Window.java b/src/org/infinity/resource/chu/Window.java index 248edd50f..953518521 100644 --- a/src/org/infinity/resource/chu/Window.java +++ b/src/org/infinity/resource/chu/Window.java @@ -23,7 +23,7 @@ import org.infinity.resource.StructEntry; import org.infinity.util.io.StreamUtils; -final class Window extends AbstractStruct { // implements AddRemovable +final public class Window extends AbstractStruct { // implements AddRemovable // CHU/Window-specific field labels public static final String CHU_WINDOW_PANEL = "Panel"; public static final String CHU_WINDOW_NAME = "Name"; diff --git a/src/org/infinity/resource/cre/CreResource.java b/src/org/infinity/resource/cre/CreResource.java index fbd8fd580..b7b50d489 100644 --- a/src/org/infinity/resource/cre/CreResource.java +++ b/src/org/infinity/resource/cre/CreResource.java @@ -75,6 +75,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; import org.infinity.util.Table2da; @@ -437,7 +438,8 @@ public final class CreResource extends AbstractStruct "Hide status", "Affected by alternate damage", "Moving between areas", "Been in party", "Holding item", "Reset bit 16", null, null, "EE: No exploding death", null, "EE: Ignore nightmare mode", "EE: No tooltip", "Allegiance tracking", "General tracking", "Race tracking", "Class tracking", "Specifics tracking", - "Gender tracking", "Alignment tracking", "Uninterruptible" }; + "Gender tracking", "Alignment tracking", + "Uninterruptible;Used internally to indicate whether execution of creature script actions can be interrupted." }; public static final String[] FLAGS_IWD2_ARRAY = { "No flags set", "Damage don't stop casting", "No corpse", "Permanent corpse", null, null, null, null, null, null, "Fallen paladin", "Fallen ranger", "Export allowed", null, @@ -550,7 +552,7 @@ public static void addScriptName(Map> scriptNames, Re } else { offset += 0x64; } - signature = StreamUtils.readString(buffer, offset + 0, 4); + signature = StreamUtils.readString(buffer, offset, 4); } if (signature.equalsIgnoreCase("CRE ")) { @@ -564,7 +566,7 @@ public static void addScriptName(Map> scriptNames, Re } else if (version.equalsIgnoreCase("V9.0") || version.equalsIgnoreCase("V9.1")) { scriptName = StreamUtils.readString(buffer, offset + 744, 32); } - if (scriptName.equals("") || scriptName.equalsIgnoreCase("None")) { + if (scriptName.isEmpty() || scriptName.equalsIgnoreCase("None")) { return; // Apparently script name is the only thing that matters // scriptName = entry.toString().substring(0, entry.toString().length() - 4); @@ -585,6 +587,7 @@ public static void addScriptName(Map> scriptNames, Re } } } catch (Exception e) { + Logger.trace(e); } } @@ -616,7 +619,7 @@ public static void convertCHRtoCRE(ResourceEntry resourceEntry) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), "File saved to " + path, "Conversion complete", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Errors during conversion", "Error", JOptionPane.ERROR_MESSAGE); } @@ -626,7 +629,7 @@ public static void convertCHRtoCRE(ResourceEntry resourceEntry) { private static void convertToSemiStandard(CreResource crefile) { final List fields = crefile.getFields(); if (!fields.get(1).toString().equals("V1.0")) { - System.err.println("Conversion to semi-standard aborted: Unsupported CRE version"); + Logger.warn("Conversion to semi-standard aborted: Unsupported CRE version"); return; } @@ -711,9 +714,11 @@ public static String getSearchString(InputStream is) throws IOException { if (sig.equals("CHR ")) { retVal = StreamUtils.readString(is, 32); } else { - String name = StringTable.getStringRef(StreamUtils.readInt(is)); - String shortName = StringTable.getStringRef(StreamUtils.readInt(is)); - if (name.equals(shortName)) { + final int strrefName = StreamUtils.readInt(is); + final int strrefShortName = StreamUtils.readInt(is); + final String name = StringTable.getStringRef(strrefName).trim(); + final String shortName = StringTable.getStringRef(strrefShortName).trim(); + if (strrefName == strrefShortName || strrefShortName < 0 || name.equals(shortName) || shortName.isEmpty()) { retVal = name; } else { retVal = name + " - " + shortName; @@ -734,12 +739,10 @@ public static String getScriptName(ByteBuffer buffer) throws IOException { String ver = StreamUtils.readString(buffer, 4, 4); int startOfs = 0; if (sig.equals("CHR ")) { - switch (ver) { - case "V2.2": - startOfs = 0x224; - break; - default: - startOfs = 0x64; + if (ver.equals("V2.2")) { + startOfs = 0x224; + } else { + startOfs = 0x64; } ver = StreamUtils.readString(buffer, startOfs + 4, 4); } else if (!sig.equals("CRE ")) { @@ -936,8 +939,8 @@ public boolean viewerTabAddedBefore(int index) { // Needed for embedded CRE resources private boolean showRawTab() { if (hasRawTab == null) { - hasRawTab = !(Boolean.valueOf(this.isChildOf(GamResource.class)) - || Boolean.valueOf(this.isChildOf(AreResource.class))); + hasRawTab = !(this.isChildOf(GamResource.class) + || this.isChildOf(AreResource.class)); } return hasRawTab; } @@ -2130,9 +2133,9 @@ private boolean convertEffects(int version, SectionOffset so, SectionCount sc) { try { Effect newEff = (Effect) oldEff.clone(true); addDatatype(newEff); - retVal |= true; + retVal = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } else if (version == 1 && so.getSection().equals(Effect.class)) { @@ -2160,9 +2163,9 @@ private boolean convertEffects(int version, SectionOffset so, SectionCount sc) { try { Effect2 newEff = (Effect2) oldEff.clone(true); addDatatype(newEff); - retVal |= true; + retVal = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -2297,7 +2300,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = cre.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchString(struct, o, false, false); + retVal = SearchOptions.Utils.matchString(struct, o, false, false); } else { break; } @@ -2321,7 +2324,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear StructEntry struct = cre.getAttribute(scriptField, false); found |= SearchOptions.Utils.matchResourceRef(struct, o, false); } - retVal &= found; + retVal = found; } } @@ -2332,7 +2335,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = cre.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -2351,7 +2354,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = cre.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { break; } @@ -2368,13 +2371,13 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (!found) { if (effect != null) { StructEntry struct = effect.getAttribute(SearchOptions.getResourceName(key), false); - found |= SearchOptions.Utils.matchNumber(struct, o); + found = SearchOptions.Utils.matchNumber(struct, o); } } else { break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -2391,13 +2394,13 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (!found) { if (item != null) { StructEntry struct = item.getAttribute(SearchOptions.getResourceName(key), false); - found |= SearchOptions.Utils.matchResourceRef(struct, o, false); + found = SearchOptions.Utils.matchResourceRef(struct, o, false); } } else { break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -2413,13 +2416,13 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear for (Datatype spell : spells) { if (!found) { if (spell != null) { - found |= SearchOptions.Utils.matchResourceRef(spell, o, false); + found = SearchOptions.Utils.matchResourceRef(spell, o, false); } } else { break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -2431,7 +2434,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(cre, o); + retVal = SearchOptions.Utils.matchCustomFilter(cre, o); } else { break; } @@ -2439,6 +2442,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/cre/Viewer.java b/src/org/infinity/resource/cre/Viewer.java index 2a580d88b..10ec8a236 100644 --- a/src/org/infinity/resource/cre/Viewer.java +++ b/src/org/infinity/resource/cre/Viewer.java @@ -124,7 +124,7 @@ public Viewer(CreResource cre) { if (version.toString().equalsIgnoreCase("V2.2")) { tabs.addTab("Feats/Skills", makeFeatsPanel(cre)); tabs.addTab("Items/Spells", makeItemSpellsPanelIWD2(cre)); - } else if (version != null) { + } else { tabs.addTab("Items/Spells", makeItemSpellsPanel(cre)); } setLayout(new BorderLayout()); diff --git a/src/org/infinity/resource/cre/ViewerAnimation.java b/src/org/infinity/resource/cre/ViewerAnimation.java index b08e438f8..18128fb4a 100644 --- a/src/org/infinity/resource/cre/ViewerAnimation.java +++ b/src/org/infinity/resource/cre/ViewerAnimation.java @@ -47,6 +47,7 @@ import org.infinity.resource.cre.decoder.util.Sequence; import org.infinity.resource.cre.decoder.util.SpriteUtils; import org.infinity.resource.graphics.ColorConvert; +import org.infinity.util.Logger; /** * A basic creature animation viewer. @@ -247,7 +248,7 @@ public void open() { WindowBlocker.blockWindow(true); initAnimation(); } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); WindowBlocker.blockWindow(false); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Creature animation could not be loaded.\nError message: " + ex.getMessage(), "Error", @@ -286,7 +287,7 @@ public void actionPerformed(ActionEvent event) { setAnimationSequence(seq); updateControls(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); cbSequences.setSelectedItem(getAnimationSequence()); } finally { @@ -315,7 +316,7 @@ public void actionPerformed(ActionEvent event) { getDecoder().setBoundingBoxVisible(showOverlayBorders); resetAnimationSequence(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { WindowBlocker.blockWindow(false); } diff --git a/src/org/infinity/resource/cre/ViewerItems.java b/src/org/infinity/resource/cre/ViewerItems.java index 940f9f204..6e01b5224 100644 --- a/src/org/infinity/resource/cre/ViewerItems.java +++ b/src/org/infinity/resource/cre/ViewerItems.java @@ -143,7 +143,7 @@ public void valueChanged(ListSelectionEvent event) { @Override public void tableChanged(TableModelEvent event) { if (event.getType() == TableModelEvent.UPDATE) { - CreResource cre = (CreResource) event.getSource(); + final CreResource cre = (CreResource) event.getSource(); final StructEntry changed = cre.getFields().get(event.getFirstRow()); if (slots.contains(changed)) { final List items = new ArrayList<>(); @@ -154,13 +154,19 @@ public void tableChanged(TableModelEvent event) { } table.clearSelection(); tableModel.clear(); - String selectedSlotName = getSelectedWeaponSlot(cre); + final String selectedSlotName = getSelectedWeaponSlot(cre); slots.forEach(e -> { - IsNumeric slot = (IsNumeric) e; - String slotName = e.getName().equals(selectedSlotName) ? "*" + e.getName() : e.getName(); + final IsNumeric slot = (IsNumeric) e; + final String slotName = e.getName().equals(selectedSlotName) ? "*" + e.getName() : e.getName(); if (slot.getValue() >= 0 && slot.getValue() < items.size()) { - Item item = items.get(slot.getValue()); - ResourceRef itemRef = (ResourceRef) item.getAttribute(Item.CRE_ITEM_RESREF); + final Item item = items.get(slot.getValue()); + final StructEntry itemEntry = item.getAttribute(Item.CRE_ITEM_RESREF); + final ResourceRef itemRef; + if (itemEntry instanceof ResourceRef) { + itemRef = (ResourceRef) itemEntry; + } else { + itemRef = new ResourceRef(itemEntry.getDataBuffer(), 0, itemEntry.getName(), "ITM"); + } tableModel.addEntry(slotName, itemRef); } else { tableModel.addEntry(slotName, null); diff --git a/src/org/infinity/resource/cre/ViewerSpells.java b/src/org/infinity/resource/cre/ViewerSpells.java index 593c64865..d3d886666 100644 --- a/src/org/infinity/resource/cre/ViewerSpells.java +++ b/src/org/infinity/resource/cre/ViewerSpells.java @@ -119,9 +119,8 @@ private void updateTable() { private void addSpell(int type, int lvl, ResourceRef spell) { for (MemSpellTableEntry element : list) { - MemSpellTableEntry entry = element; - if (spell.getResourceName().equalsIgnoreCase(entry.spell.getResourceName())) { - entry.count++; + if (spell.getResourceName().equalsIgnoreCase(element.spell.getResourceName())) { + element.count++; return; } } diff --git a/src/org/infinity/resource/cre/browser/ColorSelectionModel.java b/src/org/infinity/resource/cre/browser/ColorSelectionModel.java index eeb50e9b7..3792d26ad 100644 --- a/src/org/infinity/resource/cre/browser/ColorSelectionModel.java +++ b/src/org/infinity/resource/cre/browser/ColorSelectionModel.java @@ -37,6 +37,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; @@ -51,9 +52,10 @@ public class ColorSelectionModel extends AbstractListModel colorList = new ArrayList<>(256); private final ColorCellRenderer renderer = new ColorCellRenderer(); + private final IdsMap colorMap; + private Object selectedItem; private ResourceEntry colorEntry; - private IdsMap colorMap; public ColorSelectionModel() { this(null); @@ -125,9 +127,7 @@ public void removeAllElements() { int oldSize = colorList.size(); colorList.clear(); selectedItem = null; - if (oldSize > 0) { - fireIntervalRemoved(this, 0, oldSize - 1); - } + fireIntervalRemoved(this, 0, oldSize - 1); } else { selectedItem = null; } @@ -177,6 +177,7 @@ private void init() { try { image = new GraphicsResource(getColorRangesEntry()).getImage(); } catch (Exception e) { + Logger.trace(e); } int max = (image != null) ? image.getHeight() - 1 : 0; @@ -185,7 +186,7 @@ private void init() { } for (int i = 0; i <= max; i++) { - String name = RANDOM_COLORS_MAP.get(Integer.valueOf(i)); + String name = RANDOM_COLORS_MAP.get(i); if (name != null) { colorList.add(new ColorEntry(i, name, true)); } else { @@ -239,7 +240,7 @@ public ColorCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - if (value == null || !(value instanceof ColorEntry)) { + if (!(value instanceof ColorEntry)) { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } @@ -306,8 +307,8 @@ public enum State { private final int index; private final Image image; + private final String name; - private String name; private State state; /** Creates a fixed color entry. */ diff --git a/src/org/infinity/resource/cre/browser/CreUtils.java b/src/org/infinity/resource/cre/browser/CreUtils.java index 24cb50d41..f96e3a6e7 100644 --- a/src/org/infinity/resource/cre/browser/CreUtils.java +++ b/src/org/infinity/resource/cre/browser/CreUtils.java @@ -24,6 +24,7 @@ import org.infinity.resource.cre.Item; import org.infinity.resource.cre.decoder.util.ItemInfo; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -132,7 +133,7 @@ public static ItemInfo getEquipmentHelmet(CreResource cre) { retVal = ItemInfo.getValidated(itemEntry); retVal.overrideDroppableFlag(((Flag) item.getAttribute(Item.CRE_ITEM_FLAGS)).isFlagSet(3)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -172,7 +173,7 @@ public static ItemInfo getEquipmentArmor(CreResource cre) { retVal = ItemInfo.getValidated(itemEntry); retVal.overrideDroppableFlag(((Flag) item.getAttribute(Item.CRE_ITEM_FLAGS)).isFlagSet(3)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -220,7 +221,7 @@ public static ItemInfo getEquipmentShield(CreResource cre) { retVal = ItemInfo.getValidated(itemEntry); retVal.overrideDroppableFlag(((Flag) item.getAttribute(Item.CRE_ITEM_FLAGS)).isFlagSet(3)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -266,7 +267,7 @@ public static ItemInfo getEquipmentWeapon(CreResource cre) { retVal = ItemInfo.getValidated(itemEntry); retVal.overrideDroppableFlag(((Flag) item.getAttribute(Item.CRE_ITEM_FLAGS)).isFlagSet(3)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -383,7 +384,7 @@ private static void addEquippedItem(CreResource cre, ItemInfo item, String slotN cre.addDatatype(newItem); setFieldValue(cre.getAttribute(slotName), null, numItems); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -528,7 +529,7 @@ private static int setFieldValue(Readable field, ByteBuffer buf, int value) { try { retVal = field.read(buf, pos); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -556,7 +557,7 @@ private static int setFieldValue(Readable field, ByteBuffer buf, String value, i try { retVal = field.read(buf, pos); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; diff --git a/src/org/infinity/resource/cre/browser/CreatureAnimationModel.java b/src/org/infinity/resource/cre/browser/CreatureAnimationModel.java index 6ad9f0a78..6f332a1c4 100644 --- a/src/org/infinity/resource/cre/browser/CreatureAnimationModel.java +++ b/src/org/infinity/resource/cre/browser/CreatureAnimationModel.java @@ -17,6 +17,7 @@ import org.infinity.util.IdsMap; import org.infinity.util.IdsMapCache; import org.infinity.util.IdsMapEntry; +import org.infinity.util.Logger; /** * {@code ComboBoxModel} for the creature animation combo box used in the Creature Animation Browser. @@ -86,9 +87,7 @@ public void removeAllElements() { int oldSize = animationList.size(); animationList.clear(); selectedItem = null; - if (oldSize > 0) { - fireIntervalRemoved(this, 0, oldSize - 1); - } + fireIntervalRemoved(this, 0, oldSize - 1); } else { selectedItem = null; } @@ -203,6 +202,7 @@ public int parseValue(Object o) { retVal = Integer.parseInt(s, base) * factor; } catch (Exception e) { + Logger.trace(e); } } return retVal; diff --git a/src/org/infinity/resource/cre/browser/CreatureBrowser.java b/src/org/infinity/resource/cre/browser/CreatureBrowser.java index b68ac1dbc..2f8ea1582 100644 --- a/src/org/infinity/resource/cre/browser/CreatureBrowser.java +++ b/src/org/infinity/resource/cre/browser/CreatureBrowser.java @@ -27,6 +27,7 @@ import org.infinity.resource.cre.CreResource; import org.infinity.resource.cre.decoder.SpriteDecoder; import org.infinity.resource.cre.decoder.util.SpriteUtils; +import org.infinity.util.Logger; /** * The Creature Browser implements a highly customizable browser and viewer for creature animations. @@ -199,7 +200,7 @@ private Object taskSetCreResource() throws Exception { /** A generic catch-all operation that can be used to evaluate exceptions thrown in a background task. */ private void postTaskDefault(Object o, Exception e) { if (e != null) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } @@ -223,28 +224,26 @@ private synchronized void performBackgroundTask() { if (worker == null && taskInfo != null) { worker = new SwingWorker() { @Override - protected TaskInfo doInBackground() throws Exception { - TaskInfo retVal = taskInfo; + protected TaskInfo doInBackground() { WindowBlocker blocker = null; try { - if (retVal.blockWindow) { + if (taskInfo.blockWindow) { blocker = new WindowBlocker(CreatureBrowser.this); blocker.setBlocked(true); } - retVal.result = retVal.action.get(); + taskInfo.result = taskInfo.action.get(); } catch (Exception e) { - if (retVal.postAction != null) { - retVal.exception = e; + if (taskInfo.postAction != null) { + taskInfo.exception = e; } else { - e.printStackTrace(); + Logger.error(e); } } finally { if (blocker != null) { blocker.setBlocked(false); - blocker = null; } } - return retVal; + return taskInfo; } }; worker.addPropertyChangeListener(listeners); @@ -268,6 +267,7 @@ public void propertyChange(PropertyChangeEvent event) { try { retVal = worker.get(); } catch (ExecutionException | InterruptedException e) { + Logger.trace(e); } if (retVal != null) { if (retVal.postAction != null) { diff --git a/src/org/infinity/resource/cre/browser/CreatureControlModel.java b/src/org/infinity/resource/cre/browser/CreatureControlModel.java index e2efa5fe1..11c5dcc68 100644 --- a/src/org/infinity/resource/cre/browser/CreatureControlModel.java +++ b/src/org/infinity/resource/cre/browser/CreatureControlModel.java @@ -20,6 +20,7 @@ import org.infinity.resource.cre.decoder.util.ItemInfo; import org.infinity.resource.cre.decoder.util.ItemInfo.ItemPredicate; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * This model controls the relationships between creature controls and provides access to the various creature-specific @@ -83,7 +84,7 @@ public void setSelectedCreature(ResourceEntry entry) throws Exception { /** * Selects the specified CRE resource and initializes related fields. * - * @param entry {@code CreResource} instance of the creature + * @param cre {@code CreResource} instance of the creature * @throws Exception if creature resource could not be initialized */ public void setSelectedCreature(CreResource cre) throws Exception { @@ -111,7 +112,7 @@ public void setSelectedAnimation(int value) { getModelAnimation().reload(); } - int idx = getModelAnimation().getIndexOf(Integer.valueOf(value)); + int idx = getModelAnimation().getIndexOf(value); if (idx >= 0) { getModelAnimation().setSelectedItem(getModelAnimation().getElementAt(idx)); } else { @@ -126,7 +127,7 @@ public void setSelectedAllegiance(int value) { getModelAllegiance().reload(); } - int idx = Math.max(0, getModelAllegiance().getIndexOf(Integer.valueOf(value))); + int idx = Math.max(0, getModelAllegiance().getIndexOf(value)); getModelAllegiance().setSelectedItem(getModelAllegiance().getElementAt(idx)); creAllegianceChanged(); } @@ -196,7 +197,7 @@ public void setSelectedColor(int index, int color) { model.reload(); } - int idx = model.getIndexOf(Integer.valueOf(color)); + int idx = model.getIndexOf(color); model.setSelectedItem(model.getElementAt(idx)); colorChanged(index); } @@ -343,6 +344,7 @@ public ColorEntry getSelectedColor(int index) { return (ColorEntry) model.getSelectedItem(); } } catch (IndexOutOfBoundsException e) { + Logger.trace(e); } return null; } @@ -449,10 +451,9 @@ public void itemWeaponChanged() { isTwoHanded |= Profile.isEnhancedEdition() && ((info.getFlags() & (1 << 12)) != 0); ItemPredicate shieldPred = null; if (!isTwoHanded) { - shieldPred = (shieldPred == null) ? ItemInfo.FILTER_SHIELD : shieldPred.or(ItemInfo.FILTER_SHIELD); + shieldPred = ItemInfo.FILTER_SHIELD; if (isMelee) { - shieldPred = (shieldPred == null) ? ItemInfo.FILTER_WEAPON_MELEE_LEFT_HANDED - : shieldPred.or(ItemInfo.FILTER_WEAPON_MELEE_LEFT_HANDED); + shieldPred = shieldPred.or(ItemInfo.FILTER_WEAPON_MELEE_LEFT_HANDED); } } if (shieldPred == null) { @@ -480,7 +481,7 @@ public void reset() { try { creSelectionChanged(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -518,7 +519,7 @@ protected void resetModified() { if (canApply || canReset) { boolean randomColor = false; for (int i = 0; i < colorModels.size() && !randomColor; i++) { - randomColor |= isColorRandom(i); + randomColor = isColorRandom(i); } canApply = randomColor; canReset = isCreatureModified(); diff --git a/src/org/infinity/resource/cre/browser/CreatureControlPanel.java b/src/org/infinity/resource/cre/browser/CreatureControlPanel.java index 08b452383..bbc3d6219 100644 --- a/src/org/infinity/resource/cre/browser/CreatureControlPanel.java +++ b/src/org/infinity/resource/cre/browser/CreatureControlPanel.java @@ -43,6 +43,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; /** @@ -145,7 +146,7 @@ public void applySettings() { try { getControlModel().resetDecoder(cre); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); getBrowser().showErrorMessage(e.getMessage(), "Loading creature"); } @@ -434,7 +435,7 @@ private boolean confirmReset() { */ public static String[] createColorLabels(SpriteDecoder decoder) { String[] retVal = null; - if (decoder != null && decoder instanceof MonsterPlanescapeDecoder) { + if (decoder instanceof MonsterPlanescapeDecoder) { MonsterPlanescapeDecoder mpd = (MonsterPlanescapeDecoder) decoder; IdsMap map = IdsMapCache.get("CLOWNRGE.IDS"); if (map != null) { @@ -506,7 +507,7 @@ public void actionPerformed(ActionEvent e) { getControlModel().creSelectionChanged(); updateToolTip(cbCreSelection); } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); getBrowser().showErrorMessage(ex.getMessage(), "Creature selection"); } } else if (e.getSource() == cbCreAnimation) { diff --git a/src/org/infinity/resource/cre/browser/CreatureSelectionModel.java b/src/org/infinity/resource/cre/browser/CreatureSelectionModel.java index 16ed74a93..6d34a6d94 100644 --- a/src/org/infinity/resource/cre/browser/CreatureSelectionModel.java +++ b/src/org/infinity/resource/cre/browser/CreatureSelectionModel.java @@ -21,6 +21,7 @@ import org.infinity.resource.cre.CreResource; import org.infinity.resource.key.BufferedResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.ResourceStructure; import org.infinity.util.io.StreamUtils; @@ -84,9 +85,7 @@ public void removeAllElements() { int oldSize = creList.size(); creList.clear(); selectedItem = null; - if (oldSize > 0) { - fireIntervalRemoved(this, 0, oldSize - 1); - } + fireIntervalRemoved(this, 0, oldSize - 1); } else { selectedItem = null; } @@ -134,9 +133,7 @@ private void init() { ResourceFactory.getResources("CRE").stream().forEach(re -> creList.add(new CreatureItem(re))); Collections.sort(creList); creList.add(0, CreatureItem.getDefault()); - if (!creList.isEmpty()) { - fireIntervalAdded(this, 0, creList.size() - 1); - } + fireIntervalAdded(this, 0, creList.size() - 1); } // -------------------------- INNER CLASSES -------------------------- @@ -261,7 +258,7 @@ private static ResourceEntry createCreature() { retVal = new BufferedResourceEntry(buf, "*.CRE"); } catch (StructureException e) { - e.printStackTrace(); + Logger.error(e); } return retVal; diff --git a/src/org/infinity/resource/cre/browser/CreatureStatusModel.java b/src/org/infinity/resource/cre/browser/CreatureStatusModel.java index 84731d9e1..a5bb84312 100644 --- a/src/org/infinity/resource/cre/browser/CreatureStatusModel.java +++ b/src/org/infinity/resource/cre/browser/CreatureStatusModel.java @@ -83,9 +83,7 @@ public void removeAllElements() { int oldSize = statusList.size(); statusList.clear(); selectedItem = null; - if (oldSize > 0) { - fireIntervalRemoved(this, 0, oldSize - 1); - } + fireIntervalRemoved(this, 0, oldSize - 1); } else { selectedItem = null; } diff --git a/src/org/infinity/resource/cre/browser/DecoderAttributesTableModel.java b/src/org/infinity/resource/cre/browser/DecoderAttributesTableModel.java index a46195e4a..84e6a1a84 100644 --- a/src/org/infinity/resource/cre/browser/DecoderAttributesTableModel.java +++ b/src/org/infinity/resource/cre/browser/DecoderAttributesTableModel.java @@ -131,7 +131,7 @@ public void reload() { attributes.put(Misc.prettifySymbol(key), value); } } - keys = attributes.keySet().toArray(new String[attributes.keySet().size()]); + keys = attributes.keySet().toArray(new String[0]); fireTableRowsInserted(0, keys.length - 1); } } diff --git a/src/org/infinity/resource/cre/browser/ItemSelectionModel.java b/src/org/infinity/resource/cre/browser/ItemSelectionModel.java index 557781131..918dd1219 100644 --- a/src/org/infinity/resource/cre/browser/ItemSelectionModel.java +++ b/src/org/infinity/resource/cre/browser/ItemSelectionModel.java @@ -96,9 +96,7 @@ public void removeAllElements() { int oldSize = itemList.size(); itemList.clear(); selectedItem = null; - if (oldSize > 0) { - fireIntervalRemoved(this, 0, oldSize - 1); - } + fireIntervalRemoved(this, 0, oldSize - 1); } else { selectedItem = null; } diff --git a/src/org/infinity/resource/cre/browser/MediaPanel.java b/src/org/infinity/resource/cre/browser/MediaPanel.java index bad015b1d..929eaa4ec 100644 --- a/src/org/infinity/resource/cre/browser/MediaPanel.java +++ b/src/org/infinity/resource/cre/browser/MediaPanel.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; @@ -53,6 +52,7 @@ import org.infinity.resource.cre.decoder.util.Direction; import org.infinity.resource.cre.decoder.util.Sequence; import org.infinity.resource.graphics.ColorConvert; +import org.infinity.util.Logger; import org.infinity.util.tuples.Couple; import ork.sevenstates.apng.APNGSeqWriter; @@ -61,7 +61,7 @@ * This panel provides controls for animation playback and related visual options. */ public class MediaPanel extends JPanel { - private static boolean isLoop; + private static final boolean isLoop; static { isLoop = true; @@ -113,7 +113,7 @@ public void reset(boolean preserveState) { Sequence oldSequence = preserveState ? getSequence() : null; Direction oldDir = preserveState ? getDirection(getCurrentDirection()) : null; int oldFrameIdx = preserveState ? getCurrentFrame() : 0; - boolean isRunning = preserveState ? isRunning() : false; + boolean isRunning = preserveState && isRunning(); stop(); modelSequences.removeAllElements(); @@ -321,7 +321,7 @@ public void loadSequence(Sequence seq) throws IllegalArgumentException { throw new Exception(); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw new IllegalArgumentException("Could not load animation sequence"); } @@ -663,7 +663,7 @@ private void initDirection(SpriteDecoder decoder, Direction defDir) { } // sorting in descending order: maps relative slider positions to more natural directions - Collections.sort(directions, (a, b) -> b - a); + directions.sort((a, b) -> b - a); int min = -directions.size() + 1; int max = directions.size(); @@ -731,7 +731,7 @@ private void initDirection(SpriteDecoder decoder, Direction defDir) { /** Returns the {@code Direction} of the specified direction slider position. Defaults to {@code Direction.S}. */ private Direction getDirection(int index) { - return directionMap.getOrDefault(Integer.valueOf(index), Direction.S); + return directionMap.getOrDefault(index, Direction.S); } /** Interactive export of the current animation sequence to an animation file. */ @@ -819,7 +819,7 @@ private void exportBamSequence() { JOptionPane.showMessageDialog(browser, message, "Export animation sequence", JOptionPane.INFORMATION_MESSAGE); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(browser, "Unable to export animation sequence.", "Error", JOptionPane.ERROR_MESSAGE); } } @@ -893,7 +893,7 @@ public void itemStateChanged(ItemEvent e) { WindowBlocker.blockWindow(getBrowser(), true); loadSequence(seq); } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); getBrowser().showErrorMessage(ex.getMessage(), "Sequence selection"); } finally { WindowBlocker.blockWindow(getBrowser(), false); diff --git a/src/org/infinity/resource/cre/browser/RenderPanel.java b/src/org/infinity/resource/cre/browser/RenderPanel.java index 2c99ddb14..7fcf7398f 100644 --- a/src/org/infinity/resource/cre/browser/RenderPanel.java +++ b/src/org/infinity/resource/cre/browser/RenderPanel.java @@ -43,7 +43,7 @@ public class RenderPanel extends JPanel { private final CreatureBrowser browser; // storage for scroll pane view size to track view size changes - private Dimension viewSize = new Dimension(); + private final Dimension viewSize = new Dimension(); private JPanel pCanvas; private RenderCanvas rcCanvas; @@ -233,8 +233,7 @@ public Couple setFrame(SpriteBamControl ctrl, Image frame, Rec frame = null; } - Couple retVal = new Couple<>(frame, frameBounds); - return retVal; + return new Couple<>(frame, frameBounds); } /** @@ -416,8 +415,8 @@ protected void updateCanvas(boolean restore) { // apply zoom factor if (rcCanvas.getImage() != null) { Dimension dim = new Dimension(rcCanvas.getImage().getWidth(null), rcCanvas.getImage().getHeight(null)); - dim.width *= getZoom(); - dim.height *= getZoom(); + dim.width *= (int) getZoom(); + dim.height *= (int) getZoom(); rcCanvas.setPreferredSize(dim); rcCanvas.setSize(dim); } diff --git a/src/org/infinity/resource/cre/browser/SettingsPanel.java b/src/org/infinity/resource/cre/browser/SettingsPanel.java index 0110ea97a..660371c68 100644 --- a/src/org/infinity/resource/cre/browser/SettingsPanel.java +++ b/src/org/infinity/resource/cre/browser/SettingsPanel.java @@ -480,7 +480,7 @@ private void init() { JLabel l3 = new JLabel("Background:"); List bgList = getBackgrounds(Profile.getGame()); - cbBackground = new JComboBox<>(bgList.toArray(new Backgrounds.BackgroundInfo[bgList.size()])); + cbBackground = new JComboBox<>(bgList.toArray(new BackgroundInfo[0])); cbBackground.setPrototypeDisplayValue(BACKGROUND_LIST.get(1)); cbBackground.setSelectedIndex(indexBackground); cbBackground.addActionListener(listeners); diff --git a/src/org/infinity/resource/cre/browser/bg/Backgrounds.java b/src/org/infinity/resource/cre/browser/bg/Backgrounds.java index 7f663fdcc..78ba31e74 100644 --- a/src/org/infinity/resource/cre/browser/bg/Backgrounds.java +++ b/src/org/infinity/resource/cre/browser/bg/Backgrounds.java @@ -15,6 +15,7 @@ import javax.swing.UIManager; import org.infinity.resource.Profile; +import org.infinity.util.Logger; /** * Backgrounds for the creature animation browser. @@ -80,7 +81,7 @@ public static Image getImage(Class c, String fileName) { URL url = getValidURL(c, fileName); retVal = ImageIO.read(url); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; } diff --git a/src/org/infinity/resource/cre/decoder/AmbientDecoder.java b/src/org/infinity/resource/cre/decoder/AmbientDecoder.java index 075cbe047..9236432c5 100644 --- a/src/org/infinity/resource/cre/decoder/AmbientDecoder.java +++ b/src/org/infinity/resource/cre/decoder/AmbientDecoder.java @@ -125,8 +125,8 @@ protected void setListType(int v) { @Override public List getAnimationFiles(boolean essential) { - String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + final String resref = getAnimationResref(); + return new ArrayList() { { add(resref + "G1.BAM"); add(resref + "G1E.BAM"); @@ -136,7 +136,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override diff --git a/src/org/infinity/resource/cre/decoder/AmbientStaticDecoder.java b/src/org/infinity/resource/cre/decoder/AmbientStaticDecoder.java index 5ba68d2d1..7e81809d3 100644 --- a/src/org/infinity/resource/cre/decoder/AmbientStaticDecoder.java +++ b/src/org/infinity/resource/cre/decoder/AmbientStaticDecoder.java @@ -93,8 +93,8 @@ protected void setInvulnerable(boolean b) { @Override public List getAnimationFiles(boolean essential) { - String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + final String resref = getAnimationResref(); + return new ArrayList() { { add(resref + "G1.BAM"); add(resref + "G1E.BAM"); @@ -104,7 +104,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override @@ -138,7 +137,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, SeqDef.DIR_REDUCED_E.length)) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycle, null, behavior); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleE, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/CharacterBaseDecoder.java b/src/org/infinity/resource/cre/decoder/CharacterBaseDecoder.java index c1ecf687f..3d1cdaa83 100644 --- a/src/org/infinity/resource/cre/decoder/CharacterBaseDecoder.java +++ b/src/org/infinity/resource/cre/decoder/CharacterBaseDecoder.java @@ -148,9 +148,7 @@ public AttackType getAttackType(ItemInfo itm, int abilityIndex, boolean preferTw } int abilType = -1; abilityIndex = Math.max(0, Math.min(itm.getAbilityCount() - 1, abilityIndex)); - if (abilityIndex >= 0) { - abilType = itm.getAbility(abilityIndex).getAbilityType(); - } + abilType = itm.getAbility(abilityIndex).getAbilityType(); switch (itm.getCategory()) { case 15: // Bows diff --git a/src/org/infinity/resource/cre/decoder/CharacterDecoder.java b/src/org/infinity/resource/cre/decoder/CharacterDecoder.java index 7d3b67cca..9795c4db9 100644 --- a/src/org/infinity/resource/cre/decoder/CharacterDecoder.java +++ b/src/org/infinity/resource/cre/decoder/CharacterDecoder.java @@ -277,7 +277,7 @@ protected void setArmorBaseResref(String s) { if (s.isEmpty()) { s = getAnimationResref(); } else { - s = getAnimationResref().substring(0, 3) + s.substring(0, 1); + s = getAnimationResref().substring(0, 3) + s.charAt(0); } setAttribute(KEY_RESREF_ARMOR_BASE, s); } @@ -294,7 +294,7 @@ protected void setArmorSpecificResref(String s) { if (s.isEmpty()) { s = getAnimationResref(); } else { - s = getAnimationResref().substring(0, 3) + s.substring(0, 1); + s = getAnimationResref().substring(0, 3) + s.charAt(0); } setAttribute(KEY_RESREF_ARMOR_SPECIFIC, s); } @@ -343,7 +343,7 @@ public List getAnimationFiles(boolean essential) { } } } - retVal = new ArrayList<>(Arrays.asList(files.toArray(new String[files.size()]))); + retVal = new ArrayList<>(Arrays.asList(files.toArray(new String[0]))); } else { // collecting suffixes HashSet actionSet = new HashSet<>(); @@ -495,9 +495,9 @@ protected SeqDef getSequenceDefinition(Sequence seq) { ResourceEntry entry = ResourceFactory.getResourceEntry(prefix + suffix + ".BAM"); if (SpriteUtils.bamCyclesExist(entry, cycleIdx, SeqDef.DIR_FULL_W.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_W, false, entry, cycleIdx, spriteType, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_E, true, entry, cycleIdx + 1, spriteType, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } diff --git a/src/org/infinity/resource/cre/decoder/CharacterOldDecoder.java b/src/org/infinity/resource/cre/decoder/CharacterOldDecoder.java index c5a10064a..819ff0867 100644 --- a/src/org/infinity/resource/cre/decoder/CharacterOldDecoder.java +++ b/src/org/infinity/resource/cre/decoder/CharacterOldDecoder.java @@ -224,7 +224,7 @@ public List getAnimationFiles(boolean essential) { } } } - retVal = new ArrayList<>(Arrays.asList(files.toArray(new String[files.size()]))); + retVal = new ArrayList<>(Arrays.asList(files.toArray(new String[0]))); } else { // collecting suffixes HashSet actionSet = new HashSet<>(); @@ -390,10 +390,10 @@ protected SeqDef getSequenceDefinition(Sequence seq) { if (SpriteUtils.bamCyclesExist(entry, cycleIdx, SeqDef.DIR_REDUCED_W.length) && SpriteUtils .bamCyclesExist(entryE, cycleIdx + SeqDef.DIR_REDUCED_W.length, SeqDef.DIR_REDUCED_E.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycleIdx, spriteType, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleIdx + SeqDef.DIR_REDUCED_W.length, spriteType, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } } diff --git a/src/org/infinity/resource/cre/decoder/EffectDecoder.java b/src/org/infinity/resource/cre/decoder/EffectDecoder.java index ef7d4d3eb..33fd75446 100644 --- a/src/org/infinity/resource/cre/decoder/EffectDecoder.java +++ b/src/org/infinity/resource/cre/decoder/EffectDecoder.java @@ -357,7 +357,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { } } - if (retVal.isEmpty()) { + if (retVal != null && retVal.isEmpty()) { retVal = null; } diff --git a/src/org/infinity/resource/cre/decoder/FlyingDecoder.java b/src/org/infinity/resource/cre/decoder/FlyingDecoder.java index 808de08d6..e7f6af1b6 100644 --- a/src/org/infinity/resource/cre/decoder/FlyingDecoder.java +++ b/src/org/infinity/resource/cre/decoder/FlyingDecoder.java @@ -87,7 +87,7 @@ protected void init() throws Exception { protected SeqDef getSequenceDefinition(Sequence seq) { SeqDef retVal = null; - int cycleIndex = 0; + final int cycleIndex; switch (seq) { case STAND: cycleIndex = 0; @@ -103,7 +103,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { if (SpriteUtils.bamCyclesExist(entry, cycleIndex, SeqDef.DIR_FULL_W.length)) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_FULL_W, false, entry, cycleIndex, null); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_E, true, entry, cycleIndex + 1, null); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/MonsterAnkhegDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterAnkhegDecoder.java index 14ed55aa6..c4a7bd445 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterAnkhegDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterAnkhegDecoder.java @@ -109,7 +109,7 @@ protected void setExtendedDirections(boolean b) { @Override public List getAnimationFiles(boolean essential) { String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + return new ArrayList() { { add(resref + "DG1.BAM"); if (!hasMirroredDirections()) { @@ -137,7 +137,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override @@ -180,16 +179,16 @@ protected SeqDef getSequenceDefinition(Sequence seq) { String suffix = SegmentDef.fixBehaviorSuffix(data.getValue0()); for (final String type : new String[] { "D", "" }) { ResourceEntry entry = ResourceFactory.getResourceEntry(resref + type + suffix + ".BAM"); - int cycle = data.getValue1().intValue() * seg; + int cycle = data.getValue1() * seg; ResourceEntry entryE = ResourceFactory.getResourceEntry(resref + type + suffix + suffixE + ".BAM"); int cycleE = cycle + eastOfs; if (SpriteUtils.bamCyclesExist(entry, cycle, dirWest.length) && SpriteUtils.bamCyclesExist(entryE, cycleE, dirEast.length)) { SeqDef tmp = SeqDef.createSequence(seq, dirWest, false, entry, cycle, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, dirEast, hasMirroredDirections(), entryE, cycleE, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterDecoder.java index 66c9db069..12ca73b78 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterDecoder.java @@ -249,9 +249,7 @@ public List getAnimationFiles(boolean essential) { } // generating file list - ArrayList retVal = new ArrayList<>(Arrays.asList(files.toArray(new String[files.size()]))); - - return retVal; + return new ArrayList<>(Arrays.asList(files.toArray(new String[0]))); } @Override @@ -329,18 +327,18 @@ protected SeqDef getSequenceDefinition(Sequence seq) { SegmentDef.SpriteType type = creInfo.getValue1(); if (SpriteUtils.bamCyclesExist(entry, ofs, SeqDef.DIR_FULL_W.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_W, false, entry, ofs, type, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_E, true, entry, ofs + 1, type, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } else if (entry != null && SpriteUtils.getBamCycles(entry) == 1) { // fallback solution: just use first bam cycle (required by a few animations) for (final Direction dir : SeqDef.DIR_FULL_W) { SeqDef tmp = SeqDef.createSequence(seq, new Direction[] { dir }, false, entry, 0, type, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } for (final Direction dir : SeqDef.DIR_FULL_E) { SeqDef tmp = SeqDef.createSequence(seq, new Direction[] { dir }, true, entry, 0, type, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterIcewindDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterIcewindDecoder.java index 653358051..366e406cb 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterIcewindDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterIcewindDecoder.java @@ -188,7 +188,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { ResourceEntry entryE = ResourceFactory.getResourceEntry(resref + ovl + suffix + "E.BAM"); if (SpriteUtils.bamCyclesExist(entry, 0, SeqDef.DIR_REDUCED_W.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, 0, spriteType, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); if (SpriteUtils.bamCyclesExist(entryE, 0, SeqDef.DIR_REDUCED_E.length)) { tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, SeqDef.DIR_REDUCED_W.length, spriteType, behavior); @@ -196,7 +196,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { // fallback: mirror eastern directions tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, true, entry, 1, spriteType, behavior); } - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterLarge16Decoder.java b/src/org/infinity/resource/cre/decoder/MonsterLarge16Decoder.java index 69f4cb2b3..ad9f0f11d 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterLarge16Decoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterLarge16Decoder.java @@ -86,7 +86,7 @@ public MonsterLarge16Decoder(CreResource cre) throws Exception { @Override public List getAnimationFiles(boolean essential) { String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + return new ArrayList() { { add(resref + "G1.BAM"); add(resref + "G1E.BAM"); @@ -96,7 +96,6 @@ public List getAnimationFiles(boolean essential) { add(resref + "G3E.BAM"); } }; - return retVal; } @Override @@ -135,7 +134,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, dir_e.length)) { retVal = SeqDef.createSequence(seq, dir_w, false, entry, cycle, null, behavior); SeqDef tmp = SeqDef.createSequence(seq, dir_e, false, entryE, cycleE, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterLargeDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterLargeDecoder.java index 8368133d7..870820d3e 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterLargeDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterLargeDecoder.java @@ -86,7 +86,7 @@ public MonsterLargeDecoder(CreResource cre) throws Exception { @Override public List getAnimationFiles(boolean essential) { String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + return new ArrayList() { { add(resref + "G1.BAM"); add(resref + "G1E.BAM"); @@ -96,7 +96,6 @@ public List getAnimationFiles(boolean essential) { add(resref + "G3E.BAM"); } }; - return retVal; } @Override @@ -129,7 +128,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, SeqDef.DIR_REDUCED_E.length)) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycle, null, behavior); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleE, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/MonsterLayeredDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterLayeredDecoder.java index 8e1428dec..78bfa4e33 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterLayeredDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterLayeredDecoder.java @@ -116,7 +116,7 @@ public List getAnimationFiles(boolean essential) { final String w1 = !getWeapon1Overlay().isEmpty() ? getWeapon1Overlay().substring(0, 1) : ""; final String w2 = !getWeapon2Overlay().isEmpty() ? getWeapon2Overlay().substring(0, 1) : ""; final String[] suffix = { "G1", "G1E", "G2", "G2E" }; - ArrayList retVal = new ArrayList() { + return new ArrayList() { { for (final String s : suffix) { add(resref + s + ".BAM"); @@ -133,7 +133,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override @@ -211,9 +210,9 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, SeqDef.DIR_REDUCED_E.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycle, resEntry.getValue1(), behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleE, resEntry.getValue1(), behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterLayeredSpellDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterLayeredSpellDecoder.java index 6c9df79c0..d3032dae8 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterLayeredSpellDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterLayeredSpellDecoder.java @@ -133,7 +133,7 @@ public List getAnimationFiles(boolean essential) { final String w1 = !getWeapon1Overlay().isEmpty() ? getWeapon1Overlay().substring(0, 1) : ""; final String w2 = !getWeapon2Overlay().isEmpty() ? getWeapon2Overlay().substring(0, 1) : ""; final String[] suffix = { "G1", "G1E", "G2", "G2E" }; - ArrayList retVal = new ArrayList() { + return new ArrayList() { { for (final String s : suffix) { add(resref + s + ".BAM"); @@ -150,7 +150,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override @@ -247,9 +246,9 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, SeqDef.DIR_REDUCED_E.length)) { SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycle, resEntry.getValue1(), behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleE, resEntry.getValue1(), behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterMultiDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterMultiDecoder.java index 51ea0cc86..c5bcd9f6b 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterMultiDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterMultiDecoder.java @@ -228,14 +228,7 @@ public List getAnimationFiles(boolean essential) { } } } - ArrayList retVal = new ArrayList() { - { - for (final String s : fileSet) { - add(s); - } - } - }; - return retVal; + return new ArrayList<>(fileSet); } @Override @@ -302,7 +295,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { cycleList.add(new SegmentDef(entry, cycleIdx, SegmentDef.SpriteType.AVATAR, behavior)); } SeqDef tmp = SeqDef.createSequence(seq, new Direction[] { dir }, false, cycleList); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } // calculating eastern directions @@ -316,7 +309,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { cycleList.add(new SegmentDef(entry, cycleIdx, SegmentDef.SpriteType.AVATAR, behavior)); } SeqDef tmp = SeqDef.createSequence(seq, new Direction[] { dir }, true, cycleList); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } // Structure: diff --git a/src/org/infinity/resource/cre/decoder/MonsterMultiNewDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterMultiNewDecoder.java index 95ac5abb8..1d49636e0 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterMultiNewDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterMultiNewDecoder.java @@ -155,7 +155,7 @@ protected void setSplittedBams(boolean b) { @Override public List getAnimationFiles(boolean essential) { String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + return new ArrayList() { { for (final HashMap.Entry> entry : getSuffixMap().entrySet()) { String suffixBase = SegmentDef.fixBehaviorSuffix(entry.getValue().getValue0()); @@ -166,7 +166,6 @@ public List getAnimationFiles(boolean essential) { } } }; - return retVal; } @Override @@ -207,14 +206,14 @@ protected SeqDef getSequenceDefinition(Sequence seq) { ResourceEntry entry = ResourceFactory.getResourceEntry(resref + suffix + ".BAM"); cycleList.add(new SegmentDef(entry, cycleOfs, null, behavior)); cycleListE.add(new SegmentDef(entry, cycleOfs + 1, null, behavior)); - valid &= SpriteUtils.bamCyclesExist(entry, cycleOfs, SeqDef.DIR_FULL_W.length); + valid = SpriteUtils.bamCyclesExist(entry, cycleOfs, SeqDef.DIR_FULL_W.length); } } if (!cycleList.isEmpty() && valid) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_FULL_W, false, cycleList); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_E, true, cycleListE); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/MonsterOldDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterOldDecoder.java index f04bf57d6..5bf6ed972 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterOldDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterOldDecoder.java @@ -103,7 +103,7 @@ public MonsterOldDecoder(CreResource cre) throws Exception { @Override public List getAnimationFiles(boolean essential) { String resref = getAnimationResref(); - ArrayList retVal = new ArrayList() { + return new ArrayList() { { add(resref + "G1.BAM"); add(resref + "G1E.BAM"); @@ -111,7 +111,6 @@ public List getAnimationFiles(boolean essential) { add(resref + "G2E.BAM"); } }; - return retVal; } @Override @@ -145,7 +144,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { && SpriteUtils.bamCyclesExist(entryE, cycleE, SeqDef.DIR_REDUCED_E.length)) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_W, false, entry, cycle, null, behavior); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_REDUCED_E, false, entryE, cycleE, null, behavior); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/MonsterPlanescapeDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterPlanescapeDecoder.java index 077a597e0..32422ce5f 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterPlanescapeDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterPlanescapeDecoder.java @@ -226,7 +226,7 @@ public static IniMap processTableData(String[] data) { } String prefix = isSpecial ? "" : s.substring(0, 1); String resref = isSpecial ? s : s.substring(1, s.length() - 1); - String suffix = isSpecial ? "" : s.substring(s.length() - 1, s.length()); + String suffix = isSpecial ? "" : s.substring(s.length() - 1); TreeMap actions = new TreeMap<>(); if (isSpecial) { actions.put(SLOT_MAP.get(Sequence.PST_STAND), resref); @@ -540,10 +540,10 @@ protected SeqDef getSequenceDefinition(Sequence seq) { if (directions != null && SpriteUtils.bamCyclesExist(entry, 0, directions.length)) { SeqDef tmp = SeqDef.createSequence(seq, directions, false, entry, 0, null); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); if (mirror) { tmp = SeqDef.createSequence(seq, directionsE, true, entry, 1, null); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } } } diff --git a/src/org/infinity/resource/cre/decoder/MonsterQuadrantDecoder.java b/src/org/infinity/resource/cre/decoder/MonsterQuadrantDecoder.java index e5dbe0d93..564789be8 100644 --- a/src/org/infinity/resource/cre/decoder/MonsterQuadrantDecoder.java +++ b/src/org/infinity/resource/cre/decoder/MonsterQuadrantDecoder.java @@ -198,7 +198,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { ResourceEntry entryE = entry; int cycle = cycleOfs; int cycleE = cycleOfs + 1; - valid &= SpriteUtils.bamCyclesExist(entry, cycle, SeqDef.DIR_FULL_W.length); + valid = SpriteUtils.bamCyclesExist(entry, cycle, SeqDef.DIR_FULL_W.length); if (isExtendedDirection()) { entryE = ResourceFactory.getResourceEntry(resref + suffix + i + "E.BAM"); cycleE = cycle + SeqDef.DIR_FULL_W.length; @@ -212,7 +212,7 @@ protected SeqDef getSequenceDefinition(Sequence seq) { if (!cycleList.isEmpty() && valid) { retVal = SeqDef.createSequence(seq, SeqDef.DIR_FULL_W, false, cycleList); SeqDef tmp = SeqDef.createSequence(seq, SeqDef.DIR_FULL_E, !isExtendedDirection(), cycleListE); - retVal.addDirections(tmp.getDirections().toArray(new DirDef[tmp.getDirections().size()])); + retVal.addDirections(tmp.getDirections().toArray(new DirDef[0])); } return retVal; diff --git a/src/org/infinity/resource/cre/decoder/PlaceholderDecoder.java b/src/org/infinity/resource/cre/decoder/PlaceholderDecoder.java index 89d53e599..9f720c617 100644 --- a/src/org/infinity/resource/cre/decoder/PlaceholderDecoder.java +++ b/src/org/infinity/resource/cre/decoder/PlaceholderDecoder.java @@ -23,6 +23,7 @@ import org.infinity.util.IniMap; import org.infinity.util.IniMapEntry; import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -50,7 +51,7 @@ private static ResourceEntry loadPlaceholderBam() { baos.flush(); retVal = new BufferedResourceEntry(StreamUtils.getByteBuffer(baos.toByteArray()), "placeholder.bam"); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } return retVal; } @@ -116,9 +117,9 @@ protected void init() throws Exception { try { int n = Integer.parseInt(value); if (n == 0 || n == 1) { - setAttribute(new DecoderAttribute(key, DecoderAttribute.DataType.BOOLEAN), Boolean.valueOf(n != 0)); + setAttribute(new DecoderAttribute(key, DecoderAttribute.DataType.BOOLEAN), n != 0); } else { - setAttribute(new DecoderAttribute(key, DecoderAttribute.DataType.DECIMAL), Integer.valueOf(n)); + setAttribute(new DecoderAttribute(key, DecoderAttribute.DataType.DECIMAL), n); } } catch (NumberFormatException e) { setAttribute(new DecoderAttribute(key, DecoderAttribute.DataType.STRING), value); diff --git a/src/org/infinity/resource/cre/decoder/SpriteDecoder.java b/src/org/infinity/resource/cre/decoder/SpriteDecoder.java index 0a93a0bc0..36874620f 100644 --- a/src/org/infinity/resource/cre/decoder/SpriteDecoder.java +++ b/src/org/infinity/resource/cre/decoder/SpriteDecoder.java @@ -58,6 +58,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.util.IniMap; import org.infinity.util.IniMapSection; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.tuples.Couple; @@ -221,7 +222,6 @@ public static SpriteDecoder importSprite(CreResource cre) throws Exception { * * @param type the animation type * @param animationId specific animation id - * @param sectionName INI section name for animation-specific data * @param ini the INI file with creature animation attributes * @throws Exception */ @@ -279,7 +279,7 @@ protected SpriteDecoder(AnimationInfo.Type type, CreResource cre) throws Excepti /** * Returns the data associated with the specified attribute name. * - * @param key the attribute name. + * @param att the attribute object. * @return attribute data in the type inferred from the method call. Returns {@code null} if data is not available for * the inferred type. */ @@ -295,7 +295,7 @@ public T getAttribute(DecoderAttribute att) { try { retVal = (T) data; } catch (ClassCastException e) { - // e.printStackTrace(); + // Logger.error(e); } } return retVal; @@ -304,7 +304,7 @@ public T getAttribute(DecoderAttribute att) { /** * Stores the attribute key and value along with the autodetected data type. * - * @param key the attribute name. + * @param att the attribute object. * @param value the value in one of the data types covered by {@link DecoderAttribute.DataType}. */ protected void setAttribute(DecoderAttribute att, Object value) { @@ -343,7 +343,7 @@ public String getAnimationSectionName() { /** Recreates the creature animation based on the current creature resource. */ public void reset() throws Exception { - Direction[] directions = getDirectionMap().keySet().toArray(new Direction[getDirectionMap().keySet().size()]); + Direction[] directions = getDirectionMap().keySet().toArray(new Direction[0]); discard(); // recreating current sequence if (getCurrentSequence() != Sequence.NONE) { @@ -392,7 +392,7 @@ public boolean loadSequence(Sequence seq, Direction[] directions) throws Excepti } catch (NullPointerException e) { retVal = (seq != Sequence.NONE); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); retVal = (seq != Sequence.NONE); } } @@ -841,7 +841,7 @@ public void applyAnimationChanges() { try { reset(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -892,7 +892,7 @@ public SpriteBamControl createControl() { */ @Override public Composite getComposite() { - int blending = ((isBrightest() ? 1 : 0) << 0) | ((isMultiplyBlend() ? 1 : 0) << 1); + int blending = ((isBrightest() ? 1 : 0)) | ((isMultiplyBlend() ? 1 : 0) << 1); switch (blending) { case 1: // brightest return BlendingComposite.Brightest; @@ -951,8 +951,8 @@ protected void initDefaults(IniMap ini) throws Exception { setNewPalette(s); // getting first available "resref" definition - for (Iterator iter = getAnimationInfo().iterator(); iter.hasNext();) { - section = iter.next(); + for (IniMapSection iniMapEntries : getAnimationInfo()) { + section = iniMapEntries; s = section.getAsString("resref", ""); if (!s.isEmpty()) { setAnimationResref(s); @@ -1001,14 +1001,13 @@ protected IniMapSection getSpecificIniSection() { /** * Assigns a cycle index to the specified BAM sequence and direction. * - * @param seq the sequence type for identification purposes. * @param dir the direction type * @param cycleIndex the cycle index associated with the specified sequence and direction. * @return The previous BAM cycle index if available. -1 otherwise. */ protected int addDirection(Direction dir, int cycleIndex) { int retVal = -1; - dir = Objects.requireNonNull(dir, "Creature direction required"); + Objects.requireNonNull(dir, "Creature direction required"); Integer value = directionMap.get(dir); if (value != null) { retVal = value; @@ -1110,7 +1109,7 @@ protected void createAnimation(SeqDef definition, List directions, Be PseudoBamControl dstCtrl = createControl(); BamV1Control srcCtrl = null; ResourceEntry entry = null; - definition = Objects.requireNonNull(definition, "Sequence definition cannot be null"); + Objects.requireNonNull(definition, "Sequence definition cannot be null"); if (directions == null) { directions = Arrays.asList(Direction.values()); @@ -1176,7 +1175,7 @@ protected void createAnimation(SeqDef definition, List directions, Be sd.advance(); } - int frameIndex = createFrame(frameInfo.toArray(new FrameInfo[frameInfo.size()]), beforeSrcFrame, afterSrcFrame); + int frameIndex = createFrame(frameInfo.toArray(new FrameInfo[0]), beforeSrcFrame, afterSrcFrame); if (afterDstFrame != null) { afterDstFrame.accept(dd, frameIndex); } @@ -1402,7 +1401,6 @@ protected float getSelectionCircleStrokeSize() { * * @param g the {@code Graphics2D} instance of the image. * @param center center position of the circle. - * @param color the circle color. Specify {@code null} to use global defaults. * @param strokeSize the thickness of the selection circle. */ protected void drawSelectionCircle(Graphics2D g, Point center, float strokeSize) { @@ -1490,7 +1488,7 @@ protected int[] getColorData(int colorIndex, boolean allowRandom) { try { retVal = SpriteUtils.getColorGradient(colorIndex, allowRandom); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; } diff --git a/src/org/infinity/resource/cre/decoder/tables/InfinityTables.java b/src/org/infinity/resource/cre/decoder/tables/InfinityTables.java index 5adcfa3c4..5f6829df4 100644 --- a/src/org/infinity/resource/cre/decoder/tables/InfinityTables.java +++ b/src/org/infinity/resource/cre/decoder/tables/InfinityTables.java @@ -20,6 +20,7 @@ import org.infinity.util.IdsMap; import org.infinity.util.IdsMapEntry; import org.infinity.util.IniMap; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -57,7 +58,7 @@ public static List createIniMaps(int animationId) { IdsMap table = new IdsMap(entry); retVal.addAll(processTable(table, animationId)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -95,9 +96,9 @@ private static List processTable(IdsMap idsMap, int animationId) { } } catch (InvocationTargetException ite) { if (ite.getCause() != null) { - ite.getCause().printStackTrace(); + Logger.error(ite.getCause()); } else { - ite.printStackTrace(); + Logger.error(ite); } } catch (Exception e) { return retVal; @@ -113,7 +114,7 @@ private static String[] parseTableEntry(int animationId, String entry) throws Ex Misc.requireCondition(items.length > 5, "Infinity Animations table entry: too few entries"); String prefix = items[0].trim(); - Misc.requireCondition(prefix.length() > 0, "Animation prefix not available"); + Misc.requireCondition(!prefix.isEmpty(), "Animation prefix not available"); int space = Misc.toNumber(SpriteTables.valueToString(items, 3, "3"), 16, 3); Misc.requireCondition(space > 0, "Invalid personal space: " + space); @@ -171,7 +172,7 @@ private static String[] parseTableEntry(int animationId, String entry) throws Ex int split = -1; String height = ""; String heightShield = ""; - switch (animType) { + switch (Objects.requireNonNull(animType)) { case MONSTER_MULTI: case MONSTER_MULTI_NEW: split = 1; @@ -219,9 +220,7 @@ private static String[] parseTableEntry(int animationId, String entry) throws Ex retVal[SpriteTables.COLUMN_ELLIPSE] = Integer.toString(ellipse); retVal[SpriteTables.COLUMN_SPACE] = Integer.toString(space); retVal[SpriteTables.COLUMN_BLENDING] = "0"; - if (clown >= 0) { - retVal[SpriteTables.COLUMN_CLOWN] = Integer.toString(clown); - } + retVal[SpriteTables.COLUMN_CLOWN] = Integer.toString(clown); if (split >= 0) { retVal[SpriteTables.COLUMN_SPLIT] = Integer.toString(split); } diff --git a/src/org/infinity/resource/cre/decoder/tables/SpriteTables.java b/src/org/infinity/resource/cre/decoder/tables/SpriteTables.java index f0a7b896b..960f3c377 100644 --- a/src/org/infinity/resource/cre/decoder/tables/SpriteTables.java +++ b/src/org/infinity/resource/cre/decoder/tables/SpriteTables.java @@ -11,6 +11,7 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.EnumMap; import java.util.List; @@ -21,6 +22,7 @@ import org.infinity.resource.key.BufferedResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.IniMap; +import org.infinity.util.Logger; import org.infinity.util.Table2da; /** @@ -63,18 +65,18 @@ public class SpriteTables { private static final EnumMap> TABLE_MAPS = new EnumMap<>(Profile.Game.class); static { - TABLE_MAPS.put(Profile.Game.BG1, Arrays.asList("avatars-bg1.2da")); + TABLE_MAPS.put(Profile.Game.BG1, Collections.singletonList("avatars-bg1.2da")); TABLE_MAPS.put(Profile.Game.BG1TotSC, TABLE_MAPS.get(Profile.Game.BG1)); - TABLE_MAPS.put(Profile.Game.IWD, Arrays.asList("avatars-iwd.2da")); + TABLE_MAPS.put(Profile.Game.IWD, Collections.singletonList("avatars-iwd.2da")); TABLE_MAPS.put(Profile.Game.IWDHoW, Arrays.asList("avatars-iwdhow.2da", "avatars-iwd.2da")); TABLE_MAPS.put(Profile.Game.IWDHowTotLM, TABLE_MAPS.get(Profile.Game.IWDHoW)); - TABLE_MAPS.put(Profile.Game.IWD2, Arrays.asList("avatars-iwd2.2da")); + TABLE_MAPS.put(Profile.Game.IWD2, Collections.singletonList("avatars-iwd2.2da")); - TABLE_MAPS.put(Profile.Game.PST, Arrays.asList("avatars-pst.2da")); + TABLE_MAPS.put(Profile.Game.PST, Collections.singletonList("avatars-pst.2da")); - TABLE_MAPS.put(Profile.Game.BG2SoA, Arrays.asList("avatars-bg2soa.2da")); + TABLE_MAPS.put(Profile.Game.BG2SoA, Collections.singletonList("avatars-bg2soa.2da")); TABLE_MAPS.put(Profile.Game.BG2ToB, Arrays.asList("avatars-bg2tob.2da", "avatars-bg2soa.2da")); TABLE_MAPS.put(Profile.Game.Tutu, TABLE_MAPS.get(Profile.Game.BG2ToB)); TABLE_MAPS.put(Profile.Game.BGT, TABLE_MAPS.get(Profile.Game.BG2ToB)); @@ -88,7 +90,7 @@ public class SpriteTables { TABLE_MAPS.put(Profile.Game.IWDEE, Arrays.asList("avatars-iwdee.2da", "avatars-bgee.2da", "avatars-bg2ee.2da")); - TABLE_MAPS.put(Profile.Game.PSTEE, Arrays.asList("avatars-pstee.2da")); + TABLE_MAPS.put(Profile.Game.PSTEE, Collections.singletonList("avatars-pstee.2da")); } @@ -113,12 +115,11 @@ public static List createIniMaps(int animationId) { * could be determined. */ public static List createIniMaps(Profile.Game game, int animationId) { - List retVal = new ArrayList<>(); if (game == null) { game = Profile.getGame(); } - retVal.addAll(processInfinityAnimations(animationId)); + List retVal = new ArrayList<>(processInfinityAnimations(animationId)); if (retVal.isEmpty()) { List tableNames = findTables(game); @@ -126,12 +127,10 @@ public static List createIniMaps(Profile.Game game, int animationId) { ResourceEntry tableEntry = getTableResource(tableName); if (tableEntry != null) { Table2da table = new Table2da(tableEntry); - if (table != null) { - List inis = processTable(game, table, animationId); - if (inis != null && !inis.isEmpty()) { - retVal.addAll(inis); - break; - } + List inis = processTable(game, table, animationId); + if (inis != null && !inis.isEmpty()) { + retVal.addAll(inis); + break; } } } @@ -206,12 +205,12 @@ private static List processTable(Table2da table, int animationId) { } } catch (InvocationTargetException ite) { if (ite.getCause() != null) { - ite.getCause().printStackTrace(); + Logger.error(ite.getCause()); } else { - ite.printStackTrace(); + Logger.error(ite); } } catch (NoSuchMethodException | IllegalAccessException e) { - e.printStackTrace(); + Logger.error(e); } } @@ -291,6 +290,7 @@ public static String valueToString(String[] arr, int arrIdx, String defValue) { retVal = defValue; } } catch (Exception e) { + Logger.trace(e); } return retVal; } @@ -306,6 +306,7 @@ public static int valueToInt(String[] arr, int arrIdx, int defValue) { retVal = Integer.parseInt(s); } } catch (NullPointerException | ArrayIndexOutOfBoundsException | NumberFormatException e) { + Logger.trace(e); } return retVal; } @@ -377,6 +378,7 @@ public static ResourceEntry getTableResource(String fileName) { entry = new BufferedResourceEntry(ByteBuffer.wrap(bos.toByteArray()), fileName); } } catch (Exception e) { + Logger.trace(e); } return entry; } diff --git a/src/org/infinity/resource/cre/decoder/util/AnimationInfo.java b/src/org/infinity/resource/cre/decoder/util/AnimationInfo.java index f3e17033c..9dea2dfa6 100644 --- a/src/org/infinity/resource/cre/decoder/util/AnimationInfo.java +++ b/src/org/infinity/resource/cre/decoder/util/AnimationInfo.java @@ -6,11 +6,13 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import org.infinity.resource.Profile; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.tuples.Couple; @@ -36,20 +38,20 @@ public class AnimationInfo { private static final EnumSet TYPE_GAME_ALL = EnumSet.complementOf(EnumSet.of(Profile.Game.Unknown, Profile.Game.PST)); // Predefined slot ranges for specific animation types - private static final List RANGE_EFFECT = Arrays.asList(new NumberRange(0, 0xfff)); - private static final List RANGE_MONSTER_QUADRANT = Arrays.asList(new NumberRange(0x1000, 0x1ff)); + private static final List RANGE_EFFECT = Collections.singletonList(new NumberRange(0, 0xfff)); + private static final List RANGE_MONSTER_QUADRANT = Collections.singletonList(new NumberRange(0x1000, 0x1ff)); private static final List RANGE_MONSTER_MULTI = Arrays.asList(new NumberRange(0x1200, 0xff), new NumberRange(0x1400, 0xbff)); - private static final List RANGE_MONSTER_MULTI_NEW = Arrays.asList(new NumberRange(0x1300, 0xff)); - private static final List RANGE_MONSTER_LAYERED = Arrays.asList(new NumberRange(0x8000, 0xfff)); - private static final List RANGE_MONSTER_LAYERED_SPELL = Arrays.asList(new NumberRange(0x2000, 0xfff)); - private static final List RANGE_MONSTER_ANKHEG = Arrays.asList(new NumberRange(0x3000, 0xfff)); - private static final List RANGE_TOWN_STATIC = Arrays.asList(new NumberRange(0x4000, 0xfff)); + private static final List RANGE_MONSTER_MULTI_NEW = Collections.singletonList(new NumberRange(0x1300, 0xff)); + private static final List RANGE_MONSTER_LAYERED = Collections.singletonList(new NumberRange(0x8000, 0xfff)); + private static final List RANGE_MONSTER_LAYERED_SPELL = Collections.singletonList(new NumberRange(0x2000, 0xfff)); + private static final List RANGE_MONSTER_ANKHEG = Collections.singletonList(new NumberRange(0x3000, 0xfff)); + private static final List RANGE_TOWN_STATIC = Collections.singletonList(new NumberRange(0x4000, 0xfff)); private static final List RANGE_CHARACTER = Arrays.asList(new NumberRange(0x5000, 0x3ff), new NumberRange(0x5500, 0xff), new NumberRange(0x6000, 0x3ff), new NumberRange(0x6500, 0xff)); - private static final List RANGE_CHARACTER_IA = Arrays.asList(new NumberRange(0x6600, 0x4ff)); + private static final List RANGE_CHARACTER_IA = Collections.singletonList(new NumberRange(0x6600, 0x4ff)); private static final List RANGE_CHARACTER_OLD = Arrays.asList(new NumberRange(0x5400, 0xff), new NumberRange(0x5600, 0x9ff), new NumberRange(0x6400, 0xff), @@ -65,7 +67,7 @@ public class AnimationInfo { new NumberRange(0x7002, 0xd, 0xc0, 0x0f, 4), new NumberRange(0x7002, 0xd, 0xe0, 0x0f, 4), new NumberRange(0x7000, 0xf, 0xf0, 0x0f, 4)); - private static final List RANGE_MONSTER_IA = Arrays.asList(new NumberRange(0x5b00, 0x4ff)); + private static final List RANGE_MONSTER_IA = Collections.singletonList(new NumberRange(0x5b00, 0x4ff)); private static final List RANGE_MONSTER_OLD = Arrays.asList(new NumberRange(0x7000, 0x1, 0x00, 0x1f, 4), new NumberRange(0x7000, 0x3, 0x20, 0x0f, 4), new NumberRange(0x7000, 0x2, 0x40, 0x0f, 4), @@ -78,24 +80,24 @@ public class AnimationInfo { new NumberRange(0x7000, 0x1, 0xc0, 0x0f, 4), new NumberRange(0x7000, 0xf, 0xd0, 0x0f, 4), new NumberRange(0x7000, 0x1, 0xe0, 0x0f, 4)); - private static final List RANGE_MONSTER_OLD_IA = Arrays.asList(new NumberRange(0x547a, 0x479)); - private static final List RANGE_MONSTER_LARGE = Arrays.asList(new NumberRange(0x9000, 0xfff)); - private static final List RANGE_MONSTER_LARGE_16 = Arrays.asList(new NumberRange(0xa000, 0xfff)); - private static final List RANGE_AMBIENT_STATIC = Arrays.asList(new NumberRange(0xb000, 0xfff)); - private static final List RANGE_AMBIENT = Arrays.asList(new NumberRange(0xc000, 0xfff)); - private static final List RANGE_FLYING = Arrays.asList(new NumberRange(0xd000, 0xfff)); - private static final List RANGE_MONSTER_ICEWIND = Arrays.asList(new NumberRange(0xe000, 0xfff)); - private static final List RANGE_MONSTER_ICEWIND_EX = Arrays.asList(new NumberRange(0xe000, 0x1fff)); - private static final List RANGE_MONSTER_ICEWIND_IA = Arrays.asList(new NumberRange(0x5000, 0x478)); - private static final List RANGE_MONSTER_PLANESCAPE = Arrays.asList(new NumberRange(0xf000, 0xfff)); - private static final List RANGE_MONSTER_PLANESCAPE_EX = Arrays.asList(new NumberRange(0x0000, 0xffff)); + private static final List RANGE_MONSTER_OLD_IA = Collections.singletonList(new NumberRange(0x547a, 0x479)); + private static final List RANGE_MONSTER_LARGE = Collections.singletonList(new NumberRange(0x9000, 0xfff)); + private static final List RANGE_MONSTER_LARGE_16 = Collections.singletonList(new NumberRange(0xa000, 0xfff)); + private static final List RANGE_AMBIENT_STATIC = Collections.singletonList(new NumberRange(0xb000, 0xfff)); + private static final List RANGE_AMBIENT = Collections.singletonList(new NumberRange(0xc000, 0xfff)); + private static final List RANGE_FLYING = Collections.singletonList(new NumberRange(0xd000, 0xfff)); + private static final List RANGE_MONSTER_ICEWIND = Collections.singletonList(new NumberRange(0xe000, 0xfff)); + private static final List RANGE_MONSTER_ICEWIND_EX = Collections.singletonList(new NumberRange(0xe000, 0x1fff)); + private static final List RANGE_MONSTER_ICEWIND_IA = Collections.singletonList(new NumberRange(0x5000, 0x478)); + private static final List RANGE_MONSTER_PLANESCAPE = Collections.singletonList(new NumberRange(0xf000, 0xfff)); + private static final List RANGE_MONSTER_PLANESCAPE_EX = Collections.singletonList(new NumberRange(0x0000, 0xffff)); public enum Type { /** Animation type: 0000 */ - EFFECT(0x0000, "effect", Arrays.asList( + EFFECT(0x0000, "effect", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_EFFECT))), // type=0 /** Animation type: 1000 (slots [1000..11ff]) */ - MONSTER_QUADRANT(0x1000, "monster_quadrant", Arrays.asList( + MONSTER_QUADRANT(0x1000, "monster_quadrant", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_QUADRANT))), // type=1 /** Animation type: 1000 (slots [1200..12ff], [1400..1fff] */ MONSTER_MULTI(0x1000, "monster_multi", Arrays.asList( @@ -107,16 +109,16 @@ public enum Type { Couple.with(TYPE_GAME_EE, RANGE_MONSTER_MULTI_NEW), Couple.with(TYPE_GAME_BG2_TOB, RANGE_MONSTER_MULTI_NEW))), // type=3 /** Animation type: 8000 */ - MONSTER_LAYERED(0x8000, "monster_layered", Arrays.asList( + MONSTER_LAYERED(0x8000, "monster_layered", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_LAYERED))), // type=4 /** Animation type: 2000 */ - MONSTER_LAYERED_SPELL(0x2000, "monster_layered_spell", Arrays.asList( + MONSTER_LAYERED_SPELL(0x2000, "monster_layered_spell", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_LAYERED_SPELL))), // type=5 /** Animation type: 3000 */ - MONSTER_ANKHEG(0x3000, "monster_ankheg", Arrays.asList( + MONSTER_ANKHEG(0x3000, "monster_ankheg", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_ANKHEG))), // type=6 /** Animation type: 4000 */ - TOWN_STATIC(0x4000, "town_static", Arrays.asList( + TOWN_STATIC(0x4000, "town_static", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_TOWN_STATIC))), // type=7 /** Animation types: 5000, 6000 (slots [5000..53ff], [5500..55ff], [6000..63ff], [6500..65ff]) */ CHARACTER(new int[] {0x5000, 0x6000}, "character", Arrays.asList( @@ -139,23 +141,23 @@ public enum Type { Couple.with(TYPE_GAME_IWD2, RANGE_MONSTER)), RANGE_MONSTER_IA), // type=10 /** Animation type: 7000 (many subranges) */ - MONSTER_OLD(0x7000, "monster_old", Arrays.asList( + MONSTER_OLD(0x7000, "monster_old", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_OLD)), RANGE_MONSTER_OLD_IA), // type=11 /** Animation type: 9000 */ - MONSTER_LARGE(0x9000, "monster_large", Arrays.asList( + MONSTER_LARGE(0x9000, "monster_large", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_LARGE))), // type=12 /** Animation type: A000 */ - MONSTER_LARGE_16(0xa000, "monster_large16", Arrays.asList( + MONSTER_LARGE_16(0xa000, "monster_large16", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_MONSTER_LARGE_16))), // type=13 /** Animation type: B000 */ - AMBIENT_STATIC(0xb000, "ambient_static", Arrays.asList( + AMBIENT_STATIC(0xb000, "ambient_static", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_AMBIENT_STATIC))), // type=14 /** Animation type: C000 */ - AMBIENT(0xc000, "ambient", Arrays.asList( + AMBIENT(0xc000, "ambient", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_AMBIENT))), // type=15 /** Animation type: D000 */ - FLYING(0xd000, "flying", Arrays.asList( + FLYING(0xd000, "flying", Collections.singletonList( Couple.with(TYPE_GAME_ALL, RANGE_FLYING))), // type=16 /** Animation type: E000 (for non-EE: also slots [f000..ffff]) */ MONSTER_ICEWIND(0xe000, "monster_icewind", Arrays.asList( @@ -174,7 +176,7 @@ public enum Type { PLACEHOLDER(new int[] {0x0000, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, 0x9000, 0xa000, 0xb000, 0xc000, 0xd000, 0xe000, 0xf000}, "placeholder", - Arrays.asList(Couple.with(TYPE_GAME_ALL, Arrays.asList(new NumberRange(0x0000, 0xffff)))), + Collections.singletonList(Couple.with(TYPE_GAME_ALL, Collections.singletonList(new NumberRange(0x0000, 0xffff)))), null); private final EnumMap> rangeMap = new EnumMap<>(Profile.Game.class); @@ -216,7 +218,7 @@ private Type(int[] types, String sectionName, List, } /** - * @param type list of slot base ranges + * @param types list of slot base ranges * @param sectionName INI section name * @param entries list of games and their associated slot ranges. * @throws IllegalArgumentException @@ -231,6 +233,7 @@ private Type(int[] types, String sectionName, List, } catch (IllegalArgumentException iae) { throw iae; } catch (Exception e) { + Logger.trace(e); } this.animationTypes = types; this.sectionName = sectionName; @@ -238,7 +241,7 @@ private Type(int[] types, String sectionName, List, EnumSet games = entry.getValue0(); List ranges = entry.getValue1(); for (final Profile.Game game : games) { - if (ranges.size() > 0) { + if (!ranges.isEmpty()) { List list = this.rangeMap.get(game); if (list != null) { list.addAll(ranges); diff --git a/src/org/infinity/resource/cre/decoder/util/CreatureInfo.java b/src/org/infinity/resource/cre/decoder/util/CreatureInfo.java index 373a99c09..cfd91bb68 100644 --- a/src/org/infinity/resource/cre/decoder/util/CreatureInfo.java +++ b/src/org/infinity/resource/cre/decoder/util/CreatureInfo.java @@ -29,6 +29,7 @@ import org.infinity.resource.cre.decoder.MonsterPlanescapeDecoder; import org.infinity.resource.cre.decoder.SpriteDecoder; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; @@ -376,7 +377,7 @@ public ItemInfo getItemInfo(ItemSlots slot) { /** * Returns a list of equipped items in the order of effect application. * - * @return List of {@code ItemInfo} instances in the order of effect application. + * @return Array of {@code ItemInfo} instances in the order of effect application. */ public ItemInfo[] getEffectiveItemInfo() { ArrayList items = new ArrayList<>(); @@ -388,7 +389,7 @@ public ItemInfo[] getEffectiveItemInfo() { } } - return items.toArray(new ItemInfo[items.size()]); + return items.toArray(new ItemInfo[0]); } /** Provides access to the {@link EffectInfo} instance which manages effects attached to the current creature. */ @@ -526,7 +527,6 @@ public int getColorValue(SegmentDef.SpriteType type, int locationIndex) { * Returns the color entry of the specified location index for the avatar sprite after applying all equipment and * effect colors as well as the source of the color value. * - * @param opcode filter by this opcode. * @param locationIndex the color location index. Available range: [-1, 6] * @return a tuple with the color entry as well as a {@code Boolean} value indicating whether random colors are * allowed. Returns {@code -1} for the color entry if value could not be determined. @@ -893,7 +893,7 @@ private void initEquipmentItem(ItemSlots slot, int itemIndex, List itemInfo.overrideDroppableFlag(isUndroppable); equipment.put(slot, itemInfo); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1016,6 +1016,7 @@ private int getEffectiveWeaponIndex(int slotIndex) { break; } } catch (Exception e) { + Logger.trace(e); } } } diff --git a/src/org/infinity/resource/cre/decoder/util/CycleDef.java b/src/org/infinity/resource/cre/decoder/util/CycleDef.java index aebdbbfb0..7bb727544 100644 --- a/src/org/infinity/resource/cre/decoder/util/CycleDef.java +++ b/src/org/infinity/resource/cre/decoder/util/CycleDef.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -99,7 +98,7 @@ public CycleDef(DirDef parent, Collection cycleInfo) { * Creates a new cycle definition with the attributes defined in the specified {@code CycleDef} argument. Parent * attribute is set to {@code null}. * - * @param sd the {@code CycleDef} object to clone. + * @param cd the {@code CycleDef} object to clone. */ public CycleDef(CycleDef cd) { Objects.requireNonNull(cd, "CycleDef instance cannot be null"); @@ -143,9 +142,9 @@ public void addCycle(ResourceEntry bamResource, int cycle, SegmentDef.SpriteType /** Adds new cycle definitions. */ public void addCycles(Collection cycleInfo) { - for (Iterator iter = cycleInfo.iterator(); iter.hasNext();) { - final SegmentDef sd = Objects.requireNonNull(iter.next(), "Segment definition cannot be null"); - if (!this.cycles.stream().anyMatch(sd2 -> sd2.equals(sd))) { + for (SegmentDef segmentDef : cycleInfo) { + final SegmentDef sd = Objects.requireNonNull(segmentDef, "Segment definition cannot be null"); + if (this.cycles.stream().noneMatch(sd2 -> sd2.equals(sd))) { sd.setParent(this); this.cycles.add(sd); } diff --git a/src/org/infinity/resource/cre/decoder/util/EffectInfo.java b/src/org/infinity/resource/cre/decoder/util/EffectInfo.java index 93a5507ab..f7f1431e5 100644 --- a/src/org/infinity/resource/cre/decoder/util/EffectInfo.java +++ b/src/org/infinity/resource/cre/decoder/util/EffectInfo.java @@ -24,6 +24,7 @@ import org.infinity.resource.cre.CreResource; import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.spl.SplResource; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; @@ -239,7 +240,7 @@ public List getEffects(CreatureInfo creInfo, SegmentDef.SpriteType type, Set set = effectMap.get(type); if (set != null) { - set.stream().filter(pred.and(e -> isEffectValid(e, creInfo))).forEach(fx -> retVal.add(fx)); + set.stream().filter(pred.and(e -> isEffectValid(e, creInfo))).forEach(retVal::add); } return retVal; @@ -276,7 +277,7 @@ public boolean hasEffect(SegmentDef.SpriteType type, Predicate pred) { Set set = effectMap.get(type); if (set != null) { - set.stream().anyMatch(pred); + return set.stream().anyMatch(pred); } return false; @@ -314,11 +315,7 @@ public void add(Effect effect) { List effects = resolveEffect(null, effect); for (final Effect fx : effects) { SegmentDef.SpriteType type = getEffectType(fx); - Set set = effectMap.get(type); - if (set == null) { - set = new HashSet<>(); - effectMap.put(type, set); - } + Set set = effectMap.computeIfAbsent(type, k -> new HashSet<>()); set.add(fx); } } @@ -462,7 +459,7 @@ private void resolveSPL(List list, Effect parent, ResourceEntry entry) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -476,7 +473,7 @@ private void resolveEFF(List list, Effect parent, ResourceEntry entry) { final List retList = resolveEffect(parent, Effect.fromEffectV2(entry.getResourceBuffer(), 8)); list.addAll(retList); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -507,8 +504,7 @@ private boolean evaluateItemCategory(CreatureInfo creInfo, int cat) { * Evaluates the IDS filter specified by type and entry value for the given target. * * @param creInfo creature target - * @param type the IDS resource type - * @param entry the IDS entry index + * @param effect the effect structure * @return whether creature stat matches reference stat. */ private boolean evaluateIds(CreatureInfo creInfo, Effect effect) { @@ -868,7 +864,7 @@ public static class Effect { /** Convenience method for creating an {@code Effect} instance from a byte array containing EFF V1 data. */ public static Effect fromEffectV1(ByteBuffer buf, int startOfs) { - Effect retVal = new Effect(buf.order(ByteOrder.LITTLE_ENDIAN).getShort(0x0 + startOfs)); + Effect retVal = new Effect(buf.order(ByteOrder.LITTLE_ENDIAN).getShort(startOfs)); retVal.initEffectV1(buf, startOfs); return retVal; } diff --git a/src/org/infinity/resource/cre/decoder/util/ItemInfo.java b/src/org/infinity/resource/cre/decoder/util/ItemInfo.java index 21639de04..3efaebb39 100644 --- a/src/org/infinity/resource/cre/decoder/util/ItemInfo.java +++ b/src/org/infinity/resource/cre/decoder/util/ItemInfo.java @@ -21,6 +21,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -147,7 +148,7 @@ public enum SlotType { boolean retVal = FILTER_EQUIPPABLE.test(info); retVal &= (info.getAbilityCount() > 0); if (retVal) { - retVal &= (info.getAbility(0).getLocation() == 1); // weapon slot + retVal = (info.getAbility(0).getLocation() == 1); // weapon slot retVal &= (info.getAbility(0).getLauncher() == 0); // no launcher required } return retVal; @@ -161,7 +162,7 @@ public enum SlotType { retVal &= (info.getAbilityCount() > 0); if (retVal) { int mask = Profile.isEnhancedEdition() ? 0x1002 : 0x2; // two-handed, fake two-handed - retVal &= (info.getFlags() & mask) != 0; + retVal = (info.getFlags() & mask) != 0; } return retVal; }; @@ -188,7 +189,7 @@ public enum SlotType { boolean retVal = FILTER_WEAPON_MELEE.test(info); if (retVal) { int mask = Profile.isEnhancedEdition() ? 0x1002 : 0x2; - retVal &= (info.getFlags() & mask) != 0; + retVal = (info.getFlags() & mask) != 0; } return retVal; }; @@ -216,7 +217,7 @@ public enum SlotType { retVal &= (info.getAbilityCount() > 0); if (retVal) { AbilityEntry ai = info.getAbility(0); - retVal &= (ai.getLauncher() == 0); + retVal = (ai.getLauncher() == 0); retVal &= (ai.getAbilityType() == 2) || (ai.getAbilityType() == 4); } return retVal; @@ -231,7 +232,7 @@ public enum SlotType { retVal &= (info.getAbilityCount() > 0); if (retVal) { AbilityEntry ai = info.getAbility(0); - retVal &= (ai.getLauncher() == 0); + retVal = (ai.getLauncher() == 0); retVal &= (ai.getAbilityType() == 4); } return retVal; @@ -373,7 +374,7 @@ public static void clearCache() { /** * Removes the specified ITM {@code ResourceEntry} instances from the cache. * - * @param entries Sequence of ITM {@codee ResourceEntry} instances to remove from the cache. + * @param entries Sequence of ITM {@code ResourceEntry} instances to remove from the cache. * @return Number of successfully removed entries. */ public static int removeFromCache(ResourceEntry... entries) { @@ -411,6 +412,7 @@ public static List getItemList(ItemPredicate pred, boolean sorted) { retVal.add(ii); } } catch (Exception e) { + Logger.trace(e); } } @@ -430,7 +432,7 @@ public static boolean testAll(ItemInfo info, ItemPredicate... pred) { if (retVal) { for (final ItemPredicate p : pred) { if (p != null) { - retVal &= p.test(info); + retVal = p.test(info); } if (!retVal) { break; @@ -445,18 +447,20 @@ public static boolean testAll(ItemInfo info, ItemPredicate... pred) { * {@code false} if info is {@code null}. Returns {@code true} if no predicate is specified. */ public static boolean testAny(ItemInfo info, ItemPredicate... pred) { - boolean retVal = (info != null); - if (retVal && pred.length > 0) { - for (final ItemPredicate p : pred) { - if (p != null) { - retVal |= p.test(info); - } - if (retVal) { - break; + if (info == null) { + return false; + } + if (pred.length == 0) { + return true; + } + for (final ItemPredicate p : pred) { + if (p != null) { + if (p.test(info)) { + return true; } } } - return retVal; + return false; } /** @@ -480,7 +484,7 @@ public static int getItemCategory(ResourceEntry itmEntry) { Misc.requireCondition(is.skip(0x14) == 0x14, "Could not advance in data stream"); return StreamUtils.readShort(is); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return -1; diff --git a/src/org/infinity/resource/cre/decoder/util/NumberRange.java b/src/org/infinity/resource/cre/decoder/util/NumberRange.java index b7d0a9be3..b9b7d55b5 100644 --- a/src/org/infinity/resource/cre/decoder/util/NumberRange.java +++ b/src/org/infinity/resource/cre/decoder/util/NumberRange.java @@ -43,7 +43,7 @@ public NumberRange(int base, int range, int subBase, int subRange, int subPos) { /** Returns whether the range covers the specified value. */ public boolean contains(int value) { return ranges.stream().anyMatch( - c -> (value >= c.getValue0().intValue() && value <= (c.getValue0().intValue() + c.getValue1().intValue()))); + c -> (value >= c.getValue0() && value <= (c.getValue0() + c.getValue1()))); } private void init(int base, int range, int subBase, int subRange, int subPos) { diff --git a/src/org/infinity/resource/cre/decoder/util/SegmentDef.java b/src/org/infinity/resource/cre/decoder/util/SegmentDef.java index e9b3c4d62..080892f9a 100644 --- a/src/org/infinity/resource/cre/decoder/util/SegmentDef.java +++ b/src/org/infinity/resource/cre/decoder/util/SegmentDef.java @@ -290,12 +290,10 @@ public void advance() { } break; case REVERSE_REPEAT: - if (curFrame > 0) { - curFrame--; - } else if (curFrame <= 0) { - curFrame = numFrames - 1; - } else if (curFrame >= getMaximumFrames() - 1) { + if (curFrame >= getMaximumFrames() - 1 || curFrame <= 0) { curFrame = numFrames - 1; + } else { + curFrame--; } break; case REVERSE_SINGLE: diff --git a/src/org/infinity/resource/cre/decoder/util/SeqDef.java b/src/org/infinity/resource/cre/decoder/util/SeqDef.java index 2c9325438..fa6f68ead 100644 --- a/src/org/infinity/resource/cre/decoder/util/SeqDef.java +++ b/src/org/infinity/resource/cre/decoder/util/SeqDef.java @@ -12,7 +12,6 @@ import java.util.List; import java.util.Objects; -import org.infinity.resource.cre.decoder.SpriteDecoder; import org.infinity.resource.key.ResourceEntry; /** @@ -151,7 +150,7 @@ public static ResourceEntry[] getBamResourceList(SegmentDef.SpriteType type, Seq } } } - return resources.toArray(new ResourceEntry[resources.size()]); + return resources.toArray(new ResourceEntry[0]); } /** @@ -159,7 +158,7 @@ public static ResourceEntry[] getBamResourceList(SegmentDef.SpriteType type, Seq * resource. Behavior is assumed to be {@link SegmentDef.Behavior#REPEAT}. Composite object is initialized with * {@link AlphaComposite#SrcOver}. * - * @param seq the animation {@link SpriteDecoder.Sequence}. + * @param seq the animation {@link Sequence}. * @param directions List of directions to add. Cycle indices are advanced accordingly for each direction. * @param mirrored indicates whether cycle indices are calculated in reversed direction * @param bamResource the BAM resource used for all cycle definitions. @@ -180,7 +179,7 @@ public static SeqDef createSequence(Sequence seq, Direction[] directions, boolea * Convenience method: Creates a fully defined sequence if specified directions are found within a single BAM * resource. Composite object is initialized with {@link AlphaComposite#SrcOver}. * - * @param seq the animation {@link SpriteDecoder.Sequence}. + * @param seq the animation {@link Sequence}. * @param directions List of directions to add. Cycle indices are advanced accordingly for each direction. * @param mirrored indicates whether cycle indices are calculated in reversed direction * @param bamResource the BAM resource used for all cycle definitions. @@ -202,7 +201,7 @@ public static SeqDef createSequence(Sequence seq, Direction[] directions, boolea * Convenience method: Creates a fully defined sequence if specified directions are found within a single BAM * resource. * - * @param seq the animation {@link SpriteDecoder.Sequence}. + * @param seq the animation {@link Sequence}. * @param directions List of directions to add. Cycle indices are advanced accordingly for each direction. * @param mirrored indicates whether cycle indices are calculated in reversed direction * @param bamResource the BAM resource used for all cycle definitions. @@ -224,7 +223,7 @@ public static SeqDef createSequence(Sequence seq, Direction[] directions, boolea /** * Convenience method: Creates a fully defined sequence for all directions and their associated segment definitions. * - * @param seq the animation {@link SpriteDecoder.Sequence}. + * @param seq the animation {@link Sequence}. * @param directions List of directions to add. Cycle indices are advanced accordingly for each direction. * @param mirrored indicates whether cycle indices are calculated in reversed direction * @param cycleInfo collection of {@link SegmentDef} instances that are to be associated with the directions. diff --git a/src/org/infinity/resource/cre/decoder/util/SpriteUtils.java b/src/org/infinity/resource/cre/decoder/util/SpriteUtils.java index 6d41a2181..8db51f420 100644 --- a/src/org/infinity/resource/cre/decoder/util/SpriteUtils.java +++ b/src/org/infinity/resource/cre/decoder/util/SpriteUtils.java @@ -60,6 +60,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.Table2da; import org.infinity.util.Table2daCache; @@ -321,19 +322,17 @@ public static CreResource getPseudoCre(int animationId, HashMap } } - if (buffer != null) { - buffer.putInt(0x08, -1); // creature name - buffer.putInt(0x0c, -1); // creature tooltip - buffer.putInt(0x28, animationId); - if (equipment != null) { - for (final HashMap.Entry itm : equipment.entrySet()) { - addPseudoCreItem(buffer, itm.getKey(), itm.getValue()); - } + buffer.putInt(0x08, -1); // creature name + buffer.putInt(0x0c, -1); // creature tooltip + buffer.putInt(0x28, animationId); + if (equipment != null) { + for (final HashMap.Entry itm : equipment.entrySet()) { + addPseudoCreItem(buffer, itm.getKey(), itm.getValue()); } - - entry = new CreResource(null, String.format("%04X", animationId & 0xffff), buffer, 0); } + entry = new CreResource(null, String.format("%04X", animationId & 0xffff), buffer, 0); + return entry; } @@ -448,7 +447,7 @@ public static Couple loadBamDecoderCont retVal = Couple.with(decoder, control); BAM_CACHE.put(entry, retVal); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -468,6 +467,7 @@ public static boolean bamCyclesExist(ResourceEntry entry, int cycle, int length) int numCycles = control.cycleCount(); return (numCycles >= cycle + length && control.cycleFrameCount(cycle) > 0); } catch (Exception e) { + Logger.trace(e); } return false; } @@ -484,6 +484,7 @@ public static int getBamCycles(ResourceEntry entry) { BamV1Decoder.BamV1Control control = loadBamController(entry); retVal = control.cycleCount(); } catch (Exception e) { + Logger.trace(e); } return retVal; } @@ -503,6 +504,7 @@ public static int getBamCycleFrames(ResourceEntry entry, int cycleIdx) { retVal = control.cycleFrameCount(cycleIdx); } } catch (Exception e) { + Logger.trace(e); } return retVal; } @@ -531,6 +533,7 @@ public static boolean bamHasFalseColors(ResourceEntry entry) { retVal &= (palette[87] & 0xffffff) == 0x004000; } } catch (Exception e) { + Logger.trace(e); } return retVal; } @@ -591,13 +594,12 @@ public static int[] loadReplacementPalette(String resref, int index) { return retVal; } - String resName = resref; String suffix = (index >= 0) ? Integer.toString(index) : ""; String[] suffixList = (suffix.isEmpty()) ? new String[] { "" } : new String[] { suffix, "" }; ResourceEntry entry = null; for (final String s : suffixList) { - if (ResourceFactory.resourceExists(resName + s + ".BMP")) { - entry = ResourceFactory.getResourceEntry(resName + s + ".BMP"); + if (ResourceFactory.resourceExists(resref + s + ".BMP")) { + entry = ResourceFactory.getResourceEntry(resref + s + ".BMP"); break; } } @@ -609,14 +611,12 @@ public static int[] loadReplacementPalette(String resref, int index) { if (retVal == null) { try { retVal = ColorConvert.loadPaletteBMP(entry); - if (retVal != null) { - if (retVal.length < 256) { - retVal = Arrays.copyOf(retVal, 256); - } - PALETTE_CACHE.put(entry, retVal); + if (retVal.length < 256) { + retVal = Arrays.copyOf(retVal, 256); } + PALETTE_CACHE.put(entry, retVal); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -711,7 +711,7 @@ public static int[] getColorGradient(int index, boolean allowRandom) { COLOR_GRADIENTS.put(y, pixels); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else { // dummy entry to skip continuous gradient initialization attempts if gradient bitmap isn't available @@ -1017,10 +1017,8 @@ public static Class getSpriteDecoderClass(int animation * animation info could be assembled. */ public static IniMap getAnimationInfo(int animationId) { - List retVal = new ArrayList<>(); - // 1. look up existing INI resource - retVal.addAll(getAnimationInfoByIni(animationId)); + List retVal = new ArrayList<>(getAnimationInfoByIni(animationId)); if (retVal.isEmpty()) { // 2. look up hardcoded tables @@ -1048,8 +1046,7 @@ public static IniMap getAnimationInfo(int animationId) { public static Class detectAnimationType(int animationId) { Class retVal = null; - List iniList = new ArrayList<>(); - iniList.addAll(getAnimationInfoByIni(animationId)); + List iniList = new ArrayList<>(getAnimationInfoByIni(animationId)); if (iniList.isEmpty()) { iniList.addAll(getAnimationInfoByTable(animationId)); @@ -1191,15 +1188,16 @@ private static boolean isSpriteDecoderAvailable(Class s try { Constructor ctor = spriteClass.getConstructor(int.class, IniMap.class); - if (ctor != null) { - for (final IniMap ini : iniList) { - try { - retVal = (ctor.newInstance(animationId, ini).getClass() != null); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { - } + for (final IniMap ini : iniList) { + try { + ctor.newInstance(animationId, ini); + retVal = true; + } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { + Logger.trace(e); } } } catch (NoSuchMethodException e) { + Logger.trace(e); } return retVal; @@ -1268,7 +1266,7 @@ private static List guessIniMaps(int animationId) { try { String key = entry.getKey(); int id = (key.startsWith("0x") || key.startsWith("0X")) - ? Misc.toNumber(key.substring(2, key.length()), 16, -1) + ? Misc.toNumber(key.substring(2), 16, -1) : Misc.toNumber(key, -1); if (id == animationId) { String value = entry.getValue(); @@ -1279,7 +1277,7 @@ private static List guessIniMaps(int animationId) { break; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1460,7 +1458,7 @@ private static List guessIniMaps(int animationId) { break; case MONSTER_ICEWIND: { boolean found = false; - if (resref.length() >= 4 && !found) { + if (resref.length() >= 4) { for (final String suffix : new String[] { "A1", "A2", "A3", "A4", "CA", "DE", "GH", "GU", "SC", "SD", "SL", "SP", "TW", "WK" }) { if (ResourceFactory.resourceExists(resref + suffix + ".BAM")) { @@ -1547,7 +1545,7 @@ private static List guessIniMapsPst(int animationId) { ResourceEntry bamEntry = ResourceFactory.getResourceEntry(key + "b.bam"); if (bamEntry != null) { clown = SpriteUtils.bamHasFalseColors(bamEntry) ? 1 : 0; - resref = key.substring(0, 1) + key.substring(4, key.length()) + "b"; + resref = key.charAt(0) + key.substring(4) + "b"; break; } } diff --git a/src/org/infinity/resource/dlg/AbstractCode.java b/src/org/infinity/resource/dlg/AbstractCode.java index a32620809..5e42cee6d 100644 --- a/src/org/infinity/resource/dlg/AbstractCode.java +++ b/src/org/infinity/resource/dlg/AbstractCode.java @@ -45,6 +45,7 @@ import org.infinity.resource.bcs.Compiler; import org.infinity.resource.bcs.ScriptMessage; import org.infinity.resource.bcs.ScriptType; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.StreamUtils; @@ -69,12 +70,12 @@ public abstract class AbstractCode extends Datatype private SortedSet warnings; private String text; - AbstractCode(String name) { + protected AbstractCode(String name) { this(StreamUtils.getByteBuffer(8), 0, name); this.text = ""; } - AbstractCode(ByteBuffer buffer, int offset, String name) { + protected AbstractCode(ByteBuffer buffer, int offset, String name) { super(offset, 8, name); read(buffer, offset); this.text = (len.getValue() > 0) ? StreamUtils.readString(buffer, off.getValue(), len.getValue()) : ""; @@ -94,8 +95,8 @@ public void actionPerformed(ActionEvent event) { errors = compiler.getErrors(); warnings = compiler.getWarnings(); textArea.clearGutterIcons(); - if (errors.size() > 0) { - JMenuItem errorItems[] = new JMenuItem[errors.size()]; + if (!errors.isEmpty()) { + JMenuItem[] errorItems = new JMenuItem[errors.size()]; int count = 0; for (final ScriptMessage sm : errors) { textArea.setLineError(sm.getLine(), sm.getMessage(), false); @@ -103,8 +104,8 @@ public void actionPerformed(ActionEvent event) { } bpmErrors.setMenuItems(errorItems, false); } - if (warnings.size() > 0) { - JMenuItem warningItems[] = new JMenuItem[warnings.size()]; + if (!warnings.isEmpty()) { + JMenuItem[] warningItems = new JMenuItem[warnings.size()]; int count = 0; for (final ScriptMessage sm : warnings) { textArea.setLineWarning(sm.getLine(), sm.getMessage(), false); @@ -112,8 +113,8 @@ public void actionPerformed(ActionEvent event) { } bpmWarnings.setMenuItems(warningItems, false); } - bpmErrors.setEnabled(errors.size() > 0); - bpmWarnings.setEnabled(warnings.size() > 0); + bpmErrors.setEnabled(!errors.isEmpty()); + bpmWarnings.setEnabled(!warnings.isEmpty()); bpmErrors.setText("Errors (" + errors.size() + ")..."); bpmWarnings.setText("Warnings (" + warnings.size() + ")..."); bCheck.setEnabled(false); @@ -226,7 +227,7 @@ public boolean updateValue(AbstractStruct struct) { bCheck.doClick(); } if (!errors.isEmpty()) { - String options[] = { "Update", "Cancel" }; + String[] options = { "Update", "Cancel" }; if (JOptionPane.showOptionDialog(textArea.getTopLevelAncestor(), "Errors exist. Update anyway?", "Update value", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != JOptionPane.YES_OPTION) { @@ -325,7 +326,7 @@ public void addFlatList(List flatList) { ts.setOffset(off.getValue()); flatList.add(ts); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/resource/dlg/BrokenReference.java b/src/org/infinity/resource/dlg/BrokenReference.java index 4f234ffa2..f47321f06 100644 --- a/src/org/infinity/resource/dlg/BrokenReference.java +++ b/src/org/infinity/resource/dlg/BrokenReference.java @@ -9,5 +9,5 @@ * * @author Mingun */ -interface BrokenReference { +public interface BrokenReference { } diff --git a/src/org/infinity/resource/dlg/BrokenStateItem.java b/src/org/infinity/resource/dlg/BrokenStateItem.java index 17dee644a..a7346664a 100644 --- a/src/org/infinity/resource/dlg/BrokenStateItem.java +++ b/src/org/infinity/resource/dlg/BrokenStateItem.java @@ -15,7 +15,7 @@ * * @author Mingun */ -class BrokenStateItem extends StateItem implements BrokenReference { +public class BrokenStateItem extends StateItem implements BrokenReference { private static final ImageIcon ICON = Icons.ICON_WARNING_16.getIcon(); /** Dialog which contains non-existent state. */ diff --git a/src/org/infinity/resource/dlg/BrokenTransitionItem.java b/src/org/infinity/resource/dlg/BrokenTransitionItem.java index 58d261081..940d6090c 100644 --- a/src/org/infinity/resource/dlg/BrokenTransitionItem.java +++ b/src/org/infinity/resource/dlg/BrokenTransitionItem.java @@ -15,7 +15,7 @@ * * @author Mingun */ -final class BrokenTransitionItem extends TransitionItem implements BrokenReference { +public class BrokenTransitionItem extends TransitionItem implements BrokenReference { private static final ImageIcon ICON = Icons.ICON_WARNING_16.getIcon(); /** Number of non-existent response. */ diff --git a/src/org/infinity/resource/dlg/DlgElement.java b/src/org/infinity/resource/dlg/DlgElement.java index 07f86e783..a90497a4d 100644 --- a/src/org/infinity/resource/dlg/DlgElement.java +++ b/src/org/infinity/resource/dlg/DlgElement.java @@ -12,7 +12,7 @@ * * @author Mingun */ -final class DlgElement { +public class DlgElement { /** * All GUI items, that represent dialogue entry in the tree. Used for update tree when entry changes. */ @@ -30,6 +30,9 @@ final class DlgElement { */ ItemBase main; + public DlgElement() { + } + public void add(ItemBase item) { all.add(item); // The first added element becomes the main thing diff --git a/src/org/infinity/resource/dlg/DlgItem.java b/src/org/infinity/resource/dlg/DlgItem.java index 481cc5d95..e9b2e51bb 100644 --- a/src/org/infinity/resource/dlg/DlgItem.java +++ b/src/org/infinity/resource/dlg/DlgItem.java @@ -23,7 +23,7 @@ import org.infinity.resource.StructEntry; /** Meta class for identifying dialogue node. */ -final class DlgItem extends StateOwnerItem implements Iterable { +public class DlgItem extends StateOwnerItem implements Iterable { private static final ImageIcon ICON = Icons.ICON_ROW_INSERT_AFTER_16.getIcon(); private final DlgTreeModel parent; @@ -70,7 +70,7 @@ public DlgItem(DlgTreeModel parent, DlgResource dlg) { } } // Sort by weight or natural order - Collections.sort(states, new StateComparator()); + states.sort(new StateComparator()); } @Override @@ -95,7 +95,10 @@ public Icon getIcon() { @Override public boolean removeChild(ItemBase child) { - return states.remove(child); + if (child instanceof StateItem) { + return states.remove(child); + } + return false; } @Override @@ -120,7 +123,10 @@ public TreeNode getParent() { @Override public int getIndex(TreeNode node) { - return states.indexOf(node); + if (node instanceof StateItem) { + return states.indexOf(node); + } + return -1; } @Override @@ -194,7 +200,7 @@ public int compare(StateItem state1, StateItem state2) { if (idx1 < 0) { return (idx1 == idx2) ? 0 : 1; } else if (idx2 < 0) { - return (idx1 == idx2) ? 0 : -1; + return -1; } else { return idx1 - idx2; } diff --git a/src/org/infinity/resource/dlg/DlgResource.java b/src/org/infinity/resource/dlg/DlgResource.java index 2c497e1cf..e569044fc 100644 --- a/src/org/infinity/resource/dlg/DlgResource.java +++ b/src/org/infinity/resource/dlg/DlgResource.java @@ -48,6 +48,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.updater.Utils; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -189,10 +190,10 @@ public void write(OutputStream os) throws IOException { if (fields.size() > 12 && fields.get(12).getName().equalsIgnoreCase(DLG_THREAT_RESPONSE)) { offsetState.setValue(0x34); } - offsetTrans.setValue(offsetState.getValue() + 0x10 * countState.getValue()); - offsetStaTri.setValue(offsetTrans.getValue() + 0x20 * countTrans.getValue()); - offsetTranTri.setValue(offsetStaTri.getValue() + 0x8 * countStaTri.getValue()); - offsetAction.setValue(offsetTranTri.getValue() + 0x8 * countTranTri.getValue()); + offsetTrans.setValue(offsetState.getValue() + 0x10L * countState.getValue()); + offsetStaTri.setValue(offsetTrans.getValue() + 0x20L * countTrans.getValue()); + offsetTranTri.setValue(offsetStaTri.getValue() + 0x8L * countStaTri.getValue()); + offsetAction.setValue(offsetTranTri.getValue() + 0x8L * countTranTri.getValue()); int stringoff = offsetAction.getValue() + 0x8 * countAction.getValue(); for (final StructEntry o : fields) { if (o instanceof AbstractCode) { @@ -222,7 +223,7 @@ public void actionPerformed(ActionEvent e) { throw new Exception(); } } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); JOptionPane.showMessageDialog(getViewer().getTopLevelAncestor(), "Could not export resource into WeiDU dialog format.", "Error", JOptionPane.ERROR_MESSAGE); return; @@ -554,7 +555,7 @@ private boolean exportDlgAsText(PrintWriter writer) { if (writer != null) { // *** write header comment *** String niPath = Utils.getJarFileName(NearInfinity.class); - if (niPath == null || niPath.isEmpty()) { + if (niPath.isEmpty()) { niPath = "Near Infinity"; } niPath += " (" + NearInfinity.getVersion() + ")"; @@ -671,14 +672,15 @@ private final class DlgState { /** Contains correctly ordered list of responses. */ public final ArrayList responses = new ArrayList<>(); + /** Strref of state. */ + private final int strref; + /** Space-separated list of transition origins for this state. */ private String cmtFrom; /** Space-separated list of states that are processed before this state. */ private String cmtWeight; /** Used for weight. */ public int triggerIndex; - /** Strref of state. */ - private int strref; /** Trigger text. */ private String trigger; diff --git a/src/org/infinity/resource/dlg/DlgTreeCellRenderer.java b/src/org/infinity/resource/dlg/DlgTreeCellRenderer.java index 21117f351..a2020bae5 100644 --- a/src/org/infinity/resource/dlg/DlgTreeCellRenderer.java +++ b/src/org/infinity/resource/dlg/DlgTreeCellRenderer.java @@ -18,7 +18,7 @@ /** *

* Renderer for dialogue tree, drawing elements of each dialog with its own color (maximum of - * {@link #OTHER_DIALOG_COLORS}{@code .length} different colors). + * {@link ViewerUtil#getBackgroundColors()}{@code .length} different colors). *

* *

@@ -28,7 +28,7 @@ * * @author Mingun */ -final class DlgTreeCellRenderer extends DefaultTreeCellRenderer { +public class DlgTreeCellRenderer extends DefaultTreeCellRenderer { // Color for response entry (if colored) private static final Color COLOR_RESPONSE = Color.BLUE; private static final Color COLOR_RESPONSE_DARK = Color.CYAN; diff --git a/src/org/infinity/resource/dlg/DlgTreeModel.java b/src/org/infinity/resource/dlg/DlgTreeModel.java index b2a1c2d78..22271de2d 100644 --- a/src/org/infinity/resource/dlg/DlgTreeModel.java +++ b/src/org/infinity/resource/dlg/DlgTreeModel.java @@ -35,9 +35,10 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** Creates and manages the dialog tree structure. */ -final class DlgTreeModel implements TreeModel, TreeNode, TableModelListener, PropertyChangeListener { +public class DlgTreeModel implements TreeModel, TreeNode, TableModelListener, PropertyChangeListener { private final ArrayList listeners = new ArrayList<>(); /** * List of all dialogs, that contains at tree root. Each of these dialogs also stored in the {@link #linkedDialogs} @@ -905,7 +906,7 @@ private DlgResource getDialogResource(ResourceRef dlgRef) { try { return new DlgResource(ResourceFactory.getResourceEntry(name)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; }); diff --git a/src/org/infinity/resource/dlg/ItemBase.java b/src/org/infinity/resource/dlg/ItemBase.java index 640a0d703..35ce94357 100644 --- a/src/org/infinity/resource/dlg/ItemBase.java +++ b/src/org/infinity/resource/dlg/ItemBase.java @@ -19,14 +19,14 @@ import org.infinity.util.StringTable; /** Common base class for node type specific classes. */ -abstract class ItemBase implements TreeNode { +public abstract class ItemBase implements TreeNode { /** Maximum string length to display. */ private static final int MAX_LENGTH = 200; private final boolean showStrrefs; private final boolean showTechInfo; - public ItemBase() { + protected ItemBase() { this.showStrrefs = BrowserMenuBar.getInstance().getOptions().showStrrefs(); this.showTechInfo = BrowserMenuBar.getInstance().getOptions().showDlgTechInfo(); } @@ -114,21 +114,3 @@ private String getText(StringRef value) { return text; } } - -/** Auxiliary class, being the parent for states, for a type safety. */ -abstract class StateOwnerItem extends ItemBase { - @Override - public abstract StateItem getChildAt(int childIndex); - - @Override - public abstract Enumeration children(); -} - -/** Auxiliary class, being the parent for transitions, for a type safety. */ -abstract class TransitionOwnerItem extends ItemBase implements Iterable { - @Override - public abstract TransitionItem getChildAt(int childIndex); - - @Override - public abstract Enumeration children(); -} diff --git a/src/org/infinity/resource/dlg/OrphanStates.java b/src/org/infinity/resource/dlg/OrphanStates.java index d4c15a215..706a318b4 100644 --- a/src/org/infinity/resource/dlg/OrphanStates.java +++ b/src/org/infinity/resource/dlg/OrphanStates.java @@ -20,7 +20,7 @@ * * @author Mingun */ -final class OrphanStates extends StateOwnerItem implements Iterable { +public class OrphanStates extends StateOwnerItem implements Iterable { private final DlgTreeModel parent; protected final List states = new ArrayList<>(); @@ -51,7 +51,10 @@ public TreeNode getParent() { @Override public int getIndex(TreeNode node) { - return states.indexOf(node); + if (node instanceof StateItem) { + return states.indexOf(node); + } + return -1; } @Override @@ -96,7 +99,10 @@ public Icon getIcon() { @Override public boolean removeChild(ItemBase child) { - return states.remove(child); + if (child instanceof StateItem) { + return states.remove(child); + } + return false; } @Override diff --git a/src/org/infinity/resource/dlg/OrphanTransitions.java b/src/org/infinity/resource/dlg/OrphanTransitions.java index 81cbe34ed..2b2c54375 100644 --- a/src/org/infinity/resource/dlg/OrphanTransitions.java +++ b/src/org/infinity/resource/dlg/OrphanTransitions.java @@ -20,7 +20,7 @@ * * @author Mingun */ -final class OrphanTransitions extends TransitionOwnerItem { +public class OrphanTransitions extends TransitionOwnerItem { private final DlgTreeModel parent; protected final List trans = new ArrayList<>(); @@ -51,7 +51,10 @@ public TreeNode getParent() { @Override public int getIndex(TreeNode node) { - return trans.indexOf(node); + if (node instanceof TransitionItem) { + return trans.indexOf(node); + } + return -1; } @Override @@ -96,7 +99,10 @@ public Icon getIcon() { @Override public boolean removeChild(ItemBase child) { - return trans.remove(child); + if (child instanceof TransitionItem) { + return trans.remove(child); + } + return false; } @Override diff --git a/src/org/infinity/resource/dlg/ResponseTrigger.java b/src/org/infinity/resource/dlg/ResponseTrigger.java index dae30d9d8..6697ecebf 100644 --- a/src/org/infinity/resource/dlg/ResponseTrigger.java +++ b/src/org/infinity/resource/dlg/ResponseTrigger.java @@ -6,17 +6,17 @@ import java.nio.ByteBuffer; -public final class ResponseTrigger extends AbstractCode { +public class ResponseTrigger extends AbstractCode { // DLG/ResponseTrigger-specific field labels public static final String DLG_RESPONSE_TRIGGER = "Response trigger"; private int nr; - ResponseTrigger() { + public ResponseTrigger() { super(DLG_RESPONSE_TRIGGER); } - ResponseTrigger(ByteBuffer buffer, int offset, int count) { + public ResponseTrigger(ByteBuffer buffer, int offset, int count) { super(buffer, offset, DLG_RESPONSE_TRIGGER + " " + count); this.nr = count; } diff --git a/src/org/infinity/resource/dlg/State.java b/src/org/infinity/resource/dlg/State.java index e7673e9c8..cd63a0ca8 100644 --- a/src/org/infinity/resource/dlg/State.java +++ b/src/org/infinity/resource/dlg/State.java @@ -18,7 +18,7 @@ * and may have associated {@link StateTrigger trigger} with a condition, defining whether it is possible to use this * state. */ -public final class State extends AbstractStruct implements AddRemovable, TreeItemEntry { +public class State extends AbstractStruct implements AddRemovable, TreeItemEntry { // DLG/State-specific field labels public static final String DLG_STATE = "State"; public static final String DLG_STATE_RESPONSE = "Response"; @@ -29,11 +29,11 @@ public final class State extends AbstractStruct implements AddRemovable, TreeIte /** State number which is unique defining it in a dialog. */ private int nr; - State() throws Exception { + public State() throws Exception { super(null, DLG_STATE, StreamUtils.getByteBuffer(16), 0); } - State(DlgResource dlg, ByteBuffer buffer, int offset, int count) throws Exception { + public State(DlgResource dlg, ByteBuffer buffer, int offset, int count) throws Exception { super(dlg, DLG_STATE + " " + count, buffer, offset); nr = count; } diff --git a/src/org/infinity/resource/dlg/StateItem.java b/src/org/infinity/resource/dlg/StateItem.java index 550c6c9ef..1633db2a1 100644 --- a/src/org/infinity/resource/dlg/StateItem.java +++ b/src/org/infinity/resource/dlg/StateItem.java @@ -21,7 +21,7 @@ import org.infinity.icon.Icons; /** Encapsulates a dialog state entry. */ -class StateItem extends TransitionOwnerItem { +public class StateItem extends TransitionOwnerItem { private static final ImageIcon ICON = Icons.ICON_STOP_16.getIcon(); private final State state; @@ -77,7 +77,10 @@ public Icon getIcon() { @Override public boolean removeChild(ItemBase child) { - return trans.remove(child); + if (child instanceof TransitionItem) { + return trans.remove(child); + } + return false; } @Override @@ -109,7 +112,10 @@ public ItemBase getParent() { @Override public int getIndex(TreeNode node) { - return getAllowsChildren() ? trans.indexOf(node) : -1; + if (getAllowsChildren() && node instanceof TransitionItem) { + return trans.indexOf(node); + } + return -1; } @Override @@ -119,7 +125,7 @@ public boolean getAllowsChildren() { @Override public boolean isLeaf() { - return getAllowsChildren() ? trans.isEmpty() : true; + return !getAllowsChildren() || trans.isEmpty(); } @Override diff --git a/src/org/infinity/resource/dlg/StateOwnerItem.java b/src/org/infinity/resource/dlg/StateOwnerItem.java new file mode 100644 index 000000000..69996d5bd --- /dev/null +++ b/src/org/infinity/resource/dlg/StateOwnerItem.java @@ -0,0 +1,16 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.resource.dlg; + +import java.util.Enumeration; + +/** Auxiliary class, being the parent for states, for a type safety. */ +public abstract class StateOwnerItem extends ItemBase { + @Override + public abstract StateItem getChildAt(int childIndex); + + @Override + public abstract Enumeration children(); +} diff --git a/src/org/infinity/resource/dlg/StateTrigger.java b/src/org/infinity/resource/dlg/StateTrigger.java index e36f84513..5ab032755 100644 --- a/src/org/infinity/resource/dlg/StateTrigger.java +++ b/src/org/infinity/resource/dlg/StateTrigger.java @@ -6,17 +6,17 @@ import java.nio.ByteBuffer; -public final class StateTrigger extends AbstractCode { +public class StateTrigger extends AbstractCode { // DLG/StateTrigger-specific field labels public static final String DLG_STATE_TRIGGER = "State trigger"; private int nr; - StateTrigger() { + public StateTrigger() { super(DLG_STATE_TRIGGER); } - StateTrigger(ByteBuffer buffer, int offset, int count) { + public StateTrigger(ByteBuffer buffer, int offset, int count) { super(buffer, offset, DLG_STATE_TRIGGER + " " + count); this.nr = count; } diff --git a/src/org/infinity/resource/dlg/Transition.java b/src/org/infinity/resource/dlg/Transition.java index 258891785..f0c95058e 100644 --- a/src/org/infinity/resource/dlg/Transition.java +++ b/src/org/infinity/resource/dlg/Transition.java @@ -16,7 +16,7 @@ import org.infinity.util.io.StreamUtils; /** Player {@link DlgResource dialog} option. */ -public final class Transition extends AbstractStruct implements AddRemovable, TreeItemEntry { +public class Transition extends AbstractStruct implements AddRemovable, TreeItemEntry { // DLG/Transition-specific field labels public static final String DLG_TRANS = "Response"; public static final String DLG_TRANS_FLAGS = "Flags"; @@ -34,11 +34,11 @@ public final class Transition extends AbstractStruct implements AddRemovable, Tr /** Transition number which is unique defining it in a dialog. */ private int nr; - Transition() throws Exception { + public Transition() throws Exception { super(null, DLG_TRANS, StreamUtils.getByteBuffer(32), 0); } - Transition(DlgResource dlg, ByteBuffer buffer, int offset, int nr) throws Exception { + public Transition(DlgResource dlg, ByteBuffer buffer, int offset, int nr) throws Exception { super(dlg, DLG_TRANS + " " + nr, buffer, offset); this.nr = nr; } diff --git a/src/org/infinity/resource/dlg/TransitionItem.java b/src/org/infinity/resource/dlg/TransitionItem.java index 42c095a4f..17a8332c5 100644 --- a/src/org/infinity/resource/dlg/TransitionItem.java +++ b/src/org/infinity/resource/dlg/TransitionItem.java @@ -20,7 +20,7 @@ import org.infinity.icon.Icons; /** Encapsulates a dialog transition entry. */ -class TransitionItem extends StateOwnerItem { +public class TransitionItem extends StateOwnerItem { private static final ImageIcon ICON = Icons.ICON_PLAY_16.getIcon(); private final Transition trans; @@ -123,7 +123,7 @@ public boolean getAllowsChildren() { @Override public boolean isLeaf() { - return isMain() ? nextState == null : true; + return !isMain() || nextState == null; } @Override diff --git a/src/org/infinity/resource/dlg/TransitionOwnerItem.java b/src/org/infinity/resource/dlg/TransitionOwnerItem.java new file mode 100644 index 000000000..2ec3eeb9c --- /dev/null +++ b/src/org/infinity/resource/dlg/TransitionOwnerItem.java @@ -0,0 +1,16 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.resource.dlg; + +import java.util.Enumeration; + +/** Auxiliary class, being the parent for transitions, for a type safety. */ +public abstract class TransitionOwnerItem extends ItemBase implements Iterable { + @Override + public abstract TransitionItem getChildAt(int childIndex); + + @Override + public abstract Enumeration children(); +} diff --git a/src/org/infinity/resource/dlg/TreeViewer.java b/src/org/infinity/resource/dlg/TreeViewer.java index 84cdc8787..aaa8573fa 100644 --- a/src/org/infinity/resource/dlg/TreeViewer.java +++ b/src/org/infinity/resource/dlg/TreeViewer.java @@ -58,7 +58,7 @@ import org.infinity.util.StringTable; /** Show dialog content as tree structure. */ -final class TreeViewer extends JPanel implements ActionListener, TreeSelectionListener, PropertyChangeListener { +public class TreeViewer extends JPanel implements ActionListener, TreeSelectionListener, PropertyChangeListener { private final JPopupMenu pmTree = new JPopupMenu(); private final JMenuItem miExpandAll = new JMenuItem("Expand all nodes", Icons.ICON_EXPAND_ALL_24.getIcon()); @@ -81,7 +81,7 @@ final class TreeViewer extends JPanel implements ActionListener, TreeSelectionLi private TreeWorker worker; private WindowBlocker blocker; - TreeViewer(DlgResource dlg) { + public TreeViewer(DlgResource dlg) { super(new BorderLayout()); this.dlg = dlg; dlgModel = new DlgTreeModel(dlg); @@ -521,7 +521,7 @@ private enum Type { private static final String CARD_RESPONSE = "Response"; private static final Color COLOR_BACKGROUND = UIManager.getColor("Panel.background"); - private static final Font FONT_DEFAULT = UIManager.getFont("Label.font").deriveFont(0); + private static final Font FONT_DEFAULT = UIManager.getFont("Label.font").deriveFont(Font.PLAIN); private final CardLayout cardLayout; private final JPanel pMainPanel; diff --git a/src/org/infinity/resource/dlg/TreeWorker.java b/src/org/infinity/resource/dlg/TreeWorker.java index da9495add..ef8f9cfc7 100644 --- a/src/org/infinity/resource/dlg/TreeWorker.java +++ b/src/org/infinity/resource/dlg/TreeWorker.java @@ -13,10 +13,12 @@ import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; +import org.infinity.util.Logger; + //-------------------------- INNER CLASSES -------------------------- /** Applies expand or collapse operations on a set of dialog tree nodes in a background task. */ -class TreeWorker extends SwingWorker { +public class TreeWorker extends SwingWorker { /** Path that must be collapsed or expanded. */ private final TreePath path; @@ -49,7 +51,7 @@ protected Void doInBackground() throws Exception { collapseNode(path); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -88,7 +90,7 @@ private void expandNode(final TreePath path) { try { SwingUtilities.invokeAndWait(() -> dlgTree.expandPath(path)); } catch (InterruptedException | InvocationTargetException e) { - e.printStackTrace(); + Logger.error(e); } } @@ -126,7 +128,7 @@ private void collapseNode(final TreePath path) { try { SwingUtilities.invokeAndWait(() -> dlgTree.collapsePath(path)); } catch (InterruptedException | InvocationTargetException e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/dlg/Viewer.java b/src/org/infinity/resource/dlg/Viewer.java index 737da8dbd..355a24276 100644 --- a/src/org/infinity/resource/dlg/Viewer.java +++ b/src/org/infinity/resource/dlg/Viewer.java @@ -51,10 +51,11 @@ import org.infinity.resource.bcs.ScriptType; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.DialogSearcher; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StringTable; -final class Viewer extends JPanel implements ActionListener, ItemListener, TableModelListener { +public class Viewer extends JPanel implements ActionListener, ItemListener, TableModelListener { private static final ButtonPanel.Control CTRL_NEXT_STATE = ButtonPanel.Control.CUSTOM_1; private static final ButtonPanel.Control CTRL_PREV_STATE = ButtonPanel.Control.CUSTOM_2; private static final ButtonPanel.Control CTRL_NEXT_TRANS = ButtonPanel.Control.CUSTOM_3; @@ -130,7 +131,7 @@ final class Viewer extends JPanel implements ActionListener, ItemListener, Table private DlgResource undoDlg; private boolean alive = true; - Viewer(DlgResource dlg) { + public Viewer(DlgResource dlg) { this.dlg = dlg; this.dlg.addTableModelListener(this); @@ -406,7 +407,7 @@ public void select(StructEntry entry) { showState(stateNrToShow); showTransition(transNrToShow); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -448,7 +449,7 @@ private void showState(int nr) { if (!isValid) { if (nr >= 0) { // Print warning about not correct resource - System.err.println(dlg.getName() + ": state " + nr + " is not exist"); + Logger.warn("{}: state {} does not exist", dlg.getName(), nr); } stateTextPanel.clearDisplay(); stateTriggerPanel.clearDisplay(); @@ -500,10 +501,9 @@ private void showTransition(int nr) { if (nr >= 0 && currentState != null) { // Print warning about not correct resource if (isValid) { - System.err.println( - dlg.getName() + ": transition " + nr + " is not transition from state " + currentState.getNumber()); + Logger.warn("{}: transition {} is not transition from state {}", dlg.getName(), nr, currentState.getNumber()); } else if (isBroken) { - System.err.println(dlg.getName() + ": transition " + nr + " is not exist"); + Logger.warn("{}: transition {} does not exist", dlg.getName(), nr); } } transTextPanel.clearDisplay(); diff --git a/src/org/infinity/resource/effects/BaseOpcode.java b/src/org/infinity/resource/effects/BaseOpcode.java index 28de51e10..6d89e7e50 100644 --- a/src/org/infinity/resource/effects/BaseOpcode.java +++ b/src/org/infinity/resource/effects/BaseOpcode.java @@ -31,6 +31,7 @@ import org.infinity.resource.Effect2; import org.infinity.resource.Profile; import org.infinity.resource.StructEntry; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; @@ -546,8 +547,8 @@ public static enum EffectEntry { ATTACKS_EE_MAP.put(10L, "4.5 attacks per round"); } - private int id; - private String name; + private final int id; + private final String name; /** One-time initialization of opcode classes. */ public static void initOpcodes() { @@ -604,7 +605,7 @@ public static synchronized String[] getEffectNames() { names.add(opcode.getName()); } - effectNames = names.toArray(new String[names.size()]); + effectNames = names.toArray(new String[0]); } return effectNames; } @@ -636,6 +637,7 @@ public static synchronized String[] getPortraitIconNames(String defaultName) { int index = Integer.parseInt(table.get(row, 0)); maxIndex = Math.max(maxIndex, index); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } } @@ -650,12 +652,12 @@ public static synchronized String[] getPortraitIconNames(String defaultName) { portraitIconNames[index] = StringTable.getStringRef(strref); } } catch (NumberFormatException nfe) { - nfe.printStackTrace(); + Logger.error(nfe); } } } } catch (NullPointerException npe) { - npe.printStackTrace(); + Logger.error(npe); } } @@ -853,7 +855,7 @@ public static StructEntry getEntry(AbstractStruct struct, EffectEntry id) throws { StructEntry retVal = null; final EnumMap map = getEffectStructure(struct); - if (map != null && map.containsKey(id)) { + if (map.containsKey(id)) { retVal = getEntryByIndex(struct, map.get(id)); } return retVal; @@ -888,7 +890,7 @@ public static ByteBuffer getEntryData(StructEntry entry) try (ByteBufferOutputStream bbos = new ByteBufferOutputStream(bb)) { entry.write(bbos); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); return null; } return bb; @@ -906,14 +908,14 @@ public static ByteBuffer getEntryData(AbstractStruct struct, EffectEntry id) if (struct != null) { try { EnumMap map = getEffectStructure(struct); - if (map != null && map.containsKey(id)) { + if (map.containsKey(id)) { int idx = map.get(id); if (idx >= 0 && idx < struct.getFields().size()) { return getEntryData(struct.getFields().get(idx)); } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return null; @@ -931,8 +933,7 @@ public static void replaceEntry(AbstractStruct struct, EffectEntry index, Effect StructEntry newEntry) throws Exception { EnumMap map = getEffectStructure(struct); - if (struct != null && newEntry != null && - map != null && map.containsKey(index) && map.containsKey(offset)) { + if (newEntry != null && map.containsKey(index) && map.containsKey(offset)) { int idx = map.get(index); int ofs = map.get(offset); final List list = struct.getFields(); @@ -1018,15 +1019,13 @@ private static synchronized TreeMap getOpcodeMap() { for (final Class cls : OPCODE_CLASSES) { try { Constructor ctor = cls.getConstructor(); - if (ctor != null) { - BaseOpcode opcode = ctor.newInstance(); - if (opcode.isAvailable()) { - opcodeList.put(opcode.getId(), opcode); - } + BaseOpcode opcode = ctor.newInstance(); + if (opcode.isAvailable()) { + opcodeList.put(opcode.getId(), opcode); } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1074,7 +1073,7 @@ protected BaseOpcode(int id, String name) { protected int makeEffectStruct(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) throws Exception { if (buffer != null && offset >= 0 && list != null) { - buffer.position(); + buffer.position(offset); int param1 = buffer.getInt(); int param2 = buffer.getInt(); diff --git a/src/org/infinity/resource/effects/Opcode000.java b/src/org/infinity/resource/effects/Opcode000.java index 09222d1b1..f1c227f28 100644 --- a/src/org/infinity/resource/effects/Opcode000.java +++ b/src/org/infinity/resource/effects/Opcode000.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 0. + * Implementation of opcode 0. */ public class Opcode000 extends BaseOpcode { private static final String EFFECT_AC_VALUE = "AC value"; diff --git a/src/org/infinity/resource/effects/Opcode001.java b/src/org/infinity/resource/effects/Opcode001.java index 084e3cc2f..ac66d2c8c 100644 --- a/src/org/infinity/resource/effects/Opcode001.java +++ b/src/org/infinity/resource/effects/Opcode001.java @@ -19,7 +19,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 1. + * Implementation of opcode 1. */ public class Opcode001 extends BaseOpcode { private static final String[] ATTACKS_IWD = Arrays.copyOf(ATTACKS, 6); @@ -62,7 +62,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs } Bitmap item = new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES_EE); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { item.addUpdateListener((UpdateListener)parent); } list.add(item); diff --git a/src/org/infinity/resource/effects/Opcode002.java b/src/org/infinity/resource/effects/Opcode002.java index 13410831f..2a4e4e600 100644 --- a/src/org/infinity/resource/effects/Opcode002.java +++ b/src/org/infinity/resource/effects/Opcode002.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 2. + * Implementation of opcode 2. */ public class Opcode002 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode003.java b/src/org/infinity/resource/effects/Opcode003.java index 60f6814f5..9eea35dc1 100644 --- a/src/org/infinity/resource/effects/Opcode003.java +++ b/src/org/infinity/resource/effects/Opcode003.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 3. + * Implementation of opcode 3. */ public class Opcode003 extends BaseOpcode { private static final String EFFECT_BERSERK_TYPE = "Berserk type"; diff --git a/src/org/infinity/resource/effects/Opcode004.java b/src/org/infinity/resource/effects/Opcode004.java index 92e98c54f..61a1d28a3 100644 --- a/src/org/infinity/resource/effects/Opcode004.java +++ b/src/org/infinity/resource/effects/Opcode004.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 4. + * Implementation of opcode 4. */ public class Opcode004 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode005.java b/src/org/infinity/resource/effects/Opcode005.java index b24b04b12..c25d8a749 100644 --- a/src/org/infinity/resource/effects/Opcode005.java +++ b/src/org/infinity/resource/effects/Opcode005.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 5. + * Implementation of opcode 5. */ public class Opcode005 extends BaseOpcode { private static final String EFFECT_CREATURE_TYPE = "Creature type"; diff --git a/src/org/infinity/resource/effects/Opcode006.java b/src/org/infinity/resource/effects/Opcode006.java index 2ce925e63..d73a5438f 100644 --- a/src/org/infinity/resource/effects/Opcode006.java +++ b/src/org/infinity/resource/effects/Opcode006.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 6. + * Implementation of opcode 6. */ public class Opcode006 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode007.java b/src/org/infinity/resource/effects/Opcode007.java index ef62b9529..6a07b2443 100644 --- a/src/org/infinity/resource/effects/Opcode007.java +++ b/src/org/infinity/resource/effects/Opcode007.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 7. + * Implementation of opcode 7. */ public class Opcode007 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode008.java b/src/org/infinity/resource/effects/Opcode008.java index 125eadb21..2c3af8d34 100644 --- a/src/org/infinity/resource/effects/Opcode008.java +++ b/src/org/infinity/resource/effects/Opcode008.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 8. + * Implementation of opcode 8. */ public class Opcode008 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode009.java b/src/org/infinity/resource/effects/Opcode009.java index 69808f3ca..31942a9a3 100644 --- a/src/org/infinity/resource/effects/Opcode009.java +++ b/src/org/infinity/resource/effects/Opcode009.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 9. + * Implementation of opcode 9. */ public class Opcode009 extends BaseOpcode { private static final String EFFECT_CYCLE_SPEED = "Cycle speed"; diff --git a/src/org/infinity/resource/effects/Opcode010.java b/src/org/infinity/resource/effects/Opcode010.java index eb4f08310..930445054 100644 --- a/src/org/infinity/resource/effects/Opcode010.java +++ b/src/org/infinity/resource/effects/Opcode010.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 10. + * Implementation of opcode 10. */ public class Opcode010 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode011.java b/src/org/infinity/resource/effects/Opcode011.java index 53dea78ff..e2ea231c1 100644 --- a/src/org/infinity/resource/effects/Opcode011.java +++ b/src/org/infinity/resource/effects/Opcode011.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 11. + * Implementation of opcode 11. */ public class Opcode011 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode012.java b/src/org/infinity/resource/effects/Opcode012.java index 1b32f6acf..361a0e574 100644 --- a/src/org/infinity/resource/effects/Opcode012.java +++ b/src/org/infinity/resource/effects/Opcode012.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 12. + * Implementation of opcode 12. */ public class Opcode012 extends BaseOpcode { private static final String EFFECT_DAMAGE_TYPE = "Damage type"; diff --git a/src/org/infinity/resource/effects/Opcode013.java b/src/org/infinity/resource/effects/Opcode013.java index 384bcce56..5b2f6e31e 100644 --- a/src/org/infinity/resource/effects/Opcode013.java +++ b/src/org/infinity/resource/effects/Opcode013.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 13. + * Implementation of opcode 13. */ public class Opcode013 extends BaseOpcode { private static final String EFFECT_DISPLAY_TEXT = "Display text?"; diff --git a/src/org/infinity/resource/effects/Opcode014.java b/src/org/infinity/resource/effects/Opcode014.java index 811e39b1f..c3dfaad09 100644 --- a/src/org/infinity/resource/effects/Opcode014.java +++ b/src/org/infinity/resource/effects/Opcode014.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 14. + * Implementation of opcode 14. */ public class Opcode014 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode015.java b/src/org/infinity/resource/effects/Opcode015.java index a85968e1f..d98b86926 100644 --- a/src/org/infinity/resource/effects/Opcode015.java +++ b/src/org/infinity/resource/effects/Opcode015.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 15. + * Implementation of opcode 15. */ public class Opcode015 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -55,7 +55,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs Bitmap item = new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, new String[] { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Cat's grace" }); list.add(item); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { item.addUpdateListener((UpdateListener)parent); } return null; diff --git a/src/org/infinity/resource/effects/Opcode016.java b/src/org/infinity/resource/effects/Opcode016.java index a367ca533..f83ea2b6a 100644 --- a/src/org/infinity/resource/effects/Opcode016.java +++ b/src/org/infinity/resource/effects/Opcode016.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 16. + * Implementation of opcode 16. */ public class Opcode016 extends BaseOpcode { private static final String EFFECT_HASTE_TYPE = "Haste type"; diff --git a/src/org/infinity/resource/effects/Opcode017.java b/src/org/infinity/resource/effects/Opcode017.java index d457254ba..2cab374de 100644 --- a/src/org/infinity/resource/effects/Opcode017.java +++ b/src/org/infinity/resource/effects/Opcode017.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 17. + * Implementation of opcode 17. */ public class Opcode017 extends BaseOpcode { private static final String EFFECTS_HEAL_FLAGS = "Heal flags"; diff --git a/src/org/infinity/resource/effects/Opcode018.java b/src/org/infinity/resource/effects/Opcode018.java index 2da1c972d..22f459d59 100644 --- a/src/org/infinity/resource/effects/Opcode018.java +++ b/src/org/infinity/resource/effects/Opcode018.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 18. + * Implementation of opcode 18. */ public class Opcode018 extends BaseOpcode { private static final String[] TYPES = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], diff --git a/src/org/infinity/resource/effects/Opcode019.java b/src/org/infinity/resource/effects/Opcode019.java index 8dedde266..39609fc75 100644 --- a/src/org/infinity/resource/effects/Opcode019.java +++ b/src/org/infinity/resource/effects/Opcode019.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 19. + * Implementation of opcode 19. */ public class Opcode019 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode020.java b/src/org/infinity/resource/effects/Opcode020.java index ae672141e..a99d5146e 100644 --- a/src/org/infinity/resource/effects/Opcode020.java +++ b/src/org/infinity/resource/effects/Opcode020.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 20. + * Implementation of opcode 20. */ public class Opcode020 extends BaseOpcode { private static final String EFFECT_INVISIBILITY_TYPE = "Invisibility type"; diff --git a/src/org/infinity/resource/effects/Opcode021.java b/src/org/infinity/resource/effects/Opcode021.java index 7b191d279..ea1ff2c12 100644 --- a/src/org/infinity/resource/effects/Opcode021.java +++ b/src/org/infinity/resource/effects/Opcode021.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 21. + * Implementation of opcode 21. */ public class Opcode021 extends BaseOpcode { private static final String[] TYPE_IWD2 = { INC_TYPES[0], INC_TYPES[1], "Mastery" }; diff --git a/src/org/infinity/resource/effects/Opcode022.java b/src/org/infinity/resource/effects/Opcode022.java index 3d65ceac2..4f361999b 100644 --- a/src/org/infinity/resource/effects/Opcode022.java +++ b/src/org/infinity/resource/effects/Opcode022.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 22. + * Implementation of opcode 22. */ public class Opcode022 extends BaseOpcode { private static final String[] TYPE_TOBEX = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Instantaneous" }; diff --git a/src/org/infinity/resource/effects/Opcode023.java b/src/org/infinity/resource/effects/Opcode023.java index f62ee1713..70489da5e 100644 --- a/src/org/infinity/resource/effects/Opcode023.java +++ b/src/org/infinity/resource/effects/Opcode023.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 23. + * Implementation of opcode 23. */ public class Opcode023 extends BaseOpcode { private static final String[] MODES_EE = { "BG2 mode", "BG1 mode" }; diff --git a/src/org/infinity/resource/effects/Opcode024.java b/src/org/infinity/resource/effects/Opcode024.java index 4b4a510de..c8540b106 100644 --- a/src/org/infinity/resource/effects/Opcode024.java +++ b/src/org/infinity/resource/effects/Opcode024.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 24. + * Implementation of opcode 24. */ public class Opcode024 extends BaseOpcode { private static final String EFFECT_PANIC_TYPE = "Panic type"; diff --git a/src/org/infinity/resource/effects/Opcode025.java b/src/org/infinity/resource/effects/Opcode025.java index 470ba91e2..11e86c4e4 100644 --- a/src/org/infinity/resource/effects/Opcode025.java +++ b/src/org/infinity/resource/effects/Opcode025.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 25. + * Implementation of opcode 25. */ public class Opcode025 extends BaseOpcode { private static final String EFFECT_POISON_TYPE = "Poison type"; @@ -75,7 +75,7 @@ private String makeEffectParamsInternal(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset, 4, EFFECT_AMOUNT)); final Bitmap bmp = new Bitmap(buffer, offset + 4, 4, EFFECT_POISON_TYPE, poisonTypes); list.add(bmp); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { bmp.addUpdateListener((UpdateListener)parent); } return null; diff --git a/src/org/infinity/resource/effects/Opcode026.java b/src/org/infinity/resource/effects/Opcode026.java index 295b0035f..6e8ee8a93 100644 --- a/src/org/infinity/resource/effects/Opcode026.java +++ b/src/org/infinity/resource/effects/Opcode026.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 26. + * Implementation of opcode 26. */ public class Opcode026 extends BaseOpcode { private static final String EFFECT_CURSE_TYPE = "Curse type"; diff --git a/src/org/infinity/resource/effects/Opcode027.java b/src/org/infinity/resource/effects/Opcode027.java index 7c8383b85..28e5b5a16 100644 --- a/src/org/infinity/resource/effects/Opcode027.java +++ b/src/org/infinity/resource/effects/Opcode027.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 27. + * Implementation of opcode 27. */ public class Opcode027 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode028.java b/src/org/infinity/resource/effects/Opcode028.java index a01821ded..ca82f3616 100644 --- a/src/org/infinity/resource/effects/Opcode028.java +++ b/src/org/infinity/resource/effects/Opcode028.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 28. + * Implementation of opcode 28. */ public class Opcode028 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode029.java b/src/org/infinity/resource/effects/Opcode029.java index ee9f11e57..21d5451b1 100644 --- a/src/org/infinity/resource/effects/Opcode029.java +++ b/src/org/infinity/resource/effects/Opcode029.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 29. + * Implementation of opcode 29. */ public class Opcode029 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode030.java b/src/org/infinity/resource/effects/Opcode030.java index 43ff916da..ae4b5471e 100644 --- a/src/org/infinity/resource/effects/Opcode030.java +++ b/src/org/infinity/resource/effects/Opcode030.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 30. + * Implementation of opcode 30. */ public class Opcode030 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode031.java b/src/org/infinity/resource/effects/Opcode031.java index fe87aae61..ccdfb8ac4 100644 --- a/src/org/infinity/resource/effects/Opcode031.java +++ b/src/org/infinity/resource/effects/Opcode031.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 31. + * Implementation of opcode 31. */ public class Opcode031 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode032.java b/src/org/infinity/resource/effects/Opcode032.java index 5a8ad5fe7..d21ef4b13 100644 --- a/src/org/infinity/resource/effects/Opcode032.java +++ b/src/org/infinity/resource/effects/Opcode032.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 32. + * Implementation of opcode 32. */ public class Opcode032 extends BaseOpcode { private static final String EFFECT_RESTORE_CRE_ANIM = "Restore creature animation?"; diff --git a/src/org/infinity/resource/effects/Opcode033.java b/src/org/infinity/resource/effects/Opcode033.java index 34e63d07e..1b465accd 100644 --- a/src/org/infinity/resource/effects/Opcode033.java +++ b/src/org/infinity/resource/effects/Opcode033.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 33. + * Implementation of opcode 33. */ public class Opcode033 extends BaseOpcode { private static final String[] TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment instantaneously" }; diff --git a/src/org/infinity/resource/effects/Opcode034.java b/src/org/infinity/resource/effects/Opcode034.java index 4602ebd6f..8b1f630e1 100644 --- a/src/org/infinity/resource/effects/Opcode034.java +++ b/src/org/infinity/resource/effects/Opcode034.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 34. + * Implementation of opcode 34. */ public class Opcode034 extends BaseOpcode { private static final String[] TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment instantaneously" }; diff --git a/src/org/infinity/resource/effects/Opcode035.java b/src/org/infinity/resource/effects/Opcode035.java index 23680e891..f5da5bd68 100644 --- a/src/org/infinity/resource/effects/Opcode035.java +++ b/src/org/infinity/resource/effects/Opcode035.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 35. + * Implementation of opcode 35. */ public class Opcode035 extends BaseOpcode { private static final String[] TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment instantaneously" }; diff --git a/src/org/infinity/resource/effects/Opcode036.java b/src/org/infinity/resource/effects/Opcode036.java index f5d8a9ec0..9aefdf3c0 100644 --- a/src/org/infinity/resource/effects/Opcode036.java +++ b/src/org/infinity/resource/effects/Opcode036.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 36. + * Implementation of opcode 36. */ public class Opcode036 extends BaseOpcode { private static final String[] TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment instantaneously" }; @@ -57,10 +57,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, TYPES_EE)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode037.java b/src/org/infinity/resource/effects/Opcode037.java index e1e0a3e1b..53883c3c8 100644 --- a/src/org/infinity/resource/effects/Opcode037.java +++ b/src/org/infinity/resource/effects/Opcode037.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 37. + * Implementation of opcode 37. */ public class Opcode037 extends BaseOpcode { private static final String[] TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment instantaneously" }; @@ -57,10 +57,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, TYPES_EE)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode038.java b/src/org/infinity/resource/effects/Opcode038.java index 795d8386d..917904c40 100644 --- a/src/org/infinity/resource/effects/Opcode038.java +++ b/src/org/infinity/resource/effects/Opcode038.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 38. + * Implementation of opcode 38. */ public class Opcode038 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode039.java b/src/org/infinity/resource/effects/Opcode039.java index a80c2c635..147dbd1a3 100644 --- a/src/org/infinity/resource/effects/Opcode039.java +++ b/src/org/infinity/resource/effects/Opcode039.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 39. + * Implementation of opcode 39. */ public class Opcode039 extends BaseOpcode { private static final String EFFECT_WAKE_ON_DAMAGE = "Wake on damage?"; diff --git a/src/org/infinity/resource/effects/Opcode040.java b/src/org/infinity/resource/effects/Opcode040.java index 604d849c0..dd67f47dd 100644 --- a/src/org/infinity/resource/effects/Opcode040.java +++ b/src/org/infinity/resource/effects/Opcode040.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 40. + * Implementation of opcode 40. */ public class Opcode040 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode041.java b/src/org/infinity/resource/effects/Opcode041.java index a96192d79..753ce5755 100644 --- a/src/org/infinity/resource/effects/Opcode041.java +++ b/src/org/infinity/resource/effects/Opcode041.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 41. + * Implementation of opcode 41. */ public class Opcode041 extends BaseOpcode { private static final String EFFECT_PARTICLE_EFFECT = "Particle effect"; diff --git a/src/org/infinity/resource/effects/Opcode042.java b/src/org/infinity/resource/effects/Opcode042.java index 1e79790f9..2506cbc56 100644 --- a/src/org/infinity/resource/effects/Opcode042.java +++ b/src/org/infinity/resource/effects/Opcode042.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 42. + * Implementation of opcode 42. */ public class Opcode042 extends BaseOpcode { private static final String EFFECT_NUM_SPELLS_TO_ADD = "# spells to add"; diff --git a/src/org/infinity/resource/effects/Opcode043.java b/src/org/infinity/resource/effects/Opcode043.java index 8f26df193..2f2841b1d 100644 --- a/src/org/infinity/resource/effects/Opcode043.java +++ b/src/org/infinity/resource/effects/Opcode043.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 43. + * Implementation of opcode 43. */ public class Opcode043 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode044.java b/src/org/infinity/resource/effects/Opcode044.java index 2d7b6b6c8..db76ab944 100644 --- a/src/org/infinity/resource/effects/Opcode044.java +++ b/src/org/infinity/resource/effects/Opcode044.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 44. + * Implementation of opcode 44. */ public class Opcode044 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -55,7 +55,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs Bitmap item = new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, new String[] { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Bull's Strength" }); list.add(item); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { item.addUpdateListener((UpdateListener)parent); } return null; diff --git a/src/org/infinity/resource/effects/Opcode045.java b/src/org/infinity/resource/effects/Opcode045.java index 3a90afefa..57a5ea178 100644 --- a/src/org/infinity/resource/effects/Opcode045.java +++ b/src/org/infinity/resource/effects/Opcode045.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 45. + * Implementation of opcode 45. */ public class Opcode045 extends BaseOpcode { private static final String EFFECT_STUN_TYPE = "Stun type"; diff --git a/src/org/infinity/resource/effects/Opcode046.java b/src/org/infinity/resource/effects/Opcode046.java index 9b67ca7c6..f8560bb54 100644 --- a/src/org/infinity/resource/effects/Opcode046.java +++ b/src/org/infinity/resource/effects/Opcode046.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 46. + * Implementation of opcode 46. */ public class Opcode046 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode047.java b/src/org/infinity/resource/effects/Opcode047.java index 687160f35..80f246776 100644 --- a/src/org/infinity/resource/effects/Opcode047.java +++ b/src/org/infinity/resource/effects/Opcode047.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 47. + * Implementation of opcode 47. */ public class Opcode047 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode048.java b/src/org/infinity/resource/effects/Opcode048.java index 1bfd3e5de..752345fcb 100644 --- a/src/org/infinity/resource/effects/Opcode048.java +++ b/src/org/infinity/resource/effects/Opcode048.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 48. + * Implementation of opcode 48. */ public class Opcode048 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode049.java b/src/org/infinity/resource/effects/Opcode049.java index ad7ba45c0..129cee2cf 100644 --- a/src/org/infinity/resource/effects/Opcode049.java +++ b/src/org/infinity/resource/effects/Opcode049.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 49. + * Implementation of opcode 49. */ public class Opcode049 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode050.java b/src/org/infinity/resource/effects/Opcode050.java index 9cd89af0b..c08b35430 100644 --- a/src/org/infinity/resource/effects/Opcode050.java +++ b/src/org/infinity/resource/effects/Opcode050.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 50. + * Implementation of opcode 50. */ public class Opcode050 extends BaseOpcode { private static final String EFFECT_CYCLE_SPEED = "Cycle speed"; diff --git a/src/org/infinity/resource/effects/Opcode051.java b/src/org/infinity/resource/effects/Opcode051.java index 1f5342518..39645363b 100644 --- a/src/org/infinity/resource/effects/Opcode051.java +++ b/src/org/infinity/resource/effects/Opcode051.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 51. + * Implementation of opcode 51. */ public class Opcode051 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode052.java b/src/org/infinity/resource/effects/Opcode052.java index 65b27ac1b..d98c328b2 100644 --- a/src/org/infinity/resource/effects/Opcode052.java +++ b/src/org/infinity/resource/effects/Opcode052.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 52. + * Implementation of opcode 52. */ public class Opcode052 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode053.java b/src/org/infinity/resource/effects/Opcode053.java index 26eed19b8..357ad6a2b 100644 --- a/src/org/infinity/resource/effects/Opcode053.java +++ b/src/org/infinity/resource/effects/Opcode053.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 53. + * Implementation of opcode 53. */ public class Opcode053 extends BaseOpcode { private static final String EFFECT_MORPH_INTO = "Morph into"; diff --git a/src/org/infinity/resource/effects/Opcode054.java b/src/org/infinity/resource/effects/Opcode054.java index 52f701677..5a7f45c9c 100644 --- a/src/org/infinity/resource/effects/Opcode054.java +++ b/src/org/infinity/resource/effects/Opcode054.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 54. + * Implementation of opcode 54. */ public class Opcode054 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode055.java b/src/org/infinity/resource/effects/Opcode055.java index ab1f001a5..c0698a891 100644 --- a/src/org/infinity/resource/effects/Opcode055.java +++ b/src/org/infinity/resource/effects/Opcode055.java @@ -12,7 +12,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 55. + * Implementation of opcode 55. */ public class Opcode055 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode056.java b/src/org/infinity/resource/effects/Opcode056.java index 4a90f3e78..af7dc77fd 100644 --- a/src/org/infinity/resource/effects/Opcode056.java +++ b/src/org/infinity/resource/effects/Opcode056.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 56. + * Implementation of opcode 56. */ public class Opcode056 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode057.java b/src/org/infinity/resource/effects/Opcode057.java index 0f32ec0ae..b06d8abac 100644 --- a/src/org/infinity/resource/effects/Opcode057.java +++ b/src/org/infinity/resource/effects/Opcode057.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 57. + * Implementation of opcode 57. */ public class Opcode057 extends BaseOpcode { private static final String EFFECT_ALIGNMENT = "Alignment"; diff --git a/src/org/infinity/resource/effects/Opcode058.java b/src/org/infinity/resource/effects/Opcode058.java index 6cfad3040..5f1408367 100644 --- a/src/org/infinity/resource/effects/Opcode058.java +++ b/src/org/infinity/resource/effects/Opcode058.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 58. + * Implementation of opcode 58. */ public class Opcode058 extends BaseOpcode { private static final String EFFECT_LEVEL = "Level"; diff --git a/src/org/infinity/resource/effects/Opcode059.java b/src/org/infinity/resource/effects/Opcode059.java index a66ed930d..0fa9c9751 100644 --- a/src/org/infinity/resource/effects/Opcode059.java +++ b/src/org/infinity/resource/effects/Opcode059.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 59. + * Implementation of opcode 59. */ public class Opcode059 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode060.java b/src/org/infinity/resource/effects/Opcode060.java index 031e21697..7d233a1d8 100644 --- a/src/org/infinity/resource/effects/Opcode060.java +++ b/src/org/infinity/resource/effects/Opcode060.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 60. + * Implementation of opcode 60. */ public class Opcode060 extends BaseOpcode { private static final String EFFECT_FAILURE_TYPE = "Failure type"; diff --git a/src/org/infinity/resource/effects/Opcode061.java b/src/org/infinity/resource/effects/Opcode061.java index 7168ea18f..3290d80f0 100644 --- a/src/org/infinity/resource/effects/Opcode061.java +++ b/src/org/infinity/resource/effects/Opcode061.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 61. + * Implementation of opcode 61. */ public class Opcode061 extends BaseOpcode { private static final String EFFECT_FADE_SPEED = "Fade speed"; diff --git a/src/org/infinity/resource/effects/Opcode062.java b/src/org/infinity/resource/effects/Opcode062.java index 56716ce90..e8aacb75b 100644 --- a/src/org/infinity/resource/effects/Opcode062.java +++ b/src/org/infinity/resource/effects/Opcode062.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 62. + * Implementation of opcode 62. */ public class Opcode062 extends BaseOpcode { private static final String EFFECT_NUM_SPELLS_TO_ADD = "# spells to add"; diff --git a/src/org/infinity/resource/effects/Opcode063.java b/src/org/infinity/resource/effects/Opcode063.java index 808aef34a..f6236fdda 100644 --- a/src/org/infinity/resource/effects/Opcode063.java +++ b/src/org/infinity/resource/effects/Opcode063.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 63. + * Implementation of opcode 63. */ public class Opcode063 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode064.java b/src/org/infinity/resource/effects/Opcode064.java index e14b88a73..30c860bec 100644 --- a/src/org/infinity/resource/effects/Opcode064.java +++ b/src/org/infinity/resource/effects/Opcode064.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 64. + * Implementation of opcode 64. */ public class Opcode064 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode065.java b/src/org/infinity/resource/effects/Opcode065.java index 8831612cf..5a7e0ecb0 100644 --- a/src/org/infinity/resource/effects/Opcode065.java +++ b/src/org/infinity/resource/effects/Opcode065.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 65. + * Implementation of opcode 65. */ public class Opcode065 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode066.java b/src/org/infinity/resource/effects/Opcode066.java index 7b3b29505..dc55a9721 100644 --- a/src/org/infinity/resource/effects/Opcode066.java +++ b/src/org/infinity/resource/effects/Opcode066.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 66. + * Implementation of opcode 66. */ public class Opcode066 extends BaseOpcode { private static final String EFFECT_FADE_AMOUNT = "Fade amount"; diff --git a/src/org/infinity/resource/effects/Opcode067.java b/src/org/infinity/resource/effects/Opcode067.java index 5d7b05ce8..ea9e9f388 100644 --- a/src/org/infinity/resource/effects/Opcode067.java +++ b/src/org/infinity/resource/effects/Opcode067.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 67. + * Implementation of opcode 67. */ public class Opcode067 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; diff --git a/src/org/infinity/resource/effects/Opcode068.java b/src/org/infinity/resource/effects/Opcode068.java index cb49c1a39..511a78f0a 100644 --- a/src/org/infinity/resource/effects/Opcode068.java +++ b/src/org/infinity/resource/effects/Opcode068.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 68. + * Implementation of opcode 68. */ public class Opcode068 extends BaseOpcode { private static final String EFFECT_DISPLAY_TEXT = "Display text?"; diff --git a/src/org/infinity/resource/effects/Opcode069.java b/src/org/infinity/resource/effects/Opcode069.java index 095c059e1..a534eacec 100644 --- a/src/org/infinity/resource/effects/Opcode069.java +++ b/src/org/infinity/resource/effects/Opcode069.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 69. + * Implementation of opcode 69. */ public class Opcode069 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode070.java b/src/org/infinity/resource/effects/Opcode070.java index fb6cdf210..4606d903d 100644 --- a/src/org/infinity/resource/effects/Opcode070.java +++ b/src/org/infinity/resource/effects/Opcode070.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 70. + * Implementation of opcode 70. */ public class Opcode070 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode071.java b/src/org/infinity/resource/effects/Opcode071.java index eeb165d92..30dc5d553 100644 --- a/src/org/infinity/resource/effects/Opcode071.java +++ b/src/org/infinity/resource/effects/Opcode071.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 71. + * Implementation of opcode 71. */ public class Opcode071 extends BaseOpcode { private static final String EFFECT_GENDER = "Gender"; diff --git a/src/org/infinity/resource/effects/Opcode072.java b/src/org/infinity/resource/effects/Opcode072.java index d2a6bf7c8..89372b8c4 100644 --- a/src/org/infinity/resource/effects/Opcode072.java +++ b/src/org/infinity/resource/effects/Opcode072.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 72. + * Implementation of opcode 72. */ public class Opcode072 extends BaseOpcode { private static final String[] IDS_TYPES = { "EA.IDS", "GENERAL.IDS", "RACE.IDS", "CLASS.IDS", "SPECIFIC.IDS", diff --git a/src/org/infinity/resource/effects/Opcode073.java b/src/org/infinity/resource/effects/Opcode073.java index 7ce75fcde..c2c6af1a0 100644 --- a/src/org/infinity/resource/effects/Opcode073.java +++ b/src/org/infinity/resource/effects/Opcode073.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 73. + * Implementation of opcode 73. */ public class Opcode073 extends BaseOpcode { private static final String EFFECT_DAMAGE_TYPE = "Damage type"; diff --git a/src/org/infinity/resource/effects/Opcode074.java b/src/org/infinity/resource/effects/Opcode074.java index 87ada7bf9..9313ac511 100644 --- a/src/org/infinity/resource/effects/Opcode074.java +++ b/src/org/infinity/resource/effects/Opcode074.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 74. + * Implementation of opcode 74. */ public class Opcode074 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode075.java b/src/org/infinity/resource/effects/Opcode075.java index ca17aa1bb..e18d3be3a 100644 --- a/src/org/infinity/resource/effects/Opcode075.java +++ b/src/org/infinity/resource/effects/Opcode075.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 75. + * Implementation of opcode 75. */ public class Opcode075 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode076.java b/src/org/infinity/resource/effects/Opcode076.java index 50d5c0da9..38607e3a5 100644 --- a/src/org/infinity/resource/effects/Opcode076.java +++ b/src/org/infinity/resource/effects/Opcode076.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 76. + * Implementation of opcode 76. */ public class Opcode076 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode077.java b/src/org/infinity/resource/effects/Opcode077.java index 8ea13859e..e9efeacbd 100644 --- a/src/org/infinity/resource/effects/Opcode077.java +++ b/src/org/infinity/resource/effects/Opcode077.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 77. + * Implementation of opcode 77. */ public class Opcode077 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode078.java b/src/org/infinity/resource/effects/Opcode078.java index b48b18cf3..dd53597d9 100644 --- a/src/org/infinity/resource/effects/Opcode078.java +++ b/src/org/infinity/resource/effects/Opcode078.java @@ -20,7 +20,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 78. + * Implementation of opcode 78. */ public class Opcode078 extends BaseOpcode { private static final String EFFECT_AMOUNT_PER_SECOND = "Amount per second"; @@ -83,7 +83,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new DecNumber(buffer, offset, 4, EFFECT_AMOUNT)); final Bitmap bmp = new Bitmap(buffer, offset + 4, 4, EFFECT_DISEASE_TYPE, DISEASE_TYPES_EE); list.add(bmp); - if (Profile.isEnhancedEdition() && parent != null && parent instanceof UpdateListener) { + if (Profile.isEnhancedEdition() && parent instanceof UpdateListener) { bmp.addUpdateListener((UpdateListener)parent); if (bmp.getValue() == 11 || bmp.getValue() == 12) { return RES_TYPE; diff --git a/src/org/infinity/resource/effects/Opcode079.java b/src/org/infinity/resource/effects/Opcode079.java index db2241012..37a9817d7 100644 --- a/src/org/infinity/resource/effects/Opcode079.java +++ b/src/org/infinity/resource/effects/Opcode079.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 79. + * Implementation of opcode 79. */ public class Opcode079 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode080.java b/src/org/infinity/resource/effects/Opcode080.java index 8bd9979eb..b10329bbf 100644 --- a/src/org/infinity/resource/effects/Opcode080.java +++ b/src/org/infinity/resource/effects/Opcode080.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 80. + * Implementation of opcode 80. */ public class Opcode080 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode081.java b/src/org/infinity/resource/effects/Opcode081.java index ea9953497..f230c0bae 100644 --- a/src/org/infinity/resource/effects/Opcode081.java +++ b/src/org/infinity/resource/effects/Opcode081.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 81. + * Implementation of opcode 81. */ public class Opcode081 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode082.java b/src/org/infinity/resource/effects/Opcode082.java index cdfc87043..848e35b85 100644 --- a/src/org/infinity/resource/effects/Opcode082.java +++ b/src/org/infinity/resource/effects/Opcode082.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 82. + * Implementation of opcode 82. */ public class Opcode082 extends BaseOpcode { private static final String EFFECT_SCRIPT_LEVEL = "Script level"; diff --git a/src/org/infinity/resource/effects/Opcode083.java b/src/org/infinity/resource/effects/Opcode083.java index 4135850fb..c9c7a7d39 100644 --- a/src/org/infinity/resource/effects/Opcode083.java +++ b/src/org/infinity/resource/effects/Opcode083.java @@ -17,7 +17,7 @@ import org.infinity.util.IdsMapEntry; /** - * Implemention of opcode 83. + * Implementation of opcode 83. */ public class Opcode083 extends BaseOpcode { private static final String EFFECT_PROJECTILE = "Projectile"; diff --git a/src/org/infinity/resource/effects/Opcode084.java b/src/org/infinity/resource/effects/Opcode084.java index 1e06265c7..0d11aad55 100644 --- a/src/org/infinity/resource/effects/Opcode084.java +++ b/src/org/infinity/resource/effects/Opcode084.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 84. + * Implementation of opcode 84. */ public class Opcode084 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -39,16 +39,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode085.java b/src/org/infinity/resource/effects/Opcode085.java index bf156eb0c..af46f5485 100644 --- a/src/org/infinity/resource/effects/Opcode085.java +++ b/src/org/infinity/resource/effects/Opcode085.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 85. + * Implementation of opcode 85. */ public class Opcode085 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -39,16 +39,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode086.java b/src/org/infinity/resource/effects/Opcode086.java index d3d3bd1ab..fcda3e6ac 100644 --- a/src/org/infinity/resource/effects/Opcode086.java +++ b/src/org/infinity/resource/effects/Opcode086.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 86. + * Implementation of opcode 86. */ public class Opcode086 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode087.java b/src/org/infinity/resource/effects/Opcode087.java index aba1e5feb..1fb45bdb8 100644 --- a/src/org/infinity/resource/effects/Opcode087.java +++ b/src/org/infinity/resource/effects/Opcode087.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 87. + * Implementation of opcode 87. */ public class Opcode087 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode088.java b/src/org/infinity/resource/effects/Opcode088.java index fd7208c01..120751602 100644 --- a/src/org/infinity/resource/effects/Opcode088.java +++ b/src/org/infinity/resource/effects/Opcode088.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 88. + * Implementation of opcode 88. */ public class Opcode088 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode089.java b/src/org/infinity/resource/effects/Opcode089.java index d4b7d67f9..d38abe57a 100644 --- a/src/org/infinity/resource/effects/Opcode089.java +++ b/src/org/infinity/resource/effects/Opcode089.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 89. + * Implementation of opcode 89. */ public class Opcode089 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode090.java b/src/org/infinity/resource/effects/Opcode090.java index 59becc2d6..fbd648ad4 100644 --- a/src/org/infinity/resource/effects/Opcode090.java +++ b/src/org/infinity/resource/effects/Opcode090.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 90. + * Implementation of opcode 90. */ public class Opcode090 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode091.java b/src/org/infinity/resource/effects/Opcode091.java index f1cd98c6b..4f9ec1435 100644 --- a/src/org/infinity/resource/effects/Opcode091.java +++ b/src/org/infinity/resource/effects/Opcode091.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 91. + * Implementation of opcode 91. */ public class Opcode091 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode092.java b/src/org/infinity/resource/effects/Opcode092.java index 6c8ce33ad..875c167ad 100644 --- a/src/org/infinity/resource/effects/Opcode092.java +++ b/src/org/infinity/resource/effects/Opcode092.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 92. + * Implementation of opcode 92. */ public class Opcode092 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode093.java b/src/org/infinity/resource/effects/Opcode093.java index 5b3283fe1..79d877d04 100644 --- a/src/org/infinity/resource/effects/Opcode093.java +++ b/src/org/infinity/resource/effects/Opcode093.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 93. + * Implementation of opcode 93. */ public class Opcode093 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode094.java b/src/org/infinity/resource/effects/Opcode094.java index 0e61233f6..250d18cf5 100644 --- a/src/org/infinity/resource/effects/Opcode094.java +++ b/src/org/infinity/resource/effects/Opcode094.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 94. + * Implementation of opcode 94. */ public class Opcode094 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode095.java b/src/org/infinity/resource/effects/Opcode095.java index 783f39f22..a0952e126 100644 --- a/src/org/infinity/resource/effects/Opcode095.java +++ b/src/org/infinity/resource/effects/Opcode095.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 95. + * Implementation of opcode 95. */ public class Opcode095 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode096.java b/src/org/infinity/resource/effects/Opcode096.java index 0f71df4a2..60b5da6b2 100644 --- a/src/org/infinity/resource/effects/Opcode096.java +++ b/src/org/infinity/resource/effects/Opcode096.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 96. + * Implementation of opcode 96. */ public class Opcode096 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode097.java b/src/org/infinity/resource/effects/Opcode097.java index f4bbc75d6..8b0712bea 100644 --- a/src/org/infinity/resource/effects/Opcode097.java +++ b/src/org/infinity/resource/effects/Opcode097.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 97. + * Implementation of opcode 97. */ public class Opcode097 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode098.java b/src/org/infinity/resource/effects/Opcode098.java index b5744b125..40ec73c79 100644 --- a/src/org/infinity/resource/effects/Opcode098.java +++ b/src/org/infinity/resource/effects/Opcode098.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 98. + * Implementation of opcode 98. */ public class Opcode098 extends BaseOpcode { private static final String EFFECT_REGENERATION_TYPE = "Regeneration type"; @@ -61,7 +61,7 @@ protected String makeEffectParamsInternal(Datatype parent, ByteBuffer buffer, in list.add(new DecNumber(buffer, offset, 4, EFFECT_VALUE)); final Bitmap bmp = new Bitmap(buffer, offset + 4, 4, EFFECT_REGENERATION_TYPE, regenTypes); list.add(bmp); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { bmp.addUpdateListener((UpdateListener)parent); } return null; diff --git a/src/org/infinity/resource/effects/Opcode099.java b/src/org/infinity/resource/effects/Opcode099.java index 9b9f2c761..9f0872587 100644 --- a/src/org/infinity/resource/effects/Opcode099.java +++ b/src/org/infinity/resource/effects/Opcode099.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 99. + * Implementation of opcode 99. */ public class Opcode099 extends BaseOpcode { private static final String EFFECT_PERCENTAGE = "Percentage"; diff --git a/src/org/infinity/resource/effects/Opcode100.java b/src/org/infinity/resource/effects/Opcode100.java index 0d32d499c..ef19b566d 100644 --- a/src/org/infinity/resource/effects/Opcode100.java +++ b/src/org/infinity/resource/effects/Opcode100.java @@ -12,7 +12,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 100. + * Implementation of opcode 100. */ public class Opcode100 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode101.java b/src/org/infinity/resource/effects/Opcode101.java index eff538639..75814e180 100644 --- a/src/org/infinity/resource/effects/Opcode101.java +++ b/src/org/infinity/resource/effects/Opcode101.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 101. + * Implementation of opcode 101. */ public class Opcode101 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode102.java b/src/org/infinity/resource/effects/Opcode102.java index a133eef28..e631f63e5 100644 --- a/src/org/infinity/resource/effects/Opcode102.java +++ b/src/org/infinity/resource/effects/Opcode102.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 102. + * Implementation of opcode 102. */ public class Opcode102 extends BaseOpcode { private static final String EFFECT_SPELL_LEVEL = "Spell level"; diff --git a/src/org/infinity/resource/effects/Opcode103.java b/src/org/infinity/resource/effects/Opcode103.java index 7cb761623..133f57c0f 100644 --- a/src/org/infinity/resource/effects/Opcode103.java +++ b/src/org/infinity/resource/effects/Opcode103.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 103. + * Implementation of opcode 103. */ public class Opcode103 extends BaseOpcode { private static final String EFFECT_NAME = "Name"; diff --git a/src/org/infinity/resource/effects/Opcode104.java b/src/org/infinity/resource/effects/Opcode104.java index 93f8136d2..48242cd3e 100644 --- a/src/org/infinity/resource/effects/Opcode104.java +++ b/src/org/infinity/resource/effects/Opcode104.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 104. + * Implementation of opcode 104. */ public class Opcode104 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode105.java b/src/org/infinity/resource/effects/Opcode105.java index 8f9a1c80e..cf876e0a0 100644 --- a/src/org/infinity/resource/effects/Opcode105.java +++ b/src/org/infinity/resource/effects/Opcode105.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 105. + * Implementation of opcode 105. */ public class Opcode105 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode106.java b/src/org/infinity/resource/effects/Opcode106.java index a276b1076..2a50c99ce 100644 --- a/src/org/infinity/resource/effects/Opcode106.java +++ b/src/org/infinity/resource/effects/Opcode106.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 106. + * Implementation of opcode 106. */ public class Opcode106 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode107.java b/src/org/infinity/resource/effects/Opcode107.java index f5ce46c0d..0e9345a93 100644 --- a/src/org/infinity/resource/effects/Opcode107.java +++ b/src/org/infinity/resource/effects/Opcode107.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 107. + * Implementation of opcode 107. */ public class Opcode107 extends BaseOpcode { private static final String EFFECT_WHICH_PORTRAIT = "Which portrait?"; diff --git a/src/org/infinity/resource/effects/Opcode108.java b/src/org/infinity/resource/effects/Opcode108.java index b6fd0ed96..a47be811c 100644 --- a/src/org/infinity/resource/effects/Opcode108.java +++ b/src/org/infinity/resource/effects/Opcode108.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 108. + * Implementation of opcode 108. */ public class Opcode108 extends BaseOpcode { private static final String[] INC_TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], "Increment (party)", diff --git a/src/org/infinity/resource/effects/Opcode109.java b/src/org/infinity/resource/effects/Opcode109.java index 11bb67789..ff5eb238d 100644 --- a/src/org/infinity/resource/effects/Opcode109.java +++ b/src/org/infinity/resource/effects/Opcode109.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 109. + * Implementation of opcode 109. */ public class Opcode109 extends BaseOpcode { private static final String EFFECT_FX = "Effect"; diff --git a/src/org/infinity/resource/effects/Opcode110.java b/src/org/infinity/resource/effects/Opcode110.java index fc1ed7338..8b485227f 100644 --- a/src/org/infinity/resource/effects/Opcode110.java +++ b/src/org/infinity/resource/effects/Opcode110.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 110. + * Implementation of opcode 110. */ public class Opcode110 extends BaseOpcode { private static final String[] MOVE_TYPES = { "Run", "Run", "Run", "Run", "Run", "Run", "Run", "Weak", "Walk" }; diff --git a/src/org/infinity/resource/effects/Opcode111.java b/src/org/infinity/resource/effects/Opcode111.java index d586c479c..7de6655bb 100644 --- a/src/org/infinity/resource/effects/Opcode111.java +++ b/src/org/infinity/resource/effects/Opcode111.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 111. + * Implementation of opcode 111. */ public class Opcode111 extends BaseOpcode { private static final String EFFECT_NUM_TO_CREATE = "# to create"; diff --git a/src/org/infinity/resource/effects/Opcode112.java b/src/org/infinity/resource/effects/Opcode112.java index e85a5d055..9c162acca 100644 --- a/src/org/infinity/resource/effects/Opcode112.java +++ b/src/org/infinity/resource/effects/Opcode112.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 112. + * Implementation of opcode 112. */ public class Opcode112 extends BaseOpcode { private static final String RES_TYPE = "ITM"; diff --git a/src/org/infinity/resource/effects/Opcode113.java b/src/org/infinity/resource/effects/Opcode113.java index a68070a51..355a60a56 100644 --- a/src/org/infinity/resource/effects/Opcode113.java +++ b/src/org/infinity/resource/effects/Opcode113.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 113. + * Implementation of opcode 113. */ public class Opcode113 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode114.java b/src/org/infinity/resource/effects/Opcode114.java index e21ac3b3e..7f0b9fb11 100644 --- a/src/org/infinity/resource/effects/Opcode114.java +++ b/src/org/infinity/resource/effects/Opcode114.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 114. + * Implementation of opcode 114. */ public class Opcode114 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode115.java b/src/org/infinity/resource/effects/Opcode115.java index 9d2806e76..549a99291 100644 --- a/src/org/infinity/resource/effects/Opcode115.java +++ b/src/org/infinity/resource/effects/Opcode115.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 115. + * Implementation of opcode 115. */ public class Opcode115 extends BaseOpcode { private static final String EFFECT_ALIGNMENT_MASK = "Alignment mask"; diff --git a/src/org/infinity/resource/effects/Opcode116.java b/src/org/infinity/resource/effects/Opcode116.java index 421772b1f..0cfd71abf 100644 --- a/src/org/infinity/resource/effects/Opcode116.java +++ b/src/org/infinity/resource/effects/Opcode116.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 116. + * Implementation of opcode 116. */ public class Opcode116 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode117.java b/src/org/infinity/resource/effects/Opcode117.java index eb3e7bcc3..3c89998ef 100644 --- a/src/org/infinity/resource/effects/Opcode117.java +++ b/src/org/infinity/resource/effects/Opcode117.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 117. + * Implementation of opcode 117. */ public class Opcode117 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode118.java b/src/org/infinity/resource/effects/Opcode118.java index 1ac3cfa8b..40f5d37fa 100644 --- a/src/org/infinity/resource/effects/Opcode118.java +++ b/src/org/infinity/resource/effects/Opcode118.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 118. + * Implementation of opcode 118. */ public class Opcode118 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode119.java b/src/org/infinity/resource/effects/Opcode119.java index c0958450f..e701328b1 100644 --- a/src/org/infinity/resource/effects/Opcode119.java +++ b/src/org/infinity/resource/effects/Opcode119.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 119. + * Implementation of opcode 119. */ public class Opcode119 extends BaseOpcode { private static final String EFFECT_NUM_IMAGES = "# images"; diff --git a/src/org/infinity/resource/effects/Opcode120.java b/src/org/infinity/resource/effects/Opcode120.java index aa36f3278..1fa5bb351 100644 --- a/src/org/infinity/resource/effects/Opcode120.java +++ b/src/org/infinity/resource/effects/Opcode120.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 120. + * Implementation of opcode 120. */ public class Opcode120 extends BaseOpcode { private static final String EFFECT_MAX_ENCHANTMENT = "Maximum enchantment"; diff --git a/src/org/infinity/resource/effects/Opcode121.java b/src/org/infinity/resource/effects/Opcode121.java index 4833e5fdb..9f730aa18 100644 --- a/src/org/infinity/resource/effects/Opcode121.java +++ b/src/org/infinity/resource/effects/Opcode121.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 121. + * Implementation of opcode 121. */ public class Opcode121 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode122.java b/src/org/infinity/resource/effects/Opcode122.java index 9df91073a..2558e39d8 100644 --- a/src/org/infinity/resource/effects/Opcode122.java +++ b/src/org/infinity/resource/effects/Opcode122.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 122. + * Implementation of opcode 122. */ public class Opcode122 extends BaseOpcode { private static final String EFFECT_NUM_TO_CREATE = "# to create"; diff --git a/src/org/infinity/resource/effects/Opcode123.java b/src/org/infinity/resource/effects/Opcode123.java index bac07208e..162109e3f 100644 --- a/src/org/infinity/resource/effects/Opcode123.java +++ b/src/org/infinity/resource/effects/Opcode123.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 123. + * Implementation of opcode 123. */ public class Opcode123 extends BaseOpcode { private static final String RES_TYPE = "ITM"; diff --git a/src/org/infinity/resource/effects/Opcode124.java b/src/org/infinity/resource/effects/Opcode124.java index 17c859f50..99c7d1047 100644 --- a/src/org/infinity/resource/effects/Opcode124.java +++ b/src/org/infinity/resource/effects/Opcode124.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 124. + * Implementation of opcode 124. */ public class Opcode124 extends BaseOpcode { private static final String EFFECT_BEHAVIOR = "Behavior"; diff --git a/src/org/infinity/resource/effects/Opcode125.java b/src/org/infinity/resource/effects/Opcode125.java index acd8bf662..994b37404 100644 --- a/src/org/infinity/resource/effects/Opcode125.java +++ b/src/org/infinity/resource/effects/Opcode125.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 125. + * Implementation of opcode 125. */ public class Opcode125 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode126.java b/src/org/infinity/resource/effects/Opcode126.java index f854f8d12..c77034937 100644 --- a/src/org/infinity/resource/effects/Opcode126.java +++ b/src/org/infinity/resource/effects/Opcode126.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 126. + * Implementation of opcode 126. */ public class Opcode126 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode127.java b/src/org/infinity/resource/effects/Opcode127.java index 06ac92e10..a7b6278ce 100644 --- a/src/org/infinity/resource/effects/Opcode127.java +++ b/src/org/infinity/resource/effects/Opcode127.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 127. + * Implementation of opcode 127. */ public class Opcode127 extends BaseOpcode { private static final String EFFECT_TOTAL_XP = "Total XP"; @@ -46,10 +46,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_FROM_2DA, FILE_TYPES)); return RES_TYPE; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode128.java b/src/org/infinity/resource/effects/Opcode128.java index fb5a3e282..b4dfa928c 100644 --- a/src/org/infinity/resource/effects/Opcode128.java +++ b/src/org/infinity/resource/effects/Opcode128.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 128. + * Implementation of opcode 128. */ public class Opcode128 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode129.java b/src/org/infinity/resource/effects/Opcode129.java index c2eb5304f..ac69150c4 100644 --- a/src/org/infinity/resource/effects/Opcode129.java +++ b/src/org/infinity/resource/effects/Opcode129.java @@ -12,7 +12,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 129. + * Implementation of opcode 129. */ public class Opcode129 extends BaseOpcode { private static final String EFFECT_HP_BONUS = "HP bonus"; diff --git a/src/org/infinity/resource/effects/Opcode130.java b/src/org/infinity/resource/effects/Opcode130.java index e4c67ec9f..0547047f7 100644 --- a/src/org/infinity/resource/effects/Opcode130.java +++ b/src/org/infinity/resource/effects/Opcode130.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 130. + * Implementation of opcode 130. */ public class Opcode130 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode131.java b/src/org/infinity/resource/effects/Opcode131.java index ae85bcd62..cddad74b8 100644 --- a/src/org/infinity/resource/effects/Opcode131.java +++ b/src/org/infinity/resource/effects/Opcode131.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 131. + * Implementation of opcode 131. */ public class Opcode131 extends BaseOpcode { private static final String EFFECT_PRAYER_TYPE = "Prayer type"; diff --git a/src/org/infinity/resource/effects/Opcode132.java b/src/org/infinity/resource/effects/Opcode132.java index 053f47534..f77b0f324 100644 --- a/src/org/infinity/resource/effects/Opcode132.java +++ b/src/org/infinity/resource/effects/Opcode132.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 132. + * Implementation of opcode 132. */ public class Opcode132 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode133.java b/src/org/infinity/resource/effects/Opcode133.java index 17b9aa682..f974dc203 100644 --- a/src/org/infinity/resource/effects/Opcode133.java +++ b/src/org/infinity/resource/effects/Opcode133.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 133. + * Implementation of opcode 133. */ public class Opcode133 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode134.java b/src/org/infinity/resource/effects/Opcode134.java index 60b8923bc..2f9dae7dd 100644 --- a/src/org/infinity/resource/effects/Opcode134.java +++ b/src/org/infinity/resource/effects/Opcode134.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 134. + * Implementation of opcode 134. */ public class Opcode134 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode135.java b/src/org/infinity/resource/effects/Opcode135.java index 4ebeaa0e1..b4b4b8731 100644 --- a/src/org/infinity/resource/effects/Opcode135.java +++ b/src/org/infinity/resource/effects/Opcode135.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 135. + * Implementation of opcode 135. */ public class Opcode135 extends BaseOpcode { private static final String EFFECT_POLYMORPH_TYPE = "Polymorph type"; diff --git a/src/org/infinity/resource/effects/Opcode136.java b/src/org/infinity/resource/effects/Opcode136.java index fcf722603..297e3632e 100644 --- a/src/org/infinity/resource/effects/Opcode136.java +++ b/src/org/infinity/resource/effects/Opcode136.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 136. + * Implementation of opcode 136. */ public class Opcode136 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode137.java b/src/org/infinity/resource/effects/Opcode137.java index 12f992714..2eef3e707 100644 --- a/src/org/infinity/resource/effects/Opcode137.java +++ b/src/org/infinity/resource/effects/Opcode137.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 137. + * Implementation of opcode 137. */ public class Opcode137 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -37,10 +37,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode138.java b/src/org/infinity/resource/effects/Opcode138.java index 46bf7e721..b8ec9ab03 100644 --- a/src/org/infinity/resource/effects/Opcode138.java +++ b/src/org/infinity/resource/effects/Opcode138.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 138. + * Implementation of opcode 138. */ public class Opcode138 extends BaseOpcode { private static final String EFFECT_SEQUENCE = "Sequence"; diff --git a/src/org/infinity/resource/effects/Opcode139.java b/src/org/infinity/resource/effects/Opcode139.java index caf981896..303a1860b 100644 --- a/src/org/infinity/resource/effects/Opcode139.java +++ b/src/org/infinity/resource/effects/Opcode139.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 139. + * Implementation of opcode 139. */ public class Opcode139 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode140.java b/src/org/infinity/resource/effects/Opcode140.java index ff896ec00..a08c32a55 100644 --- a/src/org/infinity/resource/effects/Opcode140.java +++ b/src/org/infinity/resource/effects/Opcode140.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 140. + * Implementation of opcode 140. */ public class Opcode140 extends BaseOpcode { private static final String EFFECT_GLOW = "Glow"; diff --git a/src/org/infinity/resource/effects/Opcode141.java b/src/org/infinity/resource/effects/Opcode141.java index af718ce82..b160e314a 100644 --- a/src/org/infinity/resource/effects/Opcode141.java +++ b/src/org/infinity/resource/effects/Opcode141.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 141. + * Implementation of opcode 141. */ public class Opcode141 extends BaseOpcode { private static final String EFFECT_TARGET = "Target"; diff --git a/src/org/infinity/resource/effects/Opcode142.java b/src/org/infinity/resource/effects/Opcode142.java index a946c8c7d..92f1a1e58 100644 --- a/src/org/infinity/resource/effects/Opcode142.java +++ b/src/org/infinity/resource/effects/Opcode142.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 142. + * Implementation of opcode 142. */ public class Opcode142 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode143.java b/src/org/infinity/resource/effects/Opcode143.java index 568a649bc..7b6e633aa 100644 --- a/src/org/infinity/resource/effects/Opcode143.java +++ b/src/org/infinity/resource/effects/Opcode143.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 143. + * Implementation of opcode 143. */ public class Opcode143 extends BaseOpcode { private static final String EFFECT_SLOT = "Slot"; diff --git a/src/org/infinity/resource/effects/Opcode144.java b/src/org/infinity/resource/effects/Opcode144.java index fefdd2678..11e9d3031 100644 --- a/src/org/infinity/resource/effects/Opcode144.java +++ b/src/org/infinity/resource/effects/Opcode144.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 144. + * Implementation of opcode 144. */ public class Opcode144 extends BaseOpcode { private static final String EFFECT_BUTTON = "Button"; diff --git a/src/org/infinity/resource/effects/Opcode145.java b/src/org/infinity/resource/effects/Opcode145.java index 8bca6de12..9583ebdbe 100644 --- a/src/org/infinity/resource/effects/Opcode145.java +++ b/src/org/infinity/resource/effects/Opcode145.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 145. + * Implementation of opcode 145. */ public class Opcode145 extends BaseOpcode { private static final String EFFECT_SPELL_CLASS = "Spell class"; diff --git a/src/org/infinity/resource/effects/Opcode146.java b/src/org/infinity/resource/effects/Opcode146.java index e72390d0a..b0621997b 100644 --- a/src/org/infinity/resource/effects/Opcode146.java +++ b/src/org/infinity/resource/effects/Opcode146.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 146. + * Implementation of opcode 146. */ public class Opcode146 extends BaseOpcode { private static final String EFFECT_CAST_AT_LEVEL = "Cast at level"; diff --git a/src/org/infinity/resource/effects/Opcode147.java b/src/org/infinity/resource/effects/Opcode147.java index 036f69bf1..3076da63e 100644 --- a/src/org/infinity/resource/effects/Opcode147.java +++ b/src/org/infinity/resource/effects/Opcode147.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 147. + * Implementation of opcode 147. */ public class Opcode147 extends BaseOpcode { private static final String EFFECT_BEHAVIOR = "Behavior"; diff --git a/src/org/infinity/resource/effects/Opcode148.java b/src/org/infinity/resource/effects/Opcode148.java index 5c736cf6b..df04aa35a 100644 --- a/src/org/infinity/resource/effects/Opcode148.java +++ b/src/org/infinity/resource/effects/Opcode148.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 148. + * Implementation of opcode 148. */ public class Opcode148 extends BaseOpcode { private static final String EFFECT_CAST_AT_LEVEL = "Cast at level"; diff --git a/src/org/infinity/resource/effects/Opcode149.java b/src/org/infinity/resource/effects/Opcode149.java index 411121913..12d2ac157 100644 --- a/src/org/infinity/resource/effects/Opcode149.java +++ b/src/org/infinity/resource/effects/Opcode149.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 149. + * Implementation of opcode 149. */ public class Opcode149 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode150.java b/src/org/infinity/resource/effects/Opcode150.java index 0c96d5be8..bd58cd395 100644 --- a/src/org/infinity/resource/effects/Opcode150.java +++ b/src/org/infinity/resource/effects/Opcode150.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 150. + * Implementation of opcode 150. */ public class Opcode150 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode151.java b/src/org/infinity/resource/effects/Opcode151.java index ff08421ec..1c1ae09b0 100644 --- a/src/org/infinity/resource/effects/Opcode151.java +++ b/src/org/infinity/resource/effects/Opcode151.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 151. + * Implementation of opcode 151. */ public class Opcode151 extends BaseOpcode { private static final String EFFECT_REPLACEMENT_METHOD = "Replacement method"; diff --git a/src/org/infinity/resource/effects/Opcode152.java b/src/org/infinity/resource/effects/Opcode152.java index 7f1fca1c3..9a98b37b4 100644 --- a/src/org/infinity/resource/effects/Opcode152.java +++ b/src/org/infinity/resource/effects/Opcode152.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 152. + * Implementation of opcode 152. */ public class Opcode152 extends BaseOpcode { private static final String RES_TYPE = "MVE"; diff --git a/src/org/infinity/resource/effects/Opcode153.java b/src/org/infinity/resource/effects/Opcode153.java index f3bbd630a..d6188ceb6 100644 --- a/src/org/infinity/resource/effects/Opcode153.java +++ b/src/org/infinity/resource/effects/Opcode153.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 153. + * Implementation of opcode 153. */ public class Opcode153 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; diff --git a/src/org/infinity/resource/effects/Opcode154.java b/src/org/infinity/resource/effects/Opcode154.java index 78b9ae8ce..ce2c23873 100644 --- a/src/org/infinity/resource/effects/Opcode154.java +++ b/src/org/infinity/resource/effects/Opcode154.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 154. + * Implementation of opcode 154. */ public class Opcode154 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; diff --git a/src/org/infinity/resource/effects/Opcode155.java b/src/org/infinity/resource/effects/Opcode155.java index 0f4cea26c..6ee7dab35 100644 --- a/src/org/infinity/resource/effects/Opcode155.java +++ b/src/org/infinity/resource/effects/Opcode155.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 155. + * Implementation of opcode 155. */ public class Opcode155 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; @@ -50,10 +50,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODE, MODES_EE)); return RES_TYPE_EE; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode156.java b/src/org/infinity/resource/effects/Opcode156.java index ec0d28214..8ceab9056 100644 --- a/src/org/infinity/resource/effects/Opcode156.java +++ b/src/org/infinity/resource/effects/Opcode156.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 156. + * Implementation of opcode 156. */ public class Opcode156 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; @@ -50,10 +50,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODE, MODES_EE)); return RES_TYPE_EE; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode157.java b/src/org/infinity/resource/effects/Opcode157.java index aab7bdf88..2589671da 100644 --- a/src/org/infinity/resource/effects/Opcode157.java +++ b/src/org/infinity/resource/effects/Opcode157.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 157. + * Implementation of opcode 157. */ public class Opcode157 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; diff --git a/src/org/infinity/resource/effects/Opcode158.java b/src/org/infinity/resource/effects/Opcode158.java index ac51dd6da..4b1709ef7 100644 --- a/src/org/infinity/resource/effects/Opcode158.java +++ b/src/org/infinity/resource/effects/Opcode158.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 158. + * Implementation of opcode 158. */ public class Opcode158 extends BaseOpcode { private static final String RES_TYPE_EE = "VVC:BAM"; diff --git a/src/org/infinity/resource/effects/Opcode159.java b/src/org/infinity/resource/effects/Opcode159.java index f3f0651d0..dc3208183 100644 --- a/src/org/infinity/resource/effects/Opcode159.java +++ b/src/org/infinity/resource/effects/Opcode159.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 159. + * Implementation of opcode 159. */ public class Opcode159 extends BaseOpcode { private static final String EFFECT_NUM_IMAGES = "# images"; diff --git a/src/org/infinity/resource/effects/Opcode160.java b/src/org/infinity/resource/effects/Opcode160.java index f9dae01f6..eb240a13e 100644 --- a/src/org/infinity/resource/effects/Opcode160.java +++ b/src/org/infinity/resource/effects/Opcode160.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 160. + * Implementation of opcode 160. */ public class Opcode160 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode161.java b/src/org/infinity/resource/effects/Opcode161.java index bc89f0ee7..c8611b265 100644 --- a/src/org/infinity/resource/effects/Opcode161.java +++ b/src/org/infinity/resource/effects/Opcode161.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 161. + * Implementation of opcode 161. */ public class Opcode161 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode162.java b/src/org/infinity/resource/effects/Opcode162.java index 816095b06..fea1b94db 100644 --- a/src/org/infinity/resource/effects/Opcode162.java +++ b/src/org/infinity/resource/effects/Opcode162.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 162. + * Implementation of opcode 162. */ public class Opcode162 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode163.java b/src/org/infinity/resource/effects/Opcode163.java index 6d050096a..7679f8b75 100644 --- a/src/org/infinity/resource/effects/Opcode163.java +++ b/src/org/infinity/resource/effects/Opcode163.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 163. + * Implementation of opcode 163. */ public class Opcode163 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode164.java b/src/org/infinity/resource/effects/Opcode164.java index 2f4dd7823..dbf5a4baa 100644 --- a/src/org/infinity/resource/effects/Opcode164.java +++ b/src/org/infinity/resource/effects/Opcode164.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 164. + * Implementation of opcode 164. */ public class Opcode164 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode165.java b/src/org/infinity/resource/effects/Opcode165.java index 48e047017..77edf68b3 100644 --- a/src/org/infinity/resource/effects/Opcode165.java +++ b/src/org/infinity/resource/effects/Opcode165.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 165. + * Implementation of opcode 165. */ public class Opcode165 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode166.java b/src/org/infinity/resource/effects/Opcode166.java index df8ddd099..750481ef6 100644 --- a/src/org/infinity/resource/effects/Opcode166.java +++ b/src/org/infinity/resource/effects/Opcode166.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 166. + * Implementation of opcode 166. */ public class Opcode166 extends BaseOpcode { private static final String[] INC_TYPES_GENERIC = Arrays.copyOf(INC_TYPES, 2); diff --git a/src/org/infinity/resource/effects/Opcode167.java b/src/org/infinity/resource/effects/Opcode167.java index 6bdb63503..66ab10b6b 100644 --- a/src/org/infinity/resource/effects/Opcode167.java +++ b/src/org/infinity/resource/effects/Opcode167.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 167. + * Implementation of opcode 167. */ public class Opcode167 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode168.java b/src/org/infinity/resource/effects/Opcode168.java index 6be760f24..5d7df5b63 100644 --- a/src/org/infinity/resource/effects/Opcode168.java +++ b/src/org/infinity/resource/effects/Opcode168.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 168. + * Implementation of opcode 168. */ public class Opcode168 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode169.java b/src/org/infinity/resource/effects/Opcode169.java index 346c1b021..3706e6a3e 100644 --- a/src/org/infinity/resource/effects/Opcode169.java +++ b/src/org/infinity/resource/effects/Opcode169.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 169. + * Implementation of opcode 169. */ public class Opcode169 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode170.java b/src/org/infinity/resource/effects/Opcode170.java index f5fb7909b..b15a61012 100644 --- a/src/org/infinity/resource/effects/Opcode170.java +++ b/src/org/infinity/resource/effects/Opcode170.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 170. + * Implementation of opcode 170. */ public class Opcode170 extends BaseOpcode { private static final String EFFECT_ANIMATION = "Animation"; diff --git a/src/org/infinity/resource/effects/Opcode171.java b/src/org/infinity/resource/effects/Opcode171.java index 5bfd709d4..d809a4da8 100644 --- a/src/org/infinity/resource/effects/Opcode171.java +++ b/src/org/infinity/resource/effects/Opcode171.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 171. + * Implementation of opcode 171. */ public class Opcode171 extends BaseOpcode { private static final String RES_TYPE = "SPL"; diff --git a/src/org/infinity/resource/effects/Opcode172.java b/src/org/infinity/resource/effects/Opcode172.java index 6e54dbe0e..cdb2fefcc 100644 --- a/src/org/infinity/resource/effects/Opcode172.java +++ b/src/org/infinity/resource/effects/Opcode172.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 172. + * Implementation of opcode 172. */ public class Opcode172 extends BaseOpcode { private static final String RES_TYPE = "SPL"; diff --git a/src/org/infinity/resource/effects/Opcode173.java b/src/org/infinity/resource/effects/Opcode173.java index e4881f841..dbc631df2 100644 --- a/src/org/infinity/resource/effects/Opcode173.java +++ b/src/org/infinity/resource/effects/Opcode173.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 173. + * Implementation of opcode 173. */ public class Opcode173 extends BaseOpcode { private static final String[] INC_TYPES_TOBEX = { INC_TYPES[1], INC_TYPES[0], INC_TYPES[2], "Instantaneous" }; diff --git a/src/org/infinity/resource/effects/Opcode174.java b/src/org/infinity/resource/effects/Opcode174.java index 35e9943db..be9b80761 100644 --- a/src/org/infinity/resource/effects/Opcode174.java +++ b/src/org/infinity/resource/effects/Opcode174.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 174. + * Implementation of opcode 174. */ public class Opcode174 extends BaseOpcode { private static final String RES_TYPE = "WAV"; diff --git a/src/org/infinity/resource/effects/Opcode175.java b/src/org/infinity/resource/effects/Opcode175.java index d9df3a5ae..d9a7cda76 100644 --- a/src/org/infinity/resource/effects/Opcode175.java +++ b/src/org/infinity/resource/effects/Opcode175.java @@ -12,7 +12,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 175. + * Implementation of opcode 175. */ public class Opcode175 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode176.java b/src/org/infinity/resource/effects/Opcode176.java index f8cf25fbb..eed7262fe 100644 --- a/src/org/infinity/resource/effects/Opcode176.java +++ b/src/org/infinity/resource/effects/Opcode176.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 176. + * Implementation of opcode 176. */ public class Opcode176 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -49,10 +49,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new HashBitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES_MAP, false)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode177.java b/src/org/infinity/resource/effects/Opcode177.java index 991889f76..2e95f7984 100644 --- a/src/org/infinity/resource/effects/Opcode177.java +++ b/src/org/infinity/resource/effects/Opcode177.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 177. + * Implementation of opcode 177. */ public class Opcode177 extends BaseOpcode { private static final String RES_TYPE = "EFF"; @@ -39,10 +39,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(param2); return RES_TYPE; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode178.java b/src/org/infinity/resource/effects/Opcode178.java index a1347ef8f..7af7e4760 100644 --- a/src/org/infinity/resource/effects/Opcode178.java +++ b/src/org/infinity/resource/effects/Opcode178.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 178. + * Implementation of opcode 178. */ public class Opcode178 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -39,12 +39,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode179.java b/src/org/infinity/resource/effects/Opcode179.java index fc7f0e2e7..799a95878 100644 --- a/src/org/infinity/resource/effects/Opcode179.java +++ b/src/org/infinity/resource/effects/Opcode179.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 179. + * Implementation of opcode 179. */ public class Opcode179 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -39,12 +39,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode180.java b/src/org/infinity/resource/effects/Opcode180.java index 5ecf4d032..9a290031f 100644 --- a/src/org/infinity/resource/effects/Opcode180.java +++ b/src/org/infinity/resource/effects/Opcode180.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 180. + * Implementation of opcode 180. */ public class Opcode180 extends BaseOpcode { private static final String EFFECT_RESTRICTION = "Restriction"; @@ -53,10 +53,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_RESTRICTION, RESTRICTION_TYPES_EE)); return RES_TYPE; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode181.java b/src/org/infinity/resource/effects/Opcode181.java index 3a570ace8..4d1a6ccfc 100644 --- a/src/org/infinity/resource/effects/Opcode181.java +++ b/src/org/infinity/resource/effects/Opcode181.java @@ -9,13 +9,13 @@ import org.infinity.datatype.Bitmap; import org.infinity.datatype.Datatype; +import org.infinity.datatype.ItemTypeBitmap; import org.infinity.datatype.StringRef; import org.infinity.resource.Profile; import org.infinity.resource.StructEntry; -import org.infinity.resource.itm.ItmResource; /** - * Implemention of opcode 181. + * Implementation of opcode 181. */ public class Opcode181 extends BaseOpcode { private static final String EFFECT_DESC_NOTE = "Description note"; @@ -41,24 +41,18 @@ public Opcode181() { protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { list.add(new StringRef(buffer, offset, EFFECT_DESC_NOTE)); - list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE, ItmResource.CATEGORIES_ARRAY)); + list.add(new ItemTypeBitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE)); return null; } @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { - list.add(new Bitmap(buffer, offset, 4, EFFECT_ITEM_TYPE, ItmResource.CATEGORIES_ARRAY)); + list.add(new ItemTypeBitmap(buffer, offset, 4, EFFECT_ITEM_TYPE)); list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_RESTRICTION, RESTRICTION_TYPES_EE)); return null; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode182.java b/src/org/infinity/resource/effects/Opcode182.java index 8ece14a7b..bc8b62935 100644 --- a/src/org/infinity/resource/effects/Opcode182.java +++ b/src/org/infinity/resource/effects/Opcode182.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 182. + * Implementation of opcode 182. */ public class Opcode182 extends BaseOpcode { private static final String RES_TYPE = "ITM"; diff --git a/src/org/infinity/resource/effects/Opcode183.java b/src/org/infinity/resource/effects/Opcode183.java index 50f7fabf1..c9002b66c 100644 --- a/src/org/infinity/resource/effects/Opcode183.java +++ b/src/org/infinity/resource/effects/Opcode183.java @@ -7,17 +7,16 @@ import java.nio.ByteBuffer; import java.util.List; -import org.infinity.datatype.Bitmap; import org.infinity.datatype.Datatype; import org.infinity.datatype.DecNumber; +import org.infinity.datatype.ItemTypeBitmap; import org.infinity.datatype.StringRef; import org.infinity.resource.AbstractStruct; import org.infinity.resource.Profile; import org.infinity.resource.StructEntry; -import org.infinity.resource.itm.ItmResource; /** - * Implemention of opcode 183. + * Implementation of opcode 183. */ public class Opcode183 extends BaseOpcode { private static final String EFFECT_ITEM_TYPE = "Item type"; @@ -41,7 +40,7 @@ public Opcode183() { protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { list.add(new DecNumber(buffer, offset, 4, AbstractStruct.COMMON_UNUSED)); - list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE, ItmResource.CATEGORIES_ARRAY)); + list.add(new ItemTypeBitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE)); return RES_TYPE; } @@ -49,13 +48,7 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { list.add(new StringRef(buffer, offset, EFFECT_STRING)); - list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE, ItmResource.CATEGORIES_ARRAY)); + list.add(new ItemTypeBitmap(buffer, offset + 4, 4, EFFECT_ITEM_TYPE)); return RES_TYPE; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode184.java b/src/org/infinity/resource/effects/Opcode184.java index 4f6d3918a..e14e86810 100644 --- a/src/org/infinity/resource/effects/Opcode184.java +++ b/src/org/infinity/resource/effects/Opcode184.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 184. + * Implementation of opcode 184. */ public class Opcode184 extends BaseOpcode { private static final String EFFECT_PASS_WALLS = "Pass walls?"; @@ -40,10 +40,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_PASS_WALLS, AbstractStruct.OPTION_NOYES)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode185.java b/src/org/infinity/resource/effects/Opcode185.java index 0c5119512..7ffcc5ef0 100644 --- a/src/org/infinity/resource/effects/Opcode185.java +++ b/src/org/infinity/resource/effects/Opcode185.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 185. + * Implementation of opcode 185. */ public class Opcode185 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -53,10 +53,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode186.java b/src/org/infinity/resource/effects/Opcode186.java index e8e64e0de..8a7a800a6 100644 --- a/src/org/infinity/resource/effects/Opcode186.java +++ b/src/org/infinity/resource/effects/Opcode186.java @@ -18,7 +18,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 186. + * Implementation of opcode 186. */ public class Opcode186 extends BaseOpcode { private static final String EFFECT_DELAY = "Delay"; diff --git a/src/org/infinity/resource/effects/Opcode187.java b/src/org/infinity/resource/effects/Opcode187.java index 0f7c6aa3c..686dd85bf 100644 --- a/src/org/infinity/resource/effects/Opcode187.java +++ b/src/org/infinity/resource/effects/Opcode187.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 187. + * Implementation of opcode 187. */ public class Opcode187 extends BaseOpcode { private static final String EFFECT_METHOD = "Method"; diff --git a/src/org/infinity/resource/effects/Opcode188.java b/src/org/infinity/resource/effects/Opcode188.java index af7a9e8a7..f30e5b343 100644 --- a/src/org/infinity/resource/effects/Opcode188.java +++ b/src/org/infinity/resource/effects/Opcode188.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 188. + * Implementation of opcode 188. */ public class Opcode188 extends BaseOpcode { private static final String EFFECT_SPELLS_PER_ROUND = "Spells per round"; diff --git a/src/org/infinity/resource/effects/Opcode189.java b/src/org/infinity/resource/effects/Opcode189.java index d83f6ebd3..f94d11eaf 100644 --- a/src/org/infinity/resource/effects/Opcode189.java +++ b/src/org/infinity/resource/effects/Opcode189.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 189. + * Implementation of opcode 189. */ public class Opcode189 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode190.java b/src/org/infinity/resource/effects/Opcode190.java index 51f7daff6..9cd9ffed3 100644 --- a/src/org/infinity/resource/effects/Opcode190.java +++ b/src/org/infinity/resource/effects/Opcode190.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 190. + * Implementation of opcode 190. */ public class Opcode190 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode191.java b/src/org/infinity/resource/effects/Opcode191.java index 99450af50..832414ec3 100644 --- a/src/org/infinity/resource/effects/Opcode191.java +++ b/src/org/infinity/resource/effects/Opcode191.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 191. + * Implementation of opcode 191. */ public class Opcode191 extends BaseOpcode { private static final String EFFECT_SPELL_CLASS = "Spell class"; diff --git a/src/org/infinity/resource/effects/Opcode192.java b/src/org/infinity/resource/effects/Opcode192.java index c5cc755d6..d8a46addd 100644 --- a/src/org/infinity/resource/effects/Opcode192.java +++ b/src/org/infinity/resource/effects/Opcode192.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 192. + * Implementation of opcode 192. */ public class Opcode192 extends BaseOpcode { private static final String EFFECT_DIRECTION = "Direction"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode193.java b/src/org/infinity/resource/effects/Opcode193.java index dd8760515..41a5aae2a 100644 --- a/src/org/infinity/resource/effects/Opcode193.java +++ b/src/org/infinity/resource/effects/Opcode193.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 193. + * Implementation of opcode 193. */ public class Opcode193 extends BaseOpcode { private static final String EFFECT_IGNORE_VISIBILITY = "Ignore visibility?"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode194.java b/src/org/infinity/resource/effects/Opcode194.java index 1218da68f..e00a78d57 100644 --- a/src/org/infinity/resource/effects/Opcode194.java +++ b/src/org/infinity/resource/effects/Opcode194.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 194. + * Implementation of opcode 194. */ public class Opcode194 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,24 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode195.java b/src/org/infinity/resource/effects/Opcode195.java index a4dacf042..89f105cbd 100644 --- a/src/org/infinity/resource/effects/Opcode195.java +++ b/src/org/infinity/resource/effects/Opcode195.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 195. + * Implementation of opcode 195. */ public class Opcode195 extends BaseOpcode { private static final String EFFECT_HP_AMOUNT = "HP amount"; @@ -67,24 +67,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode196.java b/src/org/infinity/resource/effects/Opcode196.java index 36dc5354b..9ef308fdc 100644 --- a/src/org/infinity/resource/effects/Opcode196.java +++ b/src/org/infinity/resource/effects/Opcode196.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 196. + * Implementation of opcode 196. */ public class Opcode196 extends BaseOpcode { private static final String EFFECT_FX = "Effect"; @@ -48,24 +48,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode197.java b/src/org/infinity/resource/effects/Opcode197.java index 4971a6599..695fb529c 100644 --- a/src/org/infinity/resource/effects/Opcode197.java +++ b/src/org/infinity/resource/effects/Opcode197.java @@ -16,7 +16,7 @@ import org.infinity.util.IdsMapEntry; /** - * Implemention of opcode 197. + * Implementation of opcode 197. */ public class Opcode197 extends BaseOpcode { private static final String EFFECT_PROJECTILE = "Projectile"; @@ -47,28 +47,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(ids); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode198.java b/src/org/infinity/resource/effects/Opcode198.java index 939ece295..7386d8db0 100644 --- a/src/org/infinity/resource/effects/Opcode198.java +++ b/src/org/infinity/resource/effects/Opcode198.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 198. + * Implementation of opcode 198. */ public class Opcode198 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,28 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new EffectBitmap(buffer, offset + 4, 4)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode199.java b/src/org/infinity/resource/effects/Opcode199.java index 797792452..e1628693c 100644 --- a/src/org/infinity/resource/effects/Opcode199.java +++ b/src/org/infinity/resource/effects/Opcode199.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 199. + * Implementation of opcode 199. */ public class Opcode199 extends BaseOpcode { private static final String EFFECT_SPELL_LEVEL = "Spell level"; @@ -43,28 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode200.java b/src/org/infinity/resource/effects/Opcode200.java index 23cbcbd03..439d74b7d 100644 --- a/src/org/infinity/resource/effects/Opcode200.java +++ b/src/org/infinity/resource/effects/Opcode200.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 200. + * Implementation of opcode 200. */ public class Opcode200 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -59,22 +53,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_SPELL_LEVEL)); return RES_TYPE; } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode201.java b/src/org/infinity/resource/effects/Opcode201.java index 12b094d60..4a195eaaf 100644 --- a/src/org/infinity/resource/effects/Opcode201.java +++ b/src/org/infinity/resource/effects/Opcode201.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 201. + * Implementation of opcode 201. */ public class Opcode201 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -55,12 +55,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -69,18 +63,6 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs return RES_TYPE; } - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode202.java b/src/org/infinity/resource/effects/Opcode202.java index 83f51e0ef..36e61565e 100644 --- a/src/org/infinity/resource/effects/Opcode202.java +++ b/src/org/infinity/resource/effects/Opcode202.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 202. + * Implementation of opcode 202. */ public class Opcode202 extends BaseOpcode { private static final String EFFECT_SPELL_SCHOOL = "Spell school"; @@ -44,28 +44,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new PriTypeBitmap(buffer, offset + 4, 4, EFFECT_SPELL_SCHOOL)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode203.java b/src/org/infinity/resource/effects/Opcode203.java index 4bec5773d..220fecae7 100644 --- a/src/org/infinity/resource/effects/Opcode203.java +++ b/src/org/infinity/resource/effects/Opcode203.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 203. + * Implementation of opcode 203. */ public class Opcode203 extends BaseOpcode { private static final String EFFECT_SPELL_TYPE = "Spell type"; @@ -46,24 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode204.java b/src/org/infinity/resource/effects/Opcode204.java index d416d0fc5..91be4a0f5 100644 --- a/src/org/infinity/resource/effects/Opcode204.java +++ b/src/org/infinity/resource/effects/Opcode204.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 204. + * Implementation of opcode 204. */ public class Opcode204 extends BaseOpcode { private static final String EFFECT_SPELL_SCHOOL = "Spell school"; @@ -46,24 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode205.java b/src/org/infinity/resource/effects/Opcode205.java index 1e3d329d5..44b062e9c 100644 --- a/src/org/infinity/resource/effects/Opcode205.java +++ b/src/org/infinity/resource/effects/Opcode205.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 205. + * Implementation of opcode 205. */ public class Opcode205 extends BaseOpcode { private static final String EFFECT_SPELL_TYPE = "Spell type"; @@ -47,24 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode206.java b/src/org/infinity/resource/effects/Opcode206.java index 9633facce..f52eff811 100644 --- a/src/org/infinity/resource/effects/Opcode206.java +++ b/src/org/infinity/resource/effects/Opcode206.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 206. + * Implementation of opcode 206. */ public class Opcode206 extends BaseOpcode { private static final String EFFECT_EMBALMING_TYPE = "Embalming type"; @@ -50,12 +50,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode207.java b/src/org/infinity/resource/effects/Opcode207.java index 593979c11..774c23b62 100644 --- a/src/org/infinity/resource/effects/Opcode207.java +++ b/src/org/infinity/resource/effects/Opcode207.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 207. + * Implementation of opcode 207. */ public class Opcode207 extends BaseOpcode { private static final String RES_TYPE = "SPL"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,12 +57,6 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off return null; } - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode208.java b/src/org/infinity/resource/effects/Opcode208.java index dca3eb58a..3df176e1c 100644 --- a/src/org/infinity/resource/effects/Opcode208.java +++ b/src/org/infinity/resource/effects/Opcode208.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 208. + * Implementation of opcode 208. */ public class Opcode208 extends BaseOpcode { private static final String EFFECT_HP_AMOUNT = "HP amount"; @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode209.java b/src/org/infinity/resource/effects/Opcode209.java index c4fd1c010..a3067f13c 100644 --- a/src/org/infinity/resource/effects/Opcode209.java +++ b/src/org/infinity/resource/effects/Opcode209.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 209. + * Implementation of opcode 209. */ public class Opcode209 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,16 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode210.java b/src/org/infinity/resource/effects/Opcode210.java index 51e844fcf..025bd78d8 100644 --- a/src/org/infinity/resource/effects/Opcode210.java +++ b/src/org/infinity/resource/effects/Opcode210.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 210. + * Implementation of opcode 210. */ public class Opcode210 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,18 +42,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode211.java b/src/org/infinity/resource/effects/Opcode211.java index 36c571cf7..ce5c40bc8 100644 --- a/src/org/infinity/resource/effects/Opcode211.java +++ b/src/org/infinity/resource/effects/Opcode211.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 211. + * Implementation of opcode 211. */ public class Opcode211 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,16 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode212.java b/src/org/infinity/resource/effects/Opcode212.java index 58d016959..e2b484243 100644 --- a/src/org/infinity/resource/effects/Opcode212.java +++ b/src/org/infinity/resource/effects/Opcode212.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 212. + * Implementation of opcode 212. */ public class Opcode212 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,18 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { diff --git a/src/org/infinity/resource/effects/Opcode213.java b/src/org/infinity/resource/effects/Opcode213.java index b4722210b..5d3020208 100644 --- a/src/org/infinity/resource/effects/Opcode213.java +++ b/src/org/infinity/resource/effects/Opcode213.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 213. + * Implementation of opcode 213. */ public class Opcode213 extends BaseOpcode { private static final String[] MODE_TYPES = { "Use INTMOD.2DA", "Use duration" }; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,18 +54,6 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off return null; } - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode214.java b/src/org/infinity/resource/effects/Opcode214.java index 11bf9e96d..c670ac710 100644 --- a/src/org/infinity/resource/effects/Opcode214.java +++ b/src/org/infinity/resource/effects/Opcode214.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 214. + * Implementation of opcode 214. */ public class Opcode214 extends BaseOpcode { private static final String EFFECT_SHOW = "Show"; @@ -52,12 +52,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -80,9 +74,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode215.java b/src/org/infinity/resource/effects/Opcode215.java index 0dc3e76e2..ada4728ab 100644 --- a/src/org/infinity/resource/effects/Opcode215.java +++ b/src/org/infinity/resource/effects/Opcode215.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 215. + * Implementation of opcode 215. */ public class Opcode215 extends BaseOpcode { private static final String EFFECT_PLAY_WHERE = "Play where?"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,16 +58,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode216.java b/src/org/infinity/resource/effects/Opcode216.java index dcbb133be..a0906b27f 100644 --- a/src/org/infinity/resource/effects/Opcode216.java +++ b/src/org/infinity/resource/effects/Opcode216.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 216. + * Implementation of opcode 216. */ public class Opcode216 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -58,16 +52,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode217.java b/src/org/infinity/resource/effects/Opcode217.java index 0002c780b..c4f430e21 100644 --- a/src/org/infinity/resource/effects/Opcode217.java +++ b/src/org/infinity/resource/effects/Opcode217.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 217. + * Implementation of opcode 217. */ public class Opcode217 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,22 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode218.java b/src/org/infinity/resource/effects/Opcode218.java index 71ddb2170..288a13e56 100644 --- a/src/org/infinity/resource/effects/Opcode218.java +++ b/src/org/infinity/resource/effects/Opcode218.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 218. + * Implementation of opcode 218. */ public class Opcode218 extends BaseOpcode { private static final String EFFECT_NUM_SKINS = "# skins"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -73,12 +67,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return null; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectResource(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode219.java b/src/org/infinity/resource/effects/Opcode219.java index 38706f0bb..88ffcaf57 100644 --- a/src/org/infinity/resource/effects/Opcode219.java +++ b/src/org/infinity/resource/effects/Opcode219.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 219. + * Implementation of opcode 219. */ public class Opcode219 extends BaseOpcode { private final String[] idsList = { "", "", "EA.IDS", "GENERAL.IDS", "RACE.IDS", "CLASS.IDS", "", "GENDER.IDS", @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -73,16 +67,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode220.java b/src/org/infinity/resource/effects/Opcode220.java index e88e18a98..009d994d5 100644 --- a/src/org/infinity/resource/effects/Opcode220.java +++ b/src/org/infinity/resource/effects/Opcode220.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 220. + * Implementation of opcode 220. */ public class Opcode220 extends BaseOpcode { private static final String EFFECT_MAX_LEVEL = "Maximum level"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,16 +54,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode221.java b/src/org/infinity/resource/effects/Opcode221.java index 32b71b7ba..11417dedb 100644 --- a/src/org/infinity/resource/effects/Opcode221.java +++ b/src/org/infinity/resource/effects/Opcode221.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 221. + * Implementation of opcode 221. */ public class Opcode221 extends BaseOpcode { private static final String EFFECT_MAX_LEVEL = "Maximum level"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,16 +54,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode222.java b/src/org/infinity/resource/effects/Opcode222.java index 419f37384..cae3bebf6 100644 --- a/src/org/infinity/resource/effects/Opcode222.java +++ b/src/org/infinity/resource/effects/Opcode222.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 222. + * Implementation of opcode 222. */ public class Opcode222 extends BaseOpcode { private static final String EFFECT_MAX_RANGE = "Maximum range"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -58,16 +52,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode223.java b/src/org/infinity/resource/effects/Opcode223.java index 740d96960..c77bcea8e 100644 --- a/src/org/infinity/resource/effects/Opcode223.java +++ b/src/org/infinity/resource/effects/Opcode223.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 223. + * Implementation of opcode 223. */ public class Opcode223 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,16 +64,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode224.java b/src/org/infinity/resource/effects/Opcode224.java index e4aade971..54b82d403 100644 --- a/src/org/infinity/resource/effects/Opcode224.java +++ b/src/org/infinity/resource/effects/Opcode224.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 224. + * Implementation of opcode 224. */ public class Opcode224 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,22 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode225.java b/src/org/infinity/resource/effects/Opcode225.java index 68fb22c15..577587396 100644 --- a/src/org/infinity/resource/effects/Opcode225.java +++ b/src/org/infinity/resource/effects/Opcode225.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 225. + * Implementation of opcode 225. */ public class Opcode225 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,22 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode226.java b/src/org/infinity/resource/effects/Opcode226.java index e5f52f9f0..528d51b0b 100644 --- a/src/org/infinity/resource/effects/Opcode226.java +++ b/src/org/infinity/resource/effects/Opcode226.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 226. + * Implementation of opcode 226. */ public class Opcode226 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,16 +64,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode227.java b/src/org/infinity/resource/effects/Opcode227.java index a52a233da..46e498aa4 100644 --- a/src/org/infinity/resource/effects/Opcode227.java +++ b/src/org/infinity/resource/effects/Opcode227.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 227. + * Implementation of opcode 227. */ public class Opcode227 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,16 +64,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode228.java b/src/org/infinity/resource/effects/Opcode228.java index d3e56d32d..f26319005 100644 --- a/src/org/infinity/resource/effects/Opcode228.java +++ b/src/org/infinity/resource/effects/Opcode228.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 228. + * Implementation of opcode 228. */ public class Opcode228 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,16 +64,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode229.java b/src/org/infinity/resource/effects/Opcode229.java index dbd1fc993..4a64fc01c 100644 --- a/src/org/infinity/resource/effects/Opcode229.java +++ b/src/org/infinity/resource/effects/Opcode229.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 229. + * Implementation of opcode 229. */ public class Opcode229 extends BaseOpcode { private static final String EFFECT_MAX_LEVEL = "Maximum level"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,16 +54,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode230.java b/src/org/infinity/resource/effects/Opcode230.java index a9a7cc708..9ed3e0b65 100644 --- a/src/org/infinity/resource/effects/Opcode230.java +++ b/src/org/infinity/resource/effects/Opcode230.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 230. + * Implementation of opcode 230. */ public class Opcode230 extends BaseOpcode { private static final String EFFECT_MAX_LEVEL = "Maximum level"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,16 +54,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode231.java b/src/org/infinity/resource/effects/Opcode231.java index d3918d475..e00b48b4a 100644 --- a/src/org/infinity/resource/effects/Opcode231.java +++ b/src/org/infinity/resource/effects/Opcode231.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 231. + * Implementation of opcode 231. */ public class Opcode231 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,22 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode232.java b/src/org/infinity/resource/effects/Opcode232.java index 849e3463b..45826293e 100644 --- a/src/org/infinity/resource/effects/Opcode232.java +++ b/src/org/infinity/resource/effects/Opcode232.java @@ -22,7 +22,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 232. + * Implementation of opcode 232. */ public class Opcode232 extends BaseOpcode { private static final String EFFECT_TARGET = "Target"; @@ -93,12 +93,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -118,7 +112,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new Bitmap(buffer, offset, 4, EFFECT_TARGET, TARGETS)); Bitmap item = new Bitmap(buffer, offset + 4, 4, EFFECT_CONDITION, CONDITIONS_EE); list.add(item); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { item.addUpdateListener((UpdateListener)parent); } return RES_TYPE; @@ -141,12 +135,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return null; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected boolean update(AbstractStruct struct) throws Exception { if (struct != null && Profile.isEnhancedEdition()) { diff --git a/src/org/infinity/resource/effects/Opcode233.java b/src/org/infinity/resource/effects/Opcode233.java index 5f40a28ce..81dfa1c28 100644 --- a/src/org/infinity/resource/effects/Opcode233.java +++ b/src/org/infinity/resource/effects/Opcode233.java @@ -19,7 +19,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 233. + * Implementation of opcode 233. */ public class Opcode233 extends BaseOpcode { private static final String EFFECT_NUM_STARS = "# stars"; @@ -56,12 +56,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -104,12 +98,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected boolean update(AbstractStruct struct) throws Exception { if (struct != null && Profile.isEnhancedEdition()) { diff --git a/src/org/infinity/resource/effects/Opcode234.java b/src/org/infinity/resource/effects/Opcode234.java index cafaf723c..64a95a7ad 100644 --- a/src/org/infinity/resource/effects/Opcode234.java +++ b/src/org/infinity/resource/effects/Opcode234.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 234. + * Implementation of opcode 234. */ public class Opcode234 extends BaseOpcode { private static final String EFFECT_MAX_SPELL_LEVEL = "Maximum spell level"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,16 +58,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode235.java b/src/org/infinity/resource/effects/Opcode235.java index 3051deeaf..74a41adcf 100644 --- a/src/org/infinity/resource/effects/Opcode235.java +++ b/src/org/infinity/resource/effects/Opcode235.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 235. + * Implementation of opcode 235. */ public class Opcode235 extends BaseOpcode { private static final String EFFECT_STRENGTH = "Strength"; @@ -54,12 +54,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -73,10 +67,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode236.java b/src/org/infinity/resource/effects/Opcode236.java index 6be9422c4..7c81e1987 100644 --- a/src/org/infinity/resource/effects/Opcode236.java +++ b/src/org/infinity/resource/effects/Opcode236.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 236. + * Implementation of opcode 236. */ public class Opcode236 extends BaseOpcode { private static final String EFFECT_IMAGE_TYPE = "Image type"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode237.java b/src/org/infinity/resource/effects/Opcode237.java index e616ae6ac..171d9eb96 100644 --- a/src/org/infinity/resource/effects/Opcode237.java +++ b/src/org/infinity/resource/effects/Opcode237.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 237. + * Implementation of opcode 237. */ public class Opcode237 extends BaseOpcode { private static final String EFFECT_PUPPET_MASTER = "Puppet master"; @@ -63,12 +63,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -76,16 +70,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode238.java b/src/org/infinity/resource/effects/Opcode238.java index 50601bdd3..d7bbeb1a2 100644 --- a/src/org/infinity/resource/effects/Opcode238.java +++ b/src/org/infinity/resource/effects/Opcode238.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 238. + * Implementation of opcode 238. */ public class Opcode238 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,10 +58,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode239.java b/src/org/infinity/resource/effects/Opcode239.java index 332395e94..ab827c496 100644 --- a/src/org/infinity/resource/effects/Opcode239.java +++ b/src/org/infinity/resource/effects/Opcode239.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 239. + * Implementation of opcode 239. */ public class Opcode239 extends BaseOpcode { private static final String EFFECT_VIEW_UNEXPLORED = "Can view unexplored?"; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -65,10 +59,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode240.java b/src/org/infinity/resource/effects/Opcode240.java index a9812ef66..1766fca2c 100644 --- a/src/org/infinity/resource/effects/Opcode240.java +++ b/src/org/infinity/resource/effects/Opcode240.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 240. + * Implementation of opcode 240. */ public class Opcode240 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; @@ -52,12 +52,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -65,16 +59,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_SUMMON_TYPE, SUMMON_TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode241.java b/src/org/infinity/resource/effects/Opcode241.java index c915005d8..b8072cc09 100644 --- a/src/org/infinity/resource/effects/Opcode241.java +++ b/src/org/infinity/resource/effects/Opcode241.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 241. + * Implementation of opcode 241. */ public class Opcode241 extends BaseOpcode { private static final String EFFECT_CRE_TYPE = "Creature type"; @@ -69,12 +69,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -88,10 +82,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode242.java b/src/org/infinity/resource/effects/Opcode242.java index ce38c9ce5..7b8e8bec5 100644 --- a/src/org/infinity/resource/effects/Opcode242.java +++ b/src/org/infinity/resource/effects/Opcode242.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 242. + * Implementation of opcode 242. */ public class Opcode242 extends BaseOpcode { private static final String EFFECT_OVERLAY = "Overlay"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,16 +58,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_OVERLAY, OVERLAY_TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode243.java b/src/org/infinity/resource/effects/Opcode243.java index 1d31064b3..289db4721 100644 --- a/src/org/infinity/resource/effects/Opcode243.java +++ b/src/org/infinity/resource/effects/Opcode243.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 243. + * Implementation of opcode 243. */ public class Opcode243 extends BaseOpcode { private static final String EFFECT_INCLUDE_WEAPONS = "Include weapons?"; @@ -52,12 +52,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -77,16 +71,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_UNDEAD_TYPE, UNDEAD_TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode244.java b/src/org/infinity/resource/effects/Opcode244.java index 383371b00..57cbae476 100644 --- a/src/org/infinity/resource/effects/Opcode244.java +++ b/src/org/infinity/resource/effects/Opcode244.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 244. + * Implementation of opcode 244. */ public class Opcode244 extends BaseOpcode { private static final String EFFECT_NUM_SPELLS = "# spells"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_PRAYER_TYPE, PRAYER_TYPES_IWD2)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode245.java b/src/org/infinity/resource/effects/Opcode245.java index 9491e9862..e2156e72d 100644 --- a/src/org/infinity/resource/effects/Opcode245.java +++ b/src/org/infinity/resource/effects/Opcode245.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 245. + * Implementation of opcode 245. */ public class Opcode245 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -56,16 +50,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode246.java b/src/org/infinity/resource/effects/Opcode246.java index a8628f9d5..a33a86c70 100644 --- a/src/org/infinity/resource/effects/Opcode246.java +++ b/src/org/infinity/resource/effects/Opcode246.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 246. + * Implementation of opcode 246. */ public class Opcode246 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,16 +58,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_CREATURE_TYPE, CREATURE_TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode247.java b/src/org/infinity/resource/effects/Opcode247.java index 452798394..56259feaa 100644 --- a/src/org/infinity/resource/effects/Opcode247.java +++ b/src/org/infinity/resource/effects/Opcode247.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 247. + * Implementation of opcode 247. */ public class Opcode247 extends BaseOpcode { private static final String EFFECT_NUM_HITS = "# hits"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,10 +58,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode248.java b/src/org/infinity/resource/effects/Opcode248.java index 185bfdf1b..a06a8aef6 100644 --- a/src/org/infinity/resource/effects/Opcode248.java +++ b/src/org/infinity/resource/effects/Opcode248.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 248. + * Implementation of opcode 248. */ public class Opcode248 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; @@ -60,12 +60,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -87,10 +81,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode249.java b/src/org/infinity/resource/effects/Opcode249.java index 343a6a66d..adf4cc4cd 100644 --- a/src/org/infinity/resource/effects/Opcode249.java +++ b/src/org/infinity/resource/effects/Opcode249.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 249. + * Implementation of opcode 249. */ public class Opcode249 extends BaseOpcode { private static final String EFFECT_PRAYER_TYPE = "Prayer type"; @@ -50,12 +50,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -71,10 +65,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_PRAYER_TYPE, PRAYER_TYPES_IWD2)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode250.java b/src/org/infinity/resource/effects/Opcode250.java index 11599ca13..3dee20987 100644 --- a/src/org/infinity/resource/effects/Opcode250.java +++ b/src/org/infinity/resource/effects/Opcode250.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 250. + * Implementation of opcode 250. */ public class Opcode250 extends BaseOpcode { private static final String EFFECT_DAMAGE_VALUE = "Damage value"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -58,16 +52,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode251.java b/src/org/infinity/resource/effects/Opcode251.java index f9ad3877f..fc69017b3 100644 --- a/src/org/infinity/resource/effects/Opcode251.java +++ b/src/org/infinity/resource/effects/Opcode251.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 251. + * Implementation of opcode 251. */ public class Opcode251 extends BaseOpcode { private static final String EFFECT_NUM_SECONDS = "# seconds"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -60,16 +54,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode252.java b/src/org/infinity/resource/effects/Opcode252.java index 0d9da7107..ea277a5c7 100644 --- a/src/org/infinity/resource/effects/Opcode252.java +++ b/src/org/infinity/resource/effects/Opcode252.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 252. + * Implementation of opcode 252. */ public class Opcode252 extends BaseOpcode { private static final String RES_TYPE = "SPL"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -58,16 +52,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode253.java b/src/org/infinity/resource/effects/Opcode253.java index 833529504..b0cb3121e 100644 --- a/src/org/infinity/resource/effects/Opcode253.java +++ b/src/org/infinity/resource/effects/Opcode253.java @@ -20,7 +20,7 @@ import org.infinity.resource.are.AutomapNote; /** - * Implemention of opcode 253. + * Implementation of opcode 253. */ public class Opcode253 extends BaseOpcode { private static final String EFFECT_AC_VALUE = "AC value"; @@ -55,12 +55,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -88,16 +82,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Flag(buffer, offset + 4, 4, EFFECT_BONUS_TO, WEAPON_TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode254.java b/src/org/infinity/resource/effects/Opcode254.java index 42e93702d..6837a2779 100644 --- a/src/org/infinity/resource/effects/Opcode254.java +++ b/src/org/infinity/resource/effects/Opcode254.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 254. + * Implementation of opcode 254. */ public class Opcode254 extends BaseOpcode { private static final String EFFECT_DISPEL_TYPE = "Dispel type"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode255.java b/src/org/infinity/resource/effects/Opcode255.java index 05b24f496..b71773858 100644 --- a/src/org/infinity/resource/effects/Opcode255.java +++ b/src/org/infinity/resource/effects/Opcode255.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 255. + * Implementation of opcode 255. */ public class Opcode255 extends BaseOpcode { private static final String EFFECT_NUM_IN_STACK = "# items in stack"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode256.java b/src/org/infinity/resource/effects/Opcode256.java index a9abf29b5..3417f9bc2 100644 --- a/src/org/infinity/resource/effects/Opcode256.java +++ b/src/org/infinity/resource/effects/Opcode256.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 256. + * Implementation of opcode 256. */ public class Opcode256 extends BaseOpcode { private static final String EFFECT_NUM_SECONDS = "# seconds"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -66,10 +60,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode257.java b/src/org/infinity/resource/effects/Opcode257.java index 08192b25a..104d8dd52 100644 --- a/src/org/infinity/resource/effects/Opcode257.java +++ b/src/org/infinity/resource/effects/Opcode257.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 257. + * Implementation of opcode 257. */ public class Opcode257 extends BaseOpcode { private static final String EFFECT_MAX_LEVEL = "Maximum level"; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -59,16 +53,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode258.java b/src/org/infinity/resource/effects/Opcode258.java index c22b31f4a..ded898924 100644 --- a/src/org/infinity/resource/effects/Opcode258.java +++ b/src/org/infinity/resource/effects/Opcode258.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 258. + * Implementation of opcode 258. */ public class Opcode258 extends BaseOpcode { private static final String RES_TYPE = "ITM:SPL"; @@ -48,12 +48,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -61,10 +55,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_TYPE, TYPES_IWD)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode259.java b/src/org/infinity/resource/effects/Opcode259.java index af8e54f23..a0e890cff 100644 --- a/src/org/infinity/resource/effects/Opcode259.java +++ b/src/org/infinity/resource/effects/Opcode259.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 259. + * Implementation of opcode 259. */ public class Opcode259 extends BaseOpcode { private static final String EFFECT_NUM_SPELLS = "# spells"; @@ -53,12 +53,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -75,15 +69,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off return RES_TYPE_IWD; } - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode260.java b/src/org/infinity/resource/effects/Opcode260.java index 72090b45c..587edb30a 100644 --- a/src/org/infinity/resource/effects/Opcode260.java +++ b/src/org/infinity/resource/effects/Opcode260.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 260. + * Implementation of opcode 260. */ public class Opcode260 extends BaseOpcode { private static final String RES_TYPE = "ITM:SPL"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,10 +58,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode261.java b/src/org/infinity/resource/effects/Opcode261.java index a6412045c..5f07d5744 100644 --- a/src/org/infinity/resource/effects/Opcode261.java +++ b/src/org/infinity/resource/effects/Opcode261.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 261. + * Implementation of opcode 261. */ public class Opcode261 extends BaseOpcode { private static final String EFFECT_SPELL_LEVEL = "Spell level"; @@ -53,12 +53,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -74,10 +68,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new EffectBitmap(buffer, offset + 4, 4)); return RES_TYPE_IWD2; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode262.java b/src/org/infinity/resource/effects/Opcode262.java index d615c9d32..1e834459d 100644 --- a/src/org/infinity/resource/effects/Opcode262.java +++ b/src/org/infinity/resource/effects/Opcode262.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 262. + * Implementation of opcode 262. */ public class Opcode262 extends BaseOpcode { private static final String[] INC_TYPES_SPELLS = new String[] { "Increment", "Set" }; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -59,16 +53,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode263.java b/src/org/infinity/resource/effects/Opcode263.java index 13a1b17aa..9ebd3667b 100644 --- a/src/org/infinity/resource/effects/Opcode263.java +++ b/src/org/infinity/resource/effects/Opcode263.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 263. + * Implementation of opcode 263. */ public class Opcode263 extends BaseOpcode { private static final String EFFECT_CREATURE_TYPE = "Creature type"; @@ -59,12 +59,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -78,10 +72,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode264.java b/src/org/infinity/resource/effects/Opcode264.java index fecfee0b1..3a27cfb03 100644 --- a/src/org/infinity/resource/effects/Opcode264.java +++ b/src/org/infinity/resource/effects/Opcode264.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 264. + * Implementation of opcode 264. */ public class Opcode264 extends BaseOpcode { private static final String EFFECT_ONLY_QUICK = "Only weapons in quick slots?"; @@ -49,12 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return RES_TYPE_IWD2; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode265.java b/src/org/infinity/resource/effects/Opcode265.java index 865f7a4e5..46cae5690 100644 --- a/src/org/infinity/resource/effects/Opcode265.java +++ b/src/org/infinity/resource/effects/Opcode265.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 265. + * Implementation of opcode 265. */ public class Opcode265 extends BaseOpcode { private static final String EFFECT_NUM_HITS = "# hits"; @@ -50,12 +50,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE_STRING; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -71,10 +65,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return RES_TYPE_IWD2; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode266.java b/src/org/infinity/resource/effects/Opcode266.java index 3f071db1d..8b4e38f1f 100644 --- a/src/org/infinity/resource/effects/Opcode266.java +++ b/src/org/infinity/resource/effects/Opcode266.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 266. + * Implementation of opcode 266. */ public class Opcode266 extends BaseOpcode { private static final String RES_TYPE = "SPL"; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -65,10 +59,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode267.java b/src/org/infinity/resource/effects/Opcode267.java index 871d33393..cdf4a13ce 100644 --- a/src/org/infinity/resource/effects/Opcode267.java +++ b/src/org/infinity/resource/effects/Opcode267.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 267. + * Implementation of opcode 267. */ public class Opcode267 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode268.java b/src/org/infinity/resource/effects/Opcode268.java index 28b7a4993..0ed9cad58 100644 --- a/src/org/infinity/resource/effects/Opcode268.java +++ b/src/org/infinity/resource/effects/Opcode268.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 268. + * Implementation of opcode 268. */ public class Opcode268 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,16 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode269.java b/src/org/infinity/resource/effects/Opcode269.java index 8499583c3..afa43443d 100644 --- a/src/org/infinity/resource/effects/Opcode269.java +++ b/src/org/infinity/resource/effects/Opcode269.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 269. + * Implementation of opcode 269. */ public class Opcode269 extends BaseOpcode { private static final String EFFECT_STRENGTH = "Strength"; @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,10 +58,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode270.java b/src/org/infinity/resource/effects/Opcode270.java index 912f47123..14885d959 100644 --- a/src/org/infinity/resource/effects/Opcode270.java +++ b/src/org/infinity/resource/effects/Opcode270.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 270. + * Implementation of opcode 270. */ public class Opcode270 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode271.java b/src/org/infinity/resource/effects/Opcode271.java index 255b98203..acb2addf9 100644 --- a/src/org/infinity/resource/effects/Opcode271.java +++ b/src/org/infinity/resource/effects/Opcode271.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 271. + * Implementation of opcode 271. */ public class Opcode271 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,16 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode272.java b/src/org/infinity/resource/effects/Opcode272.java index c5a4e164a..3ebd96e0a 100644 --- a/src/org/infinity/resource/effects/Opcode272.java +++ b/src/org/infinity/resource/effects/Opcode272.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 272. + * Implementation of opcode 272. */ public class Opcode272 extends BaseOpcode { private static final String EFFECT_CONDITION = "Condition"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -71,12 +65,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode273.java b/src/org/infinity/resource/effects/Opcode273.java index a9eb236a9..68f4729ed 100644 --- a/src/org/infinity/resource/effects/Opcode273.java +++ b/src/org/infinity/resource/effects/Opcode273.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 273. + * Implementation of opcode 273. */ public class Opcode273 extends BaseOpcode { private static final String RES_TYPE = "2DA"; @@ -48,12 +48,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -73,10 +67,4 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return RES_TYPE; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode274.java b/src/org/infinity/resource/effects/Opcode274.java index 1c6c17c5f..3a0aeced6 100644 --- a/src/org/infinity/resource/effects/Opcode274.java +++ b/src/org/infinity/resource/effects/Opcode274.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 274. + * Implementation of opcode 274. */ public class Opcode274 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,16 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode275.java b/src/org/infinity/resource/effects/Opcode275.java index ec9e9717d..18261f38e 100644 --- a/src/org/infinity/resource/effects/Opcode275.java +++ b/src/org/infinity/resource/effects/Opcode275.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 275. + * Implementation of opcode 275. */ public class Opcode275 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode276.java b/src/org/infinity/resource/effects/Opcode276.java index c300ddde6..b74f7f25b 100644 --- a/src/org/infinity/resource/effects/Opcode276.java +++ b/src/org/infinity/resource/effects/Opcode276.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 276. + * Implementation of opcode 276. */ public class Opcode276 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -45,12 +45,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -64,10 +58,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode277.java b/src/org/infinity/resource/effects/Opcode277.java index 5581fbdcd..fa673f126 100644 --- a/src/org/infinity/resource/effects/Opcode277.java +++ b/src/org/infinity/resource/effects/Opcode277.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 277. + * Implementation of opcode 277. */ public class Opcode277 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -57,16 +51,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode278.java b/src/org/infinity/resource/effects/Opcode278.java index 4d5b82f9a..3629b21f1 100644 --- a/src/org/infinity/resource/effects/Opcode278.java +++ b/src/org/infinity/resource/effects/Opcode278.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 278. + * Implementation of opcode 278. */ public class Opcode278 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode279.java b/src/org/infinity/resource/effects/Opcode279.java index 7e0ad6ecf..a0c691943 100644 --- a/src/org/infinity/resource/effects/Opcode279.java +++ b/src/org/infinity/resource/effects/Opcode279.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 279. + * Implementation of opcode 279. */ public class Opcode279 extends BaseOpcode { private static final String EFFECT_BUTTON = "Button"; @@ -62,12 +62,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -101,10 +95,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode280.java b/src/org/infinity/resource/effects/Opcode280.java index 9640ae1e1..af9a959f5 100644 --- a/src/org/infinity/resource/effects/Opcode280.java +++ b/src/org/infinity/resource/effects/Opcode280.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 280. + * Implementation of opcode 280. */ public class Opcode280 extends BaseOpcode { private static final String EFFECT_AFFECT = "Affect"; @@ -52,12 +52,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -84,12 +78,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode281.java b/src/org/infinity/resource/effects/Opcode281.java index 6dbff9709..a096e7040 100644 --- a/src/org/infinity/resource/effects/Opcode281.java +++ b/src/org/infinity/resource/effects/Opcode281.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 281. + * Implementation of opcode 281. */ public class Opcode281 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode282.java b/src/org/infinity/resource/effects/Opcode282.java index 3b6f08b86..278a44227 100644 --- a/src/org/infinity/resource/effects/Opcode282.java +++ b/src/org/infinity/resource/effects/Opcode282.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 282. + * Implementation of opcode 282. */ public class Opcode282 extends BaseOpcode { private static final String EFFECT_STATE = "State"; @@ -77,12 +77,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -104,10 +98,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode283.java b/src/org/infinity/resource/effects/Opcode283.java index da612acff..7fb0500f4 100644 --- a/src/org/infinity/resource/effects/Opcode283.java +++ b/src/org/infinity/resource/effects/Opcode283.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 283. + * Implementation of opcode 283. */ public class Opcode283 extends BaseOpcode { private static final String EFFECT_DISPLAY_TYPE = "Display type"; @@ -51,12 +51,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,10 +64,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode284.java b/src/org/infinity/resource/effects/Opcode284.java index 16f03a25c..b5517a087 100644 --- a/src/org/infinity/resource/effects/Opcode284.java +++ b/src/org/infinity/resource/effects/Opcode284.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 284. + * Implementation of opcode 284. */ public class Opcode284 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode285.java b/src/org/infinity/resource/effects/Opcode285.java index 1880b63c9..84a79dda5 100644 --- a/src/org/infinity/resource/effects/Opcode285.java +++ b/src/org/infinity/resource/effects/Opcode285.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 285. + * Implementation of opcode 285. */ public class Opcode285 extends BaseOpcode { private static final String EFFECT_WAKE_ON_DAMAGE = "Wake on damage?"; @@ -46,12 +46,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -65,10 +59,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode286.java b/src/org/infinity/resource/effects/Opcode286.java index f088542ed..b280b8770 100644 --- a/src/org/infinity/resource/effects/Opcode286.java +++ b/src/org/infinity/resource/effects/Opcode286.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 286. + * Implementation of opcode 286. */ public class Opcode286 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +57,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode287.java b/src/org/infinity/resource/effects/Opcode287.java index 00ecf02dd..40592a54d 100644 --- a/src/org/infinity/resource/effects/Opcode287.java +++ b/src/org/infinity/resource/effects/Opcode287.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 287. + * Implementation of opcode 287. */ public class Opcode287 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -42,16 +42,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode288.java b/src/org/infinity/resource/effects/Opcode288.java index 4159d81c8..fb78ad9e9 100644 --- a/src/org/infinity/resource/effects/Opcode288.java +++ b/src/org/infinity/resource/effects/Opcode288.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 288. + * Implementation of opcode 288. */ public class Opcode288 extends BaseOpcode { private static final String EFFECT_STATE = "State"; @@ -47,12 +47,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -68,10 +62,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new IdsBitmap(buffer, offset + 4, 4, EFFECT_STATE, "SPLSTATE.IDS")); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode289.java b/src/org/infinity/resource/effects/Opcode289.java index a084d6c1e..20c1ad95a 100644 --- a/src/org/infinity/resource/effects/Opcode289.java +++ b/src/org/infinity/resource/effects/Opcode289.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 289. + * Implementation of opcode 289. */ public class Opcode289 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,12 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -57,16 +51,4 @@ protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int off list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode290.java b/src/org/infinity/resource/effects/Opcode290.java index 323248d5f..0157f1499 100644 --- a/src/org/infinity/resource/effects/Opcode290.java +++ b/src/org/infinity/resource/effects/Opcode290.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 290. + * Implementation of opcode 290. */ public class Opcode290 extends BaseOpcode { private static final String EFFECT_TITLE = "Title"; @@ -55,12 +55,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -77,12 +71,6 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of return RES_TYPE_IWD; } - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode291.java b/src/org/infinity/resource/effects/Opcode291.java index 422e8d745..dc353d0e5 100644 --- a/src/org/infinity/resource/effects/Opcode291.java +++ b/src/org/infinity/resource/effects/Opcode291.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 291. + * Implementation of opcode 291. */ public class Opcode291 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode292.java b/src/org/infinity/resource/effects/Opcode292.java index 4d3784396..86edd7e77 100644 --- a/src/org/infinity/resource/effects/Opcode292.java +++ b/src/org/infinity/resource/effects/Opcode292.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 292. + * Implementation of opcode 292. */ public class Opcode292 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode293.java b/src/org/infinity/resource/effects/Opcode293.java index 68070bd6a..8075abd9c 100644 --- a/src/org/infinity/resource/effects/Opcode293.java +++ b/src/org/infinity/resource/effects/Opcode293.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 293. + * Implementation of opcode 293. */ public class Opcode293 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode294.java b/src/org/infinity/resource/effects/Opcode294.java index 0ac518746..e69827d1f 100644 --- a/src/org/infinity/resource/effects/Opcode294.java +++ b/src/org/infinity/resource/effects/Opcode294.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 294. + * Implementation of opcode 294. */ public class Opcode294 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode295.java b/src/org/infinity/resource/effects/Opcode295.java index 2da9aec9c..8587818d2 100644 --- a/src/org/infinity/resource/effects/Opcode295.java +++ b/src/org/infinity/resource/effects/Opcode295.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 295. + * Implementation of opcode 295. */ public class Opcode295 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -43,12 +43,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -62,10 +56,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode296.java b/src/org/infinity/resource/effects/Opcode296.java index 99eaac68c..7ed74f917 100644 --- a/src/org/infinity/resource/effects/Opcode296.java +++ b/src/org/infinity/resource/effects/Opcode296.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 296. + * Implementation of opcode 296. */ public class Opcode296 extends BaseOpcode { private static final String EFFECT_VARIABLE = "Variable"; @@ -50,12 +50,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return RES_TYPE; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -69,10 +63,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of boolean isVersion1) { return makeEffectParamsIWD(parent, buffer, offset, list, isVersion1); } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode297.java b/src/org/infinity/resource/effects/Opcode297.java index df8fc9524..e9dbcbdc4 100644 --- a/src/org/infinity/resource/effects/Opcode297.java +++ b/src/org/infinity/resource/effects/Opcode297.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 297. + * Implementation of opcode 297. */ public class Opcode297 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -44,18 +44,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -63,10 +51,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode298.java b/src/org/infinity/resource/effects/Opcode298.java index 3cfa52778..daf5ca01b 100644 --- a/src/org/infinity/resource/effects/Opcode298.java +++ b/src/org/infinity/resource/effects/Opcode298.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 298. + * Implementation of opcode 298. */ public class Opcode298 extends BaseOpcode { private static final String EFFECT_STORE_LOCATION = "Store party location"; @@ -52,12 +52,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,12 +64,6 @@ protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int off } } - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -83,10 +71,4 @@ protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int of list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode299.java b/src/org/infinity/resource/effects/Opcode299.java index fb4ad92b7..bf622faa3 100644 --- a/src/org/infinity/resource/effects/Opcode299.java +++ b/src/org/infinity/resource/effects/Opcode299.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 299. + * Implementation of opcode 299. */ public class Opcode299 extends BaseOpcode { private static final String EFFECT_PORTRAIT = "Portrait"; @@ -45,28 +45,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_PORTRAIT, PORTRAITS)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode300.java b/src/org/infinity/resource/effects/Opcode300.java index 665a58061..139a0c57b 100644 --- a/src/org/infinity/resource/effects/Opcode300.java +++ b/src/org/infinity/resource/effects/Opcode300.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 300. + * Implementation of opcode 300. */ public class Opcode300 extends BaseOpcode { private static final String EFFECT_BEHAVIOR = "Behavior"; @@ -46,28 +46,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Flag(buffer, offset + 4, 4, EFFECT_BEHAVIOR, BEHAVIORS)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode301.java b/src/org/infinity/resource/effects/Opcode301.java index 90ced3345..332bdf9dc 100644 --- a/src/org/infinity/resource/effects/Opcode301.java +++ b/src/org/infinity/resource/effects/Opcode301.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 301. + * Implementation of opcode 301. */ public class Opcode301 extends BaseOpcode { private static final String EFFECT_CONDITION = "Condition"; @@ -49,30 +49,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, List list, String resType, int param1, int param2) { diff --git a/src/org/infinity/resource/effects/Opcode302.java b/src/org/infinity/resource/effects/Opcode302.java index 2b4dfdedb..7c5503fea 100644 --- a/src/org/infinity/resource/effects/Opcode302.java +++ b/src/org/infinity/resource/effects/Opcode302.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 302. + * Implementation of opcode 302. */ public class Opcode302 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_STAT_VALUE)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode303.java b/src/org/infinity/resource/effects/Opcode303.java index 63a697cc4..1515d81a3 100644 --- a/src/org/infinity/resource/effects/Opcode303.java +++ b/src/org/infinity/resource/effects/Opcode303.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 303. + * Implementation of opcode 303. */ public class Opcode303 extends BaseOpcode { private static final TreeMap TYPE_MAP_TOBEX = new TreeMap<>(); @@ -53,12 +53,6 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int return null; } - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - @Override protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int offset, List list, boolean isVersion1) { @@ -70,22 +64,4 @@ protected String makeEffectParamsBG2(Datatype parent, ByteBuffer buffer, int off return makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); } } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode304.java b/src/org/infinity/resource/effects/Opcode304.java index e54edab24..c82817c11 100644 --- a/src/org/infinity/resource/effects/Opcode304.java +++ b/src/org/infinity/resource/effects/Opcode304.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 304. + * Implementation of opcode 304. */ public class Opcode304 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode305.java b/src/org/infinity/resource/effects/Opcode305.java index 3fbc5ceda..3d6a9767d 100644 --- a/src/org/infinity/resource/effects/Opcode305.java +++ b/src/org/infinity/resource/effects/Opcode305.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 305. + * Implementation of opcode 305. */ public class Opcode305 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode306.java b/src/org/infinity/resource/effects/Opcode306.java index 210550006..18153ff5f 100644 --- a/src/org/infinity/resource/effects/Opcode306.java +++ b/src/org/infinity/resource/effects/Opcode306.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 306. + * Implementation of opcode 306. */ public class Opcode306 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode307.java b/src/org/infinity/resource/effects/Opcode307.java index 4cc1f187e..d8764363f 100644 --- a/src/org/infinity/resource/effects/Opcode307.java +++ b/src/org/infinity/resource/effects/Opcode307.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 307. + * Implementation of opcode 307. */ public class Opcode307 extends BaseOpcode { private static final String EFFECT_RANGE = "Range"; @@ -43,28 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode308.java b/src/org/infinity/resource/effects/Opcode308.java index aa8c501df..1a31cadfd 100644 --- a/src/org/infinity/resource/effects/Opcode308.java +++ b/src/org/infinity/resource/effects/Opcode308.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 308. + * Implementation of opcode 308. */ public class Opcode308 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_STAT_VALUE)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode309.java b/src/org/infinity/resource/effects/Opcode309.java index 6e890a7b9..0d24d6925 100644 --- a/src/org/infinity/resource/effects/Opcode309.java +++ b/src/org/infinity/resource/effects/Opcode309.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 309. + * Implementation of opcode 309. */ public class Opcode309 extends BaseOpcode { private static final String[] INC_TYPES_VARS = { "Set", "Increment" }; @@ -43,28 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_MODIFIER_TYPE, INC_TYPES_VARS)); return RES_TYPE_STRING; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode310.java b/src/org/infinity/resource/effects/Opcode310.java index 86356ac5b..b9bd59184 100644 --- a/src/org/infinity/resource/effects/Opcode310.java +++ b/src/org/infinity/resource/effects/Opcode310.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 310. + * Implementation of opcode 310. */ public class Opcode310 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_STAT_VALUE)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode311.java b/src/org/infinity/resource/effects/Opcode311.java index 28ac7d4fc..f7fd74e13 100644 --- a/src/org/infinity/resource/effects/Opcode311.java +++ b/src/org/infinity/resource/effects/Opcode311.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 311. + * Implementation of opcode 311. */ public class Opcode311 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode312.java b/src/org/infinity/resource/effects/Opcode312.java index 1c7916ba4..109f56db7 100644 --- a/src/org/infinity/resource/effects/Opcode312.java +++ b/src/org/infinity/resource/effects/Opcode312.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 312. + * Implementation of opcode 312. */ public class Opcode312 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_STAT_VALUE)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode313.java b/src/org/infinity/resource/effects/Opcode313.java index 7ed74de7e..d9ff72382 100644 --- a/src/org/infinity/resource/effects/Opcode313.java +++ b/src/org/infinity/resource/effects/Opcode313.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 313. + * Implementation of opcode 313. */ public class Opcode313 extends BaseOpcode { private static final String RES_TYPE = "SPL"; @@ -43,28 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return RES_TYPE; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode314.java b/src/org/infinity/resource/effects/Opcode314.java index 207267b7f..e368af67c 100644 --- a/src/org/infinity/resource/effects/Opcode314.java +++ b/src/org/infinity/resource/effects/Opcode314.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 314. + * Implementation of opcode 314. */ public class Opcode314 extends BaseOpcode { private static final String EFFECT_NUM_SKINS = "# skins"; @@ -43,28 +43,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode315.java b/src/org/infinity/resource/effects/Opcode315.java index 04581777c..7edebf204 100644 --- a/src/org/infinity/resource/effects/Opcode315.java +++ b/src/org/infinity/resource/effects/Opcode315.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 315. + * Implementation of opcode 315. */ public class Opcode315 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, EFFECT_STAT_VALUE)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode316.java b/src/org/infinity/resource/effects/Opcode316.java index 0a905dafb..68ddbd7b4 100644 --- a/src/org/infinity/resource/effects/Opcode316.java +++ b/src/org/infinity/resource/effects/Opcode316.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 316. + * Implementation of opcode 316. */ public class Opcode316 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ @@ -41,28 +41,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new DecNumber(buffer, offset + 4, 4, AbstractStruct.COMMON_UNUSED)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode317.java b/src/org/infinity/resource/effects/Opcode317.java index e44eb79c1..7807d4674 100644 --- a/src/org/infinity/resource/effects/Opcode317.java +++ b/src/org/infinity/resource/effects/Opcode317.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 317. + * Implementation of opcode 317. */ public class Opcode317 extends BaseOpcode { private static final String EFFECT_HASTE_TYPE = "Haste type"; @@ -46,28 +46,4 @@ protected String makeEffectParamsGeneric(Datatype parent, ByteBuffer buffer, int list.add(new Bitmap(buffer, offset + 4, 4, EFFECT_HASTE_TYPE, HASTE_TYPES)); return null; } - - @Override - protected String makeEffectParamsBG1(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsIWD2(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } - - @Override - protected String makeEffectParamsPST(Datatype parent, ByteBuffer buffer, int offset, List list, - boolean isVersion1) { - return super.makeEffectParamsGeneric(parent, buffer, offset, list, isVersion1); - } } diff --git a/src/org/infinity/resource/effects/Opcode318.java b/src/org/infinity/resource/effects/Opcode318.java index 0c3d4ddbc..965bfbec7 100644 --- a/src/org/infinity/resource/effects/Opcode318.java +++ b/src/org/infinity/resource/effects/Opcode318.java @@ -17,7 +17,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 318. + * Implementation of opcode 318. */ public class Opcode318 extends BaseOpcode { private static final String EFFECT_STAT_OPCODE = "Stat opcode"; diff --git a/src/org/infinity/resource/effects/Opcode319.java b/src/org/infinity/resource/effects/Opcode319.java index acf660863..d96b071f9 100644 --- a/src/org/infinity/resource/effects/Opcode319.java +++ b/src/org/infinity/resource/effects/Opcode319.java @@ -19,7 +19,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 319. + * Implementation of opcode 319. */ public class Opcode319 extends BaseOpcode { private static final String EFFECT_MODE_EEEX = "EEex: Mode"; diff --git a/src/org/infinity/resource/effects/Opcode320.java b/src/org/infinity/resource/effects/Opcode320.java index 24e5164d2..84113cfa0 100644 --- a/src/org/infinity/resource/effects/Opcode320.java +++ b/src/org/infinity/resource/effects/Opcode320.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 320. + * Implementation of opcode 320. */ public class Opcode320 extends BaseOpcode { private static final String[] WEATHER_TYPES = { "Normal", "Rain", "Snow", "Nothing" }; diff --git a/src/org/infinity/resource/effects/Opcode321.java b/src/org/infinity/resource/effects/Opcode321.java index 4d93a761b..eab8a86e8 100644 --- a/src/org/infinity/resource/effects/Opcode321.java +++ b/src/org/infinity/resource/effects/Opcode321.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 321. + * Implementation of opcode 321. */ public class Opcode321 extends BaseOpcode { private static final String RES_TYPE = "ITM:SPL"; diff --git a/src/org/infinity/resource/effects/Opcode322.java b/src/org/infinity/resource/effects/Opcode322.java index d77ed28b8..a202aa3f4 100644 --- a/src/org/infinity/resource/effects/Opcode322.java +++ b/src/org/infinity/resource/effects/Opcode322.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 322. + * Implementation of opcode 322. */ public class Opcode322 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode323.java b/src/org/infinity/resource/effects/Opcode323.java index 5b42587c8..50aeb9e6a 100644 --- a/src/org/infinity/resource/effects/Opcode323.java +++ b/src/org/infinity/resource/effects/Opcode323.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 323. + * Implementation of opcode 323. */ public class Opcode323 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode324.java b/src/org/infinity/resource/effects/Opcode324.java index 0378b91cf..f9f6c3243 100644 --- a/src/org/infinity/resource/effects/Opcode324.java +++ b/src/org/infinity/resource/effects/Opcode324.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 324. + * Implementation of opcode 324. */ public class Opcode324 extends BaseOpcode { private static final String EFFECT_OVERRIDE_STRREF = "EEex: Override strref"; diff --git a/src/org/infinity/resource/effects/Opcode325.java b/src/org/infinity/resource/effects/Opcode325.java index c30958c26..104d17e37 100644 --- a/src/org/infinity/resource/effects/Opcode325.java +++ b/src/org/infinity/resource/effects/Opcode325.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 325. + * Implementation of opcode 325. */ public class Opcode325 extends BaseOpcode { private static final String[] INC_TYPES_EE = { INC_TYPES[0], INC_TYPES[1], INC_TYPES[2], diff --git a/src/org/infinity/resource/effects/Opcode326.java b/src/org/infinity/resource/effects/Opcode326.java index b541de372..315b9ed47 100644 --- a/src/org/infinity/resource/effects/Opcode326.java +++ b/src/org/infinity/resource/effects/Opcode326.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 326. + * Implementation of opcode 326. */ public class Opcode326 extends BaseOpcode { private static final String RES_TYPE = "SPL"; diff --git a/src/org/infinity/resource/effects/Opcode327.java b/src/org/infinity/resource/effects/Opcode327.java index 3230ce122..1c30b1bca 100644 --- a/src/org/infinity/resource/effects/Opcode327.java +++ b/src/org/infinity/resource/effects/Opcode327.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 327. + * Implementation of opcode 327. */ public class Opcode327 extends BaseOpcode { private static final String EFFECT_TARGET = "Target"; diff --git a/src/org/infinity/resource/effects/Opcode328.java b/src/org/infinity/resource/effects/Opcode328.java index da158eda8..f0a90d2ed 100644 --- a/src/org/infinity/resource/effects/Opcode328.java +++ b/src/org/infinity/resource/effects/Opcode328.java @@ -19,7 +19,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 328. + * Implementation of opcode 328. */ public class Opcode328 extends BaseOpcode { private static final String EFFECT_STATE = "State"; @@ -80,7 +80,7 @@ protected int makeEffectSpecial(Datatype parent, ByteBuffer buffer, int offset, if (Profile.isEnhancedEdition()) { final Bitmap bmp = new Bitmap(buffer, offset, 4, EFFECT_MODE, MODES_EE); list.add(bmp); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { bmp.addUpdateListener((UpdateListener)parent); } return offset + 4; diff --git a/src/org/infinity/resource/effects/Opcode329.java b/src/org/infinity/resource/effects/Opcode329.java index 54aefbc46..c6f5c31f0 100644 --- a/src/org/infinity/resource/effects/Opcode329.java +++ b/src/org/infinity/resource/effects/Opcode329.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 329. + * Implementation of opcode 329. */ public class Opcode329 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode330.java b/src/org/infinity/resource/effects/Opcode330.java index c7e78c909..c8e14c330 100644 --- a/src/org/infinity/resource/effects/Opcode330.java +++ b/src/org/infinity/resource/effects/Opcode330.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 330. + * Implementation of opcode 330. */ public class Opcode330 extends BaseOpcode { private static final String EFFECT_DISPLAY_TYPE = "Display type"; diff --git a/src/org/infinity/resource/effects/Opcode331.java b/src/org/infinity/resource/effects/Opcode331.java index 048c81bdb..2c914513c 100644 --- a/src/org/infinity/resource/effects/Opcode331.java +++ b/src/org/infinity/resource/effects/Opcode331.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 331. + * Implementation of opcode 331. */ public class Opcode331 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; diff --git a/src/org/infinity/resource/effects/Opcode332.java b/src/org/infinity/resource/effects/Opcode332.java index 7bafb46cc..bf5ffaf29 100644 --- a/src/org/infinity/resource/effects/Opcode332.java +++ b/src/org/infinity/resource/effects/Opcode332.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 332. + * Implementation of opcode 332. */ public class Opcode332 extends BaseOpcode { private static final String EFFECT_DAMAGE_TYPE = "Damage type"; diff --git a/src/org/infinity/resource/effects/Opcode333.java b/src/org/infinity/resource/effects/Opcode333.java index 5b4663a01..1a355d978 100644 --- a/src/org/infinity/resource/effects/Opcode333.java +++ b/src/org/infinity/resource/effects/Opcode333.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 333. + * Implementation of opcode 333. */ public class Opcode333 extends BaseOpcode { private static final String EFFECT_NUM_HITS = "# hits"; diff --git a/src/org/infinity/resource/effects/Opcode334.java b/src/org/infinity/resource/effects/Opcode334.java index e2cf99c5e..f70ac9431 100644 --- a/src/org/infinity/resource/effects/Opcode334.java +++ b/src/org/infinity/resource/effects/Opcode334.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 334. + * Implementation of opcode 334. */ public class Opcode334 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode335.java b/src/org/infinity/resource/effects/Opcode335.java index 3b7168c66..e30175edd 100644 --- a/src/org/infinity/resource/effects/Opcode335.java +++ b/src/org/infinity/resource/effects/Opcode335.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 335. + * Implementation of opcode 335. */ public class Opcode335 extends BaseOpcode { private static final String EFFECT_STATE = "State"; diff --git a/src/org/infinity/resource/effects/Opcode336.java b/src/org/infinity/resource/effects/Opcode336.java index ef242ec7a..f9d2194ac 100644 --- a/src/org/infinity/resource/effects/Opcode336.java +++ b/src/org/infinity/resource/effects/Opcode336.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 336. + * Implementation of opcode 336. */ public class Opcode336 extends BaseOpcode { private static final String EFFECT_LAST_LETTER = "Last VVC letter"; diff --git a/src/org/infinity/resource/effects/Opcode337.java b/src/org/infinity/resource/effects/Opcode337.java index 78a5016a1..26ee4fa07 100644 --- a/src/org/infinity/resource/effects/Opcode337.java +++ b/src/org/infinity/resource/effects/Opcode337.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 337. + * Implementation of opcode 337. */ public class Opcode337 extends BaseOpcode { private static final String EFFECT_MATCH_P2_VALUE = "Match 'Parameter 2' value"; diff --git a/src/org/infinity/resource/effects/Opcode338.java b/src/org/infinity/resource/effects/Opcode338.java index 3feea0eff..6de0d5929 100644 --- a/src/org/infinity/resource/effects/Opcode338.java +++ b/src/org/infinity/resource/effects/Opcode338.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 338. + * Implementation of opcode 338. */ public class Opcode338 extends BaseOpcode { private static final String EFFECT_MESSAGE = "Message"; diff --git a/src/org/infinity/resource/effects/Opcode339.java b/src/org/infinity/resource/effects/Opcode339.java index 8bf57d153..bd7336725 100644 --- a/src/org/infinity/resource/effects/Opcode339.java +++ b/src/org/infinity/resource/effects/Opcode339.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 339. + * Implementation of opcode 339. */ public class Opcode339 extends BaseOpcode { private static final String EFFECT_PROJECTILE = "Projectile"; diff --git a/src/org/infinity/resource/effects/Opcode340.java b/src/org/infinity/resource/effects/Opcode340.java index 2a5b1b6af..bb41c2c10 100644 --- a/src/org/infinity/resource/effects/Opcode340.java +++ b/src/org/infinity/resource/effects/Opcode340.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 340. + * Implementation of opcode 340. */ public class Opcode340 extends BaseOpcode { private static final String RES_TYPE = "SPL"; diff --git a/src/org/infinity/resource/effects/Opcode341.java b/src/org/infinity/resource/effects/Opcode341.java index 53df681f4..e9570a00b 100644 --- a/src/org/infinity/resource/effects/Opcode341.java +++ b/src/org/infinity/resource/effects/Opcode341.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 341. + * Implementation of opcode 341. */ public class Opcode341 extends BaseOpcode { private static final String EFFECT_CONDITION = "Condition"; diff --git a/src/org/infinity/resource/effects/Opcode342.java b/src/org/infinity/resource/effects/Opcode342.java index aa026abe2..ea110ff18 100644 --- a/src/org/infinity/resource/effects/Opcode342.java +++ b/src/org/infinity/resource/effects/Opcode342.java @@ -18,7 +18,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 342. + * Implementation of opcode 342. */ public class Opcode342 extends BaseOpcode { private static final String EFFECT_FIELD = "Field"; @@ -55,7 +55,7 @@ protected String makeEffectParamsEE(Datatype parent, ByteBuffer buffer, int offs list.add(new DecNumber(buffer, offset, 4, EFFECT_VALUE)); } list.add(bmp); - if (parent != null && parent instanceof UpdateListener) { + if (parent instanceof UpdateListener) { bmp.addUpdateListener((UpdateListener)parent); } return null; diff --git a/src/org/infinity/resource/effects/Opcode343.java b/src/org/infinity/resource/effects/Opcode343.java index e1d19a76e..9dbd7809b 100644 --- a/src/org/infinity/resource/effects/Opcode343.java +++ b/src/org/infinity/resource/effects/Opcode343.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 343. + * Implementation of opcode 343. */ public class Opcode343 extends BaseOpcode { private static final String[] MODES = { "Swap if caster HP > target HP", "Always swap" }; diff --git a/src/org/infinity/resource/effects/Opcode344.java b/src/org/infinity/resource/effects/Opcode344.java index 3177b878b..739b53274 100644 --- a/src/org/infinity/resource/effects/Opcode344.java +++ b/src/org/infinity/resource/effects/Opcode344.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 344. + * Implementation of opcode 344. */ public class Opcode344 extends BaseOpcode { private static final String EFFECT_ENCHANTMENT = "Enchantment"; diff --git a/src/org/infinity/resource/effects/Opcode345.java b/src/org/infinity/resource/effects/Opcode345.java index e76809bd8..e447f7641 100644 --- a/src/org/infinity/resource/effects/Opcode345.java +++ b/src/org/infinity/resource/effects/Opcode345.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 345. + * Implementation of opcode 345. */ public class Opcode345 extends BaseOpcode { private static final String EFFECT_ENCHANTMENT = "Enchantment"; diff --git a/src/org/infinity/resource/effects/Opcode346.java b/src/org/infinity/resource/effects/Opcode346.java index 60169318b..21480ec46 100644 --- a/src/org/infinity/resource/effects/Opcode346.java +++ b/src/org/infinity/resource/effects/Opcode346.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 346. + * Implementation of opcode 346. */ public class Opcode346 extends BaseOpcode { private static final String EFFECT_SCHOOL_OF_MAGIC = "School of magic"; diff --git a/src/org/infinity/resource/effects/Opcode347.java b/src/org/infinity/resource/effects/Opcode347.java index c4a930713..3536f915b 100644 --- a/src/org/infinity/resource/effects/Opcode347.java +++ b/src/org/infinity/resource/effects/Opcode347.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 347. + * Implementation of opcode 347. */ public class Opcode347 extends BaseOpcode { private static final String EFFECT_SCROLL_SPEED = "Scroll speed"; diff --git a/src/org/infinity/resource/effects/Opcode348.java b/src/org/infinity/resource/effects/Opcode348.java index 967303aea..e62fccfac 100644 --- a/src/org/infinity/resource/effects/Opcode348.java +++ b/src/org/infinity/resource/effects/Opcode348.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 348. + * Implementation of opcode 348. */ public class Opcode348 extends BaseOpcode { private static final String EFFECT_BASE_AMOUNT = "Base amount"; diff --git a/src/org/infinity/resource/effects/Opcode349.java b/src/org/infinity/resource/effects/Opcode349.java index 5c7a764aa..6e13f1ed6 100644 --- a/src/org/infinity/resource/effects/Opcode349.java +++ b/src/org/infinity/resource/effects/Opcode349.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 349. + * Implementation of opcode 349. */ public class Opcode349 extends BaseOpcode { private static final String EFFECT_DAMAGE_EFFECTS_TO_REFLECT = "# damage effects to reflect"; diff --git a/src/org/infinity/resource/effects/Opcode350.java b/src/org/infinity/resource/effects/Opcode350.java index 7fffa09f8..0351c2316 100644 --- a/src/org/infinity/resource/effects/Opcode350.java +++ b/src/org/infinity/resource/effects/Opcode350.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 350. + * Implementation of opcode 350. */ public class Opcode350 extends BaseOpcode { private static final String EFFECT_ENABLED = "Enabled?"; diff --git a/src/org/infinity/resource/effects/Opcode351.java b/src/org/infinity/resource/effects/Opcode351.java index a506345bb..acf065dc1 100644 --- a/src/org/infinity/resource/effects/Opcode351.java +++ b/src/org/infinity/resource/effects/Opcode351.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 351. + * Implementation of opcode 351. */ public class Opcode351 extends BaseOpcode { private static final String EFFECT_AMOUNT = "Amount"; diff --git a/src/org/infinity/resource/effects/Opcode352.java b/src/org/infinity/resource/effects/Opcode352.java index c7c2bcec5..e06a349a3 100644 --- a/src/org/infinity/resource/effects/Opcode352.java +++ b/src/org/infinity/resource/effects/Opcode352.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 352. + * Implementation of opcode 352. */ public class Opcode352 extends BaseOpcode { private static final String RES_TYPE = "BMP"; diff --git a/src/org/infinity/resource/effects/Opcode353.java b/src/org/infinity/resource/effects/Opcode353.java index 19b41bb06..51bfc8dbd 100644 --- a/src/org/infinity/resource/effects/Opcode353.java +++ b/src/org/infinity/resource/effects/Opcode353.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 353. + * Implementation of opcode 353. */ public class Opcode353 extends BaseOpcode { private static final String EFFECT_METHOD = "Method"; diff --git a/src/org/infinity/resource/effects/Opcode354.java b/src/org/infinity/resource/effects/Opcode354.java index 2757e3a44..5f748a756 100644 --- a/src/org/infinity/resource/effects/Opcode354.java +++ b/src/org/infinity/resource/effects/Opcode354.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 354. + * Implementation of opcode 354. */ public class Opcode354 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode355.java b/src/org/infinity/resource/effects/Opcode355.java index 3b2993ca0..b5560acc2 100644 --- a/src/org/infinity/resource/effects/Opcode355.java +++ b/src/org/infinity/resource/effects/Opcode355.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 355. + * Implementation of opcode 355. */ public class Opcode355 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode356.java b/src/org/infinity/resource/effects/Opcode356.java index 15bb49fdf..b4a9bfd2e 100644 --- a/src/org/infinity/resource/effects/Opcode356.java +++ b/src/org/infinity/resource/effects/Opcode356.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 356. + * Implementation of opcode 356. */ public class Opcode356 extends BaseOpcode { private static final String[] MODES = { "Pause actions", "Unpause actions" }; diff --git a/src/org/infinity/resource/effects/Opcode357.java b/src/org/infinity/resource/effects/Opcode357.java index f41dcaeba..15e187741 100644 --- a/src/org/infinity/resource/effects/Opcode357.java +++ b/src/org/infinity/resource/effects/Opcode357.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 357. + * Implementation of opcode 357. */ public class Opcode357 extends BaseOpcode { private static final String EFFECT_ACTION = "Action"; diff --git a/src/org/infinity/resource/effects/Opcode358.java b/src/org/infinity/resource/effects/Opcode358.java index c74ed5b2f..94d6c9710 100644 --- a/src/org/infinity/resource/effects/Opcode358.java +++ b/src/org/infinity/resource/effects/Opcode358.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 358. + * Implementation of opcode 358. */ public class Opcode358 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode360.java b/src/org/infinity/resource/effects/Opcode360.java index c79d4ecf6..16016a520 100644 --- a/src/org/infinity/resource/effects/Opcode360.java +++ b/src/org/infinity/resource/effects/Opcode360.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 360. + * Implementation of opcode 360. */ public class Opcode360 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode361.java b/src/org/infinity/resource/effects/Opcode361.java index 6ce6de11b..d84fdc482 100644 --- a/src/org/infinity/resource/effects/Opcode361.java +++ b/src/org/infinity/resource/effects/Opcode361.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 361. + * Implementation of opcode 361. */ public class Opcode361 extends BaseOpcode { private static final String EFFECT_CURRENT_WEAPON = "Current weapon only?"; diff --git a/src/org/infinity/resource/effects/Opcode362.java b/src/org/infinity/resource/effects/Opcode362.java index 5befba577..c0bcf436b 100644 --- a/src/org/infinity/resource/effects/Opcode362.java +++ b/src/org/infinity/resource/effects/Opcode362.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 362. + * Implementation of opcode 362. */ public class Opcode362 extends BaseOpcode { private static final String EFFECT_CURRENT_WEAPON = "Current weapon only?"; diff --git a/src/org/infinity/resource/effects/Opcode363.java b/src/org/infinity/resource/effects/Opcode363.java index f628f9123..b376dbcce 100644 --- a/src/org/infinity/resource/effects/Opcode363.java +++ b/src/org/infinity/resource/effects/Opcode363.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 363. + * Implementation of opcode 363. */ public class Opcode363 extends BaseOpcode { private static final String EFFECT_MODAL_TO_CHECK = "Modal state to check"; diff --git a/src/org/infinity/resource/effects/Opcode365.java b/src/org/infinity/resource/effects/Opcode365.java index 36fca3485..27af114dd 100644 --- a/src/org/infinity/resource/effects/Opcode365.java +++ b/src/org/infinity/resource/effects/Opcode365.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 365. + * Implementation of opcode 365. */ public class Opcode365 extends BaseOpcode { private static final String EFFECT_DISABLE_DIALOG = "Disable dialogue?"; diff --git a/src/org/infinity/resource/effects/Opcode366.java b/src/org/infinity/resource/effects/Opcode366.java index 773e2ffee..37a0dfd66 100644 --- a/src/org/infinity/resource/effects/Opcode366.java +++ b/src/org/infinity/resource/effects/Opcode366.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 366. + * Implementation of opcode 366. */ public class Opcode366 extends BaseOpcode { private static final String EFFECT_MODAL_TO_CHECK = "Modal state to check"; diff --git a/src/org/infinity/resource/effects/Opcode367.java b/src/org/infinity/resource/effects/Opcode367.java index 59791afd0..8927aa783 100644 --- a/src/org/infinity/resource/effects/Opcode367.java +++ b/src/org/infinity/resource/effects/Opcode367.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 367. + * Implementation of opcode 367. */ public class Opcode367 extends BaseOpcode { private static final String EFFECT_ENABLED = "Enabled?"; diff --git a/src/org/infinity/resource/effects/Opcode368.java b/src/org/infinity/resource/effects/Opcode368.java index 81b9ccff8..669980c18 100644 --- a/src/org/infinity/resource/effects/Opcode368.java +++ b/src/org/infinity/resource/effects/Opcode368.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 368. + * Implementation of opcode 368. */ public class Opcode368 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode369.java b/src/org/infinity/resource/effects/Opcode369.java index 6afa35f14..f4e703cf8 100644 --- a/src/org/infinity/resource/effects/Opcode369.java +++ b/src/org/infinity/resource/effects/Opcode369.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 369. + * Implementation of opcode 369. */ public class Opcode369 extends BaseOpcode { private static final String EFFECT_METHOD = "Method"; diff --git a/src/org/infinity/resource/effects/Opcode370.java b/src/org/infinity/resource/effects/Opcode370.java index 08f99830b..851900751 100644 --- a/src/org/infinity/resource/effects/Opcode370.java +++ b/src/org/infinity/resource/effects/Opcode370.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 370. + * Implementation of opcode 370. */ public class Opcode370 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode371.java b/src/org/infinity/resource/effects/Opcode371.java index f599eef32..c75db7645 100644 --- a/src/org/infinity/resource/effects/Opcode371.java +++ b/src/org/infinity/resource/effects/Opcode371.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 371. + * Implementation of opcode 371. */ public class Opcode371 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode372.java b/src/org/infinity/resource/effects/Opcode372.java index 14f94f57c..e79afc8f7 100644 --- a/src/org/infinity/resource/effects/Opcode372.java +++ b/src/org/infinity/resource/effects/Opcode372.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 372. + * Implementation of opcode 372. */ public class Opcode372 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode373.java b/src/org/infinity/resource/effects/Opcode373.java index ad6c78e60..63f12d5d0 100644 --- a/src/org/infinity/resource/effects/Opcode373.java +++ b/src/org/infinity/resource/effects/Opcode373.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 373. + * Implementation of opcode 373. */ public class Opcode373 extends BaseOpcode { private static final String EFFECT_FLAGS = "Flags"; diff --git a/src/org/infinity/resource/effects/Opcode374.java b/src/org/infinity/resource/effects/Opcode374.java index f8f75edad..6851abfd5 100644 --- a/src/org/infinity/resource/effects/Opcode374.java +++ b/src/org/infinity/resource/effects/Opcode374.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 374. + * Implementation of opcode 374. */ public class Opcode374 extends BaseOpcode { private static final String EFFECT_FX = "Effect"; diff --git a/src/org/infinity/resource/effects/Opcode375.java b/src/org/infinity/resource/effects/Opcode375.java index 2b9833337..11d265748 100644 --- a/src/org/infinity/resource/effects/Opcode375.java +++ b/src/org/infinity/resource/effects/Opcode375.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 375. + * Implementation of opcode 375. */ public class Opcode375 extends BaseOpcode { private static final String EFFECT_FX = "Effect"; diff --git a/src/org/infinity/resource/effects/Opcode376.java b/src/org/infinity/resource/effects/Opcode376.java index 3d6829d70..5d041cc2e 100644 --- a/src/org/infinity/resource/effects/Opcode376.java +++ b/src/org/infinity/resource/effects/Opcode376.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 376. + * Implementation of opcode 376. */ public class Opcode376 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode377.java b/src/org/infinity/resource/effects/Opcode377.java index 9ca8f7cec..a3aeb5339 100644 --- a/src/org/infinity/resource/effects/Opcode377.java +++ b/src/org/infinity/resource/effects/Opcode377.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 377. + * Implementation of opcode 377. */ public class Opcode377 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode378.java b/src/org/infinity/resource/effects/Opcode378.java index ae8e656ad..052ce12f7 100644 --- a/src/org/infinity/resource/effects/Opcode378.java +++ b/src/org/infinity/resource/effects/Opcode378.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 378. + * Implementation of opcode 378. */ public class Opcode378 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode379.java b/src/org/infinity/resource/effects/Opcode379.java index 780b6d948..f1f8036fb 100644 --- a/src/org/infinity/resource/effects/Opcode379.java +++ b/src/org/infinity/resource/effects/Opcode379.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 379. + * Implementation of opcode 379. */ public class Opcode379 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode380.java b/src/org/infinity/resource/effects/Opcode380.java index 45f9e7446..d1bc1c06b 100644 --- a/src/org/infinity/resource/effects/Opcode380.java +++ b/src/org/infinity/resource/effects/Opcode380.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 380. + * Implementation of opcode 380. */ public class Opcode380 extends BaseOpcode { private static final String EFFECT_EMBALMING_TYPE = "Embalming type"; diff --git a/src/org/infinity/resource/effects/Opcode381.java b/src/org/infinity/resource/effects/Opcode381.java index 49d9b998c..2d2770916 100644 --- a/src/org/infinity/resource/effects/Opcode381.java +++ b/src/org/infinity/resource/effects/Opcode381.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 381. + * Implementation of opcode 381. */ public class Opcode381 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode382.java b/src/org/infinity/resource/effects/Opcode382.java index d3e7ba314..5120a930e 100644 --- a/src/org/infinity/resource/effects/Opcode382.java +++ b/src/org/infinity/resource/effects/Opcode382.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 382. + * Implementation of opcode 382. */ public class Opcode382 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode383.java b/src/org/infinity/resource/effects/Opcode383.java index 26b106240..98c72b59f 100644 --- a/src/org/infinity/resource/effects/Opcode383.java +++ b/src/org/infinity/resource/effects/Opcode383.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 383. + * Implementation of opcode 383. */ public class Opcode383 extends BaseOpcode { private static final String EFFECT_DIRECTION = "Direction"; diff --git a/src/org/infinity/resource/effects/Opcode400.java b/src/org/infinity/resource/effects/Opcode400.java index 5cde9a22d..abdd931f3 100644 --- a/src/org/infinity/resource/effects/Opcode400.java +++ b/src/org/infinity/resource/effects/Opcode400.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 400. + * Implementation of opcode 400. */ public class Opcode400 extends BaseOpcode { private static final String EFFECT_SCRIPT_LEVEL = "Script level"; diff --git a/src/org/infinity/resource/effects/Opcode401.java b/src/org/infinity/resource/effects/Opcode401.java index 0c019297a..cd71e3442 100644 --- a/src/org/infinity/resource/effects/Opcode401.java +++ b/src/org/infinity/resource/effects/Opcode401.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 401. + * Implementation of opcode 401. */ public class Opcode401 extends BaseOpcode { private static final String EFFECT_STAT = "Stat"; diff --git a/src/org/infinity/resource/effects/Opcode402.java b/src/org/infinity/resource/effects/Opcode402.java index f4a35a2d9..00976ee13 100644 --- a/src/org/infinity/resource/effects/Opcode402.java +++ b/src/org/infinity/resource/effects/Opcode402.java @@ -16,7 +16,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 402. + * Implementation of opcode 402. */ public class Opcode402 extends BaseOpcode { private static final String EFFECT_LUA_FUNCTION = "Lua function"; diff --git a/src/org/infinity/resource/effects/Opcode403.java b/src/org/infinity/resource/effects/Opcode403.java index 7d340f3a7..65a419f2a 100644 --- a/src/org/infinity/resource/effects/Opcode403.java +++ b/src/org/infinity/resource/effects/Opcode403.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 403. + * Implementation of opcode 403. */ public class Opcode403 extends BaseOpcode { private static final String EFFECT_LUA_FUNCTION = "Lua function"; diff --git a/src/org/infinity/resource/effects/Opcode404.java b/src/org/infinity/resource/effects/Opcode404.java index 600507acf..255c4e51c 100644 --- a/src/org/infinity/resource/effects/Opcode404.java +++ b/src/org/infinity/resource/effects/Opcode404.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 404. + * Implementation of opcode 404. */ public class Opcode404 extends BaseOpcode { private static final String EFFECT_TYPE_TO_OVERRIDE = "Type to override"; diff --git a/src/org/infinity/resource/effects/Opcode405.java b/src/org/infinity/resource/effects/Opcode405.java index fb3c4326f..525ff46d3 100644 --- a/src/org/infinity/resource/effects/Opcode405.java +++ b/src/org/infinity/resource/effects/Opcode405.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 405. + * Implementation of opcode 405. */ public class Opcode405 extends BaseOpcode { private static final String EFFECT_INDEX_TO_OVERRIDE = "Index to override"; diff --git a/src/org/infinity/resource/effects/Opcode406.java b/src/org/infinity/resource/effects/Opcode406.java index fc6ed98de..5affc500b 100644 --- a/src/org/infinity/resource/effects/Opcode406.java +++ b/src/org/infinity/resource/effects/Opcode406.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 406. + * Implementation of opcode 406. */ public class Opcode406 extends BaseOpcode { private static final String EFFECT_SHIELD_TYPE = "Shield type"; diff --git a/src/org/infinity/resource/effects/Opcode407.java b/src/org/infinity/resource/effects/Opcode407.java index 9a607f18a..4661b9f58 100644 --- a/src/org/infinity/resource/effects/Opcode407.java +++ b/src/org/infinity/resource/effects/Opcode407.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 407. + * Implementation of opcode 407. */ public class Opcode407 extends BaseOpcode { private static final String EFFECT_ON_REMOVE = "EEex: On remove"; diff --git a/src/org/infinity/resource/effects/Opcode408.java b/src/org/infinity/resource/effects/Opcode408.java index 0e7d13107..9e6d191f4 100644 --- a/src/org/infinity/resource/effects/Opcode408.java +++ b/src/org/infinity/resource/effects/Opcode408.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 408. + * Implementation of opcode 408. */ public class Opcode408 extends BaseOpcode { private static final String EFFECT_LUA_TABLE = "Lua table"; diff --git a/src/org/infinity/resource/effects/Opcode409.java b/src/org/infinity/resource/effects/Opcode409.java index a740f7d99..092608fed 100644 --- a/src/org/infinity/resource/effects/Opcode409.java +++ b/src/org/infinity/resource/effects/Opcode409.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 409. + * Implementation of opcode 409. */ public class Opcode409 extends BaseOpcode { private static final String EFFECT_AFFECT = "Affect"; diff --git a/src/org/infinity/resource/effects/Opcode410.java b/src/org/infinity/resource/effects/Opcode410.java index 0dbd5412e..488ec4f4b 100644 --- a/src/org/infinity/resource/effects/Opcode410.java +++ b/src/org/infinity/resource/effects/Opcode410.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 410. + * Implementation of opcode 410. */ public class Opcode410 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; diff --git a/src/org/infinity/resource/effects/Opcode411.java b/src/org/infinity/resource/effects/Opcode411.java index 402b1a33c..9204d6ad4 100644 --- a/src/org/infinity/resource/effects/Opcode411.java +++ b/src/org/infinity/resource/effects/Opcode411.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 411. + * Implementation of opcode 411. */ public class Opcode411 extends BaseOpcode { private static final String EFFECT_NUM_CREATURES = "# creatures"; diff --git a/src/org/infinity/resource/effects/Opcode412.java b/src/org/infinity/resource/effects/Opcode412.java index 6c9c8317e..9009e43b9 100644 --- a/src/org/infinity/resource/effects/Opcode412.java +++ b/src/org/infinity/resource/effects/Opcode412.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 412. + * Implementation of opcode 412. */ public class Opcode412 extends BaseOpcode { private static final String EFFECT_CONTROL_TYPE = "Control type"; diff --git a/src/org/infinity/resource/effects/Opcode413.java b/src/org/infinity/resource/effects/Opcode413.java index dcab18ad6..2357a1cf8 100644 --- a/src/org/infinity/resource/effects/Opcode413.java +++ b/src/org/infinity/resource/effects/Opcode413.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 413. + * Implementation of opcode 413. */ public class Opcode413 extends BaseOpcode { private static final String EFFECT_ANIMATION = "Animation"; diff --git a/src/org/infinity/resource/effects/Opcode414.java b/src/org/infinity/resource/effects/Opcode414.java index 2a6885288..e3ed74767 100644 --- a/src/org/infinity/resource/effects/Opcode414.java +++ b/src/org/infinity/resource/effects/Opcode414.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 414. + * Implementation of opcode 414. */ public class Opcode414 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode415.java b/src/org/infinity/resource/effects/Opcode415.java index 6404adff8..3de48d031 100644 --- a/src/org/infinity/resource/effects/Opcode415.java +++ b/src/org/infinity/resource/effects/Opcode415.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 415. + * Implementation of opcode 415. */ public class Opcode415 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode416.java b/src/org/infinity/resource/effects/Opcode416.java index b800ea627..e495aa004 100644 --- a/src/org/infinity/resource/effects/Opcode416.java +++ b/src/org/infinity/resource/effects/Opcode416.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 416. + * Implementation of opcode 416. */ public class Opcode416 extends BaseOpcode { private static final String EFFECT_DAMAGE_TYPE = "Damage type"; diff --git a/src/org/infinity/resource/effects/Opcode417.java b/src/org/infinity/resource/effects/Opcode417.java index a748311ab..fc65ebf49 100644 --- a/src/org/infinity/resource/effects/Opcode417.java +++ b/src/org/infinity/resource/effects/Opcode417.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 417. + * Implementation of opcode 417. */ public class Opcode417 extends BaseOpcode { private static final String EFFECT_RADIUS = "Radius"; diff --git a/src/org/infinity/resource/effects/Opcode418.java b/src/org/infinity/resource/effects/Opcode418.java index 423f5161e..c0008846c 100644 --- a/src/org/infinity/resource/effects/Opcode418.java +++ b/src/org/infinity/resource/effects/Opcode418.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 418. + * Implementation of opcode 418. */ public class Opcode418 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode419.java b/src/org/infinity/resource/effects/Opcode419.java index 3f888339e..a73f1a703 100644 --- a/src/org/infinity/resource/effects/Opcode419.java +++ b/src/org/infinity/resource/effects/Opcode419.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 419. + * Implementation of opcode 419. */ public class Opcode419 extends BaseOpcode { private static final String EFFECT_WAKE_ON_DAMAGE = "Wake on damage?"; diff --git a/src/org/infinity/resource/effects/Opcode420.java b/src/org/infinity/resource/effects/Opcode420.java index 3de2fde5c..b90171a1c 100644 --- a/src/org/infinity/resource/effects/Opcode420.java +++ b/src/org/infinity/resource/effects/Opcode420.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 420. + * Implementation of opcode 420. */ public class Opcode420 extends BaseOpcode { private static final String EFFECT_DEATH_TYPE = "Death type"; diff --git a/src/org/infinity/resource/effects/Opcode421.java b/src/org/infinity/resource/effects/Opcode421.java index 3465b18bf..45b38f00d 100644 --- a/src/org/infinity/resource/effects/Opcode421.java +++ b/src/org/infinity/resource/effects/Opcode421.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 421. + * Implementation of opcode 421. */ public class Opcode421 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode422.java b/src/org/infinity/resource/effects/Opcode422.java index 824dd5ea4..6015c6314 100644 --- a/src/org/infinity/resource/effects/Opcode422.java +++ b/src/org/infinity/resource/effects/Opcode422.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 422. + * Implementation of opcode 422. */ public class Opcode422 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode423.java b/src/org/infinity/resource/effects/Opcode423.java index dbb857794..f8e0bad97 100644 --- a/src/org/infinity/resource/effects/Opcode423.java +++ b/src/org/infinity/resource/effects/Opcode423.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 423. + * Implementation of opcode 423. */ public class Opcode423 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode424.java b/src/org/infinity/resource/effects/Opcode424.java index 1b51595d2..ae79f188e 100644 --- a/src/org/infinity/resource/effects/Opcode424.java +++ b/src/org/infinity/resource/effects/Opcode424.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 424. + * Implementation of opcode 424. */ public class Opcode424 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode425.java b/src/org/infinity/resource/effects/Opcode425.java index 504574024..5a9f37488 100644 --- a/src/org/infinity/resource/effects/Opcode425.java +++ b/src/org/infinity/resource/effects/Opcode425.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 425. + * Implementation of opcode 425. */ public class Opcode425 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode426.java b/src/org/infinity/resource/effects/Opcode426.java index 420c1c43c..846b1700c 100644 --- a/src/org/infinity/resource/effects/Opcode426.java +++ b/src/org/infinity/resource/effects/Opcode426.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 426. + * Implementation of opcode 426. */ public class Opcode426 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode427.java b/src/org/infinity/resource/effects/Opcode427.java index 855e40b32..2de5a76ec 100644 --- a/src/org/infinity/resource/effects/Opcode427.java +++ b/src/org/infinity/resource/effects/Opcode427.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 427. + * Implementation of opcode 427. */ public class Opcode427 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode428.java b/src/org/infinity/resource/effects/Opcode428.java index e75622560..c09d9dd1e 100644 --- a/src/org/infinity/resource/effects/Opcode428.java +++ b/src/org/infinity/resource/effects/Opcode428.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 428. + * Implementation of opcode 428. */ public class Opcode428 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode429.java b/src/org/infinity/resource/effects/Opcode429.java index 38c5b82d2..b1180b17d 100644 --- a/src/org/infinity/resource/effects/Opcode429.java +++ b/src/org/infinity/resource/effects/Opcode429.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 429. + * Implementation of opcode 429. */ public class Opcode429 extends BaseOpcode { private static final String RES_TYPE_IWD2 = "SPL"; diff --git a/src/org/infinity/resource/effects/Opcode430.java b/src/org/infinity/resource/effects/Opcode430.java index 09fc70395..7dedc7252 100644 --- a/src/org/infinity/resource/effects/Opcode430.java +++ b/src/org/infinity/resource/effects/Opcode430.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 430. + * Implementation of opcode 430. */ public class Opcode430 extends BaseOpcode { private static final String EFFECT_PROJECTILE = "Projectile"; diff --git a/src/org/infinity/resource/effects/Opcode431.java b/src/org/infinity/resource/effects/Opcode431.java index ce967cc6f..0b44eebd9 100644 --- a/src/org/infinity/resource/effects/Opcode431.java +++ b/src/org/infinity/resource/effects/Opcode431.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 431. + * Implementation of opcode 431. */ public class Opcode431 extends BaseOpcode { private static final String EFFECT_NUM_LEVELS = "# levels"; diff --git a/src/org/infinity/resource/effects/Opcode432.java b/src/org/infinity/resource/effects/Opcode432.java index 4c19b852c..1fb057511 100644 --- a/src/org/infinity/resource/effects/Opcode432.java +++ b/src/org/infinity/resource/effects/Opcode432.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 432. + * Implementation of opcode 432. */ public class Opcode432 extends BaseOpcode { private static final String EFFECT_HP_AMOUNT = "HP amount"; diff --git a/src/org/infinity/resource/effects/Opcode433.java b/src/org/infinity/resource/effects/Opcode433.java index 7e5d1aa98..7144bd8b6 100644 --- a/src/org/infinity/resource/effects/Opcode433.java +++ b/src/org/infinity/resource/effects/Opcode433.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 433. + * Implementation of opcode 433. */ public class Opcode433 extends BaseOpcode { private static final String EFFECT_BLINK_TYPE = "Blink type"; diff --git a/src/org/infinity/resource/effects/Opcode434.java b/src/org/infinity/resource/effects/Opcode434.java index fcc710236..42911e1d7 100644 --- a/src/org/infinity/resource/effects/Opcode434.java +++ b/src/org/infinity/resource/effects/Opcode434.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 434. + * Implementation of opcode 434. */ public class Opcode434 extends BaseOpcode { private static final String EFFECT_INTERVAL = "Interval"; diff --git a/src/org/infinity/resource/effects/Opcode435.java b/src/org/infinity/resource/effects/Opcode435.java index 982344459..483415daf 100644 --- a/src/org/infinity/resource/effects/Opcode435.java +++ b/src/org/infinity/resource/effects/Opcode435.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 435. + * Implementation of opcode 435. */ public class Opcode435 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode436.java b/src/org/infinity/resource/effects/Opcode436.java index 6ceab4f4f..7929beebb 100644 --- a/src/org/infinity/resource/effects/Opcode436.java +++ b/src/org/infinity/resource/effects/Opcode436.java @@ -13,7 +13,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 436. + * Implementation of opcode 436. */ public class Opcode436 extends BaseOpcode { private static final String EFFECT_ENCHANTMENT_TO_OVERCOME = "Enchantment to overcome"; diff --git a/src/org/infinity/resource/effects/Opcode437.java b/src/org/infinity/resource/effects/Opcode437.java index 461e25475..cbdf42554 100644 --- a/src/org/infinity/resource/effects/Opcode437.java +++ b/src/org/infinity/resource/effects/Opcode437.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 437. + * Implementation of opcode 437. */ public class Opcode437 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode438.java b/src/org/infinity/resource/effects/Opcode438.java index bd650f9f0..7fccdc00f 100644 --- a/src/org/infinity/resource/effects/Opcode438.java +++ b/src/org/infinity/resource/effects/Opcode438.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 438. + * Implementation of opcode 438. */ public class Opcode438 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode439.java b/src/org/infinity/resource/effects/Opcode439.java index 5fa5e9584..5482a54c8 100644 --- a/src/org/infinity/resource/effects/Opcode439.java +++ b/src/org/infinity/resource/effects/Opcode439.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 439. + * Implementation of opcode 439. */ public class Opcode439 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode440.java b/src/org/infinity/resource/effects/Opcode440.java index 38d8735f5..2fa27ae57 100644 --- a/src/org/infinity/resource/effects/Opcode440.java +++ b/src/org/infinity/resource/effects/Opcode440.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 440. + * Implementation of opcode 440. */ public class Opcode440 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode441.java b/src/org/infinity/resource/effects/Opcode441.java index c0d1a305d..1e4d85a64 100644 --- a/src/org/infinity/resource/effects/Opcode441.java +++ b/src/org/infinity/resource/effects/Opcode441.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 441. + * Implementation of opcode 441. */ public class Opcode441 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode442.java b/src/org/infinity/resource/effects/Opcode442.java index 8290f028d..960358935 100644 --- a/src/org/infinity/resource/effects/Opcode442.java +++ b/src/org/infinity/resource/effects/Opcode442.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 442. + * Implementation of opcode 442. */ public class Opcode442 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode443.java b/src/org/infinity/resource/effects/Opcode443.java index 90299e88d..43994a37a 100644 --- a/src/org/infinity/resource/effects/Opcode443.java +++ b/src/org/infinity/resource/effects/Opcode443.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 443. + * Implementation of opcode 443. */ public class Opcode443 extends BaseOpcode { private static final String EFFECT_DAMAGE_REDUCTION = "Damage reduction"; diff --git a/src/org/infinity/resource/effects/Opcode444.java b/src/org/infinity/resource/effects/Opcode444.java index 7b72bb1ce..d0f92068f 100644 --- a/src/org/infinity/resource/effects/Opcode444.java +++ b/src/org/infinity/resource/effects/Opcode444.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 444. + * Implementation of opcode 444. */ public class Opcode444 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode445.java b/src/org/infinity/resource/effects/Opcode445.java index aa7f2defd..3b5cd278a 100644 --- a/src/org/infinity/resource/effects/Opcode445.java +++ b/src/org/infinity/resource/effects/Opcode445.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 445. + * Implementation of opcode 445. */ public class Opcode445 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode446.java b/src/org/infinity/resource/effects/Opcode446.java index 4a0ea1207..03b37a25a 100644 --- a/src/org/infinity/resource/effects/Opcode446.java +++ b/src/org/infinity/resource/effects/Opcode446.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 446. + * Implementation of opcode 446. */ public class Opcode446 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode447.java b/src/org/infinity/resource/effects/Opcode447.java index b20431abd..c15eb7ae1 100644 --- a/src/org/infinity/resource/effects/Opcode447.java +++ b/src/org/infinity/resource/effects/Opcode447.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 447. + * Implementation of opcode 447. */ public class Opcode447 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode448.java b/src/org/infinity/resource/effects/Opcode448.java index bdaa8260d..27e2247fa 100644 --- a/src/org/infinity/resource/effects/Opcode448.java +++ b/src/org/infinity/resource/effects/Opcode448.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 448. + * Implementation of opcode 448. */ public class Opcode448 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode449.java b/src/org/infinity/resource/effects/Opcode449.java index 8733fca93..601f7c4d0 100644 --- a/src/org/infinity/resource/effects/Opcode449.java +++ b/src/org/infinity/resource/effects/Opcode449.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 449. + * Implementation of opcode 449. */ public class Opcode449 extends BaseOpcode { private static final String EFFECT_NUM_HITS = "# hits"; diff --git a/src/org/infinity/resource/effects/Opcode450.java b/src/org/infinity/resource/effects/Opcode450.java index e8666772a..541b7410c 100644 --- a/src/org/infinity/resource/effects/Opcode450.java +++ b/src/org/infinity/resource/effects/Opcode450.java @@ -15,7 +15,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 450. + * Implementation of opcode 450. */ public class Opcode450 extends BaseOpcode { private static final String EFFECT_GLOBE_TYPE = "Globe type"; diff --git a/src/org/infinity/resource/effects/Opcode451.java b/src/org/infinity/resource/effects/Opcode451.java index 512fc46f5..399aa1675 100644 --- a/src/org/infinity/resource/effects/Opcode451.java +++ b/src/org/infinity/resource/effects/Opcode451.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 451. + * Implementation of opcode 451. */ public class Opcode451 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode452.java b/src/org/infinity/resource/effects/Opcode452.java index 652d37653..0ed3de0c4 100644 --- a/src/org/infinity/resource/effects/Opcode452.java +++ b/src/org/infinity/resource/effects/Opcode452.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 452. + * Implementation of opcode 452. */ public class Opcode452 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode453.java b/src/org/infinity/resource/effects/Opcode453.java index ea86c3c5c..a2c819c64 100644 --- a/src/org/infinity/resource/effects/Opcode453.java +++ b/src/org/infinity/resource/effects/Opcode453.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 453. + * Implementation of opcode 453. */ public class Opcode453 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode454.java b/src/org/infinity/resource/effects/Opcode454.java index 6fd053d49..e9991f148 100644 --- a/src/org/infinity/resource/effects/Opcode454.java +++ b/src/org/infinity/resource/effects/Opcode454.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 454. + * Implementation of opcode 454. */ public class Opcode454 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode455.java b/src/org/infinity/resource/effects/Opcode455.java index 63a5a8b88..97e031eb1 100644 --- a/src/org/infinity/resource/effects/Opcode455.java +++ b/src/org/infinity/resource/effects/Opcode455.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 455. + * Implementation of opcode 455. */ public class Opcode455 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode456.java b/src/org/infinity/resource/effects/Opcode456.java index f83596a38..679de34ad 100644 --- a/src/org/infinity/resource/effects/Opcode456.java +++ b/src/org/infinity/resource/effects/Opcode456.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 456. + * Implementation of opcode 456. */ public class Opcode456 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/effects/Opcode457.java b/src/org/infinity/resource/effects/Opcode457.java index a7cdc4536..8f15b789c 100644 --- a/src/org/infinity/resource/effects/Opcode457.java +++ b/src/org/infinity/resource/effects/Opcode457.java @@ -14,7 +14,7 @@ import org.infinity.resource.StructEntry; /** - * Implemention of opcode 457. + * Implementation of opcode 457. */ public class Opcode457 extends BaseOpcode { /** Returns the opcode name for the current game variant. */ diff --git a/src/org/infinity/resource/gam/GamResource.java b/src/org/infinity/resource/gam/GamResource.java index dbf54c734..d77c80784 100644 --- a/src/org/infinity/resource/gam/GamResource.java +++ b/src/org/infinity/resource/gam/GamResource.java @@ -44,6 +44,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.text.QuestsPanel; import org.infinity.resource.text.QuestsResource; +import org.infinity.util.Logger; import org.infinity.util.Variables; /** @@ -192,7 +193,7 @@ public JComponent getViewerTab(int index) { try { return new QuestsPanel(new QuestsResource().readQuests(), globalVars); } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); final StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); return new JTextArea(w.toString()); @@ -449,7 +450,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } } - if (offIWD2 != null && numIWD2 != null) { // Icewind2 + if (numIWD2 != null) { // Icewind2 // a leftover from BG2 Familiar Info structure? if (numIWD2.getValue() > 0) { offset = offIWD2.getValue(); @@ -470,7 +471,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } } - if (numIWD != null && offIWD != null) { // Icewind + if (numIWD != null) { // Icewind // a leftover from BG2 Familiar Info structure? if (numIWD.getValue() > 0) { offset = offIWD.getValue(); @@ -488,7 +489,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } } - if (offLocation != null && numLocation != null) { // BG2? + if (offLocation != null) { // BG2? offset = offLocation.getValue(); if (offset > 0) { for (int i = 0; i < numLocation.getValue(); i++) { @@ -499,7 +500,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } } - if (offPocket != null && numPocket != null) { // BG2 + if (offPocket != null) { // BG2 offset = offPocket.getValue(); if (offset > 0) { for (int i = 0; i < numPocket.getValue(); i++) { diff --git a/src/org/infinity/resource/graphics/BamDecoder.java b/src/org/infinity/resource/graphics/BamDecoder.java index b7efbbd95..505324c06 100644 --- a/src/org/infinity/resource/graphics/BamDecoder.java +++ b/src/org/infinity/resource/graphics/BamDecoder.java @@ -16,6 +16,7 @@ import java.util.Objects; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -60,7 +61,7 @@ public static Type getType(ResourceEntry bamEntry) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; diff --git a/src/org/infinity/resource/graphics/BamResource.java b/src/org/infinity/resource/graphics/BamResource.java index 7c1be00d9..7120f0090 100644 --- a/src/org/infinity/resource/graphics/BamResource.java +++ b/src/org/infinity/resource/graphics/BamResource.java @@ -78,6 +78,7 @@ import org.infinity.search.ReferenceSearcher; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -155,7 +156,7 @@ public BamResource(ResourceEntry entry) { ((BamV1Decoder.BamV1Control) bamControl).setTransparencyEnabled(transparencyEnabled); } } catch (Throwable t) { - t.printStackTrace(); + Logger.error(t); decoder = null; } WindowBlocker.blockWindow(false); @@ -274,7 +275,7 @@ public void actionPerformed(ActionEvent event) { ByteBuffer buffer = Compressor.decompress(entry.getResourceBuffer()); ResourceFactory.exportResource(entry, buffer, entry.getResourceName(), panelMain.getTopLevelAncestor()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -293,7 +294,7 @@ public void actionPerformed(ActionEvent event) { ByteBuffer buffer = Compressor.compress(entry.getResourceBuffer(), "BAMC", "V1 "); ResourceFactory.exportResource(entry, buffer, entry.getResourceName(), panelMain.getTopLevelAncestor()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -357,7 +358,7 @@ public void propertyChange(PropertyChangeEvent event) { l = null; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (bamData != null) { if (bamData.length > 0) { @@ -398,7 +399,7 @@ public void stateChanged(ChangeEvent event) { hexViewer.setCurrentOffset(0L); panelRaw.add(hexViewer, BorderLayout.CENTER); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { WindowBlocker.blockWindow(false); } @@ -823,40 +824,40 @@ public static String exportFrames(BamDecoder decoder, Path filePath, String file int max = 0, counter = 0, failCounter = 0; try { - if (decoder != null) { - BamDecoder.BamControl control = decoder.createControl(); - control.setMode(BamDecoder.BamControl.Mode.INDIVIDUAL); - // using selected transparency mode for BAM v1 frames - if (control instanceof BamV1Decoder.BamV1Control) { - ((BamV1Decoder.BamV1Control) control).setTransparencyEnabled(enableTransparency); + BamDecoder.BamControl control = decoder.createControl(); + control.setMode(BamDecoder.BamControl.Mode.INDIVIDUAL); + // using selected transparency mode for BAM v1 frames + if (control instanceof BamV1Decoder.BamV1Control) { + ((BamV1Decoder.BamV1Control) control).setTransparencyEnabled(enableTransparency); + } + max = decoder.frameCount(); + for (int i = 0; i < decoder.frameCount(); i++) { + String fileIndex = String.format("%05d", i); + BufferedImage image = null; + try { + image = prepareFrameImage(decoder, i); + } catch (Exception e) { + Logger.trace(e); } - max = decoder.frameCount(); - for (int i = 0; i < decoder.frameCount(); i++) { - String fileIndex = String.format("%05d", i); - BufferedImage image = null; + if (image != null) { + decoder.frameGet(control, i, image); try { - image = prepareFrameImage(decoder, i); - } catch (Exception e) { - } - if (image != null) { - decoder.frameGet(control, i, image); - try { - Path file = filePath.resolve(fileBase + fileIndex + fileExt); - ImageIO.write(image, format, file.toFile()); - counter++; - } catch (IOException e) { - failCounter++; - System.err.println("Error writing frame #" + i); - } - image.flush(); - image = null; - } else { + Path file = filePath.resolve(fileBase + fileIndex + fileExt); + ImageIO.write(image, format, file.toFile()); + counter++; + } catch (IOException e) { failCounter++; - System.err.println("Skipping frame #" + i); + Logger.warn("Error writing frame #{}", i); } + image.flush(); + image = null; + } else { + failCounter++; + Logger.warn("Skipping frame #{}", i); } } } catch (Throwable t) { + Logger.trace(t); } // displaying results @@ -1213,9 +1214,7 @@ private byte[] convertToBamV1(boolean compressed) throws Exception { // optionally compressing to MOSC V1 if (compressed) { - if (bamArray != null) { - bamArray = Compressor.compress(bamArray, "BAMC", "V1 "); - } + bamArray = Compressor.compress(bamArray, "BAMC", "V1 "); } return bamArray; @@ -1236,7 +1235,7 @@ public List doInBackground() { list.add(buf); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return list; } @@ -1286,7 +1285,7 @@ public boolean containsPvrzReference(int index) { retVal = (curIndex == index); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; diff --git a/src/org/infinity/resource/graphics/BamV1Decoder.java b/src/org/infinity/resource/graphics/BamV1Decoder.java index 8a544d7ab..387eeb165 100644 --- a/src/org/infinity/resource/graphics/BamV1Decoder.java +++ b/src/org/infinity/resource/graphics/BamV1Decoder.java @@ -18,6 +18,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -149,7 +150,7 @@ private void init() { if ("BAMC".equals(signature)) { setType(Type.BAMC); bamBuffer = Compressor.decompress(bamBuffer); - signature = StreamUtils.readString(bamBuffer, 00, 4); + signature = StreamUtils.readString(bamBuffer, 0, 4); version = StreamUtils.readString(bamBuffer, 4, 4); } else if ("BAM ".equals(signature) && "V1 ".equals(version)) { setType(Type.BAMV1); @@ -223,7 +224,7 @@ private void init() { defaultControl.setMode(BamControl.Mode.SHARED); defaultControl.setSharedPerCycle(false); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } @@ -270,8 +271,8 @@ private void decodeFrame(BamControl control, int frameIdx, Image canvas) { dstOfs = top * dstWidth + left; } else { left = top = 0; - maxWidth = (dstWidth < srcWidth) ? dstWidth : srcWidth; - maxHeight = (dstHeight < srcHeight) ? dstHeight : srcHeight; + maxWidth = Math.min(dstWidth, srcWidth); + maxHeight = Math.min(dstHeight, srcHeight); srcOfs = ofsData; dstOfs = 0; } @@ -308,9 +309,8 @@ private void decodeFrame(BamControl control, int frameIdx, Image canvas) { dstOfs += dstWidth - srcWidth; } } catch (Exception e) { - System.err.printf("Error [%s]: input (offset=%d, size=%d), output (offset=%d, size=%d)\n", - e.getClass().getName(), srcOfs, bamBuffer.limit(), dstOfs, - bufferB != null ? bufferB.length : bufferI.length); + Logger.error("Error [{}]: input (offset={}, size={}), output (offset={}, size={})", + e.getClass().getName(), srcOfs, bamBuffer.limit(), dstOfs, bufferB != null ? bufferB.length : bufferI.length); } bufferB = null; bufferI = null; @@ -362,19 +362,19 @@ public boolean equals(Object obj) { // -------------------------- INNER CLASSES -------------------------- /** Provides information for a single frame entry */ - public class BamV1FrameEntry implements BamDecoder.FrameEntry { - private int width; - private int height; - private int centerX; - private int centerY; - private int ofsData; + public static class BamV1FrameEntry implements BamDecoder.FrameEntry { + private final int width; + private final int height; + private final int centerX; + private final int centerY; + private final int ofsData; + private final boolean compressed; private int overrideCenterX; private int overrideCenterY; - private boolean compressed; private BamV1FrameEntry(ByteBuffer buffer, int ofs) { if (buffer != null && ofs + 12 <= buffer.limit()) { - width = buffer.getShort(ofs + 0) & 0xffff; + width = buffer.getShort(ofs) & 0xffff; height = buffer.getShort(ofs + 2) & 0xffff; centerX = overrideCenterX = buffer.getShort(ofs + 4); centerY = overrideCenterY = buffer.getShort(ofs + 6); @@ -760,7 +760,7 @@ private void preparePalette(int[] externalPalette) { currentPalette[idx] |= alphaMask; } alphaUsed |= (currentPalette[idx] & 0xff000000) != 0; - if (idx == 0 || (currentPalette[idx] & 0x00ffffff) == 0x0000ff00) { + if (idx == 0 || (currentPalette[idx] & 0x00ffffff) == 0x0000ff00 && transIndices.size() < 2) { transIndices.add(idx); } } @@ -773,23 +773,27 @@ private void preparePalette(int[] externalPalette) { } } - // applying transparent indices - for (int i : transIndices) { + // applying transparent index + // use only one transparent color index (prefer magic color "green" over first palette index) + if (transIndices.size() > 1 && (currentPalette[transIndices.get(0)] & 0x00ffffff) != 0x0000ff00) { + transIndices.remove(0); + } + final int transIndex = !transIndices.isEmpty() ? transIndices.get(0) : -1; + if (transIndex >= 0) { if (transparencyEnabled) { - currentPalette[i] = 0; + currentPalette[transIndex] = 0; } else { - currentPalette[i] |= 0xff000000; + currentPalette[transIndex] |= 0xff000000; } } } } // Stores information for a single cycle - private class CycleEntry { + private static class CycleEntry { private final int[] frames; // list of frame indices used in this cycle - - private int indexCount; // number of frame indices in this cycle - private int lookupIndex; // index into frame lookup table + private final int indexCount; // number of frame indices in this cycle + private final int lookupIndex; // index into frame lookup table /** * @param buffer The BAM data buffer diff --git a/src/org/infinity/resource/graphics/BamV2Decoder.java b/src/org/infinity/resource/graphics/BamV2Decoder.java index 459e6d9fe..8a294ce2e 100644 --- a/src/org/infinity/resource/graphics/BamV2Decoder.java +++ b/src/org/infinity/resource/graphics/BamV2Decoder.java @@ -23,6 +23,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; import org.infinity.util.io.StreamUtils; @@ -156,12 +157,10 @@ private void init() { bamPath = bamFile.getParent(); // Skip path if it denotes an override folder of the game List list = Profile.getOverrideFolders(true); - if (list != null) { - for (final Path path : list) { - if (bamPath.equals(path)) { - bamPath = null; - break; - } + for (final Path path : list) { + if (bamPath.equals(path)) { + bamPath = null; + break; } } } @@ -220,7 +219,7 @@ private void init() { defaultControl.setMode(BamControl.Mode.SHARED); defaultControl.setSharedPerCycle(false); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } @@ -247,7 +246,7 @@ private PvrDecoder getPVR(int page) { return PvrDecoder.loadPvr(entry); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -282,8 +281,8 @@ private void renderFrame(BamControl control, int frameIdx, Image canvas) { } else { // drawing on individual canvas int srcOfs = 0, dstOfs = 0; - int maxWidth = (dstWidth < srcWidth) ? dstWidth : srcWidth; - int maxHeight = (dstHeight < srcHeight) ? dstHeight : srcHeight; + int maxWidth = Math.min(dstWidth, srcWidth); + int maxHeight = Math.min(dstHeight, srcHeight); for (int y = 0; y < maxHeight; y++) { System.arraycopy(srcBuffer, srcOfs, dstBuffer, dstOfs, maxWidth); srcOfs += srcWidth; @@ -339,12 +338,13 @@ public boolean equals(Object obj) { // Stores information for a single frame entry public class BamV2FrameEntry implements BamDecoder.FrameEntry { - private final int dataBlockSize = 0x1c; // size of a single data block + private static final int DATA_BLOCK_SIZE = 0x1c; // size of a single data block + + private final int width; + private final int height; + private final int centerX; + private final int centerY; - private int width; - private int height; - private int centerX; - private int centerY; private int overrideCenterX; private int overrideCenterY; private BufferedImage frame; @@ -415,7 +415,7 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result - + Objects.hash(centerX, centerY, dataBlockSize, height, overrideCenterX, overrideCenterY, width); + + Objects.hash(centerX, centerY, height, overrideCenterX, overrideCenterY, width); return result; } @@ -431,7 +431,7 @@ public boolean equals(Object obj) { return false; } BamV2FrameEntry other = (BamV2FrameEntry) obj; - return centerX == other.centerX && centerY == other.centerY && dataBlockSize == other.dataBlockSize + return centerX == other.centerX && centerY == other.centerY && height == other.height && overrideCenterX == other.overrideCenterX && overrideCenterY == other.overrideCenterY && width == other.width; } @@ -441,7 +441,7 @@ private void decodeImage(ByteBuffer buffer, int ofsBlocks, int start, int count) if (width > 0 && height > 0) { frame = ColorConvert.createCompatibleImage(width, height, Transparency.TRANSLUCENT); - int ofs = ofsBlocks + start * dataBlockSize; + int ofs = ofsBlocks + start * DATA_BLOCK_SIZE; for (int i = 0; i < count; i++) { int page = buffer.getInt(ofs); int srcX = buffer.getInt(ofs + 0x04); @@ -450,7 +450,7 @@ private void decodeImage(ByteBuffer buffer, int ofsBlocks, int start, int count) int h = buffer.getInt(ofs + 0x10); int dstX = buffer.getInt(ofs + 0x14); int dstY = buffer.getInt(ofs + 0x18); - ofs += dataBlockSize; + ofs += DATA_BLOCK_SIZE; PvrDecoder decoder = getPVR(page); if (decoder != null) { @@ -466,7 +466,7 @@ private void decodeImage(ByteBuffer buffer, int ofsBlocks, int start, int count) decoder = null; srcImage = null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -644,7 +644,7 @@ private void init() { } // Stores information for a single cycle - private class CycleEntry { + private static class CycleEntry { public int startIndex; public int framesCount; diff --git a/src/org/infinity/resource/graphics/BlendingComposite.java b/src/org/infinity/resource/graphics/BlendingComposite.java index f2b45937b..645c3f317 100644 --- a/src/org/infinity/resource/graphics/BlendingComposite.java +++ b/src/org/infinity/resource/graphics/BlendingComposite.java @@ -86,7 +86,7 @@ void blend(int[] src, int[] dst, int[] result) { /** * - * @param modes + * @param mode */ public BlendingComposite(BlendingMode mode) { this(1.0f, mode); @@ -95,7 +95,7 @@ public BlendingComposite(BlendingMode mode) { /** * * @param alpha - * @param modes + * @param mode */ public BlendingComposite(float alpha, BlendingMode mode) { // filtering out null items @@ -110,7 +110,7 @@ public BlendingComposite(float alpha, BlendingMode mode) { /** * - * @param modes + * @param mode * @return */ public static BlendingComposite getInstance(BlendingMode mode) { @@ -120,7 +120,7 @@ public static BlendingComposite getInstance(BlendingMode mode) { /** * * @param alpha - * @param modes + * @param mode * @return */ public static BlendingComposite getInstance(float alpha, BlendingMode mode) { @@ -129,7 +129,7 @@ public static BlendingComposite getInstance(float alpha, BlendingMode mode) { /** * - * @param modes + * @param mode * @return */ public BlendingComposite derive(BlendingMode mode) { diff --git a/src/org/infinity/resource/graphics/BmpDecoder.java b/src/org/infinity/resource/graphics/BmpDecoder.java index ae80f98bb..44758ca02 100644 --- a/src/org/infinity/resource/graphics/BmpDecoder.java +++ b/src/org/infinity/resource/graphics/BmpDecoder.java @@ -89,7 +89,7 @@ public static BmpDecoder loadBmp(InputStream input) throws Exception { int bufferSize = bufList.stream().mapToInt(b -> b.length).sum(); final ByteBuffer bb = StreamUtils.getByteBuffer(bufferSize); - bufList.forEach(b -> bb.put(b)); + bufList.forEach(bb::put); bb.rewind(); return new BmpDecoder(bb); @@ -122,10 +122,7 @@ private void init(ByteBuffer buffer) throws Exception { Objects.requireNonNull(buffer); // Checking signature - boolean isBMP = false; - if ("BM".equals(StreamUtils.readString(buffer, 0, 2))) { - isBMP = true; - } + boolean isBMP = "BM".equals(StreamUtils.readString(buffer, 0, 2)); image = null; palette = null; @@ -175,8 +172,8 @@ private void init(ByteBuffer buffer) throws Exception { final int[] colors = new int[numColors]; icm.getRGBs(colors); final ByteBuffer pb = StreamUtils.getByteBuffer(colors.length * 4); - for (int i = 0; i < colors.length; i++) { - pb.putInt(colors[i]); + for (int color : colors) { + pb.putInt(color); } pb.rewind(); palette = new Palette(pb, 0, pb.capacity()); @@ -263,10 +260,10 @@ public String toString() { } } - private Compression compression; - private int width; - private int height; - private int bpp; + private final Compression compression; + private final int width; + private final int height; + private final int bpp; private Info(BufferedImage image) { this(image, -1, 0); diff --git a/src/org/infinity/resource/graphics/ColorConvert.java b/src/org/infinity/resource/graphics/ColorConvert.java index 14d3673a6..a62432b82 100644 --- a/src/org/infinity/resource/graphics/ColorConvert.java +++ b/src/org/infinity/resource/graphics/ColorConvert.java @@ -34,16 +34,18 @@ import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; +import javax.swing.ImageIcon; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; import org.infinity.util.tuples.Triple; /** - * Contains a set of color-related static methods (little endian order only). + * Contains a set of color and graphics-related static methods. */ public class ColorConvert { /** @@ -262,6 +264,56 @@ public static BufferedImage cloneImage(BufferedImage image) { return dstImage; } + /** + * A static method that loads a graphics file from the folder relative to the specified {@code Class} object and + * returns it as an {@link Image} instance. + * + * @param cls {@code Class} object used to to determine the root path within the Java archive. + * @param fileName Filename of the graphics file relative to the class path. + * @return {@link Image} instance of the graphics file. Returns {@code null} if graphics file could not be loaded. + */ + public static Image loadAppImage(Class cls, String fileName) { + Image retVal = null; + + if (fileName == null) { + return retVal; + } + + if (cls == null) { + cls = ColorConvert.class; + } + + try (InputStream is = cls.getResourceAsStream(fileName)) { + if (is != null) { + retVal = ImageIO.read(is); + } + } catch (IOException e) { + Logger.error(e); + } + + return retVal; + } + + /** + * A static method that loads a graphics file from the folder relative to the specified {@code Class} object and + * returns it as an {@link ImageIcon} instance. + * + * @param cls {@code Class} object used to determine the root path within the Java archive. + * @param fileName Filename of the graphics file relative to the root path. The following file format are supported: + * BMP, GIF, JPEG, PNG and WEBP. + * @return {@link ImageIcon} instance of the graphics file. Returns {@code null} if graphics file could not be loaded. + */ + public static ImageIcon loadAppIcon(Class cls, String fileName) { + ImageIcon retVal = null; + + final Image image = loadAppImage(cls, fileName); + if (image != null) { + retVal = new ImageIcon(image); + } + + return retVal; + } + /** * Attempts to retrieve the width and height of the specified image file without loading it completely. * @@ -806,7 +858,7 @@ public static int[] loadPaletteBMP(ResourceEntry entry) throws Exception { throw new Exception("Invalid BMP resource: " + entry.getResourceName()); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unable to read BMP resource: " + entry.getResourceName()); } } else { @@ -840,7 +892,7 @@ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exce throw new Exception("Error loading palette from PNG file " + file.getFileName()); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unable to read PNG file " + file.getFileName()); } } else { @@ -893,7 +945,7 @@ public static int[] loadPalettePAL(Path file) throws Exception { throw new Exception("Invalid Windows palette file " + file.getFileName()); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unable to read Windows palette file " + file.getFileName()); } } else { @@ -935,7 +987,7 @@ public static int[] loadPaletteACT(Path file) throws Exception { throw new Exception("Invalid Adobe Photoshop palette file " + file.getFileName()); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unable to read Adobe Photoshop palette file " + file.getFileName()); } } else { @@ -987,7 +1039,7 @@ public static int[] loadPaletteBAM(ResourceEntry entry, boolean preserveAlpha) t throw new Exception("Unsupport file type."); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unable to read BAM resource: " + entry.getResourceName()); } } else { @@ -1217,7 +1269,7 @@ public int getElement(int index) { a = rgba[3] * rgba[3] * 0.5; dist[i] = Math.sqrt(b + g + r + a); } - return (dist[0] < dist[1]) ? -1 : ((dist[0] > dist[1]) ? 1 : 0); + return Double.compare(dist[0], dist[1]); }; // Compare colors by saturation. @@ -1226,11 +1278,11 @@ public int getElement(int index) { double[] dist = new double[colors.length]; for (int i = 0; i < colors.length; i++) { double[] rgba = getNormalizedColor(colors[i]); - double cmin = rgba[0] < rgba[1] ? rgba[0] : rgba[1]; + double cmin = Math.min(rgba[0], rgba[1]); if (rgba[2] < cmin) { cmin = rgba[2]; } - double cmax = rgba[0] > rgba[1] ? rgba[0] : rgba[1]; + double cmax = Math.max(rgba[0], rgba[1]); if (rgba[2] > cmax) { cmax = rgba[2]; } @@ -1244,7 +1296,7 @@ public int getElement(int index) { } dist[i] = s; } - return (dist[0] < dist[1]) ? -1 : ((dist[0] > dist[1]) ? 1 : 0); + return Double.compare(dist[0], dist[1]); }; // Compare colors by hue. @@ -1253,11 +1305,11 @@ public int getElement(int index) { double[] dist = new double[colors.length]; for (int i = 0; i < colors.length; i++) { double[] rgba = getNormalizedColor(colors[i]); - double cmin = rgba[0] < rgba[1] ? rgba[0] : rgba[1]; + double cmin = Math.min(rgba[0], rgba[1]); if (rgba[2] < cmin) { cmin = rgba[2]; } - double cmax = rgba[0] > rgba[1] ? rgba[0] : rgba[1]; + double cmax = Math.max(rgba[0], rgba[1]); if (rgba[2] > cmax) { cmax = rgba[2]; } @@ -1286,7 +1338,7 @@ public int getElement(int index) { } dist[i] = h; } - return (dist[0] < dist[1]) ? -1 : ((dist[0] > dist[1]) ? 1 : 0); + return Double.compare(dist[0], dist[1]); }; // Compare colors by red amount. @@ -1321,13 +1373,7 @@ public int getElement(int index) { private static final Comparator COMPARE_BY_LAB_L = (c1, c2) -> { Triple dist1 = convertRGBtoLab(c1); Triple dist2 = convertRGBtoLab(c2); - if (dist1.getValue0() < dist2.getValue0()) { - return -1; - } else if (dist1.getValue0() > dist2.getValue0()) { - return 1; - } else { - return 0; - } + return dist1.getValue0().compareTo(dist2.getValue0()); // int dist1 = (c1 >>> 24) & 0xff; // int dist2 = (c2 >>> 24) & 0xff; // return dist1 - dist2; diff --git a/src/org/infinity/resource/graphics/Compressor.java b/src/org/infinity/resource/graphics/Compressor.java index 4063e819f..0a54989c7 100644 --- a/src/org/infinity/resource/graphics/Compressor.java +++ b/src/org/infinity/resource/graphics/Compressor.java @@ -55,8 +55,8 @@ public static ByteBuffer compress(ByteBuffer buffer, String signature, String ve * @param version Version ID for the header. * @return The compressed data including header. */ - public static byte[] compress(byte data[], String signature, String version) { - byte header[] = ArrayUtil.mergeArrays(signature.getBytes(), version.getBytes()); + public static byte[] compress(byte[] data, String signature, String version) { + byte[] header = ArrayUtil.mergeArrays(signature.getBytes(), version.getBytes()); header = ArrayUtil.mergeArrays(header, DynamicArray.convertInt(data.length)); byte[] result = compress(data, 0, data.length, false); if (result != null) { @@ -108,7 +108,7 @@ public static byte[] compress(byte[] data, int ofs, int len, boolean prependSize * @param len Length of data to compress, in bytes. Specify {@code 0} to compress until no more input data is available. * @param prependSize If {@code true} then uncompressed size value will be written to the output stream * before compressed data is written. Ignored if {@code len} is 0. - * @return + * @return Number of bytes compressed * @throws IOException if an I/O error occurs. */ public static int compress(InputStream is, OutputStream os, int len, boolean prependSize) throws IOException { @@ -163,11 +163,10 @@ public static ByteBuffer decompress(ByteBuffer buffer, int offset) throws IOExce * Decompresses the data of the specified byte array and returns it as a new byte array object. * * @param buffer Byte array with data to decompress. - * @param offset Start offset of compressed data. * @return A byte array with decompressed data. - * @throws IOException + * @throws IOException if an I/O error occurs. */ - public static byte[] decompress(byte buffer[]) throws IOException { + public static byte[] decompress(byte[] buffer) throws IOException { return decompress(buffer, 8); } @@ -175,13 +174,13 @@ public static byte[] decompress(byte buffer[]) throws IOException { * Decompresses the data of the specified byte array and returns it as a new byte array object. * * @param buffer Byte array with data to decompress. - * @param offset Start offset of compressed data. + * @param ofs Start offset of compressed data. * @return A byte array with decompressed data. * @throws IOException if an I/O error occurs. */ - public static byte[] decompress(byte buffer[], int ofs) throws IOException { + public static byte[] decompress(byte[] buffer, int ofs) throws IOException { Inflater inflater = new Inflater(); - byte result[] = new byte[DynamicArray.getInt(buffer, ofs)]; + byte[] result = new byte[DynamicArray.getInt(buffer, ofs)]; ofs += 4; inflater.setInput(buffer, ofs, buffer.length - ofs); try { @@ -199,7 +198,7 @@ public static byte[] decompress(byte buffer[], int ofs) throws IOException { * @param is {@code InputStream} with data to decompress. * The current stream position should point to the start of the game resource. * @return A byte array with decompressed data. - * @throws IOException + * @throws IOException if an I/O error occurs. */ public static byte[] decompress(InputStream is) throws IOException { return decompress(is, 8, 0); diff --git a/src/org/infinity/resource/graphics/DxtEncoder.java b/src/org/infinity/resource/graphics/DxtEncoder.java index cec5f7f97..80fc3da97 100644 --- a/src/org/infinity/resource/graphics/DxtEncoder.java +++ b/src/org/infinity/resource/graphics/DxtEncoder.java @@ -30,6 +30,7 @@ package org.infinity.resource.graphics; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.Future; @@ -506,9 +507,10 @@ protected void computeEndPoints(final SingleColorLookup[][] lookups) { } private static class RangeFit extends ColorFit { - private Vec3 metric; - private Vec3 start; - private Vec3 end; + private final Vec3 metric; + private final Vec3 start; + private final Vec3 end; + private float bestError; public RangeFit(final ColorSet colors, final DxtType dxtType) { @@ -1089,7 +1091,7 @@ private static void writeColorBlock(final int a, final int b, final int[] indice // write the indices for (int i = 0; i < 4; i++) { final int idx = 4 * i; - block[i + 4] = (byte) ((indices[idx + 0]) | (indices[idx + 1] << 2) | (indices[idx + 2] << 4) + block[i + 4] = (byte) ((indices[idx]) | (indices[idx + 1] << 2) | (indices[idx + 2] << 4) | (indices[idx + 3] << 6)); } } @@ -2887,16 +2889,12 @@ private static Vec3 getMultiplicity2Evector(final Sym3x3 matrix, final float eva public Sym3x3() { m = new float[6]; - for (int i = 0; i < m.length; i++) { - m[i] = 0.0f; - } + Arrays.fill(m, 0.0f); } public Sym3x3(final float s) { m = new float[6]; - for (int i = 0; i < m.length; i++) { - m[i] = s; - } + Arrays.fill(m, s); } @Override diff --git a/src/org/infinity/resource/graphics/GifSequenceReader.java b/src/org/infinity/resource/graphics/GifSequenceReader.java index 6f29be0bd..6ee7d12c4 100644 --- a/src/org/infinity/resource/graphics/GifSequenceReader.java +++ b/src/org/infinity/resource/graphics/GifSequenceReader.java @@ -26,6 +26,7 @@ import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; +import org.infinity.util.Logger; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -251,6 +252,7 @@ private int getIntValue(Node node) { try { retVal = Integer.parseInt(node.getNodeValue()); } catch (NumberFormatException e) { + Logger.trace(e); } } return retVal; @@ -276,10 +278,11 @@ private static ImageReader getReader() throws IOException { // -------------------------- INNER CLASSES -------------------------- public static class Frame { - private int index; + private final int index; + private final Rectangle rect; + private BufferedImage image; private BufferedImage renderedImage; - private Rectangle rect; private int delay; private DisposalMethod disposal; private int transIndex; diff --git a/src/org/infinity/resource/graphics/GifSequenceWriter.java b/src/org/infinity/resource/graphics/GifSequenceWriter.java index b61fb5228..18a86c51e 100644 --- a/src/org/infinity/resource/graphics/GifSequenceWriter.java +++ b/src/org/infinity/resource/graphics/GifSequenceWriter.java @@ -78,7 +78,7 @@ public GifSequenceWriter(ImageOutputStream outputStream, int imageType, int time int loop = loopContinuously ? 0 : 1; - child.setUserObject(new byte[] { 0x1, (byte) (loop & 0xFF), (byte) ((loop >> 8) & 0xFF) }); + child.setUserObject(new byte[] { 0x1, (byte) (loop & 0xff), (byte) ((loop >> 8) & 0xff) }); appEntensionsNode.appendChild(child); imageMetaData.setFromTree(metaFormatName, root); diff --git a/src/org/infinity/resource/graphics/MosDecoder.java b/src/org/infinity/resource/graphics/MosDecoder.java index c3094e41f..91d2812a5 100644 --- a/src/org/infinity/resource/graphics/MosDecoder.java +++ b/src/org/infinity/resource/graphics/MosDecoder.java @@ -9,6 +9,7 @@ import java.nio.ByteBuffer; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -39,10 +40,9 @@ public static boolean isValid(ResourceEntry mosEntry) { public static Type getType(ResourceEntry mosEntry) { Type retVal = Type.INVALID; if (mosEntry != null) { - try (InputStream is = mosEntry.getResourceDataAsStream()) { + try (final InputStream is = mosEntry.getResourceDataAsStream()) { String signature = StreamUtils.readString(is, 4); String version = StreamUtils.readString(is, 4); - is.close(); if ("MOSC".equals(signature)) { retVal = Type.MOSC; } else if ("MOS ".equals(signature)) { @@ -53,7 +53,7 @@ public static Type getType(ResourceEntry mosEntry) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; diff --git a/src/org/infinity/resource/graphics/MosResource.java b/src/org/infinity/resource/graphics/MosResource.java index 017c6c2ea..4e9d3e2bc 100644 --- a/src/org/infinity/resource/graphics/MosResource.java +++ b/src/org/infinity/resource/graphics/MosResource.java @@ -60,6 +60,7 @@ import org.infinity.search.ReferenceSearcher; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -114,6 +115,7 @@ public void actionPerformed(ActionEvent event) { rcImage.setImage(loadImage()); WindowBlocker.blockWindow(false); } catch (Exception e) { + Logger.trace(e); } WindowBlocker.blockWindow(false); } @@ -137,7 +139,7 @@ public void actionPerformed(ActionEvent event) { buffer = Compressor.decompress(buffer); ResourceFactory.exportResource(entry, buffer, entry.getResourceName(), panel.getTopLevelAncestor()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Error while exporting " + entry, "Error", JOptionPane.ERROR_MESSAGE); } @@ -156,7 +158,7 @@ public void actionPerformed(ActionEvent event) { buffer = Compressor.compress(buffer, "MOSC", "V1 "); ResourceFactory.exportResource(entry, buffer, entry.getResourceName(), panel.getTopLevelAncestor()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Error while exporting " + entry, "Error", JOptionPane.ERROR_MESSAGE); } @@ -181,7 +183,7 @@ public void actionPerformed(ActionEvent event) { JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } else if (event.getSource() == miPvrzShow) { if (lastBlockIndex >= 0) { @@ -223,7 +225,7 @@ public void propertyChange(PropertyChangeEvent event) { l = null; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (mosData != null) { if (mosData.length > 0) { @@ -439,7 +441,7 @@ private void showProperties() { sb.append(""); JOptionPane.showMessageDialog(panel, sb.toString(), "Properties of " + resName, JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { if (decoder != null) { decoder.close(); @@ -497,7 +499,7 @@ private BufferedImage loadImage() { decoder = MosDecoder.loadMos(entry); mosType = decoder.getType(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -591,7 +593,7 @@ private byte[] convertToMosV1(boolean compressed) throws Exception { tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte) 255; for (int i = 1; i < 256; i++) { - tilePalette[(i << 2) + 0] = (byte) (palette[i - 1] & 0xff); + tilePalette[(i << 2)] = (byte) (palette[i - 1] & 0xff); tilePalette[(i << 2) + 1] = (byte) ((palette[i - 1] >>> 8) & 0xff); tilePalette[(i << 2) + 2] = (byte) ((palette[i - 1] >>> 16) & 0xff); tilePalette[(i << 2) + 3] = 0; @@ -654,7 +656,7 @@ public List doInBackground() { list.add(buf); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return list; } @@ -704,7 +706,7 @@ public boolean containsPvrzReference(int index) { retVal = (curIndex == index); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; diff --git a/src/org/infinity/resource/graphics/MosV1Decoder.java b/src/org/infinity/resource/graphics/MosV1Decoder.java index 4c1de7962..be90ed61c 100644 --- a/src/org/infinity/resource/graphics/MosV1Decoder.java +++ b/src/org/infinity/resource/graphics/MosV1Decoder.java @@ -15,6 +15,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; public class MosV1Decoder extends MosDecoder { @@ -68,7 +69,7 @@ public static MosDecoder.MosInfo getInfo(ResourceEntry mosEntry) { retVal = new MosDecoder.MosInfo(compressed, width, height, columns, rows, blockSize); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -137,7 +138,7 @@ public boolean getPalette(int blockIdx, int[] buffer) { if (isValidBlock(blockIdx) && buffer != null) { int ofs = getPaletteOffset(blockIdx); if (ofs > 0) { - int maxSize = (buffer.length < 256) ? buffer.length : 256; + int maxSize = Math.min(buffer.length, 256); boolean transSet = false; for (int i = 0; i < maxSize; i++, ofs += 4) { int color = 0xff000000 | mosBuffer.getInt(ofs); @@ -185,7 +186,7 @@ public boolean getRawBlockData(int blockIdx, byte[] buffer) { int ofs = getBlockOffset(blockIdx); if (ofs > 0) { int size = getBlockWidth(blockIdx) * getBlockHeight(blockIdx); - int maxSize = (buffer.length < size) ? buffer.length : size; + int maxSize = Math.min(buffer.length, size); mosBuffer.position(ofs); mosBuffer.get(buffer, 0, maxSize); return true; @@ -357,7 +358,7 @@ public boolean getBlockData(int blockIdx, int[] buffer) { BufferedImage image = ColorConvert.toBufferedImage(getBlock(blockIdx), true); if (image != null) { int[] src = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - int maxSize = (buffer.length < src.length) ? buffer.length : src.length; + int maxSize = Math.min(buffer.length, src.length); System.arraycopy(src, 0, buffer, 0, maxSize); image.flush(); image = null; @@ -418,7 +419,7 @@ private void init() { workingPalette = new int[256]; workingCanvas = new BufferedImage(BLOCK_DIMENSION, BLOCK_DIMENSION, BufferedImage.TYPE_INT_ARGB); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } diff --git a/src/org/infinity/resource/graphics/MosV2Decoder.java b/src/org/infinity/resource/graphics/MosV2Decoder.java index b572a299e..be1357fef 100644 --- a/src/org/infinity/resource/graphics/MosV2Decoder.java +++ b/src/org/infinity/resource/graphics/MosV2Decoder.java @@ -21,6 +21,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; public class MosV2Decoder extends MosDecoder { @@ -59,7 +60,7 @@ public static MosDecoder.MosInfo getInfo(ResourceEntry mosEntry) { retVal = new MosDecoder.MosInfo(width, height, numBlocks); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -307,7 +308,7 @@ private void init() { dataBlocks.add(block); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } @@ -321,7 +322,7 @@ private PvrDecoder getPVR(int page) { return PvrDecoder.loadPvr(entry); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -372,7 +373,7 @@ private boolean renderBlock(MosBlock block, Image canvas, int left, int top) { } return true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return false; @@ -415,7 +416,7 @@ private boolean renderBlock(MosBlock block, int[] buffer, int width, int height, return true; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return false; diff --git a/src/org/infinity/resource/graphics/Palette.java b/src/org/infinity/resource/graphics/Palette.java index 0bf3daac4..c6fddfeb8 100644 --- a/src/org/infinity/resource/graphics/Palette.java +++ b/src/org/infinity/resource/graphics/Palette.java @@ -8,7 +8,7 @@ import org.infinity.util.io.StreamUtils; -final class Palette { +public class Palette { private final ByteBuffer colors; public static int getColor(ByteBuffer buffer, int offset, int index) { @@ -29,12 +29,11 @@ public int getColor(int index) { public short[] getColorBytes(int index) { index = Math.max(0, Math.min(255, index)); int offset = index * 4; - short[] shorts = { + return new short[]{ (short) (colors.get(offset) & 0xff), (short) (colors.get(offset + 1) & 0xff), (short) (colors.get(offset + 2) & 0xff), (short) (colors.get(offset + 3) & 0xff) }; - return shorts; } } diff --git a/src/org/infinity/resource/graphics/PltResource.java b/src/org/infinity/resource/graphics/PltResource.java index b4ed02478..833876f88 100644 --- a/src/org/infinity/resource/graphics/PltResource.java +++ b/src/org/infinity/resource/graphics/PltResource.java @@ -61,6 +61,7 @@ import org.infinity.resource.Writeable; import org.infinity.resource.cre.CreResource; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; import org.infinity.util.io.StreamUtils; @@ -286,7 +287,7 @@ public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("PNG writing is not supported"); } } catch (Exception ioe) { - ioe.printStackTrace(); + Logger.error(ioe); JOptionPane.showMessageDialog(panelMain.getTopLevelAncestor(), "Error while exporting " + entry, "Error", JOptionPane.ERROR_MESSAGE); } @@ -341,7 +342,7 @@ public void stateChanged(ChangeEvent event) { hexViewer.setCurrentOffset(0L); panelRaw.add(hexViewer, BorderLayout.CENTER); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { WindowBlocker.blockWindow(false); } @@ -672,9 +673,10 @@ private void init() { try { int v = Integer.parseInt(s); if (v >= numItems) { - randomIndices.add(Integer.valueOf(v)); + randomIndices.add(v); } } catch (NumberFormatException nfe) { + Logger.trace(nfe); } } } @@ -706,8 +708,9 @@ private void init() { try { v = Integer.parseInt(s); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } - if (randomIndices.contains(Integer.valueOf(v))) { + if (randomIndices.contains(v)) { int index = v; ColorItem[] randItems = new ColorItem[numRows - 1]; for (int row = 1; row < numRows; ++row) { @@ -716,6 +719,7 @@ private void init() { try { v = Integer.parseInt(s); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } if (v < 0 || v >= numItems) v = 0; @@ -727,7 +731,7 @@ private void init() { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } if (items == null) { @@ -788,7 +792,7 @@ private BufferedImage getColorCircle(ColorItem item) { g2.drawString(msg, x, y); } else { // fixed color range - int[] indices = iconIndexMap.get(Integer.valueOf(item.getIndex())); + int[] indices = iconIndexMap.get(item.getIndex()); if (indices == null) { indices = new int[ICON_WIDTH * ICON_HEIGHT]; int maxDist = (ICON_WIDTH - 1) / 2; @@ -809,7 +813,7 @@ private BufferedImage getColorCircle(ColorItem item) { indices[y * ICON_WIDTH + x] = index; } } - iconIndexMap.put(Integer.valueOf(item.getIndex()), indices); + iconIndexMap.put(item.getIndex(), indices); } int[] buffer = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); diff --git a/src/org/infinity/resource/graphics/PseudoBamDecoder.java b/src/org/infinity/resource/graphics/PseudoBamDecoder.java index 191824438..b2badc75b 100644 --- a/src/org/infinity/resource/graphics/PseudoBamDecoder.java +++ b/src/org/infinity/resource/graphics/PseudoBamDecoder.java @@ -31,6 +31,7 @@ import org.infinity.resource.Profile; import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; import org.infinity.util.tuples.Couple; @@ -548,8 +549,8 @@ private void renderFrame(BamControl control, int frameIdx, Image canvas) { } else { // drawing on individual canvas int srcOfs = 0, dstOfs = 0; - int maxWidth = (dstWidth < srcWidth) ? dstWidth : srcWidth; - int maxHeight = (dstHeight < srcHeight) ? dstHeight : srcHeight; + int maxWidth = Math.min(dstWidth, srcWidth); + int maxHeight = Math.min(dstHeight, srcHeight); for (int y = 0; y < maxHeight; y++) { for (int x = 0; x < maxWidth; x++) { if (srcBufferB != null) { @@ -623,9 +624,7 @@ public static boolean isTransparentColor(int color, int threshold) { return (color & 0xff000000) == 0; } final int Green = 0x0000ff00; - if (threshold < 0) { - threshold = 0; - } else if (threshold > 255) { + if (threshold > 255) { threshold = 255; } boolean isAlpha = (((color >>> 24) & 0xff) < (255 - threshold)); @@ -727,7 +726,7 @@ public boolean exportBamV1(Path fileName, ProgressMonitor progress, int curProgr // encoding frames Object o = getOption(OPTION_INT_RLEINDEX); - byte rleIndex = (byte) (((o != null) ? ((Integer) o).intValue() : 0) & 0xff); + byte rleIndex = (byte) (((o != null) ? (Integer) o : 0) & 0xff); byte[] dstData = new byte[maxImageSize]; for (int idx = 0; idx < listFrames.size(); idx++) { @@ -794,7 +793,7 @@ public boolean exportBamV1(Path fileName, ProgressMonitor progress, int curProgr for (int i = 0; i < listFrameData.size(); i++) { frameDataOffsets[i] = bamSize; o = listFrames.get(i).getOption(OPTION_BOOL_COMPRESSED); - if (o == null || !((Boolean) o).booleanValue()) { + if (o == null || !(Boolean) o) { frameDataOffsets[i] |= 0x80000000; } bamSize += listFrameData.get(i).length; @@ -865,7 +864,7 @@ public boolean exportBamV1(Path fileName, ProgressMonitor progress, int curProgr try (OutputStream os = StreamUtils.getOutputStream(fileName, true)) { os.write(bamData); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw e; } bamData = null; @@ -938,15 +937,14 @@ public boolean exportBamV2(Path fileName, DxtEncoder.DxtType dxtType, int pvrzIn Couple cycle = Couple.with((short) cycleFrames.size(), (short) frameStartIndex); listCycleData.add(cycle); - for (int j = 0; j < cycleFrames.size(); j++) { - int idx = cycleFrames.get(j); + for (int idx : cycleFrames) { try { FrameDataV2 frame = listFrameData.get(idx); PseudoBamFrameEntry bfe = listFrames.get(idx); PseudoBamFrameEntry entry = new PseudoBamFrameEntry(bfe.frame, bfe.getCenterX(), bfe.getCenterY()); - entry.setOption(OPTION_INT_BLOCKINDEX, Integer.valueOf(blockStartIndex)); - entry.setOption(OPTION_INT_BLOCKCOUNT, Integer.valueOf(1)); + entry.setOption(OPTION_INT_BLOCKINDEX, blockStartIndex); + entry.setOption(OPTION_INT_BLOCKCOUNT, 1); listFrameEntries.add(entry); blockStartIndex++; listFrameDataBlocks.add(frame); @@ -1014,7 +1012,7 @@ public boolean exportBamV2(Path fileName, DxtEncoder.DxtType dxtType, int pvrzIn try (OutputStream os = StreamUtils.getOutputStream(fileName, true)) { os.write(bamData); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw e; } bamData = null; @@ -1047,8 +1045,8 @@ public int[] createGlobalPalette(HashMap colorMap) { } else { newMap = new HashMap<>(colorMap.size()); colorMap.forEach((k, v) -> { - if ((k.intValue() & 0xff000000) == 0) { - k = k.intValue() | 0xff000000; + if ((k & 0xff000000) == 0) { + k = k | 0xff000000; } newMap.put(k, v); }); @@ -1225,9 +1223,9 @@ private boolean buildFrameDataList(List framesList, List final int pageDim = 1024; final BinPack2D.HeuristicRules binPackRule = BinPack2D.HeuristicRules.BOTTOM_LEFT_RULE; - for (int frameIdx = 0; frameIdx < listFrames.size(); frameIdx++) { - int imgWidth = listFrames.get(frameIdx).frame.getWidth() + 2; - int imgHeight = listFrames.get(frameIdx).frame.getHeight() + 2; + for (PseudoBamFrameEntry listFrame : listFrames) { + int imgWidth = listFrame.frame.getWidth() + 2; + int imgHeight = listFrame.frame.getHeight() + 2; // use multiple of 4 to take advantage of texture compression algorithm Dimension space = new Dimension((imgWidth + 3) & ~3, (imgHeight + 3) & ~3); @@ -1347,12 +1345,12 @@ private boolean createPvrzPages(Path path, DxtEncoder.DxtType dxtType, List mapOptions = new HashMap<>(); + private final int centerX; + private final int centerY; + private int width; private int height; - private int centerX; - private int centerY; private int overrideCenterX; private int overrideCenterY; private BufferedImage frame; @@ -1778,9 +1777,7 @@ public boolean cycleFrameHasPalette(int cycleIdx, int frameIdx) { int index = cycleGetFrameIndexAbsolute(cycleIdx, frameIdx); if (index >= 0) { BufferedImage image = getDecoder().listFrames.get(index).frame; - if (image != null && image.getType() == BufferedImage.TYPE_BYTE_INDEXED) { - return true; - } + return image != null && image.getType() == BufferedImage.TYPE_BYTE_INDEXED; } return false; } diff --git a/src/org/infinity/resource/graphics/PvrDecoder.java b/src/org/infinity/resource/graphics/PvrDecoder.java index 624002e33..820e99fc0 100644 --- a/src/org/infinity/resource/graphics/PvrDecoder.java +++ b/src/org/infinity/resource/graphics/PvrDecoder.java @@ -17,6 +17,7 @@ import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -54,7 +55,7 @@ public static PvrDecoder loadPvr(ResourceEntry entry) { try (InputStream is = entry.getResourceDataAsStream()) { decoder = createPvrDecoder(key, is); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return decoder; @@ -76,7 +77,7 @@ public static PvrDecoder loadPvr(String fileName) { try (InputStream is = StreamUtils.getInputStream(FileManager.resolve(fileName))) { decoder = createPvrDecoder(key, is); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return decoder; @@ -95,7 +96,7 @@ public static PvrDecoder loadPvr(Path file) { try (InputStream is = StreamUtils.getInputStream(file)) { decoder = createPvrDecoder(key, is); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return decoder; @@ -117,7 +118,7 @@ public static PvrDecoder loadPvr(InputStream input) { try { decoder = createPvrDecoder(key, input); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return decoder; @@ -189,7 +190,7 @@ private static synchronized PvrDecoder createPvrDecoder(String key, InputStream } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/graphics/PvrzResource.java b/src/org/infinity/resource/graphics/PvrzResource.java index dd05f5a15..f16cad5a1 100644 --- a/src/org/infinity/resource/graphics/PvrzResource.java +++ b/src/org/infinity/resource/graphics/PvrzResource.java @@ -36,6 +36,7 @@ import org.infinity.resource.ViewableContainer; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.ReferenceSearcher; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -84,8 +85,7 @@ public void actionPerformed(ActionEvent event) { try { decompressed = Compressor.decompress(getResourceEntry().getResourceBuffer(), 0); } catch (Exception e) { - decompressed = null; - e.printStackTrace(); + Logger.error(e); } if (decompressed != null) { final String fileName = StreamUtils.replaceFileExtension(entry.getResourceName(), "PVR"); @@ -106,7 +106,7 @@ public void actionPerformed(ActionEvent event) { JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -220,7 +220,7 @@ private void showProperties() { sb.append(""); JOptionPane.showMessageDialog(panel, sb.toString(), "Properties of " + resName, JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { decoder = null; } @@ -242,7 +242,7 @@ private BufferedImage loadImage() { if (decoder != null) { decoder = null; } - e.printStackTrace(); + Logger.error(e); } } return image; diff --git a/src/org/infinity/resource/graphics/TisConvert.java b/src/org/infinity/resource/graphics/TisConvert.java index 4141ba2b3..78b2b24fc 100644 --- a/src/org/infinity/resource/graphics/TisConvert.java +++ b/src/org/infinity/resource/graphics/TisConvert.java @@ -55,6 +55,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; import org.infinity.util.tuples.Couple; @@ -168,12 +169,12 @@ public boolean isImplemented() { return implemented; } - /** Returns a reference to the {@link TilsetUpdater} instance. */ + /** Returns a reference to the {@link OverlayMapUpdater} instance. */ private OverlayMapUpdater getUpdater() { return updater; } - /** Returns a reference to the {@link TilsetConverter} instance. */ + /** Returns a reference to the {@link OverlayTileConverter} instance. */ private OverlayTileConverter getConverter() { return converter; } @@ -249,7 +250,7 @@ public static Status exportPNG(List tiles, int tileCols, Path pngFile, bo } } catch (IOException e) { retVal = Status.ERROR; - e.printStackTrace(); + Logger.error(e); } if (showProgress && progress.isCanceled()) { @@ -266,7 +267,7 @@ public static Status exportPNG(List tiles, int tileCols, Path pngFile, bo try { Files.delete(pngFile); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } @@ -317,15 +318,12 @@ public static Path makeTisFileNameValid(Path fileName) { } else if (name.length() < 2) { String fmt, newName = null; int maxNum; - switch (name.length()) { - case 0: - fmt = name + "%s02d"; - maxNum = 99; - break; - default: - fmt = name + "%s01d"; - maxNum = 9; - break; + if (name.isEmpty()) { + fmt = name + "%s02d"; + maxNum = 99; + } else { + fmt = name + "%s01d"; + maxNum = 9; } for (int i = 0; i < maxNum; i++) { String s = String.format(fmt, i) + (isNight ? "N" : "") + ext; @@ -375,7 +373,7 @@ public static ResourceEntry findWed(ResourceEntry tisEntry, boolean deepSearch) } catch (IOException e) { // do nothing } catch (Exception e) { - System.err.println(e.getClass().getName() + ": " + e.getMessage()); + Logger.warn("{}: {}", e.getClass().getName(), e.getMessage()); } } return false; @@ -607,7 +605,7 @@ public static Status convertToPaletteTis(Config config, boolean showProgress, Co tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte) 255; for (int i = 1; i < 256; i++) { - tilePalette[(i << 2) + 0] = (byte) (palette[i - 1] & 0xff); + tilePalette[(i << 2)] = (byte) (palette[i - 1] & 0xff); tilePalette[(i << 2) + 1] = (byte) ((palette[i - 1] >>> 8) & 0xff); tilePalette[(i << 2) + 2] = (byte) ((palette[i - 1] >>> 16) & 0xff); tilePalette[(i << 2) + 3] = 0; @@ -639,17 +637,17 @@ public static Status convertToPaletteTis(Config config, boolean showProgress, Co tileImageOut.flush(); } catch (Exception e) { retVal = Status.ERROR; - e.printStackTrace(); + Logger.error(e); } finally { if (showProgress) { - SwingUtilities.invokeLater(() -> progress.close()); + SwingUtilities.invokeLater(progress::close); } if (retVal == Status.ERROR) { // deleting incomplete tis file try { Files.delete(config.getTisFile()); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -700,7 +698,6 @@ public static Status convertToPvrzTis(Config config, boolean showProgress, Compo overlayConversion.getUpdater().update(wedInfo); } - final List regions = new ArrayList<>(); // marks indices of tiles that have already been processed final BitSet markedTiles = new BitSet(decoder.getTileCount()); @@ -722,7 +719,7 @@ public static Status convertToPvrzTis(Config config, boolean showProgress, Compo } } final List primaryTilesList = createTileRegions(config, tmBase); - regions.addAll(primaryTilesList); + final List regions = new ArrayList<>(primaryTilesList); if (showProgress) { SwingUtilities.invokeLater(() -> { @@ -912,11 +909,10 @@ public static Status convertToPvrzTis(Config config, boolean showProgress, Compo retVal = Status.SUCCESS; } catch (Exception e) { - retVal = Status.ERROR; - e.printStackTrace(); + Logger.error(e); } finally { if (showProgress) { - SwingUtilities.invokeLater(() -> progress.close()); + SwingUtilities.invokeLater(progress::close); } } @@ -1026,8 +1022,7 @@ private static List createTileRegions(Config config, TileMap tileMap) { regionBounds.height = numTilesY; final Point p2 = new Point(); - for (final Iterator iter = locations.iterator(); iter.hasNext(); ) { - final Point p = iter.next(); + for (final Point p : locations) { if (regionBounds.contains(p)) { final TileMapItem tileMapItem = tileMap.getTile(p); if (tileMapItem.getIndex() < 0) { @@ -1041,7 +1036,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { tm.setTile(p, tileMapItem.getIndex(), TileMapItem.FLAG_ALL); // adding left border? - p2.x = p.x - 1; p2.y = p.y; + p2.x = p.x - 1; + p2.y = p.y; if (p2.x >= 0 && (p2.x == regionBounds.x - 1 || !locations.contains(p2))) { final TileInfo ti = wedInfo.getTile(p2); final int tileIdx = (isSecondary && ti.tileSecondary >= 0) ? ti.tileSecondary : ti.getPrimaryTileIndex(framePrimary); @@ -1056,7 +1052,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding right border? - p2.x = p.x + 1; p2.y = p.y; + p2.x = p.x + 1; + p2.y = p.y; if (p2.x < width && (p2.x == regionBounds.x + regionBounds.width || !locations.contains(p2))) { final TileInfo ti = wedInfo.getTile(p2); final int tileIdx = (isSecondary && ti.tileSecondary >= 0) ? ti.tileSecondary : ti.getPrimaryTileIndex(framePrimary); @@ -1071,7 +1068,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding top border? - p2.x = p.x; p2.y = p.y - 1; + p2.x = p.x; + p2.y = p.y - 1; if (p2.y >= 0 && (p2.y == regionBounds.y - 1 || !locations.contains(p2))) { final TileInfo ti = wedInfo.getTile(p2); final int tileIdx = (isSecondary && ti.tileSecondary >= 0) ? ti.tileSecondary : ti.getPrimaryTileIndex(framePrimary); @@ -1086,7 +1084,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding bottom border? - p2.x = p.x; p2.y = p.y + 1; + p2.x = p.x; + p2.y = p.y + 1; if (p2.y < height && (p2.y == regionBounds.y + regionBounds.height || !locations.contains(p2))) { final TileInfo ti = wedInfo.getTile(p2); final int tileIdx = (isSecondary && ti.tileSecondary >= 0) ? ti.tileSecondary : ti.getPrimaryTileIndex(framePrimary); @@ -1101,7 +1100,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding top-left corner? - p2.x = p.x - 1; p2.y = p.y - 1; + p2.x = p.x - 1; + p2.y = p.y - 1; if (p2.x >= 0 && p2.y >= 0 && ((p2.x == regionBounds.x - 1 && p2.y == regionBounds.y - 1) || !locations.contains(p2))) { TileMapItem tmi1 = tm.getTile(p.x, p.y - 1); @@ -1121,7 +1121,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding top-right corner? - p2.x = p.x + 1; p2.y = p.y - 1; + p2.x = p.x + 1; + p2.y = p.y - 1; if (p2.x < width && p2.y >= 0 && ((p2.x == regionBounds.x + regionBounds.width && p2.y == regionBounds.y - 1) || !locations.contains(p2))) { TileMapItem tmi1 = tm.getTile(p.x, p.y - 1); @@ -1141,7 +1142,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding bottom-left corner? - p2.x = p.x - 1; p2.y = p.y + 1; + p2.x = p.x - 1; + p2.y = p.y + 1; if (p2.x >= 0 && p2.y < height && ((p2.x == regionBounds.x - 1 && p2.y == regionBounds.y + regionBounds.height) || !locations.contains(p2))) { TileMapItem tmi1 = tm.getTile(p.x, p.y + 1); @@ -1161,7 +1163,8 @@ private static List createTileRegions(Config config, TileMap tileMap) { } // adding bottom-right corner? - p2.x = p.x + 1; p2.y = p.y + 1; + p2.x = p.x + 1; + p2.y = p.y + 1; if (p2.x < width && p2.y < height && ((p2.x == regionBounds.x + regionBounds.width && p2.y == regionBounds.y + regionBounds.height) || !locations.contains(p2))) { @@ -1220,7 +1223,7 @@ private static void createPvrz(Config config, Path pvrzFile, List tileM throw new IllegalArgumentException("Unsupported texture size (width=" + width + ", height=" + height + ")"); } if (tileMaps.isEmpty()) { - System.err.println("PVRZ creation: No tile maps available for " + pvrzFile.getFileName()); + Logger.warn("PVRZ creation: No tile maps available for {}", pvrzFile.getFileName()); } // generating texture image @@ -1263,7 +1266,7 @@ private static void createPvrz(Config config, Path pvrzFile, List tileM try { Files.delete(pvrzFile); } catch (IOException e2) { - e2.printStackTrace(); + Logger.error(e2); } throw e; } @@ -1299,7 +1302,7 @@ private static void renderTextureTiles(Config config, Graphics2D g, TileMap tile if (tmi != null) { config.getDecoder().getTile(tmi.getIndex(), tileImg); } else { - System.err.println("No tile available at " + p); + Logger.warn("No tile available at {}", p); continue; } @@ -1368,7 +1371,7 @@ private static void createPvrzTis(Config config, List ti Objects.requireNonNull(config); Objects.requireNonNull(tileList); if (tileList.isEmpty()) { - System.out.println(getErrorMessage(config, "Tile list is empty")); + Logger.info(getErrorMessage(config, "Tile list is empty")); } try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(config.getTisFile()))) { @@ -1394,7 +1397,7 @@ private static void createPvrzTis(Config config, List ti try { Files.delete(config.getTisFile()); } catch (IOException e2) { - e2.printStackTrace(); + Logger.error(e2); } throw e; } @@ -1416,8 +1419,8 @@ private static Path generatePvrzFileName(Path tisFile, int page) { tisName = tisName.substring(0, extOfs); } if (Pattern.matches(".{2,7}", tisName)) { - String pvrzName = String.format("%s%s%02d.PVRZ", tisName.substring(0, 1), - tisName.substring(2, tisName.length()), page); + String pvrzName = String.format("%s%s%02d.PVRZ", tisName.charAt(0), + tisName.substring(2), page); return path.resolve(pvrzName); } } @@ -1747,6 +1750,7 @@ public Config(Config config) throws Exception { this.defaultTilesPerRow = config.defaultTilesPerRow; this.defaultRowCount = config.defaultRowCount; this.textureSize = config.textureSize; + this.pvrzBaseIndex = config.pvrzBaseIndex; this.borderSize = config.borderSize; this.segmentSize = config.segmentSize; this.detectBlack = config.detectBlack; @@ -1927,8 +1931,7 @@ private WedInfo initWedInfo(ResourceEntry wedEntry) throws Exception { wedInfo = new WedInfo(wed); } } catch (Exception e) { - wedInfo = null; - e.printStackTrace(); + Logger.error(e); } } @@ -1989,7 +1992,7 @@ private static OverlayConversion validateOverlayConversion(OverlayConversion con case BGEE_TO_BG2: case BG2EE_TO_BG1: case BG2EE_TO_BG2: - System.err.println("Unsupported overlay conversion mode: " + retVal); + Logger.warn("Unsupported overlay conversion mode: {}", retVal); retVal = OverlayConversion.NONE; break; default: @@ -2000,7 +2003,7 @@ private static OverlayConversion validateOverlayConversion(OverlayConversion con case BG1_TO_BG2EE: case BG2_TO_BGEE: case BG2_TO_BG2EE: - System.err.println("Unsupported overlay conversion mode: " + retVal); + Logger.warn("Unsupported overlay conversion mode: {}", retVal); retVal = OverlayConversion.NONE; break; default: @@ -2055,9 +2058,9 @@ public static class WedInfo { private final WedResource wed; /** Tileset width, in tiles. */ - private int width; + private final int width; /** Tileset height, in tiles. */ - private int height; + private final int height; /** * Creates a new {@code WedInfo} structure from a WED resource. @@ -2408,7 +2411,7 @@ public int getPrimaryTileIndex() { */ public int getPrimaryTileIndex(int frame) { if (frame >= 0) { - return tilesPrimary[Math.max(0, frame) % tilesPrimary.length]; + return tilesPrimary[frame % tilesPrimary.length]; } else { return tilePrimary; } @@ -2991,7 +2994,7 @@ public boolean hasTopBorder() { for (int x = 0; x < bounds.width; x++) { final TileMapItem tmi = tiles.get(p); if (tmi != null) { - if (tmi != null && (tmi.isBottomFlag() || tmi.isBottomLeftFlag() || tmi.isBottomRightFlag())) { + if (tmi.isBottomFlag() || tmi.isBottomLeftFlag() || tmi.isBottomRightFlag()) { retVal = Math.max(retVal, 1); } else if (tmi.isAllFlag()) { retVal = Math.max(retVal, 2); diff --git a/src/org/infinity/resource/graphics/TisDecoder.java b/src/org/infinity/resource/graphics/TisDecoder.java index 7997938a8..a08d179b5 100644 --- a/src/org/infinity/resource/graphics/TisDecoder.java +++ b/src/org/infinity/resource/graphics/TisDecoder.java @@ -10,6 +10,7 @@ import java.util.Objects; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -55,7 +56,7 @@ public static Type getType(ResourceEntry tisEntry) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return retVal; @@ -84,7 +85,7 @@ public static TisInfo getInfo(ResourceEntry tisEntry) { retVal = new TisInfo(numTiles, tileSize, tileDim); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/resource/graphics/TisResource.java b/src/org/infinity/resource/graphics/TisResource.java index ec487edcd..c81a97ca7 100644 --- a/src/org/infinity/resource/graphics/TisResource.java +++ b/src/org/infinity/resource/graphics/TisResource.java @@ -107,7 +107,8 @@ import org.infinity.resource.wed.WedResource; import org.infinity.search.ReferenceSearcher; import org.infinity.util.DataString; -import org.infinity.util.Debugging; +import org.infinity.util.DebugTimer; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.tuples.Couple; @@ -197,14 +198,14 @@ public void actionPerformed(ActionEvent event) { final TisConvert.Config config = ConvertTisDialog.show(panel.getTopLevelAncestor(), this); if (config != null) { performBackgroundTask(() -> { - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); Status status = TisConvert.convertToPaletteTis(config, true, panel.getTopLevelAncestor()); - Debugging.timerShow("TIS conversion completed", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted("TIS conversion completed")); return status; }); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Tileset conversion: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } @@ -213,14 +214,14 @@ public void actionPerformed(ActionEvent event) { final TisConvert.Config config = ConvertTisDialog.show(panel.getTopLevelAncestor(), this); if (config != null) { performBackgroundTask(() -> { - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); Status status = TisConvert.convertToPvrzTis(config, true, panel.getTopLevelAncestor()); - Debugging.timerShow("TIS conversion completed", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted("TIS conversion completed")); return status; }); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Tileset conversion: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } @@ -340,7 +341,7 @@ public void propertyChange(PropertyChangeEvent event) { retVal = Status.ERROR; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (retVal == Status.SUCCESS) { @@ -597,7 +598,7 @@ private Path getPngFileName(Component parent) { if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { retVal = fc.getSelectedFile().toPath(); if (FileEx.create(retVal).exists()) { - final String options[] = { "Overwrite", "Cancel" }; + final String[] options = { "Overwrite", "Cancel" }; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]) != 0) { retVal = null; @@ -629,7 +630,7 @@ private void initTileset() { } WindowBlocker.blockWindow(false); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); WindowBlocker.blockWindow(false); if (tileImages == null) { tileImages = new ArrayList<>(); @@ -671,6 +672,7 @@ private void initOverlayMap(WedResource wed) { wedTileMap.putIfAbsent(idx, tm); }); } catch (Exception e) { + Logger.trace(e); } } } @@ -751,7 +753,7 @@ protected Status doInBackground() throws Exception { try { retVal = operation.get(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; } @@ -833,10 +835,10 @@ private static class TisPreview { private final List tiles = new ArrayList<>(); private final TisDecoder decoder; + private final Color splitColor; + private final Object renderingHints; private int tileSize; - private Color splitColor; - private Object renderingHints; /** * Creates a tileset preview with the following defaults: @@ -941,9 +943,7 @@ public BufferedImage get(int width, int height) { for (int srcOfs = 0, dstOfs = (y * pixelsPerRow + x) * tileSize, dy = 0; dy < tileSize; srcOfs += tileSize, dstOfs += pixelsPerRow, dy++) { - for (int dx = 0; dx < tileSize; dx++) { - buffer[dstOfs + dx] = block[srcOfs + dx]; - } + System.arraycopy(block, srcOfs, buffer, dstOfs, tileSize); } } } @@ -1108,8 +1108,8 @@ private static class ConvertTisDialog extends JDialog { /** * Opens a modal dialog and returns a TIS configuration. * - * @param owner Parent {@link Window} for the dialog. - * @param decoder {@link TisDecoder} of the source tileset. + * @param owner Parent {@link Window} for the dialog. + * @param tis {@link TisDecoder} of the source tileset. * @return An initialized {@link TisConvert.Config} object if the user accepts the conversion options. Returns * {@code null} if the user cancels the operation. */ @@ -1126,7 +1126,7 @@ public static TisConvert.Config show(Component owner, TisResource tis) { dlg.setVisible(true); retVal = dlg.getConfig(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { if (dlg != null) { dlg.dispose(); @@ -1177,7 +1177,7 @@ private TisConvert.Config getConfig() { throw new Exception("Conversion not supported"); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -1215,6 +1215,7 @@ private void init() { try { tfTisFile.setText(Profile.getGameRoot().resolve(tis.entry.getResourceName()).toString()); } catch (InvalidPathException ex) { + Logger.trace(ex); } tfTisFile.addMouseMotionListener(listeners.mouseMotion); helpMap.put(tfTisFile, helpTisFile); @@ -1488,7 +1489,7 @@ private void initPvrz() { try { tisPreview = new TisPreview(tis.decoder); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } final int previewWidth = sTilesPerRow.getValue(); @@ -1931,6 +1932,7 @@ private Path validateTisFileName(String fileName, boolean strict) { retVal = null; } } catch (NullPointerException | IllegalArgumentException e) { + Logger.trace(e); } if (strict) { @@ -1944,6 +1946,7 @@ private Path validateTisFileName(String fileName, boolean strict) { retVal = null; } } catch (IllegalArgumentException e) { + Logger.trace(e); } } @@ -1951,6 +1954,7 @@ private Path validateTisFileName(String fileName, boolean strict) { try { retVal = Profile.getGameRoot().resolve("OUTPUT.TIS"); } catch (IllegalArgumentException e) { + Logger.trace(e); } } @@ -1962,7 +1966,7 @@ private Path getTisPath() { try { return Paths.get(tfTisFile.getText().trim()); } catch (InvalidPathException e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -1984,12 +1988,12 @@ private int getPvrzBaseIndex() { /** Returns whether black tiles should be detected and optimized. */ private boolean isDetectBlack() { - return (cbRemoveBlack != null) ? cbRemoveBlack.isSelected() : false; + return cbRemoveBlack != null && cbRemoveBlack.isSelected(); } /** Returns whether multithreading is used to encode DXT1 pixel data. */ private boolean isMultithreaded() { - return (cbMultithreaded != null) ? cbMultithreaded.isSelected() : false; + return cbMultithreaded != null && cbMultithreaded.isSelected(); } /** @@ -1997,7 +2001,7 @@ private boolean isMultithreaded() { * conversion. */ private boolean isAutoMode() { - return (rbAuto != null) ? rbAuto.isSelected() : true; + return rbAuto == null || rbAuto.isSelected(); } /** @@ -2005,7 +2009,7 @@ private boolean isAutoMode() { * conversion. */ private boolean isManualMode() { - return (rbManual != null) ? rbManual.isSelected() : true; + return rbManual == null || rbManual.isSelected(); } /** Returns the selected overlay conversion mode. */ @@ -2161,7 +2165,7 @@ public void mouseMoved(MouseEvent e) { try { tisPreview.setTileSize(zoom); } catch (Exception ex) { - ex.printStackTrace(); + Logger.error(ex); // revert zoom change (if possible) for (int i = 0, size = cbPreviewImageZoom.getModel().getSize(); i < size; i++) { final int value = cbPreviewImageZoom.getModel().getElementAt(cbPreviewImageZoom.getSelectedIndex()).getData(); diff --git a/src/org/infinity/resource/graphics/TisV1Decoder.java b/src/org/infinity/resource/graphics/TisV1Decoder.java index 568b071b1..747654372 100644 --- a/src/org/infinity/resource/graphics/TisV1Decoder.java +++ b/src/org/infinity/resource/graphics/TisV1Decoder.java @@ -14,6 +14,7 @@ import java.util.Objects; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * Handles legacy TIS resources (using palettized tiles). @@ -62,7 +63,7 @@ public void getTilePalette(int tileIdx, int[] buffer, boolean raw) { if (buffer != null) { int ofs = getTileOffset(tileIdx); if (ofs > 0) { - int maxLen = (buffer.length > 256) ? 256 : buffer.length; + int maxLen = Math.min(buffer.length, 256); for (int i = 0; i < maxLen; i++) { buffer[i] = tisBuffer.getInt(ofs); if (!raw) { @@ -104,8 +105,7 @@ public void getRawTileData(int tileIdx, byte[] buffer) { if (buffer != null) { int ofs = getTileOffset(tileIdx); if (ofs > 0) { - int maxSize = (buffer.length > TILE_DIMENSION * TILE_DIMENSION) ? TILE_DIMENSION * TILE_DIMENSION - : buffer.length; + int maxSize = Math.min(buffer.length, TILE_DIMENSION * TILE_DIMENSION); ofs += 4 * 256; // skipping palette data tisBuffer.position(ofs); tisBuffer.get(buffer, 0, maxSize); @@ -199,7 +199,7 @@ private void init() { workingPalette = new int[256]; workingCanvas = new BufferedImage(TILE_DIMENSION, TILE_DIMENSION, Transparency.BITMASK); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } diff --git a/src/org/infinity/resource/graphics/TisV2Decoder.java b/src/org/infinity/resource/graphics/TisV2Decoder.java index dcbb15440..d05dc70ab 100644 --- a/src/org/infinity/resource/graphics/TisV2Decoder.java +++ b/src/org/infinity/resource/graphics/TisV2Decoder.java @@ -15,6 +15,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; /** * Handles new PVRZ-based TIS resources. @@ -156,14 +157,14 @@ private void init() { tisBuffer = getResourceEntry().getResourceBuffer(); String name = getResourceEntry().getResourceRef(); - pvrzNameBase = getResourceEntry().getResourceName().substring(0, 1) + pvrzNameBase = getResourceEntry().getResourceName().charAt(0) + getResourceEntry().getResourceName().substring(2, name.length()); setType(Type.PVRZ); workingCanvas = new BufferedImage(TILE_DIMENSION, TILE_DIMENSION, BufferedImage.TYPE_INT_ARGB); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); close(); } } @@ -178,7 +179,7 @@ private PvrDecoder getPVR(int page) { return PvrDecoder.loadPvr(entry); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -245,16 +246,13 @@ private boolean updateWorkingCanvas(int tileIdx) { g = null; } } else { - if (decoder != null) { - // drawing new content - decoder.decode(workingCanvas, x, y, TILE_DIMENSION, TILE_DIMENSION); - decoder = null; - } + // drawing new content + decoder.decode(workingCanvas, x, y, TILE_DIMENSION, TILE_DIMENSION); + decoder = null; } return true; } catch (Exception e) { - e.printStackTrace(); - decoder = null; + Logger.error(e); } } } diff --git a/src/org/infinity/resource/graphics/decoder/DummyDecoder.java b/src/org/infinity/resource/graphics/decoder/DummyDecoder.java index 8d75c85dd..3e67f49a1 100644 --- a/src/org/infinity/resource/graphics/decoder/DummyDecoder.java +++ b/src/org/infinity/resource/graphics/decoder/DummyDecoder.java @@ -34,8 +34,8 @@ public boolean decode(BufferedImage image, Rectangle region) throws Exception { int[] imgData = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); int ofs = 0; - int maxX = (image.getWidth() < region.width) ? image.getWidth() : region.width; - int maxY = (image.getHeight() < region.height) ? image.getHeight() : region.height; + int maxX = Math.min(image.getWidth(), region.width); + int maxY = Math.min(image.getHeight(), region.height); for (int y = 0; y < maxY; y++) { for (int x = 0; x < maxX; x++) { imgData[ofs + x] = 0; diff --git a/src/org/infinity/resource/graphics/decoder/Etc2Decoder.java b/src/org/infinity/resource/graphics/decoder/Etc2Decoder.java index 41c95de33..f9a38f582 100644 --- a/src/org/infinity/resource/graphics/decoder/Etc2Decoder.java +++ b/src/org/infinity/resource/graphics/decoder/Etc2Decoder.java @@ -337,7 +337,7 @@ private void decodeColorBlock(long code, int[] outPixels, boolean hasTransparenc */ private void decodeColorSubBlocks(long code, int[] baseColor1, int[] baseColor2, int[] outPixels, boolean hasTransparency) { final boolean flipped = isBitSet(code, 32); - final boolean opaque = hasTransparency ? isBitSet(code, 33) : true; + final boolean opaque = !hasTransparency || isBitSet(code, 33); final int[] table = { getBits(code, 37, 3, false), getBits(code, 34, 3, false) }; final int table1Idx= (hasTransparency ? 0 : 1 << 3) | table[0]; @@ -380,7 +380,7 @@ private void decodeColorSubBlocks(long code, int[] baseColor1, int[] baseColor2, */ private void decodeColorModeT(long code, int[] outPixels, boolean hasTransparency) { final int distIdx = getBitsEx(code, false, BITS_T_D); - final boolean opaque = hasTransparency ? isBitSet(code, 33) : true; + final boolean opaque = !hasTransparency || isBitSet(code, 33); final int[] baseColor1 = { getBits(code, 48, 4, false), // b getBits(code, 52, 4, false), // g @@ -438,7 +438,7 @@ private void decodeColorModeT(long code, int[] outPixels, boolean hasTransparenc */ private void decodeColorModeH(long code, int[] outPixels, boolean hasTransparency) { final int dIdx = getBitsEx(code, false, BITS_H_D); - final boolean opaque = hasTransparency ? isBitSet(code, 33) : true; + final boolean opaque = !hasTransparency || isBitSet(code, 33); final int[] baseColor1 = { getBitsEx(code, false, BITS_H_B), // b getBitsEx(code, false, BITS_H_G), // g @@ -625,7 +625,7 @@ private static int getBitsEx(long value, boolean signed, int[] offsets) { int retVal = 0; for (int i = offsets.length - 1; i >= 0; i--) { retVal <<= 1; - retVal |= (value >>> offsets[i]) & 1; + retVal |= (int) ((value >>> offsets[i]) & 1L); } int maskMsb = 1 << (offsets.length - 1); diff --git a/src/org/infinity/resource/graphics/decoder/PvrtcDecoder.java b/src/org/infinity/resource/graphics/decoder/PvrtcDecoder.java index 23610ef1b..51aa559d6 100644 --- a/src/org/infinity/resource/graphics/decoder/PvrtcDecoder.java +++ b/src/org/infinity/resource/graphics/decoder/PvrtcDecoder.java @@ -564,27 +564,27 @@ private static void mapDecompressedData(int[] outBuffer, int width, int[][] inDa for (int x = 0; x < (wordWidth >>> 1); x++) { // map p int outOfs = (((indices[IDX_P + 1] * wordHeight) + y + (wordHeight >>> 1)) * width - + indices[IDX_P + 0] * wordWidth + x + (wordWidth >>> 1)); + + indices[IDX_P] * wordWidth + x + (wordWidth >>> 1)); int inOfs = y * wordWidth + x; outBuffer[outOfs] = (inData[inOfs][CH_A] << 24) | (inData[inOfs][CH_R] << 16) | (inData[inOfs][CH_G] << 8) | inData[inOfs][CH_B]; // map q outOfs = (((indices[IDX_Q + 1] * wordHeight) + y + (wordHeight >>> 1)) * width - + indices[IDX_Q + 0] * wordWidth + x); + + indices[IDX_Q] * wordWidth + x); inOfs = y * wordWidth + x + (wordWidth >>> 1); outBuffer[outOfs] = (inData[inOfs][CH_A] << 24) | (inData[inOfs][CH_R] << 16) | (inData[inOfs][CH_G] << 8) | inData[inOfs][CH_B]; // map r - outOfs = (((indices[IDX_R + 1] * wordHeight) + y) * width + indices[IDX_R + 0] * wordWidth + x + outOfs = (((indices[IDX_R + 1] * wordHeight) + y) * width + indices[IDX_R] * wordWidth + x + (wordWidth >>> 1)); inOfs = (y + (wordHeight >>> 1)) * wordWidth + x; outBuffer[outOfs] = (inData[inOfs][CH_A] << 24) | (inData[inOfs][CH_R] << 16) | (inData[inOfs][CH_G] << 8) | inData[inOfs][CH_B]; // map s - outOfs = (((indices[IDX_S + 1] * wordHeight) + y) * width + indices[IDX_S + 0] * wordWidth + x); + outOfs = (((indices[IDX_S + 1] * wordHeight) + y) * width + indices[IDX_S] * wordWidth + x); inOfs = (y + (wordHeight >>> 1)) * wordWidth + x + (wordWidth >>> 1); outBuffer[outOfs] = (inData[inOfs][CH_A] << 24) | (inData[inOfs][CH_R] << 16) | (inData[inOfs][CH_G] << 8) | inData[inOfs][CH_B]; diff --git a/src/org/infinity/resource/itm/ItmResource.java b/src/org/infinity/resource/itm/ItmResource.java index d20e9f4ce..dd75ec4f9 100644 --- a/src/org/infinity/resource/itm/ItmResource.java +++ b/src/org/infinity/resource/itm/ItmResource.java @@ -8,6 +8,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.List; import java.util.ListIterator; @@ -15,12 +16,12 @@ import javax.swing.JComponent; import javax.swing.JScrollPane; -import org.infinity.datatype.Bitmap; import org.infinity.datatype.ColorValue; import org.infinity.datatype.DecNumber; import org.infinity.datatype.Flag; import org.infinity.datatype.IdsBitmap; import org.infinity.datatype.IsNumeric; +import org.infinity.datatype.ItemTypeBitmap; import org.infinity.datatype.ResourceRef; import org.infinity.datatype.SectionCount; import org.infinity.datatype.SectionOffset; @@ -47,6 +48,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.StringTable; import org.infinity.util.Table2da; @@ -111,24 +113,6 @@ public final class ItmResource extends AbstractStruct implements Resource, HasCh public static final String ITM_SPEAKER_NAME = "Speaker name"; public static final String ITM_WEAPON_COLOR = "Weapon color"; - 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" }; - public static final String[] FLAGS_ARRAY = { "None", "Critical item", "Two-handed", "Droppable", "Displayable", "Cursed", "Not copyable", "Magical", "Left-handed", "Silver", "Cold iron", "Off-handed", "Conversable", "EE: Fake two-handed", "EE: Forbid off-hand weapon", "", "EE: Adamantine", null, null, null, null, null, null, @@ -352,10 +336,10 @@ public int read(ByteBuffer buffer, int offset) throws Exception { addField(new ResourceRef(buffer, 16, ITM_DROP_SOUND, "WAV")); if (Profile.getGame() == Profile.Game.PSTEE) { addField(new Flag(buffer, 24, 4, ITM_FLAGS, FLAGS_PSTEE_ARRAY)); - addField(new Bitmap(buffer, 28, 2, ITM_CATEGORY, CATEGORIES_ARRAY)); + addField(new ItemTypeBitmap(buffer, 28, 2, ITM_CATEGORY)); } else { addField(new Flag(buffer, 24, 4, ITM_FLAGS, FLAGS11_ARRAY)); - addField(new Bitmap(buffer, 28, 2, ITM_CATEGORY, CATEGORIES11_ARRAY)); + addField(new ItemTypeBitmap(buffer, 28, 2, ITM_CATEGORY)); } addField(new Flag(buffer, 30, 4, ITM_UNUSABLE_BY, USABILITY11_ARRAY)); addField(new TextBitmap(buffer, 34, 2, ITM_EQUIPPED_APPEARANCE, Profile.getEquippedAppearanceMap())); @@ -363,7 +347,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { addField(new ResourceRef(buffer, 16, ITM_USED_UP_ITEM, "ITM")); addField( new Flag(buffer, 24, 4, ITM_FLAGS, IdsMapCache.getUpdatedIdsFlags(FLAGS_ARRAY, "ITEMFLAG.IDS", 4, false, false))); - addField(new Bitmap(buffer, 28, 2, ITM_CATEGORY, CATEGORIES_ARRAY)); + addField(new ItemTypeBitmap(buffer, 28, 2, ITM_CATEGORY)); if (isV20) { addField(new Flag(buffer, 30, 4, ITM_UNUSABLE_BY, USABILITY20_ARRAY)); } else { @@ -433,7 +417,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } offset = abilOffset.getValue(); - Ability abilities[] = new Ability[abilCount.getValue()]; + Ability[] abilities = new Ability[abilCount.getValue()]; for (int i = 0; i < abilities.length; i++) { abilities[i] = new Ability(this, buffer, offset, i); offset = abilities[i].getEndOffset(); @@ -508,6 +492,7 @@ private void updateKitUsability(String[] kits, int offset, int count, boolean fi try { desc = StringTable.getStringRef(strref); } catch (IndexOutOfBoundsException e) { + Logger.trace(e); } } if (desc == null || desc.isEmpty()) { @@ -583,14 +568,14 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = SearchOptions.ITM_Name; o = searchOptions.getOption(key); StructEntry struct = itm.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchString(struct, o, false, false); + retVal = SearchOptions.Utils.matchString(struct, o, false, false); } if (retVal) { key = SearchOptions.ITM_Appearance; o = searchOptions.getOption(key); StructEntry struct = itm.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchString(struct, o, true, true); + retVal = SearchOptions.Utils.matchString(struct, o, true, true); } String[] keyList = new String[] { SearchOptions.ITM_Flags, SearchOptions.ITM_Unusable, @@ -601,7 +586,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = itm.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -616,7 +601,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = itm.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { break; } @@ -633,13 +618,13 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (!found) { if (effect != null) { StructEntry struct = effect.getAttribute(SearchOptions.getResourceName(key), false); - found |= SearchOptions.Utils.matchNumber(struct, o); + found = SearchOptions.Utils.matchNumber(struct, o); } } else { break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -664,9 +649,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear final int abilityOptions = keyList.length; // number of supported spell ability options boolean[][] abilityMatches = new boolean[abilities.length][abilityOptions]; for (int i = 0; i < abilities.length; i++) { - for (int j = 0; j < abilityMatches[i].length; j++) { - abilityMatches[i][j] = false; - } + Arrays.fill(abilityMatches[i], false); } for (int i = 0; i < abilities.length; i++) { @@ -700,9 +683,6 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear // evaluating collected results boolean[] foundSingle = new boolean[abilityMatches.length]; // for single ability option - for (int i = 0; i < foundSingle.length; i++) { - foundSingle[i] = false; - } boolean[] foundMulti = new boolean[abilityOptions]; // for multiple abilities option for (int i = 0; i < foundMulti.length; i++) { foundMulti[i] = (abilityOption.getOption(keyList[i]) == null); @@ -730,18 +710,18 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear } resultMulti |= !hasAbilityOptions; - Boolean isAbilitySingle; + boolean isAbilitySingle; o = abilityOption.getOption(SearchOptions.ITM_Ability_MatchSingle); - if (o != null && o instanceof Boolean) { + if (o instanceof Boolean) { isAbilitySingle = (Boolean) o; } else { isAbilitySingle = false; } if (isAbilitySingle) { - retVal &= resultSingle; + retVal = resultSingle; } else { - retVal &= resultMulti; + retVal = resultMulti; } } @@ -751,7 +731,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(itm, o); + retVal = SearchOptions.Utils.matchCustomFilter(itm, o); } else { break; } @@ -759,6 +739,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/itm/Viewer.java b/src/org/infinity/resource/itm/Viewer.java index ad7614481..a38d31c96 100644 --- a/src/org/infinity/resource/itm/Viewer.java +++ b/src/org/infinity/resource/itm/Viewer.java @@ -43,7 +43,7 @@ final class Viewer extends JPanel { JPanel propertiesPanel = makeFieldPanel(itm); // Icons panel - JComponent itemIconPanel = ViewerUtil.makeBamPanel((ResourceRef) itm.getAttribute(ItmResource.ITM_ICON), 1, 1); + JComponent itemIconPanel = ViewerUtil.makeMaxBamPanel((ResourceRef) itm.getAttribute(ItmResource.ITM_ICON)); JComponent groundIconPanel = ViewerUtil.makeBamPanel((ResourceRef) itm.getAttribute(ItmResource.ITM_ICON_GROUND), 1); JPanel iconsPanel = new JPanel(new GridLayout(2, 1, 0, 6)); iconsPanel.add(itemIconPanel); diff --git a/src/org/infinity/resource/itm/ViewerAbility.java b/src/org/infinity/resource/itm/ViewerAbility.java index 8e23f7ff7..b27265a99 100644 --- a/src/org/infinity/resource/itm/ViewerAbility.java +++ b/src/org/infinity/resource/itm/ViewerAbility.java @@ -22,6 +22,7 @@ import org.infinity.resource.AbstractAbility; import org.infinity.resource.Effect; import org.infinity.resource.StructEntry; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.Table2da; import org.infinity.util.Table2daCache; @@ -31,8 +32,7 @@ final class ViewerAbility extends JPanel { JPanel fieldPanel = makeFieldPanel(ability); JPanel effectsPanel = ViewerUtil.makeListPanel("Effects", ability, Effect.class, EffectType.EFFECT_TYPE); JComponent iconPanel = ViewerUtil.makeBamPanel((ResourceRef) ability.getAttribute(AbstractAbility.ABILITY_ICON), 0); - JComponent boxPanel1 = ViewerUtil.makeCheckPanel((Flag) ability.getAttribute(AbstractAbility.ABILITY_TYPE_FLAGS), - 1); + JComponent boxPanel1 = ViewerUtil.makeCheckPanel((Flag) ability.getAttribute(AbstractAbility.ABILITY_TYPE_FLAGS), 1); JPanel flagPanel = ViewerUtil.makeCheckPanel((Flag) ability.getAttribute(Ability.ITM_ABIL_FLAGS), 1); JPanel boxPanel2 = new JPanel(new GridLayout(0, 1, 0, 3)); @@ -125,6 +125,7 @@ private static String getAbilityName(Ability ability) { try { number = Integer.parseInt(value); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } strrefs[col - 1] = number; } @@ -140,6 +141,7 @@ private static String getAbilityName(Ability ability) { try { number = Integer.parseInt(value); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } if (number >= 0 && number < strrefs.length) { int strref = strrefs[number]; diff --git a/src/org/infinity/resource/key/AbstractBIFFReader.java b/src/org/infinity/resource/key/AbstractBIFFReader.java index f53fe9e38..35e190eb8 100644 --- a/src/org/infinity/resource/key/AbstractBIFFReader.java +++ b/src/org/infinity/resource/key/AbstractBIFFReader.java @@ -170,7 +170,7 @@ protected void addEntry(Entry entry) { // Internally used to retrieve stored BIFF entry information protected Entry getEntry(int locator) { - return mapEntries.get(Integer.valueOf(locator & 0xfffff)); + return mapEntries.get(locator & 0xfffff); } // Internally used to remove all entries from the map @@ -185,14 +185,15 @@ private static Type detectBiffType(Path file) throws Exception { try (InputStream is = StreamUtils.getInputStream(file)) { String sigver = StreamUtils.readString(is, 8); - if ("BIFFV1 ".equals(sigver)) { - return Type.BIFF; - } else if ("BIF V1.0".equals(sigver)) { - return Type.BIF; - } else if ("BIFCV1.0".equals(sigver)) { - return Type.BIFC; - } else { - throw new IOException("Unsupported BIFF file: " + file); + switch (sigver) { + case "BIFFV1 ": + return Type.BIFF; + case "BIF V1.0": + return Type.BIF; + case "BIFCV1.0": + return Type.BIFC; + default: + throw new IOException("Unsupported BIFF file: " + file); } } } diff --git a/src/org/infinity/resource/key/BIFCReader.java b/src/org/infinity/resource/key/BIFCReader.java index d8f2c7c19..8fc3c48ba 100644 --- a/src/org/infinity/resource/key/BIFCReader.java +++ b/src/org/infinity/resource/key/BIFCReader.java @@ -120,8 +120,7 @@ public InputStream getResourceAsStream(int locator) throws IOException { InputStream is2 = new BifcInputStream( new BufferedInputStream(Files.newInputStream(getFile(), StandardOpenOption.READ)), entry.offset, entry.count * entry.size); - InputStream is = new SequenceInputStream(is1, is2); - return is; + return new SequenceInputStream(is1, is2); } else { return new BifcInputStream(new BufferedInputStream(Files.newInputStream(getFile(), StandardOpenOption.READ)), entry.offset, entry.size); @@ -146,7 +145,7 @@ private void init() throws Exception { int remaining = entryOfs - curOfs; while (remaining > 0) { long n = is.skip(remaining); - remaining -= n; + remaining -= (int) n; } // reading file entries @@ -231,7 +230,7 @@ public int read() throws IOException { } @Override - public int read(byte b[], int off, int len) throws IOException { + public int read(byte[] b, int off, int len) throws IOException { if (available() > 0) { return getData(b, off, len); } @@ -329,7 +328,7 @@ private boolean updateBuffer(boolean skipOnly, int condition) throws Exception { int remaining = compSize; while (remaining > 0) { long n = input.skip(remaining); - remaining -= n; + remaining -= (int) n; } } else { if (inBuffer == null || inBuffer.length < compSize) { diff --git a/src/org/infinity/resource/key/BIFFEntry.java b/src/org/infinity/resource/key/BIFFEntry.java index 55c54c7a7..e2a8ba1a3 100644 --- a/src/org/infinity/resource/key/BIFFEntry.java +++ b/src/org/infinity/resource/key/BIFFEntry.java @@ -16,6 +16,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.Writeable; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -218,8 +219,7 @@ public void updateBIFF(Path keyFile, int index, ByteBuffer buffer, int offset, b try { this.fileSize = (int) Files.size(this.biffFile); } catch (IOException e) { - System.err.println(String.format("Could not determine file size: %s", this.biffFile)); - e.printStackTrace(); + Logger.error(e, "Could not determine file size: {}", this.biffFile); } } } diff --git a/src/org/infinity/resource/key/BIFFReader.java b/src/org/infinity/resource/key/BIFFReader.java index 9c2399c3a..79fc51c01 100644 --- a/src/org/infinity/resource/key/BIFFReader.java +++ b/src/org/infinity/resource/key/BIFFReader.java @@ -16,6 +16,7 @@ import org.infinity.NearInfinity; import org.infinity.gui.WindowBlocker; +import org.infinity.util.Logger; import org.infinity.util.io.ByteBufferInputStream; import org.infinity.util.io.StreamUtils; @@ -72,6 +73,7 @@ public int getBIFFSize() { try { return (int) Files.size(getFile()); } catch (IOException e) { + Logger.trace(e); } return -1; } diff --git a/src/org/infinity/resource/key/BIFFResourceEntry.java b/src/org/infinity/resource/key/BIFFResourceEntry.java index 5368c2fa7..d4d3da189 100644 --- a/src/org/infinity/resource/key/BIFFResourceEntry.java +++ b/src/org/infinity/resource/key/BIFFResourceEntry.java @@ -20,6 +20,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; import org.infinity.resource.Writeable; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -154,7 +155,7 @@ public Path getActualPath(boolean ignoreOverride) { try { return ResourceFactory.getKeyfile().getBIFFFile(getBIFFEntry()).getFile(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -177,11 +178,11 @@ public long getResourceSize(boolean ignoreOverride) { if (info.length == 1) { retVal = info[0]; } else if (info.length == 2) { - retVal = info[0] * info[1] + 0x18; + retVal = (long) info[0] * info[1] + 0x18; } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return retVal; } diff --git a/src/org/infinity/resource/key/BIFFWriter.java b/src/org/infinity/resource/key/BIFFWriter.java index 7f38d7654..07a137465 100644 --- a/src/org/infinity/resource/key/BIFFWriter.java +++ b/src/org/infinity/resource/key/BIFFWriter.java @@ -20,6 +20,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -30,9 +31,9 @@ public final class BIFFWriter { private final Map tileResources = new HashMap<>(); private final AbstractBIFFReader.Type format; - private static byte[] compress(byte data[]) { + private static byte[] compress(byte[] data) { Deflater deflater = new Deflater(); - byte compr[] = new byte[data.length * 2]; + byte[] compr = new byte[data.length * 2]; deflater.setInput(data); deflater.finish(); int clength = deflater.deflate(compr); @@ -71,7 +72,7 @@ private static void compressBIFC(Path biff, Path compr) throws Exception { StreamUtils.writeString(os, "V1.0", 4); StreamUtils.writeInt(os, (int) Files.size(biff)); try (InputStream is = StreamUtils.getInputStream(biff)) { - byte block[] = readBytes(is, 8192); + byte[] block = readBytes(is, 8192); while (block.length != 0) { byte[] compressed = compress(block); StreamUtils.writeInt(os, block.length); @@ -165,12 +166,14 @@ public void write() throws Exception { try { Files.delete(dummyFile); } catch (IOException e) { + Logger.trace(e); } } if (compressedFile != null && FileEx.create(compressedFile).isFile()) { try { Files.delete(compressedFile); } catch (IOException e) { + Logger.trace(e); } } } @@ -197,7 +200,7 @@ private void writeBIFF(Path file) throws Exception { BIFFResourceEntry newentry = reloadNode(resourceEntry, index); StreamUtils.writeInt(os, newentry.getLocator()); StreamUtils.writeInt(os, offset); // Offset - int info[] = resourceEntry.getResourceInfo(entry.getValue()); + int[] info = resourceEntry.getResourceInfo(entry.getValue()); offset += info[0]; StreamUtils.writeInt(os, info[0]); // Size StreamUtils.writeShort(os, (short) ResourceFactory.getKeyfile().getExtensionType(resourceEntry.getExtension())); @@ -210,7 +213,7 @@ private void writeBIFF(Path file) throws Exception { BIFFResourceEntry newentry = reloadNode(resourceEntry, index); StreamUtils.writeInt(os, newentry.getLocator()); StreamUtils.writeInt(os, offset); // Offset - int info[] = resourceEntry.getResourceInfo(entry.getValue()); + int[] info = resourceEntry.getResourceInfo(entry.getValue()); StreamUtils.writeInt(os, info[0]); // Number of tiles StreamUtils.writeInt(os, info[1]); // Size of each tile (in bytes) offset += info[0] * info[1]; @@ -224,7 +227,7 @@ private void writeBIFF(Path file) throws Exception { for (final Map.Entry entry : tileResources.entrySet()) { final ResourceEntry resourceEntry = entry.getKey(); ByteBuffer buffer = resourceEntry.getResourceBuffer(entry.getValue()); - int info[] = resourceEntry.getResourceInfo(entry.getValue()); + int[] info = resourceEntry.getResourceInfo(entry.getValue()); int size = info[0] * info[1]; int toSkip = buffer.limit() - size; if (toSkip > 0) { diff --git a/src/org/infinity/resource/key/BIFReader.java b/src/org/infinity/resource/key/BIFReader.java index ff24dec83..bafb659f2 100644 --- a/src/org/infinity/resource/key/BIFReader.java +++ b/src/org/infinity/resource/key/BIFReader.java @@ -107,7 +107,7 @@ public ByteBuffer getResourceBuffer(int locator) throws IOException { int remaining = entry.offset; while (remaining > 0) { long n = iis.skip(entry.offset); - remaining -= n; + remaining -= (int) n; } StreamUtils.readBytes(iis, buffer); } finally { @@ -140,7 +140,7 @@ private void init() throws Exception { int remaining = entryOfs - curOfs; while (remaining > 0) { long n = iis.skip(entryOfs - curOfs); - remaining -= n; + remaining -= (int) n; } // reading file entries diff --git a/src/org/infinity/resource/key/FileResourceEntry.java b/src/org/infinity/resource/key/FileResourceEntry.java index fec931674..632b850c6 100644 --- a/src/org/infinity/resource/key/FileResourceEntry.java +++ b/src/org/infinity/resource/key/FileResourceEntry.java @@ -21,6 +21,7 @@ import org.infinity.gui.menu.OverrideMode; import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; +import org.infinity.util.Logger; import org.infinity.util.io.ByteBufferInputStream; import org.infinity.util.io.StreamUtils; @@ -56,7 +57,7 @@ public long getResourceSize(boolean ignoreOverride) { try { return Files.size(file); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } return -1L; } diff --git a/src/org/infinity/resource/key/Keyfile.java b/src/org/infinity/resource/key/Keyfile.java index 31cbc8bb4..977da67bc 100644 --- a/src/org/infinity/resource/key/Keyfile.java +++ b/src/org/infinity/resource/key/Keyfile.java @@ -27,6 +27,7 @@ import org.infinity.icon.Icons; import org.infinity.resource.ResourceFactory; import org.infinity.util.IntegerHashMap; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; @@ -348,7 +349,7 @@ public void addBIFFEntry(BIFFEntry entry) { // try { // Files.deleteIfExists(file); // } catch (IOException e) { - // e.printStackTrace(); + // Logger.error(e); // } // } // }); @@ -368,7 +369,7 @@ public void addBIFFEntry(BIFFEntry entry) { // // return true; // } catch (IOException e) { - // e.printStackTrace(); + // Logger.error(e); // } // // return false; @@ -380,12 +381,12 @@ public BIFFEntry[] getBIFFEntriesSorted() { biffList.addAll(list); } Collections.sort(biffList); - return biffList.toArray(new BIFFEntry[biffList.size()]); + return biffList.toArray(new BIFFEntry[0]); } public BIFFEntry getBIFFEntry(Path keyFile, int index) { List biffs = getBIFFList(keyFile, false); - if (biffs != null && biffs.size() > 0) { + if (biffs != null && !biffs.isEmpty()) { return biffs.get(index); } return null; @@ -455,7 +456,7 @@ private void cacheBIFFs() { try { AbstractBIFFReader.open(biffPath); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/key/ResourceEntry.java b/src/org/infinity/resource/key/ResourceEntry.java index 818313e37..dddac92f7 100644 --- a/src/org/infinity/resource/key/ResourceEntry.java +++ b/src/org/infinity/resource/key/ResourceEntry.java @@ -32,6 +32,7 @@ import org.infinity.resource.sto.StoResource; import org.infinity.resource.text.PlainTextResource; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; @@ -88,7 +89,7 @@ static int[] getLocalFileInfo(Path file) { return new int[] { (int) ch.size() }; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return null; @@ -175,29 +176,37 @@ public int[] getResourceInfo() throws Exception { public String getSearchString() { if (searchString == null) { try { - String extension = getExtension().toUpperCase(); - if (extension.equals("CRE") || extension.equals("CHR")) { - try (InputStream is = getResourceDataAsStream()) { - searchString = CreResource.getSearchString(is); - } - } else if (extension.equals("ITM")) { - try (InputStream is = getResourceDataAsStream()) { - searchString = ItmResource.getSearchString(is); - } - } else if (extension.equals("SPL")) { - try (InputStream is = getResourceDataAsStream()) { - searchString = SplResource.getSearchString(is); - } - } else if (extension.equals("STO")) { - try (InputStream is = getResourceDataAsStream()) { - searchString = StoResource.getSearchString(is); - } - } else if (extension.equals("ARE")) { - searchString = AreResource.getSearchString(this); - } else if (extension.equals("PRO")) { - searchString = ProResource.getSearchString(this); - } else if (extension.equals("INI")) { - searchString = PlainTextResource.getSearchString(this); + switch (getExtension().toUpperCase()) { + case "CRE": + case "CHR": + try (InputStream is = getResourceDataAsStream()) { + searchString = CreResource.getSearchString(is); + } + break; + case "ITM": + try (InputStream is = getResourceDataAsStream()) { + searchString = ItmResource.getSearchString(is); + } + break; + case "SPL": + try (InputStream is = getResourceDataAsStream()) { + searchString = SplResource.getSearchString(is); + } + break; + case "STO": + try (InputStream is = getResourceDataAsStream()) { + searchString = StoResource.getSearchString(is); + } + break; + case "ARE": + searchString = AreResource.getSearchString(this); + break; + case "PRO": + searchString = ProResource.getSearchString(this); + break; + case "INI": + searchString = PlainTextResource.getSearchString(this); + break; } } catch (Exception e) { if ((NearInfinity.getInstance() != null) && !BrowserMenuBar.getInstance().getOptions().ignoreReadErrors()) { @@ -205,7 +214,7 @@ public String getSearchString() { JOptionPane.ERROR_MESSAGE); } searchString = "Error"; - e.printStackTrace(); + Logger.error(e); } } return searchString; @@ -249,10 +258,10 @@ public boolean isVisible() { // 2. NOT Resource type part of skippedExtensions // 3. Filename length is valid int resLen = getResourceRef().length(); - boolean bRet = (BrowserMenuBar.isInstantiated() && BrowserMenuBar.getInstance().getOptions().showUnknownResourceTypes()) - || Profile.isResourceTypeSupported(getExtension()) - && !SKIPPED_EXTENSIONS.contains(getExtension().toUpperCase(Locale.ENGLISH)) && (resLen >= 0 && resLen <= 8); - return bRet; + return BrowserMenuBar.isInstantiated() && BrowserMenuBar.getInstance().getOptions().showUnknownResourceTypes() || + Profile.isResourceTypeSupported(getExtension()) && + !SKIPPED_EXTENSIONS.contains(getExtension().toUpperCase(Locale.ENGLISH)) && + resLen <= 8; } protected abstract Path getActualPath(boolean ignoreOverride); diff --git a/src/org/infinity/resource/key/ResourceTreeFolder.java b/src/org/infinity/resource/key/ResourceTreeFolder.java index 3abb8922f..c5410efd1 100644 --- a/src/org/infinity/resource/key/ResourceTreeFolder.java +++ b/src/org/infinity/resource/key/ResourceTreeFolder.java @@ -163,7 +163,7 @@ public boolean contains(Object o) { public boolean containsAll(Collection c) { boolean bRet = true; for (final Object o : c) { - bRet &= contains(o); + bRet = contains(o); if (!bRet) { break; } diff --git a/src/org/infinity/resource/key/ResourceTreeModel.java b/src/org/infinity/resource/key/ResourceTreeModel.java index ef8052a73..ddb515c2f 100644 --- a/src/org/infinity/resource/key/ResourceTreeModel.java +++ b/src/org/infinity/resource/key/ResourceTreeModel.java @@ -23,6 +23,7 @@ import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.FileEx; @@ -111,7 +112,7 @@ public void addDirectory(ResourceTreeFolder parentFolder, Path directory, boolea parentFolder.sortChildren(true); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); return; } } @@ -182,7 +183,7 @@ public ResourceTreeFolder addFolder(ResourceTreeFolder parent, String folderName } ResourceTreeFolder folder = getFolder(parent, folderName); if (folder == null) { - if (folderName.length() > 0) { + if (!folderName.isEmpty()) { folderName = Character.toUpperCase(folderName.charAt(0)) + folderName.substring(1); } folder = new ResourceTreeFolder(parent, folderName); diff --git a/src/org/infinity/resource/mus/Entry.java b/src/org/infinity/resource/mus/Entry.java index e52b6dc96..a3d282566 100644 --- a/src/org/infinity/resource/mus/Entry.java +++ b/src/org/infinity/resource/mus/Entry.java @@ -67,8 +67,7 @@ private static AudioBuffer getCacheEntry(Path path, String name) { if (name != null) { Path key = getCacheKey(path, name); if (BufferCache.containsKey(key)) { - AudioBuffer ab = BufferCache.get(key); - return ab; + return BufferCache.get(key); } } return null; diff --git a/src/org/infinity/resource/mus/MusResource.java b/src/org/infinity/resource/mus/MusResource.java index 4707a64c4..0d4c4cfc1 100644 --- a/src/org/infinity/resource/mus/MusResource.java +++ b/src/org/infinity/resource/mus/MusResource.java @@ -15,7 +15,7 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -46,6 +46,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.search.SongReferenceSearcher; import org.infinity.search.TextResourceSearcher; +import org.infinity.util.Logger; import org.infinity.util.Table2da; import org.infinity.util.io.StreamUtils; @@ -241,7 +242,7 @@ public void itemStateChanged(ItemEvent event) { final List files = ResourceFactory.getResources(entry.getExtension()); new TextResourceSearcher(files, panel.getTopLevelAncestor()); } else if (bpmFind.getSelectedItem() == iFindThis) { - new TextResourceSearcher(Arrays.asList(entry), panel.getTopLevelAncestor()); + new TextResourceSearcher(Collections.singletonList(entry), panel.getTopLevelAncestor()); } else if (bpmFind.getSelectedItem() == iFindReference) { searchReferences(panel.getTopLevelAncestor()); } @@ -278,6 +279,7 @@ public void highlightText(int linenr, String highlightText) { } highlightText(startOfs, endOfs); } catch (BadLocationException ble) { + Logger.trace(ble); } } @@ -288,6 +290,7 @@ public void highlightText(int startOfs, int endOfs) { editor.moveCaretPosition(endOfs - 1); editor.getCaret().setSelectionVisible(true); } catch (IllegalArgumentException e) { + Logger.trace(e); } } diff --git a/src/org/infinity/resource/mus/Viewer.java b/src/org/infinity/resource/mus/Viewer.java index 5025189d5..8ffe83718 100644 --- a/src/org/infinity/resource/mus/Viewer.java +++ b/src/org/infinity/resource/mus/Viewer.java @@ -30,6 +30,7 @@ import org.infinity.gui.menu.BrowserMenuBar; import org.infinity.icon.Icons; import org.infinity.resource.sound.AudioPlayer; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.SimpleListModel; @@ -119,7 +120,7 @@ public void run() { } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error during playback", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } player.stopPlay(); setPlayButtonState(false); @@ -163,7 +164,7 @@ private boolean parseMusFile(MusResource mus) { String dir = getNextToken(tokenizer, true); listModel.clear(); entryList.clear(); - int count = Integer.valueOf(getNextToken(tokenizer, true)); + int count = Integer.parseInt(getNextToken(tokenizer, true)); for (int i = 0; i < count; i++) { if (isClosed()) { return false; @@ -182,7 +183,7 @@ private boolean parseMusFile(MusResource mus) { try { entry.init(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(getTopLevelAncestor(), "Error loading " + entry.toString() + '\n' + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } diff --git a/src/org/infinity/resource/other/EffResource.java b/src/org/infinity/resource/other/EffResource.java index 98000b95a..c030263c3 100644 --- a/src/org/infinity/resource/other/EffResource.java +++ b/src/org/infinity/resource/other/EffResource.java @@ -22,6 +22,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; /** * This resource describes an effect (opcode) and its parameters. The resource of version 1 is only ever found embedded @@ -119,7 +120,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear } else { struct = eff.getAttribute(SearchOptions.getResourceName(key), false); } - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { break; } @@ -129,7 +130,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = SearchOptions.EFF_SaveType; o = searchOptions.getOption(key); StructEntry struct = eff.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } keyList = new String[] { SearchOptions.EFF_Resource1, SearchOptions.EFF_Resource2, @@ -145,7 +146,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear } else { struct = eff.getAttribute(SearchOptions.getResourceName(key), false); } - retVal &= SearchOptions.Utils.matchString(struct, o, false, false); + retVal = SearchOptions.Utils.matchString(struct, o, false, false); } else { break; } @@ -157,7 +158,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(eff, o); + retVal = SearchOptions.Utils.matchCustomFilter(eff, o); } else { break; } @@ -165,6 +166,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/other/TtfResource.java b/src/org/infinity/resource/other/TtfResource.java index 933e5f50f..4f2a6a3eb 100644 --- a/src/org/infinity/resource/other/TtfResource.java +++ b/src/org/infinity/resource/other/TtfResource.java @@ -39,6 +39,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.ViewableContainer; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; public class TtfResource implements Resource, DocumentListener, ActionListener { private static final ButtonPanel.Control PROPERTIES = ButtonPanel.Control.CUSTOM_1; @@ -64,7 +65,7 @@ public TtfResource(ResourceEntry entry) throws Exception { font = Font.createFont(Font.TRUETYPE_FONT, is); } catch (Exception e) { font = null; - e.printStackTrace(); + Logger.error(e); throw new Exception("Invalid TTF resource"); } @@ -148,6 +149,7 @@ public void insertUpdate(DocumentEvent event) { try { updateText(event.getDocument().getText(0, event.getDocument().getLength())); } catch (BadLocationException e) { + Logger.trace(e); } } @@ -156,6 +158,7 @@ public void removeUpdate(DocumentEvent event) { try { updateText(event.getDocument().getText(0, event.getDocument().getLength())); } catch (BadLocationException e) { + Logger.trace(e); } } @@ -164,6 +167,7 @@ public void changedUpdate(DocumentEvent event) { try { updateText(event.getDocument().getText(0, event.getDocument().getLength())); } catch (BadLocationException e) { + Logger.trace(e); } } @@ -183,7 +187,7 @@ private void updateText(String text) { try { doc.remove(0, doc.getLength()); } catch (BadLocationException e) { - e.printStackTrace(); + Logger.error(e); } } @@ -198,7 +202,7 @@ private void updateText(String text) { doc.insertString(pos, label, as); pos += label.length(); } catch (BadLocationException e) { - e.printStackTrace(); + Logger.error(e); } as = new SimpleAttributeSet(); @@ -210,7 +214,7 @@ private void updateText(String text) { doc.insertString(pos, "\n\n", as); pos += 2; } catch (BadLocationException e) { - e.printStackTrace(); + Logger.error(e); } } tpDisplay.setCaretPosition(0); diff --git a/src/org/infinity/resource/other/UnknownResource.java b/src/org/infinity/resource/other/UnknownResource.java index cfd7a466a..015721c06 100644 --- a/src/org/infinity/resource/other/UnknownResource.java +++ b/src/org/infinity/resource/other/UnknownResource.java @@ -44,6 +44,7 @@ import org.infinity.resource.Writeable; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.StreamUtils; @@ -78,7 +79,7 @@ public UnknownResource(ResourceEntry entry) throws Exception { this.entry = entry; int[] data = this.entry.getResourceInfo(); if (data != null && data.length > 0) { - entrySize = (data.length == 1) ? data[0] : (data[0] * data[1]); + entrySize = (data.length == 1) ? data[0] : ((long) data[0] * data[1]); } else { entrySize = 0L; } @@ -337,7 +338,7 @@ private void synchronizeData(int tabIndex) { hexViewer.setCurrentOffset(0L); panelRaw.add(hexViewer, BorderLayout.CENTER); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { WindowBlocker.blockWindow(false); } @@ -407,7 +408,7 @@ protected Void doInBackground() throws Exception { editor.discardAllEdits(); // don't undo loading operation success = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (success) { setEditorActive(true); diff --git a/src/org/infinity/resource/other/VvcResource.java b/src/org/infinity/resource/other/VvcResource.java index 457e7e122..19ef1a8fd 100644 --- a/src/org/infinity/resource/other/VvcResource.java +++ b/src/org/infinity/resource/other/VvcResource.java @@ -25,6 +25,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sound.SoundResource; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; /** * This resource describes visual "spell casting" effects ({@link BamResource BAM} files) with optional sounds @@ -201,7 +202,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = vvc.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -213,7 +214,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(vvc, o); + retVal = SearchOptions.Utils.matchCustomFilter(vvc, o); } else { break; } @@ -221,6 +222,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/pro/ProResource.java b/src/org/infinity/resource/pro/ProResource.java index 8d2fda849..c6cb01296 100644 --- a/src/org/infinity/resource/pro/ProResource.java +++ b/src/org/infinity/resource/pro/ProResource.java @@ -38,6 +38,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; /** * This resource describes projectiles, and the files are referenced spells and projectile weapons. Projectile files can @@ -158,7 +159,7 @@ public boolean valueUpdated(UpdateEvent event) { struct.addDatatype(new ProAreaType(), struct.getFields().size()); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return false; } } else if (proType.getValue() == 2L) { // single target @@ -171,7 +172,7 @@ public boolean valueUpdated(UpdateEvent event) { try { struct.addDatatype(new ProSingleType(), struct.getFields().size()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return false; } } @@ -403,9 +404,9 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear o = searchOptions.getOption(key); if (structList[idx] != null) { StructEntry struct = structList[idx].getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { - retVal &= (o == null); + retVal = (o == null); } } else { break; @@ -420,9 +421,9 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear o = searchOptions.getOption(key); if (structList[idx] != null) { StructEntry struct = structList[idx].getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { - retVal &= (o == null); + retVal = (o == null); } } else { break; @@ -434,9 +435,9 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear o = searchOptions.getOption(key); if (single != null) { StructEntry struct = single.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchResourceRef(struct, o, false); + retVal = SearchOptions.Utils.matchResourceRef(struct, o, false); } else { - retVal &= (o == null); + retVal = (o == null); } } @@ -446,7 +447,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(pro, o); + retVal = SearchOptions.Utils.matchCustomFilter(pro, o); } else { break; } @@ -454,6 +455,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/sav/IOHandler.java b/src/org/infinity/resource/sav/IOHandler.java index 82f37fece..a9af73b28 100644 --- a/src/org/infinity/resource/sav/IOHandler.java +++ b/src/org/infinity/resource/sav/IOHandler.java @@ -21,6 +21,7 @@ import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.FileDeletionHook; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; @@ -73,13 +74,13 @@ public void close() { } } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } try { Files.delete(tempFolder); } catch (IOException e) { FileDeletionHook.getInstance().registerFile(tempFolder); - e.printStackTrace(); + Logger.error(e); } tempFolder = null; } diff --git a/src/org/infinity/resource/sav/SavResource.java b/src/org/infinity/resource/sav/SavResource.java index 8b0fefcf2..5756c524e 100644 --- a/src/org/infinity/resource/sav/SavResource.java +++ b/src/org/infinity/resource/sav/SavResource.java @@ -49,6 +49,7 @@ import org.infinity.resource.Writeable; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.SimpleListModel; import org.infinity.util.io.FileEx; @@ -125,7 +126,7 @@ public void actionPerformed(ActionEvent event) { Resource res = ResourceFactory.getResource(fileentry); new ViewFrame(panel.getTopLevelAncestor(), res); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Could not open selected resource.", "Error", JOptionPane.ERROR_MESSAGE); } @@ -220,7 +221,7 @@ public void mouseClicked(MouseEvent event) { Resource res = ResourceFactory.getResource(fileentry); new ViewFrame(panel.getTopLevelAncestor(), res); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Could not open selected resource.", "Error", JOptionPane.ERROR_MESSAGE); } @@ -336,7 +337,7 @@ private boolean compressData(boolean showError) { if (showError) { JOptionPane.showMessageDialog(panel, "Error compressing file", "Error", JOptionPane.ERROR_MESSAGE); } - e.printStackTrace(); + Logger.error(e); return false; } return true; @@ -363,7 +364,7 @@ private boolean decompressData(boolean showError) { if (showError) { JOptionPane.showMessageDialog(panel, "Error decompressing file", "Error", JOptionPane.ERROR_MESSAGE); } - e.printStackTrace(); + Logger.error(e); return false; } return true; @@ -412,7 +413,7 @@ private void addResource(ResourceEntry resourceEntry) { buttonPanel.getControlByType(CTRL_DELETE).setEnabled(filelist.getSelectedIndex() >= 0); buttonPanel.getControlByType(CTRL_EDIT).setEnabled(filelist.getSelectedIndex() >= 0); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } @@ -426,7 +427,7 @@ private void removeResource(int entryIndex) { try { Files.delete(file); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } entries.remove(resourceEntry); @@ -437,7 +438,7 @@ private void removeResource(int entryIndex) { filelist.setSelectedIndex(entryIndex); filelist.revalidate(); filelist.repaint(); - if (listModel.size() == 0) { + if (listModel.isEmpty()) { buttonPanel.getControlByType(CTRL_DELETE).setEnabled(false); buttonPanel.getControlByType(CTRL_EDIT).setEnabled(false); } diff --git a/src/org/infinity/resource/sav/SavResourceEntry.java b/src/org/infinity/resource/sav/SavResourceEntry.java index 005a71363..5d4e3d4ca 100644 --- a/src/org/infinity/resource/sav/SavResourceEntry.java +++ b/src/org/infinity/resource/sav/SavResourceEntry.java @@ -17,6 +17,7 @@ import org.infinity.resource.Writeable; import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.key.ResourceTreeFolder; +import org.infinity.util.Logger; import org.infinity.util.io.ByteBufferInputStream; import org.infinity.util.io.ByteBufferOutputStream; import org.infinity.util.io.StreamUtils; @@ -26,11 +27,11 @@ */ public class SavResourceEntry extends ResourceEntry implements Writeable { private final String fileName; + private final ByteBuffer cdata; private int offset; private int comprLength; private int uncomprLength; - private ByteBuffer cdata; public SavResourceEntry(ByteBuffer buffer, int offset) { this.offset = offset; @@ -116,7 +117,7 @@ public int[] getResourceInfo(boolean ignoreoverride) throws Exception { return new int[] { data.getInt(8), data.getInt(12) }; } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -146,18 +147,18 @@ public long getResourceSize(boolean ignoreOverride) { if (info.length == 1) { return info[0]; } else if (info.length > 1) { - return info[0] * info[1] + 0x18; + return (long) info[0] * info[1] + 0x18; } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return -1L; } public ByteBuffer decompress() throws Exception { Inflater inflater = new Inflater(); - byte udata[] = new byte[uncomprLength]; + byte[] udata = new byte[uncomprLength]; inflater.setInput(cdata.array()); inflater.inflate(udata); return StreamUtils.getByteBuffer(udata); diff --git a/src/org/infinity/resource/sound/AcmBuffer.java b/src/org/infinity/resource/sound/AcmBuffer.java index bbd461a57..fbd30892c 100644 --- a/src/org/infinity/resource/sound/AcmBuffer.java +++ b/src/org/infinity/resource/sound/AcmBuffer.java @@ -148,7 +148,7 @@ private void makeNewSamples() { unpacker.getOneBlock(blockI); decoder.decode(blockI, subBlocks); valuesI = blockI.clone(); - samplesReady = (blockSize > samplesLeft) ? samplesLeft : blockSize; + samplesReady = Math.min(blockSize, samplesLeft); samplesLeft -= samplesReady; } diff --git a/src/org/infinity/resource/sound/AudioFactory.java b/src/org/infinity/resource/sound/AudioFactory.java index 99b924e51..6b3a558c7 100644 --- a/src/org/infinity/resource/sound/AudioFactory.java +++ b/src/org/infinity/resource/sound/AudioFactory.java @@ -7,6 +7,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sound.AudioBuffer.AudioOverride; import org.infinity.util.DynamicArray; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; public class AudioFactory { @@ -37,7 +38,7 @@ public static AudioBuffer getAudioBuffer(ResourceEntry entry, AudioOverride over try { return getAudioBuffer(StreamUtils.toArray(entry.getResourceBuffer()), 0, override); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return null; } } @@ -78,7 +79,7 @@ public static AudioBuffer getAudioBuffer(byte[] buffer, int offset, AudioOverrid return null; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return null; } } @@ -105,7 +106,7 @@ public static byte[] convertAudio(ResourceEntry entry, AudioOverride override) { try { return convertAudio(StreamUtils.toArray(entry.getResourceBuffer()), 0, override); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return null; } } @@ -138,7 +139,7 @@ public static byte[] convertAudio(byte[] buffer, int offset, AudioOverride overr return ab.getAudioData(); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return null; } return null; @@ -165,6 +166,7 @@ private static AudioFormat detectFormat(byte[] buffer, int offset) { } } } catch (Throwable t) { + Logger.trace(t); } return af; } diff --git a/src/org/infinity/resource/sound/AudioPlayer.java b/src/org/infinity/resource/sound/AudioPlayer.java index 0a9634549..f8b2846ea 100644 --- a/src/org/infinity/resource/sound/AudioPlayer.java +++ b/src/org/infinity/resource/sound/AudioPlayer.java @@ -13,6 +13,8 @@ import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; +import org.infinity.util.Logger; + public class AudioPlayer { private final byte[] buffer = new byte[8196]; @@ -133,11 +135,13 @@ public void stopPlay() { try { Thread.sleep(50L); } catch (InterruptedException e) { + Logger.trace(e); } } try { Thread.sleep(150L); } catch (InterruptedException e) { + Logger.trace(e); } setStopped(true); if (dataLine != null && dataLine.isOpen()) { diff --git a/src/org/infinity/resource/sound/OggBuffer.java b/src/org/infinity/resource/sound/OggBuffer.java index d21f78884..dcd8adef5 100644 --- a/src/org/infinity/resource/sound/OggBuffer.java +++ b/src/org/infinity/resource/sound/OggBuffer.java @@ -8,6 +8,7 @@ import java.io.ByteArrayOutputStream; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import com.jcraft.jogg.Packet; import com.jcraft.jogg.Page; @@ -243,7 +244,7 @@ private byte[] decodeOgg(byte[] inBuf, int offset) throws Exception { } if (result == -1) { // missing or corrupt data at this page position - System.err.println("Corrupt or missing data in bitstream; continuing..."); + Logger.warn("Corrupt or missing data in bitstream; continuing..."); } else { os.pagein(og); // can safely ignore errors at this point @@ -270,7 +271,7 @@ private byte[] decodeOgg(byte[] inBuf, int offset) throws Exception { while ((samples = vd.synthesis_pcmout(_pcm, _index)) > 0) { float[][] pcm = _pcm[0]; - int bout = (samples < convSize) ? samples : convSize; + int bout = Math.min(samples, convSize); // convert floats to 16 bit signed ints (host order) and interleave for (i = 0; i < oggInfo.channels; i++) { diff --git a/src/org/infinity/resource/sound/SoundResource.java b/src/org/infinity/resource/sound/SoundResource.java index 214a8ee14..05919abc2 100644 --- a/src/org/infinity/resource/sound/SoundResource.java +++ b/src/org/infinity/resource/sound/SoundResource.java @@ -42,6 +42,7 @@ import org.infinity.resource.ViewableContainer; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.WavReferenceSearcher; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -179,7 +180,7 @@ public void run() { player.play(audioBuffer); } catch (Exception e) { JOptionPane.showMessageDialog(panel, "Error during playback", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } player.stopPlay(); timerTask.stop(); @@ -336,7 +337,7 @@ private boolean loadAudio() { return true; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(getContainer(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } return false; @@ -354,7 +355,7 @@ private void showProperties() { int channels; String channelsDesc; String duration = getTotalDurationString(true); - String extra = null; + final String extra; if (audioBuffer instanceof OggBuffer) { format = "Ogg Vorbis"; final OggBuffer buf = (OggBuffer) audioBuffer; @@ -397,9 +398,7 @@ private void showProperties() { final StringBuilder sb = new StringBuilder("

"); sb.append("Format:      ").append(format).append(br); sb.append("Duration:    ").append(duration).append(br); - if (extra != null) { - sb.append(extra).append(br); - } + sb.append(extra).append(br); sb.append("Sample Rate: ").append(rate).append(" Hz").append(br); sb.append("Channels:    ").append(channels).append(channelsDesc).append(br); sb.append("
"); @@ -411,8 +410,9 @@ private void showProperties() { // -------------------------- INNER CLASSES -------------------------- private class TimerElapsedTask extends TimerTask { + private final long delay; + private Timer timer; - private long delay; private boolean paused; /** Initializes a new timer task with the given delay, in milliseconds. */ diff --git a/src/org/infinity/resource/sound/WavBuffer.java b/src/org/infinity/resource/sound/WavBuffer.java index 646fa2336..ed82a1516 100644 --- a/src/org/infinity/resource/sound/WavBuffer.java +++ b/src/org/infinity/resource/sound/WavBuffer.java @@ -53,12 +53,12 @@ protected void convert(byte[] buffer, int offset, AudioOverride override) throws // Decodes IMA ADPCM encoded audio data and returns a buffer containing // signed 16-bit PCM audio data, including WAV header private static byte[] convertADPCM(byte[] buffer, int offset, WaveFmt fmt) throws Exception { - final int stepTable[] = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, + final int[] stepTable = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - final int indexTable[] = { -1, -1, -1, -1, 2, 4, 6, 8 }; + final int[] indexTable = { -1, -1, -1, -1, 2, 4, 6, 8 }; // sanity checks if (buffer == null || fmt == null) { diff --git a/src/org/infinity/resource/spl/SplResource.java b/src/org/infinity/resource/spl/SplResource.java index 65ea74bf1..3ae933759 100644 --- a/src/org/infinity/resource/spl/SplResource.java +++ b/src/org/infinity/resource/spl/SplResource.java @@ -9,6 +9,7 @@ import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.Arrays; import java.util.List; import java.util.ListIterator; @@ -46,6 +47,7 @@ import org.infinity.resource.itm.ItmResource; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -341,7 +343,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { } offset = abilOffset.getValue(); - Ability abilities[] = new Ability[abilCount.getValue()]; + Ability[] abilities = new Ability[abilCount.getValue()]; for (int i = 0; i < abilities.length; i++) { abilities[i] = new Ability(this, buffer, offset, i); addField(abilities[i]); @@ -444,24 +446,24 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear String[] keyList = new String[] { SearchOptions.SPL_SpellType, SearchOptions.SPL_CastingAnimation, SearchOptions.SPL_PrimaryType, SearchOptions.SPL_SecondaryType, SearchOptions.SPL_Level }; - for (int idx = 0; idx < keyList.length; idx++) { + for (String s : keyList) { if (retVal) { - key = keyList[idx]; + key = s; o = searchOptions.getOption(key); StructEntry struct = spl.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { break; } } keyList = new String[] { SearchOptions.SPL_Flags, SearchOptions.SPL_Exclusion }; - for (int idx = 0; idx < keyList.length; idx++) { + for (String s : keyList) { if (retVal) { - key = keyList[idx]; + key = s; o = searchOptions.getOption(key); StructEntry struct = spl.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -469,22 +471,22 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear keyList = new String[] { SearchOptions.SPL_Effect_Type1, SearchOptions.SPL_Effect_Type2, SearchOptions.SPL_Effect_Type3 }; - for (int idx = 0; idx < keyList.length; idx++) { + for (String s : keyList) { if (retVal) { boolean found = false; - key = keyList[idx]; + key = s; o = searchOptions.getOption(key); - for (int idx2 = 0; idx2 < effects.length; idx2++) { + for (Effect effect : effects) { if (!found) { - if (effects[idx2] != null) { - StructEntry struct = effects[idx2].getAttribute(SearchOptions.getResourceName(key), false); - found |= SearchOptions.Utils.matchNumber(struct, o); + if (effect != null) { + StructEntry struct = effect.getAttribute(SearchOptions.getResourceName(key), false); + found = SearchOptions.Utils.matchNumber(struct, o); } } else { break; } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -499,17 +501,15 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear SearchOptions.SPL_Ability_Speed, SearchOptions.SPL_Ability_Projectile, SearchOptions.SPL_Ability_Effect_Type1, SearchOptions.SPL_Ability_Effect_Type2, SearchOptions.SPL_Ability_Effect_Type3 }; - for (int i = 0; i < keyList.length; i++) { - hasAbilityOptions |= (abilityOption.getOption(keyList[i]) != null); + for (String s : keyList) { + hasAbilityOptions |= (abilityOption.getOption(s) != null); } // tracks matches for each option in every available ability final int abilityOptions = keyList.length; // number of supported spell ability options boolean[][] abilityMatches = new boolean[abilities.length][abilityOptions]; for (int i = 0; i < abilities.length; i++) { - for (int j = 0; j < abilityMatches[i].length; j++) { - abilityMatches[i][j] = false; - } + Arrays.fill(abilityMatches[i], false); } for (int i = 0; i < abilities.length; i++) { @@ -536,9 +536,6 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear // evaluating collected results boolean[] foundSingle = new boolean[abilityMatches.length]; // for single ability option - for (int i = 0; i < foundSingle.length; i++) { - foundSingle[i] = false; - } boolean[] foundMulti = new boolean[abilityOptions]; // for multiple abilities option for (int i = 0; i < foundMulti.length; i++) { foundMulti[i] = (abilityOption.getOption(keyList[i]) == null); @@ -555,39 +552,39 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear } boolean resultSingle = false; - for (int i = 0; i < foundSingle.length; i++) { - resultSingle |= foundSingle[i]; + for (boolean b : foundSingle) { + resultSingle |= b; } resultSingle |= !hasAbilityOptions; boolean resultMulti = true; - for (int i = 0; i < foundMulti.length; i++) { - resultMulti &= foundMulti[i]; + for (boolean b : foundMulti) { + resultMulti &= b; } resultMulti |= !hasAbilityOptions; - Boolean isAbilitySingle; + boolean isAbilitySingle; o = abilityOption.getOption(SearchOptions.SPL_Ability_MatchSingle); - if (o != null && o instanceof Boolean) { + if (o instanceof Boolean) { isAbilitySingle = (Boolean) o; } else { isAbilitySingle = false; } if (isAbilitySingle) { - retVal &= resultSingle; + retVal = resultSingle; } else { - retVal &= resultMulti; + retVal = resultMulti; } } keyList = new String[] { SearchOptions.SPL_Custom1, SearchOptions.SPL_Custom2, SearchOptions.SPL_Custom3, SearchOptions.SPL_Custom4 }; - for (int idx = 0; idx < keyList.length; idx++) { + for (String s : keyList) { if (retVal) { - key = keyList[idx]; + key = s; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(spl, o); + retVal = SearchOptions.Utils.matchCustomFilter(spl, o); } else { break; } @@ -595,6 +592,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/spl/Viewer.java b/src/org/infinity/resource/spl/Viewer.java index b87304262..a2a5cc551 100644 --- a/src/org/infinity/resource/spl/Viewer.java +++ b/src/org/infinity/resource/spl/Viewer.java @@ -28,6 +28,7 @@ import org.infinity.util.IdsMap; import org.infinity.util.IdsMapCache; import org.infinity.util.IdsMapEntry; +import org.infinity.util.Logger; public final class Viewer extends JPanel { private static final HashMap SPELL_PREFIX_MAP = new HashMap<>(); @@ -68,6 +69,7 @@ public static String getSymbolicName(ResourceEntry entry, boolean formatted) { try { code = Integer.parseInt(s); } catch (NumberFormatException e) { + Logger.trace(e); } // returning symbolic spell name @@ -112,7 +114,7 @@ public static String getResourceName(int value, boolean extension) { type = 0; } int code = value % 1000; - String prefix = SPELL_PREFIX_MAP.get(Integer.valueOf(type)); + String prefix = SPELL_PREFIX_MAP.get(type); if (prefix != null) { String nameBase = String.format("%s%03d", prefix, code); return extension ? nameBase + ".SPL" : nameBase; diff --git a/src/org/infinity/resource/sto/Purchases.java b/src/org/infinity/resource/sto/Purchases.java index d76ef2db4..7342c8099 100644 --- a/src/org/infinity/resource/sto/Purchases.java +++ b/src/org/infinity/resource/sto/Purchases.java @@ -6,24 +6,20 @@ import java.nio.ByteBuffer; -import org.infinity.datatype.Bitmap; +import org.infinity.datatype.ItemTypeBitmap; import org.infinity.resource.AddRemovable; -import org.infinity.resource.Profile; -import org.infinity.resource.itm.ItmResource; import org.infinity.util.io.StreamUtils; -public final class Purchases extends Bitmap implements AddRemovable { +public final class Purchases extends ItemTypeBitmap implements AddRemovable { // STO/Purchases-specific field labels public static final String STO_PURCHASES = "Store purchases"; Purchases() { - super(StreamUtils.getByteBuffer(4), 0, 4, STO_PURCHASES, - (Profile.getEngine() == Profile.Engine.PST) ? ItmResource.CATEGORIES11_ARRAY : ItmResource.CATEGORIES_ARRAY); + super(StreamUtils.getByteBuffer(4), 0, 4, STO_PURCHASES); } Purchases(ByteBuffer buffer, int offset, int number) { - super(buffer, offset, 4, STO_PURCHASES + " " + number, - (Profile.getEngine() == Profile.Engine.PST) ? ItmResource.CATEGORIES11_ARRAY : ItmResource.CATEGORIES_ARRAY); + super(buffer, offset, 4, STO_PURCHASES + " " + number); } // --------------------- Begin Interface AddRemovable --------------------- diff --git a/src/org/infinity/resource/sto/StoResource.java b/src/org/infinity/resource/sto/StoResource.java index 54ff44ca6..2c1ba64ec 100644 --- a/src/org/infinity/resource/sto/StoResource.java +++ b/src/org/infinity/resource/sto/StoResource.java @@ -35,6 +35,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.SearchOptions; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -367,7 +368,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = SearchOptions.STO_Type; o = searchOptions.getOption(key); StructEntry struct = sto.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } String[] keyList = new String[] { SearchOptions.STO_Purchased1, SearchOptions.STO_Purchased2, @@ -382,7 +383,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear found |= SearchOptions.Utils.matchNumber(element2, o); } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -394,7 +395,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = sto.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchFlags(struct, o); + retVal = SearchOptions.Utils.matchFlags(struct, o); } else { break; } @@ -407,7 +408,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear key = element; o = searchOptions.getOption(key); StructEntry struct = sto.getAttribute(SearchOptions.getResourceName(key), false); - retVal &= SearchOptions.Utils.matchNumber(struct, o); + retVal = SearchOptions.Utils.matchNumber(struct, o); } else { break; } @@ -425,7 +426,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear found |= SearchOptions.Utils.matchResourceRef(item, o, false); } } - retVal &= found || (o == null); + retVal = found || (o == null); } else { break; } @@ -437,7 +438,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear if (retVal) { key = element; o = searchOptions.getOption(key); - retVal &= SearchOptions.Utils.matchCustomFilter(sto, o); + retVal = SearchOptions.Utils.matchCustomFilter(sto, o); } else { break; } @@ -445,6 +446,7 @@ public static boolean matchSearchOptions(ResourceEntry entry, SearchOptions sear return retVal; } catch (Exception e) { + Logger.trace(e); } } return false; diff --git a/src/org/infinity/resource/text/PlainTextResource.java b/src/org/infinity/resource/text/PlainTextResource.java index 3c31e082d..1a4461325 100644 --- a/src/org/infinity/resource/text/PlainTextResource.java +++ b/src/org/infinity/resource/text/PlainTextResource.java @@ -17,7 +17,7 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; @@ -52,6 +52,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.StaticSimpleXorDecryptor; import org.infinity.util.io.StreamUtils; @@ -95,6 +96,7 @@ public static String getSearchString(ResourceEntry entry) { } } } catch (NumberFormatException e) { + Logger.trace(e); } if (retVal == null) { @@ -182,24 +184,32 @@ public static String alignTableColumns(String text, int spaces, boolean alignPer int maxCols = 0; int maxTokenLength = 0; final List> matrix = new ArrayList<>(lines.length); - for (int i = 0; i < lines.length; i++) { - final String[] tokens = lines[i].split("\\s+"); + int i = 0; + for (final String item : lines) { + final String line = item.trim(); + if (line.isEmpty()) { + continue; + } + + final String[] tokens = line.split("\\s+"); if (tokens.length > 0) { - matrix.add(new ArrayList<>(tokens.length)); - if (matrix.size() == 3) { - matrix.get(matrix.size() - 1).add(""); + i++; + final ArrayList row = new ArrayList<>(tokens.length); + if (i == 3) { + row.add(""); } - for (String token : tokens) { + for (final String token : tokens) { if (!token.isEmpty()) { - matrix.get(i).add(token); + row.add(token); } } - if (matrix.size() > 2) { - maxCols = Math.max(maxCols, matrix.get(matrix.size() - 1).size()); + if (i > 2) { + maxCols = Math.max(maxCols, row.size()); for (String token : tokens) { maxTokenLength = Math.max(maxTokenLength, token.length()); } } + matrix.add(row); } } @@ -297,6 +307,7 @@ public static String sortTable(String text, boolean ascending, boolean isTrigger try { v1 = Long.parseLong(s, radix); } catch (NumberFormatException ex) { + Logger.trace(ex); } } @@ -310,6 +321,7 @@ public static String sortTable(String text, boolean ascending, boolean isTrigger try { v2 = Long.parseLong(s, radix); } catch (NumberFormatException ex) { + Logger.trace(ex); } } @@ -318,7 +330,7 @@ public static String sortTable(String text, boolean ascending, boolean isTrigger v2 &= ~0x4000; } - int result = (v1 < v2) ? -1 : ((v1 > v2) ? 1 : 0); + int result = Long.compare(v1, v2); if (!ascending) { result = -result; } @@ -430,7 +442,7 @@ public void itemStateChanged(ItemEvent event) { final List files = ResourceFactory.getResources(entry.getExtension()); new TextResourceSearcher(files, panel.getTopLevelAncestor()); } else if (bpmFind.getSelectedItem() == iFindThis) { - new TextResourceSearcher(Arrays.asList(entry), panel.getTopLevelAncestor()); + new TextResourceSearcher(Collections.singletonList(entry), panel.getTopLevelAncestor()); } } else if (event.getSource() == bpmFormat) { if (bpmFormat.getSelectedItem() == miFormatTrim) { @@ -479,6 +491,7 @@ public void highlightText(int linenr, String highlightText) { } highlightText(startOfs, endOfs); } catch (BadLocationException ble) { + Logger.trace(ble); } } @@ -489,6 +502,7 @@ public void highlightText(int startOfs, int endOfs) { editor.moveCaretPosition(endOfs - 1); editor.getCaret().setSelectionVisible(true); } catch (IllegalArgumentException e) { + Logger.trace(e); } } diff --git a/src/org/infinity/resource/text/QuestsResource.java b/src/org/infinity/resource/text/QuestsResource.java index a6a12ccde..e100d4363 100644 --- a/src/org/infinity/resource/text/QuestsResource.java +++ b/src/org/infinity/resource/text/QuestsResource.java @@ -34,7 +34,7 @@ public class QuestsResource extends PlainTextResource implements ChangeListener public static final String RESOURCE_NAME = "quests.ini"; /** - * Flag, that indicates, that {@link #quests is not synchronized with current {@link #getText() resource text} and + * Flag, that indicates, that {@code quests.ini} is not synchronized with current {@link #getText() resource text} and * reloading is required. */ private boolean dirty = false; diff --git a/src/org/infinity/resource/text/modes/BCSFoldParser.java b/src/org/infinity/resource/text/modes/BCSFoldParser.java index cfc2a5ee5..78382d9d2 100644 --- a/src/org/infinity/resource/text/modes/BCSFoldParser.java +++ b/src/org/infinity/resource/text/modes/BCSFoldParser.java @@ -15,6 +15,7 @@ import org.fife.ui.rsyntaxtextarea.folding.Fold; import org.fife.ui.rsyntaxtextarea.folding.FoldParser; import org.fife.ui.rsyntaxtextarea.folding.FoldType; +import org.infinity.util.Logger; /** * A fold parser for BCS scripts. It supports folding of multiline comments and IF/END blocks. @@ -84,7 +85,7 @@ public List getFolds(RSyntaxTextArea textArea) { } } } catch (BadLocationException e) { - e.printStackTrace(); + Logger.error(e); } return folds; diff --git a/src/org/infinity/resource/text/modes/BCSTokenMaker.java b/src/org/infinity/resource/text/modes/BCSTokenMaker.java index 2a0cdea56..e938e61f7 100644 --- a/src/org/infinity/resource/text/modes/BCSTokenMaker.java +++ b/src/org/infinity/resource/text/modes/BCSTokenMaker.java @@ -20,6 +20,7 @@ import org.infinity.util.IdsMap; import org.infinity.util.IdsMapCache; import org.infinity.util.IdsMapEntry; +import org.infinity.util.Logger; /** * A token maker that turns text into a linked list of {@code Token}s for syntax highlighting Infinity Engine BCS @@ -544,7 +545,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { throw new Exception( String.format("Invalid token %d found at position %d", currentTokenType, newStartOfs + i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } // end of default: } // end of switch (currentTokenType) diff --git a/src/org/infinity/resource/text/modes/GLSLTokenMaker.java b/src/org/infinity/resource/text/modes/GLSLTokenMaker.java index 539e0f58d..e289840f4 100644 --- a/src/org/infinity/resource/text/modes/GLSLTokenMaker.java +++ b/src/org/infinity/resource/text/modes/GLSLTokenMaker.java @@ -24,9 +24,9 @@ import org.fife.ui.rsyntaxtextarea.AbstractJFlexCTokenMaker; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenImpl; +import org.infinity.util.Logger; import org.infinity.util.Misc; - /** * Scanner for the GLSL programming language (based on scanner for C). * @@ -3805,7 +3805,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { yybegin(state); return yylex(); } catch (IOException ioe) { - ioe.printStackTrace(); + Logger.error(ioe); return new TokenImpl(); } diff --git a/src/org/infinity/resource/text/modes/INITokenMaker.java b/src/org/infinity/resource/text/modes/INITokenMaker.java index a36ba9fe2..d73437e47 100644 --- a/src/org/infinity/resource/text/modes/INITokenMaker.java +++ b/src/org/infinity/resource/text/modes/INITokenMaker.java @@ -10,6 +10,7 @@ import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMap; import org.fife.ui.rsyntaxtextarea.TokenTypes; +import org.infinity.util.Logger; /** * A token maker that turns text into a linked list of {@code Token}s for syntax highlighting Infinity Engine INI @@ -176,7 +177,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { try { throw new Exception("Invalid token " + currentTokenType + " found at position " + (newStartOfs + i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/text/modes/MenuTokenMaker.java b/src/org/infinity/resource/text/modes/MenuTokenMaker.java index 4db3227f9..671029804 100644 --- a/src/org/infinity/resource/text/modes/MenuTokenMaker.java +++ b/src/org/infinity/resource/text/modes/MenuTokenMaker.java @@ -23,7 +23,7 @@ import org.fife.ui.rsyntaxtextarea.AbstractJFlexTokenMaker; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenImpl; - +import org.infinity.util.Logger; /** * Scanner for the Menu scripting language extension.

@@ -4414,7 +4414,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { yybegin(state); return yylex(); } catch (IOException ioe) { - ioe.printStackTrace(); + Logger.error(ioe); return new TokenImpl(); } diff --git a/src/org/infinity/resource/text/modes/TLKTokenMaker.java b/src/org/infinity/resource/text/modes/TLKTokenMaker.java index dda9d9510..fa94607a4 100644 --- a/src/org/infinity/resource/text/modes/TLKTokenMaker.java +++ b/src/org/infinity/resource/text/modes/TLKTokenMaker.java @@ -13,6 +13,7 @@ import org.fife.ui.rsyntaxtextarea.TokenMap; import org.fife.ui.rsyntaxtextarea.TokenTypes; import org.infinity.resource.Profile; +import org.infinity.util.Logger; /** * A token maker that turns text into a linked list of {@link Token}s for syntax highlighting Infinity Engine text @@ -132,7 +133,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { try { throw new Exception("Invalid token " + currentTokenType + " found at position " + (newStartOfs + i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/text/modes/WeiDULogTokenMaker.java b/src/org/infinity/resource/text/modes/WeiDULogTokenMaker.java index df19e4613..f527b600d 100644 --- a/src/org/infinity/resource/text/modes/WeiDULogTokenMaker.java +++ b/src/org/infinity/resource/text/modes/WeiDULogTokenMaker.java @@ -10,6 +10,7 @@ import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMap; import org.fife.ui.rsyntaxtextarea.TokenTypes; +import org.infinity.util.Logger; /** * A token maker that turns text into a linked list of {@link Token}s for syntax highlighting WeiDU.log content. @@ -108,7 +109,7 @@ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { try { throw new Exception("Invalid token " + currentTokenType + " found at position " + (newStartOfs + i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/to/TohResource.java b/src/org/infinity/resource/to/TohResource.java index 0956b3630..d8ce327d9 100644 --- a/src/org/infinity/resource/to/TohResource.java +++ b/src/org/infinity/resource/to/TohResource.java @@ -24,6 +24,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sav.SavResource; +import org.infinity.util.Logger; import org.infinity.util.StringTable; /** @@ -138,13 +139,13 @@ public static String getOverrideString(ResourceEntry tohEntry, ResourceEntry tot try { toh = (tohEntry != null) ? new TohResource(tohEntry) : null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (!Profile.isEnhancedEdition()) { try { tot = (totEntry != null) ? new TotResource(totEntry, toh) : null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return getOverrideString(toh, tot, strref); diff --git a/src/org/infinity/resource/to/TotResource.java b/src/org/infinity/resource/to/TotResource.java index 5fb29d93c..f084436ab 100644 --- a/src/org/infinity/resource/to/TotResource.java +++ b/src/org/infinity/resource/to/TotResource.java @@ -17,6 +17,7 @@ import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sav.SavResource; +import org.infinity.util.Logger; import org.infinity.util.StringTable; import org.infinity.util.io.FileManager; @@ -60,7 +61,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { }); // handling unmapped region of data - if (tohEntries.size() > 0 && tohEntries.get(0).getOffset() > 0) { + if (!tohEntries.isEmpty() && tohEntries.get(0).getOffset() > 0) { final StrRefEntry entry = (StrRefEntry) tohEntries.get(0); final int size = ((IsNumeric) entry.getAttribute(StrRefEntry.TOH_STRREF_OFFSET_TOT_STRING)).getValue(); if (size > 0) { @@ -128,7 +129,7 @@ public static boolean isStringEntryValid(StringEntry entry) { int ofsNext = ((IsNumeric) entry.getAttribute(StringEntry.TOT_STRING_OFFSET_NEXT_ENTRY)).getValue(); retVal = (ofsPrev == -1 && ofsNext == -1) || (ofsPrev != ofsNext); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -156,7 +157,7 @@ private TohResource loadAssociatedToh(ResourceEntry totResource) { try { toh = new TohResource(new FileResourceEntry(tohPath)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/resource/vef/VefType.java b/src/org/infinity/resource/vef/VefType.java index 7195f85ee..02cb3773c 100644 --- a/src/org/infinity/resource/vef/VefType.java +++ b/src/org/infinity/resource/vef/VefType.java @@ -14,6 +14,7 @@ import org.infinity.datatype.TextString; import org.infinity.resource.AbstractStruct; import org.infinity.resource.StructEntry; +import org.infinity.util.Logger; public final class VefType extends Bitmap { // VEF/VefType-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; } diff --git a/src/org/infinity/resource/video/AudioQueue.java b/src/org/infinity/resource/video/AudioQueue.java index 225d67cf4..8ab6626be 100644 --- a/src/org/infinity/resource/video/AudioQueue.java +++ b/src/org/infinity/resource/video/AudioQueue.java @@ -4,9 +4,13 @@ package org.infinity.resource.video; + + import java.util.ArrayDeque; import java.util.Deque; +import org.infinity.util.Logger; + /** * Represents a container for audio chunks returned by the MveDecoder. */ @@ -75,6 +79,7 @@ public byte[] getNextDataWait() { try { Thread.sleep(5); } catch (InterruptedException e) { + Logger.trace(e); } } synchronized (deque) { @@ -116,6 +121,7 @@ public synchronized boolean addAudioBlock(int index, byte[] data) { deque.addLast(new AudioBlock(index, data)); return true; } catch (Throwable t) { + Logger.trace(t); } } return false; @@ -123,7 +129,7 @@ public synchronized boolean addAudioBlock(int index, byte[] data) { // ----------------------------- INNER CLASSES ----------------------------- - private class AudioBlock { + private static class AudioBlock { public final int index; // sequential number, can be used to sort audio blocks public final byte[] data; // uncompressed audio data in the globally specified audio format diff --git a/src/org/infinity/resource/video/BasicVideoBuffer.java b/src/org/infinity/resource/video/BasicVideoBuffer.java index 7ff4b8734..1750e8151 100644 --- a/src/org/infinity/resource/video/BasicVideoBuffer.java +++ b/src/org/infinity/resource/video/BasicVideoBuffer.java @@ -133,15 +133,11 @@ public boolean create(int numBuffers, int width, int height, boolean hasTranspar extraData = new Object[this.numBuffers]; currentBuffer = 0; for (int i = 0; i < this.numBuffers; i++) { - if (width > 0 && height > 0) { - buffer[i] = ColorConvert.createCompatibleImage(width, height, hasTransparency); - } else { - buffer[i] = null; - } + buffer[i] = ColorConvert.createCompatibleImage(width, height, hasTransparency); extraData[i] = null; } - return (width > 0 && height > 0); + return true; } /** diff --git a/src/org/infinity/resource/video/MveAudioDecoder.java b/src/org/infinity/resource/video/MveAudioDecoder.java index 8dc297d7a..871448829 100644 --- a/src/org/infinity/resource/video/MveAudioDecoder.java +++ b/src/org/infinity/resource/video/MveAudioDecoder.java @@ -63,7 +63,7 @@ public static MveAudioDecoder createDecoder(MveInfo info) { * @throws Exception On error. */ public boolean processAudio(MveSegment segment) throws Exception { - if (info == null || segment == null) { + if (segment == null) { throw new NullPointerException(); } diff --git a/src/org/infinity/resource/video/MveDecoder.java b/src/org/infinity/resource/video/MveDecoder.java index 7ee977186..6d88be27c 100644 --- a/src/org/infinity/resource/video/MveDecoder.java +++ b/src/org/infinity/resource/video/MveDecoder.java @@ -15,6 +15,7 @@ import javax.sound.sampled.AudioFormat; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -526,7 +527,7 @@ private boolean manageSegment(MveChunk chunk, MveSegment segment) { return true; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return false; @@ -597,6 +598,7 @@ private void close() { try { mveInput.close(); } catch (IOException e) { + Logger.trace(e); } mveInput = null; } @@ -777,7 +779,7 @@ private boolean initSegments() { segments.add(segment); curSize += segmentSize; } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); return false; } } @@ -799,7 +801,7 @@ private boolean peekNextChunk() { nextChunkSize = StreamUtils.readUnsignedShort(in); nextChunkType = StreamUtils.readUnsignedShort(in); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); return false; } } @@ -852,6 +854,7 @@ private MveSegment(InputStream in, int size, int opcode, int version) { } numRead += n; } catch (IOException e) { + Logger.trace(e); } } } diff --git a/src/org/infinity/resource/video/MvePlayer.java b/src/org/infinity/resource/video/MvePlayer.java index a16b1d9ae..749291118 100644 --- a/src/org/infinity/resource/video/MvePlayer.java +++ b/src/org/infinity/resource/video/MvePlayer.java @@ -8,13 +8,16 @@ import javax.sound.sampled.AudioSystem; import javax.sound.sampled.SourceDataLine; +import org.infinity.util.Logger; + public class MvePlayer { + private final AudioQueue audioQueue; + private boolean playing; private boolean paused; private boolean stopped; private long startTime; private long delayTime; - private AudioQueue audioQueue; private SourceDataLine dataLine; public MvePlayer() { @@ -99,6 +102,7 @@ public void play(ImageRenderer renderer, MveDecoder decoder) throws Exception { try { Thread.sleep(1); } catch (InterruptedException e) { + Logger.trace(e); } } dataLine.start(); @@ -138,11 +142,13 @@ public void stopPlay() { try { Thread.sleep(50L); } catch (InterruptedException e) { + Logger.trace(e); } } try { Thread.sleep(100L); } catch (InterruptedException e) { + Logger.trace(e); } } @@ -218,12 +224,18 @@ private void sleepUntil(long remaining) { try { Thread.sleep(1); } catch (InterruptedException e) { + Logger.trace(e); } } } if (timeRemaining() <= 2000000L) { while (timeRemaining() > remaining) { // waste remaining nanoseconds + try { + Thread.sleep(0); + } catch (InterruptedException e) { + Logger.trace(e); + } } } } @@ -243,7 +255,7 @@ private void initAudio(MveDecoder decoder) throws Exception { try { dataLine = AudioSystem.getSourceDataLine(audioFormat); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); throw new Exception("Unsupported audio format"); } dataLine.open(audioFormat, 16384); diff --git a/src/org/infinity/resource/video/MveResource.java b/src/org/infinity/resource/video/MveResource.java index e211dda17..a7e0ff659 100644 --- a/src/org/infinity/resource/video/MveResource.java +++ b/src/org/infinity/resource/video/MveResource.java @@ -49,6 +49,7 @@ import org.infinity.resource.key.BIFFResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.ReferenceSearcher; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.monte.media.AudioFormatKeys; import org.monte.media.Format; @@ -74,12 +75,12 @@ public class MveResource implements Resource, ActionListener, ItemListener, Clos private static boolean isZoom = true; private static boolean isFilter = true; - private final ResourceEntry entry; private final ButtonPanel buttonPanel = new ButtonPanel(); + private final ResourceEntry entry; + private final MvePlayer player; private MveDecoder decoder; private ImageRenderer renderer; - private MvePlayer player; private JMenuItem miExport; private JMenuItem miExportAvi; private JPanel panel; @@ -97,7 +98,7 @@ public MveResource(ResourceEntry entry) throws Exception { } } catch (Exception e) { decoder = null; - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error opening " + entry, "Error", JOptionPane.ERROR_MESSAGE); } @@ -207,7 +208,7 @@ public void run() { try { decoder.open(entry); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel, "Error starting video playback", "Error", JOptionPane.ERROR_MESSAGE); return; } @@ -221,7 +222,7 @@ public void run() { player.play(renderer, decoder); } catch (Exception e) { player.stopPlay(); - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(panel, "Error during playback", "Error", JOptionPane.ERROR_MESSAGE); } decoder.close(); @@ -449,15 +450,13 @@ AudioFormatKeys.SampleRateKey, new Rational(sampleRate), AudioFormatKeys.SampleS frameIdx++; if (!silent && pm.isCanceled()) { - if (writer != null) { - writer.close(); - writer = null; - } + writer.close(); + writer = null; if (FileEx.create(outFile).isFile()) { try { Files.delete(outFile); } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } JOptionPane.showMessageDialog(parent, "Conversion has been cancelled.", "Information", @@ -489,7 +488,7 @@ AudioFormatKeys.SampleRateKey, new Rational(sampleRate), AudioFormatKeys.SampleS } return true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } if (!silent) { JOptionPane.showMessageDialog(parent, "Error while exporting " + inEntry + " as AVI file.", "Error", diff --git a/src/org/infinity/resource/video/MveVideoDecoder.java b/src/org/infinity/resource/video/MveVideoDecoder.java index b7354398e..9a637e125 100644 --- a/src/org/infinity/resource/video/MveVideoDecoder.java +++ b/src/org/infinity/resource/video/MveVideoDecoder.java @@ -13,6 +13,7 @@ import org.infinity.resource.graphics.ColorConvert; import org.infinity.resource.video.MveDecoder.MveInfo; import org.infinity.resource.video.MveDecoder.MveSegment; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -1126,7 +1127,7 @@ private void copyBlock8x8(BufferedImage src, int srcX, int srcY, int dstX, int d int srcOfs = srcY * src.getWidth() + srcX; int dstOfs = dstY * curBuffer.getWidth() + dstX; if (srcOfs < 0) { - System.err.println("Debug: copyBlock8x8(src, " + srcX + ", " + srcY + ", " + dstX + ", " + dstY + ")"); + Logger.debug("copyBlock8x8(src, {}, {}, {}, {})", srcX, srcY, dstX, dstY); return; } diff --git a/src/org/infinity/resource/video/WbmResource.java b/src/org/infinity/resource/video/WbmResource.java index f7894378c..96920edc7 100644 --- a/src/org/infinity/resource/video/WbmResource.java +++ b/src/org/infinity/resource/video/WbmResource.java @@ -36,6 +36,7 @@ import org.infinity.search.ReferenceSearcher; import org.infinity.util.FileDeletionHook; import org.infinity.util.LauncherUtils; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -76,7 +77,7 @@ public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error opening video or no application registered " + "to play back WBM (WebM) files.", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); } } } finally { @@ -106,6 +107,7 @@ public void close() throws Exception { Files.delete(videoFile); } } catch (Exception e) { + Logger.trace(e); } } @@ -182,7 +184,7 @@ private Path getVideoFile() { isTempFile = true; FileDeletionHook.getInstance().registerFile(retVal); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); retVal = null; } } diff --git a/src/org/infinity/resource/wed/Polygon.java b/src/org/infinity/resource/wed/Polygon.java index b7d562462..573b57774 100644 --- a/src/org/infinity/resource/wed/Polygon.java +++ b/src/org/infinity/resource/wed/Polygon.java @@ -10,7 +10,6 @@ import org.infinity.datatype.Flag; import org.infinity.datatype.IsNumeric; import org.infinity.datatype.SectionCount; -import org.infinity.datatype.Unknown; import org.infinity.resource.AbstractStruct; import org.infinity.resource.AddRemovable; import org.infinity.resource.HasChildStructs; @@ -22,6 +21,7 @@ public abstract class Polygon extends AbstractStruct implements AddRemovable, Ha public static final String WED_POLY_VERTEX_INDEX = "Vertex index"; public static final String WED_POLY_NUM_VERTICES = "# vertices"; public static final String WED_POLY_FLAGS = "Polygon flags"; + public static final String WED_POLY_HEIGHT = "Height"; public static final String WED_POLY_MIN_COORD_X = "Minimum coordinate: X"; public static final String WED_POLY_MAX_COORD_X = "Maximum coordinate: X"; public static final String WED_POLY_MIN_COORD_Y = "Minimum coordinate: Y"; @@ -92,7 +92,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { addField(new DecNumber(buffer, offset, 4, WED_POLY_VERTEX_INDEX)); addField(new SectionCount(buffer, offset + 4, 4, WED_POLY_NUM_VERTICES, Vertex.class)); addField(new Flag(buffer, offset + 8, 1, WED_POLY_FLAGS, FLAGS_ARRAY)); - addField(new Unknown(buffer, offset + 9, 1)); + addField(new DecNumber(buffer, offset + 9, 1, WED_POLY_HEIGHT)); addField(new DecNumber(buffer, offset + 10, 2, WED_POLY_MIN_COORD_X)); addField(new DecNumber(buffer, offset + 12, 2, WED_POLY_MAX_COORD_X)); addField(new DecNumber(buffer, offset + 14, 2, WED_POLY_MIN_COORD_Y)); diff --git a/src/org/infinity/resource/wed/WedResource.java b/src/org/infinity/resource/wed/WedResource.java index ea2eb5e93..6d7284414 100644 --- a/src/org/infinity/resource/wed/WedResource.java +++ b/src/org/infinity/resource/wed/WedResource.java @@ -217,7 +217,7 @@ public int read(ByteBuffer buffer, int offset) throws Exception { IndexNumber.class); addField(offsetPolytable); - HexNumber offsets[] = new HexNumber[] { offsetOverlays, offsetHeader2, offsetDoors, offsetDoortile, offsetPolygons, + HexNumber[] offsets = new HexNumber[] { offsetOverlays, offsetHeader2, offsetDoors, offsetDoortile, offsetPolygons, offsetWallgroups, offsetPolytable, new HexNumber( ByteBuffer.wrap(Misc.intToArray(buffer.limit() - startOffset)).order(ByteOrder.LITTLE_ENDIAN), 0, 4, "") }; Arrays.sort(offsets, (s1, s2) -> s1.getValue() - s2.getValue()); diff --git a/src/org/infinity/resource/wmp/ViewerMap.java b/src/org/infinity/resource/wmp/ViewerMap.java index 3eb51cfbe..6f4c66210 100644 --- a/src/org/infinity/resource/wmp/ViewerMap.java +++ b/src/org/infinity/resource/wmp/ViewerMap.java @@ -66,6 +66,7 @@ import org.infinity.resource.graphics.ColorConvert; import org.infinity.resource.graphics.MosDecoder; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.StringTable; import org.infinity.util.io.StreamUtils; @@ -192,7 +193,7 @@ private enum Direction { pInfo.add(lInfoPos); add(pInfo, BorderLayout.SOUTH); } catch (Throwable t) { - t.printStackTrace(); + Logger.error(t); } // applying preselected overlays @@ -291,7 +292,7 @@ private void showMapIconLabels() { strref = ((IsNumeric) area.getAttribute(AreaEntry.WMP_AREA_TOOLTIP)).getValue(); } String mapName = (strref >= 0) ? StringTable.getStringRef(strref) : null; - if (mapName != null && mapName.trim().length() == 0) { + if (mapName != null && mapName.trim().isEmpty()) { mapName = null; } @@ -401,9 +402,7 @@ private void showMapDistances(int... areaIndices) { if (destArea != null) { found = areaIndicesList .stream() - .filter(idx -> curAreaIndex != idx && destArea.equals(getAreaEntry(idx, true))) - .findAny() - .isPresent(); + .anyMatch(idx -> curAreaIndex != idx && destArea.equals(getAreaEntry(idx, true))); } if (!found) { destLink = null; @@ -424,8 +423,10 @@ private void showMapDistances(int... areaIndices) { Point ptTarget = getMapIconCoordinate(dstAreaIndex, dstDir, false); // checking for random encounters during travels + final int randomEncounterProb = + ((IsNumeric) destLink.getAttribute(AreaLink.WMP_LINK_RANDOM_ENCOUNTER_PROBABILITY)).getValue(); boolean hasRandomEncounters = false; - if (((IsNumeric) destLink.getAttribute(AreaLink.WMP_LINK_RANDOM_ENCOUNTER_PROBABILITY)).getValue() > 0) { + if (randomEncounterProb > 0) { for (int rnd = 1; rnd < 6; rnd++) { String rndArea = ((IsReference) destLink .getAttribute(String.format(AreaLink.WMP_LINK_RANDOM_ENCOUNTER_AREA_FMT, rnd))).getResourceName(); @@ -450,8 +451,13 @@ private void showMapDistances(int... areaIndices) { g.drawLine(ptOrigin.x, ptOrigin.y, ptTarget.x, ptTarget.y); // printing travel time (in hours) - String duration = String.format("%d h", - ((IsNumeric) destLink.getAttribute(AreaLink.WMP_LINK_DISTANCE_SCALE)).getValue() * 4); + final String duration; + final int distScale = ((IsNumeric) destLink.getAttribute(AreaLink.WMP_LINK_DISTANCE_SCALE)).getValue() * 4; + if (hasRandomEncounters) { + duration = String.format("%d h (%d%%)", distScale, randomEncounterProb); + } else { + duration = String.format("%d h", distScale); + } LineMetrics lm = g.getFont().getLineMetrics(duration, g.getFontRenderContext()); Rectangle2D rectText = g.getFont().getStringBounds(duration, g.getFontRenderContext()); int textX = ptOrigin.x + ((ptTarget.x - ptOrigin.x) - rectText.getBounds().width) / 3; @@ -673,7 +679,7 @@ private void exportMap() { dstImage.flush(); dstImage = null; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } finally { showDot((AreaEntry) listPanel.getList().getSelectedValue(), false); WindowBlocker.blockWindow(wnd, false); diff --git a/src/org/infinity/search/AbstractReferenceSearcher.java b/src/org/infinity/search/AbstractReferenceSearcher.java index 9acc3b525..ce30a16d9 100644 --- a/src/org/infinity/search/AbstractReferenceSearcher.java +++ b/src/org/infinity/search/AbstractReferenceSearcher.java @@ -43,11 +43,11 @@ abstract class AbstractReferenceSearcher extends AbstractSearcher implements Run /** Actual list of resources in which perform search. */ private List files; - AbstractReferenceSearcher(ResourceEntry targetEntry, String filetypes[], Component parent) { + AbstractReferenceSearcher(ResourceEntry targetEntry, String[] filetypes, Component parent) { this(targetEntry, filetypes, setSelectedFileTypes(targetEntry, filetypes), parent); } - AbstractReferenceSearcher(ResourceEntry targetEntry, String filetypes[], boolean[] preselect, Component parent) { + AbstractReferenceSearcher(ResourceEntry targetEntry, String[] filetypes, boolean[] preselect, Component parent) { super(SEARCH_MULTI_TYPE_FORMAT, parent); this.targetEntry = targetEntry; @@ -230,7 +230,7 @@ private static boolean[] setSelectedFileTypes(ResourceEntry entry, String[] file } // defining preselection - if (selectedExt != null && selectedExt.length > 0) { + if (selectedExt != null) { for (int i = 0; i < retVal.length; i++) { for (String e : selectedExt) { if (e.equalsIgnoreCase(filetypes[i])) { diff --git a/src/org/infinity/search/AbstractSearcher.java b/src/org/infinity/search/AbstractSearcher.java index c7bf60694..b77ee584c 100644 --- a/src/org/infinity/search/AbstractSearcher.java +++ b/src/org/infinity/search/AbstractSearcher.java @@ -13,7 +13,8 @@ import org.infinity.NearInfinity; import org.infinity.resource.key.ResourceEntry; -import org.infinity.util.Debugging; +import org.infinity.util.DebugTimer; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.Threading; @@ -93,7 +94,7 @@ protected boolean runSearch(String operation, List entries) { boolean isCancelled = false; try (final Threading threadPool = new Threading()) { - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); int i = 0; for (final ResourceEntry entry : entries) { if (progress.isCanceled()) { @@ -112,6 +113,15 @@ protected boolean runSearch(String operation, List entries) { } } + // XXX: workaround for keeping progress dialog note in sync with actual progress + while (threadPool.hasQueuedSubmissions()) { + try { + Thread.sleep(0); + } catch (InterruptedException e) { + Logger.trace(e); + } + } + threadPool.submit(newWorker(entry)); } @@ -131,13 +141,14 @@ protected boolean runSearch(String operation, List entries) { try { threadPool.awaitTermination(10L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { + Logger.trace(e); } } } catch (Exception e) { - // ignored + Logger.trace(e); } - Debugging.timerShow(operation + " completed", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted(operation + " completed")); if (isCancelled) { JOptionPane.showMessageDialog(parent, operation + " cancelled", "Info", JOptionPane.INFORMATION_MESSAGE); diff --git a/src/org/infinity/search/DialogItemRefSearcher.java b/src/org/infinity/search/DialogItemRefSearcher.java index 52ede113a..f02e4736d 100644 --- a/src/org/infinity/search/DialogItemRefSearcher.java +++ b/src/org/infinity/search/DialogItemRefSearcher.java @@ -18,6 +18,8 @@ import org.infinity.resource.dlg.State; import org.infinity.resource.dlg.StateTrigger; import org.infinity.resource.dlg.Transition; +import org.infinity.util.DebugTimer; +import org.infinity.util.Logger; public class DialogItemRefSearcher implements Runnable { private final DlgResource dlg; @@ -38,7 +40,7 @@ public void run() { final List searchItems = dlg.getFields(); ProgressMonitor progress = new ProgressMonitor(parent, "Searching...", null, 0, searchItems.size()); progress.setMillisToDecideToPopup(100); - long startTime = System.currentTimeMillis(); + DebugTimer.getInstance().timerReset(); for (int i = 0; i < searchItems.size(); i++) { StructEntry entry = searchItems.get(i); if (entry instanceof State || entry instanceof Transition || entry instanceof AbstractCode) { @@ -50,7 +52,7 @@ public void run() { return; } } - System.out.println("Search completed: " + (System.currentTimeMillis() - startTime) + "ms."); + Logger.info(DebugTimer.getInstance().getTimerFormatted("Search completed")); hitFrame.setVisible(true); } @@ -125,6 +127,7 @@ private int getIndexFromName(String name) { try { return Integer.parseInt(name.substring(posSpace + 1)); } catch (NumberFormatException nfe) { + Logger.trace(nfe); } } return -1; diff --git a/src/org/infinity/search/DialogSearcher.java b/src/org/infinity/search/DialogSearcher.java index ba6596cea..af22a4d22 100644 --- a/src/org/infinity/search/DialogSearcher.java +++ b/src/org/infinity/search/DialogSearcher.java @@ -41,6 +41,7 @@ import org.infinity.resource.dlg.AbstractCode; import org.infinity.resource.dlg.Action; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; public final class DialogSearcher extends AbstractSearcher implements Runnable, ActionListener { private final ChildFrame inputFrame; @@ -176,7 +177,7 @@ protected Runnable newWorker(ResourceEntry entry) { final Map searchMap = makeSearchMap((AbstractStruct) resource); for (final Map.Entry e : searchMap.entrySet()) { final StructEntry searchEntry = e.getKey(); - String s = null; + String s = ""; if (searchEntry instanceof StringRef) { s = searchEntry.toString(); } else if (searchEntry instanceof AbstractCode) { @@ -192,14 +193,11 @@ protected Runnable newWorker(ResourceEntry entry) { s = decompiler.getSource(); } else { synchronized (System.err) { - System.err.println("Error(s) compiling " + entry.toString() + " - " + searchEntry.getName()); + Logger.error("Error(s) compiling {} - {}", entry.toString(), searchEntry.getName()); } } } catch (Exception ex) { - synchronized (System.err) { - System.err.println("Exception (de)compiling " + entry.toString() + " - " + searchEntry.getName()); - ex.printStackTrace(); - } + Logger.error(ex, "Exception (de)compiling {} - {}", entry.toString(), searchEntry.getName()); } if (s == null) { s = ""; diff --git a/src/org/infinity/search/FileTypeSelector.java b/src/org/infinity/search/FileTypeSelector.java index df3be7571..d88e1a0b9 100644 --- a/src/org/infinity/search/FileTypeSelector.java +++ b/src/org/infinity/search/FileTypeSelector.java @@ -13,6 +13,7 @@ import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -122,6 +123,13 @@ public FileTypeSelector(String title, String key, String[] filetypes, boolean[] bInvert.addActionListener(this); } + /** + * Returns a list of available file type {@link JCheckBox} instances. + */ + public List getFileTypes() { + return Collections.unmodifiableList(Arrays.asList(boxes)); + } + /** * Gets all selected resource pointers. * @@ -129,11 +137,7 @@ public FileTypeSelector(String title, String key, String[] filetypes, boolean[] * @return List with selected values. Never {@code null} */ public List getResources(String key) { - boolean[] selection = LAST_SELECTION.get(key); - if (selection == null) { - selection = new boolean[filetypes.length]; - LAST_SELECTION.put(key, selection); - } + final boolean[] selection = LAST_SELECTION.computeIfAbsent(key, k -> new boolean[filetypes.length]); final List result = new ArrayList<>(); for (int i = 0; i < filetypes.length; ++i) { diff --git a/src/org/infinity/search/ReferenceSearcher.java b/src/org/infinity/search/ReferenceSearcher.java index 1ce3087b3..c8955b370 100644 --- a/src/org/infinity/search/ReferenceSearcher.java +++ b/src/org/infinity/search/ReferenceSearcher.java @@ -34,6 +34,7 @@ import org.infinity.resource.other.EffResource; import org.infinity.resource.sav.SavResource; import org.infinity.resource.text.PlainTextResource; +import org.infinity.util.Logger; public final class ReferenceSearcher extends AbstractReferenceSearcher { /** Optional alternate name to search for. */ @@ -57,7 +58,7 @@ public ReferenceSearcher(ResourceEntry targetEntry, String[] fileTypes, Componen } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -127,8 +128,7 @@ private void searchDialog(ResourceEntry entry, AbstractStruct dialog) { } } } catch (Exception e) { - System.out.println("Exception in " + dialog.getName() + " - " + sourceCode.getName()); - e.printStackTrace(); + Logger.error(e, "Exception in {} - {}", dialog.getName(), sourceCode.getName()); } } else if (o instanceof AbstractStruct) { searchDialog(entry, (AbstractStruct) o); @@ -193,7 +193,7 @@ private void searchScript(ResourceEntry entry, BcsResource bcsfile) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -234,6 +234,7 @@ private void searchBam(ResourceEntry entry, BamResource bam) { try { index = Integer.parseInt(matcher.group(1)); } catch (NumberFormatException e) { + Logger.trace(e); } if (index >= 0 && index <= 99999) { if (bam.containsPvrzReference(index)) { @@ -251,6 +252,7 @@ private void searchMos(ResourceEntry entry, MosResource mos) { try { index = Integer.parseInt(matcher.group(1)); } catch (NumberFormatException e) { + Logger.trace(e); } if (index >= 0 && index <= 99999) { if (mos.containsPvrzReference(index)) { @@ -284,6 +286,7 @@ private void searchTis(ResourceEntry entry, TisResource tis) { try { index = Integer.parseInt(page); } catch (NumberFormatException e) { + Logger.trace(e); } if (pTis.matcher(entry.getResourceName()).find() && index >= 0 && index <= 99) { if (tis.containsPvrzReference(index)) { @@ -312,7 +315,7 @@ private void searchText(ResourceEntry entry, PlainTextResource text) { } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/search/SearchFrame.java b/src/org/infinity/search/SearchFrame.java index a51f24003..b12cd9edd 100644 --- a/src/org/infinity/search/SearchFrame.java +++ b/src/org/infinity/search/SearchFrame.java @@ -49,6 +49,7 @@ import org.infinity.resource.Viewable; import org.infinity.resource.bcs.BcsResource; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; public final class SearchFrame extends ChildFrame implements ActionListener, ListSelectionListener, Runnable { @@ -227,7 +228,7 @@ public void windowOpened(WindowEvent event) { @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == tfield || event.getSource() == bsearch) { - if (tfield.getText() == null || tfield.getText().equals("")) { + if (tfield.getText() == null || tfield.getText().isEmpty()) { return; } new Thread(this).start(); @@ -239,7 +240,7 @@ public void actionPerformed(ActionEvent event) { new ViewFrame(this, ResourceFactory.getResource(entry)); } else if (event.getSource() == binsert) { 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); return; @@ -303,7 +304,7 @@ public void run() { String text = tfield.getText(); regex = Pattern.compile(text, isCase ? 0 : Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(this, "Regular expression error:\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return; @@ -346,9 +347,9 @@ public void run() { progress.setValue(0); list.ensureIndexIsVisible(0); - if (found.size() > 0) { + if (!found.isEmpty()) { Collections.sort(found); - list.setListData(found.toArray(new ResourceWrapper[found.size()])); + list.setListData(found.toArray(new ResourceWrapper[0])); list.setEnabled(true); } } finally { diff --git a/src/org/infinity/search/SearchMaster.java b/src/org/infinity/search/SearchMaster.java index b03b027a9..f9da30e30 100644 --- a/src/org/infinity/search/SearchMaster.java +++ b/src/org/infinity/search/SearchMaster.java @@ -31,6 +31,7 @@ import org.infinity.gui.ChildFrame; import org.infinity.gui.WindowBlocker; import org.infinity.icon.Icons; +import org.infinity.util.Logger; public final class SearchMaster extends JPanel implements Runnable, ActionListener { private final JButton bnext = new JButton("Find Next", Icons.ICON_FIND_AGAIN_16.getIcon()); @@ -209,11 +210,12 @@ public void run() { try { slave.wait(); } catch (InterruptedException e) { + Logger.trace(e); } } blocker.setBlocked(true); bnext.setEnabled(false); - if (tfinput.getText().equals("")) { + if (tfinput.getText().isEmpty()) { term = null; break; } diff --git a/src/org/infinity/search/SearchOptions.java b/src/org/infinity/search/SearchOptions.java index 9b2b0c35b..3f3fafe5c 100644 --- a/src/org/infinity/search/SearchOptions.java +++ b/src/org/infinity/search/SearchOptions.java @@ -19,6 +19,7 @@ import org.infinity.resource.AbstractStruct; import org.infinity.resource.ResourceFactory; import org.infinity.resource.StructEntry; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; import org.infinity.util.tuples.Couple; @@ -289,10 +290,8 @@ public class SearchOptions { public static String getResourceType(String key) { if (key != null) { String[] segments = key.split("\\."); - if (segments != null) { - if (segments.length > 2) { - return segments[segments.length - 3]; - } + if (segments.length > 2) { + return segments[segments.length - 3]; } } return ""; @@ -307,10 +306,8 @@ public static String getResourceType(String key) { public static String getResourceName(String key) { if (key != null) { String[] segments = key.split("\\."); - if (segments != null) { - if (segments.length > 1) { - return segments[segments.length - 2]; - } + if (segments.length > 1) { + return segments[segments.length - 2]; } } return ""; @@ -325,12 +322,11 @@ public static String getResourceName(String key) { public static int getResourceIndex(String key) { if (key != null) { String[] segments = key.split("\\."); - if (segments != null) { - if (segments.length > 0) { - try { - return Integer.parseInt(segments[segments.length - 1]); - } catch (NumberFormatException e) { - } + if (segments.length > 0) { + try { + return Integer.parseInt(segments[segments.length - 1]); + } catch (NumberFormatException e) { + Logger.trace(e); } } } @@ -346,10 +342,8 @@ public static int getResourceIndex(String key) { public static int getResourceNameLevel(String key) { if (key != null) { String[] segments = key.split("\\."); - if (segments != null) { - if (segments.length > 1) { - return segments.length - 2; - } + if (segments.length > 1) { + return segments.length - 2; } } return 0; @@ -364,10 +358,8 @@ public static int getResourceNameLevel(String key) { public static boolean isResourceByOffset(String key) { if (key != null) { String[] segments = key.split("\\."); - if (segments != null) { - if (segments.length > 1) { - return segments[segments.length - 2].startsWith("_"); - } + if (segments.length > 1) { + return segments[segments.length - 2].startsWith("_"); } } return false; @@ -499,7 +491,7 @@ public static boolean matchResourceRef(StructEntry ref, Object value, boolean ca // Returns whether entry contains (or equals) value, optionally taking case-sensitivity into account. public static boolean matchString(StructEntry entry, Object value, boolean exact, boolean caseSensitive) { - if (entry != null && value != null && value instanceof String) { + if (entry != null && value instanceof String) { // preparing source String s1 = (String) value; if (s1.isEmpty()) { @@ -539,7 +531,7 @@ public static boolean matchString(StructEntry entry, Object value, boolean exact // Returns whether all bits match (exact=true) or only the set bits match (exact=false) public static boolean matchFlags(StructEntry flag, Object value) { - if (flag != null && flag instanceof Flag && value != null) { + if (flag instanceof Flag && value != null) { boolean retVal = true; int v; boolean isExact; @@ -557,7 +549,7 @@ public static boolean matchFlags(StructEntry flag, Object value) { for (int mask = 1, bit = 0; bit < (flag.getSize() << 3); bit++, mask <<= 1) { if (isExact) { - if (((v & mask) != 0) != ((Flag) flag).isFlagSet(bit)) { + if (((v & mask) == 0) == ((Flag) flag).isFlagSet(bit)) { retVal = false; break; } @@ -606,7 +598,7 @@ public static boolean matchNumber(StructEntry number, Object value) { } public static boolean matchCustomFilter(AbstractStruct struct, Object match) { - if (struct != null && match != null && match instanceof Couple + if (struct != null && match instanceof Couple && ((Couple) match).getValue0() instanceof String) { String fieldName = (String) ((Couple) match).getValue0(); Object value = ((Couple) match).getValue1(); diff --git a/src/org/infinity/search/SearchResource.java b/src/org/infinity/search/SearchResource.java index cc6ee3f04..88a26a1b3 100644 --- a/src/org/infinity/search/SearchResource.java +++ b/src/org/infinity/search/SearchResource.java @@ -61,6 +61,7 @@ import org.infinity.NearInfinity; import org.infinity.datatype.IdsBitmap; import org.infinity.datatype.IsNumeric; +import org.infinity.datatype.ItemTypeBitmap; import org.infinity.datatype.KitIdsBitmap; import org.infinity.datatype.PriTypeBitmap; import org.infinity.datatype.ProRef; @@ -92,8 +93,9 @@ import org.infinity.resource.sto.StoResource; import org.infinity.resource.ui.ResourceCellRenderer; import org.infinity.resource.ui.ResourceListModel; -import org.infinity.util.Debugging; +import org.infinity.util.DebugTimer; import org.infinity.util.IdsMapEntry; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.SimpleListModel; import org.infinity.util.Threading; @@ -107,6 +109,8 @@ public class SearchResource extends ChildFrame implements ActionListener, Proper private static final String PROPERTY_OPTIONS = "NearInfinity.Options.IsEmpty"; private final HashMap mapOptionsPanel = new HashMap<>(); + private final JProgressBar pbProgress = new JProgressBar(); + private JPanel pFindOptions, pBottomBar; private JList listResults; private JLabel lResults; @@ -118,7 +122,6 @@ public class SearchResource extends ChildFrame implements ActionListener, Proper private JToggleButton bShowHideOptions; private CardLayout clOptions; private CardLayout clBottomBar; - private JProgressBar pbProgress; public SearchResource() { super("Extended search (deprecated)"); @@ -128,7 +131,7 @@ public Void doInBackground() { try { init(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -162,7 +165,7 @@ public void actionPerformed(ActionEvent event) { } } else if (event.getSource() == bInsertRef) { 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); return; @@ -222,7 +225,7 @@ public void run() { // executing search try { - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); OptionsBasePanel panel = mapOptionsPanel.get(type); if (panel != null) { SearchOptions so = panel.getOptions(); @@ -238,10 +241,10 @@ public void run() { try { threadPool.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + Logger.error(e); } } catch (Exception e) { - // ignored + Logger.trace(e); } // preparing results for output @@ -261,7 +264,7 @@ public void run() { } } } finally { - Debugging.timerShow("Extended Search", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted("Extended Search")); blocker.setBlocked(false); bSearch.setEnabled(true); clBottomBar.show(pBottomBar, "buttons"); @@ -412,7 +415,7 @@ public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2) { Rectangle cellRect = listResults.getCellBounds(listResults.getSelectedIndex(), listResults.getSelectedIndex()); - if (cellRect != null && event.getPoint() != null) { + if (cellRect != null) { if (cellRect.contains(event.getPoint())) { actionPerformed(new ActionEvent(bOpen, 0, null)); } @@ -468,7 +471,6 @@ public void mouseClicked(MouseEvent event) { pBottomButtons.add(new JPanel(), c); JPanel pBottomProgress = new JPanel(new GridBagLayout()); - pbProgress = new JProgressBar(); c = ViewerUtil.setGBC(c, 0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0); pBottomProgress.add(pbProgress, c); @@ -2030,17 +2032,17 @@ private void init() { String[] sCat; if ((Boolean) Profile.getProperty(Profile.Key.IS_SUPPORTED_ITM_V11)) { sFlags = ItmResource.FLAGS11_ARRAY; - sCat = ItmResource.CATEGORIES11_ARRAY; + sCat = ItemTypeBitmap.CATEGORIES11_ARRAY; } else if ((Boolean) Profile.getProperty(Profile.Key.IS_SUPPORTED_ITM_V20)) { sFlags = ItmResource.FLAGS_ARRAY; - sCat = ItmResource.CATEGORIES_ARRAY; + sCat = ItemTypeBitmap.CATEGORIES_ARRAY; } else { if (Profile.getGame() == Profile.Game.PSTEE) { sFlags = ItmResource.FLAGS_PSTEE_ARRAY; } else { sFlags = ItmResource.FLAGS_ARRAY; } - sCat = ItmResource.CATEGORIES_ARRAY; + sCat = ItemTypeBitmap.CATEGORIES_ARRAY; } pFlags = new FlagsPanel(4, sFlags); @@ -4752,7 +4754,7 @@ private void init() { col = 4; row = 0; } - c = ViewerUtil.setGBC(c, col + 0, row, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, + c = ViewerUtil.setGBC(c, col, row, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets((row == 0) ? 0 : 4, (col == 0) ? 0 : 16, 0, 0), 0, 0); panel.add(cbStats[i], c); c = ViewerUtil.setGBC(c, col + 1, row, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, @@ -5425,8 +5427,9 @@ private void init() { cbLabel[i] = new JCheckBox(String.format("Category %d:", i + 1)); cbLabel[i].addActionListener(this); - String[] cat = ((Boolean) Profile.getProperty(Profile.Key.IS_SUPPORTED_STO_V11)) ? ItmResource.CATEGORIES11_ARRAY - : ItmResource.CATEGORIES_ARRAY; + String[] cat = ((Boolean) Profile.getProperty(Profile.Key.IS_SUPPORTED_STO_V11)) + ? ItemTypeBitmap.CATEGORIES11_ARRAY + : ItemTypeBitmap.CATEGORIES_ARRAY; cbCategory[i] = new AutoComboBox<>(IndexedString.createArray(cat, 0, 0)); } @@ -5684,7 +5687,7 @@ public static JComboBox getIdsMapEntryList(int bufSize, String name public static JComboBox getIdsMapEntryList(IdsBitmap ids) { final SortedMap map = ids.getBitmap(); - final IdsMapEntry[] list = map.values().toArray(new IdsMapEntry[map.size()]); + final IdsMapEntry[] list = map.values().toArray(new IdsMapEntry[0]); Arrays.sort(list); return defaultWidth(new AutoComboBox<>(list), 160); } @@ -5779,7 +5782,7 @@ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { setSelectedItem(item); } } catch (BadLocationException ble) { - ble.printStackTrace(); + Logger.error(ble); } } @@ -5797,10 +5800,6 @@ public void popupMenuCanceled(PopupMenuEvent e) { public void focusGained(FocusEvent e) { highlightCompletedText(0); } - - @Override - public void focusLost(FocusEvent e) { - } }; configureEditor(comboBox.getEditor()); @@ -5896,9 +5895,7 @@ private boolean compareItem(Object item, String pattern) { id = curItem.toString().toUpperCase(Locale.ENGLISH); } - if (name.startsWith(pattern) || id.startsWith(pattern)) { - return true; - } + return name.startsWith(pattern) || id.startsWith(pattern); } return false; } @@ -5910,7 +5907,7 @@ private void setText(String text) { super.remove(0, getLength()); super.insertString(0, text, null); } catch (BadLocationException e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/search/SongReferenceSearcher.java b/src/org/infinity/search/SongReferenceSearcher.java index 0d401cbab..c44bbf853 100644 --- a/src/org/infinity/search/SongReferenceSearcher.java +++ b/src/org/infinity/search/SongReferenceSearcher.java @@ -25,6 +25,7 @@ import org.infinity.resource.mus.MusResource; import org.infinity.util.IdsMap; import org.infinity.util.IdsMapCache; +import org.infinity.util.Logger; import org.infinity.util.io.StreamUtils; /** @@ -103,7 +104,7 @@ private void searchBcs(ResourceEntry entry, BcsResource bcs) { String text = decompiler.decompile(); searchText(entry, null, text); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/search/StringReferenceSearcher.java b/src/org/infinity/search/StringReferenceSearcher.java index 8e935af87..140bd1a37 100644 --- a/src/org/infinity/search/StringReferenceSearcher.java +++ b/src/org/infinity/search/StringReferenceSearcher.java @@ -25,6 +25,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sav.SavResource; import org.infinity.resource.text.PlainTextResource; +import org.infinity.util.Logger; /** Performs search of the specified string reference in other resources. */ public final class StringReferenceSearcher extends AbstractReferenceSearcher { @@ -95,14 +96,13 @@ private void searchDialog(ResourceEntry entry, AbstractStruct dialog) { decompiler.setGenerateResourcesUsed(true); decompiler.decompile(); for (final Integer stringRef : decompiler.getStringRefsUsed()) { - if (stringRef.intValue() == searchvalue) { + if (stringRef == searchvalue) { addHit(entry, sourceCode.getName(), sourceCode); } } } } catch (Exception e) { - System.out.println("Exception in " + dialog.getName() + " - " + sourceCode.getName()); - e.printStackTrace(); + Logger.error(e, "Exception in {} - {}", dialog.getName(), sourceCode.getName()); } } else if (o instanceof AbstractStruct) { searchDialog(entry, (AbstractStruct) o); @@ -136,12 +136,12 @@ private void searchScript(ResourceEntry entry, BcsResource bcsfile) { try { decompiler.decompile(); for (final Integer stringRef : decompiler.getStringRefsUsed()) { - if (stringRef.intValue() == searchvalue) { + if (stringRef == searchvalue) { addHit(entry, null, null); } } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/search/TextResourceSearcher.java b/src/org/infinity/search/TextResourceSearcher.java index 8dc6bf83a..38a16e335 100644 --- a/src/org/infinity/search/TextResourceSearcher.java +++ b/src/org/infinity/search/TextResourceSearcher.java @@ -32,6 +32,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.TextResource; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.Logger; public final class TextResourceSearcher extends AbstractSearcher implements Runnable, ActionListener { private final ChildFrame inputFrame; @@ -177,9 +178,7 @@ protected Runnable newWorker(ResourceEntry entry) { } } } catch (IOException e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } } advanceProgress(); diff --git a/src/org/infinity/search/advanced/AdvancedSearch.java b/src/org/infinity/search/advanced/AdvancedSearch.java index 70482bb7a..a10eea936 100644 --- a/src/org/infinity/search/advanced/AdvancedSearch.java +++ b/src/org/infinity/search/advanced/AdvancedSearch.java @@ -74,7 +74,8 @@ import org.infinity.resource.dlg.DlgResource; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.ReferenceHitFrame; -import org.infinity.util.Debugging; +import org.infinity.util.DebugTimer; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.SimpleListModel; import org.infinity.util.Threading; @@ -175,7 +176,7 @@ public Void doInBackground() { try { init(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -556,7 +557,7 @@ public void run() { // executing search try { - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); List searchOptions = getSearchOptions(); // using parallel jobs to speed up search @@ -570,7 +571,7 @@ public void run() { try { threadPool.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + Logger.error(e); } } catch (Exception e) { // ignored @@ -590,13 +591,13 @@ public void run() { // determine number of unique resource entries in the results list HashSet entrySet = new HashSet<>(); - resourceCount = found.stream().filter(e -> entrySet.add(e.getResource())).collect(Collectors.toList()).size(); + resourceCount = (int) found.stream().filter(e -> entrySet.add(e.getResource())).count(); } lResultsStatus.setText(String.format("(%d match%s in %d resource%s found)", found.size(), found.size() == 1 ? "" : "es", resourceCount, resourceCount == 1 ? "" : "s")); } finally { - Debugging.timerShow("Advanced Search", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted("Advanced Search")); blocker.setBlocked(false); bSearch.setEnabled(true); clBottomBar.show(pBottomBar, STATUS_BUTTONS); @@ -633,6 +634,7 @@ private FilterMode getCurrentFilterMode() { try { return (FilterMode) ((ToggleButtonDataModel) bgFilterMode.getSelection()).getData(); } catch (Exception e) { + Logger.trace(e); } return null; } @@ -676,7 +678,7 @@ private boolean importConfig(File xmlFile) { filterList.setSelectedIndex(0); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return false; } return true; @@ -688,7 +690,7 @@ private boolean exportConfig(File xmlFile) { return XmlConfig.Export(xmlFile, cbResourceTypes.getSelectedItem().toString(), getSelectedFilterMode(), getSearchOptions()); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); return false; } } @@ -871,7 +873,7 @@ public void mouseClicked(MouseEvent event) { if (!event.isPopupTrigger() && event.getClickCount() == 2) { // double click triggers filter edit Rectangle cellRect = filterList.getCellBounds(filterList.getSelectedIndex(), filterList.getSelectedIndex()); - if (cellRect != null && event.getPoint() != null && cellRect.contains(event.getPoint())) { + if (cellRect != null && cellRect.contains(event.getPoint())) { listeners.actionPerformed(new ActionEvent(bFilterEdit, 0, null)); } } @@ -946,7 +948,7 @@ public void contentsChanged(ListDataEvent event) { public void popupMenuWillBecomeVisible(PopupMenuEvent event) { if (event.getSource() == menuFilters) { // update menu item states based on current filter list state - List items = Arrays.asList(menuFilters.getComponents()).stream().filter(c -> c instanceof JMenuItem) + List items = Arrays.stream(menuFilters.getComponents()).filter(c -> c instanceof JMenuItem) .collect(Collectors.toList()); for (int i = 0, cnt = items.size(); i < cnt; i++) { JMenuItem mi = (JMenuItem) items.get(i); diff --git a/src/org/infinity/search/advanced/AdvancedSearchWorker.java b/src/org/infinity/search/advanced/AdvancedSearchWorker.java index 9eda495d5..fce5e5c0c 100644 --- a/src/org/infinity/search/advanced/AdvancedSearchWorker.java +++ b/src/org/infinity/search/advanced/AdvancedSearchWorker.java @@ -24,6 +24,7 @@ import org.infinity.resource.StructEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.search.ReferenceHitFrame; +import org.infinity.util.Logger; /** * Worker class for performing a full match against a resource entry. @@ -65,15 +66,13 @@ public void run() { Map, Set> groupCache = new HashMap<>(); int matches = 0; - for (int filterIdx = 0; filterIdx < searchOptions.size(); filterIdx++) { - SearchOptions so = searchOptions.get(filterIdx); - + for (SearchOptions so : searchOptions) { // keep track of grouped filter count per structure if (so.isStructureGroup()) { Integer count = groupFilters.get(so.getStructure()); if (count == null) - count = Integer.valueOf(0); - groupFilters.put(so.getStructure(), Integer.valueOf(count.intValue() + 1)); + count = 0; + groupFilters.put(so.getStructure(), count + 1); } // list of structures to search @@ -187,7 +186,7 @@ private void collapseGroupFilters(Map, Set> groupCache groupSet.removeAll(structureSet); break; case MATCH_ANY: - if (structureSet.size() == 0) + if (structureSet.isEmpty()) groupSet.removeAll(structureSet); break; case MATCH_ONE: @@ -199,11 +198,11 @@ private void collapseGroupFilters(Map, Set> groupCache } // structure level entry can be removed if it contains no matches - if (groupSet.size() == 0) { + if (groupSet.isEmpty()) { iter.remove(); } } else { - System.err.println("Skipping unidentified group match"); + Logger.warn("Skipping unidentified group match"); iter.remove(); } } @@ -298,6 +297,7 @@ else if (text.trim().endsWith("h")) number = Integer.parseInt(text.trim()); isNumber = true; } catch (NumberFormatException e) { + Logger.trace(e); } Pattern pattern; @@ -338,10 +338,7 @@ else if (text.trim().endsWith("h")) } // "catch all" check - if (pattern.matcher(se.toString()).find()) - return true; - - return false; + return pattern.matcher(se.toString()).find(); } // Match value numerically diff --git a/src/org/infinity/search/advanced/FilterInput.java b/src/org/infinity/search/advanced/FilterInput.java index f54b115fc..39961f17d 100644 --- a/src/org/infinity/search/advanced/FilterInput.java +++ b/src/org/infinity/search/advanced/FilterInput.java @@ -71,6 +71,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.ui.ResourceListModel; import org.infinity.util.DataString; +import org.infinity.util.Logger; /** * Input dialog for a advanced search filter definition. @@ -574,9 +575,7 @@ private void setStructureEnabled(boolean set) { private static Vector getValueResourceTypes(boolean addEmpty) { Vector list = new Vector<>(); String[] types = Profile.getAvailableResourceTypes(); - for (String type : types) { - list.add(type); - } + Collections.addAll(list, types); Collections.sort(list); if (addEmpty) { @@ -894,7 +893,7 @@ private boolean signalCreate(String name, int count) { * A method for synchronization purposes. Releases the specified synchronization object. */ private void signalRelease(String name) { - if (name != null && signalMap.containsKey(name)) { + if (name != null) { signalMap.remove(name); } } @@ -921,7 +920,7 @@ private void signalAwait(String name, int timeoutMs) { } signal.await(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1051,7 +1050,7 @@ protected Void doInBackground() throws Exception { JPopupMenu menu = (mi.getParent() instanceof JPopupMenu) ? (JPopupMenu) mi.getParent() : null; JFormattedTextField ftf = menuToTextFieldMap.get(menu); if (menu != null && ftf != null) { - List list = Arrays.asList(menu.getComponents()).stream().filter(c -> c instanceof JMenuItem) + List list = Arrays.stream(menu.getComponents()).filter(c -> c instanceof JMenuItem) .collect(Collectors.toList()); switch (list.indexOf(mi)) { case 0: // dec @@ -1100,7 +1099,7 @@ public void mouseClicked(MouseEvent event) { JTextField edit = (JTextField) event.getSource(); if (event.getClickCount() == 2) { // Invoke later to circumvent content validation (may not work correctly on every platform) - SwingUtilities.invokeLater(() -> edit.selectAll()); + SwingUtilities.invokeLater(edit::selectAll); } else if (!event.isPopupTrigger()) { edit.setCaretPosition(edit.viewToModel(event.getPoint())); // SwingUtilities.invokeLater(() -> edit.setCaretPosition(edit.viewToModel(event.getPoint()))); @@ -1212,7 +1211,7 @@ public void popupMenuWillBecomeVisible(PopupMenuEvent event) { JFormattedTextField ftf = menuToTextFieldMap.get(menu); if (ftf != null) { NumberFormatterEx.NumberFormat fmt = ((NumberFormatterEx) ftf.getFormatter()).getNumberFormat(); - List list = Arrays.asList(menu.getComponents()).stream().filter(c -> c instanceof JMenuItem) + List list = Arrays.stream(menu.getComponents()).filter(c -> c instanceof JMenuItem) .collect(Collectors.toList()); if (list.size() >= 2) { list.get(0).setEnabled(fmt != NumberFormatterEx.NumberFormat.DECIMAL); diff --git a/src/org/infinity/search/advanced/FlagsPanel.java b/src/org/infinity/search/advanced/FlagsPanel.java index ec0f1dccb..b366cb2f8 100644 --- a/src/org/infinity/search/advanced/FlagsPanel.java +++ b/src/org/infinity/search/advanced/FlagsPanel.java @@ -62,8 +62,8 @@ public int getValue() { /** Sets the bits according to the specified value. */ public void setValue(int value) { - for (int i = 0; i < cbFlags.length; i++) { - cbFlags[i].setSelected((value & 1) != 0); + for (JCheckBox cbFlag : cbFlags) { + cbFlag.setSelected((value & 1) != 0); value >>>= 1; } } diff --git a/src/org/infinity/search/advanced/NumberFormatterEx.java b/src/org/infinity/search/advanced/NumberFormatterEx.java index 5c7bc92de..9ea19c3d0 100644 --- a/src/org/infinity/search/advanced/NumberFormatterEx.java +++ b/src/org/infinity/search/advanced/NumberFormatterEx.java @@ -11,6 +11,7 @@ import javax.swing.JFormattedTextField.AbstractFormatter; import org.infinity.util.DataString; +import org.infinity.util.Logger; /** * A simplified NumberFormatter that handles conversion from Object to String and back. Allowed text input is limited to @@ -32,10 +33,11 @@ public enum NumberFormat { private static final String FMT_DEC = "%d"; private static final String FMT_HEX = "%x h"; + private final long valueMin; + private final long valueMax; + private final long defaultValue; + private NumberFormat numberFormat; - private long valueMin; - private long valueMax; - private long defaultValue; private long currentValue; /** @@ -66,8 +68,8 @@ public NumberFormatterEx(NumberFormat format) { */ public NumberFormatterEx(NumberFormat format, long minValue, long maxValue, long defaultValue) { this.numberFormat = (format != null) ? format : NumberFormat.DECIMAL; - this.valueMin = (minValue < maxValue) ? minValue : maxValue; - this.valueMax = (maxValue > minValue) ? maxValue : minValue; + this.valueMin = Math.min(minValue, maxValue); + this.valueMax = Math.max(maxValue, minValue); this.defaultValue = getBoundedValue(defaultValue); this.currentValue = this.defaultValue; } @@ -77,9 +79,9 @@ public Object stringToValue(String text) throws ParseException { currentValue = convertToNumber(text); switch (numberFormat) { case HEXADECIMAL: - return DataString.with(String.format(FMT_HEX, currentValue), Long.valueOf(currentValue), ""); + return DataString.with(String.format(FMT_HEX, currentValue), currentValue, ""); default: - return DataString.with(String.format(FMT_DEC, currentValue), Long.valueOf(currentValue), ""); + return DataString.with(String.format(FMT_DEC, currentValue), currentValue, ""); } } @@ -145,6 +147,7 @@ public long getNumericValue() { try { return getNumericValue(getFormattedTextField().getText()); } catch (Exception e) { + Logger.trace(e); } return currentValue; } @@ -195,7 +198,7 @@ private long convertToNumber(String text) throws ParseException { if (m.start(1) > 0) s = text.substring(0, m.start(1)); if (m.end(1) < text.length()) - s = s + text.substring(m.end(1), text.length()); + s = s + text.substring(m.end(1)); text = s; } } diff --git a/src/org/infinity/search/advanced/SearchOptions.java b/src/org/infinity/search/advanced/SearchOptions.java index c44f1d3ea..1a523ee35 100644 --- a/src/org/infinity/search/advanced/SearchOptions.java +++ b/src/org/infinity/search/advanced/SearchOptions.java @@ -198,7 +198,7 @@ public void setSearchOffsetAbsolute(int offset) { public void setSearchOffset(FieldMode mode, int offset) { if (mode == FieldMode.BY_RELATIVE_OFFSET || mode == FieldMode.BY_ABSOLUTE_OFFSET) { searchType = mode; - searchOffset = (offset >= 0) ? offset : 0; + searchOffset = Math.max(offset, 0); } } @@ -255,8 +255,8 @@ public void setValueNumber(int value) { /** Sets lower and upper bound of numeric value, and value type to "Number". */ public void setValueNumber(int valueMin, int valueMax) { valueType = ValueType.NUMBER; - valueNumberMin = (valueMin < valueMax) ? valueMin : valueMax; - valueNumberMax = (valueMax > valueMin) ? valueMax : valueMin; + valueNumberMin = Math.min(valueMin, valueMax); + valueNumberMax = Math.max(valueMax, valueMin); } /** Returns resource type (only if value type is "Resource"). */ @@ -483,22 +483,22 @@ private void init(SearchOptions so) { structure.clear(); if (so != null) structure.addAll(so.structure); - structureRecursive = (so != null) ? so.structureRecursive : false; - structureRegex = (so != null) ? so.structureRegex : false; - structureGroup = (so != null) ? so.structureGroup : true; + structureRecursive = so != null && so.structureRecursive; + structureRegex = so != null && so.structureRegex; + structureGroup = so == null || so.structureGroup; searchType = (so != null) ? so.searchType : FieldMode.BY_NAME; searchName = (so != null) ? so.searchName : ""; - searchNameCase = (so != null) ? so.searchNameCase : false; - searchNameRegex = (so != null) ? so.searchNameRegex : false; + searchNameCase = so != null && so.searchNameCase; + searchNameRegex = so != null && so.searchNameRegex; searchOffset = (so != null) ? so.searchOffset : 0; valueType = (so != null) ? so.valueType : ValueType.TEXT; valueText = (so != null) ? so.valueText : ""; - valueTextCase = (so != null) ? so.valueTextCase : false; - valueTextRegex = (so != null) ? so.valueTextRegex : false; + valueTextCase = so != null && so.valueTextCase; + valueTextRegex = so != null && so.valueTextRegex; valueNumberMin = (so != null) ? so.valueNumberMin : 0; valueNumberMax = (so != null) ? so.valueNumberMax : 32767; valueResourceType = (so != null) ? so.valueResourceType : ""; bitFieldMode = (so != null) ? so.bitFieldMode : BitFieldMode.AND; - invertMatch = (so != null) ? so.invertMatch : false; + invertMatch = so != null && so.invertMatch; } } diff --git a/src/org/infinity/search/advanced/XmlConfig.java b/src/org/infinity/search/advanced/XmlConfig.java index dc42e07a5..8b13d7130 100644 --- a/src/org/infinity/search/advanced/XmlConfig.java +++ b/src/org/infinity/search/advanced/XmlConfig.java @@ -27,6 +27,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.infinity.util.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -151,7 +152,7 @@ public static boolean Export(OutputStream xmlOut, String resourceType, AdvancedS try { builder = domFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { - e.printStackTrace(); + Logger.error(e); return false; } Document document = builder.newDocument(); @@ -318,7 +319,7 @@ public static boolean Export(OutputStream xmlOut, String resourceType, AdvancedS StreamResult sr = new StreamResult(xmlOut); transformer.transform(domSource, sr); } catch (TransformerException e) { - e.printStackTrace(); + Logger.error(e); return false; } @@ -386,17 +387,17 @@ public static XmlConfig Import(InputStream xmlIn) throws IOException, ParserConf builder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { - exception.printStackTrace(); + Logger.error(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { - exception.printStackTrace(); + Logger.error(exception); } @Override public void error(SAXParseException exception) throws SAXException { - exception.printStackTrace(); + Logger.error(exception); } }); @@ -1028,7 +1029,7 @@ private int parseNumber(String text) throws NumberFormatException { // sb.append(c); // isEntity = true; // } catch (NumberFormatException e) { - // e.printStackTrace(); + // Logger.error(e); // } // } // } diff --git a/src/org/infinity/tinylog.License.txt b/src/org/infinity/tinylog.License.txt new file mode 100644 index 000000000..f433b1a53 --- /dev/null +++ b/src/org/infinity/tinylog.License.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/src/org/infinity/updater/UpdateCheck.java b/src/org/infinity/updater/UpdateCheck.java index 750f1ef3e..ad405edbc 100644 --- a/src/org/infinity/updater/UpdateCheck.java +++ b/src/org/infinity/updater/UpdateCheck.java @@ -42,6 +42,7 @@ import org.infinity.gui.ViewerUtil; import org.infinity.gui.WindowBlocker; import org.infinity.updater.UpdateInfo.Release; +import org.infinity.util.Logger; /** * Shows information about available updates and providing options how to deal with them. @@ -150,6 +151,7 @@ public void actionPerformed(ActionEvent e) { try { fileSize = (int) getUpdateInfo().getRelease().getDefaultAsset().size; } catch (Exception e) { + Logger.trace(e); } } finally { WindowBlocker.blockWindow(NearInfinity.getInstance(), false); @@ -335,8 +337,8 @@ private boolean hasChangelog() { final Release release = getUpdateInfo().getRelease(); final String[] lines = release.body.split("\r?\n"); - for (int i = 0; i < lines.length; i++) { - final String line = lines[i].toLowerCase(); + for (String s : lines) { + final String line = s.toLowerCase(); if (line.contains("changelog:") || line.contains("changes:")) { retVal = true; break; diff --git a/src/org/infinity/updater/UpdateInfo.java b/src/org/infinity/updater/UpdateInfo.java index 2f2f0c433..1a0dc3dc2 100644 --- a/src/org/infinity/updater/UpdateInfo.java +++ b/src/org/infinity/updater/UpdateInfo.java @@ -7,7 +7,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -23,6 +22,7 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import org.infinity.util.Logger; import org.infinity.util.Misc; import org.infinity.util.io.StreamUtils; import org.infinity.util.tuples.Couple; @@ -78,11 +78,7 @@ public enum FileType { * @return {@code true} if the string conforms to the update.xml specification, {@code false} otherwise. */ public static boolean isValidXml(String s, String systemId) { - try { - return isValidXml(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8.name())), systemId); - } catch (UnsupportedEncodingException e) { - } - return false; + return isValidXml(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), systemId); } /** @@ -95,6 +91,7 @@ public static boolean isValidXml(Path f) { try (InputStream is = StreamUtils.getInputStream(f)) { return isValidXml(is, f.getParent().toAbsolutePath().toString()); } catch (IOException e) { + Logger.trace(e); } return false; } @@ -114,6 +111,7 @@ public static boolean isValidXml(InputStream is, String systemId) { Document doc = dBuilder.parse(is, systemId); return NODE_UPDATE.equals(doc.getDocumentElement().getNodeName()); } catch (Exception e) { + Logger.trace(e); } return false; } @@ -146,7 +144,7 @@ public UpdateInfo(Path f) throws Exception { * @param systemId Base path for relative URIs (required for Doctype reference). */ public UpdateInfo(String s, String systemId) throws Exception { - parseXml(new ByteArrayInputStream(s.getBytes("UTF-8")), systemId); + parseXml(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), systemId); } /** @@ -570,7 +568,7 @@ private void parseJson(String jsonString) throws Exception { reactions = new Reactions(root.getJSONObject(key)); break; default: - System.out.printf("Release parser: Skipping unknown key \"%s\"\n", key); + Logger.info("Release parser: Skipping unknown key \"{}\"", key); } } @@ -722,7 +720,7 @@ private User(JSONObject jsonUser) throws Exception { siteAdmin = root.getBoolean(key); break; default: - System.out.printf("User parser: Skipping unknown key \"%s\"\n", key); + Logger.info("User parser: Skipping unknown key \"{}\"", key); } } @@ -870,7 +868,7 @@ private Asset(JSONObject jsonAsset) throws Exception { browserDownloadUrl = new URL(root.getString(key)); break; default: - System.out.printf("Asset parser: Skipping unknown key \"%s\"\n", key); + Logger.info("Asset parser: Skipping unknown key \"{}\"", key); } } @@ -972,7 +970,7 @@ private Reactions(JSONObject jsonReactions) throws Exception { eyes = root.getInt(key); break; default: - System.out.printf("Reactions parser: Skipping unknown key \"%s\"\n", key); + Logger.info("Reactions parser: Skipping unknown key \"{}\"", key); } } diff --git a/src/org/infinity/updater/Updater.java b/src/org/infinity/updater/Updater.java index 77a0521f9..fddce3f33 100644 --- a/src/org/infinity/updater/Updater.java +++ b/src/org/infinity/updater/Updater.java @@ -4,13 +4,14 @@ package org.infinity.updater; -import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.time.Duration; import java.time.OffsetDateTime; @@ -28,6 +29,7 @@ import java.util.zip.ZipEntry; import org.infinity.NearInfinity; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -190,7 +192,7 @@ public static boolean isNewRelease(UpdateInfo.Release release, boolean onlyOnce) final long[] newVersion = getNormalizedVersion(release.tagName); compare = compareNormalizedVersion(newVersion, curVersion); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } retVal = (compare > 0); @@ -203,7 +205,7 @@ public static boolean isNewRelease(UpdateInfo.Release release, boolean onlyOnce) /** Returns the modification time of the current JAR's MANIFEST.MF as {@link FileTime} instance. */ static FileTime getJarFileTimeValue() throws Exception { String jarPath = Utils.getJarFileName(NearInfinity.class); - if (jarPath != null && !jarPath.isEmpty()) { + if (!jarPath.isEmpty()) { try (JarFile jf = new JarFile(jarPath)) { ZipEntry manifest = jf.getEntry("META-INF/MANIFEST.MF"); if (manifest != null) { @@ -224,7 +226,7 @@ static OffsetDateTime getJarFileDateTime() { return OffsetDateTime.ofInstant(ft.toInstant(), ZoneId.systemDefault()); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return null; } @@ -236,12 +238,13 @@ static OffsetDateTime getJarFileDateTime() { */ static String getJarFileHash() { String path = Utils.getJarFileName(NearInfinity.class); - if (path != null && !path.isEmpty()) { + if (!path.isEmpty()) { Path jarPath = FileManager.resolve(path); if (FileEx.create(jarPath).isFile()) { try { - return Utils.generateMD5Hash(new FileInputStream(path)); + return Utils.generateMD5Hash(Files.newInputStream(Paths.get(path))); } catch (IOException e) { + Logger.trace(e); } } } @@ -293,7 +296,7 @@ private static long[] getNormalizedVersion(String s) { long[] retVal = new long[items.size()]; for (int i = 0; i < retVal.length; i++) { - retVal[i] = items.get(i).longValue(); + retVal[i] = items.get(i); } return retVal; @@ -338,7 +341,7 @@ private Updater() { prefs = Preferences.userNodeForPackage(getClass()); } catch (SecurityException se) { prefs = null; - se.printStackTrace(); + Logger.error(se); } loadUpdateSettings(); @@ -369,8 +372,8 @@ public void addServer(String link, boolean validate) throws MalformedURLExceptio } if (isValid) { // checking if server is already in list - for (Iterator iter = serverList.iterator(); iter.hasNext();) { - if (isSameServer(link, iter.next())) { + for (String s : serverList) { + if (isSameServer(link, s)) { // consider both links as equal return; } @@ -430,7 +433,7 @@ public boolean hasAutoUpdateCheckDateExpired(Interval interval) { interval = Interval.getDefault(); } OffsetDateTime intervalExpiredAt = getAutoUpdateCheckDate().plus(interval.getInterval()); - return intervalExpiredAt.compareTo(OffsetDateTime.now()) < 0; + return intervalExpiredAt.isBefore(OffsetDateTime.now()); } /** Returns whether to use a proxy for accessing remote servers. */ @@ -526,8 +529,8 @@ public void loadUpdateSettings() { if (!server.isEmpty()) { // skip duplicate server URLs boolean isSame = false; - for (Iterator iter = serverList.iterator(); iter.hasNext();) { - if (isSameServer(server, iter.next())) { + for (String s : serverList) { + if (isSameServer(server, s)) { isSame = true; break; } @@ -545,7 +548,7 @@ public void loadUpdateSettings() { try { autoCheckDate = Utils.getDateTimeFromString(dateTime); } catch (DateTimeParseException e) { - System.out.println("DateTimeParseException: " + e.getMessage()); + Logger.warn("DateTimeParseException: {}", e.getMessage()); autoCheckDate = OffsetDateTime.now(); } @@ -561,7 +564,7 @@ public void loadUpdateSettings() { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -636,6 +639,7 @@ public String getValidatedUpdateUrl(String link) throws MalformedURLException, I try { xml = Utils.downloadText(url, getProxy(), "utf-8"); } catch (IOException e) { + Logger.trace(e); } if (xml != null && UpdateInfo.isValidXml(xml, url.toExternalForm())) { return url.toExternalForm(); @@ -647,6 +651,7 @@ public String getValidatedUpdateUrl(String link) throws MalformedURLException, I return url.toExternalForm(); } } catch (MalformedURLException e) { + Logger.trace(e); } } return null; @@ -671,6 +676,7 @@ public UpdateInfo loadUpdateInfo() throws Exception { addServer(info.getGeneral().getServer(i), true); } catch (Exception e) { // skip adding server on error + Logger.trace(e); } } @@ -678,6 +684,7 @@ public UpdateInfo loadUpdateInfo() throws Exception { } } catch (IOException e) { // skip update server on error and try next + Logger.trace(e); } } return null; diff --git a/src/org/infinity/updater/UpdaterSettings.java b/src/org/infinity/updater/UpdaterSettings.java index d08ff39fb..29eed4032 100644 --- a/src/org/infinity/updater/UpdaterSettings.java +++ b/src/org/infinity/updater/UpdaterSettings.java @@ -18,7 +18,6 @@ import java.net.MalformedURLException; import java.net.Proxy; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import javax.swing.AbstractAction; @@ -40,6 +39,7 @@ import org.infinity.gui.ViewerUtil; import org.infinity.gui.WindowBlocker; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -238,8 +238,8 @@ private void saveSettings() { if (Utils.isUrlValid(url)) { // skip duplicate server URLs boolean isSame = false; - for (Iterator iter = serverList.iterator(); iter.hasNext();) { - if (Updater.isSameServer(url, iter.next())) { + for (String s : serverList) { + if (Updater.isSameServer(url, s)) { isSame = true; break; } @@ -339,6 +339,7 @@ private boolean validateSettings() { InetSocketAddress addr = new InetSocketAddress(s, port); url = addr.getHostName(); } catch (Exception e) { + Logger.trace(e); } if (url != null && !url.isEmpty()) { tfProxyAddress.setText(url); diff --git a/src/org/infinity/updater/Utils.java b/src/org/infinity/updater/Utils.java index 561b86ee0..bdbeeb15e 100644 --- a/src/org/infinity/updater/Utils.java +++ b/src/org/infinity/updater/Utils.java @@ -45,6 +45,7 @@ import javax.net.ssl.SSLPeerUnverifiedException; import org.infinity.util.LauncherUtils; +import org.infinity.util.Logger; import org.infinity.util.io.FileEx; /** @@ -52,12 +53,12 @@ */ public class Utils { /** - * ISO date-time formatter that formats or parses a date-time with anoffset, such as '2011-12-03T10:15:30+01:00'. + * ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'. *

* This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended offset date-time format. * The format consists of: *

    - *
  • The {@link #ISO_LOCAL_DATE_TIME} + *
  • The {@code ISO_DATE_TIME} *
  • The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then they will be handled even though * this is not part of the ISO-8601 standard. Parsing is case insensitive. *
@@ -146,7 +147,7 @@ public static String getJavaExecutable() { * * @return The full path of the current JAR file or an empty string on error. */ - public static String getJarFileName(Class classType) { + public static String getJarFileName(Class classType) { if (classType != null) { URL url = classType.getProtectionDomain().getCodeSource().getLocation(); if (url != null) { @@ -156,6 +157,7 @@ public static String getJarFileName(Class classType) { return file.toString(); } } catch (URISyntaxException e) { + Logger.trace(e); } } } @@ -187,7 +189,7 @@ public static String generateMD5Hash(InputStream is) { return sb.toString(); } catch (NoSuchAlgorithmException | IOException ioe) { - ioe.printStackTrace(); + Logger.error(ioe); } } return ""; @@ -258,6 +260,7 @@ public static boolean isUrlAvailable(URL url, Proxy proxy) try (InputStream is = url.openStream()) { return true; } catch (IOException e) { + Logger.trace(e); } } } @@ -296,7 +299,7 @@ public static URL getUrl(URL base, String path) throws MalformedURLException { // try absolute url first retVal = new URL(path); } catch (MalformedURLException mue) { - retVal = null; + Logger.trace(mue); } if (retVal == null && base != null) { @@ -334,6 +337,7 @@ public static boolean isSecureUrl(String link) { URL url = new URL(link); return url.getProtocol().equalsIgnoreCase("https"); } catch (MalformedURLException e) { + Logger.trace(e); } } return false; @@ -449,6 +453,7 @@ public static String downloadText(URL url, Proxy proxy, Charset charset) try { retVal = baos.toString(charset.name()); } catch (UnsupportedEncodingException e) { + Logger.trace(e); } } baos = null; @@ -519,24 +524,20 @@ static boolean downloadRaw(InputStream is, OutputStream os, URL url, Proxy proxy throws UnknownServiceException, ProtocolException, IOException { if (is != null && os != null) { byte[] buffer = new byte[4096]; - try { - int totalSize = getFileSizeUrl(url, proxy); - int curSize = 0; - int size; - while ((size = is.read(buffer)) > 0) { - os.write(buffer, 0, size); - curSize += size; - if (fireProgressEvent(listeners, url, curSize, totalSize, false)) { - os.flush(); - return false; - } + int totalSize = getFileSizeUrl(url, proxy); + int curSize = 0; + int size; + while ((size = is.read(buffer)) > 0) { + os.write(buffer, 0, size); + curSize += size; + if (fireProgressEvent(listeners, url, curSize, totalSize, false)) { + os.flush(); + return false; } - os.flush(); - fireProgressEvent(listeners, url, curSize, totalSize, true); - return true; - } finally { - buffer = null; } + os.flush(); + fireProgressEvent(listeners, url, curSize, totalSize, true); + return true; } return false; } diff --git a/src/org/infinity/util/ArrayUtil.java b/src/org/infinity/util/ArrayUtil.java index 08ad9e231..a1abc9bca 100644 --- a/src/org/infinity/util/ArrayUtil.java +++ b/src/org/infinity/util/ArrayUtil.java @@ -4,6 +4,7 @@ package org.infinity.util; +import java.lang.reflect.Array; import java.util.Arrays; import java.util.Comparator; import java.util.Objects; @@ -13,21 +14,18 @@ public final class ArrayUtil { * Merges two or more byte arrays into one. * * @param first The first array to be placed into the new array. - * @param second The second array, needed to ensure a minimum parameter count of 2. * @param more More byte arrays to merge. * @return A new byte array containing the data of every specified array. */ - public static byte[] mergeArrays(byte[] first, byte[] second, byte[]... more) { - int totalLength = first.length + second.length; - for (byte[] ar : more) { - totalLength += ar.length; + public static byte[] mergeArrays(byte[] first, byte[]... more) { + int totalLength = Objects.requireNonNull(first).length; + for (final byte[] ar : more) { + totalLength += Objects.requireNonNull(ar).length; } - byte[] res = Arrays.copyOf(first, totalLength); + final byte[] res = Arrays.copyOf(first, totalLength); int offset = first.length; - System.arraycopy(second, 0, res, offset, second.length); - offset += second.length; - for (byte[] ar : more) { + for (final byte[] ar : more) { System.arraycopy(ar, 0, res, offset, ar.length); offset += ar.length; } @@ -35,6 +33,51 @@ public static byte[] mergeArrays(byte[] first, byte[] second, byte[]... more) { return res; } + /** + * Merges one or more arrays into a single array. + * + * @param first The first array to be placed into the new array. + * @param more More arrays to merge. + * @param The array type. + * @return A new array containing the data of every specified array. + * @throws IllegalArgumentException if any of the arguments is not an array or if not all specified arrays are of + * the the same component type. + */ + @SafeVarargs + public static T mergeArrays(T first, T... more) { + if (!first.getClass().isArray()) { + throw new IllegalArgumentException("Argument is not an array"); + } + final Class compTypeFirst = first.getClass().getComponentType(); + + int totalSize = Array.getLength(first); + for (final T item : more) { + if (!Objects.requireNonNull(item).getClass().isArray()) { + throw new IllegalArgumentException("Argument is not an array"); + } + + final Class compType = item.getClass().getComponentType(); + if (!compTypeFirst.equals(compType)) { + throw new IllegalArgumentException("Arrays have different type"); + } + + totalSize += Array.getLength(item); + } + + @SuppressWarnings("unchecked") + final T retVal = (T) Array.newInstance(compTypeFirst, totalSize); + + int ofs = Array.getLength(first); + System.arraycopy(first, 0, retVal, 0, ofs); + for (final T item : more) { + final int size = Array.getLength(item); + System.arraycopy(item, 0, retVal, ofs, size); + ofs += size; + } + + return retVal; + } + /** * Searches an unsorted array of objects for a specific element in linear time. * @@ -45,7 +88,9 @@ public static byte[] mergeArrays(byte[] first, byte[] second, byte[]... more) { public static int indexOf(T[] array, T obj) { if (array != null && array.length > 0) { for (int i = 0; i < array.length; i++) { - if (array[i] == obj) { + if (obj == null && array[i] == null) { + return i; + } else if (obj != null && obj.equals(array[i])) { return i; } } @@ -53,6 +98,24 @@ public static int indexOf(T[] array, T obj) { return -1; } + /** + * Reimplementation of {@code Arrays.compare} from Java 9, because minimum supported version now is Java 8. + * + * @param a the first array to compare + * @param b the second array to compare + * @param the type of array elements which must support the {@link Comparable} interface. + * + * @return the value {@code 0} if the first and second array are equal and contain the same elements in the same + * order; a value less than {@code 0} if the first array is lexicographically less than the second array; and + * a value greater than {@code 0} if the first array is lexicographically greater than the second array + * + * @throws NullPointerException if the comparator is {@code null} + */ + // TODO: Replace with Arrays.compare when minimum supported version raised to Java 9+ + public static > int compare(T[] a, T[] b) { + return compare(a, b, Comparator.naturalOrder()); + } + /** * Reimplementation of {@code Arrays.compare} from Java 9, because minimum supported version now is Java 8. * @@ -67,8 +130,8 @@ public static int indexOf(T[] array, T obj) { * * @throws NullPointerException if the comparator is {@code null} */ + // TODO: Replace with Arrays.compare when minimum supported version raised to Java 9+ public static int compare(T[] a, T[] b, Comparator cmp) { - // TODO: Replace with Arrays.compare when minimum supported version raised to Java 9 Objects.requireNonNull(cmp); if (a == b) { return 0; diff --git a/src/org/infinity/util/BOMStringReader.java b/src/org/infinity/util/BOMStringReader.java index 4462115e2..cb1582b69 100644 --- a/src/org/infinity/util/BOMStringReader.java +++ b/src/org/infinity/util/BOMStringReader.java @@ -37,6 +37,7 @@ public BOMStringReader(String s, boolean skipBOM) { reset(); } } catch (IOException e) { + Logger.trace(e); } } } diff --git a/src/org/infinity/util/BinPack2D.java b/src/org/infinity/util/BinPack2D.java index 4ba1a54f0..24398c6f7 100644 --- a/src/org/infinity/util/BinPack2D.java +++ b/src/org/infinity/util/BinPack2D.java @@ -157,7 +157,7 @@ public void insert(List rects, List dst, HeuristicRules ru if (rects != null && dst != null) { dst.clear(); - while (rects.size() > 0) { + while (!rects.isEmpty()) { int bestScore1 = Integer.MAX_VALUE; int bestScore2 = Integer.MAX_VALUE; int bestRectIndex = -1; @@ -241,7 +241,7 @@ public Rectangle insert(int width, int height, HeuristicRules rule) { public float getOccupancy() { long usedSurfaceArea = 0L; for (Rectangle r : usedRectangles) { - usedSurfaceArea += r.width * r.height; + usedSurfaceArea += (long) r.width * r.height; } return (float) (usedSurfaceArea) / (float) (binWidth * binHeight); diff --git a/src/org/infinity/util/CharsetDetector.java b/src/org/infinity/util/CharsetDetector.java index c7f1f53d4..2161f7485 100644 --- a/src/org/infinity/util/CharsetDetector.java +++ b/src/org/infinity/util/CharsetDetector.java @@ -190,7 +190,7 @@ public static String guessCharset(boolean detect) { } ch.close(); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -269,8 +269,8 @@ public CharLookup(String encoded, String decoded, int[] excludedStrrefs) { /** Returns whether the specified string is excluded from the encoding process. */ public boolean isExcluded(int strref) { - for (int i = 0; i < excluded.length; i++) { - if (excluded[i] == strref) { + for (int offset : excluded) { + if (offset == strref) { return true; } } diff --git a/src/org/infinity/util/CreMapCache.java b/src/org/infinity/util/CreMapCache.java index 70deb28f3..e61b3af65 100644 --- a/src/org/infinity/util/CreMapCache.java +++ b/src/org/infinity/util/CreMapCache.java @@ -108,6 +108,7 @@ private static boolean ensureInitialized(int timeOutMS) { try { Thread.sleep(1); } catch (InterruptedException e) { + Logger.trace(e); } } @@ -166,10 +167,10 @@ private static void initialize() { try { threadPool.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + Logger.error(e); } } catch (Exception e) { - // ignored + Logger.trace(e); } if (statusBar != null && statusBar.getMessage().startsWith(message)) { @@ -196,9 +197,7 @@ public void run() { try { CreResource.addScriptName(SCRIPT_NAMES_CRE, entry); } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } } } @@ -215,9 +214,7 @@ public void run() { try { AreResource.addScriptNames(SCRIPT_NAMES_ARE, entry.getResourceBuffer()); } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } } } @@ -250,9 +247,7 @@ public void run() { } } } catch (Exception e) { - synchronized (System.err) { - e.printStackTrace(); - } + Logger.error(e); } } } diff --git a/src/org/infinity/util/DebugTimer.java b/src/org/infinity/util/DebugTimer.java new file mode 100644 index 000000000..4011f8143 --- /dev/null +++ b/src/org/infinity/util/DebugTimer.java @@ -0,0 +1,191 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.util; + +/** + * Provides methods for measuring time. + */ +public class DebugTimer { + /** Supported temporal resolutions for timer methods. */ + public enum TimeFormat { + NANOSECONDS(1L, "ns"), + MICROSECONDS(1_000L, "µs"), + MILLISECONDS(1_000_000L, "ms"), + SECONDS(1_000_000_000L, "s"), + ; + + private final long factor; + private final String unit; + + TimeFormat(long factor, String unit) { + this.factor = factor; + this.unit = unit; + } + + /** Returns the scale factor to convert a value in nanoseconds into the desired time format. */ + public long getScaleFactor() { + return factor; + } + + /** Returns the time unit as string. */ + public String getUnit() { + return unit; + } + + /** + * Converts the value into the current time unit. + * + * @param nanos Time value in nanoseconds. + * @return Value in the current time unit. + */ + public long get(long nanos) { + return nanos / factor; + } + + /** + * Returns a string representation of the value in the current time unit. + * + * @param nanos Time value in nanoseconds. + * @return String of the converted time value with time unit symbol. + */ + public String toString(long nanos) { + return get(nanos) + " " + getUnit(); + } + } + + /** Static class instance for global access to the timer. */ + private static final DebugTimer INSTANCE = new DebugTimer(); + + /** + * Provides access to the global instance of the {@code DebugTimer} class. + * + *

The global {@code DebugTimer} instance defines {@link TimeFormat#MILLISECONDS} as default.

+ */ + public static synchronized DebugTimer getInstance() { + return INSTANCE; + } + + private TimeFormat defaultFormat; + private long timeBase; + + /** Creates a new {@code Debugging} object with the default time format {@link TimeFormat#MILLISECONDS}. */ + public DebugTimer() { + this(TimeFormat.MILLISECONDS); + } + + /** + * Creates a new {@code Debugging} object with the specified {@link TimeFormat}. + * + * @param defaultFormat the default time format to use by the non-parameterized timer methods. + */ + public DebugTimer(TimeFormat defaultFormat) { + this.timeBase = System.nanoTime(); + this.defaultFormat = getTimeFormat(defaultFormat); + } + + /** Resets the timer to the current system time. */ + public synchronized DebugTimer timerReset() { + timeBase = System.nanoTime(); + return this; + } + + /** + * Prints the elapsed time in the default time format. + * + * @return A formatted string of the elapsed time. + */ + public String getTimerFormatted() { + return getTimerFormatted(null, getDefaultTimeFormat()); + } + + /** + * Prints the elapsed time in the specified time format. + * + * @param format The temporal resolution of the elapsed time. + * @return A formatted string of the elapsed time. + */ + public String getTimerFormatted(TimeFormat format) { + return getTimerFormatted(null, format); + } + + /** + * Prints the elapsed time in the default time format with an optional message. + * + * @param message Optional message to show. Specify {@code null} or an empty string to omit this message. + * @return A formatted string with optional message and elapsed time. + */ + public String getTimerFormatted(String message) { + return getTimerFormatted(message, getDefaultTimeFormat()); + } + + /** + * Prints the elapsed time in the specified time format with an optional message. + * + * @param message Optional message to show. Specify {@code null} or an empty string to omit this message. + * @param format The temporal resolution of the elapsed time. + * @return A formatted string with optional message and elapsed time. + */ + public String getTimerFormatted(String message, TimeFormat format) { + final long timeDiff = timerGetRaw(); + format = getTimeFormat(format); + if (message != null && !message.isEmpty()) { + return "[" + message + "] " + format.toString(timeDiff); + } else { + return format.toString(timeDiff); + } + } + + /** + * Returns the elapsed time since the last timer reset in the default time format. + * + * @return The elapsed time in the specified resolution + */ + public long timerGet() { + return timerGet(getDefaultTimeFormat()); + } + + /** + * Returns the elapsed time since the last timer reset in the specified time format. + * + * @param format The temporal resolution of the elapsed time + * @return The elapsed time in the specified resolution + */ + public long timerGet(TimeFormat format) { + final long timeDiff = timerGetRaw(); + return getTimeFormat(format).get(timeDiff) ; + } + + /** Returns the default {@link TimeFormat}. for use with the non-parameterized methods for getting the timer value. */ + public TimeFormat getDefaultTimeFormat() { + return defaultFormat; + } + + /** + * Defines a new default {@link TimeFormat} for use with the non-parameterized methods for getting the + * timer value. + * + *

Note: The time format cannot be modified for the global {@code DebugTimer} instance + * and throws a {@link UnsupportedOperationException}.

+ * + * @param newTimeFormat new default {@link TimeFormat}. + * @throws UnsupportedOperationException if this method is invoked by the global {@link DebugTimer} instance. + */ + public void setDefaultTimeFormat(TimeFormat newTimeFormat) { + if (this == INSTANCE) { + throw new UnsupportedOperationException("Default time format cannot be modified for the global instance"); + } + this.defaultFormat = (newTimeFormat != null) ? newTimeFormat : TimeFormat.MILLISECONDS; + } + + /** Returns a non-{@code null} {@link TimeFormat} object. */ + private TimeFormat getTimeFormat(TimeFormat fmt) { + return (fmt != null) ? fmt : TimeFormat.MILLISECONDS; + } + + /** Synchronized access to the elapsed time since last timer reset. */ + private synchronized long timerGetRaw() { + return System.nanoTime() - timeBase; + } +} diff --git a/src/org/infinity/util/Debugging.java b/src/org/infinity/util/Debugging.java deleted file mode 100644 index 9d846638d..000000000 --- a/src/org/infinity/util/Debugging.java +++ /dev/null @@ -1,83 +0,0 @@ -// Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 Jon Olav Hauglid -// See LICENSE.txt for license information - -package org.infinity.util; - -/** - * Collection of static methods for debugging and profiling needs. - */ -public class Debugging { - /** - * Supported temporal resolutions for timer methods. - */ - public enum TimeFormat { - NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS - } - - private static long timeBase = System.nanoTime(); - - /** - * Resets timer to current time. - */ - public static synchronized void timerReset() { - timeBase = System.nanoTime(); - } - - /** - * Shows elapsed time in the desired resolution and resets timer. - * - * @param msg Display an optional message - * @param fmt The temporaral resolution of the elapsed time - */ - public static synchronized void timerShow(String msg, TimeFormat fmt) { - if (msg != null && !msg.isEmpty()) { - System.out.println("[" + msg + "] " + toTimeFormatString(fmt, System.nanoTime() - timeBase)); - } else { - System.out.println(toTimeFormatString(fmt, System.nanoTime() - timeBase)); - } - timerReset(); - } - - /** - * Returns elapsed time in the desired resolution and resets timer. - * - * @param fmt The temporal resolution of the elapsed time - * @return The elapsed time in the specified resolution - */ - public static synchronized long timerGet(TimeFormat fmt) { - long time = toTimeFormat(fmt, System.nanoTime() - timeBase); - timerReset(); - return time; - } - - // ------------------------------ PRIVATE METHODS ------------------------------ - - private static long toTimeFormat(TimeFormat fmt, long time) { - switch (fmt) { - case MICROSECONDS: - return time / 1000L; - case MILLISECONDS: - return time / 1000000L; - case SECONDS: - return time / 1000000000L; - default: - return time; - } - } - - private static String toTimeFormatString(TimeFormat fmt, long time) { - switch (fmt) { - case NANOSECONDS: - return toTimeFormat(fmt, time) + " ns"; - case MICROSECONDS: - return toTimeFormat(fmt, time) + " µs"; - case MILLISECONDS: - return toTimeFormat(fmt, time) + " ms"; - case SECONDS: - return toTimeFormat(fmt, time) + " s"; - default: - return Long.toString(time); - } - } -} diff --git a/src/org/infinity/util/DynamicArray.java b/src/org/infinity/util/DynamicArray.java index 0b0dab6ea..d7a099fb0 100644 --- a/src/org/infinity/util/DynamicArray.java +++ b/src/org/infinity/util/DynamicArray.java @@ -119,7 +119,7 @@ public static byte[] convertByte(byte value) { public static short getShort(byte[] buffer, int offset) { if (buffer != null && offset >= 0 && offset + 1 < buffer.length) { short v = (short) (buffer[offset] & 0xff); - v |= (buffer[offset + 1] & 0xff) << 8; + v |= (short) ((buffer[offset + 1] & 0xff) << 8); return v; } else { return 0; @@ -738,10 +738,10 @@ public short getShort(int index) { short v = 0; if (ofs < buffer.length) { - v |= buffer[ofs++] & 0xff; + v |= (short) (buffer[ofs++] & 0xff); } if (ofs < buffer.length) { - v |= (buffer[ofs++] & 0xff) << 8; + v |= (short) ((buffer[ofs++] & 0xff) << 8); } return fixShortOrder(v); diff --git a/src/org/infinity/util/FileDeletionHook.java b/src/org/infinity/util/FileDeletionHook.java index cc75c6a30..ee7ba96d3 100644 --- a/src/org/infinity/util/FileDeletionHook.java +++ b/src/org/infinity/util/FileDeletionHook.java @@ -35,6 +35,7 @@ public void run() { try { Files.delete(file); } catch (Throwable t) { + Logger.trace(t); } } } diff --git a/src/org/infinity/util/FilteredListModel.java b/src/org/infinity/util/FilteredListModel.java index 95ab3ce08..6ab88297e 100644 --- a/src/org/infinity/util/FilteredListModel.java +++ b/src/org/infinity/util/FilteredListModel.java @@ -84,7 +84,7 @@ public void addFilterChangeListener(ChangeListener listener) { /** Returns an array of all the change listeners registered to this instance. */ public ChangeListener[] getFilterChangeListeners() { - return listeners.toArray(new ChangeListener[listeners.size()]); + return listeners.toArray(new ChangeListener[0]); } /** Removes all instances of the specified ChangeListener from the listener list. */ @@ -579,7 +579,7 @@ private void updateFilter(boolean filtered, String pattern, boolean forced) { int idx = Math.max(-1, fidx) + 1; filteredList.add(idx, item); helper.updateEvent(ListDataEventHelper.EVENT_ADD, idx); - } else if (fidx >= 0 && item.equals(getElementAt(fidx))) { + } else if (item.equals(getElementAt(fidx))) { helper.updateEvent(ListDataEventHelper.EVENT_NONE, -1); fidx--; } diff --git a/src/org/infinity/util/IdsMap.java b/src/org/infinity/util/IdsMap.java index 338144beb..96b221d5c 100644 --- a/src/org/infinity/util/IdsMap.java +++ b/src/org/infinity/util/IdsMap.java @@ -34,7 +34,7 @@ public IdsMap(ResourceEntry entry) throws Exception { parse2DA(); } // } catch (Exception e) { -// e.printStackTrace(); +// Logger.error(e); // } } @@ -64,7 +64,7 @@ public SortedSet getKeys() { /** Returns the entry structure defined by the specified IDS value, or {@code null} otherwise. */ public IdsMapEntry get(long value) { - return idsMap.get(Long.valueOf(normalizedKey(value))); + return idsMap.get(normalizedKey(value)); } /** diff --git a/src/org/infinity/util/IdsMapCache.java b/src/org/infinity/util/IdsMapCache.java index 2fb87a3d3..210df221c 100644 --- a/src/org/infinity/util/IdsMapCache.java +++ b/src/org/infinity/util/IdsMapCache.java @@ -53,7 +53,7 @@ public static synchronized IdsMap get(String name) { if (name.equals("ATTSTYLE.IDS")) { entry = ResourceFactory.getResourceEntry("ATTSTYL.IDS"); } else { - System.err.println("Could not find " + name); + Logger.warn("Could not find {}", name); } } if (entry != null) { @@ -61,7 +61,7 @@ public static synchronized IdsMap get(String name) { retVal = new IdsMap(entry); CACHE.put(name, retVal); } catch (Exception e) { - System.err.println(e.getMessage()); + Logger.warn("{}: {}", e.getClass().getSimpleName(), e.getMessage()); } } } @@ -224,7 +224,7 @@ public static String[] getUpdatedIdsFlags(String[] flags, String idsFile, int si if (map != null) { final int numBits = size * 8; for (int i = 0; i < numBits; i++) { - final IdsMapEntry entry = map.get((1 << i)); + final IdsMapEntry entry = map.get((1L << i)); String s = (entry != null) ? entry.getSymbol() : null; if (s != null && !s.isEmpty()) { if (prettify) { @@ -249,7 +249,7 @@ public static String[] getUpdatedIdsFlags(String[] flags, String idsFile, int si } // converting list into array - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } /** diff --git a/src/org/infinity/util/IdsMapEntry.java b/src/org/infinity/util/IdsMapEntry.java index e55a234d4..45faad684 100644 --- a/src/org/infinity/util/IdsMapEntry.java +++ b/src/org/infinity/util/IdsMapEntry.java @@ -13,7 +13,7 @@ */ public class IdsMapEntry implements Comparable, Iterable { /** Symbolic names that can be used in scripts for specifying {@link #id}. */ - private final ArrayDeque symbols = new ArrayDeque<>(); + private final ArrayDeque symbols = new ArrayDeque<>(4); /** Value that used in compiled scripts. */ private final long id; @@ -33,9 +33,36 @@ public int getNumSymbols() { return symbols.size(); } - /** Returns the most recently added symbolic name. */ + /** Returns the first available symbolic name. */ public String getSymbol() { - return symbols.peek(); + return symbols.peekFirst(); + } + + /** Returns the most recently added symbolic name. */ + public String getLastSymbol() { + return symbols.peekLast(); + } + + /** + * Returns the symbolic name at the specified index. Call {@link #getNumSymbols()} to get the number of available + * symbolic names. + * + * @param index Index of the symbolic name. + * @return Symbolic name as string. + * @throws IndexOutOfBoundsException if {@code index} is out of bounds. + */ + public String getSymbol(int index) throws IndexOutOfBoundsException { + if (index < 0 || index >= symbols.size()) { + throw new IndexOutOfBoundsException("Index out of bounds: " + index); + } + + final Iterator iter = symbols.iterator(); + String retVal = null; + while (index >= 0) { + retVal = iter.next(); + index--; + } + return retVal; } /** Returns an iterator over the whole collection of available symbols. */ @@ -51,7 +78,7 @@ public void addSymbol(String symbol) { } if (!symbol.isEmpty() && !symbols.contains(symbol)) { - symbols.push(symbol); + symbols.add(symbol); } } diff --git a/src/org/infinity/util/IniMap.java b/src/org/infinity/util/IniMap.java index dda362d4e..51189a4ee 100644 --- a/src/org/infinity/util/IniMap.java +++ b/src/org/infinity/util/IniMap.java @@ -202,7 +202,7 @@ private IniMapEntry parseEntry(String line, int lineNr, boolean ignoreComments) value = line.substring(start, pos).trim(); } - if (key != null || value != null) { + if (key != null) { return new IniMapEntry(key, value, lineNr); } else { return null; @@ -215,7 +215,7 @@ private static String readResource(ResourceEntry entry) { final ByteBuffer bb = entry.getResourceBuffer(); return StreamUtils.readString(bb, bb.limit(), Misc.CHARSET_DEFAULT); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } return null; diff --git a/src/org/infinity/util/IniMapCache.java b/src/org/infinity/util/IniMapCache.java index 15d2329fd..ab384bd49 100644 --- a/src/org/infinity/util/IniMapCache.java +++ b/src/org/infinity/util/IniMapCache.java @@ -35,7 +35,7 @@ public static IniMap get(String name, boolean ignoreComments) { if (entry != null) { retVal = get(entry, ignoreComments); } else { - System.err.println("Could not find " + name); + Logger.warn("Could not find {}", name); } } return retVal; diff --git a/src/org/infinity/util/IniMapEntry.java b/src/org/infinity/util/IniMapEntry.java index 01be7f56f..490c96c8e 100644 --- a/src/org/infinity/util/IniMapEntry.java +++ b/src/org/infinity/util/IniMapEntry.java @@ -31,7 +31,7 @@ public IniMapEntry(String key, String value, int line) { } public boolean hasKey() { - return key != null; + return !key.isEmpty(); } public String getKey() { @@ -39,7 +39,7 @@ public String getKey() { } public boolean hasValue() { - return value != null; + return !value.isEmpty(); } public String getValue() { @@ -47,23 +47,23 @@ public String getValue() { } public Integer getIntValue() { - return value == null ? null : Integer.valueOf(value); + return hasValue() ? Integer.valueOf(value) : null; } public int getIntValue(int defValue) { - return value == null ? defValue : Integer.valueOf(value); + return hasValue() ? Integer.parseInt(value) : defValue; } public Double getDoubleValue() { - return value == null ? null : Double.valueOf(value); + return hasValue() ? Double.valueOf(value) : null; } public double getDoubleValue(double defValue) { - return value == null ? defValue : Double.valueOf(value); + return hasValue() ? Double.parseDouble(value) : defValue; } public StringRef getStringRefValue() { - return value == null ? null : new StringRef(key, Integer.valueOf(value)); + return hasValue() ? new StringRef(key, Integer.parseInt(value)) : null; } public int getLine() { @@ -108,7 +108,7 @@ public static String[] splitValues(String value, String pattern) { results.add(value.substring(matcher.start(), matcher.end())); } } catch (PatternSyntaxException e) { - e.printStackTrace(); + Logger.error(e); } retVal = new String[results.size()]; for (int i = 0; i < results.size(); i++) { @@ -138,7 +138,7 @@ public static int[] splitObjectValue(String value) { try { retVal[i] = Integer.parseInt(results.get(i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -165,7 +165,7 @@ public static int[] splitPositionValue(String value) { try { retVal[i] = Integer.parseInt(results.get(i)); } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/util/LauncherUtils.java b/src/org/infinity/util/LauncherUtils.java index 368c52eae..44f955aac 100644 --- a/src/org/infinity/util/LauncherUtils.java +++ b/src/org/infinity/util/LauncherUtils.java @@ -51,7 +51,7 @@ public static void browse(URL url) throws URISyntaxException, IOException { * specified URI, the application registered for handling URIs of the specified type is invoked. The applicationis * determined from the protocol and path of the URI, asdefined by the URI class. * - * @param url the {@link URI} to be displayed in the user's default browser. + * @param uri the {@link URI} to be displayed in the user's default browser. * @throws URISyntaxException if the specified URL is not formatted strictly according to RFC2396 and cannot be * converted to a URI. * @throws IOException if the user default browser is not found, or it fails to be launched, or the default @@ -122,7 +122,6 @@ public static void open(File file) throws IOException { * * @param arg File path or URL as string. * @return {@code true} if {code xdg-open} was called, {@code false} otherwise. - * @throws IOException if the process could not be executed. */ private static boolean xdgOpen(String arg) { boolean retVal = false; @@ -140,7 +139,7 @@ private static boolean xdgOpen(String arg) { p.waitFor(); retVal = true; } catch (IOException | InterruptedException e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/util/Logger.java b/src/org/infinity/util/Logger.java new file mode 100644 index 000000000..c1e057f17 --- /dev/null +++ b/src/org/infinity/util/Logger.java @@ -0,0 +1,606 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.util; + +import org.infinity.AppOption; +import org.tinylog.Level; +import org.tinylog.Supplier; +import org.tinylog.TaggedLogger; + +/** + * Wrapper class for the {@link org.tinylog.Logger} class from the tinylog package to provide more control over log + * level visibility. + */ +public class Logger { + /** + * Gets a tagged logger instance. Tags are case-sensitive. + * + * @param tag Tag for logger or {@code null} for receiving an untagged logger + * @return Logger instance + */ + public static TaggedLogger tag(final String tag) { + return org.tinylog.Logger.tag(tag); + } + + /** + * Gets a tagged logger instance that logs to multiple tags. Tags are case-sensitive. + * + * @param tags Tags for the logger or nothing for an untagged logger. If specified, each tag should be unique + * @return Logger instance + */ + public static TaggedLogger tags(final String... tags) { + return org.tinylog.Logger.tags(tags); + } + + /** + * Checks whether log entries at {@link Level#TRACE TRACE} level will be output. + * + * @return {@code true} if {@link Level#TRACE TRACE} level is enabled, {@code false} if disabled + */ + public static boolean isTraceEnabled() { + return isLogLevelEnabled(Level.TRACE); + } + + /** + * Logs a message at {@link Level#TRACE TRACE} level. + * + * @param message String or any other object with a meaningful {@link #toString()} method + */ + public static void trace(final Object message) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(message); + } + + /** + * Logs a lazy message at {@link Level#TRACE TRACE} level. The message will be only evaluated if the log entry is + * really output. + * + * @param message Function that produces the message + */ + public static void trace(final Supplier message) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(message); + } + + /** + * Logs a formatted message at {@link Level#TRACE TRACE} level. "{}" placeholders will be replaced by given arguments. + * + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void trace(final String message, final Object... arguments) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(message, arguments); + } + + /** + * Logs a formatted message at {@link Level#TRACE TRACE} level. "{}" placeholders will be replaced by given lazy + * arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void trace(final String message, final Supplier... arguments) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(message, arguments); + } + + /** + * Logs an exception at {@link Level#TRACE TRACE} level. + * + * @param exception Caught exception or any other throwable to log + */ + public static void trace(final Throwable exception) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(exception); + } + + /** + * Logs an exception with a custom message at {@link Level#TRACE TRACE} level. + * + * @param exception Caught exception or any other throwable to log + * @param message Text message to log + */ + public static void trace(final Throwable exception, final String message) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(exception, message); + } + + /** + * Logs an exception with a custom lazy message at {@link Level#TRACE TRACE} level. The message will be only evaluated + * if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Function that produces the message + */ + public static void trace(final Throwable exception, final Supplier message) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(exception, message); + } + + /** + * Logs an exception with a formatted custom message at {@link Level#TRACE TRACE} level. "{}" placeholders will be + * replaced by given arguments. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void trace(final Throwable exception, final String message, final Object... arguments) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(exception, message, arguments); + } + + /** + * Logs an exception with a formatted message at {@link Level#TRACE TRACE} level. "{}" placeholders will be replaced + * by given lazy arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void trace(final Throwable exception, final String message, final Supplier... arguments) { + if (isTraceEnabled()) + org.tinylog.Logger.trace(exception, message, arguments); + } + + /** + * Checks whether log entries at {@link Level#DEBUG DEBUG} level will be output. + * + * @return {@code true} if {@link Level#DEBUG DEBUG} level is enabled, {@code false} if disabled + */ + public static boolean isDebugEnabled() { + return isLogLevelEnabled(Level.DEBUG); + } + + /** + * Logs a message at {@link Level#DEBUG DEBUG} level. + * + * @param message String or any other object with a meaningful {@link #toString()} method + */ + public static void debug(final Object message) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(message); + } + + /** + * Logs a lazy message at {@link Level#DEBUG DEBUG} level. The message will be only evaluated if the log entry is + * really output. + * + * @param message Function that produces the message + */ + public static void debug(final Supplier message) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(message); + } + + /** + * Logs a formatted message at {@link Level#DEBUG DEBUG} level. "{}" placeholders will be replaced by given arguments. + * + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void debug(final String message, final Object... arguments) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(message, arguments); + } + + /** + * Logs a formatted message at {@link Level#DEBUG DEBUG} level. "{}" placeholders will be replaced by given lazy + * arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void debug(final String message, final Supplier... arguments) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(message, arguments); + } + + /** + * Logs an exception at {@link Level#DEBUG DEBUG} level. + * + * @param exception Caught exception or any other throwable to log + */ + public static void debug(final Throwable exception) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(exception); + } + + /** + * Logs an exception with a custom message at {@link Level#DEBUG DEBUG} level. + * + * @param exception Caught exception or any other throwable to log + * @param message Text message to log + */ + public static void debug(final Throwable exception, final String message) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(exception, message); + } + + /** + * Logs an exception with a custom lazy message at {@link Level#DEBUG DEBUG} level. The message will be only evaluated + * if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Function that produces the message + */ + public static void debug(final Throwable exception, final Supplier message) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(exception, message); + } + + /** + * Logs an exception with a formatted custom message at {@link Level#DEBUG DEBUG} level. "{}" placeholders will be + * replaced by given arguments. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void debug(final Throwable exception, final String message, final Object... arguments) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(exception, message, arguments); + } + + /** + * Logs an exception with a formatted message at {@link Level#DEBUG DEBUG} level. "{}" placeholders will be replaced + * by given lazy arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void debug(final Throwable exception, final String message, final Supplier... arguments) { + if (isDebugEnabled()) + org.tinylog.Logger.debug(exception, message, arguments); + } + + /** + * Checks whether log entries at {@link Level#INFO INFO} level will be output. + * + * @return {@code true} if {@link Level#INFO INFO} level is enabled, {@code false} if disabled + */ + public static boolean isInfoEnabled() { + return isLogLevelEnabled(Level.INFO); + } + + /** + * Logs a message at {@link Level#INFO INFO} level. + * + * @param message String or any other object with a meaningful {@link #toString()} method + */ + public static void info(final Object message) { + if (isInfoEnabled()) + org.tinylog.Logger.info(message); + } + + /** + * Logs a lazy message at {@link Level#INFO INFO} level. The message will be only evaluated if the log entry is really + * output. + * + * @param message Function that produces the message + */ + public static void info(final Supplier message) { + if (isInfoEnabled()) + org.tinylog.Logger.info(message); + } + + /** + * Logs a formatted message at {@link Level#INFO INFO} level. "{}" placeholders will be replaced by given arguments. + * + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void info(final String message, final Object... arguments) { + if (isInfoEnabled()) + org.tinylog.Logger.info(message, arguments); + } + + /** + * Logs a formatted message at {@link Level#INFO INFO} level. "{}" placeholders will be replaced by given lazy + * arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void info(final String message, final Supplier... arguments) { + if (isInfoEnabled()) + org.tinylog.Logger.info(message, arguments); + } + + /** + * Logs an exception at {@link Level#INFO INFO} level. + * + * @param exception Caught exception or any other throwable to log + */ + public static void info(final Throwable exception) { + if (isInfoEnabled()) + org.tinylog.Logger.info(exception); + } + + /** + * Logs an exception with a custom message at {@link Level#INFO INFO} level. + * + * @param exception Caught exception or any other throwable to log + * @param message Text message to log + */ + public static void info(final Throwable exception, final String message) { + if (isInfoEnabled()) + org.tinylog.Logger.info(exception, message); + } + + /** + * Logs an exception with a custom lazy message at {@link Level#INFO INFO} level. The message will be only evaluated + * if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Function that produces the message + */ + public static void info(final Throwable exception, final Supplier message) { + if (isInfoEnabled()) + org.tinylog.Logger.info(exception, message); + } + + /** + * Logs an exception with a formatted custom message at {@link Level#INFO INFO} level. "{}" placeholders will be + * replaced by given arguments. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void info(final Throwable exception, final String message, final Object... arguments) { + if (isInfoEnabled()) + org.tinylog.Logger.info(exception, message, arguments); + } + + /** + * Logs an exception with a formatted message at {@link Level#INFO INFO} level. "{}" placeholders will be replaced by + * given lazy arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void info(final Throwable exception, final String message, final Supplier... arguments) { + if (isInfoEnabled()) + org.tinylog.Logger.info(exception, message, arguments); + } + + /** + * Checks whether log entries at {@link Level#WARN WARN} level will be output. + * + * @return {@code true} if {@link Level#WARN WARN} level is enabled, {@code false} if disabled + */ + public static boolean isWarnEnabled() { + return isLogLevelEnabled(Level.WARN); + } + + /** + * Logs a message at {@link Level#WARN WARN} level. + * + * @param message String or any other object with a meaningful {@link #toString()} method + */ + public static void warn(final Object message) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(message); + } + + /** + * Logs a lazy message at {@link Level#WARN WARN} level. The message will be only evaluated if the log entry is really + * output. + * + * @param message Function that produces the message + */ + public static void warn(final Supplier message) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(message); + } + + /** + * Logs a formatted message at {@link Level#WARN WARN} level. "{}" placeholders will be replaced by given arguments. + * + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void warn(final String message, final Object... arguments) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(message, arguments); + } + + /** + * Logs a formatted message at {@link Level#WARN WARN} level. "{}" placeholders will be replaced by given lazy + * arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void warn(final String message, final Supplier... arguments) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(message, arguments); + } + + /** + * Logs an exception at {@link Level#WARN WARN} level. + * + * @param exception Caught exception or any other throwable to log + */ + public static void warn(final Throwable exception) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(exception); + } + + /** + * Logs an exception with a custom message at {@link Level#WARN WARN} level. + * + * @param exception Caught exception or any other throwable to log + * @param message Text message to log + */ + public static void warn(final Throwable exception, final String message) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(exception, message); + } + + /** + * Logs an exception with a custom lazy message at {@link Level#WARN WARN} level. The message will be only evaluated + * if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Function that produces the message + */ + public static void warn(final Throwable exception, final Supplier message) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(exception, message); + } + + /** + * Logs an exception with a formatted custom message at {@link Level#WARN WARN} level. "{}" placeholders will be + * replaced by given arguments. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void warn(final Throwable exception, final String message, final Object... arguments) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(exception, message, arguments); + } + + /** + * Logs an exception with a formatted message at {@link Level#WARN WARN} level. "{}" placeholders will be replaced by + * given lazy arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void warn(final Throwable exception, final String message, final Supplier... arguments) { + if (isWarnEnabled()) + org.tinylog.Logger.warn(exception, message, arguments); + } + + /** + * Checks whether log entries at {@link Level#ERROR ERROR} level will be output. + * + * @return {@code true} if {@link Level#ERROR ERROR} level is enabled, {@code false} if disabled + */ + public static boolean isErrorEnabled() { + return isLogLevelEnabled(Level.ERROR); + } + + /** + * Logs a message at {@link Level#ERROR ERROR} level. + * + * @param message String or any other object with a meaningful {@link #toString()} method + */ + public static void error(final Object message) { + if (isErrorEnabled()) + org.tinylog.Logger.error(message); + } + + /** + * Logs a lazy message at {@link Level#ERROR ERROR} level. The message will be only evaluated if the log entry is + * really output. + * + * @param message Function that produces the message + */ + public static void error(final Supplier message) { + if (isErrorEnabled()) + org.tinylog.Logger.error(message); + } + + /** + * Logs a formatted message at {@link Level#ERROR ERROR} level. "{}" placeholders will be replaced by given arguments. + * + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void error(final String message, final Object... arguments) { + if (isErrorEnabled()) + org.tinylog.Logger.error(message, arguments); + } + + /** + * Logs a formatted message at {@link Level#ERROR ERROR} level. "{}" placeholders will be replaced by given lazy + * arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void error(final String message, final Supplier... arguments) { + if (isErrorEnabled()) + org.tinylog.Logger.error(message, arguments); + } + + /** + * Logs an exception at {@link Level#ERROR ERROR} level. + * + * @param exception Caught exception or any other throwable to log + */ + public static void error(final Throwable exception) { + if (isErrorEnabled()) + org.tinylog.Logger.error(exception); + } + + /** + * Logs an exception with a custom message at {@link Level#ERROR ERROR} level. + * + * @param exception Caught exception or any other throwable to log + * @param message Text message to log + */ + public static void error(final Throwable exception, final String message) { + if (isErrorEnabled()) + org.tinylog.Logger.error(exception, message); + } + + /** + * Logs an exception with a custom lazy message at {@link Level#ERROR ERROR} level. The message will be only evaluated + * if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Function that produces the message + */ + public static void error(final Throwable exception, final Supplier message) { + if (isErrorEnabled()) + org.tinylog.Logger.error(exception, message); + } + + /** + * Logs an exception with a formatted custom message at {@link Level#ERROR ERROR} level. "{}" placeholders will be + * replaced by given arguments. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Arguments for formatted text message + */ + public static void error(final Throwable exception, final String message, final Object... arguments) { + if (isErrorEnabled()) + org.tinylog.Logger.error(exception, message, arguments); + } + + /** + * Logs an exception with a formatted message at {@link Level#ERROR ERROR} level. "{}" placeholders will be replaced + * by given lazy arguments. The arguments will be only evaluated if the log entry is really output. + * + * @param exception Caught exception or any other throwable to log + * @param message Formatted text message to log + * @param arguments Functions that produce the arguments for formatted text message + */ + public static void error(final Throwable exception, final String message, final Supplier... arguments) { + if (isErrorEnabled()) + org.tinylog.Logger.error(exception, message, arguments); + } + + /** + * Checks if the given severity level is covered by the minimum level specified in the app preferences. + * + * @param level Severity level to check. + * @return {@code true} if the given severity level is covered, otherwise {@code false}. + */ + private static boolean isLogLevelEnabled(Level level) { + return (level != null) && AppOption.APP_LOG_LEVEL.getIntValue() <= level.ordinal(); + } +} diff --git a/src/org/infinity/util/LuaParser.java b/src/org/infinity/util/LuaParser.java index 135b98461..eafa6f0ca 100644 --- a/src/org/infinity/util/LuaParser.java +++ b/src/org/infinity/util/LuaParser.java @@ -6,7 +6,7 @@ import java.nio.CharBuffer; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,7 +35,7 @@ private enum Token { * @throws Exception */ public static LuaEntry Parse(ResourceEntry entry, String name, boolean exactMatch) throws Exception { - return Parse(Arrays.asList(entry), name, exactMatch); + return Parse(Collections.singletonList(entry), name, exactMatch); } /** @@ -50,7 +50,7 @@ public static LuaEntry Parse(ResourceEntry entry, String name, boolean exactMatc * @throws Exception */ public static LuaEntry Parse(List entries, String name, boolean exactMatch) throws Exception { - if (entries == null || entries.size() == 0) { + if (entries == null || entries.isEmpty()) { return null; } @@ -335,6 +335,7 @@ private static LuaEntry ParseElement(CharBuffer buffer, LuaEntry parent) throws int code = Integer.parseInt(peekBuffer(buffer, 2) + ch, 8); ch = (char) code; } catch (Exception e) { + Logger.trace(e); } } else if (ch == 'x') { // hexadecimal value? @@ -342,6 +343,7 @@ private static LuaEntry ParseElement(CharBuffer buffer, LuaEntry parent) throws int code = Integer.parseInt(peekBuffer(buffer, 2), 16); ch = (char) code; } catch (Exception e) { + Logger.trace(e); } } } @@ -372,6 +374,7 @@ private static String peekBuffer(CharBuffer buf, int count) { try { return buf.subSequence(0, count).toString(); } catch (Exception e) { + Logger.trace(e); } return ""; } diff --git a/src/org/infinity/util/MapTree.java b/src/org/infinity/util/MapTree.java index 2836f5796..ddb6f627d 100644 --- a/src/org/infinity/util/MapTree.java +++ b/src/org/infinity/util/MapTree.java @@ -85,8 +85,8 @@ public MapTree(K key, V value) { @SuppressWarnings("unchecked") public Object clone() { MapTree node = new MapTree<>(key, value); - for (Iterator> iter = children.values().iterator(); iter.hasNext();) { - node.addChild((MapTree) iter.next().clone()); + for (MapTree kvMapTree : children.values()) { + node.addChild((MapTree) kvMapTree.clone()); } return node; } @@ -149,7 +149,7 @@ public int addChildren(Collection> children) { public MapTree findNode(K key) { if (key != null) { Collection> retVal = findNodesRecursive(null, this, key, true); - if (retVal != null && !retVal.isEmpty()) { + if (!retVal.isEmpty()) { return retVal.iterator().next(); } } @@ -229,8 +229,8 @@ public MapTree removeChild(K key) { public Collection> removeChildren(Collection keys) { Collection> retVal = new Vector<>(); if (keys != null && !keys.isEmpty()) { - for (Iterator iter = keys.iterator(); iter.hasNext();) { - MapTree node = removeChild(iter.next()); + for (K k : keys) { + MapTree node = removeChild(k); if (node != null) { retVal.add(node); } diff --git a/src/org/infinity/util/MassExporter.java b/src/org/infinity/util/MassExporter.java index fd7bf4c8e..3bf53193a 100644 --- a/src/org/infinity/util/MassExporter.java +++ b/src/org/infinity/util/MassExporter.java @@ -301,7 +301,7 @@ public void actionPerformed(ActionEvent event) { try { pattern = getPattern(); } catch (IllegalArgumentException e) { - e.printStackTrace(); + Logger.error(e); JOptionPane.showMessageDialog(this, e.getMessage(), "Pattern syntax error", JOptionPane.ERROR_MESSAGE); if (e instanceof PatternSyntaxException) { final int index = ((PatternSyntaxException)e).getIndex(); @@ -319,7 +319,7 @@ public void actionPerformed(ActionEvent event) { Files.createDirectories(outputPath); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Unable to create target directory.", "Error", JOptionPane.ERROR_MESSAGE); - e.printStackTrace(); + Logger.error(e); return; } setVisible(false); @@ -330,7 +330,7 @@ public void actionPerformed(ActionEvent event) { if (fc.showDialog(this, "Select") == JFileChooser.APPROVE_OPTION) { tfDirectory.setText(fc.getSelectedFile().toString()); } - bExport.setEnabled(listTypes.getSelectedIndices().length > 0 && tfDirectory.getText().length() > 0); + bExport.setEnabled(listTypes.getSelectedIndices().length > 0 && !tfDirectory.getText().isEmpty()); } } @@ -340,7 +340,7 @@ public void actionPerformed(ActionEvent event) { @Override public void valueChanged(ListSelectionEvent event) { - bExport.setEnabled(listTypes.getSelectedIndices().length > 0 && tfDirectory.getText().length() > 0); + bExport.setEnabled(listTypes.getSelectedIndices().length > 0 && !tfDirectory.getText().isEmpty()); } // --------------------- End Interface ListSelectionListener --------------------- @@ -413,7 +413,7 @@ public void run() { progress.setMillisToPopup(0); progress.setProgress(0); progress.setNote(String.format(FMT_PROGRESS, 0, getResourceCount())); - Debugging.timerReset(); + DebugTimer.getInstance().timerReset(); for (int i = 0, count = getResourceCount(); i < count; i++) { threadPool.submit(new Worker(selectedFiles.get(i))); if (progress.isCanceled()) { @@ -438,9 +438,11 @@ public void run() { try { threadPool.awaitTermination(10L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { + Logger.trace(e); } } } catch (Exception e) { + Logger.trace(e); } if (isCancelled) { @@ -458,7 +460,7 @@ public void run() { } selectedFiles = null; } - Debugging.timerShow("Mass export completed", Debugging.TimeFormat.MILLISECONDS); + Logger.info(DebugTimer.getInstance().getTimerFormatted("Mass export completed")); } // --------------------- End Interface Runnable --------------------- @@ -467,11 +469,10 @@ public void run() { * Returns an array with all resource types available for the current game. */ private static String[] getAvailableResourceTypes() { - List types = Arrays.asList(Profile.getAvailableResourceTypes()) - .stream() + return Arrays + .stream(Profile.getAvailableResourceTypes()) .filter(s -> !TYPES_BLACKLIST.contains(s)) - .collect(Collectors.toList()); - return types.toArray(new String[types.size()]); + .toArray(String[]::new); } private int getResourceCount() { @@ -569,7 +570,7 @@ private void decompressBamMos(ResourceEntry entry, Path output) throws Exception private void decompressWav(ResourceEntry entry, Path output) throws Exception { ByteBuffer buffer = StreamUtils.getByteBuffer(AudioFactory.convertAudio(entry)); - if (buffer != null && buffer.limit() > 0) { + if (buffer.limit() > 0) { // Keep trying. File may be in use by another thread. try (OutputStream os = tryOpenOutputStream(output, 10, 100)) { StreamUtils.writeBytes(os, buffer); @@ -679,13 +680,13 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception Files.createDirectory(path); } catch (IOException e) { String msg = String.format("Error creating folder \"%s\". Skipping file \"%s\".", fileBase, fileName); - System.err.println(msg); + Logger.warn(msg); JOptionPane.showMessageDialog(NearInfinity.getInstance(), msg, "Error", JOptionPane.ERROR_MESSAGE); return; } } else if (!FileEx.create(path).isDirectory()) { String msg = String.format("Folder \"%s\" can not be created. Skipping file \"%s\".", fileBase, fileName); - System.err.println(msg); + Logger.warn(msg); JOptionPane.showMessageDialog(NearInfinity.getInstance(), msg, "Error", JOptionPane.ERROR_MESSAGE); return; } @@ -715,7 +716,7 @@ private void chrToCre(ResourceEntry entry, Path output) throws Exception { private void exportResource(ResourceEntry entry, Path output) throws Exception { if (entry != null && output != null) { - System.err.println("Converting " + entry.toString()); + Logger.info("Converting {}", entry.toString()); int[] info = entry.getResourceInfo(); int size = info[0]; if (info.length > 1) { @@ -812,8 +813,8 @@ private void export(ResourceEntry entry) { exportResource(entry, output); } } catch (Exception e) { - System.err.println("Error in resource: " + entry.toString()); - e.printStackTrace(); + Logger.error(e, "Error in resource: {}", entry); + } } @@ -914,13 +915,13 @@ private OutputStream tryOpenOutputStream(Path output, int numAttempts, int delay try { os = StreamUtils.getOutputStream(output, true); } catch (FileNotFoundException fnfe) { - os = null; if (--numAttempts == 0) { throw fnfe; } try { Thread.sleep(delayAttempts); } catch (InterruptedException ie) { + Logger.trace(ie); } } } diff --git a/src/org/infinity/util/Misc.java b/src/org/infinity/util/Misc.java index cd616a08d..c7984ab7f 100644 --- a/src/org/infinity/util/Misc.java +++ b/src/org/infinity/util/Misc.java @@ -9,10 +9,26 @@ import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; import java.lang.reflect.Constructor; +import java.net.URI; +import java.net.URL; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; import java.util.prefs.Preferences; +import java.util.stream.Collectors; import javax.swing.JComponent; import javax.swing.UIManager; @@ -29,13 +45,13 @@ public class Misc { public static final Charset CHARSET_DEFAULT = Charset.forName("windows-1252"); /** The UTF-8 charset. */ - public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); + public static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8; /** The US-ASCII charset. */ - public static final Charset CHARSET_ASCII = Charset.forName("US-ASCII"); + public static final Charset CHARSET_ASCII = StandardCharsets.US_ASCII; /** Returns the line separator string which is used by the current operating system. */ - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + public static final String LINE_SEPARATOR = System.lineSeparator(); /** Can be used to slightly expand dialog message strings to force a bigger initial dialog width. */ public static final String MSG_EXPAND_SMALL = " \t"; @@ -170,11 +186,11 @@ public static Charset detectCharset(byte[] data, Charset defaultCharset) { Charset retVal = null; if (data != null) { if (data.length >= 3 && data[0] == -17 && data[1] == -69 && data[2] == -65) { // UTF-8 BOM (0xef, 0xbb, 0xbf) - retVal = Charset.forName("utf-8"); + retVal = StandardCharsets.UTF_8; } else if (data.length >= 2 && data[0] == -2 && data[1] == -1) { // UTF-16 BOM (0xfeff) in big-endian order - retVal = Charset.forName("utf-16be"); + retVal = StandardCharsets.UTF_16BE; } else if (data.length >= 2 && data[0] == -1 && data[1] == -2) { // UTF-16 BOM (0xfeff) in little-endian order - retVal = Charset.forName("utf-16le"); + retVal = StandardCharsets.UTF_16LE; } } @@ -194,6 +210,7 @@ public static int toNumber(String value, int defValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { + Logger.trace(e); } } return defValue; @@ -208,30 +225,31 @@ public static int toNumber(String value, int radix, int defValue) { try { return Integer.parseInt(value, radix); } catch (NumberFormatException e) { + Logger.trace(e); } } return defValue; } /** Swaps byte order of the specified short value. */ - public static final short swap16(short v) { + public static short swap16(short v) { return (short) (((v & 0xff) << 8) | ((v >> 8) & 0xff)); } /** Swaps byte order of the specified int value. */ - public static final int swap32(int v) { + public static int swap32(int v) { return ((v << 24) & 0xff000000) | ((v << 8) & 0x00ff0000) | ((v >> 8) & 0x0000ff00) | ((v >> 24) & 0x000000ff); } /** Swaps byte order of the specified long value. */ - public static final long swap64(long v) { + public static long swap64(long v) { return ((v << 56) & 0xff00000000000000L) | ((v << 40) & 0x00ff000000000000L) | ((v << 24) & 0x0000ff0000000000L) | ((v << 8) & 0x000000ff00000000L) | ((v >> 8) & 0x00000000ff000000L) | ((v >> 24) & 0x0000000000ff0000L) | ((v >> 40) & 0x000000000000ff00L) | ((v >> 56) & 0x00000000000000ffL); } /** Swaps byte order of every short value in the specified array. */ - public static final void swap(short[] array) { + public static void swap(short[] array) { if (array != null) { for (int i = 0, cnt = array.length; i < cnt; i++) { array[i] = swap16(array[i]); @@ -240,7 +258,7 @@ public static final void swap(short[] array) { } /** Swaps byte order of every int value in the specified array. */ - public static final void swap(int[] array) { + public static void swap(int[] array) { if (array != null) { for (int i = 0, cnt = array.length; i < cnt; i++) { array[i] = swap32(array[i]); @@ -249,7 +267,7 @@ public static final void swap(int[] array) { } /** Swaps byte order of every long value in the specified array. */ - public static final void swap(long[] array) { + public static void swap(long[] array) { if (array != null) { for (int i = 0, cnt = array.length; i < cnt; i++) { array[i] = swap64(array[i]); @@ -258,18 +276,18 @@ public static final void swap(long[] array) { } /** Converts a short value into a byte array (little-endian). */ - public static final byte[] shortToArray(short value) { + public static byte[] shortToArray(short value) { return new byte[] { (byte) (value & 0xff), (byte) ((value >> 8) & 0xff) }; } /** Converts an int value into a byte array (little-endian). */ - public static final byte[] intToArray(int value) { + public static byte[] intToArray(int value) { return new byte[] { (byte) (value & 0xff), (byte) ((value >> 8) & 0xff), (byte) ((value >> 16) & 0xff), (byte) ((value >> 24) & 0xff) }; } /** Converts a long value into a byte array (little-endian). */ - public static final byte[] longToArray(long value) { + public static byte[] longToArray(long value) { return new byte[] { (byte) (value & 0xffL), (byte) ((value >> 8) & 0xffL), (byte) ((value >> 16) & 0xffL), (byte) ((value >> 24) & 0xffL), (byte) ((value >> 32) & 0xffL), (byte) ((value >> 40) & 0xffL), (byte) ((value >> 48) & 0xffL), (byte) ((value >> 56) & 0xffL) }; @@ -282,7 +300,7 @@ public static final byte[] longToArray(long value) { * @param bits Size of {@code value} in bits. * @return A sign-extended version of {@code value}. */ - public static final int signExtend(int value, int bits) { + public static int signExtend(int value, int bits) { return (value << (32 - bits)) >> (32 - bits); } @@ -293,7 +311,7 @@ public static final int signExtend(int value, int bits) { * @param bits Size of {@code value} in bits. * @return A sign-extended version of {@code value}. */ - public static final long signExtend(long value, int bits) { + public static long signExtend(long value, int bits) { return (value << (64 - bits)) >> (64 - bits); } @@ -590,6 +608,21 @@ public static String safeToString(Object o) { return (o != null) ? o.toString() : ""; } + /** + * Returns {@code obj} if non-null, otherwise return {@code def}. + * @param Type of the return value. + * @param obj The value to return if non-null. + * @param def A default value + * @return Returns {@code obj} if non-null, otherwise {@code def} is returned. + */ + public static T orDefault(T obj, T def) { + if (obj != null) { + return obj; + } else { + return def; + } + } + /** * This method throws a general {@link Exception} without message if the specified condition isn't met. * @@ -658,6 +691,72 @@ public static void requireCondition(boolean cond, String message, Class getFilesInPackage(String packageName) throws Exception { + final Package pkg = Package.getPackage(Objects.requireNonNull(packageName)); + if (pkg == null) { + throw new IllegalArgumentException("Package not found: " + packageName); + } + + final String pkgPath = pkg.getName().replace('.', '/'); + final URL pkgUrl = ClassLoader.getSystemClassLoader().getResource(pkgPath); + if (pkgUrl == null) { + throw new IOException("Resource not found: " + pkgPath); + } + + if ("jar".equals(pkgUrl.getProtocol())) { + return getFilesInJarPackage(pkg); + } else if ("file".equals(pkgUrl.getProtocol())) { + return getFilesInDefaultPackage(pkg); + } else { + throw new IOException("Unsupported resource location: " + pkgUrl); + } + } + + /** Used internally to return a list of all files in the specified package if the application is a JAR file. */ + private static List getFilesInJarPackage(Package pkg) throws Exception { + final List retVal = new ArrayList<>(); + + final URI jarLocation = Misc.class.getProtectionDomain().getCodeSource().getLocation().toURI(); + try (final JarInputStream jis = new JarInputStream(Files.newInputStream(Paths.get(jarLocation), StandardOpenOption.READ))) { + final String rootPath = pkg.getName().replace('.', '/') + "/"; + JarEntry je; + while ((je = jis.getNextJarEntry()) != null) { + if (je.getName().startsWith(rootPath) && !je.getName().equals(rootPath)) { + final Path path = Paths.get(je.getName()); + retVal.add(path); + } + } + } + + return retVal; + } + + /** + * Used internally to return a list of all files in the specified package if the application is invoked by a regular + * class file. + */ + private static List getFilesInDefaultPackage(Package pkg) throws Exception { + final List retVal = new ArrayList<>(); + + final String rootPath = pkg.getName().replace('.', '/'); + try (final BufferedReader reader = + new BufferedReader(new InputStreamReader(ClassLoader.getSystemClassLoader().getResourceAsStream(rootPath)))) { + final List lines = reader.lines().collect(Collectors.toList()); + for (final String line : lines) { + final Path path = Paths.get(rootPath, line); + retVal.add(path); + } + } + + return retVal; + } + // Contains static functions only private Misc() { } diff --git a/src/org/infinity/util/Platform.java b/src/org/infinity/util/Platform.java index 693e65e57..c22aa51cf 100644 --- a/src/org/infinity/util/Platform.java +++ b/src/org/infinity/util/Platform.java @@ -4,50 +4,117 @@ package org.infinity.util; +import java.io.File; +import java.nio.file.FileSystems; +import java.util.Locale; + /** - * This class can be used to determine the operating system where this Java application is running. + * This class provides information about the current architecture and operating system. */ public class Platform { + /** Enumeration of supported operating systems. */ public enum OS { - WINDOWS, UNIX, MAC_OS, SOLARIS, UNKNOWN, + WINDOWS("^.*win.*$"), + UNIX("^.*(nix|nux|aix|hpux|bsd).*$"), + MAC_OS("^.*(mac|osx|darwin).*$"), + SOLARIS("^.*(sunos|solaris).*$"), + UNKNOWN(null), + ; + + /** Returns the {@link OS} value that matches the current system architecture. */ + public static OS getCurrentOS() { + for (final OS os : OS.values()) { + if (os.isOS()) { + return os; + } + } + return UNKNOWN; + } + + private final boolean check; + + OS(String regex) { + final String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); + this.check = regex != null && osName.matches(regex); + } + + /** Returns whether this {@link OS} enum matches the current operating system. */ + public boolean isOS() { + return check; + } + } + + /** Enumeration of supported system architectures. */ + public enum Arch { + X86_64(64, "^(x8664|amd64|ia32e|em64t|x64)$"), + X86_32(32, "^(x86(32)?|i[3-6]86|ia32|x32)$"), + ITANIUM_64(64, "^(ia64w?|itanium64)$"), + ITANIUM_32(32, "^ia64n$"), + ARM_32(32, "^arm(32)?$"), + AARCH_64(64, "^aarch64$"), + PPC_32(32, "^ppc(32)?$"), + PPC_64(64, "^ppc64$"), + PPCLE_32(32, "^ppc(32)?le$"), + PPCLE_64(64, "^ppc64le$"), + UNKNOWN(0, null), + ; + + /** Returns the {@link Arch} value that matches the current system architecture. */ + public static Arch getCurrentArchitecture() { + for (final Arch arch : Arch.values()) { + if (arch.isArch()) { + return arch; + } + } + return UNKNOWN; + } + + private final int bitness; + private final boolean check; + + Arch(int bitness, String regex) { + final String arch = System.getProperty("os.arch").toLowerCase(Locale.ROOT); + this.check = regex != null && arch.matches(regex); + this.bitness = bitness; + } + + /** + * Returns the bitness of the {@link Arch} value. + * Returns {@code 0} if the value does not provide a specific bitness. + */ + public int getBitness() { + return bitness; + } + + /** Returns whether this {@link Arch} enum value matches the current system architecture. */ + public boolean isArch() { + return check; + } } /** Whether this a Microsoft Windows system. */ - public final static boolean IS_WINDOWS = (getPlatform() == OS.WINDOWS); + public final static boolean IS_WINDOWS = OS.WINDOWS.isOS(); /** Whether this GNU/Linux or another Unix-like operating system. */ - public final static boolean IS_UNIX = (getPlatform() == OS.UNIX); + public final static boolean IS_UNIX = OS.UNIX.isOS(); /** Whether this an Apple Mac OS X system. */ - public final static boolean IS_MACOS = (getPlatform() == OS.MAC_OS); + public final static boolean IS_MACOS = OS.MAC_OS.isOS(); /** Whether this a Sun OS or Solaris system. */ - public final static boolean IS_SOLARIS = (getPlatform() == OS.SOLARIS); + public final static boolean IS_SOLARIS = OS.SOLARIS.isOS(); + + /** Whether the system is a 32-bit architecture. */ + public final static boolean IS_32BIT = (Arch.getCurrentArchitecture().bitness == 32); + /** Whether the system is a 64-bit architecture. */ + public final static boolean IS_64BIT = (Arch.getCurrentArchitecture().bitness == 64); /** Returns the symbol used to separate individual path strings from each other for the current platform. */ - public final static String PATH_SEPARATOR = System.getProperty("path.separator"); + public final static String PATH_SEPARATOR = File.pathSeparator; /** Returns the system-dependent name-separator character as string for the current platform. */ - public final static String SEPARATOR = System.getProperty("file.separator"); + public final static String FILE_SEPARATOR = FileSystems.getDefault().getSeparator(); /** Returns the major version number of the active Java Runtime. */ public final static int JAVA_VERSION = getJavaVersion(); - /** - * Determines the current operating system. - */ - public static OS getPlatform() { - String osName = System.getProperty("os.name").toLowerCase(); - if (osName.contains("mac") || osName.contains("darwin")) { - return OS.MAC_OS; - } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix")) { - return OS.UNIX; - } else if (osName.contains("win")) { - return OS.WINDOWS; - } else if (osName.contains("sunos") || osName.contains("solaris")) { - return OS.SOLARIS; - } else { - return OS.UNKNOWN; - } - } - /** * Returns the Java Runtime major version. */ @@ -62,6 +129,7 @@ public static int getJavaVersion() { } retVal = major; } catch (NumberFormatException e) { + Logger.trace(e); } return retVal; diff --git a/src/org/infinity/util/ResourceStructure.java b/src/org/infinity/util/ResourceStructure.java index 7431ed94f..46d9b306b 100644 --- a/src/org/infinity/util/ResourceStructure.java +++ b/src/org/infinity/util/ResourceStructure.java @@ -38,7 +38,7 @@ public int add(int type) { } /** - * Specialized method: value argument interpreted as size for {@link #ID_STRING} and {@link #ID_ARRAY}. + * Specialized method: value argument interpreted as size for {@link #ID_STRING} and {@link #ID_BUFFER}. */ public int add(int type, int value) { return insert(cursize, type, value); @@ -70,7 +70,7 @@ public int insert(int offset, int type) { } /** - * Specialized method: value argument interpreted as size for {@link #ID_STRING} and {@link #ID_ARRAY}. + * Specialized method: value argument interpreted as size for {@link #ID_STRING} and {@link #ID_BUFFER}. */ public int insert(int offset, int type, int value) { switch (type) { @@ -81,7 +81,6 @@ public int insert(int offset, int type, int value) { case ID_DWORD: return insert(offset, type, type & 0xf, value); case ID_STRING: - return insert(offset, type, value, null); case ID_BUFFER: return insert(offset, type, value, null); default: @@ -266,7 +265,7 @@ public boolean equals(Object obj) { // -------------------------- INNER CLASSES -------------------------- - public final class Item implements Cloneable { + public static class Item implements Cloneable { private final int type; private final int size; private final Object value; @@ -320,7 +319,7 @@ private Item(int type, int size, Object value) { this.type = type; this.size = (type == ID_BYTE || type == ID_WORD || type == ID_DWORD) ? type & 0xf : size; if (type == ID_RESREF || type == ID_STRING) { - this.value = (value == null || !(value instanceof String)) ? "" : value; + this.value = (!(value instanceof String)) ? "" : value; } else if (type == ID_BUFFER) { if (value instanceof byte[]) { this.value = StreamUtils.getByteBuffer((byte[]) value); @@ -361,7 +360,7 @@ private ByteBuffer toBuffer() { case ID_STRING: if (value instanceof String) { byte[] b = ((String) value).getBytes(); - buf.put(Arrays.copyOf(b, b.length <= size ? b.length : size)); + buf.put(Arrays.copyOf(b, Math.min(b.length, size))); } break; case ID_BUFFER: diff --git a/src/org/infinity/util/SimpleListModel.java b/src/org/infinity/util/SimpleListModel.java index 02bffde93..49f451883 100644 --- a/src/org/infinity/util/SimpleListModel.java +++ b/src/org/infinity/util/SimpleListModel.java @@ -4,12 +4,7 @@ package org.infinity.util; -import java.util.Arrays; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.Objects; -import java.util.Vector; +import java.util.*; import javax.swing.AbstractListModel; @@ -26,9 +21,7 @@ public SimpleListModel() { /** Constructs a ListModel object containing the elements from the specified array. */ public SimpleListModel(E[] items) { delegate.ensureCapacity(items.length); - for (E item : items) { - delegate.add(item); - } + Collections.addAll(delegate, items); } /** Constructs a ListModel object containing the elements from the specified collection. */ diff --git a/src/org/infinity/util/StringBufferStream.java b/src/org/infinity/util/StringBufferStream.java index d56427b7a..d51ea51aa 100644 --- a/src/org/infinity/util/StringBufferStream.java +++ b/src/org/infinity/util/StringBufferStream.java @@ -173,7 +173,7 @@ public StringBufferStream skip() { public StringBufferStream skipWhitespace() { int pos = position; for (; pos < length; pos++) { - if (WHITE_SPACE.indexOf(data.charAt(start + pos), 0) < 0) { + if (WHITE_SPACE.indexOf(data.charAt(start + pos)) < 0) { break; } } @@ -324,7 +324,6 @@ public String peek(int size) { * Tests if the substring of this string beginning at the current position starts with the specified search string. * * @param s The search string. - * @return {@code true} if the string at the current position starts with the specified search string. * @return {@code true} if the search string matches the substring of this string beginning at the current position, * {@code false} otherwise. * @throws NullPointerException if s is {@code null}. diff --git a/src/org/infinity/util/StringTable.java b/src/org/infinity/util/StringTable.java index 78398a00a..3013ee7e8 100644 --- a/src/org/infinity/util/StringTable.java +++ b/src/org/infinity/util/StringTable.java @@ -77,7 +77,7 @@ public String format(String text, int strRef) { /** String entry flag: Available tokens will be resolved */ public static final short FLAGS_HAS_TOKEN = 0x04; /** The default flags value includes all supported bits */ - public static final short FLAGS_DEFAULT = 0x07; + public static final short FLAGS_DEFAULT = FLAGS_HAS_TEXT | FLAGS_HAS_SOUND | FLAGS_HAS_TOKEN; /** Strref start index for virtual strings referenced by ENGINEST.2DA (EE only) */ public static final int STRREF_VIRTUAL = 0xf00000; @@ -129,7 +129,7 @@ public static boolean setCharset(String cs) { retVal = true; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } @@ -712,7 +712,7 @@ public static boolean writeModified(Type type, ProgressCallback callback) { instance(type)._writeModified(callback); retVal = true; } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -747,6 +747,7 @@ public static boolean write(Type type, ProgressCallback callback) { instance(type)._write(callback); retVal = true; } catch (IOException e) { + Logger.trace(e); } return retVal; @@ -766,6 +767,7 @@ public static boolean write(Type type, Path tlkFile, ProgressCallback callback) instance(type)._write(tlkFile, callback); retVal = true; } catch (IOException e) { + Logger.trace(e); } return retVal; @@ -783,7 +785,7 @@ public static boolean exportText(Type type, Path outFile, ProgressCallback callb instance(type)._exportText(outFile, callback); retVal = true; } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } return retVal; @@ -845,10 +847,10 @@ public static boolean exportTra(Path outFile, ProgressCallback callback) { } boolean retVal = true; try (PrintWriter writer = new PrintWriter(outFile.toFile(), getCharset().name())) { - String newline = System.getProperty("line.separator"); + String newline = System.lineSeparator(); // writing header String niPath = Utils.getJarFileName(NearInfinity.class); - if (niPath == null || niPath.isEmpty()) { + if (niPath.isEmpty()) { niPath = "Near Infinity"; } niPath += " (" + NearInfinity.getVersion() + ")"; @@ -859,6 +861,7 @@ public static boolean exportTra(Path outFile, ProgressCallback callback) { try { pathDialog = Profile.getGameRoot().relativize(pathDialog); } catch (IllegalArgumentException e) { + Logger.trace(e); } writer.println("// dialog : " + pathDialog); @@ -868,6 +871,7 @@ public static boolean exportTra(Path outFile, ProgressCallback callback) { try { pathDialog = Profile.getGameRoot().relativize(pathDialog); } catch (IllegalArgumentException e) { + Logger.trace(e); } writer.println(pathDialog); } else { @@ -931,7 +935,7 @@ public static boolean exportTra(Path outFile, ProgressCallback callback) { writer.println(); } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); retVal = false; } finally { if (callback != null) { @@ -1005,8 +1009,8 @@ private int _getNumEntries() { private int _getTranslatedIndex(int index) { if (Profile.isEnhancedEdition() && index >= STRREF_VIRTUAL) { - if (entriesVirtual.containsKey(Integer.valueOf(index))) { - index = entriesVirtual.get(Integer.valueOf(index)); + if (entriesVirtual.containsKey(index)) { + index = entriesVirtual.get(index); } else { final Table2da engineTable = Table2daCache.get("ENGINEST.2DA"); int row = index - STRREF_VIRTUAL; @@ -1016,7 +1020,7 @@ private int _getTranslatedIndex(int index) { entriesVirtual.put(index, strref); index = strref; } catch (NumberFormatException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1109,7 +1113,7 @@ private void _init() { entriesPending = numEntries; initialized = true; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1160,7 +1164,7 @@ private StringEntry _loadEntry(FileChannel ch, int index) text = CharsetDetector.getLookup().decodeString(text); } } catch (IllegalArgumentException e) { - System.err.println("Error: Illegal offset " + ofsString + " for string entry " + index); + Logger.error("Error: Illegal offset {} for string entry {}", ofsString, index); text = ""; } } else { @@ -1222,7 +1226,7 @@ private void _ensureFullyLoaded() { } entriesPending = 0; } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1242,7 +1246,7 @@ private void _ensureIndexIsLoaded(int index) { throw new Exception(); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -1383,6 +1387,7 @@ private void _write(Path tlkPath, ProgressCallback callback) throws IOException } catch (IOException | UnsupportedOperationException e) { throw e; } catch (Exception e) { + Logger.trace(e); } finally { // 3. removing or restoring backup if (pathBackup != null) { @@ -1413,7 +1418,7 @@ private void _exportText(Path outFile, ProgressCallback callback) throws IOExcep } boolean success = false; try (PrintWriter writer = new PrintWriter(outFile.toFile(), getCharset().name())) { - String newline = System.getProperty("line.separator"); + String newline = System.lineSeparator(); for (int idx = 0; idx < _getNumEntries(); idx++) { if (callback != null) { success = callback.progress(idx); @@ -1467,6 +1472,10 @@ public StringEntry(StringTable parent) { resetModified(); } + public StringEntry(StringTable parent, short flags) { + this(parent, flags, "", 0, 0, ""); + } + public StringEntry(StringTable parent, short flags, String soundRef, int volume, int pitch, String text) { super(null, null, 0, 4); this.parent = parent; @@ -1642,7 +1651,7 @@ public void fillList(int index) { addField(e); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } } diff --git a/src/org/infinity/util/StructClipboard.java b/src/org/infinity/util/StructClipboard.java index dd7b23487..ca458fb25 100644 --- a/src/org/infinity/util/StructClipboard.java +++ b/src/org/infinity/util/StructClipboard.java @@ -138,6 +138,7 @@ public int getContentType(AbstractStruct struct) { for (final AddRemovable targetClass : targetClasses) { if (targetClass != null && c.equals(targetClass.getClass())) { found = true; + break; } } if (!found) { @@ -178,7 +179,7 @@ public int paste(AbstractStruct targetStruct) { ++i; } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } return lastIndex; } @@ -200,7 +201,7 @@ public int pasteValue(AbstractStruct struct, int index) { struct.setField(index + i, newEntry); } } catch (CloneNotSupportedException e) { - e.printStackTrace(); + Logger.error(e); return 0; } return contents.size(); @@ -219,7 +220,7 @@ private void copy(AbstractStruct struct, int firstIndex, int lastIndex, boolean contents.add(entry.clone()); } } catch (CloneNotSupportedException e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/util/Table2da.java b/src/org/infinity/util/Table2da.java index 2c6cce285..ebb3c155c 100644 --- a/src/org/infinity/util/Table2da.java +++ b/src/org/infinity/util/Table2da.java @@ -53,7 +53,7 @@ public void reload() { init(entry); } - /** Returns total number of columns, including header column. */ + /** Returns total number of data columns. */ public int getColCount() { return table.isEmpty() ? header.size() : columnCount; } @@ -66,7 +66,7 @@ public int getColCount(int row) { return 0; } - /** Returns number of rows, including header row. */ + /** Returns number of data rows. */ public int getRowCount() { return table.size(); } @@ -187,7 +187,7 @@ private void init(ResourceEntry entry) { defaultValue = new Entry(this, "0", 1, 0); } } catch (Exception e) { - e.printStackTrace(); + Logger.error(e); } } diff --git a/src/org/infinity/util/Table2daCache.java b/src/org/infinity/util/Table2daCache.java index fdad68077..8458d69e5 100644 --- a/src/org/infinity/util/Table2daCache.java +++ b/src/org/infinity/util/Table2daCache.java @@ -24,6 +24,26 @@ public static synchronized void clearCache() { MAP.clear(); } + /** + * Returns whether the specified 2DA resource has already been cached. + * + * @param resource 2DA resource name. + * @return {@code true} if the resource has been cached, {@code false} otherwise. + */ + public static boolean isCached(String resource) { + return isCached(ResourceFactory.getResourceEntry(resource)); + } + + /** + * Returns whether the specified 2DA resource has already been cached. + * + * @param entry 2DA resource entry. + * @return {@code true} if the resource has been cached, {@code false} otherwise. + */ + public static boolean isCached(ResourceEntry entry) { + return (entry != null && MAP.containsKey(entry)); + } + /** * Returns a Table2da object based on the specified 2DA resource. * diff --git a/src/org/infinity/util/Threading.java b/src/org/infinity/util/Threading.java index 0ab00dc1c..e915a223d 100644 --- a/src/org/infinity/util/Threading.java +++ b/src/org/infinity/util/Threading.java @@ -5,7 +5,6 @@ package org.infinity.util; import java.util.Collection; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; @@ -70,7 +69,7 @@ public String toString() { public static final int MAX_THREADS_AVAILABLE = Runtime.getRuntime().availableProcessors(); /** Contains the number of remaining threads for use by new thread pools. */ - private static AtomicInteger THREADS_AVAILABLE = new AtomicInteger(MAX_THREADS_AVAILABLE); + private static final AtomicInteger THREADS_AVAILABLE = new AtomicInteger(MAX_THREADS_AVAILABLE); /** Stores submitted tasks for internal evaluation purposes. */ @@ -186,12 +185,7 @@ public boolean isTerminated() { * @return Number of remaining {@link ForkJoinTask} instances that haven been completed or cancelled yet. */ public synchronized int dispose() { - for (final Iterator> iter = taskList.iterator(); iter.hasNext(); ) { - final Future future = iter.next(); - if (future.isDone()) { - iter.remove(); - } - } + taskList.removeIf(Future::isDone); return taskList.size(); } @@ -199,10 +193,6 @@ public synchronized int dispose() { * Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be * accepted. Tasks that are in the process of being submitted concurrently during the course of this method may or may * not be rejected. - * - *

- * The predefined {@code Threading} objects {@link #DEFAULT} and {@link #SINGLE} cannot be terminated. - *

*/ public void shutdown() { executor.shutdown(); @@ -213,11 +203,7 @@ public void shutdown() { * Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. Invocation has no * additional effect if already shut down. Otherwise, tasks that are in the process of being submitted or executed * concurrently during the course of this method may or may not be rejected. This method cancels both existing and - * unexecuted tasks, in order to permit termination in the presence of task dependencies. - * - *

- * The predefined {@code Threading} objects {@link #DEFAULT} and {@link #SINGLE} cannot be terminated. - *

+ * not executed tasks, in order to permit termination in the presence of task dependencies. */ public void shutdownNow() { executor.shutdownNow(); @@ -274,11 +260,8 @@ public List> invokeAll(Collection> tasks) th Objects.requireNonNull(tasks, "Tasks collection is null"); final List> retVal = executor.invokeAll(tasks); - if (retVal != null) { - for (final Iterator> iter = retVal.iterator(); iter.hasNext(); ) { - final Future future = iter.next(); - registerFuture(future); - } + for (final Future future : retVal) { + registerFuture(future); } return retVal; } @@ -288,8 +271,6 @@ public List> invokeAll(Collection> tasks) th * first. Unlike {@link #awaitTermination(long, TimeUnit)} this method does not depend on a shutdown request, which * allows to submit more tasks after completion. * - * @param timeout the maximum time to wait. - * @param unit the time unit of the timeout argument. * @return {@code true} if all submitted tasks terminated and {@code false} if the timeout elapsed before termination. * @throws InterruptedException if interrupted while waiting. */ @@ -375,6 +356,7 @@ public void close() throws Exception { try { Thread.sleep(100L); } catch (InterruptedException e) { + Logger.trace(e); } final long timeElapsed = System.nanoTime() - timeBase; timeBase = System.nanoTime(); @@ -418,7 +400,6 @@ private > U registerFuture(U future) { * Reserves the amount of threads defined by the given {@code Threading} object and updates * {@link #THREADS_AVAILABLE}. * - * @param threading {@link Threading} object that requests thread reservation. * @return {@code true} if reservation completed successfully, {@code false} otherwise. */ private synchronized boolean allocateThreads() { @@ -434,7 +415,6 @@ private synchronized boolean allocateThreads() { * Releases the amount of threads defined by the given {@code Threading} object and updates * {@link #THREADS_AVAILABLE}. * - * @param threading {@link Threading} object that requests the release of threads. * @return {@code true} if release complete successfully, {@code false} otherwise. */ private synchronized boolean releaseThreads() { diff --git a/src/org/infinity/util/io/DlcManager.java b/src/org/infinity/util/io/DlcManager.java index 407136aa8..b9f95549d 100644 --- a/src/org/infinity/util/io/DlcManager.java +++ b/src/org/infinity/util/io/DlcManager.java @@ -14,6 +14,7 @@ import java.nio.file.spi.FileSystemProvider; import java.util.HashMap; +import org.infinity.util.Logger; import org.infinity.util.io.zip.DlcFileSystem; import org.infinity.util.io.zip.DlcFileSystemProvider; @@ -99,14 +100,14 @@ private Path _queryKey(Path path) { if (fs != null) { for (final String keyFile : KEY_FILES) { Path key = fs.getPath(keyFile); - if (key != null && FileEx.create(key).isFile()) { + if (FileEx.create(key).isFile()) { try (InputStream is = StreamUtils.getInputStream(key)) { String sig = StreamUtils.readString(is, 8); if ("KEY V1 ".equals(sig)) { return key; } } catch (IOException e) { - e.printStackTrace(); + Logger.error(e); } } } @@ -159,6 +160,7 @@ private FileSystem _validateDlc(Path dlcFile) { try { fs.close(); } catch (Throwable t2) { + Logger.trace(t2); } fs = null; } @@ -172,6 +174,7 @@ private void _close() { try { fs.close(); } catch (IOException e) { + Logger.trace(e); } } fileSystems.clear(); diff --git a/src/org/infinity/util/io/FileEx.java b/src/org/infinity/util/io/FileEx.java index 4cdbfc7d6..23b4180f2 100644 --- a/src/org/infinity/util/io/FileEx.java +++ b/src/org/infinity/util/io/FileEx.java @@ -22,10 +22,11 @@ import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; -import java.util.Iterator; +import java.util.Objects; import java.util.Set; import org.infinity.util.FileDeletionHook; +import org.infinity.util.Logger; /** * Expands the {@link File} class by custom filesystem support. @@ -138,7 +139,7 @@ public FileEx(File parent, String child, FileSystem filesystem) { * @throws NullPointerException If {@code path} is {@code null} */ public FileEx(Path path) { - super((path != null) ? path.toString() : null); + super(Objects.requireNonNull(path).toString()); this.path = validatePath(path); } @@ -265,11 +266,12 @@ public String[] list() { if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { try (DirectoryStream ds = Files.newDirectoryStream(path)) { ArrayList list = new ArrayList<>(); - for (Iterator iter = ds.iterator(); iter.hasNext();) { - list.add(iter.next().getFileName().toString()); + for (Path d : ds) { + list.add(d.getFileName().toString()); } - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } catch (Exception ex) { + Logger.trace(ex); } } return null; @@ -285,14 +287,15 @@ public String[] list(FilenameFilter filter) { try (DirectoryStream ds = Files.newDirectoryStream(path)) { File dir = new FileEx(path); ArrayList list = new ArrayList<>(); - for (Iterator iter = ds.iterator(); iter.hasNext();) { - String s = iter.next().getFileName().toString(); + for (Path d : ds) { + String s = d.getFileName().toString(); if (filter == null || filter.accept(dir, s)) { list.add(s); } } - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } catch (Exception ex) { + Logger.trace(ex); } } return null; @@ -307,11 +310,12 @@ public File[] listFiles() { if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { try (DirectoryStream ds = Files.newDirectoryStream(path)) { ArrayList list = new ArrayList<>(); - for (Iterator iter = ds.iterator(); iter.hasNext();) { - list.add(new FileEx(iter.next())); + for (Path d : ds) { + list.add(new FileEx(d)); } - return list.toArray(new File[list.size()]); + return list.toArray(new File[0]); } catch (Exception ex) { + Logger.trace(ex); } } return null; @@ -332,8 +336,9 @@ public File[] listFiles(FilenameFilter filter) { list.add(new FileEx(p)); } } - return list.toArray(new File[list.size()]); + return list.toArray(new File[0]); } catch (Exception ex) { + Logger.trace(ex); } } return null; @@ -348,14 +353,15 @@ public File[] listFiles(FileFilter filter) { if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { try (DirectoryStream ds = Files.newDirectoryStream(path)) { ArrayList list = new ArrayList<>(); - for (Iterator iter = ds.iterator(); iter.hasNext();) { - File f = new FileEx(iter.next()); + for (Path d : ds) { + File f = new FileEx(d); if (filter == null || filter.accept(f)) { list.add(f); } } - return list.toArray(new File[list.size()]); + return list.toArray(new File[0]); } catch (Exception ex) { + Logger.trace(ex); } } return null; @@ -443,6 +449,7 @@ public boolean setReadOnly() { throw new UnsupportedOperationException(); } } catch (IOException ex) { + Logger.trace(ex); } return false; } @@ -476,6 +483,7 @@ public boolean setWritable(boolean writable, boolean ownerOnly) { throw new UnsupportedOperationException(); } } catch (IOException ex) { + Logger.trace(ex); } return false; } @@ -509,6 +517,7 @@ public boolean setReadable(boolean readable, boolean ownerOnly) { throw new UnsupportedOperationException(); } } catch (IOException ex) { + Logger.trace(ex); } return false; } @@ -542,6 +551,7 @@ public boolean setExecutable(boolean executable, boolean ownerOnly) { throw new UnsupportedOperationException(); } } catch (IOException ex) { + Logger.trace(ex); } return false; } @@ -611,7 +621,7 @@ private static FileSystem validateFileSystem(FileSystem fs) { // Returns a well-defined Path instance for internal use. private static Path validatePath(Path path) { if (path != null) { - if (path.getFileSystem() == null || DEFAULT_FS.equals(path.getFileSystem())) { + if (DEFAULT_FS.equals(path.getFileSystem())) { path = null; } } diff --git a/src/org/infinity/util/io/FileManager.java b/src/org/infinity/util/io/FileManager.java index 54957267c..bd43e6db2 100644 --- a/src/org/infinity/util/io/FileManager.java +++ b/src/org/infinity/util/io/FileManager.java @@ -10,31 +10,45 @@ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardWatchEventKinds; +import java.nio.file.Paths; import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; import java.util.List; -import java.util.stream.Stream; +import java.util.Objects; +import org.infinity.util.Logger; import org.infinity.util.Platform; -import org.infinity.util.io.FileWatcher.FileWatchEvent; -import org.infinity.util.io.FileWatcher.FileWatchListener; /** * Central hub for accessing game-related I/O resources. */ -public class FileManager implements FileWatchListener { - private static final HashMap> PATH_CACHE = new HashMap<>(); +public class FileManager { + private static boolean caseSensitiveMode = getDefaultCaseSensitiveMode(); - private static FileManager instance; + /** + * Returns whether file paths should be polled directly from the filesystem + * to work with case-sensitive filesystems. + * + *

By default returns {@code true} only for Linux platforms.

+ */ + public static boolean isCaseSensitiveMode() { + return caseSensitiveMode; + } - public static void reset() { - PATH_CACHE.clear(); - if (instance != null) { - instance.close(); - } - instance = null; + /** + * This method can be used to override the default case-sensitive operation mode for filesystems. + * + * @param force Specify {@code true} to force polling path names from the filesystem. + */ + public static void setCaseSensitiveMode(boolean force) { + caseSensitiveMode = force; + } + + /** Returns the default case-sensitivity mode for the current platform. */ + public static boolean getDefaultCaseSensitiveMode() { + return Platform.IS_UNIX; } /** @@ -47,7 +61,7 @@ public static void reset() { * @return The {@code Path} based on {@code root} and the specified path elements. */ public static Path query(Path rootPath, String path, String... more) { - return getInstance()._query(rootPath, path, more); + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), path, more, false); } /** @@ -61,24 +75,7 @@ public static Path query(Path rootPath, String path, String... more) { * priority if {@code path} does not exist. */ public static Path query(List rootPaths, String path, String... more) { - return getInstance()._query(rootPaths, path, more); - } - - /** - * Returns a {@link Path} to the first matching file of the specified path in one of the listed {@code rootPaths} - * filtered by {@code rootFilter}. - * - * @param rootFilter Limit search to {@code rootPaths} which are based on this root {@code Path}. Specify {@code null} - * to ignore {@code rootFilter}. - * @param rootPaths List of {@code Path} objects which are searched in order to find {@code path}. - * @param path Relative path to a file or directory. - * @param more More optional path elements that are appended to {@code path}. - * @return The {@code Path} to the first matching file. Returns a {@code Path} based on the search path of lowest - * priority based on {@code root} if {@code path} does not exist. Returns a {@code Path} based on the current - * working path if {@code rootPaths} is empty after applying {@code rootFilter}. - */ - public static Path query(Path rootFilter, List rootPaths, String path, String... more) { - return getInstance()._query(rootFilter, rootPaths, path, more); + return queryPath(rootPaths, path, more, false); } /** @@ -92,7 +89,7 @@ public static Path query(Path rootFilter, List rootPaths, String path, Str * {@code path} does not exist. */ public static Path queryExisting(Path rootPath, String path, String... more) { - return getInstance()._queryExisting(rootPath, path, more); + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), path, more, true); } /** @@ -105,22 +102,7 @@ public static Path queryExisting(Path rootPath, String path, String... more) { * @return The {@code Path} to the first matching file. Returns {@code null} if {@code path} does not exist. */ public static Path queryExisting(List rootPaths, String path, String... more) { - return getInstance()._queryExisting(rootPaths, path, more); - } - - /** - * Returns a {@link Path} to the first matching file of the specified path in one of the listed {@code rootPaths} - * filtered by {@code rootFilter}. - * - * @param rootFilter Limit search to {@code rootPaths} which are based on this root {@code Path}. Specify {@code null} - * to ignore {@code rootFilter}. - * @param rootPaths List of {@code Path} objects which are searched in order to find {@code path}. - * @param path Relative path to a file or directory. - * @param more More optional path elements that are appended to {@code path}. - * @return The {@code Path} to the first matching file. Returns {@code null} if {@code path} does not exist. - */ - public static Path queryExisting(Path rootFilter, List rootPaths, String path, String... more) { - return getInstance()._queryExisting(rootFilter, rootPaths, path, more); + return queryPath(rootPaths, path, more, true); } /** @@ -133,14 +115,10 @@ public static Path queryExisting(Path rootFilter, List rootPaths, String p * @return The resolved path or {@code null} on error. */ public static Path resolve(String path, String... more) { - if (path != null) { - try { - return _resolve(FileSystems.getDefault().getPath(path, more)); - } catch (Throwable t) { - t.printStackTrace(); - } - } - return null; + final Path fullPath = Paths.get(Objects.requireNonNull(path), more); + final Path rootPath = fullPath.getParent(); + final String fileName = (fullPath.getFileName() != null) ? fullPath.getFileName().toString() : null; + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), new String[] {fileName}, false); } /** @@ -151,14 +129,10 @@ public static Path resolve(String path, String... more) { * @return The resolved path or {@code null} on error or the specified path does not exist. */ public static Path resolveExisting(String path, String... more) { - if (path != null) { - try { - return _resolveExisting(FileSystems.getDefault().getPath(path, more)); - } catch (Throwable t) { - t.printStackTrace(); - } - } - return null; + final Path fullPath = Paths.get(Objects.requireNonNull(path), more); + final Path rootPath = fullPath.getParent(); + final String fileName = (fullPath.getFileName() != null) ? fullPath.getFileName().toString() : null; + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), new String[] {fileName}, true); } /** @@ -170,7 +144,9 @@ public static Path resolveExisting(String path, String... more) { * @return The resolved path. */ public static Path resolve(Path path) { - return _resolve(path); + final Path rootPath = Objects.requireNonNull(path).getParent(); + final String fileName = (path.getFileName() != null) ? path.getFileName().toString() : null; + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), new String[] {fileName}, false); } /** @@ -180,36 +156,9 @@ public static Path resolve(Path path) { * @return The resolved path or {@code null} on error or the specified path does not exist. */ public static Path resolveExisting(Path path) { - return _resolveExisting(path); - } - - /** - * Removes the specified directory from the cache. - * - * @param dir The directory to remove from the cache. - */ - public static void invalidateDirectory(Path dir) { - _invalidateDirectory(dir); - } - - /** - * Registers the specified file in the file cache. This method should always be called if one or more individual files - * have been added to a game directory. Does nothing if the parent directory has not been cached yet. - * - * @param file The file to register. - */ - public static void registerFile(Path file) { - _registerFile(file); - } - - /** - * Removes the specified file from the file cache. This method should always be called if one or more individual files - * have been removed from a game directory. Does nothing if the parent directory has not been cached yet. - * - * @param file The file to unregister. - */ - public static void unregisterFile(Path file) { - _unregisterFile(file); + final Path rootPath = Objects.requireNonNull(path).getParent(); + final String fileName = (path.getFileName() != null) ? path.getFileName().toString() : null; + return queryPath(new ArrayList<>(Collections.singletonList(rootPath)), new String[] {fileName}, true); } /** @@ -221,7 +170,7 @@ public static void unregisterFile(Path file) { public static boolean isReadOnly(Path path) { if (path != null) { FileSystem fs = path.getFileSystem(); - if (fs != null && fs.isOpen()) { + if (fs.isOpen()) { return fs.isReadOnly(); } } @@ -257,6 +206,7 @@ public static boolean isSamePath(Path path, List list) { return true; } } catch (IOException e) { + Logger.trace(e); } } } @@ -295,18 +245,17 @@ public static Path getContainedPath(Path path, List list) { } /** - * Returns the file extension of the specified path. + * Returns the file extension of the specified path string. * - * @param path File or folder path. + * @param path File or folder path string. * @return the empty or non-empty file extension, or {@code null} on error. */ - public static String getFileExtension(Path path) { + public static String getFileExtension(String path) { String retVal = null; if (path != null) { - String leaf = path.getFileName().toString(); - int p = leaf.lastIndexOf('.'); - if (p >= 0) { - retVal = leaf.substring(p + 1); + int pos = path.lastIndexOf('.'); + if (pos >= 0) { + retVal = path.substring(pos + 1); } else { retVal = ""; } @@ -314,253 +263,150 @@ public static String getFileExtension(Path path) { return retVal; } - private FileManager() { - FileWatcher.getInstance().addFileWatchListener(this); - } - - private Path _query(Path rootPath, String path, String... more) { - List rootPaths = null; - if (rootPath != null) { - rootPaths = new ArrayList<>(); - rootPaths.add(rootPath); + /** + * Returns the file extension of the specified path. + * + * @param path File or folder path. + * @return the empty or non-empty file extension, or {@code null} on error. + */ + public static String getFileExtension(Path path) { + String retVal = null; + if (path != null) { + retVal = getFileExtension(path.getFileName().toString()); } - return _queryPath(false, (Path) null, rootPaths, path, more); - } - - private Path _query(List rootPaths, String path, String... more) { - return _queryPath(false, (Path) null, rootPaths, path, more); + return retVal; } - private Path _query(Path rootFilter, List rootPaths, String path, String... more) { - return _queryPath(false, rootFilter, rootPaths, path, more); + /** + * Attempts to resolve the path elements to a {@link Path} that matches the given criteria. + * + * @param rootPaths List of root {@link Path} instances to test with the specified path elements. + * @param path Path element to resolve against any of the root paths. + * @param more More optional path elements to resolve against any of the root paths. + * @param mustExist Specifies whether the resolved path must point to an existing filesystem object. + * @return a {@link Path} object with the first path the given criteria, {@code null} otherwise. + */ + private static Path queryPath(List rootPaths, String path, String[] more, boolean mustExist) { + final String[] paths = new String[more.length + 1]; + paths[0] = path; + System.arraycopy(more, 0, paths, 1, more.length); + return queryPath(rootPaths, paths, mustExist); } - private Path _queryExisting(Path rootPath, String path, String... more) { - List rootPaths = null; - if (rootPath != null) { + /** + * Attempts to resolve the path elements to a {@link Path} that matches the given criteria. + * + * @param rootPaths List of root {@link Path} instances to test with the specified path elements. + * @param paths Optional path elements to resolve against any of the root paths. + * @param mustExist Specifies whether the resolved path must point to an existing filesystem object. + * @return a {@link Path} object with the first path the given criteria, {@code null} otherwise. + */ + private static Path queryPath(List rootPaths, String[] paths, boolean mustExist) { + if (rootPaths == null) { rootPaths = new ArrayList<>(); - rootPaths.add(rootPath); + } else { + rootPaths = new ArrayList<>(rootPaths); } - return _queryPath(true, (Path) null, rootPaths, path, more); - } - private Path _queryExisting(List rootPaths, String path, String... more) { - return _queryPath(true, (Path) null, rootPaths, path, more); - } - - private Path _queryExisting(Path rootFilter, List rootPaths, String path, String... more) { - return _queryPath(true, rootFilter, rootPaths, path, more); - } - - private Path _queryPath(boolean mustExist, Path rootFilter, List rootPaths, String path, String... more) { - // path must be defined - if (path == null) { - return null; + if (rootPaths.stream().noneMatch(Objects::nonNull)) { + // add current working directory if no root paths are provided + rootPaths.add(FileSystems.getDefault().getPath(".").toAbsolutePath().normalize()); } - if (rootPaths == null) { - rootPaths = new ArrayList<>(); + if (paths.length == 0) { + paths = new String[1]; } - // filter search - if (rootFilter != null) { - int idx = 0; - while (idx < rootPaths.size()) { - Path curPath = rootPaths.get(idx); - if (curPath.startsWith(rootFilter)) { - rootPaths.remove(idx); - } else { - idx++; - } - } - } - - // use current working path as fallback - if (rootPaths.isEmpty()) { - rootPaths.add(FileSystems.getDefault().getPath("").toAbsolutePath().normalize()); + if (paths[0] == null) { + paths[0] = "."; } - // ensure that path is relative - if (!path.isEmpty()) { - if (path.charAt(0) == '/' || path.charAt(0) == '\\') { - path = path.substring(1); + // ensure that "path" is relative + if (!paths[0].isEmpty()) { + if (paths[0].charAt(0) == '/' || paths[0].charAt(0) == '\\') { + paths[0] = paths[0].substring(1); } } Path curPath = null; - boolean exists = false; - try { - for (final Path curRoot : rootPaths) { + for (final Path rootPath : rootPaths) { + if (rootPath != null) { try { - Path relPath = curRoot.getFileSystem().getPath(path, more).normalize(); - if (mustExist) { - curPath = _resolveExisting(curRoot.resolve(relPath)); - if (curPath != null) { - exists = true; - break; - } - } else { - curPath = _resolve(curRoot.resolve(relPath)); - if (curPath != null && FileEx.create(curPath).exists()) { - exists = true; - break; - } + final String path = paths[0]; + final String[] more = Arrays.copyOfRange(paths, 1, paths.length); + final Path relPath = rootPath.getFileSystem().getPath(path, more).normalize(); + curPath = resolvePath(rootPath.resolve(relPath), mustExist); + if (curPath != null && (mustExist || FileEx.create(curPath).exists())) { + break; } - } catch (Exception e) { - // e.printStackTrace(); + } catch (IllegalArgumentException e) { + Logger.trace(e); } } - } catch (Throwable t) { - curPath = null; - t.printStackTrace(); - } - - if (mustExist && !exists) { - curPath = null; } return curPath; } - private void close() { - FileWatcher.getInstance().removeFileWatchListener(this); - } - - @Override - public void fileChanged(FileWatchEvent e) { - if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - if (FileEx.create(e.getPath()).isDirectory()) { - // load whole directory into cache - _cacheDirectory(e.getPath(), true); - } else { - _registerFile(e.getPath()); - } - } else if (e.getKind() == StandardWatchEventKinds.ENTRY_DELETE) { - _unregisterFile(e.getPath()); - } - } - - private static FileManager getInstance() { - if (instance == null) { - instance = new FileManager(); - } - return instance; - } - - // Attempts to find a path which matches an existing path on case-sensitive filesystems. - // Simply returns "path" on case-insensitive filesystems. - private static Path _resolve(Path path) { + /** + * Matches as many of the path elements against existing paths. + * + * @param path Path to match against existing path. + * @param forced Instructs the resolver to return only existing paths. + * @return {@link Path} object that matches the given criteria, {@code null} otherwise. + */ + private static Path resolvePath(Path path, boolean forced) { Path retVal = path; - if (path != null && isFileSystemCaseSensitive(path.getFileSystem()) && !FileEx.create(path).exists()) { - boolean found = false; - Path curPath = path.normalize().toAbsolutePath(); - Path dir = curPath.getRoot(); - for (final Path searchPath : curPath) { - String searchString = searchPath.getFileName().toString(); - found = false; - try (DirectoryStream ds = Files.newDirectoryStream(dir)) { - for (final Path dirPath : ds) { - String dirString = dirPath.getFileName().toString(); - if (searchString.equalsIgnoreCase(dirString)) { - dir = dir.resolve(dirString); - found = true; + + final FileEx pathEx = FileEx.create(path); + if (path != null && (isCaseSensitiveMode() || !isDefaultFileSystem(path))) { + // validating path segments + Path validatedPath = path.getRoot(); + if (validatedPath != null && FileEx.create(validatedPath).exists()) { + int idx = 0; + for (; idx < path.getNameCount(); idx++) { + final Path pathItem = path.getName(idx); + final String pathName = pathItem.toString(); + + final Path resolvedPath = validatedPath.resolve(pathName); + if (Files.exists(resolvedPath)) { + validatedPath = resolvedPath; + } else { + try (final DirectoryStream ds = Files.newDirectoryStream(validatedPath, + p -> p.getFileName().toString().equalsIgnoreCase(pathName))) { + final Iterator iter = ds.iterator(); + if (iter.hasNext()) { + validatedPath = iter.next(); + } else { + break; + } + } catch (IOException e) { break; } } - } catch (Throwable t) { - } - if (!found) { - break; } - } - if (found) { - // use detected path - retVal = dir; - } else if (dir.getNameCount() < curPath.getNameCount()) { - // resolve partial path (needed if filename does not exist in path) - retVal = dir.resolve(curPath.subpath(dir.getNameCount(), curPath.getNameCount())); - } - } - - return retVal; - } - - private static void _registerFile(Path file) { - if (file != null) { - file = _resolve(file); - HashSet set = PATH_CACHE.get(file.getParent()); - if (set != null) { - set.add(file); - } - } - } - - private static void _unregisterFile(Path file) { - if (file != null) { - file = _resolve(file); - HashSet set = PATH_CACHE.get(file.getParent()); - if (set != null) { - set.remove(file); - if (set.isEmpty()) { - PATH_CACHE.remove(file.getParent()); + // adding remaining unvalidated path segments (if any) + if (forced && idx < path.getNameCount()) { + validatedPath = null; + } else { + for (; idx < path.getNameCount(); idx++) { + validatedPath = validatedPath.resolve(path.getName(idx)); + } } - } else if (PATH_CACHE.containsKey(file)) { - PATH_CACHE.remove(file); - } - } - } - private static void _invalidateDirectory(Path dir) { - if (dir != null && PATH_CACHE.containsKey(dir)) { - PATH_CACHE.remove(dir); + retVal = validatedPath; + } + } else if (forced && !pathEx.exists()) { + retVal = null; } - } - private static Path _resolveExisting(Path path) { - Path retVal = _resolve(path); if (retVal != null) { - Path folder = retVal.getParent(); - HashSet list = PATH_CACHE.get(folder); - if (list == null) { - list = _cacheDirectory(folder, false); - } - if (list == null) { - retVal = null; - } else { - final String pathString = path.getFileName().toString(); - retVal = list.stream().filter(p -> pathString.equalsIgnoreCase(p.getFileName().toString())).findAny() - .orElse(null); - } + retVal = retVal.normalize(); } - return retVal; - } - private static HashSet _cacheDirectory(Path path, boolean force) { - HashSet retVal = null; - if (path != null && FileEx.create(path).isDirectory()) { - if (force) { - PATH_CACHE.remove(path); - } - retVal = PATH_CACHE.get(path); - if (retVal == null) { - HashSet fileList = new HashSet<>(); - try (Stream pathStream = Files.list(path)) { - pathStream.forEach(file -> { - fileList.add(file); - }); - } catch (IOException e) { - } - retVal = fileList; - PATH_CACHE.put(path, retVal); - } - } return retVal; } - - // Returns whether the specified filesystem is case-sensitive - private static boolean isFileSystemCaseSensitive(FileSystem fs) { - // quick&dirty solution - return Platform.IS_UNIX; + private FileManager() { } } diff --git a/src/org/infinity/util/io/FileWatcher.java b/src/org/infinity/util/io/FileWatcher.java deleted file mode 100644 index 2a7b3b14d..000000000 --- a/src/org/infinity/util/io/FileWatcher.java +++ /dev/null @@ -1,383 +0,0 @@ -// Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 Jon Olav Hauglid -// See LICENSE.txt for license information - -package org.infinity.util.io; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchEvent.Kind; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * Continuously monitors one or more registered paths for content changes and notifies registered listeners about the - * changes. TODO: watched directories are locked on Windows and can't be properly deleted - find workaround - */ -public class FileWatcher implements Runnable { - private static final long DEFAULT_TIMEOUT = 250; - - private static FileWatcher instance = null; - - private final HashMap pathMap = new HashMap<>(); - private final ArrayList listeners = new ArrayList<>(); - - private WatchService watcher; - private Thread thread; - private long timeOutMS; - - /** Returns the active FileWatcher instance. */ - public static FileWatcher getInstance() { - if (instance == null) { - instance = new FileWatcher(DEFAULT_TIMEOUT); - } - return instance; - } - - @SuppressWarnings("unchecked") - private static WatchEvent cast(WatchEvent event) { - return (WatchEvent) event; - } - - protected FileWatcher(long timeOutMS) { - try { - this.watcher = FileSystems.getDefault().newWatchService(); - } catch (IOException e) { - this.watcher = null; - System.err.println("Could not initialize file watcher: " + e.getMessage()); - } - this.thread = null; - this.timeOutMS = Math.max(timeOutMS, 0L); - } - - /** - * Adds the specified filewatch listener to receive notifications about file changes in registered directories. - * - * @param l the filewatch listener - */ - public void addFileWatchListener(FileWatchListener l) { - if (l != null && !listeners.contains(l)) { - listeners.add(l); - } - } - - /** - * Removes the specified filewatch listener so that it no longer receives events from this FileWatcher instance. - * - * @param l the filewatch listener - */ - public void removeFileWatchListener(FileWatchListener l) { - if (l != null) { - listeners.remove(l); - } - } - - /** - * Returns an array of all filewatch listeners registered to this FileWatcher instance. - * - * @return all of this {@code FileWatcher}'s {@code FileWatchListener}s. - */ - public FileWatchListener[] getFileWatchListeners() { - return listeners.toArray(new FileWatchListener[listeners.size()]); - } - - /** Starts the file watcher background process. Does nothing if the process has already started. */ - public boolean start() { - if (Objects.isNull(watcher)) { - return false; - } - - if (thread == null) { - thread = new Thread(this); - thread.start(); - return true; - } else { - return false; - } - } - - /** Terminates the file watcher process. Does nothing if the process is not running. */ - public boolean stop() { - if (thread != null) { - Thread t = thread; - thread = null; - try { - t.join(timeOutMS * 10); - } catch (InterruptedException e) { - } - return true; - } else { - return false; - } - } - - /** Returns whether the file watcher background process is running. */ - public boolean isRunning() { - return (thread != null); - } - - /** Returns the interval between filesystem checks (in milliseconds). */ - public long getCheckInterval() { - return timeOutMS; - } - - /** Sets the interval between filesystem checks (in milliseconds). */ - public void setCheckInterval(long timeMS) { - this.timeOutMS = Math.max(timeMS, 0L); - } - - /** Removes all registered directories at once. */ - public void reset() { - synchronized (pathMap) { - for (final WatchKey key : pathMap.keySet()) { - key.cancel(); - } - pathMap.clear(); - } - } - - /** - * Adds the specified directory path and optional subdirectories to the watcher list with enabled notifications for - * create and delete operations. Does nothing if the path has already been registered. - */ - public void register(Path dir, boolean recursive) { - register(dir, recursive, true, true, false); - } - - /** - * Adds the specified directory path and optional subdirectories to the watcher list for a selected set of - * notification types. Does nothing if the path has already been registered. - * - * @param dir The directory path to add. - * @param recursive Whether to add subdirectories of "dir" as well. - * @param notifyCreate Whether to notify if a file is created in the directory. - * @param notifyDelete Whether to notify if a file is deleted in the directory. - * @param notifyModify Whether to notify if a file has been modified in the directory. - */ - public void register(Path dir, boolean recursive, boolean notifyCreate, boolean notifyDelete, boolean notifyModify) { - if (Objects.isNull(watcher)) { - return; - } - - dir = FileManager.resolve(dir); - if (dir != null && FileEx.create(dir).isDirectory()) { - if (recursive) { - try { - Files.walkFileTree(dir, new SimpleFileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - register(dir, false, notifyCreate, notifyDelete, notifyModify); - return FileVisitResult.CONTINUE; - } - }); - } catch (IOException e) { - } - } else { - WatchKey key = getWatchKey(dir); - if (key == null) { - synchronized (pathMap) { - try { - ArrayList> list = new ArrayList<>(); - if (notifyCreate) { - list.add(StandardWatchEventKinds.ENTRY_CREATE); - } - if (notifyDelete) { - list.add(StandardWatchEventKinds.ENTRY_DELETE); - } - if (notifyModify) { - list.add(StandardWatchEventKinds.ENTRY_MODIFY); - } - Kind[] kinds = list.toArray(new Kind[list.size()]); - key = dir.register(watcher, kinds); - pathMap.put(key, dir); - } catch (UnsupportedOperationException uoe) { - // no feedback necessary - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - } - } - } - } - - /** - * Removes the specified directory path and optional subdirectories from the watcher list. Does nothing if the - * specified directory path is not registered. - */ - public void unregister(Path dir, boolean recursive) { - dir = FileManager.resolve(dir); - if (dir != null) { - if (recursive) { - synchronized (pathMap) { - Iterator iter = pathMap.keySet().iterator(); - while (iter.hasNext()) { - WatchKey key = iter.next(); - Path value = pathMap.get(key); - if (value.startsWith(dir)) { - key.cancel(); - iter.remove(); - } - } - } - } else { - WatchKey key = getWatchKey(dir); - if (key != null) { - synchronized (pathMap) { - key.cancel(); - pathMap.remove(key); - } - } - } - } - } - - /** Returns whether the specified directory path is registered in the watcher list. */ - public boolean isRegistered(Path dir) { - return (getWatchKey(dir) != null); - } - - private WatchKey getWatchKey(Path dir) { - WatchKey retVal = null; - dir = FileManager.resolve(dir); - if (dir != null) { - synchronized (pathMap) { - for (final WatchKey key : pathMap.keySet()) { - Path value = pathMap.get(key); - if (dir.equals(value)) { - retVal = key; - break; - } - } - } - } - return retVal; - } - - private void init() { - } - - private void done() { - thread = null; - } - - private void fireFileWatchEvent(FileWatchEvent event) { - if (event != null) { - for (FileWatchListener l : listeners) { - if (l != null) { - try { - l.fileChanged(event); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - } - } - - // --------------------- Begin Interface Runnable --------------------- - - @Override - public void run() { - init(); - try { - while (thread != null) { - // getting signaled key - WatchKey key; - try { - key = watcher.poll(timeOutMS, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - break; - } - - if (key == null) { - continue; - } - - Path dir = pathMap.get(key); - if (dir == null) { - continue; - } - - for (WatchEvent event : key.pollEvents()) { - WatchEvent.Kind kind = event.kind(); - - FileWatchEvent fwe = null; - if (kind == StandardWatchEventKinds.OVERFLOW) { - // special: does not provide path - // System.out.println("FileWatch event: " + kind.name()); - fwe = new FileWatchEvent(this, null, kind); - } else { - WatchEvent ev = cast(event); - Path name = ev.context(); - Path child = dir.resolve(name); - // System.out.println("FileWatch event: " + kind.name() + " -> " + child); - fwe = new FileWatchEvent(this, child, kind); - } - fireFileWatchEvent(fwe); - } - - boolean valid = key.reset(); - if (!valid) { - synchronized (pathMap) { - pathMap.remove(key); - } - } - } - } finally { - done(); - } - } - - // --------------------- End Interface Runnable --------------------- - - // -------------------------- INNER CLASSES -------------------------- - - /** - * An event that indicates that a content change in one of the registered directories took place. - */ - public static class FileWatchEvent extends EventObject { - private final Path path; - private final WatchEvent.Kind kind; - - public FileWatchEvent(Object source, Path path, WatchEvent.Kind kind) { - super(source); - this.path = path; - this.kind = kind; - } - - /** The full path of the file that has triggered the watcher event. */ - public Path getPath() { - return path; - } - - /** The watch event type. Can be either of the {@link StandardWatchEventKinds}. */ - public WatchEvent.Kind getKind() { - return kind; - } - } - - /** The listener interface for receiving file watch events. */ - public static interface FileWatchListener extends EventListener { - /** - * Invoked when a file watch event is triggered. - * - * @param e The event - */ - void fileChanged(FileWatchEvent e); - } -} diff --git a/src/org/infinity/util/io/StreamUtils.java b/src/org/infinity/util/io/StreamUtils.java index b771501cb..ed6dd5bf6 100644 --- a/src/org/infinity/util/io/StreamUtils.java +++ b/src/org/infinity/util/io/StreamUtils.java @@ -19,9 +19,11 @@ import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import org.infinity.util.Logger; import org.infinity.util.Misc; /** @@ -45,7 +47,7 @@ public static String replaceFileExtension(String fileName, String newExt) { retVal = retVal.substring(0, pos); } } - if (newExt.length() > 0 && newExt.charAt(0) != '.') { + if (!newExt.isEmpty() && newExt.charAt(0) != '.') { retVal += "."; } retVal += newExt; @@ -64,7 +66,7 @@ public static Path replaceFileExtension(Path file, String newExt) { int pos = name.lastIndexOf('.'); if (pos > 0) { // no need to replace if extensions are equal - if (newExt.length() > 0 && newExt.charAt(0) == '.') { + if (!newExt.isEmpty() && newExt.charAt(0) == '.') { if (name.substring(pos).equalsIgnoreCase(newExt)) { return retVal; } @@ -75,7 +77,7 @@ public static Path replaceFileExtension(Path file, String newExt) { } name = name.substring(0, pos); } - if (newExt.length() > 0 && newExt.charAt(0) != '.') { + if (!newExt.isEmpty() && newExt.charAt(0) != '.') { name += "."; } name += newExt; @@ -115,14 +117,10 @@ public static String[] splitFileName(String fileName) { p = temp.lastIndexOf('.'); if (p > 0) { // p == 0 ? extension is file base retVal[1] = temp.substring(0, p); - if (p < temp.length()) { - temp = temp.substring(p); - } else { - temp = ""; - } + temp = temp.substring(p); } // determining file extension - if (temp.length() > 0) { + if (!temp.isEmpty()) { retVal[2] = temp; } } @@ -215,7 +213,7 @@ public static int copyBytes(ByteBuffer src, int srcOffset, ByteBuffer dst, int d bufTmp.limit(bufTmp.position() + maxLength); dst.put(bufTmp); } catch (Throwable t) { - t.printStackTrace(); + Logger.error(t); } finally { src.position(srcPos); dst.position(dstPos); @@ -738,7 +736,7 @@ public static int writeString(OutputStream os, String s, int length, Charset cha byte[] stringBytes = s.getBytes(charset); writeBytes(os, stringBytes); if (length > stringBytes.length) { - byte buffer[] = new byte[length - stringBytes.length]; + byte[] buffer = new byte[length - stringBytes.length]; writeBytes(os, buffer); } return Math.max(length, stringBytes.length); @@ -750,6 +748,7 @@ public static byte[] toArray(ByteBuffer buffer) { try { retVal = buffer.array(); } catch (Throwable t) { + Logger.trace(t); } if (retVal == null || retVal.length != buffer.limit()) { retVal = new byte[buffer.limit()]; @@ -772,20 +771,23 @@ public static byte[] toArray(ByteBuffer buffer) { public static void createZip(Path sourceDir, Path zipFile, boolean includeFolder) throws IOException { try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile))) { Path baseDir = includeFolder ? sourceDir.getParent() : sourceDir; - Files.walk(sourceDir).filter(path -> !FileEx.create(path).isDirectory()).forEach(path -> { - ZipEntry ze = new ZipEntry(baseDir.relativize(path).toString()); - try { - ze.setLastModifiedTime(Files.getLastModifiedTime(path)); - } catch (IOException e) { - } - try { - zos.putNextEntry(ze); - Files.copy(path, zos); - zos.closeEntry(); - } catch (IOException e) { - e.printStackTrace(); - } - }); + try (final Stream stream = Files.walk(sourceDir)) { + stream.filter(path -> !FileEx.create(path).isDirectory()).forEach(path -> { + ZipEntry ze = new ZipEntry(baseDir.relativize(path).toString()); + try { + ze.setLastModifiedTime(Files.getLastModifiedTime(path)); + } catch (IOException e) { + Logger.trace(e); + } + try { + zos.putNextEntry(ze); + Files.copy(path, zos); + zos.closeEntry(); + } catch (IOException e) { + Logger.error(e); + } + }); + } } } } diff --git a/src/org/infinity/util/io/zip/DlcFileAttributeView.java b/src/org/infinity/util/io/zip/DlcFileAttributeView.java index 1e6d347f5..9f7da2c90 100644 --- a/src/org/infinity/util/io/zip/DlcFileAttributeView.java +++ b/src/org/infinity/util/io/zip/DlcFileAttributeView.java @@ -42,6 +42,8 @@ import java.util.LinkedHashMap; import java.util.Map; +import org.infinity.util.Logger; + /** * FileAttributeView implementation for DLC archives in zip format. */ @@ -49,7 +51,7 @@ public class DlcFileAttributeView implements BasicFileAttributeView { protected static final String VIEW_BASIC = "basic"; protected static final String VIEW_ZIP = "zip"; - private enum AttrID { + protected enum AttrID { SIZE, CREATION_TIME, LAST_ACCESS_TIME, LAST_MODIFIED_TIME, IS_DIRECTORY, IS_REGULAR_FILE, IS_SYMBOLIC_LINK, IS_OTHER, FILE_KEY, COMPRESSED_SIZE, CRC, METHOD } @@ -117,6 +119,7 @@ protected void setAttribute(String attribute, Object value) throws IOException { } return; } catch (IllegalArgumentException x) { + Logger.trace(x); } throw new UnsupportedOperationException("'" + attribute + "' is unknown or read-only attribute"); } @@ -129,6 +132,7 @@ protected Map readAttributes(String attributes) throws IOExcepti try { map.put(id.name(), attribute(id, dfas)); } catch (IllegalArgumentException x) { + Logger.trace(x); } } } else { @@ -137,6 +141,7 @@ protected Map readAttributes(String attributes) throws IOExcepti try { map.put(a, attribute(AttrID.valueOf(a), dfas)); } catch (IllegalArgumentException x) { + Logger.trace(x); } } } diff --git a/src/org/infinity/util/io/zip/DlcFileStore.java b/src/org/infinity/util/io/zip/DlcFileStore.java index d539ae896..3c68242fe 100644 --- a/src/org/infinity/util/io/zip/DlcFileStore.java +++ b/src/org/infinity/util/io/zip/DlcFileStore.java @@ -106,16 +106,16 @@ public V getFileStoreAttributeView(Class t @Override public Object getAttribute(String attribute) throws IOException { - if (attribute.equals("totalSpace")) { - return getTotalSpace(); + switch (attribute) { + case "totalSpace": + return getTotalSpace(); + case "usableSpace": + return getUsableSpace(); + case "unallocatedSpace": + return getUnallocatedSpace(); + default: + throw new UnsupportedOperationException("does not support the given attribute"); } - if (attribute.equals("usableSpace")) { - return getUsableSpace(); - } - if (attribute.equals("unallocatedSpace")) { - return getUnallocatedSpace(); - } - throw new UnsupportedOperationException("does not support the given attribute"); } // -------------------------- INNER CLASSES -------------------------- diff --git a/src/org/infinity/util/io/zip/DlcFileSystem.java b/src/org/infinity/util/io/zip/DlcFileSystem.java index aea034c58..990a7ac8e 100644 --- a/src/org/infinity/util/io/zip/DlcFileSystem.java +++ b/src/org/infinity/util/io/zip/DlcFileSystem.java @@ -60,6 +60,8 @@ public class DlcFileSystem extends FileSystem { private static final Set SUPPORTED_FILE_ATTRIBUTE_VIEWS = Collections .unmodifiableSet(new HashSet<>(Arrays.asList(DlcFileAttributeView.VIEW_BASIC, DlcFileAttributeView.VIEW_ZIP))); + final static DirectoryStream.Filter DEFAULT_DIRECTORY_STREAM_FILTER = path -> true; + private static final String GLOB_SYNTAX = "glob"; private static final String REGEX_SYNTAX = "regex"; @@ -168,7 +170,7 @@ public Path getPath(String first, String... more) { StringBuilder sb = new StringBuilder(); sb.append(first); for (String segment : more) { - if (segment.length() > 0) { + if (!segment.isEmpty()) { if (sb.length() > 0) { sb.append('/'); } @@ -183,7 +185,7 @@ public Path getPath(String first, String... more) { @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { int pos = syntaxAndPattern.indexOf(':'); - if (pos <= 0 || pos == syntaxAndPattern.length()) { + if (pos <= 0) { throw new IllegalArgumentException(); } String syntax = syntaxAndPattern.substring(0, pos); @@ -288,10 +290,14 @@ protected Iterator iteratorOf(byte[] path, DirectoryStream.Filter children = folder.getChildren(); - List pathList = new ArrayList<>(); - for (final ZipNode child : children) { - pathList.add(toDlcPath(child.getPath())); + final List children = folder.getChildren(); + final List pathList = new ArrayList<>(children.size()); + final DirectoryStream.Filter pathFilter = (filter != null) ? filter : DEFAULT_DIRECTORY_STREAM_FILTER; + for (final ZipNode node : children) { + final Path p = toDlcPath(node.getPath()); + if (pathFilter.accept(p)) { + pathList.add(p); + } } return Collections.unmodifiableList(pathList).iterator(); } finally { @@ -610,7 +616,7 @@ public void force(boolean metaData) throws IOException { } private void checkOpen() throws IOException { - if (fch == null || !fch.isOpen()) { + if (!fch.isOpen()) { throw new IOException("Channel not open"); } } diff --git a/src/org/infinity/util/io/zip/DlcFileSystemProvider.java b/src/org/infinity/util/io/zip/DlcFileSystemProvider.java index 364ed1419..b44e14d0f 100644 --- a/src/org/infinity/util/io/zip/DlcFileSystemProvider.java +++ b/src/org/infinity/util/io/zip/DlcFileSystemProvider.java @@ -267,7 +267,7 @@ private boolean ensureFile(Path path) { } // Checks that the given file is a UnixPath - protected static final DlcPath toDlcPath(Path path) { + protected static DlcPath toDlcPath(Path path) { if (path == null) { throw new NullPointerException(); } diff --git a/src/org/infinity/util/io/zip/DlcPath.java b/src/org/infinity/util/io/zip/DlcPath.java index e9edb7e95..7193e3af2 100644 --- a/src/org/infinity/util/io/zip/DlcPath.java +++ b/src/org/infinity/util/io/zip/DlcPath.java @@ -69,6 +69,8 @@ import java.util.NoSuchElementException; import java.util.Set; +import org.infinity.util.Logger; + /** * Path implementation for DLC archives in zip format. */ @@ -207,6 +209,7 @@ public boolean startsWith(Path other) { olast--; return (o.path.length == this.path.length) || (o.path[olast] == '/') || (this.path[olast + 1] == '/'); } catch (Exception e) { + Logger.trace(e); } return false; } @@ -241,6 +244,7 @@ public boolean endsWith(Path other) { } return (o.path[olast + 1] == '/') || (last == -1) || (this.path[last] == '/'); } catch (Exception e) { + Logger.trace(e); } return false; } @@ -432,15 +436,12 @@ public int compareTo(Path other) { final DlcPath o = checkPath(other); int len1 = this.path.length; int len2 = o.path.length; - int n = Math.min(len1, len2); - byte v1[] = this.path; - byte v2[] = o.path; int k = 0; while (k < n) { - int c1 = v1[k] & 0xff; - int c2 = v2[k] & 0xff; + int c1 = this.path[k] & 0xff; + int c2 = o.path[k] & 0xff; if (c1 != c2) { return c1 - c2; } @@ -465,7 +466,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return (obj != null) && (obj instanceof DlcPath) && (this.dfs == ((DlcPath) obj).dfs) + return (obj instanceof DlcPath) && (this.dfs == ((DlcPath) obj).dfs) && (compareTo((Path) obj) == 0); } @@ -624,9 +625,6 @@ private byte[] normalize(byte[] path, int off) { // Remove DotSlash(./) and resolve DotDot (..) components private byte[] getResolved() { - if (path.length == 0) { - return path; - } for (byte c : path) { if (c == (byte) '.') { return resolve0(); @@ -692,11 +690,9 @@ protected void createDirectory(FileAttribute... attrs) { } protected InputStream newInputStream(OpenOption... options) throws IOException { - if (options.length > 0) { - for (OpenOption opt : options) { - if (opt != StandardOpenOption.READ) { - throw new UnsupportedOperationException("'" + opt + "' not allowed"); - } + for (OpenOption opt : options) { + if (opt != StandardOpenOption.READ) { + throw new UnsupportedOperationException("'" + opt + "' not allowed"); } } return dfs.newInputStream(getResolvedPath()); diff --git a/src/org/infinity/util/io/zip/ZipBaseHeader.java b/src/org/infinity/util/io/zip/ZipBaseHeader.java index b4580313f..5dfa6f1a7 100644 --- a/src/org/infinity/util/io/zip/ZipBaseHeader.java +++ b/src/org/infinity/util/io/zip/ZipBaseHeader.java @@ -56,32 +56,26 @@ public int compareTo(ZipBaseHeader o) { if (this == o) { return 0; } else if (o != null) { - if (this.offset < o.offset) { - return -1; - } else if (this.offset > o.offset) { - return 1; - } else { - return 0; - } + return Long.compare(this.offset, o.offset); } else { throw new NullPointerException(); } } - protected static final long readFullyAt(SeekableByteChannel ch, byte[] buf, int ofs, long len, long pos) throws IOException { + protected static long readFullyAt(SeekableByteChannel ch, byte[] buf, int ofs, long len, long pos) throws IOException { ByteBuffer bb = ByteBuffer.wrap(buf); bb.position(ofs); bb.limit((int) (ofs + len)); return readFullyAt(ch, bb, pos); } - protected static final long readFullyAt(SeekableByteChannel ch, ByteBuffer bb, long pos) throws IOException { + protected static long readFullyAt(SeekableByteChannel ch, ByteBuffer bb, long pos) throws IOException { synchronized (ch) { return ch.position(pos).read(bb); } } - protected static final void zerror(String msg) { + protected static void zerror(String msg) { throw new ZipError(msg); } diff --git a/src/org/infinity/util/io/zip/ZipCentralHeader.java b/src/org/infinity/util/io/zip/ZipCentralHeader.java index 3dc146caf..c6f185995 100644 --- a/src/org/infinity/util/io/zip/ZipCentralHeader.java +++ b/src/org/infinity/util/io/zip/ZipCentralHeader.java @@ -107,7 +107,7 @@ public int hashCode() { hash = 31 * hash + attribInternal; hash = 31 * hash + Long.hashCode(attribExternal); hash = 31 * hash + Long.hashCode(ofsLocalHeader); - hash = 31 * hash + ((comment == null) ? 0 : comment.hashCode()); + hash = 31 * hash + ((comment == null) ? 0 : Arrays.hashCode(comment)); hash = 31 * hash + ((localHeader == null) ? 0 : localHeader.hashCode()); return hash; } @@ -128,13 +128,7 @@ public int compareTo(ZipBaseHeader o) { if (this == o) { return 0; } else if (o instanceof ZipCentralHeader) { - if (this.ofsLocalHeader < ((ZipCentralHeader) o).ofsLocalHeader) { - return -1; - } else if (this.ofsLocalHeader > ((ZipCentralHeader) o).ofsLocalHeader) { - return 1; - } else { - return 0; - } + return Long.compare(this.ofsLocalHeader, ((ZipCentralHeader) o).ofsLocalHeader); } else if (o != null) { return super.compareTo(o); } else { diff --git a/src/org/infinity/util/io/zip/ZipCoder.java b/src/org/infinity/util/io/zip/ZipCoder.java index 67d944d09..458e50499 100644 --- a/src/org/infinity/util/io/zip/ZipCoder.java +++ b/src/org/infinity/util/io/zip/ZipCoder.java @@ -42,8 +42,11 @@ import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.util.Arrays; +import org.infinity.util.Logger; + /** * Utility class for zipfile name and comment decoding and encoding. */ @@ -103,7 +106,7 @@ byte[] getBytesUTF8(String s) { return getBytes(s); } if (utf8 == null) { - utf8 = new ZipCoder(Charset.forName("UTF-8")); + utf8 = new ZipCoder(StandardCharsets.UTF_8); } return utf8.getBytes(s); } @@ -113,7 +116,7 @@ String toStringUTF8(byte[] ba, int len) { return toString(ba, len); } if (utf8 == null) { - utf8 = new ZipCoder(Charset.forName("UTF-8")); + utf8 = new ZipCoder(StandardCharsets.UTF_8); } return utf8.toString(ba, len); } @@ -122,8 +125,8 @@ boolean isUTF8() { return isutf8; } - private Charset cs; - private boolean isutf8; + private final Charset cs; + private final boolean isutf8; private ZipCoder utf8; private ZipCoder(Charset cs) { @@ -139,7 +142,7 @@ static ZipCoder get(String csn) { try { return new ZipCoder(Charset.forName(csn)); } catch (Throwable t) { - t.printStackTrace(); + Logger.error(t); } return new ZipCoder(Charset.defaultCharset()); } diff --git a/src/org/infinity/util/io/zip/ZipConstants.java b/src/org/infinity/util/io/zip/ZipConstants.java index 041971c11..4b6c2573c 100644 --- a/src/org/infinity/util/io/zip/ZipConstants.java +++ b/src/org/infinity/util/io/zip/ZipConstants.java @@ -177,62 +177,62 @@ class ZipConstants * fields access methods */ /////////////////////////////////////////////////////// - public static final int CH(byte[] b, int n) { return Byte.toUnsignedInt(b[n]); } - public static final int SH(byte[] b, int n) { return Byte.toUnsignedInt(b[n]) | (Byte.toUnsignedInt(b[n + 1]) << 8); } - public static final long LG(byte[] b, int n) { return ((SH(b, n)) | (SH(b, n + 2) << 16)) & 0xffffffffL; } - public static final long LL(byte[] b, int n) { return (LG(b, n)) | (LG(b, n + 4) << 32); } + public static int CH(byte[] b, int n) { return Byte.toUnsignedInt(b[n]); } + public static int SH(byte[] b, int n) { return Byte.toUnsignedInt(b[n]) | (Byte.toUnsignedInt(b[n + 1]) << 8); } + public static long LG(byte[] b, int n) { return ((SH(b, n)) | ((long) SH(b, n + 2) << 16)) & 0xffffffffL; } + public static long LL(byte[] b, int n) { return (LG(b, n)) | (LG(b, n + 4) << 32); } - public static final long GETSIG(byte[] b) { return LG(b, 0); } + public static long GETSIG(byte[] b) { return LG(b, 0); } // local file (LOC) header fields - public static final long LOCSIG(byte[] b) { return LG(b, 0); } // signature - public static final int LOCVER(byte[] b) { return SH(b, 4); } // version needed to extract - public static final int LOCFLG(byte[] b) { return SH(b, 6); } // general purpose bit flags - public static final int LOCHOW(byte[] b) { return SH(b, 8); } // compression method - public static final long LOCTIM(byte[] b) { return LG(b, 10);} // modification time - public static final long LOCCRC(byte[] b) { return LG(b, 14);} // crc of uncompressed data - public static final long LOCSIZ(byte[] b) { return LG(b, 18);} // compressed data size - public static final long LOCLEN(byte[] b) { return LG(b, 22);} // uncompressed data size - public static final int LOCNAM(byte[] b) { return SH(b, 26);} // filename length - public static final int LOCEXT(byte[] b) { return SH(b, 28);} // extra field length + public static long LOCSIG(byte[] b) { return LG(b, 0); } // signature + public static int LOCVER(byte[] b) { return SH(b, 4); } // version needed to extract + public static int LOCFLG(byte[] b) { return SH(b, 6); } // general purpose bit flags + public static int LOCHOW(byte[] b) { return SH(b, 8); } // compression method + public static long LOCTIM(byte[] b) { return LG(b, 10);} // modification time + public static long LOCCRC(byte[] b) { return LG(b, 14);} // crc of uncompressed data + public static long LOCSIZ(byte[] b) { return LG(b, 18);} // compressed data size + public static long LOCLEN(byte[] b) { return LG(b, 22);} // uncompressed data size + public static int LOCNAM(byte[] b) { return SH(b, 26);} // filename length + public static int LOCEXT(byte[] b) { return SH(b, 28);} // extra field length // extra local (EXT) header fields - public static final long EXTCRC(byte[] b) { return LG(b, 4);} // crc of uncompressed data - public static final long EXTSIZ(byte[] b) { return LG(b, 8);} // compressed size - public static final long EXTLEN(byte[] b) { return LG(b, 12);} // uncompressed size + public static long EXTCRC(byte[] b) { return LG(b, 4);} // crc of uncompressed data + public static long EXTSIZ(byte[] b) { return LG(b, 8);} // compressed size + public static long EXTLEN(byte[] b) { return LG(b, 12);} // uncompressed size // end of central directory header (END) fields - public static final int ENDSUB(byte[] b) { return SH(b, 8); } // number of entries on this disk - public static final int ENDTOT(byte[] b) { return SH(b, 10);} // total number of entries - public static final long ENDSIZ(byte[] b) { return LG(b, 12);} // central directory size - public static final long ENDOFF(byte[] b) { return LG(b, 16);} // central directory offset - public static final int ENDCOM(byte[] b) { return SH(b, 20);} // size of zip file comment - public static final int ENDCOM(byte[] b, int off) { return SH(b, off + 20);} + public static int ENDSUB(byte[] b) { return SH(b, 8); } // number of entries on this disk + public static int ENDTOT(byte[] b) { return SH(b, 10);} // total number of entries + public static long ENDSIZ(byte[] b) { return LG(b, 12);} // central directory size + public static long ENDOFF(byte[] b) { return LG(b, 16);} // central directory offset + public static int ENDCOM(byte[] b) { return SH(b, 20);} // size of zip file comment + public static int ENDCOM(byte[] b, int off) { return SH(b, off + 20);} // zip64 end of central directory recoder fields - public static final long ZIP64_ENDTOD(byte[] b) { return LL(b, 24);} // total number of entries on disk - public static final long ZIP64_ENDTOT(byte[] b) { return LL(b, 32);} // total number of entries - public static final long ZIP64_ENDSIZ(byte[] b) { return LL(b, 40);} // central directory size - public static final long ZIP64_ENDOFF(byte[] b) { return LL(b, 48);} // central directory offset - public static final long ZIP64_LOCOFF(byte[] b) { return LL(b, 8);} // zip64 end offset + public static long ZIP64_ENDTOD(byte[] b) { return LL(b, 24);} // total number of entries on disk + public static long ZIP64_ENDTOT(byte[] b) { return LL(b, 32);} // total number of entries + public static long ZIP64_ENDSIZ(byte[] b) { return LL(b, 40);} // central directory size + public static long ZIP64_ENDOFF(byte[] b) { return LL(b, 48);} // central directory offset + public static long ZIP64_LOCOFF(byte[] b) { return LL(b, 8);} // zip64 end offset // central directory header (CEN) fields - public static final long CENSIG(byte[] b, int pos) { return LG(b, pos + 0); } - public static final int CENVEM(byte[] b, int pos) { return SH(b, pos + 4); } - public static final int CENVER(byte[] b, int pos) { return SH(b, pos + 6); } - public static final int CENFLG(byte[] b, int pos) { return SH(b, pos + 8); } - public static final int CENHOW(byte[] b, int pos) { return SH(b, pos + 10);} - public static final long CENTIM(byte[] b, int pos) { return LG(b, pos + 12);} - public static final long CENCRC(byte[] b, int pos) { return LG(b, pos + 16);} - public static final long CENSIZ(byte[] b, int pos) { return LG(b, pos + 20);} - public static final long CENLEN(byte[] b, int pos) { return LG(b, pos + 24);} - public static final int CENNAM(byte[] b, int pos) { return SH(b, pos + 28);} - public static final int CENEXT(byte[] b, int pos) { return SH(b, pos + 30);} - public static final int CENCOM(byte[] b, int pos) { return SH(b, pos + 32);} - public static final int CENDSK(byte[] b, int pos) { return SH(b, pos + 34);} - public static final int CENATT(byte[] b, int pos) { return SH(b, pos + 36);} - public static final long CENATX(byte[] b, int pos) { return LG(b, pos + 38);} - public static final long CENOFF(byte[] b, int pos) { return LG(b, pos + 42);} + public static long CENSIG(byte[] b, int pos) { return LG(b, pos); } + public static int CENVEM(byte[] b, int pos) { return SH(b, pos + 4); } + public static int CENVER(byte[] b, int pos) { return SH(b, pos + 6); } + public static int CENFLG(byte[] b, int pos) { return SH(b, pos + 8); } + public static int CENHOW(byte[] b, int pos) { return SH(b, pos + 10);} + public static long CENTIM(byte[] b, int pos) { return LG(b, pos + 12);} + public static long CENCRC(byte[] b, int pos) { return LG(b, pos + 16);} + public static long CENSIZ(byte[] b, int pos) { return LG(b, pos + 20);} + public static long CENLEN(byte[] b, int pos) { return LG(b, pos + 24);} + public static int CENNAM(byte[] b, int pos) { return SH(b, pos + 28);} + public static int CENEXT(byte[] b, int pos) { return SH(b, pos + 30);} + public static int CENCOM(byte[] b, int pos) { return SH(b, pos + 32);} + public static int CENDSK(byte[] b, int pos) { return SH(b, pos + 34);} + public static int CENATT(byte[] b, int pos) { return SH(b, pos + 36);} + public static long CENATX(byte[] b, int pos) { return LG(b, pos + 38);} + public static long CENOFF(byte[] b, int pos) { return LG(b, pos + 42);} /* The END header is followed by a variable length comment of size < 64k. */ public static final long END_MAXLEN = 0xFFFF + ENDHDR; diff --git a/src/org/infinity/util/io/zip/ZipNode.java b/src/org/infinity/util/io/zip/ZipNode.java index aed832cd1..9db1bdc6b 100644 --- a/src/org/infinity/util/io/zip/ZipNode.java +++ b/src/org/infinity/util/io/zip/ZipNode.java @@ -27,10 +27,10 @@ public class ZipNode { private final List children = new ArrayList<>(); - private ZipCentralHeader header; // only available for non-root nodes - private ZipCentralEndHeader endHeader; // only available for root node - private byte[] name; // last segment of filename from header structure - private ZipNode parent; + private final ZipCentralHeader header; // only available for non-root nodes + private final ZipCentralEndHeader endHeader; // only available for root node + private final byte[] name; // last segment of filename from header structure + private final ZipNode parent; /** * Returns the root of a fully initialized zip file tree based on data retrieved from the specified file. @@ -191,10 +191,10 @@ public String toString() { @Override public int hashCode() { int hash = 7; - hash = 31 * hash + ((children == null) ? 0 : children.hashCode()); + hash = 31 * hash + children.hashCode(); hash = 31 * hash + ((header == null) ? 0 : header.hashCode()); hash = 31 * hash + ((endHeader == null) ? 0 : endHeader.hashCode()); - hash = 31 * hash + ((name == null) ? 0 : name.hashCode()); + hash = 31 * hash + ((name == null) ? 0 : Arrays.hashCode(name)); return hash; } diff --git a/src/org/infinity/util/io/zip/ZipUtils.java b/src/org/infinity/util/io/zip/ZipUtils.java index 0716971dc..a0cc3f3a3 100644 --- a/src/org/infinity/util/io/zip/ZipUtils.java +++ b/src/org/infinity/util/io/zip/ZipUtils.java @@ -50,7 +50,7 @@ class ZipUtils { static { Calendar calBase = Calendar.getInstance(); - calBase.set(1970, 0, 1, 0, 0, 0); + calBase.set(1970, Calendar.JANUARY, 1, 0, 0, 0); TIME_BASE = calBase.getTimeInMillis(); } @@ -135,7 +135,7 @@ public static long javaToDosTime(long time) { if (year < 1980) { return (1 << 21) | (1 << 16); } - return ((year - 1980) << 25) | ((cal.get(Calendar.MONTH) + 1) << 21) | (cal.get(Calendar.DAY_OF_MONTH) << 16) + return ((long) (year - 1980) << 25) | ((cal.get(Calendar.MONTH) + 1) << 21) | (cal.get(Calendar.DAY_OF_MONTH) << 16) | (cal.get(Calendar.HOUR_OF_DAY) << 11) | (cal.get(Calendar.MINUTE) << 5) | (cal.get(Calendar.SECOND) >> 1); // Date d = new Date(time); // int year = d.getYear() + 1900; @@ -149,19 +149,19 @@ public static long javaToDosTime(long time) { // used to adjust values between Windows and java epoch private static final long WINDOWS_EPOCH_IN_MICROSECONDS = -11644473600000000L; - public static final long winToJavaTime(long wtime) { + public static long winToJavaTime(long wtime) { return TimeUnit.MILLISECONDS.convert(wtime / 10 + WINDOWS_EPOCH_IN_MICROSECONDS, TimeUnit.MICROSECONDS); } - public static final long javaToWinTime(long time) { + public static long javaToWinTime(long time) { return (TimeUnit.MICROSECONDS.convert(time, TimeUnit.MILLISECONDS) - WINDOWS_EPOCH_IN_MICROSECONDS) * 10; } - public static final long unixToJavaTime(long utime) { + public static long unixToJavaTime(long utime) { return TimeUnit.MILLISECONDS.convert(utime, TimeUnit.SECONDS); } - public static final long javaToUnixTime(long time) { + public static long javaToUnixTime(long time) { return TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS); } @@ -176,7 +176,7 @@ private static boolean isGlobMeta(char c) { return globMetaChars.indexOf(c) != -1; } - private static char EOL = 0; // TBD + private static final char EOL = 0; // TBD private static char next(String glob, int i) { if (i < glob.length()) { diff --git a/src/org/infinity/util/tuples/Couple.java b/src/org/infinity/util/tuples/Couple.java index b206d6822..be5cb36c1 100644 --- a/src/org/infinity/util/tuples/Couple.java +++ b/src/org/infinity/util/tuples/Couple.java @@ -31,7 +31,7 @@ public static Couple with(A value0, B value1) { /** * Creates a new tuple from the array. The array must contain at least 2 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param arr The array to be used as source for the tuple. * @return A new tuple instance. */ @@ -48,7 +48,7 @@ public static Couple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 2 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -68,7 +68,7 @@ public static Couple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -79,7 +79,7 @@ public static Couple fromIterable(Iterable iterator) { /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/org/infinity/util/tuples/Monuple.java b/src/org/infinity/util/tuples/Monuple.java index 1548976fb..86cfcebf1 100644 --- a/src/org/infinity/util/tuples/Monuple.java +++ b/src/org/infinity/util/tuples/Monuple.java @@ -29,7 +29,7 @@ public static Monuple with(A value0) { /** * Creates a new tuple from the array. The array must contain at least 1 element. * - * @param the tuple element type. + * @param the tuple element type. * @param arr the array to be used as source for the tuple. * @return a new tuple instance. */ @@ -46,7 +46,7 @@ public static Monuple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 1 element. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -54,7 +54,7 @@ public static Monuple fromCollection(Collection col) { if (col == null) { throw new IllegalArgumentException("Collection cannot be null"); } - if (col.size() < SIZE) { + if (col.isEmpty()) { throw new IllegalArgumentException("Collection must contain at least 1 element"); } Iterator iter = col.iterator(); @@ -64,7 +64,7 @@ public static Monuple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -75,7 +75,7 @@ public static Monuple fromIterable(Iterable iterator) { /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/org/infinity/util/tuples/Quadruple.java b/src/org/infinity/util/tuples/Quadruple.java index 48671d3da..a0edbd733 100644 --- a/src/org/infinity/util/tuples/Quadruple.java +++ b/src/org/infinity/util/tuples/Quadruple.java @@ -22,11 +22,14 @@ public class Quadruple extends Tuple /** * Creates a new tuple instance with the specified elements. * - * @param the tuple element type. + * @param the first tuple element type. + * @param the second tuple element type. + * @param the third tuple element type. + * @param the fourth tuple element type. * @param value0 The first element to store in the tuple. - * @param value2 The second element to store in the tuple. - * @param value3 The third element to store in the tuple. - * @param value4 The fourth element to store in the tuple. + * @param value1 The second element to store in the tuple. + * @param value2 The third element to store in the tuple. + * @param value3 The fourth element to store in the tuple. * @return A new tuple instance. */ public static Quadruple with(A value0, B value1, C value2, D value3) { @@ -36,7 +39,7 @@ public static Quadruple with(A value0, B value1, C valu /** * Creates a new tuple from the array. The array must contain at least 4 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param arr The array to be used as source for the tuple. * @return A new tuple instance. */ @@ -53,7 +56,7 @@ public static Quadruple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 4 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -75,7 +78,7 @@ public static Quadruple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -86,7 +89,7 @@ public static Quadruple fromIterable(Iterable iterator) { /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/org/infinity/util/tuples/Quintuple.java b/src/org/infinity/util/tuples/Quintuple.java index 8322ca23f..e0128cb8d 100644 --- a/src/org/infinity/util/tuples/Quintuple.java +++ b/src/org/infinity/util/tuples/Quintuple.java @@ -23,11 +23,16 @@ public class Quintuple extends Tuple /** * Creates a new tuple instance with the specified elements. * - * @param the tuple element type. + * @param the first tuple element type. + * @param the second tuple element type. + * @param the third tuple element type. + * @param the fourth tuple element type. + * @param the fifth tuple element type. * @param value0 The first element to store in the tuple. - * @param value2 The second element to store in the tuple. - * @param value3 The third element to store in the tuple. - * @param value4 The fourth element to store in the tuple. + * @param value1 The second element to store in the tuple. + * @param value2 The third element to store in the tuple. + * @param value3 The fourth element to store in the tuple. + * @param value4 The fifth element to store in the tuple. * @return A new tuple instance. */ public static Quintuple with(A value0, B value1, C value2, D value3, E value4) { @@ -37,7 +42,7 @@ public static Quintuple with(A value0, B value1, /** * Creates a new tuple from the array. The array must contain at least 5 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param arr The array to be used as source for the tuple. * @return A new tuple instance. */ @@ -54,7 +59,7 @@ public static Quintuple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 5 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -77,7 +82,7 @@ public static Quintuple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -88,7 +93,7 @@ public static Quintuple fromIterable(Iterable iterator) { /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/org/infinity/util/tuples/Sextuple.java b/src/org/infinity/util/tuples/Sextuple.java index a675fb438..7f46f951e 100644 --- a/src/org/infinity/util/tuples/Sextuple.java +++ b/src/org/infinity/util/tuples/Sextuple.java @@ -24,11 +24,18 @@ public class Sextuple extends Tuple /** * Creates a new tuple instance with the specified elements. * - * @param the tuple element type. + * @param the first tuple element type. + * @param the second tuple element type. + * @param the third tuple element type. + * @param the fourth tuple element type. + * @param the fifth tuple element type. + * @param the sixth tuple element type. * @param value0 The first element to store in the tuple. - * @param value2 The second element to store in the tuple. - * @param value3 The third element to store in the tuple. - * @param value4 The fourth element to store in the tuple. + * @param value1 The second element to store in the tuple. + * @param value2 The third element to store in the tuple. + * @param value3 The fourth element to store in the tuple. + * @param value4 The fifth element to store in the tuple. + * @param value5 The sixth element to store in the tuple. * @return A new tuple instance. */ public static Sextuple with(A value0, B value1, C value2, D value3, E value4, @@ -39,7 +46,7 @@ public static Sextuple with(A value0, B val /** * Creates a new tuple from the array. The array must contain at least 6 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param arr The array to be used as source for the tuple. * @return A new tuple instance. */ @@ -56,7 +63,7 @@ public static Sextuple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 6 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -80,7 +87,7 @@ public static Sextuple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -91,7 +98,7 @@ public static Sextuple fromIterable(Iterable iterator) /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/org/infinity/util/tuples/Triple.java b/src/org/infinity/util/tuples/Triple.java index 81e15f3c7..86208ad70 100644 --- a/src/org/infinity/util/tuples/Triple.java +++ b/src/org/infinity/util/tuples/Triple.java @@ -20,10 +20,12 @@ public class Triple extends Tuple implements TupleValue0, TupleValue /** * Creates a new tuple instance with the specified elements. * - * @param the tuple element type. + * @param the first tuple element type. + * @param the second tuple element type. + * @param the third tuple element type. * @param value0 The first element to store in the tuple. - * @param value2 The second element to store in the tuple. - * @param value3 The third element to store in the tuple. + * @param value1 The second element to store in the tuple. + * @param value2 The third element to store in the tuple. * @return A new tuple instance. */ public static Triple with(A value0, B value1, C value2) { @@ -33,7 +35,7 @@ public static Triple with(A value0, B value1, C value2) { /** * Creates a new tuple from the array. The array must contain at least 3 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param arr The array to be used as source for the tuple. * @return A new tuple instance. */ @@ -50,7 +52,7 @@ public static Triple fromArray(T[] arr) { /** * Creates a new tuple from the collection. The collection must contain at least 3 elements. * - * @param the tuple element type. + * @param the tuple element type. * @param col the collection to be used as source for the tuple. * @return a new tuple instance. */ @@ -71,7 +73,7 @@ public static Triple fromCollection(Collection col) { /** * Creates a new tuple from the {@code Iterable} object. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @return a new tuple instance. */ @@ -82,7 +84,7 @@ public static Triple fromIterable(Iterable iterator) { /** * Creates a new tuple from the {@code Iterable} object, starting the specified index. * - * @param the tuple element type. + * @param the tuple element type. * @param iterator the {@code Iterable} object to be used as source for the tuple. * @param index start index in {@code Iterable} object. * @return A new tuple instance. diff --git a/src/tinylog.properties b/src/tinylog.properties new file mode 100644 index 000000000..5ebcecb2c --- /dev/null +++ b/src/tinylog.properties @@ -0,0 +1,5 @@ +writer = console +writer.level = trace +writer.format = {level}: {message} +writer.stream = err@WARN +writingthread = true