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

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

fix javadoc + minor refactorization/code cleanup

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