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

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

fix some Sonar issues introduced recently

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