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

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

see #9899 - refactor save/upload layer stuff to allow different layers (i.e: notes layer) to benefit from the mechanism

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