From 8299e849aabfb25a3296a01858a220b3a232e31c Mon Sep 17 00:00:00 2001 From: Reinhard Pointner Date: Sat, 25 Jul 2015 22:47:19 +0000 Subject: [PATCH] * Format Source --- source/net/filebot/RenameAction.java | 4 +- source/net/filebot/ResourceManager.java | 2 +- source/net/filebot/archive/ApacheVFS.java | 3 + .../archive/ArchiveOpenVolumeCallback.java | 47 ++-- .../net/filebot/archive/ExtractCallback.java | 43 ++-- .../filebot/archive/ExtractOutProvider.java | 4 +- .../net/filebot/archive/ExtractOutStream.java | 16 +- .../filebot/archive/SevenZipExecutable.java | 3 + .../net/filebot/archive/SevenZipLoader.java | 18 +- .../archive/SevenZipNativeBindings.java | 1 + .../archive/VolumedArchiveInStream.java | 120 +++++----- source/net/filebot/cli/GroovyPad.java | 1 + .../net/filebot/cli/ScriptShellMethods.java | 6 +- .../format/AssociativeScriptObject.java | 64 ++--- source/net/filebot/format/Define.java | 4 +- .../filebot/format/ExpressionException.java | 14 +- .../format/ExpressionFormatMethods.java | 20 +- .../net/filebot/format/MediaBindingBean.java | 7 +- .../filebot/format/PrivilegedInvocation.java | 16 +- .../net/filebot/format/PropertyBindings.java | 66 +++--- source/net/filebot/gio/GIOLibrary.java | 24 +- source/net/filebot/gio/GVFS.java | 18 +- source/net/filebot/hash/ChecksumHash.java | 12 +- source/net/filebot/hash/Ed2kHash.java | 16 +- source/net/filebot/hash/Hash.java | 6 +- .../net/filebot/hash/MessageDigestHash.java | 14 +- source/net/filebot/hash/SfvFormat.java | 14 +- .../filebot/hash/VerificationFileReader.java | 38 +-- .../filebot/hash/VerificationFileWriter.java | 16 +- .../net/filebot/hash/VerificationFormat.java | 32 +-- source/net/filebot/mac/DropToUnlock.java | 2 + source/net/filebot/mac/xattr/XAttr.java | 6 +- .../media/SmartSeasonEpisodeMatcher.java | 1 + .../filebot/mediainfo/MediaInfoLibrary.java | 18 +- .../similarity/CrossPropertyMetric.java | 28 +-- .../filebot/similarity/FileNameMetric.java | 12 +- .../filebot/similarity/FileSizeMetric.java | 12 +- source/net/filebot/similarity/Match.java | 18 +- source/net/filebot/similarity/MetricMin.java | 8 +- .../similarity/NameSimilarityMetric.java | 26 +- .../similarity/NumericSimilarityMetric.java | 58 ++--- .../similarity/SeasonEpisodeMatcher.java | 2 +- .../filebot/similarity/SeriesNameMatcher.java | 8 +- .../similarity/SimilarityComparator.java | 22 +- .../filebot/similarity/SimilarityMetric.java | 4 +- .../filebot/similarity/TimeStampMetric.java | 14 +- .../net/filebot/subtitle/MicroDVDReader.java | 34 +-- source/net/filebot/subtitle/SubRipWriter.java | 14 +- .../subtitle/SubStationAlphaReader.java | 42 ++-- .../net/filebot/subtitle/SubViewerReader.java | 14 +- .../net/filebot/subtitle/SubtitleElement.java | 16 +- .../net/filebot/subtitle/SubtitleFormat.java | 22 +- .../net/filebot/subtitle/SubtitleMetrics.java | 3 + .../net/filebot/subtitle/SubtitleReader.java | 20 +- .../filebot/subtitle/SubtitleTimeFormat.java | 22 +- source/net/filebot/torrent/BDecoder.java | 222 +++++++++--------- source/net/filebot/torrent/Torrent.java | 132 +++++------ .../filebot/ui/FileBotListExportHandler.java | 14 +- source/net/filebot/ui/FileBotTab.java | 46 ++-- .../net/filebot/ui/FileBotTabComponent.java | 38 +-- .../net/filebot/ui/LanguageComboBoxModel.java | 2 + source/net/filebot/ui/MainFrame.java | 2 + .../net/filebot/ui/NotificationLogging.java | 60 ++--- source/net/filebot/ui/PanelBuilder.java | 8 +- .../net/filebot/ui/analyze/AnalyzePanel.java | 1 + .../ui/analyze/AnalyzePanelBuilder.java | 8 +- source/net/filebot/ui/analyze/FileTree.java | 1 + .../ui/analyze/FileTreeCellRenderer.java | 14 +- source/net/filebot/ui/analyze/TypeTool.java | 3 - .../episodelist/EpisodeListPanelBuilder.java | 8 +- .../ui/episodelist/SeasonSpinnerModel.java | 28 +-- .../net/filebot/ui/list/ListPanelBuilder.java | 8 +- .../ui/rename/CharacterHighlightPainter.java | 24 +- .../ui/rename/ExpressionFormatter.java | 32 +-- .../filebot/ui/rename/FileNameFormatter.java | 28 +-- .../ui/rename/HighlightListCellRenderer.java | 46 ++-- source/net/filebot/ui/rename/MatchAction.java | 1 + .../net/filebot/ui/rename/MatchFormatter.java | 12 +- source/net/filebot/ui/rename/MatchModel.java | 124 +++++----- .../net/filebot/ui/rename/MovieFormatter.java | 16 +- .../net/filebot/ui/rename/PresetEditor.java | 3 +- source/net/filebot/ui/rename/RenameList.java | 2 + source/net/filebot/ui/rename/RenamePanel.java | 5 +- .../filebot/ui/rename/RenamePanelBuilder.java | 8 +- .../ui/rename/ScrollPaneSynchronizer.java | 40 ++-- .../net/filebot/ui/rename/ValidateDialog.java | 124 +++++----- source/net/filebot/ui/sfv/ChecksumButton.java | 26 +- source/net/filebot/ui/sfv/ChecksumCell.java | 78 +++--- .../filebot/ui/sfv/ChecksumCellRenderer.java | 30 +-- .../ui/sfv/ChecksumComputationService.java | 2 +- source/net/filebot/ui/sfv/ChecksumRow.java | 73 +++--- source/net/filebot/ui/sfv/ChecksumTable.java | 30 +-- .../ui/sfv/ChecksumTableExportHandler.java | 32 +-- .../filebot/ui/sfv/ChecksumTableModel.java | 1 + .../ui/sfv/HighlightPatternCellRenderer.java | 38 +-- .../net/filebot/ui/sfv/SfvPanelBuilder.java | 8 +- .../filebot/ui/sfv/StateIconCellRenderer.java | 16 +- .../ui/sfv/SwingWorkerCellRenderer.java | 29 +-- .../filebot/ui/sfv/TotalProgressPanel.java | 70 +++--- .../subtitle/MemoryFileListExportHandler.java | 30 +-- .../ui/subtitle/SubtitleDropTarget.java | 2 + .../ui/subtitle/SubtitleFileChooser.java | 24 +- .../subtitle/SubtitlePackageCellRenderer.java | 52 ++-- .../filebot/ui/subtitle/SubtitlePanel.java | 3 + .../ui/subtitle/SubtitlePanelBuilder.java | 8 +- .../ui/subtitle/SubtitleUploadDialog.java | 3 +- .../ui/transfer/ArrayTransferable.java | 18 +- .../filebot/ui/transfer/ClipboardHandler.java | 4 +- .../ui/transfer/CompositeTranserable.java | 30 +-- .../ui/transfer/DefaultClipboardHandler.java | 32 +-- .../ui/transfer/DefaultTransferHandler.java | 54 ++--- .../ui/transfer/FileExportHandler.java | 8 +- .../net/filebot/ui/transfer/LoadAction.java | 1 + .../net/filebot/ui/transfer/SaveAction.java | 1 + .../ui/transfer/TextFileExportHandler.java | 24 +- .../ui/transfer/TextFileTransferable.java | 24 +- .../transfer/TransferableExportHandler.java | 8 +- .../ui/transfer/TransferablePolicy.java | 54 ++--- .../filebot/util/ByteBufferInputStream.java | 40 ++-- .../filebot/util/DefaultThreadFactory.java | 29 +-- source/net/filebot/util/FileUtilities.java | 4 +- source/net/filebot/util/FilterIterator.java | 26 +- .../filebot/util/ListChangeSynchronizer.java | 35 +-- source/net/filebot/util/PreferencesList.java | 52 ++-- source/net/filebot/util/PreferencesMap.java | 218 ++++++++--------- source/net/filebot/util/TeePrintStream.java | 28 +-- source/net/filebot/util/TemporaryFolder.java | 10 +- source/net/filebot/util/TreeIterator.java | 32 +-- source/net/filebot/util/UnicodeReader.java | 12 + source/net/filebot/util/XPathUtilities.java | 2 +- .../filebot/util/prefs/FilePreferences.java | 88 +++---- .../util/prefs/FilePreferencesFactory.java | 34 +-- source/net/filebot/util/ui/AbstractBean.java | 16 +- .../ui/AbstractFancyListCellRenderer.java | 108 ++++----- .../filebot/util/ui/ColorTintImageFilter.java | 16 +- .../net/filebot/util/ui/DashedSeparator.java | 20 +- .../util/ui/DefaultFancyListCellRenderer.java | 26 +- .../filebot/util/ui/EmptySelectionModel.java | 42 ++-- .../util/ui/FancyTreeCellRenderer.java | 58 ++--- source/net/filebot/util/ui/GradientStyle.java | 92 ++++---- source/net/filebot/util/ui/LabelProvider.java | 6 +- .../filebot/util/ui/LazyDocumentListener.java | 28 +-- source/net/filebot/util/ui/ListView.java | 89 +++---- .../filebot/util/ui/LoadingOverlayPane.java | 34 +-- .../filebot/util/ui/NullLabelProvider.java | 6 +- .../filebot/util/ui/ProgressIndicator.java | 72 +++--- source/net/filebot/util/ui/RoundBorder.java | 24 +- source/net/filebot/util/ui/SelectButton.java | 3 + source/net/filebot/util/ui/ShadowBorder.java | 96 ++++---- .../filebot/util/ui/SimpleLabelProvider.java | 26 +- .../ui/SwingWorkerPropertyChangeAdapter.java | 27 ++- .../util/ui/notification/Direction.java | 6 +- .../ui/notification/MessageNotification.java | 30 +-- .../ui/notification/NotificationLayout.java | 4 +- .../ui/notification/NotificationManager.java | 22 +- .../ui/notification/NotificationWindow.java | 46 ++-- .../notification/QueueNotificationLayout.java | 52 ++-- .../util/ui/notification/SeparatorBorder.java | 116 ++++----- .../SimpleNotificationLayout.java | 40 ++-- source/net/filebot/vfs/MemoryFile.java | 16 +- source/net/filebot/vfs/SimpleFileInfo.java | 2 + source/net/filebot/vfs/ZipArchive.java | 20 +- .../web/AbstractEpisodeListProvider.java | 1 + source/net/filebot/web/AcoustIDClient.java | 2 +- source/net/filebot/web/AudioTrackFormat.java | 8 +- source/net/filebot/web/MovieFormat.java | 44 ++-- .../net/filebot/web/OpenSubtitlesClient.java | 4 +- .../web/OpenSubtitlesSubtitleDescriptor.java | 2 +- .../net/filebot/web/OpenSubtitlesXmlRpc.java | 5 +- .../web/SeasonOutOfBoundsException.java | 16 +- .../net/filebot/web/SubtitleDescriptor.java | 12 +- source/net/filebot/web/TheTVDBClient.java | 3 +- .../filebot/format/ExpressionFormatTest.java | 66 +++--- .../filebot/hash/VerificationFormatTest.java | 12 +- test/net/filebot/media/ReleaseInfoTest.java | 12 +- .../filebot/similarity/DateMetricTest.java | 6 +- .../similarity/NameSimilarityMetricTest.java | 6 +- .../NumericSimilarityMetricTest.java | 34 +-- .../similarity/SeasonEpisodeMetricTest.java | 12 +- .../similarity/SeriesNameMatcherTest.java | 50 ++-- .../similarity/SimilarityTestSuite.java | 2 +- .../filebot/subtitle/MicroDVDReaderTest.java | 18 +- .../filebot/subtitle/SubRipReaderTest.java | 10 +- .../subtitle/SubtitleReaderTestSuite.java | 2 +- .../net/filebot/ui/rename/MatchModelTest.java | 48 ++-- .../util/ByteBufferOutputStreamTest.java | 20 +- test/net/filebot/util/FileUtilitiesTest.java | 16 +- test/net/filebot/util/FilterIteratorTest.java | 20 +- .../net/filebot/util/PreferencesListTest.java | 48 ++-- test/net/filebot/util/PreferencesMapTest.java | 76 +++--- test/net/filebot/util/TestUtil.java | 16 +- test/net/filebot/util/TreeIteratorTest.java | 32 +-- test/net/filebot/util/UtilTestSuite.java | 2 +- .../filebot/web/OpenSubtitlesHasherTest.java | 16 +- 194 files changed, 2700 insertions(+), 2622 deletions(-) diff --git a/source/net/filebot/RenameAction.java b/source/net/filebot/RenameAction.java index b169e0c3..2b56978b 100644 --- a/source/net/filebot/RenameAction.java +++ b/source/net/filebot/RenameAction.java @@ -6,7 +6,7 @@ import java.io.File; public interface RenameAction { - + File rename(File from, File to) throws Exception; - + } diff --git a/source/net/filebot/ResourceManager.java b/source/net/filebot/ResourceManager.java index 03ea5a75..acb81ad2 100644 --- a/source/net/filebot/ResourceManager.java +++ b/source/net/filebot/ResourceManager.java @@ -56,7 +56,7 @@ public final class ResourceManager { /** * Get the URL of an image resource in this jar. Image must be located in resources/ and the file type is assumed to be png. - * + * * @param name * simple name of the resource (without extension) * @return URL of the resource or null if resource does not exist diff --git a/source/net/filebot/archive/ApacheVFS.java b/source/net/filebot/archive/ApacheVFS.java index 2d8b1cf6..977f4af7 100644 --- a/source/net/filebot/archive/ApacheVFS.java +++ b/source/net/filebot/archive/ApacheVFS.java @@ -35,6 +35,7 @@ public class ApacheVFS implements ArchiveExtractor, Closeable { this.archive = fsm.createFileSystem(fsm.toFileObject(file)); } + @Override public List listFiles() throws Exception { List paths = new ArrayList(); for (FileObject it : archive.findFiles(ALL_FILES)) { @@ -46,10 +47,12 @@ public class ApacheVFS implements ArchiveExtractor, Closeable { return paths; } + @Override public void extract(File outputDir) throws Exception { extract(outputDir, null); } + @Override public void extract(File outputDir, FileFilter filter) throws Exception { fsm.toFileObject(outputDir).copyFrom(archive, filter == null ? ALL_FILES : new FileFilterSelector(filter)); } diff --git a/source/net/filebot/archive/ArchiveOpenVolumeCallback.java b/source/net/filebot/archive/ArchiveOpenVolumeCallback.java index 1b9ff8a4..c8688227 100644 --- a/source/net/filebot/archive/ArchiveOpenVolumeCallback.java +++ b/source/net/filebot/archive/ArchiveOpenVolumeCallback.java @@ -18,33 +18,34 @@ import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream; class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveOpenCallback, Closeable { - + /** * Cache for opened file streams */ private Map openedRandomAccessFileList = new HashMap(); - + /** * Name of the last volume returned by {@link #getStream(String)} */ private String name; - - + + /** * This method should at least provide the name of the last * opened volume (propID=PropID.NAME). - * + * * @see IArchiveOpenVolumeCallback#getProperty(PropID) */ + @Override public Object getProperty(PropID propID) throws SevenZipException { switch (propID) { - case NAME: - return name; + case NAME: + return name; } return null; } - - + + /** * The name of the required volume will be calculated out of the * name of the first volume and a volume index. In case of RAR file, @@ -56,6 +57,7 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO *
  • test.part001.rar - first part of a multi-part archive. "00" indicates, that at least 100 volumes must exist.
  • * */ + @Override public IInStream getStream(String filename) throws SevenZipException { try { // We use caching of opened streams, so check cache first @@ -64,19 +66,19 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO // Move the file pointer back to the beginning // in order to emulating new stream randomAccessFile.seek(0); - + // Save current volume name in case getProperty() will be called name = filename; - + return new RandomAccessFileInStream(randomAccessFile); } - + // Nothing useful in cache. Open required volume. randomAccessFile = new RandomAccessFile(filename, "r"); - + // Put new stream in the cache openedRandomAccessFileList.put(filename, randomAccessFile); - + // Save current volume name in case getProperty() will be called name = filename; return new RandomAccessFileInStream(randomAccessFile); @@ -85,7 +87,7 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO // 1. never exists. 7-Zip doesn't know how many volumes should // exist, so it have to try each volume. // 2. should be there, but doesn't. This is an error case. - + // Since normal and error cases are possible, // we can't throw an error message return null; // We return always null in this case @@ -93,25 +95,26 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO throw new RuntimeException(e); } } - - + + /** * Close all opened streams */ + @Override public void close() throws IOException { for (RandomAccessFile file : openedRandomAccessFileList.values()) { file.close(); } } - - + + @Override public void setCompleted(Long files, Long bytes) throws SevenZipException { } - - + + @Override public void setTotal(Long files, Long bytes) throws SevenZipException { } - + } diff --git a/source/net/filebot/archive/ExtractCallback.java b/source/net/filebot/archive/ExtractCallback.java index c994ba15..41cb0cf5 100644 --- a/source/net/filebot/archive/ExtractCallback.java +++ b/source/net/filebot/archive/ExtractCallback.java @@ -16,48 +16,51 @@ import net.sf.sevenzipjbinding.SevenZipException; class ExtractCallback implements IArchiveExtractCallback { - + private ISevenZipInArchive inArchive; private ExtractOutProvider extractOut; - + private ExtractOutStream output = null; - - + + public ExtractCallback(ISevenZipInArchive inArchive, ExtractOutProvider extractOut) { this.inArchive = inArchive; this.extractOut = extractOut; } - - + + + @Override public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException { if (extractAskMode != ExtractAskMode.EXTRACT) { return null; } - + boolean isFolder = (Boolean) inArchive.getProperty(index, PropID.IS_FOLDER); if (isFolder) { return null; } - + String path = (String) inArchive.getProperty(index, PropID.PATH); try { OutputStream target = extractOut.getStream(new File(path)); if (target == null) { return null; } - + output = new ExtractOutStream(target); return output; } catch (IOException e) { throw new SevenZipException(e); } } - - + + + @Override public void prepareOperation(ExtractAskMode extractAskMode) throws SevenZipException { } - - + + + @Override public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException { if (output != null) { try { @@ -68,18 +71,20 @@ class ExtractCallback implements IArchiveExtractCallback { output = null; } } - + if (extractOperationResult != ExtractOperationResult.OK) { throw new SevenZipException("Extraction Error: " + extractOperationResult); } } - - + + + @Override public void setCompleted(long completeValue) throws SevenZipException { } - - + + + @Override public void setTotal(long total) throws SevenZipException { } - + } diff --git a/source/net/filebot/archive/ExtractOutProvider.java b/source/net/filebot/archive/ExtractOutProvider.java index da2dbe89..ba02b7b2 100644 --- a/source/net/filebot/archive/ExtractOutProvider.java +++ b/source/net/filebot/archive/ExtractOutProvider.java @@ -8,7 +8,7 @@ import java.io.OutputStream; public interface ExtractOutProvider { - + OutputStream getStream(File archivePath) throws IOException; - + } diff --git a/source/net/filebot/archive/ExtractOutStream.java b/source/net/filebot/archive/ExtractOutStream.java index fdeac9eb..d33cb9f9 100644 --- a/source/net/filebot/archive/ExtractOutStream.java +++ b/source/net/filebot/archive/ExtractOutStream.java @@ -11,15 +11,15 @@ import net.sf.sevenzipjbinding.SevenZipException; class ExtractOutStream implements ISequentialOutStream, Closeable { - + private OutputStream out; - - + + public ExtractOutStream(OutputStream out) { this.out = out; } - - + + @Override public int write(byte[] data) throws SevenZipException { try { @@ -29,11 +29,11 @@ class ExtractOutStream implements ISequentialOutStream, Closeable { } return data.length; // return amount of proceed data } - - + + @Override public void close() throws IOException { out.close(); } - + } diff --git a/source/net/filebot/archive/SevenZipExecutable.java b/source/net/filebot/archive/SevenZipExecutable.java index e2f49d82..218e9f03 100644 --- a/source/net/filebot/archive/SevenZipExecutable.java +++ b/source/net/filebot/archive/SevenZipExecutable.java @@ -61,6 +61,7 @@ public class SevenZipExecutable implements ArchiveExtractor { } } + @Override public List listFiles() throws IOException { List paths = new ArrayList(); @@ -81,11 +82,13 @@ public class SevenZipExecutable implements ArchiveExtractor { return paths; } + @Override public void extract(File outputDir) throws IOException { // e.g. 7z x -y -aos archive.7z execute(get7zCommand(), "x", "-y", "-aos", archive.getPath(), "-o" + outputDir.getCanonicalPath()); } + @Override public void extract(File outputDir, FileFilter filter) throws IOException { // e.g. 7z x -y -aos archive.7z file.txt image.png info.nfo Stream command = Stream.of(get7zCommand(), "x", "-y", "-aos", archive.getPath(), "-o" + outputDir.getCanonicalPath()); diff --git a/source/net/filebot/archive/SevenZipLoader.java b/source/net/filebot/archive/SevenZipLoader.java index f2475302..1c78ee4e 100644 --- a/source/net/filebot/archive/SevenZipLoader.java +++ b/source/net/filebot/archive/SevenZipLoader.java @@ -14,15 +14,15 @@ import com.sun.jna.Platform; public class SevenZipLoader { - + private static boolean nativeLibrariesLoaded = false; - - + + private static synchronized void requireNativeLibraries() throws SevenZipNativeInitializationException { if (nativeLibrariesLoaded) { return; } - + // initialize 7z-JBinding native libs try { try { @@ -32,7 +32,7 @@ public class SevenZipLoader { } catch (Throwable e) { Logger.getLogger(SevenZipLoader.class.getName()).warning("Failed to preload library: " + e); } - + System.loadLibrary("7-Zip-JBinding"); SevenZip.initLoadedLibraries(); // NATIVE LIBS MUST BE LOADED WITH SYSTEM CLASSLOADER nativeLibrariesLoaded = true; @@ -40,17 +40,17 @@ public class SevenZipLoader { throw new SevenZipNativeInitializationException("Failed to load 7z-JBinding: " + e.getMessage(), e); } } - - + + public static ISevenZipInArchive open(IInStream stream, IArchiveOpenCallback callback) throws Exception { // initialize 7-Zip-JBinding requireNativeLibraries(); - + if (callback == null) { return SevenZip.openInArchive(null, stream); } else { return SevenZip.openInArchive(null, stream, callback); } } - + } diff --git a/source/net/filebot/archive/SevenZipNativeBindings.java b/source/net/filebot/archive/SevenZipNativeBindings.java index ce2a1494..834085ab 100644 --- a/source/net/filebot/archive/SevenZipNativeBindings.java +++ b/source/net/filebot/archive/SevenZipNativeBindings.java @@ -60,6 +60,7 @@ public class SevenZipNativeBindings implements ArchiveExtractor, Closeable { return item; } + @Override public List listFiles() throws SevenZipException { List paths = new ArrayList(); diff --git a/source/net/filebot/archive/VolumedArchiveInStream.java b/source/net/filebot/archive/VolumedArchiveInStream.java index 2d001264..ae67949a 100644 --- a/source/net/filebot/archive/VolumedArchiveInStream.java +++ b/source/net/filebot/archive/VolumedArchiveInStream.java @@ -13,66 +13,66 @@ import net.sf.sevenzipjbinding.SevenZipException; public class VolumedArchiveInStream implements IInStream { - + private static final String FIRST_VOLUME_POSTFIX = ".001"; - + private long absoluteOffset; private long absoluteLength = -1; - + private int currentIndex = -1; private IInStream currentInStream; private long currentVolumeOffset; private long currentVolumeLength; private List volumePositions = new ArrayList(); - + private final IArchiveOpenVolumeCallback archiveOpenVolumeCallback; private String cuttedVolumeFilename; - - + + public VolumedArchiveInStream(IArchiveOpenVolumeCallback archiveOpenVolumeCallback) throws SevenZipException { this((String) archiveOpenVolumeCallback.getProperty(PropID.NAME), archiveOpenVolumeCallback); } - - + + public VolumedArchiveInStream(String firstVolumeFilename, IArchiveOpenVolumeCallback archiveOpenVolumeCallback) throws SevenZipException { this.archiveOpenVolumeCallback = archiveOpenVolumeCallback; volumePositions.add(Long.valueOf(0)); - + if (!firstVolumeFilename.endsWith(FIRST_VOLUME_POSTFIX)) { throw new SevenZipException("The first volume filename '" + firstVolumeFilename + "' don't ends with the postfix: '" + FIRST_VOLUME_POSTFIX + "'. Can't proceed"); - + } - + cuttedVolumeFilename = firstVolumeFilename.substring(0, firstVolumeFilename.length() - 3); openVolume(1, true); } - - + + private void openVolume(int index, boolean seekToBegin) throws SevenZipException { if (currentIndex == index) { return; } - + for (int i = volumePositions.size(); i < index && absoluteLength == -1; i++) { openVolume(i, false); } - + if (absoluteLength != -1 && volumePositions.size() <= index) { return; } - + String volumeFilename = cuttedVolumeFilename + MessageFormat.format("{0,number,000}", Integer.valueOf(index)); - + // Get new IInStream IInStream newInStream = archiveOpenVolumeCallback.getStream(volumeFilename); - + if (newInStream == null) { absoluteLength = volumePositions.get(volumePositions.size() - 1).longValue(); return; } - + currentInStream = newInStream; - + if (volumePositions.size() == index) { // Determine volume size currentVolumeLength = currentInStream.seek(0, SEEK_END); @@ -80,23 +80,23 @@ public class VolumedArchiveInStream implements IInStream { throw new RuntimeException("Volume " + index + " is empty"); } volumePositions.add(Long.valueOf(volumePositions.get(index - 1).longValue() + currentVolumeLength)); - + if (seekToBegin) { currentInStream.seek(0, SEEK_SET); } } else { currentVolumeLength = volumePositions.get(index).longValue() - volumePositions.get(index - 1).longValue(); } - + if (seekToBegin) { currentVolumeOffset = 0; absoluteOffset = volumePositions.get(index - 1).longValue(); } - + currentIndex = index; } - - + + private void openVolumeToAbsoluteOffset() throws SevenZipException { int index = volumePositions.size() - 1; if (absoluteLength != -1 && absoluteOffset >= absoluteLength) { @@ -105,80 +105,80 @@ public class VolumedArchiveInStream implements IInStream { while (volumePositions.get(index).longValue() > absoluteOffset) { index--; } - + if (index < volumePositions.size() - 1) { openVolume(index + 1, false); return; } - + do { index++; openVolume(index, false); } while ((absoluteLength == -1 || absoluteOffset < absoluteLength) && volumePositions.get(index).longValue() <= absoluteOffset); - + } - - + + @Override public long seek(long offset, int seekOrigin) throws SevenZipException { long newOffset; boolean proceedWithSeek = false; switch (seekOrigin) { - case SEEK_SET: - newOffset = offset; - break; - - case SEEK_CUR: - newOffset = absoluteOffset + offset; - break; - - case SEEK_END: - if (absoluteLength == -1) { - openVolume(Integer.MAX_VALUE, false); - proceedWithSeek = true; - } - newOffset = absoluteLength + offset; - break; - - default: - throw new RuntimeException("Seek: unknown origin: " + seekOrigin); + case SEEK_SET: + newOffset = offset; + break; + + case SEEK_CUR: + newOffset = absoluteOffset + offset; + break; + + case SEEK_END: + if (absoluteLength == -1) { + openVolume(Integer.MAX_VALUE, false); + proceedWithSeek = true; + } + newOffset = absoluteLength + offset; + break; + + default: + throw new RuntimeException("Seek: unknown origin: " + seekOrigin); } - + if (newOffset == absoluteOffset && !proceedWithSeek) { return newOffset; } absoluteOffset = newOffset; - + openVolumeToAbsoluteOffset(); - + if (absoluteLength != -1 && absoluteLength <= absoluteOffset) { absoluteOffset = absoluteLength; return absoluteLength; } - + currentVolumeOffset = absoluteOffset - volumePositions.get(currentIndex - 1).longValue(); currentInStream.seek(currentVolumeOffset, SEEK_SET); - + return newOffset; } - - + + @Override public int read(byte[] data) throws SevenZipException { if (absoluteLength != -1 && absoluteOffset >= absoluteLength) { return 0; } - + int read = currentInStream.read(data); - + absoluteOffset += read; currentVolumeOffset += read; - + if (currentVolumeOffset >= currentVolumeLength) { openVolume(currentIndex + 1, true); } - + return read; } - + } diff --git a/source/net/filebot/cli/GroovyPad.java b/source/net/filebot/cli/GroovyPad.java index 6d066b7d..87f74d21 100644 --- a/source/net/filebot/cli/GroovyPad.java +++ b/source/net/filebot/cli/GroovyPad.java @@ -292,6 +292,7 @@ public class GroovyPad extends JFrame { private class ConsoleOutputStream extends ByteArrayOutputStream { + @Override public void flush() { try { String message = this.toString("UTF-8"); diff --git a/source/net/filebot/cli/ScriptShellMethods.java b/source/net/filebot/cli/ScriptShellMethods.java index 0c8f37ac..70979690 100644 --- a/source/net/filebot/cli/ScriptShellMethods.java +++ b/source/net/filebot/cli/ScriptShellMethods.java @@ -57,7 +57,7 @@ public class ScriptShellMethods { } public static List listFiles(File self, Closure closure) { - return (List) DefaultGroovyMethods.findAll(FileUtilities.getChildren(self), closure); + return DefaultGroovyMethods.findAll(FileUtilities.getChildren(self), closure); } public static boolean isVideo(File self) { @@ -121,7 +121,7 @@ public class ScriptShellMethods { List files = FileUtilities.listFiles(roots); if (closure != null) { - files = (List) DefaultGroovyMethods.findAll(files, closure); + files = DefaultGroovyMethods.findAll(files, closure); } return FileUtilities.sortByUniquePath(files); @@ -144,7 +144,7 @@ public class ScriptShellMethods { List folders = FileUtilities.listFolders(roots); if (closure != null) { - folders = (List) DefaultGroovyMethods.findAll(folders, closure); + folders = DefaultGroovyMethods.findAll(folders, closure); } return FileUtilities.sortByUniquePath(folders); diff --git a/source/net/filebot/format/AssociativeScriptObject.java b/source/net/filebot/format/AssociativeScriptObject.java index 3123a5c7..3f3d591a 100644 --- a/source/net/filebot/format/AssociativeScriptObject.java +++ b/source/net/filebot/format/AssociativeScriptObject.java @@ -15,18 +15,18 @@ import java.util.TreeSet; public class AssociativeScriptObject extends GroovyObjectSupport implements Iterable> { - + private final Map properties; - - + + public AssociativeScriptObject(Map properties) { this.properties = new LenientLookup(properties); } - - + + /** * Get the property with the given name. - * + * * @param name * the property name * @param start @@ -36,77 +36,77 @@ public class AssociativeScriptObject extends GroovyObjectSupport implements Iter public Object getProperty(String name) { return properties.get(name); } - - + + @Override public void setProperty(String name, Object value) { // ignore, object is immutable } - - + + @Override public Iterator> iterator() { return properties.entrySet().iterator(); } - - + + @Override public String toString() { // all the properties in alphabetic order return new TreeSet(properties.keySet()).toString(); } - - + + /** * Map allowing look-up of values by a fault-tolerant key as specified by the defining key. - * + * */ private static class LenientLookup extends AbstractMap { - + private final Map> lookup = new HashMap>(); - - + + public LenientLookup(Map source) { // populate lookup map for (Entry entry : source.entrySet()) { lookup.put(definingKey(entry.getKey()), entry); } } - - + + protected String definingKey(Object key) { // letters and digits are defining, everything else will be ignored return key.toString().replaceAll("[^\\p{Alnum}]", "").toLowerCase(); } - - + + @Override public boolean containsKey(Object key) { return lookup.containsKey(definingKey(key)); } - - + + @Override public Object get(Object key) { Entry entry = lookup.get(definingKey(key)); - + if (entry != null) return entry.getValue(); - + return null; } - - + + @Override public Set> entrySet() { return new AbstractSet>() { - + @Override public Iterator> iterator() { return (Iterator) lookup.values().iterator(); } - - + + @Override public int size() { return lookup.size(); @@ -114,5 +114,5 @@ public class AssociativeScriptObject extends GroovyObjectSupport implements Iter }; } } - + } diff --git a/source/net/filebot/format/Define.java b/source/net/filebot/format/Define.java index e984e5dd..50e425c1 100644 --- a/source/net/filebot/format/Define.java +++ b/source/net/filebot/format/Define.java @@ -12,8 +12,8 @@ import java.lang.annotation.Target; @Retention(RUNTIME) @Target(METHOD) public @interface Define { - + String[] value(); - + static final String undefined = ""; } diff --git a/source/net/filebot/format/ExpressionException.java b/source/net/filebot/format/ExpressionException.java index 204dc96d..cd8f7404 100644 --- a/source/net/filebot/format/ExpressionException.java +++ b/source/net/filebot/format/ExpressionException.java @@ -6,26 +6,26 @@ import javax.script.ScriptException; public class ExpressionException extends ScriptException { - + private final String message; - - + + public ExpressionException(String message, Exception cause) { super(cause); - + // can't set message via super constructor this.message = message; } - + public ExpressionException(Exception e) { this(e.getMessage(), e); } - + @Override public String getMessage() { return message; } - + } diff --git a/source/net/filebot/format/ExpressionFormatMethods.java b/source/net/filebot/format/ExpressionFormatMethods.java index ac7442ae..bedef1aa 100644 --- a/source/net/filebot/format/ExpressionFormatMethods.java +++ b/source/net/filebot/format/ExpressionFormatMethods.java @@ -32,7 +32,7 @@ public class ExpressionFormatMethods { /** * Pad strings or numbers with given characters ('0' by default). - * + * * e.g. "1" -> "01" */ public static String pad(String self, int length, String padding) { @@ -97,7 +97,7 @@ public class ExpressionFormatMethods { /** * Replace space characters with a given characters. - * + * * e.g. "Doctor Who" -> "Doctor_Who" */ public static String space(String self, String replacement) { @@ -106,7 +106,7 @@ public class ExpressionFormatMethods { /** * Upper-case all initials. - * + * * e.g. "The Day a new Demon was born" -> "The Day A New Demon Was Born" */ public static String upperInitial(String self) { @@ -131,7 +131,7 @@ public class ExpressionFormatMethods { /** * Get acronym, i.e. first letter of each word. - * + * * e.g. "Deep Space 9" -> "DS9" */ public static String acronym(String self) { @@ -148,7 +148,7 @@ public class ExpressionFormatMethods { /** * Lower-case all letters that are not initials. - * + * * e.g. "Gundam SEED" -> "Gundam Seed" */ public static String lowerTrail(String self) { @@ -220,7 +220,7 @@ public class ExpressionFormatMethods { /** * Replace trailing parenthesis including any leading whitespace. - * + * * e.g. "The IT Crowd (UK)" -> "The IT Crowd" */ public static String replaceTrailingBrackets(String self) { @@ -233,7 +233,7 @@ public class ExpressionFormatMethods { /** * Replace 'part identifier'. - * + * * e.g. "Today Is the Day: Part 1" -> "Today Is the Day, Part 1" or "Today Is the Day (1)" -> "Today Is the Day, Part 1" */ public static String replacePart(String self) { @@ -257,7 +257,7 @@ public class ExpressionFormatMethods { /** * Apply ICU transliteration - * + * * @see http://userguide.icu-project.org/transforms/general */ public static String transliterate(String self, String transformIdentifier) { @@ -266,7 +266,7 @@ public class ExpressionFormatMethods { /** * Convert Unicode to ASCII as best as possible. Works with most alphabets/scripts used in the world. - * + * * e.g. "Österreich" -> "Osterreich" "カタカナ" -> "katakana" */ public static String ascii(String self) { @@ -283,7 +283,7 @@ public class ExpressionFormatMethods { /** * Replace multiple replacement pairs - * + * * e.g. replace('ä', 'ae', 'ö', 'oe', 'ü', 'ue') */ public static String replace(String self, String tr0, String tr1, String... tr) { diff --git a/source/net/filebot/format/MediaBindingBean.java b/source/net/filebot/format/MediaBindingBean.java index c8fd5dc5..c6ff080e 100644 --- a/source/net/filebot/format/MediaBindingBean.java +++ b/source/net/filebot/format/MediaBindingBean.java @@ -91,10 +91,10 @@ public class MediaBindingBean { return getMovie().getName(); if (infoObject instanceof AudioTrack) return getAlbumArtist() != null ? getAlbumArtist() : getArtist(); - if (infoObject instanceof File) - return FileUtilities.getName((File) infoObject); + if (infoObject instanceof File) + return FileUtilities.getName((File) infoObject); - return null; + return null; } @Define("y") @@ -909,6 +909,7 @@ public class MediaBindingBean { private AssociativeScriptObject createBindingObject(File file, Object info, Map context) { MediaBindingBean mediaBindingBean = new MediaBindingBean(info, file, context) { + @Override @Define(undefined) public T undefined(String name) { return null; // never throw exceptions for empty or null values diff --git a/source/net/filebot/format/PrivilegedInvocation.java b/source/net/filebot/format/PrivilegedInvocation.java index a98140cd..e92f4987 100644 --- a/source/net/filebot/format/PrivilegedInvocation.java +++ b/source/net/filebot/format/PrivilegedInvocation.java @@ -13,22 +13,22 @@ import java.security.PrivilegedExceptionAction; public final class PrivilegedInvocation implements InvocationHandler { - + private final Object object; private final AccessControlContext context; - + private PrivilegedInvocation(Object object, AccessControlContext context) { this.object = object; this.context = context; } - + @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { - + @Override public Object run() throws Exception { return method.invoke(object, args); @@ -36,23 +36,23 @@ public final class PrivilegedInvocation implements InvocationHandler { }, context); } catch (PrivilegedActionException e) { Throwable cause = e.getException(); - + // the underlying method may have throw an exception if (cause instanceof InvocationTargetException) { // get actual cause cause = cause.getCause(); } - + // forward cause throw cause; } } - + public static I newProxy(Class interfaceClass, I object, AccessControlContext context) { InvocationHandler invocationHandler = new PrivilegedInvocation(object, context); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - + // create dynamic invocation proxy return interfaceClass.cast(Proxy.newProxyInstance(classLoader, new Class[] { interfaceClass }, invocationHandler)); } diff --git a/source/net/filebot/format/PropertyBindings.java b/source/net/filebot/format/PropertyBindings.java index 81c8d849..3ab9cf5e 100644 --- a/source/net/filebot/format/PropertyBindings.java +++ b/source/net/filebot/format/PropertyBindings.java @@ -14,17 +14,17 @@ import java.util.TreeMap; * Used to create a map view of the properties of an Object */ public class PropertyBindings extends AbstractMap { - + private final Object object; private final Map properties = new TreeMap(String.CASE_INSENSITIVE_ORDER); - + private final Object defaultValue; - - + + public PropertyBindings(Object object, Object defaultValue) { this.object = object; this.defaultValue = defaultValue; - + // get method bindings for (Method method : object.getClass().getMethods()) { if (method.getReturnType() != void.class && method.getParameterTypes().length == 0 && !method.getDeclaringClass().getName().startsWith("java")) { @@ -32,7 +32,7 @@ public class PropertyBindings extends AbstractMap { if (method.getName().length() > 3 && method.getName().substring(0, 3).equalsIgnoreCase("get")) { properties.put(method.getName().substring(3), method); } - + // boolean properties if (method.getName().length() > 2 && method.getName().substring(0, 3).equalsIgnoreCase("is")) { properties.put(method.getName().substring(2), method); @@ -40,17 +40,17 @@ public class PropertyBindings extends AbstractMap { } } } - - + + @Override public Object get(Object key) { Object value = properties.get(key); - + // evaluate method if (value instanceof Method) { try { value = ((Method) value).invoke(object); - + if (value == null) { value = defaultValue; } @@ -58,74 +58,74 @@ public class PropertyBindings extends AbstractMap { throw new RuntimeException(e); } } - + return value; } - - + + @Override public Object put(String key, Object value) { return properties.put(key, value); } - - + + @Override public Object remove(Object key) { return properties.remove(key); } - - + + @Override public boolean containsKey(Object key) { return properties.containsKey(key); } - - + + @Override public Set keySet() { return properties.keySet(); } - - + + @Override public boolean isEmpty() { return properties.isEmpty(); } - - + + @Override public String toString() { return properties.toString(); } - - + + @Override public Set> entrySet() { Set> entrySet = new HashSet>(); - + for (final String key : keySet()) { entrySet.add(new Entry() { - + @Override public String getKey() { return key; } - - + + @Override public Object getValue() { return get(key); } - - + + @Override public Object setValue(Object value) { return put(key, value); } }); } - + return entrySet; } - + } diff --git a/source/net/filebot/gio/GIOLibrary.java b/source/net/filebot/gio/GIOLibrary.java index bb7b20e5..c479ce14 100644 --- a/source/net/filebot/gio/GIOLibrary.java +++ b/source/net/filebot/gio/GIOLibrary.java @@ -7,22 +7,22 @@ import com.sun.jna.Pointer; interface GIOLibrary extends Library { - + void g_type_init(); - - + + Pointer g_vfs_get_default(); - - + + Pointer g_vfs_get_file_for_uri(Pointer gvfs, String uri); - - + + Pointer g_file_get_path(Pointer gfile); - - + + void g_free(Pointer gpointer); - - + + void g_object_unref(Pointer gobject); - + } diff --git a/source/net/filebot/gio/GVFS.java b/source/net/filebot/gio/GVFS.java index 8c623311..ce888cb1 100644 --- a/source/net/filebot/gio/GVFS.java +++ b/source/net/filebot/gio/GVFS.java @@ -10,31 +10,31 @@ import com.sun.jna.Pointer; public class GVFS { - + private static GIOLibrary lib; private static Pointer gvfs; - - + + private synchronized static GIOLibrary getLibrary() { if (lib == null) { lib = (GIOLibrary) Native.loadLibrary("gio-2.0", GIOLibrary.class); } return lib; } - - + + public synchronized static Pointer getDefaultVFS() { if (gvfs == null) { gvfs = getLibrary().g_vfs_get_default(); } return gvfs; } - - + + public static File getPathForURI(URI uri) { Pointer gfile = getLibrary().g_vfs_get_file_for_uri(getDefaultVFS(), uri.toString()); Pointer chars = getLibrary().g_file_get_path(gfile); - + try { if (chars != null) return new File(chars.getString(0)); @@ -45,5 +45,5 @@ public class GVFS { getLibrary().g_free(chars); } } - + } diff --git a/source/net/filebot/hash/ChecksumHash.java b/source/net/filebot/hash/ChecksumHash.java index 33fbf12d..253d79d9 100644 --- a/source/net/filebot/hash/ChecksumHash.java +++ b/source/net/filebot/hash/ChecksumHash.java @@ -6,24 +6,24 @@ import java.util.zip.Checksum; public class ChecksumHash implements Hash { - + private final Checksum checksum; - - + + public ChecksumHash(Checksum checksum) { this.checksum = checksum; } - + @Override public void update(byte[] bytes, int off, int len) { checksum.update(bytes, off, len); } - + @Override public String digest() { return String.format("%08X", checksum.getValue()); } - + } diff --git a/source/net/filebot/hash/Ed2kHash.java b/source/net/filebot/hash/Ed2kHash.java index 01502b17..e0a24a63 100644 --- a/source/net/filebot/hash/Ed2kHash.java +++ b/source/net/filebot/hash/Ed2kHash.java @@ -9,10 +9,10 @@ import jonelo.jacksum.algorithm.Edonkey; public class Ed2kHash implements Hash { - + private final Edonkey ed2k; - - + + public Ed2kHash() { try { this.ed2k = new Edonkey(); @@ -20,17 +20,17 @@ public class Ed2kHash implements Hash { throw new RuntimeException(e); } } - - + + @Override public void update(byte[] bytes, int off, int len) { ed2k.update(bytes, off, len); } - - + + @Override public String digest() { return String.format("%0" + (ed2k.getByteArray().length * 2) + "x", new BigInteger(1, ed2k.getByteArray())); } - + } diff --git a/source/net/filebot/hash/Hash.java b/source/net/filebot/hash/Hash.java index 5014aae6..8990965c 100644 --- a/source/net/filebot/hash/Hash.java +++ b/source/net/filebot/hash/Hash.java @@ -3,10 +3,10 @@ package net.filebot.hash; public interface Hash { - + public void update(byte[] bytes, int off, int len); - + public String digest(); - + } diff --git a/source/net/filebot/hash/MessageDigestHash.java b/source/net/filebot/hash/MessageDigestHash.java index 972f85a3..8459ad00 100644 --- a/source/net/filebot/hash/MessageDigestHash.java +++ b/source/net/filebot/hash/MessageDigestHash.java @@ -8,10 +8,10 @@ import java.security.NoSuchAlgorithmException; public class MessageDigestHash implements Hash { - + private final MessageDigest md; - - + + public MessageDigestHash(String algorithm) { try { this.md = MessageDigest.getInstance(algorithm); @@ -19,23 +19,23 @@ public class MessageDigestHash implements Hash { throw new IllegalArgumentException(e); } } - + public MessageDigestHash(MessageDigest md) { this.md = md; } - + @Override public void update(byte[] bytes, int off, int len) { md.update(bytes, off, len); } - + @Override public String digest() { // e.g. %032x (format for MD-5) return String.format("%0" + (md.getDigestLength() * 2) + "x", new BigInteger(1, md.digest())); } - + } diff --git a/source/net/filebot/hash/SfvFormat.java b/source/net/filebot/hash/SfvFormat.java index ea0b811e..61dd0018 100644 --- a/source/net/filebot/hash/SfvFormat.java +++ b/source/net/filebot/hash/SfvFormat.java @@ -10,17 +10,17 @@ import java.util.regex.Pattern; public class SfvFormat extends VerificationFormat { - + @Override public String format(String path, String hash) { // e.g folder/file.txt 970E4EF1 return String.format("%s %s", path, hash); } - + /** * Pattern used to parse the lines of a sfv file. - * + * *
     	 * Sample:
     	 * folder/file.txt 970E4EF1
    @@ -28,17 +28,17 @@ public class SfvFormat extends VerificationFormat {
     	 * 
    */ private final Pattern pattern = Pattern.compile("^(.+)\\s+(\\p{XDigit}{8})$"); - + @Override public Entry parseObject(String line) throws ParseException { Matcher matcher = pattern.matcher(line); - + if (!matcher.matches()) { throw new ParseException("Illegal input pattern", 0); } - + return entry(matcher.group(1), matcher.group(2)); } - + } diff --git a/source/net/filebot/hash/VerificationFileReader.java b/source/net/filebot/hash/VerificationFileReader.java index 1ae4f611..614bd60c 100644 --- a/source/net/filebot/hash/VerificationFileReader.java +++ b/source/net/filebot/hash/VerificationFileReader.java @@ -15,21 +15,21 @@ import java.util.logging.Logger; public class VerificationFileReader implements Iterator>, Closeable { - + private final Scanner scanner; - + private final VerificationFormat format; - + private Entry buffer; - + private int lineNumber = 0; - + public VerificationFileReader(Readable source, VerificationFormat format) { this.scanner = new Scanner(source); this.format = format; } - + @Override public boolean hasNext() { @@ -37,10 +37,10 @@ public class VerificationFileReader implements Iterator>, Cl // cache next entry buffer = nextEntry(); } - + return buffer != null; } - + @Override public Entry next() { @@ -48,7 +48,7 @@ public class VerificationFileReader implements Iterator>, Cl if (!hasNext()) { throw new NoSuchElementException(); } - + try { return buffer; } finally { @@ -56,15 +56,15 @@ public class VerificationFileReader implements Iterator>, Cl buffer = null; } } - + protected Entry nextEntry() { Entry entry = null; - + // get next valid entry while (entry == null && scanner.hasNextLine()) { String line = scanner.nextLine().trim(); - + // ignore comments if (!isComment(line)) { try { @@ -74,33 +74,33 @@ public class VerificationFileReader implements Iterator>, Cl Logger.getLogger(getClass().getName()).log(Level.WARNING, String.format("Illegal format on line %d: %s", lineNumber, line)); } } - + lineNumber++; } - + return entry; } - + public int getLineNumber() { return lineNumber; } - + protected boolean isComment(String line) { return line.isEmpty() || line.startsWith(";"); } - + @Override public void close() throws IOException { scanner.close(); } - + @Override public void remove() { throw new UnsupportedOperationException(); } - + } diff --git a/source/net/filebot/hash/VerificationFileWriter.java b/source/net/filebot/hash/VerificationFileWriter.java index d39e20f4..e4bca6e4 100644 --- a/source/net/filebot/hash/VerificationFileWriter.java +++ b/source/net/filebot/hash/VerificationFileWriter.java @@ -12,40 +12,40 @@ import net.filebot.Settings; public class VerificationFileWriter implements Closeable { - + protected PrintWriter out; protected VerificationFormat format; - + public VerificationFileWriter(File file, VerificationFormat format, String charset) throws IOException { this(new PrintWriter(file, charset), format, charset); } - + public VerificationFileWriter(PrintWriter out, VerificationFormat format, String charset) { this.out = out; this.format = format; - + // start by printing the file header writeHeader(charset); } - + protected void writeHeader(String charset) { out.format("; Generated by %s %s on %tF at % entry = (Entry) obj; - + String path = entry.getKey().getPath(); String hash = entry.getValue(); - + return sb.append(format(path, hash)); } - + public String format(String path, String hash) { // e.g. 1a02a7c1e9ac91346d08829d5037b240f42ded07 ?SHA1*folder/file.txt return String.format("%s %s*%s", hash, hashTypeHint, path); } - + /** * Pattern used to parse the lines of a md5 or sha1 file. - * + * *
     	 * Sample MD5:
     	 * 50e85fe18e17e3616774637a82968f4c *folder/file.txt
     	 * |           Group 1               |   Group 2   |
    -	 * 
    +	 *
     	 * Sample SHA-1:
     	 * 1a02a7c1e9ac91346d08829d5037b240f42ded07 ?SHA1*folder/file.txt
     	 * |               Group 1                |       |   Group 2   |
     	 * 
    */ private final Pattern pattern = Pattern.compile("^(\\p{XDigit}+)\\s+(?:\\?\\w+)?\\*?(.+)$"); - + @Override public Entry parseObject(String line) throws ParseException { Matcher matcher = pattern.matcher(line); - + if (!matcher.find()) { throw new ParseException("Illegal input pattern", 0); } - + return entry(matcher.group(2), matcher.group(1)); } - + @Override public Entry parseObject(String line, ParsePosition pos) { throw new UnsupportedOperationException(); } - + protected Entry entry(String path, String hash) { return new SimpleImmutableEntry(new File(path), hash); } - + } diff --git a/source/net/filebot/mac/DropToUnlock.java b/source/net/filebot/mac/DropToUnlock.java index cfddbb0e..ee36ecc5 100644 --- a/source/net/filebot/mac/DropToUnlock.java +++ b/source/net/filebot/mac/DropToUnlock.java @@ -284,6 +284,7 @@ public class DropToUnlock extends JList { return true; } + @Override public void handleTransferable(Transferable tr, TransferAction action) throws Exception { List files = FileTransferable.getFilesFromTransferable(tr); if (files != null) { @@ -318,6 +319,7 @@ public class DropToUnlock extends JList { protected static class FileChooserAction extends MouseAdapter { + @Override public void mouseClicked(MouseEvent evt) { DropToUnlock list = (DropToUnlock) evt.getSource(); if (evt.getClickCount() > 0) { diff --git a/source/net/filebot/mac/xattr/XAttr.java b/source/net/filebot/mac/xattr/XAttr.java index 73dead39..a685a37e 100644 --- a/source/net/filebot/mac/xattr/XAttr.java +++ b/source/net/filebot/mac/xattr/XAttr.java @@ -1,10 +1,10 @@ /* Copyright (c) 2014 Reinhard Pointner, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU @@ -18,7 +18,7 @@ import com.sun.jna.Pointer; /** * JNA wrapper for - * + * */ interface XAttr extends Library { diff --git a/source/net/filebot/media/SmartSeasonEpisodeMatcher.java b/source/net/filebot/media/SmartSeasonEpisodeMatcher.java index b42e8526..c2beea4b 100644 --- a/source/net/filebot/media/SmartSeasonEpisodeMatcher.java +++ b/source/net/filebot/media/SmartSeasonEpisodeMatcher.java @@ -33,6 +33,7 @@ public class SmartSeasonEpisodeMatcher extends SeasonEpisodeMatcher { return super.match(new File(clean(file.getPath()))); } + @Override public String head(String name) { return super.head(clean(name)); } diff --git a/source/net/filebot/mediainfo/MediaInfoLibrary.java b/source/net/filebot/mediainfo/MediaInfoLibrary.java index 0fed1061..a33accbd 100644 --- a/source/net/filebot/mediainfo/MediaInfoLibrary.java +++ b/source/net/filebot/mediainfo/MediaInfoLibrary.java @@ -24,14 +24,14 @@ interface MediaInfoLibrary extends Library { /** * Create a new handle. - * + * * @return handle */ Pointer New(); /** * Open a file and collect information about it (technical information and tags). - * + * * @param handle * @param file * full name of the file to open @@ -41,7 +41,7 @@ interface MediaInfoLibrary extends Library { /** * Configure or get information about MediaInfo. - * + * * @param handle * @param option * The name of option @@ -53,7 +53,7 @@ interface MediaInfoLibrary extends Library { /** * Get all details about a file. - * + * * @param handle * @return All details about a file in one string */ @@ -61,7 +61,7 @@ interface MediaInfoLibrary extends Library { /** * Get a piece of information about a file (parameter is a string). - * + * * @param handle * @param streamKind * Kind of stream (general, video, audio...) @@ -79,7 +79,7 @@ interface MediaInfoLibrary extends Library { /** * Get a piece of information about a file (parameter is an integer). - * + * * @param handle * @param streamKind * Kind of stream (general, video, audio...) @@ -95,7 +95,7 @@ interface MediaInfoLibrary extends Library { /** * Count of streams of a stream kind (StreamNumber not filled), or count of piece of information in this stream. - * + * * @param handle * @param streamKind * Kind of stream (general, video, audio...) @@ -107,14 +107,14 @@ interface MediaInfoLibrary extends Library { /** * Close a file opened before with Open(). - * + * * @param handle */ void Close(Pointer handle); /** * Dispose of a handle created with New(). - * + * * @param handle */ void Delete(Pointer handle); diff --git a/source/net/filebot/similarity/CrossPropertyMetric.java b/source/net/filebot/similarity/CrossPropertyMetric.java index 7ce91631..1a159c1a 100644 --- a/source/net/filebot/similarity/CrossPropertyMetric.java +++ b/source/net/filebot/similarity/CrossPropertyMetric.java @@ -10,37 +10,37 @@ import net.filebot.format.PropertyBindings; public class CrossPropertyMetric implements SimilarityMetric { - + private SimilarityMetric metric; - - + + public CrossPropertyMetric(SimilarityMetric metric) { this.metric = metric; } - - + + public CrossPropertyMetric() { this.metric = new StringEqualsMetric(); } - - + + @Override public float getSimilarity(Object o1, Object o2) { Map m1 = getProperties(o1); if (m1.isEmpty()) return 0; - + Map m2 = getProperties(o2); if (m2.isEmpty()) return 0; - + // works with commons keys Set keys = new TreeSet(String.CASE_INSENSITIVE_ORDER); keys.addAll(m1.keySet()); keys.retainAll(m2.keySet()); if (keys.isEmpty()) return 0; - + float feedback = 0; for (String k : keys) { try { @@ -49,13 +49,13 @@ public class CrossPropertyMetric implements SimilarityMetric { // ignore } } - + return feedback / keys.size(); } - - + + protected Map getProperties(Object object) { return new PropertyBindings(object, null); } - + } diff --git a/source/net/filebot/similarity/FileNameMetric.java b/source/net/filebot/similarity/FileNameMetric.java index fe3ec18a..cad64f92 100644 --- a/source/net/filebot/similarity/FileNameMetric.java +++ b/source/net/filebot/similarity/FileNameMetric.java @@ -8,28 +8,28 @@ import java.io.File; public class FileNameMetric implements SimilarityMetric { - + @Override public float getSimilarity(Object o1, Object o2) { String s1 = getFileName(o1); if (s1 == null || s1.isEmpty()) return 0; - + String s2 = getFileName(o2); if (s2 == null || s2.isEmpty()) return 0; - + return s1.startsWith(s2) || s2.startsWith(s1) ? 1 : 0; } - + protected String getFileName(Object object) { if (object instanceof File) { // name without extension normalized to lower-case return getName((File) object).trim().toLowerCase(); } - + return null; } - + } diff --git a/source/net/filebot/similarity/FileSizeMetric.java b/source/net/filebot/similarity/FileSizeMetric.java index d0ed9c66..9a0f8ff4 100644 --- a/source/net/filebot/similarity/FileSizeMetric.java +++ b/source/net/filebot/similarity/FileSizeMetric.java @@ -6,28 +6,28 @@ import java.io.File; public class FileSizeMetric implements SimilarityMetric { - + @Override public float getSimilarity(Object o1, Object o2) { long l1 = getLength(o1); if (l1 < 0) return 0; - + long l2 = getLength(o2); if (l2 < 0) return 0; - + // objects have the same non-negative length return l1 == l2 ? 1 : -1; } - + protected long getLength(Object object) { if (object instanceof File) { return ((File) object).length(); } - + return -1; } - + } diff --git a/source/net/filebot/similarity/Match.java b/source/net/filebot/similarity/Match.java index 83ee9c61..2e8dcdf5 100644 --- a/source/net/filebot/similarity/Match.java +++ b/source/net/filebot/similarity/Match.java @@ -6,26 +6,26 @@ import java.util.Arrays; public class Match { - + private final Value value; private final Candidate candidate; - + public Match(Value value, Candidate candidate) { this.value = value; this.candidate = candidate; } - + public Value getValue() { return value; } - + public Candidate getCandidate() { return candidate; } - + @Override public boolean equals(Object obj) { @@ -33,20 +33,20 @@ public class Match { Match other = (Match) obj; return value == other.value && candidate == other.candidate; } - + return false; } - + @Override public int hashCode() { return Arrays.hashCode(new Object[] { value, candidate }); } - + @Override public String toString() { return String.format("[%s, %s]", value, candidate); } - + } diff --git a/source/net/filebot/similarity/MetricMin.java b/source/net/filebot/similarity/MetricMin.java index 8b438684..8b213d55 100644 --- a/source/net/filebot/similarity/MetricMin.java +++ b/source/net/filebot/similarity/MetricMin.java @@ -3,20 +3,20 @@ package net.filebot.similarity; public class MetricMin implements SimilarityMetric { - + private final SimilarityMetric metric; private final float minValue; - + public MetricMin(SimilarityMetric metric, float minValue) { this.metric = metric; this.minValue = minValue; } - + @Override public float getSimilarity(Object o1, Object o2) { return Math.max(metric.getSimilarity(o1, o2), minValue); } - + } diff --git a/source/net/filebot/similarity/NameSimilarityMetric.java b/source/net/filebot/similarity/NameSimilarityMetric.java index b0b59c0b..7ae73ef1 100644 --- a/source/net/filebot/similarity/NameSimilarityMetric.java +++ b/source/net/filebot/similarity/NameSimilarityMetric.java @@ -11,43 +11,43 @@ import com.ibm.icu.text.Transliterator; public class NameSimilarityMetric implements SimilarityMetric { - + private final AbstractStringMetric metric; private final Transliterator transliterator; - - + + public NameSimilarityMetric() { // QGramsDistance with a QGram tokenizer seems to work best for similarity of names this(new QGramsDistance(new TokeniserQGram3()), Transliterator.getInstance("Any-Latin;Latin-ASCII;[:Diacritic:]remove")); } - - + + public NameSimilarityMetric(AbstractStringMetric metric, Transliterator transliterator) { this.metric = metric; this.transliterator = transliterator; } - - + + @Override public float getSimilarity(Object o1, Object o2) { return metric.getSimilarity(normalize(o1), normalize(o2)); } - - + + protected String normalize(Object object) { // use string representation String name = object.toString(); - + // apply transliterator if (transliterator != null) { name = transliterator.transform(name); } - + // normalize separators name = normalizePunctuation(name); - + // normalize case and trim return name.toLowerCase(); } - + } diff --git a/source/net/filebot/similarity/NumericSimilarityMetric.java b/source/net/filebot/similarity/NumericSimilarityMetric.java index 846840a9..dae807af 100644 --- a/source/net/filebot/similarity/NumericSimilarityMetric.java +++ b/source/net/filebot/similarity/NumericSimilarityMetric.java @@ -15,81 +15,81 @@ import uk.ac.shef.wit.simmetrics.wordhandlers.InterfaceTermHandler; public class NumericSimilarityMetric implements SimilarityMetric { - + private final AbstractStringMetric metric; - - + + public NumericSimilarityMetric() { - // I don't exactly know why, but I get a good matching behavior + // I don't exactly know why, but I get a good matching behavior // when using QGramsDistance or BlockDistance metric = new QGramsDistance(new NumberTokeniser()); } - - + + @Override public float getSimilarity(Object o1, Object o2) { return metric.getSimilarity(normalize(o1), normalize(o2)); } - - + + protected String normalize(Object object) { // no need to do anything special here, because we don't care about anything but number patterns anyway return object.toString(); } - - + + private static class NumberTokeniser implements InterfaceTokeniser { - + private final String delimiter = "\\D+"; - - + + @Override public ArrayList tokenizeToArrayList(String input) { ArrayList tokens = new ArrayList(); - + // scan for number patterns, use non-number pattern as delimiter Scanner scanner = new Scanner(input).useDelimiter(delimiter); - + while (scanner.hasNextInt()) { // remove leading zeros from number tokens by scanning for Integers tokens.add(String.valueOf(scanner.nextInt())); } - + return tokens; } - - + + @Override public Set tokenizeToSet(String input) { return new LinkedHashSet(tokenizeToArrayList(input)); } - - + + @Override public String getShortDescriptionString() { return getClass().getSimpleName(); } - - + + @Override public String getDelimiters() { return delimiter; } - + private InterfaceTermHandler stopWordHandler = new DummyStopTermHandler(); - - + + @Override public InterfaceTermHandler getStopWordHandler() { return stopWordHandler; } - - + + @Override public void setStopWordHandler(InterfaceTermHandler stopWordHandler) { this.stopWordHandler = stopWordHandler; } - + } - + } diff --git a/source/net/filebot/similarity/SeasonEpisodeMatcher.java b/source/net/filebot/similarity/SeasonEpisodeMatcher.java index c8ccca97..529e05df 100644 --- a/source/net/filebot/similarity/SeasonEpisodeMatcher.java +++ b/source/net/filebot/similarity/SeasonEpisodeMatcher.java @@ -154,7 +154,7 @@ public class SeasonEpisodeMatcher { /** * Try to get season and episode numbers for the given string. - * + * * @param name * match this string against the a set of know patterns * @return the matches returned by the first pattern that returns any matches for this string, or null if no pattern returned any matches diff --git a/source/net/filebot/similarity/SeriesNameMatcher.java b/source/net/filebot/similarity/SeriesNameMatcher.java index 2db34ce0..338be979 100644 --- a/source/net/filebot/similarity/SeriesNameMatcher.java +++ b/source/net/filebot/similarity/SeriesNameMatcher.java @@ -110,7 +110,7 @@ public class SeriesNameMatcher { /** * Try to match and verify all series names using known season episode patterns. - * + * * @param names * episode names * @return series names that have been matched one or multiple times depending on the threshold @@ -154,7 +154,7 @@ public class SeriesNameMatcher { /** * Try to match all common word sequences in the given list. - * + * * @param names * list of episode names * @return all common word sequences that have been found @@ -184,7 +184,7 @@ public class SeriesNameMatcher { /** * Try to match a series name from the given episode name using known season episode patterns. - * + * * @param name * episode name * @return a substring of the given name that ends before the first occurrence of a season episode pattern, or null if there is no such pattern @@ -218,7 +218,7 @@ public class SeriesNameMatcher { /** * Try to match a series name from the first common word sequence. - * + * * @param names * various episode names (at least two) * @return a word sequence all episode names have in common, or null diff --git a/source/net/filebot/similarity/SimilarityComparator.java b/source/net/filebot/similarity/SimilarityComparator.java index 978ce2cd..98486575 100644 --- a/source/net/filebot/similarity/SimilarityComparator.java +++ b/source/net/filebot/similarity/SimilarityComparator.java @@ -6,34 +6,34 @@ import java.util.Comparator; public class SimilarityComparator implements Comparator { - + protected SimilarityMetric metric; protected Object[] paragon; - - + + public SimilarityComparator(SimilarityMetric metric, Object[] paragon) { this.metric = metric; this.paragon = paragon; } - - + + public SimilarityComparator(Object... paragon) { this(new NameSimilarityMetric(), paragon); } - - + + @Override public int compare(Object o1, Object o2) { float f1 = getMaxSimilarity(o1); float f2 = getMaxSimilarity(o2); - + if (f1 == f2) return 0; - + return f1 > f2 ? -1 : 1; } - - + + public float getMaxSimilarity(Object obj) { float m = 0; for (Object it : paragon) { diff --git a/source/net/filebot/similarity/SimilarityMetric.java b/source/net/filebot/similarity/SimilarityMetric.java index 1f0f4058..0abf17d6 100644 --- a/source/net/filebot/similarity/SimilarityMetric.java +++ b/source/net/filebot/similarity/SimilarityMetric.java @@ -3,7 +3,7 @@ package net.filebot.similarity; public interface SimilarityMetric { - + public float getSimilarity(Object o1, Object o2); - + } diff --git a/source/net/filebot/similarity/TimeStampMetric.java b/source/net/filebot/similarity/TimeStampMetric.java index 8485c1ae..2b4473b9 100644 --- a/source/net/filebot/similarity/TimeStampMetric.java +++ b/source/net/filebot/similarity/TimeStampMetric.java @@ -10,22 +10,22 @@ import java.nio.file.attribute.BasicFileAttributes; public class TimeStampMetric implements SimilarityMetric { - + @Override public float getSimilarity(Object o1, Object o2) { long t1 = getTimeStamp(o1); long t2 = getTimeStamp(o2); - + if (t1 <= 0 || t2 <= 0) return -1; - + float min = min(t1, t2); float max = max(t1, t2); - + return min / max; } - - + + public long getTimeStamp(Object obj) { if (obj instanceof File) { try { @@ -43,7 +43,7 @@ public class TimeStampMetric implements SimilarityMetric { } else if (obj instanceof Number) { return ((Number) obj).longValue(); } - + return -1; } } diff --git a/source/net/filebot/subtitle/MicroDVDReader.java b/source/net/filebot/subtitle/MicroDVDReader.java index 6bfa0803..a8848852 100644 --- a/source/net/filebot/subtitle/MicroDVDReader.java +++ b/source/net/filebot/subtitle/MicroDVDReader.java @@ -9,61 +9,61 @@ import java.util.List; public class MicroDVDReader extends SubtitleReader { - + private double fps = 23.976; - + public MicroDVDReader(Readable source) { super(source); } - + @Override public SubtitleElement readNext() throws Exception { String line = scanner.nextLine(); - + List properties = new ArrayList(2); int from = 0; - + while (from < line.length() && line.charAt(from) == '{') { int to = line.indexOf('}', from + 1); - + // no more properties if (to < from) break; - + // extract property properties.add(line.substring(from + 1, to)); - + // skip property from = to + 1; } - + if (properties.size() < 2) { // ignore illegal lines return null; } - + int startFrame = Integer.parseInt(properties.get(0)); int endFrame = Integer.parseInt(properties.get(1)); String text = line.substring(from).trim(); - + // cancel format markers text = text.replaceAll("\\{[^\\}]*\\}", ""); - + if (startFrame == 1 && endFrame == 1) { // override fps fps = Double.parseDouble(text); - + // ignore line return null; } - + // translate '|' to new lines String[] lines = text.split("[|]"); - - // convert frame interval to time interval + + // convert frame interval to time interval return new SubtitleElement(Math.round(startFrame * fps), Math.round(endFrame * fps), join(lines, "\n")); } - + } diff --git a/source/net/filebot/subtitle/SubRipWriter.java b/source/net/filebot/subtitle/SubRipWriter.java index 2672c380..41179872 100644 --- a/source/net/filebot/subtitle/SubRipWriter.java +++ b/source/net/filebot/subtitle/SubRipWriter.java @@ -12,21 +12,21 @@ import java.util.TimeZone; public class SubRipWriter implements Closeable { - + private final DateFormat timeFormat; private final Formatter out; - + private int lineNumber = 0; - + public SubRipWriter(Appendable out) { this.out = new Formatter(out, Locale.ROOT); - + // format used to create time stamps (e.g. 00:02:26,407 --> 00:02:31,356) timeFormat = new SimpleDateFormat("HH:mm:ss,SSS", Locale.ROOT); timeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } - + public void write(SubtitleElement element) { // write a single subtitle in SubRip format, e.g. @@ -37,11 +37,11 @@ public class SubRipWriter implements Closeable { out.format("%s --> %s%n", timeFormat.format(element.getStart()), timeFormat.format(element.getEnd())); out.format("%s%n%n", element.getText()); } - + @Override public void close() throws IOException { out.close(); } - + } diff --git a/source/net/filebot/subtitle/SubStationAlphaReader.java b/source/net/filebot/subtitle/SubStationAlphaReader.java index 3ac68020..df8c3190 100644 --- a/source/net/filebot/subtitle/SubStationAlphaReader.java +++ b/source/net/filebot/subtitle/SubStationAlphaReader.java @@ -10,87 +10,87 @@ import java.util.regex.Pattern; public class SubStationAlphaReader extends SubtitleReader { - + private final DateFormat timeFormat = new SubtitleTimeFormat(); private final Pattern newline = Pattern.compile(Pattern.quote("\\n"), Pattern.CASE_INSENSITIVE); private final Pattern tag = Pattern.compile("[{]\\\\[^}]+[}]"); - + private String[] format; private int formatIndexStart; private int formatIndexEnd; private int formatIndexText; - + public SubStationAlphaReader(Readable source) { super(source); } - + private void readFormat() throws Exception { // read format line (e.g. Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text) String[] event = scanner.nextLine().split(":", 2); - + // sanity check if (!event[0].equals("Format")) throw new InputMismatchException("Illegal format header: " + Arrays.toString(event)); - + // read columns format = event[1].split(","); - + // normalize column names for (int i = 0; i < format.length; i++) { format[i] = format[i].trim().toLowerCase(); } - + List lookup = Arrays.asList(format); formatIndexStart = lookup.indexOf("start"); formatIndexEnd = lookup.indexOf("end"); formatIndexText = lookup.indexOf("text"); } - + @Override public SubtitleElement readNext() throws Exception { if (format == null) { // move to [Events] sections boolean found = false; - + while (!found && scanner.hasNextLine()) { found = scanner.nextLine().equals("[Events]"); } - + if (!found) { throw new InputMismatchException("Cannot find [Events] section"); } - + // read format header readFormat(); } - + // read next dialogue line String[] event = scanner.nextLine().split(":", 2); - + // sanity check if (!event[0].equals("Dialogue")) throw new InputMismatchException("Illegal dialogue event: " + Arrays.toString(event)); - + // extract information String[] values = event[1].split(",", format.length); - + long start = timeFormat.parse(values[formatIndexStart].trim()).getTime(); long end = timeFormat.parse(values[formatIndexEnd].trim()).getTime(); String text = values[formatIndexText].trim(); - + return new SubtitleElement(start, end, resolve(text)); } - + protected String resolve(String text) { // remove tags text = tag.matcher(text).replaceAll(""); - - // resolve line breaks + + // resolve line breaks return newline.matcher(text).replaceAll("\n"); } - + } diff --git a/source/net/filebot/subtitle/SubViewerReader.java b/source/net/filebot/subtitle/SubViewerReader.java index 9a9c2b1d..bcf83065 100644 --- a/source/net/filebot/subtitle/SubViewerReader.java +++ b/source/net/filebot/subtitle/SubViewerReader.java @@ -12,33 +12,33 @@ import java.util.regex.Pattern; public class SubViewerReader extends SubtitleReader { - + private final DateFormat timeFormat = new SubtitleTimeFormat(); private final Pattern newline = compile(quote("[br]"), CASE_INSENSITIVE); - + public SubViewerReader(Readable source) { super(source); } - + @Override protected SubtitleElement readNext() throws Exception { // element starts with interval (e.g. 00:42:16.33,00:42:19.39) String[] interval = scanner.nextLine().split(",", 2); - + if (interval.length < 2 || interval[0].startsWith("[")) { // ignore property lines return null; } - + try { long t1 = timeFormat.parse(interval[0]).getTime(); long t2 = timeFormat.parse(interval[1]).getTime(); - + // translate [br] to new lines String[] lines = newline.split(scanner.nextLine()); - + return new SubtitleElement(t1, t2, join(lines, "\n")); } catch (ParseException e) { // can't parse interval, ignore line diff --git a/source/net/filebot/subtitle/SubtitleElement.java b/source/net/filebot/subtitle/SubtitleElement.java index 3a228826..21af1884 100644 --- a/source/net/filebot/subtitle/SubtitleElement.java +++ b/source/net/filebot/subtitle/SubtitleElement.java @@ -3,38 +3,38 @@ package net.filebot.subtitle; public class SubtitleElement { - + private final long start; private final long end; - + private final String text; - + public SubtitleElement(long start, long end, String text) { this.start = start; this.end = end; this.text = text; } - + public long getStart() { return start; } - + public long getEnd() { return end; } - + public String getText() { return text; } - + @Override public String toString() { return String.format("[%d, %d] %s", start, end, text); } - + } diff --git a/source/net/filebot/subtitle/SubtitleFormat.java b/source/net/filebot/subtitle/SubtitleFormat.java index 803861b1..71b83649 100644 --- a/source/net/filebot/subtitle/SubtitleFormat.java +++ b/source/net/filebot/subtitle/SubtitleFormat.java @@ -7,44 +7,44 @@ import net.filebot.util.FileUtilities.ExtensionFileFilter; public enum SubtitleFormat { - + SubRip { - + @Override public SubtitleReader newReader(Readable readable) { return new SubRipReader(readable); } }, - + MicroDVD { - + @Override public SubtitleReader newReader(Readable readable) { return new MicroDVDReader(readable); } }, - + SubViewer { - + @Override public SubtitleReader newReader(Readable readable) { return new SubViewerReader(readable); } }, - + SubStationAlpha { - + @Override public SubtitleReader newReader(Readable readable) { return new SubStationAlphaReader(readable); } }; - + public abstract SubtitleReader newReader(Readable readable); - + public ExtensionFileFilter getFilter() { return MediaTypes.getDefaultFilter("subtitle/" + this.name()); } - + } diff --git a/source/net/filebot/subtitle/SubtitleMetrics.java b/source/net/filebot/subtitle/SubtitleMetrics.java index 105808ea..d37f85b3 100644 --- a/source/net/filebot/subtitle/SubtitleMetrics.java +++ b/source/net/filebot/subtitle/SubtitleMetrics.java @@ -88,6 +88,7 @@ public enum SubtitleMetrics implements SimilarityMetric { return 0; } + @Override protected float similarity(String match, String s1, String s2) { return match.length() > 0 ? 1 : 0; } @@ -153,10 +154,12 @@ public enum SubtitleMetrics implements SimilarityMetric { private final String FPS = "FPS"; private final String SECONDS = "SECS"; + @Override public float getSimilarity(Object o1, Object o2) { return o1 instanceof SubtitleDescriptor ? super.getSimilarity(o1, o2) : super.getSimilarity(o2, o1); // make sure that SubtitleDescriptor is o1 }; + @Override protected Map getProperties(Object object) { if (object instanceof OpenSubtitlesSubtitleDescriptor) { return getSubtitleProperties((OpenSubtitlesSubtitleDescriptor) object); diff --git a/source/net/filebot/subtitle/SubtitleReader.java b/source/net/filebot/subtitle/SubtitleReader.java index 43944e34..4e57f30e 100644 --- a/source/net/filebot/subtitle/SubtitleReader.java +++ b/source/net/filebot/subtitle/SubtitleReader.java @@ -12,18 +12,18 @@ import java.util.logging.Logger; public abstract class SubtitleReader implements Iterator, Closeable { - + protected final Scanner scanner; protected SubtitleElement current; - + public SubtitleReader(Readable source) { this.scanner = new Scanner(source); } - + protected abstract SubtitleElement readNext() throws Exception; - + @Override public boolean hasNext() { @@ -36,34 +36,34 @@ public abstract class SubtitleReader implements Iterator, Close Logger.getLogger(getClass().getName()).log(Level.WARNING, "Illegal input: " + e.getMessage()); } } - + return current != null; } - + @Override public SubtitleElement next() { if (!hasNext()) { throw new NoSuchElementException(); } - + try { return current; } finally { current = null; } } - + @Override public void close() throws IOException { scanner.close(); } - + @Override public void remove() { throw new UnsupportedOperationException(); } - + } diff --git a/source/net/filebot/subtitle/SubtitleTimeFormat.java b/source/net/filebot/subtitle/SubtitleTimeFormat.java index cfc16d29..9ac4d5c1 100644 --- a/source/net/filebot/subtitle/SubtitleTimeFormat.java +++ b/source/net/filebot/subtitle/SubtitleTimeFormat.java @@ -13,45 +13,45 @@ import java.util.regex.Pattern; class SubtitleTimeFormat extends DateFormat { - + public SubtitleTimeFormat() { // calendar without any kind of special handling for time zone and daylight saving time calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT); } - + @Override public StringBuffer format(Date date, StringBuffer sb, FieldPosition pos) { // e.g. 1:42:52.42 calendar.setTime(date); - + sb.append(String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY))); sb.append(':').append(String.format("%02d", calendar.get(Calendar.MINUTE))); sb.append(':').append(String.format("%02d", calendar.get(Calendar.SECOND))); - + String millis = String.format("%03d", calendar.get(Calendar.MILLISECOND)); sb.append('.').append(millis.substring(0, 2)); - + return sb; } - + private final Pattern delimiter = Pattern.compile("[:.]"); - + @Override public Date parse(String source, ParsePosition pos) { String[] split = delimiter.split(source, 4); - + // reset state calendar.clear(); - + try { // handle hours:minutes:seconds calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(split[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(split[1])); calendar.set(Calendar.SECOND, Integer.parseInt(split[2])); - + // handle hundredth seconds calendar.set(Calendar.MILLISECOND, Integer.parseInt(split[3]) * 10); } catch (Exception e) { @@ -59,7 +59,7 @@ class SubtitleTimeFormat extends DateFormat { pos.setErrorIndex(0); return null; } - + // update position pos.setIndex(source.length()); return calendar.getTime(); diff --git a/source/net/filebot/torrent/BDecoder.java b/source/net/filebot/torrent/BDecoder.java index 00534408..f29952d0 100644 --- a/source/net/filebot/torrent/BDecoder.java +++ b/source/net/filebot/torrent/BDecoder.java @@ -1,9 +1,9 @@ /* * BeDecoder.java - * + * * Created on May 30, 2003, 2:44 PM * Copyright (C) 2003, 2004, 2005, 2006 Aelitis, All Rights Reserved. - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * + * * AELITIS, SAS au capital de 46,603.30 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. */ @@ -37,190 +37,190 @@ import java.util.Map; /** * A set of utility methods to decode a bencoded array of byte into a Map. integer are * represented as Long, String as byte[], dictionnaries as Map, and list as List. - * + * * @author TdC_VgA */ class BDecoder { - + private static final Charset BINARY_CHARSET = Charset.forName("ISO-8859-1"); - - + + public static Map decode(InputStream is) throws IOException { return (new BDecoder().decodeStream(is)); } - + public Map decodeStream(InputStream data) throws IOException { Object res = decodeInputStream(data, 0); - + if (res == null) throw (new IOException("BDecoder: zero length file")); else if (!(res instanceof Map)) throw (new IOException("BDecoder: top level isn't a Map")); - + return ((Map) res); } - + private Object decodeInputStream(InputStream bais, int nesting) throws IOException { if (!bais.markSupported()) throw new IOException("InputStream must support the mark() method"); - + // set a mark bais.mark(Integer.MAX_VALUE); - + // read a byte int tempByte = bais.read(); - + // decide what to do switch (tempByte) { - case 'd': - // create a new dictionary object - Map tempMap = new HashMap(); - - // get the key - byte[] tempByteArray = null; - - while ((tempByteArray = (byte[]) decodeInputStream(bais, nesting + 1)) != null) { - - // decode some more - - Object value = decodeInputStream(bais, nesting + 1); - - // add the value to the map - - CharBuffer cb = BINARY_CHARSET.decode(ByteBuffer.wrap(tempByteArray)); - - String key = new String(cb.array(), 0, cb.limit()); - - tempMap.put(key, value); - } - - if (bais.available() < nesting) - throw (new IOException("BDecoder: invalid input data, 'e' missing from end of dictionary")); - - // return the map - return tempMap; - - case 'l': - // create the list - List tempList = new ArrayList(); - - // create the key - Object tempElement = null; - while ((tempElement = decodeInputStream(bais, nesting + 1)) != null) - // add the element - tempList.add(tempElement); - - if (bais.available() < nesting) - throw (new IOException("BDecoder: invalid input data, 'e' missing from end of list")); - - // return the list - return tempList; - - case 'e': - case -1: - return null; - - case 'i': - return new Long(getNumberFromStream(bais, 'e')); - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - // move back one - bais.reset(); - // get the string - return getByteArrayFromStream(bais); - - default: { - - int rem_len = bais.available(); - - if (rem_len > 256) - rem_len = 256; - - byte[] rem_data = new byte[rem_len]; - - bais.read(rem_data); - - throw (new IOException("BDecoder: unknown command '" + tempByte + ", remainder = " + new String(rem_data))); + case 'd': + // create a new dictionary object + Map tempMap = new HashMap(); + + // get the key + byte[] tempByteArray = null; + + while ((tempByteArray = (byte[]) decodeInputStream(bais, nesting + 1)) != null) { + + // decode some more + + Object value = decodeInputStream(bais, nesting + 1); + + // add the value to the map + + CharBuffer cb = BINARY_CHARSET.decode(ByteBuffer.wrap(tempByteArray)); + + String key = new String(cb.array(), 0, cb.limit()); + + tempMap.put(key, value); } + + if (bais.available() < nesting) + throw (new IOException("BDecoder: invalid input data, 'e' missing from end of dictionary")); + + // return the map + return tempMap; + + case 'l': + // create the list + List tempList = new ArrayList(); + + // create the key + Object tempElement = null; + while ((tempElement = decodeInputStream(bais, nesting + 1)) != null) + // add the element + tempList.add(tempElement); + + if (bais.available() < nesting) + throw (new IOException("BDecoder: invalid input data, 'e' missing from end of list")); + + // return the list + return tempList; + + case 'e': + case -1: + return null; + + case 'i': + return new Long(getNumberFromStream(bais, 'e')); + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + // move back one + bais.reset(); + // get the string + return getByteArrayFromStream(bais); + + default: { + + int rem_len = bais.available(); + + if (rem_len > 256) + rem_len = 256; + + byte[] rem_data = new byte[rem_len]; + + bais.read(rem_data); + + throw (new IOException("BDecoder: unknown command '" + tempByte + ", remainder = " + new String(rem_data))); + } } } - + private long getNumberFromStream(InputStream bais, char parseChar) throws IOException { int length = 0; - + // place a mark bais.mark(Integer.MAX_VALUE); - + int tempByte = bais.read(); while ((tempByte != parseChar) && (tempByte >= 0)) { tempByte = bais.read(); length++; } - + // are we at the end of the stream? if (tempByte < 0) return -1; - + // reset the mark bais.reset(); - + // get the length byte[] tempArray = new byte[length]; int count = 0; int len = 0; - + // get the string while ((count != length) && ((len = bais.read(tempArray, count, length - count)) > 0)) count += len; - + // jump ahead in the stream to compensate for the : bais.skip(1); - + // return the value CharBuffer cb = BINARY_CHARSET.decode(ByteBuffer.wrap(tempArray)); - + String str_value = new String(cb.array(), 0, cb.limit()); - + return Long.parseLong(str_value); } - + private byte[] getByteArrayFromStream(InputStream bais) throws IOException { int length = (int) getNumberFromStream(bais, ':'); - + if (length < 0) return null; - + // note that torrent hashes can be big (consider a 55GB file with 2MB // pieces // this generates a pieces hash of 1/2 meg if (length > 8 * 1024 * 1024) throw (new IOException("Byte array length too large (" + length + ")")); - + byte[] tempArray = new byte[length]; int count = 0; int len = 0; - + // get the string while ((count != length) && ((len = bais.read(tempArray, count, length - count)) > 0)) count += len; - + if (count != tempArray.length) throw (new IOException("BDecoder::getByteArrayFromStream: truncated")); - + return tempArray; } - + } diff --git a/source/net/filebot/torrent/Torrent.java b/source/net/filebot/torrent/Torrent.java index 5e4209fd..9a2dae6d 100644 --- a/source/net/filebot/torrent/Torrent.java +++ b/source/net/filebot/torrent/Torrent.java @@ -16,7 +16,7 @@ import java.util.Map; public class Torrent { - + private String name; private String encoding; private String createdBy; @@ -24,188 +24,188 @@ public class Torrent { private String comment; private Long creationDate; private Long pieceLength; - + private List files; private boolean singleFileTorrent; - - + + protected Torrent() { // used by serializer } - - + + public Torrent(File torrent) throws IOException { this(decodeTorrent(torrent)); } - - + + public Torrent(Map torrentMap) { Charset charset = Charset.forName("UTF-8"); encoding = decodeString(torrentMap.get("encoding"), charset); - + try { charset = Charset.forName(encoding); } catch (IllegalArgumentException e) { // invalid encoding, just keep using UTF-8 } - + createdBy = decodeString(torrentMap.get("created by"), charset); announce = decodeString(torrentMap.get("announce"), charset); comment = decodeString(torrentMap.get("comment"), charset); creationDate = decodeLong(torrentMap.get("creation date")); - + Map infoMap = (Map) torrentMap.get("info"); - + name = decodeString(infoMap.get("name"), charset); pieceLength = (Long) infoMap.get("piece length"); - + if (infoMap.containsKey("files")) { // torrent contains multiple entries singleFileTorrent = false; - + List entries = new ArrayList(); - + for (Object fileMapObject : (List) infoMap.get("files")) { Map fileMap = (Map) fileMapObject; List pathList = (List) fileMap.get("path"); - + StringBuilder path = new StringBuilder(80); - + Iterator iterator = pathList.iterator(); - + while (iterator.hasNext()) { // append path element path.append(decodeString(iterator.next(), charset)); - + // append separator if (iterator.hasNext()) { path.append("/"); } } - + Long length = decodeLong(fileMap.get("length")); - + entries.add(new Entry(path.toString(), length)); } - + files = Collections.unmodifiableList(entries); } else { // single file torrent singleFileTorrent = true; - + Long length = decodeLong(infoMap.get("length")); - + files = Collections.singletonList(new Entry(name, length)); } } - - + + private static Map decodeTorrent(File torrent) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(torrent)); - + try { return BDecoder.decode(in); } finally { in.close(); } } - - + + private String decodeString(Object byteArray, Charset charset) { if (byteArray == null) return null; - + return new String((byte[]) byteArray, charset); } - - + + private Long decodeLong(Object number) { if (number == null) return null; - + return (Long) number; } - - + + public String getAnnounce() { return announce; } - - + + public String getComment() { return comment; } - - + + public String getCreatedBy() { return createdBy; } - - + + public Long getCreationDate() { return creationDate; } - - + + public String getEncoding() { return encoding; } - - + + public List getFiles() { return files; } - - + + public String getName() { return name; } - - + + public Long getPieceLength() { return pieceLength; } - - + + public boolean isSingleFileTorrent() { return singleFileTorrent; } - - + + public static class Entry { - + private final String path; - + private final long length; - - + + public Entry(String path, long length) { this.path = path; this.length = length; } - - + + public String getPath() { return path; } - - + + public String getName() { // the last element in the path is the filename // torrents don't contain directory entries, so there is always a non-empty name return path.substring(path.lastIndexOf("/") + 1); } - - + + public long getLength() { return length; } - - + + @Override public String toString() { return getPath(); } } - + } diff --git a/source/net/filebot/ui/FileBotListExportHandler.java b/source/net/filebot/ui/FileBotListExportHandler.java index 5e5ed863..b03cd87b 100644 --- a/source/net/filebot/ui/FileBotListExportHandler.java +++ b/source/net/filebot/ui/FileBotListExportHandler.java @@ -8,20 +8,20 @@ import net.filebot.ui.transfer.TextFileExportHandler; public class FileBotListExportHandler extends TextFileExportHandler { - + protected final FileBotList list; - - + + public FileBotListExportHandler(FileBotList list) { this.list = list; } - + @Override public boolean canExport() { return list.getModel().size() > 0; } - + @Override public void export(PrintWriter out) { @@ -29,11 +29,11 @@ public class FileBotListExportHandler extends TextFileExportHandler { out.println(entry); } } - + @Override public String getDefaultFileName() { return list.getTitle() + ".txt"; } - + } diff --git a/source/net/filebot/ui/FileBotTab.java b/source/net/filebot/ui/FileBotTab.java index c63eb15e..15eb4309 100644 --- a/source/net/filebot/ui/FileBotTab.java +++ b/source/net/filebot/ui/FileBotTab.java @@ -13,91 +13,91 @@ import javax.swing.SwingUtilities; public class FileBotTab extends JComponent { - + private final FileBotTabComponent tabComponent = new FileBotTabComponent(); - + private final T component; - - + + public FileBotTab(T component) { this.component = component; - + tabComponent.getCloseButton().addActionListener(closeAction); - + setLayout(new BorderLayout()); add(component, BorderLayout.CENTER); } - + public void addTo(JTabbedPane tabbedPane) { tabbedPane.addTab(this.getTitle(), this); tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(this), tabComponent); } - + public void close() { if (!isClosed()) { getTabbedPane().remove(this); } } - + public boolean isClosed() { JTabbedPane tabbedPane = getTabbedPane(); - + if (tabbedPane == null) return true; - + return getTabbedPane().indexOfComponent(this) < 0; } - + private JTabbedPane getTabbedPane() { return (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, this); } - + public T getComponent() { return component; } - + public FileBotTabComponent getTabComponent() { return tabComponent; } - + public void setTitle(String title) { tabComponent.setText(title); } - + public String getTitle() { return tabComponent.getText(); } - + public void setIcon(Icon icon) { tabComponent.setIcon(icon); } - + public Icon getIcon() { return tabComponent.getIcon(); } - + public void setLoading(boolean loading) { tabComponent.setLoading(loading); } - + private final ActionListener closeAction = new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { close(); } - + }; - + } diff --git a/source/net/filebot/ui/FileBotTabComponent.java b/source/net/filebot/ui/FileBotTabComponent.java index 7ec7e457..2987d522 100644 --- a/source/net/filebot/ui/FileBotTabComponent.java +++ b/source/net/filebot/ui/FileBotTabComponent.java @@ -18,84 +18,84 @@ import net.miginfocom.swing.MigLayout; public class FileBotTabComponent extends JComponent { - + private ProgressIndicator progressIndicator = new ProgressIndicator(); private JLabel textLabel = new JLabel(); private JLabel iconLabel = new JLabel(); private AbstractButton closeButton = createCloseButton(); - + private boolean loading = false; - - + + public FileBotTabComponent() { iconLabel.setHorizontalAlignment(SwingConstants.CENTER); textLabel.setHorizontalAlignment(SwingConstants.LEFT); - + progressIndicator.setVisible(loading); progressIndicator.setMinimumSize(new Dimension(16, 16)); - + setLayout(new MigLayout("nogrid, insets 0 0 1 3")); - + add(progressIndicator, "hidemode 3"); add(iconLabel, "hidemode 3"); add(textLabel, "gap rel, align left"); add(closeButton, "gap unrel:push, hidemode 3, align center 45%"); } - + public void setLoading(boolean loading) { this.loading = loading; progressIndicator.setVisible(loading); iconLabel.setVisible(!loading); } - + public boolean isLoading() { return loading; } - + public void setIcon(Icon icon) { iconLabel.setIcon(icon); progressIndicator.setPreferredSize(icon != null ? SwingUI.getDimension(icon) : progressIndicator.getMinimumSize()); } - + public Icon getIcon() { return iconLabel.getIcon(); } - + public void setText(String text) { textLabel.setText(text); } - + public String getText() { return textLabel.getText(); } - + public AbstractButton getCloseButton() { return closeButton; } - + protected AbstractButton createCloseButton() { Icon icon = ResourceManager.getIcon("tab.close"); Icon rolloverIcon = ResourceManager.getIcon("tab.close.hover"); - + JButton button = new JButton(icon); button.setRolloverIcon(rolloverIcon); - + button.setPreferredSize(SwingUI.getDimension(rolloverIcon)); button.setMaximumSize(button.getPreferredSize()); - + button.setContentAreaFilled(false); button.setBorderPainted(false); button.setFocusable(false); button.setRolloverEnabled(true); - + return button; } } diff --git a/source/net/filebot/ui/LanguageComboBoxModel.java b/source/net/filebot/ui/LanguageComboBoxModel.java index 70b5b739..58375d3c 100644 --- a/source/net/filebot/ui/LanguageComboBoxModel.java +++ b/source/net/filebot/ui/LanguageComboBoxModel.java @@ -97,11 +97,13 @@ public class LanguageComboBoxModel extends AbstractListModel implements ComboBox return data.get(index); } + @Override public boolean add(Language element) { // add first return addIfAbsent(0, element); } + @Override public void add(int index, Language element) { addIfAbsent(index, element); } diff --git a/source/net/filebot/ui/MainFrame.java b/source/net/filebot/ui/MainFrame.java index 843785f4..0b8cf809 100644 --- a/source/net/filebot/ui/MainFrame.java +++ b/source/net/filebot/ui/MainFrame.java @@ -125,10 +125,12 @@ public class MainFrame extends JFrame { GroovyPad pad = new GroovyPad(); pad.addWindowListener(new WindowAdapter() { + @Override public void windowOpened(WindowEvent e) { MainFrame.this.setVisible(false); }; + @Override public void windowClosing(WindowEvent e) { MainFrame.this.setVisible(true); }; diff --git a/source/net/filebot/ui/NotificationLogging.java b/source/net/filebot/ui/NotificationLogging.java index 4dbeb1f1..f06b23e1 100644 --- a/source/net/filebot/ui/NotificationLogging.java +++ b/source/net/filebot/ui/NotificationLogging.java @@ -23,52 +23,52 @@ import net.filebot.util.ui.notification.QueueNotificationLayout; public class NotificationLogging extends Handler { - + public static final Logger UILogger = createNotificationLogger("net.filebot.logger.ui"); - - + + private static Logger createNotificationLogger(String name) { Logger log = Logger.getLogger(name); - + // don't use parent handlers log.setUseParentHandlers(false); - + // ui handler log.addHandler(new NotificationLogging()); - + // console handler (for warnings and errors only) ConsoleHandler console = new ConsoleHandler(); console.setLevel(Level.WARNING); log.addHandler(console); - + return log; } - + public final NotificationManager notificationManager; public final int timeout = 2500; - - + + public NotificationLogging() { this(new NotificationManager(new QueueNotificationLayout(NORTH, SOUTH))); } - - + + public NotificationLogging(NotificationManager notificationManager) { this.notificationManager = notificationManager; } - - + + @Override public void publish(LogRecord record) { // fail gracefully on an headless machine if (GraphicsEnvironment.isHeadless()) return; - + final Level level = record.getLevel(); final String message = getMessage(record); - + SwingUtilities.invokeLater(new Runnable() { - + @Override public void run() { if (level == Level.INFO) { @@ -81,34 +81,34 @@ public class NotificationLogging extends Handler { } }); } - - + + protected String getMessage(LogRecord record) { String message = record.getMessage(); - + if ((message == null || message.isEmpty()) && record.getThrown() != null) { // if message is empty, display exception string return ExceptionUtilities.getMessage(record.getThrown()); } - + return message; } - - + + protected void show(String message, Icon icon, int timeout) { notificationManager.show(new MessageNotification(getApplicationName(), message, icon, timeout)); } - - + + @Override public void close() throws SecurityException { - + } - - + + @Override public void flush() { - + } - + } diff --git a/source/net/filebot/ui/PanelBuilder.java b/source/net/filebot/ui/PanelBuilder.java index b5c1642d..2095471e 100644 --- a/source/net/filebot/ui/PanelBuilder.java +++ b/source/net/filebot/ui/PanelBuilder.java @@ -7,13 +7,13 @@ import javax.swing.JComponent; public interface PanelBuilder { - + public String getName(); - + public Icon getIcon(); - + public JComponent create(); - + } diff --git a/source/net/filebot/ui/analyze/AnalyzePanel.java b/source/net/filebot/ui/analyze/AnalyzePanel.java index d1192424..4cfcfebd 100644 --- a/source/net/filebot/ui/analyze/AnalyzePanel.java +++ b/source/net/filebot/ui/analyze/AnalyzePanel.java @@ -37,6 +37,7 @@ public class AnalyzePanel extends JComponent { private final PropertyChangeListener filetreeListener = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { // stopped loading, refresh tools for (int i = 0; i < toolsPanel.getTabCount(); i++) { diff --git a/source/net/filebot/ui/analyze/AnalyzePanelBuilder.java b/source/net/filebot/ui/analyze/AnalyzePanelBuilder.java index 54502625..5c5e9942 100644 --- a/source/net/filebot/ui/analyze/AnalyzePanelBuilder.java +++ b/source/net/filebot/ui/analyze/AnalyzePanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class AnalyzePanelBuilder implements PanelBuilder { - + @Override public String getName() { return "Analyze"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.analyze"); } - + @Override public JComponent create() { return new AnalyzePanel(); } - + } diff --git a/source/net/filebot/ui/analyze/FileTree.java b/source/net/filebot/ui/analyze/FileTree.java index 0fcb9a7f..8fa7ede0 100644 --- a/source/net/filebot/ui/analyze/FileTree.java +++ b/source/net/filebot/ui/analyze/FileTree.java @@ -114,6 +114,7 @@ public class FileTree extends JTree { putValue("files", files); } + @Override public void actionPerformed(ActionEvent event) { UserFiles.revealFiles((Collection) getValue("files")); } diff --git a/source/net/filebot/ui/analyze/FileTreeCellRenderer.java b/source/net/filebot/ui/analyze/FileTreeCellRenderer.java index 2a5858d9..de2d72a9 100644 --- a/source/net/filebot/ui/analyze/FileTreeCellRenderer.java +++ b/source/net/filebot/ui/analyze/FileTreeCellRenderer.java @@ -13,15 +13,15 @@ import net.filebot.util.ui.GradientStyle; public class FileTreeCellRenderer extends FancyTreeCellRenderer { - + public FileTreeCellRenderer() { super(GradientStyle.TOP_TO_BOTTOM); - + openIcon = ResourceManager.getIcon("tree.open"); closedIcon = ResourceManager.getIcon("tree.closed"); leafIcon = ResourceManager.getIcon("tree.leaf"); } - + @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { @@ -30,17 +30,17 @@ public class FileTreeCellRenderer extends FancyTreeCellRenderer { expanded = true; leaf = false; } - + super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); - + return this; } - + private boolean isFolder(Object value) { if (((TreeNode) value).getAllowsChildren()) return true; - + return false; } } diff --git a/source/net/filebot/ui/analyze/TypeTool.java b/source/net/filebot/ui/analyze/TypeTool.java index 6e4f3979..166f45e7 100644 --- a/source/net/filebot/ui/analyze/TypeTool.java +++ b/source/net/filebot/ui/analyze/TypeTool.java @@ -7,7 +7,6 @@ import static net.filebot.util.FileUtilities.*; import java.io.File; import java.io.FileFilter; -import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -15,8 +14,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JScrollPane; diff --git a/source/net/filebot/ui/episodelist/EpisodeListPanelBuilder.java b/source/net/filebot/ui/episodelist/EpisodeListPanelBuilder.java index 6885364a..90249b20 100644 --- a/source/net/filebot/ui/episodelist/EpisodeListPanelBuilder.java +++ b/source/net/filebot/ui/episodelist/EpisodeListPanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class EpisodeListPanelBuilder implements PanelBuilder { - + @Override public String getName() { return "Episodes"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.episodelist"); } - + @Override public JComponent create() { return new EpisodeListPanel(); } - + } diff --git a/source/net/filebot/ui/episodelist/SeasonSpinnerModel.java b/source/net/filebot/ui/episodelist/SeasonSpinnerModel.java index 5bd70ce3..e36047e8 100644 --- a/source/net/filebot/ui/episodelist/SeasonSpinnerModel.java +++ b/source/net/filebot/ui/episodelist/SeasonSpinnerModel.java @@ -6,47 +6,47 @@ import javax.swing.SpinnerNumberModel; class SeasonSpinnerModel extends SpinnerNumberModel { - + public static final int ALL_SEASONS = 0; - + public static final int MAX_VALUE = 99; - + private Number valueBeforeLock = null; - - + + public SeasonSpinnerModel() { super(ALL_SEASONS, ALL_SEASONS, MAX_VALUE, 1); } - + public int getSeason() { return getNumber().intValue(); } - + @Override public Integer getMinimum() { return (Integer) super.getMinimum(); } - + @Override public Integer getMaximum() { return (Integer) super.getMaximum(); } - + public void spin(int steps) { int next = getSeason() + steps; - + if (next < getMinimum()) next = getMinimum(); else if (next > getMaximum()) next = getMaximum(); - + setValue(next); } - + public void lock(int value) { valueBeforeLock = getNumber(); @@ -54,12 +54,12 @@ class SeasonSpinnerModel extends SpinnerNumberModel { setMaximum(value); setValue(value); } - + public void unlock() { setMinimum(ALL_SEASONS); setMaximum(MAX_VALUE); - + if (valueBeforeLock != null) { setValue(valueBeforeLock); valueBeforeLock = null; diff --git a/source/net/filebot/ui/list/ListPanelBuilder.java b/source/net/filebot/ui/list/ListPanelBuilder.java index 512fb847..a0c449ed 100644 --- a/source/net/filebot/ui/list/ListPanelBuilder.java +++ b/source/net/filebot/ui/list/ListPanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class ListPanelBuilder implements PanelBuilder { - + @Override public String getName() { return "List"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.list"); } - + @Override public JComponent create() { return new ListPanel(); } - + } diff --git a/source/net/filebot/ui/rename/CharacterHighlightPainter.java b/source/net/filebot/ui/rename/CharacterHighlightPainter.java index d0c7df7d..3480a1b5 100644 --- a/source/net/filebot/ui/rename/CharacterHighlightPainter.java +++ b/source/net/filebot/ui/rename/CharacterHighlightPainter.java @@ -21,42 +21,42 @@ import net.filebot.util.ui.GradientStyle; class CharacterHighlightPainter implements Highlighter.HighlightPainter { - + private Color gradientBeginColor; private Color gradientEndColor; - - + + public CharacterHighlightPainter(Color gradientBeginColor, Color gradientEndColor) { this.gradientBeginColor = gradientBeginColor; this.gradientEndColor = gradientEndColor; } - + @Override public void paint(Graphics g, int offset1, int offset2, Shape bounds, JTextComponent c) { Graphics2D g2d = (Graphics2D) g; - + try { // determine locations TextUI mapper = c.getUI(); Rectangle p1 = mapper.modelToView(c, offset1); Rectangle p2 = mapper.modelToView(c, offset2); - + Rectangle r = p1.union(p2); - + float w = r.width + 1; float h = r.height; - + float x = r.x - 1; float y = r.y; - + float arch = 5f; - + RoundRectangle2D shape = new RoundRectangle2D.Float(x, y, w, h, arch, arch); - + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setPaint(GradientStyle.TOP_TO_BOTTOM.getGradientPaint(shape, gradientBeginColor, gradientEndColor)); - + g2d.fill(shape); } catch (BadLocationException e) { //should not happen diff --git a/source/net/filebot/ui/rename/ExpressionFormatter.java b/source/net/filebot/ui/rename/ExpressionFormatter.java index 658b544d..3305d27e 100644 --- a/source/net/filebot/ui/rename/ExpressionFormatter.java +++ b/source/net/filebot/ui/rename/ExpressionFormatter.java @@ -14,55 +14,55 @@ import net.filebot.similarity.Match; class ExpressionFormatter implements MatchFormatter { - + private final String expression; private ExpressionFormat format; - + private Format preview; private Class target; - - + + public ExpressionFormatter(String expression, Format preview, Class target) { if (expression == null || expression.isEmpty()) throw new IllegalArgumentException("Expression must not be null or empty"); - + this.expression = expression; this.preview = preview; this.target = target; - + } - - + + @Override public boolean canFormat(Match match) { // target object is required, file is optional return target.isInstance(match.getValue()) && (match.getCandidate() == null || match.getCandidate() instanceof File); } - - + + @Override public String preview(Match match) { return preview != null ? preview.format(match.getValue()) : match.getValue().toString(); } - - + + @Override public synchronized String format(Match match, Map context) throws ScriptException { // lazy initialize script engine if (format == null) { format = new ExpressionFormat(expression); } - + // evaluate the expression using the given bindings Object bindingBean = new MediaBindingBean(match.getValue(), (File) match.getCandidate(), (Map) context); String result = format.format(bindingBean).trim(); - + // if result is empty, check for script exceptions if (result.isEmpty() && format.caughtScriptException() != null) { throw format.caughtScriptException(); } - + return result; } - + } diff --git a/source/net/filebot/ui/rename/FileNameFormatter.java b/source/net/filebot/ui/rename/FileNameFormatter.java index 331a2c73..b8afcd1e 100644 --- a/source/net/filebot/ui/rename/FileNameFormatter.java +++ b/source/net/filebot/ui/rename/FileNameFormatter.java @@ -11,47 +11,47 @@ import net.filebot.vfs.FileInfo; class FileNameFormatter implements MatchFormatter { - + private boolean preserveExtension; - - + + public FileNameFormatter(boolean preserveExtension) { this.preserveExtension = preserveExtension; } - - + + @Override public boolean canFormat(Match match) { return match.getValue() instanceof File || match.getValue() instanceof FileInfo || match.getValue() instanceof String; } - - + + @Override public String preview(Match match) { return format(match, null); } - - + + @Override public String format(Match match, Map context) { Object value = match.getValue(); - + if (value instanceof File) { File file = (File) value; return preserveExtension ? FileUtilities.getName(file) : file.getName(); } - + if (value instanceof FileInfo) { FileInfo file = (FileInfo) value; return preserveExtension ? file.getName() : file.getPath(); } - + if (value instanceof String) { return preserveExtension ? FileUtilities.getNameWithoutExtension(value.toString()) : value.toString(); } - + // cannot format value throw new IllegalArgumentException("Illegal value: " + value); } - + } diff --git a/source/net/filebot/ui/rename/HighlightListCellRenderer.java b/source/net/filebot/ui/rename/HighlightListCellRenderer.java index 86f2e8dd..d699c1ca 100644 --- a/source/net/filebot/ui/rename/HighlightListCellRenderer.java +++ b/source/net/filebot/ui/rename/HighlightListCellRenderer.java @@ -24,45 +24,45 @@ import net.filebot.util.ui.SwingUI; class HighlightListCellRenderer extends AbstractFancyListCellRenderer { - + protected final JTextComponent textComponent = new JTextField(); - + protected final Pattern pattern; protected final Highlighter.HighlightPainter highlightPainter; - + public HighlightListCellRenderer(Pattern pattern, Highlighter.HighlightPainter highlightPainter, int padding) { super(new Insets(0, 0, 0, 0)); - + this.pattern = pattern; this.highlightPainter = highlightPainter; - - // pad the cell from inside the text component, + + // pad the cell from inside the text component, // so the HighlightPainter may paint in this space as well textComponent.setBorder(new EmptyBorder(padding, padding, padding, padding)); - - // make text component transparent, should work for all LAFs (setOpaque(false) may not, e.g. Nimbus) + + // make text component transparent, should work for all LAFs (setOpaque(false) may not, e.g. Nimbus) textComponent.setBackground(SwingUI.TRANSLUCENT); - + this.add(textComponent, BorderLayout.WEST); - + textComponent.getDocument().addDocumentListener(new HighlightUpdateListener()); } - + @Override protected void configureListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.configureListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - + textComponent.setText(value.toString()); } - + protected void updateHighlighter() { textComponent.getHighlighter().removeAllHighlights(); - + Matcher matcher = pattern.matcher(textComponent.getText()); - + while (matcher.find()) { try { textComponent.getHighlighter().addHighlight(matcher.start(0), matcher.end(0), highlightPainter); @@ -72,38 +72,38 @@ class HighlightListCellRenderer extends AbstractFancyListCellRenderer { } } } - + @Override public void setForeground(Color fg) { super.setForeground(fg); - + // textComponent is null while in super constructor if (textComponent != null) { textComponent.setForeground(fg); } } - + private class HighlightUpdateListener implements DocumentListener { - + @Override public void changedUpdate(DocumentEvent e) { updateHighlighter(); } - + @Override public void insertUpdate(DocumentEvent e) { updateHighlighter(); } - + @Override public void removeUpdate(DocumentEvent e) { updateHighlighter(); } - + } - + } diff --git a/source/net/filebot/ui/rename/MatchAction.java b/source/net/filebot/ui/rename/MatchAction.java index 8fe04a90..d552c7cc 100644 --- a/source/net/filebot/ui/rename/MatchAction.java +++ b/source/net/filebot/ui/rename/MatchAction.java @@ -42,6 +42,7 @@ class MatchAction extends AbstractAction { putValue(SMALL_ICON, ResourceManager.getIcon(strict ? "action.match.strict" : "action.match")); } + @Override public void actionPerformed(ActionEvent evt) { if (model.names().isEmpty() || model.files().isEmpty()) { return; diff --git a/source/net/filebot/ui/rename/MatchFormatter.java b/source/net/filebot/ui/rename/MatchFormatter.java index b1f14c65..9c736fe1 100644 --- a/source/net/filebot/ui/rename/MatchFormatter.java +++ b/source/net/filebot/ui/rename/MatchFormatter.java @@ -8,13 +8,13 @@ import net.filebot.similarity.Match; public interface MatchFormatter { - + public boolean canFormat(Match match); - - + + public String preview(Match match); - - + + public String format(Match match, Map context) throws Exception; - + } diff --git a/source/net/filebot/ui/rename/MatchModel.java b/source/net/filebot/ui/rename/MatchModel.java index 482115b5..d57a22a3 100644 --- a/source/net/filebot/ui/rename/MatchModel.java +++ b/source/net/filebot/ui/rename/MatchModel.java @@ -16,48 +16,48 @@ import ca.odell.glazedlists.event.ListEvent; public class MatchModel { - + private final EventList> source = new BasicEventList>(); - + private final EventList values; - + private final EventList candidates; - - + + public MatchModel() { this.values = new MatchView(source) { - + @Override public Value getElement(Match match) { return match.getValue(); } - + @Override public Candidate getComplement(Match match) { return match.getCandidate(); } - + @Override public Match createMatch(Value element, Candidate complement) { return new Match(element, complement); } }; - + this.candidates = new MatchView(source) { - + @Override public Candidate getElement(Match match) { return match.getCandidate(); } - + @Override public Value getComplement(Match match) { return match.getValue(); } - + @Override public Match createMatch(Candidate element, Value complement) { @@ -65,154 +65,154 @@ public class MatchModel { } }; } - + public void clear() { source.clear(); } - + public int size() { return source.size(); } - + public Match getMatch(int index) { return source.get(index); } - + public boolean hasComplement(int index) { if (index >= 0 && index < size()) { return source.get(index).getValue() != null && source.get(index).getCandidate() != null; } - + return false; } - + public EventList> matches() { return source; } - + public EventList values() { return values; } - + public EventList candidates() { return candidates; } - + public void addAll(Collection> matches) { source.addAll(matches); } - + public void addAll(Collection values, Collection candidates) { if (this.values.size() != this.candidates.size()) throw new IllegalStateException("Existing matches are not balanced"); - + Iterator valueIterator = values.iterator(); Iterator candidateIterator = candidates.iterator(); - + while (valueIterator.hasNext() || candidateIterator.hasNext()) { Value value = valueIterator.hasNext() ? valueIterator.next() : null; Candidate candidate = candidateIterator.hasNext() ? candidateIterator.next() : null; - + source.add(new Match(value, candidate)); } } - - + + private abstract class MatchView extends TransformedList, Element> { - + public MatchView(EventList> source) { super(source); - + source.addListEventListener(this); } - + public abstract Element getElement(Match match); - + public abstract Complement getComplement(Match match); - + public abstract Match createMatch(Element element, Complement complement); - + @Override public Element get(int index) { return getElement(index); } - + public Element getElement(int index) { return getElement(source.get(index)); } - + public Complement getComplement(int index) { return getComplement(source.get(index)); } - + @Override public boolean addAll(Collection values) { return put(size(), values); } - + @Override public boolean add(Element value) { return put(size(), Collections.singleton(value)); }; - + @Override public void add(int index, Element value) { List range = new ArrayList(); - + range.add(value); range.addAll(subList(index, size())); - + put(index, range); } - + @Override public Element remove(int index) { Element old = getElement(index); - + int lastIndex = size() - 1; - + // shift subsequent elements put(index, new ArrayList(subList(index + 1, lastIndex + 1))); - + // remove last element if (getComplement(lastIndex) == null) { source.remove(lastIndex); } else { set(lastIndex, null); } - + return old; } - + @Override public Element set(int index, Element element) { Element old = getElement(index); - + source.set(index, createMatch(element, getComplement(index))); - + return old; } - + @Override public void clear() { @@ -220,7 +220,7 @@ public class MatchModel { // exist at the and of the source model for (int i = size() - 1; i >= 0; i--) { Complement complement = getComplement(i); - + if (complement != null) { // replace original match with null match source.set(i, createMatch(null, complement)); @@ -230,7 +230,7 @@ public class MatchModel { } } } - + private boolean put(int index, Collection elements) { for (Element element : elements) { @@ -239,37 +239,37 @@ public class MatchModel { } else { source.add(index, createMatch(element, null)); } - + index++; } - + return true; } - + @Override protected boolean isWritable() { // can't write to source directly return false; } - + private int size = 0; - - + + @Override public int size() { return size; } - + @Override public void listChanged(ListEvent> listChanges) { updates.beginEvent(true); - + while (listChanges.next()) { int index = listChanges.getIndex(); int type = listChanges.getType(); - + if (type == ListEvent.INSERT || type == ListEvent.UPDATE) { if (index < size) { if (index == size - 1 && getElement(index) == null) { @@ -287,9 +287,9 @@ public class MatchModel { size--; } } - + updates.commitEvent(); } } - + } diff --git a/source/net/filebot/ui/rename/MovieFormatter.java b/source/net/filebot/ui/rename/MovieFormatter.java index ef9eeb60..3e3d7db8 100644 --- a/source/net/filebot/ui/rename/MovieFormatter.java +++ b/source/net/filebot/ui/rename/MovieFormatter.java @@ -12,31 +12,31 @@ import net.filebot.web.MoviePart; class MovieFormatter implements MatchFormatter { - + @Override public boolean canFormat(Match match) { return match.getValue() instanceof MoviePart; } - - + + @Override public String preview(Match match) { return format(match, null); } - - + + @Override public String format(Match match, Map context) { MoviePart video = (MoviePart) match.getValue(); Formatter name = new Formatter(new StringBuilder()); - + // format as single-file or multi-part movie name.format("%s (%d)", video.getName(), video.getYear()); - + if (video.getPartCount() > 1) { name.format(".CD%d", video.getPartIndex()); } - + // remove path separators if the name contains any / or \ return replacePathSeparators(name.out().toString()); } diff --git a/source/net/filebot/ui/rename/PresetEditor.java b/source/net/filebot/ui/rename/PresetEditor.java index 9529603c..8354e3cc 100644 --- a/source/net/filebot/ui/rename/PresetEditor.java +++ b/source/net/filebot/ui/rename/PresetEditor.java @@ -237,6 +237,7 @@ public class PresetEditor extends JDialog { private final ListCellRenderer parent = (ListCellRenderer) combo.getRenderer(); + @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) parent.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); @@ -278,7 +279,7 @@ public class PresetEditor extends JDialog { JLabel label = (JLabel) parent.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof Language) { - Language it = (Language) value; + Language it = value; label.setText(it.getName()); label.setIcon(ResourceManager.getFlagIcon(it.getCode())); } diff --git a/source/net/filebot/ui/rename/RenameList.java b/source/net/filebot/ui/rename/RenameList.java index 4922c068..2a2807d6 100644 --- a/source/net/filebot/ui/rename/RenameList.java +++ b/source/net/filebot/ui/rename/RenameList.java @@ -126,6 +126,7 @@ class RenameList extends FileBotList { private final AbstractAction upAction = new AbstractAction("Align Up", ResourceManager.getIcon("action.up")) { + @Override public void actionPerformed(ActionEvent e) { int index = getListComponent().getSelectedIndex(); @@ -138,6 +139,7 @@ class RenameList extends FileBotList { private final AbstractAction downAction = new AbstractAction("Align Down", ResourceManager.getIcon("action.down")) { + @Override public void actionPerformed(ActionEvent e) { int index = getListComponent().getSelectedIndex(); diff --git a/source/net/filebot/ui/rename/RenamePanel.java b/source/net/filebot/ui/rename/RenamePanel.java index 422c8578..684a9fb7 100644 --- a/source/net/filebot/ui/rename/RenamePanel.java +++ b/source/net/filebot/ui/rename/RenamePanel.java @@ -274,7 +274,7 @@ public class RenamePanel extends JComponent { try { JList list = (JList) evt.getSource(); if (list.getSelectedIndex() >= 0) { - UserFiles.revealFiles((List) list.getSelectedValuesList()); + UserFiles.revealFiles(list.getSelectedValuesList()); } } catch (Exception e) { Logger.getLogger(RenamePanel.class.getName()).log(Level.WARNING, e.getMessage()); @@ -702,6 +702,7 @@ public class RenamePanel extends JComponent { this.preset = preset; } + @Override public List getFiles(ActionEvent evt) { List input = new ArrayList(); if (preset.getInputFolder() != null) { @@ -725,10 +726,12 @@ public class RenamePanel extends JComponent { return input; } + @Override public boolean isStrict(ActionEvent evt) { return preset.getMatchMode() != null ? MATCH_MODE_STRICT.equals(preset.getMatchMode()) : super.isStrict(evt); } + @Override public SortOrder getSortOrder(ActionEvent evt) { return preset.getSortOrder() != null ? preset.getSortOrder() : super.getSortOrder(evt); } diff --git a/source/net/filebot/ui/rename/RenamePanelBuilder.java b/source/net/filebot/ui/rename/RenamePanelBuilder.java index 2050aaed..704fc7d7 100644 --- a/source/net/filebot/ui/rename/RenamePanelBuilder.java +++ b/source/net/filebot/ui/rename/RenamePanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class RenamePanelBuilder implements PanelBuilder { - + @Override public String getName() { return "Rename"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.rename"); } - + @Override public JComponent create() { return new RenamePanel(); } - + } diff --git a/source/net/filebot/ui/rename/ScrollPaneSynchronizer.java b/source/net/filebot/ui/rename/ScrollPaneSynchronizer.java index ec39c53f..ef53e1b6 100644 --- a/source/net/filebot/ui/rename/ScrollPaneSynchronizer.java +++ b/source/net/filebot/ui/rename/ScrollPaneSynchronizer.java @@ -13,88 +13,88 @@ import javax.swing.event.ListDataListener; class ScrollPaneSynchronizer { - + private final RenameList[] components; - + public ScrollPaneSynchronizer(RenameList... components) { this.components = components; - + // share vertical and horizontal scrollbar model BoundedRangeModel horizontalScrollBarModel = components[0].getListScrollPane().getHorizontalScrollBar().getModel(); BoundedRangeModel verticalScrollBarModel = components[0].getListScrollPane().getVerticalScrollBar().getModel(); - + // recalculate common size on change ListDataListener resizeListener = new ListDataListener() { - + private final Timer timer = new Timer(50, new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { updatePreferredSize(); - + // fire only once timer.stop(); } }); - + @Override public void intervalAdded(ListDataEvent e) { timer.restart(); } - + @Override public void intervalRemoved(ListDataEvent e) { timer.restart(); } - + @Override public void contentsChanged(ListDataEvent e) { timer.restart(); } }; - + // apply to all components for (RenameList component : components) { component.getListScrollPane().getHorizontalScrollBar().setModel(horizontalScrollBarModel); component.getListScrollPane().getVerticalScrollBar().setModel(verticalScrollBarModel); - + component.getListComponent().getModel().addListDataListener(resizeListener); } - + // initial sync of component sizes updatePreferredSize(); } - + public void updatePreferredSize() { Dimension max = new Dimension(); - + for (RenameList component : components) { // reset preferred size component.getListComponent().setPreferredSize(null); - + // calculate preferred size based on data and renderer Dimension preferred = component.getListComponent().getPreferredSize(); - + // update maximum size if (preferred.width > max.width) max.width = preferred.width; if (preferred.height > max.height) max.height = preferred.height; } - + for (RenameList component : components) { // set fixed preferred size component.getListComponent().setPreferredSize(max); - + // update scrollbars component.getListComponent().revalidate(); component.getListScrollPane().revalidate(); } } - + } diff --git a/source/net/filebot/ui/rename/ValidateDialog.java b/source/net/filebot/ui/rename/ValidateDialog.java index 2bad951b..4bff5e86 100644 --- a/source/net/filebot/ui/rename/ValidateDialog.java +++ b/source/net/filebot/ui/rename/ValidateDialog.java @@ -39,36 +39,36 @@ import net.miginfocom.swing.MigLayout; class ValidateDialog extends JDialog { - + private final JList list; - + private File[] model; - + private boolean cancelled = true; - - + + public ValidateDialog(Window owner, Collection source) { super(owner, "Invalid Names", ModalityType.DOCUMENT_MODAL); - + model = source.toArray(new File[0]); - + list = new JList(model); list.setEnabled(false); - + list.setCellRenderer(new HighlightListCellRenderer(ILLEGAL_CHARACTERS, new CharacterHighlightPainter(new Color(0xFF4200), new Color(0xFF1200)), 4) { - + @Override protected void updateHighlighter() { textComponent.getHighlighter().removeAllHighlights(); - + Matcher matcher = pattern.matcher(textComponent.getText()); File file = new File(textComponent.getText()); - + // highlight path components separately to ignore "illegal characters" that are either path separators or part of the drive letter (e.g. ':' in 'E:') for (File element : listPath(file)) { int limit = element.getPath().length(); matcher.region(limit - element.getName().length(), limit); - + while (matcher.find()) { try { textComponent.getHighlighter().addHighlight(matcher.start(0), matcher.end(0), highlightPainter); @@ -80,47 +80,47 @@ class ValidateDialog extends JDialog { } } }); - + JLabel label = new JLabel("Some names contain invalid characters:"); - + JComponent content = (JComponent) getContentPane(); - + content.setLayout(new MigLayout("insets dialog, nogrid, fill", "", "[pref!][fill][pref!]")); - + content.add(label, "wrap"); content.add(new JScrollPane(list), "grow, wrap 2mm"); - + content.add(new JButton(validateAction), "align center"); content.add(new JButton(continueAction), "gap related"); content.add(new JButton(cancelAction), "gap 12mm"); - + installAction(content, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelAction); - + setDefaultCloseOperation(DISPOSE_ON_CLOSE); setMinimumSize(new Dimension(365, 280)); pack(); } - - + + public List getModel() { return unmodifiableList(Arrays.asList(model)); } - - + + public boolean isCancelled() { return cancelled; } - - + + private void finish(boolean cancelled) { this.cancelled = cancelled; - + setVisible(false); dispose(); } - + private final Action validateAction = new AbstractAction("Validate", ResourceManager.getIcon("dialog.continue")) { - + @Override public void actionPerformed(ActionEvent e) { // validate names @@ -128,110 +128,110 @@ class ValidateDialog extends JDialog { // remove illegal characters model[i] = validateFilePath(model[i]); } - + // update view list.repaint(); - + // switch icon continueAction.putValue(SMALL_ICON, getValue(SMALL_ICON)); - + // disable this action setEnabled(false); } }; - + private final Action continueAction = new AbstractAction("Continue", ResourceManager.getIcon("dialog.continue.invalid")) { - + @Override public void actionPerformed(ActionEvent e) { finish(false); } }; - + private final Action cancelAction = new AbstractAction("Cancel", ResourceManager.getIcon("dialog.cancel")) { - + @Override public void actionPerformed(ActionEvent e) { finish(true); } }; - - + + public static boolean validate(Component parent, List source) { IndexView invalidFilePaths = new IndexView(source); - + for (int i = 0; i < source.size(); i++) { // invalid file names are also invalid file paths if (isInvalidFilePath(source.get(i)) && !isUnixFS()) { invalidFilePaths.addIndex(i); } } - + // check if there is anything to do in the first place if (invalidFilePaths.isEmpty()) { return true; } - + ValidateDialog dialog = new ValidateDialog(getWindow(parent), invalidFilePaths); dialog.setLocation(getOffsetLocation(dialog.getOwner())); - + // show and block dialog.setVisible(true); - + if (dialog.isCancelled()) { // no output return false; } - + List validatedFilePaths = dialog.getModel(); - + // validate source list via index view for (int i = 0; i < invalidFilePaths.size(); i++) { invalidFilePaths.set(i, validatedFilePaths.get(i)); } - + return true; } - - + + private static class IndexView extends AbstractList { - + private final List mapping = new ArrayList(); - + private final List source; - - + + public IndexView(List source) { this.source = source; } - - + + public boolean addIndex(int index) { return mapping.add(index); } - - + + @Override public E get(int index) { int sourceIndex = mapping.get(index); - + if (sourceIndex >= 0) return source.get(sourceIndex); - + return null; } - - + + @Override public E set(int index, E element) { return source.set(mapping.get(index), element); } - - + + @Override public int size() { return mapping.size(); } } - + } diff --git a/source/net/filebot/ui/sfv/ChecksumButton.java b/source/net/filebot/ui/sfv/ChecksumButton.java index 07d8dd96..47a78f5e 100644 --- a/source/net/filebot/ui/sfv/ChecksumButton.java +++ b/source/net/filebot/ui/sfv/ChecksumButton.java @@ -22,55 +22,55 @@ import net.filebot.ResourceManager; public class ChecksumButton extends JToggleButton { - + private static final Icon contentArea = ResourceManager.getIcon("button.checksum"); private static final Icon contentAreaSelected = ResourceManager.getIcon("button.checksum.selected"); - + public ChecksumButton(Action action) { super(action); - + setPreferredSize(new Dimension(max(contentAreaSelected.getIconWidth(), contentArea.getIconWidth()), max(contentAreaSelected.getIconHeight(), contentArea.getIconHeight()))); setMinimumSize(getPreferredSize()); setMaximumSize(getPreferredSize()); - + setForeground(WHITE); setFont(new Font(DIALOG, PLAIN, 11)); - + // as image button setBorderPainted(false); setContentAreaFilled(false); setFocusPainted(false); - + setEnabled(true); } - + @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); - + // set appropriate cursor setCursor(getPredefinedCursor(enabled ? HAND_CURSOR : DEFAULT_CURSOR)); } - + @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; - + g2d.setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(KEY_RENDERING, VALUE_RENDER_QUALITY); - + // paint background image in the center if (isSelected()) { contentAreaSelected.paintIcon(this, g2d, (int) round((getWidth() - contentAreaSelected.getIconWidth()) / (double) 2), (int) round((getHeight() - contentAreaSelected.getIconHeight()) / (double) 2)); } else { contentArea.paintIcon(this, g2d, (int) round((getWidth() - contentArea.getIconWidth()) / (double) 2), (int) round((getHeight() - contentArea.getIconHeight()) / (double) 2)); } - + Rectangle2D textBounds = g2d.getFontMetrics().getStringBounds(getText(), g2d); - + // draw text in the center g2d.drawString(getText(), round((getWidth() - textBounds.getWidth()) / 2) + 1, round(getHeight() / 2 - textBounds.getY() - textBounds.getHeight() / 2)); } diff --git a/source/net/filebot/ui/sfv/ChecksumCell.java b/source/net/filebot/ui/sfv/ChecksumCell.java index 76b6f2fc..5da2ecac 100644 --- a/source/net/filebot/ui/sfv/ChecksumCell.java +++ b/source/net/filebot/ui/sfv/ChecksumCell.java @@ -17,132 +17,132 @@ import net.filebot.util.ExceptionUtilities; class ChecksumCell { - + private final String name; private final File root; - + private Map hashes; private ChecksumComputationTask task; private Throwable error; - - + + public static enum State { PENDING, PROGRESS, READY, ERROR } - - + + public ChecksumCell(String name, File root, Map hashes) { this.name = name; this.root = root; this.hashes = hashes; } - + public ChecksumCell(String name, File root, ChecksumComputationTask task) { this.name = name; this.root = root; this.hashes = new EnumMap(HashType.class); this.task = task; - + // forward property change events task.addPropertyChangeListener(taskListener); } - + public String getName() { return name; } - + public File getRoot() { return root; } - + public String getChecksum(HashType hash) { return hashes.get(hash); } - + public void putTask(ChecksumComputationTask computationTask) { if (task != null) { task.removePropertyChangeListener(taskListener); task.cancel(true); } - + task = computationTask; error = null; - + // forward property change events task.addPropertyChangeListener(taskListener); - + // state changed to PENDING pcs.firePropertyChange("state", null, getState()); } - + public ChecksumComputationTask getTask() { return task; } - + public Throwable getError() { return error; } - + public State getState() { if (task != null) { switch (task.getState()) { - case PENDING: - return State.PENDING; - default: - return State.PROGRESS; + case PENDING: + return State.PENDING; + default: + return State.PROGRESS; } } - + if (error != null) { return State.ERROR; } - + return State.READY; } - + public void dispose() { // clear property change support for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { pcs.removePropertyChangeListener(listener); } - + if (task != null) { task.removePropertyChangeListener(taskListener); task.cancel(true); } - + hashes = null; error = null; task = null; pcs = null; } - + @Override public String toString() { return String.format("%s %s", name, hashes); } - + private final PropertyChangeListener taskListener = new PropertyChangeListener() { - + @Override public void propertyChange(PropertyChangeEvent evt) { if ("state".equals(evt.getPropertyName())) { if (evt.getNewValue() == StateValue.DONE) done(evt); - + // cell state changed because worker state changed pcs.firePropertyChange("state", null, getState()); } else { @@ -150,36 +150,36 @@ class ChecksumCell { pcs.firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } } - + protected void done(PropertyChangeEvent evt) { try { hashes.putAll(task.get()); } catch (Exception e) { Throwable cause = ExceptionUtilities.getRootCause(e); - + // ignore cancellation if (cause instanceof CancellationException) { return; } - + error = cause; } finally { task = null; } } }; - + private SwingPropertyChangeSupport pcs = new SwingPropertyChangeSupport(this, true); - - + + public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } - + public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } - + } diff --git a/source/net/filebot/ui/sfv/ChecksumCellRenderer.java b/source/net/filebot/ui/sfv/ChecksumCellRenderer.java index 9e051317..6bcd4791 100644 --- a/source/net/filebot/ui/sfv/ChecksumCellRenderer.java +++ b/source/net/filebot/ui/sfv/ChecksumCellRenderer.java @@ -18,37 +18,37 @@ import net.filebot.util.ExceptionUtilities; public class ChecksumCellRenderer extends DefaultTableCellRenderer { - + private final SwingWorkerCellRenderer progressRenderer = new SwingWorkerCellRenderer(); - + private final Color verificationForeground = new Color(0x009900); - + @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { boolean pendingWorker = false; - + if (value instanceof SwingWorker) { if (((SwingWorker) value).getState() != StateValue.PENDING) return progressRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - + pendingWorker = true; } - + // ignore focus super.getTableCellRendererComponent(table, value, isSelected, false, row, column); - - // check row state for ERROR + + // check row state for ERROR boolean isError = (table.getValueAt(row, 0) == ChecksumRow.State.ERROR); - + // if row state is ERROR and if we are not selected use text color RED, // else use default table colors setForeground(isSelected ? table.getSelectionForeground() : isError ? Color.RED : isVerificationColumn(table, column) ? verificationForeground : table.getForeground()); setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); - + // use BOLD font on ERROR setFont(getFont().deriveFont(isError ? BOLD : PLAIN)); - + if (pendingWorker) { setText("Pending..."); } else if (value == null && !isSelected) { @@ -58,16 +58,16 @@ public class ChecksumCellRenderer extends DefaultTableCellRenderer { } else if (value instanceof Throwable) { setText(ExceptionUtilities.getRootCauseMessage((Throwable) value)); } - + return this; } - + private boolean isVerificationColumn(JTable table, int column) { ChecksumTableModel model = (ChecksumTableModel) table.getModel(); int modelColumn = table.getColumnModel().getColumn(column).getModelIndex(); - + return model.isVerificationColumn(modelColumn); } - + } diff --git a/source/net/filebot/ui/sfv/ChecksumComputationService.java b/source/net/filebot/ui/sfv/ChecksumComputationService.java index 9ade7b74..108287d1 100644 --- a/source/net/filebot/ui/sfv/ChecksumComputationService.java +++ b/source/net/filebot/ui/sfv/ChecksumComputationService.java @@ -53,7 +53,7 @@ class ChecksumComputationService { /** * Get the number of active executors that are associated with this {@link ChecksumComputationService}. - * + * * @return number of active executors * @see {@link #newExecutor()} */ diff --git a/source/net/filebot/ui/sfv/ChecksumRow.java b/source/net/filebot/ui/sfv/ChecksumRow.java index 0f995002..54be46ce 100644 --- a/source/net/filebot/ui/sfv/ChecksumRow.java +++ b/source/net/filebot/ui/sfv/ChecksumRow.java @@ -21,17 +21,17 @@ import net.filebot.hash.HashType; class ChecksumRow { - + private String name; - + private Map hashes = new HashMap(4); private State state = State.UNKNOWN; - + /** * Checksum that is embedded in the file name (e.g. Test[49A93C5F].txt) */ private String embeddedChecksum; - + public static enum State { UNKNOWN, @@ -39,72 +39,72 @@ class ChecksumRow { WARNING, ERROR } - + public ChecksumRow(String name) { this.name = name; this.embeddedChecksum = getEmbeddedChecksum(name); } - + public String getName() { return name; } - + public State getState() { return state; } - + protected void setState(State newValue) { State oldValue = this.state; this.state = newValue; - + pcs.firePropertyChange("state", oldValue, newValue); } - + public ChecksumCell getChecksum(File root) { return hashes.get(root); } - + public Collection values() { return Collections.unmodifiableCollection(hashes.values()); } - + public ChecksumCell put(ChecksumCell cell) { ChecksumCell old = hashes.put(cell.getRoot(), cell); - + // update state immediately, don't fire property change state = getState(hashes.values()); - + // keep state up-to-date cell.addPropertyChangeListener(updateStateListener); - + return old; } - + public void dispose() { // clear property change support for (PropertyChangeListener listener : pcs.getPropertyChangeListeners()) { pcs.removePropertyChangeListener(listener); } - + for (ChecksumCell cell : hashes.values()) { cell.dispose(); } - + name = null; embeddedChecksum = null; hashes = null; state = null; pcs = null; } - + protected State getState(Collection cells) { // check states before we bother comparing the hash values @@ -117,29 +117,29 @@ class ChecksumRow { return State.UNKNOWN; } } - + // compare hash values Set checksumSet = new HashSet(2); Set verdictSet = EnumSet.noneOf(State.class); - + for (HashType type : HashType.values()) { checksumSet.clear(); - + for (ChecksumCell cell : cells) { String checksum = cell.getChecksum(type); - + if (checksum != null) { checksumSet.add(checksum.toLowerCase()); } } - + verdictSet.add(getVerdict(checksumSet)); } - - // ERROR > WARNING > OK > UNKOWN + + // ERROR > WARNING > OK > UNKOWN return Collections.max(verdictSet); } - + protected State getVerdict(Set checksumSet) { if (checksumSet.size() < 1) { @@ -152,42 +152,43 @@ class ChecksumRow { // all hashes match if (embeddedChecksum != null) { String checksum = checksumSet.iterator().next(); - + if (checksum.length() == embeddedChecksum.length() && !checksum.equalsIgnoreCase(embeddedChecksum)) { return State.WARNING; } } - + return State.OK; } } - + @Override public String toString() { return String.format("%s %s %s", state, name, hashes); } - + private final PropertyChangeListener updateStateListener = new PropertyChangeListener() { - + + @Override public void propertyChange(PropertyChangeEvent evt) { if ("state".equals(evt.getPropertyName())) { setState(getState(hashes.values())); } } }; - + private SwingPropertyChangeSupport pcs = new SwingPropertyChangeSupport(this, true); - + public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } - + public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } - + } diff --git a/source/net/filebot/ui/sfv/ChecksumTable.java b/source/net/filebot/ui/sfv/ChecksumTable.java index b160fc54..42896702 100644 --- a/source/net/filebot/ui/sfv/ChecksumTable.java +++ b/source/net/filebot/ui/sfv/ChecksumTable.java @@ -16,46 +16,46 @@ import net.filebot.util.ui.SwingUI.DragDropRowTableUI; class ChecksumTable extends JTable { - + public ChecksumTable() { setFillsViewportHeight(true); setAutoCreateRowSorter(true); setAutoCreateColumnsFromModel(true); setAutoResizeMode(AUTO_RESIZE_SUBSEQUENT_COLUMNS); - + setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - + setRowHeight(20); - + setDragEnabled(true); setUI(new DragDropRowTableUI()); - + // force white background (e.g. gtk-laf default table background is gray) setBackground(Color.WHITE); - + // highlight CRC32 patterns in filenames in green and with smaller font-size setDefaultRenderer(String.class, new HighlightPatternCellRenderer(EMBEDDED_CHECKSUM)); setDefaultRenderer(ChecksumRow.State.class, new StateIconCellRenderer()); setDefaultRenderer(ChecksumCell.class, new ChecksumCellRenderer()); } - + @Override protected ChecksumTableModel createDefaultDataModel() { return new ChecksumTableModel(); } - + @Override protected JTableHeader createDefaultTableHeader() { return new JTableHeader(columnModel) { - + @Override public String getToolTipText(MouseEvent evt) { try { int columnIndex = columnModel.getColumnIndexAtX(evt.getX()); int modelIndex = columnModel.getColumn(columnIndex).getModelIndex(); - + // display column root of checksum column return getModel().getColumnRoot(modelIndex).getPath(); } catch (Exception e) { @@ -65,21 +65,21 @@ class ChecksumTable extends JTable { }; }; } - + @Override public ChecksumTableModel getModel() { return (ChecksumTableModel) super.getModel(); } - + @Override public void createDefaultColumnsFromModel() { super.createDefaultColumnsFromModel(); - + for (int i = 0; i < getColumnCount(); i++) { TableColumn column = getColumnModel().getColumn(i); - + if (i == 0) { column.setPreferredWidth(45); } else if (i == 1) { @@ -89,5 +89,5 @@ class ChecksumTable extends JTable { } } } - + } diff --git a/source/net/filebot/ui/sfv/ChecksumTableExportHandler.java b/source/net/filebot/ui/sfv/ChecksumTableExportHandler.java index 01d93c5d..1b574c64 100644 --- a/source/net/filebot/ui/sfv/ChecksumTableExportHandler.java +++ b/source/net/filebot/ui/sfv/ChecksumTableExportHandler.java @@ -13,32 +13,32 @@ import net.filebot.util.FileUtilities; class ChecksumTableExportHandler extends TextFileExportHandler { - + private final ChecksumTableModel model; - + public ChecksumTableExportHandler(ChecksumTableModel model) { this.model = model; } - + @Override public boolean canExport() { return model.getRowCount() > 0 && defaultColumn() != null; } - + @Override public void export(PrintWriter out) { export(new VerificationFileWriter(out, model.getHashType().getFormat(), "UTF-8"), defaultColumn(), model.getHashType()); } - + @Override public String getDefaultFileName() { return getDefaultFileName(defaultColumn()); } - + protected File defaultColumn() { // select first column that is not a verification file column @@ -46,46 +46,46 @@ class ChecksumTableExportHandler extends TextFileExportHandler { if (root.isDirectory()) return root; } - + return null; } - + public void export(File file, File column) throws IOException { VerificationFileWriter writer = new VerificationFileWriter(file, model.getHashType().getFormat(), "UTF-8"); - + try { export(writer, column, model.getHashType()); } finally { writer.close(); } } - + public void export(VerificationFileWriter out, File column, HashType type) { for (ChecksumRow row : model.rows()) { ChecksumCell cell = row.getChecksum(column); - + if (cell != null) { String hash = cell.getChecksum(type); - + if (hash != null) { out.write(cell.getName(), hash); } } } } - + public String getDefaultFileName(File column) { StringBuilder sb = new StringBuilder(); - + // append file name sb.append(column != null ? FileUtilities.getName(column) : "name"); - + // append file extension sb.append('.').append(model.getHashType().name().toLowerCase()); - + return sb.toString(); } } diff --git a/source/net/filebot/ui/sfv/ChecksumTableModel.java b/source/net/filebot/ui/sfv/ChecksumTableModel.java index 41e88243..377a6fb0 100644 --- a/source/net/filebot/ui/sfv/ChecksumTableModel.java +++ b/source/net/filebot/ui/sfv/ChecksumTableModel.java @@ -242,6 +242,7 @@ class ChecksumTableModel extends AbstractTableModel { private final PropertyChangeListener progressListener = new PropertyChangeListener() { + @Override public void propertyChange(PropertyChangeEvent evt) { ChecksumCell cell = (ChecksumCell) evt.getSource(); diff --git a/source/net/filebot/ui/sfv/HighlightPatternCellRenderer.java b/source/net/filebot/ui/sfv/HighlightPatternCellRenderer.java index bac15ac8..9c7c187f 100644 --- a/source/net/filebot/ui/sfv/HighlightPatternCellRenderer.java +++ b/source/net/filebot/ui/sfv/HighlightPatternCellRenderer.java @@ -17,63 +17,63 @@ import net.filebot.ui.sfv.ChecksumRow.State; * DefaultTableCellRenderer with highlighting of text patterns. */ class HighlightPatternCellRenderer extends DefaultTableCellRenderer { - + private final Pattern pattern; - - + + public HighlightPatternCellRenderer(Pattern pattern) { this.pattern = pattern; } - + @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, false, row, column); - + // check for error or warning boolean isError = (EnumSet.of(State.ERROR, State.WARNING).contains(table.getValueAt(row, 0))); - + // highlight patterns by using a smaller font-size and changing the font-color to a dark green // do not change the font-color if cell is selected, because that would look ugly (imagine green text on blue background ...) Matcher matcher = pattern.matcher(value.toString()); - + // use no-break, because we really don't want line-wrapping in our table cells StringBuffer htmlText = new StringBuffer(""); - + while (matcher.find()) { matcher.appendReplacement(htmlText, createReplacement(isSelected ? null : (isError ? "red" : "#009900"), "smaller", isError ? "bold" : null)); } - + matcher.appendTail(htmlText); - + htmlText.append(""); - + setText(htmlText.toString()); - + return this; } - + protected String createReplacement(String cssColor, String cssFontSize, String cssFontWeight) { // build replacement string like // e.g. $0 StringBuilder replacement = new StringBuilder(60); - + replacement.append("$0").toString(); } - + } diff --git a/source/net/filebot/ui/sfv/SfvPanelBuilder.java b/source/net/filebot/ui/sfv/SfvPanelBuilder.java index e22abda5..712e9412 100644 --- a/source/net/filebot/ui/sfv/SfvPanelBuilder.java +++ b/source/net/filebot/ui/sfv/SfvPanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class SfvPanelBuilder implements PanelBuilder { - + @Override public String getName() { return "SFV"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.sfv"); } - + @Override public JComponent create() { return new SfvPanel(); } - + } diff --git a/source/net/filebot/ui/sfv/StateIconCellRenderer.java b/source/net/filebot/ui/sfv/StateIconCellRenderer.java index 1bec997e..7548f53d 100644 --- a/source/net/filebot/ui/sfv/StateIconCellRenderer.java +++ b/source/net/filebot/ui/sfv/StateIconCellRenderer.java @@ -16,28 +16,28 @@ import net.filebot.ui.sfv.ChecksumRow.State; class StateIconCellRenderer extends DefaultTableCellRenderer { - + private final Map icons = new EnumMap(State.class); - - + + public StateIconCellRenderer() { icons.put(State.UNKNOWN, ResourceManager.getIcon("status.unknown")); icons.put(State.OK, ResourceManager.getIcon("status.ok")); icons.put(State.WARNING, ResourceManager.getIcon("status.warning")); icons.put(State.ERROR, ResourceManager.getIcon("status.error")); - + setVerticalAlignment(SwingConstants.CENTER); setHorizontalAlignment(SwingConstants.CENTER); } - + @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, null, isSelected, false, row, column); - + setIcon(icons.get(value)); - + return this; } - + } diff --git a/source/net/filebot/ui/sfv/SwingWorkerCellRenderer.java b/source/net/filebot/ui/sfv/SwingWorkerCellRenderer.java index 8e5ed212..89763cd5 100644 --- a/source/net/filebot/ui/sfv/SwingWorkerCellRenderer.java +++ b/source/net/filebot/ui/sfv/SwingWorkerCellRenderer.java @@ -15,31 +15,32 @@ import javax.swing.table.TableCellRenderer; class SwingWorkerCellRenderer extends JPanel implements TableCellRenderer { - + private final JProgressBar progressBar = new JProgressBar(0, 100); - + public SwingWorkerCellRenderer() { super(new BorderLayout()); - - // set margin for progress bar on parent component, + + // set margin for progress bar on parent component, // because setting it on the progress bar itself does not work (border size is not respected in the paint method) setBorder(new EmptyBorder(2, 2, 2, 2)); - + progressBar.setStringPainted(true); - + add(progressBar, BorderLayout.CENTER); } - + + @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); - + progressBar.setValue(((SwingWorker) value).getProgress()); - + return this; } - + /** * Overridden for performance reasons. @@ -47,7 +48,7 @@ class SwingWorkerCellRenderer extends JPanel implements TableCellRenderer { @Override public void repaint(long tm, int x, int y, int width, int height) { } - + /** * Overridden for performance reasons. @@ -55,7 +56,7 @@ class SwingWorkerCellRenderer extends JPanel implements TableCellRenderer { @Override public void repaint(Rectangle r) { } - + /** * Overridden for performance reasons. @@ -63,7 +64,7 @@ class SwingWorkerCellRenderer extends JPanel implements TableCellRenderer { @Override public void repaint() { } - + /** * Overridden for performance reasons. @@ -71,5 +72,5 @@ class SwingWorkerCellRenderer extends JPanel implements TableCellRenderer { @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } - + } diff --git a/source/net/filebot/ui/sfv/TotalProgressPanel.java b/source/net/filebot/ui/sfv/TotalProgressPanel.java index a71b038b..43f1c6ae 100644 --- a/source/net/filebot/ui/sfv/TotalProgressPanel.java +++ b/source/net/filebot/ui/sfv/TotalProgressPanel.java @@ -17,105 +17,107 @@ import net.miginfocom.swing.MigLayout; class TotalProgressPanel extends JComponent { - + private final JProgressBar progressBar = new JProgressBar(0, 0); - + private final int millisToSetVisible = 200; - - + + public TotalProgressPanel(ChecksumComputationService computationService) { setLayout(new MigLayout("insets 1px")); - + setBorder(new TitledBorder("Total Progress")); - + // invisible by default setVisible(false); - + progressBar.setStringPainted(true); - + add(progressBar, "growx"); - + computationService.addPropertyChangeListener(progressListener); } - + private final PropertyChangeListener progressListener = new PropertyChangeListener() { - + private static final String SHOW = "show"; private static final String HIDE = "hide"; - + private final DelayedToggle delayed = new DelayedToggle(); - - + + + @Override public void propertyChange(PropertyChangeEvent evt) { final int completedTaskCount = getComputationService(evt).getCompletedTaskCount(); final int totalTaskCount = getComputationService(evt).getTotalTaskCount(); - + // invoke on EDT SwingUtilities.invokeLater(new Runnable() { - + @Override public void run() { - + if (completedTaskCount == totalTaskCount) { // delayed hide on reset, immediate hide on finish delayed.toggle(HIDE, totalTaskCount == 0 ? millisToSetVisible : 0, visibilityActionHandler); } else if (totalTaskCount != 0) { delayed.toggle(SHOW, millisToSetVisible, visibilityActionHandler); } - + if (totalTaskCount != 0) { progressBar.setValue(completedTaskCount); progressBar.setMaximum(totalTaskCount); - + progressBar.setString(String.format("%d / %d", completedTaskCount, totalTaskCount)); } }; }); } - + private ChecksumComputationService getComputationService(PropertyChangeEvent evt) { return ((ChecksumComputationService) evt.getSource()); } - + private final ActionListener visibilityActionHandler = new ActionListener() { - + + @Override public void actionPerformed(ActionEvent e) { setVisible(e.getActionCommand() == SHOW); } }; - + }; - - + + protected static class DelayedToggle { - + private Timer timer = null; - - + + public void toggle(String action, int delay, final ActionListener actionHandler) { if (timer != null) { if (action.equals(timer.getActionCommand())) { // action has not changed, don't stop existing timer return; } - + timer.stop(); } - + timer = new Timer(delay, new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { actionHandler.actionPerformed(e); } }); - + timer.setActionCommand(action); timer.setRepeats(false); timer.start(); } - + } - + } diff --git a/source/net/filebot/ui/subtitle/MemoryFileListExportHandler.java b/source/net/filebot/ui/subtitle/MemoryFileListExportHandler.java index 14ff26f0..6d4d0484 100644 --- a/source/net/filebot/ui/subtitle/MemoryFileListExportHandler.java +++ b/source/net/filebot/ui/subtitle/MemoryFileListExportHandler.java @@ -21,29 +21,29 @@ import net.filebot.vfs.MemoryFile; class MemoryFileListExportHandler implements TransferableExportHandler, ClipboardHandler { - + public boolean canExport(JComponent component) { JList list = (JList) component; - + // can't export anything, if nothing is selected return !list.isSelectionEmpty(); } - + public List export(JComponent component) { JList list = (JList) component; - + // get selected values final Object[] selection = list.getSelectedValues(); - + // as file list return new AbstractList() { - + @Override public MemoryFile get(int index) { return (MemoryFile) selection[index]; } - + @Override public int size() { @@ -51,35 +51,35 @@ class MemoryFileListExportHandler implements TransferableExportHandler, Clipboar } }; } - + @Override public int getSourceActions(JComponent component) { return canExport(component) ? TransferHandler.COPY_OR_MOVE : TransferHandler.NONE; } - + @Override public Transferable createTransferable(JComponent component) { Map vfs = new HashMap(); - + for (MemoryFile file : export(component)) { vfs.put(file.getName(), file.getData()); } - + return new ByteBufferTransferable(vfs); } - + @Override public void exportToClipboard(JComponent component, Clipboard clip, int action) { clip.setContents(createTransferable(component), null); } - + @Override public void exportDone(JComponent source, Transferable data, int action) { - + } - + } diff --git a/source/net/filebot/ui/subtitle/SubtitleDropTarget.java b/source/net/filebot/ui/subtitle/SubtitleDropTarget.java index 144e34d5..c9ecfb53 100644 --- a/source/net/filebot/ui/subtitle/SubtitleDropTarget.java +++ b/source/net/filebot/ui/subtitle/SubtitleDropTarget.java @@ -216,6 +216,7 @@ abstract class SubtitleDropTarget extends JButton { return true; } + @Override protected Icon getIcon(DropAction dropAction) { switch (dropAction) { case Accept: @@ -307,6 +308,7 @@ abstract class SubtitleDropTarget extends JButton { return null; } + @Override protected Icon getIcon(DropAction dropAction) { if (dropAction == DropAction.Accept) return ResourceManager.getIcon("subtitle.exact.upload"); diff --git a/source/net/filebot/ui/subtitle/SubtitleFileChooser.java b/source/net/filebot/ui/subtitle/SubtitleFileChooser.java index d12c37e6..6ff50122 100644 --- a/source/net/filebot/ui/subtitle/SubtitleFileChooser.java +++ b/source/net/filebot/ui/subtitle/SubtitleFileChooser.java @@ -22,31 +22,31 @@ import net.miginfocom.swing.MigLayout; public class SubtitleFileChooser extends JFileChooser { - + protected final JComboBox format = new JComboBox(); protected final JComboBox encoding = new JComboBox(); protected final JSpinner offset = new JSpinner(new SpinnerNumberModel(0, -14400000, 14400000, 100)); - + public SubtitleFileChooser() { setAccessory(createAcessory()); setDefaultOptions(); } - + protected void setDefaultOptions() { setFormatOptions(singleton(SubtitleFormat.SubRip)); - + Set encodings = new LinkedHashSet(2); encodings.add(Charset.forName("UTF-8")); // UTF-8 as default charset encodings.add(Charset.defaultCharset()); // allow default system encoding to be used as well setEncodingOptions(encodings); } - + protected JComponent createAcessory() { JPanel acessory = new JPanel(new MigLayout("nogrid")); - + acessory.add(new JLabel("Encoding:"), "wrap rel"); acessory.add(encoding, "sg w, wrap para"); acessory.add(new JLabel("Format:"), "wrap rel"); @@ -54,30 +54,30 @@ public class SubtitleFileChooser extends JFileChooser { acessory.add(new JLabel("Timing Offset:"), "wrap rel"); acessory.add(offset, "wmax 50px"); acessory.add(new JLabel("ms")); - + return acessory; } - + public void setEncodingOptions(Set options) { encoding.setModel(new DefaultComboBoxModel(options.toArray())); } - + public Charset getSelectedEncoding() { return (Charset) encoding.getSelectedItem(); } - + public void setFormatOptions(Set options) { format.setModel(new DefaultComboBoxModel(options.toArray())); } - + public SubtitleFormat getSelectedFormat() { return (SubtitleFormat) format.getSelectedItem(); } - + public long getTimingOffset() { return (Integer) offset.getValue(); diff --git a/source/net/filebot/ui/subtitle/SubtitlePackageCellRenderer.java b/source/net/filebot/ui/subtitle/SubtitlePackageCellRenderer.java index 246c8178..33423895 100644 --- a/source/net/filebot/ui/subtitle/SubtitlePackageCellRenderer.java +++ b/source/net/filebot/ui/subtitle/SubtitlePackageCellRenderer.java @@ -17,69 +17,69 @@ import net.miginfocom.swing.MigLayout; class SubtitlePackageCellRenderer extends AbstractFancyListCellRenderer { - + private final JLabel titleLabel = new JLabel(); private final JLabel languageLabel = new JLabel(); - + public SubtitlePackageCellRenderer() { super(new Insets(5, 5, 5, 5)); setHighlightingEnabled(false); - + setLayout(new MigLayout("fill, nogrid, insets 0")); - + add(languageLabel, "hidemode 3, w 85px!"); add(titleLabel); - + setBorder(new CompoundBorder(new DashedSeparator(2, 4, Color.lightGray, Color.white), getBorder())); } - + @Override public void configureListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.configureListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - + SubtitlePackage subtitle = (SubtitlePackage) value; - + titleLabel.setText(subtitle.getName()); titleLabel.setIcon(getIcon(subtitle)); - + if (languageLabel.isVisible()) { languageLabel.setText(subtitle.getLanguage().getName()); languageLabel.setIcon(ResourceManager.getFlagIcon(subtitle.getLanguage().getCode())); } - + titleLabel.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); languageLabel.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); - + // don't paint border on last element setBorderPainted(index < list.getModel().getSize() - 1); } - + private Icon getIcon(SubtitlePackage subtitle) { switch (subtitle.getDownload().getPhase()) { - case PENDING: - return ResourceManager.getIcon("bullet.green"); - case WAITING: - return ResourceManager.getIcon("worker.pending"); - case DOWNLOADING: - return ResourceManager.getIcon("package.fetch"); - case EXTRACTING: - return ResourceManager.getIcon("package.extract"); - case DONE: - return ResourceManager.getIcon("status.ok"); + case PENDING: + return ResourceManager.getIcon("bullet.green"); + case WAITING: + return ResourceManager.getIcon("worker.pending"); + case DOWNLOADING: + return ResourceManager.getIcon("package.fetch"); + case EXTRACTING: + return ResourceManager.getIcon("package.extract"); + case DONE: + return ResourceManager.getIcon("status.ok"); } - + // unreachable return null; } - + public JLabel getLanguageLabel() { return languageLabel; } - + @Override public void validate() { @@ -88,5 +88,5 @@ class SubtitlePackageCellRenderer extends AbstractFancyListCellRenderer { validateTree(); } } - + } diff --git a/source/net/filebot/ui/subtitle/SubtitlePanel.java b/source/net/filebot/ui/subtitle/SubtitlePanel.java index 6ca6a497..54e23885 100644 --- a/source/net/filebot/ui/subtitle/SubtitlePanel.java +++ b/source/net/filebot/ui/subtitle/SubtitlePanel.java @@ -73,6 +73,7 @@ public class SubtitlePanel extends AbstractSearchPanel getHistory(SubtitleProvider engine) throws Exception { List names = new ArrayList(); for (SubtitleSearchResult it : MediaDetection.releaseInfo.getOpenSubtitlesIndex()) { diff --git a/source/net/filebot/ui/subtitle/SubtitlePanelBuilder.java b/source/net/filebot/ui/subtitle/SubtitlePanelBuilder.java index 49bf07a3..262ffa71 100644 --- a/source/net/filebot/ui/subtitle/SubtitlePanelBuilder.java +++ b/source/net/filebot/ui/subtitle/SubtitlePanelBuilder.java @@ -10,22 +10,22 @@ import net.filebot.ui.PanelBuilder; public class SubtitlePanelBuilder implements PanelBuilder { - + @Override public String getName() { return "Subtitles"; } - + @Override public Icon getIcon() { return ResourceManager.getIcon("panel.subtitle"); } - + @Override public JComponent create() { return new SubtitlePanel(); } - + } diff --git a/source/net/filebot/ui/subtitle/SubtitleUploadDialog.java b/source/net/filebot/ui/subtitle/SubtitleUploadDialog.java index 6a590d65..3cb7fe04 100644 --- a/source/net/filebot/ui/subtitle/SubtitleUploadDialog.java +++ b/source/net/filebot/ui/subtitle/SubtitleUploadDialog.java @@ -61,7 +61,6 @@ import net.filebot.web.Movie; import net.filebot.web.OpenSubtitlesClient; import net.filebot.web.SearchResult; import net.filebot.web.SubtitleSearchResult; -import net.filebot.web.TheTVDBSearchResult; import net.filebot.web.TheTVDBSeriesInfo; import net.filebot.web.VideoHashSubtitleService.CheckResult; import net.miginfocom.swing.MigLayout; @@ -690,7 +689,7 @@ public class SubtitleUploadDialog extends JDialog { for (String name : seriesNames) { List options = WebServices.TheTVDB.search(name, Locale.ENGLISH); for (SearchResult entry : options) { - TheTVDBSeriesInfo seriesInfo = (TheTVDBSeriesInfo) WebServices.TheTVDB.getSeriesInfo((TheTVDBSearchResult) entry, Locale.ENGLISH); + TheTVDBSeriesInfo seriesInfo = (TheTVDBSeriesInfo) WebServices.TheTVDB.getSeriesInfo(entry, Locale.ENGLISH); if (seriesInfo.getImdbId() != null) { int imdbId = grepImdbId(seriesInfo.getImdbId()).iterator().next(); mapping.setIdentity(WebServices.OpenSubtitles.getMovieDescriptor(new Movie(null, 0, imdbId, -1), Locale.ENGLISH)); diff --git a/source/net/filebot/ui/transfer/ArrayTransferable.java b/source/net/filebot/ui/transfer/ArrayTransferable.java index 5c52e0c9..5a1cbe27 100644 --- a/source/net/filebot/ui/transfer/ArrayTransferable.java +++ b/source/net/filebot/ui/transfer/ArrayTransferable.java @@ -10,38 +10,38 @@ import java.lang.reflect.Array; public class ArrayTransferable implements Transferable { - + public static DataFlavor flavor(Class componentType) { return new DataFlavor(Array.newInstance(componentType, 0).getClass(), "Array"); } - + private final T[] array; - - + + public ArrayTransferable(T... array) { this.array = array; } - + @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) { return array; } - + return null; } - + @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { new DataFlavor(array.getClass(), "Array") }; } - + @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return array.getClass().equals(flavor.getRepresentationClass()); } - + } diff --git a/source/net/filebot/ui/transfer/ClipboardHandler.java b/source/net/filebot/ui/transfer/ClipboardHandler.java index e3ef168c..859eae0b 100644 --- a/source/net/filebot/ui/transfer/ClipboardHandler.java +++ b/source/net/filebot/ui/transfer/ClipboardHandler.java @@ -8,7 +8,7 @@ import javax.swing.JComponent; public interface ClipboardHandler { - + public void exportToClipboard(JComponent comp, Clipboard clip, int action) throws IllegalStateException; - + } diff --git a/source/net/filebot/ui/transfer/CompositeTranserable.java b/source/net/filebot/ui/transfer/CompositeTranserable.java index 3fbf1349..724e2eda 100644 --- a/source/net/filebot/ui/transfer/CompositeTranserable.java +++ b/source/net/filebot/ui/transfer/CompositeTranserable.java @@ -12,55 +12,55 @@ import java.util.Collections; public class CompositeTranserable implements Transferable { - + private final Transferable[] transferables; - + private final DataFlavor[] flavors; - - + + public CompositeTranserable(Transferable... transferables) { this.transferables = transferables; - + Collection flavors = new ArrayList(); - + for (Transferable transferable : transferables) { Collections.addAll(flavors, transferable.getTransferDataFlavors()); } - + this.flavors = flavors.toArray(new DataFlavor[0]); } - + @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { Transferable transferable = getTransferable(flavor); - + if (transferable == null) return null; - + return transferable.getTransferData(flavor); } - + @Override public DataFlavor[] getTransferDataFlavors() { return flavors; } - + @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return getTransferable(flavor) != null; } - + protected Transferable getTransferable(DataFlavor flavor) { for (Transferable transferable : transferables) { if (transferable.isDataFlavorSupported(flavor)) return transferable; } - + return null; } - + } diff --git a/source/net/filebot/ui/transfer/DefaultClipboardHandler.java b/source/net/filebot/ui/transfer/DefaultClipboardHandler.java index b110fdbb..209816eb 100644 --- a/source/net/filebot/ui/transfer/DefaultClipboardHandler.java +++ b/source/net/filebot/ui/transfer/DefaultClipboardHandler.java @@ -13,14 +13,14 @@ import javax.swing.tree.TreePath; public class DefaultClipboardHandler implements ClipboardHandler { - + protected final String newLine = System.getProperty("line.separator"); - - + + @Override public void exportToClipboard(JComponent component, Clipboard clip, int action) throws IllegalStateException { StringBuilder sb = new StringBuilder(); - + if (component instanceof JList) { export(sb, (JList) component); } else if (component instanceof JTree) { @@ -28,52 +28,52 @@ public class DefaultClipboardHandler implements ClipboardHandler { } else if (component instanceof JTable) { export(sb, (JTable) component); } - + clip.setContents(new StringSelection(sb.toString()), null); } - + protected void export(StringBuilder sb, JList list) { for (Object value : list.getSelectedValues()) { sb.append(value == null ? "" : value).append(newLine); } - + // delete last newline sb.delete(sb.length() - newLine.length(), sb.length()); } - + protected void export(StringBuilder sb, JTree tree) { for (TreePath path : tree.getSelectionPaths()) { Object value = path.getLastPathComponent(); - + sb.append(value == null ? "" : value).append(newLine); } - + // delete last newline sb.delete(sb.length() - newLine.length(), sb.length()); } - + protected void export(StringBuilder sb, JTable table) { for (int row : table.getSelectedRows()) { int modelRow = table.getRowSorter().convertRowIndexToModel(row); - + for (int column = 0; column < table.getColumnCount(); column++) { Object value = table.getModel().getValueAt(modelRow, column); - + if (value != null) { sb.append(value); } - + if (column < table.getColumnCount() - 1) { sb.append("\t"); } } - + sb.append(newLine); } - + // delete last newline sb.delete(sb.length() - newLine.length(), sb.length()); } diff --git a/source/net/filebot/ui/transfer/DefaultTransferHandler.java b/source/net/filebot/ui/transfer/DefaultTransferHandler.java index c5028be3..5836c7af 100644 --- a/source/net/filebot/ui/transfer/DefaultTransferHandler.java +++ b/source/net/filebot/ui/transfer/DefaultTransferHandler.java @@ -10,117 +10,117 @@ import javax.swing.TransferHandler; public class DefaultTransferHandler extends TransferHandler { - + private TransferablePolicy transferablePolicy; private TransferableExportHandler exportHandler; private ClipboardHandler clipboardHandler; - + private boolean dragging = false; - - + + public DefaultTransferHandler(TransferablePolicy transferablePolicy, TransferableExportHandler exportHandler) { this(transferablePolicy, exportHandler, new DefaultClipboardHandler()); } - + public DefaultTransferHandler(TransferablePolicy transferablePolicy, TransferableExportHandler exportHandler, ClipboardHandler clipboardHandler) { this.transferablePolicy = transferablePolicy; this.exportHandler = exportHandler; this.clipboardHandler = clipboardHandler; } - + @Override public boolean canImport(TransferSupport support) { // show "drop allowed" cursor when dragging even though drop is not allowed if (dragging) return true; - + if (transferablePolicy != null) return transferablePolicy.canImport(support); - + return false; } - + @Override public boolean importData(TransferSupport support) { if (dragging) return false; - + if (!canImport(support)) return false; - + return transferablePolicy.importData(support); } - + @Override protected void exportDone(JComponent source, Transferable data, int action) { dragging = false; - + if (data == null) return; - + if (exportHandler != null) exportHandler.exportDone(source, data, action); } - + @Override public int getSourceActions(JComponent c) { if (exportHandler != null) return exportHandler.getSourceActions(c); - + return NONE; } - + @Override protected Transferable createTransferable(JComponent c) { dragging = true; - + if (exportHandler != null) return exportHandler.createTransferable(c); - + return null; } - + @Override public void exportToClipboard(JComponent comp, Clipboard clip, int action) throws IllegalStateException { if (clipboardHandler != null) clipboardHandler.exportToClipboard(comp, clip, action); } - + public TransferablePolicy getTransferablePolicy() { return transferablePolicy; } - + public void setTransferablePolicy(TransferablePolicy transferablePolicy) { this.transferablePolicy = transferablePolicy; } - + public TransferableExportHandler getExportHandler() { return exportHandler; } - + public void setExportHandler(TransferableExportHandler exportHandler) { this.exportHandler = exportHandler; } - + public ClipboardHandler getClipboardHandler() { return clipboardHandler; } - + public void setClipboardHandler(ClipboardHandler clipboardHandler) { this.clipboardHandler = clipboardHandler; } - + } diff --git a/source/net/filebot/ui/transfer/FileExportHandler.java b/source/net/filebot/ui/transfer/FileExportHandler.java index 9cd172ac..d597c84a 100644 --- a/source/net/filebot/ui/transfer/FileExportHandler.java +++ b/source/net/filebot/ui/transfer/FileExportHandler.java @@ -7,13 +7,13 @@ import java.io.IOException; public interface FileExportHandler { - + public boolean canExport(); - + public void export(File file) throws IOException; - + public String getDefaultFileName(); - + } diff --git a/source/net/filebot/ui/transfer/LoadAction.java b/source/net/filebot/ui/transfer/LoadAction.java index d19ae8b5..6632b4b0 100644 --- a/source/net/filebot/ui/transfer/LoadAction.java +++ b/source/net/filebot/ui/transfer/LoadAction.java @@ -39,6 +39,7 @@ public class LoadAction extends AbstractAction { return null; } + @Override public void actionPerformed(ActionEvent evt) { try { // get transferable policy from action properties diff --git a/source/net/filebot/ui/transfer/SaveAction.java b/source/net/filebot/ui/transfer/SaveAction.java index 6c3627d0..17514e2b 100644 --- a/source/net/filebot/ui/transfer/SaveAction.java +++ b/source/net/filebot/ui/transfer/SaveAction.java @@ -45,6 +45,7 @@ public class SaveAction extends AbstractAction { return new File(validateFileName(getExportHandler().getDefaultFileName())); } + @Override public void actionPerformed(ActionEvent evt) { try { if (canExport()) { diff --git a/source/net/filebot/ui/transfer/TextFileExportHandler.java b/source/net/filebot/ui/transfer/TextFileExportHandler.java index 75da2474..078a03f1 100644 --- a/source/net/filebot/ui/transfer/TextFileExportHandler.java +++ b/source/net/filebot/ui/transfer/TextFileExportHandler.java @@ -13,47 +13,49 @@ import javax.swing.TransferHandler; public abstract class TextFileExportHandler implements TransferableExportHandler, FileExportHandler { - + + @Override public abstract boolean canExport(); - + public abstract void export(PrintWriter out); - + + @Override public abstract String getDefaultFileName(); - + @Override public void export(File file) throws IOException { PrintWriter out = new PrintWriter(file, "UTF-8"); - + try { export(out); } finally { out.close(); } } - + @Override public int getSourceActions(JComponent c) { return canExport() ? TransferHandler.COPY_OR_MOVE : TransferHandler.NONE; } - + @Override public Transferable createTransferable(JComponent c) { // get transfer data StringWriter buffer = new StringWriter(); export(new PrintWriter(buffer)); - + return new TextFileTransferable(getDefaultFileName(), buffer.toString()); } - + @Override public void exportDone(JComponent source, Transferable data, int action) { - + } - + } diff --git a/source/net/filebot/ui/transfer/TextFileTransferable.java b/source/net/filebot/ui/transfer/TextFileTransferable.java index f5a7c933..ec188cd9 100644 --- a/source/net/filebot/ui/transfer/TextFileTransferable.java +++ b/source/net/filebot/ui/transfer/TextFileTransferable.java @@ -12,33 +12,33 @@ import java.util.Set; public class TextFileTransferable extends ByteBufferTransferable { - + private final String text; - + public TextFileTransferable(String name, String text) { this(name, text, Charset.forName("UTF-8")); } - + public TextFileTransferable(final String name, final String text, final Charset charset) { // lazy data map for file transfer super(new AbstractMap() { - + @Override public Set> entrySet() { // encode text Entry entry = new SimpleEntry(name, charset.encode(text)); - + // return memory file entry return Collections.singleton(entry); } }); - + // text transfer this.text = text; } - + @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { @@ -46,15 +46,15 @@ public class TextFileTransferable extends ByteBufferTransferable { if (super.isDataFlavorSupported(flavor)) { return super.getTransferData(flavor); } - + // check text flavor if (flavor.isFlavorTextType()) { return text; } - + throw new UnsupportedFlavorException(flavor); } - + @Override public DataFlavor[] getTransferDataFlavors() { @@ -62,12 +62,12 @@ public class TextFileTransferable extends ByteBufferTransferable { DataFlavor.javaFileListFlavor, FileTransferable.uriListFlavor, DataFlavor.stringFlavor }; } - + @Override public boolean isDataFlavorSupported(DataFlavor flavor) { // file flavor or text flavor return super.isDataFlavorSupported(flavor) || flavor.isFlavorTextType(); } - + } diff --git a/source/net/filebot/ui/transfer/TransferableExportHandler.java b/source/net/filebot/ui/transfer/TransferableExportHandler.java index 00145894..f839a765 100644 --- a/source/net/filebot/ui/transfer/TransferableExportHandler.java +++ b/source/net/filebot/ui/transfer/TransferableExportHandler.java @@ -8,13 +8,13 @@ import javax.swing.JComponent; public interface TransferableExportHandler { - + public Transferable createTransferable(JComponent c); - + public int getSourceActions(JComponent c); - + public void exportDone(JComponent source, Transferable data, int action); - + } diff --git a/source/net/filebot/ui/transfer/TransferablePolicy.java b/source/net/filebot/ui/transfer/TransferablePolicy.java index 236ad34e..bae8ae86 100644 --- a/source/net/filebot/ui/transfer/TransferablePolicy.java +++ b/source/net/filebot/ui/transfer/TransferablePolicy.java @@ -12,24 +12,24 @@ import javax.swing.TransferHandler.TransferSupport; public abstract class TransferablePolicy { - + public abstract boolean accept(Transferable tr) throws Exception; - - + + public abstract void handleTransferable(Transferable tr, TransferAction action) throws Exception; - - + + public boolean canImport(TransferSupport support) { if (support.isDrop()) { support.setShowDropLocation(false); } - + try { return accept(support.getTransferable()); } catch (InvalidDnDOperationException e) { // final drop may cause this exception because, the transfer data can only be accessed // *after* the drop has been accepted, but canImport is called before that - + // just assume that the transferable will be accepted, accept will be called in importData again anyway return true; } catch (Exception e) { @@ -37,11 +37,11 @@ public abstract class TransferablePolicy { return false; } } - - + + public boolean importData(TransferSupport support) { Transferable transferable = support.getTransferable(); - + try { if (accept(transferable)) { handleTransferable(transferable, getTransferAction(support)); @@ -50,49 +50,49 @@ public abstract class TransferablePolicy { } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.WARNING, e.toString(), e); } - - // transferable was not accepted, or transfer failed + + // transferable was not accepted, or transfer failed return false; } - - + + protected TransferAction getTransferAction(TransferSupport support) { if (support.isDrop()) { return TransferAction.fromDnDConstant(support.getDropAction()); } - + // use PUT by default (e.g. clipboard transfers) return TransferAction.PUT; } - - + + public static enum TransferAction { PUT(TransferHandler.MOVE), ADD(TransferHandler.COPY), LINK(TransferHandler.LINK); - + private final int dndConstant; - - + + private TransferAction(int dndConstant) { this.dndConstant = dndConstant; } - - + + public int getDnDConstant() { return dndConstant; } - - + + public static TransferAction fromDnDConstant(int dndConstant) { for (TransferAction action : values()) { if (dndConstant == action.dndConstant) return action; } - + throw new IllegalArgumentException("Unsupported dndConstant: " + dndConstant); } - + } - + } diff --git a/source/net/filebot/util/ByteBufferInputStream.java b/source/net/filebot/util/ByteBufferInputStream.java index 40be5d75..65ceadc0 100644 --- a/source/net/filebot/util/ByteBufferInputStream.java +++ b/source/net/filebot/util/ByteBufferInputStream.java @@ -8,21 +8,21 @@ import java.nio.ByteBuffer; public class ByteBufferInputStream extends InputStream { - + private final ByteBuffer buffer; - - + + public ByteBufferInputStream(ByteBuffer buffer) { this.buffer = buffer; } - - + + @Override public int read() throws IOException { return (buffer.position() < buffer.limit()) ? (buffer.get() & 0xff) : -1; } - - + + @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { @@ -30,45 +30,45 @@ public class ByteBufferInputStream extends InputStream { } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } - + if (buffer.position() >= buffer.limit()) { return -1; } - + if (len > buffer.remaining()) { len = buffer.remaining(); } - + if (len <= 0) { return 0; } - + buffer.get(b, off, len); return len; } - - + + @Override public int available() throws IOException { return buffer.remaining(); } - - + + @Override public boolean markSupported() { return true; } - - + + @Override public void mark(int readlimit) { buffer.mark(); } - - + + @Override public void reset() throws IOException { buffer.reset(); } - + } diff --git a/source/net/filebot/util/DefaultThreadFactory.java b/source/net/filebot/util/DefaultThreadFactory.java index 816e0578..b2b439c1 100644 --- a/source/net/filebot/util/DefaultThreadFactory.java +++ b/source/net/filebot/util/DefaultThreadFactory.java @@ -7,50 +7,51 @@ import java.util.concurrent.atomic.AtomicInteger; public class DefaultThreadFactory implements ThreadFactory { - + private final AtomicInteger threadNumber = new AtomicInteger(0); private final ThreadGroup group; - + private final int priority; private final boolean daemon; - - + + public DefaultThreadFactory(String name) { this(name, Thread.NORM_PRIORITY); } - + public DefaultThreadFactory(String name, int priority) { this(name, priority, false); } - + public DefaultThreadFactory(String groupName, int priority, boolean daemon) { SecurityManager sm = System.getSecurityManager(); ThreadGroup parentGroup = (sm != null) ? sm.getThreadGroup() : Thread.currentThread().getThreadGroup(); - + this.group = new ThreadGroup(parentGroup, groupName); - + this.daemon = daemon; this.priority = priority; } - + + @Override public Thread newThread(Runnable r) { Thread thread = new Thread(group, r, String.format("%s-thread-%d", group.getName(), threadNumber.incrementAndGet())); - + if (daemon != thread.isDaemon()) thread.setDaemon(daemon); - + if (priority != thread.getPriority()) thread.setPriority(priority); - + return thread; } - + public ThreadGroup getThreadGroup() { return group; } - + } diff --git a/source/net/filebot/util/FileUtilities.java b/source/net/filebot/util/FileUtilities.java index ad992b56..3321c749 100644 --- a/source/net/filebot/util/FileUtilities.java +++ b/source/net/filebot/util/FileUtilities.java @@ -262,7 +262,7 @@ public final class FileUtilities { /** * Pattern used for matching file extensions. - * + * * e.g. "file.txt" -> match "txt", ".hidden" -> no match */ public static final Pattern EXTENSION = Pattern.compile("(?<=.[.])\\p{Alnum}+$"); @@ -567,7 +567,7 @@ public final class FileUtilities { /** * Strip file name of invalid characters - * + * * @param filename * original filename * @return valid file name stripped of invalid characters diff --git a/source/net/filebot/util/FilterIterator.java b/source/net/filebot/util/FilterIterator.java index 43437991..c9fa3d18 100644 --- a/source/net/filebot/util/FilterIterator.java +++ b/source/net/filebot/util/FilterIterator.java @@ -6,25 +6,25 @@ import java.util.Iterator; public abstract class FilterIterator implements Iterator { - + private final Iterator sourceIterator; - - + + public FilterIterator(Iterable source) { this(source.iterator()); } - + public FilterIterator(Iterator sourceIterator) { this.sourceIterator = sourceIterator; } - + @Override public boolean hasNext() { return peekNext(false) != null; } - + @Override public T next() { @@ -34,25 +34,25 @@ public abstract class FilterIterator implements Iterator { current = null; } } - + private T current = null; - - + + private T peekNext(boolean forceNext) { while (current == null && (forceNext || (sourceIterator.hasNext()))) { current = filter(sourceIterator.next()); } - + return current; } - + protected abstract T filter(S sourceValue); - + @Override public void remove() { sourceIterator.remove(); } - + } diff --git a/source/net/filebot/util/ListChangeSynchronizer.java b/source/net/filebot/util/ListChangeSynchronizer.java index 0e31cbad..675f0b26 100644 --- a/source/net/filebot/util/ListChangeSynchronizer.java +++ b/source/net/filebot/util/ListChangeSynchronizer.java @@ -10,41 +10,42 @@ import ca.odell.glazedlists.event.ListEventListener; public class ListChangeSynchronizer implements ListEventListener { - + private final List target; - - + + public ListChangeSynchronizer(EventList source, List target) { this.target = target; source.addListEventListener(this); } - + + @Override public void listChanged(ListEvent listChanges) { EventList source = listChanges.getSourceList(); - + // update target list while (listChanges.next()) { int index = listChanges.getIndex(); int type = listChanges.getType(); - + switch (type) { - case ListEvent.INSERT: - target.add(index, source.get(index)); - break; - case ListEvent.UPDATE: - target.set(index, source.get(index)); - break; - case ListEvent.DELETE: - target.remove(index); - break; + case ListEvent.INSERT: + target.add(index, source.get(index)); + break; + case ListEvent.UPDATE: + target.set(index, source.get(index)); + break; + case ListEvent.DELETE: + target.remove(index); + break; } } } - + public static ListChangeSynchronizer syncEventListToList(EventList source, List target) { return new ListChangeSynchronizer(source, target); } - + } diff --git a/source/net/filebot/util/PreferencesList.java b/source/net/filebot/util/PreferencesList.java index fcb328a5..acd8abcb 100644 --- a/source/net/filebot/util/PreferencesList.java +++ b/source/net/filebot/util/PreferencesList.java @@ -13,56 +13,56 @@ import net.filebot.util.PreferencesMap.Adapter; public class PreferencesList extends AbstractList implements RandomAccess { - + private final PreferencesMap prefs; - + public PreferencesList(PreferencesMap preferencesMap) { this.prefs = preferencesMap; } - + @Override public T get(int index) { return prefs.get(key(index)); } - + private String key(int index) { return Integer.toString(index); } - + @Override public int size() { return prefs.size(); } - + @Override public boolean add(T e) { setImpl(size(), e); return true; } - + @Override public void add(int index, T element) { int size = size(); - + if (index > size) throw new IndexOutOfBoundsException(String.format("Index: %d, Size: %d", index, size)); - + copy(index, index + 1, size - index); - + setImpl(index, element); } - + private T setImpl(int index, T element) { return prefs.put(key(index), element); } - + /** * @return always null @@ -70,67 +70,67 @@ public class PreferencesList extends AbstractList implements RandomAccess @Override public T remove(int index) { int lastIndex = size() - 1; - + copy(index + 1, index, lastIndex - index); prefs.remove(key(lastIndex)); - + return null; } - + @Override public T set(int index, T element) { if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(); - + return setImpl(index, element); } - + private void copy(int startIndex, int newStartIndex, int count) { if (count == 0 || startIndex == newStartIndex) return; - + List copy = new ArrayList(subList(startIndex, startIndex + count)); - + for (int i = newStartIndex, n = 0; n < count; i++, n++) { setImpl(i, copy.get(n)); } } - + public void trimToSize(int limit) { for (int i = size() - 1; i >= limit; i--) { remove(i); } } - + public void set(Collection data) { // remove all elements beyond data.size trimToSize(data.size()); - + // override elements int i = 0; for (T element : data) { setImpl(i++, element); } } - + @Override public void clear() { prefs.clear(); } - + public static PreferencesList map(Preferences prefs) { return new PreferencesList(PreferencesMap.map(prefs)); } - + public static PreferencesList map(Preferences prefs, Adapter adapter) { return new PreferencesList(PreferencesMap.map(prefs, adapter)); } - + } diff --git a/source/net/filebot/util/PreferencesMap.java b/source/net/filebot/util/PreferencesMap.java index 6c053436..f535d21e 100644 --- a/source/net/filebot/util/PreferencesMap.java +++ b/source/net/filebot/util/PreferencesMap.java @@ -22,41 +22,41 @@ import java.util.prefs.Preferences; public class PreferencesMap implements Map { - + private final Preferences prefs; private final Adapter adapter; - - + + public PreferencesMap(Preferences prefs, Adapter adapter) { this.prefs = prefs; this.adapter = adapter; } - - + + @Override public T get(Object key) { return adapter.get(prefs, key.toString()); } - - + + @Override public T put(String key, T value) { adapter.put(prefs, key, value); - + // don't know previous entry return null; } - - + + @Override public T remove(Object key) { adapter.remove(prefs, key.toString()); - + // don't know removed entry return null; } - - + + public String[] keys() { try { return adapter.keys(prefs); @@ -64,157 +64,157 @@ public class PreferencesMap implements Map { throw new RuntimeException(e); } } - - + + @Override public void clear() { for (String key : keys()) { adapter.remove(prefs, key); } } - - + + @Override public boolean containsKey(Object key) { if (key instanceof String) { return Arrays.asList(keys()).contains(key); } - + return false; } - - + + @Override public boolean containsValue(Object value) { for (String key : keys()) { if (value.equals(get(key))) return true; } - + return false; } - - + + @Override public Set> entrySet() { Set> entries = new LinkedHashSet>(); - + for (String key : keys()) { entries.add(new PreferencesEntry(prefs, key, adapter)); } - + return entries; } - - + + @Override public boolean isEmpty() { return size() == 0; } - - + + @Override public Set keySet() { return new LinkedHashSet(Arrays.asList(keys())); } - - + + @Override public void putAll(Map map) { for (Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } - - + + @Override public int size() { return keys().length; } - - + + @Override public Collection values() { List values = new ArrayList(); - + for (String key : keys()) { values.add(get(key)); } - + return values; } - - + + public static PreferencesMap map(Preferences prefs) { return map(prefs, new StringAdapter()); } - - + + public static PreferencesMap map(Preferences prefs, Adapter adapter) { return new PreferencesMap(prefs, adapter); } - - + + public static interface Adapter { - + public String[] keys(Preferences prefs) throws BackingStoreException; - - + + public T get(Preferences prefs, String key); - - + + public void put(Preferences prefs, String key, T value); - - + + public void remove(Preferences prefs, String key); } - - + + public static abstract class AbstractAdapter implements Adapter { - + @Override public abstract T get(Preferences prefs, String key); - - + + @Override public abstract void put(Preferences prefs, String key, T value); - - + + @Override public String[] keys(Preferences prefs) throws BackingStoreException { return prefs.keys(); } - - + + @Override public void remove(Preferences prefs, String key) { prefs.remove(key); } - + } - - + + public static class StringAdapter extends AbstractAdapter { - + @Override public String get(Preferences prefs, String key) { return prefs.get(key, null); } - - + + @Override public void put(Preferences prefs, String key, String value) { prefs.put(key, value); } - + } - - + + public static class SimpleAdapter extends AbstractAdapter { - + private final Constructor constructor; - - + + public SimpleAdapter(Class type) { try { constructor = type.getConstructor(String.class); @@ -222,12 +222,12 @@ public class PreferencesMap implements Map { throw new IllegalArgumentException(e); } } - - + + @Override public T get(Preferences prefs, String key) { String value = prefs.get(key, null); - + if (value != null) { try { return constructor.newInstance(value); @@ -238,110 +238,110 @@ public class PreferencesMap implements Map { throw new RuntimeException(e); } } - + return null; } - - + + @Override public void put(Preferences prefs, String key, T value) { prefs.put(key, value.toString()); } - - + + public static SimpleAdapter forClass(Class type) { return new SimpleAdapter(type); } - + } - - + + public static class SerializableAdapter extends AbstractAdapter { - + @SuppressWarnings("unchecked") @Override public T get(Preferences prefs, String key) { byte[] bytes = prefs.getByteArray(key, null); - + if (bytes == null) return null; - + try { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object object = in.readObject(); in.close(); - + return (T) object; } catch (Exception e) { throw new RuntimeException(e); } } - - + + @Override public void put(Preferences prefs, String key, T value) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - + try { ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(value); out.close(); - + prefs.putByteArray(key, buffer.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } } - - + + public static class PreferencesEntry implements Entry { - + private final String key; - + private final Preferences prefs; - + private final Adapter adapter; - + private T defaultValue = null; - - + + public PreferencesEntry(Preferences prefs, String key, Adapter adapter) { this.key = key; this.prefs = prefs; this.adapter = adapter; } - - + + @Override public String getKey() { return key; } - - + + @Override public T getValue() { T value = adapter.get(prefs, key); return value != null ? value : defaultValue; } - - + + @Override public T setValue(T value) { adapter.put(prefs, key, value); return null; } - - + + public PreferencesEntry defaultValue(T defaultValue) { this.defaultValue = defaultValue; return this; } - - + + public void remove() { adapter.remove(prefs, key); } } - + } diff --git a/source/net/filebot/util/TeePrintStream.java b/source/net/filebot/util/TeePrintStream.java index acd9b78c..979da824 100644 --- a/source/net/filebot/util/TeePrintStream.java +++ b/source/net/filebot/util/TeePrintStream.java @@ -9,48 +9,48 @@ import java.io.UnsupportedEncodingException; public class TeePrintStream extends PrintStream { - + private final PrintStream cc; - - + + public TeePrintStream(OutputStream out, boolean autoFlush, String encoding, PrintStream cc) throws UnsupportedEncodingException { super(out, autoFlush, encoding); this.cc = cc; } - - + + @Override public void close() { super.close(); cc.close(); } - - + + @Override public void flush() { super.flush(); cc.flush(); } - - + + @Override public void write(byte[] buf, int off, int len) { super.write(buf, off, len); cc.write(buf, off, len); } - - + + @Override public void write(int b) { super.write(b); cc.write(b); } - - + + @Override public void write(byte[] b) throws IOException { super.write(b); cc.write(b); } - + } diff --git a/source/net/filebot/util/TemporaryFolder.java b/source/net/filebot/util/TemporaryFolder.java index b450f8d0..85d58396 100644 --- a/source/net/filebot/util/TemporaryFolder.java +++ b/source/net/filebot/util/TemporaryFolder.java @@ -16,7 +16,7 @@ public final class TemporaryFolder { /** * Get a {@link TemporaryFolder} instance for a given name. The actual directory will be created lazily (e.g. when a file is created). The name of the directory will start with the given name (lower-case) and contain a unique id, so multiple application instances may run at the same time without the risk of interference. - * + * * @param name * case-insensitive name of a temporary folder (e.g. application name) * @return temporary folder for this name @@ -65,7 +65,7 @@ public final class TemporaryFolder { /** * Create an empty file in this temporary folder. - * + * * @param name * name of the file * @return newly created file @@ -82,7 +82,7 @@ public final class TemporaryFolder { /** * Creates an empty file in this temporary folder, using the given prefix and suffix to generate its name. - * + * * @param prefix * The prefix string to be used in generating the file's name; must be at least three characters long * @param suffix @@ -102,7 +102,7 @@ public final class TemporaryFolder { /** * Retrieve the {@link File} object for this {@link TemporaryFolder}. The actual directory for the {@link TemporaryFolder} instance will be created by this method. - * + * * @return the {@link File} object for this {@link TemporaryFolder} */ public File getFolder() throws IOException { @@ -142,7 +142,7 @@ public final class TemporaryFolder { /** * Delete files/folders recursively - * + * * @param file * file/folder that will be deleted */ diff --git a/source/net/filebot/util/TreeIterator.java b/source/net/filebot/util/TreeIterator.java index 10fe5164..69d91f48 100644 --- a/source/net/filebot/util/TreeIterator.java +++ b/source/net/filebot/util/TreeIterator.java @@ -8,56 +8,56 @@ import java.util.LinkedList; public abstract class TreeIterator implements Iterator { - + private final LinkedList> recursionStack = new LinkedList>(); - - + + public TreeIterator(T... root) { recursionStack.push(Arrays.asList(root).iterator()); } - + protected abstract Iterator children(T node); - + @Override public boolean hasNext() { return currentIterator().hasNext(); } - + @Override public T next() { T node = currentIterator().next(); - + Iterator children = children(node); if (children != null && children.hasNext()) { - // step into next recursion level + // step into next recursion level recursionStack.push(children); } - + return node; } - + private Iterator currentIterator() { Iterator iterator = recursionStack.peek(); - + if (iterator.hasNext() || recursionStack.size() <= 1) return iterator; - + // step back one recursion level recursionStack.pop(); - + return currentIterator(); } - + @Override public void remove() { - // can't just use remove() on current iterator, because + // can't just use remove() on current iterator, because // we may have stepped into the next recursion level throw new UnsupportedOperationException(); } - + } diff --git a/source/net/filebot/util/UnicodeReader.java b/source/net/filebot/util/UnicodeReader.java index c1f6434e..efce7a07 100644 --- a/source/net/filebot/util/UnicodeReader.java +++ b/source/net/filebot/util/UnicodeReader.java @@ -58,50 +58,62 @@ public class UnicodeReader extends Reader { } } + @Override public int hashCode() { return reader.hashCode(); } + @Override public int read(CharBuffer target) throws IOException { return reader.read(target); } + @Override public boolean equals(Object obj) { return reader.equals(obj); } + @Override public int read(char[] cbuf) throws IOException { return reader.read(cbuf); } + @Override public int read() throws IOException { return reader.read(); } + @Override public int read(char[] cbuf, int offset, int length) throws IOException { return reader.read(cbuf, offset, length); } + @Override public long skip(long n) throws IOException { return reader.skip(n); } + @Override public boolean ready() throws IOException { return reader.ready(); } + @Override public void close() throws IOException { reader.close(); } + @Override public boolean markSupported() { return reader.markSupported(); } + @Override public void mark(int readAheadLimit) throws IOException { reader.mark(readAheadLimit); } + @Override public void reset() throws IOException { reader.reset(); } diff --git a/source/net/filebot/util/XPathUtilities.java b/source/net/filebot/util/XPathUtilities.java index e4b40fc7..62bd91bf 100644 --- a/source/net/filebot/util/XPathUtilities.java +++ b/source/net/filebot/util/XPathUtilities.java @@ -79,7 +79,7 @@ public final class XPathUtilities { /** * Get text content of the first child node matching the given node name. Use this method instead of {@link #selectString(String, Object)} whenever xpath support is not required, because it is much faster, especially for large documents. - * + * * @param childName * search for nodes with this name * @param parentNode diff --git a/source/net/filebot/util/prefs/FilePreferences.java b/source/net/filebot/util/prefs/FilePreferences.java index b9a3699d..b3f83e4d 100644 --- a/source/net/filebot/util/prefs/FilePreferences.java +++ b/source/net/filebot/util/prefs/FilePreferences.java @@ -25,37 +25,37 @@ import org.slf4j.LoggerFactory; * switched to SLF4J logging, and exposed preferences file property. * * Modified to use '/' as path separator and not '.' because it breaks when keys containing '.' are used. - * + * * @author David Croft (www.davidc.net) * @version $Id: FilePreferences.java 283 2009-06-18 17:06:58Z david $ */ public class FilePreferences extends AbstractPreferences { - + private static final Logger log = LoggerFactory.getLogger(FilePreferences.class.getName()); - + private Map root; - + private Map children; - + private boolean isRemoved = false; - - + + public FilePreferences(AbstractPreferences parent, String name) { super(parent, name); - + log.debug("Instantiating node {}", name); - + root = new TreeMap(); children = new TreeMap(); - + try { sync(); } catch (BackingStoreException e) { log.error("Unable to sync on creation of node " + name, e); } } - - + + @Override protected void putSpi(String key, String value) { root.put(key, value); @@ -65,14 +65,14 @@ public class FilePreferences extends AbstractPreferences { log.error("Unable to flush after putting " + key, e); } } - - + + @Override protected String getSpi(String key) { return root.get(key); } - - + + @Override protected void removeSpi(String key) { root.remove(key); @@ -82,27 +82,27 @@ public class FilePreferences extends AbstractPreferences { log.error("Unable to flush after removing " + key, e); } } - - + + @Override protected void removeNodeSpi() throws BackingStoreException { isRemoved = true; flush(); } - - + + @Override protected String[] keysSpi() throws BackingStoreException { return root.keySet().toArray(new String[root.keySet().size()]); } - - + + @Override protected String[] childrenNamesSpi() throws BackingStoreException { return children.keySet().toArray(new String[children.keySet().size()]); } - - + + @Override protected FilePreferences childSpi(String name) { FilePreferences child = children.get(name); @@ -112,29 +112,29 @@ public class FilePreferences extends AbstractPreferences { } return child; } - - + + @Override protected void syncSpi() throws BackingStoreException { if (isRemoved()) { return; } - + final File file = FilePreferencesFactory.getPreferencesFile(); - + if (!file.exists()) { return; } - + synchronized (file) { Properties p = new Properties(); try { p.load(new FileInputStream(file)); - + StringBuilder sb = new StringBuilder(); getPath(sb); String path = sb.toString(); - + final Enumeration pnen = p.propertyNames(); while (pnen.hasMoreElements()) { String propKey = (String) pnen.nextElement(); @@ -151,36 +151,36 @@ public class FilePreferences extends AbstractPreferences { } } } - - + + private void getPath(StringBuilder sb) { final FilePreferences parent = (FilePreferences) parent(); if (parent == null) { return; } - + parent.getPath(sb); sb.append(name()).append('/'); } - - + + @Override protected void flushSpi() throws BackingStoreException { final File file = FilePreferencesFactory.getPreferencesFile(); - + synchronized (file) { Properties p = new Properties(); try { - + StringBuilder sb = new StringBuilder(); getPath(sb); String path = sb.toString(); - + if (file.exists()) { p.load(new FileInputStream(file)); - + List toRemove = new ArrayList(); - + // Make a list of all direct children of this node to be removed final Enumeration pnen = p.propertyNames(); while (pnen.hasMoreElements()) { @@ -193,20 +193,20 @@ public class FilePreferences extends AbstractPreferences { } } } - + // Remove them now that the enumeration is done with for (String propKey : toRemove) { p.remove(propKey); } } - + // If this node hasn't been removed, add back in any values if (!isRemoved) { for (String s : root.keySet()) { p.setProperty(path + s, root.get(s)); } } - + p.store(new FileOutputStream(file), "FilePreferences"); } catch (IOException e) { throw new BackingStoreException(e); diff --git a/source/net/filebot/util/prefs/FilePreferencesFactory.java b/source/net/filebot/util/prefs/FilePreferencesFactory.java index 9beb65aa..cac1e5a1 100644 --- a/source/net/filebot/util/prefs/FilePreferencesFactory.java +++ b/source/net/filebot/util/prefs/FilePreferencesFactory.java @@ -15,48 +15,50 @@ import java.util.prefs.PreferencesFactory; * The file defaults to [user.home]/.fileprefs, but may be overridden with the system property * net.filebot.util.pref.FilePreferencesFactory.file. Modified by cstamas, switched to SLF4J logging, and * exposed preferences file property. - * + * * @author David Croft (www.davidc.net) * @version $Id: FilePreferencesFactory.java 282 2009-06-18 17:05:18Z david $ */ public class FilePreferencesFactory implements PreferencesFactory { - + Preferences rootPreferences; - + public static final String SYSTEM_PROPERTY_FILE = "net.filebot.util.prefs.file"; - - + + + @Override public Preferences systemRoot() { return userRoot(); } - - + + + @Override public Preferences userRoot() { if (rootPreferences == null) { rootPreferences = new FilePreferences(null, ""); } - + return rootPreferences; } - + private static File preferencesFile; - - + + public static File getPreferencesFile() { if (preferencesFile == null) { String prefsFile = System.getProperty(SYSTEM_PROPERTY_FILE); - + if (prefsFile == null || prefsFile.length() == 0) { prefsFile = System.getProperty("user.home") + File.separator + ".fileprefs"; } - + preferencesFile = new File(prefsFile).getAbsoluteFile(); } - + return preferencesFile; } - - + + public static void setPreferencesFile(File file) { preferencesFile = file; } diff --git a/source/net/filebot/util/ui/AbstractBean.java b/source/net/filebot/util/ui/AbstractBean.java index 3e745cdb..8a71816c 100644 --- a/source/net/filebot/util/ui/AbstractBean.java +++ b/source/net/filebot/util/ui/AbstractBean.java @@ -10,38 +10,38 @@ import javax.swing.event.SwingPropertyChangeSupport; public abstract class AbstractBean { - + private final PropertyChangeSupport pcs; - + public AbstractBean() { // always notify on EDT pcs = new SwingPropertyChangeSupport(this, true); } - + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { pcs.firePropertyChange(propertyName, oldValue, newValue); } - + protected void firePropertyChange(PropertyChangeEvent e) { pcs.firePropertyChange(e); } - + public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } - + public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } - + public PropertyChangeListener[] getPropertyChangeListeners() { return pcs.getPropertyChangeListeners(); } - + } diff --git a/source/net/filebot/util/ui/AbstractFancyListCellRenderer.java b/source/net/filebot/util/ui/AbstractFancyListCellRenderer.java index d86b36f6..f8fbf919 100644 --- a/source/net/filebot/util/ui/AbstractFancyListCellRenderer.java +++ b/source/net/filebot/util/ui/AbstractFancyListCellRenderer.java @@ -21,61 +21,61 @@ import javax.swing.border.LineBorder; public abstract class AbstractFancyListCellRenderer extends JPanel implements ListCellRenderer { - + private Color gradientBeginColor; private Color gradientEndColor; - + private Color highlightColor; - + private boolean borderPainted = false; private boolean gradientPainted = false; - + private GradientStyle gradientStyle = GradientStyle.TOP_TO_BOTTOM; private boolean highlightingEnabled = true; - + private final Insets margin; - + private static final Insets DEFAULT_PADDING = new Insets(7, 7, 7, 7); private static final Insets DEFAULT_MARGIN = new Insets(1, 1, 0, 1); - + public AbstractFancyListCellRenderer() { this(DEFAULT_PADDING, DEFAULT_MARGIN, null); } - + public AbstractFancyListCellRenderer(Insets padding) { this(padding, DEFAULT_MARGIN, null); } - + public AbstractFancyListCellRenderer(Insets padding, Insets margin) { this(padding, margin, null); } - + public AbstractFancyListCellRenderer(Insets padding, Insets margin, Color borderColor) { this.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); - + Border border = null; - + if (padding != null) border = new EmptyBorder(padding); - + if (borderColor != null) border = new CompoundBorder(new LineBorder(borderColor, 1), border); - + if (margin != null) { this.margin = margin; border = new CompoundBorder(new EmptyBorder(margin), border); } else { this.margin = new Insets(0, 0, 0, 0); } - + setBorder(border); setOpaque(false); } - + @Override protected void paintBorder(Graphics g) { @@ -83,57 +83,57 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li super.paintBorder(g); } } - + @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; Rectangle2D shape = new Rectangle2D.Double(margin.left, margin.top, getWidth() - (margin.left + margin.right), getHeight() - (margin.top + margin.bottom)); - + if (isOpaque()) { g2d.setPaint(getBackground()); g2d.fill(shape); } - + if (highlightingEnabled && (highlightColor != null)) { g2d.setPaint(highlightColor); g2d.fill(shape); } - + if (gradientPainted) { g2d.setPaint(gradientStyle.getGradientPaint(shape, gradientBeginColor, gradientEndColor)); g2d.fill(shape); } - + super.paintComponent(g); } - + @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { configureListCellRendererComponent(list, value, index, isSelected, cellHasFocus); validate(); - + return this; } - + protected void configureListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setGradientPainted(isSelected); setBorderPainted(isSelected); - + Color sc = list.getSelectionBackground(); - + if (isSelected) { setGradientColors(sc.brighter(), sc); } - + if (highlightingEnabled && ((index % 2) == 0)) { setHighlightColor(new Color(sc.getRed(), sc.getGreen(), sc.getBlue(), 28)); } else { setHighlightColor(null); } - + if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); @@ -142,68 +142,68 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li setForeground(list.getForeground()); } } - + public void setGradientColors(Color gradientBeginColor, Color gradientEndColor) { this.gradientBeginColor = gradientBeginColor; this.gradientEndColor = gradientEndColor; } - + public Color getGradientBeginColor() { return gradientBeginColor; } - + public Color getGradientEndColor() { return gradientEndColor; } - + public void setHighlightColor(Color highlightColor) { this.highlightColor = highlightColor; } - + public void setGradientStyle(GradientStyle gradientStyle) { this.gradientStyle = gradientStyle; } - + public void setHighlightingEnabled(boolean highlightingEnabled) { this.highlightingEnabled = highlightingEnabled; } - + public void setBorderPainted(boolean borderPainted) { this.borderPainted = borderPainted; } - + public void setGradientPainted(boolean gradientPainted) { this.gradientPainted = gradientPainted; } - + public Color getHighlightColor() { return highlightColor; } - + public boolean isBorderPainted() { return borderPainted; } - + public GradientStyle getGradientStyle() { return gradientStyle; } - + public boolean isHighlightingEnabled() { return highlightingEnabled; } - + @Override public void validate() { @@ -212,7 +212,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li validateTree(); } } - + /** * Overridden for performance reasons. @@ -220,7 +220,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void repaint() { } - + /** * Overridden for performance reasons. @@ -228,7 +228,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void repaint(long tm, int x, int y, int width, int height) { } - + /** * Overridden for performance reasons. @@ -236,7 +236,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void repaint(Rectangle r) { } - + /** * Overridden for performance reasons. @@ -244,7 +244,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { } - + /** * Overridden for performance reasons. @@ -252,7 +252,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { } - + /** * Overridden for performance reasons. @@ -260,7 +260,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, char oldValue, char newValue) { } - + /** * Overridden for performance reasons. @@ -268,7 +268,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, short oldValue, short newValue) { } - + /** * Overridden for performance reasons. @@ -276,7 +276,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) { } - + /** * Overridden for performance reasons. @@ -284,7 +284,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, long oldValue, long newValue) { } - + /** * Overridden for performance reasons. @@ -292,7 +292,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, float oldValue, float newValue) { } - + /** * Overridden for performance reasons. @@ -300,7 +300,7 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, double oldValue, double newValue) { } - + /** * Overridden for performance reasons. @@ -308,5 +308,5 @@ public abstract class AbstractFancyListCellRenderer extends JPanel implements Li @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } - + } diff --git a/source/net/filebot/util/ui/ColorTintImageFilter.java b/source/net/filebot/util/ui/ColorTintImageFilter.java index dcfcb649..cd1e821b 100644 --- a/source/net/filebot/util/ui/ColorTintImageFilter.java +++ b/source/net/filebot/util/ui/ColorTintImageFilter.java @@ -7,28 +7,28 @@ import java.awt.image.RGBImageFilter; public class ColorTintImageFilter extends RGBImageFilter { - + private Color color; private float intensity; - - + + public ColorTintImageFilter(Color color, float intensity) { this.color = color; this.intensity = intensity; - + canFilterIndexColorModel = true; } - + @Override public int filterRGB(int x, int y, int rgb) { Color c = new Color(rgb, true); - + int red = (int) ((c.getRed() * (1 - intensity)) + color.getRed() * intensity); int green = (int) ((c.getGreen() * (1 - intensity)) + color.getGreen() * intensity); int blue = (int) ((c.getBlue() * (1 - intensity)) + color.getBlue() * intensity); - + return new Color(red, green, blue, c.getAlpha()).getRGB(); } - + } diff --git a/source/net/filebot/util/ui/DashedSeparator.java b/source/net/filebot/util/ui/DashedSeparator.java index 9383d75f..cfdf4a4f 100644 --- a/source/net/filebot/util/ui/DashedSeparator.java +++ b/source/net/filebot/util/ui/DashedSeparator.java @@ -16,13 +16,13 @@ import javax.swing.border.Border; public class DashedSeparator implements Border { - + private final int height; private final int dash; - + private final Color foreground; private final Color background; - + public DashedSeparator(int height, int dash, Color foreground, Color background) { this.height = height; @@ -30,35 +30,35 @@ public class DashedSeparator implements Border { this.foreground = foreground; this.background = background; } - + @Override public Insets getBorderInsets(Component c) { return new Insets(0, 0, height, 0); } - + @Override public boolean isBorderOpaque() { return true; } - + @Override public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { Graphics2D g2d = (Graphics2D) g.create(x, h - this.height, w, h); - + // fill background g2d.setPaint(background); g2d.fillRect(0, 0, w, h); - + // draw dashed line g2d.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g2d.setColor(foreground); g2d.setStroke(new BasicStroke(1, CAP_ROUND, JOIN_ROUND, 1, new float[] { dash }, 0)); - + g2d.drawLine(dash, this.height / 2, w - dash, this.height / 2); - + g2d.dispose(); } } diff --git a/source/net/filebot/util/ui/DefaultFancyListCellRenderer.java b/source/net/filebot/util/ui/DefaultFancyListCellRenderer.java index e307d2e2..6e5c1c1d 100644 --- a/source/net/filebot/util/ui/DefaultFancyListCellRenderer.java +++ b/source/net/filebot/util/ui/DefaultFancyListCellRenderer.java @@ -12,32 +12,32 @@ import javax.swing.JList; public class DefaultFancyListCellRenderer extends AbstractFancyListCellRenderer { - + private final JLabel label = new DefaultListCellRenderer(); - + public DefaultFancyListCellRenderer() { add(label); } - + public DefaultFancyListCellRenderer(int padding) { super(new Insets(padding, padding, padding, padding)); add(label); } - + public DefaultFancyListCellRenderer(Insets padding) { super(padding); add(label); } - + protected DefaultFancyListCellRenderer(int padding, int margin, Color selectedBorderColor) { super(new Insets(padding, padding, padding, padding), new Insets(margin, margin, margin, margin), selectedBorderColor); add(label); } - + @Override protected void configureListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { @@ -45,36 +45,36 @@ public class DefaultFancyListCellRenderer extends AbstractFancyListCellRenderer label.setOpaque(false); setText(String.valueOf(value)); } - + public void setIcon(Icon icon) { label.setIcon(icon); } - + public void setText(String text) { label.setText(text); } - + public void setHorizontalTextPosition(int textPosition) { label.setHorizontalTextPosition(textPosition); } - + public void setVerticalTextPosition(int textPosition) { label.setVerticalTextPosition(textPosition); } - + @Override public void setForeground(Color fg) { super.setForeground(fg); - + // label is null while in super constructor if (label != null) { label.setForeground(fg); } } - + } diff --git a/source/net/filebot/util/ui/EmptySelectionModel.java b/source/net/filebot/util/ui/EmptySelectionModel.java index e8947e96..2ac422ba 100644 --- a/source/net/filebot/util/ui/EmptySelectionModel.java +++ b/source/net/filebot/util/ui/EmptySelectionModel.java @@ -7,112 +7,112 @@ import javax.swing.event.ListSelectionListener; public class EmptySelectionModel implements ListSelectionModel { - + @Override public void addListSelectionListener(ListSelectionListener x) { } - + @Override public void addSelectionInterval(int from, int to) { } - + @Override public void clearSelection() { } - + @Override public int getAnchorSelectionIndex() { return -1; } - + @Override public int getLeadSelectionIndex() { return -1; } - + @Override public int getMaxSelectionIndex() { return -1; } - + @Override public int getMinSelectionIndex() { return -1; } - + @Override public int getSelectionMode() { return -1; } - + @Override public boolean getValueIsAdjusting() { return false; } - + @Override public void insertIndexInterval(int index, int length, boolean before) { } - + @Override public boolean isSelectedIndex(int index) { return false; } - + @Override public boolean isSelectionEmpty() { return true; } - + @Override public void removeIndexInterval(int from, int to) { } - + @Override public void removeListSelectionListener(ListSelectionListener listener) { } - + @Override public void removeSelectionInterval(int from, int to) { } - + @Override public void setAnchorSelectionIndex(int index) { } - + @Override public void setLeadSelectionIndex(int index) { } - + @Override public void setSelectionInterval(int from, int to) { } - + @Override public void setSelectionMode(int selectionMode) { } - + @Override public void setValueIsAdjusting(boolean valueIsAdjusting) { } - + } diff --git a/source/net/filebot/util/ui/FancyTreeCellRenderer.java b/source/net/filebot/util/ui/FancyTreeCellRenderer.java index ba72160b..a530a014 100644 --- a/source/net/filebot/util/ui/FancyTreeCellRenderer.java +++ b/source/net/filebot/util/ui/FancyTreeCellRenderer.java @@ -15,36 +15,36 @@ import javax.swing.tree.DefaultTreeCellRenderer; public class FancyTreeCellRenderer extends DefaultTreeCellRenderer { - + private Color gradientBeginColor; private Color gradientEndColor; private GradientStyle gradientStyle; private boolean paintGradient; - + private Color backgroundSelectionColor; - - + + public FancyTreeCellRenderer() { this(GradientStyle.TOP_TO_BOTTOM); } - + public FancyTreeCellRenderer(GradientStyle gradientStyle) { this.gradientStyle = gradientStyle; - + backgroundSelectionColor = getBackgroundSelectionColor(); - + // disable default selection background setBackgroundSelectionColor(null); } - + @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, false); - + setIconTextGap(5); - + if (selected) { setPaintGradient(true); setGradientBeginColor(backgroundSelectionColor.brighter()); @@ -52,79 +52,79 @@ public class FancyTreeCellRenderer extends DefaultTreeCellRenderer { } else { setPaintGradient(false); } - + return this; } - + @Override protected void paintComponent(Graphics g) { if (isPaintGradient()) { Graphics2D g2d = (Graphics2D) g; - + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - + int imageOffset = getLabelStart() - 2; - + int arch = 16; RoundRectangle2D shape = new RoundRectangle2D.Double(imageOffset, 1, getWidth() - imageOffset, getHeight() - 2, arch, arch); - + g2d.setPaint(gradientStyle.getGradientPaint(shape, gradientBeginColor, gradientEndColor)); g2d.fill(shape); } - + super.paintComponent(g); } - + protected int getLabelStart() { Icon icon = getIcon(); - + if ((icon != null) && (getText() != null)) { return icon.getIconWidth() + Math.max(0, getIconTextGap() - 1); } - + return 0; } - + public Color getGradientBeginColor() { return gradientBeginColor; } - + public void setGradientBeginColor(Color gradientBeginColor) { this.gradientBeginColor = gradientBeginColor; } - + public boolean isPaintGradient() { return paintGradient; } - + public void setPaintGradient(boolean gradientEnabled) { this.paintGradient = gradientEnabled; } - + public Color getGradientEndColor() { return gradientEndColor; } - + public void setGradientEndColor(Color gradientEndColor) { this.gradientEndColor = gradientEndColor; } - + public GradientStyle getGradientStyle() { return gradientStyle; } - + public void setGradientStyle(GradientStyle gradientStyle) { this.gradientStyle = gradientStyle; } - + } diff --git a/source/net/filebot/util/ui/GradientStyle.java b/source/net/filebot/util/ui/GradientStyle.java index bd99c0a6..e6b8af6f 100644 --- a/source/net/filebot/util/ui/GradientStyle.java +++ b/source/net/filebot/util/ui/GradientStyle.java @@ -18,59 +18,59 @@ public enum GradientStyle { BOTTOM_RIGHT_TO_TOP_LEFT, TOP_RIGHT_TO_BOTTOM_LEFT, BOTTOM_LEFT_TO_TOP_RIGHT; - + public LinearGradientPaint getGradientPaint(RectangularShape shape, Color gradientBeginColor, Color gradientEndColor) { Point2D start = null; Point2D end = null; - + switch (this) { - case BOTTOM_TO_TOP: - start = new Point2D.Double(shape.getCenterX(), shape.getMaxY()); - end = new Point2D.Double(shape.getCenterX(), shape.getMinY()); - break; - - case TOP_TO_BOTTOM: - end = new Point2D.Double(shape.getCenterX(), shape.getMaxY()); - start = new Point2D.Double(shape.getCenterX(), shape.getMinY()); - break; - - case LEFT_TO_RIGHT: - start = new Point2D.Double(shape.getMinX(), shape.getCenterY()); - end = new Point2D.Double(shape.getMaxX(), shape.getCenterY()); - break; - - case RIGHT_TO_LEFT: - end = new Point2D.Double(shape.getMinX(), shape.getCenterY()); - start = new Point2D.Double(shape.getMaxX(), shape.getCenterY()); - break; - - case TOP_LEFT_TO_BOTTOM_RIGHT: - start = new Point2D.Double(shape.getMinX(), shape.getMinY()); - end = new Point2D.Double(shape.getMaxX(), shape.getMaxY()); - break; - - case BOTTOM_RIGHT_TO_TOP_LEFT: - end = new Point2D.Double(shape.getMinX(), shape.getMinY()); - start = new Point2D.Double(shape.getMaxX(), shape.getMaxY()); - break; - - case TOP_RIGHT_TO_BOTTOM_LEFT: - start = new Point2D.Double(shape.getMaxX(), shape.getMinY()); - end = new Point2D.Double(shape.getMinX(), shape.getMaxY()); - break; - - case BOTTOM_LEFT_TO_TOP_RIGHT: - end = new Point2D.Double(shape.getMaxX(), shape.getMinY()); - start = new Point2D.Double(shape.getMinX(), shape.getMaxY()); - break; - - default: - return null; + case BOTTOM_TO_TOP: + start = new Point2D.Double(shape.getCenterX(), shape.getMaxY()); + end = new Point2D.Double(shape.getCenterX(), shape.getMinY()); + break; + + case TOP_TO_BOTTOM: + end = new Point2D.Double(shape.getCenterX(), shape.getMaxY()); + start = new Point2D.Double(shape.getCenterX(), shape.getMinY()); + break; + + case LEFT_TO_RIGHT: + start = new Point2D.Double(shape.getMinX(), shape.getCenterY()); + end = new Point2D.Double(shape.getMaxX(), shape.getCenterY()); + break; + + case RIGHT_TO_LEFT: + end = new Point2D.Double(shape.getMinX(), shape.getCenterY()); + start = new Point2D.Double(shape.getMaxX(), shape.getCenterY()); + break; + + case TOP_LEFT_TO_BOTTOM_RIGHT: + start = new Point2D.Double(shape.getMinX(), shape.getMinY()); + end = new Point2D.Double(shape.getMaxX(), shape.getMaxY()); + break; + + case BOTTOM_RIGHT_TO_TOP_LEFT: + end = new Point2D.Double(shape.getMinX(), shape.getMinY()); + start = new Point2D.Double(shape.getMaxX(), shape.getMaxY()); + break; + + case TOP_RIGHT_TO_BOTTOM_LEFT: + start = new Point2D.Double(shape.getMaxX(), shape.getMinY()); + end = new Point2D.Double(shape.getMinX(), shape.getMaxY()); + break; + + case BOTTOM_LEFT_TO_TOP_RIGHT: + end = new Point2D.Double(shape.getMaxX(), shape.getMinY()); + start = new Point2D.Double(shape.getMinX(), shape.getMaxY()); + break; + + default: + return null; } - + Color[] colors = { gradientBeginColor, gradientEndColor }; float[] fractions = { 0.0f, 1.0f }; return new LinearGradientPaint(start, end, fractions, colors, CycleMethod.NO_CYCLE); } - + } diff --git a/source/net/filebot/util/ui/LabelProvider.java b/source/net/filebot/util/ui/LabelProvider.java index 73bdd42e..d97a512a 100644 --- a/source/net/filebot/util/ui/LabelProvider.java +++ b/source/net/filebot/util/ui/LabelProvider.java @@ -6,10 +6,10 @@ import javax.swing.Icon; public interface LabelProvider { - + public String getText(T value); - + public Icon getIcon(T value); - + } diff --git a/source/net/filebot/util/ui/LazyDocumentListener.java b/source/net/filebot/util/ui/LazyDocumentListener.java index 26f71f4c..8e753b78 100644 --- a/source/net/filebot/util/ui/LazyDocumentListener.java +++ b/source/net/filebot/util/ui/LazyDocumentListener.java @@ -11,38 +11,38 @@ import javax.swing.event.DocumentListener; public abstract class LazyDocumentListener implements DocumentListener { - + private DocumentEvent lastEvent; - + private Timer timer; - + public LazyDocumentListener() { this(200); } - + public LazyDocumentListener(int delay) { if (delay >= 0) { timer = new Timer(delay, new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { update(lastEvent); - + // we don't need it anymore lastEvent = null; } }); - + timer.setRepeats(false); } } - + public void defer(DocumentEvent e) { lastEvent = e; - + if (timer != null) { // defer update timer.restart(); @@ -51,26 +51,26 @@ public abstract class LazyDocumentListener implements DocumentListener { update(lastEvent); } } - + @Override public void changedUpdate(DocumentEvent e) { defer(e); } - + @Override public void insertUpdate(DocumentEvent e) { defer(e); } - + @Override public void removeUpdate(DocumentEvent e) { defer(e); } - + public abstract void update(DocumentEvent e); - + } diff --git a/source/net/filebot/util/ui/ListView.java b/source/net/filebot/util/ui/ListView.java index 3f6579af..69ae0ea1 100644 --- a/source/net/filebot/util/ui/ListView.java +++ b/source/net/filebot/util/ui/ListView.java @@ -25,95 +25,95 @@ import javax.swing.event.MouseInputAdapter; public class ListView extends JList { - + protected final BlockSelectionHandler blockSelectionHandler = new BlockSelectionHandler(); - + public ListView(ListModel dataModel) { super(dataModel); setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - + // better selection behaviour putClientProperty("List.isFileList", Boolean.TRUE); setDropMode(DropMode.ON); - + setLayoutOrientation(JList.VERTICAL_WRAP); setVisibleRowCount(-1); setCellRenderer(new ListViewRenderer()); - + addMouseListener(blockSelectionHandler); addMouseMotionListener(blockSelectionHandler); } - + public void addSelectionInterval(Rectangle selection) { Point p1 = selection.getLocation(); Point p2 = new Point(p1.x + selection.width, p1.y + selection.height); - + int startIndex = locationToIndex(p1); int endIndex = locationToIndex(p2); - + for (int i = startIndex; i <= endIndex; i++) { Rectangle cell = getCellBounds(i, i); - + if (cell != null && selection.intersects(cell)) { addSelectionInterval(i, i); } } } - + @Override public void paintComponent(Graphics g) { super.paintComponent(g); - + Rectangle selection = blockSelectionHandler.getSelection(); - + // paint block selection if (selection != null) { paintBlockSelection((Graphics2D) g, selection); } } - + protected void paintBlockSelection(Graphics2D g2d, Rectangle selection) { g2d.setPaint(SwingUI.derive(getSelectionBackground(), 0.3f)); g2d.fill(selection); - + g2d.setPaint(getSelectionBackground()); g2d.draw(selection); } - + protected String convertValueToText(Object value) { return value.toString(); } - + protected Icon convertValueToIcon(Object value) { return null; } - + protected class ListViewRenderer extends DefaultListCellRenderer { - + public ListViewRenderer() { setOpaque(false); } - + @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Icon icon = convertValueToIcon(value); - + if (isSelected && icon != null) { // apply selection color tint icon = new ImageIcon(createImage(new FilteredImageSource(SwingUI.getImage(icon).getSource(), new ColorTintImageFilter(list.getSelectionBackground(), 0.5f)))); } - + setText(convertValueToText(value)); setIcon(icon); - + if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); @@ -121,10 +121,10 @@ public class ListView extends JList { setBackground(list.getBackground()); setForeground(list.getForeground()); } - + return this; } - + @Override protected void paintComponent(Graphics g) { @@ -132,73 +132,74 @@ public class ListView extends JList { int iconWidth = (getIcon() == null ? 0 : getIcon().getIconHeight()); int startX = iconWidth + getIconTextGap(); Rectangle2D text = getFontMetrics(getFont()).getStringBounds(getText(), g); - + g.setColor(getBackground()); g.fillRect(startX - 2, 1, (int) (text.getWidth() + 6), getHeight() - 1); - + super.paintComponent(g); } }; - + protected class BlockSelectionHandler extends MouseInputAdapter { - - private Rectangle selection; - - private Point origin; - + private Rectangle selection; + + private Point origin; + + + @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && !isSelectedIndex(locationToIndex(e.getPoint()))) { origin = e.getPoint(); } } - + @Override public void mouseDragged(MouseEvent e) { if (origin == null) return; - + // begin selection if (selection == null) selection = new Rectangle(); - + // keep point within component bounds Point p2 = e.getPoint(); p2.x = max(0, min(getWidth() - 1, p2.x)); p2.y = max(0, min(getHeight() - 1, p2.y)); - + // update selection bounds selection.setFrameFromDiagonal(origin, p2); - + // auto-scroll ensureIndexIsVisible(locationToIndex(p2)); - + // update list selection clearSelection(); addSelectionInterval(selection); - + // update view repaint(); } - + @Override public void mouseReleased(MouseEvent e) { origin = null; - + // end selection selection = null; - + // update view repaint(); } - + public Rectangle getSelection() { return selection; } }; - + } diff --git a/source/net/filebot/util/ui/LoadingOverlayPane.java b/source/net/filebot/util/ui/LoadingOverlayPane.java index 4ee992ae..417b861d 100644 --- a/source/net/filebot/util/ui/LoadingOverlayPane.java +++ b/source/net/filebot/util/ui/LoadingOverlayPane.java @@ -11,33 +11,33 @@ import net.miginfocom.swing.MigLayout; public class LoadingOverlayPane extends JComponent { - + public static final String LOADING_PROPERTY = "loading"; - + private final JComponent animationComponent; - + private boolean overlayEnabled = false; - + private int millisToOverlay = 400; - - + + public LoadingOverlayPane(JComponent component, JComponent propertyChangeSource) { this(component, propertyChangeSource, null, null); } - + public LoadingOverlayPane(JComponent component, JComponent propertyChangeSource, String offsetX, String offsetY) { setLayout(new MigLayout("insets 0, fill")); - + animationComponent = new ProgressIndicator(); animationComponent.setVisible(false); - + add(animationComponent, String.format("pos n %s 100%%-%s n", offsetY != null ? offsetY : "8px", offsetX != null ? offsetX : "20px")); add(component, "grow"); - + if (propertyChangeSource != null) { propertyChangeSource.addPropertyChangeListener(LOADING_PROPERTY, new PropertyChangeListener() { - + @Override public void propertyChange(PropertyChangeEvent evt) { setOverlayVisible((Boolean) evt.getNewValue()); @@ -45,31 +45,31 @@ public class LoadingOverlayPane extends JComponent { }); } } - + @Override public boolean isOptimizedDrawingEnabled() { return false; } - + public void setOverlayVisible(boolean b) { overlayEnabled = b; - + if (overlayEnabled) { SwingUI.invokeLater(millisToOverlay, new Runnable() { - + @Override public void run() { if (overlayEnabled) { animationComponent.setVisible(true); } } - + }); } else { animationComponent.setVisible(false); } } - + } diff --git a/source/net/filebot/util/ui/NullLabelProvider.java b/source/net/filebot/util/ui/NullLabelProvider.java index 6c13bff0..cd58b322 100644 --- a/source/net/filebot/util/ui/NullLabelProvider.java +++ b/source/net/filebot/util/ui/NullLabelProvider.java @@ -6,16 +6,16 @@ import javax.swing.Icon; public class NullLabelProvider implements LabelProvider { - + @Override public Icon getIcon(T value) { return null; } - + @Override public String getText(T value) { return value.toString(); } - + } diff --git a/source/net/filebot/util/ui/ProgressIndicator.java b/source/net/filebot/util/ui/ProgressIndicator.java index 99c66e02..78595ddb 100644 --- a/source/net/filebot/util/ui/ProgressIndicator.java +++ b/source/net/filebot/util/ui/ProgressIndicator.java @@ -22,36 +22,36 @@ import javax.swing.Timer; public class ProgressIndicator extends JComponent { - + private float radius = 4.0f; private int shapeCount = 3; - + private float strokeWidth = 2f; private Stroke stroke = new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND); - + private Color progressShapeColor = Color.orange; private Color backgroundShapeColor = new Color(0f, 0f, 0f, 0.25f); - + private final Rectangle2D frame = new Rectangle2D.Double(); private final Ellipse2D circle = new Ellipse2D.Double(); private final Dimension baseSize = new Dimension(32, 32); - + private double alpha = 0; private double speed = 24; - + private Timer updateTimer; - - + + public ProgressIndicator() { setPreferredSize(baseSize); - + addComponentListener(new ComponentAdapter() { - + @Override public void componentShown(ComponentEvent e) { startAnimation(); } - + @Override public void componentHidden(ComponentEvent e) { @@ -59,78 +59,78 @@ public class ProgressIndicator extends JComponent { } }); } - + public void animateOnce() { if ((alpha += (speed / 1000)) >= 1) { alpha -= Math.floor(alpha); } } - + @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; - + double a = Math.min(getWidth(), getHeight()); - + g2d.scale(a / baseSize.width, a / baseSize.height); - + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - + frame.setFrame(radius, radius, baseSize.width - radius * 2 - 1, baseSize.height - radius * 2 - 1); - + paintShapes(g2d); } - + private void paintShapes(Graphics2D g2d) { circle.setFrame(frame); - + g2d.setStroke(stroke); g2d.setPaint(backgroundShapeColor); - + g2d.draw(circle); - + Point2D center = new Point2D.Double(frame.getCenterX(), frame.getMinY()); - + circle.setFrameFromCenter(center, new Point2D.Double(center.getX() + radius, center.getY() + radius)); - + g2d.setStroke(stroke); g2d.setPaint(progressShapeColor); - + // base rotation g2d.rotate(getTheta(alpha, 1.0), frame.getCenterX(), frame.getCenterY()); - + double theta = getTheta(1, shapeCount); - + for (int i = 0; i < shapeCount; i++) { g2d.rotate(theta, frame.getCenterX(), frame.getCenterY()); g2d.fill(circle); } } - + private double getTheta(double value, double max) { return (value / max) * 2 * Math.PI; } - + public void startAnimation() { if (updateTimer == null) { updateTimer = new Timer(20, new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { animateOnce(); repaint(); } }); - + updateTimer.start(); } } - + public void stopAnimation() { if (updateTimer != null) { @@ -138,20 +138,20 @@ public class ProgressIndicator extends JComponent { updateTimer = null; } } - + public void setShapeCount(int indeterminateShapeCount) { this.shapeCount = indeterminateShapeCount; } - + public void setSpeed(double speed) { this.speed = speed; } - + public double getSpeed() { return speed; } - + } diff --git a/source/net/filebot/util/ui/RoundBorder.java b/source/net/filebot/util/ui/RoundBorder.java index 0dd9cf9b..0edf9922 100644 --- a/source/net/filebot/util/ui/RoundBorder.java +++ b/source/net/filebot/util/ui/RoundBorder.java @@ -13,52 +13,52 @@ import javax.swing.border.AbstractBorder; public class RoundBorder extends AbstractBorder { - + private final Color color; private final Insets insets; private final int arc; - + public RoundBorder() { this.color = new Color(0xACACAC); this.arc = 12; this.insets = new Insets(1, 1, 1, 1); } - + public RoundBorder(Color color, int arc, Insets insets) { this.color = color; this.arc = arc; this.insets = insets; } - + @Override public boolean isBorderOpaque() { return false; } - + @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - + g2d.setPaint(c.getBackground()); g2d.fillRoundRect(x, y, width - 1, height - 1, arc, arc); - + g2d.setPaint(color); g2d.drawRoundRect(x, y, width - 1, height - 1, arc, arc); - + g2d.dispose(); } - + @Override public Insets getBorderInsets(Component c) { return new Insets(insets.top, insets.left, insets.bottom, insets.right); } - + @Override public Insets getBorderInsets(Component c, Insets insets) { @@ -66,8 +66,8 @@ public class RoundBorder extends AbstractBorder { insets.left = this.insets.left; insets.bottom = this.insets.bottom; insets.right = this.insets.right; - + return insets; } - + } diff --git a/source/net/filebot/util/ui/SelectButton.java b/source/net/filebot/util/ui/SelectButton.java index 618661e4..a2901b85 100644 --- a/source/net/filebot/util/ui/SelectButton.java +++ b/source/net/filebot/util/ui/SelectButton.java @@ -226,6 +226,7 @@ public class SelectButton extends JButton { this.icon = icon; } + @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g; @@ -237,10 +238,12 @@ public class SelectButton extends JButton { g2d.fill(arrow); } + @Override public int getIconWidth() { return 30; } + @Override public int getIconHeight() { return 20; } diff --git a/source/net/filebot/util/ui/ShadowBorder.java b/source/net/filebot/util/ui/ShadowBorder.java index 7da15af2..ee2540f6 100644 --- a/source/net/filebot/util/ui/ShadowBorder.java +++ b/source/net/filebot/util/ui/ShadowBorder.java @@ -16,81 +16,81 @@ import javax.swing.border.AbstractBorder; public class ShadowBorder extends AbstractBorder { - + private int smoothness; - + private int smoothnessOffset; - + private int offset; - - + + public ShadowBorder() { this(2, 2, 12); } - + public ShadowBorder(int offset, int smoothness, int smoothnessOffset) { this.offset = offset; this.smoothness = smoothness; this.smoothnessOffset = smoothnessOffset; } - + @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics2D g2d = (Graphics2D) g; - + Color bg = new Color(0, 0, 0, 81); Color faded = new Color(0, 0, 0, 0); - + int a = smoothness + smoothnessOffset; - + Rectangle2D main = new Rectangle2D.Double(a, a, width - a * 2, height - a * 2); - + g2d.setPaint(bg); g2d.fill(main); - + Rectangle2D right = new Rectangle2D.Double(main.getMaxX(), a, a, main.getHeight()); Rectangle2D left = new Rectangle2D.Double(0, a, a, main.getHeight()); Rectangle2D top = new Rectangle2D.Double(a, 0, main.getWidth(), a); Rectangle2D bottom = new Rectangle2D.Double(a, main.getMaxY(), main.getWidth(), a); - + g2d.setPaint(GradientStyle.LEFT_TO_RIGHT.getGradientPaint(right, bg, faded)); g2d.fill(right); - + g2d.setPaint(GradientStyle.RIGHT_TO_LEFT.getGradientPaint(left, bg, faded)); g2d.fill(left); - + g2d.setPaint(GradientStyle.BOTTOM_TO_TOP.getGradientPaint(top, bg, faded)); g2d.fill(top); - + g2d.setPaint(GradientStyle.TOP_TO_BOTTOM.getGradientPaint(bottom, bg, faded)); g2d.fill(bottom); - + Rectangle2D topLeftCorner = new Rectangle2D.Double(0, 0, a, a); Rectangle2D topRightCorner = new Rectangle2D.Double(width - a, 0, a, a); Rectangle2D bottomLeftCorner = new Rectangle2D.Double(0, height - a, a, a); Rectangle2D bottomRightCorner = new Rectangle2D.Double(width - a, height - a, a, a); - + g2d.setPaint(CornerGradientStyle.TOP_LEFT.getGradientPaint(topLeftCorner, a, bg, faded)); g2d.fill(topLeftCorner); - + g2d.setPaint(CornerGradientStyle.TOP_RIGHT.getGradientPaint(topRightCorner, a, bg, faded)); g2d.fill(topRightCorner); - + g2d.setPaint(CornerGradientStyle.BOTTOM_LEFT.getGradientPaint(bottomLeftCorner, a, bg, faded)); g2d.fill(bottomLeftCorner); - + g2d.setPaint(CornerGradientStyle.BOTTOM_RIGHT.getGradientPaint(bottomRightCorner, a, bg, faded)); g2d.fill(bottomRightCorner); } - + @Override public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0, 0, 0, 0)); } - + @Override public Insets getBorderInsets(Component c, Insets insets) { @@ -98,43 +98,43 @@ public class ShadowBorder extends AbstractBorder { insets.bottom = insets.right = Math.max(smoothness + offset, 4); return insets; } - - + + private static enum CornerGradientStyle { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT; - + public RadialGradientPaint getGradientPaint(RectangularShape shape, float radius, Color gradientBeginColor, Color gradientEndColor) { Point2D center = null; - + switch (this) { - case TOP_LEFT: - center = new Point2D.Double(shape.getX() + radius, shape.getY() + radius); - break; - - case TOP_RIGHT: - center = new Point2D.Double(shape.getX() + 0, shape.getY() + radius); - break; - - case BOTTOM_LEFT: - center = new Point2D.Double(shape.getX() + radius, shape.getY() + 0); - break; - - case BOTTOM_RIGHT: - center = new Point2D.Double(shape.getX() + 0, shape.getY() + 0); - break; - - default: - return null; + case TOP_LEFT: + center = new Point2D.Double(shape.getX() + radius, shape.getY() + radius); + break; + + case TOP_RIGHT: + center = new Point2D.Double(shape.getX() + 0, shape.getY() + radius); + break; + + case BOTTOM_LEFT: + center = new Point2D.Double(shape.getX() + radius, shape.getY() + 0); + break; + + case BOTTOM_RIGHT: + center = new Point2D.Double(shape.getX() + 0, shape.getY() + 0); + break; + + default: + return null; } - + float[] dist = { 0.0f, 1.0f }; Color[] colors = { gradientBeginColor, gradientEndColor }; - + return new RadialGradientPaint(center, radius, dist, colors); } } - + } diff --git a/source/net/filebot/util/ui/SimpleLabelProvider.java b/source/net/filebot/util/ui/SimpleLabelProvider.java index 91add07c..e16f3896 100644 --- a/source/net/filebot/util/ui/SimpleLabelProvider.java +++ b/source/net/filebot/util/ui/SimpleLabelProvider.java @@ -14,37 +14,37 @@ import net.filebot.util.ExceptionUtilities; * LabelProvider based on reflection. */ public class SimpleLabelProvider implements LabelProvider { - + private final Method getIconMethod; private final Method getTextMethod; - - + + /** * Factory method for {@link #SimpleLabelProvider(Class)}. - * + * * @return new LabelProvider */ public static SimpleLabelProvider forClass(Class type) { return new SimpleLabelProvider(type); } - + /** * Create a new LabelProvider which will use the getText, getName or toString * method for text and the getIcon method for the * icon. - * + * * @param type a class that has one of the text methods and the icon method */ public SimpleLabelProvider(Class type) { getTextMethod = findAnyMethod(type, "getText", "getName", "toString"); getIconMethod = findAnyMethod(type, "getIcon"); } - + /** * Create a new LabelProvider which will use a specified method of a given class - * + * * @param type a class with the specified method * @param getText a method name such as getText * @param getIcon a method name such as getIcon @@ -53,7 +53,7 @@ public class SimpleLabelProvider implements LabelProvider { getTextMethod = findAnyMethod(type, getText); getIconMethod = findAnyMethod(type, getIcon); } - + private Method findAnyMethod(Class type, String... names) { for (String name : names) { @@ -63,10 +63,10 @@ public class SimpleLabelProvider implements LabelProvider { // try next method name } } - + throw new IllegalArgumentException("Method not found: " + Arrays.toString(names)); } - + @Override public String getText(T value) { @@ -76,7 +76,7 @@ public class SimpleLabelProvider implements LabelProvider { throw ExceptionUtilities.asRuntimeException(e); } } - + @Override public Icon getIcon(T value) { @@ -86,5 +86,5 @@ public class SimpleLabelProvider implements LabelProvider { throw ExceptionUtilities.asRuntimeException(e); } } - + } diff --git a/source/net/filebot/util/ui/SwingWorkerPropertyChangeAdapter.java b/source/net/filebot/util/ui/SwingWorkerPropertyChangeAdapter.java index 529081d5..e5ec021c 100644 --- a/source/net/filebot/util/ui/SwingWorkerPropertyChangeAdapter.java +++ b/source/net/filebot/util/ui/SwingWorkerPropertyChangeAdapter.java @@ -9,7 +9,8 @@ import javax.swing.SwingWorker.StateValue; public abstract class SwingWorkerPropertyChangeAdapter implements PropertyChangeListener { - + + @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("progress")) { progress(evt); @@ -19,33 +20,33 @@ public abstract class SwingWorkerPropertyChangeAdapter implements PropertyChange event(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } } - + protected void state(PropertyChangeEvent evt) { switch ((StateValue) evt.getNewValue()) { - case STARTED: - started(evt); - break; - case DONE: - done(evt); - break; + case STARTED: + started(evt); + break; + case DONE: + done(evt); + break; } } - + protected void progress(PropertyChangeEvent evt) { } - + protected void started(PropertyChangeEvent evt) { } - + protected void done(PropertyChangeEvent evt) { } - + protected void event(String name, Object oldValue, Object newValue) { } - + } diff --git a/source/net/filebot/util/ui/notification/Direction.java b/source/net/filebot/util/ui/notification/Direction.java index a3e86864..efa2ef48 100644 --- a/source/net/filebot/util/ui/notification/Direction.java +++ b/source/net/filebot/util/ui/notification/Direction.java @@ -15,14 +15,14 @@ public enum Direction { SOUTH_WEST(-1, 1, 0.0, 1.0, SwingConstants.SOUTH_WEST), WEST(-1, 0, 0.0, 0.5, SwingConstants.WEST), NORTH_WEST(-1, -1, 0.0, 0.0, SwingConstants.NORTH_WEST); - + public final int vx; public final int vy; public final double ax; public final double ay; public final int swingConstant; - - + + private Direction(int vx, int vy, double ax, double ay, int swingConstant) { this.vx = vx; this.vy = vy; diff --git a/source/net/filebot/util/ui/notification/MessageNotification.java b/source/net/filebot/util/ui/notification/MessageNotification.java index 4b345d2f..c404e775 100644 --- a/source/net/filebot/util/ui/notification/MessageNotification.java +++ b/source/net/filebot/util/ui/notification/MessageNotification.java @@ -21,57 +21,57 @@ import javax.swing.border.Border; public class MessageNotification extends NotificationWindow { - + public MessageNotification(String head, String text, Icon icon, int timeout) { this((Window) null, head, text, icon, timeout); } - + public MessageNotification(String head, String text, Icon icon) { this(head, text, icon, -1); } - + private int margin = 10; private Border marginBorder = BorderFactory.createEmptyBorder(margin, margin, margin, margin); private Border border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(new Color(245, 155, 15), Color.WHITE), marginBorder); - + private JLabel headLabel; private JTextPane textArea; private JLabel imageLabel; - - + + public MessageNotification(Window owner, String head, String text, Icon icon, int timeout) { super(owner, timeout); - + JComponent c = (JComponent) getContentPane(); - + c.setLayout(new BorderLayout(5, 2)); c.setBackground(Color.WHITE); c.setBorder(border); - + JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setOpaque(false); textPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); - + headLabel = new JLabel(head); headLabel.setHorizontalAlignment(SwingConstants.CENTER); headLabel.setFont(headLabel.getFont().deriveFont(Font.BOLD)); textPanel.add(headLabel, BorderLayout.NORTH); - + textArea = new JTextPane(); textArea.setText(text); textArea.setEditable(false); textArea.setOpaque(false); textPanel.add(textArea, BorderLayout.CENTER); - + if (icon != null) { imageLabel = new JLabel(icon); c.add(imageLabel, BorderLayout.WEST); } - + c.add(textPanel, BorderLayout.CENTER); - + pack(); } - + } diff --git a/source/net/filebot/util/ui/notification/NotificationLayout.java b/source/net/filebot/util/ui/notification/NotificationLayout.java index 801aabb6..9c35f921 100644 --- a/source/net/filebot/util/ui/notification/NotificationLayout.java +++ b/source/net/filebot/util/ui/notification/NotificationLayout.java @@ -6,9 +6,9 @@ package net.filebot.util.ui.notification; public interface NotificationLayout { - + public void add(NotificationWindow notification); - + public void remove(NotificationWindow notification); } diff --git a/source/net/filebot/util/ui/notification/NotificationManager.java b/source/net/filebot/util/ui/notification/NotificationManager.java index 5afd1c87..23452ca9 100644 --- a/source/net/filebot/util/ui/notification/NotificationManager.java +++ b/source/net/filebot/util/ui/notification/NotificationManager.java @@ -12,36 +12,36 @@ import net.filebot.util.ui.SwingUI; public class NotificationManager { - + private final NotificationLayout layout; - - + + public NotificationManager() { this(new QueueNotificationLayout()); } - + public NotificationManager(NotificationLayout layout) { this.layout = layout; } - + public void show(NotificationWindow notification) { SwingUI.checkEventDispatchThread(); - + notification.addWindowListener(new RemoveListener()); layout.add(notification); - + notification.setVisible(true); } - - + + private class RemoveListener extends WindowAdapter { - + @Override public void windowClosing(WindowEvent e) { layout.remove((NotificationWindow) e.getWindow()); } } - + } diff --git a/source/net/filebot/util/ui/notification/NotificationWindow.java b/source/net/filebot/util/ui/notification/NotificationWindow.java index 61143870..b520757c 100644 --- a/source/net/filebot/util/ui/notification/NotificationWindow.java +++ b/source/net/filebot/util/ui/notification/NotificationWindow.java @@ -20,59 +20,59 @@ import net.filebot.util.ui.SwingUI; public class NotificationWindow extends JWindow { - + private final int timeout; - - + + public NotificationWindow(Window owner, int timeout) { this(owner, timeout, true); } - + public NotificationWindow(Window owner, int timeout, boolean closeOnClick) { super(owner); this.timeout = timeout; - + setAlwaysOnTop(true); - + if (closeOnClick) { getGlassPane().addMouseListener(clickListener); getGlassPane().setVisible(true); } - + addComponentListener(closeOnTimeout); } - + public NotificationWindow(Window owner) { this(owner, -1); } - + public final void close() { SwingUI.checkEventDispatchThread(); - + // window events are not fired automatically, required for layout updates processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); - + setVisible(false); - + // component events are not fired automatically, used to cancel timeout timer processComponentEvent(new ComponentEvent(this, ComponentEvent.COMPONENT_HIDDEN)); - + dispose(); } - + private final ComponentListener closeOnTimeout = new ComponentAdapter() { - + private Timer timer = null; - - + + @Override public void componentShown(ComponentEvent e) { if (timeout >= 0) { timer = SwingUI.invokeLater(timeout, new Runnable() { - + @Override public void run() { close(); @@ -80,7 +80,7 @@ public class NotificationWindow extends JWindow { }); } } - + @Override public void componentHidden(ComponentEvent e) { @@ -88,15 +88,15 @@ public class NotificationWindow extends JWindow { timer.stop(); } } - + }; - + private final MouseAdapter clickListener = new MouseAdapter() { - + @Override public void mouseClicked(MouseEvent e) { close(); } }; - + } diff --git a/source/net/filebot/util/ui/notification/QueueNotificationLayout.java b/source/net/filebot/util/ui/notification/QueueNotificationLayout.java index 1a10ca8f..83b6c6c5 100644 --- a/source/net/filebot/util/ui/notification/QueueNotificationLayout.java +++ b/source/net/filebot/util/ui/notification/QueueNotificationLayout.java @@ -17,96 +17,98 @@ import java.util.List; public class QueueNotificationLayout implements NotificationLayout { - + private final List notifications = new ArrayList(); - + private final Direction alignment; private final Direction direction; private final Direction growAnchor; - - + + public QueueNotificationLayout() { this(SOUTH_EAST, WEST); } - + public QueueNotificationLayout(Direction alignment, Direction direction) { this.alignment = alignment; this.growAnchor = alignment; this.direction = direction; } - + public QueueNotificationLayout(Direction orientation, Direction direction, Direction growAnchor) { this.alignment = orientation; this.direction = direction; this.growAnchor = growAnchor; } - + private Point getBaseAnchor(Dimension screen, Insets insets) { Point p = new Point(); - + screen.height -= insets.top + insets.bottom; screen.width -= insets.left + insets.right; - + p.x = (int) (alignment.ax * screen.width); p.y = (int) (alignment.ay * screen.height); - + p.x += insets.left; p.y += insets.top; - + return p; } - + private Point getLocation(Point anchor, Dimension size) { Point p = new Point(); - + p.x = (int) (anchor.x - size.width * growAnchor.ax); p.y = (int) (anchor.y - size.height * growAnchor.ay); - + return p; } - + private Point getNextAnchor(Point anchor, Dimension size) { Point p = new Point(); - + p.x = anchor.x + size.width * direction.vx; p.y = anchor.y + size.height * direction.vy; - + return p; } - + + @Override public void add(NotificationWindow notification) { notifications.add(notification); align(notification.getGraphicsConfiguration()); } - + private void align(GraphicsConfiguration gc) { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc); - + Point anchor = getBaseAnchor(screen, insets); - + for (NotificationWindow window : notifications) { Dimension size = window.getSize(); - + Point p = getLocation(anchor, size); window.setLocation(p); - + anchor = getNextAnchor(anchor, size); } } - + + @Override public void remove(NotificationWindow notification) { if (notifications.remove(notification)) { align(notification.getGraphicsConfiguration()); } } - + } diff --git a/source/net/filebot/util/ui/notification/SeparatorBorder.java b/source/net/filebot/util/ui/notification/SeparatorBorder.java index 53e4c752..12ff7447 100644 --- a/source/net/filebot/util/ui/notification/SeparatorBorder.java +++ b/source/net/filebot/util/ui/notification/SeparatorBorder.java @@ -16,74 +16,74 @@ import net.filebot.util.ui.GradientStyle; public class SeparatorBorder extends AbstractBorder { - + private int borderWidth; - + private Color beginColor; - + private Color endColor; - + private GradientStyle gradientStyle; - + private Position position; - - + + public static enum Position { TOP, BOTTOM, LEFT, RIGHT; - + public Rectangle2D getRectangle(RectangularShape shape, int borderWidth) { switch (this) { - case TOP: - return new Rectangle2D.Double(shape.getX(), shape.getY(), shape.getWidth(), borderWidth); - case BOTTOM: - return new Rectangle2D.Double(shape.getX(), shape.getMaxY() - borderWidth, shape.getWidth(), borderWidth); - case LEFT: - return new Rectangle2D.Double(shape.getX(), shape.getY(), borderWidth, shape.getHeight()); - case RIGHT: - return new Rectangle2D.Double(shape.getMaxX() - borderWidth, shape.getY(), borderWidth, shape.getHeight()); - default: - return null; + case TOP: + return new Rectangle2D.Double(shape.getX(), shape.getY(), shape.getWidth(), borderWidth); + case BOTTOM: + return new Rectangle2D.Double(shape.getX(), shape.getMaxY() - borderWidth, shape.getWidth(), borderWidth); + case LEFT: + return new Rectangle2D.Double(shape.getX(), shape.getY(), borderWidth, shape.getHeight()); + case RIGHT: + return new Rectangle2D.Double(shape.getMaxX() - borderWidth, shape.getY(), borderWidth, shape.getHeight()); + default: + return null; } } - + public Insets getInsets(Insets insets, int borderWidth) { switch (this) { - case TOP: - insets.top = borderWidth; - insets.left = insets.right = insets.bottom = 0; - return insets; - case BOTTOM: - insets.bottom = borderWidth; - insets.left = insets.right = insets.top = 0; - return insets; - case LEFT: - insets.left = borderWidth; - insets.right = insets.top = insets.bottom = 0; - return insets; - case RIGHT: - insets.right = borderWidth; - insets.left = insets.top = insets.bottom = 0; - return insets; - default: - return null; + case TOP: + insets.top = borderWidth; + insets.left = insets.right = insets.bottom = 0; + return insets; + case BOTTOM: + insets.bottom = borderWidth; + insets.left = insets.right = insets.top = 0; + return insets; + case LEFT: + insets.left = borderWidth; + insets.right = insets.top = insets.bottom = 0; + return insets; + case RIGHT: + insets.right = borderWidth; + insets.left = insets.top = insets.bottom = 0; + return insets; + default: + return null; } } } - - + + public SeparatorBorder(int height, Color color, Position position) { this(height, color, null, null, position); } - + public SeparatorBorder(int height, Color color, GradientStyle gradientStyle, Position position) { this(height, color, new Color(color.getRed(), color.getGreen(), color.getBlue(), 0), gradientStyle, position); } - + public SeparatorBorder(int height, Color beginColor, Color endColor, GradientStyle gradientStyle, Position position) { this.borderWidth = height; @@ -92,82 +92,82 @@ public class SeparatorBorder extends AbstractBorder { this.gradientStyle = gradientStyle; this.position = position; } - + @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics2D g2d = (Graphics2D) g; - + Rectangle2D shape = position.getRectangle(new Rectangle2D.Double(x, y, width, height), this.borderWidth); - + if (gradientStyle != null && endColor != null) g2d.setPaint(gradientStyle.getGradientPaint(shape, beginColor, endColor)); else g2d.setPaint(beginColor); - + g2d.fill(shape); } - + @Override public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0, 0, 0, 0)); } - + @Override public Insets getBorderInsets(Component c, Insets insets) { return position.getInsets(insets, borderWidth); } - + public Color getBeginColor() { return beginColor; } - + public void setBeginColor(Color beginColor) { this.beginColor = beginColor; } - + public Color getEndColor() { return endColor; } - + public void setEndColor(Color endColor) { this.endColor = endColor; } - + public GradientStyle getGradientStyle() { return gradientStyle; } - + public void setGradientStyle(GradientStyle gradientStyle) { this.gradientStyle = gradientStyle; } - + public int getBorderWidth() { return borderWidth; } - + public void setBorderWidth(int height) { this.borderWidth = height; } - + public Position getPosition() { return position; } - + public void setPosition(Position position) { this.position = position; } - + } diff --git a/source/net/filebot/util/ui/notification/SimpleNotificationLayout.java b/source/net/filebot/util/ui/notification/SimpleNotificationLayout.java index e23c22b6..3c9ff7bc 100644 --- a/source/net/filebot/util/ui/notification/SimpleNotificationLayout.java +++ b/source/net/filebot/util/ui/notification/SimpleNotificationLayout.java @@ -14,65 +14,67 @@ import java.awt.Toolkit; public class SimpleNotificationLayout implements NotificationLayout { - + private NotificationWindow currentNotification; private Direction alignment; - - + + public SimpleNotificationLayout() { this(NORTH); } - + public SimpleNotificationLayout(Direction alignment) { this.alignment = alignment; } - + private Point getBaseAnchor(Dimension screen, Insets insets) { Point p = new Point(); - + screen.height -= insets.top + insets.bottom; screen.width -= insets.left + insets.right; - + p.x = (int) (alignment.ax * screen.width); p.y = (int) (alignment.ay * screen.height); - + p.x += insets.left; p.y += insets.top; - + return p; } - + private Point getLocation(Point anchor, Dimension size) { Point p = new Point(); - + p.x = (int) (anchor.x - size.width * alignment.ax); p.y = (int) (anchor.y - size.height * alignment.ay); - + return p; } - + + @Override public void add(NotificationWindow notification) { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(notification.getGraphicsConfiguration()); Dimension size = notification.getSize(); - + Point anchor = getBaseAnchor(screen, insets); notification.setLocation(getLocation(anchor, size)); - + if (currentNotification != null) { currentNotification.close(); } - + currentNotification = notification; } - + + @Override public void remove(NotificationWindow notification) { - + } - + } diff --git a/source/net/filebot/vfs/MemoryFile.java b/source/net/filebot/vfs/MemoryFile.java index 23b27b0d..9fc1def7 100644 --- a/source/net/filebot/vfs/MemoryFile.java +++ b/source/net/filebot/vfs/MemoryFile.java @@ -6,37 +6,37 @@ import java.nio.ByteBuffer; public class MemoryFile { - + private final String path; - + private final ByteBuffer data; - + public MemoryFile(String path, ByteBuffer data) { // normalize folder separator this.path = path.replace('\\', '/'); this.data = data; } - + public String getName() { return path.substring(path.lastIndexOf("/") + 1); } - + public String getPath() { return path; } - + public ByteBuffer getData() { return data.duplicate(); } - + @Override public String toString() { return path; } - + } diff --git a/source/net/filebot/vfs/SimpleFileInfo.java b/source/net/filebot/vfs/SimpleFileInfo.java index e634e7eb..f01f5aa7 100644 --- a/source/net/filebot/vfs/SimpleFileInfo.java +++ b/source/net/filebot/vfs/SimpleFileInfo.java @@ -20,6 +20,7 @@ public class SimpleFileInfo implements FileInfo, Comparable { return path; } + @Override public String getName() { return getNameWithoutExtension(new File(path).getName()); } @@ -29,6 +30,7 @@ public class SimpleFileInfo implements FileInfo, Comparable { return getExtension(path); } + @Override public long getLength() { return length; } diff --git a/source/net/filebot/vfs/ZipArchive.java b/source/net/filebot/vfs/ZipArchive.java index b3cc0e44..7db22e81 100644 --- a/source/net/filebot/vfs/ZipArchive.java +++ b/source/net/filebot/vfs/ZipArchive.java @@ -15,14 +15,14 @@ import net.filebot.util.ByteBufferOutputStream; public class ZipArchive implements Iterable { - + private final ByteBuffer data; - + public ZipArchive(ByteBuffer data) { this.data = data.duplicate(); } - + @Override public Iterator iterator() { @@ -32,34 +32,34 @@ public class ZipArchive implements Iterable { throw new RuntimeException(e); } } - + public List extract() throws IOException { List vfs = new ArrayList(); - + // read first zip entry ZipInputStream zipInputStream = new ZipInputStream(new ByteBufferInputStream(data.duplicate())); ZipEntry zipEntry; - + try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { // ignore directory entries if (zipEntry.isDirectory()) { continue; } - + ByteBufferOutputStream buffer = new ByteBufferOutputStream((int) zipEntry.getSize()); - + // write contents to buffer buffer.transferFully(zipInputStream); - + // add memory file vfs.add(new MemoryFile(zipEntry.getName(), buffer.getByteBuffer())); } } finally { zipInputStream.close(); } - + return vfs; } } diff --git a/source/net/filebot/web/AbstractEpisodeListProvider.java b/source/net/filebot/web/AbstractEpisodeListProvider.java index 31fb3f1d..8be39705 100644 --- a/source/net/filebot/web/AbstractEpisodeListProvider.java +++ b/source/net/filebot/web/AbstractEpisodeListProvider.java @@ -54,6 +54,7 @@ public abstract class AbstractEpisodeListProvider implements EpisodeListProvider return getSeriesData(searchResult, null, language).getSeriesInfo(); } + @Override public SeriesInfo getSeriesInfo(int id, Locale language) throws Exception { return getSeriesInfo(createSearchResult(id), language); } diff --git a/source/net/filebot/web/AcoustIDClient.java b/source/net/filebot/web/AcoustIDClient.java index c9fff929..856b3569 100644 --- a/source/net/filebot/web/AcoustIDClient.java +++ b/source/net/filebot/web/AcoustIDClient.java @@ -131,7 +131,7 @@ public class AcoustIDClient implements MusicIdentificationService { } public AudioTrack parseResult(String json, final int targetDuration) throws IOException { - Map data = (Map) JsonReader.jsonToMaps(json); + Map data = JsonReader.jsonToMaps(json); if (!data.get("status").equals("ok")) { throw new IOException("acoustid responded with error: " + data.get("status")); diff --git a/source/net/filebot/web/AudioTrackFormat.java b/source/net/filebot/web/AudioTrackFormat.java index d39ddbd4..83d62410 100644 --- a/source/net/filebot/web/AudioTrackFormat.java +++ b/source/net/filebot/web/AudioTrackFormat.java @@ -8,13 +8,13 @@ import java.text.ParsePosition; public class AudioTrackFormat extends Format { - + @Override public StringBuffer format(Object obj, StringBuffer sb, FieldPosition pos) { return sb.append(obj.toString()); } - - + + @Override public AudioTrack parseObject(String source, ParsePosition pos) { String[] s = source.split(" - ", 2); @@ -26,5 +26,5 @@ public class AudioTrackFormat extends Format { return null; } } - + } diff --git a/source/net/filebot/web/MovieFormat.java b/source/net/filebot/web/MovieFormat.java index 89f75dcb..9aedb76f 100644 --- a/source/net/filebot/web/MovieFormat.java +++ b/source/net/filebot/web/MovieFormat.java @@ -11,54 +11,54 @@ import java.util.regex.Pattern; public class MovieFormat extends Format { - + public static final MovieFormat NameYear = new MovieFormat(true, true, true); - + private final boolean includeYear; private final boolean includePartIndex; private final boolean smart; - - + + public MovieFormat(boolean includeYear, boolean includePartIndex, boolean smart) { this.includeYear = includeYear; this.includePartIndex = includePartIndex; this.smart = smart; } - - + + @Override public StringBuffer format(Object obj, StringBuffer sb, FieldPosition pos) { // format episode object, e.g. Avatar (2009), Part 1 Movie movie = (Movie) obj; - + sb.append(movie.getName()); - + if (includeYear) { if (!smart || movie.getYear() > 0) { sb.append(' ').append('(').append(movie.getYear()).append(')'); } } - + if (includePartIndex && movie instanceof MoviePart) { MoviePart part = (MoviePart) movie; - + if (!smart || part.partCount > 1) { sb.append(", Part ").append(part.partIndex); } } - + return sb; } - + private final Pattern moviePattern = Pattern.compile("([^\\p{Punct}]+?)[\\p{Punct}\\s]+(\\d{4})(?:[\\p{Punct}\\s]+|$)"); private final Pattern partPattern = Pattern.compile("(?:Part|CD)\\D?(\\d)$", Pattern.CASE_INSENSITIVE); - - + + @Override public Movie parseObject(String source, ParsePosition pos) { String s = source; Matcher m; - + // extract part information first int partIndex = -1; int partCount = -1; @@ -66,31 +66,31 @@ public class MovieFormat extends Format { partIndex = Integer.parseInt(m.group(1)); s = m.replaceFirst(""); } - + // parse movie information if ((m = moviePattern.matcher(s)).matches()) { String name = m.group(1).trim(); int year = Integer.parseInt(m.group(2)); - + Movie movie = new Movie(name, year, -1, -1); if (partIndex >= 0) { movie = new MoviePart(movie, partIndex, partCount); } - + // did parse input pos.setIndex(source.length()); return movie; } - + // failed to parse input pos.setErrorIndex(0); return null; } - - + + @Override public Movie parseObject(String source) throws ParseException { return (Movie) super.parseObject(source); } - + } diff --git a/source/net/filebot/web/OpenSubtitlesClient.java b/source/net/filebot/web/OpenSubtitlesClient.java index 6803bcfc..6f510b17 100644 --- a/source/net/filebot/web/OpenSubtitlesClient.java +++ b/source/net/filebot/web/OpenSubtitlesClient.java @@ -371,7 +371,7 @@ public class OpenSubtitlesClient implements SubtitleProvider, VideoHashSubtitleS // search for movies and series List result = getCache().getSearchResult("search", query); if (result != null) { - return (List) result; + return result; } // require login @@ -469,7 +469,7 @@ public class OpenSubtitlesClient implements SubtitleProvider, VideoHashSubtitleS @Override public URI getSubtitleListLink(SubtitleSearchResult searchResult, String languageName) { - Movie movie = (Movie) searchResult; + Movie movie = searchResult; String sublanguageid = "all"; if (languageName != null) { diff --git a/source/net/filebot/web/OpenSubtitlesSubtitleDescriptor.java b/source/net/filebot/web/OpenSubtitlesSubtitleDescriptor.java index 603ffa35..c07f3ec5 100644 --- a/source/net/filebot/web/OpenSubtitlesSubtitleDescriptor.java +++ b/source/net/filebot/web/OpenSubtitlesSubtitleDescriptor.java @@ -17,7 +17,7 @@ import net.filebot.util.FileUtilities; /** * Describes a subtitle on OpenSubtitles. - * + * * @see OpenSubtitlesXmlRpc */ public class OpenSubtitlesSubtitleDescriptor implements SubtitleDescriptor, Serializable { diff --git a/source/net/filebot/web/OpenSubtitlesXmlRpc.java b/source/net/filebot/web/OpenSubtitlesXmlRpc.java index 665a7405..88783423 100644 --- a/source/net/filebot/web/OpenSubtitlesXmlRpc.java +++ b/source/net/filebot/web/OpenSubtitlesXmlRpc.java @@ -51,7 +51,7 @@ public class OpenSubtitlesXmlRpc { /** * This will login user. This method should be called always when starting talking with server. - * + * * @param username * username (blank for anonymous user) * @param password @@ -334,6 +334,7 @@ public class OpenSubtitlesXmlRpc { protected Map invoke(String method, Object... arguments) throws XmlRpcFault { try { XmlRpcClient rpc = new XmlRpcClient(getXmlRpcUrl(), false) { + @Override public void parse(InputStream input) throws XmlRpcException { try { super.parse(new GZIPInputStream(input)); @@ -386,7 +387,7 @@ public class OpenSubtitlesXmlRpc { /** * Check whether status is OK or not - * + * * @param status * status code and message (e.g. 200 OK, 401 Unauthorized, ...) * @throws XmlRpcFault diff --git a/source/net/filebot/web/SeasonOutOfBoundsException.java b/source/net/filebot/web/SeasonOutOfBoundsException.java index 3ea2e448..5cb4ae38 100644 --- a/source/net/filebot/web/SeasonOutOfBoundsException.java +++ b/source/net/filebot/web/SeasonOutOfBoundsException.java @@ -3,37 +3,37 @@ package net.filebot.web; public class SeasonOutOfBoundsException extends IndexOutOfBoundsException { - + private final String seriesName; private final int season; private final int lastSeason; - - + + public SeasonOutOfBoundsException(String seriesName, int season, int lastSeason) { this.seriesName = seriesName; this.season = season; this.lastSeason = lastSeason; } - + @Override public String getMessage() { return String.format("%s has only %d season%s.", seriesName, lastSeason, lastSeason != 1 ? "s" : ""); } - + public String getSeriesName() { return seriesName; } - + public int getSeason() { return season; } - + public int getLastSeason() { return lastSeason; } - + } diff --git a/source/net/filebot/web/SubtitleDescriptor.java b/source/net/filebot/web/SubtitleDescriptor.java index 6dac49b2..0c84ad66 100644 --- a/source/net/filebot/web/SubtitleDescriptor.java +++ b/source/net/filebot/web/SubtitleDescriptor.java @@ -8,16 +8,18 @@ import net.filebot.vfs.FileInfo; public interface SubtitleDescriptor extends FileInfo { - + + @Override String getName(); - + String getLanguageName(); - + + @Override String getType(); - + ByteBuffer fetch() throws Exception; - + } diff --git a/source/net/filebot/web/TheTVDBClient.java b/source/net/filebot/web/TheTVDBClient.java index a72d7220..647a0236 100644 --- a/source/net/filebot/web/TheTVDBClient.java +++ b/source/net/filebot/web/TheTVDBClient.java @@ -314,6 +314,7 @@ public class TheTVDBClient extends AbstractEpisodeListProvider { protected Document getXmlResource(final MirrorType mirrorType, final String path) throws IOException { CachedXmlResource resource = new CachedXmlResource(path) { + @Override protected URL getResourceLocation(String path) throws IOException { return getResourceURL(mirrorType, path); }; @@ -379,7 +380,7 @@ public class TheTVDBClient extends AbstractEpisodeListProvider { /** * Search for a series banner matching the given parameters - * + * * @see http://thetvdb.com/wiki/index.php/API:banners.xml */ public BannerDescriptor getBanner(TheTVDBSearchResult series, Map filterDescriptor) throws Exception { diff --git a/test/net/filebot/format/ExpressionFormatTest.java b/test/net/filebot/format/ExpressionFormatTest.java index 7caa256e..cbb0e2c3 100644 --- a/test/net/filebot/format/ExpressionFormatTest.java +++ b/test/net/filebot/format/ExpressionFormatTest.java @@ -13,60 +13,60 @@ import org.junit.Test; public class ExpressionFormatTest { - + @Test public void compile() throws Exception { ExpressionFormat format = new TestScriptFormat(""); - + Object[] expression = format.compile("name: {name}, number: {number}"); - + assertTrue(expression[0] instanceof String); assertTrue(expression[1] instanceof CompiledScript); assertTrue(expression[2] instanceof String); assertTrue(expression[3] instanceof CompiledScript); } - - + + @Test public void format() throws Exception { assertEquals("X5-452", new TestScriptFormat("X5-{value}").format("452")); - + // padding assertEquals("[007]", new TestScriptFormat("[{value.pad(3)}]").format("7")); assertEquals("[xx7]", new TestScriptFormat("[{value.pad(3, 'x')}]").format("7")); - + // case assertEquals("ALL_CAPS", new TestScriptFormat("{value.upper()}").format("all_caps")); assertEquals("lower_case", new TestScriptFormat("{value.lower()}").format("LOWER_CASE")); - + // normalize assertEquals("Doctor_Who", new TestScriptFormat("{value.space('_')}").format("Doctor Who")); assertEquals("The Day A New Demon Was Born", new TestScriptFormat("{value.upperInitial()}").format("The Day a new Demon was born")); assertEquals("Gundam Seed", new TestScriptFormat("{value.lowerTrail()}").format("Gundam SEED")); - + // substring assertEquals("first", new TestScriptFormat("{value.before(/[^a-z]/)}").format("first|second")); assertEquals("second", new TestScriptFormat("{value.after(/[^a-z]/)}").format("first|second")); - + // replace trailing braces assertEquals("The IT Crowd", new TestScriptFormat("{value.replaceTrailingBrackets()}").format("The IT Crowd (UK)")); - + // replace part assertEquals("Today Is the Day, Part 1", new TestScriptFormat("{value.replacePart(', Part $1')}").format("Today Is the Day (1)")); assertEquals("Today Is the Day, Part 1", new TestScriptFormat("{value.replacePart(', Part $1')}").format("Today Is the Day: part 1")); - + // choice assertEquals("not to be", new TestScriptFormat("{value ? 'to be' : 'not to be'}").format(null)); assertEquals("default", new TestScriptFormat("{value ?: 'default'}").format(null)); } - - + + @Test public void closures() throws Exception { assertEquals("[ant, cat]", new TestScriptFormat("{['ant', 'buffalo', 'cat', 'dinosaur'].findAll{ it.size() <= 3 }}").format(null)); } - - + + @Test public void illegalSyntax() throws Exception { try { @@ -79,8 +79,8 @@ public class ExpressionFormatTest { assertEquals("SyntaxError: unexpected token: .", e.getMessage()); } } - - + + @Test public void illegalClosingBracket() throws Exception { try { @@ -93,44 +93,44 @@ public class ExpressionFormatTest { assertEquals("SyntaxError: unexpected token: }", e.getMessage()); } } - - + + @Test public void illegalBinding() throws Exception { TestScriptFormat format = new TestScriptFormat("{xyz}"); format.format(new SimpleBindings()); - + // check message assertEquals("BindingException: \"xyz\": undefined", format.caughtScriptException().getMessage()); } - - + + @Test public void illegalProperty() throws Exception { TestScriptFormat format = new TestScriptFormat("{value.xyz}"); format.format("test"); - + // check message assertEquals("BindingException: \"xyz\": undefined", format.caughtScriptException().getMessage()); } - - + + protected static class TestScriptFormat extends ExpressionFormat { - + public TestScriptFormat(String format) throws ScriptException { super(format); } - - + + @Override public Bindings getBindings(Object value) { Bindings bindings = new SimpleBindings(); - + bindings.put("value", value); - + return bindings; } - + } - + } diff --git a/test/net/filebot/hash/VerificationFormatTest.java b/test/net/filebot/hash/VerificationFormatTest.java index 60f07c3f..35c7f179 100644 --- a/test/net/filebot/hash/VerificationFormatTest.java +++ b/test/net/filebot/hash/VerificationFormatTest.java @@ -11,21 +11,21 @@ import org.junit.Test; public class VerificationFormatTest { - + @Test public void parseLine() throws Exception { VerificationFormat format = new VerificationFormat(); - - // md5 + + // md5 Entry md5 = format.parseObject("50e85fe18e17e3616774637a82968f4c *folder/file.txt"); - + assertEquals("file.txt", md5.getKey().getName()); assertEquals("folder", md5.getKey().getParent()); assertEquals("50e85fe18e17e3616774637a82968f4c", md5.getValue()); - + // sha1 Entry sha1 = format.parseObject("1a02a7c1e9ac91346d08829d5037b240f42ded07 ?SHA1*folder/file.txt"); - + assertEquals("file.txt", sha1.getKey().getName()); assertEquals("folder", sha1.getKey().getParent()); assertEquals("1a02a7c1e9ac91346d08829d5037b240f42ded07", sha1.getValue()); diff --git a/test/net/filebot/media/ReleaseInfoTest.java b/test/net/filebot/media/ReleaseInfoTest.java index 8db64699..613e3e86 100644 --- a/test/net/filebot/media/ReleaseInfoTest.java +++ b/test/net/filebot/media/ReleaseInfoTest.java @@ -10,22 +10,22 @@ import org.junit.Test; public class ReleaseInfoTest { - + @Test public void getVideoSource() { ReleaseInfo info = new ReleaseInfo(); File f = new File("Jurassic.Park[1993]DvDrip-aXXo.avi"); - + assertEquals("DVDRip", info.getVideoSource(f.getName())); } - - + + @Test public void getReleaseGroup() throws Exception { ReleaseInfo info = new ReleaseInfo(); File f = new File("Jurassic.Park[1993]DvDrip-aXXo.avi"); - + assertEquals("aXXo", info.getReleaseGroup(f.getName())); } - + } diff --git a/test/net/filebot/similarity/DateMetricTest.java b/test/net/filebot/similarity/DateMetricTest.java index 1d9080c2..32ded121 100644 --- a/test/net/filebot/similarity/DateMetricTest.java +++ b/test/net/filebot/similarity/DateMetricTest.java @@ -8,9 +8,9 @@ import org.junit.Test; public class DateMetricTest { - + private static DateMetric metric = new DateMetric(); - + @Test public void getSimilarity() { @@ -19,5 +19,5 @@ public class DateMetricTest { assertEquals(1, metric.getSimilarity("2008-04-03", "The Daily Show - 2008.04.03 - George Clooney"), 0); assertEquals(0, metric.getSimilarity("2008-01-01", "The Daily Show - 2008.04.03 - George Clooney"), 0); } - + } diff --git a/test/net/filebot/similarity/NameSimilarityMetricTest.java b/test/net/filebot/similarity/NameSimilarityMetricTest.java index bd7b4320..f5ebe11e 100644 --- a/test/net/filebot/similarity/NameSimilarityMetricTest.java +++ b/test/net/filebot/similarity/NameSimilarityMetricTest.java @@ -8,9 +8,9 @@ import org.junit.Test; public class NameSimilarityMetricTest { - + private static NameSimilarityMetric metric = new NameSimilarityMetric(); - + @Test public void getSimilarity() { @@ -20,5 +20,5 @@ public class NameSimilarityMetricTest { assertEquals(1, metric.getSimilarity("test s01e03 third", "__test__S01E03__Third__"), 0); assertEquals(1, metric.getSimilarity("test s01e04 four", "test s01e04 four"), 0); } - + } diff --git a/test/net/filebot/similarity/NumericSimilarityMetricTest.java b/test/net/filebot/similarity/NumericSimilarityMetricTest.java index dc000ad2..e34e617c 100644 --- a/test/net/filebot/similarity/NumericSimilarityMetricTest.java +++ b/test/net/filebot/similarity/NumericSimilarityMetricTest.java @@ -18,15 +18,15 @@ import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class NumericSimilarityMetricTest { - + private static NumericSimilarityMetric metric = new NumericSimilarityMetric(); - + private static Map matches = createMatches(); - - + + public static Map createMatches() { Map matches = new LinkedHashMap(); - + // lots of naming variations matches.put("Test - 1x01", "test.S01E01.Pilot.HDTV.XviD-FQM"); matches.put("Test - 1x02", "test.S01E02.HDTV.XviD-DIMENSION"); @@ -46,49 +46,49 @@ public class NumericSimilarityMetricTest { matches.put("Test - 1x16", "test.1x16.0tv.VO"); matches.put("Test - 1x17", "Test.S01E17.42.is.the.answer.DSR.XviD-0TV"); matches.put("Test - 1x18", "Test.S01E18.DSR.XviD-0TV"); - + // lots of numbers matches.put("The 4400 - 1x01", "the.4400.s1e01.pilot.720p"); matches.put("The 4400 - 4x04", "the.4400.s4e04.eden.720p"); - + return matches; } - + @Parameters public static Collection createParameters() { return TestUtil.asParameters(matches.keySet()); } - + private final String normalizedName; - - + + public NumericSimilarityMetricTest(String normalizedName) { this.normalizedName = normalizedName; } - + @Test public void getBestMatch() { String match = getBestMatch(normalizedName, matches.values()); - + assertEquals(matches.get(normalizedName), match); } - + public String getBestMatch(String value, Collection testdata) { double maxSimilarity = -1; String mostSimilar = null; - + for (String current : testdata) { double similarity = metric.getSimilarity(value, current); - + if (similarity > maxSimilarity) { maxSimilarity = similarity; mostSimilar = current; } } - + return mostSimilar; } } diff --git a/test/net/filebot/similarity/SeasonEpisodeMetricTest.java b/test/net/filebot/similarity/SeasonEpisodeMetricTest.java index 392c41b2..185f6fb5 100644 --- a/test/net/filebot/similarity/SeasonEpisodeMetricTest.java +++ b/test/net/filebot/similarity/SeasonEpisodeMetricTest.java @@ -8,23 +8,23 @@ import org.junit.Test; public class SeasonEpisodeMetricTest { - + private static SeasonEpisodeMetric metric = new SeasonEpisodeMetric(); - + @Test public void getSimilarity() { // single pattern match, single episode match assertEquals(1.0, metric.getSimilarity("1x01", "s01e01"), 0); - + // multiple pattern matches, single episode match assertEquals(1.0, metric.getSimilarity("1x02a", "101 102 103"), 0); - + // multiple pattern matches, only partial match (season) assertEquals(0.5, metric.getSimilarity("1x03b", "104 105 106"), 0); - + // no pattern match, no episode match assertEquals(0.0, metric.getSimilarity("abc", "xyz"), 0); } - + } diff --git a/test/net/filebot/similarity/SeriesNameMatcherTest.java b/test/net/filebot/similarity/SeriesNameMatcherTest.java index 3a0ff2b4..28719813 100644 --- a/test/net/filebot/similarity/SeriesNameMatcherTest.java +++ b/test/net/filebot/similarity/SeriesNameMatcherTest.java @@ -9,73 +9,73 @@ import org.junit.Test; public class SeriesNameMatcherTest { - + private static SeriesNameMatcher matcher = new SeriesNameMatcher(); - - + + @Test public void whitelist() { - // ignore recurring word sequences when matching episode patterns + // ignore recurring word sequences when matching episode patterns String[] names = new String[] { "Test 101 - 01", "Test 101 - 02" }; - + assertArrayEquals(new String[] { "Test 101" }, matcher.matchAll(names).toArray()); } - - + + @Test public void threshold() { - // ignore recurring word sequences when matching episode patterns + // ignore recurring word sequences when matching episode patterns String[] names = new String[] { "Test 1 of 101", "Test 2 of 101", "Test 3 of 101" }; - + assertArrayEquals(new String[] { "Test" }, matcher.matchAll(names).toArray()); } - - + + @Test public void matchBeforeSeasonEpisodePattern() { assertEquals("The Test", matcher.matchByEpisodeIdentifier("The Test - 1x01")); - + // real world test assertEquals("Mushishi", matcher.matchByEpisodeIdentifier("[niizk]_Mushishi_-_1x01_-_The_Green_Gathering")); } - - + + @Test public void normalize() { // non-letter and non-digit characters assertEquals("The Test", matcher.normalize("_The_Test_-_ ...")); - + // brackets assertEquals("Luffy", matcher.normalize("[strawhat] Luffy (D.) [#Monkey]")); - + // invalid brackets assertEquals("strawhat Luffy", matcher.normalize("(strawhat [Luffy (#Monkey)")); } - - + + @Test public void firstCommonSequence() { String[] seq1 = "Common Name 1 Any Title".split("\\s"); String[] seq2 = "abc xyz Common Name 2 Any Title".split("\\s"); - + // check if common sequence can be determined assertArrayEquals(new String[] { "Common", "Name" }, matcher.firstCommonSequence(seq1, seq2, 2, String.CASE_INSENSITIVE_ORDER)); - + // check if max start index is working assertArrayEquals(null, matcher.firstCommonSequence(seq1, seq2, 0, String.CASE_INSENSITIVE_ORDER)); assertArrayEquals(null, matcher.firstCommonSequence(seq2, seq1, 1, String.CASE_INSENSITIVE_ORDER)); } - - + + @Test public void firstCharacterCaseBalance() { SeriesNameCollection n = new SeriesNameCollection(); - + assertTrue(n.firstCharacterCaseBalance("My Name is Earl") > n.firstCharacterCaseBalance("My Name Is Earl")); assertTrue(n.firstCharacterCaseBalance("My Name is Earl") > n.firstCharacterCaseBalance("my name is earl")); - + // boost upper case ration assertTrue(n.firstCharacterCaseBalance("Roswell") > n.firstCharacterCaseBalance("roswell")); - + } } diff --git a/test/net/filebot/similarity/SimilarityTestSuite.java b/test/net/filebot/similarity/SimilarityTestSuite.java index b0f1c054..9db50d04 100644 --- a/test/net/filebot/similarity/SimilarityTestSuite.java +++ b/test/net/filebot/similarity/SimilarityTestSuite.java @@ -10,5 +10,5 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { SeriesNameMatcherTest.class, SeasonEpisodeMatcherTest.class, NameSimilarityMetricTest.class, NumericSimilarityMetricTest.class, SeasonEpisodeMetricTest.class }) public class SimilarityTestSuite { - + } diff --git a/test/net/filebot/subtitle/MicroDVDReaderTest.java b/test/net/filebot/subtitle/MicroDVDReaderTest.java index cc4a045e..a3045269 100644 --- a/test/net/filebot/subtitle/MicroDVDReaderTest.java +++ b/test/net/filebot/subtitle/MicroDVDReaderTest.java @@ -10,37 +10,37 @@ import org.junit.Test; public class MicroDVDReaderTest { - + @Test public void parse() throws Exception { MicroDVDReader reader = new MicroDVDReader(new StringReader("{856}{900}what's the plan?")); - + SubtitleElement element = reader.next(); - + assertEquals(856 * 23.976, element.getStart(), 1); assertEquals(900 * 23.976, element.getEnd(), 1); assertEquals("what's the plan?", element.getText()); } - + @Test public void fps() throws Exception { MicroDVDReader reader = new MicroDVDReader(new StringReader("{1}{1}100\n{300}{400} trim me ")); - + SubtitleElement element = reader.next(); - + assertEquals(300 * 100, element.getStart(), 0); assertEquals(400 * 100, element.getEnd(), 0); assertEquals("trim me", element.getText()); } - + @Test public void newline() throws Exception { MicroDVDReader reader = new MicroDVDReader(new StringReader("\n\n{300}{400} l1|l2|l3| \n\n")); - + String[] lines = reader.next().getText().split("\\n"); - + assertEquals(3, lines.length); assertEquals("l1", lines[0]); assertEquals("l2", lines[1]); diff --git a/test/net/filebot/subtitle/SubRipReaderTest.java b/test/net/filebot/subtitle/SubRipReaderTest.java index c012170b..a4d416be 100644 --- a/test/net/filebot/subtitle/SubRipReaderTest.java +++ b/test/net/filebot/subtitle/SubRipReaderTest.java @@ -15,16 +15,16 @@ import org.junit.Test; public class SubRipReaderTest { - + @Test public void parse() throws Exception { List list = new ArrayList(); - + URL resource = new URL("http://www.opensubtitles.org/en/download/file/1951733951.gz"); InputStream source = new GZIPInputStream(resource.openStream()); - + SubRipReader reader = new SubRipReader(new InputStreamReader(source, "UTF-8")); - + try { while (reader.hasNext()) { list.add(reader.next()); @@ -32,7 +32,7 @@ public class SubRipReaderTest { } finally { reader.close(); } - + assertEquals(501, list.size(), 0); } } diff --git a/test/net/filebot/subtitle/SubtitleReaderTestSuite.java b/test/net/filebot/subtitle/SubtitleReaderTestSuite.java index 8d9340bf..e4074a6e 100644 --- a/test/net/filebot/subtitle/SubtitleReaderTestSuite.java +++ b/test/net/filebot/subtitle/SubtitleReaderTestSuite.java @@ -10,5 +10,5 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { SubRipReaderTest.class, MicroDVDReaderTest.class }) public class SubtitleReaderTestSuite { - + } diff --git a/test/net/filebot/ui/rename/MatchModelTest.java b/test/net/filebot/ui/rename/MatchModelTest.java index 2a6722fa..cac71639 100644 --- a/test/net/filebot/ui/rename/MatchModelTest.java +++ b/test/net/filebot/ui/rename/MatchModelTest.java @@ -16,86 +16,86 @@ import ca.odell.glazedlists.GlazedLists; public class MatchModelTest { - + @Test public void addAll() { MatchModel model = new MatchModel(); - + List names = Arrays.asList("A", "B", "C", "D", "E"); List values = Arrays.asList(1, 2, 3); - + model.addAll(Arrays.asList("A", "B", "C", "D", "E"), Arrays.asList(1, 2, 3)); - + assertEquals(5, model.size(), 0); - + for (int i = 0; i < model.size(); i++) { String name = i < names.size() ? names.get(i) : null; Integer value = i < values.size() ? values.get(i) : null; - + // check model and views assertMatchEquals(name, value, model.matches().get(i)); assertEquals(name, model.values().get(i)); assertEquals(value, model.candidates().get(i)); } } - + @Test public void matchViewElements() { MatchModel model = new MatchModel(); model.addAll(Arrays.asList("A", "B", "C"), Arrays.asList(1, 2, 3, 4, 5)); - + model.values().add("D"); assertMatchEquals("D", 4, model.getMatch(3)); - + model.values().add(1, "A2"); assertMatchEquals("C", 4, model.getMatch(3)); - + model.candidates().remove(3); assertMatchEquals("C", 5, model.getMatch(3)); - + model.candidates().remove(3); assertMatchEquals("C", null, model.getMatch(3)); - + model.matches().remove(0); assertMatchEquals("A2", 2, model.getMatch(0)); - + model.values().set(0, "A"); assertMatchEquals("A", 2, model.getMatch(0)); } - + @Test public void matchViewClear() { MatchModel model = new MatchModel(); - + model.values().addAll(Arrays.asList("A", "B", "C")); model.candidates().addAll(Arrays.asList(1, 2, 3, 4, 5)); - + model.values().clear(); - + assertEquals(0, model.values().size(), 0); assertEquals(5, model.candidates().size(), 0); - + model.values().addAll(Arrays.asList("A", "B", "C")); - + assertMatchEquals("A", 1, model.getMatch(0)); assertMatchEquals("C", 3, model.getMatch(2)); } - + @Test public void matchViewListEvents() { MatchModel model = new MatchModel(); - + ArrayList copy = new ArrayList(); GlazedLists.syncEventListToList(model.values(), copy); - + model.addAll(Arrays.asList("A", "B", "C"), Arrays.asList(1, 2, 3, 4, 5)); - + assertArrayEquals(Arrays.asList("A", "B", "C").toArray(), copy.toArray()); } - + private static void assertMatchEquals(V expectedValue, C expectedCandidate, Match actual) { assertEquals(expectedValue, actual.getValue()); diff --git a/test/net/filebot/util/ByteBufferOutputStreamTest.java b/test/net/filebot/util/ByteBufferOutputStreamTest.java index 5ea55b53..f3d38158 100644 --- a/test/net/filebot/util/ByteBufferOutputStreamTest.java +++ b/test/net/filebot/util/ByteBufferOutputStreamTest.java @@ -13,35 +13,35 @@ import org.junit.Test; public class ByteBufferOutputStreamTest { - + @Test public void growBufferAsNeeded() throws Exception { // initial buffer size of 1, increase size by a factor of 2 if a bigger buffer is needed ByteBufferOutputStream buffer = new ByteBufferOutputStream(1, 1.0f); - + buffer.write("asdf".getBytes("utf-8")); - + // check content assertEquals("asdf", Charset.forName("utf-8").decode(buffer.getByteBuffer()).toString()); - + // check capacity assertEquals(4, buffer.capacity()); } - + @Test public void transferFrom() throws Exception { InputStream in = new ByteArrayInputStream("asdf".getBytes("utf-8")); - + ByteBufferOutputStream buffer = new ByteBufferOutputStream(4); - + int n = buffer.transferFrom(Channels.newChannel(in)); - + // check number of bytes transfered assertEquals(4, n); - + // check content assertEquals("asdf", Charset.forName("utf-8").decode(buffer.getByteBuffer()).toString()); } - + } diff --git a/test/net/filebot/util/FileUtilitiesTest.java b/test/net/filebot/util/FileUtilitiesTest.java index 72708f1d..8ebf0c14 100644 --- a/test/net/filebot/util/FileUtilitiesTest.java +++ b/test/net/filebot/util/FileUtilitiesTest.java @@ -8,37 +8,37 @@ import org.junit.Test; public class FileUtilitiesTest { - + @Test public void hasExtension() { assertTrue(FileUtilities.hasExtension("abc.txt", "txt")); assertFalse(FileUtilities.hasExtension(".hidden", "txt")); } - - + + @Test public void getExtension() { assertEquals("txt", FileUtilities.getExtension("abc.txt")); assertEquals("out", FileUtilities.getExtension("a.out")); assertEquals(null, FileUtilities.getExtension(".hidden")); assertEquals(null, FileUtilities.getExtension("a.")); - + assertEquals("r00", FileUtilities.getExtension("archive.r00")); assertEquals(null, FileUtilities.getExtension("archive.r??")); assertEquals(null, FileUtilities.getExtension("archive.invalid extension")); } - - + + @Test public void getNameWithoutExtension() { assertEquals("abc", FileUtilities.getNameWithoutExtension("abc.txt")); assertEquals("a", FileUtilities.getNameWithoutExtension("a.out")); assertEquals(".hidden", FileUtilities.getNameWithoutExtension(".hidden")); assertEquals("a.", FileUtilities.getNameWithoutExtension("a.")); - + assertEquals("archive", FileUtilities.getNameWithoutExtension("archive.r00")); assertEquals("archive.r??", FileUtilities.getNameWithoutExtension("archive.r??")); assertEquals("archive.invalid extension", FileUtilities.getNameWithoutExtension("archive.invalid extension")); } - + } diff --git a/test/net/filebot/util/FilterIteratorTest.java b/test/net/filebot/util/FilterIteratorTest.java index 6be4875c..ea00bca6 100644 --- a/test/net/filebot/util/FilterIteratorTest.java +++ b/test/net/filebot/util/FilterIteratorTest.java @@ -13,10 +13,10 @@ import org.junit.Test; public class FilterIteratorTest { - + private List list = new ArrayList(); - - + + @Before public void setUp() { list.add("first one"); @@ -26,35 +26,35 @@ public class FilterIteratorTest { list.add("5"); list.add("last order"); } - + @Test public void iterateAndRemove() { Iterator integers = new FilterIterator(list) { - + @Override protected Integer filter(String sourceValue) { if (sourceValue.matches("\\d+")) return Integer.valueOf(sourceValue); - + return null; } }; - + assertEquals(Integer.valueOf(2), integers.next()); integers.remove(); assertEquals(Integer.valueOf(5), integers.next()); integers.remove(); - + assertFalse(integers.hasNext()); - + // check if remove() worked Iterator strings = list.iterator(); assertEquals("first one", strings.next()); assertEquals("third space", strings.next()); assertEquals("four square", strings.next()); assertEquals("last order", strings.next()); - + assertFalse(strings.hasNext()); } } diff --git a/test/net/filebot/util/PreferencesListTest.java b/test/net/filebot/util/PreferencesListTest.java index 1ed3f976..6a21c3d3 100644 --- a/test/net/filebot/util/PreferencesListTest.java +++ b/test/net/filebot/util/PreferencesListTest.java @@ -16,17 +16,17 @@ import org.junit.Test; public class PreferencesListTest { - + private static Preferences root; private static Preferences strings; private static Preferences numbers; private static Preferences temp; - - + + @BeforeClass public static void setUpBeforeClass() throws Exception { root = Preferences.userRoot().node("junit-test"); - + strings = root.node("strings"); strings.put("0", "Rei"); strings.put("1", "Firefly"); @@ -34,80 +34,80 @@ public class PreferencesListTest { strings.put("3", "Angel"); strings.put("4", "Dead like me"); strings.put("5", "Babylon"); - + numbers = root.node("numbers"); numbers.putInt("0", 4); numbers.putInt("1", 5); numbers.putInt("2", 2); - + temp = root.node("temp"); } - + @AfterClass public static void tearDownAfterClass() throws Exception { root.removeNode(); } - + @Test public void get() { List list = PreferencesList.map(strings); - + assertEquals("Rei", list.get(0)); assertEquals("Roswell", list.get(2)); assertEquals("Babylon", list.get(5)); } - + @Test public void add() { List list = PreferencesList.map(numbers, SimpleAdapter.forClass(Integer.class)); - + list.add(3); - + assertEquals("3", numbers.get("3", null)); } - + @Test public void remove() { - + ArrayList compareValues = new ArrayList(); - + compareValues.add("Gladiator 1"); compareValues.add("Gladiator 2"); compareValues.add("Gladiator 3"); compareValues.add("Gladiator 4"); compareValues.add("Gladiator 5"); - + List prefs = PreferencesList.map(temp); prefs.addAll(compareValues); - + for (int index : new int[] { 4, 0, 1 }) { prefs.remove(index); compareValues.remove(index); - + assertArrayEquals(compareValues.toArray(), prefs.toArray()); } - + } - + @Test public void setEntry() { List list = PreferencesList.map(strings); - + list.set(3, "Buffy"); - + assertEquals(strings.get("3", null), "Buffy"); } - + @Test public void toArray() throws Exception { List list = PreferencesList.map(strings); - + assertArrayEquals(list.subList(0, 3).toArray(), new Object[] { "Rei", "Firefly", "Roswell" }); } } diff --git a/test/net/filebot/util/PreferencesMapTest.java b/test/net/filebot/util/PreferencesMapTest.java index a3524e34..a0945627 100644 --- a/test/net/filebot/util/PreferencesMapTest.java +++ b/test/net/filebot/util/PreferencesMapTest.java @@ -20,155 +20,155 @@ import org.junit.Test; public class PreferencesMapTest { - + private static Preferences root; private static Preferences strings; private static Preferences numbers; private static Preferences temp; private static Preferences sequence; - + @BeforeClass public static void setUpBeforeClass() throws Exception { root = Preferences.userRoot().node("junit-test"); - + strings = root.node("strings"); strings.put("1", "Firefly"); strings.put("2", "Roswell"); strings.put("3", "Angel"); strings.put("4", "Dead like me"); strings.put("5", "Babylon"); - + numbers = root.node("numbers"); numbers.putInt("M", 4); numbers.putInt("A", 5); numbers.putInt("X", 2); - + sequence = root.node("sequence"); sequence.putInt("1", 1); sequence.putInt("2", 2); sequence.putInt("3", 3); - + temp = root.node("temp"); } - + @AfterClass public static void tearDownAfterClass() throws Exception { root.removeNode(); } - + @Test public void get() { Map stringMap = PreferencesMap.map(strings); - + assertEquals("Firefly", stringMap.get("1")); } - + @Test public void put() { Map stringMap = PreferencesMap.map(temp); - + stringMap.put("key", "snake"); - + assertEquals("snake", temp.get("key", null)); } - + @Test public void remove() throws Exception { Map map = PreferencesMap.map(numbers, SimpleAdapter.forClass(Integer.class)); - + map.remove("A"); - + assertFalse(Arrays.asList(numbers.keys()).contains("A")); } - + @Test public void clear() throws Exception { Map map = PreferencesMap.map(temp, SimpleAdapter.forClass(Integer.class)); - + map.put("X", 42); - + map.clear(); - + assertTrue(temp.keys().length == 0); } - + @Test public void containsKey() { temp.put("name", "kaya"); - + Map map = PreferencesMap.map(temp); - + assertTrue(map.containsKey("name")); } - + @Test public void values() { - + Map map = PreferencesMap.map(sequence, SimpleAdapter.forClass(Integer.class)); - + Collection list = map.values(); - + assertTrue(list.contains(1)); assertTrue(list.contains(2)); assertTrue(list.contains(3)); } - + @Test public void containsValue() { Map map = PreferencesMap.map(strings); - + assertTrue(map.containsValue("Firefly")); } - + @Test public void entrySet() { Map map = PreferencesMap.map(numbers, SimpleAdapter.forClass(Integer.class)); - + for (Entry entry : map.entrySet()) { Integer v = entry.getValue(); entry.setValue(v + 1); } - + assertEquals(5, numbers.getInt("M", -1)); } - + @Test(expected = NumberFormatException.class) public void adapterException() { PreferencesMap.map(strings, SimpleAdapter.forClass(Integer.class)).values(); } - + @Test public void containsKeyWithObjectKey() throws Exception { Map map = PreferencesMap.map(strings); - + assertFalse(map.containsKey(new Object())); } - + public void getWithObjectKey() throws Exception { Map map = PreferencesMap.map(strings); - + assertEquals(null, map.get(new Object())); } - + @Test public void serializableAdapter() { Map map = PreferencesMap.map(temp, new SerializableAdapter()); Color color = new Color(0.25f, 0.50f, 1.00f); - + map.put("color", color); assertEquals(color, map.get("color")); } diff --git a/test/net/filebot/util/TestUtil.java b/test/net/filebot/util/TestUtil.java index b13135e3..1d8d231f 100644 --- a/test/net/filebot/util/TestUtil.java +++ b/test/net/filebot/util/TestUtil.java @@ -9,33 +9,33 @@ import java.util.List; public class TestUtil { - + public static List asParameters(Object... parameters) { List list = new ArrayList(); - + for (Object parameter : parameters) { list.add(new Object[] { parameter }); } - + return list; } - + public static List asParameters(Collection parameters) { return asParameters(parameters.toArray()); } - + public static List> rotations(Collection source) { List> rotations = new ArrayList>(); - + for (int i = 0; i < source.size(); i++) { List copy = new ArrayList(source); Collections.rotate(copy, i); rotations.add(copy); } - + return rotations; } - + } diff --git a/test/net/filebot/util/TreeIteratorTest.java b/test/net/filebot/util/TreeIteratorTest.java index 0556c28f..ae9e214c 100644 --- a/test/net/filebot/util/TreeIteratorTest.java +++ b/test/net/filebot/util/TreeIteratorTest.java @@ -13,51 +13,51 @@ import org.junit.Test; public class TreeIteratorTest { - + private List tree; - - + + @Before public void setUp() throws Exception { tree = new ArrayList(); - + tree.add("r1"); - + List branch = new ArrayList(); branch.add("b1"); branch.add("b2"); - + tree.add(branch); - + tree.add("r2"); - + List treetop = new ArrayList(); treetop.add("t1"); treetop.add("t2"); treetop.add("t3"); - + List trunk = new ArrayList(); trunk.add(treetop); - + tree.add(trunk); } - + @Test public void iterate() { TreeIterator treeIterator = new TreeIterator(tree) { - + @SuppressWarnings("unchecked") @Override protected Iterator children(Object node) { if (node instanceof Iterable) return ((Iterable) node).iterator(); - + return null; } - + }; - + // check leafs (String) and nodes (Iterable) assertTrue(treeIterator.next() instanceof Iterable); // root assertEquals("r1", treeIterator.next()); @@ -70,7 +70,7 @@ public class TreeIteratorTest { assertEquals("t1", treeIterator.next()); assertEquals("t2", treeIterator.next()); assertEquals("t3", treeIterator.next()); - + assertFalse(treeIterator.hasNext()); } } diff --git a/test/net/filebot/util/UtilTestSuite.java b/test/net/filebot/util/UtilTestSuite.java index 4f2c96c6..905d558f 100644 --- a/test/net/filebot/util/UtilTestSuite.java +++ b/test/net/filebot/util/UtilTestSuite.java @@ -10,5 +10,5 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { FileUtilitiesTest.class, ByteBufferOutputStreamTest.class, PreferencesMapTest.class, PreferencesListTest.class, TreeIteratorTest.class, FilterIteratorTest.class }) public class UtilTestSuite { - + } diff --git a/test/net/filebot/web/OpenSubtitlesHasherTest.java b/test/net/filebot/web/OpenSubtitlesHasherTest.java index 651fd219..0fa0184c 100644 --- a/test/net/filebot/web/OpenSubtitlesHasherTest.java +++ b/test/net/filebot/web/OpenSubtitlesHasherTest.java @@ -17,38 +17,38 @@ import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class OpenSubtitlesHasherTest { - + private String expectedHash; private File file; - + public OpenSubtitlesHasherTest(String expectedHash, File file) { this.file = file; this.expectedHash = expectedHash; } - + @Parameters public static Collection parameters() { Object[][] parameters = new Object[3][]; - + parameters[0] = new Object[] { "8e245d9679d31e12", new File("breakdance.avi") }; parameters[1] = new Object[] { "61f7751fc2a72bfb", new File("dummy.bin") }; parameters[2] = new Object[] { "a79fa10ba3b31395", new File("mini.txt") }; - + return Arrays.asList(parameters); } - + @Test public void computeHashFile() throws Exception { assertEquals(expectedHash, OpenSubtitlesHasher.computeHash(file)); } - + @Test public void computeHashStream() throws Exception { assertEquals(expectedHash, OpenSubtitlesHasher.computeHash(new FileInputStream(file), file.length())); } - + }