From: Erik V. <ev...@us...> - 2011-08-03 21:12:01
|
rails/game/MapManager.java | 88 +++---- rails/game/correct/MapCorrectionManager.java | 71 ++---- rails/game/state/HashMapState.java | 39 +-- rails/ui/swing/UpgradesPanel.java | 32 +- rails/util/ListAndFixSavedFiles.java | 299 -------------------------- rails/util/Util.java | 34 ++- tools/ListAndFixSavedFiles.java | 301 +++++++++++++++++++++++++++ tools/Util.java | 37 --- tools/XmlUtils.java | 2 9 files changed, 431 insertions(+), 472 deletions(-) New commits: commit 66795c3b6fc0a5c416cad30dd7af0ac7316a67b1 Author: Erik Vos <eri...@xs...> Date: Wed Aug 3 23:10:21 2011 +0200 Minor tools/util refactoring. Moved ListAndFixSavedFiles to tools. Merged tools.Util into rails.util.Util. diff --git a/rails/game/MapManager.java b/rails/game/MapManager.java index f40e509..8ec32be 100644 --- a/rails/game/MapManager.java +++ b/rails/game/MapManager.java @@ -5,11 +5,7 @@ import java.util.*; import org.apache.log4j.Logger; -import rails.common.parser.Config; -import rails.common.parser.ConfigurableComponentI; -import rails.common.parser.ConfigurationException; -import rails.common.parser.Tag; -import tools.Util; +import rails.common.parser.*; /** * MapManager configures the map layout from XML @@ -23,7 +19,7 @@ public class MapManager implements ConfigurableComponentI { protected TileOrientation tileOrientation; protected boolean lettersGoHorizontal; protected boolean letterAHasEvenNumbers; - + // Optional map image (SVG file) protected String mapImageFilename = null; protected String mapImageFilepath = null; @@ -43,13 +39,13 @@ public class MapManager implements ConfigurableComponentI { // information to define neighbours protected static final int[] xDeltaNS = new int[] { 0, -1, -1, 0, +1, +1 }; protected static final int[] yXEvenDeltaNS = - new int[] { +1, 0, -1, -1, -1, 0 }; + new int[] { +1, 0, -1, -1, -1, 0 }; protected static final int[] yXOddDeltaNS = - new int[] { +1, +1, 0, -1, 0, +1 }; + new int[] { +1, +1, 0, -1, 0, +1 }; protected static final int[] xYEvenDeltaEW = - new int[] { -1, -1, -1, 0, +1, 0 }; + new int[] { -1, -1, -1, 0, +1, 0 }; protected static final int[] xYOddDeltaEW = - new int[] { 0, -1, 0, +1, +1, +1 }; + new int[] { 0, -1, 0, +1, +1, +1 }; protected static final int[] yDeltaEW = new int[] { +1, 0, -1, -1, 0, +1 }; protected static Logger log = @@ -91,7 +87,7 @@ public class MapManager implements ConfigurableComponentI { lettersGoHorizontal = false; } else { throw new ConfigurationException("Invalid letter orientation: " - + attr); + + attr); } attr = tag.getAttributeAsString("even"); @@ -130,7 +126,7 @@ public class MapManager implements ConfigurableComponentI { } } log.debug("Possible tileCosts on map are "+possibleTileCosts); - + int xOffset = 0; int yOffset = 0; if (minX < 0) { @@ -161,16 +157,16 @@ public class MapManager implements ConfigurableComponentI { int i, j, k; MapHex nb; - mapImageUsed = Util.hasValue(mapImageFilename) - && "yes".equalsIgnoreCase(Config.get("map.image.display")); + mapImageUsed = rails.util.Util.hasValue(mapImageFilename) + && "yes".equalsIgnoreCase(Config.get("map.image.display")); if (mapImageUsed) { String rootDirectory = Config.get("map.root_directory"); - if (!Util.hasValue(rootDirectory)) { + if (!rails.util.Util.hasValue(rootDirectory)) { rootDirectory = "data"; } mapImageFilepath = rootDirectory + "/" + mapImageFilename; } - + for (String hexName : mHexes.keySet()) { hex = mHexes.get(hexName); hex.finishConfiguration(gameManager); @@ -227,22 +223,22 @@ public class MapManager implements ConfigurableComponentI { public boolean lettersGoHorizontal() { return lettersGoHorizontal; } - + public int getAdjacentX (int x, int y, int orientation) { - - if (tileOrientation == TileOrientation.EW) { + + if (tileOrientation == TileOrientation.EW) { return x + (y % 2 == 0 ? xYEvenDeltaEW[orientation] : xYOddDeltaEW[orientation]); - } else { + } else { return x + xDeltaNS[orientation]; - } + } } - + public int getAdjacentY (int x, int y, int orientation) { - + if (tileOrientation == TileOrientation.EW) { return y + yDeltaEW[orientation]; } else { - return y + ((x % 2 == 0) == letterAHasEvenNumbers ? + return y + ((x % 2 == 0) == letterAHasEvenNumbers ? yXEvenDeltaNS[orientation] : yXOddDeltaNS[orientation]); } } @@ -260,7 +256,7 @@ public class MapManager implements ConfigurableComponentI { public MapHex[][] getHexes() { return hexes; } - + public List<MapHex> getHexesAsList() { return new ArrayList<MapHex>(mHexes.values()); } @@ -348,31 +344,31 @@ public class MapManager implements ConfigurableComponentI { */ public int getHexDistance (MapHex hex1, MapHex hex2) { - if (distances == null) distances = new HashMap<MapHex, Map<MapHex, Integer>> (); - if (distances.get(hex1) == null) { - distances.put(hex1, new HashMap<MapHex, Integer>()); - calculateHexDistances(hex1, hex1, 0); - } - return distances.get(hex1).get(hex2); + if (distances == null) distances = new HashMap<MapHex, Map<MapHex, Integer>> (); + if (distances.get(hex1) == null) { + distances.put(hex1, new HashMap<MapHex, Integer>()); + calculateHexDistances(hex1, hex1, 0); + } + return distances.get(hex1).get(hex2); } private void calculateHexDistances (MapHex hex1, MapHex hex2, int depth) { - if (distances.get(hex1).get(hex2) == null) { - distances.get(hex1).put(hex2, depth); - } else { - if (distances.get(hex1).get(hex2) <= depth) return; - distances.get(hex1).put(hex2, depth); - } - - for (MapHex hex3 : hex2.getNeighbors()) { - if (hex3 == null) continue; - if (distances.get(hex1).get(hex3) == null) { - calculateHexDistances (hex1, hex3, depth+1); - } else if (distances.get(hex1).get(hex3) > depth+1) { - calculateHexDistances (hex1, hex3, depth+1); - } - } + if (distances.get(hex1).get(hex2) == null) { + distances.get(hex1).put(hex2, depth); + } else { + if (distances.get(hex1).get(hex2) <= depth) return; + distances.get(hex1).put(hex2, depth); + } + + for (MapHex hex3 : hex2.getNeighbors()) { + if (hex3 == null) continue; + if (distances.get(hex1).get(hex3) == null) { + calculateHexDistances (hex1, hex3, depth+1); + } else if (distances.get(hex1).get(hex3) > depth+1) { + calculateHexDistances (hex1, hex3, depth+1); + } + } } /** Cache to hold all unique distance values of tokenable cities from a given hex */ diff --git a/rails/game/correct/MapCorrectionManager.java b/rails/game/correct/MapCorrectionManager.java index 43716f2..39a210b 100644 --- a/rails/game/correct/MapCorrectionManager.java +++ b/rails/game/correct/MapCorrectionManager.java @@ -1,53 +1,42 @@ package rails.game.correct; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import java.util.*; import rails.common.DisplayBuffer; import rails.common.LocalText; -import rails.game.BaseToken; -import rails.game.City; -import rails.game.GameManager; -import rails.game.MapHex; -import rails.game.ReportBuffer; -import rails.game.Station; -import rails.game.TileI; -import rails.game.TileManager; -import rails.game.TokenI; -import tools.Util; +import rails.game.*; public class MapCorrectionManager extends CorrectionManager { - + public static enum ActionStep { SELECT_HEX,SELECT_TILE,SELECT_ORIENTATION,CONFIRM,RELAY_BASETOKENS,FINISHED,CANCELLED; } - + private MapCorrectionAction activeTileAction = null; - + protected MapCorrectionManager(GameManager gm) { super(gm, CorrectionType.CORRECT_MAP); } - + @Override public List<CorrectionAction> createCorrections() { List<CorrectionAction> actions = super.createCorrections(); - + if (isActive()) { if (activeTileAction == null) activeTileAction = new MapCorrectionAction(); actions.add(activeTileAction); } - + return actions; } - + @Override public boolean executeCorrection(CorrectionAction action){ if (action instanceof MapCorrectionAction) return execute((MapCorrectionAction) action); else // any other action, could be a correctionMode action - return super.executeCorrection(action); + return super.executeCorrection(action); } private boolean execute(MapCorrectionAction action){ @@ -60,18 +49,18 @@ public class MapCorrectionManager extends CorrectionManager { activeTileAction = null; return true; } - + MapHex hex = action.getLocation(); - + TileI chosenTile = action.getChosenTile(); TileManager tmgr = gameManager.getTileManager(); TileI preprintedTile = tmgr.getTile(hex.getPreprintedTileId()); - // check conditions + // check conditions String errMsg = null; while (true) { // check if chosenTile is still available (not for preprinted) - if (chosenTile != null && Util.hasValue(chosenTile.getExternalId()) + if (chosenTile != null && rails.util.Util.hasValue(chosenTile.getExternalId()) && chosenTile != hex.getCurrentTile() && chosenTile.countFreeTiles() == 0) { errMsg = @@ -100,7 +89,7 @@ public class MapCorrectionManager extends CorrectionManager { } // check if chosenTile requires relays // this is not implemented yet, thus error message - if (chosenTile.getNumStations() >= 2 + if (chosenTile.getNumStations() >= 2 && hex.getCurrentTile().getColourNumber() >= chosenTile.getColourNumber() // B. or the current tile requires relays || hex.getCurrentTile().relayBaseTokensOnUpgrade()) { @@ -131,7 +120,7 @@ public class MapCorrectionManager extends CorrectionManager { // preparation for the next step switch (nextStep) { - case SELECT_TILE: + case SELECT_TILE: // create list of possible up and downgrades List<TileI> possibleTiles = tmgr.getAllUpgrades(preprintedTile, hex); if (preprintedTile == hex.getCurrentTile()) @@ -153,10 +142,10 @@ public class MapCorrectionManager extends CorrectionManager { } case RELAY_BASETOKENS: // check if relays are necessary: - // A. downgrades or equalgrades to a tile with two stations or more - if (chosenTile.getNumStations() >= 2 + // A. downgrades or equalgrades to a tile with two stations or more + if (chosenTile.getNumStations() >= 2 && hex.getCurrentTile().getColourNumber() >= chosenTile.getColourNumber() - // B. or the current tile requires relays + // B. or the current tile requires relays || hex.getCurrentTile().relayBaseTokensOnUpgrade()) { // define tokens for relays List<BaseToken> tokens = new ArrayList<BaseToken>(); @@ -178,27 +167,27 @@ public class MapCorrectionManager extends CorrectionManager { } case FINISHED: gameManager.getMoveStack().start(false); - + // lays tile int orientation = action.getOrientation(); hex.upgrade(chosenTile, orientation, new HashMap<String,Integer>()); - + String msg = LocalText.getText("CorrectMapLaysTileAt", chosenTile.getExternalId(), hex.getName(), hex.getOrientationName(orientation)); ReportBuffer.add(msg); gameManager.addToNextPlayerMessages(msg, true); // relays tokens -// if (action.getTokensToRelay() != null) { -// for (BaseToken token:action.getTokensToRelay()) { -// int i = action.getTokensToRelay().indexOf(token); -// -// } -// } - + // if (action.getTokensToRelay() != null) { + // for (BaseToken token:action.getTokensToRelay()) { + // int i = action.getTokensToRelay().indexOf(token); + // + // } + // } + activeTileAction = null; break; - + case CANCELLED: // should be captured above activeTileAction = null; @@ -207,7 +196,7 @@ public class MapCorrectionManager extends CorrectionManager { if (action.getStep() != ActionStep.FINISHED) { action.moveToNextStep(); } - + return true; } } diff --git a/rails/game/state/HashMapState.java b/rails/game/state/HashMapState.java index 225346d..5e1fe9e 100644 --- a/rails/game/state/HashMapState.java +++ b/rails/game/state/HashMapState.java @@ -1,17 +1,10 @@ package rails.game.state; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import rails.game.model.ModelObject; import rails.game.move.MapChange; import rails.game.move.RemoveFromMap; -import tools.Util; /** * State class that wraps a HashMap @@ -29,7 +22,7 @@ public class HashMapState<K,V> extends ModelObject { private final HashMap<K,V> map = new HashMap<K,V>(); private String mapName; - + /** * constructor for an empty map */ @@ -42,29 +35,29 @@ public class HashMapState<K,V> extends ModelObject { public HashMapState(String listName, Map<K,V> map) { this(listName); } - + public void put(K key, V value) { new MapChange<K,V>(map, key, value, this); } - + public void putAll(Map<K,V> map) { for (K key:map.keySet()) { new MapChange<K,V>(map, key, map.get(key), this); } } - + public V get(K key) { return map.get(key); } - + public void remove(K key) { - new RemoveFromMap<K,V>(map, key, this); + new RemoveFromMap<K,V>(map, key, this); } - + public boolean hasKey(K key) { return map.containsKey(key); } - + public void clear() { // Two-step process to avoid concurrent modification exception List<K> keys = new ArrayList<K>(); @@ -98,8 +91,8 @@ public class HashMapState<K,V> extends ModelObject { } update(); } - - /** + + /** * @return unmodifiable view of map */ public Map<K,V> viewMap() { @@ -111,26 +104,26 @@ public class HashMapState<K,V> extends ModelObject { public Set<K> viewKeySet() { return Collections.unmodifiableSet(map.keySet()); } - + public Collection<V> viewValues() { return Collections.unmodifiableCollection(map.values()); } - + public boolean isEmpty() { return map.isEmpty(); } - + @Override public String getText() { if (map == null) return ""; - + StringBuilder buf = new StringBuilder("<html>"); for (K name : map.keySet()) { if (buf.length() > 6) buf.append("<br>"); buf.append(name.toString()); Object value = map.get(name); - if (value != null && Util.hasValue(value.toString())) buf.append("=").append(value.toString()); + if (value != null && rails.util.Util.hasValue(value.toString())) buf.append("=").append(value.toString()); } if (buf.length() > 6) { buf.append("</html>"); diff --git a/rails/ui/swing/UpgradesPanel.java b/rails/ui/swing/UpgradesPanel.java index 15b258c..0d9f925 100644 --- a/rails/ui/swing/UpgradesPanel.java +++ b/rails/ui/swing/UpgradesPanel.java @@ -4,9 +4,8 @@ package rails.ui.swing; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; -import java.util.ArrayList; +import java.util.*; import java.util.List; -import java.util.Set; import javax.swing.*; import javax.swing.border.Border; @@ -21,7 +20,6 @@ import rails.game.correct.MapCorrectionAction; import rails.ui.swing.elements.ActionLabel; import rails.ui.swing.hexmap.GUIHex; import rails.ui.swing.hexmap.HexMap; -import tools.Util; public class UpgradesPanel extends Box implements MouseListener, ActionListener { private static final long serialVersionUID = 1L; @@ -45,12 +43,12 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener private boolean tokenMode = false; private boolean correctionTokenMode = false; private JButton cancelButton = - new JButton(LocalText.getText(INIT_CANCEL_TEXT)); + new JButton(LocalText.getText(INIT_CANCEL_TEXT)); private JButton doneButton = new JButton(LocalText.getText(INIT_DONE_TEXT)); private HexMap hexMap; protected static Logger log = - Logger.getLogger(UpgradesPanel.class.getPackage().getName()); + Logger.getLogger(UpgradesPanel.class.getPackage().getName()); public UpgradesPanel(ORUIManager orUIManager) { super(BoxLayout.Y_AXIS); @@ -94,12 +92,12 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener for (LayTile layTile : hexMap.getTileAllowancesForHex(hex)) { tiles = layTile.getTiles(); - if (tiles == null) { + if (tiles == null) { for (TileI tile : uiHex.getCurrentTile().getValidUpgrades(hex, orUIManager.gameUIManager.getCurrentPhase())) { // Skip if not allowed in LayTile //if (!layTile.isTileColourAllowed(tile.getColourName())) continue; - + if (!orUIManager.tileUpgrades.contains(tile)) orUIManager.tileUpgrades.add(tile); } @@ -123,7 +121,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener panelLayout.setRows(defaultNbPanelElements); if (tokenMode && possibleTokenLays != null - && possibleTokenLays.size() > 0) { + && possibleTokenLays.size() > 0) { Color fgColour = null; Color bgColour = null; @@ -145,7 +143,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener fgColour = Color.BLACK; bgColour = Color.WHITE; BonusToken token = - (BonusToken) action.getSpecialProperty().getToken(); + (BonusToken) action.getSpecialProperty().getToken(); description = token.getName(); text = "+" + token.getValue(); } @@ -245,7 +243,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener upgradePanel.add(doneButton); upgradePanel.add(cancelButton); -// repaint(); + // repaint(); revalidate(); } @@ -298,7 +296,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener upgradePanel.add(doneButton); upgradePanel.add(cancelButton); -// repaint(); + // repaint(); revalidate(); } @@ -312,7 +310,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener public void setSelectedTokenIndex(int index) { log.debug("Selected token index from " + selectedTokenIndex + " to " - + index); + + index); selectedTokenIndex = index; } @@ -474,7 +472,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener super(tokenIcon); this.token = token; } - + } /** JLabel extension to allow attaching the internal hex ID */ @@ -501,7 +499,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener void setTextFromTile(TileI tile) { StringBuffer text = new StringBuffer(); - if (Util.hasValue(tile.getExternalId())) { + if (rails.util.Util.hasValue(tile.getExternalId())) { text.append("<HTML><BODY>" + tile.getExternalId()); if (tile.countFreeTiles() != -1) { text.append("<BR> (" + tile.countFreeTiles() + ")"); @@ -515,7 +513,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener TileI currentTile = orUIManager.getGameUIManager().getGameManager().getTileManager().getTile(internalId); StringBuffer tt = new StringBuffer("<html>"); tt.append("<b>Tile</b>: ").append(currentTile.getName()); // or - // getId() + // getId() if (currentTile.hasStations()) { // for (Station st : currentTile.getStations()) int cityNumber = 0; @@ -524,11 +522,11 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener cityNumber++; // = city.getNumber(); tt.append("<br> ").append(st.getType()).append(" ").append( cityNumber) // .append("/").append(st.getNumber()) - .append(": value "); + .append(": value "); tt.append(st.getValue()); if (st.getBaseSlots() > 0) { tt.append(", ").append(st.getBaseSlots()).append( - " slots"); + " slots"); } } } diff --git a/rails/util/ListAndFixSavedFiles.java b/rails/util/ListAndFixSavedFiles.java deleted file mode 100644 index 11a6938..0000000 --- a/rails/util/ListAndFixSavedFiles.java +++ /dev/null @@ -1,299 +0,0 @@ -package rails.util; - -import java.awt.*; -import java.awt.event.*; -import java.io.*; -import java.util.*; -import java.util.List; - -import javax.swing.*; - -import org.apache.log4j.Logger; - -import rails.common.DisplayBuffer; -import rails.common.LocalText; -import rails.common.parser.Config; -import rails.common.parser.ConfigurationException; -import rails.game.*; -import rails.game.action.PossibleAction; -import rails.ui.swing.elements.ActionMenuItem; - -public class ListAndFixSavedFiles extends JFrame -implements ActionListener, KeyListener { - - private static final long serialVersionUID = 1L; - private JTextArea reportText; - private JScrollPane messageScroller; - private JScrollBar vbar; - private JPanel messagePanel; - private ListAndFixSavedFiles messageWindow; - private JMenuBar menuBar; - private JMenu fileMenu, editMenu; - private JMenuItem saveItem, loadItem; - private JMenuItem trimItem, deleteItem; - - private StringBuffer headerText = new StringBuffer(); - - private GameFileIO fileIO; - - private int vbarPos; - - private static String saveDirectory; - private String filepath; - - protected static Logger log; - - /** - * @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); - - new ListAndFixSavedFiles (); - - } - - public ListAndFixSavedFiles () { - - super(); - - messageWindow = this; - - reportText = new JTextArea(); - reportText.setEditable(false); - reportText.setLineWrap(false); - reportText.setBackground(Color.WHITE); - reportText.setOpaque(true); - reportText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - - messagePanel = new JPanel(new GridBagLayout()); - messageScroller = - new JScrollPane(reportText, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - vbar = messageScroller.getVerticalScrollBar(); - GridBagConstraints gbc = new GridBagConstraints(); - gbc.gridx = gbc.gridy = 0; - gbc.weightx = gbc.weighty = 1.0; - gbc.fill = GridBagConstraints.BOTH; - messagePanel.add(messageScroller, gbc); - - menuBar = new JMenuBar(); - fileMenu = new JMenu(LocalText.getText("FILE")); - fileMenu.setMnemonic(KeyEvent.VK_F); - editMenu = new JMenu(LocalText.getText("EDIT")); - editMenu.setMnemonic(KeyEvent.VK_E); - - loadItem = new ActionMenuItem(LocalText.getText("LOAD")); - loadItem.setActionCommand("LOAD"); - loadItem.setMnemonic(KeyEvent.VK_L); - loadItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, - ActionEvent.ALT_MASK)); - loadItem.addActionListener(this); - loadItem.setEnabled(true); - fileMenu.add(loadItem); - - saveItem = new ActionMenuItem(LocalText.getText("SAVE")); - saveItem.setActionCommand("SAVE"); - saveItem.setMnemonic(KeyEvent.VK_S); - saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, - ActionEvent.ALT_MASK)); - saveItem.addActionListener(this); - saveItem.setEnabled(true); - fileMenu.add(saveItem); - - trimItem = new ActionMenuItem("Trim"); - trimItem.setActionCommand("TRIM"); - trimItem.setMnemonic(KeyEvent.VK_T); - trimItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, - ActionEvent.ALT_MASK)); - trimItem.addActionListener(this); - trimItem.setEnabled(true); - editMenu.add(trimItem); - - deleteItem = new ActionMenuItem("Delete"); - deleteItem.setActionCommand("DELETE"); - deleteItem.setMnemonic(KeyEvent.VK_D); - deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, - ActionEvent.ALT_MASK)); - deleteItem.addActionListener(this); - deleteItem.setEnabled(true); - editMenu.add(deleteItem); - - menuBar.add(fileMenu); - menuBar.add(editMenu); - - setJMenuBar(menuBar); - - setContentPane(messagePanel); - - setSize(400, 400); - setLocation(600, 400); - setTitle("List and fix saved files"); - - addKeyListener(this); - - - setVisible(true); - - saveDirectory = Config.get("save.directory"); - - load(); - - } - - private void load() { - - JFileChooser jfc = new JFileChooser(); - jfc.setCurrentDirectory(new File(saveDirectory)); - - if (jfc.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION) { - - File selectedFile = jfc.getSelectedFile(); - filepath = selectedFile.getPath(); - saveDirectory = selectedFile.getParent(); - - // clear header text - headerText = new StringBuffer(); - - // use GameLoader object to load game - fileIO = new GameFileIO(); - - fileIO.loadGameData(filepath); - add(fileIO.getGameDataAsText()); - try{ - fileIO.initGame(); - fileIO.loadActionsAndComments(); - setReportText(true); - - } catch (ConfigurationException e) { - log.fatal("Load failed", e); - DisplayBuffer.add(LocalText.getText("LoadFailed", e.getMessage())); - } - } - - } - - public void add (String text) { - if (text.length() > 0) { - headerText.append(text); - 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; - for (PossibleAction action : fileIO.getActions()) { - reportText.append("Action "+i+" "+action.getPlayerName()+": "+action.toString()); - reportText.append("\n"); - // check for comments for this action - String comment = fileIO.getComments().get(i); - if (comment!= null) { - reportText.append("Comment to action " + i + ": " + comment + "\n"); - } - i++; - } - scrollDown(vbarPos); - } - - - public void scrollDown (int pos) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (vbarPos == -1) - messageWindow.vbar.setValue(messageWindow.vbar.getMaximum()); - else - messageWindow.vbar.setValue(vbarPos); - } - }); - } - - - - public void actionPerformed(ActionEvent actor) { - String command = actor.getActionCommand(); - if ("TRIM".equalsIgnoreCase(command)) { - String result = JOptionPane.showInputDialog("Enter last action number to be retained"); - if (Util.hasValue(result)) { - try { - int index = Integer.parseInt(result); - // delete actions - int size = fileIO.getActions().size(); - fileIO.getActions().subList(index + 1, size).clear(); - // delete comments - for (int id = 0; id < size; id++) { - if (id > index) { - fileIO.getComments().remove(id); - } - } - setReportText(false); - } catch (NumberFormatException e) { - - } - } - } else if ("DELETE".equalsIgnoreCase(command)) { - String result = JOptionPane.showInputDialog("Enter action number to be deleted"); - if (Util.hasValue(result)) { - try { - int index = Integer.parseInt(result); - fileIO.getActions().remove(index); - // delete and renumber in user Comments - SortedMap<Integer, String> newComments = new TreeMap<Integer, String>(); - for (Integer id:fileIO.getComments().keySet()) { - if (id < index) { - newComments.put(id, fileIO.getComments().get(id)); - } else if (id > index) { - newComments.put(id-1, fileIO.getComments().get(id)); - } - } - fileIO.setComments(newComments); - setReportText(false); - } catch (NumberFormatException e) { - log.error("Number format exception for '"+result+"'", e); - } - } - } else if ("SAVE".equalsIgnoreCase(command)) { - save(); - } else if ("LOAD".equalsIgnoreCase(command)) { - load(); - } - } - - private void save() { - JFileChooser jfc = new JFileChooser(); - if (Util.hasValue(saveDirectory)) { - jfc.setCurrentDirectory(new File(saveDirectory)); - } - if (Util.hasValue(filepath)) { - jfc.setSelectedFile(new File(filepath)); - } - if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { - File selectedFile = jfc.getSelectedFile(); - fileIO.saveGame(selectedFile, true, "SaveFailed"); - } - - } - - public void keyPressed(KeyEvent e) { - } - - public void keyReleased(KeyEvent e) {} - - public void keyTyped(KeyEvent e) {} - -} diff --git a/rails/util/Util.java b/rails/util/Util.java index 2e20814..e558719 100644 --- a/rails/util/Util.java +++ b/rails/util/Util.java @@ -2,6 +2,7 @@ package rails.util; import java.awt.Color; +import java.io.*; import java.util.ArrayList; import java.util.List; @@ -79,7 +80,7 @@ public final class Util { } } - + /** * Convert java string to html string * Transformations: @@ -88,9 +89,9 @@ public final class Util { public static String convertToHtml(String javaString) { return javaString.replace("\n", "<br>"); } - - - + + + /** * Safely move a list of objects from one holder to another, avoiding * ConcurrentModificationExceptions. @@ -148,7 +149,7 @@ public final class Util { } return Boolean.parseBoolean(s); } - + /** * Parse a colour definition string. * Currently supported formats: @@ -183,9 +184,9 @@ public final class Util { return c; } - - - + + + /** * Is a colour dark? (to check if FG colour needs be reversed) */ @@ -207,4 +208,21 @@ public final class Util { public static String lowerCaseFirst (String text) { return text.substring(0, 1).toLowerCase() + text.substring(1); } + + /** + * Open an input stream from a file, which may exist as a physical file or + * in a JAR file. The name must be valid for both options. + * + * @author Erik Vos + */ + public static InputStream getStreamForFile(String fileName) + throws IOException { + + File file = new File(fileName); + if (file.exists()) { + return new FileInputStream(file); + } else { + return null; + } + } } diff --git a/tools/ListAndFixSavedFiles.java b/tools/ListAndFixSavedFiles.java new file mode 100644 index 0000000..6a66c25 --- /dev/null +++ b/tools/ListAndFixSavedFiles.java @@ -0,0 +1,301 @@ +package tools; + +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import java.util.*; +import java.util.List; + +import javax.swing.*; + +import org.apache.log4j.Logger; + +import rails.common.DisplayBuffer; +import rails.common.LocalText; +import rails.common.parser.Config; +import rails.common.parser.ConfigurationException; +import rails.game.*; +import rails.game.action.PossibleAction; +import rails.ui.swing.elements.ActionMenuItem; +import rails.util.GameFileIO; +import rails.util.Util; + +public class ListAndFixSavedFiles extends JFrame +implements ActionListener, KeyListener { + + private static final long serialVersionUID = 1L; + private JTextArea reportText; + private JScrollPane messageScroller; + private JScrollBar vbar; + private JPanel messagePanel; + private ListAndFixSavedFiles messageWindow; + private JMenuBar menuBar; + private JMenu fileMenu, editMenu; + private JMenuItem saveItem, loadItem; + private JMenuItem trimItem, deleteItem; + + private StringBuffer headerText = new StringBuffer(); + + private GameFileIO fileIO; + + private int vbarPos; + + private static String saveDirectory; + private String filepath; + + protected static Logger log; + + /** + * @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); + + new ListAndFixSavedFiles (); + + } + + public ListAndFixSavedFiles () { + + super(); + + messageWindow = this; + + reportText = new JTextArea(); + reportText.setEditable(false); + reportText.setLineWrap(false); + reportText.setBackground(Color.WHITE); + reportText.setOpaque(true); + reportText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + messagePanel = new JPanel(new GridBagLayout()); + messageScroller = + new JScrollPane(reportText, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + vbar = messageScroller.getVerticalScrollBar(); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridx = gbc.gridy = 0; + gbc.weightx = gbc.weighty = 1.0; + gbc.fill = GridBagConstraints.BOTH; + messagePanel.add(messageScroller, gbc); + + menuBar = new JMenuBar(); + fileMenu = new JMenu(LocalText.getText("FILE")); + fileMenu.setMnemonic(KeyEvent.VK_F); + editMenu = new JMenu(LocalText.getText("EDIT")); + editMenu.setMnemonic(KeyEvent.VK_E); + + loadItem = new ActionMenuItem(LocalText.getText("LOAD")); + loadItem.setActionCommand("LOAD"); + loadItem.setMnemonic(KeyEvent.VK_L); + loadItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, + ActionEvent.ALT_MASK)); + loadItem.addActionListener(this); + loadItem.setEnabled(true); + fileMenu.add(loadItem); + + saveItem = new ActionMenuItem(LocalText.getText("SAVE")); + saveItem.setActionCommand("SAVE"); + saveItem.setMnemonic(KeyEvent.VK_S); + saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, + ActionEvent.ALT_MASK)); + saveItem.addActionListener(this); + saveItem.setEnabled(true); + fileMenu.add(saveItem); + + trimItem = new ActionMenuItem("Trim"); + trimItem.setActionCommand("TRIM"); + trimItem.setMnemonic(KeyEvent.VK_T); + trimItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, + ActionEvent.ALT_MASK)); + trimItem.addActionListener(this); + trimItem.setEnabled(true); + editMenu.add(trimItem); + + deleteItem = new ActionMenuItem("Delete"); + deleteItem.setActionCommand("DELETE"); + deleteItem.setMnemonic(KeyEvent.VK_D); + deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, + ActionEvent.ALT_MASK)); + deleteItem.addActionListener(this); + deleteItem.setEnabled(true); + editMenu.add(deleteItem); + + menuBar.add(fileMenu); + menuBar.add(editMenu); + + setJMenuBar(menuBar); + + setContentPane(messagePanel); + + setSize(400, 400); + setLocation(600, 400); + setTitle("List and fix saved files"); + + addKeyListener(this); + + + setVisible(true); + + saveDirectory = Config.get("save.directory"); + + load(); + + } + + private void load() { + + JFileChooser jfc = new JFileChooser(); + jfc.setCurrentDirectory(new File(saveDirectory)); + + if (jfc.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION) { + + File selectedFile = jfc.getSelectedFile(); + filepath = selectedFile.getPath(); + saveDirectory = selectedFile.getParent(); + + // clear header text + headerText = new StringBuffer(); + + // use GameLoader object to load game + fileIO = new GameFileIO(); + + fileIO.loadGameData(filepath); + add(fileIO.getGameDataAsText()); + try{ + fileIO.initGame(); + fileIO.loadActionsAndComments(); + setReportText(true); + + } catch (ConfigurationException e) { + log.fatal("Load failed", e); + DisplayBuffer.add(LocalText.getText("LoadFailed", e.getMessage())); + } + } + + } + + public void add (String text) { + if (text.length() > 0) { + headerText.append(text); + 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; + for (PossibleAction action : fileIO.getActions()) { + reportText.append("Action "+i+" "+action.getPlayerName()+": "+action.toString()); + reportText.append("\n"); + // check for comments for this action + String comment = fileIO.getComments().get(i); + if (comment!= null) { + reportText.append("Comment to action " + i + ": " + comment + "\n"); + } + i++; + } + scrollDown(vbarPos); + } + + + public void scrollDown (int pos) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + if (vbarPos == -1) + messageWindow.vbar.setValue(messageWindow.vbar.getMaximum()); + else + messageWindow.vbar.setValue(vbarPos); + } + }); + } + + + + public void actionPerformed(ActionEvent actor) { + String command = actor.getActionCommand(); + if ("TRIM".equalsIgnoreCase(command)) { + String result = JOptionPane.showInputDialog("Enter last action number to be retained"); + if (Util.hasValue(result)) { + try { + int index = Integer.parseInt(result); + // delete actions + int size = fileIO.getActions().size(); + fileIO.getActions().subList(index + 1, size).clear(); + // delete comments + for (int id = 0; id < size; id++) { + if (id > index) { + fileIO.getComments().remove(id); + } + } + setReportText(false); + } catch (NumberFormatException e) { + + } + } + } else if ("DELETE".equalsIgnoreCase(command)) { + String result = JOptionPane.showInputDialog("Enter action number to be deleted"); + if (Util.hasValue(result)) { + try { + int index = Integer.parseInt(result); + fileIO.getActions().remove(index); + // delete and renumber in user Comments + SortedMap<Integer, String> newComments = new TreeMap<Integer, String>(); + for (Integer id:fileIO.getComments().keySet()) { + if (id < index) { + newComments.put(id, fileIO.getComments().get(id)); + } else if (id > index) { + newComments.put(id-1, fileIO.getComments().get(id)); + } + } + fileIO.setComments(newComments); + setReportText(false); + } catch (NumberFormatException e) { + log.error("Number format exception for '"+result+"'", e); + } + } + } else if ("SAVE".equalsIgnoreCase(command)) { + save(); + } else if ("LOAD".equalsIgnoreCase(command)) { + load(); + } + } + + private void save() { + JFileChooser jfc = new JFileChooser(); + if (Util.hasValue(saveDirectory)) { + jfc.setCurrentDirectory(new File(saveDirectory)); + } + if (Util.hasValue(filepath)) { + jfc.setSelectedFile(new File(filepath)); + } + if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { + File selectedFile = jfc.getSelectedFile(); + fileIO.saveGame(selectedFile, true, "SaveFailed"); + } + + } + + public void keyPressed(KeyEvent e) { + } + + public void keyReleased(KeyEvent e) {} + + public void keyTyped(KeyEvent e) {} + +} diff --git a/tools/Util.java b/tools/Util.java deleted file mode 100644 index 0233f6b..0000000 --- a/tools/Util.java +++ /dev/null @@ -1,37 +0,0 @@ -/* $Header: /Users/blentz/rails_rcs/cvs/18xx/tools/Util.java,v 1.1 2010/02/03 20:16:38 evos Exp $*/ -package tools; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -public final class Util { - /** - * No-args private constructor, to prevent (meaningless) construction of one - * of these. - */ - private Util() {} - - public static boolean hasValue(String s) { - return s != null && !s.equals(""); - } - - /** - * Open an input stream from a file, which may exist as a physical file or - * in a JAR file. The name must be valid for both options. - * - * @author Erik Vos - */ - public static InputStream getStreamForFile(String fileName) - throws IOException { - - File file = new File(fileName); - if (file.exists()) { - return new FileInputStream(file); - } else { - return null; - } - } - -} diff --git a/tools/XmlUtils.java b/tools/XmlUtils.java index 244dea5..7f419cc 100644 --- a/tools/XmlUtils.java +++ b/tools/XmlUtils.java @@ -186,7 +186,7 @@ public final class XmlUtils { DocumentBuilder db = dbf.newDocumentBuilder(); // Step 3: parse the input file to get a Document object - doc = db.parse(Util.getStreamForFile(fileName)); + doc = db.parse(rails.util.Util.getStreamForFile(fileName)); } catch (ParserConfigurationException e) { throw new ConfigurationException("Could not read/parse " + fileName |