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

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

refactor tagging presets to allow presets-dependent unit tests to update them correctly at runtime

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