() {
-
+
@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 extends Element> 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 extends Element> 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 extends String, ? extends T> map) {
for (Map.Entry extends String, ? extends T> 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