1 package tim.prune.load;
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 javax.swing.event.DocumentEvent;
13 import javax.swing.event.DocumentListener;
14 import javax.swing.event.ListSelectionEvent;
15 import javax.swing.event.ListSelectionListener;
16 import javax.swing.table.TableCellEditor;
21 import tim.prune.I18nManager;
22 import tim.prune.data.Altitude;
23 import tim.prune.data.Field;
27 * Class to handle loading of text files including GUI options,
28 * and passing loaded data back to App object
30 public class TextFileLoader
32 private File _file = null;
33 private App _app = null;
34 private JFrame _parentFrame = null;
35 private JDialog _dialog = null;
36 private JPanel _cardPanel = null;
37 private CardLayout _layout = null;
38 private JButton _backButton = null, _nextButton = null;
39 private JButton _finishButton = null;
40 private JButton _moveUpButton = null, _moveDownButton = null;
41 private JRadioButton[] _delimiterRadios = null;
42 private JTextField _otherDelimiterText = null;
43 private JLabel _statusLabel = null;
44 private DelimiterInfo[] _delimiterInfos = null;
45 private FileCacher _fileCacher = null;
46 private JList _snippetBox = null;
47 private FileExtractTableModel _fileExtractTableModel = null;
48 private JTable _fieldTable;
49 private FieldSelectionTableModel _fieldTableModel = null;
50 private JComboBox _unitsDropDown = null;
51 private int _selectedField = -1;
52 private char _currentDelimiter = ',';
54 // previously selected values
55 private char _lastUsedDelimiter = ',';
56 private Field[] _lastSelectedFields = null;
57 private int _lastAltitudeFormat = Altitude.FORMAT_NONE;
60 private static final int SNIPPET_SIZE = 6;
61 private static final int MAX_SNIPPET_WIDTH = 80;
62 private static final char[] DELIMITERS = {',', '\t', ';', ' '};
66 * Inner class to listen for delimiter change operations
68 private class DelimListener implements ActionListener, DocumentListener
70 public void actionPerformed(ActionEvent e)
72 informDelimiterSelected();
74 public void changedUpdate(DocumentEvent e)
76 informDelimiterSelected();
78 public void insertUpdate(DocumentEvent e)
80 informDelimiterSelected();
82 public void removeUpdate(DocumentEvent e)
84 informDelimiterSelected();
91 * @param inApp Application object to inform of track load
92 * @param inParentFrame parent frame to reference for dialogs
94 public TextFileLoader(App inApp, JFrame inParentFrame)
97 _parentFrame = inParentFrame;
102 * Open the selected file and show the GUI dialog to select load options
103 * @param inFile file to open
105 public void openFile(File inFile)
108 if (preCheckFile(_file))
110 _dialog = new JDialog(_parentFrame, I18nManager.getText("dialog.openoptions.title"), true);
111 _dialog.setLocationRelativeTo(_parentFrame);
112 _dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
113 _dialog.getContentPane().add(makeDialogComponents());
115 // select best separator according to row counts (more is better)
116 int bestDelim = getBestOption(_delimiterInfos[0].getNumWinningRecords(),
117 _delimiterInfos[1].getNumWinningRecords(), _delimiterInfos[2].getNumWinningRecords(),
118 _delimiterInfos[3].getNumWinningRecords());
120 _delimiterRadios[bestDelim].setSelected(true);
122 _delimiterRadios[_delimiterRadios.length-1].setSelected(true);
123 informDelimiterSelected();
129 JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.load.noread"),
130 I18nManager.getText("error.load.dialogtitle"), JOptionPane.ERROR_MESSAGE);
136 * Check the given file for readability and funny characters,
137 * and count the fields for the various separators
138 * @param inFile file to check
140 private boolean preCheckFile(File inFile)
142 // Check file exists and is readable
143 if (inFile == null || !inFile.exists() || !inFile.canRead())
147 // Use a FileCacher to read the file into an array
148 _fileCacher = new FileCacher(inFile);
150 // Check each line of the file
151 String[] fileContents = _fileCacher.getContents();
152 boolean fileOK = true;
153 _delimiterInfos = new DelimiterInfo[5];
154 for (int i=0; i<4; i++) _delimiterInfos[i] = new DelimiterInfo(DELIMITERS[i]);
156 String currLine = null;
157 String[] splitFields = null;
158 int commaFields = 0, semicolonFields = 0, tabFields = 0, spaceFields = 0;
159 for (int lineNum=0; lineNum<fileContents.length && fileOK; lineNum++)
161 currLine = fileContents[lineNum];
162 // check for invalid characters
163 if (currLine.indexOf('\0') >= 0) {fileOK = false;}
165 splitFields = currLine.split(",");
166 commaFields = splitFields.length;
167 if (commaFields > 1) _delimiterInfos[0].incrementNumRecords();
168 _delimiterInfos[0].updateMaxFields(commaFields);
170 splitFields = currLine.split("\t");
171 tabFields = splitFields.length;
172 if (tabFields > 1) _delimiterInfos[1].incrementNumRecords();
173 _delimiterInfos[1].updateMaxFields(tabFields);
174 // check for semicolons
175 splitFields = currLine.split(";");
176 semicolonFields = splitFields.length;
177 if (semicolonFields > 1) _delimiterInfos[2].incrementNumRecords();
178 _delimiterInfos[2].updateMaxFields(semicolonFields);
180 splitFields = currLine.split(" ");
181 spaceFields = splitFields.length;
182 if (spaceFields > 1) _delimiterInfos[3].incrementNumRecords();
183 _delimiterInfos[3].updateMaxFields(spaceFields);
184 // increment counters
185 int bestScorer = getBestOption(commaFields, tabFields, semicolonFields, spaceFields);
187 _delimiterInfos[bestScorer].incrementNumWinningRecords();
194 * Get the index of the best one in the list
195 * @return the index of the maximum of the four given values
197 private static int getBestOption(int inOpt0, int inOpt1, int inOpt2, int inOpt3)
201 if (inOpt0 > maxScore) {bestIndex = 0; maxScore = inOpt0;}
202 if (inOpt1 > maxScore) {bestIndex = 1; maxScore = inOpt1;}
203 if (inOpt2 > maxScore) {bestIndex = 2; maxScore = inOpt2;}
204 if (inOpt3 > maxScore) {bestIndex = 3; maxScore = inOpt3;}
210 * Make the components for the open options dialog
211 * @return Component for all options
213 private Component makeDialogComponents()
215 JPanel wholePanel = new JPanel();
216 wholePanel.setLayout(new BorderLayout());
218 // add buttons to south
219 JPanel buttonPanel = new JPanel();
220 buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
221 _backButton = new JButton(I18nManager.getText("button.back"));
222 _backButton.addActionListener(new ActionListener() {
223 public void actionPerformed(ActionEvent e)
225 _layout.previous(_cardPanel);
226 _backButton.setEnabled(false);
227 _nextButton.setEnabled(true);
228 _finishButton.setEnabled(false);
231 _backButton.setEnabled(false);
232 buttonPanel.add(_backButton);
233 _nextButton = new JButton(I18nManager.getText("button.next"));
234 _nextButton.addActionListener(new ActionListener() {
235 public void actionPerformed(ActionEvent e)
237 prepareSecondPanel();
238 _layout.next(_cardPanel);
239 _nextButton.setEnabled(false);
240 _backButton.setEnabled(true);
241 _finishButton.setEnabled(_fieldTableModel.getRowCount() > 1);
244 buttonPanel.add(_nextButton);
245 _finishButton = new JButton(I18nManager.getText("button.finish"));
246 _finishButton.addActionListener(new ActionListener() {
247 public void actionPerformed(ActionEvent e)
252 _finishButton.setEnabled(false);
253 buttonPanel.add(_finishButton);
254 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
255 cancelButton.addActionListener(new ActionListener() {
256 public void actionPerformed(ActionEvent e)
261 buttonPanel.add(cancelButton);
262 wholePanel.add(buttonPanel, BorderLayout.SOUTH);
264 // Make the two cards, for delimiter and fields
265 _cardPanel = new JPanel();
266 _layout = new CardLayout();
267 _cardPanel.setLayout(_layout);
268 JPanel firstCard = new JPanel();
269 firstCard.setLayout(new BorderLayout());
270 firstCard.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
272 JPanel delimsPanel = new JPanel();
273 delimsPanel.setLayout(new GridLayout(0, 2));
274 delimsPanel.add(new JLabel(I18nManager.getText("dialog.delimiter.label")));
275 delimsPanel.add(new JLabel("")); // blank label to go to next grid row
277 _delimiterRadios = new JRadioButton[5];
278 _delimiterRadios[0] = new JRadioButton(I18nManager.getText("dialog.delimiter.comma"));
279 delimsPanel.add(_delimiterRadios[0]);
280 _delimiterRadios[1] = new JRadioButton(I18nManager.getText("dialog.delimiter.tab"));
281 delimsPanel.add(_delimiterRadios[1]);
282 _delimiterRadios[2] = new JRadioButton(I18nManager.getText("dialog.delimiter.semicolon"));
283 delimsPanel.add(_delimiterRadios[2]);
284 _delimiterRadios[3] = new JRadioButton(I18nManager.getText("dialog.delimiter.space"));
285 delimsPanel.add(_delimiterRadios[3]);
286 JPanel otherPanel = new JPanel();
287 otherPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
288 _delimiterRadios[4] = new JRadioButton(I18nManager.getText("dialog.delimiter.other"));
289 otherPanel.add(_delimiterRadios[4]);
290 _otherDelimiterText = new JTextField(new OneCharDocument(), null, 2);
291 otherPanel.add(_otherDelimiterText);
292 // Group radio buttons
293 ButtonGroup delimGroup = new ButtonGroup();
294 DelimListener delimListener = new DelimListener();
295 for (int i=0; i<_delimiterRadios.length; i++)
297 delimGroup.add(_delimiterRadios[i]);
298 _delimiterRadios[i].addActionListener(delimListener);
300 _otherDelimiterText.getDocument().addDocumentListener(delimListener);
301 delimsPanel.add(new JLabel(""));
302 delimsPanel.add(otherPanel);
303 _statusLabel = new JLabel("");
304 delimsPanel.add(_statusLabel);
305 firstCard.add(delimsPanel, BorderLayout.SOUTH);
306 // load snippet to show first few lines
307 _snippetBox = new JList(_fileCacher.getSnippet(SNIPPET_SIZE, MAX_SNIPPET_WIDTH));
308 _snippetBox.setEnabled(false);
309 firstCard.add(makeLabelledPanel("dialog.openoptions.filesnippet", _snippetBox), BorderLayout.CENTER);
311 // Second screen, for field order selection
312 JPanel secondCard = new JPanel();
313 secondCard.setLayout(new BorderLayout());
314 secondCard.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
315 // table for file contents
316 _fileExtractTableModel = new FileExtractTableModel();
317 JTable extractTable = new JTable(_fileExtractTableModel);
318 JScrollPane tableScrollPane = new JScrollPane(extractTable);
319 extractTable.setPreferredScrollableViewportSize(new Dimension(350, 80));
320 extractTable.getTableHeader().setReorderingAllowed(false);
321 secondCard.add(makeLabelledPanel("dialog.openoptions.tabledesc", tableScrollPane), BorderLayout.NORTH);
322 JPanel innerPanel2 = new JPanel();
323 innerPanel2.setLayout(new BorderLayout());
324 innerPanel2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
326 _fieldTable = new JTable(new FieldSelectionTableModel());
327 _fieldTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
328 // add listener for selected table row
329 _fieldTable.getSelectionModel().addListSelectionListener(
330 new ListSelectionListener() {
331 public void valueChanged(ListSelectionEvent e) {
332 ListSelectionModel lsm = (ListSelectionModel) e.getSource();
333 if (lsm.isSelectionEmpty()) {
334 //no rows are selected
337 selectField(lsm.getMinSelectionIndex());
341 JPanel tablePanel = new JPanel();
342 tablePanel.setLayout(new BorderLayout());
343 tablePanel.add(_fieldTable.getTableHeader(), BorderLayout.NORTH);
344 tablePanel.add(_fieldTable, BorderLayout.CENTER);
345 innerPanel2.add(tablePanel, BorderLayout.CENTER);
347 JPanel innerPanel3 = new JPanel();
348 innerPanel3.setLayout(new BoxLayout(innerPanel3, BoxLayout.Y_AXIS));
349 _moveUpButton = new JButton(I18nManager.getText("button.moveup"));
350 _moveUpButton.addActionListener(new ActionListener() {
351 public void actionPerformed(ActionEvent e)
353 int currRow = _fieldTable.getSelectedRow();
354 closeTableComboBox(currRow);
355 _fieldTableModel.moveUp(currRow);
356 _fieldTable.setRowSelectionInterval(currRow-1, currRow-1);
359 innerPanel3.add(_moveUpButton);
360 _moveDownButton = new JButton(I18nManager.getText("button.movedown"));
361 _moveDownButton.addActionListener(new ActionListener() {
362 public void actionPerformed(ActionEvent e)
364 int currRow = _fieldTable.getSelectedRow();
365 closeTableComboBox(currRow);
366 _fieldTableModel.moveDown(currRow);
367 _fieldTable.setRowSelectionInterval(currRow+1, currRow+1);
370 innerPanel3.add(_moveDownButton);
371 innerPanel3.add(Box.createVerticalStrut(60));
372 JButton guessButton = new JButton(I18nManager.getText("button.guessfields"));
373 guessButton.addActionListener(new ActionListener() {
374 public void actionPerformed(ActionEvent e)
376 _lastSelectedFields = null;
377 prepareSecondPanel();
380 innerPanel3.add(guessButton);
382 innerPanel2.add(innerPanel3, BorderLayout.EAST);
383 secondCard.add(innerPanel2, BorderLayout.CENTER);
384 JPanel altUnitsPanel = new JPanel();
385 altUnitsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
386 altUnitsPanel.add(new JLabel(I18nManager.getText("dialog.openoptions.altitudeunits")));
387 String[] units = {I18nManager.getText("units.metres"), I18nManager.getText("units.feet")};
388 _unitsDropDown = new JComboBox(units);
389 altUnitsPanel.add(_unitsDropDown);
390 secondCard.add(altUnitsPanel, BorderLayout.SOUTH);
391 _cardPanel.add(firstCard, "card1");
392 _cardPanel.add(secondCard, "card2");
394 wholePanel.add(_cardPanel, BorderLayout.CENTER);
400 * Close the combo box on the selected row of the field table
401 * @param inRow currently selected row number
403 private void closeTableComboBox(int inRow)
405 TableCellEditor editor = _fieldTable.getCellEditor(inRow, 1);
408 editor.stopCellEditing();
414 * change the status based on selection of a delimiter
416 protected void informDelimiterSelected()
419 // Loop through radios to see which one is selected
420 for (int i=0; i<(_delimiterRadios.length-1); i++)
422 if (_delimiterRadios[i].isSelected())
424 // Set label text to describe records and fields
425 int numRecords = _delimiterInfos[i].getNumRecords();
428 _statusLabel.setText(I18nManager.getText("dialog.openoptions.deliminfo.norecords"));
432 fields = _delimiterInfos[i].getMaxFields();
433 _statusLabel.setText("" + numRecords + " " + I18nManager.getText("dialog.openoptions.deliminfo.records")
434 + " " + fields + " " + I18nManager.getText("dialog.openoptions.deliminfo.fields"));
438 // Don't show label if "other" delimiter is chosen (as records, fields are unknown)
439 if (_delimiterRadios[_delimiterRadios.length-1].isSelected())
441 _statusLabel.setText("");
443 // enable/disable next button
444 _nextButton.setEnabled((_delimiterRadios[4].isSelected() == false && fields > 1)
445 || _otherDelimiterText.getText().length() == 1);
450 * Get the delimiter info from the first step
451 * @return delimiter information object for the selected delimiter
453 public DelimiterInfo getSelectedDelimiterInfo()
455 for (int i=0; i<4; i++)
456 if (_delimiterRadios[i].isSelected()) return _delimiterInfos[i];
457 // must be "other" - build info if necessary
458 if (_delimiterInfos[4] == null)
459 _delimiterInfos[4] = new DelimiterInfo(_otherDelimiterText.getText().charAt(0));
460 return _delimiterInfos[4];
465 * Use the delimiter selected to determine the fields in the file
466 * and prepare the second panel accordingly
468 private void prepareSecondPanel()
470 DelimiterInfo info = getSelectedDelimiterInfo();
471 FileSplitter splitter = new FileSplitter(_fileCacher);
472 // Check info makes sense - num fields > 0, num records > 0
473 // set "Finished" button to disabled if not ok
474 // Add data to GUI elements
475 String[][] tableData = splitter.splitFieldData(info.getDelimiter());
476 // possible to ignore blank columns here
477 _currentDelimiter = info.getDelimiter();
478 _fileExtractTableModel.updateData(tableData);
479 _fieldTableModel = new FieldSelectionTableModel();
481 // Check number of fields and use last ones if count matches
482 Field[] startFieldArray = null;
483 if (_lastSelectedFields != null && splitter.getNumColumns() == _lastSelectedFields.length)
485 startFieldArray = _lastSelectedFields;
489 // Take first full row of file and use it to guess fields
490 startFieldArray = FieldGuesser.guessFields(splitter.getFirstFullRow());
493 _fieldTableModel.updateData(startFieldArray);
494 _fieldTable.setModel(_fieldTableModel);
495 // add dropdowns to second column
496 JComboBox fieldTypesBox = new JComboBox();
497 for (int i=0; i<Field.ALL_AVAILABLE_FIELDS.length; i++)
499 fieldTypesBox.addItem(Field.ALL_AVAILABLE_FIELDS[i].getName());
501 _fieldTable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(fieldTypesBox));
503 // Set altitude format to same as last time if available
504 if (_lastAltitudeFormat == Altitude.FORMAT_METRES)
505 _unitsDropDown.setSelectedIndex(0);
506 else if (_lastAltitudeFormat == Altitude.FORMAT_FEET)
507 _unitsDropDown.setSelectedIndex(1);
508 // no selection on field list
514 * All options have been selected, so load file
516 private void finished()
518 // Save delimiter, field array and altitude format for later use
519 _lastUsedDelimiter = _currentDelimiter;
520 _lastSelectedFields = _fieldTableModel.getFieldArray();
521 int altitudeFormat = Altitude.FORMAT_METRES;
522 if (_unitsDropDown.getSelectedIndex() == 1)
524 altitudeFormat = Altitude.FORMAT_FEET;
526 _lastAltitudeFormat = altitudeFormat;
528 _app.informDataLoaded(_fieldTableModel.getFieldArray(),
529 _fileExtractTableModel.getData(), altitudeFormat,
531 // clear up file cacher
539 * Make a panel with a label and a component
540 * @param inLabelKey label key to use
541 * @param inComponent component for main area of panel
542 * @return labelled Panel
544 private static JPanel makeLabelledPanel(String inLabelKey, JComponent inComponent)
546 JPanel panel = new JPanel();
547 panel.setLayout(new BorderLayout());
548 panel.add(new JLabel(I18nManager.getText(inLabelKey)), BorderLayout.NORTH);
549 panel.add(inComponent, BorderLayout.CENTER);
555 * An entry in the field list has been selected
556 * @param inFieldNum index of field, starting with 0
558 private void selectField(int inFieldNum)
560 if (inFieldNum == -1 || inFieldNum != _selectedField)
562 _selectedField = inFieldNum;
563 _moveUpButton.setEnabled(inFieldNum > 0);
564 _moveDownButton.setEnabled(inFieldNum >= 0
565 && inFieldNum < (_fieldTableModel.getRowCount()-1));
571 * @return the last delimiter character used for a load
573 public char getLastUsedDelimiter()
575 return _lastUsedDelimiter;