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 Altitude.Format _lastAltitudeFormat = Altitude.Format.NO_FORMAT;
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();
125 _dialog.setVisible(true);
128 // Didn't pass pre-check
129 _app.showErrorMessage("error.load.dialogtitle", "error.load.noread");
135 * Check the given file for readability and funny characters,
136 * and count the fields for the various separators
137 * @param inFile file to check
139 private boolean preCheckFile(File inFile)
141 // Check file exists and is readable
142 if (inFile == null || !inFile.exists() || !inFile.canRead())
146 // Use a FileCacher to read the file into an array
147 _fileCacher = new FileCacher(inFile);
149 // Check each line of the file
150 String[] fileContents = _fileCacher.getContents();
151 boolean fileOK = true;
152 _delimiterInfos = new DelimiterInfo[5];
153 for (int i=0; i<4; i++) _delimiterInfos[i] = new DelimiterInfo(DELIMITERS[i]);
155 String currLine = null;
156 String[] splitFields = null;
157 int commaFields = 0, semicolonFields = 0, tabFields = 0, spaceFields = 0;
158 for (int lineNum=0; lineNum<fileContents.length && fileOK; lineNum++)
160 currLine = fileContents[lineNum];
161 // check for invalid characters
162 if (currLine.indexOf('\0') >= 0) {fileOK = false;}
164 splitFields = currLine.split(",");
165 commaFields = splitFields.length;
166 if (commaFields > 1) _delimiterInfos[0].incrementNumRecords();
167 _delimiterInfos[0].updateMaxFields(commaFields);
169 splitFields = currLine.split("\t");
170 tabFields = splitFields.length;
171 if (tabFields > 1) _delimiterInfos[1].incrementNumRecords();
172 _delimiterInfos[1].updateMaxFields(tabFields);
173 // check for semicolons
174 splitFields = currLine.split(";");
175 semicolonFields = splitFields.length;
176 if (semicolonFields > 1) _delimiterInfos[2].incrementNumRecords();
177 _delimiterInfos[2].updateMaxFields(semicolonFields);
179 splitFields = currLine.split(" ");
180 spaceFields = splitFields.length;
181 if (spaceFields > 1) _delimiterInfos[3].incrementNumRecords();
182 _delimiterInfos[3].updateMaxFields(spaceFields);
183 // increment counters
184 int bestScorer = getBestOption(commaFields, tabFields, semicolonFields, spaceFields);
186 _delimiterInfos[bestScorer].incrementNumWinningRecords();
193 * Get the index of the best one in the list
194 * @return the index of the maximum of the four given values
196 private static int getBestOption(int inOpt0, int inOpt1, int inOpt2, int inOpt3)
200 if (inOpt0 > maxScore) {bestIndex = 0; maxScore = inOpt0;}
201 if (inOpt1 > maxScore) {bestIndex = 1; maxScore = inOpt1;}
202 if (inOpt2 > maxScore) {bestIndex = 2; maxScore = inOpt2;}
203 if (inOpt3 > maxScore) {bestIndex = 3; maxScore = inOpt3;}
209 * Make the components for the open options dialog
210 * @return Component for all options
212 private Component makeDialogComponents()
214 JPanel wholePanel = new JPanel();
215 wholePanel.setLayout(new BorderLayout());
217 // add buttons to south
218 JPanel buttonPanel = new JPanel();
219 buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
220 _backButton = new JButton(I18nManager.getText("button.back"));
221 _backButton.addActionListener(new ActionListener() {
222 public void actionPerformed(ActionEvent e)
224 _layout.previous(_cardPanel);
225 _backButton.setEnabled(false);
226 _nextButton.setEnabled(true);
227 _finishButton.setEnabled(false);
230 _backButton.setEnabled(false);
231 buttonPanel.add(_backButton);
232 _nextButton = new JButton(I18nManager.getText("button.next"));
233 _nextButton.addActionListener(new ActionListener() {
234 public void actionPerformed(ActionEvent e)
236 prepareSecondPanel();
237 _layout.next(_cardPanel);
238 _nextButton.setEnabled(false);
239 _backButton.setEnabled(true);
240 _finishButton.setEnabled(_fieldTableModel.getRowCount() > 1);
243 buttonPanel.add(_nextButton);
244 _finishButton = new JButton(I18nManager.getText("button.finish"));
245 _finishButton.addActionListener(new ActionListener() {
246 public void actionPerformed(ActionEvent e)
251 _finishButton.setEnabled(false);
252 buttonPanel.add(_finishButton);
253 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
254 cancelButton.addActionListener(new ActionListener() {
255 public void actionPerformed(ActionEvent e)
260 buttonPanel.add(cancelButton);
261 wholePanel.add(buttonPanel, BorderLayout.SOUTH);
263 // Make the two cards, for delimiter and fields
264 _cardPanel = new JPanel();
265 _layout = new CardLayout();
266 _cardPanel.setLayout(_layout);
267 JPanel firstCard = new JPanel();
268 firstCard.setLayout(new BorderLayout());
269 firstCard.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
271 JPanel delimsPanel = new JPanel();
272 delimsPanel.setLayout(new GridLayout(0, 2));
273 delimsPanel.add(new JLabel(I18nManager.getText("dialog.delimiter.label")));
274 delimsPanel.add(new JLabel("")); // blank label to go to next grid row
276 _delimiterRadios = new JRadioButton[5];
277 _delimiterRadios[0] = new JRadioButton(I18nManager.getText("dialog.delimiter.comma"));
278 delimsPanel.add(_delimiterRadios[0]);
279 _delimiterRadios[1] = new JRadioButton(I18nManager.getText("dialog.delimiter.tab"));
280 delimsPanel.add(_delimiterRadios[1]);
281 _delimiterRadios[2] = new JRadioButton(I18nManager.getText("dialog.delimiter.semicolon"));
282 delimsPanel.add(_delimiterRadios[2]);
283 _delimiterRadios[3] = new JRadioButton(I18nManager.getText("dialog.delimiter.space"));
284 delimsPanel.add(_delimiterRadios[3]);
285 JPanel otherPanel = new JPanel();
286 otherPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
287 _delimiterRadios[4] = new JRadioButton(I18nManager.getText("dialog.delimiter.other"));
288 otherPanel.add(_delimiterRadios[4]);
289 _otherDelimiterText = new JTextField(new OneCharDocument(), null, 2);
290 otherPanel.add(_otherDelimiterText);
291 // Group radio buttons
292 ButtonGroup delimGroup = new ButtonGroup();
293 DelimListener delimListener = new DelimListener();
294 for (int i=0; i<_delimiterRadios.length; i++)
296 delimGroup.add(_delimiterRadios[i]);
297 _delimiterRadios[i].addActionListener(delimListener);
299 _otherDelimiterText.getDocument().addDocumentListener(delimListener);
300 delimsPanel.add(new JLabel(""));
301 delimsPanel.add(otherPanel);
302 _statusLabel = new JLabel("");
303 delimsPanel.add(_statusLabel);
304 firstCard.add(delimsPanel, BorderLayout.SOUTH);
305 // load snippet to show first few lines
306 _snippetBox = new JList(_fileCacher.getSnippet(SNIPPET_SIZE, MAX_SNIPPET_WIDTH));
307 _snippetBox.setEnabled(false);
308 firstCard.add(makeLabelledPanel("dialog.openoptions.filesnippet", _snippetBox), BorderLayout.CENTER);
310 // Second screen, for field order selection
311 JPanel secondCard = new JPanel();
312 secondCard.setLayout(new BorderLayout());
313 secondCard.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
314 // table for file contents
315 _fileExtractTableModel = new FileExtractTableModel();
316 JTable extractTable = new JTable(_fileExtractTableModel);
317 JScrollPane tableScrollPane = new JScrollPane(extractTable);
318 extractTable.setPreferredScrollableViewportSize(new Dimension(350, 80));
319 extractTable.getTableHeader().setReorderingAllowed(false);
320 secondCard.add(makeLabelledPanel("dialog.openoptions.filesnippet", tableScrollPane), BorderLayout.NORTH);
321 JPanel innerPanel2 = new JPanel();
322 innerPanel2.setLayout(new BorderLayout());
323 innerPanel2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
325 _fieldTable = new JTable(new FieldSelectionTableModel());
326 _fieldTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
327 // add listener for selected table row
328 _fieldTable.getSelectionModel().addListSelectionListener(
329 new ListSelectionListener() {
330 public void valueChanged(ListSelectionEvent e) {
331 ListSelectionModel lsm = (ListSelectionModel) e.getSource();
332 if (lsm.isSelectionEmpty()) {
333 //no rows are selected
336 selectField(lsm.getMinSelectionIndex());
340 JPanel tablePanel = new JPanel();
341 tablePanel.setLayout(new BorderLayout());
342 tablePanel.add(_fieldTable.getTableHeader(), BorderLayout.NORTH);
343 tablePanel.add(_fieldTable, BorderLayout.CENTER);
344 innerPanel2.add(tablePanel, BorderLayout.CENTER);
346 JPanel innerPanel3 = new JPanel();
347 innerPanel3.setLayout(new BoxLayout(innerPanel3, BoxLayout.Y_AXIS));
348 _moveUpButton = new JButton(I18nManager.getText("button.moveup"));
349 _moveUpButton.addActionListener(new ActionListener() {
350 public void actionPerformed(ActionEvent e)
352 int currRow = _fieldTable.getSelectedRow();
353 closeTableComboBox(currRow);
354 _fieldTableModel.moveUp(currRow);
355 _fieldTable.setRowSelectionInterval(currRow-1, currRow-1);
358 innerPanel3.add(_moveUpButton);
359 _moveDownButton = new JButton(I18nManager.getText("button.movedown"));
360 _moveDownButton.addActionListener(new ActionListener() {
361 public void actionPerformed(ActionEvent e)
363 int currRow = _fieldTable.getSelectedRow();
364 closeTableComboBox(currRow);
365 _fieldTableModel.moveDown(currRow);
366 _fieldTable.setRowSelectionInterval(currRow+1, currRow+1);
369 innerPanel3.add(_moveDownButton);
370 innerPanel3.add(Box.createVerticalStrut(60));
371 JButton guessButton = new JButton(I18nManager.getText("button.guessfields"));
372 guessButton.addActionListener(new ActionListener() {
373 public void actionPerformed(ActionEvent e)
375 _lastSelectedFields = null;
376 prepareSecondPanel();
379 innerPanel3.add(guessButton);
381 innerPanel2.add(innerPanel3, BorderLayout.EAST);
382 secondCard.add(innerPanel2, BorderLayout.CENTER);
383 JPanel altUnitsPanel = new JPanel();
384 altUnitsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
385 altUnitsPanel.add(new JLabel(I18nManager.getText("dialog.openoptions.altitudeunits")));
386 String[] units = {I18nManager.getText("units.metres"), I18nManager.getText("units.feet")};
387 _unitsDropDown = new JComboBox(units);
388 altUnitsPanel.add(_unitsDropDown);
389 secondCard.add(altUnitsPanel, BorderLayout.SOUTH);
390 _cardPanel.add(firstCard, "card1");
391 _cardPanel.add(secondCard, "card2");
393 wholePanel.add(_cardPanel, BorderLayout.CENTER);
399 * Close the combo box on the selected row of the field table
400 * @param inRow currently selected row number
402 private void closeTableComboBox(int inRow)
404 TableCellEditor editor = _fieldTable.getCellEditor(inRow, 1);
407 editor.stopCellEditing();
413 * change the status based on selection of a delimiter
415 protected void informDelimiterSelected()
418 // Loop through radios to see which one is selected
419 for (int i=0; i<(_delimiterRadios.length-1); i++)
421 if (_delimiterRadios[i].isSelected())
423 // Set label text to describe records and fields
424 int numRecords = _delimiterInfos[i].getNumRecords();
427 _statusLabel.setText(I18nManager.getText("dialog.openoptions.deliminfo.norecords"));
431 fields = _delimiterInfos[i].getMaxFields();
432 _statusLabel.setText("" + numRecords + " " + I18nManager.getText("dialog.openoptions.deliminfo.records")
433 + " " + fields + " " + I18nManager.getText("dialog.openoptions.deliminfo.fields"));
437 // Don't show label if "other" delimiter is chosen (as records, fields are unknown)
438 if (_delimiterRadios[_delimiterRadios.length-1].isSelected())
440 _statusLabel.setText("");
442 // enable/disable next button
443 _nextButton.setEnabled((_delimiterRadios[4].isSelected() == false && fields > 1)
444 || _otherDelimiterText.getText().length() == 1);
449 * Get the delimiter info from the first step
450 * @return delimiter information object for the selected delimiter
452 public DelimiterInfo getSelectedDelimiterInfo()
454 for (int i=0; i<4; i++)
455 if (_delimiterRadios[i].isSelected()) return _delimiterInfos[i];
456 // must be "other" - build info if necessary
457 if (_delimiterInfos[4] == null)
458 _delimiterInfos[4] = new DelimiterInfo(_otherDelimiterText.getText().charAt(0));
459 return _delimiterInfos[4];
464 * Use the delimiter selected to determine the fields in the file
465 * and prepare the second panel accordingly
467 private void prepareSecondPanel()
469 DelimiterInfo info = getSelectedDelimiterInfo();
470 FileSplitter splitter = new FileSplitter(_fileCacher);
471 // Check info makes sense - num fields > 0, num records > 0
472 // set "Finished" button to disabled if not ok
473 // Add data to GUI elements
474 String[][] tableData = splitter.splitFieldData(info.getDelimiter());
475 // possible to ignore blank columns here
476 _currentDelimiter = info.getDelimiter();
477 _fileExtractTableModel.updateData(tableData);
478 _fieldTableModel = new FieldSelectionTableModel();
480 // Check number of fields and use last ones if count matches
481 Field[] startFieldArray = null;
482 if (_lastSelectedFields != null && splitter.getNumColumns() == _lastSelectedFields.length)
484 startFieldArray = _lastSelectedFields;
488 // Take first full row of file and use it to guess fields
489 startFieldArray = FieldGuesser.guessFields(splitter.getFirstFullRow());
492 _fieldTableModel.updateData(startFieldArray);
493 _fieldTable.setModel(_fieldTableModel);
494 // add dropdowns to second column
495 JComboBox fieldTypesBox = new JComboBox();
496 String[] fieldNames = Field.getFieldNames();
497 for (int i=0; i<fieldNames.length; i++)
499 fieldTypesBox.addItem(fieldNames[i]);
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 Altitude.Format 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;