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

Last change on this file since 7004 was 7001, checked in by Don-vip, 10 years ago

see #8465 - switch core to Java 7

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