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

Last change on this file since 7026 was 7026, checked in by stoecker, 10 years ago

fix #3142 - drop applet code finally

  • 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.StringTokenizer;
30import java.util.concurrent.Callable;
31import java.util.concurrent.ExecutorService;
32import java.util.concurrent.Executors;
33import java.util.concurrent.Future;
34
35import javax.swing.Action;
36import javax.swing.InputMap;
37import javax.swing.JComponent;
38import javax.swing.JFrame;
39import javax.swing.JOptionPane;
40import javax.swing.JPanel;
41import javax.swing.JTextArea;
42import javax.swing.KeyStroke;
43import javax.swing.UIManager;
44import javax.swing.UnsupportedLookAndFeelException;
45
46import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
47import org.openstreetmap.josm.actions.JosmAction;
48import org.openstreetmap.josm.actions.OpenFileAction;
49import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
50import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
51import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
52import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
53import org.openstreetmap.josm.actions.mapmode.DrawAction;
54import org.openstreetmap.josm.actions.mapmode.MapMode;
55import org.openstreetmap.josm.actions.search.SearchAction;
56import org.openstreetmap.josm.data.Bounds;
57import org.openstreetmap.josm.data.Preferences;
58import org.openstreetmap.josm.data.UndoRedoHandler;
59import org.openstreetmap.josm.data.ViewportData;
60import org.openstreetmap.josm.data.coor.CoordinateFormat;
61import org.openstreetmap.josm.data.coor.LatLon;
62import org.openstreetmap.josm.data.osm.DataSet;
63import org.openstreetmap.josm.data.osm.OsmPrimitive;
64import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
65import org.openstreetmap.josm.data.projection.Projection;
66import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
67import org.openstreetmap.josm.data.validation.OsmValidator;
68import org.openstreetmap.josm.gui.GettingStarted;
69import org.openstreetmap.josm.gui.MainApplication.Option;
70import org.openstreetmap.josm.gui.MainMenu;
71import org.openstreetmap.josm.gui.MapFrame;
72import org.openstreetmap.josm.gui.MapFrameListener;
73import org.openstreetmap.josm.gui.MapView;
74import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
75import org.openstreetmap.josm.gui.help.HelpUtil;
76import org.openstreetmap.josm.gui.io.SaveLayersDialog;
77import org.openstreetmap.josm.gui.layer.Layer;
78import org.openstreetmap.josm.gui.layer.OsmDataLayer;
79import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
80import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
81import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
82import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
83import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
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.util.RedirectInputMap;
88import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
89import org.openstreetmap.josm.io.OsmApi;
90import org.openstreetmap.josm.tools.CheckParameterUtil;
91import org.openstreetmap.josm.tools.I18n;
92import org.openstreetmap.josm.tools.ImageProvider;
93import org.openstreetmap.josm.tools.OpenBrowser;
94import org.openstreetmap.josm.tools.OsmUrlToBounds;
95import org.openstreetmap.josm.tools.PlatformHook;
96import org.openstreetmap.josm.tools.PlatformHookOsx;
97import org.openstreetmap.josm.tools.PlatformHookUnixoid;
98import org.openstreetmap.josm.tools.PlatformHookWindows;
99import org.openstreetmap.josm.tools.Shortcut;
100import org.openstreetmap.josm.tools.Utils;
101import org.openstreetmap.josm.tools.WindowGeometry;
102
103/**
104 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
105 * @since 98
106 */
107public abstract class Main {
108
109 /**
110 * The JOSM website URL.
111 * @since 6897 (was public from 6143 to 6896)
112 */
113 private static final String JOSM_WEBSITE = "https://josm.openstreetmap.de";
114
115 /**
116 * The OSM website URL.
117 * @since 6897 (was public from 6453 to 6896)
118 */
119 private static final String OSM_WEBSITE = "https://www.openstreetmap.org";
120
121 /**
122 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
123 * it only shows the MOTD panel.
124 *
125 * @return <code>true</code> if JOSM currently displays a map view
126 */
127 public static boolean isDisplayingMapView() {
128 if (map == null) return false;
129 if (map.mapView == null) return false;
130 return true;
131 }
132
133 /**
134 * Global parent component for all dialogs and message boxes
135 */
136 public static Component parent;
137
138 /**
139 * Global application.
140 */
141 public static Main main;
142
143 /**
144 * Command-line arguments used to run the application.
145 */
146 public static String[] commandLineArgs;
147
148 /**
149 * The worker thread slave. This is for executing all long and intensive
150 * calculations. The executed runnables are guaranteed to be executed separately
151 * and sequential.
152 */
153 public static final ExecutorService worker = new ProgressMonitorExecutor();
154
155 /**
156 * Global application preferences
157 */
158 public static Preferences pref;
159
160 /**
161 * The global paste buffer.
162 */
163 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
164
165 /**
166 * The layer source from which {@link Main#pasteBuffer} data comes from.
167 */
168 public static Layer pasteSource;
169
170 /**
171 * The MapFrame. Use {@link Main#setMapFrame} to set or clear it.
172 */
173 public static MapFrame map;
174
175 /**
176 * The toolbar preference control to register new actions.
177 */
178 public static ToolbarPreferences toolbar;
179
180 /**
181 * The commands undo/redo handler.
182 */
183 public UndoRedoHandler undoRedo = new UndoRedoHandler();
184
185 /**
186 * The progress monitor being currently displayed.
187 */
188 public static PleaseWaitProgressMonitor currentProgressMonitor;
189
190 /**
191 * The main menu bar at top of screen.
192 */
193 public MainMenu menu;
194
195 /**
196 * The data validation handler.
197 */
198 public OsmValidator validator;
199
200 /**
201 * The MOTD Layer.
202 */
203 private GettingStarted gettingStarted = new GettingStarted();
204
205 private static final Collection<MapFrameListener> mapFrameListeners = new ArrayList<>();
206
207 protected static final Map<String, Throwable> NETWORK_ERRORS = new HashMap<>();
208
209 /**
210 * Logging level (5 = trace, 4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
211 * @since 6248
212 */
213 public static int logLevel = 3;
214
215 /**
216 * Prints an error message if logging is on.
217 * @param msg The message to print.
218 * @since 6248
219 */
220 public static void error(String msg) {
221 if (logLevel < 1)
222 return;
223 if (msg != null && !msg.isEmpty()) {
224 System.err.println(tr("ERROR: {0}", msg));
225 }
226 }
227
228 /**
229 * Prints a warning message if logging is on.
230 * @param msg The message to print.
231 */
232 public static void warn(String msg) {
233 if (logLevel < 2)
234 return;
235 if (msg != null && !msg.isEmpty()) {
236 System.err.println(tr("WARNING: {0}", msg));
237 }
238 }
239
240 /**
241 * Prints an informational message if logging is on.
242 * @param msg The message to print.
243 */
244 public static void info(String msg) {
245 if (logLevel < 3)
246 return;
247 if (msg != null && !msg.isEmpty()) {
248 System.out.println(tr("INFO: {0}", msg));
249 }
250 }
251
252 /**
253 * Prints a debug message if logging is on.
254 * @param msg The message to print.
255 */
256 public static void debug(String msg) {
257 if (logLevel < 4)
258 return;
259 if (msg != null && !msg.isEmpty()) {
260 System.out.println(tr("DEBUG: {0}", msg));
261 }
262 }
263
264 /**
265 * Prints a trace message if logging is on.
266 * @param msg The message to print.
267 */
268 public static void trace(String msg) {
269 if (logLevel < 5)
270 return;
271 if (msg != null && !msg.isEmpty()) {
272 System.out.print("TRACE: ");
273 System.out.println(msg);
274 }
275 }
276
277 /**
278 * Determines if debug log level is enabled.
279 * Useful to avoid costly construction of debug messages when not enabled.
280 * @return {@code true} if log level is at least debug, {@code false} otherwise
281 * @since 6852
282 */
283 public static boolean isDebugEnabled() {
284 return logLevel >= 4;
285 }
286
287 /**
288 * Determines if trace log level is enabled.
289 * Useful to avoid costly construction of trace messages when not enabled.
290 * @return {@code true} if log level is at least trace, {@code false} otherwise
291 * @since 6852
292 */
293 public static boolean isTraceEnabled() {
294 return logLevel >= 5;
295 }
296
297 /**
298 * Prints a formatted error message if logging is on. Calls {@link MessageFormat#format}
299 * function to format text.
300 * @param msg The formatted message to print.
301 * @param objects The objects to insert into format string.
302 * @since 6248
303 */
304 public static void error(String msg, Object... objects) {
305 error(MessageFormat.format(msg, objects));
306 }
307
308 /**
309 * Prints a formatted warning message if logging is on. Calls {@link MessageFormat#format}
310 * function to format text.
311 * @param msg The formatted message to print.
312 * @param objects The objects to insert into format string.
313 */
314 public static void warn(String msg, Object... objects) {
315 warn(MessageFormat.format(msg, objects));
316 }
317
318 /**
319 * Prints a formatted informational message if logging is on. Calls {@link MessageFormat#format}
320 * function to format text.
321 * @param msg The formatted message to print.
322 * @param objects The objects to insert into format string.
323 */
324 public static void info(String msg, Object... objects) {
325 info(MessageFormat.format(msg, objects));
326 }
327
328 /**
329 * Prints a formatted debug message if logging is on. Calls {@link MessageFormat#format}
330 * function to format text.
331 * @param msg The formatted message to print.
332 * @param objects The objects to insert into format string.
333 */
334 public static void debug(String msg, Object... objects) {
335 debug(MessageFormat.format(msg, objects));
336 }
337
338 /**
339 * Prints an error message for the given Throwable.
340 * @param t The throwable object causing the error
341 * @since 6248
342 */
343 public static void error(Throwable t) {
344 error(t, true);
345 }
346
347 /**
348 * Prints a warning message for the given Throwable.
349 * @param t The throwable object causing the error
350 * @since 6248
351 */
352 public static void warn(Throwable t) {
353 warn(t, true);
354 }
355
356 /**
357 * Prints an error message for the given Throwable.
358 * @param t The throwable object causing the error
359 * @param stackTrace {@code true}, if the stacktrace should be displayed
360 * @since 6642
361 */
362 public static void error(Throwable t, boolean stackTrace) {
363 error(getErrorMessage(t));
364 if (stackTrace) {
365 t.printStackTrace();
366 }
367 }
368
369 /**
370 * Prints a warning message for the given Throwable.
371 * @param t The throwable object causing the error
372 * @param stackTrace {@code true}, if the stacktrace should be displayed
373 * @since 6642
374 */
375 public static void warn(Throwable t, boolean stackTrace) {
376 warn(getErrorMessage(t));
377 if (stackTrace) {
378 t.printStackTrace();
379 }
380 }
381
382 /**
383 * Returns a human-readable message of error, also usable for developers.
384 * @param t The error
385 * @return The human-readable error message
386 * @since 6642
387 */
388 public static String getErrorMessage(Throwable t) {
389 if (t == null) {
390 return null;
391 }
392 StringBuilder sb = new StringBuilder(t.getClass().getName());
393 String msg = t.getMessage();
394 if (msg != null) {
395 sb.append(": ").append(msg.trim());
396 }
397 Throwable cause = t.getCause();
398 if (cause != null && !cause.equals(t)) {
399 sb.append(". ").append(tr("Cause: ")).append(getErrorMessage(cause));
400 }
401 return sb.toString();
402 }
403
404 /**
405 * Platform specific code goes in here.
406 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
407 * So if you need to hook into those early ones, split your class and send the one with the early hooks
408 * to the JOSM team for inclusion.
409 */
410 public static PlatformHook platform;
411
412 /**
413 * Whether or not the java vm is openjdk
414 * We use this to work around openjdk bugs
415 */
416 public static boolean isOpenjdk;
417
418 /**
419 * Initializes {@code Main.pref} in normal application context.
420 * @since 6471
421 */
422 public static void initApplicationPreferences() {
423 Main.pref = new Preferences();
424 }
425
426 /**
427 * Set or clear (if passed <code>null</code>) the map.
428 * @param map The map to set {@link Main#map} to. Can be null.
429 */
430 public final void setMapFrame(final MapFrame map) {
431 MapFrame old = Main.map;
432 panel.setVisible(false);
433 panel.removeAll();
434 if (map != null) {
435 map.fillPanel(panel);
436 } else {
437 old.destroy();
438 panel.add(gettingStarted, BorderLayout.CENTER);
439 }
440 panel.setVisible(true);
441 redoUndoListener.commandChanged(0,0);
442
443 Main.map = map;
444
445 for (MapFrameListener listener : mapFrameListeners ) {
446 listener.mapFrameInitialized(old, map);
447 }
448 if (map == null && currentProgressMonitor != null) {
449 currentProgressMonitor.showForegroundDialog();
450 }
451 }
452
453 /**
454 * Remove the specified layer from the map. If it is the last layer,
455 * remove the map as well.
456 * @param layer The layer to remove
457 */
458 public final synchronized void removeLayer(final Layer layer) {
459 if (map != null) {
460 map.mapView.removeLayer(layer);
461 if (isDisplayingMapView() && map.mapView.getAllLayers().isEmpty()) {
462 setMapFrame(null);
463 }
464 }
465 }
466
467 private static InitStatusListener initListener = null;
468
469 public static interface InitStatusListener {
470
471 void updateStatus(String event);
472 }
473
474 public static void setInitStatusListener(InitStatusListener listener) {
475 initListener = listener;
476 }
477
478 /**
479 * Constructs new {@code Main} object. A lot of global variables are initialized here.
480 */
481 public Main() {
482 main = this;
483 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
484
485 if (initListener != null) {
486 initListener.updateStatus(tr("Executing platform startup hook"));
487 }
488 platform.startupHook();
489
490 if (initListener != null) {
491 initListener.updateStatus(tr("Building main menu"));
492 }
493 contentPanePrivate.add(panel, BorderLayout.CENTER);
494 panel.add(gettingStarted, BorderLayout.CENTER);
495 menu = new MainMenu();
496
497 undoRedo.addCommandQueueListener(redoUndoListener);
498
499 // creating toolbar
500 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
501
502 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
503 KeyEvent.VK_F1, Shortcut.DIRECT));
504
505 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
506 List<Callable<Void>> tasks = new ArrayList<>();
507
508 tasks.add(new InitializationTask(tr("Initializing OSM API")) {
509
510 @Override
511 public void initialize() throws Exception {
512 // We try to establish an API connection early, so that any API
513 // capabilities are already known to the editor instance. However
514 // if it goes wrong that's not critical at this stage.
515 try {
516 OsmApi.getOsmApi().initialize(null, true);
517 } catch (Exception e) {
518 Main.warn(getErrorMessage(Utils.getRootCause(e)));
519 }
520 }
521 });
522
523 tasks.add(new InitializationTask(tr("Initializing validator")) {
524
525 @Override
526 public void initialize() throws Exception {
527 validator = new OsmValidator();
528 MapView.addLayerChangeListener(validator);
529 }
530 });
531
532 tasks.add(new InitializationTask(tr("Initializing presets")) {
533
534 @Override
535 public void initialize() throws Exception {
536 TaggingPresetPreference.initialize();
537 }
538 });
539
540 tasks.add(new InitializationTask(tr("Initializing map styles")) {
541
542 @Override
543 public void initialize() throws Exception {
544 MapPaintPreference.initialize();
545 }
546 });
547
548 tasks.add(new InitializationTask(tr("Loading imagery preferences")) {
549
550 @Override
551 public void initialize() throws Exception {
552 ImageryPreference.initialize();
553 }
554 });
555
556 try {
557 for (Future<Void> i : Executors.newFixedThreadPool(
558 Runtime.getRuntime().availableProcessors()).invokeAll(tasks)) {
559 i.get();
560 }
561 } catch (Exception ex) {
562 throw new RuntimeException(ex);
563 }
564
565 // hooks for the jmapviewer component
566 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
567 @Override
568 public void openLink(String url) {
569 OpenBrowser.displayUrl(url);
570 }
571 });
572 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
573
574 if (initListener != null) {
575 initListener.updateStatus(tr("Updating user interface"));
576 }
577
578 toolbar.refreshToolbarControl();
579
580 toolbar.control.updateUI();
581 contentPanePrivate.updateUI();
582
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 && !Utils.equal(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.