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

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

see #8885 - cleanup in command line arguments and website URL handling

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