[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

@ -8,359 +8,359 @@ import java.util.Timer;
import java.util.TimerTask;
abstract public class Animation {
static private final long TARGET_MILLIS_PER_FRAME = 30;
//static private final float HALF_PI = (float)(Math.PI / 2);
static private final long TARGET_MILLIS_PER_FRAME = 30;
//static private final float HALF_PI = (float)(Math.PI / 2);
static private Timer timer = new Timer("Animation", true);
static private Timer timer = new Timer("Animation", true);
//static private CardPanel delayedCardPanel;
//static private long delayedTime;
static private CardPanel enlargedCardPanel;
static private CardPanel enlargedAnimationPanel;
static private Object enlargeLock = new Object();
//static private CardPanel delayedCardPanel;
//static private long delayedTime;
static private CardPanel enlargedCardPanel;
static private CardPanel enlargedAnimationPanel;
static private Object enlargeLock = new Object();
private TimerTask timerTask;
private FrameTimer frameTimer;
private long elapsed;
private TimerTask timerTask;
private FrameTimer frameTimer;
private long elapsed;
public Animation (final long duration) {
this(duration, 0);
}
public Animation (final long duration) {
this(duration, 0);
}
public Animation (final long duration, long delay) {
timerTask = new TimerTask() {
public void run () {
if (frameTimer == null) {
start();
frameTimer = new FrameTimer();
}
elapsed += frameTimer.getTimeSinceLastFrame();
if (elapsed >= duration) {
cancel();
elapsed = duration;
}
update(elapsed / (float)duration);
if (elapsed == duration) end();
}
};
timer.scheduleAtFixedRate(timerTask, delay, TARGET_MILLIS_PER_FRAME);
}
public Animation (final long duration, long delay) {
timerTask = new TimerTask() {
public void run () {
if (frameTimer == null) {
start();
frameTimer = new FrameTimer();
}
elapsed += frameTimer.getTimeSinceLastFrame();
if (elapsed >= duration) {
cancel();
elapsed = duration;
}
update(elapsed / (float)duration);
if (elapsed == duration) end();
}
};
timer.scheduleAtFixedRate(timerTask, delay, TARGET_MILLIS_PER_FRAME);
}
abstract protected void update (float percentage);
abstract protected void update (float percentage);
protected void cancel () {
timerTask.cancel();
end();
}
protected void cancel () {
timerTask.cancel();
end();
}
protected void start () {
}
protected void start () {
}
protected void end () {
}
protected void end () {
}
/**
* Uses averaging of the time between the past few frames to provide smooth animation.
*/
private class FrameTimer {
static private final int SAMPLES = 6;
static private final long MAX_FRAME = 100; // Max time for one frame, to weed out spikes.
/**
* Uses averaging of the time between the past few frames to provide smooth animation.
*/
private class FrameTimer {
static private final int SAMPLES = 6;
static private final long MAX_FRAME = 100; // Max time for one frame, to weed out spikes.
private long samples[] = new long[SAMPLES];
private int sampleIndex;
private long samples[] = new long[SAMPLES];
private int sampleIndex;
public FrameTimer () {
long currentTime = System.currentTimeMillis();
for (int i = SAMPLES - 1; i >= 0; i--)
samples[i] = currentTime - (SAMPLES - i) * TARGET_MILLIS_PER_FRAME;
}
public FrameTimer () {
long currentTime = System.currentTimeMillis();
for (int i = SAMPLES - 1; i >= 0; i--)
samples[i] = currentTime - (SAMPLES - i) * TARGET_MILLIS_PER_FRAME;
}
public long getTimeSinceLastFrame () {
long currentTime = System.currentTimeMillis();
public long getTimeSinceLastFrame () {
long currentTime = System.currentTimeMillis();
int id = sampleIndex - 1;
if (id < 0) id += SAMPLES;
int id = sampleIndex - 1;
if (id < 0) id += SAMPLES;
long timeSinceLastSample = currentTime - samples[id];
long timeSinceLastSample = currentTime - samples[id];
// If the slice was too big, advance all the previous times by the diff.
if (timeSinceLastSample > MAX_FRAME) {
long diff = timeSinceLastSample - MAX_FRAME;
for (int i = 0; i < SAMPLES; i++)
samples[i] += diff;
}
// If the slice was too big, advance all the previous times by the diff.
if (timeSinceLastSample > MAX_FRAME) {
long diff = timeSinceLastSample - MAX_FRAME;
for (int i = 0; i < SAMPLES; i++)
samples[i] += diff;
}
long timeSinceOldestSample = currentTime - samples[sampleIndex];
samples[sampleIndex] = currentTime;
sampleIndex = (sampleIndex + 1) % SAMPLES;
long timeSinceOldestSample = currentTime - samples[sampleIndex];
samples[sampleIndex] = currentTime;
sampleIndex = (sampleIndex + 1) % SAMPLES;
return timeSinceOldestSample / (long)SAMPLES;
}
}
return timeSinceOldestSample / (long)SAMPLES;
}
}
static public void tapCardToggle (final CardPanel panel, final MagePermanent parent, final boolean tapped, final boolean flipped) {
new Animation(300) {
protected void start () {
parent.onBeginAnimation();
}
static public void tapCardToggle (final CardPanel panel, final MagePermanent parent, final boolean tapped, final boolean flipped) {
new Animation(300) {
protected void start () {
parent.onBeginAnimation();
}
protected void update (float percentage) {
if (tapped) {
panel.tappedAngle = CardPanel.TAPPED_ANGLE * percentage;
// reverse movement if untapping
if (!panel.isTapped()) panel.tappedAngle = CardPanel.TAPPED_ANGLE - panel.tappedAngle;
}
if (flipped) {
panel.flippedAngle = CardPanel.FLIPPED_ANGLE * percentage;
if (!panel.isFlipped()) panel.flippedAngle = CardPanel.FLIPPED_ANGLE - panel.flippedAngle;
}
panel.repaint();
}
protected void update (float percentage) {
if (tapped) {
panel.tappedAngle = CardPanel.TAPPED_ANGLE * percentage;
// reverse movement if untapping
if (!panel.isTapped()) panel.tappedAngle = CardPanel.TAPPED_ANGLE - panel.tappedAngle;
}
if (flipped) {
panel.flippedAngle = CardPanel.FLIPPED_ANGLE * percentage;
if (!panel.isFlipped()) panel.flippedAngle = CardPanel.FLIPPED_ANGLE - panel.flippedAngle;
}
panel.repaint();
}
protected void end () {
if (tapped) panel.tappedAngle = panel.isTapped() ? CardPanel.TAPPED_ANGLE : 0;
if (flipped) panel.flippedAngle = panel.isFlipped() ? CardPanel.FLIPPED_ANGLE : 0;
parent.onEndAnimation();
parent.repaint();
}
};
}
protected void end () {
if (tapped) panel.tappedAngle = panel.isTapped() ? CardPanel.TAPPED_ANGLE : 0;
if (flipped) panel.flippedAngle = panel.isFlipped() ? CardPanel.FLIPPED_ANGLE : 0;
parent.onEndAnimation();
parent.repaint();
}
};
}
public static void transformCard (final CardPanel panel, final MagePermanent parent, final boolean transformed) {
public static void transformCard (final CardPanel panel, final MagePermanent parent, final boolean transformed) {
new Animation(1200) {
boolean state = false;
new Animation(1200) {
boolean state = false;
protected void start () {
parent.onBeginAnimation();
}
protected void start () {
parent.onBeginAnimation();
}
protected void update (float percentage) {
double p = percentage * 2;
if (percentage > 0.5) {
if (!state) {
parent.toggleTransformed();
}
state = true;
p = (p - 0.5) * 2;
}
if (!state) {
panel.transformAngle = Math.max(0.01, 1 - p);
} else {
panel.transformAngle = Math.max(0.01, p - 1);
}
panel.repaint();
}
protected void update (float percentage) {
double p = percentage * 2;
if (percentage > 0.5) {
if (!state) {
parent.toggleTransformed();
}
state = true;
p = (p - 0.5) * 2;
}
if (!state) {
panel.transformAngle = Math.max(0.01, 1 - p);
} else {
panel.transformAngle = Math.max(0.01, p - 1);
}
panel.repaint();
}
protected void end () {
parent.onEndAnimation();
parent.repaint();
}
};
}
protected void end () {
parent.onEndAnimation();
parent.repaint();
}
};
}
// static public void moveCardToPlay (Component source, final CardPanel dest, final CardPanel animationPanel) {
static public void moveCardToPlay (final int startX, final int startY, final int startWidth, final int endX, final int endY,
final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane,
final int speed) {
UI.invokeLater(new Runnable() {
public void run () {
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
final float a = 2f;
final float sqrta = (float)Math.sqrt(1 / a);
// static public void moveCardToPlay (Component source, final CardPanel dest, final CardPanel animationPanel) {
static public void moveCardToPlay (final int startX, final int startY, final int startWidth, final int endX, final int endY,
final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane,
final int speed) {
UI.invokeLater(new Runnable() {
public void run () {
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
final float a = 2f;
final float sqrta = (float)Math.sqrt(1 / a);
animationPanel.setCardBounds(startX, startY, startWidth, startHeight);
animationPanel.setAnimationPanel(true);
Container parent = animationPanel.getParent();
if (parent != layeredPane) {
layeredPane.add(animationPanel);
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
}
animationPanel.setCardBounds(startX, startY, startWidth, startHeight);
animationPanel.setAnimationPanel(true);
Container parent = animationPanel.getParent();
if (parent != layeredPane) {
layeredPane.add(animationPanel);
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
}
new Animation(700) {
protected void update (float percentage) {
if (placeholder != null && !placeholder.isShowing()) {
cancel();
return;
}
int currentX = startX + Math.round((endX - startX + endWidth / 2f) * percentage);
int currentY = startY + Math.round((endY - startY + endHeight / 2f) * percentage);
int currentWidth, currentHeight;
int midWidth = Math.max(200, endWidth * 2);
int midHeight = Math.round(midWidth * CardPanel.ASPECT_RATIO);
if (percentage <= 0.5f) {
percentage = percentage * 2;
float pp = sqrta * (1 - percentage);
percentage = 1 - a * pp * pp;
currentWidth = startWidth + Math.round((midWidth - startWidth) * percentage);
currentHeight = startHeight + Math.round((midHeight - startHeight) * percentage);
} else {
percentage = (percentage - 0.5f) * 2;
float pp = sqrta * percentage;
percentage = a * pp * pp;
currentWidth = midWidth + Math.round((endWidth - midWidth) * percentage);
currentHeight = midHeight + Math.round((endHeight - midHeight) * percentage);
}
currentX -= Math.round(currentWidth / 2);
currentY -= Math.round(currentHeight / 2);
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
new Animation(700) {
protected void update (float percentage) {
if (placeholder != null && !placeholder.isShowing()) {
cancel();
return;
}
int currentX = startX + Math.round((endX - startX + endWidth / 2f) * percentage);
int currentY = startY + Math.round((endY - startY + endHeight / 2f) * percentage);
int currentWidth, currentHeight;
int midWidth = Math.max(200, endWidth * 2);
int midHeight = Math.round(midWidth * CardPanel.ASPECT_RATIO);
if (percentage <= 0.5f) {
percentage = percentage * 2;
float pp = sqrta * (1 - percentage);
percentage = 1 - a * pp * pp;
currentWidth = startWidth + Math.round((midWidth - startWidth) * percentage);
currentHeight = startHeight + Math.round((midHeight - startHeight) * percentage);
} else {
percentage = (percentage - 0.5f) * 2;
float pp = sqrta * percentage;
percentage = a * pp * pp;
currentWidth = midWidth + Math.round((endWidth - midWidth) * percentage);
currentHeight = midHeight + Math.round((endHeight - midHeight) * percentage);
}
currentX -= Math.round(currentWidth / 2);
currentY -= Math.round(currentHeight / 2);
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
protected void end () {
EventQueue.invokeLater(new Runnable() {
public void run () {
if (placeholder != null) {
placeholder.setDisplayEnabled(true);
placeholder.setImage(animationPanel);
}
animationPanel.setVisible(false);
animationPanel.repaint();
layeredPane.remove(animationPanel);
}
});
}
};
}
});
}
protected void end () {
EventQueue.invokeLater(new Runnable() {
public void run () {
if (placeholder != null) {
placeholder.setDisplayEnabled(true);
placeholder.setImage(animationPanel);
}
animationPanel.setVisible(false);
animationPanel.repaint();
layeredPane.remove(animationPanel);
}
});
}
};
}
});
}
static public void moveCard (final int startX, final int startY, final int startWidth, final int endX, final int endY,
final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane,
final int speed) {
UI.invokeLater(new Runnable() {
public void run () {
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
static public void moveCard (final int startX, final int startY, final int startWidth, final int endX, final int endY,
final int endWidth, final CardPanel animationPanel, final CardPanel placeholder, final JLayeredPane layeredPane,
final int speed) {
UI.invokeLater(new Runnable() {
public void run () {
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
animationPanel.setCardBounds(startX, startY, startWidth, startHeight);
animationPanel.setAnimationPanel(true);
Container parent = animationPanel.getParent();
if (parent != layeredPane) {
layeredPane.add(animationPanel);
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
}
animationPanel.setCardBounds(startX, startY, startWidth, startHeight);
animationPanel.setAnimationPanel(true);
Container parent = animationPanel.getParent();
if (parent != layeredPane) {
layeredPane.add(animationPanel);
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
}
new Animation(speed) {
protected void update (float percentage) {
int currentX = startX + Math.round((endX - startX) * percentage);
int currentY = startY + Math.round((endY - startY) * percentage);
int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage);
int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage);
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
new Animation(speed) {
protected void update (float percentage) {
int currentX = startX + Math.round((endX - startX) * percentage);
int currentY = startY + Math.round((endY - startY) * percentage);
int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage);
int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage);
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
protected void end () {
EventQueue.invokeLater(new Runnable() {
public void run () {
if (placeholder != null) {
placeholder.setDisplayEnabled(true);
placeholder.setImage(animationPanel);
}
animationPanel.setVisible(false);
animationPanel.repaint();
layeredPane.remove(animationPanel);
}
});
}
};
}
});
}
protected void end () {
EventQueue.invokeLater(new Runnable() {
public void run () {
if (placeholder != null) {
placeholder.setDisplayEnabled(true);
placeholder.setImage(animationPanel);
}
animationPanel.setVisible(false);
animationPanel.repaint();
layeredPane.remove(animationPanel);
}
});
}
};
}
});
}
static public void shrinkCard () {
CardPanel enlargedCardPanel, enlargedAnimationPanel;
synchronized (enlargeLock) {
//delayedCardPanel = null;
//delayedTime = 0;
enlargedCardPanel = Animation.enlargedCardPanel;
enlargedAnimationPanel = Animation.enlargedAnimationPanel;
if (enlargedAnimationPanel == null) return;
Animation.enlargedCardPanel = null;
Animation.enlargedAnimationPanel = null;
}
static public void shrinkCard () {
CardPanel enlargedCardPanel, enlargedAnimationPanel;
synchronized (enlargeLock) {
//delayedCardPanel = null;
//delayedTime = 0;
enlargedCardPanel = Animation.enlargedCardPanel;
enlargedAnimationPanel = Animation.enlargedAnimationPanel;
if (enlargedAnimationPanel == null) return;
Animation.enlargedCardPanel = null;
Animation.enlargedAnimationPanel = null;
}
final CardPanel overPanel = enlargedCardPanel, animationPanel = enlargedAnimationPanel;
final CardPanel overPanel = enlargedCardPanel, animationPanel = enlargedAnimationPanel;
animationPanel.setAnimationPanel(true);
final JLayeredPane layeredPane = SwingUtilities.getRootPane(overPanel).getLayeredPane();
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
animationPanel.setAnimationPanel(true);
final JLayeredPane layeredPane = SwingUtilities.getRootPane(overPanel).getLayeredPane();
layeredPane.setLayer(animationPanel, JLayeredPane.MODAL_LAYER);
final int startWidth = animationPanel.getCardWidth();
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endWidth = overPanel.getCardWidth();
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
final int startWidth = animationPanel.getCardWidth();
final int startHeight = Math.round(startWidth * CardPanel.ASPECT_RATIO);
final int endWidth = overPanel.getCardWidth();
final int endHeight = Math.round(endWidth * CardPanel.ASPECT_RATIO);
new Animation(200) {
protected void update (float percentage) {
int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage);
int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage);
Point startPos = SwingUtilities.convertPoint(overPanel.getParent(), overPanel.getCardLocation(), layeredPane);
int centerX = startPos.x + Math.round(endWidth / 2f);
int centerY = startPos.y + Math.round(endHeight / 2f);
int currentX = Math.max(0, centerX - Math.round(currentWidth / 2f));
currentX = Math.min(currentX, layeredPane.getWidth() - currentWidth);
int currentY = Math.max(0, centerY - Math.round(currentHeight / 2f));
currentY = Math.min(currentY, layeredPane.getHeight() - currentHeight);
animationPanel.tappedAngle = overPanel.tappedAngle * percentage;
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
new Animation(200) {
protected void update (float percentage) {
int currentWidth = startWidth + Math.round((endWidth - startWidth) * percentage);
int currentHeight = startHeight + Math.round((endHeight - startHeight) * percentage);
Point startPos = SwingUtilities.convertPoint(overPanel.getParent(), overPanel.getCardLocation(), layeredPane);
int centerX = startPos.x + Math.round(endWidth / 2f);
int centerY = startPos.y + Math.round(endHeight / 2f);
int currentX = Math.max(0, centerX - Math.round(currentWidth / 2f));
currentX = Math.min(currentX, layeredPane.getWidth() - currentWidth);
int currentY = Math.max(0, centerY - Math.round(currentHeight / 2f));
currentY = Math.min(currentY, layeredPane.getHeight() - currentHeight);
animationPanel.tappedAngle = overPanel.tappedAngle * percentage;
animationPanel.setCardBounds(currentX, currentY, currentWidth, currentHeight);
}
protected void end () {
animationPanel.setVisible(false);
animationPanel.repaint();
EventQueue.invokeLater(new Runnable() {
public void run () {
layeredPane.remove(animationPanel);
}
});
}
};
}
protected void end () {
animationPanel.setVisible(false);
animationPanel.repaint();
EventQueue.invokeLater(new Runnable() {
public void run () {
layeredPane.remove(animationPanel);
}
});
}
};
}
static public boolean isShowingEnlargedCard () {
synchronized (enlargeLock) {
return enlargedAnimationPanel != null;
}
}
static public void showCard(final MagePermanent card, int count) {
if (count == 0) {
static public boolean isShowingEnlargedCard () {
synchronized (enlargeLock) {
return enlargedAnimationPanel != null;
}
}
static public void showCard(final MagePermanent card, int count) {
if (count == 0) {
count = 1;
}
new Animation(600 / count) {
protected void start () {
}
protected void start () {
}
protected void update (float percentage) {
float alpha = percentage;
card.setAlpha(alpha);
card.repaint();
}
protected void update (float percentage) {
float alpha = percentage;
card.setAlpha(alpha);
card.repaint();
}
protected void end () {
card.setAlpha(1.f);
}
};
}
static public void hideCard(final MagePermanent card, int count) {
if (count == 0) {
protected void end () {
card.setAlpha(1.f);
}
};
}
static public void hideCard(final MagePermanent card, int count) {
if (count == 0) {
count = 1;
}
new Animation(600 / count) {
protected void start () {
}
protected void start () {
}
protected void update (float percentage) {
float alpha = 1 - percentage;
card.setAlpha(alpha);
card.repaint();
}
protected void update (float percentage) {
float alpha = 1 - percentage;
card.setAlpha(alpha);
card.repaint();
}
protected void end () {
protected void end () {
card.setAlpha(0f);
}
};
}
}
};
}
}

