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

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

adjust number of errors/warnings in bug reports to avoid incomplete stacktraces

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