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

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

Sonar/FindBugs - Loose coupling

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