File diff suppressed because it is too large Load diff

View file

@ -18,85 +18,85 @@ import java.util.Locale;
import javax.swing.JLabel;
public class GlowText extends JLabel {
private static final long serialVersionUID = 1827677946939348001L;
private int glowSize;
@SuppressWarnings("unused")
private float glowIntensity;
private Color glowColor;
private boolean wrap;
private int lineCount = 0;
private static final long serialVersionUID = 1827677946939348001L;
private int glowSize;
@SuppressWarnings("unused")
private float glowIntensity;
private Color glowColor;
private boolean wrap;
private int lineCount = 0;
public void setGlow (Color glowColor, int size, float intensity) {
this.glowColor = glowColor;
this.glowSize = size;
this.glowIntensity = intensity;
}
public void setGlow (Color glowColor, int size, float intensity) {
this.glowColor = glowColor;
this.glowSize = size;
this.glowIntensity = intensity;
}
public void setWrap (boolean wrap) {
this.wrap = wrap;
}
public void setWrap (boolean wrap) {
this.wrap = wrap;
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width += glowSize;
size.height += glowSize / 2;
return size;
}
public Dimension getPreferredSize () {
Dimension size = super.getPreferredSize();
size.width += glowSize;
size.height += glowSize / 2;
return size;
}
public void setText (String text) {
super.setText(text);
}
public void setText (String text) {
super.setText(text);
}
public void paint (Graphics g) {
if (getText().length() == 0) return;
public void paint (Graphics g) {
if (getText().length() == 0) return;
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Dimension size = getSize();
int textX = 0, textY = 0;
int wrapWidth = Math.max(0, wrap ? size.width - glowSize : Integer.MAX_VALUE);
Dimension size = getSize();
int textX = 0, textY = 0;
int wrapWidth = Math.max(0, wrap ? size.width - glowSize : Integer.MAX_VALUE);
AttributedString attributedString = new AttributedString(getText());
attributedString.addAttribute(TextAttribute.FONT, getFont());
AttributedCharacterIterator charIterator = attributedString.getIterator();
FontRenderContext fontContext = g2d.getFontRenderContext();
AttributedString attributedString = new AttributedString(getText());
attributedString.addAttribute(TextAttribute.FONT, getFont());
AttributedCharacterIterator charIterator = attributedString.getIterator();
FontRenderContext fontContext = g2d.getFontRenderContext();
LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, BreakIterator.getWordInstance(Locale.ENGLISH), fontContext);
lineCount = 0;
while (measurer.getPosition() < charIterator.getEndIndex()) {
//TextLayout textLayout = measurer.nextLayout(wrapWidth);
lineCount++;
if (lineCount > 2) break;
}
charIterator.first();
// Use char wrap if word wrap would cause more than two lines of text.
if (lineCount > 2)
measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH), fontContext);
else
measurer.setPosition(0);
while (measurer.getPosition() < charIterator.getEndIndex()) {
TextLayout textLayout = measurer.nextLayout(wrapWidth);
float ascent = textLayout.getAscent();
textY += ascent; // Move down to baseline.
LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, BreakIterator.getWordInstance(Locale.ENGLISH), fontContext);
lineCount = 0;
while (measurer.getPosition() < charIterator.getEndIndex()) {
//TextLayout textLayout = measurer.nextLayout(wrapWidth);
lineCount++;
if (lineCount > 2) break;
}
charIterator.first();
// Use char wrap if word wrap would cause more than two lines of text.
if (lineCount > 2)
measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH), fontContext);
else
measurer.setPosition(0);
while (measurer.getPosition() < charIterator.getEndIndex()) {
TextLayout textLayout = measurer.nextLayout(wrapWidth);
float ascent = textLayout.getAscent();
textY += ascent; // Move down to baseline.
g2d.setColor(glowColor);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
textLayout.draw(g2d, textX + glowSize / 2 + 1, textY + glowSize / 2 - 1);
textLayout.draw(g2d, textX + glowSize / 2 + 1, textY + glowSize / 2 + 1);
textLayout.draw(g2d, textX + glowSize / 2 - 1, textY + glowSize / 2 - 1);
textLayout.draw(g2d, textX + glowSize / 2 - 1, textY + glowSize / 2 + 1);
g2d.setColor(glowColor);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
textLayout.draw(g2d, textX + glowSize / 2 + 1, textY + glowSize / 2 - 1);
textLayout.draw(g2d, textX + glowSize / 2 + 1, textY + glowSize / 2 + 1);
textLayout.draw(g2d, textX + glowSize / 2 - 1, textY + glowSize / 2 - 1);
textLayout.draw(g2d, textX + glowSize / 2 - 1, textY + glowSize / 2 + 1);
g2d.setColor(getForeground());
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
textLayout.draw(g2d, textX + glowSize / 2, textY + glowSize / 2);
g2d.setColor(getForeground());
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
textLayout.draw(g2d, textX + glowSize / 2, textY + glowSize / 2);
textY += textLayout.getDescent() + textLayout.getLeading(); // Move down to top of next line.
}
}
public int getLineCount() {
return this.lineCount;
}
textY += textLayout.getDescent() + textLayout.getLeading(); // Move down to top of next line.
}
}
public int getLineCount() {
return this.lineCount;
}
}

