Create FModel for loading preferences and other information

This commit is contained in:
drdev
2014-03-05 22:55:06 +00:00
parent d13e4dbdc5
commit 44da03a8f9
12 changed files with 793 additions and 84 deletions

5
.gitattributes vendored
View File

@@ -16011,6 +16011,7 @@ forge-m-base/src/forge/assets/FSkinColor.java -text
forge-m-base/src/forge/assets/FSkinFont.java -text
forge-m-base/src/forge/assets/FSkinImage.java -text
forge-m-base/src/forge/assets/FSkinTexture.java -text
forge-m-base/src/forge/model/FModel.java -text
forge-m-base/src/forge/player/LobbyPlayerHuman.java -text
forge-m-base/src/forge/player/PlayerControllerHuman.java -text
forge-m-base/src/forge/screens/FScreen.java -text
@@ -16041,7 +16042,9 @@ forge-m-base/src/forge/toolbox/FOverlay.java -text
forge-m-base/src/forge/toolbox/FProgressBar.java -text
forge-m-base/src/forge/toolbox/FScrollPane.java -text
forge-m-base/src/forge/utils/Constants.java -text
forge-m-base/src/forge/utils/FileLocation.java -text
forge-m-base/src/forge/utils/ForgePreferences.java -text
forge-m-base/src/forge/utils/Preferences.java -text
forge-m-base/src/forge/utils/PreferencesStore.java -text
forge-m-base/src/forge/utils/Utils.java -text
forge-m-desktop/.classpath -text
forge-m-desktop/.project -text

View File

