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

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

see #8582 - Use Main.removeLayer() everywhere

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