[refactoring][minor] Replaced all tabs with four spaces.

This commit is contained in:
North 2012-06-19 23:50:20 +03:00
parent e646e4768d
commit 239a4fb100
2891 changed files with 79411 additions and 79411 deletions

View file

@ -103,10 +103,10 @@ public class CardPluginImpl implements CardPlugin {
@Override
public int sortPermanents(Map<String, JComponent> ui, Collection<MagePermanent> permanents, Map<String, String> options) {
//TODO: add caching
//requires to find out is position have been changed that includes:
//adding/removing permanents, type change
//requires to find out is position have been changed that includes:
//adding/removing permanents, type change
if (ui == null)
if (ui == null)
throw new RuntimeException("Error: no components");
//JComponent component = ui.get("jScrollPane");
JComponent component2 = ui.get("battlefieldPanel");
@ -164,14 +164,14 @@ public class CardPluginImpl implements CardPlugin {
Row allCreatures = new Row(permanents, RowType.creature);
Row allOthers = new Row(permanents, RowType.other);
boolean othersOnTheRight = true;
if (options != null && options.containsKey("nonLandPermanentsInOnePile")) {
if (options.get("nonLandPermanentsInOnePile").equals("true")) {
othersOnTheRight = false;
allCreatures.addAll(allOthers);
allOthers.clear();
}
}
boolean othersOnTheRight = true;
if (options != null && options.containsKey("nonLandPermanentsInOnePile")) {
if (options.get("nonLandPermanentsInOnePile").equals("true")) {
othersOnTheRight = false;
allCreatures.addAll(allOthers);
allOthers.clear();
}
}
cardWidth = cardWidthMax;
Rectangle rect = battlefieldPanel.getVisibleRect();
@ -214,7 +214,7 @@ public class CardPluginImpl implements CardPlugin {
if (creatures.isEmpty() && lands.isEmpty() && others.isEmpty())
break;
//cardWidth = (int)(cardWidth / 1.2);
//FIXME: -1 is too slow. why not binary search?
//FIXME: -1 is too slow. why not binary search?
cardWidth -= 3;
}
@ -255,13 +255,13 @@ public class CardPluginImpl implements CardPlugin {
int panelX = x + (stackPosition * stackSpacingX);
int panelY = y + (stackPosition * stackSpacingY);
//panel.setLocation(panelX, panelY);
try {
// may cause:
// java.lang.IllegalArgumentException: illegal component position 26 should be less then 26
try {
// may cause:
// java.lang.IllegalArgumentException: illegal component position 26 should be less then 26
battlefieldPanel.moveToFront(panel);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
panel.setCardBounds(panelX, panelY, cardWidth, cardHeight);
}
rowBottom = Math.max(rowBottom, y + stack.getHeight());
@ -366,7 +366,7 @@ public class CardPluginImpl implements CardPlugin {
for (MagePermanent panel : permanents) {
if (!type.isType(panel)) {
continue;
}
}
Stack stack = new Stack();
stack.add(panel);
add(stack);
@ -425,7 +425,7 @@ public class CardPluginImpl implements CardPlugin {
public boolean newImages(Set<Card> allCards, String imagesPath) {
return DownloadPictures.checkForNewCards(allCards, imagesPath);
}
/**
* Download images.
*
@ -453,9 +453,9 @@ public class CardPluginImpl implements CardPlugin {
}
it = new GathererSets(imagesPath);
for(DownloadJob job:it) {
g.getDownloader().add(job);
}
for(DownloadJob job:it) {
g.getDownloader().add(job);
}
JDialog d = new JDialog((Frame) null, "Download pictures", false);
d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
@ -510,7 +510,7 @@ public class CardPluginImpl implements CardPlugin {
}
@Override
public BufferedImage getOriginalImage(CardView card) {
return ImageCache.getImageOriginal(card);
}
public BufferedImage getOriginalImage(CardView card) {
return ImageCache.getImageOriginal(card);
}
}

View file

@ -4,19 +4,19 @@ import java.awt.Rectangle;
import java.io.File;
public class Constants {
public static final String RESOURCE_PATH_MANA_LARGE = IO.imageBaseDir + File.separator + "symbols" + File.separator + "large";
public static final String RESOURCE_PATH_MANA_MEDIUM = IO.imageBaseDir + File.separator + "symbols" + File.separator + "medium";
public static final String RESOURCE_PATH_MANA_LARGE = IO.imageBaseDir + File.separator + "symbols" + File.separator + "large";
public static final String RESOURCE_PATH_MANA_MEDIUM = IO.imageBaseDir + File.separator + "symbols" + File.separator + "medium";
public static final String RESOURCE_PATH_SET = IO.imageBaseDir + File.separator + "sets" + File.separator;
public static final String RESOURCE_PATH_SET_SMALL = RESOURCE_PATH_SET + File.separator + "small" + File.separator;
public static final String RESOURCE_PATH_SET = IO.imageBaseDir + File.separator + "sets" + File.separator;
public static final String RESOURCE_PATH_SET_SMALL = RESOURCE_PATH_SET + File.separator + "small" + File.separator;
public static final Rectangle CARD_SIZE_FULL = new Rectangle(101, 149);
public static final Rectangle THUMBNAIL_SIZE_FULL = new Rectangle(102, 146);
public interface IO {
public static final String imageBaseDir = "plugins" + File.separator + "images";
public static final String IMAGE_PROPERTIES_FILE = "image.url.properties";
}
public static final String CARD_IMAGE_PATH_TEMPLATE = "." + File.separator + "plugins" + File.separator + "images/{set}/{name}.{collector}.full.jpg";
public static final Rectangle CARD_SIZE_FULL = new Rectangle(101, 149);
public static final Rectangle THUMBNAIL_SIZE_FULL = new Rectangle(102, 146);
public interface IO {
public static final String imageBaseDir = "plugins" + File.separator + "images";
public static final String IMAGE_PROPERTIES_FILE = "image.url.properties";
}
public static final String CARD_IMAGE_PATH_TEMPLATE = "." + File.separator + "plugins" + File.separator + "images/{set}/{name}.{collector}.full.jpg";
}

View file

@ -37,20 +37,20 @@ import org.mage.plugins.card.dl.DownloadJob.State;
*/
public class DownloadGui extends JPanel {
private static final long serialVersionUID = -7346572382493844327L;
private final Downloader d;
private final DownloadListener l = new DownloadListener();
private final BoundedRangeModel model = new DefaultBoundedRangeModel(0, 0, 0, 0);
private final JProgressBar progress = new JProgressBar(model);
private final Map<DownloadJob, DownloadPanel> progresses = new HashMap<DownloadJob, DownloadPanel>();
private final JPanel panel = new JPanel();
public DownloadGui(Downloader d) {
super(new BorderLayout());
this.d = d;
d.addPropertyChangeListener(l);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder("Progress:"));
p.add(progress);
@ -63,7 +63,7 @@ public class DownloadGui extends JPanel {
});
p.add(b, BorderLayout.EAST);
add(p, BorderLayout.NORTH);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JScrollPane pane = new JScrollPane(panel);
pane.setPreferredSize(new Dimension(500, 300));
@ -71,11 +71,11 @@ public class DownloadGui extends JPanel {
for(int i = 0; i < d.getJobs().size(); i++)
addJob(i, d.getJobs().get(i));
}
public Downloader getDownloader() {
return d;
}
private class DownloadListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
@ -105,17 +105,17 @@ public class DownloadGui extends JPanel {
if("jobs".equals(name)) {
IndexedPropertyChangeEvent ev = (IndexedPropertyChangeEvent) evt;
int index = ev.getIndex();
DownloadJob oldValue = (DownloadJob) ev.getOldValue();
if(oldValue != null) removeJob(index, oldValue);
DownloadJob newValue = (DownloadJob) ev.getNewValue();
if(newValue != null) addJob(index, newValue);
}
}
}
}
private synchronized void addJob(int index, DownloadJob job) {
job.addPropertyChangeListener(l);
changeProgress(0, +1);
@ -124,7 +124,7 @@ public class DownloadGui extends JPanel {
panel.add(p, index);
panel.revalidate();
}
private synchronized void removeJob(int index, DownloadJob job) {
assert progresses.get(job) == panel.getComponent(index);
job.removePropertyChangeListener(l);
@ -133,7 +133,7 @@ public class DownloadGui extends JPanel {
panel.remove(index);
panel.revalidate();
}
private synchronized void changeProgress(int progress, int total) {
progress += model.getValue();
total += model.getMaximum();
@ -142,17 +142,17 @@ public class DownloadGui extends JPanel {
this.progress.setStringPainted(true);
this.progress.setString(progress + "/" + total);
}
private class DownloadPanel extends JPanel {
private static final long serialVersionUID = 1187986738303477168L;
private DownloadJob job;
private JProgressBar bar;
public DownloadPanel(DownloadJob job) {
super(new BorderLayout());
this.job = job;
setBorder(BorderFactory.createTitledBorder(job.getName()));
add(bar = new JProgressBar(job.getProgress()));
JButton b = new JButton("X");
@ -167,27 +167,27 @@ public class DownloadGui extends JPanel {
}
});
add(b, BorderLayout.EAST);
if(job.getState() == State.FINISHED | job.getState() == State.ABORTED) {
changeProgress(+1, 0);
}
setVisible(job.getState() != State.FINISHED);
String message = job.getMessage();
bar.setStringPainted(message != null);
bar.setString(message);
Dimension d = getPreferredSize();
d.width = Integer.MAX_VALUE;
setMaximumSize(d);
// d.width = 500;
// setMinimumSize(d);
}
public DownloadJob getJob() {
return job;
}
public JProgressBar getBar() {
return bar;
}

View file

@ -33,7 +33,7 @@ public class DownloadJob extends AbstractLaternaBean {
public static enum State {
NEW, WORKING, FINISHED, ABORTED;
}
private final String name;
private final Source source;
private final Destination destination;
@ -41,13 +41,13 @@ public class DownloadJob extends AbstractLaternaBean {
private final Property<String> message = properties.property("message");
private final Property<Exception> error = properties.property("error");
private final BoundedRangeModel progress = new DefaultBoundedRangeModel();
public DownloadJob(String name, Source source, Destination destination) {
this.name = name;
this.source = source;
this.destination = destination;
}
/**
* Sets the job's state. If the state is {@link State#ABORTED}, it instead sets the error to "ABORTED"
*/
@ -55,7 +55,7 @@ public class DownloadJob extends AbstractLaternaBean {
if(state == State.ABORTED) setError("ABORTED");
else this.state.setValue(state);
}
/**
* Sets the job's state to {@link State#ABORTED} and the error message to the given message. Logs a warning
* with the given message.
@ -63,7 +63,7 @@ public class DownloadJob extends AbstractLaternaBean {
public void setError(String message) {
setError(message, null);
}
/**
* Sets the job's state to {@link State#ABORTED} and the error to the given exception. Logs a warning with the
* given exception.
@ -71,7 +71,7 @@ public class DownloadJob extends AbstractLaternaBean {
public void setError(Exception error) {
setError(null, error);
}
/**
* Sets the job's state to {@link State#ABORTED} and the error to the given exception. Logs a warning with the
* given message and exception.
@ -83,97 +83,97 @@ public class DownloadJob extends AbstractLaternaBean {
this.error.setValue(error);
this.message.setValue(message);
}
/**
* Sets the job's message.
*/
public void setMessage(String message) {
this.message.setValue(message);
}
public BoundedRangeModel getProgress() {
return progress;
}
public State getState() {
return state.getValue();
}
public Exception getError() {
return error.getValue();
}
public String getMessage() {
return message.getValue();
}
public String getName() {
return name;
}
public Source getSource() {
return source;
}
public Destination getDestination() {
return destination;
}
public static Source fromURL(final String url) {
return fromURL(null, url);
}
public static Source fromURL(final URL url) {
return fromURL(null, url);
}
public static Source fromURL(final Proxy proxy, final String url) {
return new Source() {
private URLConnection c;
public URLConnection getConnection() throws IOException {
if(c == null) c = proxy == null? new URL(url).openConnection():new URL(url).openConnection(proxy);
return c;
}
@Override
public InputStream open() throws IOException {
return getConnection().getInputStream();
}
@Override
public int length() throws IOException {
return getConnection().getContentLength();
}
};
}
public static Source fromURL(final Proxy proxy, final URL url) {
return new Source() {
private URLConnection c;
public URLConnection getConnection() throws IOException {
if(c == null) c = proxy == null? url.openConnection():url.openConnection(proxy);
return c;
}
@Override
public InputStream open() throws IOException {
return getConnection().getInputStream();
}
@Override
public int length() throws IOException {
return getConnection().getContentLength();
}
};
}
public static Destination toFile(final String file) {
return toFile(new File(file));
}
public static Destination toFile(final File file) {
return new Destination() {
@Override
@ -184,30 +184,30 @@ public class DownloadJob extends AbstractLaternaBean {
+ ": directory could not be created");
return new FileOutputStream(file);
}
@Override
public boolean exists() {
return file.isFile();
}
@Override
public void delete() throws IOException {
if(file.exists() && !file.delete()) throw new IOException(file + " couldn't be deleted");
}
};
}
public static interface Source {
public InputStream open() throws IOException;
public int length() throws IOException;
}
public static interface Destination {
public OutputStream open() throws IOException;
public boolean exists() throws IOException;
public void delete() throws IOException;
}
}

View file

@ -40,15 +40,15 @@ import org.mage.plugins.card.dl.lm.AbstractLaternaBean;
* @author Clemens Koza
*/
public class Downloader extends AbstractLaternaBean implements Disposable {
private static final Logger log = Logger.getLogger(Downloader.class);
private static final Logger log = Logger.getLogger(Downloader.class);
private final List<DownloadJob> jobs = properties.list("jobs");
private final Channel<DownloadJob> channel = new MemoryChannel<DownloadJob>();
private final ExecutorService pool = Executors.newCachedThreadPool();
private final List<Fiber> fibers = new ArrayList<Fiber>();
public Downloader() {
PoolFiberFactory f = new PoolFiberFactory(pool);
//subscribe multiple fibers for parallel execution
@ -59,7 +59,7 @@ public class Downloader extends AbstractLaternaBean implements Disposable {
channel.subscribe(fiber, new DownloadCallback());
}
}
@Override
public void dispose() {
for(DownloadJob j:getJobs()) {
@ -69,18 +69,18 @@ public class Downloader extends AbstractLaternaBean implements Disposable {
j.setState(State.ABORTED);
}
}
for(Fiber f:fibers)
f.dispose();
pool.shutdown();
}
@Override
protected void finalize() throws Throwable {
dispose();
super.finalize();
}
public void add(DownloadJob job) {
if(job.getState() == State.WORKING) throw new IllegalArgumentException("Job already running");
if(job.getState() == State.FINISHED) throw new IllegalArgumentException("Job already finished");
@ -88,11 +88,11 @@ public class Downloader extends AbstractLaternaBean implements Disposable {
jobs.add(job);
channel.publish(job);
}
public List<DownloadJob> getJobs() {
return jobs;
}
/**
* Performs the download job: Transfers data from {@link Source} to {@link Destination} and updates the
* download job's state to reflect the progress.
@ -109,7 +109,7 @@ public class Downloader extends AbstractLaternaBean implements Disposable {
Source src = job.getSource();
Destination dst = job.getDestination();
BoundedRangeModel progress = job.getProgress();
if(dst.exists()) {
progress.setMaximum(1);
progress.setValue(1);

View file

@ -18,19 +18,19 @@ import java.beans.PropertyChangeListener;
*/
public abstract class AbstractBoundBean implements BoundBean {
protected PropertyChangeSupport s = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
s.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
s.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
s.removePropertyChangeListener(listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
s.removePropertyChangeListener(propertyName, listener);
}

View file

@ -18,10 +18,10 @@ import java.beans.PropertyChangeListener;
*/
public interface BoundBean {
public void addPropertyChangeListener(PropertyChangeListener listener);
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);
public void removePropertyChangeListener(PropertyChangeListener listener);
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener);
}

View file

@ -29,7 +29,7 @@ import com.google.common.collect.Lists;
*/
public class EventListenerList extends javax.swing.event.EventListenerList {
private static final long serialVersionUID = -7545754245081842909L;
/**
* Returns an iterable over all listeners for the specified classes. the listener classes are in the specified
* order. for every class, listeners are in the reverse order of registering. A listener contained multiple
@ -38,10 +38,10 @@ public class EventListenerList extends javax.swing.event.EventListenerList {
public <T extends EventListener> Iterable<T> getIterable(final Class<? extends T>... listenerClass) {
//transform class -> iterable
List<Iterable<T>> l = Lists.transform(asList(listenerClass), new ClassToIterableFunction<T>());
//compose iterable (use an arraylist to memoize the function's results)
final Iterable<T> it = Iterables.concat(new ArrayList<Iterable<T>>(l));
//transform to singleton iterators
return new Iterable<T>() {
public Iterator<T> iterator() {
@ -49,7 +49,7 @@ public class EventListenerList extends javax.swing.event.EventListenerList {
}
};
}
/**
* Returns an iterator over all listeners for the specified classes. the listener classes are in the specified
* order. for every class, listeners are in the reverse order of registering. A listener contained multiple
@ -58,7 +58,7 @@ public class EventListenerList extends javax.swing.event.EventListenerList {
public <T extends EventListener> Iterator<T> getIterator(Class<? extends T>... listenerClass) {
return getIterable(listenerClass).iterator();
}
/**
* Iterates backwards over the listeners registered for a class by using the original array. The Listener runs
* backwards, just as listener notification usually works.
@ -67,11 +67,11 @@ public class EventListenerList extends javax.swing.event.EventListenerList {
private final Class<? extends T> listenerClass;
private Object[] listeners = listenerList;
private int index = listeners.length;
private ListenerIterator(Class<? extends T> listenerClass) {
this.listenerClass = listenerClass;
}
@Override
@SuppressWarnings("unchecked")
protected T computeNext() {
@ -81,34 +81,34 @@ public class EventListenerList extends javax.swing.event.EventListenerList {
return endOfData();
}
}
/**
* Transforms a class to the associated listener iterator
*/
private class ClassToIterableFunction<T> implements Function<Class<? extends T>, Iterable<T>> {
public Iterable<T> apply(final Class<? extends T> from) {
return new Iterable<T>() {
public Iterator<T> iterator() {
return new ListenerIterator<T>(from);
}
};
}
}
/**
* Filters the delegate iterator so that every but the first occurrence of every element is ignored.
*/
private static class SingletonIterator<T> extends AbstractIterator<T> {
private Iterator<T> it;
private HashSet<T> previous = new HashSet<T>();
public SingletonIterator(Iterator<T> it) {
this.it = it;
}
@Override
protected T computeNext() {
while(it.hasNext()) {

View file

@ -17,14 +17,14 @@ package org.mage.plugins.card.dl.beans;
*/
public class PropertyChangeSupport extends java.beans.PropertyChangeSupport {
private static final long serialVersionUID = -4241465377828790076L;
private Object sourceBean;
public PropertyChangeSupport(Object sourceBean) {
super(sourceBean);
this.sourceBean = sourceBean;
}
public Object getSourceBean() {
return sourceBean;
}

View file

@ -31,183 +31,183 @@ import java.util.Set;
*/
public final class ListenableCollections {
private ListenableCollections() {}
public static <E> List<E> listenableList(List<E> list, ListListener<E> listener) {
if(list instanceof RandomAccess) return new ListenableList<E>(list, listener);
else return new ListenableSequentialList<E>(list, listener);
}
public static <E> Set<E> listenableSet(Set<E> set, SetListener<E> listener) {
return new ListenableSet<E>(set, listener);
}
public static <K, V> Map<K, V> listenableMap(Map<K, V> map, MapListener<K, V> listener) {
return new ListenableMap<K, V>(map, listener);
}
public static interface ListListener<E> extends Serializable {
/**
* Notified after a value was added to the list.
*/
public void add(int index, E newValue);
/**
* Notified after a value in the list was changed.
*/
public void set(int index, E oldValue, E newValue);
/**
* Notified after a value was removed from the list.
*/
public void remove(int index, E oldValue);
}
private static class ListenableList<E> extends AbstractList<E> implements RandomAccess, Serializable {
private static final long serialVersionUID = 8622608480525537692L;
private List<E> delegate;
private ListListener<E> listener;
public ListenableList(List<E> delegate, ListListener<E> listener) {
this.delegate = delegate;
this.listener = listener;
}
@Override
public void add(int index, E e) {
delegate.add(index, e);
listener.add(index, e);
}
@Override
public E set(int index, E element) {
E e = delegate.set(index, element);
listener.set(index, e, element);
return e;
}
@Override
public E remove(int index) {
E e = delegate.remove(index);
listener.remove(index, e);
return e;
}
@Override
public E get(int index) {
return delegate.get(index);
}
@Override
public int size() {
return delegate.size();
}
}
private static class ListenableSequentialList<E> extends AbstractSequentialList<E> implements Serializable {
private static final long serialVersionUID = 3630474556578001885L;
private List<E> delegate;
private ListListener<E> listener;
public ListenableSequentialList(List<E> delegate, ListListener<E> listener) {
this.delegate = delegate;
this.listener = listener;
}
@Override
public ListIterator<E> listIterator(final int index) {
return new ListIterator<E>() {
private final ListIterator<E> it = delegate.listIterator(index);
private int lastIndex;
private E lastValue;
public boolean hasNext() {
return it.hasNext();
}
public boolean hasPrevious() {
return it.hasPrevious();
}
public E next() {
lastIndex = it.nextIndex();
lastValue = it.next();
return lastValue;
}
public int nextIndex() {
return it.nextIndex();
}
public E previous() {
lastIndex = it.previousIndex();
lastValue = it.previous();
return lastValue;
}
public int previousIndex() {
return it.previousIndex();
}
public void add(E o) {
it.add(o);
listener.add(previousIndex(), o);
}
public void set(E o) {
it.set(o);
listener.set(lastIndex, lastValue, o);
}
public void remove() {
it.remove();
listener.remove(lastIndex, lastValue);
}
};
}
@Override
public int size() {
return delegate.size();
}
}
public static interface SetListener<E> extends Serializable {
/**
* Notified after a value was added to the set.
*/
public void add(E newValue);
/**
* Notified after a value was removed from the set.
*/
public void remove(E oldValue);
}
private static class ListenableSet<E> extends AbstractSet<E> implements Serializable {
private static final long serialVersionUID = 7728087988927063221L;
private Set<E> delegate;
private SetListener<E> listener;
public ListenableSet(Set<E> set, SetListener<E> listener) {
delegate = set;
this.listener = listener;
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public boolean add(E o) {
boolean b = delegate.add(o);
if(b) listener.add(o);
return b;
};
@SuppressWarnings("unchecked")
@Override
public boolean remove(Object o) {
@ -215,24 +215,24 @@ public final class ListenableCollections {
if(b) listener.remove((E) o);
return b;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private final Iterator<E> it = delegate.iterator();
private boolean hasLast;
private E last;
public boolean hasNext() {
return it.hasNext();
}
public E next() {
last = it.next();
hasLast = true;
return last;
}
public void remove() {
if(!hasLast) throw new IllegalStateException();
it.remove();
@ -240,43 +240,43 @@ public final class ListenableCollections {
}
};
}
@Override
public int size() {
return delegate.size();
}
}
public static interface MapListener<K, V> extends Serializable {
/**
* Notified after a value was put into the map.
*/
public void put(K key, V newValue);
/**
* Notified after a value in the map was changed.
*/
public void set(K key, V oldValue, V newValue);
/**
* Notified after a value was removed from the map.
*/
public void remove(K key, V oldValue);
}
private static class ListenableMap<K, V> extends AbstractMap<K, V> implements Serializable {
private static final long serialVersionUID = 4032087477448965103L;
private Map<K, V> delegate;
private MapListener<K, V> listener;
private Set<Entry<K, V>> entrySet;
public ListenableMap(Map<K, V> map, MapListener<K, V> listener) {
this.listener = listener;
delegate = map;
entrySet = new EntrySet();
}
@Override
public V put(K key, V value) {
if(delegate.containsKey(key)) {
@ -288,9 +288,9 @@ public final class ListenableCollections {
listener.put(key, value);
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
@ -300,53 +300,53 @@ public final class ListenableCollections {
return old;
} else return null;
}
@Override
public V get(Object key) {
return delegate.get(key);
}
@Override
public boolean containsKey(Object key) {
return delegate.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
return entrySet;
}
private final class EntrySet extends AbstractSet<Entry<K, V>> implements Serializable {
private static final long serialVersionUID = -780485106953107075L;
private final Set<Entry<K, V>> delegate = ListenableMap.this.delegate.entrySet();
@Override
public int size() {
return delegate.size();
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private final Iterator<Entry<K, V>> it = delegate.iterator();
private boolean hasLast;
private Entry<K, V> last;
public boolean hasNext() {
return it.hasNext();
}
public Entry<K, V> next() {
last = it.next();
hasLast = true;
return last;
}
public void remove() {
if(!hasLast) throw new IllegalStateException();
hasLast = false;

View file

@ -27,21 +27,21 @@ public abstract class AbstractProperties implements Properties {
public <T> Property<T> property(String name, T value) {
return property(name, new BasicProperty<T>(value));
}
public <T> Property<T> property(String name) {
return property(name, new BasicProperty<T>());
}
public <E> List<E> list(String name) {
return list(name, new ArrayList<E>());
}
public <E> Set<E> set(String name) {
return set(name, new HashSet<E>());
}
public <K, V> Map<K, V> map(String name) {
return map(name, new HashMap<K, V>());
}
}

View file

@ -22,7 +22,7 @@ public abstract class AbstractProperty<T> implements Property<T> {
T value = getValue();
return value == null? 0:value.hashCode();
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Property<?>)) return false;
@ -30,7 +30,7 @@ public abstract class AbstractProperty<T> implements Property<T> {
Object other = ((Property<?>) obj).getValue();
return value == other || (value != null && value.equals(other));
}
@Override
public String toString() {
return valueOf(getValue());

View file

@ -24,35 +24,35 @@ import java.util.Set;
*/
public class CompoundProperties extends AbstractProperties {
private List<Properties> delegates;
public CompoundProperties(Properties... delegates) {
this.delegates = asList(delegates);
Collections.reverse(this.delegates);
}
public CompoundProperties(List<Properties> delegates) {
this.delegates = new ArrayList<Properties>(delegates);
Collections.reverse(this.delegates);
}
public <T> Property<T> property(String name, Property<T> property) {
for(Properties p:delegates)
property = p.property(name, property);
return property;
}
public <E> List<E> list(String name, List<E> list) {
for(Properties p:delegates)
list = p.list(name, list);
return list;
}
public <E> Set<E> set(String name, Set<E> set) {
for(Properties p:delegates)
set = p.set(name, set);
return set;
}
public <K, V> Map<K, V> map(String name, Map<K, V> map) {
for(Properties p:delegates)
map = p.map(name, map);

View file

@ -24,21 +24,21 @@ import org.mage.plugins.card.dl.beans.properties.bound.BoundProperties;
*/
public interface Properties {
public <T> Property<T> property(String name, Property<T> property);
public <E> List<E> list(String name, List<E> list);
public <E> Set<E> set(String name, Set<E> set);
public <K, V> Map<K, V> map(String name, Map<K, V> map);
public <T> Property<T> property(String name, T value);
public <T> Property<T> property(String name);
public <E> List<E> list(String name);
public <E> Set<E> set(String name);
public <K, V> Map<K, V> map(String name);
}

View file

@ -15,15 +15,15 @@ package org.mage.plugins.card.dl.beans.properties;
*/
public interface Property<T> {
public void setValue(T value);
public T getValue();
/**
* A property's hash code is its value's hashCode, or {@code null} if the value is null.
*/
@Override
public int hashCode();
/**
* Two properties are equal if their values are equal.
*/

View file

@ -25,15 +25,15 @@ public class BasicProperties extends AbstractProperties {
public <T> Property<T> property(String name, Property<T> value) {
return value;
}
public <E> List<E> list(String name, List<E> list) {
return list;
}
public <E> Set<E> set(String name, Set<E> set) {
return set;
}
public <K, V> Map<K, V> map(String name, Map<K, V> map) {
return map;
}

View file

@ -18,19 +18,19 @@ import org.mage.plugins.card.dl.beans.properties.AbstractProperty;
*/
public class BasicProperty<T> extends AbstractProperty<T> {
private T value;
public BasicProperty() {
this(null);
}
public BasicProperty(T initialValue) {
value = initialValue;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}

View file

@ -28,28 +28,28 @@ import org.mage.plugins.card.dl.beans.properties.Property;
*/
public class BoundProperties extends AbstractProperties {
public final PropertyChangeSupport s;
public BoundProperties(Object sourceBean) {
this(new PropertyChangeSupport(sourceBean));
}
public BoundProperties(PropertyChangeSupport s) {
if(s == null) throw new IllegalArgumentException("s == null");
this.s = s;
}
public <T> Property<T> property(String name, Property<T> property) {
return new BoundProperty<T>(s, name, property);
}
public <E> List<E> list(String name, List<E> list) {
return listenableList(list, new PropertyChangeListListener<E>(s, name));
}
public <E> Set<E> set(String name, Set<E> set) {
return listenableSet(set, new PropertyChangeSetListener<E>(s, set, name));
}
public <K, V> Map<K, V> map(String name, Map<K, V> map) {
return listenableMap(map, new PropertyChangeMapListener<K, V>(s, map, name));
}

View file

@ -23,21 +23,21 @@ public class BoundProperty<T> extends AbstractProperty<T> {
private PropertyChangeSupport s;
private String name;
private Property<T> property;
public BoundProperty(PropertyChangeSupport s, String name, Property<T> property) {
if(property == null) throw new IllegalArgumentException();
this.s = s;
this.name = name;
this.property = property;
}
public void setValue(T value) {
T old = getValue();
property.setValue(value);
s.firePropertyChange(name, old, getValue());
}
public T getValue() {
return property.getValue();
}

View file

@ -20,23 +20,23 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.ListList
*/
public class PropertyChangeListListener<E> implements ListListener<E> {
private static final long serialVersionUID = 625853864429729560L;
private PropertyChangeSupport s;
private String propertyName;
public PropertyChangeListListener(PropertyChangeSupport s, String propertyName) {
this.s = s;
this.propertyName = propertyName;
}
public void add(int index, E newValue) {
s.fireIndexedPropertyChange(propertyName, index, null, newValue);
}
public void set(int index, E oldValue, E newValue) {
s.fireIndexedPropertyChange(propertyName, index, oldValue, newValue);
}
public void remove(int index, E oldValue) {
s.fireIndexedPropertyChange(propertyName, index, oldValue, null);
}

View file

@ -23,102 +23,102 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.MapListe
*/
public class PropertyChangeMapListener<K, V> implements MapListener<K, V> {
private static final long serialVersionUID = 625853864429729560L;
private PropertyChangeSupport s;
private Map<K, V> map;
private String propertyName;
public PropertyChangeMapListener(PropertyChangeSupport s, Map<K, V> map, String propertyName) {
this.s = s;
this.map = map;
this.propertyName = propertyName;
}
public void put(K key, V newValue) {
s.firePropertyChange(new MapPutEvent<K, V>(s.getSourceBean(), propertyName, map, key, newValue));
}
public void set(K key, V oldValue, V newValue) {
s.firePropertyChange(new MapSetEvent<K, V>(s.getSourceBean(), propertyName, map, key, oldValue, newValue));
}
public void remove(K key, V oldValue) {
s.firePropertyChange(new MapRemoveEvent<K, V>(s.getSourceBean(), propertyName, map, key, oldValue));
}
public static abstract class MapEvent<K, V> extends PropertyChangeEvent {
private static final long serialVersionUID = -651568020675693544L;
private Map<K, V> map;
private K key;
public MapEvent(Object source, String propertyName, Map<K, V> map, K key) {
super(source, propertyName, null, null);
this.map = map;
this.key = key;
}
@Override
public Map<K, V> getOldValue() {
//old and new value must not be equal
return null;
}
@Override
public Map<K, V> getNewValue() {
return map;
}
public K getKey() {
return key;
}
}
public static class MapPutEvent<K, V> extends MapEvent<K, V> {
private static final long serialVersionUID = 6006291474676939650L;
private V newElement;
public MapPutEvent(Object source, String propertyName, Map<K, V> map, K key, V newElement) {
super(source, propertyName, map, key);
this.newElement = newElement;
}
public V getNewElement() {
return newElement;
}
}
public static class MapSetEvent<K, V> extends MapEvent<K, V> {
private static final long serialVersionUID = -2419438379909500079L;
private V oldElement, newElement;
public MapSetEvent(Object source, String propertyName, Map<K, V> map, K key, V oldElement, V newElement) {
super(source, propertyName, map, key);
this.oldElement = oldElement;
this.newElement = newElement;
}
public V getOldElement() {
return oldElement;
}
public V getNewElement() {
return newElement;
}
}
public static class MapRemoveEvent<K, V> extends MapEvent<K, V> {
private static final long serialVersionUID = -2644879706878221895L;
private V oldElement;
public MapRemoveEvent(Object source, String propertyName, Map<K, V> map, K key, V oldElement) {
super(source, propertyName, map, key);
this.oldElement = oldElement;
}
public V getOldElement() {
return oldElement;
}

View file

@ -23,72 +23,72 @@ import org.mage.plugins.card.dl.beans.collections.ListenableCollections.SetListe
*/
public class PropertyChangeSetListener<E> implements SetListener<E> {
private static final long serialVersionUID = 625853864429729560L;
private PropertyChangeSupport s;
private Set<E> set;
private String propertyName;
public PropertyChangeSetListener(PropertyChangeSupport s, Set<E> set, String propertyName) {
this.s = s;
this.set = set;
this.propertyName = propertyName;
}
public void add(E newValue) {
s.firePropertyChange(new SetAddEvent<E>(s.getSourceBean(), propertyName, set, newValue));
}
public void remove(E oldValue) {
s.firePropertyChange(new SetRemoveEvent<E>(s.getSourceBean(), propertyName, set, oldValue));
}
public static abstract class SetEvent<E> extends PropertyChangeEvent {
private static final long serialVersionUID = -651568020675693544L;
private Set<E> set;
public SetEvent(Object source, String propertyName, Set<E> set) {
super(source, propertyName, null, null);
this.set = set;
}
@Override
public Set<E> getOldValue() {
//old and new value must not be equal
return null;
}
@Override
public Set<E> getNewValue() {
return set;
}
}
public static class SetAddEvent<E> extends SetEvent<E> {
private static final long serialVersionUID = 9041766866796759871L;
private E newElement;
public SetAddEvent(Object source, String propertyName, Set<E> set, E newElement) {
super(source, propertyName, set);
this.newElement = newElement;
}
public E getNewElement() {
return newElement;
}
}
public static class SetRemoveEvent<E> extends SetEvent<E> {
private static final long serialVersionUID = -1315342339926392385L;
private E oldElement;
public SetRemoveEvent(Object source, String propertyName, Set<E> set, E oldElement) {
super(source, propertyName, set);
this.oldElement = oldElement;
}
public E getOldElement() {
return oldElement;
}

View file

@ -21,7 +21,7 @@ import org.mage.plugins.card.dl.beans.properties.bound.BoundProperties;
* @author Clemens Koza
*/
public class AbstractLaternaBean extends AbstractBoundBean {
protected static final Logger log = Logger.getLogger(AbstractLaternaBean.class);
protected static final Logger log = Logger.getLogger(AbstractLaternaBean.class);
protected Properties properties = new BoundProperties(s);
protected EventListenerList listeners = new EventListenerList();
}

View file

@ -27,21 +27,21 @@ import static org.mage.plugins.card.dl.DownloadJob.toFile;
public class GathererSymbols implements Iterable<DownloadJob> {
//TODO chaos and planeswalker symbol
//chaos: http://gatherer.wizards.com/Images/Symbols/chaos.gif
private final static String SYMBOLS_PATH = File.separator + "symbols";
private final static File DEFAULT_OUT_DIR = new File("plugins" + File.separator + "images" + SYMBOLS_PATH);
private static File outDir = DEFAULT_OUT_DIR;
private static final String urlFmt = "http://gatherer.wizards.com/handlers/image.ashx?size=%1$s&name=%2$s&type=symbol";
private static final String[] sizes = {"small", "medium", "large"};
private static final String[] symbols = {"W", "U", "B", "R", "G",
"W/U", "U/B", "B/R", "R/G", "G/W", "W/B", "U/R", "B/G", "R/W", "G/U",
"2/W", "2/U", "2/B", "2/R", "2/G",
"WP", "UP", "BP", "RP", "GP",
"X", "S", "T", "Q"};
@ -54,13 +54,13 @@ public class GathererSymbols implements Iterable<DownloadJob> {
changeOutDir(path);
}
}
@Override
public Iterator<DownloadJob> iterator() {
return new AbstractIterator<DownloadJob>() {
private int sizeIndex, symIndex, numeric = minNumeric;
private File dir = new File(outDir, sizes[sizeIndex]);
@Override
protected DownloadJob computeNext() {
String sym;
@ -71,7 +71,7 @@ public class GathererSymbols implements Iterable<DownloadJob> {
} else {
sizeIndex++;
if(sizeIndex == sizes.length) return endOfData();
symIndex = 0;
numeric = 0;
dir = new File(outDir, sizes[sizeIndex]);
@ -79,13 +79,13 @@ public class GathererSymbols implements Iterable<DownloadJob> {
}
String symbol = sym.replaceAll("/", "");
File dst = new File(dir, symbol + ".jpg");
if(symbol.equals("T")) symbol = "tap";
else if(symbol.equals("Q")) symbol = "untap";
else if(symbol.equals("S")) symbol = "snow";
String url = format(urlFmt, sizes[sizeIndex], symbol);
return new DownloadJob(sym, fromURL(url), toFile(dst));
}
};

View file

@ -35,107 +35,107 @@ import java.util.concurrent.Executors;
public class DownloadPictures extends DefaultBoundedRangeModel implements Runnable {
private JProgressBar bar;
private JOptionPane dlg;
private boolean cancel;
private JButton closeButton;
private JProgressBar bar;
private JOptionPane dlg;
private boolean cancel;
private JButton closeButton;
private JButton startDownloadButton;
private int cardIndex;
private ArrayList<CardInfo> cards;
private JComboBox jComboBox1;
private JLabel jLabel1;
private static boolean offlineMode = false;
private JCheckBox checkBox;
private final Object sync = new Object();
private int cardIndex;
private ArrayList<CardInfo> cards;
private JComboBox jComboBox1;
private JLabel jLabel1;
private static boolean offlineMode = false;
private JCheckBox checkBox;
private final Object sync = new Object();
private String imagesPath;
private static CardImageSource cardImageSource;
private Proxy p = Proxy.NO_PROXY;
private ExecutorService executor = Executors.newFixedThreadPool(10);
public static final Proxy.Type[] types = Proxy.Type.values();
private Proxy p = Proxy.NO_PROXY;
public static void main(String[] args) {
startDownload(null, null, null);
}
private ExecutorService executor = Executors.newFixedThreadPool(10);
public static void startDownload(JFrame frame, Set<Card> allCards, String imagesPath) {
ArrayList<CardInfo> cards = getNeededCards(allCards, imagesPath);
public static final Proxy.Type[] types = Proxy.Type.values();
/*
* if (cards == null || cards.size() == 0) {
* JOptionPane.showMessageDialog(null,
* "All card pictures have been downloaded."); return; }
*/
public static void main(String[] args) {
startDownload(null, null, null);
}
DownloadPictures download = new DownloadPictures(cards, imagesPath);
JDialog dlg = download.getDlg(frame);
dlg.setVisible(true);
dlg.dispose();
download.setCancel(true);
}
public static void startDownload(JFrame frame, Set<Card> allCards, String imagesPath) {
ArrayList<CardInfo> cards = getNeededCards(allCards, imagesPath);
public JDialog getDlg(JFrame frame) {
String title = "Downloading";
/*
* if (cards == null || cards.size() == 0) {
* JOptionPane.showMessageDialog(null,
* "All card pictures have been downloaded."); return; }
*/
final JDialog dialog = this.dlg.createDialog(frame, title);
closeButton.addActionListener(new ActionListener() {
DownloadPictures download = new DownloadPictures(cards, imagesPath);
JDialog dlg = download.getDlg(frame);
dlg.setVisible(true);
dlg.dispose();
download.setCancel(true);
}
public JDialog getDlg(JFrame frame) {
String title = "Downloading";
final JDialog dialog = this.dlg.createDialog(frame, title);
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
return dialog;
}
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
return dialog;
}
public void setCancel(boolean cancel) {
this.cancel = cancel;
}
public void setCancel(boolean cancel) {
this.cancel = cancel;
}
public DownloadPictures(ArrayList<CardInfo> cards, String imagesPath) {
this.cards = cards;
public DownloadPictures(ArrayList<CardInfo> cards, String imagesPath) {
this.cards = cards;
this.imagesPath = imagesPath;
//addr = new JTextField("Proxy Address");
//port = new JTextField("Proxy Port");
bar = new JProgressBar(this);
//addr = new JTextField("Proxy Address");
//port = new JTextField("Proxy Port");
bar = new JProgressBar(this);
JPanel p0 = new JPanel();
p0.setLayout(new BoxLayout(p0, BoxLayout.Y_AXIS));
JPanel p0 = new JPanel();
p0.setLayout(new BoxLayout(p0, BoxLayout.Y_AXIS));
// Proxy Choice
/*ButtonGroup bg = new ButtonGroup();
String[] labels = { "No Proxy", "HTTP Proxy", "SOCKS Proxy" };
for (int i = 0; i < types.length; i++) {
JRadioButton rb = new JRadioButton(labels[i]);
rb.addChangeListener(new ProxyHandler(i));
bg.add(rb);
p0.add(rb);
if (i == 0)
rb.setSelected(true);
}*/
// Proxy Choice
/*ButtonGroup bg = new ButtonGroup();
String[] labels = { "No Proxy", "HTTP Proxy", "SOCKS Proxy" };
for (int i = 0; i < types.length; i++) {
JRadioButton rb = new JRadioButton(labels[i]);
rb.addChangeListener(new ProxyHandler(i));
bg.add(rb);
p0.add(rb);
if (i == 0)
rb.setSelected(true);
}*/
// Proxy config
//p0.add(addr);
//p0.add(port);
// Proxy config
//p0.add(addr);
//p0.add(port);
p0.add(Box.createVerticalStrut(5));
jLabel1 = new JLabel();
jLabel1.setText("Please select server:");
p0.add(Box.createVerticalStrut(5));
jLabel1 = new JLabel();
jLabel1.setText("Please select server:");
jLabel1.setAlignmentX(Component.LEFT_ALIGNMENT);
jLabel1.setAlignmentX(Component.LEFT_ALIGNMENT);
p0.add(jLabel1);
p0.add(Box.createVerticalStrut(5));
ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[] { "magiccards.info", "wizards.com"/*, "mtgathering.ru HQ", "mtgathering.ru MQ", "mtgathering.ru LQ"*/});
jComboBox1 = new JComboBox();
p0.add(jLabel1);
p0.add(Box.createVerticalStrut(5));
ComboBoxModel jComboBox1Model = new DefaultComboBoxModel(new String[] { "magiccards.info", "wizards.com"/*, "mtgathering.ru HQ", "mtgathering.ru MQ", "mtgathering.ru LQ"*/});
jComboBox1 = new JComboBox();
cardImageSource = MagicCardsImageSource.getInstance();
jComboBox1.setModel(jComboBox1Model);
jComboBox1.setAlignmentX(Component.LEFT_ALIGNMENT);
jComboBox1.setModel(jComboBox1Model);
jComboBox1.setAlignmentX(Component.LEFT_ALIGNMENT);
jComboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@ -163,55 +163,55 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
: "%d of %d cards finished! Please wait! [%.1f Mb]", 0, count, mb));
}
});
p0.add(jComboBox1);
p0.add(Box.createVerticalStrut(5));
p0.add(jComboBox1);
p0.add(Box.createVerticalStrut(5));
// Start
startDownloadButton = new JButton("Start download");
startDownloadButton.addActionListener(new ActionListener() {
// Start
startDownloadButton = new JButton("Start download");
startDownloadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(DownloadPictures.this).start();
startDownloadButton.setEnabled(false);
checkBox.setEnabled(false);
}
});
p0.add(Box.createVerticalStrut(5));
public void actionPerformed(ActionEvent e) {
new Thread(DownloadPictures.this).start();
startDownloadButton.setEnabled(false);
checkBox.setEnabled(false);
}
});
p0.add(Box.createVerticalStrut(5));
// Progress
p0.add(bar);
bar.setStringPainted(true);
int count = cards.size();
float mb = (count * cardImageSource.getAverageSize()) / 1024;
bar.setString(String.format(cardIndex == cards.size() ? "%d of %d cards finished! Please close!"
: "%d of %d cards finished! Please wait! [%.1f Mb]", 0, cards.size(), mb));
Dimension d = bar.getPreferredSize();
d.width = 300;
bar.setPreferredSize(d);
// Progress
p0.add(bar);
bar.setStringPainted(true);
int count = cards.size();
float mb = (count * cardImageSource.getAverageSize()) / 1024;
bar.setString(String.format(cardIndex == cards.size() ? "%d of %d cards finished! Please close!"
: "%d of %d cards finished! Please wait! [%.1f Mb]", 0, cards.size(), mb));
Dimension d = bar.getPreferredSize();
d.width = 300;
bar.setPreferredSize(d);
p0.add(Box.createVerticalStrut(5));
checkBox = new JCheckBox("Download for current game only.");
p0.add(checkBox);
p0.add(Box.createVerticalStrut(5));
checkBox.setEnabled(!offlineMode);
p0.add(Box.createVerticalStrut(5));
checkBox = new JCheckBox("Download for current game only.");
p0.add(checkBox);
p0.add(Box.createVerticalStrut(5));
checkBox.setEnabled(!offlineMode);
checkBox.addActionListener(new ActionListener() {
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
public void actionPerformed(ActionEvent e) {
int count = DownloadPictures.this.cards.size();
float mb = (count * cardImageSource.getAverageSize()) / 1024;
bar.setString(String.format(cardIndex == count ? "%d of %d cards finished! Please close!"
: "%d of %d cards finished! Please wait! [%.1f Mb]", 0, count, mb));
}
});
}
});
// JOptionPane
Object[] options = { startDownloadButton, closeButton = new JButton("Cancel") };
dlg = new JOptionPane(p0, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
}
// JOptionPane
Object[] options = { startDownloadButton, closeButton = new JButton("Cancel") };
dlg = new JOptionPane(p0, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
}
public static boolean checkForNewCards(Set<Card> allCards, String imagesPath) {
File file;
File file;
for (Card card : allCards) {
if (card.getCardNumber() > 0 && !card.getExpansionSetCode().isEmpty()) {
CardInfo url = new CardInfo(card.getName(), card.getExpansionSetCode(), card.getCardNumber(), 0, false, card.canTransform(), card.isNightCard());
@ -226,18 +226,18 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
}
return false;
}
private static ArrayList<CardInfo> getNeededCards(Set<Card> allCards, String imagesPath) {
ArrayList<CardInfo> cardsToDownload = new ArrayList<CardInfo>();
private static ArrayList<CardInfo> getNeededCards(Set<Card> allCards, String imagesPath) {
/**
* read all card names and urls
*/
ArrayList<CardInfo> allCardsUrls = new ArrayList<CardInfo>();
ArrayList<CardInfo> cardsToDownload = new ArrayList<CardInfo>();
try {
offlineMode = true;
/**
* read all card names and urls
*/
ArrayList<CardInfo> allCardsUrls = new ArrayList<CardInfo>();
try {
offlineMode = true;
for (Card card : allCards) {
if (card.getCardNumber() > 0 && !card.getExpansionSetCode().isEmpty()) {
@ -269,154 +269,154 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
}
}
allCardsUrls.addAll(getTokenCardUrls());
} catch (Exception e) {
log.error(e);
}
allCardsUrls.addAll(getTokenCardUrls());
} catch (Exception e) {
log.error(e);
}
File file;
File file;
/**
* check to see which cards we already have
*/
for (CardInfo card : allCardsUrls) {
boolean withCollectorId = false;
if (card.getName().equals("Forest") || card.getName().equals("Mountain") || card.getName().equals("Swamp") || card.getName().equals("Island")
|| card.getName().equals("Plains")) {
withCollectorId = true;
}
file = new File(CardImageUtils.getImagePath(card, withCollectorId, imagesPath));
if (!file.exists()) {
cardsToDownload.add(card);
}
}
/**
* check to see which cards we already have
*/
for (CardInfo card : allCardsUrls) {
boolean withCollectorId = false;
if (card.getName().equals("Forest") || card.getName().equals("Mountain") || card.getName().equals("Swamp") || card.getName().equals("Island")
|| card.getName().equals("Plains")) {
withCollectorId = true;
}
file = new File(CardImageUtils.getImagePath(card, withCollectorId, imagesPath));
if (!file.exists()) {
cardsToDownload.add(card);
}
}
for (CardInfo card : cardsToDownload) {
if (card.isToken()) {
log.info("Card to download: " + card.getName() + " (Token) ");
} else {
try {
log.info("Card to download: " + card.getName() + " (" + card.getSet() + ")");
} catch (Exception e) {
log.error(e);
}
}
}
for (CardInfo card : cardsToDownload) {
if (card.isToken()) {
log.info("Card to download: " + card.getName() + " (Token) ");
} else {
try {
log.info("Card to download: " + card.getName() + " (" + card.getSet() + ")");
} catch (Exception e) {
log.error(e);
}
}
}
return cardsToDownload;
}
return cardsToDownload;
}
private static ArrayList<CardInfo> getTokenCardUrls() throws RuntimeException {
ArrayList<CardInfo> list = new ArrayList<CardInfo>();
HashSet<String> filter = new HashSet<String>();
InputStream in = DownloadPictures.class.getClassLoader().getResourceAsStream("card-pictures-tok.txt");
readImageURLsFromFile(in, list, filter);
return list;
}
private static ArrayList<CardInfo> getTokenCardUrls() throws RuntimeException {
ArrayList<CardInfo> list = new ArrayList<CardInfo>();
HashSet<String> filter = new HashSet<String>();
InputStream in = DownloadPictures.class.getClassLoader().getResourceAsStream("card-pictures-tok.txt");
readImageURLsFromFile(in, list, filter);
return list;
}
private static void readImageURLsFromFile(InputStream in, ArrayList<CardInfo> list, Set<String> filter) throws RuntimeException {
if (in == null) {
log.error("resources input stream is null");
return;
}
private static void readImageURLsFromFile(InputStream in, ArrayList<CardInfo> list, Set<String> filter) throws RuntimeException {
if (in == null) {
log.error("resources input stream is null");
return;
}
BufferedReader reader = null;
InputStreamReader input = null;
try {
input = new InputStreamReader(in);
reader = new BufferedReader(input);
String line;
BufferedReader reader = null;
InputStreamReader input = null;
try {
input = new InputStreamReader(in);
reader = new BufferedReader(input);
String line;
line = reader.readLine();
while (line != null) {
line = line.trim();
if (line.startsWith("|")) { // new format
String[] params = line.split("\\|");
if (params.length >= 4) {
if (params[1].toLowerCase().equals("generate") && params[2].startsWith("TOK:")) {
String set = params[2].substring(4);
CardInfo card = new CardInfo(params[3], set, 0, 0, true);
list.add(card);
} else if (params[1].toLowerCase().equals("generate") && params[2].startsWith("EMBLEM:")) {
line = reader.readLine();
while (line != null) {
line = line.trim();
if (line.startsWith("|")) { // new format
String[] params = line.split("\\|");
if (params.length >= 4) {
if (params[1].toLowerCase().equals("generate") && params[2].startsWith("TOK:")) {
String set = params[2].substring(4);
CardInfo card = new CardInfo(params[3], set, 0, 0, true);
list.add(card);
} else if (params[1].toLowerCase().equals("generate") && params[2].startsWith("EMBLEM:")) {
String set = params[2].substring(7);
CardInfo card = new CardInfo("Emblem " + params[3], set, 0, 0, true);
list.add(card);
}
} else {
log.error("wrong format for image urls: " + line);
}
}
line = reader.readLine();
}
} else {
log.error("wrong format for image urls: " + line);
}
}
line = reader.readLine();
}
} catch (Exception ex) {
log.error(ex);
throw new RuntimeException("DownloadPictures : readFile() error");
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception ex) {
log.error(ex);
throw new RuntimeException("DownloadPictures : readFile() error");
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
@Override
public void run() {
public void run() {
File base = new File(this.imagesPath != null ? imagesPath : Constants.IO.imageBaseDir);
if (!base.exists()) {
base.mkdir();
}
File base = new File(this.imagesPath != null ? imagesPath : Constants.IO.imageBaseDir);
if (!base.exists()) {
base.mkdir();
}
Connection.ProxyType configProxyType = Connection.ProxyType.valueByText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));
Connection.ProxyType configProxyType = Connection.ProxyType.valueByText(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));
Proxy.Type type = Proxy.Type.DIRECT;
switch (configProxyType) {
case HTTP: type = Proxy.Type.HTTP; break;
case SOCKS: type = Proxy.Type.SOCKS; break;
case NONE:
default: p = Proxy.NO_PROXY; break;
}
Proxy.Type type = Proxy.Type.DIRECT;
switch (configProxyType) {
case HTTP: type = Proxy.Type.HTTP; break;
case SOCKS: type = Proxy.Type.SOCKS; break;
case NONE:
default: p = Proxy.NO_PROXY; break;
}
if (type != Proxy.Type.DIRECT) {
try {
String address = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_ADDRESS, "");
Integer port = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_PORT, "80"));
p = new Proxy(type, new InetSocketAddress(address, port));
} catch (Exception ex) {
throw new RuntimeException("Gui_DownloadPictures : error 1 - " + ex);
}
}
if (type != Proxy.Type.DIRECT) {
try {
String address = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_ADDRESS, "");
Integer port = Integer.parseInt(PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_PORT, "80"));
p = new Proxy(type, new InetSocketAddress(address, port));
} catch (Exception ex) {
throw new RuntimeException("Gui_DownloadPictures : error 1 - " + ex);
}
}
if (p != null) {
HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls();
if (p != null) {
HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls();
update(0);
for (int i = 0; i < cards.size() && !cancel; i++) {
try {
update(0);
for (int i = 0; i < cards.size() && !cancel; i++) {
try {
CardInfo card = cards.get(i);
CardInfo card = cards.get(i);
log.info("Downloading card: " + card.getName() + " (" + card.getSet() + ")");
log.info("Downloading card: " + card.getName() + " (" + card.getSet() + ")");
String url;
if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
if (card.getCollectorId() != 0) {
continue;
}
url = cardImageSource.generateTokenUrl(card.getName(), card.getSet());
} else {
String url;
if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
if (card.getCollectorId() != 0) {
continue;
}
url = cardImageSource.generateTokenUrl(card.getName(), card.getSet());
} else {
url = cardImageSource.generateURL(card.getCollectorId(), card.getDownloadName(), card.getSet(),
card.isTwoFacedCard(), card.isSecondSide(), card.isFlipCard());
}
@ -429,19 +429,19 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
update(cardIndex + 1);
}
}
} catch (Exception ex) {
log.error(ex, ex);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
closeButton.setText("Close");
}
} catch (Exception ex) {
log.error(ex, ex);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
}
closeButton.setText("Close");
}
private final class DownloadTask implements Runnable {
@ -529,16 +529,16 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
}
}
private static File createDirForCard(CardInfo card, String imagesPath) throws Exception {
File setDir = new File(CardImageUtils.getImageDir(card, imagesPath));
if (!setDir.exists()) {
setDir.mkdirs();
}
return setDir;
}
private static File createDirForCard(CardInfo card, String imagesPath) throws Exception {
File setDir = new File(CardImageUtils.getImageDir(card, imagesPath));
if (!setDir.exists()) {
setDir.mkdirs();
}
return setDir;
}
private void update(int card) {
this.cardIndex = card;
private void update(int card) {
this.cardIndex = card;
int count = DownloadPictures.this.cards.size();
if (cardIndex < count) {
@ -569,9 +569,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
startDownloadButton.setEnabled(true);
}
}
}
}
private static final Logger log = Logger.getLogger(DownloadPictures.class);
private static final Logger log = Logger.getLogger(DownloadPictures.class);
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}

View file

@ -35,70 +35,70 @@ import java.util.regex.Pattern;
*/
public class ImageCache {
private static final Logger log = Logger.getLogger(ImageCache.class);
private static final Logger log = Logger.getLogger(ImageCache.class);
private static final Map<String, BufferedImage> imageCache;
private static final Map<String, BufferedImage> imageCache;
/**
* Common pattern for keys.
* Format: "<cardname>#<setname>#<collectorID>"
*/
private static final Pattern KEY_PATTERN = Pattern.compile("(.*)#(.*)#(.*)#(.*)");
static {
imageCache = new MapMaker().softValues().makeComputingMap(new Function<String, BufferedImage>() {
/**
* Common pattern for keys.
* Format: "<cardname>#<setname>#<collectorID>"
*/
private static final Pattern KEY_PATTERN = Pattern.compile("(.*)#(.*)#(.*)#(.*)");
static {
imageCache = new MapMaker().softValues().makeComputingMap(new Function<String, BufferedImage>() {
@Override
public BufferedImage apply(String key) {
try {
boolean thumbnail = false;
if (key.endsWith("#thumb")) {
thumbnail = true;
key = key.replace("#thumb", "");
}
Matcher m = KEY_PATTERN.matcher(key);
public BufferedImage apply(String key) {
try {
boolean thumbnail = false;
if (key.endsWith("#thumb")) {
thumbnail = true;
key = key.replace("#thumb", "");
}
Matcher m = KEY_PATTERN.matcher(key);
if (m.matches()) {
String name = m.group(1);
String set = m.group(2);
if (m.matches()) {
String name = m.group(1);
String set = m.group(2);
Integer type = Integer.parseInt(m.group(3));
Integer collectorId = Integer.parseInt(m.group(4));
CardInfo info = new CardInfo(name, set, collectorId, type);
if (collectorId == 0) info.setToken(true);
String path = CardImageUtils.getImagePath(info);
if (path == null) return null;
File file = new File(path);
CardInfo info = new CardInfo(name, set, collectorId, type);
if (thumbnail && path.endsWith(".jpg")) {
String thumbnailPath = path.replace(".jpg", ".thumb.jpg");
File thumbnailFile = new File(thumbnailPath);
if (thumbnailFile.exists()) {
//log.debug("loading thumbnail for " + key + ", path="+thumbnailPath);
return loadImage(thumbnailFile);
} else {
BufferedImage image = loadImage(file);
image = getWizardsCard(image);
if (image == null) return null;
//log.debug("creating thumbnail for " + key);
return makeThumbnail(image, thumbnailPath);
}
} else {
return getWizardsCard(loadImage(file));
}
} else {
throw new RuntimeException(
"Requested image doesn't fit the requirement for key (<cardname>#<setname>#<collectorID>): " + key);
}
} catch (Exception ex) {
if (ex instanceof ComputationException)
throw (ComputationException) ex;
else
throw new ComputationException(ex);
}
}
});
}
if (collectorId == 0) info.setToken(true);
String path = CardImageUtils.getImagePath(info);
if (path == null) return null;
File file = new File(path);
if (thumbnail && path.endsWith(".jpg")) {
String thumbnailPath = path.replace(".jpg", ".thumb.jpg");
File thumbnailFile = new File(thumbnailPath);
if (thumbnailFile.exists()) {
//log.debug("loading thumbnail for " + key + ", path="+thumbnailPath);
return loadImage(thumbnailFile);
} else {
BufferedImage image = loadImage(file);
image = getWizardsCard(image);
if (image == null) return null;
//log.debug("creating thumbnail for " + key);
return makeThumbnail(image, thumbnailPath);
}
} else {
return getWizardsCard(loadImage(file));
}
} else {
throw new RuntimeException(
"Requested image doesn't fit the requirement for key (<cardname>#<setname>#<collectorID>): " + key);
}
} catch (Exception ex) {
if (ex instanceof ComputationException)
throw (ComputationException) ex;
else
throw new ComputationException(ex);
}
}
});
}
public static BufferedImage getWizardsCard(BufferedImage image) {
if (image.getWidth() == 265 && image.getHeight() == 370) {
@ -112,140 +112,140 @@ public class ImageCache {
}
}
public static BufferedImage getThumbnail(CardView card) {
String key = getKey(card) + "#thumb";
//log.debug("#key: " + key);
return getImage(key);
}
public static BufferedImage getThumbnail(CardView card) {
String key = getKey(card) + "#thumb";
//log.debug("#key: " + key);
return getImage(key);
}
public static BufferedImage getImageOriginal(CardView card) {
String key = getKey(card);
//log.debug("#key: " + key);
return getImage(key);
}
public static BufferedImage getImageOriginal(CardView card) {
String key = getKey(card);
//log.debug("#key: " + key);
return getImage(key);
}
/**
* Returns the Image corresponding to the key
*/
private static BufferedImage getImage(String key) {
try {
BufferedImage image = imageCache.get(key);
return image;
} catch (NullPointerException ex) {
// unfortunately NullOutputException, thrown when apply() returns
// null, is not public
// NullOutputException is a subclass of NullPointerException
// legitimate, happens when a card has no image
return null;
} catch (ComputationException ex) {
if (ex.getCause() instanceof NullPointerException)
return null;
log.error(ex,ex);
return null;
}
}
/**
* Returns the Image corresponding to the key
*/
private static BufferedImage getImage(String key) {
try {
BufferedImage image = imageCache.get(key);
return image;
} catch (NullPointerException ex) {
// unfortunately NullOutputException, thrown when apply() returns
// null, is not public
// NullOutputException is a subclass of NullPointerException
// legitimate, happens when a card has no image
return null;
} catch (ComputationException ex) {
if (ex.getCause() instanceof NullPointerException)
return null;
log.error(ex,ex);
return null;
}
}
/**
* Returns the map key for a card, without any suffixes for the image size.
*/
private static String getKey(CardView card) {
String set = card.getExpansionSetCode();
/**
* Returns the map key for a card, without any suffixes for the image size.
*/
private static String getKey(CardView card) {
String set = card.getExpansionSetCode();
int type = card.getType();
String key = card.getName() + "#" + set + "#" + type + "#" + String.valueOf(card.getCardNumber());
String key = card.getName() + "#" + set + "#" + type + "#" + String.valueOf(card.getCardNumber());
return key;
}
return key;
}
/**
* Load image from file
*
* @param file
* file to load image from
* @return {@link BufferedImage}
*/
public static BufferedImage loadImage(File file) {
BufferedImage image = null;
if (!file.exists()) {
return null;
}
try {
image = ImageIO.read(file);
} catch (Exception e) {
log.error(e, e);
}
/**
* Load image from file
*
* @param file
* file to load image from
* @return {@link BufferedImage}
*/
public static BufferedImage loadImage(File file) {
BufferedImage image = null;
if (!file.exists()) {
return null;
}
try {
image = ImageIO.read(file);
} catch (Exception e) {
log.error(e, e);
}
return image;
}
return image;
}
public static BufferedImage makeThumbnail(BufferedImage original, String path) {
BufferedImage image = getResizedImage(original, Constants.THUMBNAIL_SIZE_FULL);
File imagePath = new File(path);
try {
//log.debug("thumbnail path:"+path);
ImageIO.write(image, "jpg", imagePath);
} catch (Exception e) {
log.error(e,e);
}
return image;
}
/**
* Returns an image scaled to the size given
*/
public static BufferedImage getNormalSizeImage(BufferedImage original) {
if (original == null) {
return null;
}
int srcWidth = original.getWidth();
int srcHeight = original.getHeight();
int tgtWidth = Constants.CARD_SIZE_FULL.width;
int tgtHeight = Constants.CARD_SIZE_FULL.height;
if (srcWidth == tgtWidth && srcHeight == tgtHeight)
return original;
public static BufferedImage makeThumbnail(BufferedImage original, String path) {
BufferedImage image = getResizedImage(original, Constants.THUMBNAIL_SIZE_FULL);
File imagePath = new File(path);
try {
//log.debug("thumbnail path:"+path);
ImageIO.write(image, "jpg", imagePath);
} catch (Exception e) {
log.error(e,e);
}
return image;
}
ResampleOp resampleOp = new ResampleOp(tgtWidth, tgtHeight);
BufferedImage image = resampleOp.filter(original, null);
return image;
}
/**
* Returns an image scaled to the size given
*/
public static BufferedImage getNormalSizeImage(BufferedImage original) {
if (original == null) {
return null;
}
/**
* Returns an image scaled to the size appropriate for the card picture
* panel For future use.
*/
private static BufferedImage getFullSizeImage(BufferedImage original, double scale) {
if (scale == 1)
return original;
ResampleOp resampleOp = new ResampleOp((int) (original.getWidth() * scale), (int) (original.getHeight() * scale));
BufferedImage image = resampleOp.filter(original, null);
return image;
}
int srcWidth = original.getWidth();
int srcHeight = original.getHeight();
/**
* Returns an image scaled to the size appropriate for the card picture
* panel
*/
public static BufferedImage getResizedImage(BufferedImage original, Rectangle sizeNeed) {
ResampleOp resampleOp = new ResampleOp(sizeNeed.width, sizeNeed.height);
BufferedImage image = resampleOp.filter(original, null);
return image;
}
int tgtWidth = Constants.CARD_SIZE_FULL.width;
int tgtHeight = Constants.CARD_SIZE_FULL.height;
/**
* Returns the image appropriate to display the card in the picture panel
*/
public static BufferedImage getImage(CardView card, int width, int height) {
String key = getKey(card);
BufferedImage original = getImage(key);
if (original == null)
return null;
if (srcWidth == tgtWidth && srcHeight == tgtHeight)
return original;
double scale = Math.min((double) width / original.getWidth(), (double) height / original.getHeight());
if (scale > 1)
scale = 1;
ResampleOp resampleOp = new ResampleOp(tgtWidth, tgtHeight);
BufferedImage image = resampleOp.filter(original, null);
return image;
}
return getFullSizeImage(original, scale);
}
/**
* Returns an image scaled to the size appropriate for the card picture
* panel For future use.
*/
private static BufferedImage getFullSizeImage(BufferedImage original, double scale) {
if (scale == 1)
return original;
ResampleOp resampleOp = new ResampleOp((int) (original.getWidth() * scale), (int) (original.getHeight() * scale));
BufferedImage image = resampleOp.filter(original, null);
return image;
}
/**
* Returns an image scaled to the size appropriate for the card picture
* panel
*/
public static BufferedImage getResizedImage(BufferedImage original, Rectangle sizeNeed) {
ResampleOp resampleOp = new ResampleOp(sizeNeed.width, sizeNeed.height);
BufferedImage image = resampleOp.filter(original, null);
return image;
}
/**
* Returns the image appropriate to display the card in the picture panel
*/
public static BufferedImage getImage(CardView card, int width, int height) {
String key = getKey(card);
BufferedImage original = getImage(key);
if (original == null)
return null;
double scale = Math.min((double) width / original.getWidth(), (double) height / original.getHeight());
if (scale > 1)
scale = 1;
return getFullSizeImage(original, scale);
}
}

View file

@ -32,157 +32,157 @@ public class CardInfoPaneImpl extends JEditorPane implements CardInfoPane {
}
public void setCard(final CardView card) {
if (card == null) return;
if (card == null) return;
if (isCurrentCard(card)) return;
currentCard = card;
currentCard = card;
ThreadUtils.threadPool.submit(new Runnable() {
public void run() {
try {
if (!card.equals(currentCard)) return;
try {
if (!card.equals(currentCard)) return;
String manaCost = "";
for (String m : card.getManaCost()) {
manaCost += m;
}
String castingCost = UI.getDisplayManaCost(manaCost);
castingCost = ManaSymbols.replaceSymbolsWithHTML(castingCost, ManaSymbols.Type.CARD);
String manaCost = "";
for (String m : card.getManaCost()) {
manaCost += m;
}
String castingCost = UI.getDisplayManaCost(manaCost);
castingCost = ManaSymbols.replaceSymbolsWithHTML(castingCost, ManaSymbols.Type.CARD);
int symbolCount = 0;
int offset = 0;
while ((offset = castingCost.indexOf("<img", offset) + 1) != 0)
symbolCount++;
int symbolCount = 0;
int offset = 0;
while ((offset = castingCost.indexOf("<img", offset) + 1) != 0)
symbolCount++;
List<String> rules = card.getRules();
List<String> rulings = new ArrayList<String>(rules);
List<String> rules = card.getRules();
List<String> rulings = new ArrayList<String>(rules);
if (card instanceof PermanentView) {
if (card instanceof PermanentView) {
if (card.getPairedCard() != null) {
rulings.add("<span color='green'><i>Paired with another creature</i></span>");
}
List<CounterView> counters = ((PermanentView) card).getCounters();
int count = counters != null ? counters.size() : 0;
if (count > 0) {
StringBuilder sb = new StringBuilder();
int index = 0;
for (CounterView counter : ((PermanentView) card).getCounters()) {
if (counter.getCount() > 0) {
if (index == 0) {
sb.append("<b>Counters:</b> ");
} else {
sb.append(", ");
}
sb.append(counter.getCount() + "x<i>" + counter.getName() + "</i>");
index++;
}
}
rulings.add(sb.toString());
}
int damage = ((PermanentView)card).getDamage();
if (damage > 0) {
rulings.add("<span color='red'><b>Damage dealt:</b> " + damage + "</span>");
}
}
List<CounterView> counters = ((PermanentView) card).getCounters();
int count = counters != null ? counters.size() : 0;
if (count > 0) {
StringBuilder sb = new StringBuilder();
int index = 0;
for (CounterView counter : ((PermanentView) card).getCounters()) {
if (counter.getCount() > 0) {
if (index == 0) {
sb.append("<b>Counters:</b> ");
} else {
sb.append(", ");
}
sb.append(counter.getCount() + "x<i>" + counter.getName() + "</i>");
index++;
}
}
rulings.add(sb.toString());
}
int damage = ((PermanentView)card).getDamage();
if (damage > 0) {
rulings.add("<span color='red'><b>Damage dealt:</b> " + damage + "</span>");
}
}
boolean smallImages = true;
int fontSize = 11;
boolean smallImages = true;
int fontSize = 11;
String fontFamily = "tahoma";
/*if (prefs.fontFamily == CardFontFamily.arial)
fontFamily = "arial";
else if (prefs.fontFamily == CardFontFamily.verdana) {
fontFamily = "verdana";
}*/
String fontFamily = "tahoma";
/*if (prefs.fontFamily == CardFontFamily.arial)
fontFamily = "arial";
else if (prefs.fontFamily == CardFontFamily.verdana) {
fontFamily = "verdana";
}*/
final StringBuffer buffer = new StringBuffer(512);
buffer.append("<html><body style='font-family:");
buffer.append(fontFamily);
buffer.append(";font-size:");
buffer.append(fontSize);
buffer.append("pt;margin:0px 1px 0px 1px'>");
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'>");
buffer.append("<tr><td valign='top'><b>");
buffer.append(card.getName());
buffer.append("</b></td><td align='right' valign='top' style='width:");
buffer.append(symbolCount * 11 + 1);
buffer.append("px'>");
buffer.append(castingCost);
buffer.append("</td></tr></table>");
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'><tr><td style='margin-left: 1px'>");
buffer.append(getTypes(card));
buffer.append("</td><td align='right'>");
switch (card.getRarity()) {
case RARE:
buffer.append("<b color='#FFBF00'>");
break;
case UNCOMMON:
buffer.append("<b color='silver'>");
break;
case COMMON:
buffer.append("<b color='black'>");
break;
case MYTHIC:
buffer.append("<b color='#D5330B'>");
break;
}
String rarity = card.getRarity().getCode();
if (card.getExpansionSetCode() != null) {
buffer.append(ManaSymbols.replaceSetCodeWithHTML(card.getExpansionSetCode().toUpperCase(), rarity));
}
buffer.append("</td></tr></table>");
final StringBuffer buffer = new StringBuffer(512);
buffer.append("<html><body style='font-family:");
buffer.append(fontFamily);
buffer.append(";font-size:");
buffer.append(fontSize);
buffer.append("pt;margin:0px 1px 0px 1px'>");
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'>");
buffer.append("<tr><td valign='top'><b>");
buffer.append(card.getName());
buffer.append("</b></td><td align='right' valign='top' style='width:");
buffer.append(symbolCount * 11 + 1);
buffer.append("px'>");
buffer.append(castingCost);
buffer.append("</td></tr></table>");
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'><tr><td style='margin-left: 1px'>");
buffer.append(getTypes(card));
buffer.append("</td><td align='right'>");
switch (card.getRarity()) {
case RARE:
buffer.append("<b color='#FFBF00'>");
break;
case UNCOMMON:
buffer.append("<b color='silver'>");
break;
case COMMON:
buffer.append("<b color='black'>");
break;
case MYTHIC:
buffer.append("<b color='#D5330B'>");
break;
}
String rarity = card.getRarity().getCode();
if (card.getExpansionSetCode() != null) {
buffer.append(ManaSymbols.replaceSetCodeWithHTML(card.getExpansionSetCode().toUpperCase(), rarity));
}
buffer.append("</td></tr></table>");
String pt = "";
if (CardUtil.isCreature(card)) {
pt = card.getPower() + "/" + card.getToughness();
} else if (CardUtil.isPlaneswalker(card)) {
pt = card.getLoyalty().toString();
}
if (pt.length() > 0) {
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%' valign='bottom'><tr><td>");
buffer.append("<b>");
buffer.append(pt);
buffer.append("</b>");
buffer.append("</td></tr></table>");
}
String pt = "";
if (CardUtil.isCreature(card)) {
pt = card.getPower() + "/" + card.getToughness();
} else if (CardUtil.isPlaneswalker(card)) {
pt = card.getLoyalty().toString();
}
if (pt.length() > 0) {
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%' valign='bottom'><tr><td>");
buffer.append("<b>");
buffer.append(pt);
buffer.append("</b>");
buffer.append("</td></tr></table>");
}
String legal = "";
if (rulings.size() > 0) {
legal = legal.replaceAll("#([^#]+)#", "<i>$1</i>");
legal = legal.replaceAll("\\s*//\\s*", "<hr width='50%'>");
legal = legal.replace("\r\n", "<div style='font-size:5pt'></div>");
legal += "<br>";
for (String ruling : rulings) {
if (ruling != null && !ruling.replace(".", "").trim().isEmpty()) {
legal += "<p style='margin: 2px'>";
legal += ruling;
legal += "</p>";
}
}
}
String legal = "";
if (rulings.size() > 0) {
legal = legal.replaceAll("#([^#]+)#", "<i>$1</i>");
legal = legal.replaceAll("\\s*//\\s*", "<hr width='50%'>");
legal = legal.replace("\r\n", "<div style='font-size:5pt'></div>");
legal += "<br>";
for (String ruling : rulings) {
if (ruling != null && !ruling.replace(".", "").trim().isEmpty()) {
legal += "<p style='margin: 2px'>";
legal += ruling;
legal += "</p>";
}
}
}
if (legal.length() > 0) {
//buffer.append("<br>");
legal = legal.replaceAll("\\{this\\}", card.getName());
legal = legal.replaceAll("\\{source\\}", card.getName());
buffer.append(ManaSymbols.replaceSymbolsWithHTML(legal, ManaSymbols.Type.CARD));
}
if (legal.length() > 0) {
//buffer.append("<br>");
legal = legal.replaceAll("\\{this\\}", card.getName());
legal = legal.replaceAll("\\{source\\}", card.getName());
buffer.append(ManaSymbols.replaceSymbolsWithHTML(legal, ManaSymbols.Type.CARD));
}
buffer.append("<br></body></html>");
buffer.append("<br></body></html>");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (!card.equals(currentCard)) return;
setText(buffer.toString());
//System.out.println(buffer.toString());
setCaretPosition(0);
//ThreadUtils.sleep(300);
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (!card.equals(currentCard)) return;
setText(buffer.toString());
//System.out.println(buffer.toString());
setCaretPosition(0);
//ThreadUtils.sleep(300);
}
});
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

View file

@ -11,68 +11,68 @@ import org.mage.plugins.card.constants.Constants;
public class SettingsManager {
private static SettingsManager settingsManager = null;
private static SettingsManager settingsManager = null;
public static SettingsManager getIntance() {
if (settingsManager == null) {
synchronized (SettingsManager.class) {
if (settingsManager == null) settingsManager = new SettingsManager();
}
}
return settingsManager;
}
public static SettingsManager getIntance() {
if (settingsManager == null) {
synchronized (SettingsManager.class) {
if (settingsManager == null) settingsManager = new SettingsManager();
}
}
return settingsManager;
}
private SettingsManager() {
loadImageProperties();
}
public void reloadImageProperties() {
loadImageProperties();
}
private void loadImageProperties() {
imageUrlProperties = new Properties();
try {
InputStream is = SettingsManager.class.getClassLoader().getResourceAsStream(Constants.IO.IMAGE_PROPERTIES_FILE);
if (is == null)
throw new RuntimeException("Couldn't load " + Constants.IO.IMAGE_PROPERTIES_FILE);
imageUrlProperties.load(is);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private SettingsManager() {
loadImageProperties();
}
public String getSetNameReplacement(String setName) {
String result = setName;
if (imageUrlProperties != null) {
result = imageUrlProperties.getProperty(setName, setName);
}
return result;
}
public HashSet<String> getIgnoreUrls() {
HashSet<String> ignoreUrls = new HashSet<String>();
if (imageUrlProperties != null) {
String result = imageUrlProperties.getProperty("ignore.urls");
if (result != null) {
String[] ignore = result.split(",");
public void reloadImageProperties() {
loadImageProperties();
}
private void loadImageProperties() {
imageUrlProperties = new Properties();
try {
InputStream is = SettingsManager.class.getClassLoader().getResourceAsStream(Constants.IO.IMAGE_PROPERTIES_FILE);
if (is == null)
throw new RuntimeException("Couldn't load " + Constants.IO.IMAGE_PROPERTIES_FILE);
imageUrlProperties.load(is);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public String getSetNameReplacement(String setName) {
String result = setName;
if (imageUrlProperties != null) {
result = imageUrlProperties.getProperty(setName, setName);
}
return result;
}
public HashSet<String> getIgnoreUrls() {
HashSet<String> ignoreUrls = new HashSet<String>();
if (imageUrlProperties != null) {
String result = imageUrlProperties.getProperty("ignore.urls");
if (result != null) {
String[] ignore = result.split(",");
ignoreUrls.addAll(Arrays.asList(ignore));
}
}
return ignoreUrls;
}
public ArrayList<String> getTokenLookupOrder() {
ArrayList<String> order = new ArrayList<String>();
if (imageUrlProperties != null) {
String result = imageUrlProperties.getProperty("token.lookup.order");
if (result != null) {
String[] sets = result.split(",");
order.addAll(Arrays.asList(sets));
}
}
return order;
}
}
}
return ignoreUrls;
}
private Properties imageUrlProperties;
public ArrayList<String> getTokenLookupOrder() {
ArrayList<String> order = new ArrayList<String>();
if (imageUrlProperties != null) {
String result = imageUrlProperties.getProperty("token.lookup.order");
if (result != null) {
String[] sets = result.split(",");
order.addAll(Arrays.asList(sets));
}
}
return order;
}
private Properties imageUrlProperties;
}

View file

@ -9,80 +9,80 @@ import java.util.HashMap;
public class CardImageUtils {
private static HashMap<CardInfo, String> pathCache = new HashMap<CardInfo, String>();
/**
* Get path to image for specific card.
*
* @param card
* card to get path for
* @return String if image exists, else null
*/
public static String getImagePath(CardInfo card) {
String filePath;
private static HashMap<CardInfo, String> pathCache = new HashMap<CardInfo, String>();
/**
* Get path to image for specific card.
*
* @param card
* card to get path for
* @return String if image exists, else null
*/
public static String getImagePath(CardInfo card) {
String filePath;
String suffix = ".jpg";
File file = null;
if (card.isToken()) {
if (pathCache.containsKey(card)) {
return pathCache.get(card);
}
filePath = getTokenImagePath(card);
file = new File(filePath);
if (!file.exists()) {
filePath = searchForCardImage(card);
file = new File(filePath);
}
if (file.exists()) {
pathCache.put(card, filePath);
}
} else {
filePath = getImagePath(card, false);
file = new File(filePath);
if (!file.exists()) {
filePath = getImagePath(card, true);
file = new File(filePath);
}
}
/**
* try current directory
*/
if (file == null || !file.exists()) {
filePath = cleanString(card.getName()) + suffix;
file = new File(filePath);
}
File file = null;
if (card.isToken()) {
if (pathCache.containsKey(card)) {
return pathCache.get(card);
}
filePath = getTokenImagePath(card);
file = new File(filePath);
if (file.exists()) {
return filePath;
} else {
return null;
}
}
private static String getTokenImagePath(CardInfo card) {
String filename = getImagePath(card, false);
File file = new File(filename);
if (!file.exists()) {
if (!file.exists()) {
filePath = searchForCardImage(card);
file = new File(filePath);
}
if (file.exists()) {
pathCache.put(card, filePath);
}
} else {
filePath = getImagePath(card, false);
file = new File(filePath);
if (!file.exists()) {
filePath = getImagePath(card, true);
file = new File(filePath);
}
}
/**
* try current directory
*/
if (file == null || !file.exists()) {
filePath = cleanString(card.getName()) + suffix;
file = new File(filePath);
}
if (file.exists()) {
return filePath;
} else {
return null;
}
}
private static String getTokenImagePath(CardInfo card) {
String filename = getImagePath(card, false);
File file = new File(filename);
if (!file.exists()) {
CardInfo updated = new CardInfo(card);
updated.setName(card.getName() + " 1");
filename = getImagePath(updated, false);
file = new File(filename);
if (!file.exists()) {
updated.setName(card.getName() + " 1");
filename = getImagePath(updated, false);
file = new File(filename);
if (!file.exists()) {
updated = new CardInfo(card);
updated.setName(card.getName() + " 2");
filename = getImagePath(updated, false);
file = new File(filename);
}
}
return filename;
}
updated.setName(card.getName() + " 2");
filename = getImagePath(updated, false);
file = new File(filename);
}
}
return filename;
}
private static String searchForCardImage(CardInfo card) {
File file = null;
String path = "";
@ -100,57 +100,57 @@ public class CardImageUtils {
return "";
}
public static String cleanString(String in) {
in = in.trim();
StringBuilder out = new StringBuilder();
char c;
for (int i = 0; i < in.length(); i++) {
c = in.charAt(i);
if (c == ' ' || c == '-')
out.append('_');
else if (Character.isLetterOrDigit(c)) {
out.append(c);
}
}
public static String cleanString(String in) {
in = in.trim();
StringBuilder out = new StringBuilder();
char c;
for (int i = 0; i < in.length(); i++) {
c = in.charAt(i);
if (c == ' ' || c == '-')
out.append('_');
else if (Character.isLetterOrDigit(c)) {
out.append(c);
}
}
return out.toString().toLowerCase();
}
public static String updateSet(String cardSet, boolean forUrl) {
String set = cardSet.toLowerCase();
if (set.equals("con")) {
set = "cfx";
}
if (forUrl) {
set = SettingsManager.getIntance().getSetNameReplacement(set);
}
return set;
}
public static String getImageDir(CardInfo card, String imagesPath) {
if (card.getSet() == null) {
return "";
}
String set = updateSet(card.getSet(), false).toUpperCase();
return out.toString().toLowerCase();
}
public static String updateSet(String cardSet, boolean forUrl) {
String set = cardSet.toLowerCase();
if (set.equals("con")) {
set = "cfx";
}
if (forUrl) {
set = SettingsManager.getIntance().getSetNameReplacement(set);
}
return set;
}
public static String getImageDir(CardInfo card, String imagesPath) {
if (card.getSet() == null) {
return "";
}
String set = updateSet(card.getSet(), false).toUpperCase();
String imagesDir = (imagesPath != null ? imagesPath : Constants.IO.imageBaseDir);
if (card.isToken()) {
return imagesDir + File.separator + "TOK" + File.separator + set;
} else {
return imagesDir + File.separator + set;
}
}
if (card.isToken()) {
return imagesDir + File.separator + "TOK" + File.separator + set;
} else {
return imagesDir + File.separator + set;
}
}
public static String getImagePath(CardInfo card, boolean withCollector) {
return getImagePath(card, withCollector, null);
}
public static String getImagePath(CardInfo card, boolean withCollector, String imagesPath) {
String type = card.getType() != 0 ? " " + Integer.toString(card.getType()) : "";
public static String getImagePath(CardInfo card, boolean withCollector, String imagesPath) {
String type = card.getType() != 0 ? " " + Integer.toString(card.getType()) : "";
String name = card.getName();
if (withCollector) {
return getImageDir(card, imagesPath) + File.separator + name + "." + card.getCollectorId() + ".full.jpg";
} else {
return getImageDir(card, imagesPath) + File.separator + name + type + ".full.jpg";
}
}
return getImageDir(card, imagesPath) + File.separator + name + "." + card.getCollectorId() + ".full.jpg";
} else {
return getImageDir(card, imagesPath) + File.separator + name + type + ".full.jpg";
}
}
}

View file

@ -3,9 +3,9 @@ package org.mage.plugins.card.utils;
import java.awt.*;
public interface ImageManager {
public Image getSicknessImage();
public Image getDayImage();
public Image getNightImage();
public Image getSicknessImage();
public Image getDayImage();
public Image getNightImage();
public Image getDlgAcceptButtonImage();
public Image getDlgActiveAcceptButtonImage();

View file

@ -13,40 +13,40 @@ import java.net.URL;
public class ImageManagerImpl implements ImageManager {
private static ImageManagerImpl fInstance = new ImageManagerImpl();
public static ImageManagerImpl getInstance() {
return fInstance;
}
@Override
public BufferedImage getSicknessImage() {
if (imageSickness == null) {
Image image = getImageFromResourceTransparent("/sickness.png", Color.WHITE, new Rectangle(296, 265));
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(0, 0, 200, 285)));
imageSickness = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageSickness;
}
private static ImageManagerImpl fInstance = new ImageManagerImpl();
@Override
public BufferedImage getDayImage() {
if (imageDay == null) {
Image image = getImageFromResourceTransparent("/card/day.png", Color.WHITE, new Rectangle(20, 20));
imageDay = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageDay;
}
public static ImageManagerImpl getInstance() {
return fInstance;
}
@Override
public BufferedImage getNightImage() {
if (imageNight == null) {
Image image = getImageFromResourceTransparent("/card/night.png", Color.WHITE, new Rectangle(20, 20));
imageNight = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageNight;
}
@Override
public BufferedImage getSicknessImage() {
if (imageSickness == null) {
Image image = getImageFromResourceTransparent("/sickness.png", Color.WHITE, new Rectangle(296, 265));
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(0, 0, 200, 285)));
imageSickness = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageSickness;
}
@Override
public BufferedImage getDayImage() {
if (imageDay == null) {
Image image = getImageFromResourceTransparent("/card/day.png", Color.WHITE, new Rectangle(20, 20));
imageDay = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageDay;
}
@Override
public BufferedImage getNightImage() {
if (imageNight == null) {
Image image = getImageFromResourceTransparent("/card/night.png", Color.WHITE, new Rectangle(20, 20));
imageNight = BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB);
}
return imageNight;
}
@Override
public Image getDlgCancelButtonImage() {
@ -112,9 +112,9 @@ public class ImageManagerImpl implements ImageManager {
return image;
}
private static BufferedImage imageSickness;
private static BufferedImage imageDay;
private static BufferedImage imageNight;
private static BufferedImage imageSickness;
private static BufferedImage imageDay;
private static BufferedImage imageNight;
private static BufferedImage imageDlgAcceptButton;
private static BufferedImage imageDlgActiveAcceptButton;