source: josm/trunk/src/org/openstreetmap/josm/Main.java@ 5839

Last change on this file since 5839 was 5831, checked in by Don-vip, 11 years ago

see #8571 - Include command-line arguments in status report

  • Property svn:eol-style set to native
File size: 44.8 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.BorderLayout;
7import java.awt.Component;
8import java.awt.GridBagConstraints;
9import java.awt.GridBagLayout;
10import java.awt.Window;
11import java.awt.event.ComponentEvent;
12import java.awt.event.ComponentListener;
13import java.awt.event.KeyEvent;
14import java.awt.event.WindowAdapter;
15import java.awt.event.WindowEvent;
16import java.io.File;
17import java.lang.ref.WeakReference;
18import java.net.URI;
19import java.net.URISyntaxException;
20import java.text.MessageFormat;
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Collection;
24import java.util.Iterator;
25import java.util.List;
26import java.util.Map;
27import java.util.StringTokenizer;
28import java.util.concurrent.Callable;
29import java.util.concurrent.ExecutorService;
30import java.util.concurrent.Executors;
31import java.util.concurrent.Future;
32
33import javax.swing.Action;
34import javax.swing.InputMap;
35import javax.swing.JComponent;
36import javax.swing.JFrame;
37import javax.swing.JLabel;
38import javax.swing.JOptionPane;
39import javax.swing.JPanel;
40import javax.swing.JTextArea;
41import javax.swing.KeyStroke;
42import javax.swing.UIManager;
43
44import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
45import org.openstreetmap.josm.actions.JosmAction;
46import org.openstreetmap.josm.actions.OpenFileAction;
47import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
48import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
49import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
50import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
51import org.openstreetmap.josm.actions.mapmode.MapMode;
52import org.openstreetmap.josm.actions.search.SearchAction;
53import org.openstreetmap.josm.data.Bounds;
54import org.openstreetmap.josm.data.Preferences;
55import org.openstreetmap.josm.data.UndoRedoHandler;
56import org.openstreetmap.josm.data.coor.CoordinateFormat;
57import org.openstreetmap.josm.data.coor.LatLon;
58import org.openstreetmap.josm.data.osm.DataSet;
59import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
60import org.openstreetmap.josm.data.projection.Projection;
61import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
62import org.openstreetmap.josm.data.validation.OsmValidator;
63import org.openstreetmap.josm.gui.GettingStarted;
64import org.openstreetmap.josm.gui.MainApplication.Option;
65import org.openstreetmap.josm.gui.MainMenu;
66import org.openstreetmap.josm.gui.MapFrame;
67import org.openstreetmap.josm.gui.MapView;
68import org.openstreetmap.josm.gui.NavigatableComponent.ViewportData;
69import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
70import org.openstreetmap.josm.gui.io.SaveLayersDialog;
71import org.openstreetmap.josm.gui.layer.Layer;
72import org.openstreetmap.josm.gui.layer.OsmDataLayer;
73import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
74import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
75import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
76import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
77import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
78import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
79import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
80import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
81import org.openstreetmap.josm.gui.util.RedirectInputMap;
82import org.openstreetmap.josm.io.OsmApi;
83import org.openstreetmap.josm.plugins.PluginHandler;
84import org.openstreetmap.josm.tools.CheckParameterUtil;
85import org.openstreetmap.josm.tools.I18n;
86import org.openstreetmap.josm.tools.ImageProvider;
87import org.openstreetmap.josm.tools.OpenBrowser;
88import org.openstreetmap.josm.tools.OsmUrlToBounds;
89import org.openstreetmap.josm.tools.PlatformHook;
90import org.openstreetmap.josm.tools.PlatformHookOsx;
91import org.openstreetmap.josm.tools.PlatformHookUnixoid;
92import org.openstreetmap.josm.tools.PlatformHookWindows;
93import org.openstreetmap.josm.tools.Shortcut;
94import org.openstreetmap.josm.tools.Utils;
95import org.openstreetmap.josm.tools.WindowGeometry;
96
97/**
98 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
99 * @since 98
100 */
101abstract public class Main {
102
103 /**
104 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
105 * it only shows the MOTD panel.
106 *
107 * @return <code>true</code> if JOSM currently displays a map view
108 */
109 static public boolean isDisplayingMapView() {
110 if (map == null) return false;
111 if (map.mapView == null) return false;
112 return true;
113 }
114
115 /**
116 * Global parent component for all dialogs and message boxes
117 */
118 public static Component parent;
119
120 /**
121 * Global application.
122 */
123 public static Main main;
124
125 /**
126 * Command-line arguments used to run the application.
127 */
128 public static String[] commandLineArgs;
129
130 /**
131 * The worker thread slave. This is for executing all long and intensive
132 * calculations. The executed runnables are guaranteed to be executed separately
133 * and sequential.
134 */
135 public final static ExecutorService worker = new ProgressMonitorExecutor();
136
137 /**
138 * Global application preferences
139 */
140 public static Preferences pref;
141
142 /**
143 * The global paste buffer.
144 */
145 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
146
147 /**
148 * The layer source from which {@link Main#pasteBuffer} data comes from.
149 */
150 public static Layer pasteSource;
151
152 /**
153 * The MapFrame. Use {@link Main#setMapFrame} to set or clear it.
154 */
155 public static MapFrame map;
156
157 /**
158 * Set to <code>true</code>, when in applet mode
159 */
160 public static boolean applet = false;
161
162 /**
163 * The toolbar preference control to register new actions.
164 */
165 public static ToolbarPreferences toolbar;
166
167 /**
168 * The commands undo/redo handler.
169 */
170 public UndoRedoHandler undoRedo = new UndoRedoHandler();
171
172 /**
173 * The progress monitor being currently displayed.
174 */
175 public static PleaseWaitProgressMonitor currentProgressMonitor;
176
177 /**
178 * The main menu bar at top of screen.
179 */
180 public MainMenu menu;
181
182 /**
183 * The data validation handler.
184 */
185 public OsmValidator validator;
186 /**
187 * The MOTD Layer.
188 */
189 private GettingStarted gettingStarted = new GettingStarted();
190
191 /**
192 * Logging level (3 = debug, 2 = info, 1 = warn, 0 = none).
193 */
194 static public int log_level = 2;
195 /**
196 * Print a warning message if logging is on.
197 * @param msg The message to print.
198 */
199 static public void warn(String msg) {
200 if (log_level < 1)
201 return;
202 System.out.println(msg);
203 }
204 /**
205 * Print an informational message if logging is on.
206 * @param msg The message to print.
207 */
208 static public void info(String msg) {
209 if (log_level < 2)
210 return;
211 System.out.println(msg);
212 }
213 /**
214 * Print an debug message if logging is on.
215 * @param msg The message to print.
216 */
217 static public void debug(String msg) {
218 if (log_level < 3)
219 return;
220 System.out.println(msg);
221 }
222 /**
223 * Print a formated warning message if logging is on. Calls {@link MessageFormat#format}
224 * function to format text.
225 * @param msg The formated message to print.
226 * @param objects The objects to insert into format string.
227 */
228 static public void warn(String msg, Object... objects) {
229 warn(MessageFormat.format(msg, objects));
230 }
231 /**
232 * Print a formated informational message if logging is on. Calls {@link MessageFormat#format}
233 * function to format text.
234 * @param msg The formated message to print.
235 * @param objects The objects to insert into format string.
236 */
237 static public void info(String msg, Object... objects) {
238 info(MessageFormat.format(msg, objects));
239 }
240 /**
241 * Print a formated debug message if logging is on. Calls {@link MessageFormat#format}
242 * function to format text.
243 * @param msg The formated message to print.
244 * @param objects The objects to insert into format string.
245 */
246 static public void debug(String msg, Object... objects) {
247 debug(MessageFormat.format(msg, objects));
248 }
249
250 /**
251 * Platform specific code goes in here.
252 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
253 * So if you need to hook into those early ones, split your class and send the one with the early hooks
254 * to the JOSM team for inclusion.
255 */
256 public static PlatformHook platform;
257
258 /**
259 * Whether or not the java vm is openjdk
260 * We use this to work around openjdk bugs
261 */
262 public static boolean isOpenjdk;
263
264 /**
265 * Set or clear (if passed <code>null</code>) the map.
266 * @param map The map to set {@link Main#map} to. Can be null.
267 */
268 public final void setMapFrame(final MapFrame map) {
269 MapFrame old = Main.map;
270 panel.setVisible(false);
271 panel.removeAll();
272 if (map != null) {
273 map.fillPanel(panel);
274 } else {
275 old.destroy();
276 panel.add(gettingStarted, BorderLayout.CENTER);
277 }
278 panel.setVisible(true);
279 redoUndoListener.commandChanged(0,0);
280
281 Main.map = map;
282
283 PluginHandler.notifyMapFrameChanged(old, map);
284 if (map == null && currentProgressMonitor != null) {
285 currentProgressMonitor.showForegroundDialog();
286 }
287 }
288
289 /**
290 * Remove the specified layer from the map. If it is the last layer,
291 * remove the map as well.
292 * @param layer The layer to remove
293 */
294 public final void removeLayer(final Layer layer) {
295 if (map != null) {
296 map.mapView.removeLayer(layer);
297 if (map != null && map.mapView.getAllLayers().isEmpty()) {
298 setMapFrame(null);
299 }
300 }
301 }
302
303 private static InitStatusListener initListener = null;
304
305 public static interface InitStatusListener {
306
307 void updateStatus(String event);
308 }
309
310 public static void setInitStatusListener(InitStatusListener listener) {
311 initListener = listener;
312 }
313
314 public Main() {
315 main = this;
316 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
317
318 if (initListener != null) {
319 initListener.updateStatus(tr("Executing platform startup hook"));
320 }
321 platform.startupHook();
322
323 if (initListener != null) {
324 initListener.updateStatus(tr("Building main menu"));
325 }
326 contentPanePrivate.add(panel, BorderLayout.CENTER);
327 panel.add(gettingStarted, BorderLayout.CENTER);
328 menu = new MainMenu();
329
330 undoRedo.addCommandQueueListener(redoUndoListener);
331
332 // creating toolbar
333 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
334
335 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
336 KeyEvent.VK_F1, Shortcut.DIRECT));
337
338 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
339 List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
340
341 tasks.add(new Callable<Void>() {
342
343 @Override
344 public Void call() throws Exception {
345 // We try to establish an API connection early, so that any API
346 // capabilities are already known to the editor instance. However
347 // if it goes wrong that's not critical at this stage.
348 if (initListener != null) {
349 initListener.updateStatus(tr("Initializing OSM API"));
350 }
351 try {
352 OsmApi.getOsmApi().initialize(null, true);
353 } catch (Exception x) {
354 // ignore any exception here.
355 }
356 return null;
357 }
358 });
359
360 tasks.add(new Callable<Void>() {
361
362 @Override
363 public Void call() throws Exception {
364 if (initListener != null) {
365 initListener.updateStatus(tr("Initializing presets"));
366 }
367 TaggingPresetPreference.initialize();
368 // some validator tests require the presets to be initialized
369 // TODO remove this dependency for parallel initialization
370 if (initListener != null) {
371 initListener.updateStatus(tr("Initializing validator"));
372 }
373 validator = new OsmValidator();
374 MapView.addLayerChangeListener(validator);
375 return null;
376 }
377 });
378
379 tasks.add(new Callable<Void>() {
380
381 @Override
382 public Void call() throws Exception {
383 if (initListener != null) {
384 initListener.updateStatus(tr("Initializing map styles"));
385 }
386 MapPaintPreference.initialize();
387 return null;
388 }
389 });
390
391 tasks.add(new Callable<Void>() {
392
393 @Override
394 public Void call() throws Exception {
395 if (initListener != null) {
396 initListener.updateStatus(tr("Loading imagery preferences"));
397 }
398 ImageryPreference.initialize();
399 return null;
400 }
401 });
402
403 try {
404 for (Future<Void> i : Executors.newFixedThreadPool(
405 Runtime.getRuntime().availableProcessors()).invokeAll(tasks)) {
406 i.get();
407 }
408 } catch (Exception ex) {
409 throw new RuntimeException(ex);
410 }
411
412 // hooks for the jmapviewer component
413 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
414 @Override
415 public void openLink(String url) {
416 OpenBrowser.displayUrl(url);
417 }
418 });
419 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
420
421 if (initListener != null) {
422 initListener.updateStatus(tr("Updating user interface"));
423 }
424
425 toolbar.refreshToolbarControl();
426
427 toolbar.control.updateUI();
428 contentPanePrivate.updateUI();
429
430 }
431
432 /**
433 * Add a new layer to the map. If no map exists, create one.
434 */
435 public final synchronized void addLayer(final Layer layer) {
436 boolean noMap = map == null;
437 if (noMap) {
438 createMapFrame(layer, null);
439 }
440 layer.hookUpMapView();
441 map.mapView.addLayer(layer);
442 if (noMap) {
443 Main.map.setVisible(true);
444 }
445 }
446
447 public synchronized void createMapFrame(Layer firstLayer, ViewportData viewportData) {
448 MapFrame mapFrame = new MapFrame(contentPanePrivate, viewportData);
449 setMapFrame(mapFrame);
450 if (firstLayer != null) {
451 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), firstLayer);
452 }
453 mapFrame.initializeDialogsPane();
454 // bootstrapping problem: make sure the layer list dialog is going to
455 // listen to change events of the very first layer
456 //
457 firstLayer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
458 }
459
460 /**
461 * Replies <code>true</code> if there is an edit layer
462 *
463 * @return <code>true</code> if there is an edit layer
464 */
465 public boolean hasEditLayer() {
466 if (getEditLayer() == null) return false;
467 return true;
468 }
469
470 /**
471 * Replies the current edit layer
472 *
473 * @return the current edit layer. <code>null</code>, if no current edit layer exists
474 */
475 public OsmDataLayer getEditLayer() {
476 if (map == null) return null;
477 if (map.mapView == null) return null;
478 return map.mapView.getEditLayer();
479 }
480
481 /**
482 * Replies the current data set.
483 *
484 * @return the current data set. <code>null</code>, if no current data set exists
485 */
486 public DataSet getCurrentDataSet() {
487 if (!hasEditLayer()) return null;
488 return getEditLayer().data;
489 }
490
491 /**
492 * Returns the currently active layer
493 *
494 * @return the currently active layer. <code>null</code>, if currently no active layer exists
495 */
496 public Layer getActiveLayer() {
497 if (map == null) return null;
498 if (map.mapView == null) return null;
499 return map.mapView.getActiveLayer();
500 }
501
502 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
503
504 public static void redirectToMainContentPane(JComponent source) {
505 RedirectInputMap.redirect(source, contentPanePrivate);
506 }
507
508 public static void registerActionShortcut(JosmAction action) {
509 registerActionShortcut(action, action.getShortcut());
510 }
511
512 public static void registerActionShortcut(Action action, Shortcut shortcut) {
513 KeyStroke keyStroke = shortcut.getKeyStroke();
514 if (keyStroke == null)
515 return;
516
517 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
518 Object existing = inputMap.get(keyStroke);
519 if (existing != null && !existing.equals(action)) {
520 System.out.println(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
521 }
522 inputMap.put(keyStroke, action);
523
524 contentPanePrivate.getActionMap().put(action, action);
525 }
526
527 public static void unregisterShortcut(Shortcut shortcut) {
528 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
529 }
530
531 public static void unregisterActionShortcut(JosmAction action) {
532 unregisterActionShortcut(action, action.getShortcut());
533 }
534
535 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
536 unregisterShortcut(shortcut);
537 contentPanePrivate.getActionMap().remove(action);
538 }
539
540 /**
541 * Replies the registered action for the given shortcut
542 * @param shortcut The shortcut to look for
543 * @return the registered action for the given shortcut
544 * @since 5696
545 */
546 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
547 KeyStroke keyStroke = shortcut.getKeyStroke();
548 if (keyStroke == null)
549 return null;
550 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
551 if (action instanceof Action)
552 return (Action) action;
553 return null;
554 }
555
556 ///////////////////////////////////////////////////////////////////////////
557 // Implementation part
558 ///////////////////////////////////////////////////////////////////////////
559
560 /**
561 * Global panel.
562 */
563 public static final JPanel panel = new JPanel(new BorderLayout());
564
565 protected static WindowGeometry geometry;
566 protected static int windowState = JFrame.NORMAL;
567
568 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
569 public void commandChanged(final int queueSize, final int redoSize) {
570 menu.undo.setEnabled(queueSize > 0);
571 menu.redo.setEnabled(redoSize > 0);
572 }
573 };
574
575 /**
576 * Should be called before the main constructor to setup some parameter stuff
577 * @param args The parsed argument list.
578 */
579 public static void preConstructorInit(Map<Option, Collection<String>> args) {
580 ProjectionPreference.setProjection();
581
582 try {
583 String defaultlaf = platform.getDefaultStyle();
584 String laf = Main.pref.get("laf", defaultlaf);
585 try {
586 UIManager.setLookAndFeel(laf);
587 }
588 catch (final java.lang.ClassNotFoundException e) {
589 System.out.println("Look and Feel not found: " + laf);
590 Main.pref.put("laf", defaultlaf);
591 }
592 catch (final javax.swing.UnsupportedLookAndFeelException e) {
593 System.out.println("Look and Feel not supported: " + laf);
594 Main.pref.put("laf", defaultlaf);
595 }
596 toolbar = new ToolbarPreferences();
597 contentPanePrivate.updateUI();
598 panel.updateUI();
599 } catch (final Exception e) {
600 e.printStackTrace();
601 }
602 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
603 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
604 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
605 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
606
607 I18n.translateJavaInternalMessages();
608
609 // init default coordinate format
610 //
611 try {
612 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
613 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
614 } catch (IllegalArgumentException iae) {
615 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
616 }
617
618 geometry = WindowGeometry.mainWindow("gui.geometry",
619 (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
620 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
621 }
622
623 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
624 if (args.containsKey(Option.DOWNLOAD)) {
625 List<File> fileList = new ArrayList<File>();
626 for (String s : args.get(Option.DOWNLOAD)) {
627 File f = null;
628 switch(paramType(s)) {
629 case httpUrl:
630 downloadFromParamHttp(false, s);
631 break;
632 case bounds:
633 downloadFromParamBounds(false, s);
634 break;
635 case fileUrl:
636 try {
637 f = new File(new URI(s));
638 } catch (URISyntaxException e) {
639 JOptionPane.showMessageDialog(
640 Main.parent,
641 tr("Ignoring malformed file URL: \"{0}\"", s),
642 tr("Warning"),
643 JOptionPane.WARNING_MESSAGE
644 );
645 }
646 if (f!=null) {
647 fileList.add(f);
648 }
649 break;
650 case fileName:
651 f = new File(s);
652 fileList.add(f);
653 break;
654 }
655 }
656 if(!fileList.isEmpty())
657 {
658 OpenFileAction.openFiles(fileList, true);
659 }
660 }
661 if (args.containsKey(Option.DOWNLOADGPS)) {
662 for (String s : args.get(Option.DOWNLOADGPS)) {
663 switch(paramType(s)) {
664 case httpUrl:
665 downloadFromParamHttp(true, s);
666 break;
667 case bounds:
668 downloadFromParamBounds(true, s);
669 break;
670 case fileUrl:
671 case fileName:
672 JOptionPane.showMessageDialog(
673 Main.parent,
674 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
675 tr("Warning"),
676 JOptionPane.WARNING_MESSAGE
677 );
678 }
679 }
680 }
681 if (args.containsKey(Option.SELECTION)) {
682 for (String s : args.get(Option.SELECTION)) {
683 SearchAction.search(s, SearchAction.SearchMode.add);
684 }
685 }
686 }
687
688 /**
689 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) for all {@link OsmDataLayer} before JOSM exits.
690 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels.
691 * @since 2025
692 */
693 public static boolean saveUnsavedModifications() {
694 if (map == null || map.mapView == null) return true;
695 return saveUnsavedModifications(map.mapView.getLayersOfType(OsmDataLayer.class), true);
696 }
697
698 /**
699 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) before osm layers deletion.
700 *
701 * @param selectedLayers The layers to check. Only instances of {@link OsmDataLayer} are considered.
702 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
703 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels.
704 * @since 5519
705 */
706 public static boolean saveUnsavedModifications(List<? extends Layer> selectedLayers, boolean exit) {
707 SaveLayersDialog dialog = new SaveLayersDialog(parent);
708 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
709 for (Layer l: selectedLayers) {
710 if (!(l instanceof OsmDataLayer)) {
711 continue;
712 }
713 OsmDataLayer odl = (OsmDataLayer)l;
714 if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.data.isModified()) {
715 layersWithUnmodifiedChanges.add(odl);
716 }
717 }
718 if (exit) {
719 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
720 } else {
721 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
722 }
723 if (!layersWithUnmodifiedChanges.isEmpty()) {
724 dialog.getModel().populate(layersWithUnmodifiedChanges);
725 dialog.setVisible(true);
726 switch(dialog.getUserAction()) {
727 case CANCEL: return false;
728 case PROCEED: return true;
729 default: return false;
730 }
731 }
732
733 return true;
734 }
735
736 /**
737 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM). If there are some unsaved data layers, asks first for user confirmation.
738 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a return code of 0.
739 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
740 * @since 3378
741 */
742 public static boolean exitJosm(boolean exit) {
743 if (Main.saveUnsavedModifications()) {
744 geometry.remember("gui.geometry");
745 if (map != null) {
746 map.rememberToggleDialogWidth();
747 }
748 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
749 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
750 if (Main.isDisplayingMapView()) {
751 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
752 for (Layer l: layers) {
753 Main.map.mapView.removeLayer(l);
754 }
755 }
756 if (exit) {
757 System.exit(0);
758 }
759 return true;
760 }
761 return false;
762 }
763
764 /**
765 * The type of a command line parameter, to be used in switch statements.
766 * @see #paramType
767 */
768 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
769
770 /**
771 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
772 * @param s A parameter string
773 * @return The guessed parameter type
774 */
775 private static DownloadParamType paramType(String s) {
776 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
777 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
778 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
779 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
780 // everything else must be a file name
781 return DownloadParamType.fileName;
782 }
783
784 /**
785 * Download area specified on the command line as OSM URL.
786 * @param rawGps Flag to download raw GPS tracks
787 * @param s The URL parameter
788 */
789 private static void downloadFromParamHttp(final boolean rawGps, String s) {
790 final Bounds b = OsmUrlToBounds.parse(s);
791 if (b == null) {
792 JOptionPane.showMessageDialog(
793 Main.parent,
794 tr("Ignoring malformed URL: \"{0}\"", s),
795 tr("Warning"),
796 JOptionPane.WARNING_MESSAGE
797 );
798 } else {
799 downloadFromParamBounds(rawGps, b);
800 }
801 }
802
803 /**
804 * Download area specified on the command line as bounds string.
805 * @param rawGps Flag to download raw GPS tracks
806 * @param s The bounds parameter
807 */
808 private static void downloadFromParamBounds(final boolean rawGps, String s) {
809 final StringTokenizer st = new StringTokenizer(s, ",");
810 if (st.countTokens() == 4) {
811 Bounds b = new Bounds(
812 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
813 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
814 );
815 downloadFromParamBounds(rawGps, b);
816 }
817 }
818
819 /**
820 * Download area specified as Bounds value.
821 * @param rawGps Flag to download raw GPS tracks
822 * @param b The bounds value
823 * @see #downloadFromParamBounds(boolean, String)
824 * @see #downloadFromParamHttp
825 */
826 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
827 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
828 // asynchronously launch the download task ...
829 Future<?> future = task.download(true, b, null);
830 // ... and the continuation when the download is finished (this will wait for the download to finish)
831 Main.worker.execute(new PostDownloadHandler(task, future));
832 }
833
834 /**
835 * Identifies the current operating system family and initializes the platform hook accordingly.
836 * @since 1849
837 */
838 public static void determinePlatformHook() {
839 String os = System.getProperty("os.name");
840 if (os == null) {
841 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
842 platform = new PlatformHookUnixoid();
843 } else if (os.toLowerCase().startsWith("windows")) {
844 platform = new PlatformHookWindows();
845 } else if (os.equals("Linux") || os.equals("Solaris") ||
846 os.equals("SunOS") || os.equals("AIX") ||
847 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
848 platform = new PlatformHookUnixoid();
849 } else if (os.toLowerCase().startsWith("mac os x")) {
850 platform = new PlatformHookOsx();
851 } else {
852 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
853 platform = new PlatformHookUnixoid();
854 }
855 }
856
857 private static class WindowPositionSizeListener extends WindowAdapter implements
858 ComponentListener {
859 @Override
860 public void windowStateChanged(WindowEvent e) {
861 Main.windowState = e.getNewState();
862 }
863
864 @Override
865 public void componentHidden(ComponentEvent e) {
866 }
867
868 @Override
869 public void componentMoved(ComponentEvent e) {
870 handleComponentEvent(e);
871 }
872
873 @Override
874 public void componentResized(ComponentEvent e) {
875 handleComponentEvent(e);
876 }
877
878 @Override
879 public void componentShown(ComponentEvent e) {
880 }
881
882 private void handleComponentEvent(ComponentEvent e) {
883 Component c = e.getComponent();
884 if (c instanceof JFrame && c.isVisible()) {
885 if(Main.windowState == JFrame.NORMAL) {
886 Main.geometry = new WindowGeometry((JFrame) c);
887 } else {
888 Main.geometry.fixScreen((JFrame) c);
889 }
890 }
891 }
892 }
893
894 protected static void addListener() {
895 parent.addComponentListener(new WindowPositionSizeListener());
896 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
897 }
898
899 /**
900 * Checks that JOSM is at least running with Java 6.
901 * @since 3815
902 */
903 public static void checkJava6() {
904 String version = System.getProperty("java.version");
905 if (version != null) {
906 if (version.startsWith("1.6") || version.startsWith("6") ||
907 version.startsWith("1.7") || version.startsWith("7") ||
908 version.startsWith("1.8") || version.startsWith("8"))
909 return;
910 if (version.startsWith("1.5") || version.startsWith("5")) {
911 JLabel ho = new JLabel("<html>"+
912 tr("<h2>JOSM requires Java version 6.</h2>"+
913 "Detected Java version: {0}.<br>"+
914 "You can <ul><li>update your Java (JRE) or</li>"+
915 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
916 "More Info:", version)+"</html>");
917 JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
918 link.setEditable(false);
919 link.setBackground(panel.getBackground());
920 JPanel panel = new JPanel(new GridBagLayout());
921 GridBagConstraints gbc = new GridBagConstraints();
922 gbc.gridwidth = GridBagConstraints.REMAINDER;
923 gbc.anchor = GridBagConstraints.WEST;
924 gbc.weightx = 1.0;
925 panel.add(ho, gbc);
926 panel.add(link, gbc);
927 final String EXIT = tr("Exit JOSM");
928 final String CONTINUE = tr("Continue, try anyway");
929 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
930 if (ret == 0) {
931 System.exit(0);
932 }
933 return;
934 }
935 }
936 System.err.println("Error: Could not recognize Java Version: "+version);
937 }
938
939 /* ----------------------------------------------------------------------------------------- */
940 /* projection handling - Main is a registry for a single, global projection instance */
941 /* */
942 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
943 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
944 /* ----------------------------------------------------------------------------------------- */
945 /**
946 * The projection method used.
947 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
948 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
949 */
950 private static Projection proj;
951
952 /**
953 * Replies the current projection.
954 *
955 * @return the currently active projection
956 */
957 public static Projection getProjection() {
958 return proj;
959 }
960
961 /**
962 * Sets the current projection
963 *
964 * @param p the projection
965 */
966 public static void setProjection(Projection p) {
967 CheckParameterUtil.ensureParameterNotNull(p);
968 Projection oldValue = proj;
969 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
970 proj = p;
971 fireProjectionChanged(oldValue, proj, b);
972 }
973
974 /*
975 * Keep WeakReferences to the listeners. This relieves clients from the burden of
976 * explicitly removing the listeners and allows us to transparently register every
977 * created dataset as projection change listener.
978 */
979 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
980
981 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
982 if (newValue == null ^ oldValue == null
983 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
984
985 synchronized(Main.class) {
986 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
987 while (it.hasNext()){
988 WeakReference<ProjectionChangeListener> wr = it.next();
989 ProjectionChangeListener listener = wr.get();
990 if (listener == null) {
991 it.remove();
992 continue;
993 }
994 listener.projectionChanged(oldValue, newValue);
995 }
996 }
997 if (newValue != null && oldBounds != null) {
998 Main.map.mapView.zoomTo(oldBounds);
999 }
1000 /* TODO - remove layers with fixed projection */
1001 }
1002 }
1003
1004 /**
1005 * Register a projection change listener.
1006 *
1007 * @param listener the listener. Ignored if <code>null</code>.
1008 */
1009 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1010 if (listener == null) return;
1011 synchronized (Main.class) {
1012 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1013 // already registered ? => abort
1014 if (wr.get() == listener) return;
1015 }
1016 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
1017 }
1018 }
1019
1020 /**
1021 * Removes a projection change listener.
1022 *
1023 * @param listener the listener. Ignored if <code>null</code>.
1024 */
1025 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1026 if (listener == null) return;
1027 synchronized(Main.class){
1028 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1029 while (it.hasNext()){
1030 WeakReference<ProjectionChangeListener> wr = it.next();
1031 // remove the listener - and any other listener which got garbage
1032 // collected in the meantime
1033 if (wr.get() == null || wr.get() == listener) {
1034 it.remove();
1035 }
1036 }
1037 }
1038 }
1039
1040 /**
1041 * Listener for window switch events.
1042 *
1043 * These are events, when the user activates a window of another application
1044 * or comes back to JOSM. Window switches from one JOSM window to another
1045 * are not reported.
1046 */
1047 public static interface WindowSwitchListener {
1048 /**
1049 * Called when the user activates a window of another application.
1050 */
1051 void toOtherApplication();
1052 /**
1053 * Called when the user comes from a window of another application
1054 * back to JOSM.
1055 */
1056 void fromOtherApplication();
1057 }
1058
1059 private static final ArrayList<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<WeakReference<WindowSwitchListener>>();
1060
1061 /**
1062 * Register a window switch listener.
1063 *
1064 * @param listener the listener. Ignored if <code>null</code>.
1065 */
1066 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1067 if (listener == null) return;
1068 synchronized (Main.class) {
1069 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1070 // already registered ? => abort
1071 if (wr.get() == listener) return;
1072 }
1073 boolean wasEmpty = windowSwitchListeners.isEmpty();
1074 windowSwitchListeners.add(new WeakReference<WindowSwitchListener>(listener));
1075 if (wasEmpty) {
1076 // The following call will have no effect, when there is no window
1077 // at the time. Therefore, MasterWindowListener.setup() will also be
1078 // called, as soon as the main window is shown.
1079 MasterWindowListener.setup();
1080 }
1081 }
1082 }
1083
1084 /**
1085 * Removes a window switch listener.
1086 *
1087 * @param listener the listener. Ignored if <code>null</code>.
1088 */
1089 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1090 if (listener == null) return;
1091 synchronized (Main.class){
1092 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1093 while (it.hasNext()){
1094 WeakReference<WindowSwitchListener> wr = it.next();
1095 // remove the listener - and any other listener which got garbage
1096 // collected in the meantime
1097 if (wr.get() == null || wr.get() == listener) {
1098 it.remove();
1099 }
1100 }
1101 if (windowSwitchListeners.isEmpty()) {
1102 MasterWindowListener.teardown();
1103 }
1104 }
1105 }
1106
1107 /**
1108 * WindowListener, that is registered on all Windows of the application.
1109 *
1110 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1111 * another application, e.g. a browser, or back to JOSM.
1112 *
1113 * When changing from JOSM to another application and back (e.g. two times
1114 * alt+tab), the active Window within JOSM may be different.
1115 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1116 * Windows in JOSM, and it does not suffice to monitor the one that was
1117 * deactivated last.
1118 *
1119 * This class is only "active" on demand, i.e. when there is at least one
1120 * WindowSwitchListener registered.
1121 */
1122 protected static class MasterWindowListener extends WindowAdapter {
1123
1124 private static MasterWindowListener INSTANCE;
1125
1126 public static MasterWindowListener getInstance() {
1127 if (INSTANCE == null) {
1128 INSTANCE = new MasterWindowListener();
1129 }
1130 return INSTANCE;
1131 }
1132
1133 /**
1134 * Register listeners to all non-hidden windows.
1135 *
1136 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1137 */
1138 public static void setup() {
1139 if (!windowSwitchListeners.isEmpty()) {
1140 for (Window w : Window.getWindows()) {
1141 if (w.isShowing()) {
1142 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1143 w.addWindowListener(getInstance());
1144 }
1145 }
1146 }
1147 }
1148 }
1149
1150 /**
1151 * Unregister all listeners.
1152 */
1153 public static void teardown() {
1154 for (Window w : Window.getWindows()) {
1155 w.removeWindowListener(getInstance());
1156 }
1157 }
1158
1159 @Override
1160 public void windowActivated(WindowEvent e) {
1161 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1162 // fire WindowSwitchListeners
1163 synchronized (Main.class) {
1164 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1165 while (it.hasNext()){
1166 WeakReference<WindowSwitchListener> wr = it.next();
1167 WindowSwitchListener listener = wr.get();
1168 if (listener == null) {
1169 it.remove();
1170 continue;
1171 }
1172 listener.fromOtherApplication();
1173 }
1174 }
1175 }
1176 }
1177
1178 @Override
1179 public void windowDeactivated(WindowEvent e) {
1180 // set up windows that have been created in the meantime
1181 for (Window w : Window.getWindows()) {
1182 if (!w.isShowing()) {
1183 w.removeWindowListener(getInstance());
1184 } else {
1185 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1186 w.addWindowListener(getInstance());
1187 }
1188 }
1189 }
1190 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1191 // fire WindowSwitchListeners
1192 synchronized (Main.class) {
1193 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1194 while (it.hasNext()){
1195 WeakReference<WindowSwitchListener> wr = it.next();
1196 WindowSwitchListener listener = wr.get();
1197 if (listener == null) {
1198 it.remove();
1199 continue;
1200 }
1201 listener.toOtherApplication();
1202 }
1203 }
1204 }
1205 }
1206 }
1207
1208}
Note: See TracBrowser for help on using the repository browser.