remove UI references from CardStorageReader

This commit is contained in:
Maxmtg
2013-11-19 21:53:01 +00:00
parent fd7d0e1d99
commit 6e9a316460
7 changed files with 82 additions and 72 deletions

View File

@@ -18,8 +18,7 @@ import forge.util.storage.IStorage;
import forge.util.storage.StorageBase; import forge.util.storage.StorageBase;
/**
/**
* The class holding game invariants, such as cards, editions, game formats. All that data, which is not supposed to be changed by player * The class holding game invariants, such as cards, editions, game formats. All that data, which is not supposed to be changed by player
* *
* @author Max * @author Max
@@ -39,6 +38,7 @@ public class StaticData {
private static StaticData lastInstance = null; private static StaticData lastInstance = null;
public StaticData(ICardStorageReader reader, String editionFolder, String blockDataFolder) { public StaticData(ICardStorageReader reader, String editionFolder, String blockDataFolder) {
this.editions = new EditionCollection(new CardEdition.Reader(new File(editionFolder))); this.editions = new EditionCollection(new CardEdition.Reader(new File(editionFolder)));
lastInstance = this; lastInstance = this;
@@ -46,22 +46,22 @@ public class StaticData {
final Map<String, CardRules> regularCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER); final Map<String, CardRules> regularCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER);
final Map<String, CardRules> variantsCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER); final Map<String, CardRules> variantsCards = new TreeMap<String, CardRules>(String.CASE_INSENSITIVE_ORDER);
synchronized (CardDb.class) {
List<CardRules> rules = reader.loadCards();
for (CardRules card : rules) {
if (null == card) continue;
final String cardName = card.getName(); List<CardRules> rules = reader.loadCards();
if ( card.isVariant() ) for (CardRules card : rules) {
variantsCards.put(cardName, card); if (null == card) continue;
else
regularCards.put(cardName, card);
}
commonCards = new CardDb(regularCards, editions, false); final String cardName = card.getName();
variantCards = new CardDb(variantsCards, editions, false); if ( card.isVariant() )
variantsCards.put(cardName, card);
else
regularCards.put(cardName, card);
} }
commonCards = new CardDb(regularCards, editions, false);
variantCards = new CardDb(variantsCards, editions, false);
this.formats = new FormatCollection(new GameFormat.Reader(new File(blockDataFolder, "formats.txt"))); this.formats = new FormatCollection(new GameFormat.Reader(new File(blockDataFolder, "formats.txt")));
this.boosters = new StorageBase<SealedProductTemplate>("Boosters", editions.getBoosterGenerator()); this.boosters = new StorageBase<SealedProductTemplate>("Boosters", editions.getBoosterGenerator());

View File

@@ -57,7 +57,7 @@ public class FThreads {
* @param mustBeEDT &emsp; boolean: true = exception if not EDT, false = exception if EDT * @param mustBeEDT &emsp; boolean: true = exception if not EDT, false = exception if EDT
*/ */
public static void assertExecutedByEdt(final boolean mustBeEDT) { public static void assertExecutedByEdt(final boolean mustBeEDT) {
if (isEDT() != mustBeEDT ) { if (isGuiThread() != mustBeEDT ) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace(); StackTraceElement[] trace = Thread.currentThread().getStackTrace();
final String methodName = trace[2].getClassName() + "." + trace[2].getMethodName(); final String methodName = trace[2].getClassName() + "." + trace[2].getMethodName();
String modalOperator = mustBeEDT ? " must be" : " may not be"; String modalOperator = mustBeEDT ? " must be" : " may not be";
@@ -77,7 +77,7 @@ public class FThreads {
* TODO: Write javadoc for this method. * TODO: Write javadoc for this method.
*/ */
public static void invokeInEdtNowOrLater(Runnable proc) { public static void invokeInEdtNowOrLater(Runnable proc) {
if( isEDT() ) if( isGuiThread() )
proc.run(); proc.run();
else else
invokeInEdtLater(proc); invokeInEdtLater(proc);
@@ -119,7 +119,7 @@ public class FThreads {
* TODO: Write javadoc for this method. * TODO: Write javadoc for this method.
* @return * @return
*/ */
public static boolean isEDT() { public static boolean isGuiThread() {
return SwingUtilities.isEventDispatchThread(); return SwingUtilities.isEventDispatchThread();
} }
@@ -138,7 +138,7 @@ public class FThreads {
} }
public static String debugGetCurrThreadId() { public static String debugGetCurrThreadId() {
return isEDT() ? "EDT" : Thread.currentThread().getName(); return isGuiThread() ? "EDT" : Thread.currentThread().getName();
} }
public static String prependThreadId(String message) { public static String prependThreadId(String message) {

View File

@@ -19,6 +19,7 @@ package forge;
import forge.card.cardfactory.CardStorageReader; import forge.card.cardfactory.CardStorageReader;
import forge.control.FControl; import forge.control.FControl;
import forge.gui.toolbox.FProgressBar;
import forge.model.FModel; import forge.model.FModel;
import forge.properties.NewConstants; import forge.properties.NewConstants;
import forge.view.FView; import forge.view.FView;
@@ -27,6 +28,7 @@ import forge.view.FView;
* Provides global/static access to singleton instances. * Provides global/static access to singleton instances.
*/ */
public final class Singletons { public final class Singletons {
private static boolean initialized = false;
private static FModel model = null; private static FModel model = null;
private static FView view = null; private static FView view = null;
private static FControl control = null; private static FControl control = null;
@@ -42,12 +44,37 @@ public final class Singletons {
public static StaticData getMagicDb() { return magicDb; } public static StaticData getMagicDb() { return magicDb; }
public static void initializeOnce(boolean withUi) { public static void initializeOnce(boolean withUi) {
FThreads.assertExecutedByEdt(false);
synchronized (Singletons.class) {
if(initialized)
throw new IllegalStateException("Singletons.initializeOnce really cannot be called again");
initialized = true;
}
if(withUi) if(withUi)
view = FView.SINGLETON_INSTANCE; view = FView.SINGLETON_INSTANCE;
IProgressObserver progressBarBridge = view == null ? IProgressObserver.emptyObserver : new IProgressObserver() {
FProgressBar bar = view.getSplash().getProgressBar();
@Override
public void setOperationName(final String name, final boolean usePercents) {
FThreads.invokeInEdtLater(new Runnable() { @Override public void run() {
bar.setDescription(name);
bar.setPercentMode(usePercents);
} });
}
@Override
public void report(int current, int total) {
if ( total != bar.getMaximum())
bar.setMaximum(total);
bar.setValueThreadSafe(current);
}
};
// Loads all cards (using progress bar). // Loads all cards (using progress bar).
FThreads.assertExecutedByEdt(false); final CardStorageReader reader = new CardStorageReader(NewConstants.CARD_DATA_DIR, true, progressBarBridge);
final CardStorageReader reader = new CardStorageReader(NewConstants.CARD_DATA_DIR, true, withUi ? view.getSplash().getProgressBar() : null);
magicDb = new StaticData(reader, "res/editions", "res/blockdata"); magicDb = new StaticData(reader, "res/editions", "res/blockdata");
model = FModel.getInstance(withUi); model = FModel.getInstance(withUi);

View File

@@ -35,15 +35,12 @@ import java.util.concurrent.Future;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.time.StopWatch; import org.apache.commons.lang.time.StopWatch;
import forge.FThreads; import forge.FThreads;
import forge.ICardStorageReader; import forge.ICardStorageReader;
import forge.IProgressObserver;
import forge.card.CardRules; import forge.card.CardRules;
import forge.error.BugReporter;
import forge.gui.toolbox.FProgressBar;
import forge.util.FileUtil; import forge.util.FileUtil;
/** /**
@@ -62,11 +59,11 @@ public class CardStorageReader implements ICardStorageReader {
/** Default charset when loading from files. */ /** Default charset when loading from files. */
public static final String DEFAULT_CHARSET_NAME = "US-ASCII"; public static final String DEFAULT_CHARSET_NAME = "US-ASCII";
final private boolean useThreadPool = FThreads.isMultiCoreSystem(); private final boolean useThreadPool = FThreads.isMultiCoreSystem();
final private int NUMBER_OF_PARTS = 25; public final static int NUMBER_OF_PARTS = 25;
final private CountDownLatch cdl = new CountDownLatch(NUMBER_OF_PARTS); private final CountDownLatch cdl = new CountDownLatch(NUMBER_OF_PARTS);
final private FProgressBar barProgress; private final IProgressObserver progressObserver;
private transient File cardsfolder; private transient File cardsfolder;
@@ -88,31 +85,28 @@ public class CardStorageReader implements ICardStorageReader {
* if true, attempts to load cards from a zip file, if one * if true, attempts to load cards from a zip file, if one
* exists. * exists.
*/ */
public CardStorageReader(String cardDataDir, final boolean useZip, FProgressBar barProgress) { public CardStorageReader(String cardDataDir, final boolean useZip, IProgressObserver progressObserver) {
this.barProgress = barProgress; this.progressObserver = progressObserver != null ? progressObserver : IProgressObserver.emptyObserver;
this.cardsfolder = new File(cardDataDir);
// These read data for lightweight classes. // These read data for lightweight classes.
File theCardsFolder = new File(cardDataDir); if (!cardsfolder.exists()) {
throw new RuntimeException("CardReader : constructor error -- " + cardsfolder.getAbsolutePath() + " file/folder not found.");
if (!theCardsFolder.exists()) {
throw new RuntimeException("CardReader : constructor error -- file not found -- filename is "
+ theCardsFolder.getAbsolutePath());
} }
if (!theCardsFolder.isDirectory()) { if (!cardsfolder.isDirectory()) {
throw new RuntimeException("CardReader : constructor error -- not a directory -- " throw new RuntimeException("CardReader : constructor error -- not a directory -- " + cardsfolder.getAbsolutePath());
+ theCardsFolder.getAbsolutePath());
} }
this.cardsfolder = theCardsFolder;
final File zipFile = new File(theCardsFolder, "cardsfolder.zip");
final File zipFile = new File(cardsfolder, "cardsfolder.zip");
if (useZip && zipFile.exists()) { if (useZip && zipFile.exists()) {
try { try {
this.zip = new ZipFile(zipFile); this.zip = new ZipFile(zipFile);
} catch (final Exception exn) { } catch (final Exception exn) {
System.err.printf("Error reading zip file \"%s\": %s. Defaulting to txt files in \"%s\".%n", zipFile.getAbsolutePath(), exn, theCardsFolder.getAbsolutePath()); System.err.printf("Error reading zip file \"%s\": %s. Defaulting to txt files in \"%s\".%n", zipFile.getAbsolutePath(), exn, cardsfolder.getAbsolutePath());
} }
} }
@@ -155,16 +149,8 @@ public class CardStorageReader implements ICardStorageReader {
* @return the Card or null if it was not found. * @return the Card or null if it was not found.
*/ */
public final List<CardRules> loadCards() { public final List<CardRules> loadCards() {
if (barProgress != null) { progressObserver.setOperationName("Loading card data", true);
barProgress.setMaximum(NUMBER_OF_PARTS); progressObserver.report(0, NUMBER_OF_PARTS);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
barProgress.setPercentMode(true);
barProgress.setDescription("Loading card data: ");
}
});
}
final List<Callable<List<CardRules>>> tasks; final List<Callable<List<CardRules>>> tasks;
long estimatedFilesRemaining; long estimatedFilesRemaining;
@@ -200,8 +186,8 @@ public class CardStorageReader implements ICardStorageReader {
sw.stop(); sw.stop();
final long timeOnParse = sw.getTime(); final long timeOnParse = sw.getTime();
System.out.printf("Read cards: %s %s in %d ms (%d parts) %s%n", estimatedFilesRemaining, zip == null? "files" : "archived files", timeOnParse, NUMBER_OF_PARTS, useThreadPool ? "using thread pool" : "in same thread"); System.out.printf("Read cards: %s %s in %d ms (%d parts) %s%n", estimatedFilesRemaining, zip == null? "files" : "archived files", timeOnParse, NUMBER_OF_PARTS, useThreadPool ? "using thread pool" : "in same thread");
if ( null != barProgress ) // if ( null != barProgress )
barProgress.setPercentMode(false); // barProgress.setPercentMode(false);
return res; return res;
} // loadCardsUntilYouFind(String) } // loadCardsUntilYouFind(String)
@@ -244,9 +230,8 @@ public class CardStorageReader implements ICardStorageReader {
@Override @Override
public List<CardRules> call() throws Exception{ public List<CardRules> call() throws Exception{
List<CardRules> res = loadCardsInRangeFromZip(entries, from, till); List<CardRules> res = loadCardsInRangeFromZip(entries, from, till);
if ( null != barProgress )
barProgress.increment();
cdl.countDown(); cdl.countDown();
progressObserver.report(NUMBER_OF_PARTS - (int)cdl.getCount(), NUMBER_OF_PARTS);
return res; return res;
} }
}); });
@@ -265,9 +250,8 @@ public class CardStorageReader implements ICardStorageReader {
@Override @Override
public List<CardRules> call() throws Exception{ public List<CardRules> call() throws Exception{
List<CardRules> res = loadCardsInRange(allFiles, from, till); List<CardRules> res = loadCardsInRange(allFiles, from, till);
if ( null != barProgress )
barProgress.increment();
cdl.countDown(); cdl.countDown();
progressObserver.report(NUMBER_OF_PARTS - (int)cdl.getCount(), NUMBER_OF_PARTS);
return res; return res;
} }
}); });
@@ -329,9 +313,7 @@ public class CardStorageReader implements ICardStorageReader {
//rules.setSourceFile(file); //rules.setSourceFile(file);
return rules; return rules;
} catch (final FileNotFoundException ex) { } catch (final FileNotFoundException ex) {
BugReporter.reportException(ex, "File \"%s\" exception", file.getAbsolutePath()); throw new RuntimeException("CardReader : run error -- file not found: " + file.getPath(), ex);
throw new RuntimeException("CardReader : run error -- file exception -- filename is "
+ file.getPath(), ex);
} finally { } finally {
try { try {
fileInputStream.close(); fileInputStream.close();

View File

@@ -51,9 +51,9 @@ public class FProgressBar extends JProgressBar {
}; };
/** Increments bar, thread safe. Calculations executed on separate thread. */ /** Increments bar, thread safe. Calculations executed on separate thread. */
public void increment() { public void setValueThreadSafe(int value) {
//GuiUtils.checkEDT("FProgressBar$increment", false); //GuiUtils.checkEDT("FProgressBar$increment", false);
tempVal++; tempVal = value;
// String.format leads to StringBuilder anyway. Direct calls will be faster // String.format leads to StringBuilder anyway. Direct calls will be faster
StringBuilder sb = new StringBuilder(desc); StringBuilder sb = new StringBuilder(desc);

View File

@@ -1793,19 +1793,20 @@ public enum FSkin {
final File f6 = new File(DEFAULT_DIR + FILE_OLD_FOIL_SPRITE); final File f6 = new File(DEFAULT_DIR + FILE_OLD_FOIL_SPRITE);
try { try {
int p = 0;
bimDefaultSprite = ImageIO.read(f1); bimDefaultSprite = ImageIO.read(f1);
FView.SINGLETON_INSTANCE.incrementSplashProgessBar(); FView.SINGLETON_INSTANCE.incrementSplashProgessBar(++p);
bimPreferredSprite = ImageIO.read(f2); bimPreferredSprite = ImageIO.read(f2);
FView.SINGLETON_INSTANCE.incrementSplashProgessBar(); FView.SINGLETON_INSTANCE.incrementSplashProgessBar(++p);
bimFoils = ImageIO.read(f3); bimFoils = ImageIO.read(f3);
FView.SINGLETON_INSTANCE.incrementSplashProgessBar(); FView.SINGLETON_INSTANCE.incrementSplashProgessBar(++p);
bimOldFoils = f6.exists() ? ImageIO.read(f6) : ImageIO.read(f3); bimOldFoils = f6.exists() ? ImageIO.read(f6) : ImageIO.read(f3);
FView.SINGLETON_INSTANCE.incrementSplashProgessBar(); FView.SINGLETON_INSTANCE.incrementSplashProgessBar(++p);
bimDefaultAvatars = ImageIO.read(f4); bimDefaultAvatars = ImageIO.read(f4);
if (f5.exists()) { bimPreferredAvatars = ImageIO.read(f5); } if (f5.exists()) { bimPreferredAvatars = ImageIO.read(f5); }
FView.SINGLETON_INSTANCE.incrementSplashProgessBar(); FView.SINGLETON_INSTANCE.incrementSplashProgessBar(++p);
preferredH = bimPreferredSprite.getHeight(); preferredH = bimPreferredSprite.getHeight();
preferredW = bimPreferredSprite.getWidth(); preferredW = bimPreferredSprite.getWidth();

View File

@@ -414,9 +414,9 @@ public enum FView {
VBazaarUI.SINGLETON_INSTANCE.instantiate(); VBazaarUI.SINGLETON_INSTANCE.instantiate();
} }
public void incrementSplashProgessBar() { public void incrementSplashProgessBar(int value) {
if (this.frmSplash == null) { return; } if (this.frmSplash == null) { return; }
this.frmSplash.getProgressBar().increment(); this.frmSplash.getProgressBar().setValueThreadSafe(value);
} }
public void setSplashProgessBarMessage(final String message) { public void setSplashProgessBarMessage(final String message) {