]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/load/TextFileLoader.java
Version 4, January 2008
[GpsPrune.git] / tim / prune / load / TextFileLoader.java
1 package tim.prune.load;
2
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;
11 import javax.swing.*;
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;
17
18 import java.io.File;
19
20 import tim.prune.App;
21 import tim.prune.I18nManager;
22 import tim.prune.data.Altitude;
23 import tim.prune.data.Field;
24
25
26 /**
27  * Class to handle loading of text files including GUI options,
28  * and passing loaded data back to App object
29  */
30 public class TextFileLoader
31 {
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 = ',';
53
54         // previously selected values
55         private char _lastUsedDelimiter = ',';
56         private Field[] _lastSelectedFields = null;
57         private int _lastAltitudeFormat = Altitude.FORMAT_NONE;
58
59         // constants
60         private static final int SNIPPET_SIZE = 6;
61         private static final int MAX_SNIPPET_WIDTH = 80;
62         private static final char[] DELIMITERS = {',', '\t', ';', ' '};
63
64
65         /**
66          * Inner class to listen for delimiter change operations
67          */
68         private class DelimListener implements ActionListener, DocumentListener
69         {
70                 public void actionPerformed(ActionEvent e)
71                 {
72                         informDelimiterSelected();
73                 }
74                 public void changedUpdate(DocumentEvent e)
75                 {
76                         informDelimiterSelected();
77                 }
78                 public void insertUpdate(DocumentEvent e)
79                 {
80                         informDelimiterSelected();
81                 }
82                 public void removeUpdate(DocumentEvent e)
83                 {
84                         informDelimiterSelected();
85                 }
86         }
87
88
89         /**
90          * Constructor
91          * @param inApp Application object to inform of track load
92          * @param inParentFrame parent frame to reference for dialogs
93          */
94         public TextFileLoader(App inApp, JFrame inParentFrame)
95         {
96                 _app = inApp;
97                 _parentFrame = inParentFrame;
98         }
99
100
101         /**
102          * Open the selected file and show the GUI dialog to select load options
103          * @param inFile file to open
104          */
105         public void openFile(File inFile)
106         {
107                 _file = inFile;
108                 if (preCheckFile(_file))
109                 {
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());
114
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());
119                         if (bestDelim >= 0)
120                                 _delimiterRadios[bestDelim].setSelected(true);
121                         else
122                                 _delimiterRadios[_delimiterRadios.length-1].setSelected(true);
123                         informDelimiterSelected();
124                         _dialog.pack();
125                         _dialog.show();
126                 }
127                 else
128                 {
129                         JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.load.noread"),
130                                 I18nManager.getText("error.load.dialogtitle"), JOptionPane.ERROR_MESSAGE);
131                 }
132         }
133
134
135         /**
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
139          */
140         private boolean preCheckFile(File inFile)
141         {
142                 // Check file exists and is readable
143                 if (inFile == null || !inFile.exists() || !inFile.canRead())
144                 {
145                         return false;
146                 }
147                 // Use a FileCacher to read the file into an array
148                 _fileCacher = new FileCacher(inFile);
149
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]);
155
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++)
160                 {
161                         currLine = fileContents[lineNum];
162                         // check for invalid characters
163                         if (currLine.indexOf('\0') >= 0) {fileOK = false;}
164                         // check for commas
165                         splitFields = currLine.split(",");
166                         commaFields = splitFields.length;
167                         if (commaFields > 1) _delimiterInfos[0].incrementNumRecords();
168                         _delimiterInfos[0].updateMaxFields(commaFields);
169                         // check for tabs
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);
179                         // check for spaces
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);
186                         if (bestScorer >= 0)
187                                 _delimiterInfos[bestScorer].incrementNumWinningRecords();
188                 }
189                 return fileOK;
190         }
191
192
193         /**
194          * Get the index of the best one in the list
195          * @return the index of the maximum of the four given values
196          */
197         private static int getBestOption(int inOpt0, int inOpt1, int inOpt2, int inOpt3)
198         {
199                 int bestIndex = -1;
200                 int maxScore = 1;
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;}
205                 return bestIndex;
206         }
207
208
209         /**
210          * Make the components for the open options dialog
211          * @return Component for all options
212          */
213         private Component makeDialogComponents()
214         {
215                 JPanel wholePanel = new JPanel();
216                 wholePanel.setLayout(new BorderLayout());
217
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)
224                         {
225                                 _layout.previous(_cardPanel);
226                                 _backButton.setEnabled(false);
227                                 _nextButton.setEnabled(true);
228                                 _finishButton.setEnabled(false);
229                         }
230                 });
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)
236                         {
237                                 prepareSecondPanel();
238                                 _layout.next(_cardPanel);
239                                 _nextButton.setEnabled(false);
240                                 _backButton.setEnabled(true);
241                                 _finishButton.setEnabled(_fieldTableModel.getRowCount() > 1);
242                         }
243                 });
244                 buttonPanel.add(_nextButton);
245                 _finishButton = new JButton(I18nManager.getText("button.finish"));
246                 _finishButton.addActionListener(new ActionListener() {
247                         public void actionPerformed(ActionEvent e)
248                         {
249                                 finished();
250                         }
251                 });
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)
257                         {
258                                 _dialog.dispose();
259                         }
260                 });
261                 buttonPanel.add(cancelButton);
262                 wholePanel.add(buttonPanel, BorderLayout.SOUTH);
263
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
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
275                 // radio buttons
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++)
295                 {
296                         delimGroup.add(_delimiterRadios[i]);
297                         _delimiterRadios[i].addActionListener(delimListener);
298                 }
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);
309
310                 // Second screen, for field order selection
311                 JPanel secondCard = new JPanel();
312                 secondCard.setLayout(new BorderLayout());
313                 // table for file contents
314                 _fileExtractTableModel = new FileExtractTableModel();
315                 JTable extractTable = new JTable(_fileExtractTableModel);
316                 JScrollPane tableScrollPane = new JScrollPane(extractTable);
317                 extractTable.setPreferredScrollableViewportSize(new Dimension(350, 80));
318                 extractTable.getTableHeader().setReorderingAllowed(false);
319                 secondCard.add(makeLabelledPanel("dialog.openoptions.tabledesc", tableScrollPane), BorderLayout.NORTH);
320                 JPanel innerPanel2 = new JPanel();
321                 innerPanel2.setLayout(new BorderLayout());
322                 _fieldTable = new JTable(new FieldSelectionTableModel());
323                 _fieldTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
324                 // add listener for selected table row
325                 _fieldTable.getSelectionModel().addListSelectionListener(
326                         new ListSelectionListener() {
327                                 public void valueChanged(ListSelectionEvent e) {
328                                         ListSelectionModel lsm = (ListSelectionModel) e.getSource();
329                                         if (lsm.isSelectionEmpty()) {
330                                                 //no rows are selected
331                                                 selectField(-1);
332                                         } else {
333                                                 selectField(lsm.getMinSelectionIndex());
334                                         }
335                                 }
336                         });
337                 JPanel tablePanel = new JPanel();
338                 tablePanel.setLayout(new BorderLayout());
339                 tablePanel.add(_fieldTable.getTableHeader(), BorderLayout.NORTH);
340                 tablePanel.add(_fieldTable, BorderLayout.CENTER);
341                 innerPanel2.add(tablePanel, BorderLayout.CENTER);
342
343                 JPanel innerPanel3 = new JPanel();
344                 innerPanel3.setLayout(new BoxLayout(innerPanel3, BoxLayout.Y_AXIS));
345                 _moveUpButton = new JButton(I18nManager.getText("button.moveup"));
346                 _moveUpButton.addActionListener(new ActionListener() {
347                         public void actionPerformed(ActionEvent e)
348                         {
349                                 int currRow = _fieldTable.getSelectedRow();
350                                 closeTableComboBox(currRow);
351                                 _fieldTableModel.moveUp(currRow);
352                                 _fieldTable.setRowSelectionInterval(currRow-1, currRow-1);
353                         }
354                 });
355                 innerPanel3.add(_moveUpButton);
356                 _moveDownButton = new JButton(I18nManager.getText("button.movedown"));
357                 _moveDownButton.addActionListener(new ActionListener() {
358                         public void actionPerformed(ActionEvent e)
359                         {
360                                 int currRow = _fieldTable.getSelectedRow();
361                                 closeTableComboBox(currRow);
362                                 _fieldTableModel.moveDown(currRow);
363                                 _fieldTable.setRowSelectionInterval(currRow+1, currRow+1);
364                         }
365                 });
366                 innerPanel3.add(_moveDownButton);
367                 innerPanel3.add(Box.createVerticalStrut(60));
368                 JButton guessButton = new JButton(I18nManager.getText("button.guessfields"));
369                 guessButton.addActionListener(new ActionListener() {
370                         public void actionPerformed(ActionEvent e)
371                         {
372                                 _lastSelectedFields = null;
373                                 prepareSecondPanel();
374                         }
375                 });
376                 innerPanel3.add(guessButton);
377
378                 innerPanel2.add(innerPanel3, BorderLayout.EAST);
379                 secondCard.add(innerPanel2, BorderLayout.CENTER);
380                 JPanel altUnitsPanel = new JPanel();
381                 altUnitsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
382                 altUnitsPanel.add(new JLabel(I18nManager.getText("dialog.openoptions.altitudeunits")));
383                 String[] units = {I18nManager.getText("units.metres"), I18nManager.getText("units.feet")};
384                 _unitsDropDown = new JComboBox(units);
385                 altUnitsPanel.add(_unitsDropDown);
386                 secondCard.add(altUnitsPanel, BorderLayout.SOUTH);
387                 _cardPanel.add(firstCard, "card1");
388                 _cardPanel.add(secondCard, "card2");
389
390                 wholePanel.add(_cardPanel, BorderLayout.CENTER);
391                 return wholePanel;
392         }
393
394
395         /**
396          * Close the combo box on the selected row of the field table
397          * @param inRow currently selected row number
398          */
399         private void closeTableComboBox(int inRow)
400         {
401                 TableCellEditor editor = _fieldTable.getCellEditor(inRow, 1);
402                 if (editor != null)
403                 {
404                         editor.stopCellEditing();
405                 }
406         }
407
408
409         /**
410          * change the status based on selection of a delimiter
411          */
412         protected void informDelimiterSelected()
413         {
414                 int fields = 0;
415                 // Loop through radios to see which one is selected
416                 for (int i=0; i<(_delimiterRadios.length-1); i++)
417                 {
418                         if (_delimiterRadios[i].isSelected())
419                         {
420                                 // Set label text to describe records and fields
421                                 int numRecords = _delimiterInfos[i].getNumRecords();
422                                 if (numRecords == 0)
423                                 {
424                                         _statusLabel.setText(I18nManager.getText("dialog.openoptions.deliminfo.norecords"));
425                                 }
426                                 else
427                                 {
428                                         fields = _delimiterInfos[i].getMaxFields();
429                                         _statusLabel.setText("" + numRecords + " " + I18nManager.getText("dialog.openoptions.deliminfo.records")
430                                                 + fields + " " + I18nManager.getText("dialog.openoptions.deliminfo.fields"));
431                                 }
432                         }
433                 }
434                 // Don't show label if "other" delimiter is chosen (as records, fields are unknown)
435                 if (_delimiterRadios[_delimiterRadios.length-1].isSelected())
436                 {
437                         _statusLabel.setText("");
438                 }
439                 // enable/disable next button
440                 _nextButton.setEnabled((_delimiterRadios[4].isSelected() == false && fields > 1)
441                         || _otherDelimiterText.getText().length() == 1);
442         }
443
444
445         /**
446          * Get the delimiter info from the first step
447          * @return delimiter information object for the selected delimiter
448          */
449         public DelimiterInfo getSelectedDelimiterInfo()
450         {
451                 for (int i=0; i<4; i++)
452                         if (_delimiterRadios[i].isSelected()) return _delimiterInfos[i];
453                 // must be "other" - build info if necessary
454                 if (_delimiterInfos[4] == null)
455                         _delimiterInfos[4] = new DelimiterInfo(_otherDelimiterText.getText().charAt(0));
456                 return _delimiterInfos[4];
457         }
458
459
460         /**
461          * Use the delimiter selected to determine the fields in the file
462          * and prepare the second panel accordingly
463          */
464         private void prepareSecondPanel()
465         {
466                 DelimiterInfo info = getSelectedDelimiterInfo();
467                 FileSplitter splitter = new FileSplitter(_fileCacher);
468                 // Check info makes sense - num fields > 0, num records > 0
469                 // set "Finished" button to disabled if not ok
470                 // Add data to GUI elements
471                 String[][] tableData = splitter.splitFieldData(info.getDelimiter());
472                 // possible to ignore blank columns here
473                 _currentDelimiter = info.getDelimiter();
474                 _fileExtractTableModel.updateData(tableData);
475                 _fieldTableModel = new FieldSelectionTableModel();
476
477                 // Check number of fields and use last ones if count matches
478                 Field[] startFieldArray = null;
479                 if (_lastSelectedFields != null && splitter.getNumColumns() == _lastSelectedFields.length)
480                 {
481                         startFieldArray = _lastSelectedFields;
482                 }
483                 else
484                 {
485                         // Take first full row of file and use it to guess fields
486                         startFieldArray = FieldGuesser.guessFields(splitter.getFirstFullRow());
487                 }
488
489                 _fieldTableModel.updateData(startFieldArray);
490                 _fieldTable.setModel(_fieldTableModel);
491                 // add dropdowns to second column
492                 JComboBox fieldTypesBox = new JComboBox();
493                 for (int i=0; i<Field.ALL_AVAILABLE_FIELDS.length; i++)
494                 {
495                         fieldTypesBox.addItem(Field.ALL_AVAILABLE_FIELDS[i].getName());
496                 }
497                 _fieldTable.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(fieldTypesBox));
498
499                 // Set altitude format to same as last time if available
500                 if (_lastAltitudeFormat == Altitude.FORMAT_METRES)
501                         _unitsDropDown.setSelectedIndex(0);
502                 else if (_lastAltitudeFormat == Altitude.FORMAT_FEET)
503                         _unitsDropDown.setSelectedIndex(1);
504                 // no selection on field list
505                 selectField(-1);
506         }
507
508
509         /**
510          * All options have been selected, so load file
511          */
512         private void finished()
513         {
514                 // Save delimiter, field array and altitude format for later use
515                 _lastUsedDelimiter = _currentDelimiter;
516                 _lastSelectedFields = _fieldTableModel.getFieldArray();
517                 int altitudeFormat = Altitude.FORMAT_METRES;
518                 if (_unitsDropDown.getSelectedIndex() == 1)
519                 {
520                         altitudeFormat = Altitude.FORMAT_FEET;
521                 }
522                 _lastAltitudeFormat = altitudeFormat;
523                 // give data to App
524                 _app.informDataLoaded(_fieldTableModel.getFieldArray(),
525                         _fileExtractTableModel.getData(), altitudeFormat,
526                         _file.getName());
527                 // clear up file cacher
528                 _fileCacher.clear();
529                 // dispose of dialog
530                 _dialog.dispose();
531         }
532
533
534         /**
535          * Make a panel with a label and a component
536          * @param inLabelKey label key to use
537          * @param inComponent component for main area of panel
538          * @return labelled Panel
539          */
540         private static JPanel makeLabelledPanel(String inLabelKey, JComponent inComponent)
541         {
542                 JPanel panel = new JPanel();
543                 panel.setLayout(new BorderLayout());
544                 panel.add(new JLabel(I18nManager.getText(inLabelKey)), BorderLayout.NORTH);
545                 panel.add(inComponent, BorderLayout.CENTER);
546                 return panel;
547         }
548
549
550         /**
551          * An entry in the field list has been selected
552          * @param inFieldNum index of field, starting with 0
553          */
554         private void selectField(int inFieldNum)
555         {
556                 if (inFieldNum == -1 || inFieldNum != _selectedField)
557                 {
558                         _selectedField = inFieldNum;
559                         _moveUpButton.setEnabled(inFieldNum > 0);
560                         _moveDownButton.setEnabled(inFieldNum >= 0
561                                 && inFieldNum < (_fieldTableModel.getRowCount()-1));
562                 }
563         }
564
565
566         /**
567          * @return the last delimiter character used for a load
568          */
569         public char getLastUsedDelimiter()
570         {
571                 return _lastUsedDelimiter;
572         }
573 }