From 415048d61efd0f850d54b279d467415cb6450d9c Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Wed, 1 Jul 2020 10:05:05 +0200 Subject: [PATCH 01/14] Cosmetic --- src/org/infinity/util/Platform.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/org/infinity/util/Platform.java b/src/org/infinity/util/Platform.java index 73611d0c1..1921dfc96 100644 --- a/src/org/infinity/util/Platform.java +++ b/src/org/infinity/util/Platform.java @@ -5,8 +5,7 @@ package org.infinity.util; /** - * This class can be used to determine the operating system where this Java application is running. - * Determines + * This class can be used to determine the operating system where this Java application is running. */ public class Platform { From cc002350cabe75e39e55d948a183ef59cad7b08e Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Wed, 1 Jul 2020 10:06:02 +0200 Subject: [PATCH 02/14] Properly overwrite transparent pixels in worldmap viewer --- src/org/infinity/resource/wmp/ViewerMap.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/org/infinity/resource/wmp/ViewerMap.java b/src/org/infinity/resource/wmp/ViewerMap.java index 2b4e7e372..836134c74 100644 --- a/src/org/infinity/resource/wmp/ViewerMap.java +++ b/src/org/infinity/resource/wmp/ViewerMap.java @@ -9,6 +9,7 @@ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; +import java.awt.Composite; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.Image; @@ -588,7 +589,10 @@ private void resetMap() { Graphics2D g = ((BufferedImage)rcMap.getImage()).createGraphics(); try { + Composite comp = g.getComposite(); + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC)); g.drawImage(mapOrig, 0, 0, null); + g.setComposite(comp); } finally { g.dispose(); g = null; From 8c236208a2fed1bd302db14668f9d382f7e6bf41 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Wed, 19 Aug 2020 10:10:08 +0200 Subject: [PATCH 03/14] Fix null pointer issues --- src/org/infinity/datatype/ResourceBitmap.java | 4 ++-- src/org/infinity/util/Misc.java | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/org/infinity/datatype/ResourceBitmap.java b/src/org/infinity/datatype/ResourceBitmap.java index 0278e64aa..71d8f2dc7 100644 --- a/src/org/infinity/datatype/ResourceBitmap.java +++ b/src/org/infinity/datatype/ResourceBitmap.java @@ -375,13 +375,13 @@ public String toString() @Override public boolean equals(Object o) { - return desc.equalsIgnoreCase(o.toString()); + return desc.equalsIgnoreCase(Misc.safeToString(o)); } @Override public int compareTo(RefEntry o) { - return desc.compareToIgnoreCase(o.toString()); + return desc.compareToIgnoreCase(Misc.safeToString(o)); } public boolean isResource() { return (entry != null); } diff --git a/src/org/infinity/util/Misc.java b/src/org/infinity/util/Misc.java index 5a9392370..b4af02055 100644 --- a/src/org/infinity/util/Misc.java +++ b/src/org/infinity/util/Misc.java @@ -531,6 +531,15 @@ public static String trim(String s, char[] trimChars) return s; } + /** + * Returns a string representation of the specified object. + * Returns an empty string if the specified object is {@code null}. + */ + public static String safeToString(Object o) + { + return (o != null) ? o.toString() : ""; + } + // Contains static functions only private Misc() {} } From 0c3edd1bdb7cad3022f2eff0352de641cce7fb84 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Wed, 19 Aug 2020 10:11:03 +0200 Subject: [PATCH 04/14] Fix missing update event in SimpleListModel --- src/org/infinity/util/SimpleListModel.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/org/infinity/util/SimpleListModel.java b/src/org/infinity/util/SimpleListModel.java index 7e9bdd10d..cf0ad2ec9 100644 --- a/src/org/infinity/util/SimpleListModel.java +++ b/src/org/infinity/util/SimpleListModel.java @@ -212,6 +212,7 @@ public void setElementAt(E item, int index) public void removeElementAt(int index) { delegate.removeElementAt(index); + fireIntervalRemoved(this, index, index); } /** Inserts the specified object as a component in this list at the specified {@code index}. */ From b9e2d8028c213c62200aeb9d02011d2e67d13dec Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Wed, 19 Aug 2020 10:12:46 +0200 Subject: [PATCH 05/14] Add filter feature to listbox datatypes for structured resources --- src/org/infinity/gui/TextListPanel.java | 214 +++++- src/org/infinity/icon/Filter16.png | Bin 0 -> 379 bytes src/org/infinity/util/FilteredListModel.java | 701 +++++++++++++++++++ 3 files changed, 883 insertions(+), 32 deletions(-) create mode 100644 src/org/infinity/icon/Filter16.png create mode 100644 src/org/infinity/util/FilteredListModel.java diff --git a/src/org/infinity/gui/TextListPanel.java b/src/org/infinity/gui/TextListPanel.java index 68d46cca6..f9f12d4b4 100644 --- a/src/org/infinity/gui/TextListPanel.java +++ b/src/org/infinity/gui/TextListPanel.java @@ -1,36 +1,53 @@ // Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 - 2005 Jon Olav Hauglid +// Copyright (C) 2001 - 2020 Jon Olav Hauglid // See LICENSE.txt for license information package org.infinity.gui; import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.util.Collections; import java.util.List; import java.util.Locale; import javax.swing.BorderFactory; +import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; +import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; +import javax.swing.JToggleButton; import javax.swing.ListModel; import javax.swing.ListSelectionModel; +import javax.swing.UIManager; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import org.infinity.NearInfinity; +import org.infinity.icon.Icons; +import org.infinity.util.FilteredListModel; import org.infinity.util.Misc; -import org.infinity.util.SimpleListModel; -public final class TextListPanel extends JPanel implements DocumentListener, ListSelectionListener +public final class TextListPanel extends JPanel implements DocumentListener, ListSelectionListener, ActionListener, ChangeListener { + private static boolean filterEnabled = false; + private boolean sortValues = true; - private final SimpleListModel listmodel = new SimpleListModel<>(); - private final JList list; - private final JTextField tfield = new JTextField(10); + private final FilteredListModel listmodel = new FilteredListModel<>(filterEnabled); + private final JList list = new JList<>(); + private final JTextField tfield = new JTextField(); + private final JToggleButton tbFilter = new JToggleButton(Icons.getIcon("Filter16.png"), filterEnabled); public TextListPanel(List values) { @@ -39,18 +56,35 @@ public TextListPanel(List values) public TextListPanel(List values, boolean sortValues) { + super(new BorderLayout()); this.sortValues = sortValues; setValues(values); - list = new JList<>(listmodel); + list.setModel(listmodel); list.setSelectedIndex(0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(this); list.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); + listmodel.addFilterChangeListener(this); tfield.getDocument().addDocumentListener(this); - setLayout(new BorderLayout()); - add(tfield, BorderLayout.NORTH); + tbFilter.setToolTipText("Toggle filtering on or off"); + tbFilter.addActionListener(this); + // Horizontal margins are too wasteful on default l&f + Insets margin = tbFilter.getMargin(); + margin.left = Math.min(4, margin.left); + margin.right = Math.min(4, margin.right); + margin.top = Math.min(4, margin.top); + margin.bottom = Math.min(4, margin.bottom); + tbFilter.setMargin(margin); + + JPanel pInput = new JPanel(new BorderLayout()); + pInput.add(tfield, BorderLayout.CENTER); + pInput.add(tbFilter, BorderLayout.EAST); + + add(pInput, BorderLayout.NORTH); add(new JScrollPane(list), BorderLayout.CENTER); + ensurePreferredComponentWidth(list, true); + ensurePreferredComponentWidth(tfield, false); } // --------------------- Begin Interface DocumentListener --------------------- @@ -58,15 +92,23 @@ public TextListPanel(List values, boolean sortValues) @Override public void insertUpdate(DocumentEvent event) { - if (tfield.hasFocus()) - selectClosest(tfield.getText()); + if (tfield.hasFocus()) { + if (!filterEnabled) { + selectClosest(tfield.getText()); + } + listmodel.setPattern(tfield.getText()); + } } @Override public void removeUpdate(DocumentEvent event) { - if (tfield.hasFocus()) - selectClosest(tfield.getText()); + if (tfield.hasFocus()) { + if (!filterEnabled) { + selectClosest(tfield.getText()); + } + listmodel.setPattern(tfield.getText()); + } } @Override @@ -76,19 +118,67 @@ public void changedUpdate(DocumentEvent event) // --------------------- End Interface DocumentListener --------------------- - // --------------------- Begin Interface ListSelectionListener --------------------- @Override public void valueChanged(ListSelectionEvent event) { if (list.hasFocus() && list.getSelectedValue() != null) { - tfield.setText(list.getSelectedValue().toString()); + if (!tfield.getText().equals(list.getSelectedValue().toString())) { + tfield.setText(list.getSelectedValue().toString()); + listmodel.setPattern(tfield.getText()); + } } } // --------------------- End Interface ListSelectionListener --------------------- +// --------------------- Begin Interface ChangeListener --------------------- + + @Override + public void stateChanged(ChangeEvent e) + { + // fixes issues with scrollbar visibility and visibility of selected entry + calculatePreferredComponentHeight(list); + } + +// --------------------- End Interface ChangeListener --------------------- + +// --------------------- Begin Interface ActionListener --------------------- + + @Override + public void actionPerformed(ActionEvent e) + { + if (e.getSource() == tbFilter) { + filterEnabled = tbFilter.isSelected(); + + if (filterEnabled) { + listmodel.setPattern(tfield.getText()); + } + listmodel.setFiltered(filterEnabled); + + ensurePreferredComponentWidth(list, true); + ensurePreferredComponentWidth(tfield, false); + + int idx = list.getSelectedIndex(); + E item = null; + try { + item = listmodel.get(idx); + } catch (Exception ex) { + } + if (item == null || !item.toString().equals(tfield.getText())) { + selectClosest(tfield.getText()); + idx = list.getSelectedIndex(); + } + + if (idx >= 0) { + ensureIndexIsVisible(idx); + } + } + } + +// --------------------- End Interface ActionListener --------------------- + @Override public synchronized void addMouseListener(MouseListener listener) { @@ -101,6 +191,7 @@ public void setEnabled(boolean enabled) super.setEnabled(enabled); list.setEnabled(enabled); tfield.setEditable(enabled); + tbFilter.setEnabled(enabled); } public void addListSelectionListener(ListSelectionListener listener) @@ -138,12 +229,14 @@ public void setSelectedIndex(int index) list.setSelectedIndex(index); list.ensureIndexIsVisible(index); tfield.setText(list.getSelectedValue().toString()); + listmodel.setPattern(list.getSelectedValue().toString()); } public void setSelectedValue(E value, boolean shouldScroll) { list.setSelectedValue(value, shouldScroll); tfield.setText(value.toString()); + listmodel.setPattern(value.toString()); } public void setValues(List values) @@ -151,10 +244,8 @@ public void setValues(List values) if (this.sortValues) { Collections.sort(values, Misc.getIgnoreCaseComparator()); } - listmodel.clear(); - for (int i = 0; i < values.size(); i++) { - listmodel.addElement(values.get(i)); - } + listmodel.baseClear(); + listmodel.baseAddAll(values); tfield.setText(""); if (list != null) { list.setSelectedIndex(0); @@ -162,22 +253,81 @@ public void setValues(List values) } } - private void selectClosest(String text) + /** + * Selects the first list item starting with the specified text. + * Returns the index of the selected item or -1 if not available. + */ + private int selectClosest(String text) { - int selected = 0; - if (!text.isEmpty()) { - text = text.toUpperCase(Locale.ENGLISH); - for (int size = listmodel.getSize(); selected < size; selected++) { - final String s = listmodel.getElementAt(selected).toString().toUpperCase(Locale.ENGLISH); - if (s.startsWith(text)) { - break; - } + int retVal = -1; + if (!text.isEmpty() && listmodel.getSize() > 0) { + final String pattern = text.toUpperCase(Locale.ENGLISH); + E item = listmodel + .elements() + .stream() + .filter(f -> f.toString().toUpperCase(Locale.ENGLISH).startsWith(pattern)) + .findFirst() + .orElse(listmodel.firstElement()); + retVal = listmodel.indexOf(item); + if (retVal >= 0) { + list.setSelectedIndex(retVal); + list.ensureIndexIsVisible(retVal); } } - if (selected < listmodel.getSize()) { - list.setSelectedIndex(selected); - list.ensureIndexIsVisible(selected); + return retVal; + } + + /** Recalculates preferred control width enough to fit all list items horizontally. */ + private void ensurePreferredComponentWidth(JComponent c, boolean includeScrollBar) + { + if (c == null) + return; + + final Graphics g = c.getGraphics() != null ? c.getGraphics() : NearInfinity.getInstance().getGraphics(); + final FontMetrics fm = c.getFontMetrics(c.getFont()); + if (fm == null) + return; + + final E item = listmodel.baseElements() + .stream() + .max((e1, e2) -> { + double w1 = fm.getStringBounds(e1.toString(), g).getWidth(); + double w2 = fm.getStringBounds(e2.toString(), g).getWidth(); + return (int)(w1 - w2); + }) + .get(); + if (item != null) { + int cw = (int)fm.getStringBounds(item.toString(), g).getWidth(); + cw += c.getInsets().left; + cw += c.getInsets().right; + if (includeScrollBar) { + int sbWidth = 0; + try { + sbWidth = ((Integer)UIManager.get("ScrollBar.width")).intValue(); + } catch (Exception ex) { + // not all l&f styles provide UIManager value + sbWidth = (new JScrollBar(JScrollBar.VERTICAL)).getWidth(); + } + cw += sbWidth; + } + Dimension d = c.getPreferredSize(); + d.width = cw; + c.setPreferredSize(d); + c.invalidate(); } } -} + /** Enforces recalculation of preferred control height. */ + private void calculatePreferredComponentHeight(JComponent c) + { + if (c == null) + return; + + int width = c.getPreferredSize().width; + c.setPreferredSize(null); + Dimension d = c.getPreferredSize(); + d.width = width; + c.setPreferredSize(d); + c.invalidate(); + } +} diff --git a/src/org/infinity/icon/Filter16.png b/src/org/infinity/icon/Filter16.png new file mode 100644 index 0000000000000000000000000000000000000000..68b9d0d89d5d3466f578312649a626aa930a1c82 GIT binary patch literal 379 zcmV->0fhdEP)K_yZ(k z$m|a&xMV6gm?@j2P{d8|bgQ^_OqK+i^&F&UuD#SiU$`N6-}~Hq-(46Kw$hGmaxxfN zvFBeOtP=nLjt};X@3-0f{{+pQoqpe}oXz!mGYMPm!DKL0Czlu2-Cm!b*N&k9R7^1Fg zYZF(^Yk($1U#H`=nt!G2gNRg`rYeqOMMSEtuD9u(bIx@?+SJ3AVw?WP<>RuSy#t_& ZegLZ*f%+bFk>~&b002ovPDHLkV1lf9p#%T` literal 0 HcmV?d00001 diff --git a/src/org/infinity/util/FilteredListModel.java b/src/org/infinity/util/FilteredListModel.java new file mode 100644 index 000000000..ed1b29a80 --- /dev/null +++ b/src/org/infinity/util/FilteredListModel.java @@ -0,0 +1,701 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 - 2020 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Vector; + +import javax.swing.AbstractListModel; +import javax.swing.DefaultListModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +/** + * Definition of a list model that filters a collection of items based on a search pattern. + * Filtering can be enabled and disabled. The model behaves like the {@link DefaultListModel} + * if filtering is disabled. + */ +public class FilteredListModel extends AbstractListModel +{ + private final Vector list = new Vector(); + private final Vector filteredList = new Vector(); + private final ArrayList listeners = new ArrayList<>(); + + private boolean filtered; + private String pattern; + + /** Creates a new FilteredListModel instance with filtering initially disabled. */ + public FilteredListModel() + { + this(false); + } + + /** Creates a new FilteredListModel instance with filtering set to the specified parameter. */ + public FilteredListModel(boolean filtered) + { + super(); + this.filtered = filtered; + this.pattern = ""; + } + + /** Creates a new FilteredListModel instance with the specified reference items and filtering initially disabled. */ + public FilteredListModel(E[] items) + { + this(items, false); + } + + /** Creates a new FilteredListModel instance with the specified reference items and filtering set to the specified parameter. */ + public FilteredListModel(E[] items, boolean filtered) + { + super(); + this.filtered = filtered; + this.pattern = ""; + this.baseAddAll(items); + } + + /** Creates a new FilteredListModel instance with the specified reference items and filtering initially disabled. */ + public FilteredListModel(Collection items) + { + this(items, false); + } + + /** Creates a new FilteredListModel instance with the specified reference items and filtering set to the specified parameter. */ + public FilteredListModel(Collection items, boolean filtered) + { + super(); + this.filtered = filtered; + this.pattern = ""; + this.baseAddAll(items); + } + + /** + * Adds the specified ChangeListener to the listener list. + * A change listener is notified whenever the content of the filter list is changed. + */ + public void addFilterChangeListener(ChangeListener listener) + { + if (listener != null) { + listeners.add(listener); + } + } + + /** Returns an array of all the change listeners registered to this instance. */ + public ChangeListener[] getFilterChangeListeners() + { + return listeners.toArray(new ChangeListener[listeners.size()]); + } + + /** Removes all instances of the specified ChangeListener from the listener list. */ + public void removeFilterChangeListener(ChangeListener listener) + { + if (listener != null) { + while (listeners.remove(listener)) ; + } + } + + /** Called one per successful filter update. */ + protected void fireFilterChange() + { + ChangeEvent e = null; + if (!listeners.isEmpty()) { + e = new ChangeEvent(this); + } + + for (int i = 0, cnt = listeners.size(); i < cnt; i++) { + ChangeListener l = listeners.get(i); + l.stateChanged(e); + } + } + + /** + * Returns the current search pattern. + * @return search pattern as string. + */ + public String getPattern() + { + return pattern; + } + + /** + * Specifies the current search pattern. Empty string indicates "match all". + * The pattern is only regarded when filter is active. + * @param pattern The search pattern as string. + */ + public void setPattern(String pattern) + { + updateFilter(this.filtered, pattern, false); + } + + /** + * Returns whether the item list is filtered by search pattern. + * @return whether filtering is enabled. + */ + public boolean isFiltered() + { + return filtered; + } + + /** + * Specifies whether to filter the item list. + * @param filtered Set to {@code true} to filter list items by the current search pattern. + * Set to {@code false} to output unfiltered list. + */ + public void setFiltered(boolean filtered) + { + updateFilter(filtered, this.pattern, false); + } + + /** Returns an unmodifiable collection of the components of the reference list. */ + public Collection baseElements() + { + return Collections.unmodifiableCollection(list); + } + + /** Returns the element at the specified position in the reference list. */ + public E baseGet(int index) + { + return list.get(index); + } + + /** Replaces the element at the specified position in the reference list with the specified element. */ + public E baseSet(int index, E newItem) + { + E retVal = list.set(index, newItem); + if (retVal != newItem) + updateFilter(); + return retVal; + } + + /** Appends the specified element to the end of the reference list. */ + public boolean baseAdd(E item) + { + boolean retVal = list.add(item); + if (retVal) + updateFilter(); + return retVal; + } + + /** Inserts the specified element at the specified position in the reference list. */ + public void baseAdd(int index, E item) + { + list.add(index, item); + updateFilter(); + } + + /** Appends all of the elements in the specified Array to the end of this list. */ + public boolean baseAddAll(E[] items) + { + return baseAddAll(list.size(), Arrays.asList(items)); + } + + /** Inserts all of the elements in the specified Array into the reference list at the specified position. */ + public boolean baseAddAll(int index, E[] items) + { + return baseAddAll(index, Arrays.asList(items)); + } + + /** + * Appends all of the elements in the specified Collection to the end of the reference list, + * in the order that they are returned by the specified Collection's Iterator. + */ + public boolean baseAddAll(Collection coll) + { + return baseAddAll(list.size(), coll); + } + + /** Inserts all of the elements in the specified Collection into the reference list at the specified position. */ + public boolean baseAddAll(int index, Collection coll) + { + boolean retVal = list.addAll(index, coll); + if (retVal) + updateFilter(); + return retVal; + } + + /** Removes the element at the specified position in the reference list. */ + public E baseRemove(int index) + { + E retVal = list.remove(index); + updateFilter(); + return retVal; + } + + /** Removes the first occurrence of the specified element in the reference list. */ + public boolean baseRemove(E item) + { + boolean retVal = list.remove(item); + if (retVal) + updateFilter(); + return retVal; + } + + /** Removes from the reference list all of its elements that are contained in the specified Collection. */ + public boolean baseRemoveAll(Collection c) + { + boolean retVal = list.removeAll(c); + if (retVal) + updateFilter(); + return retVal; + } + + /** Retains only the elements in the reference list that are contained in the specified Collection. */ + public boolean baseRetainAll(Collection c) + { + boolean retVal = list.retainAll(c); + if (retVal) + updateFilter(); + return retVal; + } + + /** Removes all of the elements from the reference list. */ + public void baseClear() + { + if (!list.isEmpty()) { + list.clear(); + updateFilter(); + } + } + + /** Deletes the elements at the specified range of indexes from the reference llist. The removal is inclusive. */ + public void baseRemoveRange(int fromIndex, int toIndex) + { + if (fromIndex > toIndex) { + throw new IllegalArgumentException("fromIndex must be <= toIndex"); + } + boolean modified = false; + for(int i = toIndex; i >= fromIndex; i--) { + list.removeElementAt(i); + modified = true; + } + if (modified) + updateFilter(); + } + + @Override + public int getSize() + { + return filteredList.size(); + } + + @Override + public E getElementAt(int index) + { + return filteredList.get(index); + } + + @Override + public String toString() + { + return filteredList.toString(); + } + + @Override + public boolean equals(Object o) + { + return filteredList.equals(o); + } + + @Override + public int hashCode() + { + return filteredList.hashCode(); + } + + /** Returns an unmodifiable collection of the components of this list. */ + public Collection elements() + { + return Collections.unmodifiableCollection(filteredList); + } + + /** Returns {@code true} if this list contains the specified element. */ + public boolean contains(E item) + { + return filteredList.contains(item); + } + + /** Returns true if this list contains all of the elements in the specified Collection. */ + public boolean containsAll(Collection c) + { + return filteredList.containsAll(c); + } + + /** + * Returns the index of the first occurrence of the specified element in this list, + * or -1 if this list does not contain the element. + */ + public int indexOf(E item) + { + return filteredList.indexOf(item); + } + + /** + * Returns the index of the first occurrence of the specified element in this list, + * searching forwards from {@code index}, or returns -1 if the element is not found. + */ + public int indexOf(E item, int index) + { + return filteredList.indexOf(item, index); + } + + /** + * Returns the index of the last occurrence of the specified element in this list, + * or -1 if this list does not contain the element. + */ + public int lastIndexOf(E item) + { + return filteredList.lastIndexOf(item); + } + + /** + * Returns the index of the last occurrence of the specified element in this list, + * searching backwards from {@code index}, or returns -1 if the element is not found. + */ + public int lastIndexOf(E item, int index) + { + return filteredList.lastIndexOf(item, index); + } + + /** Returns the component at the specified index. */ + public E elementAt(int index) + { + return filteredList.elementAt(index); + } + + /** Returns the first component (the item at index {@code 0}) of this list. */ + public E firstElement() + { + return filteredList.firstElement(); + } + + /** Returns the last component of the list. */ + public E lastElement() + { + return filteredList.lastElement(); + } + + /** + * Sets the component at the specified {@code index} of this list to be the specified object. + * The previous component at that position is discarded. + */ + public void setElementAt(E item, int index) + { + filteredList.setElementAt(item, index); + fireContentsChanged(this, index, index); + } + + /** Deletes the component at the specified index. */ + public void removeElementAt(int index) + { + filteredList.removeElementAt(index); + fireIntervalRemoved(this, index, index); + } + + /** Inserts the specified object as a component in this list at the specified {@code index}. */ + public void insertElementAt(E item, int index) + { + filteredList.insertElementAt(item, index); + fireIntervalAdded(this, index, index); + } + + /** Adds the specified component to the end of this list, increasing its size by one. */ + public void addElement(E item) + { + int index = filteredList.size(); + filteredList.addElement(item); + fireIntervalAdded(this, index, index); + } + + /** Removes the first (lowest-indexed) occurrence of the argument from this list. */ + public boolean removeElement(E item) + { + int index = filteredList.indexOf(item); + boolean ret = (index >= 0); + if (index >= 0) { + filteredList.removeElementAt(index); + fireIntervalRemoved(this, index, index); + } + return ret; + } + + /** Removes all components from this list and sets its size to zero. */ + public void removeAllElements() + { + int index1 = filteredList.size() - 1; + filteredList.removeAllElements(); + if (index1 > 0) { + fireIntervalRemoved(this, 0, index1); + } + } + + /** Returns an array containing all of the elements in this list in the correct order. */ + public Object[] toArray() + { + return filteredList.toArray(); + } + + /** Returns the element at the specified position in this list. */ + public E get(int index) + { + return filteredList.get(index); + } + + /** Replaces the element at the specified position in this list with the specified element. */ + public E set(int index, E newItem) + { + E retVal = filteredList.set(index, newItem); + if (retVal != newItem) + fireContentsChanged(this, index, index); + return retVal; + } + + /** Appends the specified element to the end of this list. */ + public boolean add(E item) + { + int index = filteredList.size(); + boolean retVal = filteredList.add(item); + fireIntervalAdded(this, index, index); + return retVal; + } + + /** Inserts the specified element at the specified position in this list. */ + public void add(int index, E item) + { + filteredList.add(index, item); + fireIntervalAdded(this, index, index); + } + + /** + * Appends all of the elements in the specified Array to the end of this list. + */ + public boolean addAll(E[] items) + { + return addAll(filteredList.size(), Arrays.asList(items)); + } + + /** + * Inserts all of the elements in the specified Array into this list + * at the specified position. + */ + public boolean addAll(int index, E[] items) + { + return addAll(index, Arrays.asList(items)); + } + + /** + * Appends all of the elements in the specified Collection to the end of this list, + * in the order that they are returned by the specified Collection's Iterator. + */ + public boolean addAll(Collection coll) + { + return addAll(filteredList.size(), coll); + } + + /** + * Inserts all of the elements in the specified Collection into this list + * at the specified position. + */ + public boolean addAll(int index, Collection coll) + { + int index0 = index; + int index1 = index0 + coll.size() - 1; + filteredList.addAll(index, coll); + if (index1 >= index0) + fireIntervalAdded(this, index0, index1); + return (index1 >= index0); + } + + /** Removes the element at the specified position in this list. */ + public E remove(int index) + { + E retVal = filteredList.remove(index); + fireIntervalRemoved(this, index, index); + return retVal; + } + + /** Removes the first occurrence of the specified element in this list. */ + public boolean remove(E item) + { + int index = filteredList.indexOf(item); + if (index >= 0) { + filteredList.remove(index); + fireIntervalRemoved(this, index, index); + } + return (index >= 0); + } + + /** Removes from this list all of its elements that are contained in the specified Collection. */ + public boolean removeAll(Collection c) + { + boolean modified = false; + for (int idx = filteredList.size() - 1; idx >= 0; idx--) { + if (c.contains(filteredList.get(idx))) { + filteredList.remove(idx); + fireIntervalRemoved(this, idx, idx); + modified = true; + } + } + return modified; + } + + /** Retains only the elements in this list that are contained in the specified Collection. */ + public boolean retainAll(Collection c) + { + boolean modified = false; + for (int idx = filteredList.size() - 1; idx >= 0; idx--) { + if (!c.contains(filteredList.get(idx))) { + filteredList.remove(idx); + fireIntervalRemoved(this, idx, idx); + modified = true; + } + } + return modified; + } + + /** Removes all of the elements from this list. */ + public void clear() + { + int index1 = filteredList.size() - 1; + filteredList.clear(); + if (index1 >= 0) + fireIntervalRemoved(this, 0, index1); + } + + /** Deletes the elements at the specified range of indexes. The removal is inclusive. */ + public void removeRange(int fromIndex, int toIndex) + { + if (fromIndex > toIndex) { + throw new IllegalArgumentException("fromIndex must be <= toIndex"); + } + for(int i = toIndex; i >= fromIndex; i--) { + filteredList.removeElementAt(i); + } + fireIntervalRemoved(this, fromIndex, toIndex); + } + + /** Convenience method: Enforces a filter update with the global flags. */ + private void updateFilter() + { + updateFilter(filtered, pattern, true); + } + + /** Performs an update on the filter list based on specified parameters. */ + private void updateFilter(boolean filtered, String pattern, boolean forced) + { + boolean filterModified = (this.filtered != filtered); + if (filterModified) + this.filtered = filtered; + + pattern = normalize(pattern); + boolean patternModified = !this.pattern.equals(pattern); + if (patternModified) + this.pattern = pattern; + + if (!forced && !this.filtered && !filterModified) + return; + if (!forced && this.filtered && !filterModified && !patternModified) + return; + + pattern = this.pattern.toLowerCase(); + boolean filter = this.filtered && !this.pattern.isEmpty(); + + // Scanning list from back to front for performance reason. + // A helper object keeps number of fired data events to a minimum for greatly improved performance. + ListDataEventHelper helper = new ListDataEventHelper(); + int fidx = filteredList.size() - 1; + for (int bidx = list.size() - 1; bidx >= 0; bidx--) { + E item = list.get(bidx); + boolean match = !filter || (item != null ? item : "").toString().toLowerCase().contains(pattern); + if (match) { + if (fidx < 0 || !item.equals(getElementAt(fidx))) { + 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))) { + helper.updateEvent(ListDataEventHelper.EVENT_NONE, -1); + fidx--; + } + } else if (fidx >= 0 && item.equals(getElementAt(fidx))) { + filteredList.remove(fidx); + helper.updateEvent(ListDataEventHelper.EVENT_REMOVE, fidx); + fidx--; + } + } + helper.fireEvent(); // finalizing trailing event + + fireFilterChange(); + } + + /** Ensures that strings are not {@code null} and trimmed. */ + private String normalize(String s) + { + return (s != null) ? s.trim() : ""; + } + + + /** Used internally to reduce the number of fired list data events when building the filter list. */ + private class ListDataEventHelper + { + /** This event type does nothing. */ + public static final int EVENT_NONE = 0; + /** Event for adding new list items. */ + public static final int EVENT_ADD = 1; + /** Event for removing existing list items. */ + public static final int EVENT_REMOVE = 2; + /** Event for updating existing list items. */ + public static final int EVENT_CHANGED = 3; + + private int event; + private int index0, index1; + + public ListDataEventHelper() + { + this.event = EVENT_NONE; + this.index0 = -1; + this.index1 = -1; + } + + /** + * Registers the specified index for the event type. + * A change of the event type will automatically fire the previous event. + * This method should be called AFTER making the change to the list. + * @param eventType See EVENT_xxx constants. + * @param index The list item index associated with the event type. + */ + public void updateEvent(int eventType, int index) + { + if (eventType != this.event) { + fireEvent(); + event = eventType; + index0 = index; + } + if (eventType != EVENT_NONE) + index1 = index; + } + + /** + * Fires the currently active event with all accumulated indices at once. + * If invoked manually it should be called AFTER making the change to the list. + */ + public void fireEvent() + { + switch (event) { + case EVENT_ADD: + FilteredListModel.this.fireIntervalAdded(FilteredListModel.this, Math.min(index0, index1), Math.max(index0, index1)); + break; + case EVENT_REMOVE: + FilteredListModel.this.fireIntervalRemoved(FilteredListModel.this, Math.min(index0, index1), Math.max(index0, index1)); + break; + case EVENT_CHANGED: + FilteredListModel.this.fireContentsChanged(FilteredListModel.this, Math.min(index0, index1), Math.max(index0, index1)); + break; + } + event = EVENT_NONE; + index0 = index1 = -1; + } + } +} From 36d206337861f5c26b83546c589fb9e62e889fe4 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 23 Aug 2020 11:52:43 +0200 Subject: [PATCH 06/14] Improve performance for various I/O-based check operations see https://rules.sonarsource.com/java/tag/performance/RSPEC-3725 --- src/org/infinity/NearInfinity.java | 17 ++- src/org/infinity/gui/BIFFEditor.java | 2 +- src/org/infinity/gui/BcsDropFrame.java | 4 +- src/org/infinity/gui/BrowserMenuBar.java | 9 +- src/org/infinity/gui/DebugConsole.java | 2 +- src/org/infinity/gui/GameProperties.java | 3 +- src/org/infinity/gui/OpenFileFrame.java | 3 +- src/org/infinity/gui/ResourceTree.java | 16 +-- src/org/infinity/gui/SortableTable.java | 2 +- src/org/infinity/gui/StringEditor.java | 3 +- .../gui/converter/BamFilterColorReplace.java | 3 +- .../gui/converter/BamOptionsDialog.java | 9 +- .../gui/converter/BamPaletteDialog.java | 3 +- .../infinity/gui/converter/ConvertToBam.java | 16 +-- .../infinity/gui/converter/ConvertToBmp.java | 8 +- .../infinity/gui/converter/ConvertToMos.java | 7 +- .../infinity/gui/converter/ConvertToPvrz.java | 8 +- .../infinity/gui/converter/ConvertToTis.java | 11 +- .../infinity/gui/hexview/StructHexViewer.java | 8 +- src/org/infinity/resource/Profile.java | 130 +++++++++--------- .../infinity/resource/ResourceFactory.java | 58 ++++---- .../infinity/resource/StructureFactory.java | 7 +- .../are/viewer/LayerObjectAutomap.java | 5 +- .../resource/graphics/BamV2Decoder.java | 3 +- .../resource/graphics/ColorConvert.java | 10 +- .../resource/graphics/TisResource.java | 12 +- src/org/infinity/resource/key/BIFFEntry.java | 5 +- .../resource/key/BIFFResourceEntry.java | 16 +-- src/org/infinity/resource/key/BIFFWriter.java | 12 +- src/org/infinity/resource/key/Keyfile.java | 10 +- .../infinity/resource/key/ResourceEntry.java | 2 +- .../resource/key/ResourceTreeModel.java | 2 +- src/org/infinity/resource/mus/Entry.java | 6 +- src/org/infinity/resource/sav/IOHandler.java | 4 +- .../infinity/resource/sav/SavResource.java | 4 +- .../infinity/resource/video/MveResource.java | 2 +- .../infinity/resource/video/WbmResource.java | 4 +- src/org/infinity/updater/Updater.java | 3 +- src/org/infinity/updater/Utils.java | 3 +- src/org/infinity/util/FileDeletionHook.java | 2 +- src/org/infinity/util/MassExporter.java | 18 +-- src/org/infinity/util/StringTable.java | 4 +- src/org/infinity/util/io/DlcManager.java | 6 +- src/org/infinity/util/io/FileManager.java | 8 +- src/org/infinity/util/io/FileWatcher.java | 2 +- src/org/infinity/util/io/StreamUtils.java | 2 +- .../infinity/util/io/zip/DlcFileSystem.java | 2 +- 47 files changed, 230 insertions(+), 246 deletions(-) diff --git a/src/org/infinity/NearInfinity.java b/src/org/infinity/NearInfinity.java index 84120fe5a..7509fb9bd 100644 --- a/src/org/infinity/NearInfinity.java +++ b/src/org/infinity/NearInfinity.java @@ -30,7 +30,6 @@ import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; @@ -247,10 +246,10 @@ public static void main(String args[]) } else { // Override game folder via application parameter Path f = FileManager.resolve(args[idx]); - if (Files.isRegularFile(f)) { + if (f.toFile().isFile()) { f = f.getParent(); } - if (Files.isDirectory(f)) { + if (f.toFile().isDirectory()) { gameOverride = f; break; } @@ -304,7 +303,7 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) setJMenuBar(menu); final String lastDir; - if (gameOverride != null && Files.isDirectory(gameOverride)) { + if (gameOverride != null && gameOverride.toFile().isDirectory()) { lastDir = gameOverride.toString(); } else { lastDir = prefs.get(LAST_GAMEDIR, null); @@ -312,9 +311,9 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) final Path keyFile; Path path; - if (Files.isRegularFile(path = FileManager.resolve(KEYFILENAME))) { + if ((path = FileManager.resolve(KEYFILENAME)).toFile().isFile()) { keyFile = path; - } else if (lastDir != null && Files.isRegularFile(path = FileManager.resolve(lastDir, KEYFILENAME))) { + } else if (lastDir != null && (path = FileManager.resolve(lastDir, KEYFILENAME)).toFile().isFile()) { keyFile = path; } else { keyFile = findKeyfile(); @@ -774,7 +773,7 @@ public boolean editGameIni(Component parent) boolean retVal = false; Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); try { - if (iniFile != null && Files.isRegularFile(iniFile)) { + if (iniFile != null && iniFile.toFile().isFile()) { new ViewFrame(parent, new PlainTextResource(new FileResourceEntry(iniFile))); } else { throw new Exception(); @@ -1109,7 +1108,7 @@ public void drop(DropTargetDropEvent event) event.dropComplete(true); if (files != null && files.size() == 1) { Path path = files.get(0).toPath(); - if (path != null && Files.isRegularFile(path) && + if (path != null && path.toFile().isFile() && path.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".KEY")) { Path curFile = Profile.getChitinKey(); if (!path.equals(curFile)) { @@ -1133,7 +1132,7 @@ public void run() if (files != null) { files.forEach((file) -> { Path path = file.toPath(); - if (Files.isRegularFile(path)) { + if (path.toFile().isFile()) { OpenFileFrame.openExternalFile(NearInfinity.getInstance(), path); } }); diff --git a/src/org/infinity/gui/BIFFEditor.java b/src/org/infinity/gui/BIFFEditor.java index 27b4cf8e4..b46ca0211 100644 --- a/src/org/infinity/gui/BIFFEditor.java +++ b/src/org/infinity/gui/BIFFEditor.java @@ -166,7 +166,7 @@ public void run() for (final ResourceEntry entry : tobif) { Path file = FileManager.query(Profile.getRootFolders(), Profile.getOverrideFolderName(), entry.getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/gui/BcsDropFrame.java b/src/org/infinity/gui/BcsDropFrame.java index 6ca39c99c..931e3345b 100644 --- a/src/org/infinity/gui/BcsDropFrame.java +++ b/src/org/infinity/gui/BcsDropFrame.java @@ -324,7 +324,7 @@ private void filesDropped(Component component, List files) if (component == compZone) { for (File f : files) { Path file = f.toPath(); - if (Files.isDirectory(file)) { + if (file.toFile().isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); @@ -356,7 +356,7 @@ else if (file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BA else if (component == decompZone) { for (File f : files) { final Path file = f.toPath(); - if (Files.isDirectory(file)) { + if (file.toFile().isDirectory()) { try (final DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index c18d64d3b..bc130f897 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -26,7 +26,6 @@ import java.awt.event.WindowEvent; import java.io.IOException; import java.nio.charset.Charset; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -1050,7 +1049,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(bookmarkList.get(selected).getPath()); - if (!Files.isRegularFile(keyFile)) { + if (!keyFile.toFile().isFile()) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), bookmarkList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -1069,7 +1068,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(recentList.get(selected).getPath()); - if (!Files.isRegularFile(keyFile)) { + if (!keyFile.toFile().isFile()) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), recentList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -3558,7 +3557,7 @@ public String setName(String newName) public JMenuItem getMenuItem() { return item; } /** Returns whether the bookmark points to an existing game installation. */ - public boolean isEnabled() { return (Files.isRegularFile(FileManager.resolve(path))); } + public boolean isEnabled() { return (FileManager.resolve(path).toFile().isFile()); } /** Returns ActionListener used by the associated menu item. */ public ActionListener getActionListener() { return listener; } @@ -3654,7 +3653,7 @@ static final class RecentGame implements Cloneable public RecentGame(Profile.Game game, String path, int index, ActionListener listener) { if (game == null || game == Profile.Game.Unknown || - path == null || !Files.isRegularFile(FileManager.resolve(path))) { + path == null || !FileManager.resolve(path).toFile().isFile()) { throw new NullPointerException(); } this.game = game; diff --git a/src/org/infinity/gui/DebugConsole.java b/src/org/infinity/gui/DebugConsole.java index c42f06380..9cd32a5bf 100644 --- a/src/org/infinity/gui/DebugConsole.java +++ b/src/org/infinity/gui/DebugConsole.java @@ -76,7 +76,7 @@ else if (event.getSource() == bSaveConsole) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "nidebuglog.txt")); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { Path output = chooser.getSelectedFile().toPath(); - if (Files.exists(output)) { + if (output.toFile().exists()) { 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) diff --git a/src/org/infinity/gui/GameProperties.java b/src/org/infinity/gui/GameProperties.java index 0f181ac1b..8cc03fe75 100644 --- a/src/org/infinity/gui/GameProperties.java +++ b/src/org/infinity/gui/GameProperties.java @@ -18,7 +18,6 @@ import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -249,7 +248,7 @@ private void init() pIni.add(tf, gbc); bEdit.setMargin(new Insets(2, 4, 2, 4)); bEdit.addActionListener(this); - bEdit.setEnabled(iniFile != null && Files.isRegularFile(iniFile)); + bEdit.setEnabled(iniFile != null && iniFile.toFile().isFile()); gbc = ViewerUtil.setGBC(gbc, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0, 4, 0, 0), 0, 0); pIni.add(bEdit, gbc); diff --git a/src/org/infinity/gui/OpenFileFrame.java b/src/org/infinity/gui/OpenFileFrame.java index 3e1763e06..de1435c3a 100644 --- a/src/org/infinity/gui/OpenFileFrame.java +++ b/src/org/infinity/gui/OpenFileFrame.java @@ -22,7 +22,6 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -240,7 +239,7 @@ else if (event.getSource() == bOpenNew) { /** Attempts to open the specified external game resource. */ public static void openExternalFile(Component parent, Path file) { - if (!Files.exists(file)) { + if (file != null && !file.toFile().exists()) { JOptionPane.showMessageDialog(parent, '\"' + file.toString() + "\" not found", "Error", JOptionPane.ERROR_MESSAGE); } else { diff --git a/src/org/infinity/gui/ResourceTree.java b/src/org/infinity/gui/ResourceTree.java index e671b887e..b1d68751a 100644 --- a/src/org/infinity/gui/ResourceTree.java +++ b/src/org/infinity/gui/ResourceTree.java @@ -264,8 +264,8 @@ static void renameResource(FileResourceEntry entry) if (!filename.contains(".")) { filename = filename + '.' + entry.getExtension(); } - if (Files.exists(entry.getActualPath().getParent().resolve(filename)) - && JOptionPane.showConfirmDialog(NearInfinity.getInstance(), + if (entry.getActualPath().getParent().resolve(filename).toFile().exists() && + JOptionPane.showConfirmDialog(NearInfinity.getInstance(), "File with name \"" + filename + "\" already exists! Overwrite?", "Confirm overwrite " + filename, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.OK_OPTION @@ -360,8 +360,8 @@ static void restoreResource(ResourceEntry entry) // .bak available -> restore .bak version Path curFile = getCurrentFile(entry); Path tmpFile = getTempFile(curFile); - if (curFile != null && Files.isRegularFile(curFile) && - bakFile != null && Files.isRegularFile(bakFile)) { + if (curFile != null && curFile.toFile().isFile() && + bakFile != null && bakFile.toFile().isFile()) { try { Files.move(curFile, tmpFile); try { @@ -415,7 +415,7 @@ static void restoreResource(ResourceEntry entry) static void createZipFile(Path path) { - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { JFileChooser fc = new JFileChooser(Profile.getGameRoot().toFile()); fc.setDialogTitle("Save as"); fc.setFileFilter(new FileNameExtensionFilter("Zip files (*.zip)", "zip")); @@ -484,7 +484,7 @@ private static Path getBackupFile(ResourceEntry entry) (entry instanceof BIFFResourceEntry && entry.hasOverride())) { if (file != null) { Path bakFile = file.getParent().resolve(file.getFileName().toString() + ".bak"); - if (Files.isRegularFile(bakFile)) { + if (bakFile.toFile().isFile()) { return bakFile; } } @@ -509,13 +509,13 @@ private static Path getCurrentFile(ResourceEntry entry) private static Path getTempFile(Path file) { Path retVal = null; - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { final String fmt = ".%03d"; Path filePath = file.getParent(); String fileName = file.getFileName().toString(); for (int i = 0; i < 1000; i++) { Path tmp = filePath.resolve(fileName + String.format(fmt, i)); - if (!Files.exists(tmp) && Files.notExists(tmp)) { + if (!tmp.toFile().exists()) { retVal = tmp; break; } diff --git a/src/org/infinity/gui/SortableTable.java b/src/org/infinity/gui/SortableTable.java index b9fb95ebd..96c3ae227 100644 --- a/src/org/infinity/gui/SortableTable.java +++ b/src/org/infinity/gui/SortableTable.java @@ -107,7 +107,7 @@ private void saveResult(Component parent, String dialogTitle, String header) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "result.txt")); if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { final Path output = chooser.getSelectedFile().toPath(); - if (Files.exists(output)) { + if (output.toFile().exists()) { final String[] options = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, output + " exists. Overwrite?", dialogTitle, JOptionPane.YES_NO_OPTION, diff --git a/src/org/infinity/gui/StringEditor.java b/src/org/infinity/gui/StringEditor.java index e738b6780..83222f0dc 100644 --- a/src/org/infinity/gui/StringEditor.java +++ b/src/org/infinity/gui/StringEditor.java @@ -14,7 +14,6 @@ import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Locale; @@ -732,7 +731,7 @@ private void save(boolean interactive) int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { outPath = fc.getSelectedFile().toPath(); - if (!Files.isDirectory(outPath)) { + if (!outPath.toFile().isDirectory()) { outPath = outPath.getParent(); } outFile = outPath.resolve(StringTable.getPath(StringTable.Type.MALE).getFileName().toString()); diff --git a/src/org/infinity/gui/converter/BamFilterColorReplace.java b/src/org/infinity/gui/converter/BamFilterColorReplace.java index c66b5ab75..f01a90423 100644 --- a/src/org/infinity/gui/converter/BamFilterColorReplace.java +++ b/src/org/infinity/gui/converter/BamFilterColorReplace.java @@ -21,7 +21,6 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; @@ -281,7 +280,7 @@ public int[] getPalette() /** Loads the palette from the specified file resource into the color grid component. */ public void loadPalette(Path paletteFile) throws Exception { - if (paletteFile != null && Files.isRegularFile(paletteFile)) { + if (paletteFile != null && paletteFile.toFile().isFile()) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/BamOptionsDialog.java b/src/org/infinity/gui/converter/BamOptionsDialog.java index 59f439a28..384c622f3 100644 --- a/src/org/infinity/gui/converter/BamOptionsDialog.java +++ b/src/org/infinity/gui/converter/BamOptionsDialog.java @@ -17,7 +17,6 @@ import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.io.IOError; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -161,7 +160,7 @@ private static void validateSettings() { bamVersion = Math.min(Math.max(bamVersion, ConvertToBam.VERSION_BAMV1), ConvertToBam.VERSION_BAMV2); if (path == null) path = DEFAULT_PATH; - if (!path.isEmpty() && !(Files.isDirectory(FileManager.resolve(path)))) path = DEFAULT_PATH; + if (!path.isEmpty() && !FileManager.resolve(path).toFile().isDirectory()) path = DEFAULT_PATH; transparencyThreshold = Math.min(Math.max(transparencyThreshold, 0), 100); useAlpha = Math.min(Math.max(useAlpha, ConvertToBam.ALPHA_AUTO), ConvertToBam.ALPHA_NEVER); @@ -249,7 +248,7 @@ private static void loadRecentSessions(Preferences prefs) value = value.trim(); if (!finished && !value.isEmpty()) { Path path = Paths.get(value); - if (Files.isRegularFile(path)) { + if (path.toFile().isFile()) { recentSessions.add(path); } } @@ -292,7 +291,7 @@ public void actionPerformed(ActionEvent event) { if (event.getSource() == miPathSet) { Path path = FileManager.resolve(tfPath.getText()); - if (!Files.isDirectory(path)) { + if (!path.toFile().isDirectory()) { path = Profile.getGameRoot(); } Path rootPath = ConvertToBam.getOpenPathName(this, "Select initial directory", path); @@ -335,7 +334,7 @@ public void focusLost(FocusEvent event) { if (event.getSource() == tfPath) { String path = tfPath.getText(); - if (!path.isEmpty() && !Files.isDirectory(FileManager.resolve(path))) { + if (!path.isEmpty() && !FileManager.resolve(path).toFile().isDirectory()) { tfPath.setText(path); } } diff --git a/src/org/infinity/gui/converter/BamPaletteDialog.java b/src/org/infinity/gui/converter/BamPaletteDialog.java index 37a54e5c4..b6b3e5cab 100644 --- a/src/org/infinity/gui/converter/BamPaletteDialog.java +++ b/src/org/infinity/gui/converter/BamPaletteDialog.java @@ -20,7 +20,6 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; @@ -249,7 +248,7 @@ public void loadExternalPalette(int type, Path paletteFile) throws Exception } // fetching file signature - if (paletteFile != null && Files.isRegularFile(paletteFile)) { + if (paletteFile != null && paletteFile.toFile().isFile()) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/ConvertToBam.java b/src/org/infinity/gui/converter/ConvertToBam.java index 13ef2c90e..c49fd8a05 100644 --- a/src/org/infinity/gui/converter/ConvertToBam.java +++ b/src/org/infinity/gui/converter/ConvertToBam.java @@ -302,7 +302,7 @@ public static Path[] getOpenFileName(Component parent, String title, Path rootPa rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!Files.isDirectory(rootPath)) { + if (!rootPath.toFile().isDirectory()) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -369,7 +369,7 @@ public static Path getSaveFileName(Component parent, String title, Path rootPath rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!Files.isDirectory(rootPath)) { + if (!rootPath.toFile().isDirectory()) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -516,7 +516,7 @@ public void actionPerformed(ActionEvent event) do { file = setBamOutput(); if (file != null) { - if (!Files.exists(file) || + if (!file.toFile().exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -2749,13 +2749,13 @@ public void framesAddFolder() public void framesAddFolder(Path path) { - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { // preparing list of valid files FileNameExtensionFilter filters = getGraphicsFilters()[0]; List validFiles = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { - if (Files.isRegularFile(file) && filters.accept(file.toFile())) { + if (file.toFile().isFile() && filters.accept(file.toFile())) { validFiles.add(file); } } @@ -5068,7 +5068,7 @@ public boolean importData(boolean silent) Path[] files = getOpenFileName(bam, "Import BAM session", null, false, new FileNameExtensionFilter[]{getIniFilter()}, 0); if (files != null && files.length > 0) { - if (!Files.isRegularFile(files[0])) { + if (!files[0].toFile().isFile()) { files[0] = StreamUtils.replaceFileExtension(files[0], "ini"); } if (loadData(files[0], silent)) { @@ -5189,7 +5189,7 @@ private boolean loadFrameData(IniMapSection frames) throws Exception } } else { Path file = FileManager.resolve(value); - if (!Files.isRegularFile(file)) { + if (!file.toFile().isFile()) { throw new Exception("Frame source path not found at line " + (entry.getLine() + 1)); } } @@ -5375,7 +5375,7 @@ public SourceData(Path image) } } else { Path file = FileManager.resolve(value); - if (Files.isRegularFile(file)) { + if (file.toFile().isFile()) { resource = new FileResourceEntry(file); } } diff --git a/src/org/infinity/gui/converter/ConvertToBmp.java b/src/org/infinity/gui/converter/ConvertToBmp.java index a02cbee78..cc515a300 100644 --- a/src/org/infinity/gui/converter/ConvertToBmp.java +++ b/src/org/infinity/gui/converter/ConvertToBmp.java @@ -98,7 +98,7 @@ private static Path[] getOpenFileName(Component parent, String title, Path rootP } Path file = FileManager.resolve(rootPath); JFileChooser fc = new JFileChooser(file.toFile()); - if (!Files.isDirectory(file)) { + if (!file.toFile().isDirectory()) { fc.setSelectedFile(file.toFile()); } if (title == null) { @@ -520,7 +520,7 @@ private void inputAddFolder() rootPath = FileManager.resolve(modelInputFiles.get(modelInputFiles.size() - 1)); } Path path = getOpenPathName(this, "Choose folder", rootPath); - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { // adding all files in the directory FileNameExtensionFilter[] filters = getGraphicsFilters(); List skippedFiles = new ArrayList(); @@ -528,7 +528,7 @@ private void inputAddFolder() try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { for (final FileNameExtensionFilter filter: filters) { - if (Files.isRegularFile(file) && filter.accept(file.toFile())) { + if (file.toFile().isFile() && filter.accept(file.toFile())) { if (isValidInput(file)) { modelInputFiles.addElement(file.toString()); idx++; @@ -633,7 +633,7 @@ private List convert() // 1. prepare data Path inFile = FileManager.resolve(modelInputFiles.get(i)); Path outFile = FileManager.resolve(outPath, StreamUtils.replaceFileExtension(inFile.getFileName().toString(), "BMP")); - if (Files.exists(outFile)) { + if (outFile.toFile().exists()) { if (cbOverwrite.getSelectedIndex() == 0) { // ask String msg = String.format("File %s already exists. Overwrite?", outFile.getFileName()); int ret = JOptionPane.showConfirmDialog(this, msg, "Overwrite?", JOptionPane.YES_NO_CANCEL_OPTION); diff --git a/src/org/infinity/gui/converter/ConvertToMos.java b/src/org/infinity/gui/converter/ConvertToMos.java index cc0777f62..b0ceca03b 100644 --- a/src/org/infinity/gui/converter/ConvertToMos.java +++ b/src/org/infinity/gui/converter/ConvertToMos.java @@ -24,7 +24,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -544,7 +543,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutputV2.getText()); } if (file != null) { - if (!Files.exists(file) || + if (!file.toFile().exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -906,7 +905,7 @@ private boolean isReady() boolean ret = false; if (!tfInputV1.getText().isEmpty() && !tfOutputV1.getText().isEmpty()) { Path file = FileManager.resolve(tfInputV1.getText()); - ret = Files.isRegularFile(file); + ret = file.toFile().isFile(); } return ret; } @@ -975,7 +974,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(tfInputV1.getText()); - if (!Files.isRegularFile(inFile)) { + if (!inFile.toFile().isFile()) { result.add(null); result.add(String.format("Input file \"%s\" does not exist.", tfInputV1.getText())); return result; diff --git a/src/org/infinity/gui/converter/ConvertToPvrz.java b/src/org/infinity/gui/converter/ConvertToPvrz.java index 83dd116c1..100321686 100644 --- a/src/org/infinity/gui/converter/ConvertToPvrz.java +++ b/src/org/infinity/gui/converter/ConvertToPvrz.java @@ -480,7 +480,7 @@ private boolean isReady() // checks graphics input file properties private static boolean isValidGraphicsInput(Path inFile) { - boolean result = (inFile != null && Files.isRegularFile(inFile)); + boolean result = (inFile != null && inFile.toFile().isFile()); if (result) { Dimension d = ColorConvert.getImageDimension(inFile); if (d == null || d.width <= 0 || d.width > 1024 || d.height <= 0 || d.height > 1024) { @@ -493,7 +493,7 @@ private static boolean isValidGraphicsInput(Path inFile) // checks PVR input file properties private static boolean isValidPVRInput(Path inFile) { - boolean result = (inFile != null && Files.isRegularFile(inFile)); + boolean result = (inFile != null && inFile.toFile().isFile()); if (result) { try (InputStream is = StreamUtils.getInputStream(inFile)) { String sig = StreamUtils.readString(is, 4); @@ -540,7 +540,7 @@ private List convert() if (tfTargetDir.getText() != null && !tfTargetDir.getText().isEmpty()) { targetPath = FileManager.resolve(tfTargetDir.getText()); } - if (!Files.isDirectory(targetPath)) { + if (!targetPath.toFile().isDirectory()) { List l = new Vector(2); l.add(null); l.add("Invalid target directory specified. No conversion takes place."); @@ -594,7 +594,7 @@ private List convert() Path outFile = targetPath.resolve(outFileName); // handling overwrite existing file - if (Files.exists(outFile)) { + if (outFile.toFile().exists()) { if (skip) { skippedFiles++; continue; diff --git a/src/org/infinity/gui/converter/ConvertToTis.java b/src/org/infinity/gui/converter/ConvertToTis.java index 1115f78fa..17047ea94 100644 --- a/src/org/infinity/gui/converter/ConvertToTis.java +++ b/src/org/infinity/gui/converter/ConvertToTis.java @@ -24,7 +24,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -592,7 +591,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutput.getText()); } if (file != null) { - if (!Files.exists(file) || + if (!file.toFile().exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -650,7 +649,7 @@ public List doInBackground() String fileName = tfOutput.getText(); if (fileName.isEmpty() && !tfInput.getText().isEmpty()) { Path f = FileManager.resolve(tfInput.getText()); - if (Files.isRegularFile(f)) { + if (f.toFile().isFile()) { fileName = createValidTisName(tfInput.getText(), getTisVersion()); } } @@ -976,7 +975,7 @@ private boolean isReady() boolean ret = false; if (!getInputFile().isEmpty()) { Path f = FileManager.resolve(getInputFile()); - ret = Files.isRegularFile(f); + ret = f.toFile().isFile(); } return ret; } @@ -1032,7 +1031,7 @@ private boolean validateInput(String inputFile) inFileName = inputFile; if (inFileName != null && !inFileName.isEmpty()) { Path f = FileManager.resolve(inFileName); - if (Files.isRegularFile(f)) { + if (f.toFile().isFile()) { Dimension dimImage = ColorConvert.getImageDimension(f); if (dimImage.width >= 0 && (dimImage.width % 64) == 0 && dimImage.height >= 0 && (dimImage.height % 64) == 0) { @@ -1072,7 +1071,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(inFileName); - if (!Files.isRegularFile(inFile)) { + if (!inFile.toFile().isFile()) { ret.add(null); ret.add(String.format("Input file \"%s\" does not exist.", inFileName)); return ret; diff --git a/src/org/infinity/gui/hexview/StructHexViewer.java b/src/org/infinity/gui/hexview/StructHexViewer.java index 2adf7e0ce..8b2baf6e1 100644 --- a/src/org/infinity/gui/hexview/StructHexViewer.java +++ b/src/org/infinity/gui/hexview/StructHexViewer.java @@ -263,7 +263,7 @@ public void actionPerformed(ActionEvent event) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!Files.isDirectory(overridePath)) { + if (!overridePath.toFile().isDirectory()) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -278,7 +278,7 @@ public void actionPerformed(ActionEvent event) } else { outPath = entry.getActualPath(); } - if (Files.exists(outPath)) { + if (outPath.toFile().exists()) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(this, outPath + " exists. Overwrite?", "Save resource", @@ -287,10 +287,10 @@ public void actionPerformed(ActionEvent event) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (Files.isRegularFile(bakPath)) { + if (bakPath.toFile().isFile()) { Files.delete(bakPath); } - if (!Files.exists(bakPath)) { + if (!bakPath.toFile().exists()) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/Profile.java b/src/org/infinity/resource/Profile.java index 759683be4..5a844b1f8 100644 --- a/src/org/infinity/resource/Profile.java +++ b/src/org/infinity/resource/Profile.java @@ -880,7 +880,7 @@ public static boolean updateGameLanguage(String language) // updating dialog.tlks updateProperty(Key.GET_GAME_DIALOG_FILE, FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME))); Path femaleTlkFile = FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (Files.isRegularFile(femaleTlkFile)) { + if (femaleTlkFile.toFile().isFile()) { addProperty(Key.GET_GAME_DIALOGF_FILE, Type.PATH, femaleTlkFile); } else { updateProperty(Key.GET_GAME_DIALOGF_FILE, null); @@ -1211,7 +1211,7 @@ private static String getLuaHomeFolderName(Game game) private static String getLuaValue(Path file, String key, String defaultValue, boolean ifLuaExists) { String retVal = ifLuaExists ? null : defaultValue; - if (file != null && Files.isRegularFile(file) && key != null && !key.trim().isEmpty()) { + if (file != null && file.toFile().isFile() && key != null && !key.trim().isEmpty()) { retVal = defaultValue; try (Stream lines = Files.lines(file, StandardCharsets.UTF_8)) { for (Iterator iter = lines.iterator(); iter.hasNext();) { @@ -1269,7 +1269,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception { if (keyFile == null) { throw new Exception("No chitin.key specified"); - } else if (!Files.isRegularFile(keyFile)) { + } else if (!keyFile.toFile().isFile()) { throw new Exception(keyFile.toString() + " does not exist"); } @@ -1296,7 +1296,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception if (home != null) { addEntry(Key.GET_GAME_HOME_FOLDER_NAME, Type.STRING, home); homeDir = ResourceFactory.getHomeRoot(true); - if (homeDir != null && Files.isDirectory(homeDir)) { + if (homeDir != null && homeDir.toFile().isDirectory()) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeDir); } } @@ -1327,85 +1327,85 @@ private void initGame() throws Exception } if (game == Game.IWDEE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm"))) { + FileManager.query(gameRoots, "movies/howseer.wbm").toFile().isFile()) { if (game == null) game = Game.IWDEE; // Note: baldur.ini is initialized later } else if (game == Game.PSTEE || - (Files.isRegularFile(FileManager.query(gameRoots, "data/MrtGhost.bif")) && - Files.isRegularFile(FileManager.query(gameRoots, "data/shaders.bif")) && + (FileManager.query(gameRoots, "data/MrtGhost.bif").toFile().isFile() && + FileManager.query(gameRoots, "data/shaders.bif").toFile().isFile() && getLuaValue(FileManager.query(gameRoots, "engine.lua"), "engine_mode", "0", false).equals("3"))) { if (game == null) game = Game.PSTEE; // Note: baldur.ini is initialized later } else if (game == Game.EET || game == Game.BG2EE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/pocketzz.wbm"))) { - if ((Files.isRegularFile(FileManager.query(gameRoots, "override/EET.flag"))) || - (Files.isRegularFile(FileManager.query(gameRoots, "data/eetTU00.bif")))) { + FileManager.query(gameRoots, "movies/pocketzz.wbm").toFile().isFile()) { + if ((FileManager.query(gameRoots, "override/EET.flag").toFile().isFile()) || + (FileManager.query(gameRoots, "data/eetTU00.bif").toFile().isFile())) { if (game == null) game = Game.EET; } else { if (game == null) game = Game.BG2EE; } // Note: baldur.ini is initialized later } else if (game == Game.BG1SoD || - Files.isRegularFile(FileManager.query(gameRoots, "movies/sodcin01.wbm"))) { + FileManager.query(gameRoots, "movies/sodcin01.wbm").toFile().isFile()) { if (game == null) game = Game.BG1SoD; // Note: baldur.ini is initialized later } else if (game == Game.BG1EE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/bgenter.wbm"))) { + FileManager.query(gameRoots, "movies/bgenter.wbm").toFile().isFile()) { if (game == null) game = Game.BG1EE; // Note: baldur.ini is initialized later } else if ((game == Game.PST || - Files.isRegularFile(FileManager.query(gameRoots, "torment.exe"))) && - (!Files.isRegularFile(FileManager.query(gameRoots, "movies/sigil.wbm")))) { + FileManager.query(gameRoots, "torment.exe").toFile().isFile()) && + (!FileManager.query(gameRoots, "movies/sigil.wbm").toFile().isFile())) { if (game == null) game = Game.PST; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "torment.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD || game == Game.IWDHoW || game == Game.IWDHowTotLM || - (Files.isRegularFile(FileManager.query(gameRoots, "idmain.exe"))) && - (!Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm")))) { + (FileManager.query(gameRoots, "idmain.exe").toFile().isFile()) && + (!FileManager.query(gameRoots, "movies/howseer.wbm").toFile().isFile())) { if (game == null) game = Game.IWD; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD2 || - (Files.isRegularFile(FileManager.query(gameRoots, "iwd2.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "Data/Credits.mve")))) { + (FileManager.query(gameRoots, "iwd2.exe").toFile().isFile()) && + (FileManager.query(gameRoots, "Data/Credits.mve").toFile().isFile())) { if (game == null) game = Game.IWD2; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind2.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.Tutu || - Files.isRegularFile(FileManager.query(gameRoots, "bg1tutu.exe")) || - Files.isRegularFile(FileManager.query(gameRoots, "bg1mov/MovieCD1.bif"))) { + FileManager.query(gameRoots, "bg1tutu.exe").toFile().isFile() || + FileManager.query(gameRoots, "bg1mov/MovieCD1.bif").toFile().isFile()) { if (game == null) game = Game.Tutu; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG2SoA || game == Game.BG2ToB || game == Game.BGT || - (Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "BGConfig.exe")))) { + (FileManager.query(gameRoots, "baldur.exe").toFile().isFile()) && + (FileManager.query(gameRoots, "BGConfig.exe").toFile().isFile())) { if (game == null) game = Game.BG2SoA; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG1 || game == Game.BG1TotSC || - (Files.isRegularFile(FileManager.query(gameRoots, "movies/graphsim.mov"))) || // Mac BG1 detection hack - ((Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "Config.exe"))))) { + (FileManager.query(gameRoots, "movies/graphsim.mov").toFile().isFile()) || // Mac BG1 detection hack + ((FileManager.query(gameRoots, "baldur.exe").toFile().isFile()) && + (FileManager.query(gameRoots, "Config.exe").toFile().isFile()))) { if (game == null) game = Game.BG1; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else { @@ -1414,7 +1414,7 @@ private void initGame() throws Exception if (game == null) game = Game.Unknown; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } @@ -1431,7 +1431,7 @@ private void initGame() throws Exception if (isEnhancedEdition()) { Path langDir = FileManager.query(gameRoots, "lang"); - if (langDir != null && Files.isDirectory(langDir)) { + if (langDir != null && langDir.toFile().isDirectory()) { addEntry(Key.GET_GAME_LANG_FOLDER_BASE, Type.PATH, langDir); } } @@ -1456,11 +1456,11 @@ private void initGame() throws Exception // initializing dialog.tlk and dialogf.tlk Path tlk = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME)); - if (tlk != null && Files.isRegularFile(tlk)) { + if (tlk != null && tlk.toFile().isFile()) { addEntry(Key.GET_GAME_DIALOG_FILE, Type.PATH, tlk); } Path tlkf = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (tlkf != null && Files.isRegularFile(tlkf)) { + if (tlkf != null && tlkf.toFile().isFile()) { addEntry(Key.GET_GAME_DIALOGF_FILE, Type.PATH, tlkf); } @@ -1552,7 +1552,7 @@ private void initIniFile(String... iniFiles) Path homeRoot = ResourceFactory.getHomeRoot(false); for (int i = 0; i < iniFiles.length; i++) { Path ini = FileManager.query(homeRoot, iniFiles[i]); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_NAME, Type.STRING, iniFiles[i]); break; } @@ -1574,7 +1574,7 @@ private void initRootDirs() if (homeRoot != null) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeRoot); Path ini = FileManager.query(homeRoot, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && ini.toFile().isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } listRoots.add(homeRoot); @@ -1594,7 +1594,7 @@ private void initRootDirs() roots.forEach((root) -> { // adding root of active language Path langRoot = FileManager.query(root, (String)getProperty(Key.GET_GLOBAL_LANG_NAME), language); - if (langRoot != null && Files.isDirectory(langRoot)) { + if (langRoot != null && langRoot.toFile().isDirectory()) { addEntry(Key.GET_GAME_LANG_FOLDER_NAME, Type.STRING, language); addEntry(Key.GET_GAME_LANG_FOLDER, Type.PATH, langRoot); List langPaths = ResourceFactory.getAvailableGameLanguages(); @@ -1607,7 +1607,7 @@ private void initRootDirs() // adding fallback language added if selected language is non-english Path langRootDef = FileManager.query((Path)getProperty(Key.GET_GAME_LANG_FOLDER_BASE), languageDef); - if (!languageDef.equals(language) && langRootDef != null && Files.isDirectory(langRootDef)) { + if (!languageDef.equals(language) && langRootDef != null && langRootDef.toFile().isDirectory()) { listRoots.add(langRootDef); } @@ -1630,7 +1630,7 @@ private void initExtraFolders() List list = new ArrayList<>(extraFolders.size()); extraFolders.forEach((folder) -> { Path path = FileManager.query(root, folder); - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { list.add(path); } }); @@ -1681,48 +1681,48 @@ private void initOverrides() // registering override paths for (final Path root: gameRoots) { Path path = FileManager.query(root, langFolder, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } } path = FileManager.query(root, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, langFolder, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } } path = FileManager.query(root, langFolder, "Fonts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, langFolder, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } } } else { Path root = getGameRoot(); Path path = FileManager.query(root, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && path.toFile().isDirectory()) { list.add(path); } } list.forEach((path) -> { FileWatcher.getInstance().register(path, false); }); @@ -1905,7 +1905,7 @@ private void initFeatures() // Has TobEx been installed? if (engine == Engine.BG2) { Path tobexIni = FileManager.query(getGameRoot(), "TobEx_ini/TobExCore.ini"); - addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Files.isRegularFile(tobexIni)); + addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, tobexIni.toFile().isFile()); } else { addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Boolean.FALSE); } @@ -1980,7 +1980,7 @@ private void initCampaigns() if (model != null) { List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); for (final Path path: extraDirs) { - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { String folderName = path.getFileName().toString(); if (model.getFolder(folderName) == null) { model.addDirectory((ResourceTreeFolder)model.getRoot(), path, false); @@ -2004,19 +2004,19 @@ private List initDlc(Path rootDir, Path homeDir) List gameFolders = new ArrayList<>(); // Getting potential DLC folders (search order is important) - if (rootDir != null && Files.isDirectory(rootDir)) { + if (rootDir != null && rootDir.toFile().isDirectory()) { gameFolders.add(new ObjectString("mod", rootDir.resolve("workshop"))); gameFolders.add(new ObjectString("zip", rootDir.resolve("dlc"))); gameFolders.add(new ObjectString("zip", rootDir)); } - if (homeDir != null && Files.isDirectory(homeDir)) { + if (homeDir != null && homeDir.toFile().isDirectory()) { gameFolders.add(new ObjectString("zip", homeDir)); } for (final ObjectString root: gameFolders) { String ext = root.getString(); Path dir = root.getObject(); - if (dir != null && Files.isDirectory(dir)) { + if (dir != null && dir.toFile().isDirectory()) { List list = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(dir)) { for (final Path file: dstream) { @@ -2065,7 +2065,7 @@ private List initDlc(Path rootDir, Path homeDir) private Path validateDlc(Path file, String ext) throws IOException { // is regular file? - if (file == null && !Files.isRegularFile(file)) { + if (file == null || !file.toFile().isFile()) { return null; } @@ -2098,7 +2098,7 @@ public void fileChanged(FileWatchEvent e) if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { Path path = e.getPath(); - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { // Note: skipping extra folders because of issues on Windows systems // List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); // if (FileManager.containsPath(path, extraDirs)) { diff --git a/src/org/infinity/resource/ResourceFactory.java b/src/org/infinity/resource/ResourceFactory.java index 0827e5a01..55f2e3e69 100644 --- a/src/org/infinity/resource/ResourceFactory.java +++ b/src/org/infinity/resource/ResourceFactory.java @@ -499,7 +499,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search List extraFolders = Profile.getOverrideFolders(searchExtraDirs); if (extraFolders != null) { Path file = FileManager.query(extraFolders, resourceName); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { entry = new FileResourceEntry(file); } } @@ -508,7 +508,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search // checking custom folder list if (extraDirs != null && (entry == null)) { Path file = FileManager.query(extraDirs, resourceName); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { entry = new FileResourceEntry(file); } } @@ -710,12 +710,12 @@ public static List getAvailableGameLanguages() if (Profile.isEnhancedEdition()) { Path langPath = Profile.getProperty(Profile.Key.GET_GAME_LANG_FOLDER_BASE); - if (langPath != null && Files.isDirectory(langPath)) { + if (langPath != null && langPath.toFile().isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(langPath, (Path entry) -> { - return Files.isDirectory(entry) && + return entry.toFile().isDirectory() && entry.getFileName().toString().matches("[a-z]{2}_[A-Z]{2}") && - Files.isRegularFile(FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME))); + FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME)).toFile().isFile(); })) { dstream.forEach((path) -> list.add(path)); } catch (IOException e) { @@ -730,7 +730,7 @@ public static List getAvailableGameLanguages() public static String autodetectGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { + if (Profile.isEnhancedEdition() && iniFile != null && iniFile.toFile().isFile()) { // Attempt to autodetect game language try (BufferedReader br = Files.newBufferedReader(iniFile, Misc.CHARSET_UTF8)) { String line; @@ -743,7 +743,7 @@ public static String autodetectGameLanguage(Path iniFile) lang = lang.replaceFirst("'.*$", ""); if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { try { // try to fetch the actual path name to ensure correct case return path.toRealPath().getFileName().toString(); @@ -771,7 +771,7 @@ static Path getHomeRoot(boolean allowMissing) final Path EE_DOC_ROOT = FileSystemView.getFileSystemView().getDefaultDirectory().toPath(); final String EE_DIR = Profile.getProperty(Profile.Key.GET_GAME_HOME_FOLDER_NAME); Path userPath = FileManager.query(EE_DOC_ROOT, EE_DIR); - if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { + if (allowMissing || (userPath != null && userPath.toFile().isDirectory())) { return userPath; } else { // fallback solution @@ -797,7 +797,7 @@ static Path getHomeRoot(boolean allowMissing) } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("bsd")) { userPath = FileManager.resolve(FileManager.resolve(userPrefix, ".local", "share", EE_DIR)); } - if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { + if (allowMissing || (userPath != null && userPath.toFile().isDirectory())) { return userPath; } } @@ -825,7 +825,7 @@ static List getBIFFDirs() // fetching the CD folders in a game installation Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); List rootFolders = Profile.getRootFolders(); - if (iniFile != null && Files.isRegularFile(iniFile)) { + if (iniFile != null && iniFile.toFile().isFile()) { try (BufferedReader br = Files.newBufferedReader(iniFile)) { String line; while ((line = br.readLine()) != null) { @@ -845,7 +845,7 @@ static List getBIFFDirs() Path path; if (line.charAt(0) == '/') { // absolute Unix path path = FileManager.resolve(line); - if (path == null || !Files.isDirectory(path)) { // try relative Unix path + if (path == null || !path.toFile().isDirectory()) { // try relative Unix path path = FileManager.query(rootFolders, line); } } else if (line.indexOf(':') < 0) { // relative Unix path @@ -853,7 +853,7 @@ static List getBIFFDirs() } else { path = FileManager.resolve(line); } - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { dirList.add(path); } } @@ -871,13 +871,13 @@ static List getBIFFDirs() Path path; for (int i = 1; i < 7; i++) { path = FileManager.query(rootFolders, "CD" + i); - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { dirList.add(path); } } // used in certain games path = FileManager.query(rootFolders, "CDALL"); - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { dirList.add(path); } } @@ -890,7 +890,7 @@ static String fetchGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { + if (Profile.isEnhancedEdition() && iniFile != null && iniFile.toFile().isFile()) { String lang = BrowserMenuBar.getInstance().getSelectedGameLanguage(); if (lang == null || lang.isEmpty()) { @@ -899,7 +899,7 @@ static String fetchGameLanguage(Path iniFile) // Using user-defined language if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { String retVal; try { // try to fetch the actual path name to ensure correct case @@ -1023,7 +1023,7 @@ private Path getExportFileDialogInternal(Component parent, String fileName, bool fc.setSelectedFile(new File(fc.getCurrentDirectory(), fileName)); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { path = fc.getSelectedFile().toPath(); - if (!forceOverwrite && Files.exists(path)) { + if (!forceOverwrite && path.toFile().exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, path + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -1169,7 +1169,7 @@ private void registerResourceInternal(Path resource, boolean autoselect) !Profile.isResourceTypeSupported(FileManager.getFileExtension(resource))) { return; } - if (resource == null || !Files.isRegularFile(resource)) { + if (resource == null || !resource.toFile().isFile()) { return; } @@ -1301,7 +1301,7 @@ private void loadResourcesInternal() throws Exception NearInfinity.advanceProgress("Loading extra resources..."); List extraPaths = Profile.getProperty(Profile.Key.GET_GAME_EXTRA_FOLDERS); extraPaths.forEach((path) -> { - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { treeModel.addDirectory(treeModel.getRoot(), path, false); } }); @@ -1312,10 +1312,10 @@ private void loadResourcesInternal() throws Exception String overrideFolder = Profile.getOverrideFolderName(); List overridePaths = Profile.getOverrideFolders(false); for (final Path overridePath: overridePaths) { - if (Files.isDirectory(overridePath)) { + if (overridePath.toFile().isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(overridePath)) { dstream.forEach((path) -> { - if (Files.isRegularFile(path)) { + if (path.toFile().isFile()) { ResourceEntry entry = getResourceEntry(path.getFileName().toString()); if (entry instanceof FileResourceEntry) { treeModel.addResourceEntry(entry, entry.getTreeFolderName(), true); @@ -1388,7 +1388,7 @@ private void loadSpecialResources() */ private void addFileResource(Path path) { - if (path != null && Files.isRegularFile(path)) { + if (path != null && path.toFile().isFile()) { treeModel.addResourceEntry(new FileResourceEntry(path), SPECIAL_CATEGORY, false); } } @@ -1516,7 +1516,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) outFile = FileManager.query(Profile.getGameRoot(), "Scripts", fileName); } - if (Files.exists(outFile)) { + if (outFile.toFile().exists()) { String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(NearInfinity.getInstance(), outFile + " exists. Overwrite?", "Confirm overwrite " + outFile, JOptionPane.YES_NO_OPTION, @@ -1525,7 +1525,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) } // creating override folder in game directory if it doesn't exist - if (!Files.isDirectory(outPath)) { + if (!outPath.toFile().isDirectory()) { try { Files.createDirectory(outPath); } catch (IOException e) { @@ -1573,7 +1573,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!Files.isDirectory(overridePath)) { + if (!overridePath.toFile().isDirectory()) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -1590,7 +1590,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) // 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 && !Files.exists(outPath.getParent())) { + if (outPath != null && !outPath.getParent().toFile().exists()) { try { Files.createDirectories(outPath.getParent()); } catch (IOException e) { @@ -1602,7 +1602,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) } } } - if (Files.exists(outPath)) { + if (outPath.toFile().exists()) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, outPath + " exists. Overwrite?", "Save resource", @@ -1611,10 +1611,10 @@ private boolean saveResourceInternal(Resource resource, Component parent) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (Files.isRegularFile(bakPath)) { + if (bakPath.toFile().isFile()) { Files.delete(bakPath); } - if (!Files.exists(bakPath)) { + if (!bakPath.toFile().exists()) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/StructureFactory.java b/src/org/infinity/resource/StructureFactory.java index 3fa9e537d..d372ef2c3 100644 --- a/src/org/infinity/resource/StructureFactory.java +++ b/src/org/infinity/resource/StructureFactory.java @@ -7,7 +7,6 @@ import java.awt.Window; 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.EnumMap; @@ -90,7 +89,7 @@ public void newResource(ResType type, Window parent) roots.add(Profile.getGameRoot()); } savePath = FileManager.query(roots, "Characters"); - if (!Files.isDirectory(savePath)) { + if (!savePath.toFile().isDirectory()) { savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); } break; @@ -99,7 +98,7 @@ public void newResource(ResType type, Window parent) savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); break; } - if (savePath == null || !Files.isDirectory(savePath) ) { + if (savePath == null || !savePath.toFile().isDirectory()) { savePath = Profile.getGameRoot(); } JFileChooser fc = new JFileChooser(savePath.toFile()); @@ -110,7 +109,7 @@ public void newResource(ResType type, Window parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), "UNTITLED." + resExt.get(type))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { Path outFile = fc.getSelectedFile().toPath(); - if (Files.exists(outFile)) { + if (outFile.toFile().exists()) { 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) diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java index 0f44cee0f..0fe0dbb81 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java @@ -6,7 +6,6 @@ import java.awt.Image; import java.awt.Point; -import java.nio.file.Files; import java.nio.file.Path; import org.infinity.datatype.IsNumeric; @@ -65,7 +64,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) if (Profile.isEnhancedEdition()) { // processing new TOH structure Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); - if (Files.exists(tohFile)) { + if (tohFile.toFile().exists()) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); TohResource toh = new TohResource(tohEntry); SectionOffset so = (SectionOffset)toh.getAttribute(TohResource.TOH_OFFSET_ENTRIES); @@ -92,7 +91,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) // processing legacy TOH/TOT structures Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); Path totFile = FileManager.resolve(path, "DEFAULT.TOT"); - if (Files.exists(tohFile) && Files.exists(totFile)) { + if (tohFile.toFile().exists() && totFile.toFile().exists()) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); FileResourceEntry totEntry = new FileResourceEntry(totFile); TohResource toh = new TohResource(tohEntry); diff --git a/src/org/infinity/resource/graphics/BamV2Decoder.java b/src/org/infinity/resource/graphics/BamV2Decoder.java index cf28a0ba6..b9352b4fa 100644 --- a/src/org/infinity/resource/graphics/BamV2Decoder.java +++ b/src/org/infinity/resource/graphics/BamV2Decoder.java @@ -11,7 +11,6 @@ import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.nio.ByteBuffer; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -250,7 +249,7 @@ private PvrDecoder getPVR(int page) if (bamPath != null) { // preferring PVRZ files from the BAM's base path Path pvrzFile = FileManager.resolve(bamPath.resolve(name)); - if (Files.isRegularFile(pvrzFile)) { + if (pvrzFile.toFile().isFile()) { entry = new FileResourceEntry(pvrzFile); } } diff --git a/src/org/infinity/resource/graphics/ColorConvert.java b/src/org/infinity/resource/graphics/ColorConvert.java index 777b2117f..2e75863be 100644 --- a/src/org/infinity/resource/graphics/ColorConvert.java +++ b/src/org/infinity/resource/graphics/ColorConvert.java @@ -437,7 +437,7 @@ public static boolean medianCut(int[] pixels, int desiredColors, int[] palette, */ public static int[] loadPaletteBMP(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); @@ -485,7 +485,7 @@ public static int[] loadPaletteBMP(Path file) throws Exception */ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { BufferedImage img = ImageIO.read(is); if (img.getType() == BufferedImage.TYPE_BYTE_INDEXED) { @@ -517,7 +517,7 @@ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exce */ public static int[] loadPalettePAL(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[12]; boolean eof = is.read(signature) != signature.length; @@ -569,7 +569,7 @@ public static int[] loadPalettePAL(Path file) throws Exception */ public static int[] loadPaletteACT(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { int size = (int)Files.size(file); if (size >= 768) { @@ -611,7 +611,7 @@ public static int[] loadPaletteACT(Path file) throws Exception */ public static int[] loadPaletteBAM(Path file, boolean preserveAlpha) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); diff --git a/src/org/infinity/resource/graphics/TisResource.java b/src/org/infinity/resource/graphics/TisResource.java index 3fecf273f..17b62c5d0 100644 --- a/src/org/infinity/resource/graphics/TisResource.java +++ b/src/org/infinity/resource/graphics/TisResource.java @@ -567,7 +567,7 @@ private Path getTisFileName(Component parent, boolean enforceValidName) } else { repeat = false; } - if (Files.exists(retVal)) { + if (retVal.toFile().exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -596,7 +596,7 @@ private Path getPngFileName(Component parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), getResourceEntry().getResourceName().toUpperCase(Locale.ENGLISH).replace(".TIS", ".PNG"))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { retVal = fc.getSelectedFile().toPath(); - if (Files.exists(retVal)) { + if (retVal.toFile().exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -744,7 +744,7 @@ public Status convertToPaletteTis(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && output.toFile().isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -980,7 +980,7 @@ public Status convertToPvrzTis(Path output, boolean showProgress) retVal = Status.ERROR; e.printStackTrace(); } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && output.toFile().isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -1038,7 +1038,7 @@ public Status exportPNG(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && output.toFile().isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -1133,7 +1133,7 @@ private Status writePvrzPages(Path tisFile, List pageList, if (retVal != Status.SUCCESS) { for (int i = 0; i < pageList.size(); i++) { Path pvrzFile = generatePvrzFileName(tisFile, i); - if (pvrzFile != null && Files.isRegularFile(pvrzFile)) { + if (pvrzFile != null && pvrzFile.toFile().isFile()) { try { Files.delete(pvrzFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/BIFFEntry.java b/src/org/infinity/resource/key/BIFFEntry.java index de369f3ce..d66f9b001 100644 --- a/src/org/infinity/resource/key/BIFFEntry.java +++ b/src/org/infinity/resource/key/BIFFEntry.java @@ -7,7 +7,6 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -125,7 +124,7 @@ public String getFileName() /** Returns whether the referenced BIFF file exists in the game. */ public boolean exists() { - return (biffFile != null && Files.isRegularFile(biffFile)); + return (biffFile != null && biffFile.toFile().isFile()); } /** Returns the absolute path to the BIFF file if it exists. */ @@ -241,7 +240,7 @@ private static Path findBiffFile(Path root, int location, String fileName) final String[] baseFolders = { "", "cache", "cd1", "cd2", "cd3", "cd4", "cd5", "cd6", "cd7", "cdall" }; for (final String folderName: baseFolders) { Path path = FileManager.resolve(root.resolve(folderName)); - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { biffFolders.add(path); } } diff --git a/src/org/infinity/resource/key/BIFFResourceEntry.java b/src/org/infinity/resource/key/BIFFResourceEntry.java index 030710ff7..62e06e4cb 100644 --- a/src/org/infinity/resource/key/BIFFResourceEntry.java +++ b/src/org/infinity/resource/key/BIFFResourceEntry.java @@ -113,12 +113,12 @@ public void deleteOverride() throws IOException { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { Files.deleteIfExists(file); } file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && Files.isRegularFile(file)); + hasOverride = (file != null && file.toFile().isFile()); } } @@ -128,7 +128,7 @@ public Path getActualPath(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { return file; } } @@ -148,7 +148,7 @@ public long getResourceSize(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { retVal = Files.size(file); return retVal; } @@ -191,7 +191,7 @@ public ByteBuffer getResourceBuffer(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { @@ -212,7 +212,7 @@ public InputStream getResourceDataAsStream(boolean ignoreOverride) throws Except if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { return StreamUtils.getInputStream(file); } } @@ -226,7 +226,7 @@ public int[] getResourceInfo(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { return getLocalFileInfo(file); } } @@ -277,7 +277,7 @@ public boolean hasOverride() List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && Files.isRegularFile(file)); + hasOverride = (file != null && file.toFile().isFile()); } } return hasOverride; diff --git a/src/org/infinity/resource/key/BIFFWriter.java b/src/org/infinity/resource/key/BIFFWriter.java index 2c369f37b..d2acbf8b0 100644 --- a/src/org/infinity/resource/key/BIFFWriter.java +++ b/src/org/infinity/resource/key/BIFFWriter.java @@ -121,7 +121,7 @@ public void addResource(ResourceEntry resourceEntry, boolean ignoreoverride) public void write() throws Exception { Path biffPath = FileManager.query(Profile.getGameRoot(), "data"); - if (biffPath == null || !Files.isDirectory(biffPath)) { + if (biffPath == null || !biffPath.toFile().isDirectory()) { throw new Exception("No BIFF folder found."); } Path dummyFile = Files.createTempFile(biffPath, "_dummy", ".bif"); @@ -136,7 +136,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (realFile.toFile().isFile()) { Files.delete(realFile); } Files.move(dummyFile, realFile); @@ -149,7 +149,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (realFile.toFile().isFile()) { Files.delete(realFile); } Files.move(compressedFile, realFile); @@ -162,19 +162,19 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getRootFolders(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (realFile.toFile().isFile()) { Files.delete(realFile); } Files.move(compressedFile, realFile); } } finally { - if (dummyFile != null && Files.isRegularFile(dummyFile)) { + if (dummyFile != null && dummyFile.toFile().isFile()) { try { Files.delete(dummyFile); } catch (IOException e) { } } - if (compressedFile != null && Files.isRegularFile(compressedFile)) { + if (compressedFile != null && compressedFile.toFile().isFile()) { try { Files.delete(compressedFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/Keyfile.java b/src/org/infinity/resource/key/Keyfile.java index feaf81009..443f223cf 100644 --- a/src/org/infinity/resource/key/Keyfile.java +++ b/src/org/infinity/resource/key/Keyfile.java @@ -112,7 +112,7 @@ public Keyfile(Path keyFile) throws FileNotFoundException if (keyFile == null) { throw new NullPointerException("No keyfile specified"); } - if (!Files.isRegularFile(keyFile)) { + if (!keyFile.toFile().isFile()) { throw new FileNotFoundException("Keyfile " + keyFile + " not found or is not regular file"); } @@ -461,7 +461,7 @@ public void run() biffList.forEach((entry) -> { if (entry != null) { Path biffPath = entry.getPath(); - if (biffPath != null && Files.isRegularFile(biffPath)) { + if (biffPath != null && biffPath.toFile().isFile()) { try { AbstractBIFFReader.open(biffPath); } catch (Exception e) { @@ -481,7 +481,7 @@ public void run() // if (keyFile == null) { // throw new NullPointerException(); // } -// if (!Files.isRegularFile(keyFile)) { +// if (!keyFile.toFile().isFile()) { // throw new IOException("Key file not found: " + keyFile); // } // @@ -515,11 +515,11 @@ private void init() throws IOException if (getKeyfile() == null) { throw new NullPointerException(); } - if (!Files.isRegularFile(getKeyfile())) { + if (!getKeyfile().toFile().isFile()) { throw new IOException("Key file not found: " + getKeyfile()); } for (final Path file: keyList) { - if (file != null && !Files.isRegularFile(file)) { + if (file != null && !file.toFile().isFile()) { throw new IOException("Key file not found: " + file); } } diff --git a/src/org/infinity/resource/key/ResourceEntry.java b/src/org/infinity/resource/key/ResourceEntry.java index 1b5ffac7e..aa0d20814 100644 --- a/src/org/infinity/resource/key/ResourceEntry.java +++ b/src/org/infinity/resource/key/ResourceEntry.java @@ -47,7 +47,7 @@ public abstract class ResourceEntry implements Comparable static int[] getLocalFileInfo(Path file) { - if (file != null && Files.isRegularFile(file)) { + if (file != null && file.toFile().isFile()) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { diff --git a/src/org/infinity/resource/key/ResourceTreeModel.java b/src/org/infinity/resource/key/ResourceTreeModel.java index ea4777b11..c08e0762a 100644 --- a/src/org/infinity/resource/key/ResourceTreeModel.java +++ b/src/org/infinity/resource/key/ResourceTreeModel.java @@ -113,7 +113,7 @@ public void addDirectory(ResourceTreeFolder parentFolder, Path directory, boolea if (iter.hasNext()) { final ResourceTreeFolder folder = addFolder(parentFolder, directory.getFileName().toString()); iter.forEachRemaining((path) -> { - if (Files.isDirectory(path)) { + if (path.toFile().isDirectory()) { addDirectory(folder, path, overwrite); } else { folder.addResourceEntry(new FileResourceEntry(path), overwrite); diff --git a/src/org/infinity/resource/mus/Entry.java b/src/org/infinity/resource/mus/Entry.java index de04eff38..2266ec5d0 100644 --- a/src/org/infinity/resource/mus/Entry.java +++ b/src/org/infinity/resource/mus/Entry.java @@ -175,13 +175,13 @@ private AudioBuffer getAudioBuffer(String fileName) throws IOException { // audio file can reside in a number of different locations Path acmFile = FileManager.query(entry.getActualPath().getParent(), dir, dir + fileName + ".acm"); - if (!Files.isRegularFile(acmFile)) { + if (!acmFile.toFile().isFile()) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName + ".acm"); } - if (!Files.isRegularFile(acmFile) && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { + if (!acmFile.toFile().isFile() && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName.substring(0, 6), fileName + ".acm"); } - if (!Files.isRegularFile(acmFile)) { + if (!acmFile.toFile().isFile()) { throw new IOException("Could not find " + fileName); } diff --git a/src/org/infinity/resource/sav/IOHandler.java b/src/org/infinity/resource/sav/IOHandler.java index c92c1d8b3..89c1b8b6f 100644 --- a/src/org/infinity/resource/sav/IOHandler.java +++ b/src/org/infinity/resource/sav/IOHandler.java @@ -63,7 +63,7 @@ public void write(OutputStream os) throws IOException public void close() { - if (tempFolder != null && Files.isDirectory(tempFolder)) { + if (tempFolder != null && tempFolder.toFile().isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(tempFolder)) { for (final Path file: dstream) { try { @@ -128,7 +128,7 @@ private Path createTempFolder() { for (int idx = 0; idx < Integer.MAX_VALUE; idx++) { Path path = Profile.getHomeRoot().resolve(String.format("%s.%03d", entry.getTreeFolderName(), idx)); - if (!Files.exists(path)) { + if (!path.toFile().exists()) { return path; } } diff --git a/src/org/infinity/resource/sav/SavResource.java b/src/org/infinity/resource/sav/SavResource.java index ff345fdbf..c9b6a87ee 100644 --- a/src/org/infinity/resource/sav/SavResource.java +++ b/src/org/infinity/resource/sav/SavResource.java @@ -362,7 +362,7 @@ private void addResource(ResourceEntry resourceEntry) if (resourceEntry != null) { Path output = handler.getTempFolder().resolve(resourceEntry.getResourceName()); try { - if (Files.exists(output)) { + if (output.toFile().exists()) { String msg = "File " + resourceEntry.getResourceName() + " already exists. Overwrite?"; int ret = JOptionPane.showConfirmDialog(panel.getTopLevelAncestor(), msg, "Overwrite file?", JOptionPane.YES_NO_OPTION, @@ -410,7 +410,7 @@ private void removeResource(int entryIndex) if (entryIndex >= 0 && entryIndex < entries.size()) { ResourceEntry resourceEntry = entries.get(entryIndex); Path file = resourceEntry.getActualPath(); - if (Files.exists(file)) { + if (file.toFile().exists()) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/MveResource.java b/src/org/infinity/resource/video/MveResource.java index 98365b064..5aee61fba 100644 --- a/src/org/infinity/resource/video/MveResource.java +++ b/src/org/infinity/resource/video/MveResource.java @@ -476,7 +476,7 @@ AudioFormatKeys.SampleRateKey, new Rational(sampleRate), writer.close(); writer = null; } - if (Files.isRegularFile(outFile)) { + if (outFile.toFile().isFile()) { try { Files.delete(outFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/WbmResource.java b/src/org/infinity/resource/video/WbmResource.java index 5361c20cd..89e2cac4a 100644 --- a/src/org/infinity/resource/video/WbmResource.java +++ b/src/org/infinity/resource/video/WbmResource.java @@ -107,7 +107,7 @@ public void close() throws Exception { try { // first attempt to delete temporary video file - if (videoFile != null && Files.isRegularFile(videoFile) && isTempFile) { + if (videoFile != null && videoFile.toFile().isFile() && isTempFile) { Files.delete(videoFile); } } catch (Exception e) { @@ -173,7 +173,7 @@ private Path getVideoFile() fileExt = "wbm"; try { Path outFile = Files.createTempFile(fileBase + "-", "." + fileExt); - if (Files.isRegularFile(outFile)) { + if (outFile.toFile().isFile()) { try (InputStream is = entry.getResourceDataAsStream()) { try (OutputStream os = StreamUtils.getOutputStream(outFile, true)) { byte[] buffer = new byte[8192]; diff --git a/src/org/infinity/updater/Updater.java b/src/org/infinity/updater/Updater.java index 1dd8cec8e..3a5e49054 100644 --- a/src/org/infinity/updater/Updater.java +++ b/src/org/infinity/updater/Updater.java @@ -10,7 +10,6 @@ import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; -import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarFile; @@ -190,7 +189,7 @@ static String getJarFileHash() String path = Utils.getJarFileName(NearInfinity.class); if (path != null && !path.isEmpty()) { Path jarPath = FileManager.resolve(path); - if (Files.isRegularFile(jarPath)) { + if (jarPath.toFile().isFile()) { try { return Utils.generateMD5Hash(new FileInputStream(path)); } catch (IOException e) { diff --git a/src/org/infinity/updater/Utils.java b/src/org/infinity/updater/Utils.java index 4fae8ac40..553094796 100644 --- a/src/org/infinity/updater/Utils.java +++ b/src/org/infinity/updater/Utils.java @@ -23,7 +23,6 @@ import java.net.URLConnection; import java.net.UnknownServiceException; import java.nio.charset.Charset; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; @@ -87,7 +86,7 @@ public static String getJarFileName(Class classType) if (url != null) { try { Path file = Paths.get(url.toURI()); - if (Files.exists(file)) { + if (file.toFile().exists()) { return file.toString(); } } catch (URISyntaxException e) { diff --git a/src/org/infinity/util/FileDeletionHook.java b/src/org/infinity/util/FileDeletionHook.java index 7c0101772..d26f93af8 100644 --- a/src/org/infinity/util/FileDeletionHook.java +++ b/src/org/infinity/util/FileDeletionHook.java @@ -33,7 +33,7 @@ public void run() { synchronized (listFilesToDelete) { for (final Path file: listFilesToDelete) { - if (file != null && Files.exists(file)) { + if (file != null && file.toFile().exists()) { try { Files.delete(file); } catch (Throwable t) { diff --git a/src/org/infinity/util/MassExporter.java b/src/org/infinity/util/MassExporter.java index ac074ec2c..a22b44f99 100644 --- a/src/org/infinity/util/MassExporter.java +++ b/src/org/infinity/util/MassExporter.java @@ -386,7 +386,7 @@ private void exportText(ResourceEntry entry, Path output) throws Exception private void exportDecompiledScript(ResourceEntry entry, Path output) throws Exception { output = output.getParent().resolve(StreamUtils.replaceFileExtension(output.getFileName().toString(), "BAF")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } ByteBuffer bb = entry.getResourceBuffer(); @@ -434,7 +434,7 @@ private void mosToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("MOS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } @@ -459,7 +459,7 @@ private void pvrzToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("PVRZ")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } @@ -481,7 +481,7 @@ private void tisToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("TIS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } @@ -531,7 +531,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception // creating subfolder for frames Path path = filePath.resolve(fileBase); - if (!Files.exists(path)) { + if (!path.toFile().exists()) { try { Files.createDirectory(path); } catch (IOException e) { @@ -541,7 +541,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception JOptionPane.showMessageDialog(NearInfinity.getInstance(), msg, "Error", JOptionPane.ERROR_MESSAGE); return; } - } else if (!Files.isDirectory(path)) { + } else if (!path.toFile().isDirectory()) { String msg = String.format("Folder \"%s\" can not be created. Skipping file \"%s\".", fileBase, fileName); System.err.println(msg); @@ -557,7 +557,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception private void chrToCre(ResourceEntry entry, Path output) throws Exception { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "CRE")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } CreResource crefile = new CreResource(entry); @@ -612,7 +612,7 @@ private void export(ResourceEntry entry) { try { Path output = outputPath.resolve(entry.getResourceName()); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } if ((entry.getExtension().equalsIgnoreCase("IDS") || @@ -658,7 +658,7 @@ else if (entry.getExtension().equalsIgnoreCase("WAV") && cbConvertWAV.isSelected } else if (entry.getExtension().equalsIgnoreCase("MVE") && cbExportMVEasAVI.isSelected()) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "avi")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (output.toFile().exists() && !cbOverwrite.isSelected()) { return; } MveResource.convertAvi(entry, output, null, true); diff --git a/src/org/infinity/util/StringTable.java b/src/org/infinity/util/StringTable.java index b23968bde..e69099815 100644 --- a/src/org/infinity/util/StringTable.java +++ b/src/org/infinity/util/StringTable.java @@ -1341,11 +1341,11 @@ private void _write(Path tlkPath, ProgressCallback callback) throws IOException // 1. backing up current string table file if needed Path pathBackup = null; - if (Files.isRegularFile(tlkPath)) { + if (tlkPath.toFile().isFile()) { String name = tlkPath.getFileName().toString(); for (int i = 0; i < 999; i++) { Path path = tlkPath.getParent().resolve(name + "-" + i); - if (!Files.exists(path)) { + if (!path.toFile().exists()) { pathBackup = path; break; } diff --git a/src/org/infinity/util/io/DlcManager.java b/src/org/infinity/util/io/DlcManager.java index 250cba146..562c1cf6b 100644 --- a/src/org/infinity/util/io/DlcManager.java +++ b/src/org/infinity/util/io/DlcManager.java @@ -90,7 +90,7 @@ private FileSystem _register(Path dlcFile) throws IOException private FileSystem _getDlc(Path dlcFile) { - if (dlcFile != null && Files.isRegularFile(dlcFile)) { + if (dlcFile != null && dlcFile.toFile().isFile()) { return fileSystems.get(dlcFile); } return null; @@ -107,7 +107,7 @@ private Path _queryKey(Path path) if (fs != null) { for (final String keyFile: KEY_FILES) { Path key = fs.getPath(keyFile); - if (key != null && Files.isRegularFile(key)) { + if (key != null && key.toFile().isFile()) { try (InputStream is = StreamUtils.getInputStream(key)) { String sig = StreamUtils.readString(is, 8); if ("KEY V1 ".equals(sig)) { @@ -126,7 +126,7 @@ private Path _queryKey(Path path) private FileSystem _validateDlc(Path dlcFile) throws IOException { - if (dlcFile == null || !Files.isRegularFile(dlcFile)) { + if (dlcFile == null || !dlcFile.toFile().isFile()) { return null; } diff --git a/src/org/infinity/util/io/FileManager.java b/src/org/infinity/util/io/FileManager.java index 25f520dc5..5476f22e1 100644 --- a/src/org/infinity/util/io/FileManager.java +++ b/src/org/infinity/util/io/FileManager.java @@ -430,7 +430,7 @@ private Path _queryPath(boolean mustExist, Path rootFilter, List rootPaths } } else { curPath = _resolve(curRoot.resolve(relPath)); - if (curPath != null && Files.exists(curPath)) { + if (curPath != null && curPath.toFile().exists()) { exists = true; break; } @@ -460,7 +460,7 @@ private void close() public void fileChanged(FileWatchEvent e) { if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - if (Files.isDirectory(e.getPath())) { + if (e.getPath().toFile().isDirectory()) { // load whole directory into cache _cacheDirectory(e.getPath(), true); } else { @@ -566,7 +566,7 @@ private static Path _resolveExisting(Path path) retVal = null; } } -// if (retVal != null && !Files.exists(retVal)) { +// if (retVal != null && !retVal.toFile().exists()) { // retVal = null; // } return retVal; @@ -575,7 +575,7 @@ private static Path _resolveExisting(Path path) private static HashSet _cacheDirectory(Path path, boolean force) { HashSet retVal = null; - if (path != null && Files.isDirectory(path)) { + if (path != null && path.toFile().isDirectory()) { if (force) { pathCache.remove(path); } diff --git a/src/org/infinity/util/io/FileWatcher.java b/src/org/infinity/util/io/FileWatcher.java index 8f0f18c6a..5a5970272 100644 --- a/src/org/infinity/util/io/FileWatcher.java +++ b/src/org/infinity/util/io/FileWatcher.java @@ -177,7 +177,7 @@ public void register(Path dir, boolean recursive) public void register(Path dir, boolean recursive, boolean notifyCreate, boolean notifyDelete, boolean notifyModify) { dir = FileManager.resolve(dir); - if (dir != null && Files.isDirectory(dir)) { + if (dir != null && dir.toFile().isDirectory()) { if (recursive) { try { Files.walkFileTree(dir, new SimpleFileVisitor() { diff --git a/src/org/infinity/util/io/StreamUtils.java b/src/org/infinity/util/io/StreamUtils.java index 5c44b99ca..e990611c7 100644 --- a/src/org/infinity/util/io/StreamUtils.java +++ b/src/org/infinity/util/io/StreamUtils.java @@ -800,7 +800,7 @@ public static void createZip(Path sourceDir, Path zipFile, boolean includeFolder try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile))) { Path baseDir = includeFolder ? sourceDir.getParent() : sourceDir; Files.walk(sourceDir) - .filter(path -> !Files.isDirectory(path)) + .filter(path -> !path.toFile().isDirectory()) .forEach(path -> { ZipEntry ze = new ZipEntry(baseDir.relativize(path).toString()); try { diff --git a/src/org/infinity/util/io/zip/DlcFileSystem.java b/src/org/infinity/util/io/zip/DlcFileSystem.java index 01e839336..c540f2f7d 100644 --- a/src/org/infinity/util/io/zip/DlcFileSystem.java +++ b/src/org/infinity/util/io/zip/DlcFileSystem.java @@ -101,7 +101,7 @@ public class DlcFileSystem extends FileSystem this.readOnly = true; this.provider = provider; this.dfpath = dfpath; - if (Files.notExists(this.dfpath)) { + if (!this.dfpath.toFile().exists()) { throw new FileSystemNotFoundException(this.dfpath.toString()); } this.dfpath.getFileSystem().provider().checkAccess(this.dfpath, AccessMode.READ); From 9b38adc0dfeb141862eba70421e4bd4c1a94cf57 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 23 Aug 2020 12:45:20 +0200 Subject: [PATCH 07/14] Various minor optimizations --- src/org/infinity/check/StringUseChecker.java | 2 +- src/org/infinity/datatype/Song2daBitmap.java | 2 +- src/org/infinity/datatype/TextBitmap.java | 6 +++--- src/org/infinity/gui/DebugConsole.java | 6 ++++-- src/org/infinity/gui/NewResSettings.java | 2 +- .../infinity/gui/converter/ConvertToBam.java | 11 +++++----- src/org/infinity/resource/bcs/ScriptInfo.java | 6 +++--- .../infinity/resource/cre/CreResource.java | 2 +- src/org/infinity/resource/key/BIFFWriter.java | 21 +++++++++++-------- .../infinity/search/advanced/FilterInput.java | 11 ++++++---- src/org/infinity/util/CreMapCache.java | 2 +- src/org/infinity/util/IdsMapCache.java | 2 +- 12 files changed, 41 insertions(+), 32 deletions(-) diff --git a/src/org/infinity/check/StringUseChecker.java b/src/org/infinity/check/StringUseChecker.java index 12de0faeb..6f1b95510 100644 --- a/src/org/infinity/check/StringUseChecker.java +++ b/src/org/infinity/check/StringUseChecker.java @@ -333,7 +333,7 @@ public Object getObjectAt(int columnIndex) @Override public String toString() { - return "StringRef: " + strRef + " /* " + string.replaceAll("\r\n", Misc.LINE_SEPARATOR) + " */"; + return "StringRef: " + strRef + " /* " + string.replace("\r\n", Misc.LINE_SEPARATOR) + " */"; } } } diff --git a/src/org/infinity/datatype/Song2daBitmap.java b/src/org/infinity/datatype/Song2daBitmap.java index d0bd3ce19..ed1afcef5 100644 --- a/src/org/infinity/datatype/Song2daBitmap.java +++ b/src/org/infinity/datatype/Song2daBitmap.java @@ -107,7 +107,7 @@ private static List createSongList_MUSIC(List searchDirs) String name = e.getSymbol(); long key = e.getID(); name = Character.toUpperCase(name.charAt(0)) + name.substring(1); - String ref = name.replaceAll("_", "").toUpperCase(Locale.ENGLISH) + ".MUS"; + String ref = name.replace("_", "").toUpperCase(Locale.ENGLISH) + ".MUS"; if (key == 0L) { ref = name; } diff --git a/src/org/infinity/datatype/TextBitmap.java b/src/org/infinity/datatype/TextBitmap.java index 543ceb634..5bbcd28d6 100644 --- a/src/org/infinity/datatype/TextBitmap.java +++ b/src/org/infinity/datatype/TextBitmap.java @@ -55,9 +55,9 @@ public TextBitmap(ByteBuffer buffer, int offset, int length, String name, Map entry : items.entrySet()) { + this.ids[idx] = entry.getKey(); + this.names[idx] = entry.getValue(); idx++; } } else { diff --git a/src/org/infinity/gui/DebugConsole.java b/src/org/infinity/gui/DebugConsole.java index 9cd32a5bf..9126a5215 100644 --- a/src/org/infinity/gui/DebugConsole.java +++ b/src/org/infinity/gui/DebugConsole.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Map; import java.util.Properties; import javax.swing.JButton; @@ -90,8 +91,9 @@ else if (event.getSource() == bSaveConsole) { bw.write(NearInfinity.getConsoleText().getText()); bw.newLine(); bw.newLine(); Properties props = System.getProperties(); - for (Object key : props.keySet()) { - bw.write(key + "=" + props.get(key)); bw.newLine(); + for (Map.Entry entry : props.entrySet()) { + bw.write(entry.getKey() + "=" + entry.getValue()); + bw.newLine(); } JOptionPane.showMessageDialog(this, "Console saved to " + output, "Save complete", JOptionPane.INFORMATION_MESSAGE); diff --git a/src/org/infinity/gui/NewResSettings.java b/src/org/infinity/gui/NewResSettings.java index f3f74937c..06599d985 100644 --- a/src/org/infinity/gui/NewResSettings.java +++ b/src/org/infinity/gui/NewResSettings.java @@ -293,7 +293,7 @@ public String getText() private void setText(String newText) { if (newText != null) - desc = newText.replaceAll("\r", ""); // not sure if CR is supported + desc = newText.replace("\r", ""); // not sure if CR is supported else desc = ""; } diff --git a/src/org/infinity/gui/converter/ConvertToBam.java b/src/org/infinity/gui/converter/ConvertToBam.java index c49fd8a05..09a478ba1 100644 --- a/src/org/infinity/gui/converter/ConvertToBam.java +++ b/src/org/infinity/gui/converter/ConvertToBam.java @@ -46,6 +46,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Vector; import javax.imageio.ImageIO; @@ -5477,8 +5478,8 @@ private boolean applyCycleData(boolean silent) throws Exception // post-processing int[][] cycleArray = new int[maxCycle + 1][]; - for (Integer idx : cycles.keySet()) { - cycleArray[idx] = cycles.get(idx); + for (Map.Entry entry : cycles.entrySet()) { + cycleArray[entry.getKey()] = entry.getValue(); } bam.filterRemoveAll(); @@ -5549,13 +5550,13 @@ public Config() {} // post-processing data Config[] configArray = new Config[maxIndex + 1]; - for (Integer idx : filterMap.keySet()) { - Config config = filterMap.get(idx); + for (Map.Entry entry : filterMap.entrySet()) { + final Config config = entry.getValue(); if (config.name != null) { if (config.param == null) { config.param = ""; } - configArray[idx] = config; + configArray[entry.getKey()] = config; } } diff --git a/src/org/infinity/resource/bcs/ScriptInfo.java b/src/org/infinity/resource/bcs/ScriptInfo.java index 0d8179d19..fa289bf07 100644 --- a/src/org/infinity/resource/bcs/ScriptInfo.java +++ b/src/org/infinity/resource/bcs/ScriptInfo.java @@ -508,10 +508,10 @@ protected ScriptInfo(ScriptInfo obj, String[] objectSpecifierIds) this((objectSpecifierIds != null) ? objectSpecifierIds : obj.OBJECT_SPECIFIER_IDS, obj.SCOPES); this.FUNCTION_RESTYPE.putAll(obj.FUNCTION_RESTYPE); this.FUNCTION_CONCAT.putAll(obj.FUNCTION_CONCAT); - for (final Function.FunctionType ft: obj.FUNCTION_SIGNATURES.keySet()) { - List oldList = obj.FUNCTION_SIGNATURES.get(ft); + for (final Map.Entry> entry : obj.FUNCTION_SIGNATURES.entrySet()) { + List oldList = entry.getValue(); if (oldList != null) { - this.FUNCTION_SIGNATURES.put(ft, new ArrayList(oldList)); + this.FUNCTION_SIGNATURES.put(entry.getKey(), new ArrayList(oldList)); } } this.FUNCTION_PARAM_COMMENT.putAll(obj.FUNCTION_PARAM_COMMENT); diff --git a/src/org/infinity/resource/cre/CreResource.java b/src/org/infinity/resource/cre/CreResource.java index 8773c4f35..7bc163a93 100644 --- a/src/org/infinity/resource/cre/CreResource.java +++ b/src/org/infinity/resource/cre/CreResource.java @@ -555,7 +555,7 @@ public static void addScriptName(Map> scriptNames, // Apparently script name is the only thing that matters // scriptName = entry.toString().substring(0, entry.toString().length() - 4); } else { - scriptName = scriptName.toLowerCase(Locale.ENGLISH).replaceAll(" ", ""); + scriptName = scriptName.toLowerCase(Locale.ENGLISH).replace(" ", ""); if (scriptNames.containsKey(scriptName)) { synchronized (scriptNames) { Set entries = scriptNames.get(scriptName); diff --git a/src/org/infinity/resource/key/BIFFWriter.java b/src/org/infinity/resource/key/BIFFWriter.java index d2acbf8b0..fb900d872 100644 --- a/src/org/infinity/resource/key/BIFFWriter.java +++ b/src/org/infinity/resource/key/BIFFWriter.java @@ -201,11 +201,12 @@ private void writeBIFF(Path file) throws Exception StreamUtils.writeInt(os, 0x14); int offset = 20 + 16 * resources.size() + 20 * tileResources.size(); int index = 0; // Non-tileset index starts at 0 - for (final ResourceEntry resourceEntry : resources.keySet()) { + for (final Map.Entry entry : resources.entrySet()) { + final ResourceEntry resourceEntry = entry.getKey(); BIFFResourceEntry newentry = reloadNode(resourceEntry, index); StreamUtils.writeInt(os, newentry.getLocator()); StreamUtils.writeInt(os, offset); // Offset - int info[] = resourceEntry.getResourceInfo(resources.get(resourceEntry).booleanValue()); + int info[] = resourceEntry.getResourceInfo(entry.getValue().booleanValue()); offset += info[0]; StreamUtils.writeInt(os, info[0]); // Size StreamUtils.writeShort(os, (short)ResourceFactory.getKeyfile().getExtensionType(resourceEntry.getExtension())); @@ -213,11 +214,12 @@ private void writeBIFF(Path file) throws Exception index++; } index = 1; // Tileset index starts at 1 - for (final ResourceEntry resourceEntry : tileResources.keySet()) { + for (final Map.Entry entry : tileResources.entrySet()) { + final ResourceEntry resourceEntry = entry.getKey(); BIFFResourceEntry newentry = reloadNode(resourceEntry, index); StreamUtils.writeInt(os, newentry.getLocator()); StreamUtils.writeInt(os, offset); // Offset - int info[] = resourceEntry.getResourceInfo(tileResources.get(resourceEntry).booleanValue()); + int info[] = resourceEntry.getResourceInfo(entry.getValue().booleanValue()); StreamUtils.writeInt(os, info[0]); // Number of tiles StreamUtils.writeInt(os, info[1]); // Size of each tile (in bytes) offset += info[0] * info[1]; @@ -225,12 +227,13 @@ private void writeBIFF(Path file) throws Exception StreamUtils.writeShort(os, (short)0); // Unknown index++; } - for (final ResourceEntry resourceEntry : resources.keySet()) { - StreamUtils.writeBytes(os, resourceEntry.getResourceBuffer(resources.get(resourceEntry).booleanValue())); + for (final Map.Entry entry : resources.entrySet()) { + StreamUtils.writeBytes(os, entry.getKey().getResourceBuffer(entry.getValue().booleanValue())); } - for (final ResourceEntry resourceEntry : tileResources.keySet()) { - ByteBuffer buffer = resourceEntry.getResourceBuffer(tileResources.get(resourceEntry).booleanValue()); - int info[] = resourceEntry.getResourceInfo(tileResources.get(resourceEntry).booleanValue()); + for (final Map.Entry entry : tileResources.entrySet()) { + final ResourceEntry resourceEntry = entry.getKey(); + ByteBuffer buffer = resourceEntry.getResourceBuffer(entry.getValue().booleanValue()); + int info[] = resourceEntry.getResourceInfo(entry.getValue().booleanValue()); int size = info[0]*info[1]; int toSkip = buffer.limit() - size; if (toSkip > 0) { diff --git a/src/org/infinity/search/advanced/FilterInput.java b/src/org/infinity/search/advanced/FilterInput.java index a6e8e7fad..24e04b6c4 100644 --- a/src/org/infinity/search/advanced/FilterInput.java +++ b/src/org/infinity/search/advanced/FilterInput.java @@ -23,6 +23,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Vector; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -1052,8 +1053,9 @@ public void mousePressed(MouseEvent event) if (event.getSource() instanceof JFormattedTextField) { if (event.isPopupTrigger()) { // find popup menu associated with formatted text field and display it - for (final JPopupMenu menu : menuToTextFieldMap.keySet()) { - JFormattedTextField ftf = menuToTextFieldMap.get(menu); + for (final Map.Entry entry : menuToTextFieldMap.entrySet()) { + final JPopupMenu menu = entry.getKey(); + final JFormattedTextField ftf = entry.getValue(); if (ftf == event.getSource()) { if (!menu.isVisible()) menu.show(ftf, event.getX(), event.getY()); @@ -1070,8 +1072,9 @@ public void mouseReleased(MouseEvent event) if (event.getSource() instanceof JFormattedTextField) { if (event.isPopupTrigger()) { // find popup menu associated with formatted text field and display it - for (final JPopupMenu menu : menuToTextFieldMap.keySet()) { - JFormattedTextField ftf = menuToTextFieldMap.get(menu); + for (final Map.Entry entry : menuToTextFieldMap.entrySet()) { + final JPopupMenu menu = entry.getKey(); + final JFormattedTextField ftf = entry.getValue(); if (ftf == event.getSource()) { if (!menu.isVisible()) menu.show(ftf, event.getX(), event.getY()); diff --git a/src/org/infinity/util/CreMapCache.java b/src/org/infinity/util/CreMapCache.java index 40be1a893..d7b8b1595 100644 --- a/src/org/infinity/util/CreMapCache.java +++ b/src/org/infinity/util/CreMapCache.java @@ -131,7 +131,7 @@ private static boolean ensureInitialized(int timeOutMS) private static String normalized(String s) { if (s != null) { - return s.replaceAll(" ", "").toLowerCase(Locale.ENGLISH); + return s.replace(" ", "").toLowerCase(Locale.ENGLISH); } else { return ""; } diff --git a/src/org/infinity/util/IdsMapCache.java b/src/org/infinity/util/IdsMapCache.java index 23bcca575..21641e4cb 100644 --- a/src/org/infinity/util/IdsMapCache.java +++ b/src/org/infinity/util/IdsMapCache.java @@ -254,7 +254,7 @@ private static String prettifyName(String name) if (name == null || name.trim().isEmpty()) { return name; } - String retVal = name.replaceAll("_", " ").toLowerCase(Locale.ENGLISH); + String retVal = name.replace("_", " ").toLowerCase(Locale.ENGLISH); retVal = Character.toUpperCase(retVal.charAt(0)) + retVal.substring(1); return retVal; } From b4fb3fb00c61fe51326a8fb3eb1c9bd441a799da Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 23 Aug 2020 14:01:07 +0200 Subject: [PATCH 08/14] Revert "Improve performance for various I/O-based check operations" This reverts commit 36d206337861f5c26b83546c589fb9e62e889fe4. Reason: No support for virtual filesystems --- src/org/infinity/NearInfinity.java | 17 +-- src/org/infinity/gui/BIFFEditor.java | 2 +- src/org/infinity/gui/BcsDropFrame.java | 4 +- src/org/infinity/gui/BrowserMenuBar.java | 9 +- src/org/infinity/gui/DebugConsole.java | 2 +- src/org/infinity/gui/GameProperties.java | 3 +- src/org/infinity/gui/OpenFileFrame.java | 3 +- src/org/infinity/gui/ResourceTree.java | 16 +-- src/org/infinity/gui/SortableTable.java | 2 +- src/org/infinity/gui/StringEditor.java | 3 +- .../gui/converter/BamFilterColorReplace.java | 3 +- .../gui/converter/BamOptionsDialog.java | 9 +- .../gui/converter/BamPaletteDialog.java | 3 +- .../infinity/gui/converter/ConvertToBam.java | 16 +-- .../infinity/gui/converter/ConvertToBmp.java | 8 +- .../infinity/gui/converter/ConvertToMos.java | 7 +- .../infinity/gui/converter/ConvertToPvrz.java | 8 +- .../infinity/gui/converter/ConvertToTis.java | 11 +- .../infinity/gui/hexview/StructHexViewer.java | 8 +- src/org/infinity/resource/Profile.java | 130 +++++++++--------- .../infinity/resource/ResourceFactory.java | 58 ++++---- .../infinity/resource/StructureFactory.java | 7 +- .../are/viewer/LayerObjectAutomap.java | 5 +- .../resource/graphics/BamV2Decoder.java | 3 +- .../resource/graphics/ColorConvert.java | 10 +- .../resource/graphics/TisResource.java | 12 +- src/org/infinity/resource/key/BIFFEntry.java | 5 +- .../resource/key/BIFFResourceEntry.java | 16 +-- src/org/infinity/resource/key/BIFFWriter.java | 12 +- src/org/infinity/resource/key/Keyfile.java | 10 +- .../infinity/resource/key/ResourceEntry.java | 2 +- .../resource/key/ResourceTreeModel.java | 2 +- src/org/infinity/resource/mus/Entry.java | 6 +- src/org/infinity/resource/sav/IOHandler.java | 4 +- .../infinity/resource/sav/SavResource.java | 4 +- .../infinity/resource/video/MveResource.java | 2 +- .../infinity/resource/video/WbmResource.java | 4 +- src/org/infinity/updater/Updater.java | 3 +- src/org/infinity/updater/Utils.java | 3 +- src/org/infinity/util/FileDeletionHook.java | 2 +- src/org/infinity/util/MassExporter.java | 18 +-- src/org/infinity/util/StringTable.java | 4 +- src/org/infinity/util/io/DlcManager.java | 6 +- src/org/infinity/util/io/FileManager.java | 8 +- src/org/infinity/util/io/FileWatcher.java | 2 +- src/org/infinity/util/io/StreamUtils.java | 2 +- .../infinity/util/io/zip/DlcFileSystem.java | 2 +- 47 files changed, 246 insertions(+), 230 deletions(-) diff --git a/src/org/infinity/NearInfinity.java b/src/org/infinity/NearInfinity.java index 7509fb9bd..84120fe5a 100644 --- a/src/org/infinity/NearInfinity.java +++ b/src/org/infinity/NearInfinity.java @@ -30,6 +30,7 @@ import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; @@ -246,10 +247,10 @@ public static void main(String args[]) } else { // Override game folder via application parameter Path f = FileManager.resolve(args[idx]); - if (f.toFile().isFile()) { + if (Files.isRegularFile(f)) { f = f.getParent(); } - if (f.toFile().isDirectory()) { + if (Files.isDirectory(f)) { gameOverride = f; break; } @@ -303,7 +304,7 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) setJMenuBar(menu); final String lastDir; - if (gameOverride != null && gameOverride.toFile().isDirectory()) { + if (gameOverride != null && Files.isDirectory(gameOverride)) { lastDir = gameOverride.toString(); } else { lastDir = prefs.get(LAST_GAMEDIR, null); @@ -311,9 +312,9 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) final Path keyFile; Path path; - if ((path = FileManager.resolve(KEYFILENAME)).toFile().isFile()) { + if (Files.isRegularFile(path = FileManager.resolve(KEYFILENAME))) { keyFile = path; - } else if (lastDir != null && (path = FileManager.resolve(lastDir, KEYFILENAME)).toFile().isFile()) { + } else if (lastDir != null && Files.isRegularFile(path = FileManager.resolve(lastDir, KEYFILENAME))) { keyFile = path; } else { keyFile = findKeyfile(); @@ -773,7 +774,7 @@ public boolean editGameIni(Component parent) boolean retVal = false; Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); try { - if (iniFile != null && iniFile.toFile().isFile()) { + if (iniFile != null && Files.isRegularFile(iniFile)) { new ViewFrame(parent, new PlainTextResource(new FileResourceEntry(iniFile))); } else { throw new Exception(); @@ -1108,7 +1109,7 @@ public void drop(DropTargetDropEvent event) event.dropComplete(true); if (files != null && files.size() == 1) { Path path = files.get(0).toPath(); - if (path != null && path.toFile().isFile() && + if (path != null && Files.isRegularFile(path) && path.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".KEY")) { Path curFile = Profile.getChitinKey(); if (!path.equals(curFile)) { @@ -1132,7 +1133,7 @@ public void run() if (files != null) { files.forEach((file) -> { Path path = file.toPath(); - if (path.toFile().isFile()) { + if (Files.isRegularFile(path)) { OpenFileFrame.openExternalFile(NearInfinity.getInstance(), path); } }); diff --git a/src/org/infinity/gui/BIFFEditor.java b/src/org/infinity/gui/BIFFEditor.java index b46ca0211..27b4cf8e4 100644 --- a/src/org/infinity/gui/BIFFEditor.java +++ b/src/org/infinity/gui/BIFFEditor.java @@ -166,7 +166,7 @@ public void run() for (final ResourceEntry entry : tobif) { Path file = FileManager.query(Profile.getRootFolders(), Profile.getOverrideFolderName(), entry.getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/gui/BcsDropFrame.java b/src/org/infinity/gui/BcsDropFrame.java index 931e3345b..6ca39c99c 100644 --- a/src/org/infinity/gui/BcsDropFrame.java +++ b/src/org/infinity/gui/BcsDropFrame.java @@ -324,7 +324,7 @@ private void filesDropped(Component component, List files) if (component == compZone) { for (File f : files) { Path file = f.toPath(); - if (file.toFile().isDirectory()) { + if (Files.isDirectory(file)) { try (DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); @@ -356,7 +356,7 @@ else if (file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BA else if (component == decompZone) { for (File f : files) { final Path file = f.toPath(); - if (file.toFile().isDirectory()) { + if (Files.isDirectory(file)) { try (final DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index bc130f897..c18d64d3b 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -26,6 +26,7 @@ import java.awt.event.WindowEvent; import java.io.IOException; import java.nio.charset.Charset; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -1049,7 +1050,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(bookmarkList.get(selected).getPath()); - if (!keyFile.toFile().isFile()) { + if (!Files.isRegularFile(keyFile)) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), bookmarkList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -1068,7 +1069,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(recentList.get(selected).getPath()); - if (!keyFile.toFile().isFile()) { + if (!Files.isRegularFile(keyFile)) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), recentList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -3557,7 +3558,7 @@ public String setName(String newName) public JMenuItem getMenuItem() { return item; } /** Returns whether the bookmark points to an existing game installation. */ - public boolean isEnabled() { return (FileManager.resolve(path).toFile().isFile()); } + public boolean isEnabled() { return (Files.isRegularFile(FileManager.resolve(path))); } /** Returns ActionListener used by the associated menu item. */ public ActionListener getActionListener() { return listener; } @@ -3653,7 +3654,7 @@ static final class RecentGame implements Cloneable public RecentGame(Profile.Game game, String path, int index, ActionListener listener) { if (game == null || game == Profile.Game.Unknown || - path == null || !FileManager.resolve(path).toFile().isFile()) { + path == null || !Files.isRegularFile(FileManager.resolve(path))) { throw new NullPointerException(); } this.game = game; diff --git a/src/org/infinity/gui/DebugConsole.java b/src/org/infinity/gui/DebugConsole.java index 9126a5215..8e93f8d7d 100644 --- a/src/org/infinity/gui/DebugConsole.java +++ b/src/org/infinity/gui/DebugConsole.java @@ -77,7 +77,7 @@ else if (event.getSource() == bSaveConsole) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "nidebuglog.txt")); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { Path output = chooser.getSelectedFile().toPath(); - if (output.toFile().exists()) { + if (Files.exists(output)) { 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) diff --git a/src/org/infinity/gui/GameProperties.java b/src/org/infinity/gui/GameProperties.java index 8cc03fe75..0f181ac1b 100644 --- a/src/org/infinity/gui/GameProperties.java +++ b/src/org/infinity/gui/GameProperties.java @@ -18,6 +18,7 @@ import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -248,7 +249,7 @@ private void init() pIni.add(tf, gbc); bEdit.setMargin(new Insets(2, 4, 2, 4)); bEdit.addActionListener(this); - bEdit.setEnabled(iniFile != null && iniFile.toFile().isFile()); + bEdit.setEnabled(iniFile != null && Files.isRegularFile(iniFile)); gbc = ViewerUtil.setGBC(gbc, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0, 4, 0, 0), 0, 0); pIni.add(bEdit, gbc); diff --git a/src/org/infinity/gui/OpenFileFrame.java b/src/org/infinity/gui/OpenFileFrame.java index de1435c3a..3e1763e06 100644 --- a/src/org/infinity/gui/OpenFileFrame.java +++ b/src/org/infinity/gui/OpenFileFrame.java @@ -22,6 +22,7 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -239,7 +240,7 @@ else if (event.getSource() == bOpenNew) { /** Attempts to open the specified external game resource. */ public static void openExternalFile(Component parent, Path file) { - if (file != null && !file.toFile().exists()) { + if (!Files.exists(file)) { JOptionPane.showMessageDialog(parent, '\"' + file.toString() + "\" not found", "Error", JOptionPane.ERROR_MESSAGE); } else { diff --git a/src/org/infinity/gui/ResourceTree.java b/src/org/infinity/gui/ResourceTree.java index b1d68751a..e671b887e 100644 --- a/src/org/infinity/gui/ResourceTree.java +++ b/src/org/infinity/gui/ResourceTree.java @@ -264,8 +264,8 @@ static void renameResource(FileResourceEntry entry) if (!filename.contains(".")) { filename = filename + '.' + entry.getExtension(); } - if (entry.getActualPath().getParent().resolve(filename).toFile().exists() && - JOptionPane.showConfirmDialog(NearInfinity.getInstance(), + if (Files.exists(entry.getActualPath().getParent().resolve(filename)) + && JOptionPane.showConfirmDialog(NearInfinity.getInstance(), "File with name \"" + filename + "\" already exists! Overwrite?", "Confirm overwrite " + filename, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.OK_OPTION @@ -360,8 +360,8 @@ static void restoreResource(ResourceEntry entry) // .bak available -> restore .bak version Path curFile = getCurrentFile(entry); Path tmpFile = getTempFile(curFile); - if (curFile != null && curFile.toFile().isFile() && - bakFile != null && bakFile.toFile().isFile()) { + if (curFile != null && Files.isRegularFile(curFile) && + bakFile != null && Files.isRegularFile(bakFile)) { try { Files.move(curFile, tmpFile); try { @@ -415,7 +415,7 @@ static void restoreResource(ResourceEntry entry) static void createZipFile(Path path) { - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { JFileChooser fc = new JFileChooser(Profile.getGameRoot().toFile()); fc.setDialogTitle("Save as"); fc.setFileFilter(new FileNameExtensionFilter("Zip files (*.zip)", "zip")); @@ -484,7 +484,7 @@ private static Path getBackupFile(ResourceEntry entry) (entry instanceof BIFFResourceEntry && entry.hasOverride())) { if (file != null) { Path bakFile = file.getParent().resolve(file.getFileName().toString() + ".bak"); - if (bakFile.toFile().isFile()) { + if (Files.isRegularFile(bakFile)) { return bakFile; } } @@ -509,13 +509,13 @@ private static Path getCurrentFile(ResourceEntry entry) private static Path getTempFile(Path file) { Path retVal = null; - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { final String fmt = ".%03d"; Path filePath = file.getParent(); String fileName = file.getFileName().toString(); for (int i = 0; i < 1000; i++) { Path tmp = filePath.resolve(fileName + String.format(fmt, i)); - if (!tmp.toFile().exists()) { + if (!Files.exists(tmp) && Files.notExists(tmp)) { retVal = tmp; break; } diff --git a/src/org/infinity/gui/SortableTable.java b/src/org/infinity/gui/SortableTable.java index 96c3ae227..b9fb95ebd 100644 --- a/src/org/infinity/gui/SortableTable.java +++ b/src/org/infinity/gui/SortableTable.java @@ -107,7 +107,7 @@ private void saveResult(Component parent, String dialogTitle, String header) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "result.txt")); if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { final Path output = chooser.getSelectedFile().toPath(); - if (output.toFile().exists()) { + if (Files.exists(output)) { final String[] options = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, output + " exists. Overwrite?", dialogTitle, JOptionPane.YES_NO_OPTION, diff --git a/src/org/infinity/gui/StringEditor.java b/src/org/infinity/gui/StringEditor.java index 83222f0dc..e738b6780 100644 --- a/src/org/infinity/gui/StringEditor.java +++ b/src/org/infinity/gui/StringEditor.java @@ -14,6 +14,7 @@ import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Locale; @@ -731,7 +732,7 @@ private void save(boolean interactive) int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { outPath = fc.getSelectedFile().toPath(); - if (!outPath.toFile().isDirectory()) { + if (!Files.isDirectory(outPath)) { outPath = outPath.getParent(); } outFile = outPath.resolve(StringTable.getPath(StringTable.Type.MALE).getFileName().toString()); diff --git a/src/org/infinity/gui/converter/BamFilterColorReplace.java b/src/org/infinity/gui/converter/BamFilterColorReplace.java index f01a90423..c66b5ab75 100644 --- a/src/org/infinity/gui/converter/BamFilterColorReplace.java +++ b/src/org/infinity/gui/converter/BamFilterColorReplace.java @@ -21,6 +21,7 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; @@ -280,7 +281,7 @@ public int[] getPalette() /** Loads the palette from the specified file resource into the color grid component. */ public void loadPalette(Path paletteFile) throws Exception { - if (paletteFile != null && paletteFile.toFile().isFile()) { + if (paletteFile != null && Files.isRegularFile(paletteFile)) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/BamOptionsDialog.java b/src/org/infinity/gui/converter/BamOptionsDialog.java index 384c622f3..59f439a28 100644 --- a/src/org/infinity/gui/converter/BamOptionsDialog.java +++ b/src/org/infinity/gui/converter/BamOptionsDialog.java @@ -17,6 +17,7 @@ import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.io.IOError; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -160,7 +161,7 @@ private static void validateSettings() { bamVersion = Math.min(Math.max(bamVersion, ConvertToBam.VERSION_BAMV1), ConvertToBam.VERSION_BAMV2); if (path == null) path = DEFAULT_PATH; - if (!path.isEmpty() && !FileManager.resolve(path).toFile().isDirectory()) path = DEFAULT_PATH; + if (!path.isEmpty() && !(Files.isDirectory(FileManager.resolve(path)))) path = DEFAULT_PATH; transparencyThreshold = Math.min(Math.max(transparencyThreshold, 0), 100); useAlpha = Math.min(Math.max(useAlpha, ConvertToBam.ALPHA_AUTO), ConvertToBam.ALPHA_NEVER); @@ -248,7 +249,7 @@ private static void loadRecentSessions(Preferences prefs) value = value.trim(); if (!finished && !value.isEmpty()) { Path path = Paths.get(value); - if (path.toFile().isFile()) { + if (Files.isRegularFile(path)) { recentSessions.add(path); } } @@ -291,7 +292,7 @@ public void actionPerformed(ActionEvent event) { if (event.getSource() == miPathSet) { Path path = FileManager.resolve(tfPath.getText()); - if (!path.toFile().isDirectory()) { + if (!Files.isDirectory(path)) { path = Profile.getGameRoot(); } Path rootPath = ConvertToBam.getOpenPathName(this, "Select initial directory", path); @@ -334,7 +335,7 @@ public void focusLost(FocusEvent event) { if (event.getSource() == tfPath) { String path = tfPath.getText(); - if (!path.isEmpty() && !FileManager.resolve(path).toFile().isDirectory()) { + if (!path.isEmpty() && !Files.isDirectory(FileManager.resolve(path))) { tfPath.setText(path); } } diff --git a/src/org/infinity/gui/converter/BamPaletteDialog.java b/src/org/infinity/gui/converter/BamPaletteDialog.java index b6b3e5cab..37a54e5c4 100644 --- a/src/org/infinity/gui/converter/BamPaletteDialog.java +++ b/src/org/infinity/gui/converter/BamPaletteDialog.java @@ -20,6 +20,7 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; @@ -248,7 +249,7 @@ public void loadExternalPalette(int type, Path paletteFile) throws Exception } // fetching file signature - if (paletteFile != null && paletteFile.toFile().isFile()) { + if (paletteFile != null && Files.isRegularFile(paletteFile)) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/ConvertToBam.java b/src/org/infinity/gui/converter/ConvertToBam.java index 09a478ba1..eb7e2da6e 100644 --- a/src/org/infinity/gui/converter/ConvertToBam.java +++ b/src/org/infinity/gui/converter/ConvertToBam.java @@ -303,7 +303,7 @@ public static Path[] getOpenFileName(Component parent, String title, Path rootPa rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!rootPath.toFile().isDirectory()) { + if (!Files.isDirectory(rootPath)) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -370,7 +370,7 @@ public static Path getSaveFileName(Component parent, String title, Path rootPath rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!rootPath.toFile().isDirectory()) { + if (!Files.isDirectory(rootPath)) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -517,7 +517,7 @@ public void actionPerformed(ActionEvent event) do { file = setBamOutput(); if (file != null) { - if (!file.toFile().exists() || + if (!Files.exists(file) || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -2750,13 +2750,13 @@ public void framesAddFolder() public void framesAddFolder(Path path) { - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { // preparing list of valid files FileNameExtensionFilter filters = getGraphicsFilters()[0]; List validFiles = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { - if (file.toFile().isFile() && filters.accept(file.toFile())) { + if (Files.isRegularFile(file) && filters.accept(file.toFile())) { validFiles.add(file); } } @@ -5069,7 +5069,7 @@ public boolean importData(boolean silent) Path[] files = getOpenFileName(bam, "Import BAM session", null, false, new FileNameExtensionFilter[]{getIniFilter()}, 0); if (files != null && files.length > 0) { - if (!files[0].toFile().isFile()) { + if (!Files.isRegularFile(files[0])) { files[0] = StreamUtils.replaceFileExtension(files[0], "ini"); } if (loadData(files[0], silent)) { @@ -5190,7 +5190,7 @@ private boolean loadFrameData(IniMapSection frames) throws Exception } } else { Path file = FileManager.resolve(value); - if (!file.toFile().isFile()) { + if (!Files.isRegularFile(file)) { throw new Exception("Frame source path not found at line " + (entry.getLine() + 1)); } } @@ -5376,7 +5376,7 @@ public SourceData(Path image) } } else { Path file = FileManager.resolve(value); - if (file.toFile().isFile()) { + if (Files.isRegularFile(file)) { resource = new FileResourceEntry(file); } } diff --git a/src/org/infinity/gui/converter/ConvertToBmp.java b/src/org/infinity/gui/converter/ConvertToBmp.java index cc515a300..a02cbee78 100644 --- a/src/org/infinity/gui/converter/ConvertToBmp.java +++ b/src/org/infinity/gui/converter/ConvertToBmp.java @@ -98,7 +98,7 @@ private static Path[] getOpenFileName(Component parent, String title, Path rootP } Path file = FileManager.resolve(rootPath); JFileChooser fc = new JFileChooser(file.toFile()); - if (!file.toFile().isDirectory()) { + if (!Files.isDirectory(file)) { fc.setSelectedFile(file.toFile()); } if (title == null) { @@ -520,7 +520,7 @@ private void inputAddFolder() rootPath = FileManager.resolve(modelInputFiles.get(modelInputFiles.size() - 1)); } Path path = getOpenPathName(this, "Choose folder", rootPath); - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { // adding all files in the directory FileNameExtensionFilter[] filters = getGraphicsFilters(); List skippedFiles = new ArrayList(); @@ -528,7 +528,7 @@ private void inputAddFolder() try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { for (final FileNameExtensionFilter filter: filters) { - if (file.toFile().isFile() && filter.accept(file.toFile())) { + if (Files.isRegularFile(file) && filter.accept(file.toFile())) { if (isValidInput(file)) { modelInputFiles.addElement(file.toString()); idx++; @@ -633,7 +633,7 @@ private List convert() // 1. prepare data Path inFile = FileManager.resolve(modelInputFiles.get(i)); Path outFile = FileManager.resolve(outPath, StreamUtils.replaceFileExtension(inFile.getFileName().toString(), "BMP")); - if (outFile.toFile().exists()) { + if (Files.exists(outFile)) { if (cbOverwrite.getSelectedIndex() == 0) { // ask String msg = String.format("File %s already exists. Overwrite?", outFile.getFileName()); int ret = JOptionPane.showConfirmDialog(this, msg, "Overwrite?", JOptionPane.YES_NO_CANCEL_OPTION); diff --git a/src/org/infinity/gui/converter/ConvertToMos.java b/src/org/infinity/gui/converter/ConvertToMos.java index b0ceca03b..cc0777f62 100644 --- a/src/org/infinity/gui/converter/ConvertToMos.java +++ b/src/org/infinity/gui/converter/ConvertToMos.java @@ -24,6 +24,7 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -543,7 +544,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutputV2.getText()); } if (file != null) { - if (!file.toFile().exists() || + if (!Files.exists(file) || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -905,7 +906,7 @@ private boolean isReady() boolean ret = false; if (!tfInputV1.getText().isEmpty() && !tfOutputV1.getText().isEmpty()) { Path file = FileManager.resolve(tfInputV1.getText()); - ret = file.toFile().isFile(); + ret = Files.isRegularFile(file); } return ret; } @@ -974,7 +975,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(tfInputV1.getText()); - if (!inFile.toFile().isFile()) { + if (!Files.isRegularFile(inFile)) { result.add(null); result.add(String.format("Input file \"%s\" does not exist.", tfInputV1.getText())); return result; diff --git a/src/org/infinity/gui/converter/ConvertToPvrz.java b/src/org/infinity/gui/converter/ConvertToPvrz.java index 100321686..83dd116c1 100644 --- a/src/org/infinity/gui/converter/ConvertToPvrz.java +++ b/src/org/infinity/gui/converter/ConvertToPvrz.java @@ -480,7 +480,7 @@ private boolean isReady() // checks graphics input file properties private static boolean isValidGraphicsInput(Path inFile) { - boolean result = (inFile != null && inFile.toFile().isFile()); + boolean result = (inFile != null && Files.isRegularFile(inFile)); if (result) { Dimension d = ColorConvert.getImageDimension(inFile); if (d == null || d.width <= 0 || d.width > 1024 || d.height <= 0 || d.height > 1024) { @@ -493,7 +493,7 @@ private static boolean isValidGraphicsInput(Path inFile) // checks PVR input file properties private static boolean isValidPVRInput(Path inFile) { - boolean result = (inFile != null && inFile.toFile().isFile()); + boolean result = (inFile != null && Files.isRegularFile(inFile)); if (result) { try (InputStream is = StreamUtils.getInputStream(inFile)) { String sig = StreamUtils.readString(is, 4); @@ -540,7 +540,7 @@ private List convert() if (tfTargetDir.getText() != null && !tfTargetDir.getText().isEmpty()) { targetPath = FileManager.resolve(tfTargetDir.getText()); } - if (!targetPath.toFile().isDirectory()) { + if (!Files.isDirectory(targetPath)) { List l = new Vector(2); l.add(null); l.add("Invalid target directory specified. No conversion takes place."); @@ -594,7 +594,7 @@ private List convert() Path outFile = targetPath.resolve(outFileName); // handling overwrite existing file - if (outFile.toFile().exists()) { + if (Files.exists(outFile)) { if (skip) { skippedFiles++; continue; diff --git a/src/org/infinity/gui/converter/ConvertToTis.java b/src/org/infinity/gui/converter/ConvertToTis.java index 17047ea94..1115f78fa 100644 --- a/src/org/infinity/gui/converter/ConvertToTis.java +++ b/src/org/infinity/gui/converter/ConvertToTis.java @@ -24,6 +24,7 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -591,7 +592,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutput.getText()); } if (file != null) { - if (!file.toFile().exists() || + if (!Files.exists(file) || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -649,7 +650,7 @@ public List doInBackground() String fileName = tfOutput.getText(); if (fileName.isEmpty() && !tfInput.getText().isEmpty()) { Path f = FileManager.resolve(tfInput.getText()); - if (f.toFile().isFile()) { + if (Files.isRegularFile(f)) { fileName = createValidTisName(tfInput.getText(), getTisVersion()); } } @@ -975,7 +976,7 @@ private boolean isReady() boolean ret = false; if (!getInputFile().isEmpty()) { Path f = FileManager.resolve(getInputFile()); - ret = f.toFile().isFile(); + ret = Files.isRegularFile(f); } return ret; } @@ -1031,7 +1032,7 @@ private boolean validateInput(String inputFile) inFileName = inputFile; if (inFileName != null && !inFileName.isEmpty()) { Path f = FileManager.resolve(inFileName); - if (f.toFile().isFile()) { + if (Files.isRegularFile(f)) { Dimension dimImage = ColorConvert.getImageDimension(f); if (dimImage.width >= 0 && (dimImage.width % 64) == 0 && dimImage.height >= 0 && (dimImage.height % 64) == 0) { @@ -1071,7 +1072,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(inFileName); - if (!inFile.toFile().isFile()) { + if (!Files.isRegularFile(inFile)) { ret.add(null); ret.add(String.format("Input file \"%s\" does not exist.", inFileName)); return ret; diff --git a/src/org/infinity/gui/hexview/StructHexViewer.java b/src/org/infinity/gui/hexview/StructHexViewer.java index 8b2baf6e1..2adf7e0ce 100644 --- a/src/org/infinity/gui/hexview/StructHexViewer.java +++ b/src/org/infinity/gui/hexview/StructHexViewer.java @@ -263,7 +263,7 @@ public void actionPerformed(ActionEvent event) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!overridePath.toFile().isDirectory()) { + if (!Files.isDirectory(overridePath)) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -278,7 +278,7 @@ public void actionPerformed(ActionEvent event) } else { outPath = entry.getActualPath(); } - if (outPath.toFile().exists()) { + if (Files.exists(outPath)) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(this, outPath + " exists. Overwrite?", "Save resource", @@ -287,10 +287,10 @@ public void actionPerformed(ActionEvent event) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (bakPath.toFile().isFile()) { + if (Files.isRegularFile(bakPath)) { Files.delete(bakPath); } - if (!bakPath.toFile().exists()) { + if (!Files.exists(bakPath)) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/Profile.java b/src/org/infinity/resource/Profile.java index 5a844b1f8..759683be4 100644 --- a/src/org/infinity/resource/Profile.java +++ b/src/org/infinity/resource/Profile.java @@ -880,7 +880,7 @@ public static boolean updateGameLanguage(String language) // updating dialog.tlks updateProperty(Key.GET_GAME_DIALOG_FILE, FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME))); Path femaleTlkFile = FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (femaleTlkFile.toFile().isFile()) { + if (Files.isRegularFile(femaleTlkFile)) { addProperty(Key.GET_GAME_DIALOGF_FILE, Type.PATH, femaleTlkFile); } else { updateProperty(Key.GET_GAME_DIALOGF_FILE, null); @@ -1211,7 +1211,7 @@ private static String getLuaHomeFolderName(Game game) private static String getLuaValue(Path file, String key, String defaultValue, boolean ifLuaExists) { String retVal = ifLuaExists ? null : defaultValue; - if (file != null && file.toFile().isFile() && key != null && !key.trim().isEmpty()) { + if (file != null && Files.isRegularFile(file) && key != null && !key.trim().isEmpty()) { retVal = defaultValue; try (Stream lines = Files.lines(file, StandardCharsets.UTF_8)) { for (Iterator iter = lines.iterator(); iter.hasNext();) { @@ -1269,7 +1269,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception { if (keyFile == null) { throw new Exception("No chitin.key specified"); - } else if (!keyFile.toFile().isFile()) { + } else if (!Files.isRegularFile(keyFile)) { throw new Exception(keyFile.toString() + " does not exist"); } @@ -1296,7 +1296,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception if (home != null) { addEntry(Key.GET_GAME_HOME_FOLDER_NAME, Type.STRING, home); homeDir = ResourceFactory.getHomeRoot(true); - if (homeDir != null && homeDir.toFile().isDirectory()) { + if (homeDir != null && Files.isDirectory(homeDir)) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeDir); } } @@ -1327,85 +1327,85 @@ private void initGame() throws Exception } if (game == Game.IWDEE || - FileManager.query(gameRoots, "movies/howseer.wbm").toFile().isFile()) { + Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm"))) { if (game == null) game = Game.IWDEE; // Note: baldur.ini is initialized later } else if (game == Game.PSTEE || - (FileManager.query(gameRoots, "data/MrtGhost.bif").toFile().isFile() && - FileManager.query(gameRoots, "data/shaders.bif").toFile().isFile() && + (Files.isRegularFile(FileManager.query(gameRoots, "data/MrtGhost.bif")) && + Files.isRegularFile(FileManager.query(gameRoots, "data/shaders.bif")) && getLuaValue(FileManager.query(gameRoots, "engine.lua"), "engine_mode", "0", false).equals("3"))) { if (game == null) game = Game.PSTEE; // Note: baldur.ini is initialized later } else if (game == Game.EET || game == Game.BG2EE || - FileManager.query(gameRoots, "movies/pocketzz.wbm").toFile().isFile()) { - if ((FileManager.query(gameRoots, "override/EET.flag").toFile().isFile()) || - (FileManager.query(gameRoots, "data/eetTU00.bif").toFile().isFile())) { + Files.isRegularFile(FileManager.query(gameRoots, "movies/pocketzz.wbm"))) { + if ((Files.isRegularFile(FileManager.query(gameRoots, "override/EET.flag"))) || + (Files.isRegularFile(FileManager.query(gameRoots, "data/eetTU00.bif")))) { if (game == null) game = Game.EET; } else { if (game == null) game = Game.BG2EE; } // Note: baldur.ini is initialized later } else if (game == Game.BG1SoD || - FileManager.query(gameRoots, "movies/sodcin01.wbm").toFile().isFile()) { + Files.isRegularFile(FileManager.query(gameRoots, "movies/sodcin01.wbm"))) { if (game == null) game = Game.BG1SoD; // Note: baldur.ini is initialized later } else if (game == Game.BG1EE || - FileManager.query(gameRoots, "movies/bgenter.wbm").toFile().isFile()) { + Files.isRegularFile(FileManager.query(gameRoots, "movies/bgenter.wbm"))) { if (game == null) game = Game.BG1EE; // Note: baldur.ini is initialized later } else if ((game == Game.PST || - FileManager.query(gameRoots, "torment.exe").toFile().isFile()) && - (!FileManager.query(gameRoots, "movies/sigil.wbm").toFile().isFile())) { + Files.isRegularFile(FileManager.query(gameRoots, "torment.exe"))) && + (!Files.isRegularFile(FileManager.query(gameRoots, "movies/sigil.wbm")))) { if (game == null) game = Game.PST; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "torment.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD || game == Game.IWDHoW || game == Game.IWDHowTotLM || - (FileManager.query(gameRoots, "idmain.exe").toFile().isFile()) && - (!FileManager.query(gameRoots, "movies/howseer.wbm").toFile().isFile())) { + (Files.isRegularFile(FileManager.query(gameRoots, "idmain.exe"))) && + (!Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm")))) { if (game == null) game = Game.IWD; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD2 || - (FileManager.query(gameRoots, "iwd2.exe").toFile().isFile()) && - (FileManager.query(gameRoots, "Data/Credits.mve").toFile().isFile())) { + (Files.isRegularFile(FileManager.query(gameRoots, "iwd2.exe"))) && + (Files.isRegularFile(FileManager.query(gameRoots, "Data/Credits.mve")))) { if (game == null) game = Game.IWD2; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind2.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.Tutu || - FileManager.query(gameRoots, "bg1tutu.exe").toFile().isFile() || - FileManager.query(gameRoots, "bg1mov/MovieCD1.bif").toFile().isFile()) { + Files.isRegularFile(FileManager.query(gameRoots, "bg1tutu.exe")) || + Files.isRegularFile(FileManager.query(gameRoots, "bg1mov/MovieCD1.bif"))) { if (game == null) game = Game.Tutu; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG2SoA || game == Game.BG2ToB || game == Game.BGT || - (FileManager.query(gameRoots, "baldur.exe").toFile().isFile()) && - (FileManager.query(gameRoots, "BGConfig.exe").toFile().isFile())) { + (Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && + (Files.isRegularFile(FileManager.query(gameRoots, "BGConfig.exe")))) { if (game == null) game = Game.BG2SoA; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG1 || game == Game.BG1TotSC || - (FileManager.query(gameRoots, "movies/graphsim.mov").toFile().isFile()) || // Mac BG1 detection hack - ((FileManager.query(gameRoots, "baldur.exe").toFile().isFile()) && - (FileManager.query(gameRoots, "Config.exe").toFile().isFile()))) { + (Files.isRegularFile(FileManager.query(gameRoots, "movies/graphsim.mov"))) || // Mac BG1 detection hack + ((Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && + (Files.isRegularFile(FileManager.query(gameRoots, "Config.exe"))))) { if (game == null) game = Game.BG1; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else { @@ -1414,7 +1414,7 @@ private void initGame() throws Exception if (game == null) game = Game.Unknown; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } @@ -1431,7 +1431,7 @@ private void initGame() throws Exception if (isEnhancedEdition()) { Path langDir = FileManager.query(gameRoots, "lang"); - if (langDir != null && langDir.toFile().isDirectory()) { + if (langDir != null && Files.isDirectory(langDir)) { addEntry(Key.GET_GAME_LANG_FOLDER_BASE, Type.PATH, langDir); } } @@ -1456,11 +1456,11 @@ private void initGame() throws Exception // initializing dialog.tlk and dialogf.tlk Path tlk = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME)); - if (tlk != null && tlk.toFile().isFile()) { + if (tlk != null && Files.isRegularFile(tlk)) { addEntry(Key.GET_GAME_DIALOG_FILE, Type.PATH, tlk); } Path tlkf = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (tlkf != null && tlkf.toFile().isFile()) { + if (tlkf != null && Files.isRegularFile(tlkf)) { addEntry(Key.GET_GAME_DIALOGF_FILE, Type.PATH, tlkf); } @@ -1552,7 +1552,7 @@ private void initIniFile(String... iniFiles) Path homeRoot = ResourceFactory.getHomeRoot(false); for (int i = 0; i < iniFiles.length; i++) { Path ini = FileManager.query(homeRoot, iniFiles[i]); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_NAME, Type.STRING, iniFiles[i]); break; } @@ -1574,7 +1574,7 @@ private void initRootDirs() if (homeRoot != null) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeRoot); Path ini = FileManager.query(homeRoot, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && ini.toFile().isFile()) { + if (ini != null && Files.isRegularFile(ini)) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } listRoots.add(homeRoot); @@ -1594,7 +1594,7 @@ private void initRootDirs() roots.forEach((root) -> { // adding root of active language Path langRoot = FileManager.query(root, (String)getProperty(Key.GET_GLOBAL_LANG_NAME), language); - if (langRoot != null && langRoot.toFile().isDirectory()) { + if (langRoot != null && Files.isDirectory(langRoot)) { addEntry(Key.GET_GAME_LANG_FOLDER_NAME, Type.STRING, language); addEntry(Key.GET_GAME_LANG_FOLDER, Type.PATH, langRoot); List langPaths = ResourceFactory.getAvailableGameLanguages(); @@ -1607,7 +1607,7 @@ private void initRootDirs() // adding fallback language added if selected language is non-english Path langRootDef = FileManager.query((Path)getProperty(Key.GET_GAME_LANG_FOLDER_BASE), languageDef); - if (!languageDef.equals(language) && langRootDef != null && langRootDef.toFile().isDirectory()) { + if (!languageDef.equals(language) && langRootDef != null && Files.isDirectory(langRootDef)) { listRoots.add(langRootDef); } @@ -1630,7 +1630,7 @@ private void initExtraFolders() List list = new ArrayList<>(extraFolders.size()); extraFolders.forEach((folder) -> { Path path = FileManager.query(root, folder); - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { list.add(path); } }); @@ -1681,48 +1681,48 @@ private void initOverrides() // registering override paths for (final Path root: gameRoots) { Path path = FileManager.query(root, langFolder, "Movies"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Movies"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } } path = FileManager.query(root, "Movies"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, langFolder, "Sounds"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Sounds"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } } path = FileManager.query(root, langFolder, "Fonts"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, langFolder, "Override"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } } } else { Path root = getGameRoot(); Path path = FileManager.query(root, "Movies"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && path.toFile().isDirectory()) { list.add(path); } + if (path != null && Files.isDirectory(path)) { list.add(path); } } list.forEach((path) -> { FileWatcher.getInstance().register(path, false); }); @@ -1905,7 +1905,7 @@ private void initFeatures() // Has TobEx been installed? if (engine == Engine.BG2) { Path tobexIni = FileManager.query(getGameRoot(), "TobEx_ini/TobExCore.ini"); - addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, tobexIni.toFile().isFile()); + addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Files.isRegularFile(tobexIni)); } else { addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Boolean.FALSE); } @@ -1980,7 +1980,7 @@ private void initCampaigns() if (model != null) { List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); for (final Path path: extraDirs) { - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { String folderName = path.getFileName().toString(); if (model.getFolder(folderName) == null) { model.addDirectory((ResourceTreeFolder)model.getRoot(), path, false); @@ -2004,19 +2004,19 @@ private List initDlc(Path rootDir, Path homeDir) List gameFolders = new ArrayList<>(); // Getting potential DLC folders (search order is important) - if (rootDir != null && rootDir.toFile().isDirectory()) { + if (rootDir != null && Files.isDirectory(rootDir)) { gameFolders.add(new ObjectString("mod", rootDir.resolve("workshop"))); gameFolders.add(new ObjectString("zip", rootDir.resolve("dlc"))); gameFolders.add(new ObjectString("zip", rootDir)); } - if (homeDir != null && homeDir.toFile().isDirectory()) { + if (homeDir != null && Files.isDirectory(homeDir)) { gameFolders.add(new ObjectString("zip", homeDir)); } for (final ObjectString root: gameFolders) { String ext = root.getString(); Path dir = root.getObject(); - if (dir != null && dir.toFile().isDirectory()) { + if (dir != null && Files.isDirectory(dir)) { List list = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(dir)) { for (final Path file: dstream) { @@ -2065,7 +2065,7 @@ private List initDlc(Path rootDir, Path homeDir) private Path validateDlc(Path file, String ext) throws IOException { // is regular file? - if (file == null || !file.toFile().isFile()) { + if (file == null && !Files.isRegularFile(file)) { return null; } @@ -2098,7 +2098,7 @@ public void fileChanged(FileWatchEvent e) if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { Path path = e.getPath(); - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { // Note: skipping extra folders because of issues on Windows systems // List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); // if (FileManager.containsPath(path, extraDirs)) { diff --git a/src/org/infinity/resource/ResourceFactory.java b/src/org/infinity/resource/ResourceFactory.java index 55f2e3e69..0827e5a01 100644 --- a/src/org/infinity/resource/ResourceFactory.java +++ b/src/org/infinity/resource/ResourceFactory.java @@ -499,7 +499,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search List extraFolders = Profile.getOverrideFolders(searchExtraDirs); if (extraFolders != null) { Path file = FileManager.query(extraFolders, resourceName); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { entry = new FileResourceEntry(file); } } @@ -508,7 +508,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search // checking custom folder list if (extraDirs != null && (entry == null)) { Path file = FileManager.query(extraDirs, resourceName); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { entry = new FileResourceEntry(file); } } @@ -710,12 +710,12 @@ public static List getAvailableGameLanguages() if (Profile.isEnhancedEdition()) { Path langPath = Profile.getProperty(Profile.Key.GET_GAME_LANG_FOLDER_BASE); - if (langPath != null && langPath.toFile().isDirectory()) { + if (langPath != null && Files.isDirectory(langPath)) { try (DirectoryStream dstream = Files.newDirectoryStream(langPath, (Path entry) -> { - return entry.toFile().isDirectory() && + return Files.isDirectory(entry) && entry.getFileName().toString().matches("[a-z]{2}_[A-Z]{2}") && - FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME)).toFile().isFile(); + Files.isRegularFile(FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME))); })) { dstream.forEach((path) -> list.add(path)); } catch (IOException e) { @@ -730,7 +730,7 @@ public static List getAvailableGameLanguages() public static String autodetectGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && iniFile.toFile().isFile()) { + if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { // Attempt to autodetect game language try (BufferedReader br = Files.newBufferedReader(iniFile, Misc.CHARSET_UTF8)) { String line; @@ -743,7 +743,7 @@ public static String autodetectGameLanguage(Path iniFile) lang = lang.replaceFirst("'.*$", ""); if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { try { // try to fetch the actual path name to ensure correct case return path.toRealPath().getFileName().toString(); @@ -771,7 +771,7 @@ static Path getHomeRoot(boolean allowMissing) final Path EE_DOC_ROOT = FileSystemView.getFileSystemView().getDefaultDirectory().toPath(); final String EE_DIR = Profile.getProperty(Profile.Key.GET_GAME_HOME_FOLDER_NAME); Path userPath = FileManager.query(EE_DOC_ROOT, EE_DIR); - if (allowMissing || (userPath != null && userPath.toFile().isDirectory())) { + if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { return userPath; } else { // fallback solution @@ -797,7 +797,7 @@ static Path getHomeRoot(boolean allowMissing) } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("bsd")) { userPath = FileManager.resolve(FileManager.resolve(userPrefix, ".local", "share", EE_DIR)); } - if (allowMissing || (userPath != null && userPath.toFile().isDirectory())) { + if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { return userPath; } } @@ -825,7 +825,7 @@ static List getBIFFDirs() // fetching the CD folders in a game installation Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); List rootFolders = Profile.getRootFolders(); - if (iniFile != null && iniFile.toFile().isFile()) { + if (iniFile != null && Files.isRegularFile(iniFile)) { try (BufferedReader br = Files.newBufferedReader(iniFile)) { String line; while ((line = br.readLine()) != null) { @@ -845,7 +845,7 @@ static List getBIFFDirs() Path path; if (line.charAt(0) == '/') { // absolute Unix path path = FileManager.resolve(line); - if (path == null || !path.toFile().isDirectory()) { // try relative Unix path + if (path == null || !Files.isDirectory(path)) { // try relative Unix path path = FileManager.query(rootFolders, line); } } else if (line.indexOf(':') < 0) { // relative Unix path @@ -853,7 +853,7 @@ static List getBIFFDirs() } else { path = FileManager.resolve(line); } - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { dirList.add(path); } } @@ -871,13 +871,13 @@ static List getBIFFDirs() Path path; for (int i = 1; i < 7; i++) { path = FileManager.query(rootFolders, "CD" + i); - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { dirList.add(path); } } // used in certain games path = FileManager.query(rootFolders, "CDALL"); - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { dirList.add(path); } } @@ -890,7 +890,7 @@ static String fetchGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && iniFile.toFile().isFile()) { + if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { String lang = BrowserMenuBar.getInstance().getSelectedGameLanguage(); if (lang == null || lang.isEmpty()) { @@ -899,7 +899,7 @@ static String fetchGameLanguage(Path iniFile) // Using user-defined language if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { String retVal; try { // try to fetch the actual path name to ensure correct case @@ -1023,7 +1023,7 @@ private Path getExportFileDialogInternal(Component parent, String fileName, bool fc.setSelectedFile(new File(fc.getCurrentDirectory(), fileName)); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { path = fc.getSelectedFile().toPath(); - if (!forceOverwrite && path.toFile().exists()) { + if (!forceOverwrite && Files.exists(path)) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, path + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -1169,7 +1169,7 @@ private void registerResourceInternal(Path resource, boolean autoselect) !Profile.isResourceTypeSupported(FileManager.getFileExtension(resource))) { return; } - if (resource == null || !resource.toFile().isFile()) { + if (resource == null || !Files.isRegularFile(resource)) { return; } @@ -1301,7 +1301,7 @@ private void loadResourcesInternal() throws Exception NearInfinity.advanceProgress("Loading extra resources..."); List extraPaths = Profile.getProperty(Profile.Key.GET_GAME_EXTRA_FOLDERS); extraPaths.forEach((path) -> { - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { treeModel.addDirectory(treeModel.getRoot(), path, false); } }); @@ -1312,10 +1312,10 @@ private void loadResourcesInternal() throws Exception String overrideFolder = Profile.getOverrideFolderName(); List overridePaths = Profile.getOverrideFolders(false); for (final Path overridePath: overridePaths) { - if (overridePath.toFile().isDirectory()) { + if (Files.isDirectory(overridePath)) { try (DirectoryStream dstream = Files.newDirectoryStream(overridePath)) { dstream.forEach((path) -> { - if (path.toFile().isFile()) { + if (Files.isRegularFile(path)) { ResourceEntry entry = getResourceEntry(path.getFileName().toString()); if (entry instanceof FileResourceEntry) { treeModel.addResourceEntry(entry, entry.getTreeFolderName(), true); @@ -1388,7 +1388,7 @@ private void loadSpecialResources() */ private void addFileResource(Path path) { - if (path != null && path.toFile().isFile()) { + if (path != null && Files.isRegularFile(path)) { treeModel.addResourceEntry(new FileResourceEntry(path), SPECIAL_CATEGORY, false); } } @@ -1516,7 +1516,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) outFile = FileManager.query(Profile.getGameRoot(), "Scripts", fileName); } - if (outFile.toFile().exists()) { + if (Files.exists(outFile)) { String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(NearInfinity.getInstance(), outFile + " exists. Overwrite?", "Confirm overwrite " + outFile, JOptionPane.YES_NO_OPTION, @@ -1525,7 +1525,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) } // creating override folder in game directory if it doesn't exist - if (!outPath.toFile().isDirectory()) { + if (!Files.isDirectory(outPath)) { try { Files.createDirectory(outPath); } catch (IOException e) { @@ -1573,7 +1573,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!overridePath.toFile().isDirectory()) { + if (!Files.isDirectory(overridePath)) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -1590,7 +1590,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) // 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 && !outPath.getParent().toFile().exists()) { + if (outPath != null && !Files.exists(outPath.getParent())) { try { Files.createDirectories(outPath.getParent()); } catch (IOException e) { @@ -1602,7 +1602,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) } } } - if (outPath.toFile().exists()) { + if (Files.exists(outPath)) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, outPath + " exists. Overwrite?", "Save resource", @@ -1611,10 +1611,10 @@ private boolean saveResourceInternal(Resource resource, Component parent) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (bakPath.toFile().isFile()) { + if (Files.isRegularFile(bakPath)) { Files.delete(bakPath); } - if (!bakPath.toFile().exists()) { + if (!Files.exists(bakPath)) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/StructureFactory.java b/src/org/infinity/resource/StructureFactory.java index d372ef2c3..3fa9e537d 100644 --- a/src/org/infinity/resource/StructureFactory.java +++ b/src/org/infinity/resource/StructureFactory.java @@ -7,6 +7,7 @@ import java.awt.Window; 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.EnumMap; @@ -89,7 +90,7 @@ public void newResource(ResType type, Window parent) roots.add(Profile.getGameRoot()); } savePath = FileManager.query(roots, "Characters"); - if (!savePath.toFile().isDirectory()) { + if (!Files.isDirectory(savePath)) { savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); } break; @@ -98,7 +99,7 @@ public void newResource(ResType type, Window parent) savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); break; } - if (savePath == null || !savePath.toFile().isDirectory()) { + if (savePath == null || !Files.isDirectory(savePath) ) { savePath = Profile.getGameRoot(); } JFileChooser fc = new JFileChooser(savePath.toFile()); @@ -109,7 +110,7 @@ public void newResource(ResType type, Window parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), "UNTITLED." + resExt.get(type))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { Path outFile = fc.getSelectedFile().toPath(); - if (outFile.toFile().exists()) { + if (Files.exists(outFile)) { 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) diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java index 0fe0dbb81..0f44cee0f 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java @@ -6,6 +6,7 @@ import java.awt.Image; import java.awt.Point; +import java.nio.file.Files; import java.nio.file.Path; import org.infinity.datatype.IsNumeric; @@ -64,7 +65,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) if (Profile.isEnhancedEdition()) { // processing new TOH structure Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); - if (tohFile.toFile().exists()) { + if (Files.exists(tohFile)) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); TohResource toh = new TohResource(tohEntry); SectionOffset so = (SectionOffset)toh.getAttribute(TohResource.TOH_OFFSET_ENTRIES); @@ -91,7 +92,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) // processing legacy TOH/TOT structures Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); Path totFile = FileManager.resolve(path, "DEFAULT.TOT"); - if (tohFile.toFile().exists() && totFile.toFile().exists()) { + if (Files.exists(tohFile) && Files.exists(totFile)) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); FileResourceEntry totEntry = new FileResourceEntry(totFile); TohResource toh = new TohResource(tohEntry); diff --git a/src/org/infinity/resource/graphics/BamV2Decoder.java b/src/org/infinity/resource/graphics/BamV2Decoder.java index b9352b4fa..cf28a0ba6 100644 --- a/src/org/infinity/resource/graphics/BamV2Decoder.java +++ b/src/org/infinity/resource/graphics/BamV2Decoder.java @@ -11,6 +11,7 @@ import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.nio.ByteBuffer; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -249,7 +250,7 @@ private PvrDecoder getPVR(int page) if (bamPath != null) { // preferring PVRZ files from the BAM's base path Path pvrzFile = FileManager.resolve(bamPath.resolve(name)); - if (pvrzFile.toFile().isFile()) { + if (Files.isRegularFile(pvrzFile)) { entry = new FileResourceEntry(pvrzFile); } } diff --git a/src/org/infinity/resource/graphics/ColorConvert.java b/src/org/infinity/resource/graphics/ColorConvert.java index 2e75863be..777b2117f 100644 --- a/src/org/infinity/resource/graphics/ColorConvert.java +++ b/src/org/infinity/resource/graphics/ColorConvert.java @@ -437,7 +437,7 @@ public static boolean medianCut(int[] pixels, int desiredColors, int[] palette, */ public static int[] loadPaletteBMP(Path file) throws Exception { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); @@ -485,7 +485,7 @@ public static int[] loadPaletteBMP(Path file) throws Exception */ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exception { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (InputStream is = StreamUtils.getInputStream(file)) { BufferedImage img = ImageIO.read(is); if (img.getType() == BufferedImage.TYPE_BYTE_INDEXED) { @@ -517,7 +517,7 @@ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exce */ public static int[] loadPalettePAL(Path file) throws Exception { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[12]; boolean eof = is.read(signature) != signature.length; @@ -569,7 +569,7 @@ public static int[] loadPalettePAL(Path file) throws Exception */ public static int[] loadPaletteACT(Path file) throws Exception { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (InputStream is = StreamUtils.getInputStream(file)) { int size = (int)Files.size(file); if (size >= 768) { @@ -611,7 +611,7 @@ public static int[] loadPaletteACT(Path file) throws Exception */ public static int[] loadPaletteBAM(Path file, boolean preserveAlpha) throws Exception { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); diff --git a/src/org/infinity/resource/graphics/TisResource.java b/src/org/infinity/resource/graphics/TisResource.java index 17b62c5d0..3fecf273f 100644 --- a/src/org/infinity/resource/graphics/TisResource.java +++ b/src/org/infinity/resource/graphics/TisResource.java @@ -567,7 +567,7 @@ private Path getTisFileName(Component parent, boolean enforceValidName) } else { repeat = false; } - if (retVal.toFile().exists()) { + if (Files.exists(retVal)) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -596,7 +596,7 @@ private Path getPngFileName(Component parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), getResourceEntry().getResourceName().toUpperCase(Locale.ENGLISH).replace(".TIS", ".PNG"))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { retVal = fc.getSelectedFile().toPath(); - if (retVal.toFile().exists()) { + if (Files.exists(retVal)) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -744,7 +744,7 @@ public Status convertToPaletteTis(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && output.toFile().isFile()) { + if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { try { Files.delete(output); } catch (IOException e) { @@ -980,7 +980,7 @@ public Status convertToPvrzTis(Path output, boolean showProgress) retVal = Status.ERROR; e.printStackTrace(); } - if (retVal != Status.SUCCESS && output.toFile().isFile()) { + if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { try { Files.delete(output); } catch (IOException e) { @@ -1038,7 +1038,7 @@ public Status exportPNG(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && output.toFile().isFile()) { + if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { try { Files.delete(output); } catch (IOException e) { @@ -1133,7 +1133,7 @@ private Status writePvrzPages(Path tisFile, List pageList, if (retVal != Status.SUCCESS) { for (int i = 0; i < pageList.size(); i++) { Path pvrzFile = generatePvrzFileName(tisFile, i); - if (pvrzFile != null && pvrzFile.toFile().isFile()) { + if (pvrzFile != null && Files.isRegularFile(pvrzFile)) { try { Files.delete(pvrzFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/BIFFEntry.java b/src/org/infinity/resource/key/BIFFEntry.java index d66f9b001..de369f3ce 100644 --- a/src/org/infinity/resource/key/BIFFEntry.java +++ b/src/org/infinity/resource/key/BIFFEntry.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -124,7 +125,7 @@ public String getFileName() /** Returns whether the referenced BIFF file exists in the game. */ public boolean exists() { - return (biffFile != null && biffFile.toFile().isFile()); + return (biffFile != null && Files.isRegularFile(biffFile)); } /** Returns the absolute path to the BIFF file if it exists. */ @@ -240,7 +241,7 @@ private static Path findBiffFile(Path root, int location, String fileName) final String[] baseFolders = { "", "cache", "cd1", "cd2", "cd3", "cd4", "cd5", "cd6", "cd7", "cdall" }; for (final String folderName: baseFolders) { Path path = FileManager.resolve(root.resolve(folderName)); - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { biffFolders.add(path); } } diff --git a/src/org/infinity/resource/key/BIFFResourceEntry.java b/src/org/infinity/resource/key/BIFFResourceEntry.java index 62e06e4cb..030710ff7 100644 --- a/src/org/infinity/resource/key/BIFFResourceEntry.java +++ b/src/org/infinity/resource/key/BIFFResourceEntry.java @@ -113,12 +113,12 @@ public void deleteOverride() throws IOException { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { Files.deleteIfExists(file); } file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && file.toFile().isFile()); + hasOverride = (file != null && Files.isRegularFile(file)); } } @@ -128,7 +128,7 @@ public Path getActualPath(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { return file; } } @@ -148,7 +148,7 @@ public long getResourceSize(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { retVal = Files.size(file); return retVal; } @@ -191,7 +191,7 @@ public ByteBuffer getResourceBuffer(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { @@ -212,7 +212,7 @@ public InputStream getResourceDataAsStream(boolean ignoreOverride) throws Except if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { return StreamUtils.getInputStream(file); } } @@ -226,7 +226,7 @@ public int[] getResourceInfo(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { return getLocalFileInfo(file); } } @@ -277,7 +277,7 @@ public boolean hasOverride() List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && file.toFile().isFile()); + hasOverride = (file != null && Files.isRegularFile(file)); } } return hasOverride; diff --git a/src/org/infinity/resource/key/BIFFWriter.java b/src/org/infinity/resource/key/BIFFWriter.java index fb900d872..a5cd0b333 100644 --- a/src/org/infinity/resource/key/BIFFWriter.java +++ b/src/org/infinity/resource/key/BIFFWriter.java @@ -121,7 +121,7 @@ public void addResource(ResourceEntry resourceEntry, boolean ignoreoverride) public void write() throws Exception { Path biffPath = FileManager.query(Profile.getGameRoot(), "data"); - if (biffPath == null || !biffPath.toFile().isDirectory()) { + if (biffPath == null || !Files.isDirectory(biffPath)) { throw new Exception("No BIFF folder found."); } Path dummyFile = Files.createTempFile(biffPath, "_dummy", ".bif"); @@ -136,7 +136,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (realFile.toFile().isFile()) { + if (Files.isRegularFile(realFile)) { Files.delete(realFile); } Files.move(dummyFile, realFile); @@ -149,7 +149,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (realFile.toFile().isFile()) { + if (Files.isRegularFile(realFile)) { Files.delete(realFile); } Files.move(compressedFile, realFile); @@ -162,19 +162,19 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getRootFolders(), bifEntry.getFileName()); } - if (realFile.toFile().isFile()) { + if (Files.isRegularFile(realFile)) { Files.delete(realFile); } Files.move(compressedFile, realFile); } } finally { - if (dummyFile != null && dummyFile.toFile().isFile()) { + if (dummyFile != null && Files.isRegularFile(dummyFile)) { try { Files.delete(dummyFile); } catch (IOException e) { } } - if (compressedFile != null && compressedFile.toFile().isFile()) { + if (compressedFile != null && Files.isRegularFile(compressedFile)) { try { Files.delete(compressedFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/Keyfile.java b/src/org/infinity/resource/key/Keyfile.java index 443f223cf..feaf81009 100644 --- a/src/org/infinity/resource/key/Keyfile.java +++ b/src/org/infinity/resource/key/Keyfile.java @@ -112,7 +112,7 @@ public Keyfile(Path keyFile) throws FileNotFoundException if (keyFile == null) { throw new NullPointerException("No keyfile specified"); } - if (!keyFile.toFile().isFile()) { + if (!Files.isRegularFile(keyFile)) { throw new FileNotFoundException("Keyfile " + keyFile + " not found or is not regular file"); } @@ -461,7 +461,7 @@ public void run() biffList.forEach((entry) -> { if (entry != null) { Path biffPath = entry.getPath(); - if (biffPath != null && biffPath.toFile().isFile()) { + if (biffPath != null && Files.isRegularFile(biffPath)) { try { AbstractBIFFReader.open(biffPath); } catch (Exception e) { @@ -481,7 +481,7 @@ public void run() // if (keyFile == null) { // throw new NullPointerException(); // } -// if (!keyFile.toFile().isFile()) { +// if (!Files.isRegularFile(keyFile)) { // throw new IOException("Key file not found: " + keyFile); // } // @@ -515,11 +515,11 @@ private void init() throws IOException if (getKeyfile() == null) { throw new NullPointerException(); } - if (!getKeyfile().toFile().isFile()) { + if (!Files.isRegularFile(getKeyfile())) { throw new IOException("Key file not found: " + getKeyfile()); } for (final Path file: keyList) { - if (file != null && !file.toFile().isFile()) { + if (file != null && !Files.isRegularFile(file)) { throw new IOException("Key file not found: " + file); } } diff --git a/src/org/infinity/resource/key/ResourceEntry.java b/src/org/infinity/resource/key/ResourceEntry.java index aa0d20814..1b5ffac7e 100644 --- a/src/org/infinity/resource/key/ResourceEntry.java +++ b/src/org/infinity/resource/key/ResourceEntry.java @@ -47,7 +47,7 @@ public abstract class ResourceEntry implements Comparable static int[] getLocalFileInfo(Path file) { - if (file != null && file.toFile().isFile()) { + if (file != null && Files.isRegularFile(file)) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { diff --git a/src/org/infinity/resource/key/ResourceTreeModel.java b/src/org/infinity/resource/key/ResourceTreeModel.java index c08e0762a..ea4777b11 100644 --- a/src/org/infinity/resource/key/ResourceTreeModel.java +++ b/src/org/infinity/resource/key/ResourceTreeModel.java @@ -113,7 +113,7 @@ public void addDirectory(ResourceTreeFolder parentFolder, Path directory, boolea if (iter.hasNext()) { final ResourceTreeFolder folder = addFolder(parentFolder, directory.getFileName().toString()); iter.forEachRemaining((path) -> { - if (path.toFile().isDirectory()) { + if (Files.isDirectory(path)) { addDirectory(folder, path, overwrite); } else { folder.addResourceEntry(new FileResourceEntry(path), overwrite); diff --git a/src/org/infinity/resource/mus/Entry.java b/src/org/infinity/resource/mus/Entry.java index 2266ec5d0..de04eff38 100644 --- a/src/org/infinity/resource/mus/Entry.java +++ b/src/org/infinity/resource/mus/Entry.java @@ -175,13 +175,13 @@ private AudioBuffer getAudioBuffer(String fileName) throws IOException { // audio file can reside in a number of different locations Path acmFile = FileManager.query(entry.getActualPath().getParent(), dir, dir + fileName + ".acm"); - if (!acmFile.toFile().isFile()) { + if (!Files.isRegularFile(acmFile)) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName + ".acm"); } - if (!acmFile.toFile().isFile() && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { + if (!Files.isRegularFile(acmFile) && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName.substring(0, 6), fileName + ".acm"); } - if (!acmFile.toFile().isFile()) { + if (!Files.isRegularFile(acmFile)) { throw new IOException("Could not find " + fileName); } diff --git a/src/org/infinity/resource/sav/IOHandler.java b/src/org/infinity/resource/sav/IOHandler.java index 89c1b8b6f..c92c1d8b3 100644 --- a/src/org/infinity/resource/sav/IOHandler.java +++ b/src/org/infinity/resource/sav/IOHandler.java @@ -63,7 +63,7 @@ public void write(OutputStream os) throws IOException public void close() { - if (tempFolder != null && tempFolder.toFile().isDirectory()) { + if (tempFolder != null && Files.isDirectory(tempFolder)) { try (DirectoryStream dstream = Files.newDirectoryStream(tempFolder)) { for (final Path file: dstream) { try { @@ -128,7 +128,7 @@ private Path createTempFolder() { for (int idx = 0; idx < Integer.MAX_VALUE; idx++) { Path path = Profile.getHomeRoot().resolve(String.format("%s.%03d", entry.getTreeFolderName(), idx)); - if (!path.toFile().exists()) { + if (!Files.exists(path)) { return path; } } diff --git a/src/org/infinity/resource/sav/SavResource.java b/src/org/infinity/resource/sav/SavResource.java index c9b6a87ee..ff345fdbf 100644 --- a/src/org/infinity/resource/sav/SavResource.java +++ b/src/org/infinity/resource/sav/SavResource.java @@ -362,7 +362,7 @@ private void addResource(ResourceEntry resourceEntry) if (resourceEntry != null) { Path output = handler.getTempFolder().resolve(resourceEntry.getResourceName()); try { - if (output.toFile().exists()) { + if (Files.exists(output)) { String msg = "File " + resourceEntry.getResourceName() + " already exists. Overwrite?"; int ret = JOptionPane.showConfirmDialog(panel.getTopLevelAncestor(), msg, "Overwrite file?", JOptionPane.YES_NO_OPTION, @@ -410,7 +410,7 @@ private void removeResource(int entryIndex) if (entryIndex >= 0 && entryIndex < entries.size()) { ResourceEntry resourceEntry = entries.get(entryIndex); Path file = resourceEntry.getActualPath(); - if (file.toFile().exists()) { + if (Files.exists(file)) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/MveResource.java b/src/org/infinity/resource/video/MveResource.java index 5aee61fba..98365b064 100644 --- a/src/org/infinity/resource/video/MveResource.java +++ b/src/org/infinity/resource/video/MveResource.java @@ -476,7 +476,7 @@ AudioFormatKeys.SampleRateKey, new Rational(sampleRate), writer.close(); writer = null; } - if (outFile.toFile().isFile()) { + if (Files.isRegularFile(outFile)) { try { Files.delete(outFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/WbmResource.java b/src/org/infinity/resource/video/WbmResource.java index 89e2cac4a..5361c20cd 100644 --- a/src/org/infinity/resource/video/WbmResource.java +++ b/src/org/infinity/resource/video/WbmResource.java @@ -107,7 +107,7 @@ public void close() throws Exception { try { // first attempt to delete temporary video file - if (videoFile != null && videoFile.toFile().isFile() && isTempFile) { + if (videoFile != null && Files.isRegularFile(videoFile) && isTempFile) { Files.delete(videoFile); } } catch (Exception e) { @@ -173,7 +173,7 @@ private Path getVideoFile() fileExt = "wbm"; try { Path outFile = Files.createTempFile(fileBase + "-", "." + fileExt); - if (outFile.toFile().isFile()) { + if (Files.isRegularFile(outFile)) { try (InputStream is = entry.getResourceDataAsStream()) { try (OutputStream os = StreamUtils.getOutputStream(outFile, true)) { byte[] buffer = new byte[8192]; diff --git a/src/org/infinity/updater/Updater.java b/src/org/infinity/updater/Updater.java index 3a5e49054..1dd8cec8e 100644 --- a/src/org/infinity/updater/Updater.java +++ b/src/org/infinity/updater/Updater.java @@ -10,6 +10,7 @@ import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; +import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarFile; @@ -189,7 +190,7 @@ static String getJarFileHash() String path = Utils.getJarFileName(NearInfinity.class); if (path != null && !path.isEmpty()) { Path jarPath = FileManager.resolve(path); - if (jarPath.toFile().isFile()) { + if (Files.isRegularFile(jarPath)) { try { return Utils.generateMD5Hash(new FileInputStream(path)); } catch (IOException e) { diff --git a/src/org/infinity/updater/Utils.java b/src/org/infinity/updater/Utils.java index 553094796..4fae8ac40 100644 --- a/src/org/infinity/updater/Utils.java +++ b/src/org/infinity/updater/Utils.java @@ -23,6 +23,7 @@ import java.net.URLConnection; import java.net.UnknownServiceException; import java.nio.charset.Charset; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; @@ -86,7 +87,7 @@ public static String getJarFileName(Class classType) if (url != null) { try { Path file = Paths.get(url.toURI()); - if (file.toFile().exists()) { + if (Files.exists(file)) { return file.toString(); } } catch (URISyntaxException e) { diff --git a/src/org/infinity/util/FileDeletionHook.java b/src/org/infinity/util/FileDeletionHook.java index d26f93af8..7c0101772 100644 --- a/src/org/infinity/util/FileDeletionHook.java +++ b/src/org/infinity/util/FileDeletionHook.java @@ -33,7 +33,7 @@ public void run() { synchronized (listFilesToDelete) { for (final Path file: listFilesToDelete) { - if (file != null && file.toFile().exists()) { + if (file != null && Files.exists(file)) { try { Files.delete(file); } catch (Throwable t) { diff --git a/src/org/infinity/util/MassExporter.java b/src/org/infinity/util/MassExporter.java index a22b44f99..ac074ec2c 100644 --- a/src/org/infinity/util/MassExporter.java +++ b/src/org/infinity/util/MassExporter.java @@ -386,7 +386,7 @@ private void exportText(ResourceEntry entry, Path output) throws Exception private void exportDecompiledScript(ResourceEntry entry, Path output) throws Exception { output = output.getParent().resolve(StreamUtils.replaceFileExtension(output.getFileName().toString(), "BAF")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } ByteBuffer bb = entry.getResourceBuffer(); @@ -434,7 +434,7 @@ private void mosToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("MOS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } @@ -459,7 +459,7 @@ private void pvrzToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("PVRZ")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } @@ -481,7 +481,7 @@ private void tisToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("TIS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } @@ -531,7 +531,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception // creating subfolder for frames Path path = filePath.resolve(fileBase); - if (!path.toFile().exists()) { + if (!Files.exists(path)) { try { Files.createDirectory(path); } catch (IOException e) { @@ -541,7 +541,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception JOptionPane.showMessageDialog(NearInfinity.getInstance(), msg, "Error", JOptionPane.ERROR_MESSAGE); return; } - } else if (!path.toFile().isDirectory()) { + } else if (!Files.isDirectory(path)) { String msg = String.format("Folder \"%s\" can not be created. Skipping file \"%s\".", fileBase, fileName); System.err.println(msg); @@ -557,7 +557,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception private void chrToCre(ResourceEntry entry, Path output) throws Exception { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "CRE")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } CreResource crefile = new CreResource(entry); @@ -612,7 +612,7 @@ private void export(ResourceEntry entry) { try { Path output = outputPath.resolve(entry.getResourceName()); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } if ((entry.getExtension().equalsIgnoreCase("IDS") || @@ -658,7 +658,7 @@ else if (entry.getExtension().equalsIgnoreCase("WAV") && cbConvertWAV.isSelected } else if (entry.getExtension().equalsIgnoreCase("MVE") && cbExportMVEasAVI.isSelected()) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "avi")); - if (output.toFile().exists() && !cbOverwrite.isSelected()) { + if (Files.exists(output) && !cbOverwrite.isSelected()) { return; } MveResource.convertAvi(entry, output, null, true); diff --git a/src/org/infinity/util/StringTable.java b/src/org/infinity/util/StringTable.java index e69099815..b23968bde 100644 --- a/src/org/infinity/util/StringTable.java +++ b/src/org/infinity/util/StringTable.java @@ -1341,11 +1341,11 @@ private void _write(Path tlkPath, ProgressCallback callback) throws IOException // 1. backing up current string table file if needed Path pathBackup = null; - if (tlkPath.toFile().isFile()) { + if (Files.isRegularFile(tlkPath)) { String name = tlkPath.getFileName().toString(); for (int i = 0; i < 999; i++) { Path path = tlkPath.getParent().resolve(name + "-" + i); - if (!path.toFile().exists()) { + if (!Files.exists(path)) { pathBackup = path; break; } diff --git a/src/org/infinity/util/io/DlcManager.java b/src/org/infinity/util/io/DlcManager.java index 562c1cf6b..250cba146 100644 --- a/src/org/infinity/util/io/DlcManager.java +++ b/src/org/infinity/util/io/DlcManager.java @@ -90,7 +90,7 @@ private FileSystem _register(Path dlcFile) throws IOException private FileSystem _getDlc(Path dlcFile) { - if (dlcFile != null && dlcFile.toFile().isFile()) { + if (dlcFile != null && Files.isRegularFile(dlcFile)) { return fileSystems.get(dlcFile); } return null; @@ -107,7 +107,7 @@ private Path _queryKey(Path path) if (fs != null) { for (final String keyFile: KEY_FILES) { Path key = fs.getPath(keyFile); - if (key != null && key.toFile().isFile()) { + if (key != null && Files.isRegularFile(key)) { try (InputStream is = StreamUtils.getInputStream(key)) { String sig = StreamUtils.readString(is, 8); if ("KEY V1 ".equals(sig)) { @@ -126,7 +126,7 @@ private Path _queryKey(Path path) private FileSystem _validateDlc(Path dlcFile) throws IOException { - if (dlcFile == null || !dlcFile.toFile().isFile()) { + if (dlcFile == null || !Files.isRegularFile(dlcFile)) { return null; } diff --git a/src/org/infinity/util/io/FileManager.java b/src/org/infinity/util/io/FileManager.java index 5476f22e1..25f520dc5 100644 --- a/src/org/infinity/util/io/FileManager.java +++ b/src/org/infinity/util/io/FileManager.java @@ -430,7 +430,7 @@ private Path _queryPath(boolean mustExist, Path rootFilter, List rootPaths } } else { curPath = _resolve(curRoot.resolve(relPath)); - if (curPath != null && curPath.toFile().exists()) { + if (curPath != null && Files.exists(curPath)) { exists = true; break; } @@ -460,7 +460,7 @@ private void close() public void fileChanged(FileWatchEvent e) { if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - if (e.getPath().toFile().isDirectory()) { + if (Files.isDirectory(e.getPath())) { // load whole directory into cache _cacheDirectory(e.getPath(), true); } else { @@ -566,7 +566,7 @@ private static Path _resolveExisting(Path path) retVal = null; } } -// if (retVal != null && !retVal.toFile().exists()) { +// if (retVal != null && !Files.exists(retVal)) { // retVal = null; // } return retVal; @@ -575,7 +575,7 @@ private static Path _resolveExisting(Path path) private static HashSet _cacheDirectory(Path path, boolean force) { HashSet retVal = null; - if (path != null && path.toFile().isDirectory()) { + if (path != null && Files.isDirectory(path)) { if (force) { pathCache.remove(path); } diff --git a/src/org/infinity/util/io/FileWatcher.java b/src/org/infinity/util/io/FileWatcher.java index 5a5970272..8f0f18c6a 100644 --- a/src/org/infinity/util/io/FileWatcher.java +++ b/src/org/infinity/util/io/FileWatcher.java @@ -177,7 +177,7 @@ public void register(Path dir, boolean recursive) public void register(Path dir, boolean recursive, boolean notifyCreate, boolean notifyDelete, boolean notifyModify) { dir = FileManager.resolve(dir); - if (dir != null && dir.toFile().isDirectory()) { + if (dir != null && Files.isDirectory(dir)) { if (recursive) { try { Files.walkFileTree(dir, new SimpleFileVisitor() { diff --git a/src/org/infinity/util/io/StreamUtils.java b/src/org/infinity/util/io/StreamUtils.java index e990611c7..5c44b99ca 100644 --- a/src/org/infinity/util/io/StreamUtils.java +++ b/src/org/infinity/util/io/StreamUtils.java @@ -800,7 +800,7 @@ public static void createZip(Path sourceDir, Path zipFile, boolean includeFolder try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile))) { Path baseDir = includeFolder ? sourceDir.getParent() : sourceDir; Files.walk(sourceDir) - .filter(path -> !path.toFile().isDirectory()) + .filter(path -> !Files.isDirectory(path)) .forEach(path -> { ZipEntry ze = new ZipEntry(baseDir.relativize(path).toString()); try { diff --git a/src/org/infinity/util/io/zip/DlcFileSystem.java b/src/org/infinity/util/io/zip/DlcFileSystem.java index c540f2f7d..01e839336 100644 --- a/src/org/infinity/util/io/zip/DlcFileSystem.java +++ b/src/org/infinity/util/io/zip/DlcFileSystem.java @@ -101,7 +101,7 @@ public class DlcFileSystem extends FileSystem this.readOnly = true; this.provider = provider; this.dfpath = dfpath; - if (!this.dfpath.toFile().exists()) { + if (Files.notExists(this.dfpath)) { throw new FileSystemNotFoundException(this.dfpath.toString()); } this.dfpath.getFileSystem().provider().checkAccess(this.dfpath, AccessMode.READ); From 28a56e2f5ed2691ff2e121607f3385ba74b3ed8f Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Mon, 24 Aug 2020 18:14:26 +0200 Subject: [PATCH 09/14] Improve performance for I/O-based check operations (2nd attempt) Source: https://rules.sonarsource.com/java/tag/performance/RSPEC-3725 All platforms: Custom FileEx class for faster path checks Linux: Skipping case-sensitivity checks if matching path is found --- src/org/infinity/NearInfinity.java | 24 +- src/org/infinity/gui/BIFFEditor.java | 3 +- src/org/infinity/gui/BcsDropFrame.java | 5 +- src/org/infinity/gui/BrowserMenuBar.java | 10 +- src/org/infinity/gui/DebugConsole.java | 3 +- src/org/infinity/gui/GameProperties.java | 4 +- src/org/infinity/gui/OpenFileFrame.java | 4 +- src/org/infinity/gui/ResourceTree.java | 17 +- src/org/infinity/gui/SortableTable.java | 3 +- src/org/infinity/gui/StringEditor.java | 4 +- .../gui/converter/BamFilterColorReplace.java | 4 +- .../gui/converter/BamOptionsDialog.java | 10 +- .../gui/converter/BamPaletteDialog.java | 4 +- .../infinity/gui/converter/ConvertToBam.java | 17 +- .../infinity/gui/converter/ConvertToBmp.java | 9 +- .../infinity/gui/converter/ConvertToMos.java | 8 +- .../infinity/gui/converter/ConvertToPvrz.java | 9 +- .../infinity/gui/converter/ConvertToTis.java | 12 +- .../infinity/gui/hexview/StructHexViewer.java | 9 +- src/org/infinity/resource/Profile.java | 131 ++-- .../infinity/resource/ResourceFactory.java | 59 +- .../infinity/resource/StructureFactory.java | 8 +- .../are/viewer/LayerObjectAutomap.java | 6 +- .../resource/graphics/BamV2Decoder.java | 4 +- .../resource/graphics/ColorConvert.java | 11 +- .../resource/graphics/TisResource.java | 13 +- src/org/infinity/resource/key/BIFFEntry.java | 6 +- .../resource/key/BIFFResourceEntry.java | 17 +- src/org/infinity/resource/key/BIFFWriter.java | 13 +- src/org/infinity/resource/key/Keyfile.java | 11 +- .../infinity/resource/key/ResourceEntry.java | 3 +- .../resource/key/ResourceTreeModel.java | 3 +- src/org/infinity/resource/mus/Entry.java | 7 +- src/org/infinity/resource/sav/IOHandler.java | 5 +- .../infinity/resource/sav/SavResource.java | 5 +- .../infinity/resource/video/MveResource.java | 3 +- .../infinity/resource/video/WbmResource.java | 5 +- src/org/infinity/updater/Updater.java | 4 +- src/org/infinity/updater/Utils.java | 5 +- src/org/infinity/util/FileDeletionHook.java | 4 +- src/org/infinity/util/MassExporter.java | 19 +- src/org/infinity/util/StringTable.java | 5 +- src/org/infinity/util/io/DlcManager.java | 6 +- src/org/infinity/util/io/FileEx.java | 666 ++++++++++++++++++ src/org/infinity/util/io/FileManager.java | 10 +- src/org/infinity/util/io/FileWatcher.java | 2 +- src/org/infinity/util/io/StreamUtils.java | 2 +- 47 files changed, 941 insertions(+), 251 deletions(-) create mode 100644 src/org/infinity/util/io/FileEx.java diff --git a/src/org/infinity/NearInfinity.java b/src/org/infinity/NearInfinity.java index 84120fe5a..347821034 100644 --- a/src/org/infinity/NearInfinity.java +++ b/src/org/infinity/NearInfinity.java @@ -30,7 +30,6 @@ import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; @@ -101,6 +100,7 @@ import org.infinity.util.StringTable; import org.infinity.util.Table2daCache; import org.infinity.util.io.DlcManager; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; public final class NearInfinity extends JFrame implements ActionListener, ViewableContainer @@ -247,10 +247,10 @@ public static void main(String args[]) } else { // Override game folder via application parameter Path f = FileManager.resolve(args[idx]); - if (Files.isRegularFile(f)) { + if (FileEx.create(f).isFile()) { f = f.getParent(); } - if (Files.isDirectory(f)) { + if (FileEx.create(f).isDirectory()) { gameOverride = f; break; } @@ -304,7 +304,7 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) setJMenuBar(menu); final String lastDir; - if (gameOverride != null && Files.isDirectory(gameOverride)) { + if (gameOverride != null && FileEx.create(gameOverride).isDirectory()) { lastDir = gameOverride.toString(); } else { lastDir = prefs.get(LAST_GAMEDIR, null); @@ -312,9 +312,9 @@ private NearInfinity(Path gameOverride, Profile.Game forcedGame) final Path keyFile; Path path; - if (Files.isRegularFile(path = FileManager.resolve(KEYFILENAME))) { + if (FileEx.create(path = FileManager.resolve(KEYFILENAME)).isFile()) { keyFile = path; - } else if (lastDir != null && Files.isRegularFile(path = FileManager.resolve(lastDir, KEYFILENAME))) { + } else if (lastDir != null && FileEx.create(path = FileManager.resolve(lastDir, KEYFILENAME)).isFile()) { keyFile = path; } else { keyFile = findKeyfile(); @@ -355,11 +355,7 @@ protected Void doInBackground() throws Exception @Override public void windowClosing(WindowEvent event) { - if (removeViewable()) { - storePreferences(); - ChildFrame.closeWindows(); - System.exit(0); - } + quit(); } }); try { @@ -774,7 +770,7 @@ public boolean editGameIni(Component parent) boolean retVal = false; Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); try { - if (iniFile != null && Files.isRegularFile(iniFile)) { + if (iniFile != null && FileEx.create(iniFile).isFile()) { new ViewFrame(parent, new PlainTextResource(new FileResourceEntry(iniFile))); } else { throw new Exception(); @@ -1109,7 +1105,7 @@ public void drop(DropTargetDropEvent event) event.dropComplete(true); if (files != null && files.size() == 1) { Path path = files.get(0).toPath(); - if (path != null && Files.isRegularFile(path) && + if (path != null && FileEx.create(path).isFile() && path.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".KEY")) { Path curFile = Profile.getChitinKey(); if (!path.equals(curFile)) { @@ -1133,7 +1129,7 @@ public void run() if (files != null) { files.forEach((file) -> { Path path = file.toPath(); - if (Files.isRegularFile(path)) { + if (FileEx.create(path).isFile()) { OpenFileFrame.openExternalFile(NearInfinity.getInstance(), path); } }); diff --git a/src/org/infinity/gui/BIFFEditor.java b/src/org/infinity/gui/BIFFEditor.java index 27b4cf8e4..efd6bce95 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.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -166,7 +167,7 @@ public void run() for (final ResourceEntry entry : tobif) { Path file = FileManager.query(Profile.getRootFolders(), Profile.getOverrideFolderName(), entry.getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/gui/BcsDropFrame.java b/src/org/infinity/gui/BcsDropFrame.java index 6ca39c99c..00c2ddcec 100644 --- a/src/org/infinity/gui/BcsDropFrame.java +++ b/src/org/infinity/gui/BcsDropFrame.java @@ -59,6 +59,7 @@ import org.infinity.resource.bcs.ScriptType; import org.infinity.resource.key.FileResourceEntry; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; final class BcsDropFrame extends ChildFrame implements ActionListener, ListSelectionListener @@ -324,7 +325,7 @@ private void filesDropped(Component component, List files) if (component == compZone) { for (File f : files) { Path file = f.toPath(); - if (Files.isDirectory(file)) { + if (FileEx.create(file).isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); @@ -356,7 +357,7 @@ else if (file.getFileName().toString().toUpperCase(Locale.ENGLISH).endsWith(".BA else if (component == decompZone) { for (File f : files) { final Path file = f.toPath(); - if (Files.isDirectory(file)) { + if (FileEx.create(file).isDirectory()) { try (final DirectoryStream dstream = Files.newDirectoryStream(file)) { for (final Path p: dstream) { files.add(p.toFile()); diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index c18d64d3b..1cfe10d2a 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -26,7 +26,6 @@ import java.awt.event.WindowEvent; import java.io.IOException; import java.nio.charset.Charset; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -102,6 +101,7 @@ import org.infinity.util.ObjectString; import org.infinity.util.Pair; import org.infinity.util.StringTable; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; public final class BrowserMenuBar extends JMenuBar implements KeyEventDispatcher @@ -1050,7 +1050,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(bookmarkList.get(selected).getPath()); - if (!Files.isRegularFile(keyFile)) { + if (!FileEx.create(keyFile).isFile()) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), bookmarkList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -1069,7 +1069,7 @@ public void actionPerformed(ActionEvent event) } if (selected != -1) { Path keyFile = FileManager.resolve(recentList.get(selected).getPath()); - if (!Files.isRegularFile(keyFile)) { + if (!FileEx.create(keyFile).isFile()) { JOptionPane.showMessageDialog(NearInfinity.getInstance(), recentList.get(selected).getPath() + " could not be found", "Open game failed", JOptionPane.ERROR_MESSAGE); @@ -3558,7 +3558,7 @@ public String setName(String newName) public JMenuItem getMenuItem() { return item; } /** Returns whether the bookmark points to an existing game installation. */ - public boolean isEnabled() { return (Files.isRegularFile(FileManager.resolve(path))); } + public boolean isEnabled() { return (FileEx.create(FileManager.resolve(path)).isFile()); } /** Returns ActionListener used by the associated menu item. */ public ActionListener getActionListener() { return listener; } @@ -3654,7 +3654,7 @@ static final class RecentGame implements Cloneable public RecentGame(Profile.Game game, String path, int index, ActionListener listener) { if (game == null || game == Profile.Game.Unknown || - path == null || !Files.isRegularFile(FileManager.resolve(path))) { + path == null || !FileEx.create(FileManager.resolve(path)).isFile()) { throw new NullPointerException(); } this.game = game; diff --git a/src/org/infinity/gui/DebugConsole.java b/src/org/infinity/gui/DebugConsole.java index 8e93f8d7d..14d82a189 100644 --- a/src/org/infinity/gui/DebugConsole.java +++ b/src/org/infinity/gui/DebugConsole.java @@ -26,6 +26,7 @@ import org.infinity.icon.Icons; import org.infinity.resource.Profile; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; final class DebugConsole extends ChildFrame implements ActionListener { @@ -77,7 +78,7 @@ else if (event.getSource() == bSaveConsole) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "nidebuglog.txt")); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { Path output = chooser.getSelectedFile().toPath(); - if (Files.exists(output)) { + if (FileEx.create(output).exists()) { 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) diff --git a/src/org/infinity/gui/GameProperties.java b/src/org/infinity/gui/GameProperties.java index 0f181ac1b..92a2dc839 100644 --- a/src/org/infinity/gui/GameProperties.java +++ b/src/org/infinity/gui/GameProperties.java @@ -18,7 +18,6 @@ import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -43,6 +42,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; import org.infinity.util.Pair; +import org.infinity.util.io.FileEx; /** * Display verbose information about the currently selected game. @@ -249,7 +249,7 @@ private void init() pIni.add(tf, gbc); bEdit.setMargin(new Insets(2, 4, 2, 4)); bEdit.addActionListener(this); - bEdit.setEnabled(iniFile != null && Files.isRegularFile(iniFile)); + bEdit.setEnabled(iniFile != null && FileEx.create(iniFile).isFile()); gbc = ViewerUtil.setGBC(gbc, 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0, 4, 0, 0), 0, 0); pIni.add(bEdit, gbc); diff --git a/src/org/infinity/gui/OpenFileFrame.java b/src/org/infinity/gui/OpenFileFrame.java index 3e1763e06..242591c5b 100644 --- a/src/org/infinity/gui/OpenFileFrame.java +++ b/src/org/infinity/gui/OpenFileFrame.java @@ -22,7 +22,6 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -46,6 +45,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; public final class OpenFileFrame extends ChildFrame implements ActionListener @@ -240,7 +240,7 @@ else if (event.getSource() == bOpenNew) { /** Attempts to open the specified external game resource. */ public static void openExternalFile(Component parent, Path file) { - if (!Files.exists(file)) { + if (!FileEx.create(file).exists()) { JOptionPane.showMessageDialog(parent, '\"' + file.toString() + "\" not found", "Error", JOptionPane.ERROR_MESSAGE); } else { diff --git a/src/org/infinity/gui/ResourceTree.java b/src/org/infinity/gui/ResourceTree.java index e671b887e..3240dcfce 100644 --- a/src/org/infinity/gui/ResourceTree.java +++ b/src/org/infinity/gui/ResourceTree.java @@ -54,6 +54,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.key.ResourceTreeFolder; import org.infinity.resource.key.ResourceTreeModel; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -264,8 +265,8 @@ static void renameResource(FileResourceEntry entry) if (!filename.contains(".")) { filename = filename + '.' + entry.getExtension(); } - if (Files.exists(entry.getActualPath().getParent().resolve(filename)) - && JOptionPane.showConfirmDialog(NearInfinity.getInstance(), + if (FileEx.create(entry.getActualPath().getParent().resolve(filename)).exists() && + JOptionPane.showConfirmDialog(NearInfinity.getInstance(), "File with name \"" + filename + "\" already exists! Overwrite?", "Confirm overwrite " + filename, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.OK_OPTION @@ -360,8 +361,8 @@ static void restoreResource(ResourceEntry entry) // .bak available -> restore .bak version Path curFile = getCurrentFile(entry); Path tmpFile = getTempFile(curFile); - if (curFile != null && Files.isRegularFile(curFile) && - bakFile != null && Files.isRegularFile(bakFile)) { + if (curFile != null && FileEx.create(curFile).isFile() && + bakFile != null && FileEx.create(bakFile).isFile()) { try { Files.move(curFile, tmpFile); try { @@ -415,7 +416,7 @@ static void restoreResource(ResourceEntry entry) static void createZipFile(Path path) { - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { JFileChooser fc = new JFileChooser(Profile.getGameRoot().toFile()); fc.setDialogTitle("Save as"); fc.setFileFilter(new FileNameExtensionFilter("Zip files (*.zip)", "zip")); @@ -484,7 +485,7 @@ private static Path getBackupFile(ResourceEntry entry) (entry instanceof BIFFResourceEntry && entry.hasOverride())) { if (file != null) { Path bakFile = file.getParent().resolve(file.getFileName().toString() + ".bak"); - if (Files.isRegularFile(bakFile)) { + if (FileEx.create(bakFile).isFile()) { return bakFile; } } @@ -509,13 +510,13 @@ private static Path getCurrentFile(ResourceEntry entry) private static Path getTempFile(Path file) { Path retVal = null; - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { final String fmt = ".%03d"; Path filePath = file.getParent(); String fileName = file.getFileName().toString(); for (int i = 0; i < 1000; i++) { Path tmp = filePath.resolve(fileName + String.format(fmt, i)); - if (!Files.exists(tmp) && Files.notExists(tmp)) { + if (!FileEx.create(tmp).exists()) { retVal = tmp; break; } diff --git a/src/org/infinity/gui/SortableTable.java b/src/org/infinity/gui/SortableTable.java index b9fb95ebd..677baf0ef 100644 --- a/src/org/infinity/gui/SortableTable.java +++ b/src/org/infinity/gui/SortableTable.java @@ -33,6 +33,7 @@ import org.infinity.icon.Icons; import org.infinity.resource.Profile; import org.infinity.util.ArrayUtil; +import org.infinity.util.io.FileEx; public final class SortableTable extends JTable implements MouseListener { @@ -107,7 +108,7 @@ private void saveResult(Component parent, String dialogTitle, String header) { chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "result.txt")); if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { final Path output = chooser.getSelectedFile().toPath(); - if (Files.exists(output)) { + if (FileEx.create(output).exists()) { final String[] options = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, output + " exists. Overwrite?", dialogTitle, JOptionPane.YES_NO_OPTION, diff --git a/src/org/infinity/gui/StringEditor.java b/src/org/infinity/gui/StringEditor.java index e738b6780..feade47bd 100644 --- a/src/org/infinity/gui/StringEditor.java +++ b/src/org/infinity/gui/StringEditor.java @@ -14,7 +14,6 @@ import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Locale; @@ -59,6 +58,7 @@ import org.infinity.search.StringReferenceSearcher; import org.infinity.util.Misc; import org.infinity.util.StringTable; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; public class StringEditor extends ChildFrame implements SearchClient @@ -732,7 +732,7 @@ private void save(boolean interactive) int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { outPath = fc.getSelectedFile().toPath(); - if (!Files.isDirectory(outPath)) { + if (!FileEx.create(outPath).isDirectory()) { outPath = outPath.getParent(); } outFile = outPath.resolve(StringTable.getPath(StringTable.Type.MALE).getFileName().toString()); diff --git a/src/org/infinity/gui/converter/BamFilterColorReplace.java b/src/org/infinity/gui/converter/BamFilterColorReplace.java index c66b5ab75..52edc6185 100644 --- a/src/org/infinity/gui/converter/BamFilterColorReplace.java +++ b/src/org/infinity/gui/converter/BamFilterColorReplace.java @@ -21,7 +21,6 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; @@ -46,6 +45,7 @@ import org.infinity.resource.graphics.ColorConvert; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; // TODO: change filter to display the palette in the state after applying previous filters (if any) @@ -281,7 +281,7 @@ public int[] getPalette() /** Loads the palette from the specified file resource into the color grid component. */ public void loadPalette(Path paletteFile) throws Exception { - if (paletteFile != null && Files.isRegularFile(paletteFile)) { + if (paletteFile != null && FileEx.create(paletteFile).isFile()) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/BamOptionsDialog.java b/src/org/infinity/gui/converter/BamOptionsDialog.java index 59f439a28..e7b7eb4fd 100644 --- a/src/org/infinity/gui/converter/BamOptionsDialog.java +++ b/src/org/infinity/gui/converter/BamOptionsDialog.java @@ -17,7 +17,6 @@ import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.io.IOError; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -45,6 +44,7 @@ import org.infinity.gui.ViewerUtil; import org.infinity.resource.Profile; import org.infinity.resource.graphics.ColorConvert; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; /** @@ -161,7 +161,7 @@ private static void validateSettings() { bamVersion = Math.min(Math.max(bamVersion, ConvertToBam.VERSION_BAMV1), ConvertToBam.VERSION_BAMV2); if (path == null) path = DEFAULT_PATH; - if (!path.isEmpty() && !(Files.isDirectory(FileManager.resolve(path)))) path = DEFAULT_PATH; + if (!path.isEmpty() && !(FileEx.create(FileManager.resolve(path)).isDirectory())) path = DEFAULT_PATH; transparencyThreshold = Math.min(Math.max(transparencyThreshold, 0), 100); useAlpha = Math.min(Math.max(useAlpha, ConvertToBam.ALPHA_AUTO), ConvertToBam.ALPHA_NEVER); @@ -249,7 +249,7 @@ private static void loadRecentSessions(Preferences prefs) value = value.trim(); if (!finished && !value.isEmpty()) { Path path = Paths.get(value); - if (Files.isRegularFile(path)) { + if (FileEx.create(path).isFile()) { recentSessions.add(path); } } @@ -292,7 +292,7 @@ public void actionPerformed(ActionEvent event) { if (event.getSource() == miPathSet) { Path path = FileManager.resolve(tfPath.getText()); - if (!Files.isDirectory(path)) { + if (!FileEx.create(path).isDirectory()) { path = Profile.getGameRoot(); } Path rootPath = ConvertToBam.getOpenPathName(this, "Select initial directory", path); @@ -335,7 +335,7 @@ public void focusLost(FocusEvent event) { if (event.getSource() == tfPath) { String path = tfPath.getText(); - if (!path.isEmpty() && !Files.isDirectory(FileManager.resolve(path))) { + if (!path.isEmpty() && !FileEx.create(FileManager.resolve(path)).isDirectory()) { tfPath.setText(path); } } diff --git a/src/org/infinity/gui/converter/BamPaletteDialog.java b/src/org/infinity/gui/converter/BamPaletteDialog.java index 37a54e5c4..fcd8e54f9 100644 --- a/src/org/infinity/gui/converter/BamPaletteDialog.java +++ b/src/org/infinity/gui/converter/BamPaletteDialog.java @@ -20,7 +20,6 @@ import java.awt.image.IndexColorModel; import java.io.IOException; import java.io.InputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; @@ -51,6 +50,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.graphics.ColorConvert; import org.infinity.resource.graphics.PseudoBamDecoder.PseudoBamFrameEntry; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; /** @@ -249,7 +249,7 @@ public void loadExternalPalette(int type, Path paletteFile) throws Exception } // fetching file signature - if (paletteFile != null && Files.isRegularFile(paletteFile)) { + if (paletteFile != null && FileEx.create(paletteFile).isFile()) { byte[] signature = new byte[8]; try (InputStream is = StreamUtils.getInputStream(paletteFile)) { is.read(signature); diff --git a/src/org/infinity/gui/converter/ConvertToBam.java b/src/org/infinity/gui/converter/ConvertToBam.java index eb7e2da6e..5af69c6b5 100644 --- a/src/org/infinity/gui/converter/ConvertToBam.java +++ b/src/org/infinity/gui/converter/ConvertToBam.java @@ -117,6 +117,7 @@ import org.infinity.util.Misc; import org.infinity.util.Pair; import org.infinity.util.SimpleListModel; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -303,7 +304,7 @@ public static Path[] getOpenFileName(Component parent, String title, Path rootPa rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!Files.isDirectory(rootPath)) { + if (!FileEx.create(rootPath).isDirectory()) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -370,7 +371,7 @@ public static Path getSaveFileName(Component parent, String title, Path rootPath rootPath = currentPath; } JFileChooser fc = new JFileChooser(rootPath.toFile()); - if (!Files.isDirectory(rootPath)) { + if (!FileEx.create(rootPath).isDirectory()) { fc.setSelectedFile(rootPath.toFile()); } if (title == null) { @@ -517,7 +518,7 @@ public void actionPerformed(ActionEvent event) do { file = setBamOutput(); if (file != null) { - if (!Files.exists(file) || + if (!FileEx.create(file).exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -2750,13 +2751,13 @@ public void framesAddFolder() public void framesAddFolder(Path path) { - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { // preparing list of valid files FileNameExtensionFilter filters = getGraphicsFilters()[0]; List validFiles = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { - if (Files.isRegularFile(file) && filters.accept(file.toFile())) { + if (FileEx.create(file).isFile() && filters.accept(file.toFile())) { validFiles.add(file); } } @@ -5069,7 +5070,7 @@ public boolean importData(boolean silent) Path[] files = getOpenFileName(bam, "Import BAM session", null, false, new FileNameExtensionFilter[]{getIniFilter()}, 0); if (files != null && files.length > 0) { - if (!Files.isRegularFile(files[0])) { + if (!FileEx.create(files[0]).isFile()) { files[0] = StreamUtils.replaceFileExtension(files[0], "ini"); } if (loadData(files[0], silent)) { @@ -5190,7 +5191,7 @@ private boolean loadFrameData(IniMapSection frames) throws Exception } } else { Path file = FileManager.resolve(value); - if (!Files.isRegularFile(file)) { + if (!FileEx.create(file).isFile()) { throw new Exception("Frame source path not found at line " + (entry.getLine() + 1)); } } @@ -5376,7 +5377,7 @@ public SourceData(Path image) } } else { Path file = FileManager.resolve(value); - if (Files.isRegularFile(file)) { + if (FileEx.create(file).isFile()) { resource = new FileResourceEntry(file); } } diff --git a/src/org/infinity/gui/converter/ConvertToBmp.java b/src/org/infinity/gui/converter/ConvertToBmp.java index a02cbee78..91a119f6e 100644 --- a/src/org/infinity/gui/converter/ConvertToBmp.java +++ b/src/org/infinity/gui/converter/ConvertToBmp.java @@ -55,6 +55,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.graphics.ColorConvert; import org.infinity.util.SimpleListModel; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -98,7 +99,7 @@ private static Path[] getOpenFileName(Component parent, String title, Path rootP } Path file = FileManager.resolve(rootPath); JFileChooser fc = new JFileChooser(file.toFile()); - if (!Files.isDirectory(file)) { + if (!FileEx.create(file).isDirectory()) { fc.setSelectedFile(file.toFile()); } if (title == null) { @@ -520,7 +521,7 @@ private void inputAddFolder() rootPath = FileManager.resolve(modelInputFiles.get(modelInputFiles.size() - 1)); } Path path = getOpenPathName(this, "Choose folder", rootPath); - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { // adding all files in the directory FileNameExtensionFilter[] filters = getGraphicsFilters(); List skippedFiles = new ArrayList(); @@ -528,7 +529,7 @@ private void inputAddFolder() try (DirectoryStream dstream = Files.newDirectoryStream(path)) { for (final Path file: dstream) { for (final FileNameExtensionFilter filter: filters) { - if (Files.isRegularFile(file) && filter.accept(file.toFile())) { + if (FileEx.create(file).isFile() && filter.accept(file.toFile())) { if (isValidInput(file)) { modelInputFiles.addElement(file.toString()); idx++; @@ -633,7 +634,7 @@ private List convert() // 1. prepare data Path inFile = FileManager.resolve(modelInputFiles.get(i)); Path outFile = FileManager.resolve(outPath, StreamUtils.replaceFileExtension(inFile.getFileName().toString(), "BMP")); - if (Files.exists(outFile)) { + if (FileEx.create(outFile).exists()) { if (cbOverwrite.getSelectedIndex() == 0) { // ask String msg = String.format("File %s already exists. Overwrite?", outFile.getFileName()); int ret = JOptionPane.showConfirmDialog(this, msg, "Overwrite?", JOptionPane.YES_NO_CANCEL_OPTION); diff --git a/src/org/infinity/gui/converter/ConvertToMos.java b/src/org/infinity/gui/converter/ConvertToMos.java index cc0777f62..f074296db 100644 --- a/src/org/infinity/gui/converter/ConvertToMos.java +++ b/src/org/infinity/gui/converter/ConvertToMos.java @@ -24,7 +24,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -60,6 +59,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -544,7 +544,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutputV2.getText()); } if (file != null) { - if (!Files.exists(file) || + if (!FileEx.create(file).exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -906,7 +906,7 @@ private boolean isReady() boolean ret = false; if (!tfInputV1.getText().isEmpty() && !tfOutputV1.getText().isEmpty()) { Path file = FileManager.resolve(tfInputV1.getText()); - ret = Files.isRegularFile(file); + ret = FileEx.create(file).isFile(); } return ret; } @@ -975,7 +975,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(tfInputV1.getText()); - if (!Files.isRegularFile(inFile)) { + if (!FileEx.create(inFile).isFile()) { result.add(null); result.add(String.format("Input file \"%s\" does not exist.", tfInputV1.getText())); return result; diff --git a/src/org/infinity/gui/converter/ConvertToPvrz.java b/src/org/infinity/gui/converter/ConvertToPvrz.java index 83dd116c1..995420dd9 100644 --- a/src/org/infinity/gui/converter/ConvertToPvrz.java +++ b/src/org/infinity/gui/converter/ConvertToPvrz.java @@ -56,6 +56,7 @@ import org.infinity.resource.graphics.DxtEncoder; import org.infinity.util.DynamicArray; import org.infinity.util.SimpleListModel; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -480,7 +481,7 @@ private boolean isReady() // checks graphics input file properties private static boolean isValidGraphicsInput(Path inFile) { - boolean result = (inFile != null && Files.isRegularFile(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) { @@ -493,7 +494,7 @@ private static boolean isValidGraphicsInput(Path inFile) // checks PVR input file properties private static boolean isValidPVRInput(Path inFile) { - boolean result = (inFile != null && Files.isRegularFile(inFile)); + boolean result = (inFile != null && FileEx.create(inFile).isFile()); if (result) { try (InputStream is = StreamUtils.getInputStream(inFile)) { String sig = StreamUtils.readString(is, 4); @@ -540,7 +541,7 @@ private List convert() if (tfTargetDir.getText() != null && !tfTargetDir.getText().isEmpty()) { targetPath = FileManager.resolve(tfTargetDir.getText()); } - if (!Files.isDirectory(targetPath)) { + if (!FileEx.create(targetPath).isDirectory()) { List l = new Vector(2); l.add(null); l.add("Invalid target directory specified. No conversion takes place."); @@ -594,7 +595,7 @@ private List convert() Path outFile = targetPath.resolve(outFileName); // handling overwrite existing file - if (Files.exists(outFile)) { + if (FileEx.create(outFile).exists()) { if (skip) { skippedFiles++; continue; diff --git a/src/org/infinity/gui/converter/ConvertToTis.java b/src/org/infinity/gui/converter/ConvertToTis.java index 1115f78fa..57cb757c7 100644 --- a/src/org/infinity/gui/converter/ConvertToTis.java +++ b/src/org/infinity/gui/converter/ConvertToTis.java @@ -24,7 +24,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.OutputStream; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -61,6 +60,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -592,7 +592,7 @@ public void actionPerformed(ActionEvent event) file = FileManager.resolve(tfOutput.getText()); } if (file != null) { - if (!Files.exists(file) || + if (!FileEx.create(file).exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, msg, "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) { @@ -650,7 +650,7 @@ public List doInBackground() String fileName = tfOutput.getText(); if (fileName.isEmpty() && !tfInput.getText().isEmpty()) { Path f = FileManager.resolve(tfInput.getText()); - if (Files.isRegularFile(f)) { + if (FileEx.create(f).isFile()) { fileName = createValidTisName(tfInput.getText(), getTisVersion()); } } @@ -976,7 +976,7 @@ private boolean isReady() boolean ret = false; if (!getInputFile().isEmpty()) { Path f = FileManager.resolve(getInputFile()); - ret = Files.isRegularFile(f); + ret = FileEx.create(f).isFile(); } return ret; } @@ -1032,7 +1032,7 @@ private boolean validateInput(String inputFile) inFileName = inputFile; if (inFileName != null && !inFileName.isEmpty()) { Path f = FileManager.resolve(inFileName); - if (Files.isRegularFile(f)) { + if (FileEx.create(f).isFile()) { Dimension dimImage = ColorConvert.getImageDimension(f); if (dimImage.width >= 0 && (dimImage.width % 64) == 0 && dimImage.height >= 0 && (dimImage.height % 64) == 0) { @@ -1072,7 +1072,7 @@ private List convert() // validating input file Path inFile = FileManager.resolve(inFileName); - if (!Files.isRegularFile(inFile)) { + if (!FileEx.create(inFile).isFile()) { ret.add(null); ret.add(String.format("Input file \"%s\" does not exist.", inFileName)); return ret; diff --git a/src/org/infinity/gui/hexview/StructHexViewer.java b/src/org/infinity/gui/hexview/StructHexViewer.java index 2adf7e0ce..3791f37fd 100644 --- a/src/org/infinity/gui/hexview/StructHexViewer.java +++ b/src/org/infinity/gui/hexview/StructHexViewer.java @@ -76,6 +76,7 @@ import org.infinity.resource.key.BIFFResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -263,7 +264,7 @@ public void actionPerformed(ActionEvent event) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!Files.isDirectory(overridePath)) { + if (!FileEx.create(overridePath).isDirectory()) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -278,7 +279,7 @@ public void actionPerformed(ActionEvent event) } else { outPath = entry.getActualPath(); } - if (Files.exists(outPath)) { + if (FileEx.create(outPath).exists()) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(this, outPath + " exists. Overwrite?", "Save resource", @@ -287,10 +288,10 @@ public void actionPerformed(ActionEvent event) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (Files.isRegularFile(bakPath)) { + if (FileEx.create(bakPath).isFile()) { Files.delete(bakPath); } - if (!Files.exists(bakPath)) { + if (!FileEx.create(bakPath).exists()) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/Profile.java b/src/org/infinity/resource/Profile.java index 759683be4..09e22142f 100644 --- a/src/org/infinity/resource/Profile.java +++ b/src/org/infinity/resource/Profile.java @@ -34,6 +34,7 @@ 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; @@ -880,7 +881,7 @@ public static boolean updateGameLanguage(String language) // updating dialog.tlks updateProperty(Key.GET_GAME_DIALOG_FILE, FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME))); Path femaleTlkFile = FileManager.query(langPath, getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (Files.isRegularFile(femaleTlkFile)) { + if (FileEx.create(femaleTlkFile).isFile()) { addProperty(Key.GET_GAME_DIALOGF_FILE, Type.PATH, femaleTlkFile); } else { updateProperty(Key.GET_GAME_DIALOGF_FILE, null); @@ -1211,7 +1212,7 @@ private static String getLuaHomeFolderName(Game game) private static String getLuaValue(Path file, String key, String defaultValue, boolean ifLuaExists) { String retVal = ifLuaExists ? null : defaultValue; - if (file != null && Files.isRegularFile(file) && key != null && !key.trim().isEmpty()) { + if (file != null && FileEx.create(file).isFile() && key != null && !key.trim().isEmpty()) { retVal = defaultValue; try (Stream lines = Files.lines(file, StandardCharsets.UTF_8)) { for (Iterator iter = lines.iterator(); iter.hasNext();) { @@ -1269,7 +1270,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception { if (keyFile == null) { throw new Exception("No chitin.key specified"); - } else if (!Files.isRegularFile(keyFile)) { + } else if (!FileEx.create(keyFile).isFile()) { throw new Exception(keyFile.toString() + " does not exist"); } @@ -1296,7 +1297,7 @@ private void init(Path keyFile, String desc, Game forcedGame) throws Exception if (home != null) { addEntry(Key.GET_GAME_HOME_FOLDER_NAME, Type.STRING, home); homeDir = ResourceFactory.getHomeRoot(true); - if (homeDir != null && Files.isDirectory(homeDir)) { + if (homeDir != null && FileEx.create(homeDir).isDirectory()) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeDir); } } @@ -1327,85 +1328,85 @@ private void initGame() throws Exception } if (game == Game.IWDEE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm"))) { + FileEx.create(FileManager.query(gameRoots, "movies/howseer.wbm")).isFile()) { if (game == null) game = Game.IWDEE; // Note: baldur.ini is initialized later } else if (game == Game.PSTEE || - (Files.isRegularFile(FileManager.query(gameRoots, "data/MrtGhost.bif")) && - Files.isRegularFile(FileManager.query(gameRoots, "data/shaders.bif")) && + (FileEx.create(FileManager.query(gameRoots, "data/MrtGhost.bif")).isFile() && + FileEx.create(FileManager.query(gameRoots, "data/shaders.bif")).isFile() && getLuaValue(FileManager.query(gameRoots, "engine.lua"), "engine_mode", "0", false).equals("3"))) { if (game == null) game = Game.PSTEE; // Note: baldur.ini is initialized later } else if (game == Game.EET || game == Game.BG2EE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/pocketzz.wbm"))) { - if ((Files.isRegularFile(FileManager.query(gameRoots, "override/EET.flag"))) || - (Files.isRegularFile(FileManager.query(gameRoots, "data/eetTU00.bif")))) { + FileEx.create(FileManager.query(gameRoots, "movies/pocketzz.wbm")).isFile()) { + if ((FileEx.create(FileManager.query(gameRoots, "override/EET.flag")).isFile()) || + (FileEx.create(FileManager.query(gameRoots, "data/eetTU00.bif")).isFile())) { if (game == null) game = Game.EET; } else { if (game == null) game = Game.BG2EE; } // Note: baldur.ini is initialized later } else if (game == Game.BG1SoD || - Files.isRegularFile(FileManager.query(gameRoots, "movies/sodcin01.wbm"))) { + FileEx.create(FileManager.query(gameRoots, "movies/sodcin01.wbm")).isFile()) { if (game == null) game = Game.BG1SoD; // Note: baldur.ini is initialized later } else if (game == Game.BG1EE || - Files.isRegularFile(FileManager.query(gameRoots, "movies/bgenter.wbm"))) { + FileEx.create(FileManager.query(gameRoots, "movies/bgenter.wbm")).isFile()) { if (game == null) game = Game.BG1EE; // Note: baldur.ini is initialized later } else if ((game == Game.PST || - Files.isRegularFile(FileManager.query(gameRoots, "torment.exe"))) && - (!Files.isRegularFile(FileManager.query(gameRoots, "movies/sigil.wbm")))) { + FileEx.create(FileManager.query(gameRoots, "torment.exe")).isFile()) && + (!FileEx.create(FileManager.query(gameRoots, "movies/sigil.wbm")).isFile())) { if (game == null) game = Game.PST; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "torment.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD || game == Game.IWDHoW || game == Game.IWDHowTotLM || - (Files.isRegularFile(FileManager.query(gameRoots, "idmain.exe"))) && - (!Files.isRegularFile(FileManager.query(gameRoots, "movies/howseer.wbm")))) { + (FileEx.create(FileManager.query(gameRoots, "idmain.exe")).isFile()) && + (!FileEx.create(FileManager.query(gameRoots, "movies/howseer.wbm")).isFile())) { if (game == null) game = Game.IWD; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.IWD2 || - (Files.isRegularFile(FileManager.query(gameRoots, "iwd2.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "Data/Credits.mve")))) { + (FileEx.create(FileManager.query(gameRoots, "iwd2.exe")).isFile()) && + (FileEx.create(FileManager.query(gameRoots, "Data/Credits.mve")).isFile())) { if (game == null) game = Game.IWD2; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "icewind2.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.Tutu || - Files.isRegularFile(FileManager.query(gameRoots, "bg1tutu.exe")) || - Files.isRegularFile(FileManager.query(gameRoots, "bg1mov/MovieCD1.bif"))) { + FileEx.create(FileManager.query(gameRoots, "bg1tutu.exe")).isFile() || + FileEx.create(FileManager.query(gameRoots, "bg1mov/MovieCD1.bif")).isFile()) { if (game == null) game = Game.Tutu; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG2SoA || game == Game.BG2ToB || game == Game.BGT || - (Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "BGConfig.exe")))) { + (FileEx.create(FileManager.query(gameRoots, "baldur.exe")).isFile()) && + (FileEx.create(FileManager.query(gameRoots, "BGConfig.exe")).isFile())) { if (game == null) game = Game.BG2SoA; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else if (game == Game.BG1 || game == Game.BG1TotSC || - (Files.isRegularFile(FileManager.query(gameRoots, "movies/graphsim.mov"))) || // Mac BG1 detection hack - ((Files.isRegularFile(FileManager.query(gameRoots, "baldur.exe"))) && - (Files.isRegularFile(FileManager.query(gameRoots, "Config.exe"))))) { + (FileEx.create(FileManager.query(gameRoots, "movies/graphsim.mov")).isFile()) || // Mac BG1 detection hack + ((FileEx.create(FileManager.query(gameRoots, "baldur.exe")).isFile()) && + (FileEx.create(FileManager.query(gameRoots, "Config.exe")).isFile()))) { if (game == null) game = Game.BG1; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } else { @@ -1414,7 +1415,7 @@ private void initGame() throws Exception if (game == null) game = Game.Unknown; addEntry(Key.GET_GAME_INI_NAME, Type.STRING, "baldur.ini"); Path ini = FileManager.query(gameRoots, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } } @@ -1431,7 +1432,7 @@ private void initGame() throws Exception if (isEnhancedEdition()) { Path langDir = FileManager.query(gameRoots, "lang"); - if (langDir != null && Files.isDirectory(langDir)) { + if (langDir != null && FileEx.create(langDir).isDirectory()) { addEntry(Key.GET_GAME_LANG_FOLDER_BASE, Type.PATH, langDir); } } @@ -1456,11 +1457,11 @@ private void initGame() throws Exception // initializing dialog.tlk and dialogf.tlk Path tlk = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME)); - if (tlk != null && Files.isRegularFile(tlk)) { + if (tlk != null && FileEx.create(tlk).isFile()) { addEntry(Key.GET_GAME_DIALOG_FILE, Type.PATH, tlk); } Path tlkf = FileManager.query(getRootFolders(), getProperty(Key.GET_GLOBAL_DIALOG_NAME_FEMALE)); - if (tlkf != null && Files.isRegularFile(tlkf)) { + if (tlkf != null && FileEx.create(tlkf).isFile()) { addEntry(Key.GET_GAME_DIALOGF_FILE, Type.PATH, tlkf); } @@ -1552,7 +1553,7 @@ private void initIniFile(String... iniFiles) Path homeRoot = ResourceFactory.getHomeRoot(false); for (int i = 0; i < iniFiles.length; i++) { Path ini = FileManager.query(homeRoot, iniFiles[i]); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_NAME, Type.STRING, iniFiles[i]); break; } @@ -1574,7 +1575,7 @@ private void initRootDirs() if (homeRoot != null) { addEntry(Key.GET_GAME_HOME_FOLDER, Type.PATH, homeRoot); Path ini = FileManager.query(homeRoot, getProperty(Key.GET_GAME_INI_NAME)); - if (ini != null && Files.isRegularFile(ini)) { + if (ini != null && FileEx.create(ini).isFile()) { addEntry(Key.GET_GAME_INI_FILE, Type.PATH, ini); } listRoots.add(homeRoot); @@ -1594,7 +1595,7 @@ private void initRootDirs() roots.forEach((root) -> { // adding root of active language Path langRoot = FileManager.query(root, (String)getProperty(Key.GET_GLOBAL_LANG_NAME), language); - if (langRoot != null && Files.isDirectory(langRoot)) { + if (langRoot != null && FileEx.create(langRoot).isDirectory()) { addEntry(Key.GET_GAME_LANG_FOLDER_NAME, Type.STRING, language); addEntry(Key.GET_GAME_LANG_FOLDER, Type.PATH, langRoot); List langPaths = ResourceFactory.getAvailableGameLanguages(); @@ -1607,7 +1608,7 @@ private void initRootDirs() // adding fallback language added if selected language is non-english Path langRootDef = FileManager.query((Path)getProperty(Key.GET_GAME_LANG_FOLDER_BASE), languageDef); - if (!languageDef.equals(language) && langRootDef != null && Files.isDirectory(langRootDef)) { + if (!languageDef.equals(language) && langRootDef != null && FileEx.create(langRootDef).isDirectory()) { listRoots.add(langRootDef); } @@ -1630,7 +1631,7 @@ private void initExtraFolders() List list = new ArrayList<>(extraFolders.size()); extraFolders.forEach((folder) -> { Path path = FileManager.query(root, folder); - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } }); @@ -1681,48 +1682,48 @@ private void initOverrides() // registering override paths for (final Path root: gameRoots) { Path path = FileManager.query(root, langFolder, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } } path = FileManager.query(root, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, langFolder, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } if (langFolderDef != null) { path = FileManager.query(root, langFolderDef, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } } path = FileManager.query(root, langFolder, "Fonts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, langFolder, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } } } else { Path root = getGameRoot(); Path path = FileManager.query(root, "Movies"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Characters"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Portraits"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Sounds"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Scripts"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } path = FileManager.query(root, "Override"); - if (path != null && Files.isDirectory(path)) { list.add(path); } + if (path != null && FileEx.create(path).isDirectory()) { list.add(path); } } list.forEach((path) -> { FileWatcher.getInstance().register(path, false); }); @@ -1905,7 +1906,7 @@ private void initFeatures() // Has TobEx been installed? if (engine == Engine.BG2) { Path tobexIni = FileManager.query(getGameRoot(), "TobEx_ini/TobExCore.ini"); - addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Files.isRegularFile(tobexIni)); + addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, FileEx.create(tobexIni).isFile()); } else { addEntry(Key.IS_GAME_TOBEX, Type.BOOLEAN, Boolean.FALSE); } @@ -1980,7 +1981,7 @@ private void initCampaigns() if (model != null) { List extraDirs = getProperty(Key.GET_GAME_EXTRA_FOLDERS); for (final Path path: extraDirs) { - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { String folderName = path.getFileName().toString(); if (model.getFolder(folderName) == null) { model.addDirectory((ResourceTreeFolder)model.getRoot(), path, false); @@ -2004,19 +2005,19 @@ private List initDlc(Path rootDir, Path homeDir) List gameFolders = new ArrayList<>(); // Getting potential DLC folders (search order is important) - if (rootDir != null && Files.isDirectory(rootDir)) { + if (rootDir != null && FileEx.create(rootDir).isDirectory()) { gameFolders.add(new ObjectString("mod", rootDir.resolve("workshop"))); gameFolders.add(new ObjectString("zip", rootDir.resolve("dlc"))); gameFolders.add(new ObjectString("zip", rootDir)); } - if (homeDir != null && Files.isDirectory(homeDir)) { + if (homeDir != null && FileEx.create(homeDir).isDirectory()) { gameFolders.add(new ObjectString("zip", homeDir)); } for (final ObjectString root: gameFolders) { String ext = root.getString(); Path dir = root.getObject(); - if (dir != null && Files.isDirectory(dir)) { + if (dir != null && FileEx.create(dir).isDirectory()) { List list = new ArrayList<>(); try (DirectoryStream dstream = Files.newDirectoryStream(dir)) { for (final Path file: dstream) { @@ -2065,7 +2066,7 @@ private List initDlc(Path rootDir, Path homeDir) private Path validateDlc(Path file, String ext) throws IOException { // is regular file? - if (file == null && !Files.isRegularFile(file)) { + if (file == null && !FileEx.create(file).isFile()) { return null; } @@ -2098,7 +2099,7 @@ public void fileChanged(FileWatchEvent e) if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { Path path = e.getPath(); - if (Files.isDirectory(path)) { + 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)) { diff --git a/src/org/infinity/resource/ResourceFactory.java b/src/org/infinity/resource/ResourceFactory.java index 0827e5a01..5af28ee65 100644 --- a/src/org/infinity/resource/ResourceFactory.java +++ b/src/org/infinity/resource/ResourceFactory.java @@ -90,6 +90,7 @@ import org.infinity.util.DynamicArray; import org.infinity.util.IdsMapCache; import org.infinity.util.Misc; +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; @@ -499,7 +500,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search List extraFolders = Profile.getOverrideFolders(searchExtraDirs); if (extraFolders != null) { Path file = FileManager.query(extraFolders, resourceName); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { entry = new FileResourceEntry(file); } } @@ -508,7 +509,7 @@ public static ResourceEntry getResourceEntry(String resourceName, boolean search // checking custom folder list if (extraDirs != null && (entry == null)) { Path file = FileManager.query(extraDirs, resourceName); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { entry = new FileResourceEntry(file); } } @@ -710,12 +711,12 @@ public static List getAvailableGameLanguages() if (Profile.isEnhancedEdition()) { Path langPath = Profile.getProperty(Profile.Key.GET_GAME_LANG_FOLDER_BASE); - if (langPath != null && Files.isDirectory(langPath)) { + if (langPath != null && FileEx.create(langPath).isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(langPath, (Path entry) -> { - return Files.isDirectory(entry) && + return FileEx.create(entry).isDirectory() && entry.getFileName().toString().matches("[a-z]{2}_[A-Z]{2}") && - Files.isRegularFile(FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME))); + FileEx.create(FileManager.query(entry, Profile.getProperty(Profile.Key.GET_GLOBAL_DIALOG_NAME))).isFile(); })) { dstream.forEach((path) -> list.add(path)); } catch (IOException e) { @@ -730,7 +731,7 @@ public static List getAvailableGameLanguages() public static String autodetectGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { + if (Profile.isEnhancedEdition() && iniFile != null && FileEx.create(iniFile).isFile()) { // Attempt to autodetect game language try (BufferedReader br = Files.newBufferedReader(iniFile, Misc.CHARSET_UTF8)) { String line; @@ -743,7 +744,7 @@ public static String autodetectGameLanguage(Path iniFile) lang = lang.replaceFirst("'.*$", ""); if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { try { // try to fetch the actual path name to ensure correct case return path.toRealPath().getFileName().toString(); @@ -771,7 +772,7 @@ static Path getHomeRoot(boolean allowMissing) final Path EE_DOC_ROOT = FileSystemView.getFileSystemView().getDefaultDirectory().toPath(); final String EE_DIR = Profile.getProperty(Profile.Key.GET_GAME_HOME_FOLDER_NAME); Path userPath = FileManager.query(EE_DOC_ROOT, EE_DIR); - if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { + if (allowMissing || (userPath != null && FileEx.create(userPath).isDirectory())) { return userPath; } else { // fallback solution @@ -797,7 +798,7 @@ static Path getHomeRoot(boolean allowMissing) } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("bsd")) { userPath = FileManager.resolve(FileManager.resolve(userPrefix, ".local", "share", EE_DIR)); } - if (allowMissing || (userPath != null && Files.isDirectory(userPath))) { + if (allowMissing || (userPath != null && FileEx.create(userPath).isDirectory())) { return userPath; } } @@ -825,7 +826,7 @@ static List getBIFFDirs() // fetching the CD folders in a game installation Path iniFile = Profile.getProperty(Profile.Key.GET_GAME_INI_FILE); List rootFolders = Profile.getRootFolders(); - if (iniFile != null && Files.isRegularFile(iniFile)) { + if (iniFile != null && FileEx.create(iniFile).isFile()) { try (BufferedReader br = Files.newBufferedReader(iniFile)) { String line; while ((line = br.readLine()) != null) { @@ -845,7 +846,7 @@ static List getBIFFDirs() Path path; if (line.charAt(0) == '/') { // absolute Unix path path = FileManager.resolve(line); - if (path == null || !Files.isDirectory(path)) { // try relative Unix path + if (path == null || !FileEx.create(path).isDirectory()) { // try relative Unix path path = FileManager.query(rootFolders, line); } } else if (line.indexOf(':') < 0) { // relative Unix path @@ -853,7 +854,7 @@ static List getBIFFDirs() } else { path = FileManager.resolve(line); } - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { dirList.add(path); } } @@ -871,13 +872,13 @@ static List getBIFFDirs() Path path; for (int i = 1; i < 7; i++) { path = FileManager.query(rootFolders, "CD" + i); - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { dirList.add(path); } } // used in certain games path = FileManager.query(rootFolders, "CDALL"); - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { dirList.add(path); } } @@ -890,7 +891,7 @@ static String fetchGameLanguage(Path iniFile) { final String langDefault = "en_US"; // using default language, if no language entry found - if (Profile.isEnhancedEdition() && iniFile != null && Files.isRegularFile(iniFile)) { + if (Profile.isEnhancedEdition() && iniFile != null && FileEx.create(iniFile).isFile()) { String lang = BrowserMenuBar.getInstance().getSelectedGameLanguage(); if (lang == null || lang.isEmpty()) { @@ -899,7 +900,7 @@ static String fetchGameLanguage(Path iniFile) // Using user-defined language if (lang.matches("[A-Za-z]{2}_[A-Za-z]{2}")) { Path path = FileManager.query(Profile.getGameRoot(), "lang", lang); - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { String retVal; try { // try to fetch the actual path name to ensure correct case @@ -1023,7 +1024,7 @@ private Path getExportFileDialogInternal(Component parent, String fileName, bool fc.setSelectedFile(new File(fc.getCurrentDirectory(), fileName)); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { path = fc.getSelectedFile().toPath(); - if (!forceOverwrite && Files.exists(path)) { + if (!forceOverwrite && FileEx.create(path).exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, path + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -1169,7 +1170,7 @@ private void registerResourceInternal(Path resource, boolean autoselect) !Profile.isResourceTypeSupported(FileManager.getFileExtension(resource))) { return; } - if (resource == null || !Files.isRegularFile(resource)) { + if (resource == null || !FileEx.create(resource).isFile()) { return; } @@ -1301,7 +1302,7 @@ private void loadResourcesInternal() throws Exception NearInfinity.advanceProgress("Loading extra resources..."); List extraPaths = Profile.getProperty(Profile.Key.GET_GAME_EXTRA_FOLDERS); extraPaths.forEach((path) -> { - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { treeModel.addDirectory(treeModel.getRoot(), path, false); } }); @@ -1312,10 +1313,10 @@ private void loadResourcesInternal() throws Exception String overrideFolder = Profile.getOverrideFolderName(); List overridePaths = Profile.getOverrideFolders(false); for (final Path overridePath: overridePaths) { - if (Files.isDirectory(overridePath)) { + if (FileEx.create(overridePath).isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(overridePath)) { dstream.forEach((path) -> { - if (Files.isRegularFile(path)) { + if (FileEx.create(path).isFile()) { ResourceEntry entry = getResourceEntry(path.getFileName().toString()); if (entry instanceof FileResourceEntry) { treeModel.addResourceEntry(entry, entry.getTreeFolderName(), true); @@ -1388,7 +1389,7 @@ private void loadSpecialResources() */ private void addFileResource(Path path) { - if (path != null && Files.isRegularFile(path)) { + if (path != null && FileEx.create(path).isFile()) { treeModel.addResourceEntry(new FileResourceEntry(path), SPECIAL_CATEGORY, false); } } @@ -1516,7 +1517,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) outFile = FileManager.query(Profile.getGameRoot(), "Scripts", fileName); } - if (Files.exists(outFile)) { + if (FileEx.create(outFile).exists()) { String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(NearInfinity.getInstance(), outFile + " exists. Overwrite?", "Confirm overwrite " + outFile, JOptionPane.YES_NO_OPTION, @@ -1525,7 +1526,7 @@ private void saveCopyOfResourceInternal(ResourceEntry entry) } // creating override folder in game directory if it doesn't exist - if (!Files.isDirectory(outPath)) { + if (!FileEx.create(outPath).isDirectory()) { try { Files.createDirectory(outPath); } catch (IOException e) { @@ -1573,7 +1574,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) Path outPath; if (entry instanceof BIFFResourceEntry) { Path overridePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); - if (!Files.isDirectory(overridePath)) { + if (!FileEx.create(overridePath).isDirectory()) { try { Files.createDirectory(overridePath); } catch (IOException e) { @@ -1590,7 +1591,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) // 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 && !Files.exists(outPath.getParent())) { + if (outPath != null && !FileEx.create(outPath.getParent()).exists()) { try { Files.createDirectories(outPath.getParent()); } catch (IOException e) { @@ -1602,7 +1603,7 @@ private boolean saveResourceInternal(Resource resource, Component parent) } } } - if (Files.exists(outPath)) { + if (FileEx.create(outPath).exists()) { outPath = outPath.toAbsolutePath(); String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, outPath + " exists. Overwrite?", "Save resource", @@ -1611,10 +1612,10 @@ private boolean saveResourceInternal(Resource resource, Component parent) if (BrowserMenuBar.getInstance().backupOnSave()) { try { Path bakPath = outPath.getParent().resolve(outPath.getFileName() + ".bak"); - if (Files.isRegularFile(bakPath)) { + if (FileEx.create(bakPath).isFile()) { Files.delete(bakPath); } - if (!Files.exists(bakPath)) { + if (!FileEx.create(bakPath).exists()) { Files.move(outPath, bakPath); } } catch (IOException e) { diff --git a/src/org/infinity/resource/StructureFactory.java b/src/org/infinity/resource/StructureFactory.java index 3fa9e537d..08360b4d2 100644 --- a/src/org/infinity/resource/StructureFactory.java +++ b/src/org/infinity/resource/StructureFactory.java @@ -7,7 +7,6 @@ import java.awt.Window; 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.EnumMap; @@ -23,6 +22,7 @@ import org.infinity.gui.NewResSettings; import org.infinity.util.Misc; import org.infinity.util.ResourceStructure; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -90,7 +90,7 @@ public void newResource(ResType type, Window parent) roots.add(Profile.getGameRoot()); } savePath = FileManager.query(roots, "Characters"); - if (!Files.isDirectory(savePath)) { + if (!FileEx.create(savePath).isDirectory()) { savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); } break; @@ -99,7 +99,7 @@ public void newResource(ResType type, Window parent) savePath = FileManager.query(Profile.getGameRoot(), Profile.getOverrideFolderName()); break; } - if (savePath == null || !Files.isDirectory(savePath) ) { + if (savePath == null || !FileEx.create(savePath).isDirectory()) { savePath = Profile.getGameRoot(); } JFileChooser fc = new JFileChooser(savePath.toFile()); @@ -110,7 +110,7 @@ public void newResource(ResType type, Window parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), "UNTITLED." + resExt.get(type))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { Path outFile = fc.getSelectedFile().toPath(); - if (Files.exists(outFile)) { + if (FileEx.create(outFile).exists()) { 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) diff --git a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java index 0f44cee0f..0ec147c1d 100644 --- a/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java +++ b/src/org/infinity/resource/are/viewer/LayerObjectAutomap.java @@ -6,7 +6,6 @@ import java.awt.Image; import java.awt.Point; -import java.nio.file.Files; import java.nio.file.Path; import org.infinity.datatype.IsNumeric; @@ -27,6 +26,7 @@ import org.infinity.resource.to.StringEntry2; import org.infinity.resource.to.TohResource; import org.infinity.resource.to.TotResource; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; /** @@ -65,7 +65,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) if (Profile.isEnhancedEdition()) { // processing new TOH structure Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); - if (Files.exists(tohFile)) { + if (FileEx.create(tohFile).exists()) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); TohResource toh = new TohResource(tohEntry); SectionOffset so = (SectionOffset)toh.getAttribute(TohResource.TOH_OFFSET_ENTRIES); @@ -92,7 +92,7 @@ public LayerObjectAutomap(AreResource parent, AutomapNote note) // processing legacy TOH/TOT structures Path tohFile = FileManager.resolve(path, "DEFAULT.TOH"); Path totFile = FileManager.resolve(path, "DEFAULT.TOT"); - if (Files.exists(tohFile) && Files.exists(totFile)) { + if (FileEx.create(tohFile).exists() && FileEx.create(totFile).exists()) { FileResourceEntry tohEntry = new FileResourceEntry(tohFile); FileResourceEntry totEntry = new FileResourceEntry(totFile); TohResource toh = new TohResource(tohEntry); diff --git a/src/org/infinity/resource/graphics/BamV2Decoder.java b/src/org/infinity/resource/graphics/BamV2Decoder.java index cf28a0ba6..bf061f011 100644 --- a/src/org/infinity/resource/graphics/BamV2Decoder.java +++ b/src/org/infinity/resource/graphics/BamV2Decoder.java @@ -11,7 +11,6 @@ import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.nio.ByteBuffer; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; @@ -23,6 +22,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -250,7 +250,7 @@ private PvrDecoder getPVR(int page) if (bamPath != null) { // preferring PVRZ files from the BAM's base path Path pvrzFile = FileManager.resolve(bamPath.resolve(name)); - if (Files.isRegularFile(pvrzFile)) { + if (FileEx.create(pvrzFile).isFile()) { entry = new FileResourceEntry(pvrzFile); } } diff --git a/src/org/infinity/resource/graphics/ColorConvert.java b/src/org/infinity/resource/graphics/ColorConvert.java index 777b2117f..a5ba46378 100644 --- a/src/org/infinity/resource/graphics/ColorConvert.java +++ b/src/org/infinity/resource/graphics/ColorConvert.java @@ -34,6 +34,7 @@ import javax.imageio.stream.ImageInputStream; import org.infinity.util.DynamicArray; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; /** @@ -437,7 +438,7 @@ public static boolean medianCut(int[] pixels, int desiredColors, int[] palette, */ public static int[] loadPaletteBMP(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); @@ -485,7 +486,7 @@ public static int[] loadPaletteBMP(Path file) throws Exception */ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { BufferedImage img = ImageIO.read(is); if (img.getType() == BufferedImage.TYPE_BYTE_INDEXED) { @@ -517,7 +518,7 @@ public static int[] loadPalettePNG(Path file, boolean preserveAlpha) throws Exce */ public static int[] loadPalettePAL(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[12]; boolean eof = is.read(signature) != signature.length; @@ -569,7 +570,7 @@ public static int[] loadPalettePAL(Path file) throws Exception */ public static int[] loadPaletteACT(Path file) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { int size = (int)Files.size(file); if (size >= 768) { @@ -611,7 +612,7 @@ public static int[] loadPaletteACT(Path file) throws Exception */ public static int[] loadPaletteBAM(Path file, boolean preserveAlpha) throws Exception { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (InputStream is = StreamUtils.getInputStream(file)) { byte[] signature = new byte[8]; is.read(signature); diff --git a/src/org/infinity/resource/graphics/TisResource.java b/src/org/infinity/resource/graphics/TisResource.java index 3fecf273f..0830352da 100644 --- a/src/org/infinity/resource/graphics/TisResource.java +++ b/src/org/infinity/resource/graphics/TisResource.java @@ -84,6 +84,7 @@ import org.infinity.util.BinPack2D; import org.infinity.util.DynamicArray; import org.infinity.util.IntegerHashMap; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; /** @@ -567,7 +568,7 @@ private Path getTisFileName(Component parent, boolean enforceValidName) } else { repeat = false; } - if (Files.exists(retVal)) { + if (FileEx.create(retVal).exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -596,7 +597,7 @@ private Path getPngFileName(Component parent) fc.setSelectedFile(new File(fc.getCurrentDirectory(), getResourceEntry().getResourceName().toUpperCase(Locale.ENGLISH).replace(".TIS", ".PNG"))); if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { retVal = fc.getSelectedFile().toPath(); - if (Files.exists(retVal)) { + if (FileEx.create(retVal).exists()) { final String options[] = {"Overwrite", "Cancel"}; if (JOptionPane.showOptionDialog(parent, retVal + " exists. Overwrite?", "Export resource", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, @@ -744,7 +745,7 @@ public Status convertToPaletteTis(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && FileEx.create(output).isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -980,7 +981,7 @@ public Status convertToPvrzTis(Path output, boolean showProgress) retVal = Status.ERROR; e.printStackTrace(); } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && FileEx.create(output).isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -1038,7 +1039,7 @@ public Status exportPNG(Path output, boolean showProgress) progress = null; } } - if (retVal != Status.SUCCESS && Files.isRegularFile(output)) { + if (retVal != Status.SUCCESS && FileEx.create(output).isFile()) { try { Files.delete(output); } catch (IOException e) { @@ -1133,7 +1134,7 @@ private Status writePvrzPages(Path tisFile, List pageList, if (retVal != Status.SUCCESS) { for (int i = 0; i < pageList.size(); i++) { Path pvrzFile = generatePvrzFileName(tisFile, i); - if (pvrzFile != null && Files.isRegularFile(pvrzFile)) { + if (pvrzFile != null && FileEx.create(pvrzFile).isFile()) { try { Files.delete(pvrzFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/BIFFEntry.java b/src/org/infinity/resource/key/BIFFEntry.java index de369f3ce..8188e7498 100644 --- a/src/org/infinity/resource/key/BIFFEntry.java +++ b/src/org/infinity/resource/key/BIFFEntry.java @@ -7,13 +7,13 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.infinity.resource.Writeable; import org.infinity.resource.Profile; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -125,7 +125,7 @@ public String getFileName() /** Returns whether the referenced BIFF file exists in the game. */ public boolean exists() { - return (biffFile != null && Files.isRegularFile(biffFile)); + return (biffFile != null && FileEx.create(biffFile).isFile()); } /** Returns the absolute path to the BIFF file if it exists. */ @@ -241,7 +241,7 @@ private static Path findBiffFile(Path root, int location, String fileName) final String[] baseFolders = { "", "cache", "cd1", "cd2", "cd3", "cd4", "cd5", "cd6", "cd7", "cdall" }; for (final String folderName: baseFolders) { Path path = FileManager.resolve(root.resolve(folderName)); - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { biffFolders.add(path); } } diff --git a/src/org/infinity/resource/key/BIFFResourceEntry.java b/src/org/infinity/resource/key/BIFFResourceEntry.java index 030710ff7..c923481fc 100644 --- a/src/org/infinity/resource/key/BIFFResourceEntry.java +++ b/src/org/infinity/resource/key/BIFFResourceEntry.java @@ -18,6 +18,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.ResourceFactory; import org.infinity.resource.Writeable; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -113,12 +114,12 @@ public void deleteOverride() throws IOException { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { Files.deleteIfExists(file); } file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && Files.isRegularFile(file)); + hasOverride = (file != null && FileEx.create(file).isFile()); } } @@ -128,7 +129,7 @@ public Path getActualPath(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { return file; } } @@ -148,7 +149,7 @@ public long getResourceSize(boolean ignoreOverride) if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { retVal = Files.size(file); return retVal; } @@ -191,7 +192,7 @@ public ByteBuffer getResourceBuffer(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { @@ -212,7 +213,7 @@ public InputStream getResourceDataAsStream(boolean ignoreOverride) throws Except if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { return StreamUtils.getInputStream(file); } } @@ -226,7 +227,7 @@ public int[] getResourceInfo(boolean ignoreOverride) throws Exception if (!ignoreOverride) { List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { return getLocalFileInfo(file); } } @@ -277,7 +278,7 @@ public boolean hasOverride() List overrides = Profile.getOverrideFolders(false); Path file = FileManager.query(overrides, getResourceName()); synchronized (this) { - hasOverride = (file != null && Files.isRegularFile(file)); + hasOverride = (file != null && FileEx.create(file).isFile()); } } return hasOverride; diff --git a/src/org/infinity/resource/key/BIFFWriter.java b/src/org/infinity/resource/key/BIFFWriter.java index a5cd0b333..e911ef3de 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.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -121,7 +122,7 @@ public void addResource(ResourceEntry resourceEntry, boolean ignoreoverride) public void write() throws Exception { Path biffPath = FileManager.query(Profile.getGameRoot(), "data"); - if (biffPath == null || !Files.isDirectory(biffPath)) { + if (biffPath == null || !FileEx.create(biffPath).isDirectory()) { throw new Exception("No BIFF folder found."); } Path dummyFile = Files.createTempFile(biffPath, "_dummy", ".bif"); @@ -136,7 +137,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (FileEx.create(realFile).isFile()) { Files.delete(realFile); } Files.move(dummyFile, realFile); @@ -149,7 +150,7 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getGameRoot(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (FileEx.create(realFile).isFile()) { Files.delete(realFile); } Files.move(compressedFile, realFile); @@ -162,19 +163,19 @@ public void write() throws Exception if (realFile == null) { realFile = FileManager.query(Profile.getRootFolders(), bifEntry.getFileName()); } - if (Files.isRegularFile(realFile)) { + if (FileEx.create(realFile).isFile()) { Files.delete(realFile); } Files.move(compressedFile, realFile); } } finally { - if (dummyFile != null && Files.isRegularFile(dummyFile)) { + if (dummyFile != null && FileEx.create(dummyFile).isFile()) { try { Files.delete(dummyFile); } catch (IOException e) { } } - if (compressedFile != null && Files.isRegularFile(compressedFile)) { + if (compressedFile != null && FileEx.create(compressedFile).isFile()) { try { Files.delete(compressedFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/key/Keyfile.java b/src/org/infinity/resource/key/Keyfile.java index feaf81009..aaef18511 100644 --- a/src/org/infinity/resource/key/Keyfile.java +++ b/src/org/infinity/resource/key/Keyfile.java @@ -27,6 +27,7 @@ import org.infinity.resource.ResourceFactory; import org.infinity.util.IntegerHashMap; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; public class Keyfile @@ -112,7 +113,7 @@ public Keyfile(Path keyFile) throws FileNotFoundException if (keyFile == null) { throw new NullPointerException("No keyfile specified"); } - if (!Files.isRegularFile(keyFile)) { + if (!FileEx.create(keyFile).isFile()) { throw new FileNotFoundException("Keyfile " + keyFile + " not found or is not regular file"); } @@ -461,7 +462,7 @@ public void run() biffList.forEach((entry) -> { if (entry != null) { Path biffPath = entry.getPath(); - if (biffPath != null && Files.isRegularFile(biffPath)) { + if (biffPath != null && FileEx.create(biffPath).isFile()) { try { AbstractBIFFReader.open(biffPath); } catch (Exception e) { @@ -481,7 +482,7 @@ public void run() // if (keyFile == null) { // throw new NullPointerException(); // } -// if (!Files.isRegularFile(keyFile)) { +// if (!FileEx.fromPath(keyFile).isFile()) { // throw new IOException("Key file not found: " + keyFile); // } // @@ -515,11 +516,11 @@ private void init() throws IOException if (getKeyfile() == null) { throw new NullPointerException(); } - if (!Files.isRegularFile(getKeyfile())) { + if (!FileEx.create(getKeyfile()).isFile()) { throw new IOException("Key file not found: " + getKeyfile()); } for (final Path file: keyList) { - if (file != null && !Files.isRegularFile(file)) { + if (file != null && !FileEx.create(file).isFile()) { throw new IOException("Key file not found: " + file); } } diff --git a/src/org/infinity/resource/key/ResourceEntry.java b/src/org/infinity/resource/key/ResourceEntry.java index 1b5ffac7e..49cb603a6 100644 --- a/src/org/infinity/resource/key/ResourceEntry.java +++ b/src/org/infinity/resource/key/ResourceEntry.java @@ -31,6 +31,7 @@ import org.infinity.resource.sto.StoResource; import org.infinity.resource.text.PlainTextResource; import org.infinity.search.SearchOptions; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; public abstract class ResourceEntry implements Comparable @@ -47,7 +48,7 @@ public abstract class ResourceEntry implements Comparable static int[] getLocalFileInfo(Path file) { - if (file != null && Files.isRegularFile(file)) { + if (file != null && FileEx.create(file).isFile()) { try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.READ)) { ByteBuffer bb = StreamUtils.getByteBuffer((int)ch.size()); if (ch.read(bb) < ch.size()) { diff --git a/src/org/infinity/resource/key/ResourceTreeModel.java b/src/org/infinity/resource/key/ResourceTreeModel.java index ea4777b11..f0116c17a 100644 --- a/src/org/infinity/resource/key/ResourceTreeModel.java +++ b/src/org/infinity/resource/key/ResourceTreeModel.java @@ -24,6 +24,7 @@ import javax.swing.tree.TreePath; import org.infinity.util.Misc; +import org.infinity.util.io.FileEx; public final class ResourceTreeModel implements TreeModel { @@ -113,7 +114,7 @@ public void addDirectory(ResourceTreeFolder parentFolder, Path directory, boolea if (iter.hasNext()) { final ResourceTreeFolder folder = addFolder(parentFolder, directory.getFileName().toString()); iter.forEachRemaining((path) -> { - if (Files.isDirectory(path)) { + if (FileEx.create(path).isDirectory()) { addDirectory(folder, path, overwrite); } else { folder.addResourceEntry(new FileResourceEntry(path), overwrite); diff --git a/src/org/infinity/resource/mus/Entry.java b/src/org/infinity/resource/mus/Entry.java index de04eff38..fdc5b962a 100644 --- a/src/org/infinity/resource/mus/Entry.java +++ b/src/org/infinity/resource/mus/Entry.java @@ -17,6 +17,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sound.AudioBuffer; import org.infinity.resource.sound.AudioFactory; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -175,13 +176,13 @@ private AudioBuffer getAudioBuffer(String fileName) throws IOException { // audio file can reside in a number of different locations Path acmFile = FileManager.query(entry.getActualPath().getParent(), dir, dir + fileName + ".acm"); - if (!Files.isRegularFile(acmFile)) { + if (!FileEx.create(acmFile).isFile()) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName + ".acm"); } - if (!Files.isRegularFile(acmFile) && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { + if (!FileEx.create(acmFile).isFile() && fileName.toUpperCase(Locale.ENGLISH).startsWith("MX")) { acmFile = FileManager.query(entry.getActualPath().getParent(), fileName.substring(0, 6), fileName + ".acm"); } - if (!Files.isRegularFile(acmFile)) { + if (!FileEx.create(acmFile).isFile()) { throw new IOException("Could not find " + fileName); } diff --git a/src/org/infinity/resource/sav/IOHandler.java b/src/org/infinity/resource/sav/IOHandler.java index c92c1d8b3..d0fc5044e 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.io.FileEx; import org.infinity.util.io.StreamUtils; public final class IOHandler implements Writeable @@ -63,7 +64,7 @@ public void write(OutputStream os) throws IOException public void close() { - if (tempFolder != null && Files.isDirectory(tempFolder)) { + if (tempFolder != null && FileEx.create(tempFolder).isDirectory()) { try (DirectoryStream dstream = Files.newDirectoryStream(tempFolder)) { for (final Path file: dstream) { try { @@ -128,7 +129,7 @@ private Path createTempFolder() { for (int idx = 0; idx < Integer.MAX_VALUE; idx++) { Path path = Profile.getHomeRoot().resolve(String.format("%s.%03d", entry.getTreeFolderName(), idx)); - if (!Files.exists(path)) { + if (!FileEx.create(path).exists()) { return path; } } diff --git a/src/org/infinity/resource/sav/SavResource.java b/src/org/infinity/resource/sav/SavResource.java index ff345fdbf..3ee3ef65c 100644 --- a/src/org/infinity/resource/sav/SavResource.java +++ b/src/org/infinity/resource/sav/SavResource.java @@ -50,6 +50,7 @@ import org.infinity.resource.key.FileResourceEntry; import org.infinity.resource.key.ResourceEntry; import org.infinity.util.SimpleListModel; +import org.infinity.util.io.FileEx; /** * This resource acts as a standalone compressed archive. The file is zlib compressed, @@ -362,7 +363,7 @@ private void addResource(ResourceEntry resourceEntry) if (resourceEntry != null) { Path output = handler.getTempFolder().resolve(resourceEntry.getResourceName()); try { - if (Files.exists(output)) { + if (FileEx.create(output).exists()) { String msg = "File " + resourceEntry.getResourceName() + " already exists. Overwrite?"; int ret = JOptionPane.showConfirmDialog(panel.getTopLevelAncestor(), msg, "Overwrite file?", JOptionPane.YES_NO_OPTION, @@ -410,7 +411,7 @@ private void removeResource(int entryIndex) if (entryIndex >= 0 && entryIndex < entries.size()) { ResourceEntry resourceEntry = entries.get(entryIndex); Path file = resourceEntry.getActualPath(); - if (Files.exists(file)) { + if (FileEx.create(file).exists()) { try { Files.delete(file); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/MveResource.java b/src/org/infinity/resource/video/MveResource.java index 98365b064..af236f073 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.io.FileEx; import org.monte.media.AudioFormatKeys; import org.monte.media.Format; import org.monte.media.FormatKeys; @@ -476,7 +477,7 @@ AudioFormatKeys.SampleRateKey, new Rational(sampleRate), writer.close(); writer = null; } - if (Files.isRegularFile(outFile)) { + if (FileEx.create(outFile).isFile()) { try { Files.delete(outFile); } catch (IOException e) { diff --git a/src/org/infinity/resource/video/WbmResource.java b/src/org/infinity/resource/video/WbmResource.java index 5361c20cd..f06b492c3 100644 --- a/src/org/infinity/resource/video/WbmResource.java +++ b/src/org/infinity/resource/video/WbmResource.java @@ -36,6 +36,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.search.ReferenceSearcher; import org.infinity.util.FileDeletionHook; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -107,7 +108,7 @@ public void close() throws Exception { try { // first attempt to delete temporary video file - if (videoFile != null && Files.isRegularFile(videoFile) && isTempFile) { + if (videoFile != null && FileEx.create(videoFile).isFile() && isTempFile) { Files.delete(videoFile); } } catch (Exception e) { @@ -173,7 +174,7 @@ private Path getVideoFile() fileExt = "wbm"; try { Path outFile = Files.createTempFile(fileBase + "-", "." + fileExt); - if (Files.isRegularFile(outFile)) { + if (FileEx.create(outFile).isFile()) { try (InputStream is = entry.getResourceDataAsStream()) { try (OutputStream os = StreamUtils.getOutputStream(outFile, true)) { byte[] buffer = new byte[8192]; diff --git a/src/org/infinity/updater/Updater.java b/src/org/infinity/updater/Updater.java index 1dd8cec8e..fb4348ca7 100644 --- a/src/org/infinity/updater/Updater.java +++ b/src/org/infinity/updater/Updater.java @@ -10,7 +10,6 @@ import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; -import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarFile; @@ -18,6 +17,7 @@ import java.util.zip.ZipEntry; import org.infinity.NearInfinity; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; /** @@ -190,7 +190,7 @@ static String getJarFileHash() String path = Utils.getJarFileName(NearInfinity.class); if (path != null && !path.isEmpty()) { Path jarPath = FileManager.resolve(path); - if (Files.isRegularFile(jarPath)) { + if (FileEx.create(jarPath).isFile()) { try { return Utils.generateMD5Hash(new FileInputStream(path)); } catch (IOException e) { diff --git a/src/org/infinity/updater/Utils.java b/src/org/infinity/updater/Utils.java index 4fae8ac40..0bc13ccff 100644 --- a/src/org/infinity/updater/Utils.java +++ b/src/org/infinity/updater/Utils.java @@ -23,7 +23,6 @@ import java.net.URLConnection; import java.net.UnknownServiceException; import java.nio.charset.Charset; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; @@ -47,6 +46,8 @@ import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; +import org.infinity.util.io.FileEx; + import static org.infinity.util.Misc.toNumber; /** @@ -87,7 +88,7 @@ public static String getJarFileName(Class classType) if (url != null) { try { Path file = Paths.get(url.toURI()); - if (Files.exists(file)) { + if (FileEx.create(file).exists()) { return file.toString(); } } catch (URISyntaxException e) { diff --git a/src/org/infinity/util/FileDeletionHook.java b/src/org/infinity/util/FileDeletionHook.java index 7c0101772..573e81fbc 100644 --- a/src/org/infinity/util/FileDeletionHook.java +++ b/src/org/infinity/util/FileDeletionHook.java @@ -9,6 +9,8 @@ import java.util.LinkedHashSet; import java.util.Set; +import org.infinity.util.io.FileEx; + /** * Attempts to delete all registered files when the JVM terminates. */ @@ -33,7 +35,7 @@ public void run() { synchronized (listFilesToDelete) { for (final Path file: listFilesToDelete) { - if (file != null && Files.exists(file)) { + if (file != null && FileEx.create(file).exists()) { try { Files.delete(file); } catch (Throwable t) { diff --git a/src/org/infinity/util/MassExporter.java b/src/org/infinity/util/MassExporter.java index ac074ec2c..5b7c43005 100644 --- a/src/org/infinity/util/MassExporter.java +++ b/src/org/infinity/util/MassExporter.java @@ -68,6 +68,7 @@ import org.infinity.resource.key.ResourceEntry; import org.infinity.resource.sound.AudioFactory; import org.infinity.resource.video.MveResource; +import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; import org.infinity.util.io.StreamUtils; @@ -386,7 +387,7 @@ private void exportText(ResourceEntry entry, Path output) throws Exception private void exportDecompiledScript(ResourceEntry entry, Path output) throws Exception { output = output.getParent().resolve(StreamUtils.replaceFileExtension(output.getFileName().toString(), "BAF")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } ByteBuffer bb = entry.getResourceBuffer(); @@ -434,7 +435,7 @@ private void mosToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("MOS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } @@ -459,7 +460,7 @@ private void pvrzToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("PVRZ")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } @@ -481,7 +482,7 @@ private void tisToPng(ResourceEntry entry, Path output) throws Exception { if (entry != null && entry.getExtension().equalsIgnoreCase("TIS")) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "PNG")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } @@ -531,7 +532,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception // creating subfolder for frames Path path = filePath.resolve(fileBase); - if (!Files.exists(path)) { + if (!FileEx.create(path).exists()) { try { Files.createDirectory(path); } catch (IOException e) { @@ -541,7 +542,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception JOptionPane.showMessageDialog(NearInfinity.getInstance(), msg, "Error", JOptionPane.ERROR_MESSAGE); return; } - } else if (!Files.isDirectory(path)) { + } 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); @@ -557,7 +558,7 @@ private void extractBamFrames(ResourceEntry entry, Path output) throws Exception private void chrToCre(ResourceEntry entry, Path output) throws Exception { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "CRE")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } CreResource crefile = new CreResource(entry); @@ -612,7 +613,7 @@ private void export(ResourceEntry entry) { try { Path output = outputPath.resolve(entry.getResourceName()); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } if ((entry.getExtension().equalsIgnoreCase("IDS") || @@ -658,7 +659,7 @@ else if (entry.getExtension().equalsIgnoreCase("WAV") && cbConvertWAV.isSelected } else if (entry.getExtension().equalsIgnoreCase("MVE") && cbExportMVEasAVI.isSelected()) { output = outputPath.resolve(StreamUtils.replaceFileExtension(entry.getResourceName(), "avi")); - if (Files.exists(output) && !cbOverwrite.isSelected()) { + if (FileEx.create(output).exists() && !cbOverwrite.isSelected()) { return; } MveResource.convertAvi(entry, output, null, true); diff --git a/src/org/infinity/util/StringTable.java b/src/org/infinity/util/StringTable.java index b23968bde..fcc802785 100644 --- a/src/org/infinity/util/StringTable.java +++ b/src/org/infinity/util/StringTable.java @@ -27,6 +27,7 @@ import org.infinity.resource.Profile; import org.infinity.resource.StructEntry; import org.infinity.updater.Utils; +import org.infinity.util.io.FileEx; import org.infinity.util.io.StreamUtils; /** @@ -1341,11 +1342,11 @@ private void _write(Path tlkPath, ProgressCallback callback) throws IOException // 1. backing up current string table file if needed Path pathBackup = null; - if (Files.isRegularFile(tlkPath)) { + if (FileEx.create(tlkPath).isFile()) { String name = tlkPath.getFileName().toString(); for (int i = 0; i < 999; i++) { Path path = tlkPath.getParent().resolve(name + "-" + i); - if (!Files.exists(path)) { + if (!FileEx.create(path).exists()) { pathBackup = path; break; } diff --git a/src/org/infinity/util/io/DlcManager.java b/src/org/infinity/util/io/DlcManager.java index 250cba146..36c22f7b6 100644 --- a/src/org/infinity/util/io/DlcManager.java +++ b/src/org/infinity/util/io/DlcManager.java @@ -90,7 +90,7 @@ private FileSystem _register(Path dlcFile) throws IOException private FileSystem _getDlc(Path dlcFile) { - if (dlcFile != null && Files.isRegularFile(dlcFile)) { + if (dlcFile != null && FileEx.create(dlcFile).isFile()) { return fileSystems.get(dlcFile); } return null; @@ -107,7 +107,7 @@ private Path _queryKey(Path path) if (fs != null) { for (final String keyFile: KEY_FILES) { Path key = fs.getPath(keyFile); - if (key != null && Files.isRegularFile(key)) { + if (key != null && FileEx.create(key).isFile()) { try (InputStream is = StreamUtils.getInputStream(key)) { String sig = StreamUtils.readString(is, 8); if ("KEY V1 ".equals(sig)) { @@ -126,7 +126,7 @@ private Path _queryKey(Path path) private FileSystem _validateDlc(Path dlcFile) throws IOException { - if (dlcFile == null || !Files.isRegularFile(dlcFile)) { + if (dlcFile == null || !FileEx.create(dlcFile).isFile()) { return null; } diff --git a/src/org/infinity/util/io/FileEx.java b/src/org/infinity/util/io/FileEx.java new file mode 100644 index 000000000..3f06faa65 --- /dev/null +++ b/src/org/infinity/util/io/FileEx.java @@ -0,0 +1,666 @@ +// Near Infinity - An Infinity Engine Browser and Editor +// Copyright (C) 2001 - 2020 Jon Olav Hauglid +// See LICENSE.txt for license information + +package org.infinity.util.io; + +import java.io.File; +import java.io.FileFilter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.DosFileAttributeView; +import java.nio.file.attribute.FileTime; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Set; + +import org.infinity.util.FileDeletionHook; + +/** + * Expands the {@link File} class by custom filesystem support. + */ +public class FileEx extends File +{ + private static final FileSystem DEFAULT_FS = FileSystems.getDefault(); + + private final Path path; + + /** + * Constructs a FileEx instance from the specified Path argument. + * @param path The path definition with associated filesystem. + * @throws NullPointerException + * If {@code path} is {@code null} + */ + public static FileEx create(Path path) + { + return new FileEx(path); + } + + /** + * Creates a new {@code FileEx} instance by converting the given + * pathname string into an abstract pathname using the default filesystem. + * If the given string is the empty string, then the result is the empty + * abstract pathname. + * @param pathname A pathname string + * @throws NullPointerException + * If the {@code pathname} argument is {@code null} + */ + public FileEx(String pathname) + { + this(pathname, (FileSystem)null); + } + + /** + * Creates a new {@code FileEx} instance by converting the given + * pathname string into an abstract pathname using the specified filesystem. + * If the given string is the empty string, then the result is the empty + * abstract pathname. + * @param pathname A pathname string + * @param filesystem The associated filesystem. Specify {@code null} to use + * the default filesystem. + * @throws NullPointerException + * If the {@code pathname} argument is {@code null} + */ + public FileEx(String pathname, FileSystem filesystem) + { + super(pathname); + path = validatePath(validateFileSystem(filesystem).getPath(pathname)); + } + + /** + * Creates a new {@code FileEx} instance from a parent pathname string + * and a child pathname string using the default filesystem. + * @param parent The parent pathname string + * @param child The child pathname string + * @throws NullPointerException + * If {@code child} is {@code null} + */ + public FileEx(String parent, String child) + { + this(parent, child, null); + } + + /** + * Creates a new {@code FileEx} instance from a parent pathname string + * and a child pathname string with the specified filesystem. + * @param parent The parent pathname string + * @param child The child pathname string + * @param filesystem The associated filesystem. Specify {@code null} to use + * the default filesystem. + * @throws NullPointerException + * If {@code child} is {@code null} + */ + public FileEx(String parent, String child, FileSystem filesystem) + { + super(parent, child); + if (parent == null) { + path = validatePath(validateFileSystem(filesystem).getPath(child)); + } else { + path = validatePath(validateFileSystem(filesystem).getPath(parent, child)); + } + } + + /** + * Creates a new {@code FileEx} instance from a parent abstract + * pathname and a child pathname string with the default filesystem. + * @param parent The parent abstract pathname + * @param child The child pathname string + * @throws NullPointerException + * If {@code child} is {@code null} + * @throws InvalidPathException If no valid path can be constructed from the + * specified arguments. + */ + public FileEx(File parent, String child) + { + this(parent, child, null); + } + + /** + * Creates a new {@code FileEx} instance from a parent abstract + * pathname and a child pathname string with the specified filesystem. + * @param parent The parent abstract pathname + * @param child The child pathname string + * @param filesystem The associated filesystem. Specify {@code null} to use + * the default filesystem. + * @throws NullPointerException + * If {@code child} is {@code null} + * @throws InvalidPathException If no valid path can be constructed from the + * specified arguments. + */ + public FileEx(File parent, String child, FileSystem filesystem) + { + super(parent, child); + if (parent == null) { + path = validatePath(validateFileSystem(filesystem).getPath(child)); + } else { + path = validatePath(validateFileSystem(filesystem).getPath(parent.getAbsolutePath(), child)); + } + } + + /** + * Constructs a {@code FileEx} instance from the specified Path argument. + * @param path The path definition with associated filesystem. + * @throws NullPointerException + * If {@code path} is {@code null} + */ + public FileEx(Path path) + { + super((path != null) ? path.toString() : null); + this.path = validatePath(path); + } + + @Override + public boolean isAbsolute() + { + return (path == null) ? super.isAbsolute() : path.isAbsolute(); + } + + @Override + public String getAbsolutePath() + { + return (path == null) ? super.getAbsolutePath() : path.toAbsolutePath().toString(); + } + + @Override + public File getAbsoluteFile() + { + return (path == null) ? super.getAbsoluteFile() : new FileEx(path.toAbsolutePath()); + } + + @Override + public String getCanonicalPath() throws IOException + { + return (path == null) ? super.getCanonicalPath() : path.toAbsolutePath().normalize().toString(); + } + + @Override + public File getCanonicalFile() throws IOException + { + return (path == null) ? super.getCanonicalFile() : new FileEx(path.toAbsolutePath().normalize()); + } + + @Override + public boolean canRead() + { + return (path == null) ? super.canRead() : Files.isReadable(path); + } + + @Override + public boolean canWrite() + { + return (path == null) ? super.canWrite() : Files.isWritable(path); + } + + @Override + public boolean exists() + { + return (path == null) ? super.exists() : Files.exists(path, LinkOption.NOFOLLOW_LINKS); + } + + @Override + public boolean isDirectory() + { + return (path == null) ? super.isDirectory() : Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS); + } + + @Override + public boolean isFile() + { + return (path == null) ? super.isFile() : Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS); + } + + @Override + public boolean isHidden() + { + try { + return (path == null) ? super.isHidden() : Files.isHidden(path); + } catch (IOException ex) { + return false; + } + } + + @Override + public long lastModified() + { + try { + return (path == null) ? super.lastModified() : Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS).toMillis(); + } catch (IOException ex) { + return 0L; + } + } + + @Override + public long length() + { + try { + return (path == null) ? super.length() : Files.size(path); + } catch (IOException ex) { + return 0L; + } + } + + @Override + public boolean createNewFile() throws IOException + { + if (path == null) + return super.createNewFile(); + else { + try { + Files.createFile(path); + return true; + } catch (FileAlreadyExistsException | UnsupportedOperationException ex) { + return false; + } + } + } + + @Override + public boolean delete() + { + if (path == null) + return super.delete(); + else { + try { + Files.delete(path); + return true; + } catch (Exception ex) { + return false; + } + } + } + + @Override + public void deleteOnExit() + { + if (path == null) + super.deleteOnExit(); + else + FileDeletionHook.getInstance().registerFile(path); + } + + @Override + public String[] list() + { + if (path == null) + return super.list(); + else { + 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()); + return list.toArray(new String[list.size()]); + } catch (Exception ex) { + } + } + return null; + } + } + + @Override + public String[] list(FilenameFilter filter) + { + if (path == null) + return super.list(filter); + else { + if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { + 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(); + if (filter == null || filter.accept(dir, s)) + list.add(s); + } + return list.toArray(new String[list.size()]); + } catch (Exception ex) { + } + } + return null; + } + } + + @Override + public File[] listFiles() + { + if (path == null) + return super.listFiles(); + else { + 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())); + return list.toArray(new File[list.size()]); + } catch (Exception ex) { + } + } + return null; + } + } + + @Override + public File[] listFiles(FilenameFilter filter) + { + if (path == null) + return super.listFiles(); + else { + if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { + try (DirectoryStream ds = Files.newDirectoryStream(path)) { + File dir = new FileEx(path); + ArrayList list = new ArrayList<>(); + for (Iterator iter = ds.iterator(); iter.hasNext(); ) { + Path p = iter.next(); + if (filter == null || filter.accept(dir, p.getFileName().toString())) + list.add(new FileEx(p)); + } + return list.toArray(new File[list.size()]); + } catch (Exception ex) { + } + } + return null; + } + } + + @Override + public File[] listFiles(FileFilter filter) + { + if (path == null) + return super.listFiles(); + else { + 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()); + if (filter == null || filter.accept(f)) + list.add(f); + } + return list.toArray(new File[list.size()]); + } catch (Exception ex) { + } + } + return null; + } + } + + @Override + public boolean mkdir() + { + if (path == null) + return super.mkdir(); + else { + try { + Files.createDirectory(path); + return true; + } catch (Exception ex) { + return false; + } + } + } + + @Override + public boolean mkdirs() + { + if (path == null) + return super.mkdirs(); + else { + try { + Files.createDirectories(path); + return true; + } catch (Exception ex) { + return false; + } + } + } + + @Override + public boolean renameTo(File dest) + { + if (path == null) + return super.renameTo(dest); + else { + Path target = path.getFileSystem().getPath(dest.toString()); + try { + Files.move(path, target); + return true; + } catch (Exception ex) { + return false; + } + } + } + + @Override + public boolean setLastModified(long time) + { + if (path == null) + return super.setLastModified(time); + else { + if (time < 0L) throw new IllegalArgumentException("Negative time"); + try { + Files.setLastModifiedTime(path, FileTime.fromMillis(time)); + return true; + } catch (Exception ex) { + return false; + } + } + } + + @Override + public boolean setReadOnly() + { + if (path == null) + return super.setReadOnly(); + else { + try { + FileStore fs = Files.getFileStore(path); + if (fs.supportsFileAttributeView(DosFileAttributeView.class)) { + Files.setAttribute(path, "dos:readonly", true); + } else if (fs.supportsFileAttributeView(PosixFileAttributeView.class)) { + PosixFileAttributeView pfav = Files.getFileAttributeView(path, PosixFileAttributeView.class); + Set set = pfav.readAttributes().permissions(); + set.remove(PosixFilePermission.OWNER_WRITE); + set.remove(PosixFilePermission.GROUP_WRITE); + set.remove(PosixFilePermission.OTHERS_WRITE); + pfav.setPermissions(set); + return true; + } else { + throw new UnsupportedOperationException(); + } + } catch (IOException ex) { + } + return false; + } + } + + @Override + public boolean setWritable(boolean writable) + { + return setWritable(writable, true); + } + + @Override + public boolean setWritable(boolean writable, boolean ownerOnly) + { + if (path == null) + return super.setWritable(writable, ownerOnly); + else { + try { + FileStore fs = Files.getFileStore(path); + if (fs.supportsFileAttributeView(DosFileAttributeView.class)) { + Files.setAttribute(path, "dos:readonly", false); + } else if (fs.supportsFileAttributeView(PosixFileAttributeView.class)) { + PosixFileAttributeView pfav = Files.getFileAttributeView(path, PosixFileAttributeView.class); + Set set = pfav.readAttributes().permissions(); + set.add(PosixFilePermission.OWNER_WRITE); + if (!ownerOnly) { + set.add(PosixFilePermission.GROUP_WRITE); + set.add(PosixFilePermission.OTHERS_WRITE); + } + pfav.setPermissions(set); + return true; + } else { + throw new UnsupportedOperationException(); + } + } catch (IOException ex) { + } + return false; + } + } + + @Override + public boolean setReadable(boolean readable) + { + return setReadable(readable, true); + } + + @Override + public boolean setReadable(boolean readable, boolean ownerOnly) + { + if (path == null) + return super.setReadable(readable, ownerOnly); + else { + try { + FileStore fs = Files.getFileStore(path); + if (fs.supportsFileAttributeView(DosFileAttributeView.class)) { + return true; // always true + } else if (fs.supportsFileAttributeView(PosixFileAttributeView.class)) { + PosixFileAttributeView pfav = Files.getFileAttributeView(path, PosixFileAttributeView.class); + Set set = pfav.readAttributes().permissions(); + set.add(PosixFilePermission.OWNER_READ); + if (!ownerOnly) { + set.add(PosixFilePermission.GROUP_READ); + set.add(PosixFilePermission.OTHERS_READ); + } + pfav.setPermissions(set); + return true; + } else { + throw new UnsupportedOperationException(); + } + } catch (IOException ex) { + } + return false; + } + } + + @Override + public boolean setExecutable(boolean executable) + { + return setExecutable(executable, true); + } + + @Override + public boolean setExecutable(boolean executable, boolean ownerOnly) + { + if (path == null) + return super.setExecutable(executable, ownerOnly); + else { + try { + FileStore fs = Files.getFileStore(path); + if (fs.supportsFileAttributeView(DosFileAttributeView.class)) { + return true; // always true + } else if (fs.supportsFileAttributeView(PosixFileAttributeView.class)) { + PosixFileAttributeView pfav = Files.getFileAttributeView(path, PosixFileAttributeView.class); + Set set = pfav.readAttributes().permissions(); + set.add(PosixFilePermission.OWNER_EXECUTE); + if (!ownerOnly) { + set.add(PosixFilePermission.GROUP_EXECUTE); + set.add(PosixFilePermission.OTHERS_EXECUTE); + } + pfav.setPermissions(set); + return true; + } else { + throw new UnsupportedOperationException(); + } + } catch (IOException ex) { + } + return false; + } + } + + @Override + public boolean canExecute() + { + return (path == null) ? super.canExecute() : Files.isExecutable(path); + } + + @Override + public int compareTo(File pathname) + { + if (pathname == null) + throw new NullPointerException(); + + if (path == null && !(pathname instanceof FileEx)) { + return super.compareTo(pathname); + } else { + return toPath().compareTo(pathname.toPath()); + } + } + + @Override + public boolean equals(Object obj) + { + if (obj instanceof File) + return compareTo((File)obj) == 0; + return false; + } + + @Override + public int hashCode() + { + return (path == null) ? super.hashCode() : path.hashCode(); + } + + @Override + public String toString() + { + return (path == null) ? super.toString() : path.toString(); + } + + /** + * Returns a {@link Path java.nio.file.Path} object constructed from the + * this abstract path and the associated {@link java.nio.file.FileSystem}. + * @return a {@code Path} constructed from this abstract path. + */ + @Override + public Path toPath() + { + return (path == null) ? super.toPath() : path; + } + + /** + * Returns the file system associated with this object. + * @return the file system associated with this object + */ + public FileSystem getFileSystem() + { + return (path == null) ? DEFAULT_FS : path.getFileSystem(); + } + + // Ensures that the returned FileSystem is always non-null. + private static FileSystem validateFileSystem(FileSystem fs) + { + return (fs != null) ? fs : DEFAULT_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())) + path = null; + } + return path; + } +} diff --git a/src/org/infinity/util/io/FileManager.java b/src/org/infinity/util/io/FileManager.java index 25f520dc5..69880d2ca 100644 --- a/src/org/infinity/util/io/FileManager.java +++ b/src/org/infinity/util/io/FileManager.java @@ -430,7 +430,7 @@ private Path _queryPath(boolean mustExist, Path rootFilter, List rootPaths } } else { curPath = _resolve(curRoot.resolve(relPath)); - if (curPath != null && Files.exists(curPath)) { + if (curPath != null && FileEx.create(curPath).exists()) { exists = true; break; } @@ -460,7 +460,7 @@ private void close() public void fileChanged(FileWatchEvent e) { if (e.getKind() == StandardWatchEventKinds.ENTRY_CREATE) { - if (Files.isDirectory(e.getPath())) { + if (FileEx.create(e.getPath()).isDirectory()) { // load whole directory into cache _cacheDirectory(e.getPath(), true); } else { @@ -484,7 +484,7 @@ private static FileManager getInstance() private static Path _resolve(Path path) { Path retVal = path; - if (path != null && isFileSystemCaseSensitive(path.getFileSystem())) { + if (path != null && isFileSystemCaseSensitive(path.getFileSystem()) && !FileEx.create(path).exists()) { boolean found = false; Path curPath = path.normalize().toAbsolutePath(); Path dir = curPath.getRoot(); @@ -566,7 +566,7 @@ private static Path _resolveExisting(Path path) retVal = null; } } -// if (retVal != null && !Files.exists(retVal)) { +// if (retVal != null && !FileEx.fromPath(retVal).exists()) { // retVal = null; // } return retVal; @@ -575,7 +575,7 @@ private static Path _resolveExisting(Path path) private static HashSet _cacheDirectory(Path path, boolean force) { HashSet retVal = null; - if (path != null && Files.isDirectory(path)) { + if (path != null && FileEx.create(path).isDirectory()) { if (force) { pathCache.remove(path); } diff --git a/src/org/infinity/util/io/FileWatcher.java b/src/org/infinity/util/io/FileWatcher.java index 8f0f18c6a..f0105f348 100644 --- a/src/org/infinity/util/io/FileWatcher.java +++ b/src/org/infinity/util/io/FileWatcher.java @@ -177,7 +177,7 @@ public void register(Path dir, boolean recursive) public void register(Path dir, boolean recursive, boolean notifyCreate, boolean notifyDelete, boolean notifyModify) { dir = FileManager.resolve(dir); - if (dir != null && Files.isDirectory(dir)) { + if (dir != null && FileEx.create(dir).isDirectory()) { if (recursive) { try { Files.walkFileTree(dir, new SimpleFileVisitor() { diff --git a/src/org/infinity/util/io/StreamUtils.java b/src/org/infinity/util/io/StreamUtils.java index 5c44b99ca..56aa52f03 100644 --- a/src/org/infinity/util/io/StreamUtils.java +++ b/src/org/infinity/util/io/StreamUtils.java @@ -800,7 +800,7 @@ public static void createZip(Path sourceDir, Path zipFile, boolean includeFolder try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile))) { Path baseDir = includeFolder ? sourceDir.getParent() : sourceDir; Files.walk(sourceDir) - .filter(path -> !Files.isDirectory(path)) + .filter(path -> !FileEx.create(path).isDirectory()) .forEach(path -> { ZipEntry ze = new ZipEntry(baseDir.relativize(path).toString()); try { From 87e2eeed4be59e0d9659be89c06f6e5f6a6a9064 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Fri, 28 Aug 2020 17:17:03 +0200 Subject: [PATCH 10/14] Options menu: Add description tooltips to look&feel theme list --- src/org/infinity/gui/BrowserMenuBar.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index 1cfe10d2a..b1341fd6b 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -53,6 +53,7 @@ import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.KeyStroke; +import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; @@ -2255,6 +2256,14 @@ private OptionsMenu() dbmi = new DataRadioButtonMenuItem(info[i].getName(), selectedLF.equalsIgnoreCase(info[i].getClassName()), info[i]); + try { + // L&F description is only available from class instance + Class cls = Class.forName(info[i].getClassName()); + Object o = cls.newInstance(); + if (o instanceof LookAndFeel) + dbmi.setToolTipText(((LookAndFeel)o).getDescription()); + } catch (Exception ex) { + } lookAndFeel.add(dbmi); bg.add(dbmi); } From 21d71ad85b0ce6e8446b7d9af4db4d082a16e9e9 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 30 Aug 2020 12:30:01 +0200 Subject: [PATCH 11/14] Add feature to launch game directly from NI Executable is determined from a list of potential names per game. Customizable via bookmarks. --- src/org/infinity/NearInfinity.java | 150 +++++++++++- src/org/infinity/gui/BookmarkEditor.java | 201 +++++++++++++++- src/org/infinity/gui/BrowserMenuBar.java | 169 +++++++++++++- src/org/infinity/icon/Icons.java | 2 + src/org/infinity/icon/LaunchRed24.png | Bin 0 -> 532 bytes src/org/infinity/icon/LaunchRedPlus24.png | Bin 0 -> 585 bytes src/org/infinity/resource/Profile.java | 269 +++++++++++++++++++++- src/org/infinity/util/Platform.java | 6 + 8 files changed, 781 insertions(+), 16 deletions(-) create mode 100644 src/org/infinity/icon/LaunchRed24.png create mode 100644 src/org/infinity/icon/LaunchRedPlus24.png diff --git a/src/org/infinity/NearInfinity.java b/src/org/infinity/NearInfinity.java index 347821034..8a8771d42 100644 --- a/src/org/infinity/NearInfinity.java +++ b/src/org/infinity/NearInfinity.java @@ -1,5 +1,5 @@ // Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 - 2018 Jon Olav Hauglid +// Copyright (C) 2001 - 2020 Jon Olav Hauglid // See LICENSE.txt for license information package org.infinity; @@ -7,7 +7,9 @@ import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; +import java.awt.Desktop; import java.awt.Dimension; +import java.awt.Event; import java.awt.Font; import java.awt.Frame; import java.awt.Image; @@ -30,6 +32,7 @@ import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; @@ -40,11 +43,14 @@ import java.util.prefs.Preferences; import javax.swing.BorderFactory; +import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; +import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; +import javax.swing.JPopupMenu; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JToolBar; @@ -61,6 +67,7 @@ import org.infinity.gui.BrowserMenuBar; import org.infinity.gui.ButtonPopupWindow; import org.infinity.gui.ChildFrame; +import org.infinity.gui.DataMenuItem; import org.infinity.gui.InfinityTextArea; import org.infinity.gui.OpenFileFrame; import org.infinity.gui.PopupWindowEvent; @@ -136,6 +143,8 @@ public final class NearInfinity extends JFrame implements ActionListener, Viewab private Viewable viewable; private ButtonPopupWindow bpwQuickSearch; + private JButton btnLaunchGame; + private JPopupMenu launchMenu; private int tablePanelHeight; private ProgressMonitor pmProgress; private int progressIndex, globalFontSize; @@ -377,6 +386,7 @@ public void windowClosing(WindowEvent event) tree.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); JToolBar toolBar = new JToolBar("Navigation", JToolBar.HORIZONTAL); + toolBar.setMargin(new Insets(4, 4, 4, 4)); JButton b; toolBar.setRollover(true); toolBar.setFloatable(false); @@ -445,6 +455,16 @@ public void run() } }); + toolBar.add(Box.createHorizontalGlue()); + btnLaunchGame = new JButton(Icons.getIcon(Icons.ICON_LAUNCH_24)); + btnLaunchGame.setFocusable(false); + btnLaunchGame.setEnabled(false); + btnLaunchGame.setMargin(new Insets(0, 0, 0, 0)); + btnLaunchGame.setToolTipText("Launch game"); + btnLaunchGame.addActionListener(this); + toolBar.add(btnLaunchGame); + launchMenu = new JPopupMenu(); + JPanel leftPanel = new JPanel(new BorderLayout()); leftPanel.add(tree, BorderLayout.CENTER); leftPanel.add(toolBar, BorderLayout.NORTH); @@ -461,6 +481,7 @@ public void run() hideProgress(); } + updateLauncher(); setSize(prefs.getInt(WINDOW_SIZEX, 930), prefs.getInt(WINDOW_SIZEY, 700)); int centerX = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth() - getSize().width >> 1; int centerY = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight() - getSize().height >> 1; @@ -609,6 +630,40 @@ public void actionPerformed(ActionEvent event) } finally { WindowBlocker.blockWindow(this, false); } + } else if (event.getSource() == btnLaunchGame) { + //Path launchPath = null; + DataMenuItem dmi = null; + boolean ctrl = (event.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0; + if (ctrl || launchMenu.getComponentCount() == 1) { + // getting first available binary path + for (int i = 0, cnt = launchMenu.getComponentCount(); i < cnt; i++) { + if (launchMenu.getComponent(i) instanceof DataMenuItem) { + dmi = (DataMenuItem)launchMenu.getComponent(i); + break; + } + } + } + + if ((launchMenu.getComponentCount() > 1 && ctrl) || launchMenu.getComponentCount() == 1) { + if (dmi != null) { + dmi.doClick(); + } else { + JOptionPane.showMessageDialog(this, "Could not determine game executable.", + "Launch game", JOptionPane.ERROR_MESSAGE); + } + } else if (launchMenu.getComponentCount() > 1) { + launchMenu.show(btnLaunchGame, 0, btnLaunchGame.getHeight()); + } + } else if (event.getSource() instanceof DataMenuItem && + ((DataMenuItem)event.getSource()).getParent() == launchMenu) { + DataMenuItem dmi = (DataMenuItem)event.getSource(); + if (dmi.getData() instanceof Path) { + Path path = (Path)dmi.getData(); + if (!launchGameBinary(path)) { + JOptionPane.showMessageDialog(this, "Game executable could not be launched.", + "Launch game", JOptionPane.ERROR_MESSAGE); + } + } } } @@ -681,6 +736,7 @@ public void openGame(Path keyFile) removeViewable(); ResourceTreeModel treemodel = ResourceFactory.getResourceTreeModel(); updateWindowTitle(); + updateLauncher(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), Profile.getGameRoot(), treemodel.size()); @@ -737,6 +793,7 @@ public void refreshGame() if (removeViewable()) { ChildFrame.closeWindows(); ResourceTreeModel treemodel = ResourceFactory.getResourceTreeModel(); + updateLauncher(); final String msg = String.format(STATUSBAR_TEXT_FMT, Profile.getProperty(Profile.Key.GET_GAME_TITLE), Profile.getGameRoot(), treemodel.size()); @@ -847,6 +904,74 @@ public int getGlobalFontSize() return globalFontSize; } + /** Updates the launcher button configuration. */ + public void updateLauncher() + { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() + { + // cleaning up old configuration + for (int idx = launchMenu.getComponentCount() - 1; idx >= 0; idx--) { + Component c = launchMenu.getComponent(idx); + if (c instanceof JMenuItem) { + ((JMenuItem)c).removeActionListener(NearInfinity.this); + } + } + launchMenu.removeAll(); + + // setting up new configuration + BrowserMenuBar.Bookmark bookmark = BrowserMenuBar.getInstance().getBookmarkOf(Profile.getChitinKey()); + List binPaths = null; + if (bookmark != null) { + List list = bookmark.getBinaryPaths(Platform.getPlatform()); + if (list != null && !list.isEmpty()) { + binPaths = new ArrayList<>(); + for (final String name : list) { + Path path = null; + if (name.startsWith("/")) { + path = FileManager.resolveExisting(name); + if (path == null) + path = FileManager.resolveExisting(Profile.getGameRoot().toString(), name); + } else { + path = FileManager.resolveExisting(Profile.getGameRoot().toString(), name); + } + if (path != null) + binPaths.add(path); + } + } + } + if (binPaths == null || binPaths.isEmpty()) + binPaths = Profile.getGameBinaryPaths(); + if (binPaths != null && binPaths.isEmpty()) + binPaths = null; + + // updating launch controls + if (binPaths != null) { + for (final Path path : binPaths) { + DataMenuItem dmi = new DataMenuItem(path.toString()); + dmi.setData(path); + dmi.addActionListener(NearInfinity.this); + launchMenu.add(dmi); + } + } + boolean isEnabled = (binPaths != null) && BrowserMenuBar.getInstance().getLauncherEnabled(); + btnLaunchGame.setEnabled(isEnabled); + if (binPaths == null ) { + btnLaunchGame.setIcon(Icons.getIcon(Icons.ICON_LAUNCH_24)); + btnLaunchGame.setToolTipText("Launch game"); + } else if (binPaths.size() == 1) { + btnLaunchGame.setIcon(Icons.getIcon(Icons.ICON_LAUNCH_24)); + btnLaunchGame.setToolTipText("Launch " + binPaths.get(0).toString()); + } else { + String ctrlName = (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() == Event.CTRL_MASK) ? "Ctrl" : "Command"; + btnLaunchGame.setIcon(Icons.getIcon(Icons.ICON_LAUNCH_PLUS_24)); + btnLaunchGame.setToolTipText("Launch game (launch directly with " + ctrlName + "+Click)"); + } + } + }); + } + private static boolean reloadFactory(boolean refreshOnly) { boolean retVal = false; @@ -1034,6 +1159,29 @@ private void enableOSXQuitStrategy() } } + // Executes the specified path + private boolean launchGameBinary(Path binPath) + { + boolean retVal = false; + if (binPath != null && Files.exists(binPath)) { + try { + if (Platform.IS_MACOS && binPath.toString().toLowerCase(Locale.ENGLISH).endsWith(".app")) { + // This method may be required for launching Mac App Bundles + Desktop.getDesktop().open(binPath.toFile()); + } else { + ProcessBuilder pb = new ProcessBuilder(binPath.toString()); + pb.directory(binPath.getParent().toFile()); + pb.inheritIO(); + pb.start(); + } + retVal = true; + } catch (Exception e) { + e.printStackTrace(); + } + } + return retVal; + } + // -------------------------- INNER CLASSES -------------------------- private static final class ConsoleStream extends PrintStream diff --git a/src/org/infinity/gui/BookmarkEditor.java b/src/org/infinity/gui/BookmarkEditor.java index 4446a13c0..8746fa85a 100644 --- a/src/org/infinity/gui/BookmarkEditor.java +++ b/src/org/infinity/gui/BookmarkEditor.java @@ -1,5 +1,5 @@ // Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 - 2005 Jon Olav Hauglid +// Copyright (C) 2001 - 2020 Jon Olav Hauglid // See LICENSE.txt for license information package org.infinity.gui; @@ -14,15 +14,25 @@ import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; import java.awt.event.KeyEvent; +import java.io.File; +import java.nio.file.Path; import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.swing.AbstractAction; +import javax.swing.DefaultComboBoxModel; +import javax.swing.DefaultListModel; import javax.swing.JButton; +import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; +import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; @@ -35,15 +45,20 @@ import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileNameExtensionFilter; import org.infinity.NearInfinity; import org.infinity.gui.BrowserMenuBar.Bookmark; +import org.infinity.resource.Profile; +import org.infinity.util.Platform; import org.infinity.util.SimpleListModel; +import org.infinity.util.io.FileManager; /** * Edit or remove bookmarked games. */ -public class BookmarkEditor extends JDialog implements ActionListener, FocusListener, ListSelectionListener +public class BookmarkEditor extends JDialog implements ActionListener, FocusListener, ListSelectionListener, ItemListener { private final SimpleListModel modelEntries = new SimpleListModel(); private final JList listEntries = new JList(modelEntries); @@ -53,8 +68,15 @@ public class BookmarkEditor extends JDialog implements ActionListener, FocusList private final JButton bClear = new JButton("Clear"); private final JButton bOK = new JButton("OK"); private final JButton bCancel = new JButton("Cancel"); + private final JButton bBinPathAdd = new JButton("+"); + private final JButton bBinPathRemove = new JButton("-"); private final JTextField tfName = new JTextField(); private final JTextField tfPath = createReadOnlyField(null, true); + private final DefaultComboBoxModel cbPlatformModel = + new DefaultComboBoxModel(BrowserMenuBar.Bookmark.getSupportedOS()); + private final JComboBox cbPlatform = new JComboBox<>(cbPlatformModel); + private final EnumMap> listBinPathModels = new EnumMap<>(Platform.OS.class); + private final JList listBinPaths = new JList(); private final List listBookmarks = new ArrayList(); @@ -97,20 +119,53 @@ public void actionPerformed(ActionEvent e) JPanel pDetails = new JPanel(new GridBagLayout()); JLabel lName = new JLabel("Name:"); JLabel lPath = new JLabel("Path:"); + JLabel lBinPath = new JLabel("Game executable:"); tfName.addFocusListener(this); gbc = ViewerUtil.setGBC(gbc, 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, - GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0); + GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); pDetails.add(lName, gbc); gbc = ViewerUtil.setGBC(gbc, 1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0), 0, 0); pDetails.add(tfName, gbc); gbc = ViewerUtil.setGBC(gbc, 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, - GridBagConstraints.HORIZONTAL, new Insets(8, 0, 0, 0), 0, 0); + GridBagConstraints.NONE, new Insets(8, 0, 0, 0), 0, 0); pDetails.add(lPath, gbc); gbc = ViewerUtil.setGBC(gbc, 1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(8, 8, 0, 0), 0, 0); pDetails.add(tfPath, gbc); + // adding binary path support + gbc = ViewerUtil.setGBC(gbc, 0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, + GridBagConstraints.NONE, new Insets(8, 0, 0, 0), 0, 0); + pDetails.add(lBinPath, gbc); + + // Subpanel: platform-specific path selection + JPanel pGames = new JPanel(new GridBagLayout()); + gbc = ViewerUtil.setGBC(gbc, 0, 0, 1, 2, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, + GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); + pGames.add(cbPlatform, gbc); + gbc = ViewerUtil.setGBC(gbc, 1, 0, 1, 2, 1.0, 0.0, GridBagConstraints.FIRST_LINE_START, + GridBagConstraints.BOTH, new Insets(0, 8, 0, 0), 0, 0); + + + listBinPaths.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + listBinPaths.setVisibleRowCount(2); + listBinPaths.setToolTipText("Leave empty to use game-specific defaults."); + JScrollPane spBinList = new JScrollPane(listBinPaths); + pGames.add(spBinList, gbc); + bBinPathAdd.addActionListener(this); + gbc = ViewerUtil.setGBC(gbc, 2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, + GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0), 0, 0); + pGames.add(bBinPathAdd, gbc); + bBinPathRemove.addActionListener(this); + gbc = ViewerUtil.setGBC(gbc, 2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, + GridBagConstraints.HORIZONTAL, new Insets(4, 8, 0, 0), 0, 0); + pGames.add(bBinPathRemove, gbc); + + gbc = ViewerUtil.setGBC(gbc, 1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, + GridBagConstraints.HORIZONTAL, new Insets(8, 8, 0, 0), 0, 0); + pDetails.add(pGames, gbc); + // creating edit buttons panel JPanel pEdit = new JPanel(new GridBagLayout()); bUp.setEnabled(false); @@ -183,8 +238,6 @@ public void actionPerformed(ActionEvent e) GridBagConstraints.BOTH, new Insets(8, 8, 8, 8), 0, 0); add(pMain, gbc); - initData(bookmarks); - pack(); setMinimumSize(getPreferredSize()); d = new Dimension(getPreferredSize()); @@ -192,6 +245,9 @@ public void actionPerformed(ActionEvent e) d.height = (d.height * 4) / 3; setPreferredSize(d); pack(); + + initData(bookmarks); + setLocationRelativeTo(getOwner()); setVisible(true); } @@ -210,6 +266,14 @@ private void initData(List bookmarks) } } + int platformIdx = Math.max(cbPlatformModel.getIndexOf(Platform.getPlatform()), 0); + cbPlatform.setSelectedIndex(platformIdx); + for (int idx = 0; idx < cbPlatformModel.getSize(); idx++) + listBinPathModels.put(cbPlatformModel.getElementAt(idx), new DefaultListModel()); + listBinPaths.setModel(getBinPathModel()); + listBinPaths.addListSelectionListener(this); + cbPlatform.addItemListener(this); + if (listBookmarks != null) { for (Iterator iter = listBookmarks.iterator(); iter.hasNext();) { modelEntries.addElement(iter.next()); @@ -291,16 +355,117 @@ private void updateEntry(int index) bClear.setEnabled(!modelEntries.isEmpty()); if (index >= 0) { - BrowserMenuBar.Bookmark bookmark = (BrowserMenuBar.Bookmark)modelEntries.get(index); + BrowserMenuBar.Bookmark bookmark = modelEntries.get(index); tfName.setText(bookmark.getName()); tfName.setSelectionStart(0); tfName.setSelectionEnd(0); tfPath.setText(bookmark.getPath()); tfPath.setSelectionStart(0); tfPath.setSelectionEnd(0); + + for (int idx = 0; idx < cbPlatformModel.getSize(); idx++) { + Platform.OS os = cbPlatformModel.getElementAt(idx); + getBinPathModel(os).clear(); + List paths = bookmark.getBinaryPaths(os); + for (int i = 0; i < paths.size(); i++) { + Path path = FileManager.resolve(paths.get(i)); + if (path != null) + getBinPathModel(os).addElement(path); + } + } + if (listBinPaths.getModel().getSize() > 0) + listBinPaths.setSelectedIndex(0); } else { tfName.setText(""); tfPath.setText(""); + getBinPathModel().clear(); + } + } + + // Updates all binary path lists for the selected bookmark + private void updateBinPaths() + { + BrowserMenuBar.Bookmark bookmark = listEntries.getSelectedValue(); + for (int i = 0; i < cbPlatformModel.getSize(); i++) { + Platform.OS os = cbPlatformModel.getElementAt(i); + DefaultListModel model = getBinPathModel(os); + List pathList = new ArrayList<>(); + for (Enumeration iter = model.elements(); iter.hasMoreElements(); ) + pathList.add(iter.nextElement().toString()); + bookmark.setBinaryPaths(os, pathList); + } + } + + // Returns the currently selected ListModel for the binary path list + private DefaultListModel getBinPathModel() + { + return getBinPathModel(cbPlatformModel.getElementAt(cbPlatform.getSelectedIndex())); + } + + // Returns the specified ListModel for the binary path list + private DefaultListModel getBinPathModel(Platform.OS os) + { + return listBinPathModels.get(os); + } + + // Adds a new executable file entry to the current binary file list + private void addBinPathInteractive() + { + JFileChooser fc = new JFileChooser(Profile.getGameRoot().toFile()); + fc.setDialogTitle("Select game executable"); + FileFilter exeFilter = null; + fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); + if (cbPlatform.getSelectedItem() == Platform.OS.Windows) { + exeFilter = new FileNameExtensionFilter("Executable Files", "exe", "lnk", "cmd", "bat", "ps1", "pif"); + } else { + exeFilter = new FileFilter() { + @Override public String getDescription() { return "Executable Files"; } + @Override public boolean accept(File f) { return !f.isFile() || Platform.IS_WINDOWS || f.canExecute(); } }; + } + if (exeFilter != null) + fc.addChoosableFileFilter(exeFilter); + fc.addChoosableFileFilter(fc.getAcceptAllFileFilter()); + if (exeFilter != null) + fc.setFileFilter(exeFilter); + if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + Path path = fc.getSelectedFile().toPath(); + try { + path = Profile.getGameRoot().relativize(path); + } catch (IllegalArgumentException ex) { + } + DefaultListModel model = getBinPathModel(); + boolean exists = false; + for (int i = 0; i < model.getSize(); i++) { + if (path.equals(model.get(i))) { + exists = true; + listBinPaths.setSelectedIndex(i); + listBinPaths.ensureIndexIsVisible(i); + JOptionPane.showMessageDialog(this, "Selected game executable is already listed.", + "Game executable", JOptionPane.WARNING_MESSAGE); + break; + } + } + if (!exists) { + model.addElement(path); + listBinPaths.setSelectedValue(path, true); + updateBinPaths(); + } + } + } + + // Removes the selected executable file entry from the current binary file list + private void removeBinPathInteractive() + { + Path path = listBinPaths.getSelectedValue(); + if (path != null) { + if (JOptionPane.showConfirmDialog(this, "Remove game executable:\n" + path, "Game executable", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { + if (getBinPathModel().removeElement(path)) { + updateBinPaths(); + } + } + } else { + JOptionPane.showMessageDialog(this, "No game executable selected.", "Game executable", JOptionPane.WARNING_MESSAGE); } } @@ -347,6 +512,10 @@ public void actionPerformed(ActionEvent event) updateEntry(-1); } } + } else if (event.getSource() == bBinPathAdd) { + addBinPathInteractive(); + } else if (event.getSource() == bBinPathRemove) { + removeBinPathInteractive(); } } @@ -389,8 +558,26 @@ public void valueChanged(ListSelectionEvent event) { if (event.getSource() == listEntries) { updateEntry(listEntries.getSelectedIndex()); + } else if (event.getSource() == listBinPaths) { + bBinPathRemove.setEnabled(listBinPaths.getSelectedIndex() >= 0); } } //--------------------- End Interface ListSelectionListener --------------------- + + //--------------------- Begin Interface ItemListener --------------------- + + @Override + public void itemStateChanged(ItemEvent event) + { + if (event.getSource() == cbPlatform) { + DefaultListModel model = listBinPathModels.get(cbPlatformModel.getElementAt(cbPlatform.getSelectedIndex())); + if (model != null) + listBinPaths.setModel(model); + else + throw new NullPointerException(); + } + } + + //--------------------- Begin Interface ItemListener --------------------- } diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index b1341fd6b..0404fa576 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -1,5 +1,5 @@ // Near Infinity - An Infinity Engine Browser and Editor -// Copyright (C) 2001 - 2018 Jon Olav Hauglid +// Copyright (C) 2001 - 2020 Jon Olav Hauglid // See LICENSE.txt for license information package org.infinity.gui; @@ -29,6 +29,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; +import java.util.EnumMap; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; @@ -101,6 +102,7 @@ import org.infinity.util.Misc; import org.infinity.util.ObjectString; import org.infinity.util.Pair; +import org.infinity.util.Platform; import org.infinity.util.StringTable; import org.infinity.util.io.FileEx; import org.infinity.util.io.FileManager; @@ -569,6 +571,12 @@ public String getSelectedCharset() return optionsMenu.charsetName(optionsMenu.getSelectedButtonData(), true); } + /** Returns whether launching game executables in NI is enabled. */ + public boolean getLauncherEnabled() + { + return optionsMenu.optionLaunchGameAllowed.isSelected(); + } + /** Returns whether a backup is created when resources are modified. */ public boolean backupOnSave() { @@ -643,6 +651,16 @@ public String getBookmarkName(Path keyFile) return (bookmark != null) ? bookmark.getName() : null; } + /** + * Attempts to find and return a matching bookmark object. + * @param keyFile The path to the game's chitin.key used to determine the correct bookmark instance. + * @return The matching bookmark instance if available, {@code null} otherwise. + */ + public Bookmark getBookmarkOf(Path keyFile) + { + return gameMenu.getBookmarkOf(keyFile); + } + public void storePreferences() { toolsMenu.storePreferences(); @@ -767,8 +785,18 @@ private GameMenu() Profile.Game.Unknown.toString())); String gamePath = getPrefsProfiles().get(Bookmark.getPathKey(i), null); String gameName = getPrefsProfiles().get(Bookmark.getNameKey(i), null); + EnumMap> binPaths = null; + for (final Platform.OS os : Bookmark.getSupportedOS()) { + String path = getPrefsProfiles().get(Bookmark.getBinaryPathKey(os, i), null); + if (path != null) { + if (binPaths == null) + binPaths = new EnumMap>(Platform.OS.class); + List list = Bookmark.unpackBinPaths(os, path); + binPaths.put(os, list); + } + } try { - Bookmark b = new Bookmark(gameName, game, gamePath, this); + Bookmark b = new Bookmark(gameName, game, gamePath, binPaths, this); addBookmarkedGame(bookmarkList.size(), b); } catch (NullPointerException e) { // skipping entry @@ -996,6 +1024,9 @@ private void storePreferences() getPrefsProfiles().remove(Bookmark.getNameKey(i)); getPrefsProfiles().remove(Bookmark.getPathKey(i)); getPrefsProfiles().remove(Bookmark.getGameKey(i)); + for (final Platform.OS os : Bookmark.getSupportedOS()) { + getPrefsProfiles().remove(Bookmark.getBinaryPathKey(os, i)); + } } } // 2. storing bookmarks in preferences @@ -1005,6 +1036,13 @@ private void storePreferences() getPrefsProfiles().put(Bookmark.getNameKey(i), bookmark.getName()); getPrefsProfiles().put(Bookmark.getPathKey(i), bookmark.getPath()); getPrefsProfiles().put(Bookmark.getGameKey(i), bookmark.getGame().toString()); + for (final Platform.OS os : Bookmark.getSupportedOS()) { + String value = Bookmark.packBinPaths(os, bookmark.getBinaryPaths(os)); + if (value.isEmpty()) + getPrefsProfiles().remove(Bookmark.getBinaryPathKey(os, i)); + else + getPrefsProfiles().put(Bookmark.getBinaryPathKey(os, i), value); + } } // storing recently used games @@ -1328,7 +1366,7 @@ private EditMenu() editString = makeMenuItem("String table", KeyEvent.VK_S, Icons.getIcon(Icons.ICON_EDIT_16), KeyEvent.VK_S, this); add(editString); - // TODO: reactive when fixed + // TODO: reactivate when fixed editBIFF = makeMenuItem("BIFF", KeyEvent.VK_B, Icons.getIcon(Icons.ICON_EDIT_16), KeyEvent.VK_E, this); editBIFF.setToolTipText("Temporarily disabled"); editBIFF.setEnabled(false); @@ -1791,6 +1829,7 @@ private static final class OptionsMenu extends JMenu implements ActionListener, private static final String OPTION_BACKUPONSAVE = "BackupOnSave"; private static final String OPTION_IGNOREOVERRIDE = "IgnoreOverride"; private static final String OPTION_IGNOREREADERRORS = "IgnoreReadErrors"; + private static final String OPTION_LAUNCHGAMEALLOWED = "LaunchGameAllowed"; private static final String OPTION_SHOWUNKNOWNRESOURCES = "ShowUnknownResources"; private static final String OPTION_AUTOCHECK_BCS = "AutocheckBCS"; private static final String OPTION_AUTOGEN_BCS_COMMENTS = "AutogenBCSComments"; @@ -1875,7 +1914,7 @@ private static final class OptionsMenu extends JMenu implements ActionListener, optionIgnoreOverride, optionIgnoreReadErrors, optionCacheOverride, optionShowStrrefs, optionShowColoredStructures, optionShowHexColored, optionShowUnknownResources, optionKeepViewOnCopy, optionTreeSearchNames, - optionHighlightOverridden; + optionHighlightOverridden, optionLaunchGameAllowed; // optionMonitorFileChanges; private final JMenu mCharsetMenu, mLanguageMenu; private ButtonGroup bgCharsetButtons; @@ -1898,6 +1937,12 @@ private OptionsMenu() optionBackupOnSave.setToolTipText("Enable this option to automatically create a backup " + "of the resource you want to save."); add(optionBackupOnSave); + optionLaunchGameAllowed = + new JCheckBoxMenuItem("Allow launching games", getPrefs().getBoolean(OPTION_LAUNCHGAMEALLOWED, true)); + optionLaunchGameAllowed.setToolTipText("Enabling this option allows you to launch the game executable " + + "associated with the current game from within Near Infinity."); + optionLaunchGameAllowed.addActionListener(this); + add(optionLaunchGameAllowed); optionIgnoreOverride = new JCheckBoxMenuItem("Ignore Overrides", getPrefs().getBoolean(OPTION_IGNOREOVERRIDE, false)); add(optionIgnoreOverride); @@ -2591,6 +2636,7 @@ private void storePreferences() getPrefs().putBoolean(OPTION_SHOWSIZE, optionShowSize.isSelected()); getPrefs().putBoolean(OPTION_SHOWSIZEHEX, optionSizeInHex.isSelected()); getPrefs().putBoolean(OPTION_BACKUPONSAVE, optionBackupOnSave.isSelected()); + getPrefs().putBoolean(OPTION_LAUNCHGAMEALLOWED, optionLaunchGameAllowed.isSelected()); getPrefs().putBoolean(OPTION_IGNOREOVERRIDE, optionIgnoreOverride.isSelected()); getPrefs().putBoolean(OPTION_IGNOREREADERRORS, optionIgnoreReadErrors.isSelected()); getPrefs().putBoolean(OPTION_SHOWUNKNOWNRESOURCES, optionShowUnknownResources.isSelected()); @@ -2986,6 +3032,9 @@ public void actionPerformed(ActionEvent event) if (event.getSource() == optionShowOffset) { optionOffsetRelative.setEnabled(optionShowOffset.isSelected()); } + else if (event.getSource() == optionLaunchGameAllowed) { + NearInfinity.getInstance().updateLauncher(); + } else if (event.getSource() == optionShowSize) { optionSizeInHex.setEnabled(optionShowSize.isSelected()); } @@ -3498,24 +3547,33 @@ private void displayLicense(String classPath, String title) } /** Manages bookmarked game entries. */ - static final class Bookmark implements Cloneable + public static final class Bookmark implements Cloneable { /** "Bookmarks" preferences entries (numbers are 1-based). */ private static final String BOOKMARK_NUM_ENTRIES = "BookmarkEntries"; private static final String FMT_BOOKMARK_NAME = "BookmarkName%d"; private static final String FMT_BOOKMARK_ID = "BookmarkID%d"; private static final String FMT_BOOKMARK_PATH = "BookmarkPath%d"; + private static final String FMT_BOOKMARK_BIN_PATH = "BookmarkPath%s%d"; // %s: Platform.OS, %d: bookmark index private static final String MENUITEM_COMMAND = "OpenBookmark"; + private static final Platform.OS[] SUPPORTED_OS = { Platform.OS.Windows, Platform.OS.MacOS, Platform.OS.Unix }; + private final Profile.Game game; private final String path; + private final EnumMap> binPaths = new EnumMap<>(Platform.OS.class); private String name; private ActionListener listener; private JMenuItem item; public Bookmark(String name, Profile.Game game, String path, ActionListener listener) + { + this(name, game, path, null, listener); + } + + public Bookmark(String name, Profile.Game game, String path, EnumMap> binPaths, ActionListener listener) { if (game == null || path == null) { throw new NullPointerException(); @@ -3527,6 +3585,8 @@ public Bookmark(String name, Profile.Game game, String path, ActionListener list this.game = game; this.path = path; this.listener = listener; + if (binPaths != null) + this.binPaths.putAll(binPaths); updateMenuItem(); } @@ -3539,10 +3599,9 @@ public String toString() @Override public Object clone() throws CloneNotSupportedException { - return new Bookmark(getName(), getGame(), getPath(), listener); + return new Bookmark(name, game, path, binPaths, listener); } - /** Returns user-defined game name. */ public String getName() { return name; } @@ -3563,6 +3622,37 @@ public String setName(String newName) /** Returns game path (i.e. full path to the chitin.key). */ public String getPath() { return path; } + /** Returns a list of available paths to executables for the current platform. */ + public List getBinaryPaths() { return getBinaryPaths(Platform.getPlatform()); } + + /** Returns a list of available paths to executables for the given platform. */ + public List getBinaryPaths(Platform.OS os) + { + if (os == null) + os = Platform.getPlatform(); + return Collections.unmodifiableList(binPaths.getOrDefault(os, new ArrayList(1))); + } + + /** Assigns a new list of executable paths to the specified platform. Returns the previous path list if available. */ + public List setBinaryPaths(Platform.OS os, List pathList) + { + if (os == null) + os = Platform.getPlatform(); + List retVal = binPaths.get(os); + + List newList = new ArrayList<>(); + if (pathList != null) { + for (String path : pathList) { + if (path != null && !(path = path.trim()).isEmpty()) { + newList.add(path); + } + } + } + binPaths.put(os, newList); + + return retVal; + } + /** Returns associated menu item. */ public JMenuItem getMenuItem() { return item; } @@ -3641,6 +3731,71 @@ public static String getNameKey(int idx) return null; } } + + /** Returns the Preferences key for a specific BookmarkBinPath for the current platform. */ + public static String getBinaryPathKey(int idx) + { + return getBinaryPathKey(Platform.getPlatform(), idx); + } + + /** Returns the Preferences key for a specific BookmarkBinPath for the given platform. */ + public static String getBinaryPathKey(Platform.OS os, int idx) + { + if (idx >= 0) { + return String.format(FMT_BOOKMARK_BIN_PATH, os.name().toUpperCase(Locale.ENGLISH), idx+1); + } else { + return null; + } + } + + /** + * Constructs a Preferences string value out of the specified list of path strings. + * @param os Platform associated with the path strings. Needed to determine the correct path separator. + * @param binPaths List of path strings. + * @return A string consisting of concatenated path strings. + */ + public static String packBinPaths(Platform.OS os, List binPaths) + { + StringBuilder sb = new StringBuilder(); + if (os != null && binPaths != null && !binPaths.isEmpty()) { + String sep = (os == Platform.OS.Windows) ? ";" : ":"; + for (int i = 0; i < binPaths.size(); i++) { + String path = binPaths.get(i); + if (path != null && !(path = path.trim()).isEmpty()) { + path = path.replace(sep, "?"); // hack: avoid ambiguity with path separator char + if (sb.length() > 0) + sb.append(sep); + sb.append(path); + } + } + } + return sb.toString(); + } + + /** + * Splits all paths defined in the specified argument and returns them as a list. + */ + public static List unpackBinPaths(Platform.OS os, String paths) + { + List list = new ArrayList<>(); + if (os != null && paths != null) { + String sep = (os == Platform.OS.Windows) ? ";" : ":"; + String[] items = paths.split(sep); + for (String item : items) { + item = item.replace("?", sep); // hack: fix ambiguity with path separator char + item = item.trim(); + if (!item.isEmpty()) + list.add(item); + } + } + return list; + } + + /** Returns an array containing all supported {@code Platform.OS} types. */ + public static Platform.OS[] getSupportedOS() + { + return SUPPORTED_OS; + } } /** Manages individual "Recently used games" entries. */ diff --git a/src/org/infinity/icon/Icons.java b/src/org/infinity/icon/Icons.java index cb5ff4af4..26c225870 100644 --- a/src/org/infinity/icon/Icons.java +++ b/src/org/infinity/icon/Icons.java @@ -51,6 +51,8 @@ public class Icons public static final String ICON_HISTORY_16 = "History16.gif"; public static final String ICON_IMPORT_16 = "Import16.gif"; public static final String ICON_INFORMATION_16 = "Information16.png"; + public static final String ICON_LAUNCH_24 = "LaunchRed24.png"; + public static final String ICON_LAUNCH_PLUS_24 = "LaunchRedPlus24.png"; public static final String ICON_MAGNIFY_16 = "Magnify16.png"; public static final String ICON_MOVIE_16 = "Movie16.gif"; public static final String ICON_NEW_16 = "New16.gif"; diff --git a/src/org/infinity/icon/LaunchRed24.png b/src/org/infinity/icon/LaunchRed24.png new file mode 100644 index 0000000000000000000000000000000000000000..1fbe57013fff4eb458725760665aeb65010e9e1b GIT binary patch literal 532 zcmV+v0_**WP)*|YQR%)Dn#sT}5NIOO&3 z159mqygh$zMz~Hfhde^BQY@(uLD60p(EBa1m6Ok&@1B9lHIg~nKyndXB;Lh8R3h6P zPaC2{5sBVbKL8hgAE3d`E6|rC0X$~%M12XIqN!hOa)Jr8y>!7l8xc>7uh9o3M-L1T z#Wr0idVBQT2K)EXOG&;UHx8D8f$B=5LiIwg+jPw7beY^!7nL)U$~FPOUIJzl$c>Bx zj?0M#Uo^%1p65V?)=gH9{Zn>0OaGe)}UFQuA=rki#pzK zE56;v4Pd#=t5vw1syBl^u-kjJD}dIBOrs4c_}2PyMX#*G)2S+^q#Jezou(_v`y;?~ z-@sL1CC;zOou-QEreL4JCj+#(zg|oqfm>_xco=4B>fNA&Z&_QNR-ggASh@+ zX`mn#lzas!f%FLJEGUVffu1%Ie?k&2A-SEQuzm97F1dt|0*RGIyI!x~_`R9k4ci=N z%Q)ut?-O)(Pkg?7Y1VLuU>@@v`xe29ZIHpnuKNJ$d53W_XI{PDKLbm*k>*JP=_>Xz z@W|HEW_3Aa1=8cewPIcQ}=;wNFKU!q#qpb5U6=O)pWCwnyRCIIpoK`TI_~_rsob7EAd-j*6kUdpII9YzJ)0&o|Xyy<4k&3G8Uh)GScI&*X1?`^F9|b|UB) zF1&fm+}xbYUfC*fMO739y SUPPORTED_RESOURCE_TYPES = new HashSet<>(); private static final HashMap KNOWN_EQUIPPED_APPEARANCE = new HashMap<>(); + // A list of potential game executable filenames for each game + private static final EnumMap>> DEFAULT_GAME_BINARIES = new EnumMap<>(Game.class); // Using the singleton approach private static Profile instance = null; @@ -564,6 +567,9 @@ public enum Key { KNOWN_EQUIPPED_APPEARANCE.put("YW", "Wings (male)"); KNOWN_EQUIPPED_APPEARANCE.put("ZW", "Wings (female)"); + // initializing potential game executable filenames + initDefaultGameBinaries(); + // static properties are always available initStaticProperties(); } @@ -1139,6 +1145,71 @@ public static boolean isSaveGame(Path relPath) return retVal; } + /** + * Returns a list of potential game binary filenames for the current game and platform. + * Returned list can be empty but is never {@code null}. + */ + public static List getGameBinaries() + { + return getGameBinaries(null, null); + } + + /** + * Returns a list of potential game binary filenames for the specified game and platform. + * Returned list can be empty but is never {@code null}. + */ + public static List getGameBinaries(Game game, Platform.OS os) + { + List list = null; + + if (game == null) + game = getGame(); + if (os == null) + os = Platform.getPlatform(); + + EnumMap> osMap = DEFAULT_GAME_BINARIES.get(game); + if (osMap != null) + list = osMap.get(os); + + return Collections.unmodifiableList((list != null) ? list : new ArrayList<>(1)); + } + + /** Returns a list of paths for existing game binaries associated with the current game and platform. */ + public static List getGameBinaryPaths() + { + return getGameBinaryPaths(null, null); + } + + /** Returns a list of existing game binary paths associated with the specified game and platform. */ + public static List getGameBinaryPaths(Game game, Platform.OS os) + { + List list = new ArrayList<>(); + + if (game == null) + game = getGame(); + if (os == null) + os = Platform.getPlatform(); + + List listNames = getGameBinaries(game, os); + Path root = getGameRoot(); + for (String name : listNames) { + Path path = FileManager.queryExisting(root, name); + if (path != null) { + if (os == Platform.OS.MacOS && + path.toString().toLowerCase(Locale.ENGLISH).endsWith(".app") && + Files.isDirectory(path)) { + if (!list.contains(path)) + list.add(path); + } else if (Files.isRegularFile(path)) { + if (!list.contains(path)) + list.add(path); + } + } + } + + return list; + } + // Returns the Property object assigned to the given key. private static Property getEntry(Key key) { @@ -1189,6 +1260,202 @@ private static void initStaticProperties() addEntry(Key.GET_GLOBAL_DIALOG_NAME_FEMALE, Type.STRING, "dialogf.tlk"); } + // Initializes a list of potential executable filenames for each game and platform + private static void initDefaultGameBinaries() + { + DEFAULT_GAME_BINARIES.clear(); + EnumMap> osMap; + List emptyList = new ArrayList<>();; + List list; + + // BG1 & BG1TotSC (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("bgmain2.exe"); + list.add("bgmain.exe"); + list.add("baldur.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BG1, osMap); + DEFAULT_GAME_BINARIES.put(Game.BG1TotSC, osMap); + + // Tutu (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("bgmain.exe"); + list.add("baldur.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.Tutu, osMap); + + // BG2SoA & BG2ToB (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("bgmain.exe"); + list.add("baldur.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BG2SoA, osMap); + DEFAULT_GAME_BINARIES.put(Game.BG2ToB, osMap); + + // BGT (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("bgmain.exe"); + list.add("baldur.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BGT, osMap); + + // PST (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("torment.exe"); + list.add("pst.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.PST, osMap); + + // IWD & IWDHoW & IWDHowTotLM (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("idmain.exe"); + list.add("icewind.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.IWD, osMap); + DEFAULT_GAME_BINARIES.put(Game.IWDHoW, osMap); + DEFAULT_GAME_BINARIES.put(Game.IWDHowTotLM, osMap); + + // IWD2 (Windows) + osMap = new EnumMap<>(Platform.OS.class); + osMap.put(Platform.OS.Unix, emptyList); + osMap.put(Platform.OS.MacOS, emptyList); + list = new ArrayList<>(); + list.add("iwd2.exe"); + list.add("icewind2.exe"); + list.add("icewind.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.IWD2, osMap); + + // BG1EE (Linux, macOS, Windows) + osMap = new EnumMap<>(Platform.OS.class); + list = new ArrayList<>(); + list.add("baldursgate64"); + list.add("baldursgate"); + list.add("baldur"); + osMap.put(Platform.OS.Unix, list); + list = new ArrayList<>(); + list.add("Baldur's Gate - Enhanced Edition.app"); + list.add("Baldur's Gate - Enhanced Edition.app/Contents/MacOS/Baldur's Gate - Enhanced Edition"); + list.add("Baldur's Gate - Enhanced Edition"); + osMap.put(Platform.OS.MacOS, list); + list = new ArrayList<>(); + list.add("Baldur.exe"); + list.add("BGEE.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BG1EE, osMap); + + // BG1BG1SoD (Linux, macOS, Windows) + osMap = new EnumMap<>(Platform.OS.class); + list = new ArrayList<>(); + list.add("SiegeOfDragonspear64"); + list.add("SiegeOfDragonspear"); + list.add("BaldursGate64"); + list.add("BaldursGate"); + list.add("Baldur"); + list.add("siegeofdragonspear64"); + list.add("siegeofdragonspear"); + list.add("baldursgate64"); + list.add("baldursgate"); + list.add("baldur"); + osMap.put(Platform.OS.Unix, list); + list = new ArrayList<>(); + list.add("Baldur's Gate - Enhanced Edition.app"); + list.add("Baldur's Gate - Enhanced Edition.app/Contents/MacOS/Baldur's Gate - Enhanced Edition"); + list.add("Baldur's Gate - Enhanced Edition"); + osMap.put(Platform.OS.MacOS, list); + list = new ArrayList<>(); + list.add("SiegeOfDragonspear.exe"); + list.add("SOD.exe"); + list.add("Baldur.exe"); + list.add("BGEE.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BG1SoD, osMap); + + // BG2EE & EET (Linux, macOS, Windows) + osMap = new EnumMap<>(Platform.OS.class); + list = new ArrayList<>(); + list.add("BaldursGateII64"); + list.add("BaldursGateII"); + list.add("Baldur"); + list.add("baldursgateii64"); + list.add("baldursgateii"); + list.add("baldur"); + osMap.put(Platform.OS.Unix, list); + list = new ArrayList<>(); + list.add("BaldursGateIIEnhancedEdition.app"); + list.add("BaldursGateIIEnhancedEdition.app/Contents/MacOS/BaldursGateIIEnhancedEdition"); + list.add("BaldursGateIIEnhancedEdition"); + list.add("Baldur's Gate II - Enhanced Edition.app"); + list.add("Baldur's Gate II - Enhanced Edition.app/Contents/MacOS/Baldur's Gate II - Enhanced Edition"); + list.add("Baldur's Gate II - Enhanced Edition"); + osMap.put(Platform.OS.MacOS, list); + list = new ArrayList<>(); + list.add("Baldur.exe"); + list.add("BG2EE.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.BG2EE, osMap); + DEFAULT_GAME_BINARIES.put(Game.EET, osMap); + + // IWDEE (Linux, macOS, Windows) + osMap = new EnumMap<>(Platform.OS.class); + list = new ArrayList<>(); + list.add("IcewindDale64"); + list.add("IcewindDale"); + list.add("Icewind"); + list.add("icewinddale64"); + list.add("icewinddale"); + list.add("icewind"); + osMap.put(Platform.OS.Unix, list); + list = new ArrayList<>(); + list.add("IcewindDale.app"); + list.add("IcewindDale.app/Contents/MacOS/IcewindDale"); + list.add("Icewind Dale - Enhanced Edition.app"); + list.add("Icewind Dale - Enhanced Edition.app/Contents/MacOS/Icewind Dale - Enhanced Edition"); + osMap.put(Platform.OS.MacOS, list); + list = new ArrayList<>(); + list.add("Icewind.exe"); + list.add("IWD.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.IWDEE, osMap); + + // PSTEE (Linux, macOS, Windows) + osMap = new EnumMap<>(Platform.OS.class); + list = new ArrayList<>(); + list.add("Torment64"); + list.add("Torment"); + list.add("torment64"); + list.add("torment"); + osMap.put(Platform.OS.Unix, list); + list = new ArrayList<>(); + list.add("Planescape Torment - Enhanced Edition.app"); + list.add("Planescape Torment - Enhanced Edition.app/Contents/MacOS/Planescape Torment - Enhanced Edition"); + list.add("Planescape Torment - Enhanced Edition"); + osMap.put(Platform.OS.MacOS, list); + list = new ArrayList<>(); + list.add("Torment.exe"); + list.add("PST.exe"); + osMap.put(Platform.OS.Windows, list); + DEFAULT_GAME_BINARIES.put(Game.PSTEE, osMap); + } + // Attempts to determine home folder name from the game's "engine.lua" file if available private static String getLuaHomeFolderName(Game game) { diff --git a/src/org/infinity/util/Platform.java b/src/org/infinity/util/Platform.java index 1921dfc96..4ce0c7761 100644 --- a/src/org/infinity/util/Platform.java +++ b/src/org/infinity/util/Platform.java @@ -26,6 +26,12 @@ public enum OS { /** Whether this a Sun OS or Solaris system. */ public final static boolean IS_SOLARIS = (getPlatform() == OS.Solaris); + /** 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"); + + /** Returns the system-dependent name-separator character as string for the current platform. */ + public final static String SEPARATOR = System.getProperty("file.separator"); + /** * Determines the current operating system. */ From 8fcf47d43b5acca0e3302bc742020edb44147b6b Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 30 Aug 2020 13:48:58 +0200 Subject: [PATCH 12/14] Remove functionless Game menu entry "Release Dialog.tlk Lock" --- src/org/infinity/gui/BrowserMenuBar.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index 0404fa576..ac31f71f6 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -737,7 +737,7 @@ private static Frame findActiveFrame() /////////////////////////////// private static final class GameMenu extends JMenu implements ActionListener { - private final JMenuItem gameOpenFile, gameOpenGame, gameRefresh, gameExit, gameCloseTLK, + private final JMenuItem gameOpenFile, gameOpenGame, gameRefresh, gameExit, gameProperties, gameBookmarkAdd, gameBookmarkEdit, gameRecentClear; private final JMenu gameRecent = new JMenu("Recently opened games"); @@ -765,9 +765,6 @@ private GameMenu() gameRefresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); gameRefresh.setActionCommand("Refresh"); add(gameRefresh); - gameCloseTLK = makeMenuItem("Release Dialog.tlk Lock", KeyEvent.VK_D, Icons.getIcon(Icons.ICON_RELEASE_16), - -1, this); - add(gameCloseTLK); gameProperties = makeMenuItem("Game Properties...", KeyEvent.VK_P, Icons.getIcon(Icons.ICON_EDIT_16), -1, this); add(gameProperties); @@ -1116,9 +1113,6 @@ public void actionPerformed(ActionEvent event) NearInfinity.getInstance().openGame(keyFile); } } - } else if (event.getSource() == gameCloseTLK) { - JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Read lock released", - "Release Dialog.tlk", JOptionPane.INFORMATION_MESSAGE); } else if (event.getSource() == gameProperties) { new GameProperties(NearInfinity.getInstance()); } else if (event.getSource() == gameBookmarkAdd) { From 7860992d92e62dd8280b528cf340e2a41b3c626a Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Sun, 30 Aug 2020 17:17:04 +0200 Subject: [PATCH 13/14] Add "Properties" feature to TTF resource viewer --- .../resource/graphics/MosResource.java | 2 +- .../infinity/resource/other/TtfResource.java | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/org/infinity/resource/graphics/MosResource.java b/src/org/infinity/resource/graphics/MosResource.java index 868e19412..e49d9477b 100644 --- a/src/org/infinity/resource/graphics/MosResource.java +++ b/src/org/infinity/resource/graphics/MosResource.java @@ -394,7 +394,7 @@ private void showProperties() sb.append(br).append("Referenced PVRZ pages:").append(br); sb.append(pageList.toString()).append(br); } - sb.append(""); + sb.append(""); JOptionPane.showMessageDialog(panel, sb.toString(), "Properties of " + resName, JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { diff --git a/src/org/infinity/resource/other/TtfResource.java b/src/org/infinity/resource/other/TtfResource.java index ca014e84a..b9fc1c7dc 100644 --- a/src/org/infinity/resource/other/TtfResource.java +++ b/src/org/infinity/resource/other/TtfResource.java @@ -13,11 +13,13 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.InputStream; +import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; +import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; @@ -32,6 +34,7 @@ import org.infinity.gui.ButtonPanel; import org.infinity.gui.ViewerUtil; +import org.infinity.icon.Icons; import org.infinity.resource.Resource; import org.infinity.resource.ResourceFactory; import org.infinity.resource.ViewableContainer; @@ -39,6 +42,8 @@ public class TtfResource implements Resource, DocumentListener, ActionListener { + private static final ButtonPanel.Control Properties = ButtonPanel.Control.CUSTOM_1; + private static final String DEFAULT_STRING = "The quick brown fox jumps over the lazy dog. 1234567890"; private static final int[] FONT_SIZE = { 12, 18, 24, 36, 48, 60, 72, 96, 128, 192 }; @@ -113,6 +118,9 @@ public JComponent makeViewer(ViewableContainer container) scroll.setBorder(BorderFactory.createLoweredBevelBorder()); ((JButton)buttonPanel.addControl(ButtonPanel.Control.EXPORT_BUTTON)).addActionListener(this); + JButton bProperties = new JButton("Properties...", Icons.getIcon(Icons.ICON_EDIT_16)); + bProperties.addActionListener(this); + buttonPanel.addControl(bProperties, Properties); panel = new JPanel(new BorderLayout()); panel.add(pInput, BorderLayout.NORTH); @@ -131,6 +139,8 @@ public void actionPerformed(ActionEvent event) { if (buttonPanel.getControlByType(ButtonPanel.Control.EXPORT_BUTTON) == event.getSource()) { ResourceFactory.exportResource(entry, panel.getTopLevelAncestor()); + } else if (buttonPanel.getControlByType(Properties) == event.getSource()) { + showProperties(); } } @@ -215,4 +225,19 @@ private void updateText(String text) tpDisplay.setCaretPosition(0); } } + + // Shows message box about basic resource properties + private void showProperties() + { + String resName = entry.getResourceName().toUpperCase(Locale.ENGLISH); + String fontName = font.getFontName(); + String fontFamily = font.getFamily(); + + StringBuilder sb = new StringBuilder(""); + sb.append(""); + sb.append(""); + sb.append("
Font name:").append(fontName).append("
Font family:").append(fontFamily).append("
"); + JOptionPane.showMessageDialog(panel, sb.toString(), "Properties of " + resName, + JOptionPane.INFORMATION_MESSAGE); + } } From 08e2f79e6a76367540ebc20a8b086e127b0f3698 Mon Sep 17 00:00:00 2001 From: Argent77 <4519923+Argent77@users.noreply.github.com> Date: Tue, 1 Sep 2020 12:07:23 +0200 Subject: [PATCH 14/14] Version 2.1-20200901 --- src/org/infinity/gui/BrowserMenuBar.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/org/infinity/gui/BrowserMenuBar.java b/src/org/infinity/gui/BrowserMenuBar.java index ac31f71f6..b483aeb64 100644 --- a/src/org/infinity/gui/BrowserMenuBar.java +++ b/src/org/infinity/gui/BrowserMenuBar.java @@ -109,7 +109,7 @@ public final class BrowserMenuBar extends JMenuBar implements KeyEventDispatcher { - public static final String VERSION = "v2.1-20200620"; + public static final String VERSION = "v2.1-20200901"; public static final LookAndFeelInfo DEFAULT_LOOKFEEL = new LookAndFeelInfo("Metal", "javax.swing.plaf.metal.MetalLookAndFeel");