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

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

code cleanup / robustness in edit layer handling

  • Property svn:eol-style set to native
File size: 47.3 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 (isDisplayingMapView() && 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 (!isDisplayingMapView()) return null;
547 return map.mapView.getEditLayer();
548 }
549
550 /**
551 * Replies the current data set.
552 *
553 * @return the current data set. <code>null</code>, if no current data set exists
554 */
555 public DataSet getCurrentDataSet() {
556 if (!hasEditLayer()) return null;
557 return getEditLayer().data;
558 }
559
560 /**
561 * Returns the currently active layer
562 *
563 * @return the currently active layer. <code>null</code>, if currently no active layer exists
564 */
565 public Layer getActiveLayer() {
566 if (!isDisplayingMapView()) return null;
567 return map.mapView.getActiveLayer();
568 }
569
570 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
571
572 public static void redirectToMainContentPane(JComponent source) {
573 RedirectInputMap.redirect(source, contentPanePrivate);
574 }
575
576 public static void registerActionShortcut(JosmAction action) {
577 registerActionShortcut(action, action.getShortcut());
578 }
579
580 public static void registerActionShortcut(Action action, Shortcut shortcut) {
581 KeyStroke keyStroke = shortcut.getKeyStroke();
582 if (keyStroke == null)
583 return;
584
585 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
586 Object existing = inputMap.get(keyStroke);
587 if (existing != null && !existing.equals(action)) {
588 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
589 }
590 inputMap.put(keyStroke, action);
591
592 contentPanePrivate.getActionMap().put(action, action);
593 }
594
595 public static void unregisterShortcut(Shortcut shortcut) {
596 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
597 }
598
599 public static void unregisterActionShortcut(JosmAction action) {
600 unregisterActionShortcut(action, action.getShortcut());
601 }
602
603 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
604 unregisterShortcut(shortcut);
605 contentPanePrivate.getActionMap().remove(action);
606 }
607
608 /**
609 * Replies the registered action for the given shortcut
610 * @param shortcut The shortcut to look for
611 * @return the registered action for the given shortcut
612 * @since 5696
613 */
614 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
615 KeyStroke keyStroke = shortcut.getKeyStroke();
616 if (keyStroke == null)
617 return null;
618 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
619 if (action instanceof Action)
620 return (Action) action;
621 return null;
622 }
623
624 ///////////////////////////////////////////////////////////////////////////
625 // Implementation part
626 ///////////////////////////////////////////////////////////////////////////
627
628 /**
629 * Global panel.
630 */
631 public static final JPanel panel = new JPanel(new BorderLayout());
632
633 protected static WindowGeometry geometry;
634 protected static int windowState = JFrame.NORMAL;
635
636 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
637 @Override
638 public void commandChanged(final int queueSize, final int redoSize) {
639 menu.undo.setEnabled(queueSize > 0);
640 menu.redo.setEnabled(redoSize > 0);
641 }
642 };
643
644 /**
645 * Should be called before the main constructor to setup some parameter stuff
646 * @param args The parsed argument list.
647 */
648 public static void preConstructorInit(Map<Option, Collection<String>> args) {
649 ProjectionPreference.setProjection();
650
651 try {
652 String defaultlaf = platform.getDefaultStyle();
653 String laf = Main.pref.get("laf", defaultlaf);
654 try {
655 UIManager.setLookAndFeel(laf);
656 }
657 catch (final ClassNotFoundException e) {
658 info("Look and Feel not found: " + laf);
659 Main.pref.put("laf", defaultlaf);
660 }
661 catch (final UnsupportedLookAndFeelException e) {
662 info("Look and Feel not supported: " + laf);
663 Main.pref.put("laf", defaultlaf);
664 }
665 toolbar = new ToolbarPreferences();
666 contentPanePrivate.updateUI();
667 panel.updateUI();
668 } catch (final Exception e) {
669 e.printStackTrace();
670 }
671 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
672 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
673 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
674 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
675
676 I18n.translateJavaInternalMessages();
677
678 // init default coordinate format
679 //
680 try {
681 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
682 } catch (IllegalArgumentException iae) {
683 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
684 }
685
686 geometry = WindowGeometry.mainWindow("gui.geometry",
687 (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
688 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
689 }
690
691 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
692 if (args.containsKey(Option.DOWNLOAD)) {
693 List<File> fileList = new ArrayList<File>();
694 for (String s : args.get(Option.DOWNLOAD)) {
695 File f = null;
696 switch(paramType(s)) {
697 case httpUrl:
698 downloadFromParamHttp(false, s);
699 break;
700 case bounds:
701 downloadFromParamBounds(false, s);
702 break;
703 case fileUrl:
704 try {
705 f = new File(new URI(s));
706 } catch (URISyntaxException e) {
707 JOptionPane.showMessageDialog(
708 Main.parent,
709 tr("Ignoring malformed file URL: \"{0}\"", s),
710 tr("Warning"),
711 JOptionPane.WARNING_MESSAGE
712 );
713 }
714 if (f!=null) {
715 fileList.add(f);
716 }
717 break;
718 case fileName:
719 f = new File(s);
720 fileList.add(f);
721 break;
722 }
723 }
724 if(!fileList.isEmpty())
725 {
726 OpenFileAction.openFiles(fileList, true);
727 }
728 }
729 if (args.containsKey(Option.DOWNLOADGPS)) {
730 for (String s : args.get(Option.DOWNLOADGPS)) {
731 switch(paramType(s)) {
732 case httpUrl:
733 downloadFromParamHttp(true, s);
734 break;
735 case bounds:
736 downloadFromParamBounds(true, s);
737 break;
738 case fileUrl:
739 case fileName:
740 JOptionPane.showMessageDialog(
741 Main.parent,
742 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
743 tr("Warning"),
744 JOptionPane.WARNING_MESSAGE
745 );
746 }
747 }
748 }
749 if (args.containsKey(Option.SELECTION)) {
750 for (String s : args.get(Option.SELECTION)) {
751 SearchAction.search(s, SearchAction.SearchMode.add);
752 }
753 }
754 }
755
756 /**
757 * 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.
758 * @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.
759 * @since 2025
760 */
761 public static boolean saveUnsavedModifications() {
762 if (!isDisplayingMapView()) return true;
763 return saveUnsavedModifications(map.mapView.getLayersOfType(OsmDataLayer.class), true);
764 }
765
766 /**
767 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) before osm layers deletion.
768 *
769 * @param selectedLayers The layers to check. Only instances of {@link OsmDataLayer} are considered.
770 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
771 * @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.
772 * @since 5519
773 */
774 public static boolean saveUnsavedModifications(List<? extends Layer> selectedLayers, boolean exit) {
775 SaveLayersDialog dialog = new SaveLayersDialog(parent);
776 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
777 for (Layer l: selectedLayers) {
778 if (!(l instanceof OsmDataLayer)) {
779 continue;
780 }
781 OsmDataLayer odl = (OsmDataLayer)l;
782 if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.data.isModified()) {
783 layersWithUnmodifiedChanges.add(odl);
784 }
785 }
786 if (exit) {
787 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
788 } else {
789 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
790 }
791 if (!layersWithUnmodifiedChanges.isEmpty()) {
792 dialog.getModel().populate(layersWithUnmodifiedChanges);
793 dialog.setVisible(true);
794 switch(dialog.getUserAction()) {
795 case CANCEL: return false;
796 case PROCEED: return true;
797 default: return false;
798 }
799 }
800
801 return true;
802 }
803
804 /**
805 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM). If there are some unsaved data layers, asks first for user confirmation.
806 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a return code of 0.
807 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
808 * @since 3378
809 */
810 public static boolean exitJosm(boolean exit, int exitCode) {
811 if (Main.saveUnsavedModifications()) {
812 geometry.remember("gui.geometry");
813 if (map != null) {
814 map.rememberToggleDialogWidth();
815 }
816 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
817 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
818 if (Main.isDisplayingMapView()) {
819 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
820 for (Layer l: layers) {
821 Main.main.removeLayer(l);
822 }
823 }
824 if (exit) {
825 System.exit(exitCode);
826 }
827 return true;
828 }
829 return false;
830 }
831
832 /**
833 * The type of a command line parameter, to be used in switch statements.
834 * @see #paramType
835 */
836 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
837
838 /**
839 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
840 * @param s A parameter string
841 * @return The guessed parameter type
842 */
843 private static DownloadParamType paramType(String s) {
844 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
845 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
846 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
847 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
848 // everything else must be a file name
849 return DownloadParamType.fileName;
850 }
851
852 /**
853 * Download area specified on the command line as OSM URL.
854 * @param rawGps Flag to download raw GPS tracks
855 * @param s The URL parameter
856 */
857 private static void downloadFromParamHttp(final boolean rawGps, String s) {
858 final Bounds b = OsmUrlToBounds.parse(s);
859 if (b == null) {
860 JOptionPane.showMessageDialog(
861 Main.parent,
862 tr("Ignoring malformed URL: \"{0}\"", s),
863 tr("Warning"),
864 JOptionPane.WARNING_MESSAGE
865 );
866 } else {
867 downloadFromParamBounds(rawGps, b);
868 }
869 }
870
871 /**
872 * Download area specified on the command line as bounds string.
873 * @param rawGps Flag to download raw GPS tracks
874 * @param s The bounds parameter
875 */
876 private static void downloadFromParamBounds(final boolean rawGps, String s) {
877 final StringTokenizer st = new StringTokenizer(s, ",");
878 if (st.countTokens() == 4) {
879 Bounds b = new Bounds(
880 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
881 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
882 );
883 downloadFromParamBounds(rawGps, b);
884 }
885 }
886
887 /**
888 * Download area specified as Bounds value.
889 * @param rawGps Flag to download raw GPS tracks
890 * @param b The bounds value
891 * @see #downloadFromParamBounds(boolean, String)
892 * @see #downloadFromParamHttp
893 */
894 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
895 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
896 // asynchronously launch the download task ...
897 Future<?> future = task.download(true, b, null);
898 // ... and the continuation when the download is finished (this will wait for the download to finish)
899 Main.worker.execute(new PostDownloadHandler(task, future));
900 }
901
902 /**
903 * Identifies the current operating system family and initializes the platform hook accordingly.
904 * @since 1849
905 */
906 public static void determinePlatformHook() {
907 String os = System.getProperty("os.name");
908 if (os == null) {
909 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
910 platform = new PlatformHookUnixoid();
911 } else if (os.toLowerCase().startsWith("windows")) {
912 platform = new PlatformHookWindows();
913 } else if (os.equals("Linux") || os.equals("Solaris") ||
914 os.equals("SunOS") || os.equals("AIX") ||
915 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
916 platform = new PlatformHookUnixoid();
917 } else if (os.toLowerCase().startsWith("mac os x")) {
918 platform = new PlatformHookOsx();
919 } else {
920 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
921 platform = new PlatformHookUnixoid();
922 }
923 }
924
925 private static class WindowPositionSizeListener extends WindowAdapter implements
926 ComponentListener {
927 @Override
928 public void windowStateChanged(WindowEvent e) {
929 Main.windowState = e.getNewState();
930 }
931
932 @Override
933 public void componentHidden(ComponentEvent e) {
934 }
935
936 @Override
937 public void componentMoved(ComponentEvent e) {
938 handleComponentEvent(e);
939 }
940
941 @Override
942 public void componentResized(ComponentEvent e) {
943 handleComponentEvent(e);
944 }
945
946 @Override
947 public void componentShown(ComponentEvent e) {
948 }
949
950 private void handleComponentEvent(ComponentEvent e) {
951 Component c = e.getComponent();
952 if (c instanceof JFrame && c.isVisible()) {
953 if(Main.windowState == JFrame.NORMAL) {
954 Main.geometry = new WindowGeometry((JFrame) c);
955 } else {
956 Main.geometry.fixScreen((JFrame) c);
957 }
958 }
959 }
960 }
961
962 protected static void addListener() {
963 parent.addComponentListener(new WindowPositionSizeListener());
964 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
965 }
966
967 /**
968 * Checks that JOSM is at least running with Java 6.
969 * @since 3815
970 */
971 public static void checkJava6() {
972 String version = System.getProperty("java.version");
973 if (version != null) {
974 if (version.startsWith("1.6") || version.startsWith("6") ||
975 version.startsWith("1.7") || version.startsWith("7") ||
976 version.startsWith("1.8") || version.startsWith("8"))
977 return;
978 if (version.startsWith("1.5") || version.startsWith("5")) {
979 JLabel ho = new JLabel("<html>"+
980 tr("<h2>JOSM requires Java version 6.</h2>"+
981 "Detected Java version: {0}.<br>"+
982 "You can <ul><li>update your Java (JRE) or</li>"+
983 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
984 "More Info:", version)+"</html>");
985 JTextArea link = new JTextArea(HelpUtil.getWikiBaseHelpUrl()+"/Help/SystemRequirements");
986 link.setEditable(false);
987 link.setBackground(panel.getBackground());
988 JPanel panel = new JPanel(new GridBagLayout());
989 GridBagConstraints gbc = new GridBagConstraints();
990 gbc.gridwidth = GridBagConstraints.REMAINDER;
991 gbc.anchor = GridBagConstraints.WEST;
992 gbc.weightx = 1.0;
993 panel.add(ho, gbc);
994 panel.add(link, gbc);
995 final String EXIT = tr("Exit JOSM");
996 final String CONTINUE = tr("Continue, try anyway");
997 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
998 if (ret == 0) {
999 System.exit(0);
1000 }
1001 return;
1002 }
1003 }
1004 error("Could not recognize Java Version: "+version);
1005 }
1006
1007 /* ----------------------------------------------------------------------------------------- */
1008 /* projection handling - Main is a registry for a single, global projection instance */
1009 /* */
1010 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1011 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1012 /* ----------------------------------------------------------------------------------------- */
1013 /**
1014 * The projection method used.
1015 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1016 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
1017 */
1018 private static Projection proj;
1019
1020 /**
1021 * Replies the current projection.
1022 *
1023 * @return the currently active projection
1024 */
1025 public static Projection getProjection() {
1026 return proj;
1027 }
1028
1029 /**
1030 * Sets the current projection
1031 *
1032 * @param p the projection
1033 */
1034 public static void setProjection(Projection p) {
1035 CheckParameterUtil.ensureParameterNotNull(p);
1036 Projection oldValue = proj;
1037 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
1038 proj = p;
1039 fireProjectionChanged(oldValue, proj, b);
1040 }
1041
1042 /*
1043 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1044 * explicitly removing the listeners and allows us to transparently register every
1045 * created dataset as projection change listener.
1046 */
1047 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
1048
1049 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
1050 if (newValue == null ^ oldValue == null
1051 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
1052
1053 synchronized(Main.class) {
1054 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1055 while (it.hasNext()){
1056 WeakReference<ProjectionChangeListener> wr = it.next();
1057 ProjectionChangeListener listener = wr.get();
1058 if (listener == null) {
1059 it.remove();
1060 continue;
1061 }
1062 listener.projectionChanged(oldValue, newValue);
1063 }
1064 }
1065 if (newValue != null && oldBounds != null) {
1066 Main.map.mapView.zoomTo(oldBounds);
1067 }
1068 /* TODO - remove layers with fixed projection */
1069 }
1070 }
1071
1072 /**
1073 * Register a projection change listener.
1074 *
1075 * @param listener the listener. Ignored if <code>null</code>.
1076 */
1077 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1078 if (listener == null) return;
1079 synchronized (Main.class) {
1080 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1081 // already registered ? => abort
1082 if (wr.get() == listener) return;
1083 }
1084 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
1085 }
1086 }
1087
1088 /**
1089 * Removes a projection change listener.
1090 *
1091 * @param listener the listener. Ignored if <code>null</code>.
1092 */
1093 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1094 if (listener == null) return;
1095 synchronized(Main.class){
1096 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1097 while (it.hasNext()){
1098 WeakReference<ProjectionChangeListener> wr = it.next();
1099 // remove the listener - and any other listener which got garbage
1100 // collected in the meantime
1101 if (wr.get() == null || wr.get() == listener) {
1102 it.remove();
1103 }
1104 }
1105 }
1106 }
1107
1108 /**
1109 * Listener for window switch events.
1110 *
1111 * These are events, when the user activates a window of another application
1112 * or comes back to JOSM. Window switches from one JOSM window to another
1113 * are not reported.
1114 */
1115 public static interface WindowSwitchListener {
1116 /**
1117 * Called when the user activates a window of another application.
1118 */
1119 void toOtherApplication();
1120 /**
1121 * Called when the user comes from a window of another application
1122 * back to JOSM.
1123 */
1124 void fromOtherApplication();
1125 }
1126
1127 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<WeakReference<WindowSwitchListener>>();
1128
1129 /**
1130 * Register a window switch listener.
1131 *
1132 * @param listener the listener. Ignored if <code>null</code>.
1133 */
1134 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1135 if (listener == null) return;
1136 synchronized (Main.class) {
1137 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1138 // already registered ? => abort
1139 if (wr.get() == listener) return;
1140 }
1141 boolean wasEmpty = windowSwitchListeners.isEmpty();
1142 windowSwitchListeners.add(new WeakReference<WindowSwitchListener>(listener));
1143 if (wasEmpty) {
1144 // The following call will have no effect, when there is no window
1145 // at the time. Therefore, MasterWindowListener.setup() will also be
1146 // called, as soon as the main window is shown.
1147 MasterWindowListener.setup();
1148 }
1149 }
1150 }
1151
1152 /**
1153 * Removes a window switch listener.
1154 *
1155 * @param listener the listener. Ignored if <code>null</code>.
1156 */
1157 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1158 if (listener == null) return;
1159 synchronized (Main.class){
1160 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1161 while (it.hasNext()){
1162 WeakReference<WindowSwitchListener> wr = it.next();
1163 // remove the listener - and any other listener which got garbage
1164 // collected in the meantime
1165 if (wr.get() == null || wr.get() == listener) {
1166 it.remove();
1167 }
1168 }
1169 if (windowSwitchListeners.isEmpty()) {
1170 MasterWindowListener.teardown();
1171 }
1172 }
1173 }
1174
1175 /**
1176 * WindowListener, that is registered on all Windows of the application.
1177 *
1178 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1179 * another application, e.g. a browser, or back to JOSM.
1180 *
1181 * When changing from JOSM to another application and back (e.g. two times
1182 * alt+tab), the active Window within JOSM may be different.
1183 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1184 * Windows in JOSM, and it does not suffice to monitor the one that was
1185 * deactivated last.
1186 *
1187 * This class is only "active" on demand, i.e. when there is at least one
1188 * WindowSwitchListener registered.
1189 */
1190 protected static class MasterWindowListener extends WindowAdapter {
1191
1192 private static MasterWindowListener INSTANCE;
1193
1194 public static MasterWindowListener getInstance() {
1195 if (INSTANCE == null) {
1196 INSTANCE = new MasterWindowListener();
1197 }
1198 return INSTANCE;
1199 }
1200
1201 /**
1202 * Register listeners to all non-hidden windows.
1203 *
1204 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1205 */
1206 public static void setup() {
1207 if (!windowSwitchListeners.isEmpty()) {
1208 for (Window w : Window.getWindows()) {
1209 if (w.isShowing()) {
1210 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1211 w.addWindowListener(getInstance());
1212 }
1213 }
1214 }
1215 }
1216 }
1217
1218 /**
1219 * Unregister all listeners.
1220 */
1221 public static void teardown() {
1222 for (Window w : Window.getWindows()) {
1223 w.removeWindowListener(getInstance());
1224 }
1225 }
1226
1227 @Override
1228 public void windowActivated(WindowEvent e) {
1229 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1230 // fire WindowSwitchListeners
1231 synchronized (Main.class) {
1232 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1233 while (it.hasNext()){
1234 WeakReference<WindowSwitchListener> wr = it.next();
1235 WindowSwitchListener listener = wr.get();
1236 if (listener == null) {
1237 it.remove();
1238 continue;
1239 }
1240 listener.fromOtherApplication();
1241 }
1242 }
1243 }
1244 }
1245
1246 @Override
1247 public void windowDeactivated(WindowEvent e) {
1248 // set up windows that have been created in the meantime
1249 for (Window w : Window.getWindows()) {
1250 if (!w.isShowing()) {
1251 w.removeWindowListener(getInstance());
1252 } else {
1253 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1254 w.addWindowListener(getInstance());
1255 }
1256 }
1257 }
1258 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1259 // fire WindowSwitchListeners
1260 synchronized (Main.class) {
1261 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1262 while (it.hasNext()){
1263 WeakReference<WindowSwitchListener> wr = it.next();
1264 WindowSwitchListener listener = wr.get();
1265 if (listener == null) {
1266 it.remove();
1267 continue;
1268 }
1269 listener.toOtherApplication();
1270 }
1271 }
1272 }
1273 }
1274 }
1275
1276 /**
1277 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1278 * @param listener The MapFrameListener
1279 * @return {@code true} if the listeners collection changed as a result of the call
1280 * @since 5957
1281 */
1282 public static boolean addMapFrameListener(MapFrameListener listener) {
1283 return listener != null ? mapFrameListeners.add(listener) : false;
1284 }
1285
1286 /**
1287 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1288 * @param listener The MapFrameListener
1289 * @return {@code true} if the listeners collection changed as a result of the call
1290 * @since 5957
1291 */
1292 public static boolean removeMapFrameListener(MapFrameListener listener) {
1293 return listener != null ? mapFrameListeners.remove(listener) : false;
1294 }
1295}
Note: See TracBrowser for help on using the repository browser.