@@ -40,7 +40,7 @@ import java.util.Map;
public class AiProfileUtil {
private static Map<String, Map<AiProps, String>> loadedProfiles = new HashMap<String, Map<AiProps, String>>();
private static final String AI_PROFILE_DIR = "res/ai";
private static String AI_PROFILE_DIR;
private static final String AI_PROFILE_EXT = ".ai";
public static final String AI_PROFILE_RANDOM_MATCH = "* Random (Match) *";
@@ -58,7 +58,9 @@ public class AiProfileUtil {
/**
* Load all profiles
*/
public static final void loadAllProfiles() {
public static final void loadAllProfiles(String aiProfileDir) {
AI_PROFILE_DIR = aiProfileDir;
loadedProfiles.clear();
ArrayList<String> availableProfiles = getAvailableProfiles();
for (String profile : availableProfiles) {

View File

@@ -150,17 +150,14 @@ public class FModel {
this.decks = new CardCollections();
this.quest = new QuestController();
// Preload AI profiles
AiProfileUtil.loadAllProfiles();
AiProfileUtil.loadAllProfiles(NewConstants.AI_PROFILE_DIR);
}
public final QuestController getQuest() {
return quest;
}
private static boolean KeywordsLoaded = false;
/**

View File

@@ -45,6 +45,7 @@ public final class NewConstants {
public static final String BAZAAR_FILE = _QUEST_DIR + "bazaar/index.xml";
public static final String CARD_DATA_DIR = _RES_ROOT + "cardsfolder/";
public static final String DECK_CUBE_DIR = _RES_ROOT + "cube";
public static final String AI_PROFILE_DIR = _RES_ROOT + "ai";
public static final String QUEST_WORLD_DIR = _QUEST_DIR + "worlds/";
public static final String QUEST_PRECON_DIR = _QUEST_DIR + "precons/";

View File

@@ -24,6 +24,7 @@ import forge.assets.FSkin;
import forge.assets.FSkinColor;
import forge.assets.FSkinFont;
import forge.assets.FImage;
import forge.model.FModel;
import forge.screens.FScreen;
import forge.screens.SplashScreen;
import forge.screens.home.HomeScreen;
@@ -37,7 +38,6 @@ public class Forge implements ApplicationListener {
private static SpriteBatch batch;
private static ShapeRenderer shapeRenderer;
private static FScreen currentScreen;
private static StaticData magicDb;
private static SplashScreen splashScreen;
private static final Stack<FScreen> screens = new Stack<FScreen>();
@@ -56,38 +56,13 @@ public class Forge implements ApplicationListener {
splashScreen = new SplashScreen();
FSkin.loadLight("journeyman", splashScreen);
// Loads card database on background thread (using progress bar to report progress)
/*new Thread(new Runnable() {
//load model on background thread (using progress bar to report progress)
new Thread(new Runnable() {
@Override
public void run() {
final FProgressBar bar = splashScreen.getProgressBar();
final CardStorageReader.ProgressObserver progressBarBridge = new CardStorageReader.ProgressObserver() {
@Override
public void setOperationName(final String name, final boolean usePercents) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
bar.setDescription(name);
bar.setPercentMode(usePercents);
}
});
}
FModel.initialize(splashScreen.getProgressBar());
@Override
public void report(final int current, final int total) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
bar.setMaximum(total);
bar.setValue(current);
}
});
}
};
final CardStorageReader reader = new CardStorageReader(Constants.CARD_DATA_DIR, progressBarBridge, null);
magicDb = new StaticData(reader, Constants.EDITIONS_DIR, Constants.BLOCK_DATA_DIR);
bar.setDescription("Opening main window...");
splashScreen.getProgressBar().setDescription("Opening main window...");
Gdx.app.postRunnable(new Runnable() {
@Override
@@ -96,8 +71,7 @@ public class Forge implements ApplicationListener {
}
});
}
}).start();*/
afterDbLoaded();
}).start();
}
private void afterDbLoaded() {
@@ -133,10 +107,6 @@ public class Forge implements ApplicationListener {
currentScreen.setSize(screenWidth, screenHeight);
}
public static StaticData getMagicDb() {
return magicDb;
}
@Override
public void render () {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); // Clear the screen.

View File

@@ -0,0 +1,323 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.model;
import forge.CardStorageReader;
import forge.StaticData;
import forge.ai.AiProfileUtil;
import forge.card.CardType;
import forge.game.GameFormat;
import forge.game.card.CardUtil;
import forge.toolbox.FProgressBar;
import forge.util.FileUtil;
import forge.utils.Constants;
import forge.utils.ForgePreferences;
import java.io.*;
import java.util.List;
import com.badlogic.gdx.Gdx;
/**
* The default Model implementation for Forge.
*
* This used to be an interface, but it seems unlikely that we will ever use a
* different model.
*
* In case we need to convert it into an interface in the future, all fields of
* this class must be either private or public static final.
*/
public class FModel {
private static StaticData magicDb;
private static PrintStream oldSystemOut;
private static PrintStream oldSystemErr;
private static OutputStream logFileStream;
//private final QuestPreferences questPreferences;
private static ForgePreferences preferences;
// Someone should take care of 2 gauntlets here
/*private static GauntletData gauntletData;
private static GauntletMini gauntlet;
private static QuestController quest;
private static CardCollections decks;
private static IStorage<CardBlock> blocks;
private static IStorage<CardBlock> fantasyBlocks;
private static IStorage<QuestWorld> worlds;*/
private static GameFormat.Collection formats;
public static void initialize(final FProgressBar progressBar) {
// install our error reporter
//ExceptionHandler.registerErrorHandling();
//load card database
final CardStorageReader.ProgressObserver progressBarBridge = new CardStorageReader.ProgressObserver() {
@Override
public void setOperationName(final String name, final boolean usePercents) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
progressBar.setDescription(name);
progressBar.setPercentMode(usePercents);
}
});
}
@Override
public void report(final int current, final int total) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
progressBar.setMaximum(total);
progressBar.setValue(current);
}
});
}
};
final CardStorageReader reader = new CardStorageReader(Constants.CARD_DATA_DIR, progressBarBridge, null);
magicDb = new StaticData(reader, Constants.EDITIONS_DIR, Constants.BLOCK_DATA_DIR);
//create profile dirs if they don't already exist
for (String dname : Constants.PROFILE_DIRS) {
File path = new File(dname);
if (path.isDirectory()) {
// already exists
continue;
}
if (!path.mkdirs()) {
throw new RuntimeException("cannot create profile directory: " + dname);
}
}
//initialize log file
File logFile = new File(Constants.LOG_FILE);
int i = 0;
while (logFile.exists() && !logFile.delete()) {
String pathname = logFile.getPath().replaceAll("[0-9]{0,2}.log$", String.valueOf(i++) + ".log");
logFile = new File(pathname);
}
try {
logFileStream = new FileOutputStream(logFile);
}
catch (final FileNotFoundException e) {
e.printStackTrace();
}
/*oldSystemOut = System.out;
System.setOut(new PrintStream(new MultiplexOutputStream(System.out, logFileStream), true));
oldSystemErr = System.err;
System.setErr(new PrintStream(new MultiplexOutputStream(System.err, logFileStream), true));*/
// Instantiate preferences: quest and regular
try {
preferences = new ForgePreferences();
}
catch (final Exception exn) {
throw new RuntimeException(exn);
}
formats = new GameFormat.Collection(new GameFormat.Reader(new File(Constants.BLOCK_DATA_DIR + "formats.txt")));
/*blocks = new StorageBase<CardBlock>("Block definitions", new CardBlock.Reader(Constants.BLOCK_DATA_DIR + "blocks.txt", magicDb.getEditions()));
questPreferences = new QuestPreferences();
gauntletData = new GauntletData();
fantasyBlocks = new StorageBase<CardBlock>("Custom blocks", new CardBlock.Reader(Constants.BLOCK_DATA_DIR + "fantasyblocks.txt", magicDb.getEditions()));
worlds = new StorageBase<QuestWorld>("Quest worlds", new QuestWorld.Reader(Constants.QUEST_WORLD_DIR + "worlds.txt"));*/
loadDynamicGamedata();
progressBar.setDescription("Loading decks");
/*decks = new CardCollections();
quest = new QuestController();*/
//preload AI profiles
AiProfileUtil.loadAllProfiles(Constants.AI_PROFILE_DIR);
}
/*public static QuestController getQuest() {
return quest;
}*/
private static boolean keywordsLoaded = false;
/**
* Load dynamic gamedata.
*/
public static void loadDynamicGamedata() {
if (!CardType.Constant.LOADED[0]) {
final List<String> typeListFile = FileUtil.readFile(Constants.TYPE_LIST_FILE);
List<String> tList = null;
if (typeListFile.size() > 0) {
for (int i = 0; i < typeListFile.size(); i++) {
final String s = typeListFile.get(i);
if (s.equals("[CardTypes]")) {
tList = CardType.Constant.CARD_TYPES;
}
else if (s.equals("[SuperTypes]")) {
tList = CardType.Constant.SUPER_TYPES;
}
else if (s.equals("[BasicTypes]")) {
tList = CardType.Constant.BASIC_TYPES;
}
else if (s.equals("[LandTypes]")) {
tList = CardType.Constant.LAND_TYPES;
}
else if (s.equals("[CreatureTypes]")) {
tList = CardType.Constant.CREATURE_TYPES;
}
else if (s.equals("[InstantTypes]")) {
tList = CardType.Constant.INSTANT_TYPES;
}
else if (s.equals("[SorceryTypes]")) {
tList = CardType.Constant.SORCERY_TYPES;
}
else if (s.equals("[EnchantmentTypes]")) {
tList = CardType.Constant.ENCHANTMENT_TYPES;
}
else if (s.equals("[ArtifactTypes]")) {
tList = CardType.Constant.ARTIFACT_TYPES;
}
else if (s.equals("[WalkerTypes]")) {
tList = CardType.Constant.WALKER_TYPES;
}
else if (s.length() > 1) {
tList.add(s);
}
}
}
CardType.Constant.LOADED[0] = true;
/*
* if (Constant.Runtime.DevMode[0]) {
* System.out.println(CardType.Constant.cardTypes[0].list);
* System.out.println(CardType.Constant.superTypes[0].list);
* System.out.println(CardType.Constant.basicTypes[0].list);
* System.out.println(CardType.Constant.landTypes[0].list);
* System.out.println(CardType.Constant.creatureTypes[0].list);
* System.out.println(CardType.Constant.instantTypes[0].list);
* System.out.println(CardType.Constant.sorceryTypes[0].list);
* System.out.println(CardType.Constant.enchantmentTypes[0].list);
* System.out.println(CardType.Constant.artifactTypes[0].list);
* System.out.println(CardType.Constant.walkerTypes[0].list); }
*/
}
if (!keywordsLoaded) {
final List<String> nskwListFile = FileUtil.readFile(Constants.KEYWORD_LIST_FILE);
if (nskwListFile.size() > 1) {
for (String s : nskwListFile) {
if (s.length() > 1) {
CardUtil.NON_STACKING_LIST.add(s);
}
}
}
keywordsLoaded = true;
/*
* if (Constant.Runtime.DevMode[0]) {
* System.out.println(Constant.Keywords.NonStackingList[0].list); }
*/
}
/*
* if (!MagicColor.Constant.loaded[0]) { ArrayList<String> lcListFile =
* FileUtil.readFile("res/gamedata/LandColorList");
*
* if (lcListFile.size() > 1) { for (int i=0; i<lcListFile.size(); i++)
* { String s = lcListFile.get(i); if (s.length() > 1)
* MagicColor.Constant.LandColor[0].map.add(s); } }
* Constant.Keywords.loaded[0] = true; if (Constant.Runtime.DevMode[0])
* { System.out.println(Constant.Keywords.NonStackingList[0].list); } }
*/
}
public static StaticData getMagicDb() {
return magicDb;
}
public static ForgePreferences getPreferences() {
return preferences;
}
/*public static IStorage<CardBlock> getBlocks() {
return blocks;
}
public static QuestPreferences getQuestPreferences() {
return questPreferences;
}
public static GauntletData getGauntletData() {
return gauntletData;
}
public static CardCollections getDecks() {
return decks;
}
public static IStorage<QuestWorld> getWorlds() {
return worlds;
}*/
public static GameFormat.Collection getFormats() {
return formats;
}
/**
* Finalizer, generally should be avoided, but here closes the log file
* stream and resets the system output streams.
*/
public static void close() throws IOException {
System.setOut(oldSystemOut);
System.setErr(oldSystemErr);
logFileStream.close();
}
/*public static void setGauntletData(GauntletData data0) {
gauntletData = data0;
}
public static IStorage<CardBlock> getFantasyBlocks() {
return fantasyBlocks;
}
public static GauntletMini getGauntletMini() {
if (gauntlet == null) {
gauntlet = new GauntletMini();
}
return gauntlet;
}*/
}

