You can subscribe to this list here.
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(3) |
Nov
(46) |
Dec
(57) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2009 |
Jan
(51) |
Feb
(10) |
Mar
|
Apr
|
May
(14) |
Jun
|
Jul
(13) |
Aug
(30) |
Sep
(83) |
Oct
(56) |
Nov
(148) |
Dec
(107) |
2010 |
Jan
(260) |
Feb
(164) |
Mar
(183) |
Apr
(99) |
May
(160) |
Jun
(40) |
Jul
(33) |
Aug
(48) |
Sep
(22) |
Oct
(24) |
Nov
(1) |
Dec
(12) |
2011 |
Jan
(6) |
Feb
(15) |
Mar
(13) |
Apr
(37) |
May
(27) |
Jun
(29) |
Jul
(33) |
Aug
(20) |
Sep
(17) |
Oct
(20) |
Nov
(33) |
Dec
(17) |
2012 |
Jan
(39) |
Feb
(38) |
Mar
(20) |
Apr
(21) |
May
(17) |
Jun
(22) |
Jul
(16) |
Aug
(3) |
Sep
(9) |
Oct
(10) |
Nov
|
Dec
|
From: <ev...@us...> - 2010-07-25 17:08:43
|
Revision: 1357 http://rails.svn.sourceforge.net/rails/?rev=1357&view=rev Author: evos Date: 2010-07-25 17:08:37 +0000 (Sun, 25 Jul 2010) Log Message: ----------- Executed actions are no longer saved as a List<PossibleAction> but as a containerless sequence of PossibleAction objects. This allows postponing object assignment during deserialization until all previous actions have been processed, so that the game always is in the same state as during playing the game. This should fix bugs attributable to assignment to objects that do not exist at the start of the game. Modified Paths: -------------- trunk/18xx/rails/game/Game.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/util/ListAndFixSavedFiles.java Modified: trunk/18xx/rails/game/Game.java =================================================================== --- trunk/18xx/rails/game/Game.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/Game.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -94,7 +94,7 @@ // set special properties and token static variables SpecialProperty.init(); Token.init(); - + // Have the ComponentManager work through the other rails.game files componentManager.finishPreparation(); @@ -163,7 +163,7 @@ "No TileManager XML element found in file " + GAME_XML_FILE); } - + revenueManager = (RevenueManager) componentManager.findComponent("RevenueManager"); // revenueManager is optional so far @@ -189,7 +189,7 @@ bank.finishConfiguration(gameManager); stockMarket.finishConfiguration(gameManager); tileManager.finishConfiguration(gameManager); - if (revenueManager != null) + if (revenueManager != null) revenueManager.finishConfiguration(gameManager); } catch (Exception e) { String message = @@ -251,24 +251,59 @@ throw new ConfigurationException("Error in setting up " + name); } - List<PossibleAction> executedActions = - (List<PossibleAction>) ois.readObject(); - ois.close(); - log.debug("Number of loaded actions: " + executedActions.size()); - String startError = game.start(); if (startError != null) { DisplayBuffer.add(startError); return null; } + GameManagerI gameManager = game.getGameManager(); + int numberOfActions = 0; log.debug("Starting to execute loaded actions"); - if (!game.getGameManager().processOnReload(executedActions)) { - log.error ("Load interrupted"); - DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + while (true) { // Single-pass loop. + Object firstActionObject; + try { + firstActionObject = ois.readObject(); + } catch (EOFException e) { + // Allow saved file at start of game (with no actions). + break; + } + if (firstActionObject instanceof List) { + // Old-style: one List of PossibleActions + List<PossibleAction> executedActions = + (List<PossibleAction>) firstActionObject; + numberOfActions = executedActions.size(); + for (PossibleAction action : executedActions) { + if (!gameManager.processOnReload(action)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + } + + } else { + // New style: separate PossibleActionsObjects, since Rails 1.3.1 + PossibleAction action = (PossibleAction) firstActionObject; + while (true) { + numberOfActions++; + if (!gameManager.processOnReload(action)) { + log.error ("Load interrupted"); + DisplayBuffer.add(LocalText.getText("LoadInterrupted")); + break; + } + try { + action = (PossibleAction) ois.readObject(); + } catch (EOFException e) { + break; + } + } + } + break; } + ois.close(); + game.getGameManager().finishLoading(); return game; } catch (Exception e) { Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/GameManager.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -891,64 +891,60 @@ /* (non-Javadoc) * @see rails.game.GameManagerI#processOnReload(java.util.List) */ - public boolean processOnReload(List<PossibleAction> actions) throws Exception { + public boolean processOnReload(PossibleAction action) throws Exception { - for (PossibleAction action : actions) { + DisplayBuffer.clear(); + // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED + if (gameName.equals("1856") + && possibleActions.contains(RepayLoans.class) + && (!possibleActions.contains(action.getClass()) + || (action.getClass() == NullAction.class + && ((NullAction)action).getMode() != NullAction.DONE))) { + // Insert "Done" + log.debug("Action DONE inserted"); + getCurrentRound().process(new NullAction (NullAction.DONE)); + possibleActions.clear(); + getCurrentRound().setPossibleActions(); + if (!isGameOver()) setCorrectionActions(); + } - DisplayBuffer.clear(); - // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED - if (gameName.equals("1856") - && possibleActions.contains(RepayLoans.class) - && (!possibleActions.contains(action.getClass()) - || (action.getClass() == NullAction.class - && ((NullAction)action).getMode() != NullAction.DONE))) { - // Insert "Done" - log.debug("Action DONE inserted"); - getCurrentRound().process(new NullAction (NullAction.DONE)); - possibleActions.clear(); - getCurrentRound().setPossibleActions(); - if (!isGameOver()) setCorrectionActions(); + try { + log.debug("Action ("+action.getPlayerName()+"): " + action); + if (!processCorrectionActions(action) && !getCurrentRound().process(action)) { + String msg = "Player "+action.getPlayerName()+"\'s action \"" + +action.toString()+"\"\n in "+getCurrentRound().getRoundName() + +" is considered invalid by the game engine"; + log.error(msg); + DisplayBuffer.add(msg); + if (moveStack.isOpen()) moveStack.finish(); + return false; } + possibleActions.clear(); + getCurrentRound().setPossibleActions(); - try { - log.debug("Action ("+action.getPlayerName()+"): " + action); - if (!processCorrectionActions(action) && !getCurrentRound().process(action)) { - String msg = "Player "+action.getPlayerName()+"\'s action \"" - +action.toString()+"\"\n in "+getCurrentRound().getRoundName() - +" is considered invalid by the game engine"; - log.error(msg); - DisplayBuffer.add(msg); - if (moveStack.isOpen()) moveStack.finish(); - return false; - } - possibleActions.clear(); - getCurrentRound().setPossibleActions(); + // Log possible actions (normally this is outcommented) + String playerName = getCurrentPlayer().getName(); + for (PossibleAction a : possibleActions.getList()) { + log.debug(playerName+" may: "+a.toString()); + } - // Log possible actions (normally this is outcommented) - String playerName = getCurrentPlayer().getName(); - for (PossibleAction a : possibleActions.getList()) { - log.debug(playerName+" may: "+a.toString()); - } + if (!isGameOver()) setCorrectionActions(); - if (!isGameOver()) setCorrectionActions(); + } catch (Exception e) { + log.error("Error while reprocessing " + action.toString(), e); + throw new Exception("Reload failure", e); + } + new AddToList<PossibleAction>(executedActions, action, "ExecutedActions"); + if (moveStack.isOpen()) moveStack.finish(); - } catch (Exception e) { - log.error("Error while reprocessing " + action.toString(), e); - throw new Exception("Reload failure", e); - } - new AddToList<PossibleAction>(executedActions, action, - "ExecutedActions"); - if (moveStack.isOpen()) moveStack.finish(); + log.debug("Turn: "+getCurrentPlayer().getName()); + return true; + } - log.debug("Turn: "+getCurrentPlayer().getName()); - } + public void finishLoading () { - // DisplayBuffer.clear(); - // previous line removed to allow display of nextPlayerMessages guiHints.clearVisibilityHints(); - - return true; } /** recoverySave method @@ -1023,7 +1019,9 @@ oos.writeObject(gameName); oos.writeObject(gameOptions); oos.writeObject(playerNames); - oos.writeObject(executedActions); + for (PossibleAction action : executedActions) { + oos.writeObject(action); + } oos.close(); result = true; Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/game/GameManagerI.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -55,9 +55,11 @@ */ public abstract boolean process(PossibleAction action); - public abstract boolean processOnReload(List<PossibleAction> actions) + public abstract boolean processOnReload(PossibleAction action) throws Exception; + public void finishLoading (); + public abstract void finishShareSellingRound(); public abstract void finishTreasuryShareRound(); Modified: trunk/18xx/rails/util/ListAndFixSavedFiles.java =================================================================== --- trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-24 15:47:32 UTC (rev 1356) +++ trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-25 17:08:37 UTC (rev 1357) @@ -29,12 +29,12 @@ private JMenuItem trimItem, deleteItem; private StringBuffer headerText = new StringBuffer(); - + private List<Object> savedObjects = new ArrayList<Object>(512); private List<PossibleAction> executedActions; - + private int vbarPos; - + private static String saveDirectory; private String filepath; @@ -44,13 +44,13 @@ * @param args */ public static void main(String[] args) { - + // intialize configuration Config.setConfigSelection(); // delayed setting of logger log = Logger.getLogger(ListAndFixSavedFiles.class.getPackage().getName()); - + saveDirectory = Config.get("save.directory"); System.out.println("Save directory = " + saveDirectory); @@ -142,11 +142,12 @@ setVisible(true); saveDirectory = Config.get("save.directory"); - + load(); } + @SuppressWarnings("unchecked") private void load() { JFileChooser jfc = new JFileChooser(); @@ -211,10 +212,26 @@ throw new ConfigurationException("Error in setting up " + name); } - executedActions = - (List<PossibleAction>) ois.readObject(); - savedObjects.add(executedActions); - + Object firstActionObject = ois.readObject(); + if (firstActionObject instanceof List) { + // Old-style: one List of PossibleActions + executedActions = + (List<PossibleAction>) firstActionObject; + savedObjects.add(executedActions); + } else { + // New style: separate PossibleActionsObjects, since Rails 1.3.1 + executedActions = new ArrayList<PossibleAction>(); + PossibleAction action = (PossibleAction) firstActionObject; + while (true) { + savedObjects.add (action); + executedActions.add(action); + try { + action = (PossibleAction) ois.readObject(); + } catch (EOFException e) { + break; + } + } + } setReportText(true); ois.close(); @@ -232,13 +249,13 @@ headerText.append("\n"); } } - + private void setReportText(boolean initial) { if (initial) vbarPos = -1; else vbarPos = this.vbar.getValue(); - + reportText.setText(headerText.toString()); // append actionText int i=0; @@ -248,8 +265,8 @@ } scrollDown(vbarPos); } - + public void scrollDown (int pos) { SwingUtilities.invokeLater(new Runnable() { public void run() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-24 15:47:39
|
Revision: 1356 http://rails.svn.sourceforge.net/rails/?rev=1356&view=rev Author: evos Date: 2010-07-24 15:47:32 +0000 (Sat, 24 Jul 2010) Log Message: ----------- Fixed bug that prevented some cash transfers after the bank has broken. Also fixed an incorrect change in the previous commit (BuyCertificate reorganisation) Modified Paths: -------------- trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/CashHolder.java trunk/18xx/rails/game/Player.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/model/CashModel.java trunk/18xx/rails/game/move/CashMove.java Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/Bank.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -136,9 +136,10 @@ /** * Adds cash back to the bank */ - public boolean addCash(int amount) { - boolean negative = money.addCash(amount); + public void addCash(int amount) { + money.addCash(amount); + /* * Check if the bank has broken. In some games <0 could apply, so this * will become configurable. @@ -147,7 +148,6 @@ broken.set(true); GameManager.getInstance().registerBrokenBank(); } - return negative; } public boolean isBroken() { Modified: trunk/18xx/rails/game/CashHolder.java =================================================================== --- trunk/18xx/rails/game/CashHolder.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/CashHolder.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -18,7 +18,7 @@ /** * Add (or subtract) cash. */ - public abstract boolean addCash(int amount); + public abstract void addCash(int amount); /** Get the cash owner's name (needed for logging) */ public abstract String getName(); Modified: trunk/18xx/rails/game/Player.java =================================================================== --- trunk/18xx/rails/game/Player.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/Player.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -73,9 +73,8 @@ return wallet; } - public boolean addCash(int amount) { - boolean result = wallet.addCash(amount); - return result; + public void addCash(int amount) { + wallet.addCash(amount); } /** Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/PublicCompany.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -1147,8 +1147,8 @@ * * @param amount The amount to add (may be negative). */ - public boolean addCash(int amount) { - return treasury.addCash(amount); + public void addCash(int amount) { + treasury.addCash(amount); } /** Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/StockRound.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -28,7 +28,7 @@ protected BooleanState hasSoldThisTurnBeforeBuying = new BooleanState("HoldSoldBeforeBuyingThisTurn", false); - protected BooleanState hasActed = new BooleanState("HasActed", false); // Is + protected BooleanState hasActed = new BooleanState("HasActed", false); protected IntegerState numPasses = new IntegerState("StockRoundPasses"); Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -246,7 +246,8 @@ int number = action.getNumberBought(); int shareUnit = company.getShareUnit(); int sharePerCert = action.getSharePerCertificate(); - int shares = number * sharePerCert; + int share = number * sharePerCert; + int shares = share/shareUnit; String errMsg = null; int price = 0; @@ -296,7 +297,7 @@ } // Check if that many shares are available - if (shares > from.getShare(company)) { + if (share > from.getShare(company)) { errMsg = LocalText.getText("NotAvailable", companyName, @@ -308,8 +309,7 @@ // Check if company would exceed the per-company share limit int treasuryShareLimit = getGameParameterAsInt(GameDef.Parm.TREASURY_SHARE_LIMIT); - if (portfolio.getShare(company) + shares * company.getShareUnit() - > treasuryShareLimit) { + if (portfolio.getShare(company) + share > treasuryShareLimit) { errMsg = LocalText.getText("TreasuryOverHoldLimit", String.valueOf(treasuryShareLimit)); @@ -359,7 +359,7 @@ moveStack.start(true); PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, sharePerCert, false); + cert2 = from.findCertificate(company, sharePerCert/shareUnit, false); executeTradeCertificate(cert2, portfolio, cert2.getShares() * price); } Modified: trunk/18xx/rails/game/model/CashModel.java =================================================================== --- trunk/18xx/rails/game/model/CashModel.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/model/CashModel.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -1,9 +1,7 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/model/CashModel.java,v 1.5 2008/06/04 19:00:37 evos Exp $*/ package rails.game.model; -import rails.game.Bank; -import rails.game.CashHolder; -import rails.game.PublicCompanyI; +import rails.game.*; public class CashModel extends ModelObject { @@ -22,14 +20,9 @@ update(); } - public boolean addCash(int addedCash) { + public void addCash(int addedCash) { cash += addedCash; update(); - - if (cash <= 0) - return false; - else - return true; } public int getCash() { @@ -38,9 +31,10 @@ /* * (non-Javadoc) - * + * * @see rails.rails.game.model.ModelObject#getValue() */ + @Override public String getText() { if (cash == 0 && (option & SUPPRESS_ZERO) > 0 || owner instanceof PublicCompanyI Modified: trunk/18xx/rails/game/move/CashMove.java =================================================================== --- trunk/18xx/rails/game/move/CashMove.java 2010-07-23 21:29:38 UTC (rev 1355) +++ trunk/18xx/rails/game/move/CashMove.java 2010-07-24 15:47:32 UTC (rev 1356) @@ -48,9 +48,10 @@ return true; } - private boolean transferCash(CashHolder from, CashHolder to, + private void transferCash(CashHolder from, CashHolder to, int amount) { - return to.addCash(amount) && from.addCash(-amount); + to.addCash(amount); + from.addCash(-amount); } @Override This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-23 21:29:44
|
Revision: 1355 http://rails.svn.sourceforge.net/rails/?rev=1355&view=rev Author: evos Date: 2010-07-23 21:29:38 +0000 (Fri, 23 Jul 2010) Log Message: ----------- Fixed config error that prevented PR to buy the extra train Modified Paths: -------------- trunk/18xx/data/1835/CompanyManager.xml Modified: trunk/18xx/data/1835/CompanyManager.xml =================================================================== --- trunk/18xx/data/1835/CompanyManager.xml 2010-07-23 20:05:34 UTC (rev 1354) +++ trunk/18xx/data/1835/CompanyManager.xml 2010-07-23 21:29:38 UTC (rev 1355) @@ -203,7 +203,7 @@ <Certificate shares="2" number="3"/> <Certificate shares="2" number="4" status="reserved"/> <Certificate shares="1" number="4" status="reserved"/> - <TrainLimit number="0,0,4,3"/> + <Trains number="0,0,4,3"/> </Company> <StartPacket roundClass="rails.game.StartRound_1835" variant="Snake"> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-23 20:05:41
|
Revision: 1354 http://rails.svn.sourceforge.net/rails/?rev=1354&view=rev Author: evos Date: 2010-07-23 20:05:34 +0000 (Fri, 23 Jul 2010) Log Message: ----------- Changed BuyCertificate to pass on share size per certificate rather that the certificate ID. This is to make BuyCertificate consistent will SellShares and help preventing saved file loading problems. Various minor fixes have als been applied for issues detected during testing. Modified Paths: -------------- trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/GameManagerI.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/ReportBuffer.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/TreasuryShareRound.java trunk/18xx/rails/game/action/BuyCertificate.java trunk/18xx/rails/game/action/StartCompany.java trunk/18xx/rails/game/move/ObjectMove.java trunk/18xx/rails/game/specific/_1835/StockRound_1835.java trunk/18xx/rails/game/specific/_1856/StockRound_1856.java trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java trunk/18xx/rails/ui/swing/GameStatus.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java trunk/18xx/rails/util/Util.java Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/GameManager.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -68,12 +68,16 @@ protected State currentPlayer = new State("CurrentPlayer", Player.class); protected State priorityPlayer = new State("PriorityPlayer", Player.class); - /** Map relating portfolio names and objects, to enable deserialization */ + /** Map relating portfolio names and objects, to enable deserialization. + * OBSOLETE since Rails 1.3.1, but still required to enable reading old saved files */ protected Map<String, Portfolio> portfolioMap = new HashMap<String, Portfolio> (); + /** Map relating portfolio unique names and objects, to enable deserialization */ + protected Map<String, Portfolio> portfolioUniqueNameMap = + new HashMap<String, Portfolio> (); protected IntegerState playerCertificateLimit - = new IntegerState ("PlayerCertificateLimit", 0); + = new IntegerState ("PlayerCertificateLimit", 0); protected int currentNumberOfOperatingRounds = 1; protected boolean skipFirstStockRound = false; protected boolean showCompositeORNumber = true; @@ -83,7 +87,7 @@ protected boolean gameEndsAfterSetOfORs = true; protected EnumMap<GameDef.Parm, Object> gameParameters - = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); + = new EnumMap<GameDef.Parm, Object>(GameDef.Parm.class); // protected EnumSet<CorrectionType> activeCorrections // = EnumSet.noneOf(CorrectionType.class); @@ -893,11 +897,15 @@ DisplayBuffer.clear(); // TEMPORARY FIX TO ALLOW OLD 1856 SAVED FILES TO BE PROCESSED - if (!possibleActions.contains(action.getClass()) - && possibleActions.contains(RepayLoans.class)) { + if (gameName.equals("1856") + && possibleActions.contains(RepayLoans.class) + && (!possibleActions.contains(action.getClass()) + || (action.getClass() == NullAction.class + && ((NullAction)action).getMode() != NullAction.DONE))) { // Insert "Done" log.debug("Action DONE inserted"); getCurrentRound().process(new NullAction (NullAction.DONE)); + possibleActions.clear(); getCurrentRound().setPossibleActions(); if (!isGameOver()) setCorrectionActions(); } @@ -913,11 +921,16 @@ if (moveStack.isOpen()) moveStack.finish(); return false; } + possibleActions.clear(); getCurrentRound().setPossibleActions(); - //String playerName = getCurrentPlayer().getName(); - //for (PossibleAction a : possibleActions.getList()) { - // log.debug(playerName+" may: "+a.toString()); - //} + + // Log possible actions (normally this is outcommented) + String playerName = getCurrentPlayer().getName(); + for (PossibleAction a : possibleActions.getList()) { + log.debug(playerName+" may: "+a.toString()); + } + + if (!isGameOver()) setCorrectionActions(); } catch (Exception e) { @@ -1352,12 +1365,18 @@ public void addPortfolio (Portfolio portfolio) { portfolioMap.put(portfolio.getName(), portfolio); + portfolioUniqueNameMap.put(portfolio.getUniqueName(), portfolio); } + /* since Rails 1.3.1, but still required to enable loading old saved files */ public Portfolio getPortfolioByName (String name) { return portfolioMap.get(name); } + public Portfolio getPortfolioByUniqueName (String name) { + return portfolioUniqueNameMap.get(name); + } + /* (non-Javadoc) * @see rails.game.GameManagerI#getStartPacket() */ Modified: trunk/18xx/rails/game/GameManagerI.java =================================================================== --- trunk/18xx/rails/game/GameManagerI.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/GameManagerI.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -146,6 +146,7 @@ public void addPortfolio (Portfolio portfolio); public Portfolio getPortfolioByName (String name); + public Portfolio getPortfolioByUniqueName (String name); /** * @return the StartPacket Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -71,6 +71,8 @@ /** Name of portfolio */ protected String name; + /** Unique name (including owner class name) */ + protected String uniqueName; /** Specific portfolio names */ public static final String IPO_NAME = "IPO"; @@ -84,7 +86,8 @@ public Portfolio(String name, CashHolder holder) { this.name = name; this.owner = holder; - //portfolioMap.put(name, this); + this.uniqueName = holder.getClass().getSimpleName() + "_" + name; + GameManager.getInstance().addPortfolio(this); if (owner instanceof PublicCompanyI) { @@ -303,6 +306,14 @@ return name; } + /** Get unique name (prefixed by the owners class type, to avoid Bank, Player and Company + * namespace clashes). + * @return + */ + public String getUniqueName () { + return uniqueName; + } + /** * Returns percentage that a portfolio contains of one company. * Modified: trunk/18xx/rails/game/ReportBuffer.java =================================================================== --- trunk/18xx/rails/game/ReportBuffer.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/ReportBuffer.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -14,12 +14,12 @@ /** * Class to write a log, and also to maintain a log message stack for writing to * the UI. - * + * * Each gameManager has one unique ReportBuffer, which is used by the public static methods. * Messages before the creation of that buffer are kept in an internal initial queue. - * + * * Also used for regression testing comparing the output of the report buffer. - * + * */ public final class ReportBuffer { /** @@ -28,7 +28,7 @@ * rails.game report. */ private List<String> reportQueue = new ArrayList<String>(); - + /** Another stack for messages that must "wait" for other messages */ private List<String> waitQueue = new ArrayList<String> (); @@ -44,7 +44,7 @@ private static final String DEFAULT_REPORT_EXTENSION = "txt"; static { - reportDirectory = Config.get("report.directory"); + reportDirectory = Config.get("report.directory").trim(); wantReport = Util.hasValue(reportDirectory); } @@ -69,7 +69,7 @@ private void clearReportQueue() { reportQueue.clear(); } - + private void addMessage (String message) { if (message != null) { if (message.equals("")) @@ -81,11 +81,11 @@ if (wantReport) writeToReport(message); } } - + private void writeToReport(String message) { /* Get out if we don't want a report */ - if (!Util.hasValue(reportDirectory) || !wantReport) return; + if (!wantReport) return; if (report == null) openReportFile(); @@ -97,6 +97,9 @@ private void openReportFile() { + /* Get out if we don't want a report */ + if (!wantReport) return; + /* Get any configured date/time pattern, or else set the default */ String reportFilenamePattern = Config.get("report.filename.date_time_pattern"); @@ -132,15 +135,15 @@ /** Get the current log buffer, and clear it */ public static String get() { ReportBuffer instance = getInstance(); - + // convert to String StringBuffer result = new StringBuffer(); - for (String msg:instance.getReportQueue()) + for (String msg:instance.getReportQueue()) result.append(msg).append("\n"); // clear current queue instance.clearReportQueue(); - + return result.toString(); } @@ -160,23 +163,23 @@ /** return the current buffer as list */ public static List<String> getAsList() { ReportBuffer instance = getInstance(); - - if (instance == null) + + if (instance == null) return initialQueue; else return instance.getReportQueue(); } - + /** clear the current buffer */ public static void clear() { ReportBuffer instance = getInstance(); - - if (instance == null) + + if (instance == null) initialQueue.clear(); else instance.clearReportQueue(); } - + private static ReportBuffer getInstance() { return GameManager.getInstance().getReportBuffer(); } Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/StockRound.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -196,14 +196,14 @@ if (!cert.isPresidentShare()) { price = comp.getIPOPrice() / unitsForPrice; if (price <= playerCash) { - possibleActions.add(new BuyCertificate(cert, from, - price)); + possibleActions.add(new BuyCertificate(comp, cert.getShare(), + from, price)); } } else if (!comp.hasStarted()) { if (comp.getIPOPrice() != 0) { price = comp.getIPOPrice() * cert.getShares() / unitsForPrice; if (price <= playerCash) { - possibleActions.add(new StartCompany(cert, price)); + possibleActions.add(new StartCompany(comp, price)); } } else { List<Integer> startPrices = new ArrayList<Integer>(); @@ -218,7 +218,7 @@ for (int i = 0; i < prices.length; i++) { prices[i] = startPrices.get(i); } - possibleActions.add(new StartCompany(cert, prices)); + possibleActions.add(new StartCompany(comp, prices)); } } } @@ -247,7 +247,7 @@ price = stockSpace.getPrice() / unitsForPrice; shareUnit = comp.getShareUnit(); maxNumberOfSharesToBuy - = maxAllowedNumberOfSharesToBuy(currentPlayer, comp, shareUnit); + = maxAllowedNumberOfSharesToBuy(currentPlayer, comp, shareUnit); /* Checks if the player can buy any shares of this company */ if (maxNumberOfSharesToBuy < 1) continue; @@ -296,7 +296,8 @@ } if (number > 0) { - possibleActions.add(new BuyCertificate(uniqueCerts[shares], + possibleActions.add(new BuyCertificate(comp, + uniqueCerts[shares].getShare(), from, price, number)); } @@ -320,7 +321,7 @@ if (!stockSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; if (company.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, + possibleActions.add(new BuyCertificate(company, cert.getShare(), company.getPortfolio(), company.getMarketPrice())); } } @@ -524,7 +525,7 @@ * @return True if the company could be started. False indicates an error. */ public boolean startCompany(String playerName, StartCompany action) { - PublicCompanyI company = action.getCertificate().getCompany(); + PublicCompanyI company = action.getCompany(); int price = action.getPrice(); int shares = action.getNumberBought(); @@ -618,7 +619,7 @@ // All is OK, now start the company company.start(startSpace); - CashHolder priceRecipient = getSharePriceRecipient (cert, price); + CashHolder priceRecipient = getSharePriceRecipient (company, ipo, price); // Transfer the President's certificate cert.moveTo(currentPlayer.getPortfolio()); @@ -668,17 +669,18 @@ */ public boolean buyShares(String playerName, BuyCertificate action) { - PublicCertificateI cert = action.getCertificate(); - Portfolio from = cert.getPortfolio(); - String companyName = cert.getCompany().getName(); + PublicCompanyI company = action.getCompany(); + Portfolio from = action.getFromPortfolio(); + String companyName = company.getName(); int number = action.getNumberBought(); - int shares = number * cert.getShares(); - int shareUnit = cert.getShare(); + int shareUnit = company.getShareUnit(); + int sharePerCert = action.getSharePerCertificate(); + int share = number * sharePerCert; + int shares = share / shareUnit; String errMsg = null; int price = 0; int cost = 0; - PublicCompanyI company = null; currentPlayer = getCurrentPlayer(); @@ -748,6 +750,10 @@ // Check if player would not exceed the certificate limit. // (shortcut: assume 1 cert == 1 certificate) + PublicCertificateI cert = from.findCertificate(company, sharePerCert/shareUnit, false); + if (cert == null) { + log.fatal("Cannot find "+sharePerCert+"% of "+company.getName()+" in "+from.getName()); + } if (!currentSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, number * cert.getCertificateCount())) { errMsg = @@ -791,7 +797,7 @@ // All seems OK, now buy the shares. moveStack.start(true); - CashHolder priceRecipient = getSharePriceRecipient (cert, cost); + CashHolder priceRecipient = getSharePriceRecipient (company, from, cost); if (number == 1) { ReportBuffer.add(LocalText.getText("BUY_SHARE_LOG", @@ -814,9 +820,9 @@ PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, cert.getShares(), false); + cert2 = from.findCertificate(company, sharePerCert/shareUnit, false); if (cert2 == null) { - log.error("Cannot find " + companyName + " " + shareUnit + log.error("Cannot find " + companyName + " " + shareUnit*sharePerCert + "% share in " + from.getName()); } cert2.moveTo(currentPlayer.getPortfolio()); @@ -864,17 +870,16 @@ * @param cert * @return */ - protected CashHolder getSharePriceRecipient (PublicCertificateI cert, int price) { + protected CashHolder getSharePriceRecipient (PublicCompanyI comp, + Portfolio from, int price) { - Portfolio oldHolder = (Portfolio) cert.getHolder(); - PublicCompanyI comp; CashHolder recipient; - if ((comp = (cert).getCompany()).hasFloated() - && oldHolder == ipo + if (comp.hasFloated() + && from == ipo && comp.getCapitalisation() == PublicCompanyI.CAPITALISE_INCREMENTAL) { recipient = comp; } else { - recipient = oldHolder.getOwner(); + recipient = from.getOwner(); } return recipient; } Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -141,7 +141,7 @@ number--; if (number > 0) { - possibleActions.add(new BuyCertificate(cert, from, price, + possibleActions.add(new BuyCertificate(comp, cert.getShare(), from, price, number)); } } @@ -240,16 +240,16 @@ @Override public boolean buyShares(String playerName, BuyCertificate action) { - PublicCertificateI cert = action.getCertificate(); - Portfolio from = cert.getPortfolio(); - String companyName = cert.getCompany().getName(); + PublicCompanyI company = action.getCompany(); + Portfolio from = action.getFromPortfolio(); + String companyName = company.getName(); int number = action.getNumberBought(); - int shares = number * cert.getShares(); - int shareUnit = cert.getShare(); + int shareUnit = company.getShareUnit(); + int sharePerCert = action.getSharePerCertificate(); + int shares = number * sharePerCert; String errMsg = null; int price = 0; - PublicCompanyI company = null; Portfolio portfolio = null; currentPlayer = getCurrentPlayer(); @@ -359,7 +359,7 @@ moveStack.start(true); PublicCertificateI cert2; for (int i = 0; i < number; i++) { - cert2 = from.findCertificate(company, cert.getShares(), false); + cert2 = from.findCertificate(company, sharePerCert, false); executeTradeCertificate(cert2, portfolio, cert2.getShares() * price); } Modified: trunk/18xx/rails/game/action/BuyCertificate.java =================================================================== --- trunk/18xx/rails/game/action/BuyCertificate.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/action/BuyCertificate.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -16,10 +16,22 @@ public class BuyCertificate extends PossibleAction { // Server-side settings - transient protected PublicCertificateI certificate; - protected String certUniqueId; + + /* Some obsolete properties, which are only retained for backwards compatibility + * (i.e. to remain able to load older saved files). + * The certificate was in fact only used to find the below replacement + * attributes. It was NOT actually used to select the bought certificate! + */ + transient protected PublicCertificateI certificate = null; + protected String certUniqueId = null; + + /* Replacement for the above.*/ + transient protected PublicCompanyI company; + protected String companyName; + protected int sharePerCert; // Share % per buyable certificate. + transient protected Portfolio from; - protected String fromName; + protected String fromName; // Old: portfolio name. New: portfolio unique name. protected int price; protected int maximumNumber; @@ -28,30 +40,24 @@ public static final long serialVersionUID = 1L; - /** - * Common constructor. - */ - public BuyCertificate(PublicCertificateI certificate, Portfolio from, + public BuyCertificate(PublicCompanyI company, int sharePerCert, + Portfolio from, int price, int maximumNumber) { - this.certificate = certificate; - this.certUniqueId = certificate.getUniqueId(); // TODO: Must be - // replaced by a unique - // Id! + this.company = company; + this.sharePerCert = sharePerCert; this.from = from; - this.fromName = from.getName(); + this.fromName = from.getUniqueName(); this.price = price; this.maximumNumber = maximumNumber; + + companyName = company.getName(); } - /** Buy a certificate from some portfolio at the current price */ - //public BuyCertificate(PublicCertificateI certificate, Portfolio from) { - // this(certificate, from, certificate.getCertificatePrice(), 1); - //} - /** Buy a certificate from some portfolio at a given price */ - public BuyCertificate(PublicCertificateI certificate, Portfolio from, + public BuyCertificate(PublicCompanyI company, int sharePerCert, + Portfolio from, int price) { - this(certificate, from, price, 1); + this(company, sharePerCert, from, price, 1); } /** Required for deserialization */ @@ -61,10 +67,6 @@ return from; } - public String getFromName() { - return fromName; - } - /** * @return Returns the maximumNumber. */ @@ -79,13 +81,22 @@ return price; } - /** - * @return Returns the certificate. - */ - public PublicCertificateI getCertificate() { - return certificate; + public PublicCompanyI getCompany() { + return company; } + public String getCompanyName() { + return companyName; + } + + public int getSharePerCertificate() { + return sharePerCert; + } + + public int getSharesPerCertificate() { + return sharePerCert / company.getShareUnit(); + } + public int getNumberBought() { return numberBought; } @@ -106,26 +117,46 @@ public String toString() { StringBuffer text = new StringBuffer(); text.append("BuyCertificate: "); - if (numberBought > 1) { - text.append(numberBought).append(" of "); - } else if (numberBought == 0 && maximumNumber > 1) { - text.append("up to ").append(maximumNumber).append(" of "); - } - text.append(certificate.getName()).append(" from ").append( - from.getName()).append(" price=").append( - Bank.format(certificate.getShares() * price)); + if (acted) text.append("Bought "+numberBought +" of "); + if (maximumNumber > 1) text.append ("max."+maximumNumber+" of "); + text.append(sharePerCert).append("% ").append(companyName) + .append(" from ").append(from.getName()) + .append(" price=").append(Bank.format((sharePerCert/company.getShareUnit()) * price)); return text.toString(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); + //in.defaultReadObject(); + // Custom reading for backwards compatibility + ObjectInputStream.GetField fields = in.readFields(); + certUniqueId = (String) fields.get("certUniqueId", null); + companyName = (String) fields.get("companyName", null); + fromName = (String) fields.get("fromName", fromName); + price = fields.get("price", price); + maximumNumber = fields.get("maximumNumber", maximumNumber); + sharePerCert = fields.get("sharePerCert", -1); + + numberBought = fields.get("numberBought", numberBought); + GameManagerI gameManager = GameManager.getInstance(); - certificate = PublicCertificate.getByUniqueId(certUniqueId); - from = gameManager.getPortfolioByName(fromName); + if (certUniqueId != null) { + // Old style + certificate = PublicCertificate.getByUniqueId(certUniqueId); + from = gameManager.getPortfolioByName(fromName); + company = certificate.getCompany(); + companyName = company.getName(); + sharePerCert = certificate.getShare(); + } else if (companyName != null) { + // New style (since Rails.1.3.1) + company = gameManager.getCompanyManager().getPublicCompany(companyName); + from = gameManager.getPortfolioByUniqueName(fromName); + // We don't need the certificate anymore. + } + } } Modified: trunk/18xx/rails/game/action/StartCompany.java =================================================================== --- trunk/18xx/rails/game/action/StartCompany.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/action/StartCompany.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -9,24 +9,28 @@ public static final long serialVersionUID = 1L; - public StartCompany(PublicCertificateI certificate, int[] prices, + public StartCompany(PublicCompanyI company, int[] prices, int maximumNumber) { - super(certificate, GameManager.getInstance().getBank().getIpo(), 0, maximumNumber); + super(company, company.getPresidentsShare().getShare(), + GameManager.getInstance().getBank().getIpo(), + 0, maximumNumber); this.startPrices = prices.clone(); } - public StartCompany(PublicCertificateI certificate, int[] startPrice) { - this(certificate, startPrice, 1); + public StartCompany(PublicCompanyI company, int[] startPrice) { + this(company, startPrice, 1); } - public StartCompany(PublicCertificateI certificate, int price, + public StartCompany(PublicCompanyI company, int price, int maximumNumber) { - super(certificate, GameManager.getInstance().getBank().getIpo(), 0, maximumNumber); + super(company, company.getPresidentsShare().getShare(), + GameManager.getInstance().getBank().getIpo(), + 0, maximumNumber); this.price = price; } - public StartCompany(PublicCertificateI certificate, int price) { - this(certificate, price, 1); + public StartCompany(PublicCompanyI company, int price) { + this(company, price, 1); } public int[] getStartPrices() { @@ -44,7 +48,7 @@ @Override public String toString() { StringBuffer text = new StringBuffer(); - text.append("StartCompany: ").append(certificate.getName()); + text.append("StartCompany: ").append(company.getName()); if (price > 0) { text.append(" price=").append(Bank.format(price)); if (numberBought > 1) { Modified: trunk/18xx/rails/game/move/ObjectMove.java =================================================================== --- trunk/18xx/rails/game/move/ObjectMove.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/move/ObjectMove.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -5,6 +5,8 @@ */ package rails.game.move; +import rails.util.Util; + /** * @author Erik Vos */ @@ -77,9 +79,18 @@ if (moveableObject == null) log.error("Token is null"); if (from == null) log.warn("From is null"); if (to == null) log.error("To is null"); - return "Move " + objectClassName + ": " + moveableObject.getName() - + " from " + (from == null ? from : from.getName()) + "["+fromPosition - + "] to " + to.getName() + "["+toPosition+"]"; + StringBuilder buf = new StringBuilder(); + + buf.append("Move ").append(objectClassName).append(": ").append(moveableObject.getName()) + .append(" from ").append(from == null ? from : from.getName()); + if (fromPosition != null) { + buf.append("[").append(Util.joinWithDelimiter(fromPosition, ",")).append("]"); + } + buf.append(" to ").append(to == null ? to : to.getName()); + if (toPosition != null) { + buf.append("[").append(Util.joinWithDelimiter(toPosition, ",")).append("]"); + } + return buf.toString(); } } Modified: trunk/18xx/rails/game/specific/_1835/StockRound_1835.java =================================================================== --- trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_1835/StockRound_1835.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -12,7 +12,7 @@ import rails.util.LocalText; public class StockRound_1835 extends StockRound { - + /** * Constructor with the GameManager, will call super class (StockRound's) Constructor to initialize * @@ -22,19 +22,21 @@ public StockRound_1835 (GameManagerI aGameManager) { super (aGameManager); } - + /** Add nationalisations */ + @Override protected void setGameSpecificActions() { if (!mayCurrentPlayerBuyAnything()) return; if (companyBoughtThisTurnWrapper.getObject() != null) return; - + List<Player> otherPlayers = new ArrayList<Player>(); Portfolio holder; CashHolder owner; Player otherPlayer; int price; int cash = currentPlayer.getCash(); - + + // Nationalization for (PublicCompanyI company : companyManager.getAllPublicCompanies()) { if (!company.getTypeName().equalsIgnoreCase("Major")) continue; if (!company.hasFloated()) continue; @@ -49,7 +51,8 @@ if (!otherPlayers.contains(otherPlayer)) { price = (int)(1.5 * company.getCurrentPriceModel().getPrice().getPrice()); if (price <= cash) { - possibleActions.add(new BuyCertificate (cert, holder, + possibleActions.add(new BuyCertificate (company, cert.getShare(), + holder, (int)(1.5 * company.getCurrentPriceModel().getPrice().getPrice()), 1)); } @@ -61,10 +64,12 @@ } } + @Override public boolean checkAgainstHoldLimit(Player player, PublicCompanyI company, int number) { return true; } + @Override protected int getBuyPrice (BuyCertificate action, StockSpaceI currentSpace) { int price = currentSpace.getPrice(); if (action.getFromPortfolio().getOwner() instanceof Player) { @@ -72,9 +77,10 @@ } return price; } - + /** Share price goes down 1 space for any number of shares sold. */ + @Override protected void adjustSharePrice (PublicCompanyI company, int numberSold, boolean soldBefore) { // No more changes if it has already dropped if (!soldBefore) { Modified: trunk/18xx/rails/game/specific/_1856/StockRound_1856.java =================================================================== --- trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_1856/StockRound_1856.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -85,16 +85,15 @@ } @Override - protected CashHolder getSharePriceRecipient(PublicCertificateI cert, int cost) { + protected CashHolder getSharePriceRecipient(PublicCompanyI company, Portfolio from, int price) { CashHolder recipient; - Portfolio oldHolder = (Portfolio) cert.getHolder(); - if (cost != 0 - && !cert.getCompany().getName().equalsIgnoreCase(PublicCompany_CGR.NAME) - && oldHolder == ipo) { + if (price != 0 + && !company.getName().equalsIgnoreCase(PublicCompany_CGR.NAME) + && from == ipo) { - PublicCompany_1856 comp = (PublicCompany_1856)(cert).getCompany(); + PublicCompany_1856 comp = (PublicCompany_1856)company; switch (comp.getTrainNumberAvailableAtStart()) { case 2: @@ -104,9 +103,9 @@ if (getSoldPercentage(comp) >= 50 && !comp.hasReachedDestination()) { recipient = bank; - comp.addMoneyInEscrow(cost); + comp.addMoneyInEscrow(price); ReportBuffer.addWaiting(LocalText.getText("HoldMoneyInEscrow", - Bank.format(cost), + Bank.format(price), Bank.format(comp.getMoneyInEscrow()), comp.getName() )); break; @@ -120,7 +119,7 @@ recipient = bank; } } else { - recipient = oldHolder.getOwner(); + recipient = from.getOwner(); } return recipient; } @@ -183,10 +182,10 @@ } else { // Player has enough cash if (cert1 != null && price1 <= cash) { - possibleActions.add(new BuyCertificate(cert1, ipo, price1)); + possibleActions.add(new BuyCertificate(cgr, 1, ipo, price1)); } if (cert2 != null && price2 <= cash) { - possibleActions.add(new BuyCertificate(cert2, pool, price2)); + possibleActions.add(new BuyCertificate(cgr, 1, pool, price2)); } } Modified: trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -29,8 +29,8 @@ public static final long serialVersionUID = 1L; - public StartCompany_18EU(PublicCertificateI certificate, int[] prices) { - super(certificate, prices, 1); + public StartCompany_18EU(PublicCompanyI company, int[] prices) { + super(company, prices, 1); } public void setMinorsToMerge(List<PublicCompanyI> minors) { Modified: trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/game/specific/_18EU/StockRound_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -149,7 +149,7 @@ prices[i] = startPrices.get(i); } StartCompany_18EU action = - new StartCompany_18EU(cert, prices); + new StartCompany_18EU(comp, prices); if (mustMergeMinor) { action.setMinorsToMerge(minors); } else { @@ -158,7 +158,8 @@ possibleActions.add(action); } } else if (comp.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, from, + possibleActions.add(new BuyCertificate(comp, cert.getShare(), + from, comp.getMarketPrice())); } @@ -187,7 +188,7 @@ // Does the player have enough cash? if (playerCash < price) continue; - possibleActions.add(new BuyCertificate(cert, from, price, 1)); + possibleActions.add(new BuyCertificate(comp, cert.getShare(), from, price, 1)); } // Get any shares in company treasuries that can be bought @@ -207,7 +208,7 @@ if (!stockSpace.isNoCertLimit() && !mayPlayerBuyCertificate(currentPlayer, company, 1)) continue; if (company.getMarketPrice() <= playerCash) { - possibleActions.add(new BuyCertificate(cert, + possibleActions.add(new BuyCertificate(company, cert.getShare(), company.getPortfolio(), company.getMarketPrice())); } @@ -271,7 +272,7 @@ */ @Override public boolean startCompany(String playerName, StartCompany action) { - PublicCompanyI company = action.getCertificate().getCompany(); + PublicCompanyI company = action.getCompany(); int price = action.getPrice(); int shares = action.getNumberBought(); Modified: trunk/18xx/rails/ui/swing/GameStatus.java =================================================================== --- trunk/18xx/rails/ui/swing/GameStatus.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/GameStatus.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -509,14 +509,14 @@ addField(futureTrains, futureTrainsXOffset, futureTrainsYOffset, futureTrainsWidth, 1, 0, true); - // Train cost overview + // Train cost overview String text = gameUIManager.getGameManager().getTrainManager().getTrainCostOverview(); addField (new Caption(text), poolTrainsXOffset, newTrainsYOffset + 1, futureTrainsWidth + 2, 1, 0, true); dummyButton = new ClickField("", "", "", this, buySellGroup); } - + public void actionPerformed(ActionEvent actor) { JComponent source = (JComponent) actor.getSource(); List<PossibleAction> actions; @@ -589,13 +589,19 @@ PublicCertificateI cert; String companyName = ""; String playerName = ""; + int sharePerCert; + int sharesPerCert; + int shareUnit; for (PossibleAction action : actions) { buy = (BuyCertificate) action; - cert = buy.getCertificate(); + //cert = buy.getCertificate(); playerName = buy.getPlayerName (); - PublicCompanyI company = cert.getCompany(); + PublicCompanyI company = buy.getCompany(); companyName = company.getName(); + sharePerCert = buy.getSharePerCertificate(); + shareUnit = company.getShareUnit(); + sharesPerCert = sharePerCert / shareUnit; if (buy instanceof StartCompany) { @@ -608,9 +614,8 @@ for (int i = 0; i < startPrices.length; i++) { options.add(LocalText.getText("StartCompany", Bank.format(startPrices[i]), - cert.getShare(), - Bank.format(cert.getShares() - * startPrices[i]) )); + sharePerCert, + Bank.format(sharesPerCert * startPrices[i]) )); buyActions.add(buy); buyAmounts.add(startPrices[i]); } @@ -618,7 +623,7 @@ startPrices = new int[] {((StartCompany) buy).getPrice()}; options.add(LocalText.getText("StartCompanyFixed", companyName, - cert.getShare(), + sharePerCert, Bank.format(startPrices[0]) )); buyActions.add(buy); buyAmounts.add(startPrices[0]); @@ -627,20 +632,19 @@ } else { options.add(LocalText.getText("BuyCertificate", - cert.getShare(), - cert.getCompany().getName(), - cert.getPortfolio().getName(), - Bank.format(cert.getShares() - * buy.getPrice()) )); + sharePerCert, + companyName, + buy.getFromPortfolio().getName(), + Bank.format(sharesPerCert * buy.getPrice()) )); buyActions.add(buy); buyAmounts.add(1); for (int i = 2; i <= buy.getMaximumNumber(); i++) { options.add(LocalText.getText("BuyCertificates", i, - cert.getShare(), - cert.getCompany().getName(), - cert.getPortfolio().getName(), - Bank.format(i * cert.getShares() + sharePerCert, + companyName, + buy.getFromPortfolio().getName(), + Bank.format(i * sharesPerCert * buy.getPrice()) )); buyActions.add(buy); buyAmounts.add(i); @@ -683,7 +687,7 @@ } else if (startCompany) { chosenAction = buyActions.get(index); ((StartCompany) chosenAction).setStartPrice(buyAmounts.get(index)); - ((StartCompany) chosenAction).setNumberBought(((StartCompany) chosenAction).getCertificate().getShares()); + ((StartCompany) chosenAction).setNumberBought(((StartCompany) chosenAction).getSharesPerCertificate()); } else { chosenAction = buyActions.get(index); ((BuyCertificate) chosenAction).setNumberBought(buyAmounts.get(index)); @@ -767,7 +771,7 @@ treasurySharesCaption.setHighlight(true); } - PublicCertificateI cert; + PublicCompanyI company; Portfolio holder; int index; CashHolder owner; @@ -776,8 +780,8 @@ possibleActions.getType(BuyCertificate.class); if (buyableCerts != null) { for (BuyCertificate bCert : buyableCerts) { - cert = bCert.getCertificate(); - index = cert.getCompany().getPublicNumber(); + company = bCert.getCompany(); + index = company.getPublicNumber(); holder = bCert.getFromPortfolio(); owner = holder.getOwner(); if (holder == ipo) { @@ -792,7 +796,6 @@ } } - PublicCompanyI company; List<SellShares> sellableShares = possibleActions.getType(SellShares.class); if (sellableShares != null) { @@ -831,7 +834,7 @@ * Initializes the CashCorrectionActions */ public boolean initCashCorrectionActions() { - + // Clear all buttons for (int i = 0; i < nc; i++) { setCompanyCashButton(i, false, null); @@ -839,7 +842,7 @@ for (int j = 0; j < np; j++) { setPlayerCashButton(j, false, null); } - + List<CashCorrectionAction> actions = possibleActions.getType(CashCorrectionAction.class); @@ -860,9 +863,9 @@ } return (actions != null && !actions.isEmpty()); - + } - + public void setPriorityPlayer(int index) { for (int j = 0; j < np; j++) { @@ -990,7 +993,7 @@ } playerCash[i].setVisible(!clickable); playerCashButton[i].setVisible(clickable); - + if (action != null) playerCashButton[i].addPossibleAction(action); } Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -130,7 +130,7 @@ } if (font != null) log.debug("Change text fonts globally to " + font.getName() + " / " + (boldStyle ? "Bold" : "Plain")); } - + String fontScale = Config.getGameSpecific("font.ui.scale"); if (Util.hasValue(fontScale)) { try { @@ -143,13 +143,13 @@ } public void gameUIInit() { - + imageLoader = new ImageLoader(); stockChart = new StockChart(this); reportWindow = new ReportWindow(gameManager); orWindow = new ORWindow(this); orUIManager = orWindow.getORUIManager(); - + String statusWindowClassName = getClassName(GuiDef.ClassName.STATUS_WINDOW); try { Class<? extends StatusWindow> statusWindowClass = @@ -230,7 +230,7 @@ // // return true; // -// } +// } // else if (gameManager.getBank().isJustBroken()) { // // statusWindow.reportBankBroken(); @@ -252,7 +252,7 @@ return true; } } - + // display the end of game report if (gameManager.isGameOver()) statusWindow.endOfGameReport(); @@ -412,8 +412,8 @@ orWindow.setVisible(true); orWindow.toFront(); } - - + + // Update the currently visible round window // "Switchable" rounds will be handled from subclasses of this class. if (StartRoundWindow.class.isAssignableFrom(activeWindow.getClass())) { @@ -554,7 +554,7 @@ public void dialogActionPerformed (boolean ready) { if (!ready) { - + if (checkGameSpecificDialogAction()) { ; } else if (currentDialog instanceof RadioButtonDialog @@ -567,7 +567,7 @@ if (index >= 0) { int price = action.getStartPrices()[index]; action.setStartPrice(price); - action.setNumberBought(action.getCertificate().getShares()); + action.setNumberBought(action.getSharesPerCertificate()); } else { // No selection done - no action return; @@ -669,12 +669,12 @@ if(font != null) { float newSize = font.getSize2D() * (float)scale; UIManager.put(key, new FontUIResource(font.deriveFont(newSize))); - } - } - } + } + } + } } - - + + public void exportGame(GameAction exportAction) { JFileChooser jfc = new JFileChooser(); String filename; @@ -699,8 +699,8 @@ processOnServer(exportAction); } } - - + + public void saveGame(GameAction saveAction) { JFileChooser jfc = new JFileChooser(); Modified: trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java =================================================================== --- trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -76,7 +76,7 @@ LocalText.getText("PleaseSelect"), LocalText.getText( "SelectMinorToMerge", - action.getCertificate().getCompany().getName()), + action.getCompanyName()), options, -1); setCurrentDialog(dialog, action); return; @@ -93,7 +93,7 @@ LocalText.getText("PleaseSelect"), LocalText.getText( "SelectHomeStation", - action.getCertificate().getCompany().getName()), + action.getCompanyName()), options, -1); setCurrentDialog(dialog, action); return; Modified: trunk/18xx/rails/util/Util.java =================================================================== --- trunk/18xx/rails/util/Util.java 2010-07-21 18:45:07 UTC (rev 1353) +++ trunk/18xx/rails/util/Util.java 2010-07-23 20:05:34 UTC (rev 1354) @@ -42,6 +42,15 @@ return b.toString(); } + public static String joinWithDelimiter (int[] sa, String delimiter) { + StringBuilder b = new StringBuilder(); + for (int s : sa) { + if (b.length() > 0) b.append(delimiter); + b.append(s); + } + return b.toString(); + } + public static int parseInt(String value) throws ConfigurationException { if (!hasValue(value)) return 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-21 18:45:14
|
Revision: 1353 http://rails.svn.sourceforge.net/rails/?rev=1353&view=rev Author: stefanfrey Date: 2010-07-21 18:45:07 +0000 (Wed, 21 Jul 2010) Log Message: ----------- Fixed bug that station for token might not exist yet, thus delayed interpretation of station to lay token in startcompany Modified Paths: -------------- trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java Modified: trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-21 18:43:52 UTC (rev 1352) +++ trunk/18xx/rails/game/specific/_18EU/StartCompany_18EU.java 2010-07-21 18:45:07 UTC (rev 1353) @@ -78,6 +78,15 @@ } public City getSelectedHomeStation() { + // use delayed selectedHomeStation initialization + // as not all cities are defined immediately + if (selectedHomeStation == null && selectedHomeStationName != null) { + MapManager mapManager = GameManager.getInstance().getMapManager(); + String[] parts = parseStationName (selectedHomeStationName); + MapHex hex = mapManager.getHex(parts[0]); + selectedHomeStation = hex.getCity(Integer.parseInt(parts[1])); + } + return selectedHomeStation; } @@ -130,11 +139,7 @@ availableHomeStations.add (hex.getCity(Integer.parseInt(parts[1]))); } } - if (selectedHomeStationName != null) { - String[] parts = parseStationName (selectedHomeStationName); - MapHex hex = mapManager.getHex(parts[0]); - selectedHomeStation = hex.getCity(Integer.parseInt(parts[1])); - } + // selectedHomeStation is delayed } private String[] parseStationName (String name) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-21 18:43:58
|
Revision: 1352 http://rails.svn.sourceforge.net/rails/?rev=1352&view=rev Author: stefanfrey Date: 2010-07-21 18:43:52 +0000 (Wed, 21 Jul 2010) Log Message: ----------- Activated delayed logger ListandFixSavedFiles Modified Paths: -------------- trunk/18xx/rails/util/ListAndFixSavedFiles.java Modified: trunk/18xx/rails/util/ListAndFixSavedFiles.java =================================================================== --- trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-19 20:52:17 UTC (rev 1351) +++ trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-21 18:43:52 UTC (rev 1352) @@ -47,6 +47,9 @@ // intialize configuration Config.setConfigSelection(); + + // delayed setting of logger + log = Logger.getLogger(ListAndFixSavedFiles.class.getPackage().getName()); saveDirectory = Config.get("save.directory"); System.out.println("Save directory = " + saveDirectory); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-19 20:52:25
|
Revision: 1351 http://rails.svn.sourceforge.net/rails/?rev=1351&view=rev Author: stefanfrey Date: 2010-07-19 20:52:17 +0000 (Mon, 19 Jul 2010) Log Message: ----------- Further update of configuration mechanism Modified Paths: -------------- trunk/18xx/data/Properties.xml trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/ui/swing/GameUIManager.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/test/test.properties Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-07-18 17:24:36 UTC (rev 1350) +++ trunk/18xx/data/Properties.xml 2010-07-19 20:52:17 UTC (rev 1351) @@ -4,8 +4,12 @@ --> <Properties> <Panel name="General"> - <Property name="locale" type="LIST" values="en_US,de" /> + <Property name="locale" type="LIST" values="en_US,te_ST" helpText="Language Selection" /> </Panel> + <Panel name="Save"> + <Property name="save.dir" type="DIRECTORY" helpText="Default save file directory" /> + + </Panel> <Panel name="Colors"> <Property name="route.colour.1" type="COLOR"/> </Panel> Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-18 17:24:36 UTC (rev 1350) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-19 20:52:17 UTC (rev 1351) @@ -2,13 +2,18 @@ import java.awt.Color; import java.awt.EventQueue; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; import java.awt.GridLayout; +import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.io.File; import java.util.Map; import java.util.List; @@ -19,6 +24,7 @@ import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; +import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; @@ -26,6 +32,7 @@ import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; +import javax.swing.WindowConstants; import javax.swing.border.Border; import rails.game.ConfigurationException; @@ -38,7 +45,7 @@ private static final long serialVersionUID = 1L; private static final String CONFIG_EXTENSION = ".rails_config"; - private static final String CONFIG_DESCRIPTION = "Rails configuration files (.rails_config)"; + private static final String CONFIG_DESCRIPTION = "Rails configuration files ( *.rails_config )"; private JPanel profilePanel; private JTabbedPane configPane; @@ -61,10 +68,17 @@ buttonPanel = new JPanel(); add(buttonPanel, "South"); - init(); + // hide on close and inform + this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + cancelConfig(); + } + }); } - private void init() { + public void init() { setupProfilePanel(); setupConfigPane(); setupButtonPanel(); @@ -94,7 +108,9 @@ ); profilePanel.add(comboBoxUser); - // new button + JPanel buttonPanel = new JPanel(); + + // button to create a new profile JButton newButton = new JButton(LocalText.getText("NEW")); newButton.addActionListener( new ActionListener() { @@ -103,7 +119,20 @@ } } ); - profilePanel.add(newButton); + buttonPanel.add(newButton); + + // button to load a new profile + JButton loadButton = new JButton(LocalText.getText("LOAD")); + loadButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + loadProfile(); + } + } + ); + buttonPanel.add(loadButton); + + profilePanel.add(buttonPanel); } @@ -118,75 +147,123 @@ for (String panelName:configPanels.keySet()) { JPanel newPanel = new JPanel(); - newPanel.setLayout(new GridLayout(0,3)); + newPanel.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridwidth = 1; + gbc.gridheight = 1; + gbc.gridx = 0; + gbc.weightx = 0.8; + gbc.weighty = 0.8; + gbc.insets = new Insets(10,10,10,10); + gbc.anchor = GridBagConstraints.WEST; for (ConfigItem item:configPanels.get(panelName)) { - defineElement(newPanel, item); + gbc.gridx = 0; + defineElement(newPanel, item, gbc); + gbc.gridy ++; } configPane.addTab(panelName, newPanel); } } - private void defineElement(JPanel panel, final ConfigItem item) { - // item label - panel.add(new JLabel(LocalText.getText("Config." + item.name))); + + private void addToGridBag(JComponent container, JComponent element, GridBagConstraints gbc) { + container.add(element, gbc); + gbc.gridx ++; + } + + private void defineElement(JPanel panel, final ConfigItem item, GridBagConstraints gbc) { // standard components final String configValue = item.getCurrentValue(); + final String toolTip = item.helpText; + // item label + JLabel label = new JLabel(LocalText.getText("Config." + item.name)); + label.setToolTipText(toolTip); + gbc.fill = GridBagConstraints.NONE; + addToGridBag(panel, label, gbc); switch (item.type) { + case LIST: + final JComboBox comboBox = new JComboBox(item.allowedValues.toArray()); + comboBox.setSelectedItem(configValue); + comboBox.setToolTipText(toolTip); + comboBox.addFocusListener(new FocusListener() { + public void focusGained(FocusEvent arg0) { + // do nothing + } + public void focusLost(FocusEvent arg0) { + item.setNewValue((String)comboBox.getSelectedItem()); + } + } + ); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, comboBox, gbc); + break; + case DIRECTORY: + final JLabel dirLabel = new JLabel(configValue); + dirLabel.setHorizontalAlignment(SwingConstants.CENTER); + dirLabel.setToolTipText(toolTip); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, dirLabel, gbc); + JButton dirButton = new JButton("Choose..."); + dirButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + JFileChooser fc = new JFileChooser(dirLabel.getText()); + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int state = fc.showOpenDialog(ConfigWindow.this); + if ( state == JFileChooser.APPROVE_OPTION ){ + File file = fc.getSelectedFile(); + dirLabel.setText(file.getAbsolutePath()); + item.setNewValue(file.getAbsolutePath()); + } + } + } + ); + gbc.fill = GridBagConstraints.NONE; + addToGridBag(panel, dirButton, gbc); + break; case COLOR: - final JLabel label = new JLabel(configValue); + final JLabel colorLabel = new JLabel(configValue); Color selectedColor; try { selectedColor = Util.parseColour(configValue); } catch (ConfigurationException e) { selectedColor = Color.WHITE; } - label.setOpaque(true); - label.setHorizontalAlignment(SwingConstants.CENTER); - label.setBackground(selectedColor); + colorLabel.setOpaque(true); + colorLabel.setHorizontalAlignment(SwingConstants.CENTER); + colorLabel.setBackground(selectedColor); if (Util.isDark(selectedColor)) { - label.setForeground(Color.WHITE); + colorLabel.setForeground(Color.WHITE); } else { - label.setForeground(Color.BLACK); + colorLabel.setForeground(Color.BLACK); } - panel.add(label); - JButton button = new JButton("Choose..."); - final Color oldColor = selectedColor; - button.addActionListener( + colorLabel.setToolTipText(toolTip); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, colorLabel, gbc); + JButton colorButton = new JButton("Choose..."); + colorButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { - Color selectedColor=JColorChooser.showDialog(ConfigWindow.this, "", oldColor); + Color selectedColor=JColorChooser.showDialog(ConfigWindow.this, "", colorLabel.getBackground()); if (selectedColor == null) return; String newValue = Integer.toHexString(selectedColor.getRGB()).substring(3); - label.setText(newValue); + colorLabel.setText(newValue); item.setNewValue(newValue); - label.setBackground(selectedColor); + colorLabel.setBackground(selectedColor); if (Util.isDark(selectedColor)) { - label.setForeground(Color.WHITE); + colorLabel.setForeground(Color.WHITE); } else { - label.setForeground(Color.BLACK); + colorLabel.setForeground(Color.BLACK); } } } ); - panel.add(button); + gbc.fill = GridBagConstraints.NONE; + addToGridBag(panel, colorButton, gbc); break; - case LIST: - final JComboBox comboBox = new JComboBox(item.allowedValues.toArray()); - comboBox.setSelectedItem(configValue); - comboBox.addFocusListener(new FocusListener() { - public void focusGained(FocusEvent arg0) { - // do nothing - } - public void focusLost(FocusEvent arg0) { - item.setNewValue((String)comboBox.getSelectedItem()); - } - } - ); - panel.add(comboBox); - break; case STRING: default: // default like String final JFormattedTextField textField = new JFormattedTextField(); @@ -200,7 +277,8 @@ } } ); - panel.add(textField); + gbc.fill = GridBagConstraints.HORIZONTAL; + addToGridBag(panel, textField, gbc); break; } } @@ -262,6 +340,31 @@ }); } + private void loadProfile() { + String directory = Config.get("save.directory"); + + JFileChooser fc = new JFileChooser(directory); + fc.setFileFilter( + new FileFilter() { + public boolean accept( File f ){ + return f.isDirectory() || + f.getName().toLowerCase().endsWith( ".rails_config" ); + } + public String getDescription() { + return CONFIG_DESCRIPTION; + } + } + ); + int state = fc.showOpenDialog(this); + if ( state == JFileChooser.APPROVE_OPTION ) + { + File file = fc.getSelectedFile(); + if (Config.loadProfileFromFile(file)) { + changeProfile(Config.getActiveProfileName()); + } + } + } + private void changeProfile(String profileName) { Config.changeActiveProfile(profileName); EventQueue.invokeLater(new Runnable() { @@ -273,7 +376,10 @@ } private void saveConfig() { + Config.updateProfile(); // transfer the configitem to the active profile Config.saveActiveProfile(); + JOptionPane.showMessageDialog(ConfigWindow.this, LocalText.getText("CONFIG_SAVE_MESSAGE"), + LocalText.getText("CONFIG_SAVE_TITLE"), JOptionPane.INFORMATION_MESSAGE); } private void saveAsConfig() { @@ -303,12 +409,19 @@ File file = fc.getSelectedFile(); Config.setActiveFilepath(file.getPath()); saveConfig(); - setupButtonPanel(); + EventQueue.invokeLater(new Runnable() { + public void run() { + setupButtonPanel(); + ConfigWindow.this.pack(); + ConfigWindow.this.repaint(); + } + }); } } private void cancelConfig() { - this.dispose(); + StatusWindow.uncheckMenuItemBox(StatusWindow.CONFIG_CMD); + this.setVisible(false); } } Modified: trunk/18xx/rails/ui/swing/GameUIManager.java =================================================================== --- trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-18 17:24:36 UTC (rev 1350) +++ trunk/18xx/rails/ui/swing/GameUIManager.java 2010-07-19 20:52:17 UTC (rev 1351) @@ -1,6 +1,9 @@ package rails.ui.swing; import java.awt.Font; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; import java.io.File; import java.text.SimpleDateFormat; import java.util.*; @@ -26,6 +29,7 @@ public StockChart stockChart; public StatusWindow statusWindow; public ReportWindow reportWindow; + public ConfigWindow configWindow; public ORUIManager orUIManager; public ORWindow orWindow; // TEMPORARY private StartRoundWindow startRoundWindow; @@ -151,6 +155,13 @@ Class<? extends StatusWindow> statusWindowClass = Class.forName(statusWindowClassName).asSubclass(StatusWindow.class); statusWindow = statusWindowClass.newInstance(); + +// GraphicsEnvironment ge = GraphicsEnvironment. +// getLocalGraphicsEnvironment(); +// GraphicsDevice[] gs = ge.getScreenDevices(); +// log.debug("ScreenDevices = " + Arrays.toString(gs)); +// statusWindow = statusWindowClass.getConstructor(GraphicsConfiguration.class).newInstance(gs[1].getDefaultConfiguration()); + statusWindow.init(this); } catch (Exception e) { log.fatal("Cannot instantiate class " + statusWindowClassName, e); @@ -160,6 +171,10 @@ updateUI(); reportWindow.scrollDown(); + + // define configWindow + configWindow = new ConfigWindow(); + configWindow.init(); } public void startLoadedGame() { Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-18 17:24:36 UTC (rev 1350) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-19 20:52:17 UTC (rev 1351) @@ -608,9 +608,7 @@ } else if (command.equals(MAP_CMD)) { gameUIManager.orWindow.setVisible(((JMenuItem) actor.getSource()).isSelected()); } else if (command.equals(CONFIG_CMD)) { - JFrame configWindow = new ConfigWindow(); - configWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - configWindow.setVisible(true); + gameUIManager.configWindow.setVisible(((JMenuItem) actor.getSource()).isSelected()); } else if (executedAction == null) { ; } else if (executedAction instanceof GameAction) { Modified: trunk/18xx/test/test.properties =================================================================== --- trunk/18xx/test/test.properties 2010-07-18 17:24:36 UTC (rev 1350) +++ trunk/18xx/test/test.properties 2010-07-19 20:52:17 UTC (rev 1351) @@ -17,7 +17,7 @@ # (implying a language variant of that country; no default). # Locale: concatenation of the above. If present, overrides any of the above. # Examples: en, en_US, en_UK, fr_FR, fr_CA. -locale=te_st0 +locale=te_st #language= #country= This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-18 17:24:42
|
Revision: 1350 http://rails.svn.sourceforge.net/rails/?rev=1350&view=rev Author: stefanfrey Date: 2010-07-18 17:24:36 +0000 (Sun, 18 Jul 2010) Log Message: ----------- Further updates to the configuration mechanism and integration of Eriks fix Modified Paths: -------------- trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/ConfigItem.java trunk/18xx/rails/util/LocalText.java Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-18 16:36:38 UTC (rev 1349) +++ trunk/18xx/rails/util/Config.java 2010-07-18 17:24:36 UTC (rev 1350) @@ -1,8 +1,18 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/util/Config.java,v 1.13 2010/06/24 21:48:08 stefanfrey Exp $*/ package rails.util; -import java.io.*; -import java.util.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import org.apache.log4j.Logger; @@ -35,7 +45,7 @@ /** Log 4j configuration */ private static final String LOG4J_CONFIG_FILE = "log4j.properties"; - + /** Rails profile configurations */ private static String defaultProfilesFile = "default.profiles"; private static Properties defaultProfiles = new Properties(); @@ -44,27 +54,28 @@ private static boolean profilesLoaded = false; private static final String TEST_PROFILE_SELECTION = "test"; private static final String DEFAULT_PROFILE_SELECTION = "default"; - private static final String DEFAULT_PROFILE_PROPERTY = "default.profile"; private static final String STANDARD_PROFILE_SELECTION = "user"; - + private static final String DEFAULTPROFILE_PROPERTY = "default.profile"; + private static final String PROFILENAME_PROPERTY = "profile.name"; + /** selected profile */ private static String selectedProfile; private static boolean legacyConfigFile; - + /** properties storage. */ private static Properties defaultProperties = new Properties(); private static Properties userProperties = new Properties(); private static boolean propertiesLoaded = false; - + /** Map that holds the panel, which contains config items */ - private static Map<String, List<ConfigItem>> configPanels = null; - + private static Map<String, List<ConfigItem>> configPanels = null; + /** * Hidden constructor, the class is never instantiated, everything is static */ private Config() {} - /** + /** * Reads the config.xml file that defines all config items */ public static void readConfigSetupXML() { @@ -75,7 +86,7 @@ Tag configTag = Tag.findTopTagInFile(CONFIG_XML_FILE, directories, CONFIG_TAG); log.debug("Opened config xml, filename = " + CONFIG_XML_FILE); - + configPanels = new LinkedHashMap<String, List<ConfigItem>>(); // find panels List<Tag> panelTags = configTag.getChildren(PANEL_TAG); @@ -84,7 +95,7 @@ // find name attribute String panelName = panelTag.getAttributeAsString("name"); if (!Util.hasValue(panelName)) continue; - + // find items List<Tag> itemTags = panelTag.getChildren(ITEM_TAG); if (itemTags == null || itemTags.size() == 0) continue; @@ -95,12 +106,12 @@ configPanels.put(panelName, panelItems); } } - + } catch (ConfigurationException e) { log.error("Configuration error in setup of "); } } - + public static Map<String, List<ConfigItem>> getConfigPanels() { if (configPanels == null) { readConfigSetupXML(); @@ -108,14 +119,28 @@ log.debug("Configuration setup = " + configPanels); return configPanels; } - + /** - * First tries to return {key}.{gameName}, if undefined returns {key} + * updates the profile according to the changes in configitems */ + public static void updateProfile() { + for (List<ConfigItem> items:configPanels.values()) { + for (ConfigItem item:items) { + if (!item.hasNewValue() || item.getNewValue().equals(defaultProperties.get(item.name))) continue; + userProperties.setProperty(item.name, item.getNewValue()); + log.debug("Changed property name = " + item.name + " to value = " + item.getNewValue()); + item.setNewValue(null); + } + } + } + + /** + * First tries to return {key}.{gameName}, if undefined returns {key} + */ public static String getGameSpecific(String key) { return Config.getSpecific(key, GameManager.getInstance().getGameName()); } - + /** * First tries to return {key}.{appendix}, if undefined returns {key} */ @@ -126,11 +151,11 @@ } return value; } - + public static String get(String key) { return get(key, ""); } - + public static String get(String key, String defaultValue) { if (defaultProperties.isEmpty() || !propertiesLoaded) { initialLoad(); @@ -140,19 +165,8 @@ return defaultValue; } + - - private static boolean storePropertyFile(Properties properties, String filepath) { - File outFile = new File(filepath); - boolean result = true; - try { - properties.store(new FileOutputStream(outFile), "Automatically generated, do not edit"); - } catch (IOException e) { - result = false; - } - return result; - } - /** * save active Profile */ @@ -164,38 +178,38 @@ return false; } } - + /** - * change active Profile + * change active Profile */ public static boolean changeActiveProfile(String profileName) { readConfigSetupXML(); - loadPropertyProfile(profileName); + loadProfile(profileName); selectedProfile = profileName; return true; } - + /** * create new profile */ public static boolean createUserProfile(String profileName, String defaultProfile) { userProperties = new Properties(); defaultProperties = new Properties(); - - + // add to list of user profiles userProfiles.setProperty(profileName, ""); // define and load default profile String defaultConfigFile = defaultProfiles.getProperty(defaultProfile); - userProperties.setProperty(DEFAULT_PROFILE_PROPERTY, defaultProfile); + userProperties.setProperty(PROFILENAME_PROPERTY, profileName); + userProperties.setProperty(DEFAULTPROFILE_PROPERTY, defaultProfile); loadPropertyFile(defaultProperties, defaultConfigFile, true); setSaveDirDefaults(); selectedProfile = profileName; return true; } - - + + private static Map<String, String> convertProperties(Properties properties) { Map<String, String> converted = new HashMap<String, String>(); for (Object key:properties.keySet()) { @@ -203,50 +217,50 @@ } return converted; } - - /** - * get all default profiles + + /** + * get all default profiles */ public static List<String> getDefaultProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); Collections.sort(profiles); return profiles; } - + public static String getDefaultProfileSelection() { return DEFAULT_PROFILE_SELECTION; } - /** - * get all user profiles + /** + * get all user profiles */ public static List<String> getUserProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(userProfiles).keySet()); Collections.sort(profiles); return profiles; } - + /** * returns name of (active) default profile */ public static String getDefaultProfileName() { - return userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); + return userProperties.getProperty(DEFAULTPROFILE_PROPERTY); } - + /** * returns name of active profile */ public static String getActiveProfileName() { return selectedProfile; } - + /** * returns true if legacy configfile is used */ public static boolean isLegacyConfigFile() { return legacyConfigFile; } - + /** * sets filename for an active profile (and store list of profiles) */ @@ -254,7 +268,7 @@ userProfiles.setProperty(selectedProfile, filepath); return storePropertyFile(userProfiles, userProfilesFile); } - + /** * returns filename of active profile, (null if undefined or default profile) */ @@ -269,7 +283,7 @@ return Util.hasValue(userProfiles.getProperty(selectedProfile)); } - + /** * activates settings used for testing */ @@ -278,13 +292,22 @@ * Set the system property that tells log4j to use this file. (Note: * this MUST be done before updating Config) */ - System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE); + String log4jSelection = System.getProperty("log4j.configuration"); + if (!Util.hasValue(log4jSelection)) { + log4jSelection = LOG4J_CONFIG_FILE; + } + System.setProperty("log4j.configuration", log4jSelection); + System.out.println("log4j.configuration = " + log4jSelection); + + // delayed setting of logger + log = Logger.getLogger(Config.class.getPackage().getName()); + legacyConfigFile = false; selectedProfile = TEST_PROFILE_SELECTION; initialLoad(); } - + /** * activates configuration settings based on default settings */ @@ -293,15 +316,16 @@ * Set the system property that tells log4j to use this file. (Note: * this MUST be done before updating Config) */ - String log4jSelection = System.getProperty(LOG4J_CMDLINE); + String log4jSelection = System.getProperty("log4j.configuration"); if (!Util.hasValue(log4jSelection)) { log4jSelection = LOG4J_CONFIG_FILE; } System.setProperty("log4j.configuration", log4jSelection); - System.out.println("Log4j selection = " + log4jSelection); + System.out.println("log4j.configuration = " + log4jSelection); + // delayed setting of logger log = Logger.getLogger(Config.class.getPackage().getName()); - + /* * Check if the profile has been set from the command line * to do this is adding an option to the java command: -Dprofile=<profile-name> @@ -314,31 +338,31 @@ /* * Check if the property file has been set on the command line. The way * to do this is adding an option to the java command: -Dconfigfile=<property-filename> - * + * * This is for legacy reasons only */ configSelection = System.getProperty(CONFIGFILE_CMDLINE); - + if (Util.hasValue(configSelection)) { System.out.println("Cmdline configfile selection (legacy!) = " + configSelection); legacyConfigFile = true; } } - + /* if nothing has selected so far, choose standardProfile */ if (!Util.hasValue(configSelection)) { configSelection = STANDARD_PROFILE_SELECTION; } - + selectedProfile = configSelection; if (!legacyConfigFile) { System.out.println("Profile selection = " + selectedProfile); } - + initialLoad(); } - + private static void initialLoad() { if (legacyConfigFile) { if (!propertiesLoaded) { @@ -348,79 +372,137 @@ } return; } - + if (!profilesLoaded) { loadPropertyFile(defaultProfiles, defaultProfilesFile, true); loadPropertyFile(userProfiles, userProfilesFile, false); profilesLoaded = true; } - + /* Tell the properties loader to read this file. */ log.info("Selected profile = " + selectedProfile); if (!propertiesLoaded) { - loadPropertyProfile(selectedProfile); + loadProfile(selectedProfile); propertiesLoaded = true; } } - + + /** - * loads a user profile and the according default profile + * loads an external user profile + * defined by the filepath + */ + public static boolean loadProfileFromFile(File file) { + String filepath = file.getAbsolutePath(); + if (loadPropertyFile(userProperties, filepath, false)) { + String profile = userProperties.getProperty(PROFILENAME_PROPERTY); + if (!Util.hasValue(profile)) { + profile = STANDARD_PROFILE_SELECTION; + } + selectedProfile = profile; + setActiveFilepath(filepath); + loadDefaultProfile(); + setSaveDirDefaults(); + return true; + } else { + return false; + } + } + + + /** + * loads a user profile * if not defined or loadable, creates a default user profile */ - private static void loadPropertyProfile(String userProfile) { + private static void loadProfile(String userProfile) { // reset properties userProperties = new Properties(); defaultProperties = new Properties(); - - // check if the profile is already defined under userProfiles + + // check if the profile is already defined under userProfiles String userConfigFile = userProfiles.getProperty(userProfile); - String defaultConfigFile = null; if (Util.hasValue(userConfigFile) && // load user profile loadPropertyFile(userProperties, userConfigFile, false)) { - String defaultConfig = userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); - if (defaultConfig != null) { - defaultConfigFile = defaultProfiles.getProperty(defaultConfig); - } - } else { + // do nothing, only side effects + } else { // if not defined or loadable, define userprofile with file association userProfiles.setProperty(userProfile, ""); } + + // check if profilename is defined in user properties + if (!Util.hasValue(userProfiles.getProperty(PROFILENAME_PROPERTY))) { + userProperties.setProperty(PROFILENAME_PROPERTY, userProfile); + } + loadDefaultProfile(); + setSaveDirDefaults(); + } + + /** + * loads the associated default profile + * if none is defined, uses standard default profile + */ + private static void loadDefaultProfile() { + String defaultConfigFile = null; + String defaultConfig = userProperties.getProperty(DEFAULTPROFILE_PROPERTY); + if (defaultConfig != null) { + defaultConfigFile = defaultProfiles.getProperty(defaultConfig); + } if (defaultConfigFile == null) { defaultConfigFile = defaultProfiles.getProperty(DEFAULT_PROFILE_SELECTION); - userProperties.setProperty(DEFAULT_PROFILE_PROPERTY, DEFAULT_PROFILE_SELECTION); + userProperties.setProperty(DEFAULTPROFILE_PROPERTY, DEFAULT_PROFILE_SELECTION); } loadPropertyFile(defaultProperties, defaultConfigFile, true); - setSaveDirDefaults(); } /** * This method loads a property file. * - * @param filename - file key name as a String. + * @param properties - the property to store + * @param filepath - filname as a String. * @param resource - if TRUE, loaded from jar (via classloader), otherwise from filesystem * @return TRUE if load was successful */ - private static boolean loadPropertyFile(Properties properties, String filename, boolean resource) { - - boolean result = true; + private static boolean loadPropertyFile(Properties properties, String filepath, boolean resource) { + + boolean result = true; try { - log.info("Loading properties from file " + filename); + log.info("Loading properties from file " + filepath); InputStream inFile; if (resource) { - inFile = Config.class.getClassLoader().getResourceAsStream(filename); + inFile = Config.class.getClassLoader().getResourceAsStream(filepath); } else { - inFile = new FileInputStream(filename); + inFile = new FileInputStream(filepath); } properties.load(inFile); } catch (Exception e) { System.err.println(e + " whilst loading properties file " - + filename); + + filepath); // e.printStackTrace(System.err); result = false; } return result; } + /** + * This method stores a property file + * @param properties - + * @param filepath + * @return + */ + + private static boolean storePropertyFile(Properties properties, String filepath) { + File outFile = new File(filepath); + boolean result = true; + try { + properties.store(new FileOutputStream(outFile), "Automatically generated, do not edit"); + log.info("Storing properties to file " + filepath); + } catch (IOException e) { + result = false; + } + return result; + } + + private static void setSaveDirDefaults() { if (!Util.hasValue(defaultProperties.getProperty("save.directory"))) { log.debug("Setting save directory to "+System.getProperty("user.dir")); Modified: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java 2010-07-18 16:36:38 UTC (rev 1349) +++ trunk/18xx/rails/util/ConfigItem.java 2010-07-18 17:24:36 UTC (rev 1350) @@ -68,7 +68,7 @@ formatMask = tag.getAttributeAsString("formatMask"); // optional: helpText - helpText = tag.getAttributeAsString("formatMask"); + helpText = tag.getAttributeAsString("helpText"); newValue = null; } @@ -82,7 +82,7 @@ } public void setNewValue(String newValue) { - if (newValue.equals(getConfigValue())) { + if (newValue == null || newValue.equals(getConfigValue())) { this.newValue = null; } else { this.newValue = newValue; Modified: trunk/18xx/rails/util/LocalText.java =================================================================== --- trunk/18xx/rails/util/LocalText.java 2010-07-18 16:36:38 UTC (rev 1349) +++ trunk/18xx/rails/util/LocalText.java 2010-07-18 17:24:36 UTC (rev 1350) @@ -83,8 +83,8 @@ } } - // special treatment for test - if (localeCode.equals("te_st0")) { + // special treatment for te_ST (test) + if (localeCode.equals("te_ST")) { StringBuffer s = new StringBuffer(key); if (parameters != null) for (Object o:parameters) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-18 16:36:44
|
Revision: 1349 http://rails.svn.sourceforge.net/rails/?rev=1349&view=rev Author: evos Date: 2010-07-18 16:36:38 +0000 (Sun, 18 Jul 2010) Log Message: ----------- Suspended logger initialization until after the system property log4j.configuration is set; otherwise teh latter is just ignored. Modified Paths: -------------- trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-18 08:28:37 UTC (rev 1348) +++ trunk/18xx/rails/util/Config.java 2010-07-18 16:36:38 UTC (rev 1349) @@ -1,18 +1,8 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/util/Config.java,v 1.13 2010/06/24 21:48:08 stefanfrey Exp $*/ package rails.util; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; +import java.io.*; +import java.util.*; import org.apache.log4j.Logger; @@ -29,8 +19,7 @@ */ public final class Config { - protected static Logger log = - Logger.getLogger(Config.class.getPackage().getName()); + protected static Logger log; /** Commandline options */ private static final String LOG4J_CMDLINE = "log4j"; @@ -46,7 +35,7 @@ /** Log 4j configuration */ private static final String LOG4J_CONFIG_FILE = "log4j.properties"; - + /** Rails profile configurations */ private static String defaultProfilesFile = "default.profiles"; private static Properties defaultProfiles = new Properties(); @@ -57,25 +46,25 @@ private static final String DEFAULT_PROFILE_SELECTION = "default"; private static final String DEFAULT_PROFILE_PROPERTY = "default.profile"; private static final String STANDARD_PROFILE_SELECTION = "user"; - + /** selected profile */ private static String selectedProfile; private static boolean legacyConfigFile; - + /** properties storage. */ private static Properties defaultProperties = new Properties(); private static Properties userProperties = new Properties(); private static boolean propertiesLoaded = false; - + /** Map that holds the panel, which contains config items */ - private static Map<String, List<ConfigItem>> configPanels = null; - + private static Map<String, List<ConfigItem>> configPanels = null; + /** * Hidden constructor, the class is never instantiated, everything is static */ private Config() {} - /** + /** * Reads the config.xml file that defines all config items */ public static void readConfigSetupXML() { @@ -86,7 +75,7 @@ Tag configTag = Tag.findTopTagInFile(CONFIG_XML_FILE, directories, CONFIG_TAG); log.debug("Opened config xml, filename = " + CONFIG_XML_FILE); - + configPanels = new LinkedHashMap<String, List<ConfigItem>>(); // find panels List<Tag> panelTags = configTag.getChildren(PANEL_TAG); @@ -95,7 +84,7 @@ // find name attribute String panelName = panelTag.getAttributeAsString("name"); if (!Util.hasValue(panelName)) continue; - + // find items List<Tag> itemTags = panelTag.getChildren(ITEM_TAG); if (itemTags == null || itemTags.size() == 0) continue; @@ -106,12 +95,12 @@ configPanels.put(panelName, panelItems); } } - + } catch (ConfigurationException e) { log.error("Configuration error in setup of "); } } - + public static Map<String, List<ConfigItem>> getConfigPanels() { if (configPanels == null) { readConfigSetupXML(); @@ -119,14 +108,14 @@ log.debug("Configuration setup = " + configPanels); return configPanels; } - + /** - * First tries to return {key}.{gameName}, if undefined returns {key} + * First tries to return {key}.{gameName}, if undefined returns {key} */ public static String getGameSpecific(String key) { return Config.getSpecific(key, GameManager.getInstance().getGameName()); } - + /** * First tries to return {key}.{appendix}, if undefined returns {key} */ @@ -137,11 +126,11 @@ } return value; } - + public static String get(String key) { return get(key, ""); } - + public static String get(String key, String defaultValue) { if (defaultProperties.isEmpty() || !propertiesLoaded) { initialLoad(); @@ -151,19 +140,19 @@ return defaultValue; } - + private static boolean storePropertyFile(Properties properties, String filepath) { File outFile = new File(filepath); boolean result = true; - try { + try { properties.store(new FileOutputStream(outFile), "Automatically generated, do not edit"); } catch (IOException e) { result = false; } return result; } - + /** * save active Profile */ @@ -175,9 +164,9 @@ return false; } } - + /** - * change active Profile + * change active Profile */ public static boolean changeActiveProfile(String profileName) { readConfigSetupXML(); @@ -185,7 +174,7 @@ selectedProfile = profileName; return true; } - + /** * create new profile */ @@ -193,7 +182,7 @@ userProperties = new Properties(); defaultProperties = new Properties(); - + // add to list of user profiles userProfiles.setProperty(profileName, ""); // define and load default profile @@ -205,8 +194,8 @@ selectedProfile = profileName; return true; } - - + + private static Map<String, String> convertProperties(Properties properties) { Map<String, String> converted = new HashMap<String, String>(); for (Object key:properties.keySet()) { @@ -214,50 +203,50 @@ } return converted; } - - /** - * get all default profiles + + /** + * get all default profiles */ public static List<String> getDefaultProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); Collections.sort(profiles); return profiles; } - + public static String getDefaultProfileSelection() { return DEFAULT_PROFILE_SELECTION; } - /** - * get all user profiles + /** + * get all user profiles */ public static List<String> getUserProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(userProfiles).keySet()); Collections.sort(profiles); return profiles; } - + /** * returns name of (active) default profile */ public static String getDefaultProfileName() { return userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); } - + /** * returns name of active profile */ public static String getActiveProfileName() { return selectedProfile; } - + /** * returns true if legacy configfile is used */ public static boolean isLegacyConfigFile() { return legacyConfigFile; } - + /** * sets filename for an active profile (and store list of profiles) */ @@ -265,7 +254,7 @@ userProfiles.setProperty(selectedProfile, filepath); return storePropertyFile(userProfiles, userProfilesFile); } - + /** * returns filename of active profile, (null if undefined or default profile) */ @@ -280,7 +269,7 @@ return Util.hasValue(userProfiles.getProperty(selectedProfile)); } - + /** * activates settings used for testing */ @@ -295,7 +284,7 @@ initialLoad(); } - + /** * activates configuration settings based on default settings */ @@ -310,7 +299,9 @@ } System.setProperty("log4j.configuration", log4jSelection); System.out.println("Log4j selection = " + log4jSelection); - + + log = Logger.getLogger(Config.class.getPackage().getName()); + /* * Check if the profile has been set from the command line * to do this is adding an option to the java command: -Dprofile=<profile-name> @@ -323,31 +314,31 @@ /* * Check if the property file has been set on the command line. The way * to do this is adding an option to the java command: -Dconfigfile=<property-filename> - * + * * This is for legacy reasons only */ configSelection = System.getProperty(CONFIGFILE_CMDLINE); - + if (Util.hasValue(configSelection)) { System.out.println("Cmdline configfile selection (legacy!) = " + configSelection); legacyConfigFile = true; } } - + /* if nothing has selected so far, choose standardProfile */ if (!Util.hasValue(configSelection)) { configSelection = STANDARD_PROFILE_SELECTION; } - + selectedProfile = configSelection; if (!legacyConfigFile) { System.out.println("Profile selection = " + selectedProfile); } - + initialLoad(); } - + private static void initialLoad() { if (legacyConfigFile) { if (!propertiesLoaded) { @@ -357,13 +348,13 @@ } return; } - + if (!profilesLoaded) { loadPropertyFile(defaultProfiles, defaultProfilesFile, true); loadPropertyFile(userProfiles, userProfilesFile, false); profilesLoaded = true; } - + /* Tell the properties loader to read this file. */ log.info("Selected profile = " + selectedProfile); @@ -372,7 +363,7 @@ propertiesLoaded = true; } } - + /** * loads a user profile and the according default profile * if not defined or loadable, creates a default user profile @@ -381,8 +372,8 @@ // reset properties userProperties = new Properties(); defaultProperties = new Properties(); - - // check if the profile is already defined under userProfiles + + // check if the profile is already defined under userProfiles String userConfigFile = userProfiles.getProperty(userProfile); String defaultConfigFile = null; if (Util.hasValue(userConfigFile) && // load user profile @@ -410,13 +401,13 @@ * @return TRUE if load was successful */ private static boolean loadPropertyFile(Properties properties, String filename, boolean resource) { - - boolean result = true; + + boolean result = true; try { log.info("Loading properties from file " + filename); InputStream inFile; if (resource) { - inFile = Config.class.getClassLoader().getResourceAsStream(filename); + inFile = Config.class.getClassLoader().getResourceAsStream(filename); } else { inFile = new FileInputStream(filename); } @@ -429,7 +420,7 @@ } return result; } - + private static void setSaveDirDefaults() { if (!Util.hasValue(defaultProperties.getProperty("save.directory"))) { log.debug("Setting save directory to "+System.getProperty("user.dir")); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-18 08:28:43
|
Revision: 1348 http://rails.svn.sourceforge.net/rails/?rev=1348&view=rev Author: stefanfrey Date: 2010-07-18 08:28:37 +0000 (Sun, 18 Jul 2010) Log Message: ----------- Further update of config mechanism Modified Paths: -------------- trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -1,7 +1,6 @@ package rails.ui.swing; import java.awt.Color; -import java.awt.Component; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; @@ -18,20 +17,16 @@ import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComboBox; -import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; +import javax.swing.JOptionPane; import javax.swing.JPanel; -import javax.swing.JSpinner; import javax.swing.JTabbedPane; -import javax.swing.SpinnerListModel; import javax.swing.SwingConstants; import javax.swing.border.Border; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; import rails.game.ConfigurationException; import rails.util.Config; @@ -41,6 +36,9 @@ class ConfigWindow extends JFrame { private static final long serialVersionUID = 1L; + + private static final String CONFIG_EXTENSION = ".rails_config"; + private static final String CONFIG_DESCRIPTION = "Rails configuration files (.rails_config)"; private JPanel profilePanel; private JTabbedPane configPane; @@ -90,19 +88,23 @@ comboBoxUser.setSelectedItem(Config.getActiveProfileName()); comboBoxUser.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { - Config.changeActiveProfile((String)comboBoxUser.getSelectedItem()); - EventQueue.invokeLater(new Runnable() { - public void run() { - init(); - ConfigWindow.this.repaint(); - } - } - ); + changeProfile((String)comboBoxUser.getSelectedItem()); } } ); profilePanel.add(comboBoxUser); + // new button + JButton newButton = new JButton(LocalText.getText("NEW")); + newButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + newProfile(); + } + } + ); + profilePanel.add(newButton); + } private void setupConfigPane() { @@ -206,6 +208,17 @@ private void setupButtonPanel() { buttonPanel.removeAll(); + // saveas button + JButton saveAsButton = new JButton(LocalText.getText("SAVEAS")); + saveAsButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.saveAsConfig(); + } + } + ); + buttonPanel.add(saveAsButton); + // save button if (Config.isFilePathDefined()) { JButton saveButton = new JButton(LocalText.getText("SAVE")); @@ -219,15 +232,6 @@ buttonPanel.add(saveButton); } - JButton saveAsButton = new JButton(LocalText.getText("SAVEAS")); - saveAsButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - ConfigWindow.this.saveAsConfig(); - } - } - ); - buttonPanel.add(saveAsButton); JButton cancelButton = new JButton(LocalText.getText("CANCEL")); cancelButton.addActionListener( @@ -241,12 +245,47 @@ } + private void newProfile() { + String newProfile = JOptionPane.showInputDialog(ConfigWindow.this, LocalText.getText("CONFIG_NEW_MESSAGE"), + LocalText.getText("CONFIG_NEW_TITLE"), JOptionPane.QUESTION_MESSAGE); + if (Util.hasValue(newProfile)) { + String defaultProfile = (String)JOptionPane.showInputDialog(ConfigWindow.this, LocalText.getText("CONFIG_DEFAULT_MESSAGE"), + LocalText.getText("CONFIG_DEFAULT_TITLE"), JOptionPane.QUESTION_MESSAGE, null, + Config.getDefaultProfiles().toArray(), Config.getDefaultProfileSelection()); + Config.createUserProfile(newProfile, defaultProfile); + } + EventQueue.invokeLater(new Runnable() { + public void run() { + init(); + ConfigWindow.this.repaint(); + } + }); + } + + private void changeProfile(String profileName) { + Config.changeActiveProfile(profileName); + EventQueue.invokeLater(new Runnable() { + public void run() { + init(); + ConfigWindow.this.repaint(); + } + }); + } + private void saveConfig() { Config.saveActiveProfile(); } private void saveAsConfig() { + String directory = Config.get("save.directory"); + String filepath; + if (Util.hasValue(directory)) { + filepath = directory + File.separator + Config.getActiveProfileName() + CONFIG_EXTENSION; + } else { + filepath = Config.getActiveProfileName() + CONFIG_EXTENSION; + } JFileChooser fc = new JFileChooser(); + fc.setSelectedFile(new File(filepath)); fc.setFileFilter( new FileFilter() { public boolean accept( File f ){ @@ -254,12 +293,11 @@ f.getName().toLowerCase().endsWith( ".rails_config" ); } public String getDescription() { - return "Rails Config"; + return CONFIG_DESCRIPTION; } } ); - - int state = fc.showOpenDialog( null ); + int state = fc.showSaveDialog(this); if ( state == JFileChooser.APPROVE_OPTION ) { File file = fc.getSelectedFile(); Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -176,12 +176,15 @@ menuItem.addActionListener(this); optMenu.add(menuItem); - menuItem = new JCheckBoxMenuItem(LocalText.getText("CONFIG")); - menuItem.setName(CONFIG_CMD); - menuItem.setActionCommand(CONFIG_CMD); - menuItem.setMnemonic(KeyEvent.VK_C); - menuItem.addActionListener(this); - optMenu.add(menuItem); + // new config menu only for non legacy configgfiles + if (!Config.isLegacyConfigFile()) { + menuItem = new JCheckBoxMenuItem(LocalText.getText("CONFIG")); + menuItem.setName(CONFIG_CMD); + menuItem.setActionCommand(CONFIG_CMD); + menuItem.setMnemonic(KeyEvent.VK_C); + menuItem.addActionListener(this); + optMenu.add(menuItem); + } menuBar.add(optMenu); Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-17 22:45:27 UTC (rev 1347) +++ trunk/18xx/rails/util/Config.java 2010-07-18 08:28:37 UTC (rev 1348) @@ -3,7 +3,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -14,7 +13,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; import org.apache.log4j.Logger; @@ -26,8 +24,8 @@ * a property object from a property file, to retrieve a particular value from * the property file etc. * - * @author Ramiah Bala, rewritten by Erik Vos - * @version 1.0 + * @author Ramiah Bala, rewritten by Erik Vos, rewritten by Stefan Frey + * @version 2.0 */ public final class Config { @@ -48,8 +46,7 @@ /** Log 4j configuration */ private static final String LOG4J_CONFIG_FILE = "log4j.properties"; - - + /** Rails profile configurations */ private static String defaultProfilesFile = "default.profiles"; private static Properties defaultProfiles = new Properties(); @@ -156,13 +153,6 @@ } - /** - * @return if user location is defined - */ - public static boolean isFilePathDefined() { - return Util.hasValue(userProfiles.getProperty(selectedProfile)); - } - private static boolean storePropertyFile(Properties properties, String filepath) { File outFile = new File(filepath); boolean result = true; @@ -196,6 +186,27 @@ return true; } + /** + * create new profile + */ + public static boolean createUserProfile(String profileName, String defaultProfile) { + userProperties = new Properties(); + defaultProperties = new Properties(); + + + // add to list of user profiles + userProfiles.setProperty(profileName, ""); + // define and load default profile + String defaultConfigFile = defaultProfiles.getProperty(defaultProfile); + userProperties.setProperty(DEFAULT_PROFILE_PROPERTY, defaultProfile); + loadPropertyFile(defaultProperties, defaultConfigFile, true); + setSaveDirDefaults(); + + selectedProfile = profileName; + return true; + } + + private static Map<String, String> convertProperties(Properties properties) { Map<String, String> converted = new HashMap<String, String>(); for (Object key:properties.keySet()) { @@ -204,16 +215,18 @@ return converted; } - /** * get all default profiles */ public static List<String> getDefaultProfiles() { List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); - profiles.remove(DEFAULT_PROFILE_PROPERTY); Collections.sort(profiles); return profiles; } + + public static String getDefaultProfileSelection() { + return DEFAULT_PROFILE_SELECTION; + } /** * get all user profiles @@ -239,6 +252,13 @@ } /** + * returns true if legacy configfile is used + */ + public static boolean isLegacyConfigFile() { + return legacyConfigFile; + } + + /** * sets filename for an active profile (and store list of profiles) */ public static boolean setActiveFilepath(String filepath) { @@ -252,6 +272,14 @@ public static String getActiveFilepath() { return userProfiles.getProperty(selectedProfile); } + + /** + * @return if user location is defined + */ + public static boolean isFilePathDefined() { + return Util.hasValue(userProfiles.getProperty(selectedProfile)); + } + /** * activates settings used for testing This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-17 22:45:34
|
Revision: 1347 http://rails.svn.sourceforge.net/rails/?rev=1347&view=rev Author: evos Date: 2010-07-17 22:45:27 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Allow the old object positions in more than one list to be saved in ObjectMove. This should restore ALL lists affected by ObjectMove into original order after an Undo. Modified Paths: -------------- trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/City.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/PrivateCompany.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/TrainType.java trunk/18xx/rails/game/move/Moveable.java trunk/18xx/rails/game/move/MoveableHolder.java trunk/18xx/rails/game/move/ObjectMove.java trunk/18xx/rails/game/move/RemoveFromList.java Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/Bank.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -107,9 +107,9 @@ for (PublicCompanyI comp : companies) { for (PublicCertificateI cert : comp.getCertificates()) { if (cert.isInitiallyAvailable()) { - ipo.addCertificate(cert, -1); + ipo.addCertificate(cert); } else { - unavailable.addCertificate(cert, -1); + unavailable.addCertificate(cert); } } } Modified: trunk/18xx/rails/game/City.java =================================================================== --- trunk/18xx/rails/game/City.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/City.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -23,7 +23,7 @@ * tile. However, the City numbers will not change, unless cities are merged * during upgrades; but even then it is attempted to retain the old city numbers * as much as possible. - * + * * @author Erik Vos */ public class City implements TokenHolder { @@ -100,9 +100,9 @@ return result; } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -163,11 +163,11 @@ return false; } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof BaseToken) { - return tokens.indexOf(object); + return new int[] {tokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/GameManager.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1500,21 +1500,21 @@ * @param object The object to add. * @return True if successful. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof SpecialPropertyI) { SpecialPropertyI sp = (SpecialPropertyI) object; sp.setHolder(null); - return addSpecialProperty(sp, position); + return addSpecialProperty(sp, position == null ? -1 : position[0]); } else { return false; } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof SpecialPropertyI) { - return commonSpecialProperties.indexOf(object); + return new int[] {commonSpecialProperties.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/MapHex.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -827,9 +827,9 @@ return offStationTokens.remove(token); } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -843,11 +843,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof TokenI) { - return offStationTokens.indexOf(object); + return new int[] {offStationTokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } @@ -1015,7 +1015,7 @@ * NOTE: this method currently only checks for prohibitions caused * by the presence of unlaid home base tokens. * It does NOT (yet) check for free space. - * + * * Remark: There are the following cases to check * A) isBlockedForTokenLays is active for the MapHex => return the state of this * (Example: Erie home base in 1830) Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/OperatingRound.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1716,7 +1716,7 @@ train.getType().addToBoughtFromIPO(); // Clone the train if infinitely available if (train.getType().hasInfiniteAmount()) { - ipo.addTrain(train.getType().cloneTrain(), -1); + ipo.addTrain(train.getType().cloneTrain()); } } @@ -2670,7 +2670,7 @@ * This method can be extended to perform other generic checks, * such as if a route exists, * and possibly in subclasses for game-specific checks. - * + * * @param company The company laying a tile. * @param hex The hex on which a tile is laid. * @param station The number of the station/city on which the token Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -121,23 +121,28 @@ privatesOwnedModel.update(); } - public void addCertificate(PublicCertificateI certificate, int position) { + public void addCertificate(PublicCertificateI certificate){ + addCertificate (certificate, new int[] {-1,-1,-1}); + } + + public void addCertificate(PublicCertificateI certificate, int[] position) { // When undoing a company start, put the President back at the top. - if (certificate.isPresidentShare()) position = 0; + if (certificate.isPresidentShare()) position = new int[] {0,0,0}; + Util.addToList(certificates, certificate, position[0]); + String companyName = certificate.getCompany().getName(); if (!certPerCompany.containsKey(companyName)) { certPerCompany.put(companyName, new ArrayList<PublicCertificateI>()); } - Util.addToList(certificates, certificate, position); - (certPerCompany.get(companyName)).add(certificate); + Util.addToList(certPerCompany.get(companyName), certificate, position[1]); String certTypeId = certificate.getTypeId(); if (!certsPerType.containsKey(certTypeId)) { certsPerType.put(certTypeId, new ArrayList<PublicCertificateI>()); } - certsPerType.get(certTypeId).add(certificate); + Util.addToList(certsPerType.get(certTypeId), certificate, position[2]); certificate.setPortfolio(this); @@ -373,14 +378,18 @@ return swapped; } - public void addTrain(TrainI train, int position) { + public void addTrain (TrainI train) { + addTrain (train, new int[] {-1,-1}); + } - Util.addToList(trains, train, position); + public void addTrain(TrainI train, int[] position) { + + Util.addToList(trains, train, position[0]); TrainTypeI type = train.getType(); if (!trainsPerType.containsKey(type)) { trainsPerType.put(type, new ArrayList<TrainI>()); } - trainsPerType.get(train.getType()).add(train); + Util.addToList(trainsPerType.get(train.getType()), train, position[1]); train.setHolder(this); trainsModel.update(); } @@ -574,20 +583,22 @@ * @param object The object to add. * @return True if successful. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof PublicCertificateI) { + if (position == null) position = new int[] {-1, -1, -1}; addCertificate((PublicCertificateI) object, position); return true; } else if (object instanceof PrivateCompanyI) { - addPrivate((PrivateCompanyI) object, position); + addPrivate((PrivateCompanyI) object, position == null ? -1 : position[0]); return true; } else if (object instanceof TrainI) { + if (position == null) position = new int[] {-1, -1}; addTrain((TrainI) object, position); return true; } else if (object instanceof SpecialPropertyI) { - return addSpecialProperty((SpecialPropertyI) object, position); + return addSpecialProperty((SpecialPropertyI) object, position == null ? -1 : position[0]); } else if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -618,19 +629,28 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof PublicCertificateI) { - return certificates.indexOf(object); + PublicCertificateI cert = (PublicCertificateI) object; + return new int[] { + certificates.indexOf(object), + certPerCompany.get(cert.getCompany().getName()).indexOf(cert), + certsPerType.get(cert.getTypeId()).indexOf(cert) + }; } else if (object instanceof PrivateCompanyI) { - return privateCompanies.indexOf(object); + return new int[] {privateCompanies.indexOf(object)}; } else if (object instanceof TrainI) { - return trains.indexOf(object); + TrainI train = (TrainI) object; + return new int[] { + trains.indexOf(train), + trainsPerType.get(train.getType()).indexOf(train) + }; } else if (object instanceof SpecialPropertyI) { - return specialProperties.indexOf(object); + return new int[] {specialProperties.indexOf(object)}; } else if (object instanceof TokenI) { - return tokens.indexOf(object); + return new int[] {tokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/PrivateCompany.java =================================================================== --- trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -2,7 +2,6 @@ package rails.game; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import rails.game.move.*; @@ -55,14 +54,14 @@ // sfy 1889 changed to IntegerArray revenue = tag.getAttributeAsIntegerArray("revenue", new int[0]); - + // pld: adding revenue to info text infoText += "<br>Revenue: "; for (int i = 0; i < revenue.length;i++) { infoText += (Bank.format(revenue[i])); if (i < revenue.length-1) {infoText += ", ";}; } - + // Blocked hexes (until bought by a company) Tag blockedTag = tag.getChild("Blocking"); if (blockedTag != null) { @@ -333,9 +332,10 @@ * Stub to satisfy MoveableHolderI. Special properties are never added after * completing the initial setup. */ - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof SpecialPropertyI) { - return Util.addToList(specialProperties, (SpecialPropertyI)object, position); + return Util.addToList(specialProperties, (SpecialPropertyI)object, + position == null ? -1 : position[0]); } else { return false; } @@ -356,11 +356,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof SpecialPropertyI) { - return specialProperties.indexOf(object); + return new int[] {specialProperties.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/PublicCompany.java =================================================================== --- trunk/18xx/rails/game/PublicCompany.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/PublicCompany.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1809,18 +1809,10 @@ public boolean addToken(TokenI token, int position) { boolean result = false; - if (token instanceof BaseToken && laidBaseTokens.remove(token)) { + if (token instanceof BaseToken + && laidBaseTokens.remove(token) + && Util.addToList(freeBaseTokens, token, position)) { token.setHolder(this); - if (position == -1) { - result = freeBaseTokens.add(token); - } else { - try { - freeBaseTokens.add(position, token); - result = true; - } catch (IndexOutOfBoundsException e) { - result = false; - } - } this.baseTokensModel.update(); } return result; @@ -1864,9 +1856,9 @@ } - public boolean addObject(Moveable object, int position) { + public boolean addObject(Moveable object, int[] position) { if (object instanceof TokenI) { - return addToken((TokenI) object, position); + return addToken((TokenI) object, position == null ? -1 : position[0]); } else { return false; } @@ -1880,11 +1872,11 @@ } } - public int getListIndex (Moveable object) { + public int[] getListIndex (Moveable object) { if (object instanceof BaseToken) { - return freeBaseTokens.indexOf(object); + return new int[] {freeBaseTokens.indexOf(object)}; } else { - return -1; + return Moveable.AT_END; } } Modified: trunk/18xx/rails/game/TrainType.java =================================================================== --- trunk/18xx/rails/game/TrainType.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/TrainType.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -230,7 +230,7 @@ for (TrainI train : trains) { train.init(this, lastIndex++); - unavailable.addTrain(train, -1); + unavailable.addTrain(train); } } Modified: trunk/18xx/rails/game/move/Moveable.java =================================================================== --- trunk/18xx/rails/game/move/Moveable.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/Moveable.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -2,6 +2,8 @@ public interface Moveable { + public static final int[] AT_END = new int[] {-1}; + public void moveTo(MoveableHolder newHolder); public String getName(); Modified: trunk/18xx/rails/game/move/MoveableHolder.java =================================================================== --- trunk/18xx/rails/game/move/MoveableHolder.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/MoveableHolder.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -8,12 +8,12 @@ * @param position Position to insert object at. O: at front, -1, at end, >0: at that position. * @return True if successful. */ - public boolean addObject(Moveable object, int position); + public boolean addObject(Moveable object, int[] position); public boolean removeObject(Moveable object); public String getName(); - public int getListIndex (Moveable object); + public int[] getListIndex (Moveable object); } Modified: trunk/18xx/rails/game/move/ObjectMove.java =================================================================== --- trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -14,8 +14,8 @@ MoveableHolder from; MoveableHolder to; String objectClassName; - int fromPosition; - int toPosition = -1; // Default: at end + int[] fromPosition; + int[] toPosition = new int[] {-1}; // Default: at end /** * Create a generic ObjectMove object. Any specific side effects must be @@ -30,7 +30,7 @@ public ObjectMove(Moveable moveableObject, MoveableHolder from, MoveableHolder to) { - this (moveableObject, from, to, -1); + this (moveableObject, from, to, null); } /** @@ -46,13 +46,13 @@ */ public ObjectMove(Moveable moveableObject, MoveableHolder from, - MoveableHolder to, int toPosition) { + MoveableHolder to, int[] toPosition) { this.moveableObject = moveableObject; this.from = from; this.to = to; objectClassName = moveableObject.getClass().getSimpleName(); - this.fromPosition = from.getListIndex(moveableObject); + this.fromPosition = from != null ? from.getListIndex(moveableObject) : null; this.toPosition = toPosition; MoveSet.add(this); @@ -78,8 +78,8 @@ if (from == null) log.warn("From is null"); if (to == null) log.error("To is null"); return "Move " + objectClassName + ": " + moveableObject.getName() - + " from " + (from == null ? from : from.getName()) + "["+fromPosition - + "] to " + to.getName() + "["+toPosition+"]"; + + " from " + (from == null ? from : from.getName()) + "["+fromPosition + + "] to " + to.getName() + "["+toPosition+"]"; } } Modified: trunk/18xx/rails/game/move/RemoveFromList.java =================================================================== --- trunk/18xx/rails/game/move/RemoveFromList.java 2010-07-17 22:34:52 UTC (rev 1346) +++ trunk/18xx/rails/game/move/RemoveFromList.java 2010-07-17 22:45:27 UTC (rev 1347) @@ -1,5 +1,5 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/game/move/RemoveFromList.java,v 1.3 2009/09/23 21:38:57 evos Exp $ - * + * * Created on 18-Jul-2006 * Change Log: */ @@ -32,18 +32,21 @@ public RemoveFromList(List<E> list, E object, String listName) { this (list, object, listName, null); - } + } - public boolean execute() { + @Override + public boolean execute() { list.remove(object); return true; } + @Override public boolean undo() { list.add(index, object); return true; } + @Override public String toString() { return "RemoveFromList " + listName + ": " + object.toString(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-17 22:34:58
|
Revision: 1346 http://rails.svn.sourceforge.net/rails/?rev=1346&view=rev Author: stefanfrey Date: 2010-07-17 22:34:52 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Added cmdline log4j configuration Modified Paths: -------------- trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 20:43:58 UTC (rev 1345) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 22:34:52 UTC (rev 1346) @@ -242,7 +242,7 @@ } private void saveConfig() { - this.dispose(); + Config.saveActiveProfile(); } private void saveAsConfig() { @@ -264,6 +264,8 @@ { File file = fc.getSelectedFile(); Config.setActiveFilepath(file.getPath()); + saveConfig(); + setupButtonPanel(); } } Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-17 20:43:58 UTC (rev 1345) +++ trunk/18xx/rails/util/Config.java 2010-07-17 22:34:52 UTC (rev 1346) @@ -34,6 +34,10 @@ protected static Logger log = Logger.getLogger(Config.class.getPackage().getName()); + /** Commandline options */ + private static final String LOG4J_CMDLINE = "log4j"; + private static final String CONFIGFILE_CMDLINE = "configfile"; + private static final String PROFILE_CMDLINE = "profile"; /** XML setup */ private static final String CONFIG_XML_DIR = "data"; @@ -173,8 +177,13 @@ /** * save active Profile */ - public static boolean saveActiveProfile(String filepath) { - return storePropertyFile(userProperties, filepath); + public static boolean saveActiveProfile() { + String filepath = userProfiles.getProperty(selectedProfile); + if (Util.hasValue(filepath)) { + return storePropertyFile(userProperties, filepath); + } else { + return false; + } } /** @@ -267,13 +276,18 @@ * Set the system property that tells log4j to use this file. (Note: * this MUST be done before updating Config) */ - System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE); + String log4jSelection = System.getProperty(LOG4J_CMDLINE); + if (!Util.hasValue(log4jSelection)) { + log4jSelection = LOG4J_CONFIG_FILE; + } + System.setProperty("log4j.configuration", log4jSelection); + System.out.println("Log4j selection = " + log4jSelection); /* * Check if the profile has been set from the command line * to do this is adding an option to the java command: -Dprofile=<profile-name> */ - String configSelection = System.getProperty("profile"); + String configSelection = System.getProperty(PROFILE_CMDLINE); System.out.println("Cmdline profile selection = " + configSelection); legacyConfigFile = false; @@ -284,9 +298,9 @@ * * This is for legacy reasons only */ - configSelection = System.getProperty("configfile"); + configSelection = System.getProperty(CONFIGFILE_CMDLINE); - if (configSelection != null) { + if (Util.hasValue(configSelection)) { System.out.println("Cmdline configfile selection (legacy!) = " + configSelection); legacyConfigFile = true; } @@ -298,6 +312,10 @@ } selectedProfile = configSelection; + if (!legacyConfigFile) { + System.out.println("Profile selection = " + selectedProfile); + } + initialLoad(); } @@ -378,7 +396,7 @@ } catch (Exception e) { System.err.println(e + " whilst loading properties file " + filename); - e.printStackTrace(System.err); +// e.printStackTrace(System.err); result = false; } return result; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-17 20:44:04
|
Revision: 1345 http://rails.svn.sourceforge.net/rails/?rev=1345&view=rev Author: stefanfrey Date: 2010-07-17 20:43:58 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Delete user.profiles, should not by in repo Removed Paths: ------------- trunk/18xx/user.profiles Deleted: trunk/18xx/user.profiles =================================================================== --- trunk/18xx/user.profiles 2010-07-17 20:27:23 UTC (rev 1344) +++ trunk/18xx/user.profiles 2010-07-17 20:43:58 UTC (rev 1345) @@ -1,2 +0,0 @@ -standard.profile=sfy -sfy=sfy.my.properties This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-17 20:27:29
|
Revision: 1344 http://rails.svn.sourceforge.net/rails/?rev=1344&view=rev Author: stefanfrey Date: 2010-07-17 20:27:23 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Update configuration management Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/data/Properties.xml trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/ConfigItem.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-17 15:06:13 UTC (rev 1343) +++ trunk/18xx/LocalisedText.properties 2010-07-17 20:27:23 UTC (rev 1344) @@ -64,6 +64,7 @@ CLOSE_WINDOW=Do you really want to exit the game? COMPANY=Company COMPANY_DETAILS=Company details +CONFIG_CURRENT_PROFILE=Active profile = {0} (based on = {1}) CORRECT_CASH=Cash Correction CORRECT_MAP=Map Correction CURRENT=Current Modified: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml 2010-07-17 15:06:13 UTC (rev 1343) +++ trunk/18xx/data/Properties.xml 2010-07-17 20:27:23 UTC (rev 1344) @@ -4,7 +4,7 @@ --> <Properties> <Panel name="General"> - <Property name="locale" type="STRING"/> + <Property name="locale" type="LIST" values="en_US,de" /> </Panel> <Panel name="Colors"> <Property name="route.colour.1" type="COLOR"/> Modified: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 15:06:13 UTC (rev 1343) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-17 20:27:23 UTC (rev 1344) @@ -2,29 +2,49 @@ import java.awt.Color; import java.awt.Component; +import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.File; import java.util.Map; import java.util.List; +import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JColorChooser; +import javax.swing.JComboBox; import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; +import javax.swing.JSpinner; import javax.swing.JTabbedPane; +import javax.swing.SpinnerListModel; +import javax.swing.SwingConstants; +import javax.swing.border.Border; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import rails.game.ConfigurationException; import rails.util.Config; import rails.util.ConfigItem; import rails.util.LocalText; +import rails.util.Util; class ConfigWindow extends JFrame { private static final long serialVersionUID = 1L; - private JTabbedPane pane; + private JPanel profilePanel; + private JTabbedPane configPane; + private JPanel buttonPanel; ConfigWindow() { // JFrame properties @@ -32,55 +52,66 @@ // setSize(400,300); // add profile panel - add(setupProfilePanel(), "North"); + profilePanel = new JPanel(); + add(profilePanel, "North"); // configSetup pane - setupConfigPane(); - add(pane, "Center"); + configPane = new JTabbedPane(); + add(configPane, "Center"); // buttons - JPanel buttonPanel = new JPanel(); - - JButton saveButton = new JButton(LocalText.getText("Save")); - saveButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - ConfigWindow.this.saveConfig(); - } - } - ); - buttonPanel.add(saveButton); + buttonPanel = new JPanel(); + add(buttonPanel, "South"); - JButton cancelButton = new JButton(LocalText.getText("Cancel")); - cancelButton.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - ConfigWindow.this.cancelConfig(); - } - } - ); - buttonPanel.add(cancelButton); - - add(buttonPanel, "South"); - + init(); + } + + private void init() { + setupProfilePanel(); + setupConfigPane(); + setupButtonPanel(); this.pack(); } - - private JComponent setupProfilePanel() { - JComponent panel = new JPanel(); - panel.setLayout(new GridLayout(0,4)); + private void setupProfilePanel() { + profilePanel.removeAll(); - // default profile + profilePanel.setLayout(new GridLayout(0,4)); + String activeProfile = Config.getActiveProfileName(); + String defaultProfile = Config.getDefaultProfileName(); + Border etched = BorderFactory.createEtchedBorder(); + Border titled = BorderFactory.createTitledBorder(etched, LocalText.getText("CONFIG_CURRENT_PROFILE", activeProfile, defaultProfile)); + profilePanel.setBorder(titled); - return panel; + JLabel userLabel = new JLabel(LocalText.getText("CONFIG_SELECT_USER")); + profilePanel.add(userLabel); + final JComboBox comboBoxUser = new JComboBox(Config.getUserProfiles().toArray()); + comboBoxUser.setSelectedItem(Config.getActiveProfileName()); + comboBoxUser.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent arg0) { + Config.changeActiveProfile((String)comboBoxUser.getSelectedItem()); + EventQueue.invokeLater(new Runnable() { + public void run() { + init(); + ConfigWindow.this.repaint(); + } + } + ); + } + } + ); + profilePanel.add(comboBoxUser); + } private void setupConfigPane() { - // create pane - pane = new JTabbedPane(); + configPane.removeAll(); + Border etched = BorderFactory.createEtchedBorder(); + Border titled = BorderFactory.createTitledBorder(etched, LocalText.getText("CONFIG_SETTINGS")); + configPane.setBorder(titled); + Map<String, List<ConfigItem>> configPanels = Config.getConfigPanels(); for (String panelName:configPanels.keySet()) { @@ -89,54 +120,153 @@ for (ConfigItem item:configPanels.get(panelName)) { defineElement(newPanel, item); } - pane.addTab(panelName, newPanel); + configPane.addTab(panelName, newPanel); } } - private void defineElement(JPanel panel, ConfigItem item) { - + private void defineElement(JPanel panel, final ConfigItem item) { + // item label panel.add(new JLabel(LocalText.getText("Config." + item.name))); - final String configValue = Config.get(item.name); + // standard components + final String configValue = item.getCurrentValue(); + + switch (item.type) { - case COLOR: { + case COLOR: final JLabel label = new JLabel(configValue); Color selectedColor; try { - selectedColor = Color.decode(configValue); - } catch (NumberFormatException e) { + selectedColor = Util.parseColour(configValue); + } catch (ConfigurationException e) { selectedColor = Color.WHITE; } label.setOpaque(true); + label.setHorizontalAlignment(SwingConstants.CENTER); label.setBackground(selectedColor); + if (Util.isDark(selectedColor)) { + label.setForeground(Color.WHITE); + } else { + label.setForeground(Color.BLACK); + } panel.add(label); - JButton button = new JButton("Color"); + JButton button = new JButton("Choose..."); final Color oldColor = selectedColor; button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Color selectedColor=JColorChooser.showDialog(ConfigWindow.this, "", oldColor); - label.setText(Integer.toHexString(selectedColor.getRGB()).substring(2)); + if (selectedColor == null) return; + String newValue = Integer.toHexString(selectedColor.getRGB()).substring(3); + label.setText(newValue); + item.setNewValue(newValue); label.setBackground(selectedColor); + if (Util.isDark(selectedColor)) { + label.setForeground(Color.WHITE); + } else { + label.setForeground(Color.BLACK); + } } } ); panel.add(button); break; - } + case LIST: + final JComboBox comboBox = new JComboBox(item.allowedValues.toArray()); + comboBox.setSelectedItem(configValue); + comboBox.addFocusListener(new FocusListener() { + public void focusGained(FocusEvent arg0) { + // do nothing + } + public void focusLost(FocusEvent arg0) { + item.setNewValue((String)comboBox.getSelectedItem()); + } + } + ); + panel.add(comboBox); + break; case STRING: - default: { - JFormattedTextField textField = new JFormattedTextField(); + default: // default like String + final JFormattedTextField textField = new JFormattedTextField(); textField.setValue(configValue); + textField.addFocusListener(new FocusListener() { + public void focusGained(FocusEvent arg0) { + // do nothing + } + public void focusLost(FocusEvent arg0) { + item.setNewValue(textField.getText()); + } + } + ); panel.add(textField); + break; } + } + + private void setupButtonPanel() { + buttonPanel.removeAll(); + + // save button + if (Config.isFilePathDefined()) { + JButton saveButton = new JButton(LocalText.getText("SAVE")); + saveButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.saveConfig(); + } + } + ); + buttonPanel.add(saveButton); } + + JButton saveAsButton = new JButton(LocalText.getText("SAVEAS")); + saveAsButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.saveAsConfig(); + } + } + ); + buttonPanel.add(saveAsButton); + + JButton cancelButton = new JButton(LocalText.getText("CANCEL")); + cancelButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.cancelConfig(); + } + } + ); + buttonPanel.add(cancelButton); + } private void saveConfig() { this.dispose(); } + private void saveAsConfig() { + JFileChooser fc = new JFileChooser(); + fc.setFileFilter( + new FileFilter() { + public boolean accept( File f ){ + return f.isDirectory() || + f.getName().toLowerCase().endsWith( ".rails_config" ); + } + public String getDescription() { + return "Rails Config"; + } + } + ); + + int state = fc.showOpenDialog( null ); + if ( state == JFileChooser.APPROVE_OPTION ) + { + File file = fc.getSelectedFile(); + Config.setActiveFilepath(file.getPath()); + } + } + private void cancelConfig() { this.dispose(); } Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-17 15:06:13 UTC (rev 1343) +++ trunk/18xx/rails/util/Config.java 2010-07-17 20:27:23 UTC (rev 1344) @@ -8,10 +8,13 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.Set; import org.apache.log4j.Logger; @@ -31,13 +34,6 @@ protected static Logger log = Logger.getLogger(Config.class.getPackage().getName()); - - /** - * Defines possible types (Java classes used as types in ConfigItem below - */ - public static enum ConfigType { - INTEGER, FLOAT, STRING, BOOLEAN, DIRECTORY, COLOR; - } /** XML setup */ private static final String CONFIG_XML_DIR = "data"; @@ -59,12 +55,11 @@ private static final String TEST_PROFILE_SELECTION = "test"; private static final String DEFAULT_PROFILE_SELECTION = "default"; private static final String DEFAULT_PROFILE_PROPERTY = "default.profile"; - private static final String STANDARD_PROFILE_PROPERTY = "standard.profile"; + private static final String STANDARD_PROFILE_SELECTION = "user"; /** selected profile */ private static String selectedProfile; private static boolean legacyConfigFile; - private static boolean standardProfile; /** properties storage. */ private static Properties defaultProperties = new Properties(); @@ -157,20 +152,13 @@ } -// /** -// * store user config file -// */ -// public static boolean saveUserConfig() { -// } -// -// /** -// * @return if user location is defined -// */ -// public static boolean hasUserLocation() { -// return userConfigFile != null; -// } + /** + * @return if user location is defined + */ + public static boolean isFilePathDefined() { + return Util.hasValue(userProfiles.getProperty(selectedProfile)); + } - private static boolean storePropertyFile(Properties properties, String filepath) { File outFile = new File(filepath); boolean result = true; @@ -192,24 +180,46 @@ /** * change active Profile */ - public static boolean setActiveProfile(String profileName) { - boolean result = loadPropertyProfile(profileName); - if (result) selectedProfile = profileName; - return result; + public static boolean changeActiveProfile(String profileName) { + readConfigSetupXML(); + loadPropertyProfile(profileName); + selectedProfile = profileName; + return true; } + private static Map<String, String> convertProperties(Properties properties) { + Map<String, String> converted = new HashMap<String, String>(); + for (Object key:properties.keySet()) { + converted.put((String) key, (String) properties.get(key)); + } + return converted; + } + + + /** + * get all default profiles + */ + public static List<String> getDefaultProfiles() { + List<String> profiles = new ArrayList<String>(convertProperties(defaultProfiles).keySet()); + profiles.remove(DEFAULT_PROFILE_PROPERTY); + Collections.sort(profiles); + return profiles; + } + + /** + * get all user profiles + */ + public static List<String> getUserProfiles() { + List<String> profiles = new ArrayList<String>(convertProperties(userProfiles).keySet()); + Collections.sort(profiles); + return profiles; + } + /** * returns name of (active) default profile */ public static String getDefaultProfileName() { - String defaultProfileName = null; - if (isUserProfileActive()) { - defaultProfileName = userProfiles.getProperty(DEFAULT_PROFILE_PROPERTY); - if (defaultProfileName == null) { -// return - } - } - return defaultProfileName; + return userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); } /** @@ -235,13 +245,6 @@ } /** - * returns true if active profile is a user profile - */ - public static boolean isUserProfileActive() { - return userProfiles.getProperty(selectedProfile) != null; - } - - /** * activates settings used for testing */ public static void setConfigTest() { @@ -290,9 +293,8 @@ } /* if nothing has selected so far, choose standardProfile */ - standardProfile = false; if (!Util.hasValue(configSelection)) { - standardProfile = true; + configSelection = STANDARD_PROFILE_SELECTION; } selectedProfile = configSelection; @@ -303,7 +305,7 @@ private static void initialLoad() { if (legacyConfigFile) { if (!propertiesLoaded) { - loadPropertyFile(defaultProperties, selectedProfile, true, false); + loadPropertyFile(defaultProperties, selectedProfile, false); propertiesLoaded = true; setSaveDirDefaults(); } @@ -311,45 +313,47 @@ } if (!profilesLoaded) { - loadPropertyFile(defaultProfiles, defaultProfilesFile, true, false); - loadPropertyFile(userProfiles, userProfilesFile, false, false); + loadPropertyFile(defaultProfiles, defaultProfilesFile, true); + loadPropertyFile(userProfiles, userProfilesFile, false); profilesLoaded = true; } - if (standardProfile) { - selectedProfile = userProfiles.getProperty(STANDARD_PROFILE_PROPERTY); - if (selectedProfile == null) { - selectedProfile = defaultProfiles.getProperty(STANDARD_PROFILE_PROPERTY); - } - if (selectedProfile == null) { - selectedProfile = DEFAULT_PROFILE_SELECTION; - } - } - /* Tell the properties loader to read this file. */ log.info("Selected profile = " + selectedProfile); if (!propertiesLoaded) { - propertiesLoaded = loadPropertyProfile(selectedProfile); + loadPropertyProfile(selectedProfile); + propertiesLoaded = true; } } - private static boolean loadPropertyProfile(String profileName) { + /** + * loads a user profile and the according default profile + * if not defined or loadable, creates a default user profile + */ + private static void loadPropertyProfile(String userProfile) { + // reset properties + userProperties = new Properties(); + defaultProperties = new Properties(); - /* first check if it is a default profile */ - String defaultConfigFile = defaultProfiles.getProperty(profileName); + // check if the profile is already defined under userProfiles + String userConfigFile = userProfiles.getProperty(userProfile); + String defaultConfigFile = null; + if (Util.hasValue(userConfigFile) && // load user profile + loadPropertyFile(userProperties, userConfigFile, false)) { + String defaultConfig = userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); + if (defaultConfig != null) { + defaultConfigFile = defaultProfiles.getProperty(defaultConfig); + } + } else { + userProfiles.setProperty(userProfile, ""); + } if (defaultConfigFile == null) { - String userConfigFile = userProfiles.getProperty(profileName); - if (userConfigFile == null) return false; - loadPropertyFile(userProperties, userConfigFile, false, false); - defaultConfigFile = userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); - if (defaultConfigFile == null) { - defaultConfigFile = defaultProfiles.getProperty(DEFAULT_PROFILE_SELECTION); - } + defaultConfigFile = defaultProfiles.getProperty(DEFAULT_PROFILE_SELECTION); + userProperties.setProperty(DEFAULT_PROFILE_PROPERTY, DEFAULT_PROFILE_SELECTION); } - loadPropertyFile(defaultProperties, defaultConfigFile, true, false); + loadPropertyFile(defaultProperties, defaultConfigFile, true); setSaveDirDefaults(); - return true; } /** @@ -357,11 +361,11 @@ * * @param filename - file key name as a String. * @param resource - if TRUE, loaded from jar (via classloader), otherwise from filesystem - * @param required - if TRUE, an exception will be logged if the file does - * not exist. + * @return TRUE if load was successful */ - private static void loadPropertyFile(Properties properties, String filename, boolean resource, boolean required) { + private static boolean loadPropertyFile(Properties properties, String filename, boolean resource) { + boolean result = true; try { log.info("Loading properties from file " + filename); InputStream inFile; @@ -371,15 +375,13 @@ inFile = new FileInputStream(filename); } properties.load(inFile); - } catch (FileNotFoundException FNFE) { - if (required) { - System.err.println("File not found: " + filename); - } } catch (Exception e) { System.err.println(e + " whilst loading properties file " + filename); e.printStackTrace(System.err); + result = false; } + return result; } private static void setSaveDirDefaults() { Modified: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java 2010-07-17 15:06:13 UTC (rev 1343) +++ trunk/18xx/rails/util/ConfigItem.java 2010-07-17 20:27:23 UTC (rev 1344) @@ -2,21 +2,38 @@ import java.util.Arrays; import java.util.List; + +import org.apache.log4j.Logger; + import rails.game.ConfigurationException; -import rails.util.Config.ConfigType; /** * Defines an item used for the configuration of rails * T represents the value type */ -public class ConfigItem { +public final class ConfigItem { + + protected static Logger log = + Logger.getLogger(ConfigItem.class.getPackage().getName()); + + /** + * Defines possible types (Java classes used as types in ConfigItem below + */ + public static enum ConfigType { + INTEGER, FLOAT, STRING, BOOLEAN, LIST, DIRECTORY, COLOR; + } + + // static attributes public final String name; public final ConfigType type; public final List<String> allowedValues; public final String formatMask; public final String helpText; + // dynamic attributes + private String newValue; + ConfigItem(Tag tag) throws ConfigurationException { // check name and type (required) String name = tag.getAttributeAsString("name"); @@ -25,29 +42,68 @@ } else { throw new ConfigurationException("Missing name for configuration item"); } - String type = tag.getAttributeAsString("type"); - if (Util.hasValue(type)) { - this.type = ConfigType.valueOf(type); - } else { - throw new ConfigurationException("Missing or invalid type for configuration item"); - } // optional: list of allowed values String valueString = tag.getAttributeAsString("values"); if (Util.hasValue(valueString)) { allowedValues = Arrays.asList(valueString.split(",")); + this.type = ConfigType.LIST; } else { allowedValues = null; + String type = tag.getAttributeAsString("type"); + if (Util.hasValue(type)) { + try { + this.type = ConfigType.valueOf(type.toUpperCase()); + } catch (Exception e) { + throw new ConfigurationException("Missing or invalid type for configuration item"); + } + } else { + throw new ConfigurationException("Missing or invalid type for configuration item"); + } + if (this.type == ConfigType.LIST) { + throw new ConfigurationException("No values defined for LIST config item"); + } } + // optional: formatMask formatMask = tag.getAttributeAsString("formatMask"); // optional: helpText helpText = tag.getAttributeAsString("formatMask"); + + newValue = null; } + public boolean hasNewValue() { + return (newValue != null); + } + + public String getNewValue() { + return newValue; + } + + public void setNewValue(String newValue) { + if (newValue.equals(getConfigValue())) { + this.newValue = null; + } else { + this.newValue = newValue; + } + log.debug("ConfigItem " + name + " set to new value " + this.newValue); + } + + public String getCurrentValue() { + if (newValue != null) return newValue; + return getConfigValue(); + } + + public String getConfigValue() { + return Config.get(this.name); + } + public String toString() { StringBuffer s = new StringBuffer(); s.append("Configuration Item: name = " + name + ", type = " + type); + s.append(", config value = " + getConfigValue()); + s.append(", current value = " + getCurrentValue()); if (allowedValues != null) { s.append(", allowedValues = " + allowedValues); } @@ -57,6 +113,7 @@ if (helpText != null) { s.append(", helpText = " + helpText); } + return s.toString(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-17 15:06:21
|
Revision: 1343 http://rails.svn.sourceforge.net/rails/?rev=1343&view=rev Author: evos Date: 2010-07-17 15:06:13 +0000 (Sat, 17 Jul 2010) Log Message: ----------- Simplified addXxxx methods by using the new Util.addToList. Applied Phil's patch to add more private info Modified Paths: -------------- trunk/18xx/.settings/org.eclipse.jdt.core.prefs trunk/18xx/rails/game/City.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/PrivateCompany.java trunk/18xx/rails/game/StockRound.java trunk/18xx/rails/game/move/ObjectMove.java trunk/18xx/rails/util/Util.java Property Changed: ---------------- trunk/18xx/data/ Modified: trunk/18xx/.settings/org.eclipse.jdt.core.prefs =================================================================== --- trunk/18xx/.settings/org.eclipse.jdt.core.prefs 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/.settings/org.eclipse.jdt.core.prefs 2010-07-17 15:06:13 UTC (rev 1343) @@ -1,248 +1,258 @@ -#Tue Jun 03 20:16:50 GMT+01:00 2008 -eclipse.preferences.version=1 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=16 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=18 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=0 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false -org.eclipse.jdt.core.formatter.comment.format_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -org.eclipse.jdt.core.formatter.comment.format_html=false -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=80 -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=true -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=80 -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=space -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +#Sun Jul 04 20:27:07 CEST 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=16 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=18 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=0 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false +org.eclipse.jdt.core.formatter.comment.format_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false +org.eclipse.jdt.core.formatter.comment.indent_root_tags=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=true +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false Property changes on: trunk/18xx/data ___________________________________________________________________ Added: svn:ignore + MyGames.xml Modified: trunk/18xx/rails/game/City.java =================================================================== --- trunk/18xx/rails/game/City.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/City.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -93,21 +93,11 @@ public boolean addToken(TokenI token, int position) { - if (tokens.contains(token)) { - return false; - } else { - token.setHolder(this); - if (position == -1) { - return tokens.add(token); - } else { - try { - tokens.add(position, token); - return true; - } catch (IndexOutOfBoundsException e) { - return false; - } - } - } + if (tokens.contains(token)) return false; + + boolean result = Util.addToList(tokens, token, position); + if (result) token.setHolder(this); + return result; } public boolean addObject(Moveable object, int position) { Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/GameManager.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -1537,16 +1537,7 @@ if (commonSpecialProperties == null) { commonSpecialProperties = new ArrayList<SpecialPropertyI>(2); } - if (position == -1) { - return commonSpecialProperties.add(property); - } else { - try { - commonSpecialProperties.add(position, property); - return true; - } catch (IndexOutOfBoundsException e) { - return false; - } - } + return Util.addToList(commonSpecialProperties, property, position); } /** Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/MapHex.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -794,19 +794,11 @@ offStationTokens = new ArrayList<TokenI>(); if (offStationTokens.contains(token)) { return false; - } else { - token.setHolder(this); - if (position == -1) { - return offStationTokens.add(token); - } else { - try { - offStationTokens.add(position, token); - return true; - } catch (IndexOutOfBoundsException e) { - return false; - } - } } + + boolean result = Util.addToList(offStationTokens, token, position); + if (result) token.setHolder(this); + return result; } public List<BaseToken> getBaseTokens () { Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -107,14 +107,9 @@ } public void addPrivate(PrivateCompanyI privateCompany, int position) { - if (position == -1) { - privateCompanies.add(privateCompany); - } else { - try { - privateCompanies.add(position, privateCompany); - } catch (IndexOutOfBoundsException e) { - } - } + + if (!Util.addToList(privateCompanies, privateCompany, position)) return; + privateCompany.setHolder(this); log.debug("Adding " + privateCompany.getName() + " to portfolio of " + name); @@ -135,16 +130,8 @@ certPerCompany.put(companyName, new ArrayList<PublicCertificateI>()); } - if (position == -1) { - certificates.add(certificate); - (certPerCompany.get(companyName)).add(certificate); - } else { - try { - certificates.add(position, certificate); - (certPerCompany.get(companyName)).add(position, certificate); - } catch (IndexOutOfBoundsException e) { - } - } + Util.addToList(certificates, certificate, position); + (certPerCompany.get(companyName)).add(certificate); String certTypeId = certificate.getTypeId(); if (!certsPerType.containsKey(certTypeId)) { @@ -387,14 +374,8 @@ } public void addTrain(TrainI train, int position) { - if (position == -1) { - trains.add(train); - } else { - try { - trains.add(position, train); - } catch (IndexOutOfBoundsException e) { - } - } + + Util.addToList(trains, train, position); TrainTypeI type = train.getType(); if (!trainsPerType.containsKey(type)) { trainsPerType.put(type, new ArrayList<TrainI>()); @@ -534,19 +515,14 @@ */ public boolean addSpecialProperty(SpecialPropertyI property, int position) { - boolean result = false; if (specialProperties == null) { specialProperties = new ArrayList<SpecialPropertyI>(2); } - if (position == -1) { - specialProperties.add(property); - } else { - try { - specialProperties.add(position, property); - } catch (IndexOutOfBoundsException e) { - } - } + + boolean result = Util.addToList(specialProperties, property, position); + if (!result) return false; + property.setHolder(this); // Special case for bonuses with predefined locations @@ -734,16 +710,8 @@ } public boolean addToken(TokenI token, int position) { - if (position == -1) { - return tokens.add(token); - } else { - try { - tokens.add(position, token); - return true; - } catch (IndexOutOfBoundsException e) { - return false; - } - } + + return Util.addToList(tokens, token, position); } public boolean removeToken(TokenI token) { Modified: trunk/18xx/rails/game/PrivateCompany.java =================================================================== --- trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/PrivateCompany.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -2,6 +2,7 @@ package rails.game; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import rails.game.move.*; @@ -54,7 +55,14 @@ // sfy 1889 changed to IntegerArray revenue = tag.getAttributeAsIntegerArray("revenue", new int[0]); - + + // pld: adding revenue to info text + infoText += "<br>Revenue: "; + for (int i = 0; i < revenue.length;i++) { + infoText += (Bank.format(revenue[i])); + if (i < revenue.length-1) {infoText += ", ";}; + } + // Blocked hexes (until bought by a company) Tag blockedTag = tag.getChild("Blocking"); if (blockedTag != null) { @@ -327,16 +335,7 @@ */ public boolean addObject(Moveable object, int position) { if (object instanceof SpecialPropertyI) { - if (position == -1) { - return specialProperties.add((SpecialPropertyI)object); - } else { - try { - specialProperties.add(position, (SpecialPropertyI)object); - return true; - } catch (IndexOutOfBoundsException e) { - return false; - } - } + return Util.addToList(specialProperties, (SpecialPropertyI)object, position); } else { return false; } Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/StockRound.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -190,7 +190,7 @@ stockSpace = comp.getCurrentSpace(); if ((stockSpace == null || !stockSpace.isNoCertLimit()) && !mayPlayerBuyCertificate( currentPlayer, comp, cert.getCertificateCount())) continue; - + shares = cert.getShares(); if (!cert.isPresidentShare()) { @@ -285,7 +285,7 @@ /* Would the player exceed the total certificate limit? */ if (!stockSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, comp, + && !mayPlayerBuyCertificate(currentPlayer, comp, number * uniqueCerts[shares].getCertificateCount())) continue; } @@ -766,7 +766,6 @@ break; } - //price = currentSpace.getPrice(); price = getBuyPrice (action, currentSpace); cost = shares * price / company.getShareUnitsForSharePrice(); @@ -1461,8 +1460,8 @@ company.getCurrentSpace().isNoHoldLimit() ? 100 : playerShareLimit; } - int maxAllowed = (limit - player.getPortfolio().getShare(company)) / shareSize; -// log.debug("MaxAllowedNumberOfSharesToBuy = " + maxAllowed + " for company = " + company + " shareSize " + shareSize); + int maxAllowed = (limit - player.getPortfolio().getShare(company)) / shareSize; + // log.debug("MaxAllowedNumberOfSharesToBuy = " + maxAllowed + " for company = " + company + " shareSize " + shareSize); return maxAllowed; } Modified: trunk/18xx/rails/game/move/ObjectMove.java =================================================================== --- trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/game/move/ObjectMove.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -19,15 +19,13 @@ /** * Create a generic ObjectMove object. Any specific side effects must be - * implemented in the addToken and removeToken methods of the 'from' and - * 'to' TokenHolders. <p>The parameter descriptions cover the usual case of - * a Base Token lay, which is physically removed from a PublicCompany and - * added to a Station on a MapHex. + * implemented in the various addXxxx and removeXxxx methods of the 'from' and + * 'to' MoveableHolders, depending on the object type. * - * @param moveableObject The moveableObject to be moved (e.g. a BaseToken). - * @param from Where the moveableObject is removed from (e.g. a - * PublicCompany charter). + * @param moveableObject The object to be moved (e.g. a BaseToken). + * @param from Where the moveableObject is removed from (e.g. a PublicCompany charter). * @param to Where the moveableObject is moved to (e.g. a MapHex). + * It is moved to the end of the List in which the moved object type is stored. */ public ObjectMove(Moveable moveableObject, MoveableHolder from, @@ -35,6 +33,18 @@ this (moveableObject, from, to, -1); } + /** + * Create a generic ObjectMove object. Any specific side effects must be + * implemented in the various addXxxx and removeXxxx methods of the 'from' and + * 'to' MoveableHolders, depending on the object type. + * + * @param moveableObject The object to be moved (e.g. a BaseToken). + * @param from Where the moveableObject is removed from (e.g. a PublicCompany charter). + * @param to Where the moveableObject is moved to (e.g. a MapHex). + * @param toPosition At which List index in the 'to' holder the object must be inserted, + * -1 means at the end. + */ + public ObjectMove(Moveable moveableObject, MoveableHolder from, MoveableHolder to, int toPosition) { Modified: trunk/18xx/rails/util/Util.java =================================================================== --- trunk/18xx/rails/util/Util.java 2010-07-17 11:08:38 UTC (rev 1342) +++ trunk/18xx/rails/util/Util.java 2010-07-17 15:06:13 UTC (rev 1343) @@ -65,13 +65,13 @@ return bitmask | value; } else { System.out.println("Reset bit " + value + ": from " + bitmask - + " to " + (bitmask & ~value)); + + " to " + (bitmask & ~value)); return bitmask & ~value; } } /** - * Safely move objects from one holder to another, avoiding + * Safely move a list of objects from one holder to another, avoiding * ConcurrentModificationExceptions. * * @param from @@ -93,6 +93,29 @@ } + /** Safely add an object to a List at a given position + * @param objects The List to add the object to. + * @param object The object to be added. + * @param position The position at which the object must be added. + * <br>If between 0 and the current list size (inclusive), the object is inserted at + * the given position.<br>If -1, the object is inserted at the end. + * <br>If any other value, nothing is done. + * @return True if the insertion was successful. + * */ + public static <T extends Moveable, U extends T> boolean addToList (List<T> objects, + U object, int position) { + if (objects == null || object == null) { + return false; + } + if (position == -1) { + return objects.add(object); + } else if (position >= 0 && position <= objects.size()){ + objects.add(position, object); + return true; + } + return false; + } + /** * Parse a colour definition string. * Currently supported formats: @@ -117,8 +140,8 @@ try { String[] parts = s.split(","); c = new Color (Integer.parseInt(parts[0]), - Integer.parseInt(parts[1]), - Integer.parseInt(parts[2])); + Integer.parseInt(parts[1]), + Integer.parseInt(parts[2])); } catch (NumberFormatException e) { getLogger().error ("Invalid nummeric RGB colour: "+s, e); throw new ConfigurationException (e); @@ -133,8 +156,8 @@ public static boolean isDark(Color c) { if (c == null) return false; return Math.sqrt(0.241*c.getRed()*c.getRed() - + 0.691*c.getBlue()*c.getBlue() - + 0.068*c.getGreen()*c.getGreen()) < 128; + + 0.691*c.getBlue()*c.getBlue() + + 0.068*c.getGreen()*c.getGreen()) < 128; // Copied this formula from // http://www.nbdtech.com/blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ev...@us...> - 2010-07-17 11:08:45
|
Revision: 1342 http://rails.svn.sourceforge.net/rails/?rev=1342&view=rev Author: evos Date: 2010-07-17 11:08:38 +0000 (Sat, 17 Jul 2010) Log Message: ----------- All addObject() and related methods now take a position argument. ObjectMove has an additional fromPosition attribute. Also toPosition, but that isn't used yet. This all is used to ensure that Undo always restores the original List order for moves executed via ObjectMove. Also fixed a bug that allowed price tokens to vanish into the empty upper left corner of the 1835 stock chart. Modified Paths: -------------- trunk/18xx/rails/game/Bank.java trunk/18xx/rails/game/City.java trunk/18xx/rails/game/Company.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/game/OperatingRound.java trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/PrivateCompany.java trunk/18xx/rails/game/PublicCompany.java trunk/18xx/rails/game/PublicCompanyI.java trunk/18xx/rails/game/StockMarket.java trunk/18xx/rails/game/Token.java trunk/18xx/rails/game/TokenHolder.java trunk/18xx/rails/game/TrainType.java trunk/18xx/rails/game/move/MoveableHolder.java trunk/18xx/rails/game/move/ObjectMove.java Property Changed: ---------------- trunk/18xx/ Property changes on: trunk/18xx ___________________________________________________________________ Modified: svn:ignore - *.bat *.txt .cvsignore .classpath .externalToolBuilders 18xx.zip deploy.xml .project zip.xml NewUIstuff.zip COMP.WPS rails.jar rails.jardesc Rails-1.0.1.jar my_my.properties log rails-1.0.1.jar rails*.zip rails-*.jar tools rails-?.*.* jar/* classes/* + *.bat *.txt .cvsignore .classpath .externalToolBuilders 18xx.zip deploy.xml .project zip.xml NewUIstuff.zip COMP.WPS rails.jar rails.jardesc Rails-1.0.1.jar my_my.properties log rails-1.0.1.jar rails*.zip rails-*.jar tools rails-?.*.* jar/* classes/* 18xx_autosave.rails 18xx_autosave.rails.tmp Modified: trunk/18xx/rails/game/Bank.java =================================================================== --- trunk/18xx/rails/game/Bank.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/Bank.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -31,8 +31,8 @@ /** Is the bank broken (remains true once set) */ private BooleanState broken = new BooleanState("Bank.broken", false); -// /** Is the bank just broken (returns true exactly once) */ -// private BooleanState brokenReported = new BooleanState("Bank.brokenReported", false); + // /** Is the bank just broken (returns true exactly once) */ + // private BooleanState brokenReported = new BooleanState("Bank.brokenReported", false); /** * The money format template. '@' is replaced by the numeric amount, the @@ -41,7 +41,7 @@ private String moneyFormat = null; protected static Logger log = - Logger.getLogger(Bank.class.getPackage().getName()); + Logger.getLogger(Bank.class.getPackage().getName()); public Bank() { @@ -98,7 +98,7 @@ List<PrivateCompanyI> privates = gameManager.getCompanyManager().getAllPrivateCompanies(); for (PrivateCompanyI priv : privates) { - ipo.addPrivate(priv); + ipo.addPrivate(priv, -1); } // Add public companies @@ -107,13 +107,13 @@ for (PublicCompanyI comp : companies) { for (PublicCertificateI cert : comp.getCertificates()) { if (cert.isInitiallyAvailable()) { - ipo.addCertificate(cert); - } else { - unavailable.addCertificate(cert); - } + ipo.addCertificate(cert, -1); + } else { + unavailable.addCertificate(cert, -1); + } } } -} + } /** * @return IPO Portfolio @@ -154,11 +154,11 @@ return broken.booleanValue(); } -// public boolean isJustBroken() { -// boolean result = broken.booleanValue() && !brokenReported.booleanValue(); -// brokenReported.set(true); -// return result; -// } + // public boolean isJustBroken() { + // boolean result = broken.booleanValue() && !brokenReported.booleanValue(); + // brokenReported.set(true); + // return result; + // } /** * @return Portfolio of stock in Bank Pool Modified: trunk/18xx/rails/game/City.java =================================================================== --- trunk/18xx/rails/game/City.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/City.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -37,12 +37,12 @@ private String trackEdges; protected static Logger log = - Logger.getLogger(City.class.getPackage().getName()); + Logger.getLogger(City.class.getPackage().getName()); public City(MapHex mapHex, int number, Station station) { this.mapHex = mapHex; this.number = number; - + uniqueId = mapHex.getName() + "_" + number; relatedStation = new GenericState<Station>("City_"+uniqueId+"_station", station); setRelatedStation(station); @@ -53,7 +53,7 @@ public String getName() { return mapHex.getName() + "/" + number; - + } /** @@ -75,9 +75,9 @@ this.relatedStation.set(relatedStation); slots = relatedStation.getBaseSlots(); trackEdges = - mapHex.getConnectionString(mapHex.getCurrentTile(), - mapHex.getCurrentTileRotation(), - relatedStation.getNumber()); + mapHex.getConnectionString(mapHex.getCurrentTile(), + mapHex.getCurrentTileRotation(), + relatedStation.getNumber()); } public void setSlots(int slots) { @@ -91,20 +91,28 @@ return uniqueId; } - public boolean addToken(TokenI token) { + public boolean addToken(TokenI token, int position) { if (tokens.contains(token)) { return false; } else { token.setHolder(this); - boolean result = tokens.add(token); - return result; + if (position == -1) { + return tokens.add(token); + } else { + try { + tokens.add(position, token); + return true; + } catch (IndexOutOfBoundsException e) { + return false; + } + } } } - public boolean addObject(Moveable object) { + public boolean addObject(Moveable object, int position) { if (object instanceof TokenI) { - return addToken((TokenI) object); + return addToken((TokenI) object, position); } else { return false; } @@ -133,7 +141,7 @@ public boolean hasTokenSlotsLeft() { return tokens.size() < slots; } - + public int getTokenSlotsLeft () { return slots - tokens.size(); } @@ -148,13 +156,13 @@ * @param company * @return true if this City already contains an instance of the specified * company's token. Do this by calling the hasTokenOf with Company Name. - * Using a tokens.contains(company) fails since the tokens are a ArrayList + * Using a tokens.contains(company) fails since the tokens are a ArrayList * of TokenI not a ArrayList of PublicCompanyI. */ public boolean hasTokenOf(PublicCompanyI company) { return hasTokenOf (company.getName()); } - + public boolean hasTokenOf (String companyName) { for (TokenI token : tokens) { if (token instanceof BaseToken @@ -165,6 +173,14 @@ return false; } + public int getListIndex (Moveable object) { + if (object instanceof BaseToken) { + return tokens.indexOf(object); + } else { + return -1; + } + } + public void setTokens(ArrayList<TokenI> tokens) { this.tokens = tokens; } Modified: trunk/18xx/rails/game/Company.java =================================================================== --- trunk/18xx/rails/game/Company.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/Company.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -13,13 +13,13 @@ import rails.util.Util; public abstract class Company implements CompanyI, ConfigurableComponentI, - Cloneable, Comparable<Company> { +Cloneable, Comparable<Company> { protected String name; protected String longName; protected CompanyTypeI type; protected int companyNumber; // For internal use - + /* Note: portfolio is used in two ways: * In private companies, it is primarily the portfolio that holds this private. * In public companies, it is the portfolio of this company. @@ -42,12 +42,12 @@ /** Closed state */ protected BooleanState closedObject; - + // Moved here from PrivayeCOmpany on behalf of 1835 protected List<SpecialPropertyI> specialProperties = null; - + protected static Logger log = - Logger.getLogger(Company.class.getPackage().getName()); + Logger.getLogger(Company.class.getPackage().getName()); public Company() { } @@ -60,7 +60,7 @@ /** Only to be called from subclasses */ public void configureFromXML(Tag tag) throws ConfigurationException { - + // Special properties Tag spsTag = tag.getChild("SpecialProperties"); if (spsTag != null) { @@ -71,7 +71,7 @@ className = spTag.getAttributeAsString("class"); if (!Util.hasValue(className)) throw new ConfigurationException( - "Missing class in private special property"); + "Missing class in private special property"); SpecialPropertyI sp = null; try { sp = (SpecialPropertyI) Class.forName(className).newInstance(); @@ -87,7 +87,7 @@ } } } - + /** * @return ArrayList of all special properties we have. */ @@ -214,30 +214,30 @@ * * Use addToken(MapHex hex) method instead. */ - public boolean addToken(CompanyI company) { + public boolean addToken(CompanyI company, int position) { return false; } @Override public String toString() { return getTypeName() + ": " + getCompanyNumber() + ". " + getName() - + " $" + this.getValue(); + + " $" + this.getValue(); } public boolean equals(CompanyI company) { if (this.companyNumber == company.getCompanyNumber() - && this.name.equals(company.getName()) - && this.type.equals(company.getType())) return true; + && this.name.equals(company.getName()) + && this.type.equals(company.getType())) return true; return false; } - + public int compareTo(Company otherCompany){ int result; // compare typeNames first result = this.getTypeName().compareTo(otherCompany.getTypeName()); // if same typeName then name - if (result == 0) + if (result == 0) result = this.getName().compareTo(otherCompany.getName()); return result; Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/GameManager.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -187,7 +187,7 @@ /** A List of available game options */ protected List<GameOption> availableGameOptions = new ArrayList<GameOption>(); - + /** indicates that the recoverySave already issued a warning, avoids displaying several warnings */ protected boolean recoverySaveWarning = true; @@ -812,7 +812,7 @@ if (!isGameOver() && possibleActions.containsOnlyPass()) { result = process(possibleActions.getList().get(0)); } - + // moveStack closing is done here to allow state changes to occur // when setting possible actions if (action != null) { @@ -943,7 +943,7 @@ * */ protected void recoverySave() { if (Config.get("save.recovery.active", "yes").equalsIgnoreCase("no")) return; - + String filePath = Config.get("save.recovery.filepath", "18xx_autosave.rails"); // create temporary new save file File tempFile = null; @@ -978,7 +978,7 @@ recoverySaveWarning = false; return; } - + if (result) { log.debug("Renamed to recovery file, path = " + recoveryFile.getAbsolutePath()); if (!recoverySaveWarning) { @@ -992,12 +992,12 @@ } } } - + protected boolean save(GameAction saveAction) { File file = new File(saveAction.getFilepath()); return save(file, true, "SaveFailed"); } - + protected boolean save(File file, boolean displayErrorMessage, String errorMessageKey) { boolean result = false; @@ -1500,16 +1500,24 @@ * @param object The object to add. * @return True if successful. */ - public boolean addObject(Moveable object) { + public boolean addObject(Moveable object, int position) { if (object instanceof SpecialPropertyI) { SpecialPropertyI sp = (SpecialPropertyI) object; sp.setHolder(null); - return addSpecialProperty(sp); + return addSpecialProperty(sp, position); } else { return false; } } + public int getListIndex (Moveable object) { + if (object instanceof SpecialPropertyI) { + return commonSpecialProperties.indexOf(object); + } else { + return -1; + } + } + /** * Remove an object. * @@ -1524,12 +1532,21 @@ } } - public boolean addSpecialProperty(SpecialPropertyI property) { + public boolean addSpecialProperty(SpecialPropertyI property, int position) { if (commonSpecialProperties == null) { commonSpecialProperties = new ArrayList<SpecialPropertyI>(2); } - return commonSpecialProperties.add(property); + if (position == -1) { + return commonSpecialProperties.add(property); + } else { + try { + commonSpecialProperties.add(position, property); + return true; + } catch (IndexOutOfBoundsException e) { + return false; + } + } } /** Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/MapHex.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -38,15 +38,15 @@ * tiles the above picture should be rotated 30 degrees clockwise. */ public class MapHex extends ModelObject implements ConfigurableComponentI, - StationHolder, TokenHolder { +StationHolder, TokenHolder { public static final int EW = 0; public static final int NS = 1; private static final String[] ewOrNames = - { "SW", "W", "NW", "NE", "E", "SE" }; + { "SW", "W", "NW", "NE", "E", "SE" }; private static final String[] nsOrNames = - { "S", "SW", "NW", "N", "NE", "SE" }; + { "S", "SW", "NW", "N", "NE", "SE" }; // Coordinates as used in the rails.ui.swing.hexmap package protected int x; @@ -87,19 +87,19 @@ protected Map<Integer, City> mCities; /* - * changed to state variable to fix undo bug #2954645 + * changed to state variable to fix undo bug #2954645 * null as default implies false - see isBlocked() */ private BooleanState isBlockedForTileLays = null; - - /** + + /** * Is the hex initially blocked for token lays (e.g. when a home base * must first be laid)? <p> * NOTE:<br>null means: blocked unless there is more free space than unlaid home bases,<br> * false means: blocked unless there is any free space.<br> - * This makes a difference for 1835 Berlin, which is home to PR, but - * the absence of a PR token does not block the third slot - * when the green tile is laid. + * This makes a difference for 1835 Berlin, which is home to PR, but + * the absence of a PR token does not block the third slot + * when the green tile is laid. */ private BooleanState isBlockedForTokenLays = null; @@ -108,14 +108,14 @@ /** Tokens that are not bound to a Station (City), such as Bonus tokens */ protected List<TokenI> offStationTokens; - + /** Storage of revenueBonus that are bound to the hex */ protected List<RevenueBonusTemplate> revenueBonuses = null; protected MapManager mapManager = null; protected static Logger log = - Logger.getLogger(MapHex.class.getPackage().getName()); + Logger.getLogger(MapHex.class.getPackage().getName()); public MapHex(MapManager mapManager) { this.mapManager = mapManager; @@ -158,7 +158,7 @@ y = (row + 1) / 2; } } else - // letters go vertical (normal case) + // letters go vertical (normal case) { row = letter - '@'; column = number; @@ -190,13 +190,13 @@ // City name cityName = tag.getAttributeAsString("city", ""); if (Util.hasValue(cityName)) { - infoText += " " + cityName; + infoText += " " + cityName; } - + if (tag.getAttributeAsString("unlaidHomeBlocksTokens") != null) { setBlockedForTokenLays(tag.getAttributeAsBoolean("unlaidHomeBlocksTokens", false)); } - + // revenue bonus List<Tag> bonusTags = tag.getChildren("RevenueBonus"); if (bonusTags != null) { @@ -216,7 +216,7 @@ // stations. cities = new ArrayList<City>(4); mCities = new HashMap<Integer, City>(4); - for (Station s : currentTile.getStations()) { + for (Station s : currentTile.getStations()) { // sid, type, value, slots City c = new City(this, s.getNumber(), s); cities.add(c); @@ -251,8 +251,8 @@ */ TileI tile = neighbour.getCurrentTile(); if (!tile.isUpgradeable() - && !tile.hasTracks(3 + direction - - neighbour.getCurrentTileRotation())) + && !tile.hasTracks(3 + direction + - neighbour.getCurrentTileRotation())) return false; return true; @@ -319,7 +319,7 @@ public int getPreprintedTileId() { return preprintedTileId; } - + public int getPreprintedTileRotation() { return preprintedTileRotation; } @@ -374,7 +374,7 @@ return 0; } } - + public int[] getTileCostAsArray(){ return tileCost; } @@ -388,10 +388,10 @@ TileI newTile = action.getLaidTile(); int newRotation = action.getOrientation(); Map<String, Integer> relaidTokens = action.getRelaidBaseTokens(); - + upgrade(newTile, newRotation, relaidTokens); } - + /** * Prepare a tile upgrade. The actual tile replacement is done in * replaceTile(), via a TileMove object. @@ -427,12 +427,12 @@ if (citiesToStations.containsKey(city)) continue; Station oldStation = city.getRelatedStation(); int[] oldTrackEnds = - getTrackEndPoints(currentTile, currentTileRotation, - oldStation); + getTrackEndPoints(currentTile, currentTileRotation, + oldStation); if (oldTrackEnds.length == 0) continue; station: for (Station newStation : newTile.getStations()) { int[] newTrackEnds = - getTrackEndPoints(newTile, newRotation, newStation); + getTrackEndPoints(newTile, newRotation, newStation); for (int i = 0; i < oldTrackEnds.length; i++) { for (int j = 0; j < newTrackEnds.length; j++) { if (oldTrackEnds[i] == newTrackEnds[j]) { @@ -456,27 +456,27 @@ } - // Assign the new Stations to the existing cities - for (City city : citiesToStations.keySet()) { - Station newStation = citiesToStations.get(city); - Station oldStation = city.getRelatedStation(); - city.setRelatedStation(newStation); - city.setSlots(newStation.getBaseSlots()); - newTracks = - getConnectionString(newTile, - newRotation, - newStation.getNumber()); - city.setTrackEdges(newTracks); - log.debug("Assigned " - + city.getUniqueId() - + " from " - + oldStation.getId() - + " " - + getConnectionString(currentTile, - currentTileRotation, - oldStation.getNumber()) - + " to " + newStation.getId() + " " - + newTracks); + // Assign the new Stations to the existing cities + for (City city : citiesToStations.keySet()) { + Station newStation = citiesToStations.get(city); + Station oldStation = city.getRelatedStation(); + city.setRelatedStation(newStation); + city.setSlots(newStation.getBaseSlots()); + newTracks = + getConnectionString(newTile, + newRotation, + newStation.getNumber()); + city.setTrackEdges(newTracks); + log.debug("Assigned " + + city.getUniqueId() + + " from " + + oldStation.getId() + + " " + + getConnectionString(currentTile, + currentTileRotation, + oldStation.getNumber()) + + " to " + newStation.getId() + " " + + newTracks); } newCities = cities; @@ -490,7 +490,7 @@ Map<Integer, City> mNewCities = new HashMap<Integer, City>(4); Map<City, City> oldToNewCities = new HashMap<City, City>(); Map<Station, City> newStationsToCities = - new HashMap<Station, City>(); + new HashMap<Station, City>(); // Scan the old cities/stations, // and assign new stations where tracks correspond @@ -499,64 +499,64 @@ int cityNumber = oldCity.getNumber(); Station oldStation = oldCity.getRelatedStation(); int[] oldTrackEnds = - getTrackEndPoints(currentTile, currentTileRotation, - oldStation); + getTrackEndPoints(currentTile, currentTileRotation, + oldStation); log.debug("Old city #" - + currentTile.getId() - + " city " - + oldCity.getNumber() - + ": " - + getConnectionString(currentTile, - currentTileRotation, oldStation.getNumber())); + + currentTile.getId() + + " city " + + oldCity.getNumber() + + ": " + + getConnectionString(currentTile, + currentTileRotation, oldStation.getNumber())); station: for (Station newStation : newTile.getStations()) { int[] newTrackEnds = - getTrackEndPoints(newTile, newRotation, newStation); + getTrackEndPoints(newTile, newRotation, newStation); log.debug("New station #" - + newTile.getId() - + " station " - + newStation.getNumber() - + ": " - + getConnectionString(newTile, newRotation, - newStation.getNumber())); + + newTile.getId() + + " station " + + newStation.getNumber() + + ": " + + getConnectionString(newTile, newRotation, + newStation.getNumber())); for (int i = 0; i < oldTrackEnds.length; i++) { for (int j = 0; j < newTrackEnds.length; j++) { if (oldTrackEnds[i] == newTrackEnds[j]) { // Match found! if (!newStationsToCities.containsKey(newStation)) { newCity = - new City(this, ++newCityNumber, - newStation); + new City(this, ++newCityNumber, + newStation); newCities.add(newCity); mNewCities.put(cityNumber, newCity); newStationsToCities.put(newStation, newCity); newCity.setSlots(newStation.getBaseSlots()); } else { newCity = - newStationsToCities.get(newStation); + newStationsToCities.get(newStation); } oldToNewCities.put(oldCity, newCity); newTracks = - getConnectionString(newTile, - newRotation, - newStation.getNumber()); + getConnectionString(newTile, + newRotation, + newStation.getNumber()); newCity.setTrackEdges(newTracks); log.debug("Assigned from " - + oldCity.getUniqueId() - + " #" - + currentTile.getId() - + "/" - + currentTileRotation - + " " - + oldStation.getId() - + " " - + getConnectionString(currentTile, - currentTileRotation, - oldStation.getNumber()) - + " to " + newCity.getUniqueId() - + " #" + newTile.getId() + "/" - + newRotation + " " - + newStation.getId() + " " - + newTracks); + + oldCity.getUniqueId() + + " #" + + currentTile.getId() + + "/" + + currentTileRotation + + " " + + oldStation.getId() + + " " + + getConnectionString(currentTile, + currentTileRotation, + oldStation.getNumber()) + + " to " + newCity.getUniqueId() + + " #" + newTile.getId() + "/" + + newRotation + " " + + newStation.getId() + " " + + newTracks); break station; } } @@ -599,12 +599,12 @@ + getConnectionString(currentTile, currentTileRotation, oldStation.getNumber()) - + " to " + newCity.getUniqueId() - + " #" + newTile.getId() + "/" - + newRotation + " " - + newCity.getRelatedStation().getId() + " " - + newCity.getTrackEdges()); - break station; + + " to " + newCity.getUniqueId() + + " #" + newTile.getId() + "/" + + newRotation + " " + + newCity.getRelatedStation().getId() + " " + + newCity.getTrackEdges()); + break station; } @@ -629,17 +629,17 @@ newStationsToCities.put(newStation, newCity); newCity.setSlots(newStation.getBaseSlots()); newTracks = - getConnectionString(newTile, newRotation, - newStation.getNumber()); + getConnectionString(newTile, newRotation, + newStation.getNumber()); newCity.setTrackEdges(newTracks); log.debug("New city added " + newCity.getUniqueId() + " #" - + newTile.getId() + "/" + newRotation + " " - + newStation.getId() + " " + newTracks); + + newTile.getId() + "/" + newRotation + " " + + newStation.getId() + " " + newTracks); } // Move the tokens Map<TokenI, TokenHolder> tokenDestinations = - new HashMap<TokenI, TokenHolder>(); + new HashMap<TokenI, TokenHolder>(); for (City oldCity : cities) { newCity = oldToNewCities.get(oldCity); @@ -648,35 +648,35 @@ if (token instanceof BaseToken) { // Check if the new city already has such a token PublicCompanyI company = - ((BaseToken) token).getCompany(); + ((BaseToken) token).getCompany(); for (TokenI token2 : newCity.getTokens()) { if (token2 instanceof BaseToken - && company == ((BaseToken) token2).getCompany()) { + && company == ((BaseToken) token2).getCompany()) { // No duplicate tokens in one city! tokenDestinations.put(token, company); log.debug("Duplicate token " - + token.getUniqueId() - + " moved from " - + oldCity.getName() + " to " - + company.getName()); + + token.getUniqueId() + + " moved from " + + oldCity.getName() + " to " + + company.getName()); ReportBuffer.add(LocalText.getText( "DuplicateTokenRemoved", - company.getName(), - getName() )); + company.getName(), + getName() )); continue oldtoken; } } } tokenDestinations.put(token, newCity); log.debug("Token " + token.getUniqueId() - + " moved from " + oldCity.getName() + " to " - + newCity.getName()); + + " moved from " + oldCity.getName() + " to " + + newCity.getName()); } - if (!tokenDestinations.isEmpty()) { - for (TokenI token : tokenDestinations.keySet()) { - token.moveTo(tokenDestinations.get(token)); - } + if (!tokenDestinations.isEmpty()) { + for (TokenI token : tokenDestinations.keySet()) { + token.moveTo(tokenDestinations.get(token)); } + } } else { log.debug("No new city!?"); } @@ -705,16 +705,16 @@ if (oldTile != currentTile) { new Exception("ERROR! Hex " + name + " wants to replace tile #" - + oldTile.getId() + " but has tile #" - + currentTile.getId() + "!").printStackTrace(); + + oldTile.getId() + " but has tile #" + + currentTile.getId() + "!").printStackTrace(); } if (currentTile != null) { currentTile.remove(this); } log.debug("On hex " + name + " replacing tile " + currentTile.getId() - + "/" + currentTileRotation + " by " + newTile.getId() + "/" - + newTileOrientation); + + "/" + currentTileRotation + " by " + newTile.getId() + "/" + + newTileOrientation); newTile.lay(this); @@ -727,12 +727,12 @@ for (City city : cities) { mCities.put(city.getNumber(), city); log.debug("Tile #" - + newTile.getId() - + " station " - + city.getNumber() - + " has tracks to " - + getConnectionString(newTile, newTileOrientation, - city.getRelatedStation().getNumber())); + + newTile.getId() + + " station " + + city.getNumber() + + " has tracks to " + + getConnectionString(newTile, newTileOrientation, + city.getRelatedStation().getNumber())); } } /* TODO: Further consequences to be processed here, e.g. new routes etc. */ @@ -744,8 +744,8 @@ public boolean layBaseToken(PublicCompanyI company, int station) { if (cities == null || cities.isEmpty()) { log.error("Tile " + getName() - + " has no station for home token of company " - + company.getName()); + + " has no station for home token of company " + + company.getName()); return false; } City city = mCities.get(station); @@ -757,15 +757,15 @@ } else { token.moveTo(city); update(); - - if (isHomeFor(company) - && isBlockedForTokenLays != null + + if (isHomeFor(company) + && isBlockedForTokenLays != null && isBlockedForTokenLays.booleanValue()) { // Assume that there is only one home base on such a tile, // so we don't need to check for other ones isBlockedForTokenLays.set(false); } - + return true; } } @@ -788,7 +788,7 @@ } } - public boolean addToken(TokenI token) { + public boolean addToken(TokenI token, int position) { if (offStationTokens == null) offStationTokens = new ArrayList<TokenI>(); @@ -796,7 +796,16 @@ return false; } else { token.setHolder(this); - return offStationTokens.add(token); + if (position == -1) { + return offStationTokens.add(token); + } else { + try { + offStationTokens.add(position, token); + return true; + } catch (IndexOutOfBoundsException e) { + return false; + } + } } } @@ -826,9 +835,9 @@ return offStationTokens.remove(token); } - public boolean addObject(Moveable object) { + public boolean addObject(Moveable object, int position) { if (object instanceof TokenI) { - return addToken((TokenI) object); + return addToken((TokenI) object, position); } else { return false; } @@ -842,6 +851,16 @@ } } + public int getListIndex (Moveable object) { + if (object instanceof TokenI) { + return offStationTokens.indexOf(object); + } else { + return -1; + } + } + + + public boolean hasTokenSlotsLeft(int station) { if (station == 0) station = 1; // Temp. fix for old save files City city = mCities.get(station); @@ -849,7 +868,7 @@ return city.hasTokenSlotsLeft(); } else { log.error("Invalid station " + station + ", max is " - + (cities.size() - 1)); + + (cities.size() - 1)); return false; } } @@ -890,7 +909,7 @@ for (City city : cities) { for (TokenI token : city.getTokens()) { if (token instanceof BaseToken - && ((BaseToken) token).getCompany() == company) { + && ((BaseToken) token).getCompany() == company) { return city.getNumber(); } } @@ -905,7 +924,7 @@ public City getCity(int cityNumber) { return mCities.get(cityNumber); } - + public City getRelatedCity(Station station) { City foundCity = null; for (City city:mCities.values()) { @@ -986,7 +1005,7 @@ return true; } else { log.debug("Hex " + name + " tile #" + currentTile.getId() - + " is not upgradable now"); + + " is not upgradable now"); return false; } } @@ -1013,7 +1032,7 @@ * C) City is undecided => check all cities if there is a slot left */ public boolean isBlockedForTokenLays(PublicCompanyI company, int cityNumber) { - + if (isHomeFor(company)) // Company can always lay a home base return false; @@ -1079,16 +1098,16 @@ } public String getInfo () { - return infoText; + return infoText; } public List<RevenueBonusTemplate> getRevenueBonuses() { return revenueBonuses; } - + public boolean equals(MapHex hex) { if (hex.getName().equals(getName()) && hex.row == row - && hex.column == column) return true; + && hex.column == column) return true; return false; } @@ -1138,7 +1157,7 @@ public String getConnectionString(int cityNumber) { int stationNumber = - mCities.get(cityNumber).getRelatedStation().getNumber(); + mCities.get(cityNumber).getRelatedStation().getNumber(); return getConnectionString(currentTile, currentTileRotation, stationNumber); } Modified: trunk/18xx/rails/game/OperatingRound.java =================================================================== --- trunk/18xx/rails/game/OperatingRound.java 2010-07-16 21:31:11 UTC (rev 1341) +++ trunk/18xx/rails/game/OperatingRound.java 2010-07-17 11:08:38 UTC (rev 1342) @@ -5,7 +5,8 @@ import rails.common.GuiDef; import rails.game.action.*; -import rails.game.correct.*; +import rails.game.correct.ClosePrivate; +import rails.game.correct.OperatingCost; import rails.game.move.CashMove; import rails.game.move.MapChange; import rails.game.special.*; @@ -28,9 +29,9 @@ /* sfy: using rails without map support */ protected boolean noMapMode = false; - + protected List<PublicCompanyI> companiesOperatedThisRound - = new ArrayList<PublicCompanyI> (); + = new ArrayList<PublicCompanyI> (); protected List<PublicCompanyI> operatingCompanies; @@ -47,19 +48,19 @@ protected List<LayTile> currentNormalTileLays = new ArrayList<LayTile>(); protected Map<String, Integer> tileLaysPerColour = - new HashMap<String, Integer>(); + new HashMap<String, Integer>(); protected List<LayBaseToken> currentNormalTokenLays = - new ArrayList<LayBaseToken>(); + new ArrayList<LayBaseToken>(); protected List<LayBaseToken> currentSpecialTokenLays = - new ArrayList<LayBaseToken>(); + new ArrayList<LayBaseToken>(); /** A List per player with owned companies that have excess trains */ protected Map<Player, List<PublicCompanyI>> excessTrainCompanies = null; protected List<TrainTypeI> trainsBoughtThisTurn = - new ArrayList<TrainTypeI>(4); + new ArrayList<TrainTypeI>(4); protected Map<PublicCompanyI, Integer> loansThisRound = null; @@ -71,17 +72,17 @@ public static final int SPLIT_ROUND_DOWN = 2; // More to the treasury -// protected static GameDef.OrStep[] steps = - protected GameDef.OrStep[] steps = - new GameDef.OrStep[] { - GameDef.OrStep.INITIAL, - GameDef.OrStep.LAY_TRACK, - GameDef.OrStep.LAY_TOKEN, - GameDef.OrStep.CALC_REVENUE, - GameDef.OrStep.PAYOUT, - GameDef.OrStep.BUY_TRAIN, - GameDef.OrStep.TRADE_SHARES, - GameDef.OrStep.FINAL }; + // protected static GameDef.OrStep[] steps = + protected GameDef.OrStep[] steps = + new GameDef.OrStep[] { + GameDef.OrStep.INITIAL, + GameDef.OrStep.LAY_TRACK, + GameDef.OrStep.LAY_TOKEN, + GameDef.OrStep.CALC_REVENUE, + GameDef.OrStep.PAYOUT, + GameDef.OrStep.BUY_TRAIN, + GameDef.OrStep.TRADE_SHARES, + GameDef.OrStep.FINAL }; protected boolean doneAllowed = false; @@ -95,10 +96,10 @@ super (gameManager); operatingCompanies = setOperatingCompanies(); - + // sfy NoMapMode noMapMode = GameOption.convertValueToBoolean(getGameOption("NoMapMode")); - + guiHints.setVisibilityHint(GuiDef.Panel.STOCK_MARKET, false); guiHints.setVisibilityHint(GuiDef.Panel.STATUS, true); guiHints.setActivePanel(GuiDef.Panel.MAP); @@ -111,7 +112,7 @@ ReportBuffer.add(LocalText.getText("START_OR", thisOrNumber)); privatesPayOut(); - + if (operatingCompanies.size() > 0) { StringBuilder msg = new StringBuilder(); @@ -170,7 +171,7 @@ /*--- Common OR checks ---*/ /* Check operating company */ if (action instanceof PossibleORAction - && !(action instanceof DiscardTrain)) { + && !(action instanceof DiscardTrain)) { PublicCompanyI company = ((PossibleORAction) action).getCompany(); if (company != operatingCompany) { DisplayBuffer.add(LocalText.getText("WrongCompany", @@ -290,9 +291,9 @@ // Must be correct company. if (!companyName.equals(operatingCompany.getName())) { errMsg = - LocalText.getText("WrongCompany", - companyName, - operatingCompany.getName() ); + LocalText.getText("WrongCompany", + companyName, + operatingCompany.getName() ); break; } // Must be correct step @@ -305,14 +306,14 @@ if (!getCurrentPhase().isTileColourAllowed(tile.getColourName())) { errMsg = - LocalText.getText("TileNotYetAvailable", - tile.getExternalId()); + LocalText.getText("TileNotYetAvailable", + tile.getExternalId()); break; } if (tile.countFreeTiles() == 0) { errMsg = - LocalText.getText("TileNotAvailable", - tile.getExternalId()); + LocalText.getText("TileNotAvailable", + tile.getExternalId()); break; } @@ -325,10 +326,10 @@ List<TileI> tiles = action.getTiles(); if (tiles != null && !tiles.isEmpty() && !tiles.contains(tile)) { errMsg = - LocalText.getText( - "TileMayNotBeLaidInHex", - tile.getExternalId(), - hex.getName() ); + LocalText.getText( + "TileMayNotBeLaidInHex", + tile.getExternalId(), + hex.getName() ); break; } stl = action.getSpecialProperty(); @@ -341,8 +342,8 @@ */ if (!extra && !validateNormalTileLay(tile)) { errMsg = - LocalText.getText("NumberOfNormalTileLaysExceeded", - tile.getColourName()); + LocalText.getText("NumberOfNormalTileLaysExceeded", + tile.getColourName()); break; } @@ -356,23 +357,23 @@ // Amount must be non-negative multiple of 10 if (cost < 0) { errMsg = - LocalText.getText("NegativeAmountNotAllowed", - Bank.format(cost)); + LocalText.getText("NegativeAmountNotAllowed", + Bank.format(cost)); break; } if (cost % 10 != 0) { errMsg = - LocalText.getText("AmountMustBeMultipleOf10", - Bank.format(cost)); + LocalText.getText("AmountMustBeMultipleOf10", + Bank.format(cost)); break; } // Does the company have the money? if (cost > operatingCompany.getCash()) { errMsg = - LocalText.getText("NotEnoughMoney", - companyName, - Bank.format(operatingCompany.getCash()), - Bank.format(cost) ); + LocalText.getText("NotEnoughMoney", + companyName, + Bank.format(operatingCompany.getCash()), + Bank.format(cost) ); break; } break; @@ -416,7 +417,7 @@ stl.setExercised(); currentSpecialTileLays.remove(action); log.debug("This was a special tile lay, " - + (extra ? "" : " not") + " extra"); + + (extra ? "" : " not") + " extra"); } if (!extra) { @@ -426,11 +427,11 @@ setSpecialTileLays(); log.debug("There are now " + currentSpecialTileLays.size() - + " special tile lay objects"); + + " special tile lay objects"); } if (tile == null || currentNormalTileLays.isEmpty() - && currentSpecialTileLays.isEmpty()) { + && currentSpecialTileLays.isEmpty()) { nextStep(); } @@ -446,16 +447,16 @@ } protected boolean checkNormalTileLay(TileI tile, boolean update) { - -// Map<String,Integer> tileLaysPerColour = tileLaysPerColourState.getObject(); - -// if (tileLaysPerColour.isEmpty()) return false; + // Map<String,Integer> tileLaysPerColour = tileLaysPerColourState.getObject(); + + // if (tileLaysPerColour.isEmpty()) return false; + String colour = tile.getColourName(); Integer oldAllowedNumberObject = tileLaysPerColour.get(colour); if (oldAllowedNumberObject == null) return false; - + int oldAllowedNumber = oldAllowedNumberObject.intValue(); if (oldAllowedNumber <= 0) return false; @@ -467,29 +468,29 @@ * all normal tile lays have been consumed. 2. If any colour is laid, no * different colours may be laid. THIS MAY NOT BE TRUE FOR ALL GAMES! */ - -// Map<String,Integer> tileLaysPerColourUpdated = new HashMap<String, Integer>(); // new (empty) map - + + // Map<String,Integer> tileLaysPerColourUpdated = new HashMap<String, Integer>(); // new (empty) map + if (oldAllowedNumber <= 1) { - for (String key:tileLaysPerColour.keySet()) + for (String key:tileLaysPerColour.keySet()) new MapChange<String,Integer>(tileLaysPerColour, key, new Integer(0)); log.debug("No more normal tile lays allowed"); currentNormalTileLays.clear(); } else { -// tileLaysPerColourUpdated.put(colour, new Integer(oldAllowedNumber - 1)); - for (String key:tileLaysPerColour.keySet()) + // tileLaysPerColourUpdated.put(colour, new Integer(oldAllowedNumber - 1)); + for (String key:tileLaysPerColour.keySet()) if (colour.equals(key)) new MapChange<String,Integer> - (tileLaysPerColour, colour, new Integer(oldAllowedNumber-1)); + (tileLaysPerColour, colour, new Integer(oldAllowedNumber-1)); else new MapChange<String,Integer>(tileLaysPerColour, key, new Integer(0)); - log.debug((oldAllowedNumber - 1) + " more " + colour - + " tile lays allowed"); + log.debug((oldAllowedNumber - 1) + " more " + colour + + " tile lays allowed"); } - -// tileLaysPerColourState.set(tileLaysPerColourUpdated); + // tileLaysPerColourState.set(tileLaysPerColourUpdated); + return true; } @@ -503,7 +504,7 @@ MapHex hex = action.getChosenHex(); int station = action.getChosenStation(); String companyName = operatingCompany.getName(); - + // TEMPORARY FIX to enable fixing invalidated saved files //if ("N11".equals(hex.getName()) && station == 2) { // station = 1; @@ -515,7 +516,7 @@ // Checks // Must be correct step (exception: home base lay & some special token lay) - if (getStep() != GameDef.OrStep.LAY_TOKEN + if (getStep() != GameDef.OrStep.LAY_TOKEN && action.getType() != LayBaseToken.HOME_CITY && action.getType() != LayBaseToken.SPECIAL_PROPERTY) { errMsg = LocalText.getText("WrongActionNoTokenLay"); @@ -526,7 +527,7 @@ errMsg = LocalText.getText("HasNoTokensLeft", companyName); break; } - + if (!isTokenLayAllowed (operatingCompany, hex, station)) { errMsg = LocalText.getText("BaseTokenSlotIsReserved"); break; @@ -544,20 +545,20 @@ */ if (hex.hasTokenOfCompany(operatingCompany)) { errMsg = - LocalText.getText("TileAlreadyHasToken", - hex.getName(), - companyName ); + LocalText.getText("TileAlreadyHasToken", + hex.getName(), + companyName ); break; } - + if (action != null) { List<MapHex> locations = action.getLocations(); if (locations != null && locations.size() > 0 - && !locations.contains(hex) && !locations.contains(null)) { + && !locations.contains(hex) && !locations.contains(null)) { errMsg = - LocalText.getText("TokenLayingHexMismatch", - hex.getName(), - action.getLocationNameString() ); + LocalText.getText("TokenLayingHexMismatch", + hex.getName(), + action.getLocationNameString() ); break; } stl = action.getSpecialProperty(); @@ -573,7 +574,7 @@ companyName, Bank.format(operatingCompany.getCash()), Bank.format(cost)); - break; + break; } break; } @@ -616,18 +617,18 @@ stl.setExercised(); currentSpecialTokenLays.remove(action); log.debug("This was a special token lay, " - + (extra ? "" : " not") + " extra"); + + (extra ? "" : " not") + " extra"); } - + // Jump out if we aren't in the token laying step if (getStep() != GameDef.OrStep.LAY_TOKEN) return true; - + if (!extra) { currentNormalTokenLays.clear(); log.debug("This was a normal token lay"); } - + if (currentNormalTokenLays.isEmpty()) { log.debug("No more normal token lays are allowed"); } else if (operatingCompany.getNumberOfFreeBaseTokens() == 0) { @@ -638,9 +639,9 @@ } setSpecialTokenLays(); log.debug("There are now " + currentSpecialTokenLays.size() - + " special token lay objects"); + + " special token lay objects"); if (currentNormalTokenLays.isEmpty() - && currentSpecialTokenLays.isEmpty()) { + && currentSpecialTokenLays.isEmpty()) { nextStep(); } @@ -666,9 +667,9 @@ MapHex location = action.getChosenHex(); if (location != hex) { errMsg = - LocalText.getText("TokenLayingHexMismatch", - hex.getName(), - location.getName() ); + LocalText.getText("TokenLayingHexMismatch", + hex.getName(), + location.getName() ); break; } stl = action.getSpecialProperty(); @@ -681,8 +682,8 @@ // Does the company have the money? if (cost > operatingCompany.getCash()) { errMsg = - LocalText.getText("NotEnoughMoney", - operatingCompany.getName()); + LocalText.getText("NotEnoughMoney", + operatingCompany.getName()); break; } break; @@ -702,9 +703,9 @@ if (hex.layBonusToken(token, gameManager.getPhaseManager())) { /* TODO: the false return value must be impossible. */ - operatingCompany.addBonus(new Bonus(operatingCompany, - token.getName(), - token.getValue(), Collections.singletonList(hex))); + operatingCompany.addBonus(new Bonus(operatingCompany, + token.getName(), + token.getValue(), Collections.singletonList(hex))); token.setUser(operatingCompany); ReportBuffer.add(LocalText.getText("LaysBonusTokenOn", @@ -718,7 +719,7 @@ stl.setExercised(); currentSpecialTokenLays.remove(action); log.debug("This was a special token lay, " - + (extra ? "" : " not") + " extra"); + + (extra ? "" : " not") + " extra"); } @@ -745,10 +746,10 @@ // Does the company have the money? if (cost > operatingCompany.getCash()) { errMsg = - LocalText.getText("NotEnoughMoney", - operatingCompany.getName(), - Bank.format(operatingCompany.getCash()), - Bank.format(cost)); + LocalText.getText("NotEnoughMoney", + operatingCompany.getName(), + Bank.format(operatingCompany.getCash()), + Bank.format(cost)); break; } break; @@ -767,10 +768,10 @@ moveStack.start(true); new CashMove (operatingCompany, seller, cost); - operatingCompany.addBonus(new Bonus(operatingCompany, - sbt.getName(), - sbt.getValue(), - sbt.getLocations())); + operatingCompany.addBonus(new Bonus(operatingCompany, + sbt.getName(), + sbt.getValue(), + sbt.getLocations())); ReportBuffer.add(LocalText.getText("BuysBonusTokenFrom", operatingCompany.getName(), @@ -783,9 +784,9 @@ return true; } - - - + + + public boolean setRevenueAndDividend(SetDividend action) { String errMsg = validateSetRevenueAndDividend (action); @@ -831,9 +832,9 @@ companyName = company.getName(); if (company != operatingCompany) { errMsg = - LocalText.getText("WrongCompany", - companyName, - operatingCompa... [truncated message content] |
From: <ste...@us...> - 2010-07-16 21:31:17
|
Revision: 1341 http://rails.svn.sourceforge.net/rails/?rev=1341&view=rev Author: stefanfrey Date: 2010-07-16 21:31:11 +0000 (Fri, 16 Jul 2010) Log Message: ----------- Fixed bug that prevented selling several shares Modified Paths: -------------- trunk/18xx/rails/game/TreasuryShareRound.java Modified: trunk/18xx/rails/game/TreasuryShareRound.java =================================================================== --- trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-16 20:39:39 UTC (rev 1340) +++ trunk/18xx/rails/game/TreasuryShareRound.java 2010-07-16 21:31:11 UTC (rev 1341) @@ -414,7 +414,7 @@ } // Company may not sell after buying - if (hasSold.booleanValue()) { + if (hasBought.booleanValue()) { errMsg = LocalText.getText("MayNotBuyAndSell", companyName); break; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-16 20:39:45
|
Revision: 1340 http://rails.svn.sourceforge.net/rails/?rev=1340&view=rev Author: stefanfrey Date: 2010-07-16 20:39:39 +0000 (Fri, 16 Jul 2010) Log Message: ----------- Forgot to check in the required Properties.xml Added Paths: ----------- trunk/18xx/data/Properties.xml Added: trunk/18xx/data/Properties.xml =================================================================== --- trunk/18xx/data/Properties.xml (rev 0) +++ trunk/18xx/data/Properties.xml 2010-07-16 20:39:39 UTC (rev 1340) @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Supported properties +Defines rails configuration options, but do not stores the actual values + --> +<Properties> + <Panel name="General"> + <Property name="locale" type="STRING"/> + </Panel> + <Panel name="Colors"> + <Property name="route.colour.1" type="COLOR"/> + </Panel> +</Properties> \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-16 20:38:59
|
Revision: 1339 http://rails.svn.sourceforge.net/rails/?rev=1339&view=rev Author: stefanfrey Date: 2010-07-16 20:38:53 +0000 (Fri, 16 Jul 2010) Log Message: ----------- Adapted display of home token Modified Paths: -------------- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-16 20:37:33 UTC (rev 1338) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-16 20:38:53 UTC (rev 1339) @@ -401,7 +401,8 @@ } } } - p = getTokenCenter (1, 0, getHexModel().getCities().size(), + // check the number of tokens laid there already + p = getTokenCenter (1, homeCity.getTokens().size(), getHexModel().getCities().size(), homeCity.getNumber()-1); drawHome (g2, company, p); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-16 20:37:39
|
Revision: 1338 http://rails.svn.sourceforge.net/rails/?rev=1338&view=rev Author: stefanfrey Date: 2010-07-16 20:37:33 +0000 (Fri, 16 Jul 2010) Log Message: ----------- Started configuration window/item implementation Modified Paths: -------------- trunk/18xx/rails/test/GameTest.java trunk/18xx/rails/ui/swing/StatusWindow.java trunk/18xx/rails/util/Config.java trunk/18xx/rails/util/ListAndFixSavedFiles.java trunk/18xx/rails/util/RunGame.java trunk/18xx/test/TestGameBuilder.java Added Paths: ----------- trunk/18xx/default.profiles trunk/18xx/log4j.properties trunk/18xx/rails/ui/swing/ConfigWindow.java trunk/18xx/rails/util/ConfigItem.java trunk/18xx/user.profiles Added: trunk/18xx/default.profiles =================================================================== --- trunk/18xx/default.profiles (rev 0) +++ trunk/18xx/default.profiles 2010-07-16 20:37:33 UTC (rev 1338) @@ -0,0 +1,2 @@ +default=my.properties +test=test/test.properties Added: trunk/18xx/log4j.properties =================================================================== --- trunk/18xx/log4j.properties (rev 0) +++ trunk/18xx/log4j.properties 2010-07-16 20:37:33 UTC (rev 1338) @@ -0,0 +1,23 @@ +####################### Log4J properties ############################## +# For information on how to customise log4j logging, see for instance +# http://www.vipan.com/htdocs/log4jhelp.html +# It's a bit outdated: Category is now named Logger, +# and Priority is now named Level. +# But it's the best intro I know on how to configure Appenders. (EV) +####################################################################### +# Set root logger level to DEBUG and use appender F(file) +#log4j.debug=true +log4j.rootLogger=DEBUG, F +log4j.logger.rails.algorithms=INFO + +# Define the Log file appender +log4j.appender.F=org.apache.log4j.FileAppender + +# Log file properties +log4j.appender.F.File=18xx.log +log4j.appender.F.append=false + +# Log file layout +log4j.appender.F.layout=org.apache.log4j.PatternLayout +log4j.appender.F.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n +################## End of Log4J properties ############################# Modified: trunk/18xx/rails/test/GameTest.java =================================================================== --- trunk/18xx/rails/test/GameTest.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/rails/test/GameTest.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -2,35 +2,14 @@ import rails.ui.swing.GameSetupWindow; import rails.util.Config; -import rails.util.Util; public class GameTest { - /** The default properties file name */ - private static String DEFAULT_CONFIG_FILE = "my.properties"; public static void main(String[] args) { - /* - * Check if the property file has been set on the command line. The way - * to do this is adding an option to the java command: -Dconfigfile=<property-filename> - */ - String myConfigFile = System.getProperty("configfile"); - System.out.println("Cmdline configfile setting = " + myConfigFile); - - /* If not, use the default configuration file name */ - if (!Util.hasValue(myConfigFile)) { - myConfigFile = DEFAULT_CONFIG_FILE; - } - - /* - * Set the system property that tells log4j to use this file. (Note: - * this MUST be done before updating Config) - */ - System.setProperty("log4j.configuration", myConfigFile); - /* Tell the properties loader to read this file. */ - Config.setConfigFile(myConfigFile); - System.out.println("Configuration file = " + myConfigFile); - + // intialize configuration + Config.setConfigSelection(); + int nargs = 0; if (args != null && args.length > 0) { for (String arg : args) { Added: trunk/18xx/rails/ui/swing/ConfigWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/ConfigWindow.java (rev 0) +++ trunk/18xx/rails/ui/swing/ConfigWindow.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -0,0 +1,144 @@ +package rails.ui.swing; + +import java.awt.Color; +import java.awt.Component; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Map; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JComponent; +import javax.swing.JFormattedTextField; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +import rails.util.Config; +import rails.util.ConfigItem; +import rails.util.LocalText; + +class ConfigWindow extends JFrame { + private static final long serialVersionUID = 1L; + + private JTabbedPane pane; + + ConfigWindow() { + // JFrame properties + setTitle(LocalText.getText("ConfigWindowTitle")); +// setSize(400,300); + + // add profile panel + add(setupProfilePanel(), "North"); + + // configSetup pane + setupConfigPane(); + add(pane, "Center"); + + // buttons + JPanel buttonPanel = new JPanel(); + + JButton saveButton = new JButton(LocalText.getText("Save")); + saveButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.saveConfig(); + } + } + ); + buttonPanel.add(saveButton); + + JButton cancelButton = new JButton(LocalText.getText("Cancel")); + cancelButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + ConfigWindow.this.cancelConfig(); + } + } + ); + buttonPanel.add(cancelButton); + + add(buttonPanel, "South"); + + this.pack(); + } + + + private JComponent setupProfilePanel() { + JComponent panel = new JPanel(); + panel.setLayout(new GridLayout(0,4)); + + // default profile + + + return panel; + } + + private void setupConfigPane() { + // create pane + pane = new JTabbedPane(); + + Map<String, List<ConfigItem>> configPanels = Config.getConfigPanels(); + + for (String panelName:configPanels.keySet()) { + JPanel newPanel = new JPanel(); + newPanel.setLayout(new GridLayout(0,3)); + for (ConfigItem item:configPanels.get(panelName)) { + defineElement(newPanel, item); + } + pane.addTab(panelName, newPanel); + } + } + + private void defineElement(JPanel panel, ConfigItem item) { + + panel.add(new JLabel(LocalText.getText("Config." + item.name))); + + final String configValue = Config.get(item.name); + switch (item.type) { + case COLOR: { + final JLabel label = new JLabel(configValue); + Color selectedColor; + try { + selectedColor = Color.decode(configValue); + } catch (NumberFormatException e) { + selectedColor = Color.WHITE; + } + label.setOpaque(true); + label.setBackground(selectedColor); + panel.add(label); + JButton button = new JButton("Color"); + final Color oldColor = selectedColor; + button.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + Color selectedColor=JColorChooser.showDialog(ConfigWindow.this, "", oldColor); + label.setText(Integer.toHexString(selectedColor.getRGB()).substring(2)); + label.setBackground(selectedColor); + } + } + ); + panel.add(button); + break; + } + case STRING: + default: { + JFormattedTextField textField = new JFormattedTextField(); + textField.setValue(configValue); + panel.add(textField); + } + } + } + + private void saveConfig() { + this.dispose(); + } + + private void cancelConfig() { + this.dispose(); + } + +} Modified: trunk/18xx/rails/ui/swing/StatusWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/rails/ui/swing/StatusWindow.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -3,6 +3,8 @@ import java.awt.BorderLayout; import java.awt.Color; +//import java.awt.GraphicsConfiguration; +//import java.awt.Rectangle; import java.awt.event.*; import java.util.ArrayList; import java.util.Collections; @@ -48,6 +50,8 @@ protected static final String REPORT_CMD = "Report"; + protected static final String CONFIG_CMD = "Config"; + protected static final String BUY_CMD = "Buy"; protected static final String SELL_CMD = "Sell"; @@ -80,13 +84,21 @@ private JMenuItem menuItem; - private ActionMenuItem saveItem, exportItem; + private ActionMenuItem saveItem; +// private ActionMenuItem exportItem; private ActionMenuItem undoItem, forcedUndoItem, redoItem, redoItem2; protected static Logger log = Logger.getLogger(StatusWindow.class.getPackage().getName()); +// GraphicsConfiguration graphicsConfiguration; + +// public StatusWindow(GraphicsConfiguration gc) { +// super(gc); +// this.graphicsConfiguration = gc; +// } + public void initMenu() { menuBar = new JMenuBar(); fileMenu = new JMenu(LocalText.getText("FILE")); @@ -163,6 +175,13 @@ menuItem.setMnemonic(KeyEvent.VK_R); menuItem.addActionListener(this); optMenu.add(menuItem); + + menuItem = new JCheckBoxMenuItem(LocalText.getText("CONFIG")); + menuItem.setName(CONFIG_CMD); + menuItem.setActionCommand(CONFIG_CMD); + menuItem.setMnemonic(KeyEvent.VK_C); + menuItem.addActionListener(this); + optMenu.add(menuItem); menuBar.add(optMenu); @@ -257,8 +276,10 @@ autopassButton.addActionListener(this); setSize(800, 300); - setLocation(25, 450); +// Rectangle bounds = graphicsConfiguration.getBounds(); +// setLocation(bounds.x+ 25, bounds.y + 450); + buttonPanel.setBorder(BorderFactory.createEtchedBorder()); buttonPanel.setOpaque(false); @@ -583,6 +604,10 @@ gameUIManager.stockChart.setVisible(((JMenuItem) actor.getSource()).isSelected()); } else if (command.equals(MAP_CMD)) { gameUIManager.orWindow.setVisible(((JMenuItem) actor.getSource()).isSelected()); + } else if (command.equals(CONFIG_CMD)) { + JFrame configWindow = new ConfigWindow(); + configWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + configWindow.setVisible(true); } else if (executedAction == null) { ; } else if (executedAction instanceof GameAction) { Modified: trunk/18xx/rails/util/Config.java =================================================================== --- trunk/18xx/rails/util/Config.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/rails/util/Config.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -1,11 +1,21 @@ /* $Header: /Users/blentz/rails_rcs/cvs/18xx/rails/util/Config.java,v 1.13 2010/06/24 21:48:08 stefanfrey Exp $*/ package rails.util; +import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; +import rails.game.ConfigurationException; import rails.game.GameManager; /** @@ -18,28 +28,102 @@ */ public final class Config { - /** Default property file name. */ - /* It will be reset from GameTest. */ - private static String myConfigFile = "my.properties"; - //private static String gamesConfigFile = "games.properties"; + protected static Logger log = + Logger.getLogger(Config.class.getPackage().getName()); - /** One Properties object for all properties */ - private static Properties prop = new Properties(); - private static boolean loaded = false; + + /** + * Defines possible types (Java classes used as types in ConfigItem below + */ + public static enum ConfigType { + INTEGER, FLOAT, STRING, BOOLEAN, DIRECTORY, COLOR; + } - protected static Logger log = - Logger.getLogger(Config.class.getPackage().getName()); + /** XML setup */ + private static final String CONFIG_XML_DIR = "data"; + private static final String CONFIG_XML_FILE = "Properties.xml"; + private static final String CONFIG_TAG = "Properties"; + private static final String PANEL_TAG = "Panel"; + private static final String ITEM_TAG = "Property"; + /** Log 4j configuration */ + private static final String LOG4J_CONFIG_FILE = "log4j.properties"; + + + /** Rails profile configurations */ + private static String defaultProfilesFile = "default.profiles"; + private static Properties defaultProfiles = new Properties(); + private static String userProfilesFile = "user.profiles"; + private static Properties userProfiles = new Properties(); + private static boolean profilesLoaded = false; + private static final String TEST_PROFILE_SELECTION = "test"; + private static final String DEFAULT_PROFILE_SELECTION = "default"; + private static final String DEFAULT_PROFILE_PROPERTY = "default.profile"; + private static final String STANDARD_PROFILE_PROPERTY = "standard.profile"; + + /** selected profile */ + private static String selectedProfile; + private static boolean legacyConfigFile; + private static boolean standardProfile; + + /** properties storage. */ + private static Properties defaultProperties = new Properties(); + private static Properties userProperties = new Properties(); + private static boolean propertiesLoaded = false; + + /** Map that holds the panel, which contains config items */ + private static Map<String, List<ConfigItem>> configPanels = null; + /** - * Hidden contructor, the class is never instantiated. + * Hidden constructor, the class is never instantiated, everything is static */ private Config() {} - public static void setConfigFile(String myConfigFile) { - Config.myConfigFile = myConfigFile; - load(); + /** + * Reads the config.xml file that defines all config items + */ + public static void readConfigSetupXML() { + List<String> directories = new ArrayList<String>(); + directories.add(CONFIG_XML_DIR); + try { + // Find the <Config> tag + Tag configTag = + Tag.findTopTagInFile(CONFIG_XML_FILE, directories, CONFIG_TAG); + log.debug("Opened config xml, filename = " + CONFIG_XML_FILE); + + configPanels = new LinkedHashMap<String, List<ConfigItem>>(); + // find panels + List<Tag> panelTags = configTag.getChildren(PANEL_TAG); + if (panelTags != null) { + for (Tag panelTag:panelTags) { + // find name attribute + String panelName = panelTag.getAttributeAsString("name"); + if (!Util.hasValue(panelName)) continue; + + // find items + List<Tag> itemTags = panelTag.getChildren(ITEM_TAG); + if (itemTags == null || itemTags.size() == 0) continue; + List<ConfigItem> panelItems = new ArrayList<ConfigItem>(); + for (Tag itemTag:itemTags) { + panelItems.add(new ConfigItem(itemTag)); + } + configPanels.put(panelName, panelItems); + } + } + + } catch (ConfigurationException e) { + log.error("Configuration error in setup of "); + } } - + + public static Map<String, List<ConfigItem>> getConfigPanels() { + if (configPanels == null) { + readConfigSetupXML(); + } + log.debug("Configuration setup = " + configPanels); + return configPanels; + } + /** * First tries to return {key}.{gameName}, if undefined returns {key} */ @@ -59,55 +143,238 @@ } public static String get(String key) { - - if (prop.isEmpty() || !loaded) { - load(); + return get(key, ""); + } + + public static String get(String key, String defaultValue) { + if (defaultProperties.isEmpty() || !propertiesLoaded) { + initialLoad(); } - if (prop.containsKey(key)) return prop.getProperty(key).trim(); + if (userProperties.containsKey(key)) return userProperties.getProperty(key).trim(); + if (defaultProperties.containsKey(key)) return defaultProperties.getProperty(key).trim(); - return ""; + return defaultValue; } - public static String get(String key, String defaultValue) { - if (prop.isEmpty() || !loaded) { - load(); +// /** +// * store user config file +// */ +// public static boolean saveUserConfig() { +// } +// +// /** +// * @return if user location is defined +// */ +// public static boolean hasUserLocation() { +// return userConfigFile != null; +// } + + + private static boolean storePropertyFile(Properties properties, String filepath) { + File outFile = new File(filepath); + boolean result = true; + try { + properties.store(new FileOutputStream(outFile), "Automatically generated, do not edit"); + } catch (IOException e) { + result = false; } - if (prop.containsKey(key)) return prop.getProperty(key).trim(); + return result; + } + + /** + * save active Profile + */ + public static boolean saveActiveProfile(String filepath) { + return storePropertyFile(userProperties, filepath); + } + + /** + * change active Profile + */ + public static boolean setActiveProfile(String profileName) { + boolean result = loadPropertyProfile(profileName); + if (result) selectedProfile = profileName; + return result; + } + + /** + * returns name of (active) default profile + */ + public static String getDefaultProfileName() { + String defaultProfileName = null; + if (isUserProfileActive()) { + defaultProfileName = userProfiles.getProperty(DEFAULT_PROFILE_PROPERTY); + if (defaultProfileName == null) { +// return + } + } + return defaultProfileName; + } + + /** + * returns name of active profile + */ + public static String getActiveProfileName() { + return selectedProfile; + } + + /** + * sets filename for an active profile (and store list of profiles) + */ + public static boolean setActiveFilepath(String filepath) { + userProfiles.setProperty(selectedProfile, filepath); + return storePropertyFile(userProfiles, userProfilesFile); + } + + /** + * returns filename of active profile, (null if undefined or default profile) + */ + public static String getActiveFilepath() { + return userProfiles.getProperty(selectedProfile); + } + + /** + * returns true if active profile is a user profile + */ + public static boolean isUserProfileActive() { + return userProfiles.getProperty(selectedProfile) != null; + } + + /** + * activates settings used for testing + */ + public static void setConfigTest() { + /* + * Set the system property that tells log4j to use this file. (Note: + * this MUST be done before updating Config) + */ + System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE); + legacyConfigFile = false; + selectedProfile = TEST_PROFILE_SELECTION; + initialLoad(); + } - return defaultValue; + + /** + * activates configuration settings based on default settings + */ + public static void setConfigSelection() { + /* + * Set the system property that tells log4j to use this file. (Note: + * this MUST be done before updating Config) + */ + System.setProperty("log4j.configuration", LOG4J_CONFIG_FILE); + + /* + * Check if the profile has been set from the command line + * to do this is adding an option to the java command: -Dprofile=<profile-name> + */ + String configSelection = System.getProperty("profile"); + System.out.println("Cmdline profile selection = " + configSelection); + + legacyConfigFile = false; + if (configSelection == null) { + /* + * Check if the property file has been set on the command line. The way + * to do this is adding an option to the java command: -Dconfigfile=<property-filename> + * + * This is for legacy reasons only + */ + configSelection = System.getProperty("configfile"); + + if (configSelection != null) { + System.out.println("Cmdline configfile selection (legacy!) = " + configSelection); + legacyConfigFile = true; + } + } + + /* if nothing has selected so far, choose standardProfile */ + standardProfile = false; + if (!Util.hasValue(configSelection)) { + standardProfile = true; + } + + selectedProfile = configSelection; + initialLoad(); } + - private static void load() { + private static void initialLoad() { + if (legacyConfigFile) { + if (!propertiesLoaded) { + loadPropertyFile(defaultProperties, selectedProfile, true, false); + propertiesLoaded = true; + setSaveDirDefaults(); + } + return; + } - if (prop.isEmpty() || !loaded) { - /* List the property files to read here */ - load(myConfigFile, false); - //load(gamesConfigFile, false); - setDefaults(); - loaded = true; + if (!profilesLoaded) { + loadPropertyFile(defaultProfiles, defaultProfilesFile, true, false); + loadPropertyFile(userProfiles, userProfilesFile, false, false); + profilesLoaded = true; } + + if (standardProfile) { + selectedProfile = userProfiles.getProperty(STANDARD_PROFILE_PROPERTY); + if (selectedProfile == null) { + selectedProfile = defaultProfiles.getProperty(STANDARD_PROFILE_PROPERTY); + } + if (selectedProfile == null) { + selectedProfile = DEFAULT_PROFILE_SELECTION; + } + } + + /* Tell the properties loader to read this file. */ + log.info("Selected profile = " + selectedProfile); + + if (!propertiesLoaded) { + propertiesLoaded = loadPropertyProfile(selectedProfile); + } } + + private static boolean loadPropertyProfile(String profileName) { + + /* first check if it is a default profile */ + String defaultConfigFile = defaultProfiles.getProperty(profileName); + if (defaultConfigFile == null) { + String userConfigFile = userProfiles.getProperty(profileName); + if (userConfigFile == null) return false; + loadPropertyFile(userProperties, userConfigFile, false, false); + defaultConfigFile = userProperties.getProperty(DEFAULT_PROFILE_PROPERTY); + if (defaultConfigFile == null) { + defaultConfigFile = defaultProfiles.getProperty(DEFAULT_PROFILE_SELECTION); + } + } + loadPropertyFile(defaultProperties, defaultConfigFile, true, false); + setSaveDirDefaults(); + return true; + } /** * This method loads a property file. * * @param filename - file key name as a String. + * @param resource - if TRUE, loaded from jar (via classloader), otherwise from filesystem * @param required - if TRUE, an exception will be logged if the file does * not exist. */ - private static void load(String filename, boolean required) { - + private static void loadPropertyFile(Properties properties, String filename, boolean resource, boolean required) { + try { log.info("Loading properties from file " + filename); - prop.load(Config.class.getClassLoader().getResourceAsStream( - filename)); - + InputStream inFile; + if (resource) { + inFile = Config.class.getClassLoader().getResourceAsStream(filename); + } else { + inFile = new FileInputStream(filename); + } + properties.load(inFile); } catch (FileNotFoundException FNFE) { if (required) { System.err.println("File not found: " + filename); } - } catch (Exception e) { System.err.println(e + " whilst loading properties file " + filename); @@ -115,10 +382,10 @@ } } - private static void setDefaults() { - if (!Util.hasValue(prop.getProperty("save.directory"))) { + private static void setSaveDirDefaults() { + if (!Util.hasValue(defaultProperties.getProperty("save.directory"))) { log.debug("Setting save directory to "+System.getProperty("user.dir")); - prop.put("save.directory", System.getProperty("user.dir")); + defaultProperties.put("save.directory", System.getProperty("user.dir")); } } } Added: trunk/18xx/rails/util/ConfigItem.java =================================================================== --- trunk/18xx/rails/util/ConfigItem.java (rev 0) +++ trunk/18xx/rails/util/ConfigItem.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -0,0 +1,63 @@ +package rails.util; + +import java.util.Arrays; +import java.util.List; +import rails.game.ConfigurationException; +import rails.util.Config.ConfigType; + +/** + * Defines an item used for the configuration of rails + * T represents the value type + */ + +public class ConfigItem { + public final String name; + public final ConfigType type; + public final List<String> allowedValues; + public final String formatMask; + public final String helpText; + + ConfigItem(Tag tag) throws ConfigurationException { + // check name and type (required) + String name = tag.getAttributeAsString("name"); + if (Util.hasValue(name)) { + this.name = name; + } else { + throw new ConfigurationException("Missing name for configuration item"); + } + String type = tag.getAttributeAsString("type"); + if (Util.hasValue(type)) { + this.type = ConfigType.valueOf(type); + } else { + throw new ConfigurationException("Missing or invalid type for configuration item"); + } + // optional: list of allowed values + String valueString = tag.getAttributeAsString("values"); + if (Util.hasValue(valueString)) { + allowedValues = Arrays.asList(valueString.split(",")); + } else { + allowedValues = null; + } + // optional: formatMask + formatMask = tag.getAttributeAsString("formatMask"); + + // optional: helpText + helpText = tag.getAttributeAsString("formatMask"); + } + + public String toString() { + StringBuffer s = new StringBuffer(); + s.append("Configuration Item: name = " + name + ", type = " + type); + if (allowedValues != null) { + s.append(", allowedValues = " + allowedValues); + } + if (formatMask != null) { + s.append(", formatMask = " + formatMask); + } + if (helpText != null) { + s.append(", helpText = " + helpText); + } + return s.toString(); + } + +} Modified: trunk/18xx/rails/util/ListAndFixSavedFiles.java =================================================================== --- trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/rails/util/ListAndFixSavedFiles.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -39,32 +39,15 @@ private String filepath; protected static Logger log; - /** * @param args */ public static void main(String[] args) { - // TODO Auto-generated method stub - - String myConfigFile = System.getProperty("configfile"); - System.out.println("Cmdline configfile setting = " + myConfigFile); - - /* If not, use the default configuration file name */ - if (!Util.hasValue(myConfigFile)) { - myConfigFile = "my.properties"; - } - - /* - * Set the system property that tells log4j to use this file. (Note: - * this MUST be done before updating Config) - */ - System.setProperty("log4j.configuration", myConfigFile); - log = Logger.getLogger(ListAndFixSavedFiles.class.getPackage().getName()); - - /* Tell the properties loader to read this file. */ - Config.setConfigFile(myConfigFile); - System.out.println("Configuration file = " + myConfigFile); + + // intialize configuration + Config.setConfigSelection(); + saveDirectory = Config.get("save.directory"); System.out.println("Save directory = " + saveDirectory); Modified: trunk/18xx/rails/util/RunGame.java =================================================================== --- trunk/18xx/rails/util/RunGame.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/rails/util/RunGame.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -7,32 +7,12 @@ import rails.ui.swing.GameUIManager; public class RunGame { - /** The default properties file name */ - private static String DEFAULT_CONFIG_FILE = "my.properties"; public static void main(String[] args) { - /* - * Check if the property file has been set on the command line. The way - * to do this is adding an option to the java command: -Dconfigfile=<property-filename> - */ - String myConfigFile = System.getProperty("configfile"); - System.out.println("Cmdline configfile setting = " + myConfigFile); - - /* If not, use the default configuration file name */ - if (!Util.hasValue(myConfigFile)) { - myConfigFile = DEFAULT_CONFIG_FILE; - } - - /* - * Set the system property that tells log4j to use this file. (Note: - * this MUST be done before updating Config) - */ - System.setProperty("log4j.configuration", myConfigFile); - /* Tell the properties loader to read this file. */ - Config.setConfigFile(myConfigFile); - System.out.println("Configuration file = " + myConfigFile); - + // intialize configuration + Config.setConfigSelection(); + int nargs = 0; if (args != null && args.length > 0) { nargs = args.length; Modified: trunk/18xx/test/TestGameBuilder.java =================================================================== --- trunk/18xx/test/TestGameBuilder.java 2010-07-11 16:44:29 UTC (rev 1337) +++ trunk/18xx/test/TestGameBuilder.java 2010-07-16 20:37:33 UTC (rev 1338) @@ -23,7 +23,6 @@ public final class TestGameBuilder extends TestCase { - private static String configFile = "test/test.properties"; private static char extensionSeparator = '.'; private static int maxRecursionLevel = 5; @@ -147,14 +146,8 @@ public static Test suite() { - // Activate logger - System.setProperty("log4j.configuration", configFile); + Config.setConfigTest(); - /* Tell the properties loader to read this file. */ - Config.setConfigFile(configFile); - System.out.println("Configuration file = " + configFile); - - // Main test directory File testDir = new File(Config.get("save.directory")); @@ -177,13 +170,8 @@ */ public static void main(String[] args) { - // Activate logger - System.setProperty("log4j.configuration", configFile); + Config.setConfigTest(); - /* Tell the properties loader to read this file. */ - Config.setConfigFile(configFile); - System.out.println("Configuration file = " + configFile); - // Main test directory String rootPath = Config.get("save.directory"); Added: trunk/18xx/user.profiles =================================================================== --- trunk/18xx/user.profiles (rev 0) +++ trunk/18xx/user.profiles 2010-07-16 20:37:33 UTC (rev 1338) @@ -0,0 +1,2 @@ +standard.profile=sfy +sfy=sfy.my.properties This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-11 16:44:35
|
Revision: 1337 http://rails.svn.sourceforge.net/rails/?rev=1337&view=rev Author: stefanfrey Date: 2010-07-11 16:44:29 +0000 (Sun, 11 Jul 2010) Log Message: ----------- Bug 3010534: 1856 1/2 share from limit can't buy 5% share of CGR Fixed now, previous checks assumed that each certificates counts a full slot. Modified Paths: -------------- trunk/18xx/rails/game/StockRound.java Modified: trunk/18xx/rails/game/StockRound.java =================================================================== --- trunk/18xx/rails/game/StockRound.java 2010-07-11 16:40:44 UTC (rev 1336) +++ trunk/18xx/rails/game/StockRound.java 2010-07-11 16:44:29 UTC (rev 1337) @@ -184,7 +184,13 @@ unitsForPrice = comp.getShareUnitsForSharePrice(); if (isSaleRecorded(currentPlayer, comp)) continue; if (maxAllowedNumberOfSharesToBuy(currentPlayer, comp, - cert.getShare()) < 1) continue; + cert.getShare()) < 1 ) continue; + + /* Would the player exceed the total certificate limit? */ + stockSpace = comp.getCurrentSpace(); + if ((stockSpace == null || !stockSpace.isNoCertLimit()) && !mayPlayerBuyCertificate( + currentPlayer, comp, cert.getCertificateCount())) continue; + shares = cert.getShares(); if (!cert.isPresidentShare()) { @@ -279,7 +285,8 @@ /* Would the player exceed the total certificate limit? */ if (!stockSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, comp, number)) + && !mayPlayerBuyCertificate(currentPlayer, comp, + number * uniqueCerts[shares].getCertificateCount())) continue; } @@ -742,7 +749,7 @@ // Check if player would not exceed the certificate limit. // (shortcut: assume 1 cert == 1 certificate) if (!currentSpace.isNoCertLimit() - && !mayPlayerBuyCertificate(currentPlayer, company, number)) { + && !mayPlayerBuyCertificate(currentPlayer, company, number * cert.getCertificateCount())) { errMsg = currentPlayer.getName() + LocalText.getText("WouldExceedCertLimit", @@ -1401,7 +1408,7 @@ * so). * @return True if it is allowed. */ - public boolean mayPlayerBuyCertificate(Player player, PublicCompanyI comp, int number) { + public boolean mayPlayerBuyCertificate(Player player, PublicCompanyI comp, float number) { if (comp.hasFloated() && comp.getCurrentSpace().isNoCertLimit()) return true; if (player.getPortfolio().getCertificateCount() + number > gameManager.getPlayerCertificateLimit(player)) @@ -1454,7 +1461,9 @@ company.getCurrentSpace().isNoHoldLimit() ? 100 : playerShareLimit; } - return (limit - player.getPortfolio().getShare(company)) / shareSize; + int maxAllowed = (limit - player.getPortfolio().getShare(company)) / shareSize; +// log.debug("MaxAllowedNumberOfSharesToBuy = " + maxAllowed + " for company = " + company + " shareSize " + shareSize); + return maxAllowed; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-11 16:40:53
|
Revision: 1336 http://rails.svn.sourceforge.net/rails/?rev=1336&view=rev Author: stefanfrey Date: 2010-07-11 16:40:44 +0000 (Sun, 11 Jul 2010) Log Message: ----------- Bug: 1856. THB token spot blocked inappropriately - ID: 3025465 Fixed, added the case of a OO-city home base, where other companies can lay tokens in the other city before the start. Modified Paths: -------------- trunk/18xx/rails/game/MapHex.java trunk/18xx/rails/ui/swing/hexmap/GUIHex.java Modified: trunk/18xx/rails/game/MapHex.java =================================================================== --- trunk/18xx/rails/game/MapHex.java 2010-07-10 22:25:10 UTC (rev 1335) +++ trunk/18xx/rails/game/MapHex.java 2010-07-11 16:40:44 UTC (rev 1336) @@ -921,7 +921,15 @@ if (cities.isEmpty()) { log.error("No cities for home station on hex " + name); } else { - homes.put(company, cities.get(Math.max(cityNumber - 1, 0))); + // not yet decided + if (cityNumber == 0) { + homes.put(company, null); + log.debug("Added home of " + company + " in hex " + this.toString() + " city not yet decided"); + } else { + City homeCity = cities.get(Math.max(cityNumber - 1, 0)); + homes.put(company, homeCity); + log.debug("Added home of " + company + " set to " + homeCity + " id= " +homeCity.getUniqueId()); + } } } @@ -994,30 +1002,44 @@ /** * @return Returns false if no base tokens may yet be laid on this hex and station. * NOTE: this method currently only checks for prohibitions caused - * by the presence of unlaid hoem base tokens. + * by the presence of unlaid home base tokens. * It does NOT (yet) check for free space. + * + * Remark: There are the following cases to check + * A) isBlockedForTokenLays is active for the MapHex => return the state of this + * (Example: Erie home base in 1830) + * otherwise + * B) City is decided => check the city if a slot is left (standard) + * C) City is undecided => check all cities if there is a slot left */ public boolean isBlockedForTokenLays(PublicCompanyI company, int cityNumber) { if (isHomeFor(company)) // Company can always lay a home base return false; - else if (isBlockedForTokenLays != null) { + else if (isBlockedForTokenLays != null) { // case A) // if true: token lay blocked because a required home base is not yet laid // if false: token lay allowed if there is any free space // Free space is not checked here (yet) return isBlockedForTokenLays.booleanValue(); } else if (homes != null && !homes.isEmpty()) { - City city; // Check if this token lay does not block an unlaid home base for (PublicCompanyI comp : homes.keySet()) { if (comp.hasLaidHomeBaseTokens() || comp.isClosed()) continue; - city = homes.get(comp); - if (cityNumber == city.getNumber() - // Assume that a city is never home to more than one company - && city.getTokens().isEmpty() - && city.getTokenSlotsLeft() < 2) { - return true; + City homeCity = homes.get(comp); + if (homeCity != null) { // case B) + if (cityNumber == homeCity.getNumber() + // Assume that a city is never home to more than one company + && homeCity.getTokens().isEmpty() + && homeCity.getTokenSlotsLeft() < 2) { + return true; + } + } else { // case C) + int tokenSlotsLeft = 0; + for (City city:cities) { + tokenSlotsLeft += city.getTokenSlotsLeft(); + } + if (tokenSlotsLeft < 2) return true; // not enough tokens left, assume only one company } } } Modified: trunk/18xx/rails/ui/swing/hexmap/GUIHex.java =================================================================== --- trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-10 22:25:10 UTC (rev 1335) +++ trunk/18xx/rails/ui/swing/hexmap/GUIHex.java 2010-07-11 16:40:44 UTC (rev 1336) @@ -383,17 +383,26 @@ Map<PublicCompanyI, City> homes = getHexModel().getHomes(); if (homes != null) { - City city; + City homeCity; Point p; for (PublicCompanyI company : homes.keySet()) { if (company.isClosed()) continue; // Only draw the company name if there isn't yet a token of that company if (model.hasTokenOfCompany(company)) continue; - - city = homes.get(company); + homeCity = homes.get(company); + if (homeCity == null) { // not yet decided where the token will be + // find a free slot + List<City> cities = getHexModel().getCities(); + for (City city:cities) { + if (city.hasTokenSlotsLeft()) { + homeCity = city; + break; + } + } + } p = getTokenCenter (1, 0, getHexModel().getCities().size(), - city.getNumber()-1); + homeCity.getNumber()-1); drawHome (g2, company, p); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-10 22:25:16
|
Revision: 1335 http://rails.svn.sourceforge.net/rails/?rev=1335&view=rev Author: stefanfrey Date: 2010-07-10 22:25:10 +0000 (Sat, 10 Jul 2010) Log Message: ----------- Fixed bug 18AL delayed obsolecence in report window - ID: 3026083 - Added report text after obsoletion and delayed rusting. Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/rails/game/Portfolio.java trunk/18xx/rails/game/TrainManager.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-10 17:02:39 UTC (rev 1334) +++ trunk/18xx/LocalisedText.properties 2010-07-10 22:25:10 UTC (rev 1335) @@ -534,6 +534,8 @@ TRADE_TREASURY_SHARES_TITLE=Rails: Game Status - TRADING TREASURY SHARES OF COMPANY {0} TrainInfo={0}-train, price: {1}, quantity: {2} TrainsAvailable={0}-trains are now available. +TrainsObsolete=All {0}-trains are obsolete and will be removed after the next run. +TrainsObsoleteRusted=Obsolete Train {0} of company {1} rusted. TrainsRusted=All {0}-trains have rusted and have been removed. TREASURY_SHARES=<html>Treasury<br>shares TreasuryOverHoldLimit=Treasury would get over the {0}% hold limit Modified: trunk/18xx/rails/game/Portfolio.java =================================================================== --- trunk/18xx/rails/game/Portfolio.java 2010-07-10 17:02:39 UTC (rev 1334) +++ trunk/18xx/rails/game/Portfolio.java 2010-07-10 22:25:10 UTC (rev 1335) @@ -721,6 +721,8 @@ // Need to separate selection and execution, // otherwise we get a ConcurrentModificationException on trains. for (TrainI train : trainsToRust) { + ReportBuffer.add(LocalText.getText("TrainsObsoleteRusted", + train.getName(), name)); log.debug("Obsolete train " + train.getUniqueId() + " (owned by " + name + ") rusted"); train.setRusted(); Modified: trunk/18xx/rails/game/TrainManager.java =================================================================== --- trunk/18xx/rails/game/TrainManager.java 2010-07-10 17:02:39 UTC (rev 1334) +++ trunk/18xx/rails/game/TrainManager.java 2010-07-10 22:25:10 UTC (rev 1335) @@ -161,9 +161,14 @@ TrainTypeI rustedType = boughtType.getRustedTrainType(); if (rustedType != null && !rustedType.hasRusted()) { rustedType.setRusted(train.getHolder()); // Or obsolete, - // where applicable - ReportBuffer.add(LocalText.getText("TrainsRusted", + // where applicable + if (rustedType.isObsoleting()) { + ReportBuffer.add(LocalText.getText("TrainsObsolete", + rustedType.getName())); + } else { + ReportBuffer.add(LocalText.getText("TrainsRusted", rustedType.getName())); + } trainsHaveRusted = true; trainAvailabilityChanged = true; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-10 17:02:45
|
Revision: 1334 http://rails.svn.sourceforge.net/rails/?rev=1334&view=rev Author: stefanfrey Date: 2010-07-10 17:02:39 +0000 (Sat, 10 Jul 2010) Log Message: ----------- Fixed the following bugs/requests: 18EU minor company initial sale problem - ID: 3021157 - Renamed pass to decline to bid Autopass during minor auction in 18EU - ID: 2899354 - General autopass in GameManager if only Pass Action is available Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/game/action/NullAction.java trunk/18xx/rails/game/action/PossibleActions.java trunk/18xx/rails/game/specific/_18EU/StartRound_18EU.java trunk/18xx/rails/ui/swing/StartRoundWindow.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/LocalisedText.properties 2010-07-10 17:02:39 UTC (rev 1334) @@ -157,6 +157,7 @@ CorrectionModeActivate={1} activated by {0} CorrectionModeDeactivate={1} deactivated by {0} CREDITS=Credits +DeclineToBid=Decline to Bid DestinationReachedByToken={0} gains {1} by laying a token on its destination {2} DestinationReached={0} has reached its destination hex {1} DestinationsReached=Destinations reached @@ -385,6 +386,7 @@ PRICE_STAYS_LOG={0} price stays at {1}({2}). PRIVATES=Privates PaysLoanInterest={0} pays {1} interest for outstanding loans +Pass=Pass PhaseClosesAllPrivates=Close all privates PhaseNumberOfORs=Number of ORs: {0} PhaseOffBoardStep=Off-board revenue step: {0} Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/rails/game/GameManager.java 2010-07-10 17:02:39 UTC (rev 1334) @@ -808,6 +808,11 @@ possibleActions.clear(); getCurrentRound().setPossibleActions(); + // only pass available => execute automatically + if (!isGameOver() && possibleActions.containsOnlyPass()) { + result = process(possibleActions.getList().get(0)); + } + // moveStack closing is done here to allow state changes to occur // when setting possible actions if (action != null) { Modified: trunk/18xx/rails/game/action/NullAction.java =================================================================== --- trunk/18xx/rails/game/action/NullAction.java 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/rails/game/action/NullAction.java 2010-07-10 17:02:39 UTC (rev 1334) @@ -10,9 +10,12 @@ public static final int START_GAME = 4; // For use after loading public static final int MAX_MODE = 4; + // optional label that is returned on toString instead of the standard labels defined below + private String optionalLabel = null; + + // standard labels defined private static String[] name = new String[] { "Done", "Pass", "Skip", "Autopass", "StartGame" }; - protected int mode = -1; public static final long serialVersionUID = 2L; @@ -26,6 +29,12 @@ public int getMode() { return mode; } + + /** returns the NullAction itself */ + public NullAction setLabel(String label) { + this.optionalLabel = label; + return this; + } @Override public boolean equals(PossibleAction action) { @@ -36,6 +45,8 @@ @Override public String toString() { + if (optionalLabel != null) return optionalLabel; return name[mode]; } + } Modified: trunk/18xx/rails/game/action/PossibleActions.java =================================================================== --- trunk/18xx/rails/game/action/PossibleActions.java 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/rails/game/action/PossibleActions.java 2010-07-10 17:02:39 UTC (rev 1334) @@ -82,6 +82,16 @@ public boolean isEmpty() { return possibleActions.isEmpty(); } + + public boolean containsOnlyPass() { + if (possibleActions.size() != 1) return false; + PossibleAction action = possibleActions.get(0); + if (action instanceof NullAction && ((NullAction)action).getMode() == NullAction.PASS) { + return true; + } else { + return false; + } + } /** Check if a given action exists in the current list of possible actions */ public boolean validate(PossibleAction checkedAction) { Modified: trunk/18xx/rails/game/specific/_18EU/StartRound_18EU.java =================================================================== --- trunk/18xx/rails/game/specific/_18EU/StartRound_18EU.java 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/rails/game/specific/_18EU/StartRound_18EU.java 2010-07-10 17:02:39 UTC (rev 1334) @@ -56,7 +56,6 @@ public boolean setPossibleActions() { possibleActions.clear(); - boolean passAllowed = false; // Refresh player, may have been reset by Undo/Redo currentPlayer = getCurrentPlayer(); @@ -81,31 +80,33 @@ } } break; - case BUY_STEP: - - possibleActions.add(new BuyStartItem( - (StartItem) currentAuctionItem.getObject(), - currentBuyPrice.intValue(), true)); - passAllowed = true; - + // only offer buy if enough money + if (currentBuyPrice.intValue() <= currentPlayer.getFreeCash()) { + possibleActions.add(new BuyStartItem( + (StartItem) currentAuctionItem.getObject(), + currentBuyPrice.intValue(), true)); + } + possibleActions.add(new NullAction(NullAction.PASS)); break; - case OPEN_STEP: case BID_STEP: - StartItem item = (StartItem) currentAuctionItem.getObject(); - BidStartItem possibleAction = + // only offer if enough money + if (item.getMinimumBid() <= currentPlayer.getFreeCash()) { + BidStartItem possibleAction = new BidStartItem(item, item.getMinimumBid(), startPacket.getModulus(), true); - possibleActions.add(possibleAction); - passAllowed = true; - + possibleActions.add(possibleAction); + } + if (getStep() == OPEN_STEP) { + possibleActions.add(new NullAction(NullAction.PASS).setLabel("DeclineToBid")); + } else { + possibleActions.add(new NullAction(NullAction.PASS)); + } break; } - if (passAllowed) possibleActions.add(new NullAction(NullAction.PASS)); - return true; } Modified: trunk/18xx/rails/ui/swing/StartRoundWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/StartRoundWindow.java 2010-07-05 18:02:13 UTC (rev 1333) +++ trunk/18xx/rails/ui/swing/StartRoundWindow.java 2010-07-10 17:02:39 UTC (rev 1334) @@ -103,7 +103,7 @@ private final boolean includeBidding; private final boolean showBasePrices; - private boolean repacked = false; +// private boolean repacked = false; protected static Logger log = Logger.getLogger(StartRoundWindow.class.getPackage().getName()); @@ -464,18 +464,14 @@ List<NullAction> inactiveItems = possibleActions.getType(NullAction.class); - if (inactiveItems != null) { - - for (NullAction na : inactiveItems) { - switch (na.getMode()) { - case NullAction.PASS: - passButton.setText(LocalText.getText("PASS")); - passAllowed = true; - passButton.setPossibleAction(na); - passButton.setMnemonic(KeyEvent.VK_P); - break; - } - } + if (inactiveItems != null && !inactiveItems.isEmpty()) { + // only one NullAction is allowed + NullAction na = inactiveItems.get(0); + // nullActions differ in text to display + passButton.setText(LocalText.getText(na.toString())); + passAllowed = true; + passButton.setPossibleAction(na); + passButton.setMnemonic(KeyEvent.VK_P); } buyButton.setEnabled(buyAllowed); @@ -485,6 +481,7 @@ } passButton.setEnabled(passAllowed); + pack(); // to avoid not displaying after label size changes requestFocus(); } @@ -538,10 +535,10 @@ passButton.setEnabled(true); passButton.setText(LocalText.getText("SelectNoBid")); passButton.setVisible(true); - if (!repacked) { +// if (!repacked) { pack(); - repacked = true; - } +// repacked = true; +// } } if (includeBidding) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ste...@us...> - 2010-07-05 18:02:20
|
Revision: 1333 http://rails.svn.sourceforge.net/rails/?rev=1333&view=rev Author: stefanfrey Date: 2010-07-05 18:02:13 +0000 (Mon, 05 Jul 2010) Log Message: ----------- Added autosave for game recovery Modified Paths: -------------- trunk/18xx/LocalisedText.properties trunk/18xx/my.properties trunk/18xx/rails/game/DisplayBuffer.java trunk/18xx/rails/game/GameManager.java trunk/18xx/rails/ui/swing/GameSetupWindow.java Modified: trunk/18xx/LocalisedText.properties =================================================================== --- trunk/18xx/LocalisedText.properties 2010-07-04 20:51:33 UTC (rev 1332) +++ trunk/18xx/LocalisedText.properties 2010-07-05 18:02:13 UTC (rev 1333) @@ -416,6 +416,9 @@ Pullman=Pullman-Car QUIT=Quit RandomizePlayers=Randomize Order +RecoverGame=Recover Previous Game +RecoverySaveFailed=Recovery save failed, reason: {0} +RecoverySaveSuccessAgain=Recovery save succeeded REDO=Redo ReleasedFromEscrow={0} receives {1} released from bank escrow ReleasesTrains=Makes {0}-trains available for purchasing Modified: trunk/18xx/my.properties =================================================================== --- trunk/18xx/my.properties 2010-07-04 20:51:33 UTC (rev 1332) +++ trunk/18xx/my.properties 2010-07-05 18:02:13 UTC (rev 1333) @@ -58,6 +58,12 @@ # The default extension is .rails #save.filename.extension=rails +### AutoSave for game recovery +# Activation of autosave (default is yes) +# save.recovery.active=yes +# Filepath for autosave (default is 18xx_autosave.rails in current working directory +# save.recovery.filepath=18xx_autosave.rails + ### Game report directory # If the below entry exists, is not empty, and specifies an existing # directory, a copy of the Game Report (as displayed in the Report Window) Modified: trunk/18xx/rails/game/DisplayBuffer.java =================================================================== --- trunk/18xx/rails/game/DisplayBuffer.java 2010-07-04 20:51:33 UTC (rev 1332) +++ trunk/18xx/rails/game/DisplayBuffer.java 2010-07-05 18:02:13 UTC (rev 1333) @@ -73,13 +73,26 @@ } private static DisplayBuffer getInstance() { - return GameManager.getInstance().getDisplayBuffer(); + GameManagerI gm = GameManager.getInstance(); + if (gm == null) { + return null; + } else { + return gm.getDisplayBuffer(); + } } /** Get the current message buffer, and clear it */ public static String[] get() { DisplayBuffer instance = getInstance(); - if (instance.displayBuffer.size() > 0) { + if (instance == null) { + if (initialQueue.isEmpty()) { + return null; + } else { + String[] message = initialQueue.toArray(new String[0]); + initialQueue.clear(); + return message; + } + } else if (instance.displayBuffer.size() > 0) { String[] message = instance.displayBuffer.toArray(new String[0]); instance.displayBuffer.clear(); return message; Modified: trunk/18xx/rails/game/GameManager.java =================================================================== --- trunk/18xx/rails/game/GameManager.java 2010-07-04 20:51:33 UTC (rev 1332) +++ trunk/18xx/rails/game/GameManager.java 2010-07-05 18:02:13 UTC (rev 1333) @@ -187,6 +187,9 @@ /** A List of available game options */ protected List<GameOption> availableGameOptions = new ArrayList<GameOption>(); + + /** indicates that the recoverySave already issued a warning, avoids displaying several warnings */ + protected boolean recoverySaveWarning = true; protected static Logger log = Logger.getLogger(GameManager.class.getPackage().getName()); @@ -810,6 +813,7 @@ if (action != null) { if (result && !(action instanceof GameAction) && action.hasActed()) { if (moveStack.isOpen()) moveStack.finish(); + recoverySave(); } else { if (moveStack.isOpen()) moveStack.cancel(); } @@ -929,15 +933,72 @@ return true; } + /** recoverySave method + * Uses filePath defined in save.recovery.filepath + * */ + protected void recoverySave() { + if (Config.get("save.recovery.active", "yes").equalsIgnoreCase("no")) return; + + String filePath = Config.get("save.recovery.filepath", "18xx_autosave.rails"); + // create temporary new save file + File tempFile = null; + tempFile = new File(filePath + ".tmp"); + if (!save(tempFile, recoverySaveWarning, "RecoverySaveFailed")) { + recoverySaveWarning = false; + return; + } + + // rename the temp file to the recover file + File recoveryFile = null; + boolean result; + try { + log.debug("Created temporary recovery file, path = " + tempFile.getAbsolutePath()); + // check if previous save file exists + recoveryFile = new File(filePath); + log.debug("Potential recovery filePath = " + recoveryFile.getAbsolutePath()); + if (recoveryFile.exists()) { + log.debug("Potential recovery filePath = " + recoveryFile.getAbsolutePath()); + File backupFile = new File(filePath + ".bak"); + if (recoveryFile.renameTo(backupFile)) { + result = tempFile.renameTo(recoveryFile); + } else { + result = backupFile.renameTo(recoveryFile); + } + } else { + log.debug("Tries to rename temporary file"); + result = tempFile.renameTo(recoveryFile); + } + } catch (Exception e) { + DisplayBuffer.add(LocalText.getText("RecoverySaveFailed", e.getMessage())); + recoverySaveWarning = false; + return; + } + + if (result) { + log.debug("Renamed to recovery file, path = " + recoveryFile.getAbsolutePath()); + if (!recoverySaveWarning) { + DisplayBuffer.add(LocalText.getText("RecoverySaveSuccessAgain")); + recoverySaveWarning = true; + } + } else { + if (recoverySaveWarning) { + DisplayBuffer.add(LocalText.getText("RecoverySaveFailed", "file renaming not possible")); + recoverySaveWarning = false; + } + } + } + protected boolean save(GameAction saveAction) { - - String filepath = saveAction.getFilepath(); + File file = new File(saveAction.getFilepath()); + return save(file, true, "SaveFailed"); + } + + protected boolean save(File file, boolean displayErrorMessage, String errorMessageKey) { boolean result = false; try { ObjectOutputStream oos = - new ObjectOutputStream(new FileOutputStream(new File( - filepath))); + new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(Game.version+" "+BuildInfo.buildDate); oos.writeObject(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); oos.writeObject(saveFileVersionID); @@ -949,10 +1010,11 @@ result = true; } catch (IOException e) { - log.error("Save failed", e); - DisplayBuffer.add(LocalText.getText("SaveFailed", e.getMessage())); + log.error(errorMessageKey, e); + if (displayErrorMessage) { + DisplayBuffer.add(LocalText.getText("SaveFailed", e.getMessage())); + } } - return result; } Modified: trunk/18xx/rails/ui/swing/GameSetupWindow.java =================================================================== --- trunk/18xx/rails/ui/swing/GameSetupWindow.java 2010-07-04 20:51:33 UTC (rev 1332) +++ trunk/18xx/rails/ui/swing/GameSetupWindow.java 2010-07-05 18:02:13 UTC (rev 1333) @@ -25,7 +25,7 @@ private static final long serialVersionUID = 1L; GridBagConstraints gc; JPanel gameListPane, playersPane, buttonPane, optionsPane; - JButton newButton, loadButton, quitButton, optionButton, infoButton; + JButton newButton, loadButton, recoveryButton, quitButton, optionButton, infoButton; JButton creditsButton, randomizeButton; JComboBox gameNameBox = new JComboBox(); JComboBox[] playerBoxes = new JComboBox[Player.MAX_PLAYERS]; @@ -66,6 +66,7 @@ newButton = new JButton(LocalText.getText("NewGame")); loadButton = new JButton(LocalText.getText("LoadGame")); + recoveryButton = new JButton(LocalText.getText("RecoverGame")); quitButton = new JButton(LocalText.getText("QUIT")); optionButton = new JButton(LocalText.getText("OPTIONS")); infoButton = new JButton(LocalText.getText("INFO")); @@ -73,6 +74,7 @@ newButton.setMnemonic(KeyEvent.VK_N); loadButton.setMnemonic(KeyEvent.VK_L); + recoveryButton.setMnemonic(KeyEvent.VK_R); quitButton.setMnemonic(KeyEvent.VK_Q); optionButton.setMnemonic(KeyEvent.VK_O); infoButton.setMnemonic(KeyEvent.VK_G); @@ -85,12 +87,15 @@ populateGameList(GamesInfo.getGameNames(), gameNameBox); gameListPane.add(new JLabel("Available Games:")); + gameListPane.add(new JLabel("")); // empty slot gameListPane.add(gameNameBox); + gameListPane.add(optionButton); gameListPane.setLayout(new GridLayout(2, 2)); gameListPane.setBorder(BorderFactory.createLoweredBevelBorder()); newButton.addActionListener(this); loadButton.addActionListener(this); + recoveryButton.addActionListener(this); quitButton.addActionListener(this); optionButton.addActionListener(this); infoButton.addActionListener(this); @@ -99,7 +104,9 @@ buttonPane.add(newButton); buttonPane.add(loadButton); - buttonPane.add(optionButton); + if (!Config.get("save.recovery.active", "yes").equalsIgnoreCase("no")) { + buttonPane.add(recoveryButton); + } buttonPane.add(infoButton); buttonPane.add(quitButton); buttonPane.add(creditsButton); @@ -187,6 +194,26 @@ } } + /* + * loads and start the game given a filename + */ + private void loadAndStartGame(String filePath, String saveDirectory) { + if ((game = Game.load(filePath)) == null) { + JOptionPane.showMessageDialog(this, + DisplayBuffer.get(), "", JOptionPane.ERROR_MESSAGE); + return; + } else if (DisplayBuffer.getSize() > 0) { + JOptionPane.showMessageDialog(this, + DisplayBuffer.get(), "", JOptionPane.ERROR_MESSAGE); + } + startGameUIManager(game); + if (saveDirectory != null) { + gameUIManager.setSaveDirectory (saveDirectory); + } + gameUIManager.startLoadedGame(); + setVisible(false); + } + public void actionPerformed(ActionEvent arg0) { if (arg0.getSource().equals(newButton)) { startNewGame(); @@ -200,24 +227,13 @@ if (jfc.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); - String filepath = selectedFile.getPath(); - saveDirectory = selectedFile.getParent(); - if ((game = Game.load(filepath)) == null) { - JOptionPane.showMessageDialog(this, - DisplayBuffer.get(), "", JOptionPane.ERROR_MESSAGE); - return; - } else if (DisplayBuffer.getSize() > 0) { - JOptionPane.showMessageDialog(this, - DisplayBuffer.get(), "", JOptionPane.ERROR_MESSAGE); - } + loadAndStartGame(selectedFile.getPath(), selectedFile.getParent()); } else { // cancel pressed return; } - - startGameUIManager(game); - gameUIManager.setSaveDirectory (saveDirectory); - gameUIManager.startLoadedGame(); - setVisible(false); + } else if (arg0.getSource().equals(recoveryButton)) { + String filePath = Config.get("save.recovery.filepath", "18xx_autosave.rails"); + loadAndStartGame(filePath, null); } else if (arg0.getSource().equals(infoButton)) { JOptionPane.showMessageDialog(this, GamesInfo.getDescription(gameName), "Information about " This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |