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

Last change on this file since 6142 was 6125, checked in by bastiK, 11 years ago

see #7275 - allow script to handle restart

When JOSM was started with parameter -Djosm.restart=true, a
user request for restart will simply terminate the application
with exit code 9.
The start script is then responsible for the restart.

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