View File

@@ -47,7 +47,8 @@ public final class Constants {
public static final String EDITIONS_DIR = _ASSETS_ROOT + "editions/";
public static final String BLOCK_DATA_DIR = _ASSETS_ROOT + "blockdata/";
public static final String DECK_CUBE_DIR = _ASSETS_ROOT + "cube";
public static final String QUEST_WORLD_DIR = _QUEST_DIR + "worlds/";
public static final String AI_PROFILE_DIR = _ASSETS_ROOT + "ai";
public static final String QUEST_WORLD_DIR = _QUEST_DIR + "world/";
public static final String QUEST_PRECON_DIR = _QUEST_DIR + "precons/";
public static final String CARD_DATA_PETS_DIR = _QUEST_DIR + "bazaar/";
@@ -77,14 +78,6 @@ public final class Constants {
public static final String QUEST_PREFS_FILE = USER_PREFS_DIR + "quest.preferences";
public static final String ITEM_VIEW_PREFS_FILE = USER_PREFS_DIR + "item_view.preferences";
// data that has defaults in the program dir but overrides/additions in the user dir
private static final String _DEFAULTS_DIR = _ASSETS_ROOT + "defaults/";
public static final FileLocation WINDOW_LAYOUT_FILE = new FileLocation(_DEFAULTS_DIR, USER_PREFS_DIR, "window.xml");
public static final FileLocation MATCH_LAYOUT_FILE = new FileLocation(_DEFAULTS_DIR, USER_PREFS_DIR, "match.xml");
public static final FileLocation WORKSHOP_LAYOUT_FILE = new FileLocation(_DEFAULTS_DIR, USER_PREFS_DIR, "workshop.xml");
public static final FileLocation EDITOR_LAYOUT_FILE = new FileLocation(_DEFAULTS_DIR, USER_PREFS_DIR, "editor.xml");
public static final FileLocation GAUNTLET_DIR = new FileLocation(_DEFAULTS_DIR, USER_DIR, "gauntlet/");
// data that is only in the cached dir
private static final String _PICS_DIR = CACHE_DIR + "pics/";
public static final String DB_DIR = CACHE_DIR + "db/";
@@ -101,7 +94,6 @@ public final class Constants {
USER_DIR,
CACHE_DIR,
USER_PREFS_DIR,
GAUNTLET_DIR.userPrefLoc,
DB_DIR,
DECK_CONSTRUCTED_DIR,
DECK_DRAFT_DIR,

View File

@@ -1,28 +0,0 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.utils;
public final class FileLocation {
public final String defaultLoc;
public final String userPrefLoc;
FileLocation (String defaultPrefix, String userPrefix, String commonSuffix) {
defaultLoc = defaultPrefix + commonSuffix;
userPrefLoc = userPrefix + commonSuffix;
}
}

View File

@@ -0,0 +1,138 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.utils;
import forge.ai.AiProfileUtil;
import forge.game.GameLogEntryType;
public class ForgePreferences extends PreferencesStore<ForgePreferences.FPref> {
/**
* Preference identifiers, and their default values.
*/
public static enum FPref {
PLAYER_NAME (""),
CONSTRUCTED_P1_DECK_STATE(""),
CONSTRUCTED_P2_DECK_STATE(""),
CONSTRUCTED_P3_DECK_STATE(""),
CONSTRUCTED_P4_DECK_STATE(""),
CONSTRUCTED_P5_DECK_STATE(""),
CONSTRUCTED_P6_DECK_STATE(""),
CONSTRUCTED_P7_DECK_STATE(""),
CONSTRUCTED_P8_DECK_STATE(""),
UI_RANDOM_FOIL ("false"),
UI_ENABLE_AI_CHEATS ("false"),
UI_AVATARS ("0,1"),
UI_SHOW_CARD_OVERLAYS ("true"),
UI_OVERLAY_CARD_NAME ("true"),
UI_OVERLAY_CARD_POWER ("true"),
UI_OVERLAY_CARD_MANA_COST ("true"),
UI_OVERLAY_CARD_ID ("true"),
UI_OVERLAY_FOIL_EFFECT ("true"),
UI_HIDE_REMINDER_TEXT ("false"),
UI_UPLOAD_DRAFT ("false"),
UI_RANDOM_ART_IN_POOLS ("true"),
UI_BUGZ_NAME (""),
UI_BUGZ_PWD (""),
UI_ANTE ("false"),
UI_MANABURN("false"),
UI_SKIN ("Default"),
UI_PREFERRED_AVATARS_ONLY ("false"),
UI_TARGETING_OVERLAY ("false"),
UI_ENABLE_SOUNDS ("true"),
UI_ALT_SOUND_SYSTEM ("false"),
UI_CURRENT_AI_PROFILE (AiProfileUtil.AI_PROFILE_RANDOM_MATCH),
UI_CLONE_MODE_SOURCE ("false"),
UI_MATCH_IMAGE_VISIBLE ("true"),
UI_FOR_TOUCHSCREN("false"),
MATCHPREF_PROMPT_FREE_BLOCKS("false"),
ENFORCE_DECK_LEGALITY ("true"),
DEV_MODE_ENABLED ("false"),
// DEV_MILLING_LOSS ("true"),
DEV_UNLIMITED_LAND ("false"),
DEV_LOG_ENTRY_TYPE (GameLogEntryType.DAMAGE.toString()),
DECK_DEFAULT_CARD_LIMIT ("4"),
DECKGEN_SINGLETONS ("false"),
DECKGEN_ARTIFACTS ("false"),
DECKGEN_NOSMALL ("false"),
PHASE_AI_UPKEEP ("true"),
PHASE_AI_DRAW ("true"),
PHASE_AI_MAIN1 ("true"),
PHASE_AI_BEGINCOMBAT ("true"),
PHASE_AI_DECLAREATTACKERS ("true"),
PHASE_AI_DECLAREBLOCKERS ("true"),
PHASE_AI_FIRSTSTRIKE ("true"),
PHASE_AI_COMBATDAMAGE ("true"),
PHASE_AI_ENDCOMBAT ("true"),
PHASE_AI_MAIN2 ("true"),
PHASE_AI_EOT ("true"),
PHASE_AI_CLEANUP ("true"),
PHASE_HUMAN_UPKEEP ("true"),
PHASE_HUMAN_DRAW ("true"),
PHASE_HUMAN_MAIN1 ("true"),
PHASE_HUMAN_BEGINCOMBAT ("true"),
PHASE_HUMAN_DECLAREATTACKERS ("true"),
PHASE_HUMAN_DECLAREBLOCKERS ("true"),
PHASE_HUMAN_FIRSTSTRIKE ("true"),
PHASE_HUMAN_COMBATDAMAGE ("true"),
PHASE_HUMAN_ENDCOMBAT ("true"),
PHASE_HUMAN_MAIN2 ("true"),
PHASE_HUMAN_EOT ("true"),
PHASE_HUMAN_CLEANUP ("true");
private final String strDefaultVal;
/** @param s0 &emsp; {@link java.lang.String} */
FPref(String s0) {
this.strDefaultVal = s0;
}
/** @return {@link java.lang.String} */
public String getDefault() {
return strDefaultVal;
}
}
/** Instantiates a ForgePreferences object. */
public ForgePreferences() {
super(Constants.MAIN_PREFS_FILE, FPref.class);
}
protected FPref[] getEnumValues() {
return FPref.values();
}
protected FPref valueOf(String name) {
try {
return FPref.valueOf(name);
}
catch (Exception e) {
return null;
}
}
protected String getPrefDefault(FPref key) {
return key.getDefault();
}
}

View File

@@ -0,0 +1,196 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.utils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
/**
* A collection of name/value pairs with sorted keys and utility methods.
*
* @author Forge
* @version $Id: Preferences.java 24769 2014-02-09 13:56:04Z Hellfish $
*/
public class Preferences {
/** The props. */
private final Properties props;
/**
* <p>
* Constructor for Preferences.
* </p>
*/
public Preferences() {
this.props = new Properties();
}
/**
* <p>
* Constructor for Preferences.
* </p>
*
* @param prefs
* a {@link forge.properties.Preferences} object.
*/
public Preferences(final Preferences prefs) {
this.props = prefs.props;
}
/**
* <p>
* keys.
* </p>
*
* @return a {@link java.util.Enumeration} object.
*/
public final synchronized Enumeration<String> keys() {
@SuppressWarnings({ "unchecked", "rawtypes" })
final Set<String> keysEnum = (Set) this.props.keySet();
final Vector<String> keyList = new Vector<String>();
keyList.addAll(keysEnum);
Collections.sort(keyList);
return keyList.elements();
}
/**
* <p>
* getInt.
* </p>
*
* @param name
* a {@link java.lang.String} object.
* @param defaultValue
* a int.
* @return a int.
*/
public final int getInt(final String name, final int defaultValue) {
final String value = this.props.getProperty(name);
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (final NumberFormatException ex) {
return defaultValue;
}
}
/**
* <p>
* getBoolean.
* </p>
*
* @param name
* a {@link java.lang.String} object.
* @param defaultValue
* a boolean.
* @return a boolean.
*/
public final boolean getBoolean(final String name, final boolean defaultValue) {
final String value = this.props.getProperty(name);
if (value == null) {
return defaultValue;
}
return Boolean.parseBoolean(value);
}
/**
* <p>
* getLong.
* </p>
*
* @param name
* a {@link java.lang.String} object.
* @param defaultValue
* a long.
* @return a long.
*/
public final long getLong(final String name, final long defaultValue) {
final String value = this.props.getProperty(name);
if (value == null) {
return defaultValue;
}
return Long.parseLong(value);
}
/**
* <p>
* set.
* </p>
*
* @param key
* a {@link java.lang.String} object.
* @param value
* a {@link java.lang.Object} object.
*/
public final void set(final String key, final Object value) {
this.props.setProperty(key, String.valueOf(value));
}
/**
* <p>
* get.
* </p>
*
* @param key
* a {@link java.lang.String} object.
* @param value
* a {@link java.lang.Object} object.
* @return a {@link java.lang.String} object.
*/
public final String get(final String key, final Object value) {
String string = null;
if (value != null) {
string = String.valueOf(value);
}
return this.props.getProperty(key, string);
}
/**
* <p>
* load.
* </p>
*
* @param stream
* a {@link java.io.FileInputStream} object.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public final void load(final FileInputStream stream) throws IOException {
this.props.load(stream);
}
/**
* <p>
* store.
* </p>
*
* @param stream
* a {@link java.io.FileOutputStream} object.
* @param comments
* a {@link java.lang.String} object.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public final void store(final FileOutputStream stream, final String comments) throws IOException {
this.props.store(stream, comments);
}
}

View File

@@ -0,0 +1,115 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.utils;
import forge.util.FileUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* Holds default preference values in an enum.
* Loads preferred values when instantiated.
* If a requested value is not present, default is returned.
*/
public abstract class PreferencesStore<T extends Enum<T>> {
private final Map<T, String> preferenceValues;
private final String filename;
public PreferencesStore(String filename0, Class<T> clasz) {
preferenceValues = new EnumMap<T, String>(clasz);
filename = filename0;
List<String> lines = FileUtil.readFile(filename);
for (String line : lines) {
line = line.trim();
if (line.startsWith("#") || (line.isEmpty())) {
continue;
}
String[] split = line.split("=");
T pref = valueOf(split[0]);
if (null == pref) {
System.out.println("unknown preference: " + line);
continue;
}
if (split.length == 2) {
this.setPref(pref, split[1]);
} else if (split.length == 1 && line.endsWith("=")) {
this.setPref(pref, "");
}
}
}
protected abstract T[] getEnumValues();
protected abstract T valueOf(String name);
protected abstract String getPrefDefault(T key);
public final void save() {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filename));
for (T key : getEnumValues()) {
writer.write(key + "=" + getPref(key));
writer.newLine();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (null != writer) {
try { writer.close(); }
catch (IOException e) { System.out.println("error while closing " + filename); }
}
}
}
public final void reset() {
this.preferenceValues.clear();
}
public final void setPref(T q0, String s0) {
preferenceValues.put(q0, s0);
}
public final void setPref(T q0, boolean val) {
setPref(q0, String.valueOf(val));
}
public final String getPref(T fp0) {
String val;
val = preferenceValues.get(fp0);
if (val == null) { val = getPrefDefault(fp0); }
return val;
}
public final int getPrefInt(T fp0) {
return Integer.parseInt(getPref(fp0));
}
public final boolean getPrefBoolean(T fp0) {
return Boolean.parseBoolean(getPref(fp0));
}
}

View File

@@ -2,7 +2,6 @@ package forge.utils;
import com.badlogic.gdx.Gdx;
import forge.Forge;
import forge.card.CardDb;
import forge.deck.Deck;
import forge.deck.generation.DeckGenerator2Color;
@@ -10,6 +9,7 @@ import forge.deck.generation.DeckGenerator3Color;
import forge.deck.generation.DeckGenerator5Color;
import forge.deck.generation.DeckGeneratorBase;
import forge.deck.generation.DeckGeneratorMonoColor;
import forge.model.FModel;
public class Utils {
private final static float ppcX = Gdx.graphics.getPpcX();
@@ -29,7 +29,7 @@ public class Utils {
}
public static Deck generateRandomDeck(final int colorCount0) {
CardDb cardDb = Forge.getMagicDb().getCommonCards();
CardDb cardDb = FModel.getMagicDb().getCommonCards();
DeckGeneratorBase gen = null;
switch (colorCount0) {
case 1: gen = new DeckGeneratorMonoColor(cardDb, null); break;