View file

@ -105,21 +105,21 @@ public class ManaSymbols {
}
}
File file;
for (String set : CardsStorage.getSetCodes()) {
file = new File(Constants.RESOURCE_PATH_SET_SMALL);
if (!file.exists()) {
break;
}
file = new File(Constants.RESOURCE_PATH_SET_SMALL + set + "-C.png");
try {
Image image = UI.getImageIcon(file.getAbsolutePath()).getImage();
int width = image.getWidth(null);
int height = image.getHeight(null);
setImagesExist.put(set, new Dimension(width, height));
} catch (Exception e) {
}
}
File file;
for (String set : CardsStorage.getSetCodes()) {
file = new File(Constants.RESOURCE_PATH_SET_SMALL);
if (!file.exists()) {
break;
}
file = new File(Constants.RESOURCE_PATH_SET_SMALL + set + "-C.png");
try {
Image image = UI.getImageIcon(file.getAbsolutePath()).getImage();
int width = image.getWidth(null);
int height = image.getHeight(null);
setImagesExist.put(set, new Dimension(width, height));
} catch (Exception e) {
}
}
}
static public Image getManaSymbolImage(String symbol) {
@ -164,23 +164,23 @@ public class ManaSymbols {
return width;
}
public enum Type {
CARD,
TOOLTIP,
PAY
}
public enum Type {
CARD,
TOOLTIP,
PAY
}
static public synchronized String replaceSymbolsWithHTML(String value, Type type) {
if (type.equals(Type.TOOLTIP)) {
return replaceSymbolsPattern.matcher(value).replaceAll("<img src='file:plugins/images/symbols/small/$1$2.jpg' alt='$1$2' width=11 height=11>");
} else if (type.equals(Type.CARD)) {
value = value.replace("{slash}", "<img src='file:plugins/images/symbols/medium/slash.jpg' alt='slash' width=10 height=13>");
value = value.replace("{slash}", "<img src='file:plugins/images/symbols/medium/slash.jpg' alt='slash' width=10 height=13>");
return replaceSymbolsPattern.matcher(value).replaceAll("<img src='file:plugins/images/symbols/medium/$1$2.jpg' alt='$1$2' width=12 height=12>");
} else if (type.equals(Type.PAY)) {
value = value.replace("{slash}", "<img src='file:plugins/images/symbols/medium/slash.jpg' alt='slash' width=10 height=13>");
value = value.replace("{slash}", "<img src='file:plugins/images/symbols/medium/slash.jpg' alt='slash' width=10 height=13>");
return replaceSymbolsPattern.matcher(value).replaceAll("<img src='file:plugins/images/symbols/medium/$1$2.jpg' alt='$1$2' width=15 height=15>");
}
return value;
return value;
}
static public String replaceSetCodeWithHTML(String set, String rarity) {

View file

@ -9,188 +9,188 @@ import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ScaledImagePanel extends JPanel {
private static final long serialVersionUID = -1523279873208605664L;
public volatile Image srcImage;
//public volatile Image srcImageBlurred;
private static final long serialVersionUID = -1523279873208605664L;
public volatile Image srcImage;
//public volatile Image srcImageBlurred;
private ScalingType scalingType = ScalingType.bilinear;
private boolean scaleLarger;
private MultipassType multiPassType = MultipassType.bilinear;
private boolean blur;
private ScalingType scalingType = ScalingType.bilinear;
private boolean scaleLarger;
private MultipassType multiPassType = MultipassType.bilinear;
private boolean blur;
public ScaledImagePanel () {
super(false);
setOpaque(false);
}
public ScaledImagePanel () {
super(false);
setOpaque(false);
}
public void setImage(Image srcImage) {
this.srcImage = srcImage;
}
this.srcImage = srcImage;
}
public void clearImage () {
srcImage = null;
repaint();
}
public void clearImage () {
srcImage = null;
repaint();
}
public void setScalingMultiPassType (MultipassType multiPassType) {
this.multiPassType = multiPassType;
}
public void setScalingMultiPassType (MultipassType multiPassType) {
this.multiPassType = multiPassType;
}
public void setScalingType (ScalingType scalingType) {
this.scalingType = scalingType;
}
public void setScalingType (ScalingType scalingType) {
this.scalingType = scalingType;
}
public void setScalingBlur (boolean blur) {
this.blur = blur;
}
public void setScalingBlur (boolean blur) {
this.blur = blur;
}
public void setScaleLarger (boolean scaleLarger) {
this.scaleLarger = scaleLarger;
}
public void setScaleLarger (boolean scaleLarger) {
this.scaleLarger = scaleLarger;
}
public boolean hasImage () {
return srcImage != null;
}
public boolean hasImage () {
return srcImage != null;
}
private ScalingInfo getScalingInfo () {
int panelWidth = getWidth();
int panelHeight = getHeight();
int srcWidth = srcImage.getWidth(null);
int srcHeight = srcImage.getHeight(null);
int targetWidth = srcWidth;
int targetHeight = srcHeight;
if (scaleLarger || srcWidth > panelWidth || srcHeight > panelHeight) {
targetWidth = Math.round(panelHeight * (srcWidth / (float)srcHeight));
if (targetWidth > panelWidth) {
targetHeight = Math.round(panelWidth * (srcHeight / (float)srcWidth));
targetWidth = panelWidth;
} else
targetHeight = panelHeight;
}
ScalingInfo info = new ScalingInfo();
info.targetWidth = targetWidth;
info.targetHeight = targetHeight;
info.srcWidth = srcWidth;
info.srcHeight = srcHeight;
info.x = panelWidth / 2 - targetWidth / 2;
info.y = panelHeight / 2 - targetHeight / 2;
return info;
}
private ScalingInfo getScalingInfo () {
int panelWidth = getWidth();
int panelHeight = getHeight();
int srcWidth = srcImage.getWidth(null);
int srcHeight = srcImage.getHeight(null);
int targetWidth = srcWidth;
int targetHeight = srcHeight;
if (scaleLarger || srcWidth > panelWidth || srcHeight > panelHeight) {
targetWidth = Math.round(panelHeight * (srcWidth / (float)srcHeight));
if (targetWidth > panelWidth) {
targetHeight = Math.round(panelWidth * (srcHeight / (float)srcWidth));
targetWidth = panelWidth;
} else
targetHeight = panelHeight;
}
ScalingInfo info = new ScalingInfo();
info.targetWidth = targetWidth;
info.targetHeight = targetHeight;
info.srcWidth = srcWidth;
info.srcHeight = srcHeight;
info.x = panelWidth / 2 - targetWidth / 2;
info.y = panelHeight / 2 - targetHeight / 2;
return info;
}
public void paint (Graphics g) {
if (srcImage == null) return;
public void paint (Graphics g) {
if (srcImage == null) return;
Graphics2D g2 = (Graphics2D)g.create();
ScalingInfo info = getScalingInfo();
Graphics2D g2 = (Graphics2D)g.create();
ScalingInfo info = getScalingInfo();
switch (scalingType) {
case nearestNeighbor:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
break;
case bilinear:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
break;
case bicubic:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
break;
case areaAveraging:
scaleWithGetScaledInstance(g2, info, Image.SCALE_AREA_AVERAGING);
break;
case replicate:
scaleWithGetScaledInstance(g2, info, Image.SCALE_REPLICATE);
break;
}
}
switch (scalingType) {
case nearestNeighbor:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
break;
case bilinear:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
break;
case bicubic:
scaleWithDrawImage(g2, info, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
break;
case areaAveraging:
scaleWithGetScaledInstance(g2, info, Image.SCALE_AREA_AVERAGING);
break;
case replicate:
scaleWithGetScaledInstance(g2, info, Image.SCALE_REPLICATE);
break;
}
}
private void scaleWithGetScaledInstance (Graphics2D g2, ScalingInfo info, int hints) {
Image srcImage = getSourceImage(info);
Image scaledImage = srcImage.getScaledInstance(info.targetWidth, info.targetHeight, hints);
g2.drawImage(scaledImage, info.x, info.y, null);
}
private void scaleWithGetScaledInstance (Graphics2D g2, ScalingInfo info, int hints) {
Image srcImage = getSourceImage(info);
Image scaledImage = srcImage.getScaledInstance(info.targetWidth, info.targetHeight, hints);
g2.drawImage(scaledImage, info.x, info.y, null);
}
private void scaleWithDrawImage (Graphics2D g2, ScalingInfo info, Object hint) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
private void scaleWithDrawImage (Graphics2D g2, ScalingInfo info, Object hint) {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
int tempDestWidth = info.srcWidth / 2, tempDestHeight = info.srcHeight / 2;
if (tempDestWidth < info.targetWidth) tempDestWidth = info.targetWidth;
if (tempDestHeight < info.targetHeight) tempDestHeight = info.targetHeight;
int tempDestWidth = info.srcWidth / 2, tempDestHeight = info.srcHeight / 2;
if (tempDestWidth < info.targetWidth) tempDestWidth = info.targetWidth;
if (tempDestHeight < info.targetHeight) tempDestHeight = info.targetHeight;
Image srcImage = getSourceImage(info);
Image srcImage = getSourceImage(info);
// If not doing multipass or multipass only needs a single pass, just scale it once directly to the panel surface.
if (multiPassType == MultipassType.none || (tempDestWidth == info.targetWidth && tempDestHeight == info.targetHeight)) {
g2.drawImage(srcImage, info.x, info.y, info.targetWidth, info.targetHeight, null);
return;
}
// If not doing multipass or multipass only needs a single pass, just scale it once directly to the panel surface.
if (multiPassType == MultipassType.none || (tempDestWidth == info.targetWidth && tempDestHeight == info.targetHeight)) {
g2.drawImage(srcImage, info.x, info.y, info.targetWidth, info.targetHeight, null);
return;
}
BufferedImage tempImage = new BufferedImage(tempDestWidth, tempDestHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2temp = tempImage.createGraphics();
switch (multiPassType) {
case nearestNeighbor:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
break;
case bilinear:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
break;
case bicubic:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
break;
}
// Render first pass from image to temp.
g2temp.drawImage(srcImage, 0, 0, tempDestWidth, tempDestHeight, null);
// Render passes between the first and last pass.
int tempSrcWidth = tempDestWidth;
int tempSrcHeight = tempDestHeight;
while (true) {
if (tempDestWidth > info.targetWidth) {
tempDestWidth = tempDestWidth / 2;
if (tempDestWidth < info.targetWidth) tempDestWidth = info.targetWidth;
}
BufferedImage tempImage = new BufferedImage(tempDestWidth, tempDestHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2temp = tempImage.createGraphics();
switch (multiPassType) {
case nearestNeighbor:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
break;
case bilinear:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
break;
case bicubic:
g2temp.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
break;
}
// Render first pass from image to temp.
g2temp.drawImage(srcImage, 0, 0, tempDestWidth, tempDestHeight, null);
// Render passes between the first and last pass.
int tempSrcWidth = tempDestWidth;
int tempSrcHeight = tempDestHeight;
while (true) {
if (tempDestWidth > info.targetWidth) {
tempDestWidth = tempDestWidth / 2;
if (tempDestWidth < info.targetWidth) tempDestWidth = info.targetWidth;
}
if (tempDestHeight > info.targetHeight) {
tempDestHeight = tempDestHeight / 2;
if (tempDestHeight < info.targetHeight) tempDestHeight = info.targetHeight;
}
if (tempDestHeight > info.targetHeight) {
tempDestHeight = tempDestHeight / 2;
if (tempDestHeight < info.targetHeight) tempDestHeight = info.targetHeight;
}
if (tempDestWidth == info.targetWidth && tempDestHeight == info.targetHeight) break;
if (tempDestWidth == info.targetWidth && tempDestHeight == info.targetHeight) break;
g2temp.drawImage(tempImage, 0, 0, tempDestWidth, tempDestHeight, 0, 0, tempSrcWidth, tempSrcHeight, null);
g2temp.drawImage(tempImage, 0, 0, tempDestWidth, tempDestHeight, 0, 0, tempSrcWidth, tempSrcHeight, null);
tempSrcWidth = tempDestWidth;
tempSrcHeight = tempDestHeight;
}
g2temp.dispose();
// Render last pass from temp to panel surface.
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(tempImage, info.x, info.y, info.x + info.targetWidth, info.y + info.targetHeight, 0, 0, tempSrcWidth,
tempSrcHeight, null);
}
tempSrcWidth = tempDestWidth;
tempSrcHeight = tempDestHeight;
}
g2temp.dispose();
// Render last pass from temp to panel surface.
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(tempImage, info.x, info.y, info.x + info.targetWidth, info.y + info.targetHeight, 0, 0, tempSrcWidth,
tempSrcHeight, null);
}
private Image getSourceImage (ScalingInfo info) {
private Image getSourceImage (ScalingInfo info) {
return srcImage;
//if (!blur || srcImageBlurred == null) return srcImage;
//if (info.srcWidth / 2 < info.targetWidth || info.srcHeight / 2 < info.targetHeight) return srcImage;
//if (!blur || srcImageBlurred == null) return srcImage;
//if (info.srcWidth / 2 < info.targetWidth || info.srcHeight / 2 < info.targetHeight) return srcImage;
//return srcImageBlurred;
}
public Image getSrcImage() {
return srcImage;
}
}
static private class ScalingInfo {
public int targetWidth;
public int targetHeight;
public int srcWidth;
public int srcHeight;
public int x;
public int y;
}
public Image getSrcImage() {
return srcImage;
}
static public enum MultipassType {
none, nearestNeighbor, bilinear, bicubic
}
static private class ScalingInfo {
public int targetWidth;
public int targetHeight;
public int srcWidth;
public int srcHeight;
public int x;
public int y;
}
static public enum ScalingType {
nearestNeighbor, replicate, bilinear, bicubic, areaAveraging
}
static public enum MultipassType {
none, nearestNeighbor, bilinear, bicubic
}
static public enum ScalingType {
nearestNeighbor, replicate, bilinear, bicubic, areaAveraging
}
}

View file

@ -44,139 +44,139 @@ import javax.swing.text.html.ImageView;
* UI utility functions.
*/
public class UI {
static private Hashtable<URL, Image> imageCache = new Hashtable<URL, Image>();
static private Hashtable<URL, Image> imageCache = new Hashtable<URL, Image>();
static public JToggleButton getToggleButton () {
JToggleButton button = new JToggleButton();
button.setMargin(new Insets(2, 4, 2, 4));
return button;
}
static public JToggleButton getToggleButton () {
JToggleButton button = new JToggleButton();
button.setMargin(new Insets(2, 4, 2, 4));
return button;
}
static public JButton getButton () {
JButton button = new JButton();
button.setMargin(new Insets(2, 4, 2, 4));
return button;
}
static public JButton getButton () {
JButton button = new JButton();
button.setMargin(new Insets(2, 4, 2, 4));
return button;
}
static public void setTitle (JPanel panel, String title) {
Border border = panel.getBorder();
if (border instanceof TitledBorder) {
((TitledBorder)panel.getBorder()).setTitle(title);
panel.repaint();
} else
panel.setBorder(BorderFactory.createTitledBorder(title));
}
static public void setTitle (JPanel panel, String title) {
Border border = panel.getBorder();
if (border instanceof TitledBorder) {
((TitledBorder)panel.getBorder()).setTitle(title);
panel.repaint();
} else
panel.setBorder(BorderFactory.createTitledBorder(title));
}
@SuppressWarnings("deprecation")
static public URL getFileURL (String path) {
File file = new File(path);
if (file.exists()) {
try {
return file.toURL();
} catch (MalformedURLException ignored) {
}
}
return UI.class.getResource(path);
}
@SuppressWarnings("deprecation")
static public URL getFileURL (String path) {
File file = new File(path);
if (file.exists()) {
try {
return file.toURL();
} catch (MalformedURLException ignored) {
}
}
return UI.class.getResource(path);
}
static public ImageIcon getImageIcon (String path) {
try {
InputStream stream;
stream = UI.class.getResourceAsStream(path);
if (stream == null && new File(path).exists()) stream = new FileInputStream(path);
if (stream == null) throw new RuntimeException("Image not found: " + path);
byte[] data = new byte[stream.available()];
stream.read(data);
return new ImageIcon(data);
} catch (IOException ex) {
throw new RuntimeException("Error reading image: " + path);
}
}
static public ImageIcon getImageIcon (String path) {
try {
InputStream stream;
stream = UI.class.getResourceAsStream(path);
if (stream == null && new File(path).exists()) stream = new FileInputStream(path);
if (stream == null) throw new RuntimeException("Image not found: " + path);
byte[] data = new byte[stream.available()];
stream.read(data);
return new ImageIcon(data);
} catch (IOException ex) {
throw new RuntimeException("Error reading image: " + path);
}
}
static public void setHTMLEditorKit (JEditorPane editorPane) {
editorPane.getDocument().putProperty("imageCache", imageCache); // Read internally by ImageView, but never written.
// Extend all this shit to cache images.
editorPane.setEditorKit(new HTMLEditorKit() {
private static final long serialVersionUID = -54602188235105448L;
static public void setHTMLEditorKit (JEditorPane editorPane) {
editorPane.getDocument().putProperty("imageCache", imageCache); // Read internally by ImageView, but never written.
// Extend all this shit to cache images.
editorPane.setEditorKit(new HTMLEditorKit() {
private static final long serialVersionUID = -54602188235105448L;
public ViewFactory getViewFactory () {
return new HTMLFactory() {
public View create (Element elem) {
Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag)o;
if (kind == HTML.Tag.IMG) return new ImageView(elem) {
public URL getImageURL () {
URL url = super.getImageURL();
// Put an image into the cache to be read by other ImageView methods.
if (url != null && imageCache.get(url) == null)
imageCache.put(url, Toolkit.getDefaultToolkit().createImage(url));
return url;
}
};
}
return super.create(elem);
}
};
}
});
}
public ViewFactory getViewFactory () {
return new HTMLFactory() {
public View create (Element elem) {
Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag)o;
if (kind == HTML.Tag.IMG) return new ImageView(elem) {
public URL getImageURL () {
URL url = super.getImageURL();
// Put an image into the cache to be read by other ImageView methods.
if (url != null && imageCache.get(url) == null)
imageCache.put(url, Toolkit.getDefaultToolkit().createImage(url));
return url;
}
};
}
return super.create(elem);
}
};
}
});
}
static public void setVerticalScrollingView (JScrollPane scrollPane, final Component view) {
final JViewport viewport = new JViewport();
viewport.setLayout(new ViewportLayout() {
private static final long serialVersionUID = 7701568740313788935L;
public void layoutContainer (Container parent) {
viewport.setViewPosition(new Point(0, 0));
Dimension viewportSize = viewport.getSize();
int width = viewportSize.width;
int height = Math.max(view.getPreferredSize().height, viewportSize.height);
viewport.setViewSize(new Dimension(width, height));
}
});
viewport.setView(view);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewport(viewport);
}
static public void setVerticalScrollingView (JScrollPane scrollPane, final Component view) {
final JViewport viewport = new JViewport();
viewport.setLayout(new ViewportLayout() {
private static final long serialVersionUID = 7701568740313788935L;
public void layoutContainer (Container parent) {
viewport.setViewPosition(new Point(0, 0));
Dimension viewportSize = viewport.getSize();
int width = viewportSize.width;
int height = Math.max(view.getPreferredSize().height, viewportSize.height);
viewport.setViewSize(new Dimension(width, height));
}
});
viewport.setView(view);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewport(viewport);
}
static public String getDisplayManaCost (String manaCost) {
manaCost = manaCost.replace("/", "");
// A pipe in the cost means "process left of the pipe as the card color, but display right of the pipe as the cost".
int pipePosition = manaCost.indexOf("{|}");
if (pipePosition != -1) manaCost = manaCost.substring(pipePosition + 3);
return manaCost;
}
static public String getDisplayManaCost (String manaCost) {
manaCost = manaCost.replace("/", "");
// A pipe in the cost means "process left of the pipe as the card color, but display right of the pipe as the cost".
int pipePosition = manaCost.indexOf("{|}");
if (pipePosition != -1) manaCost = manaCost.substring(pipePosition + 3);
return manaCost;
}
static public void invokeLater (Runnable runnable) {
EventQueue.invokeLater(runnable);
}
static public void invokeLater (Runnable runnable) {
EventQueue.invokeLater(runnable);
}
static public void invokeAndWait (Runnable runnable) {
if (EventQueue.isDispatchThread()) {
runnable.run();
return;
}
try {
EventQueue.invokeAndWait(runnable);
} catch (InterruptedException ex) {
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
static public void invokeAndWait (Runnable runnable) {
if (EventQueue.isDispatchThread()) {
runnable.run();
return;
}
try {
EventQueue.invokeAndWait(runnable);
} catch (InterruptedException ex) {
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
static public void setSystemLookAndFeel () {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
System.err.println("Error setting look and feel:");
ex.printStackTrace();
}
}
static public void setSystemLookAndFeel () {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
System.err.println("Error setting look and feel:");
ex.printStackTrace();
}
}
static public void setDefaultFont (Font font) {
for (Object key : Collections.list(UIManager.getDefaults().keys())) {
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource) UIManager.put(key, font);
}
}
static public void setDefaultFont (Font font) {
for (Object key : Collections.list(UIManager.getDefaults().keys())) {
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource) UIManager.put(key, font);
}
}
}

