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

Last change on this file since 6773 was 6730, checked in by simon04, 10 years ago

Allow to enable debug log messages by commandline argument --debug

  • Property svn:eol-style set to native
File size: 52.6 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> networkErrors = 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 Callable<Void>() {
504
505 @Override
506 public Void call() 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 if (initListener != null) {
511 initListener.updateStatus(tr("Initializing OSM API"));
512 }
513 try {
514 OsmApi.getOsmApi().initialize(null, true);
515 } catch (Exception e) {
516 Main.warn(getErrorMessage(Utils.getRootCause(e)));
517 }
518 return null;
519 }
520 });
521
522 tasks.add(new Callable<Void>() {
523
524 @Override
525 public Void call() throws Exception {
526 if (initListener != null) {
527 initListener.updateStatus(tr("Initializing presets"));
528 }
529 TaggingPresetPreference.initialize();
530 // some validator tests require the presets to be initialized
531 // TODO remove this dependency for parallel initialization
532 if (initListener != null) {
533 initListener.updateStatus(tr("Initializing validator"));
534 }
535 validator = new OsmValidator();
536 MapView.addLayerChangeListener(validator);
537 return null;
538 }
539 });
540
541 tasks.add(new Callable<Void>() {
542
543 @Override
544 public Void call() throws Exception {
545 if (initListener != null) {
546 initListener.updateStatus(tr("Initializing map styles"));
547 }
548 MapPaintPreference.initialize();
549 return null;
550 }
551 });
552
553 tasks.add(new Callable<Void>() {
554
555 @Override
556 public Void call() throws Exception {
557 if (initListener != null) {
558 initListener.updateStatus(tr("Loading imagery preferences"));
559 }
560 ImageryPreference.initialize();
561 return null;
562 }
563 });
564
565 try {
566 for (Future<Void> i : Executors.newFixedThreadPool(
567 Runtime.getRuntime().availableProcessors()).invokeAll(tasks)) {
568 i.get();
569 }
570 } catch (Exception ex) {
571 throw new RuntimeException(ex);
572 }
573
574 // hooks for the jmapviewer component
575 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
576 @Override
577 public void openLink(String url) {
578 OpenBrowser.displayUrl(url);
579 }
580 });
581 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
582
583 if (initListener != null) {
584 initListener.updateStatus(tr("Updating user interface"));
585 }
586
587 toolbar.refreshToolbarControl();
588
589 toolbar.control.updateUI();
590 contentPanePrivate.updateUI();
591
592 }
593
594 /**
595 * Add a new layer to the map. If no map exists, create one.
596 */
597 public final synchronized void addLayer(final Layer layer) {
598 boolean noMap = map == null;
599 if (noMap) {
600 createMapFrame(layer, null);
601 }
602 layer.hookUpMapView();
603 map.mapView.addLayer(layer);
604 if (noMap) {
605 Main.map.setVisible(true);
606 }
607 }
608
609 public synchronized void createMapFrame(Layer firstLayer, ViewportData viewportData) {
610 MapFrame mapFrame = new MapFrame(contentPanePrivate, viewportData);
611 setMapFrame(mapFrame);
612 if (firstLayer != null) {
613 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), firstLayer);
614 }
615 mapFrame.initializeDialogsPane();
616 // bootstrapping problem: make sure the layer list dialog is going to
617 // listen to change events of the very first layer
618 //
619 if (firstLayer != null) {
620 firstLayer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
621 }
622 }
623
624 /**
625 * Replies <code>true</code> if there is an edit layer
626 *
627 * @return <code>true</code> if there is an edit layer
628 */
629 public boolean hasEditLayer() {
630 if (getEditLayer() == null) return false;
631 return true;
632 }
633
634 /**
635 * Replies the current edit layer
636 *
637 * @return the current edit layer. <code>null</code>, if no current edit layer exists
638 */
639 public OsmDataLayer getEditLayer() {
640 if (!isDisplayingMapView()) return null;
641 return map.mapView.getEditLayer();
642 }
643
644 /**
645 * Replies the current data set.
646 *
647 * @return the current data set. <code>null</code>, if no current data set exists
648 */
649 public DataSet getCurrentDataSet() {
650 if (!hasEditLayer()) return null;
651 return getEditLayer().data;
652 }
653
654 /**
655 * Replies the current selected primitives, from a end-user point of view.
656 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
657 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
658 * see {@link DrawAction#getInProgressSelection()}.
659 *
660 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
661 * @since 6546
662 */
663 public Collection<OsmPrimitive> getInProgressSelection() {
664 if (map != null && map.mapMode instanceof DrawAction) {
665 return ((DrawAction) map.mapMode).getInProgressSelection();
666 } else {
667 DataSet ds = getCurrentDataSet();
668 if (ds == null) return null;
669 return ds.getSelected();
670 }
671 }
672
673 /**
674 * Returns the currently active layer
675 *
676 * @return the currently active layer. <code>null</code>, if currently no active layer exists
677 */
678 public Layer getActiveLayer() {
679 if (!isDisplayingMapView()) return null;
680 return map.mapView.getActiveLayer();
681 }
682
683 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
684
685 public static void redirectToMainContentPane(JComponent source) {
686 RedirectInputMap.redirect(source, contentPanePrivate);
687 }
688
689 public static void registerActionShortcut(JosmAction action) {
690 registerActionShortcut(action, action.getShortcut());
691 }
692
693 public static void registerActionShortcut(Action action, Shortcut shortcut) {
694 KeyStroke keyStroke = shortcut.getKeyStroke();
695 if (keyStroke == null)
696 return;
697
698 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
699 Object existing = inputMap.get(keyStroke);
700 if (existing != null && !existing.equals(action)) {
701 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
702 }
703 inputMap.put(keyStroke, action);
704
705 contentPanePrivate.getActionMap().put(action, action);
706 }
707
708 public static void unregisterShortcut(Shortcut shortcut) {
709 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
710 }
711
712 public static void unregisterActionShortcut(JosmAction action) {
713 unregisterActionShortcut(action, action.getShortcut());
714 }
715
716 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
717 unregisterShortcut(shortcut);
718 contentPanePrivate.getActionMap().remove(action);
719 }
720
721 /**
722 * Replies the registered action for the given shortcut
723 * @param shortcut The shortcut to look for
724 * @return the registered action for the given shortcut
725 * @since 5696
726 */
727 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
728 KeyStroke keyStroke = shortcut.getKeyStroke();
729 if (keyStroke == null)
730 return null;
731 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
732 if (action instanceof Action)
733 return (Action) action;
734 return null;
735 }
736
737 ///////////////////////////////////////////////////////////////////////////
738 // Implementation part
739 ///////////////////////////////////////////////////////////////////////////
740
741 /**
742 * Global panel.
743 */
744 public static final JPanel panel = new JPanel(new BorderLayout());
745
746 protected static WindowGeometry geometry;
747 protected static int windowState = JFrame.NORMAL;
748
749 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
750 @Override
751 public void commandChanged(final int queueSize, final int redoSize) {
752 menu.undo.setEnabled(queueSize > 0);
753 menu.redo.setEnabled(redoSize > 0);
754 }
755 };
756
757 /**
758 * Should be called before the main constructor to setup some parameter stuff
759 * @param args The parsed argument list.
760 */
761 public static void preConstructorInit(Map<Option, Collection<String>> args) {
762 ProjectionPreference.setProjection();
763
764 try {
765 String defaultlaf = platform.getDefaultStyle();
766 String laf = Main.pref.get("laf", defaultlaf);
767 try {
768 UIManager.setLookAndFeel(laf);
769 }
770 catch (final ClassNotFoundException e) {
771 info("Look and Feel not found: " + laf);
772 Main.pref.put("laf", defaultlaf);
773 }
774 catch (final UnsupportedLookAndFeelException e) {
775 info("Look and Feel not supported: " + laf);
776 Main.pref.put("laf", defaultlaf);
777 }
778 toolbar = new ToolbarPreferences();
779 contentPanePrivate.updateUI();
780 panel.updateUI();
781 } catch (final Exception e) {
782 error(e);
783 }
784 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
785 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
786 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
787 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
788
789 I18n.translateJavaInternalMessages();
790
791 // init default coordinate format
792 //
793 try {
794 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
795 } catch (IllegalArgumentException iae) {
796 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
797 }
798
799 geometry = WindowGeometry.mainWindow("gui.geometry",
800 (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
801 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
802 }
803
804 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
805 if (args.containsKey(Option.DOWNLOAD)) {
806 List<File> fileList = new ArrayList<File>();
807 for (String s : args.get(Option.DOWNLOAD)) {
808 File f = null;
809 switch(paramType(s)) {
810 case httpUrl:
811 downloadFromParamHttp(false, s);
812 break;
813 case bounds:
814 downloadFromParamBounds(false, s);
815 break;
816 case fileUrl:
817 try {
818 f = new File(new URI(s));
819 } catch (URISyntaxException e) {
820 JOptionPane.showMessageDialog(
821 Main.parent,
822 tr("Ignoring malformed file URL: \"{0}\"", s),
823 tr("Warning"),
824 JOptionPane.WARNING_MESSAGE
825 );
826 }
827 if (f!=null) {
828 fileList.add(f);
829 }
830 break;
831 case fileName:
832 f = new File(s);
833 fileList.add(f);
834 break;
835 }
836 }
837 if(!fileList.isEmpty())
838 {
839 OpenFileAction.openFiles(fileList, true);
840 }
841 }
842 if (args.containsKey(Option.DOWNLOADGPS)) {
843 for (String s : args.get(Option.DOWNLOADGPS)) {
844 switch(paramType(s)) {
845 case httpUrl:
846 downloadFromParamHttp(true, s);
847 break;
848 case bounds:
849 downloadFromParamBounds(true, s);
850 break;
851 case fileUrl:
852 case fileName:
853 JOptionPane.showMessageDialog(
854 Main.parent,
855 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
856 tr("Warning"),
857 JOptionPane.WARNING_MESSAGE
858 );
859 }
860 }
861 }
862 if (args.containsKey(Option.SELECTION)) {
863 for (String s : args.get(Option.SELECTION)) {
864 SearchAction.search(s, SearchAction.SearchMode.add);
865 }
866 }
867 }
868
869 /**
870 * 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.
871 * @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.
872 * @since 2025
873 */
874 public static boolean saveUnsavedModifications() {
875 if (!isDisplayingMapView()) return true;
876 return saveUnsavedModifications(map.mapView.getLayersOfType(OsmDataLayer.class), true);
877 }
878
879 /**
880 * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) before osm layers deletion.
881 *
882 * @param selectedLayers The layers to check. Only instances of {@link OsmDataLayer} are considered.
883 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
884 * @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.
885 * @since 5519
886 */
887 public static boolean saveUnsavedModifications(Iterable<? extends Layer> selectedLayers, boolean exit) {
888 SaveLayersDialog dialog = new SaveLayersDialog(parent);
889 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
890 for (Layer l: selectedLayers) {
891 if (!(l instanceof OsmDataLayer)) {
892 continue;
893 }
894 OsmDataLayer odl = (OsmDataLayer)l;
895 if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.data.isModified()) {
896 layersWithUnmodifiedChanges.add(odl);
897 }
898 }
899 if (exit) {
900 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
901 } else {
902 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
903 }
904 if (!layersWithUnmodifiedChanges.isEmpty()) {
905 dialog.getModel().populate(layersWithUnmodifiedChanges);
906 dialog.setVisible(true);
907 switch(dialog.getUserAction()) {
908 case CANCEL: return false;
909 case PROCEED: return true;
910 default: return false;
911 }
912 }
913
914 return true;
915 }
916
917 /**
918 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM). If there are some unsaved data layers, asks first for user confirmation.
919 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
920 * @param exitCode The return code
921 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
922 * @since 3378
923 */
924 public static boolean exitJosm(boolean exit, int exitCode) {
925 if (Main.saveUnsavedModifications()) {
926 geometry.remember("gui.geometry");
927 if (map != null) {
928 map.rememberToggleDialogWidth();
929 }
930 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
931 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
932 if (Main.isDisplayingMapView()) {
933 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
934 for (Layer l: layers) {
935 Main.main.removeLayer(l);
936 }
937 }
938 if (exit) {
939 System.exit(exitCode);
940 }
941 return true;
942 }
943 return false;
944 }
945
946 /**
947 * The type of a command line parameter, to be used in switch statements.
948 * @see #paramType
949 */
950 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
951
952 /**
953 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
954 * @param s A parameter string
955 * @return The guessed parameter type
956 */
957 private static DownloadParamType paramType(String s) {
958 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
959 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
960 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
961 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
962 // everything else must be a file name
963 return DownloadParamType.fileName;
964 }
965
966 /**
967 * Download area specified on the command line as OSM URL.
968 * @param rawGps Flag to download raw GPS tracks
969 * @param s The URL parameter
970 */
971 private static void downloadFromParamHttp(final boolean rawGps, String s) {
972 final Bounds b = OsmUrlToBounds.parse(s);
973 if (b == null) {
974 JOptionPane.showMessageDialog(
975 Main.parent,
976 tr("Ignoring malformed URL: \"{0}\"", s),
977 tr("Warning"),
978 JOptionPane.WARNING_MESSAGE
979 );
980 } else {
981 downloadFromParamBounds(rawGps, b);
982 }
983 }
984
985 /**
986 * Download area specified on the command line as bounds string.
987 * @param rawGps Flag to download raw GPS tracks
988 * @param s The bounds parameter
989 */
990 private static void downloadFromParamBounds(final boolean rawGps, String s) {
991 final StringTokenizer st = new StringTokenizer(s, ",");
992 if (st.countTokens() == 4) {
993 Bounds b = new Bounds(
994 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
995 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
996 );
997 downloadFromParamBounds(rawGps, b);
998 }
999 }
1000
1001 /**
1002 * Download area specified as Bounds value.
1003 * @param rawGps Flag to download raw GPS tracks
1004 * @param b The bounds value
1005 * @see #downloadFromParamBounds(boolean, String)
1006 * @see #downloadFromParamHttp
1007 */
1008 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
1009 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1010 // asynchronously launch the download task ...
1011 Future<?> future = task.download(true, b, null);
1012 // ... and the continuation when the download is finished (this will wait for the download to finish)
1013 Main.worker.execute(new PostDownloadHandler(task, future));
1014 }
1015
1016 /**
1017 * Identifies the current operating system family and initializes the platform hook accordingly.
1018 * @since 1849
1019 */
1020 public static void determinePlatformHook() {
1021 String os = System.getProperty("os.name");
1022 if (os == null) {
1023 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
1024 platform = new PlatformHookUnixoid();
1025 } else if (os.toLowerCase().startsWith("windows")) {
1026 platform = new PlatformHookWindows();
1027 } else if (os.equals("Linux") || os.equals("Solaris") ||
1028 os.equals("SunOS") || os.equals("AIX") ||
1029 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
1030 platform = new PlatformHookUnixoid();
1031 } else if (os.toLowerCase().startsWith("mac os x")) {
1032 platform = new PlatformHookOsx();
1033 } else {
1034 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
1035 platform = new PlatformHookUnixoid();
1036 }
1037 }
1038
1039 private static class WindowPositionSizeListener extends WindowAdapter implements
1040 ComponentListener {
1041 @Override
1042 public void windowStateChanged(WindowEvent e) {
1043 Main.windowState = e.getNewState();
1044 }
1045
1046 @Override
1047 public void componentHidden(ComponentEvent e) {
1048 }
1049
1050 @Override
1051 public void componentMoved(ComponentEvent e) {
1052 handleComponentEvent(e);
1053 }
1054
1055 @Override
1056 public void componentResized(ComponentEvent e) {
1057 handleComponentEvent(e);
1058 }
1059
1060 @Override
1061 public void componentShown(ComponentEvent e) {
1062 }
1063
1064 private void handleComponentEvent(ComponentEvent e) {
1065 Component c = e.getComponent();
1066 if (c instanceof JFrame && c.isVisible()) {
1067 if(Main.windowState == JFrame.NORMAL) {
1068 Main.geometry = new WindowGeometry((JFrame) c);
1069 } else {
1070 Main.geometry.fixScreen((JFrame) c);
1071 }
1072 }
1073 }
1074 }
1075
1076 protected static void addListener() {
1077 parent.addComponentListener(new WindowPositionSizeListener());
1078 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
1079 }
1080
1081 /**
1082 * Checks that JOSM is at least running with Java 6.
1083 * @since 3815
1084 */
1085 public static void checkJava6() {
1086 String version = System.getProperty("java.version");
1087 if (version != null) {
1088 if (version.startsWith("1.6") || version.startsWith("6") ||
1089 version.startsWith("1.7") || version.startsWith("7") ||
1090 version.startsWith("1.8") || version.startsWith("8") ||
1091 version.startsWith("1.9") || version.startsWith("9"))
1092 return;
1093 if (version.startsWith("1.5") || version.startsWith("5")) {
1094 JLabel ho = new JLabel("<html>"+
1095 tr("<h2>JOSM requires Java version 6.</h2>"+
1096 "Detected Java version: {0}.<br>"+
1097 "You can <ul><li>update your Java (JRE) or</li>"+
1098 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
1099 "More Info:", version)+"</html>");
1100 JTextArea link = new JTextArea(HelpUtil.getWikiBaseHelpUrl()+"/Help/SystemRequirements");
1101 link.setEditable(false);
1102 link.setBackground(panel.getBackground());
1103 JPanel panel = new JPanel(new GridBagLayout());
1104 GridBagConstraints gbc = new GridBagConstraints();
1105 gbc.gridwidth = GridBagConstraints.REMAINDER;
1106 gbc.anchor = GridBagConstraints.WEST;
1107 gbc.weightx = 1.0;
1108 panel.add(ho, gbc);
1109 panel.add(link, gbc);
1110 final String EXIT = tr("Exit JOSM");
1111 final String CONTINUE = tr("Continue, try anyway");
1112 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
1113 if (ret == 0) {
1114 System.exit(0);
1115 }
1116 return;
1117 }
1118 }
1119 error("Could not recognize Java Version: "+version);
1120 }
1121
1122 /* ----------------------------------------------------------------------------------------- */
1123 /* projection handling - Main is a registry for a single, global projection instance */
1124 /* */
1125 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1126 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1127 /* ----------------------------------------------------------------------------------------- */
1128 /**
1129 * The projection method used.
1130 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1131 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
1132 */
1133 private static Projection proj;
1134
1135 /**
1136 * Replies the current projection.
1137 *
1138 * @return the currently active projection
1139 */
1140 public static Projection getProjection() {
1141 return proj;
1142 }
1143
1144 /**
1145 * Sets the current projection
1146 *
1147 * @param p the projection
1148 */
1149 public static void setProjection(Projection p) {
1150 CheckParameterUtil.ensureParameterNotNull(p);
1151 Projection oldValue = proj;
1152 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
1153 proj = p;
1154 fireProjectionChanged(oldValue, proj, b);
1155 }
1156
1157 /*
1158 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1159 * explicitly removing the listeners and allows us to transparently register every
1160 * created dataset as projection change listener.
1161 */
1162 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
1163
1164 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
1165 if (newValue == null ^ oldValue == null
1166 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
1167
1168 synchronized(Main.class) {
1169 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1170 while (it.hasNext()){
1171 WeakReference<ProjectionChangeListener> wr = it.next();
1172 ProjectionChangeListener listener = wr.get();
1173 if (listener == null) {
1174 it.remove();
1175 continue;
1176 }
1177 listener.projectionChanged(oldValue, newValue);
1178 }
1179 }
1180 if (newValue != null && oldBounds != null) {
1181 Main.map.mapView.zoomTo(oldBounds);
1182 }
1183 /* TODO - remove layers with fixed projection */
1184 }
1185 }
1186
1187 /**
1188 * Register a projection change listener.
1189 *
1190 * @param listener the listener. Ignored if <code>null</code>.
1191 */
1192 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1193 if (listener == null) return;
1194 synchronized (Main.class) {
1195 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1196 // already registered ? => abort
1197 if (wr.get() == listener) return;
1198 }
1199 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
1200 }
1201 }
1202
1203 /**
1204 * Removes a projection change listener.
1205 *
1206 * @param listener the listener. Ignored if <code>null</code>.
1207 */
1208 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1209 if (listener == null) return;
1210 synchronized(Main.class){
1211 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1212 while (it.hasNext()){
1213 WeakReference<ProjectionChangeListener> wr = it.next();
1214 // remove the listener - and any other listener which got garbage
1215 // collected in the meantime
1216 if (wr.get() == null || wr.get() == listener) {
1217 it.remove();
1218 }
1219 }
1220 }
1221 }
1222
1223 /**
1224 * Listener for window switch events.
1225 *
1226 * These are events, when the user activates a window of another application
1227 * or comes back to JOSM. Window switches from one JOSM window to another
1228 * are not reported.
1229 */
1230 public static interface WindowSwitchListener {
1231 /**
1232 * Called when the user activates a window of another application.
1233 */
1234 void toOtherApplication();
1235 /**
1236 * Called when the user comes from a window of another application
1237 * back to JOSM.
1238 */
1239 void fromOtherApplication();
1240 }
1241
1242 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<WeakReference<WindowSwitchListener>>();
1243
1244 /**
1245 * Register a window switch listener.
1246 *
1247 * @param listener the listener. Ignored if <code>null</code>.
1248 */
1249 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1250 if (listener == null) return;
1251 synchronized (Main.class) {
1252 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1253 // already registered ? => abort
1254 if (wr.get() == listener) return;
1255 }
1256 boolean wasEmpty = windowSwitchListeners.isEmpty();
1257 windowSwitchListeners.add(new WeakReference<WindowSwitchListener>(listener));
1258 if (wasEmpty) {
1259 // The following call will have no effect, when there is no window
1260 // at the time. Therefore, MasterWindowListener.setup() will also be
1261 // called, as soon as the main window is shown.
1262 MasterWindowListener.setup();
1263 }
1264 }
1265 }
1266
1267 /**
1268 * Removes a window switch listener.
1269 *
1270 * @param listener the listener. Ignored if <code>null</code>.
1271 */
1272 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1273 if (listener == null) return;
1274 synchronized (Main.class){
1275 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1276 while (it.hasNext()){
1277 WeakReference<WindowSwitchListener> wr = it.next();
1278 // remove the listener - and any other listener which got garbage
1279 // collected in the meantime
1280 if (wr.get() == null || wr.get() == listener) {
1281 it.remove();
1282 }
1283 }
1284 if (windowSwitchListeners.isEmpty()) {
1285 MasterWindowListener.teardown();
1286 }
1287 }
1288 }
1289
1290 /**
1291 * WindowListener, that is registered on all Windows of the application.
1292 *
1293 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1294 * another application, e.g. a browser, or back to JOSM.
1295 *
1296 * When changing from JOSM to another application and back (e.g. two times
1297 * alt+tab), the active Window within JOSM may be different.
1298 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1299 * Windows in JOSM, and it does not suffice to monitor the one that was
1300 * deactivated last.
1301 *
1302 * This class is only "active" on demand, i.e. when there is at least one
1303 * WindowSwitchListener registered.
1304 */
1305 protected static class MasterWindowListener extends WindowAdapter {
1306
1307 private static MasterWindowListener INSTANCE;
1308
1309 public static MasterWindowListener getInstance() {
1310 if (INSTANCE == null) {
1311 INSTANCE = new MasterWindowListener();
1312 }
1313 return INSTANCE;
1314 }
1315
1316 /**
1317 * Register listeners to all non-hidden windows.
1318 *
1319 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1320 */
1321 public static void setup() {
1322 if (!windowSwitchListeners.isEmpty()) {
1323 for (Window w : Window.getWindows()) {
1324 if (w.isShowing()) {
1325 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1326 w.addWindowListener(getInstance());
1327 }
1328 }
1329 }
1330 }
1331 }
1332
1333 /**
1334 * Unregister all listeners.
1335 */
1336 public static void teardown() {
1337 for (Window w : Window.getWindows()) {
1338 w.removeWindowListener(getInstance());
1339 }
1340 }
1341
1342 @Override
1343 public void windowActivated(WindowEvent e) {
1344 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1345 // fire WindowSwitchListeners
1346 synchronized (Main.class) {
1347 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1348 while (it.hasNext()){
1349 WeakReference<WindowSwitchListener> wr = it.next();
1350 WindowSwitchListener listener = wr.get();
1351 if (listener == null) {
1352 it.remove();
1353 continue;
1354 }
1355 listener.fromOtherApplication();
1356 }
1357 }
1358 }
1359 }
1360
1361 @Override
1362 public void windowDeactivated(WindowEvent e) {
1363 // set up windows that have been created in the meantime
1364 for (Window w : Window.getWindows()) {
1365 if (!w.isShowing()) {
1366 w.removeWindowListener(getInstance());
1367 } else {
1368 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1369 w.addWindowListener(getInstance());
1370 }
1371 }
1372 }
1373 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1374 // fire WindowSwitchListeners
1375 synchronized (Main.class) {
1376 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1377 while (it.hasNext()){
1378 WeakReference<WindowSwitchListener> wr = it.next();
1379 WindowSwitchListener listener = wr.get();
1380 if (listener == null) {
1381 it.remove();
1382 continue;
1383 }
1384 listener.toOtherApplication();
1385 }
1386 }
1387 }
1388 }
1389 }
1390
1391 /**
1392 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1393 * @param listener The MapFrameListener
1394 * @return {@code true} if the listeners collection changed as a result of the call
1395 * @since 5957
1396 */
1397 public static boolean addMapFrameListener(MapFrameListener listener) {
1398 return listener != null ? mapFrameListeners.add(listener) : false;
1399 }
1400
1401 /**
1402 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1403 * @param listener The MapFrameListener
1404 * @return {@code true} if the listeners collection changed as a result of the call
1405 * @since 5957
1406 */
1407 public static boolean removeMapFrameListener(MapFrameListener listener) {
1408 return listener != null ? mapFrameListeners.remove(listener) : false;
1409 }
1410
1411 /**
1412 * Adds a new network error that occur to give a hint about broken Internet connection.
1413 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1414 *
1415 * @param url The accessed URL that caused the error
1416 * @param t The network error
1417 * @return The previous error associated to the given resource, if any. Can be {@code null}
1418 * @since 6642
1419 */
1420 public static Throwable addNetworkError(URL url, Throwable t) {
1421 if (url != null && t != null) {
1422 Throwable old = addNetworkError(url.toExternalForm(), t);
1423 if (old != null) {
1424 Main.warn("Already here "+old);
1425 }
1426 return old;
1427 }
1428 return null;
1429 }
1430
1431 /**
1432 * Adds a new network error that occur to give a hint about broken Internet connection.
1433 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1434 *
1435 * @param url The accessed URL that caused the error
1436 * @param t The network error
1437 * @return The previous error associated to the given resource, if any. Can be {@code null}
1438 * @since 6642
1439 */
1440 public static Throwable addNetworkError(String url, Throwable t) {
1441 if (url != null && t != null) {
1442 return networkErrors.put(url, t);
1443 }
1444 return null;
1445 }
1446
1447 /**
1448 * Returns the network errors that occured until now.
1449 * @return the network errors that occured until now, indexed by URL
1450 * @since 6639
1451 */
1452 public static Map<String, Throwable> getNetworkErrors() {
1453 return new HashMap<String, Throwable>(networkErrors);
1454 }
1455}
Note: See TracBrowser for help on using the repository browser.