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

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

global replacement of e.printStackTrace() by Main.error(e)

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