View file

@ -18,83 +18,83 @@ import javax.swing.SwingUtilities;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Util {
static public final boolean isMac = System.getProperty("os.name").toLowerCase().indexOf("mac") != -1;
static public final boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") == -1;
static public final boolean isMac = System.getProperty("os.name").toLowerCase().indexOf("mac") != -1;
static public final boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") == -1;
static public Robot robot;
static {
try {
new Robot();
} catch (AWTException ex) {
throw new RuntimeException("Error creating robot.", ex);
}
}
static public Robot robot;
static {
try {
new Robot();
} catch (AWTException ex) {
throw new RuntimeException("Error creating robot.", ex);
}
}
static public ThreadPoolExecutor threadPool;
static private int threadCount;
static {
threadPool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new ThreadFactory() {
public Thread newThread (Runnable runnable) {
threadCount++;
Thread thread = new Thread(runnable, "Util" + threadCount);
thread.setDaemon(true);
return thread;
}
});
threadPool.prestartAllCoreThreads();
}
static public ThreadPoolExecutor threadPool;
static private int threadCount;
static {
threadPool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new ThreadFactory() {
public Thread newThread (Runnable runnable) {
threadCount++;
Thread thread = new Thread(runnable, "Util" + threadCount);
thread.setDaemon(true);
return thread;
}
});
threadPool.prestartAllCoreThreads();
}
public static void broadcast (byte[] data, int port) throws IOException {
DatagramSocket socket = new DatagramSocket();
broadcast(socket, data, port, NetworkInterface.getNetworkInterfaces());
socket.close();
}
public static void broadcast (byte[] data, int port) throws IOException {
DatagramSocket socket = new DatagramSocket();
broadcast(socket, data, port, NetworkInterface.getNetworkInterfaces());
socket.close();
}
private static void broadcast (DatagramSocket socket, byte[] data, int port, Enumeration<NetworkInterface> ifaces)
throws IOException {
for (NetworkInterface iface : Collections.list(ifaces)) {
for (InetAddress address : Collections.list(iface.getInetAddresses())) {
if (!address.isSiteLocalAddress()) continue;
// Java 1.5 doesn't support getting the subnet mask, so try the two most common.
byte[] ip = address.getAddress();
ip[3] = -1; // 255.255.255.0
socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), port));
ip[2] = -1; // 255.255.0.0
socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), port));
}
}
}
private static void broadcast (DatagramSocket socket, byte[] data, int port, Enumeration<NetworkInterface> ifaces)
throws IOException {
for (NetworkInterface iface : Collections.list(ifaces)) {
for (InetAddress address : Collections.list(iface.getInetAddresses())) {
if (!address.isSiteLocalAddress()) continue;
// Java 1.5 doesn't support getting the subnet mask, so try the two most common.
byte[] ip = address.getAddress();
ip[3] = -1; // 255.255.255.0
socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), port));
ip[2] = -1; // 255.255.0.0
socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), port));
}
}
}
static public void sleep (int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ignored) {
}
}
static public void sleep (int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ignored) {
}
}
static public boolean classExists (String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException ex) {
return false;
}
}
static public boolean classExists (String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException ex) {
return false;
}
}
static public void wait (Object lock) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ex) {
}
}
}
static public void wait (Object lock) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ex) {
}
}
}
public static void invokeAndWait (Runnable runnable) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (Exception ex) {
throw new RuntimeException("Error invoking runnable in UI thread.", ex);
}
}
public static void invokeAndWait (Runnable runnable) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (Exception ex) {
throw new RuntimeException("Error invoking runnable in UI thread.", ex);
}
}
}

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;