Debian Codegraph @

src/footleg/cavesurvey/gui/swing/MainForm.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2015-2017 Paul Fretwell - aka 'Footleg' ([email protected])
3 *
4 * This file is part of Cave Converter.
5 *
6 * Cave Converter is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Cave Converter is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Cave Converter. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package footleg.cavesurvey.gui.swing;
20
21 import java.awt.BorderLayout;
22 import java.awt.Dimension;
23 import java.awt.EventQueue;
24 import java.awt.Font;
25 import java.awt.Point;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.awt.event.KeyEvent;
29 import java.awt.event.WindowAdapter;
30 import java.awt.event.WindowEvent;
31 import java.beans.PropertyChangeEvent;
32 import java.beans.PropertyChangeListener;
33 import java.io.File;
34 import java.io.FileWriter;
35 import java.io.IOException;
36 import java.net.URL;
37 import java.net.URLClassLoader;
38 import java.text.ParseException;
39 import java.util.ArrayList;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.ResourceBundle;
44
45 import javax.swing.AbstractAction;
46 import javax.swing.Action;
47 import javax.swing.Icon;
48 import javax.swing.ImageIcon;
49 import javax.swing.JButton;
50 import javax.swing.JFileChooser;
51 import javax.swing.JFrame;
52 import javax.swing.JMenu;
53 import javax.swing.JMenuBar;
54 import javax.swing.JMenuItem;
55 import javax.swing.JOptionPane;
56 import javax.swing.JScrollPane;
57 import javax.swing.JSplitPane;
58 import javax.swing.JTabbedPane;
59 import javax.swing.JToolBar;
60 import javax.swing.UIManager;
61 import javax.swing.UnsupportedLookAndFeelException;
62 import javax.swing.event.ChangeEvent;
63 import javax.swing.event.ChangeListener;
64 import javax.swing.filechooser.FileNameExtensionFilter;
65 import javax.swing.plaf.metal.DefaultMetalTheme;
66 import javax.swing.plaf.metal.MetalLookAndFeel;
67 import javax.swing.plaf.metal.OceanTheme;
68
69 import footleg.cavesurvey.converter.CaveConverter;
70 import footleg.cavesurvey.converter.CaveConverter.SurveyDataOutputFormats;
71 import footleg.cavesurvey.converter.DialogMsgLogger;
72 import footleg.cavesurvey.data.model.CaveSurvey;
73 import footleg.cavesurvey.data.reader.CompassParser;
74 import footleg.cavesurvey.data.reader.DxfParser;
75 import footleg.cavesurvey.data.reader.PocketTopoParser;
76 import footleg.cavesurvey.data.reader.SurvexParser;
77
78 /**
79 * GUI application built on top of CaveConverter library.
80 *
81 * @author Footleg
82 * @version 2017.01.10 (ISO 8601 YYYY.MM.DD)
83 * @since 1.7 (The Java version used)
84 *
85 * @to.do
86 * TODO Add option to output anonymous splay stations
87 * TODO Add selection of file character set encoding to preferences
88 * TODO In case of unknown file format on reading, ask user to select the survey format of the file
89 * TODO Prevent window position from preferences being beyond screen size when screen resolution is changed
90 * TODO Add selection of font in preferences
91 * TODO Add selection of look and feel in preferences
92 */
93 @SuppressWarnings("serial")
94 public class MainForm extends JFrame {
95
96 /**
97 * Private class to manage loading, saving and to hold user preferences
98 * @author Footleg
99 */
100 private class AppPrefs {
101 private static final String HEIGHT_PROPERTY = "window.height";
102 private static final String WIDTH_PROPERTY = "window.width";
103 private static final String SCREENPOSX_PROPERTY = "window.posx";
104 private static final String SCREENPOSY_PROPERTY = "window.posy";
105 private static final String FONT_PROPERTY = "font.typeface";
106 private static final String FONTSIZE_PROPERTY = "font.size";
107 private static final String CHARSET_PROPERTY = "character.set";
108 private static final String LOOKANDFEEL = "application.skin";
109 private Point position;
110 private Dimension size;
111 private String charset;
112 private String fontTypeface;
113 private int fontSize;
114 private String lookAndFeel;
115
116 /**
117 * Initialise preferences data to defaults and attempt to load user preferences from properties file
118 */
119 public AppPrefs() {
120 //Set defaults in case app preferences cannot be read from file
121 position = new Point(-1,-1);
122 size = new Dimension(600,400);
123 charset = "UTF8";
124 fontTypeface = "courier";
125 fontSize = 12;
126 lookAndFeel = "System";
127
128 //Read user preferences from file (if properties file exists)
129 try {
130 File file = new File(".");
131 URL[] urls = {file.toURI().toURL()};
132 ClassLoader loader = new URLClassLoader(urls);
133 ResourceBundle userPrefs = ResourceBundle.getBundle("app", Locale.getDefault(), loader);
134 //Set prefs from properties read from file
135 position.setLocation( Integer.parseInt( userPrefs.getString( SCREENPOSX_PROPERTY ) ),
136 Integer.parseInt( userPrefs.getString( SCREENPOSY_PROPERTY ) ));
137 size.setSize( Integer.parseInt( userPrefs.getString( WIDTH_PROPERTY ) ),
138 Integer.parseInt( userPrefs.getString( HEIGHT_PROPERTY ) ));
139 charset = userPrefs.getString( CHARSET_PROPERTY );
140 fontTypeface = userPrefs.getString( FONT_PROPERTY );
141 fontSize = Integer.valueOf( userPrefs.getString( FONTSIZE_PROPERTY ) );
142 lookAndFeel = userPrefs.getString( LOOKANDFEEL );
143 }
144 catch (Exception e) {
145 //Ignore errors in reading prefs
146 // JOptionPane.showMessageDialog(null, "Error reading prefs: " + e.getMessage(),
147 // "Error", JOptionPane.ERROR_MESSAGE);
148 }
149 }
150
151 public Point getPosition() {
152 return position;
153 }
154 public void setPosition(Point position) {
155 this.position = position;
156 }
157 public Dimension getSize() {
158 return size;
159 }
160 public void setSize(int width, int height) {
161 size.setSize(width, height);
162 }
163
164 public String getCharset() {
165 return charset;
166 }
167
168 public void setCharset(String charset) {
169 this.charset = charset;
170 }
171
172 public String getFontTypeface() {
173 return fontTypeface;
174 }
175
176 public void setFontTypeface(String fontTypeface) {
177 this.fontTypeface = fontTypeface;
178 }
179
180 public int getFontSize() {
181 return fontSize;
182 }
183
184 public void setFontSize(int fontSize) {
185 this.fontSize = fontSize;
186 }
187
188 public String getLookAndFeel() {
189 return lookAndFeel;
190 }
191
192 public void setLookAndFeel(String lookAndFeel) {
193 this.lookAndFeel = lookAndFeel;
194 }
195
196 /**
197 * Write application preference data to a properties file
198 */
199 public void writePrefsToFile() {
200 //Create prefs file text
201 String prefsData = "";
202 prefsData += SCREENPOSX_PROPERTY + "=" + (int)position.getX() + CaveConverter.newline;
203 prefsData += SCREENPOSY_PROPERTY + "=" + (int)position.getY() + CaveConverter.newline;
204 prefsData += HEIGHT_PROPERTY + "=" + (int)size.getHeight() + CaveConverter.newline;
205 prefsData += WIDTH_PROPERTY + "=" + (int)size.getWidth() + CaveConverter.newline;
206 prefsData += CHARSET_PROPERTY + "=" + getCharset() + CaveConverter.newline;
207 prefsData += FONT_PROPERTY + "=" + getFontTypeface() + CaveConverter.newline;
208 prefsData += FONTSIZE_PROPERTY + "=" + getFontSize() + CaveConverter.newline;
209 prefsData += LOOKANDFEEL + "=" + getLookAndFeel() + CaveConverter.newline;
210
211 //Save File
212 FileWriter textWriter = null;
213 try {
214 textWriter = new FileWriter("./app.properties");
215 textWriter.write( prefsData );
216 }
217 catch (Exception e) {
218 JOptionPane.showMessageDialog(null, "Error writing user preferences file: " + e.getMessage(),
219 "Error", JOptionPane.ERROR_MESSAGE);
220 }
221 finally {
222 if ( textWriter != null ) {
223 try {
224 textWriter.close();
225 }
226 catch (IOException ex) {
227 JOptionPane.showMessageDialog(null, "Error closing user preferences file: " + ex.getMessage(),
228 "Error", JOptionPane.ERROR_MESSAGE);
229 }
230 }
231 }
232 }
233 }
234
235 /**
236 * Private action class to handle file open operations
237 * @author Footleg
238 */
239 private class OpenFileAction extends AbstractAction {
240 private JFileChooser fileOpenDialog;
241
242 public OpenFileAction(String name, Icon icon) {
243 super(name, icon);
244
245 //Initialise file open dialog
246 fileOpenDialog = new JFileChooser(".");
247 fileOpenDialog.setFileSelectionMode( JFileChooser.FILES_ONLY );
248 fileOpenDialog.addChoosableFileFilter( new FileNameExtensionFilter("Compass Data Files","dat") );
249 fileOpenDialog.addChoosableFileFilter( new FileNameExtensionFilter("DXF Files","dxf") );
250 fileOpenDialog.addChoosableFileFilter( new FileNameExtensionFilter("PocketTopo Text Files","txt") );
251 fileOpenDialog.addChoosableFileFilter( new FileNameExtensionFilter("Survex Files","svx") );
252 }
253
254 @Override
255 public void actionPerformed(ActionEvent evnt) {
256 //Show file open dialog for user to pick input file
257 fileOpenDialog.showOpenDialog( getMainFrame() );
258 if (fileOpenDialog.getSelectedFile() != null) {
259 //Check if this is the first data file to be opened
260 if (inputData.getFormat() == null ) {
261 //Add tab to tab pane
262 inputData.title = "Survey Input Data";
263 tabPane.addTab ( inputData.title, inputData.getTabPaneComponent() );
264 }
265 //Open file in inputData tab
266 boolean res = inputData.openFile( fileOpenDialog.getSelectedFile(), appPrefs.getCharset() );
267 //If data was loaded successfully
268 if ( res ) {
269 //Enable actions which can act on input data
270 saveFileAction.setEnabled( true );
271 saveAsFileAction.setEnabled( true );
272 parseInputDataAction.setEnabled( true );
273 //Automatically process the data
274 buildCaveModelFromInputData();
275 }
276 }
277 }
278 }
279
280 /**
281 * Private action class to handle file save operations
282 * @author Footleg
283 */
284 private class SaveFileAction extends AbstractAction {
285
286 public SaveFileAction(String name, Icon icon) {
287 super(name, icon);
288 //Disabled by default (enables when data is loaded)
289 enabled = false;
290 }
291
292 @Override
293 public void actionPerformed(ActionEvent evnt) {
294 //Get selected tab
295 SurveyDatafileTabPane fileContentTab = getActiveSurveyDataTabPane();
296
297 if ( fileContentTab != null ) {
298 boolean saveAs = false;
299
300 //Determine action to perform
301 if ( evnt.getActionCommand().equals( saveAsActionCmd ) ) {
302 saveAs = true;
303 }
304 //Show file save dialog for user to specify file path
305 fileContentTab.saveData( saveAs, appPrefs.getCharset() );
306 }
307 else {
308 JOptionPane.showMessageDialog( getMainFrame(), "No data to save. Select a survey data file tab before selecting save.",
309 "Error", JOptionPane.ERROR_MESSAGE);
310 }
311 }
312 }
313
314 /**
315 * Private action class to read input survey data to generate a cave model in the visualiser
316 * @author Footleg
317 */
318 private class ParseInputDataAction extends AbstractAction {
319 public ParseInputDataAction(String name, Icon icon) {
320 super(name, icon);
321 //Disabled by default (enables when data is loaded)
322 enabled = false;
323 }
324
325 @Override
326 public void actionPerformed(ActionEvent evnt) {
327 //Process the data in the input data tab and generate a model
328 buildCaveModelFromInputData();
329 }
330 }
331
332 /**
333 * Private action class to generate LRUD data in cave model from splays
334 * @author Footleg
335 */
336 private class GenerateLRUDAction extends AbstractAction {
337 public GenerateLRUDAction(String name, Icon icon) {
338 super(name, icon);
339 //Disabled by default (enables when data is loaded)
340 enabled = false;
341 }
342
343 @Override
344 public void actionPerformed(ActionEvent evnt) {
345 //Process the data in the input data tab and generate a model
346 if ( visualiser != null ) {
347 visualiser.generateLRUDFromSplays();
348 }
349 }
350 }
351
352 /**
353 * Private action class to generate new nested series in cave model from stations named using full paths
354 * @author Footleg
355 */
356 private class GenerateSeriesFromStnNamesAction extends AbstractAction {
357 public GenerateSeriesFromStnNamesAction(String name, Icon icon) {
358 super(name, icon);
359 //Disabled by default (enables when data is loaded)
360 enabled = false;
361 }
362
363 @Override
364 public void actionPerformed(ActionEvent evnt) {
365 //Process selected series
366 if ( visualiser != null ) {
367 visualiser.generateSeriesFromFullPathStationNames();
368 }
369 }
370 }
371
372 /**
373 * Private action class to handle Survex export operation
374 * @author Footleg
375 */
376 private class ExportSurvexDataAction extends AbstractAction {
377 public ExportSurvexDataAction(String name, Icon icon) {
378 super(name, icon);
379 //Disabled by default (enables when data is loaded)
380 enabled = false;
381 }
382
383 @Override
384 public void actionPerformed(ActionEvent evnt) {
385 //Process the data in the input data tab and generate a model
386 generateOutputData( SurveyDataOutputFormats.Survex );
387 }
388 }
389
390 /**
391 * Private action class to handle Toporobot export operation
392 * @author Footleg
393 */
394 private class ExportToporobotDataAction extends AbstractAction {
395 public ExportToporobotDataAction(String name, Icon icon) {
396 super(name, icon);
397 //Disabled by default (enables when data is loaded)
398 enabled = false;
399 }
400
401 @Override
402 public void actionPerformed(ActionEvent evnt) {
403 //Process the data in the input data tab and generate a model
404 generateOutputData( SurveyDataOutputFormats.Toporobot );
405 }
406 }
407
408 // /**
409 // * Private action class to handle operations
410 // * @author Footleg
411 // */
412 // private class NewAction extends AbstractAction {
413 // public NewAction(String name, Icon icon) {
414 // super(name, icon);
415 // //Disabled by default (enables when data is loaded)
416 // enabled = false;
417 // }
418 //
419 // @Override
420 // public void actionPerformed(ActionEvent evnt) {
421 //
422 // }
423 // }
424
425 /**
426 * Private listener for SurveyDatafileTabPane modified events to indicate modified state in tab title
427 */
428 private PropertyChangeListener dataModified = new PropertyChangeListener() {
429 @Override
430 public void propertyChange(PropertyChangeEvent evt) {
431 SurveyDatafileTabPane source = (SurveyDatafileTabPane)evt.getSource();
432 //Indicate modified state in tab title
433 int idx = getTabIndexForObject(source);
434 if ( idx >= 0 ) {
435 if ( (Boolean)evt.getNewValue() ) {
436 tabPane.setTitleAt( idx, source.title + "(*)" );
437 }
438 else {
439 tabPane.setTitleAt( idx, source.title );
440 }
441 }
442 }
443 };
444
445 //Themes
446 private static final String[][] THEMES = {
447 {"Metal","javax.swing.plaf.metal.MetalLookAndFeel"},
448 {"Ocean","javax.swing.plaf.metal.MetalLookAndFeel"},
449 {"Motif","com.sun.java.swing.plaf.motif.MotifLookAndFeel"},
450 {"System", UIManager.getSystemLookAndFeelClassName()},
451 {"CrossPlafrom", UIManager.getCrossPlatformLookAndFeelClassName() },
452 {"GTK","com.sun.java.swing.plaf.gtk.GTKLookAndFeel"} };
453
454 //Action name constants
455 private static final String saveActionCmd = "Save";
456 private static final String saveAsActionCmd = "SaveAs";
457
458 //UI Elements
459 private JTabbedPane tabPane;
460 private Font font;
461 private OpenFileAction openFileAction;
462 private SaveFileAction saveFileAction;
463 private SaveFileAction saveAsFileAction;
464 private ParseInputDataAction parseInputDataAction;
465 private GenerateLRUDAction generateLRUDAction;
466 private GenerateSeriesFromStnNamesAction genSeriesFromStnNamesAction;
467 private ExportSurvexDataAction exportSurvexDataAction;
468 private ExportToporobotDataAction exportToporobotDataAction;
469
470 //Data Objects
471 private AppPrefs appPrefs;
472 private SourceDataComponent inputData;
473 private CaveModelVisualiser visualiser;
474 private DialogMsgLogger dialogLogger;
475
476 /**
477 * Create main application window
478 */
479 public MainForm() {
480 //Create application preferences manager first, as initialisation of UI depends on preference values
481 appPrefs = new AppPrefs();
482
483 //Set look and feel
484 initLookAndFeel( appPrefs.getLookAndFeel() );
485
486 //Create dialog logger
487 dialogLogger = new DialogMsgLogger(this);
488
489 //Set up properties from prefs
490 font = new Font( appPrefs.getFontTypeface(), Font.PLAIN, appPrefs.getFontSize() );
491
492 //Create action class instances here after look and feel is configured, or UI elements (JFileChoosers)
493 //do not pick up look and feel
494 openFileAction = new OpenFileAction("Open", createImageIcon("images/fileopen.png") );
495 saveFileAction = new SaveFileAction("Save", createImageIcon("images/filesave.png") );
496 saveAsFileAction = new SaveFileAction("Save As", createImageIcon("images/filesave.png") );
497 parseInputDataAction = new ParseInputDataAction("Build Cave Model", createImageIcon("images/process_data.png") );
498 generateLRUDAction = new GenerateLRUDAction("Generate LRUD", createImageIcon("images/lrud.png") );
499 genSeriesFromStnNamesAction = new GenerateSeriesFromStnNamesAction("Generate Series From Station Names", createImageIcon("images/expand-series.png") );
500 exportSurvexDataAction = new ExportSurvexDataAction("Export to Survex", createImageIcon("images/export_survex_data.png") );
501 exportToporobotDataAction = new ExportToporobotDataAction("Export to Toporobot", createImageIcon("images/export_toporobot_data.png") );
502
503 //Create application UI
504 initializeUI();
505 }
506
507 /**
508 * Getter for the main frame reference, for use in sub classes where 'this' cannot be used
509 * @return Returns the main frame reference from any within any sub class context
510 */
511 public MainForm getMainFrame() {
512 return this;
513 }
514
515 public DialogMsgLogger getLogger() {
516 return dialogLogger;
517 }
518
519 /**
520 * Getter for selected survey data tab if one is active.
521 * @return The active tab pane if it is a Survey data file tab, otherwise returns null
522 */
523 public SurveyDatafileTabPane getActiveSurveyDataTabPane() {
524 //Get selected tab
525 SurveyDatafileTabPane fileContentTab = null;
526
527 if ( tabPane.getTabCount() > 0 ) {
528 try {
529 JScrollPane selectedTab = (JScrollPane) tabPane.getComponentAt( tabPane.getSelectedIndex() );
530 fileContentTab = (SurveyDatafileTabPane) selectedTab.getViewport().getView();
531 }
532 catch (ClassCastException e) {
533 fileContentTab = null;
534 }
535 }
536 return fileContentTab;
537 }
538
539 /**
540 * Determines the index in the tabPane of the tab holding the specified object
541 * @param matchObj Object to match in the tabs
542 * @return The index of the tab pane matching the object, or -1 if there is no matching tab
543 */
544 public int getTabIndexForObject( SurveyDatafileTabPane matchObj ) {
545 int idx = -1;
546
547 for (int i = 0; i < tabPane.getTabCount(); i++) {
548 if ( tabPane.getComponentAt(i) == matchObj.getTabPaneComponent() ) {
549 idx = i;
550 break;
551 }
552 }
553 return idx;
554 }
555
556 /**
557 * Create UI elements
558 */
559 private void initializeUI() {
560 //Pick up version number and display in title bar
561 ResourceBundle resourceString = ResourceBundle.getBundle("footleg.cavesurvey.gui.app");
562 String version = resourceString.getString("build.version");
563 setTitle( "Footleg's Cave Converter - " + version );
564
565 //Set window size and position from preferences
566 setSize( appPrefs.getSize() );
567 if (appPrefs.getPosition().getX() < 0) {
568 setLocationRelativeTo(null);
569 }
570 else {
571 setLocation( appPrefs.getPosition() );
572 }
573
574 setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
575 addWindowListener(
576 new WindowAdapter(){
577 @Override
578 public void windowClosing(WindowEvent windowEvent) {
579 boolean close = true;
580
581 //Prompt to save changes for any modified tab panes
582 for (int i = 0; i < tabPane.getTabCount(); i++) {
583 if ( tabPane.getComponentAt(i) instanceof JScrollPane ) {
584 JScrollPane pane = (JScrollPane) tabPane.getComponentAt(i);
585 if ( pane.getViewport().getView() instanceof SurveyDatafileTabPane ) {
586 //Make this pane the selected one
587 tabPane.setSelectedComponent( pane );
588 //Call method to prompt to save changes if modified
589 SurveyDatafileTabPane filePane = (SurveyDatafileTabPane) pane.getViewport().getView();
590 int res = filePane.promptToSaveChanges( appPrefs.getCharset() );
591 if ( res == JFileChooser.CANCEL_OPTION ) {
592 //User cancelled, so abort closing of application
593 close = false;
594 break;
595 }
596 }
597 }
598 }
599
600 if ( close ) {
601 //Update preferences with window size and position
602 Point pos = windowEvent.getWindow().getLocationOnScreen();
603 appPrefs.setSize( windowEvent.getWindow().getWidth(), windowEvent.getWindow().getHeight() );
604 appPrefs.setPosition( pos );
605 appPrefs.writePrefsToFile();
606
607 //Close window to exit application
608 dispose();
609 }
610 else {
611 //Ensure window is made visible
612 setVisible( true );
613 }
614 }
615 }
616 );
617
618 createMenuBar();
619
620 //Set up tab pane
621 tabPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
622 add(tabPane,BorderLayout.CENTER);
623 tabPane.addChangeListener(new ChangeListener() {
624 @Override
625 public void stateChanged(ChangeEvent e) {
626 //Enable actions appropriate to selected tab type
627 if (e.getSource() instanceof JTabbedPane) {
628 JTabbedPane tp = (JTabbedPane) e.getSource();
629 int selIdx = tp.getSelectedIndex();
630 if ( tp.getComponentAt( selIdx ) instanceof JScrollPane) {
631 JScrollPane pane = (JScrollPane) tp.getComponentAt( selIdx );
632 if ( pane.getViewport().getView() instanceof SurveyDatafileTabPane ) {
633 saveFileAction.setEnabled( true );
634 saveAsFileAction.setEnabled( true );
635 }
636 else {
637 saveFileAction.setEnabled( false );
638 saveAsFileAction.setEnabled( false );
639 }
640 }
641 else if ( tp.getComponentAt( selIdx ) instanceof JSplitPane ) {
642 JSplitPane pane = (JSplitPane) tp.getComponentAt( selIdx );
643 if ( pane instanceof CaveModelVisualiser ) {
644 //Nothing to save directly from cave model pane
645 saveFileAction.setEnabled( false );
646 saveAsFileAction.setEnabled( false );
647 }
648 else {
649 //No other pane types yet, so disable save for when there are
650 saveFileAction.setEnabled( false );
651 saveAsFileAction.setEnabled( false );
652 }
653 }
654 }
655 }
656 });
657
658 //Create input data tab pane (but do not add to tab pane here, that is done when a file is opened
659 inputData = new SourceDataComponent( font, this.getLogger() );
660 //Add modified listener to tab pane
661 inputData.addPropertyChangeListener("modified", dataModified);
662 }
663
664 // JOptionPane.showMessageDialog(getMainFrame(), "Modified property changed to: " + inputData.isModified(),
665 // "Debug", JOptionPane.OK_OPTION);
666
667 /**
668 * Create the main form menus and toolbar
669 */
670 private void createMenuBar() {
671 JMenuBar menubar = new JMenuBar();
672 JToolBar toolbar = new JToolBar();
673
674 //File Menu
675 JMenu fileMenu = new JMenu("File");
676 fileMenu.setMnemonic(KeyEvent.VK_F);
677 menubar.add( fileMenu );
678
679 //Define Open item
680 createMenuItemAndToolbarBtn( fileMenu, toolbar, openFileAction, KeyEvent.VK_O, "Open file", "" );
681
682 //Define Save item
683 createMenuItemAndToolbarBtn( fileMenu, toolbar, saveFileAction, KeyEvent.VK_S, "Save file", saveActionCmd );
684 saveFileAction.setEnabled( false );
685
686 //Define Save As item
687 createMenuItem( fileMenu, saveAsFileAction, KeyEvent.VK_A, "Save file with a new name", saveAsActionCmd );
688
689 //Define Exit item
690 JMenuItem eMenuItem = new JMenuItem("Exit", createImageIcon("images/exit.png") );
691 eMenuItem.setMnemonic(KeyEvent.VK_X);
692 eMenuItem.setToolTipText("Exit application");
693 eMenuItem.addActionListener(new ActionListener() {
694 @Override
695 public void actionPerformed(ActionEvent event) {
696 //Trigger closing of application
697 closeApp();
698 }
699 });
700 //Add to File menu
701 fileMenu.add(eMenuItem);
702
703
704 //Data Menu
705 JMenu dataMenu = new JMenu("Data");
706 dataMenu.setMnemonic(KeyEvent.VK_D);
707 menubar.add( dataMenu );
708
709 //Define Process Data item
710 createMenuItemAndToolbarBtn( dataMenu, toolbar, parseInputDataAction, KeyEvent.VK_P, "Process Survey Data", "" );
711
712 //Define LRUD item
713 createMenuItemAndToolbarBtn( dataMenu, toolbar, generateLRUDAction, KeyEvent.VK_L, "Generate LRUD data from splays", "" );
714
715 //Define Generate Series from Stn Names item
716 createMenuItemAndToolbarBtn( dataMenu, toolbar, genSeriesFromStnNamesAction, KeyEvent.VK_G, "Generate new series using station names", "" );
717
718 //Define ConvertToSurvex item
719 createMenuItemAndToolbarBtn( dataMenu, toolbar, exportSurvexDataAction, KeyEvent.VK_U, "Export data model to Survex format", "" );
720
721 //Define ConvertToToporobot item
722 createMenuItemAndToolbarBtn( dataMenu, toolbar, exportToporobotDataAction, KeyEvent.VK_T, "Export data model to Toporobot format", "" );
723
724 //Add menu bar and toolbar to frame
725 setJMenuBar( menubar );
726 add( toolbar, BorderLayout.NORTH );
727 }
728
729 /**
730 * Sets the look and feel from one of the supported styles
731 * @param lookAndFeel
732 * @param theme
733 */
734 private static void initLookAndFeel( String lookAndFeel ) {
735 String themeClass = "";
736
737 //Look up this LookAndFeel name in the themes array to get class name and theme
738 for (int i = 0; i < THEMES.length; i++) {
739 if ( lookAndFeel.compareTo( THEMES[i][0]) == 0) {
740 //Use this look and feel item
741 themeClass = THEMES[i][1];
742 break;
743 }
744 }
745
746 //If look and feel class name was not found then use system default
747 if ( themeClass.equals("") ) {
748 themeClass = UIManager.getSystemLookAndFeelClassName();
749 }
750
751 //Set look and feel ;
752 try {
753 //Set the theme for the themed Default Metal look and feels
754 if ( lookAndFeel.equals( "Metal" ) ) {
755 MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
756 }
757 else if ( lookAndFeel.equals( "Ocean" ) ) {
758 MetalLookAndFeel.setCurrentTheme(new OceanTheme());
759 }
760 UIManager.setLookAndFeel( themeClass );
761
762 //Make sure we have nice window decorations.
763 JFrame.setDefaultLookAndFeelDecorated(true);
764 }
765
766 catch (ClassNotFoundException e) {
767 System.err.println("Couldn't find class for specified look and feel:"
768 + lookAndFeel);
769 System.err.println("Did you include the L&F library in the class path?");
770 System.err.println("Using the default look and feel.");
771 }
772
773 catch (UnsupportedLookAndFeelException e) {
774 System.err.println("Can't use the specified look and feel ("
775 + lookAndFeel
776 + ") on this platform.");
777 System.err.println("Using the default look and feel.");
778 }
779
780 catch (Exception e) {
781 System.err.println("Couldn't get specified look and feel ("
782 + lookAndFeel
783 + "), for some reason.");
784 System.err.println("Using the default look and feel.");
785 e.printStackTrace();
786 }
787 }
788
789 /**
790 * Helper method to add menu item and toolbar button for an action to the UI
791 * @param parentMenu Menu to create the new menu item under
792 * @param toolbar Toolbar to create the new button on
793 * @param action Action to associate with new menu item and toolbar button
794 * @param shortcutKey Keyboard shortcut to associate with the menu
795 * @param toolTipText Tooltop text to associate with the new menu item and toolbar button
796 */
797 private void createMenuItemAndToolbarBtn( JMenu parentMenu, JToolBar toolbar, Action action, int shortcutKey,
798 String toolTipText, String actionCommand ) {
799 createMenuItem ( parentMenu, action, shortcutKey, toolTipText, actionCommand );
800 JButton btn = toolbar.add( action );
801 btn.setToolTipText( toolTipText );
802 btn.setActionCommand( actionCommand );
803 }
804
805 /**
806 * Helper method to add menu item for an action to the UI
807 * @param parentMenu Menu to create the new menu item under
808 * @param action Action to associate with new menu item
809 * @param shortcutKey Keyboard shortcut to associate with the menu
810 * @param toolTipText Tooltop text to associate with the new menu item
811 */
812 private void createMenuItem( JMenu parentMenu, Action action, int shortcutKey, String toolTipText, String actionCommand ) {
813 JMenuItem menuItem = parentMenu.add ( action );
814 menuItem.setMnemonic( shortcutKey);
815 menuItem.setToolTipText( toolTipText );
816 menuItem.setActionCommand( actionCommand );
817 }
818
819 /**
820 * Close application in a controlled manner, allowing preferences and data to be saved
821 */
822 private void closeApp() {
823 this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
824 }
825
826 /**
827 * Generate survey data from the cave data model in the specified output format
828 */
829 private void generateOutputData( CaveConverter.SurveyDataOutputFormats format) {
830 if ( visualiser != null ) {
831 List<String> outputData = visualiser.exportModel( format );
832
833 //Create tabPane for this output data
834 SurveyDatafileTabPane exportTab = new ExportDataComponent( font, this.getLogger(), format );
835 if ( format == SurveyDataOutputFormats.Survex ) {
836 exportTab.title = "Survex Export Data";
837 }
838 else if ( format == SurveyDataOutputFormats.Toporobot ) {
839 exportTab.title = "Toporobot Export Data";
840 }
841
842 tabPane.addTab ( exportTab.title, exportTab.getTabPaneComponent() );
843 exportTab.addPropertyChangeListener("modified", dataModified);
844
845 //Write strings from list to the file
846 exportTab.setText("");
847 Iterator<String> iterator = outputData.listIterator();
848 while ( iterator.hasNext() ) {
849 String line = iterator.next();
850 if ( iterator.hasNext() ) {
851 exportTab.append( line + System.getProperty("line.separator") );
852 }
853 else {
854 exportTab.append( line );
855 }
856 }
857 //Bring to front
858 tabPane.setSelectedComponent( exportTab.getTabPaneComponent() );
859 }
860 }
861
862 /**
863 * Process the data in the input data tab and generate a model
864 */
865 private void buildCaveModelFromInputData() {
866 CaveSurvey dataModel = processInputData();
867
868 //Create or update model tab if data was loaded
869 if ( ( dataModel != null ) && ( dataModel.isEmpty() == false ) ) {
870 //Reuse tab if already exists
871 if ( visualiser == null ) {
872 visualiser = new CaveModelVisualiser(this, dataModel, font );
873 tabPane.addTab ( "Survey Data Model", visualiser.getTabPaneComponent() );
874 }
875 else {
876 //Update cave model in visualiser
877 visualiser.setCaveModel( dataModel );
878 }
879 //Bring to front
880 tabPane.setSelectedComponent( visualiser.getTabPaneComponent() );
881 //Enable actions which can act on cave model
882 generateLRUDAction.setEnabled( true );
883 exportSurvexDataAction.setEnabled( true );
884 exportToporobotDataAction.setEnabled( true );
885 }
886 }
887
888 /**
889 * Sets the enabled state of all actions which require a survey series
890 * @param enabled State to set the enabled status to
891 */
892 public void setSurveySeriesActionsEnabled( boolean enabled ) {
893 genSeriesFromStnNamesAction.setEnabled( enabled );
894 }
895
896 /**
897 * Parse the cave survey data in an input data tab into a cave data model
898 * @return Cave data model generated from parsed data file
899 */
900 private CaveSurvey processInputData() {
901 CaveSurvey surveyData = null;
902
903 //Get text data from input tab
904 List<String> surveyDataLines = getSurveyDataFromText( inputData.getText() );
905
906 //Determine data type from input tab
907 if ( inputData.getFormat() == null ) {
908 //TODO In case of unknown format, ask user to select the format
909 JOptionPane.showMessageDialog(this, "Format of data unknown. Currently this is determined by the file extension. The option to let you specify the format is not written yet.",
910 "Unknown Survey Data Format", JOptionPane.OK_OPTION);
911 }
912 if ( inputData.getFormat() != null ) {
913 //Parse the data into the cave data model
914 switch ( inputData.getFormat() ) {
915 case Compass:
916 //Parse Compass data
917 CompassParser cParser = new CompassParser(dialogLogger);
918 try {
919 surveyData = cParser.parseFile( surveyDataLines );
920 } catch (ParseException e) {
921 //Display error message
922 JOptionPane.showMessageDialog(this, "Error processing Compass file data: " + e.getMessage(),
923 "Error", JOptionPane.ERROR_MESSAGE);
924 } catch (Exception e) {
925 JOptionPane.showMessageDialog(this, "Unexpected error processing Compass file data: " + e.getMessage(),
926 "Error", JOptionPane.ERROR_MESSAGE);
927 e.printStackTrace();
928 }
929 break;
930
931 case DXF:
932 //Parse DXF data
933 DxfParser dParser = new DxfParser(dialogLogger);
934 try {
935 surveyData = dParser.parseFile( surveyDataLines, 0 );
936 } catch (Exception e) {
937 JOptionPane.showMessageDialog(this, "Unexpected error processing DXF file data: " + e.getMessage(),
938 "Error", JOptionPane.ERROR_MESSAGE);
939 e.printStackTrace();
940 }
941 break;
942
943 case PocketTopo:
944 //Parse PocketTopo data
945 PocketTopoParser pParser = new PocketTopoParser(dialogLogger);
946 try {
947 surveyData = pParser.parseFile( surveyDataLines );
948 //Generate LRUD from splays by default for PocketTopo
949 // CaveConverter.logMessage("Generating LRUD data from splays...");
950 surveyData.generateLRUDfromSplays();
951 } catch (ParseException e) {
952 //Display error message
953 JOptionPane.showMessageDialog(this, "Error processing PocketTopo file data: " + e.getMessage(),
954 "Error", JOptionPane.ERROR_MESSAGE);
955 } catch (Exception e) {
956 JOptionPane.showMessageDialog(this, "Unexpected error processing PocketTopo file data: " + e.getMessage(),
957 "Error", JOptionPane.ERROR_MESSAGE);
958 e.printStackTrace();
959 }
960 break;
961
962 case Survex:
963 //Parse Survex data
964 SurvexParser sParser = new SurvexParser(dialogLogger);
965 try {
966 surveyData = sParser.parseFile( surveyDataLines, null );
967 } catch (ParseException e) {
968 //Display error message
969 JOptionPane.showMessageDialog(this, "Error processing Survex file data: " + e.getMessage(),
970 "Error", JOptionPane.ERROR_MESSAGE);
971 } catch (Exception e) {
972 JOptionPane.showMessageDialog(this, "Unexpected error processing Survex file data: " + e.getMessage(),
973 "Error", JOptionPane.ERROR_MESSAGE);
974 e.printStackTrace();
975 }
976 break;
977
978 }
979
980 }
981
982 return surveyData;
983 }
984
985 /**
986 * Returns an ImageIcon, or null if the path was invalid
987 * @param path Path to the icon image relative to this class
988 * @return ImageIcon using the image at the path specified
989 */
990 protected static ImageIcon createImageIcon(String path) {
991 java.net.URL imgURL = MainForm.class.getResource(path);
992 if (imgURL != null) {
993 return new ImageIcon(imgURL);
994 } else {
995 System.err.println("Failed to find icon file: " + path);
996 return null;
997 }
998 }
999
1000 /**
1001 * @param args Command line arguments (ignored)
1002 */
1003 public static void main(String[] args) {
1004
1005 EventQueue.invokeLater(new Runnable() {
1006
1007 @Override
1008 public void run() {
1009 MainForm mainWindow = new MainForm();
1010 mainWindow.setVisible(true);
1011 }
1012 });
1013 }
1014
1015 private List<String> getSurveyDataFromText(String text) {
1016 List<String> dataLines = new ArrayList<String>();
1017 String[] parts = text.split("\n");
1018
1019 for (int i = 0; i < parts.length; i++) {
1020 dataLines.add( parts[i] );
1021 }
1022
1023 return dataLines;
1024 }
1025
1026 }