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

Last change on this file since 8497 was 8497, checked in by simon04, 9 years ago

fix #11355 - Splash screen: display parallel initialization tasks in a sensible way

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