1 package tim.prune.save;
3 import java.awt.BorderLayout;
4 import java.awt.CardLayout;
5 import java.awt.Component;
6 import java.awt.Dimension;
7 import java.awt.FlowLayout;
8 import java.awt.GridLayout;
9 import java.awt.event.ActionEvent;
10 import java.awt.event.ActionListener;
12 import java.io.FileWriter;
13 import java.io.IOException;
15 import javax.swing.BorderFactory;
16 import javax.swing.Box;
17 import javax.swing.BoxLayout;
18 import javax.swing.ButtonGroup;
19 import javax.swing.JButton;
20 import javax.swing.JCheckBox;
21 import javax.swing.JDialog;
22 import javax.swing.JFileChooser;
23 import javax.swing.JFrame;
24 import javax.swing.JLabel;
25 import javax.swing.JOptionPane;
26 import javax.swing.JPanel;
27 import javax.swing.JRadioButton;
28 import javax.swing.JScrollPane;
29 import javax.swing.JTable;
30 import javax.swing.JTextField;
31 import javax.swing.ListSelectionModel;
32 import javax.swing.table.TableModel;
35 import tim.prune.I18nManager;
36 import tim.prune.UpdateMessageBroker;
37 import tim.prune.data.Altitude;
38 import tim.prune.data.Coordinate;
39 import tim.prune.data.DataPoint;
40 import tim.prune.data.Field;
41 import tim.prune.data.FieldList;
42 import tim.prune.data.Timestamp;
43 import tim.prune.data.Track;
44 import tim.prune.load.OneCharDocument;
47 * Class to manage the saving of track data
48 * into a user-specified file
50 public class FileSaver
52 private App _app = null;
53 private JFrame _parentFrame = null;
54 private Track _track = null;
55 private JDialog _dialog = null;
56 private JFileChooser _fileChooser = null;
57 private JPanel _cards = null;
58 private JButton _nextButton = null, _backButton = null;
59 private JTable _table = null;
60 private FieldSelectionTableModel _model = null;
61 private JButton _moveUpButton = null, _moveDownButton = null;
62 private UpDownToggler _toggler = null;
63 private JRadioButton[] _delimiterRadios = null;
64 private JTextField _otherDelimiterText = null;
65 private JCheckBox _headerRowCheckbox = null;
66 private JRadioButton[] _coordUnitsRadios = null;
67 private JRadioButton[] _altitudeUnitsRadios = null;
68 private JRadioButton[] _timestampUnitsRadios = null;
69 private static final int[] FORMAT_COORDS = {Coordinate.FORMAT_NONE, Coordinate.FORMAT_DEG_MIN_SEC,
70 Coordinate.FORMAT_DEG_MIN, Coordinate.FORMAT_DEG};
71 private static final int[] FORMAT_ALTS = {Altitude.FORMAT_NONE, Altitude.FORMAT_METRES, Altitude.FORMAT_FEET};
72 private static final int[] FORMAT_TIMES = {Timestamp.FORMAT_ORIGINAL, Timestamp.FORMAT_LOCALE, Timestamp.FORMAT_ISO_8601};
77 * @param inApp application object to inform of success
78 * @param inParentFrame parent frame
79 * @param inTrack track object to save
81 public FileSaver(App inApp, JFrame inParentFrame, Track inTrack)
84 _parentFrame = inParentFrame;
90 * Show the save file dialog
91 * @param inDefaultDelimiter default delimiter to use
93 public void showDialog(char inDefaultDelimiter)
97 _dialog = new JDialog(_parentFrame, I18nManager.getText("dialog.saveoptions.title"), true);
98 _dialog.setLocationRelativeTo(_parentFrame);
99 _dialog.getContentPane().add(makeDialogComponents());
103 FieldList fieldList = _track.getFieldList();
104 int numFields = fieldList.getNumFields();
105 _model = new FieldSelectionTableModel(numFields);
106 for (int i=0; i<numFields; i++)
108 Field field = fieldList.getField(i);
109 FieldInfo info = new FieldInfo(field, _track.hasData(field));
110 _model.addFieldInfo(info, i);
112 // Initialise dialog and show it
113 initDialog(_model, inDefaultDelimiter);
119 * Make the dialog components
120 * @return the GUI components for the save dialog
122 private Component makeDialogComponents()
124 JPanel panel = new JPanel();
125 panel.setLayout(new BorderLayout());
126 _cards = new JPanel();
127 _cards.setLayout(new CardLayout());
128 panel.add(_cards, BorderLayout.CENTER);
130 // Make first card for field selection and delimiter
131 JPanel firstCard = new JPanel();
132 firstCard.setLayout(new BoxLayout(firstCard, BoxLayout.Y_AXIS));
133 JPanel tablePanel = new JPanel();
134 tablePanel.setLayout(new BorderLayout());
135 _table = new JTable();
136 _table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
137 // Enclose table in a scrollpane to prevent other components getting lost
138 JScrollPane scrollPane = new JScrollPane(_table);
139 _table.setPreferredScrollableViewportSize(new Dimension(300, 150));
140 tablePanel.add(scrollPane, BorderLayout.CENTER);
142 // Make a panel to hold the table and up/down buttons
143 JPanel fieldsPanel = new JPanel();
144 fieldsPanel.setLayout(new BorderLayout());
145 fieldsPanel.add(tablePanel, BorderLayout.CENTER);
146 JPanel updownPanel = new JPanel();
147 updownPanel.setLayout(new BoxLayout(updownPanel, BoxLayout.Y_AXIS));
148 _moveUpButton = new JButton(I18nManager.getText("button.moveup"));
149 _moveUpButton.addActionListener(new ActionListener() {
150 public void actionPerformed(ActionEvent e)
152 int row = _table.getSelectedRow();
155 _model.swapItems(row, row - 1);
156 _table.setRowSelectionInterval(row - 1, row - 1);
160 _moveUpButton.setEnabled(false);
161 updownPanel.add(_moveUpButton);
162 _moveDownButton = new JButton(I18nManager.getText("button.movedown"));
163 _moveDownButton.addActionListener(new ActionListener() {
164 public void actionPerformed(ActionEvent e)
166 int row = _table.getSelectedRow();
167 if (row > -1 && row < (_model.getRowCount() - 1))
169 _model.swapItems(row, row + 1);
170 _table.setRowSelectionInterval(row + 1, row + 1);
174 _moveDownButton.setEnabled(false);
175 updownPanel.add(_moveDownButton);
176 fieldsPanel.add(updownPanel, BorderLayout.EAST);
177 // enable/disable buttons based on table row selection
178 _toggler = new UpDownToggler(_moveUpButton, _moveDownButton);
179 _table.getSelectionModel().addListSelectionListener(_toggler);
181 // Add fields panel and the delimiter panel to first card in pack
182 JLabel saveOptionsLabel = new JLabel(I18nManager.getText("dialog.save.fieldstosave"));
183 saveOptionsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
184 firstCard.add(saveOptionsLabel);
185 fieldsPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
186 firstCard.add(fieldsPanel);
187 firstCard.add(Box.createRigidArea(new Dimension(0,10)));
190 JLabel delimLabel = new JLabel(I18nManager.getText("dialog.delimiter.label"));
191 delimLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
192 firstCard.add(delimLabel);
193 JPanel delimsPanel = new JPanel();
194 delimsPanel.setLayout(new GridLayout(0, 2));
195 delimsPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
197 _delimiterRadios = new JRadioButton[5];
198 _delimiterRadios[0] = new JRadioButton(I18nManager.getText("dialog.delimiter.comma"));
199 delimsPanel.add(_delimiterRadios[0]);
200 _delimiterRadios[1] = new JRadioButton(I18nManager.getText("dialog.delimiter.tab"));
201 delimsPanel.add(_delimiterRadios[1]);
202 _delimiterRadios[2] = new JRadioButton(I18nManager.getText("dialog.delimiter.semicolon"));
203 delimsPanel.add(_delimiterRadios[2]);
204 _delimiterRadios[3] = new JRadioButton(I18nManager.getText("dialog.delimiter.space"));
205 delimsPanel.add(_delimiterRadios[3]);
206 JPanel otherPanel = new JPanel();
207 otherPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
208 _delimiterRadios[4] = new JRadioButton(I18nManager.getText("dialog.delimiter.other"));
209 otherPanel.add(_delimiterRadios[4]);
210 _otherDelimiterText = new JTextField(new OneCharDocument(), null, 2);
211 otherPanel.add(_otherDelimiterText);
212 // Group radio buttons
213 ButtonGroup delimGroup = new ButtonGroup();
214 for (int i=0; i<_delimiterRadios.length; i++)
216 delimGroup.add(_delimiterRadios[i]);
218 delimsPanel.add(otherPanel);
219 firstCard.add(delimsPanel);
222 firstCard.add(Box.createRigidArea(new Dimension(0,10)));
223 _headerRowCheckbox = new JCheckBox(I18nManager.getText("dialog.save.headerrow"));
224 firstCard.add(_headerRowCheckbox);
226 _cards.add(firstCard, "card1");
228 JPanel secondCard = new JPanel();
229 secondCard.setLayout(new BorderLayout());
230 JPanel secondCardHolder = new JPanel();
231 secondCardHolder.setLayout(new BoxLayout(secondCardHolder, BoxLayout.Y_AXIS));
232 JLabel coordLabel = new JLabel(I18nManager.getText("dialog.save.coordinateunits"));
233 coordLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
234 secondCardHolder.add(coordLabel);
235 JPanel coordsUnitsPanel = new JPanel();
236 coordsUnitsPanel.setBorder(BorderFactory.createEtchedBorder());
237 coordsUnitsPanel.setLayout(new GridLayout(0, 2));
238 _coordUnitsRadios = new JRadioButton[4];
239 _coordUnitsRadios[0] = new JRadioButton(I18nManager.getText("units.original"));
240 _coordUnitsRadios[1] = new JRadioButton(I18nManager.getText("units.degminsec"));
241 _coordUnitsRadios[2] = new JRadioButton(I18nManager.getText("units.degmin"));
242 _coordUnitsRadios[3] = new JRadioButton(I18nManager.getText("units.deg"));
243 ButtonGroup coordGroup = new ButtonGroup();
244 for (int i=0; i<4; i++)
246 coordGroup.add(_coordUnitsRadios[i]);
247 coordsUnitsPanel.add(_coordUnitsRadios[i]);
248 _coordUnitsRadios[i].setSelected(i==0);
250 coordsUnitsPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
251 secondCardHolder.add(coordsUnitsPanel);
252 secondCardHolder.add(Box.createRigidArea(new Dimension(0,10)));
254 JLabel altUnitsLabel = new JLabel(I18nManager.getText("dialog.save.altitudeunits"));
255 altUnitsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
256 secondCardHolder.add(altUnitsLabel);
257 JPanel altUnitsPanel = new JPanel();
258 altUnitsPanel.setBorder(BorderFactory.createEtchedBorder());
259 altUnitsPanel.setLayout(new GridLayout(0, 2));
260 _altitudeUnitsRadios = new JRadioButton[3];
261 _altitudeUnitsRadios[0] = new JRadioButton(I18nManager.getText("units.original"));
262 _altitudeUnitsRadios[1] = new JRadioButton(I18nManager.getText("units.metres"));
263 _altitudeUnitsRadios[2] = new JRadioButton(I18nManager.getText("units.feet"));
264 ButtonGroup altGroup = new ButtonGroup();
265 for (int i=0; i<3; i++)
267 altGroup.add(_altitudeUnitsRadios[i]);
268 altUnitsPanel.add(_altitudeUnitsRadios[i]);
269 _altitudeUnitsRadios[i].setSelected(i==0);
271 altUnitsPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
272 secondCardHolder.add(altUnitsPanel);
273 secondCardHolder.add(Box.createRigidArea(new Dimension(0,10)));
274 // Selection of format of timestamps
275 JLabel timestampLabel = new JLabel(I18nManager.getText("dialog.save.timestampformat"));
276 timestampLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
277 secondCardHolder.add(timestampLabel);
278 JPanel timestampPanel = new JPanel();
279 timestampPanel.setBorder(BorderFactory.createEtchedBorder());
280 timestampPanel.setLayout(new GridLayout(0, 2));
281 _timestampUnitsRadios = new JRadioButton[3];
282 _timestampUnitsRadios[0] = new JRadioButton(I18nManager.getText("units.original"));
283 _timestampUnitsRadios[1] = new JRadioButton(I18nManager.getText("units.default"));
284 _timestampUnitsRadios[2] = new JRadioButton(I18nManager.getText("units.iso8601"));
285 ButtonGroup timeGroup = new ButtonGroup();
286 for (int i=0; i<3; i++)
288 timeGroup.add(_timestampUnitsRadios[i]);
289 timestampPanel.add(_timestampUnitsRadios[i]);
290 _timestampUnitsRadios[i].setSelected(i==0);
292 timestampPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
293 secondCardHolder.add(timestampPanel);
294 secondCard.add(secondCardHolder, BorderLayout.NORTH);
295 _cards.add(secondCard, "card2");
297 // Put together with ok/cancel buttons on the bottom
298 JPanel buttonPanel = new JPanel();
299 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
300 _backButton = new JButton(I18nManager.getText("button.back"));
301 _backButton.addActionListener(new ActionListener() {
302 public void actionPerformed(ActionEvent e)
304 CardLayout cl = (CardLayout) _cards.getLayout();
306 _backButton.setEnabled(false);
307 _nextButton.setEnabled(true);
310 _backButton.setEnabled(false);
311 buttonPanel.add(_backButton);
312 _nextButton = new JButton(I18nManager.getText("button.next"));
313 _nextButton.setEnabled(true);
314 _nextButton.addActionListener(new ActionListener() {
315 public void actionPerformed(ActionEvent e)
317 CardLayout cl = (CardLayout) _cards.getLayout();
319 _backButton.setEnabled(true);
320 _nextButton.setEnabled(false);
323 buttonPanel.add(_nextButton);
324 JButton okButton = new JButton(I18nManager.getText("button.finish"));
325 okButton.addActionListener(new ActionListener() {
326 public void actionPerformed(ActionEvent e)
334 buttonPanel.add(okButton);
335 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
336 cancelButton.addActionListener(new ActionListener() {
337 public void actionPerformed(ActionEvent e)
342 buttonPanel.add(cancelButton);
343 panel.add(buttonPanel, BorderLayout.SOUTH);
348 * Initialize the dialog with the given details
349 * @param inModel table model
350 * @param inDefaultDelimiter default delimiter character
352 private void initDialog(TableModel inModel, char inDefaultDelimiter)
355 _table.setModel(inModel);
357 _toggler.setListSize(inModel.getRowCount());
358 // choose last-used delimiter as default
359 switch (inDefaultDelimiter)
361 case ',' : _delimiterRadios[0].setSelected(true); break;
362 case '\t' : _delimiterRadios[1].setSelected(true); break;
363 case ';' : _delimiterRadios[2].setSelected(true); break;
364 case ' ' : _delimiterRadios[3].setSelected(true); break;
365 default : _delimiterRadios[4].setSelected(true);
366 _otherDelimiterText.setText("" + inDefaultDelimiter);
368 // set card and enable buttons
369 CardLayout cl = (CardLayout) _cards.getLayout();
371 _nextButton.setEnabled(true);
372 _backButton.setEnabled(false);
377 * Save the track to file with the chosen options
378 * @return true if successful or cancelled, false if failed
380 private boolean saveToFile()
382 boolean saveOK = true;
383 FileWriter writer = null;
384 if (_fileChooser == null)
385 _fileChooser = new JFileChooser();
386 _fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
387 if (_fileChooser.showSaveDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
389 File saveFile = _fileChooser.getSelectedFile();
390 String lineSeparator = System.getProperty("line.separator");
391 // Get coordinate format and altitude format
392 int coordFormat = Coordinate.FORMAT_NONE;
393 for (int i=0; i<_coordUnitsRadios.length; i++)
394 if (_coordUnitsRadios[i].isSelected())
395 coordFormat = FORMAT_COORDS[i];
396 int altitudeFormat = Altitude.FORMAT_NONE;
397 for (int i=0; i<_altitudeUnitsRadios.length; i++)
399 if (_altitudeUnitsRadios[i].isSelected())
401 altitudeFormat = FORMAT_ALTS[i];
404 // Get timestamp formats
405 int timestampFormat = Timestamp.FORMAT_ORIGINAL;
406 for (int i=0; i<_timestampUnitsRadios.length; i++)
408 if (_timestampUnitsRadios[i].isSelected())
410 timestampFormat = FORMAT_TIMES[i];
414 // Check if file exists, and confirm overwrite if necessary
415 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
416 if (!saveFile.exists() || JOptionPane.showOptionDialog(_parentFrame,
417 I18nManager.getText("dialog.save.overwrite.text"),
418 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
419 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
420 == JOptionPane.YES_OPTION)
424 // Create output file
425 writer = new FileWriter(saveFile);
426 // Determine delimiter character to use
427 char delimiter = getDelimiter();
428 FieldInfo info = null;
431 StringBuffer buffer = null;
432 int numFields = _model.getRowCount();
433 boolean firstField = true;
434 // Write header row if required
435 if (_headerRowCheckbox.isSelected())
437 buffer = new StringBuffer();
438 for (int f=0; f<numFields; f++)
440 info = _model.getFieldInfo(f);
441 if (info.isSelected())
445 // output field separator
446 buffer.append(delimiter);
448 field = info.getField();
449 buffer.append(field.getName());
453 writer.write(buffer.toString());
454 writer.write(lineSeparator);
457 // Loop over points outputting each in turn to buffer
458 int numPoints = _track.getNumPoints();
459 for (int p=0; p<numPoints; p++)
461 DataPoint point = _track.getPoint(p);
463 buffer = new StringBuffer();
464 for (int f=0; f<numFields; f++)
466 info = _model.getFieldInfo(f);
467 if (info.isSelected())
471 // output field separator
472 buffer.append(delimiter);
474 field = info.getField();
475 // Output field according to type
476 if (field == Field.LATITUDE)
478 buffer.append(point.getLatitude().output(coordFormat));
480 else if (field == Field.LONGITUDE)
482 buffer.append(point.getLongitude().output(coordFormat));
484 else if (field == Field.ALTITUDE)
488 buffer.append(point.getAltitude().getValue(altitudeFormat));
490 catch (NullPointerException npe) {}
492 else if (field == Field.TIMESTAMP)
494 if (point.hasTimestamp())
496 if (timestampFormat == Timestamp.FORMAT_ORIGINAL) {
497 // output original string
498 buffer.append(point.getFieldValue(Field.TIMESTAMP));
501 // format value accordingly
502 buffer.append(point.getTimestamp().getText(timestampFormat));
508 String value = point.getFieldValue(field);
511 buffer.append(value);
518 writer.write(buffer.toString());
519 writer.write(lineSeparator);
522 UpdateMessageBroker.informSubscribers(I18nManager.getText("confirm.save.ok1")
523 + " " + numPoints + " " + I18nManager.getText("confirm.save.ok2")
524 + " " + saveFile.getAbsolutePath());
525 _app.informDataSaved();
527 catch (IOException ioe)
530 JOptionPane.showMessageDialog(_parentFrame,
531 I18nManager.getText("error.save.failed") + ioe.getMessage(),
532 I18nManager.getText("error.save.dialogtitle"),
533 JOptionPane.ERROR_MESSAGE);
537 // try to close file if it's open
545 catch (Exception e) {}
550 // Overwrite file confirm cancelled
559 * @return the selected delimiter character
561 private char getDelimiter()
563 // Check the preset 4 delimiters
564 final char[] delimiters = {',', '\t', ';', ' '};
565 for (int i=0; i<4; i++)
567 if (_delimiterRadios[i].isSelected())
569 return delimiters[i];
572 // Wasn't any of those so must be 'other'
573 return _otherDelimiterText.getText().charAt(0);