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

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

New interface MapFrameListener to allow core classes to listen to MapFrame changes (previously only plugins could be notified of these changes)

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