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

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

see #11843 - Terminate initialization threads

  • Property svn:eol-style set to native
File size: 63.9 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("main-worker-%d", Thread.NORM_PRIORITY);
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 interface InitStatusListener {
532
533 Object updateStatus(String event);
534
535 void finish(Object status);
536 }
537
538 public static void setInitStatusListener(InitStatusListener listener) {
539 CheckParameterUtil.ensureParameterNotNull(listener);
540 initListener = listener;
541 }
542
543 /**
544 * Constructs new {@code Main} object. A lot of global variables are initialized here.
545 */
546 public Main() {
547 main = this;
548 isOpenjdk = System.getProperty("java.vm.name").toUpperCase(Locale.ENGLISH).indexOf("OPENJDK") != -1;
549
550 new InitializationTask(tr("Executing platform startup hook")) {
551 @Override
552 public void initialize() {
553 platform.startupHook();
554 }
555 }.call();
556
557 new InitializationTask(tr("Building main menu")) {
558
559 @Override
560 public void initialize() {
561 contentPanePrivate.add(panel, BorderLayout.CENTER);
562 panel.add(gettingStarted, BorderLayout.CENTER);
563 menu = new MainMenu();
564 }
565 }.call();
566
567 undoRedo.addCommandQueueListener(redoUndoListener);
568
569 // creating toolbar
570 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
571
572 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
573 KeyEvent.VK_F1, Shortcut.DIRECT));
574
575 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
576 List<Callable<Void>> tasks = new ArrayList<>();
577
578 tasks.add(new InitializationTask(tr("Initializing OSM API")) {
579
580 @Override
581 public void initialize() {
582 // We try to establish an API connection early, so that any API
583 // capabilities are already known to the editor instance. However
584 // if it goes wrong that's not critical at this stage.
585 try {
586 OsmApi.getOsmApi().initialize(null, true);
587 } catch (Exception e) {
588 Main.warn(getErrorMessage(Utils.getRootCause(e)));
589 }
590 }
591 });
592
593 tasks.add(new InitializationTask(tr("Initializing validator")) {
594
595 @Override
596 public void initialize() {
597 validator = new OsmValidator();
598 MapView.addLayerChangeListener(validator);
599 }
600 });
601
602 tasks.add(new InitializationTask(tr("Initializing presets")) {
603
604 @Override
605 public void initialize() {
606 TaggingPresets.initialize();
607 }
608 });
609
610 tasks.add(new InitializationTask(tr("Initializing map styles")) {
611
612 @Override
613 public void initialize() {
614 MapPaintPreference.initialize();
615 }
616 });
617
618 tasks.add(new InitializationTask(tr("Loading imagery preferences")) {
619
620 @Override
621 public void initialize() {
622 ImageryPreference.initialize();
623 }
624 });
625
626 try {
627 final ExecutorService service = Executors.newFixedThreadPool(
628 Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
629 for (Future<Void> i : service.invokeAll(tasks)) {
630 i.get();
631 }
632 service.shutdown();
633 } catch (Exception ex) {
634 throw new RuntimeException(ex);
635 }
636
637 // hooks for the jmapviewer component
638 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
639 @Override
640 public void openLink(String url) {
641 OpenBrowser.displayUrl(url);
642 }
643 });
644 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
645 FeatureAdapter.registerLoggingAdapter(new FeatureAdapter.LoggingAdapter() {
646 @Override
647 public Logger getLogger(String name) {
648 Logger logger = Logger.getAnonymousLogger();
649 logger.setUseParentHandlers(false);
650 logger.setLevel(Level.ALL);
651 if (logger.getHandlers().length == 0) {
652 logger.addHandler(new Handler() {
653 @Override
654 public void publish(LogRecord record) {
655 String msg = MessageFormat.format(record.getMessage(), record.getParameters());
656 if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
657 Main.error(msg);
658 } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
659 Main.warn(msg);
660 } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
661 Main.info(msg);
662 } else if (record.getLevel().intValue() >= Level.FINE.intValue()) {
663 Main.debug(msg);
664 } else {
665 Main.trace(msg);
666 }
667 }
668
669 @Override
670 public void flush() {
671 }
672
673 @Override
674 public void close() {
675 }
676 });
677 }
678 return logger;
679 }
680 });
681
682 new InitializationTask(tr("Updating user interface")) {
683
684 @Override
685 public void initialize() {
686 toolbar.refreshToolbarControl();
687 toolbar.control.updateUI();
688 contentPanePrivate.updateUI();
689 }
690 }.call();
691 }
692
693 private abstract class InitializationTask implements Callable<Void> {
694
695 private final String name;
696
697 protected InitializationTask(String name) {
698 this.name = name;
699 }
700
701 public abstract void initialize();
702
703 @Override
704 public Void call() {
705 Object status = null;
706 if (initListener != null) {
707 status = initListener.updateStatus(name);
708 }
709 initialize();
710 if (initListener != null) {
711 initListener.finish(status);
712 }
713 return null;
714 }
715 }
716
717 /**
718 * Add a new layer to the map.
719 *
720 * If no map exists, create one.
721 *
722 * @param layer the layer
723 *
724 * @see #addLayer(Layer, ProjectionBounds)
725 * @see #addLayer(Layer, ViewportData)
726 */
727 public final void addLayer(final Layer layer) {
728 BoundingXYVisitor v = new BoundingXYVisitor();
729 layer.visitBoundingBox(v);
730 addLayer(layer, v.getBounds());
731 }
732
733 /**
734 * Add a new layer to the map.
735 *
736 * If no map exists, create one.
737 *
738 * @param layer the layer
739 * @param bounds the bounds of the layer (target zoom area); can be null, then
740 * the viewport isn't changed
741 */
742 public final synchronized void addLayer(final Layer layer, ProjectionBounds bounds) {
743 addLayer(layer, bounds == null ? null : new ViewportData(bounds));
744 }
745
746 /**
747 * Add a new layer to the map.
748 *
749 * If no map exists, create one.
750 *
751 * @param layer the layer
752 * @param viewport the viewport to zoom to; can be null, then the viewport
753 * isn't changed
754 */
755 public final synchronized void addLayer(final Layer layer, ViewportData viewport) {
756 boolean noMap = map == null;
757 if (noMap) {
758 createMapFrame(layer, viewport);
759 }
760 layer.hookUpMapView();
761 map.mapView.addLayer(layer);
762 if (noMap) {
763 Main.map.setVisible(true);
764 } else if (viewport != null) {
765 Main.map.mapView.zoomTo(viewport);
766 }
767 }
768
769 public synchronized void createMapFrame(Layer firstLayer, ViewportData viewportData) {
770 MapFrame mapFrame = new MapFrame(contentPanePrivate, viewportData);
771 setMapFrame(mapFrame);
772 if (firstLayer != null) {
773 mapFrame.selectMapMode((MapMode) mapFrame.getDefaultButtonAction(), firstLayer);
774 }
775 mapFrame.initializeDialogsPane();
776 // bootstrapping problem: make sure the layer list dialog is going to
777 // listen to change events of the very first layer
778 //
779 if (firstLayer != null) {
780 firstLayer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
781 }
782 }
783
784 /**
785 * Replies <code>true</code> if there is an edit layer
786 *
787 * @return <code>true</code> if there is an edit layer
788 */
789 public boolean hasEditLayer() {
790 if (getEditLayer() == null) return false;
791 return true;
792 }
793
794 /**
795 * Replies the current edit layer
796 *
797 * @return the current edit layer. <code>null</code>, if no current edit layer exists
798 */
799 public OsmDataLayer getEditLayer() {
800 if (!isDisplayingMapView()) return null;
801 return map.mapView.getEditLayer();
802 }
803
804 /**
805 * Replies the current data set.
806 *
807 * @return the current data set. <code>null</code>, if no current data set exists
808 */
809 public DataSet getCurrentDataSet() {
810 if (!hasEditLayer()) return null;
811 return getEditLayer().data;
812 }
813
814 /**
815 * Replies the current selected primitives, from a end-user point of view.
816 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
817 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
818 * see {@link DrawAction#getInProgressSelection()}.
819 *
820 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
821 * @since 6546
822 */
823 public Collection<OsmPrimitive> getInProgressSelection() {
824 if (map != null && map.mapMode instanceof DrawAction) {
825 return ((DrawAction) map.mapMode).getInProgressSelection();
826 } else {
827 DataSet ds = getCurrentDataSet();
828 if (ds == null) return null;
829 return ds.getSelected();
830 }
831 }
832
833 /**
834 * Returns the currently active layer
835 *
836 * @return the currently active layer. <code>null</code>, if currently no active layer exists
837 */
838 public Layer getActiveLayer() {
839 if (!isDisplayingMapView()) return null;
840 return map.mapView.getActiveLayer();
841 }
842
843 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
844
845 public static void redirectToMainContentPane(JComponent source) {
846 RedirectInputMap.redirect(source, contentPanePrivate);
847 }
848
849 public static void registerActionShortcut(JosmAction action) {
850 registerActionShortcut(action, action.getShortcut());
851 }
852
853 public static void registerActionShortcut(Action action, Shortcut shortcut) {
854 KeyStroke keyStroke = shortcut.getKeyStroke();
855 if (keyStroke == null)
856 return;
857
858 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
859 Object existing = inputMap.get(keyStroke);
860 if (existing != null && !existing.equals(action)) {
861 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
862 }
863 inputMap.put(keyStroke, action);
864
865 contentPanePrivate.getActionMap().put(action, action);
866 }
867
868 public static void unregisterShortcut(Shortcut shortcut) {
869 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
870 }
871
872 public static void unregisterActionShortcut(JosmAction action) {
873 unregisterActionShortcut(action, action.getShortcut());
874 }
875
876 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
877 unregisterShortcut(shortcut);
878 contentPanePrivate.getActionMap().remove(action);
879 }
880
881 /**
882 * Replies the registered action for the given shortcut
883 * @param shortcut The shortcut to look for
884 * @return the registered action for the given shortcut
885 * @since 5696
886 */
887 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
888 KeyStroke keyStroke = shortcut.getKeyStroke();
889 if (keyStroke == null)
890 return null;
891 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
892 if (action instanceof Action)
893 return (Action) action;
894 return null;
895 }
896
897 ///////////////////////////////////////////////////////////////////////////
898 // Implementation part
899 ///////////////////////////////////////////////////////////////////////////
900
901 /**
902 * Global panel.
903 */
904 public static final JPanel panel = new JPanel(new BorderLayout());
905
906 protected static volatile WindowGeometry geometry;
907 protected static int windowState = JFrame.NORMAL;
908
909 private final CommandQueueListener redoUndoListener = new CommandQueueListener() {
910 @Override
911 public void commandChanged(final int queueSize, final int redoSize) {
912 menu.undo.setEnabled(queueSize > 0);
913 menu.redo.setEnabled(redoSize > 0);
914 }
915 };
916
917 /**
918 * Should be called before the main constructor to setup some parameter stuff
919 * @param args The parsed argument list.
920 */
921 public static void preConstructorInit(Map<Option, Collection<String>> args) {
922 ProjectionPreference.setProjection();
923
924 try {
925 String defaultlaf = platform.getDefaultStyle();
926 String laf = Main.pref.get("laf", defaultlaf);
927 try {
928 UIManager.setLookAndFeel(laf);
929 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
930 // Try to find look and feel in plugin classloaders
931 Class<?> klass = null;
932 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
933 try {
934 klass = cl.loadClass(laf);
935 break;
936 } catch (ClassNotFoundException ex) {
937 // Do nothing
938 if (Main.isTraceEnabled()) {
939 Main.trace(ex.getMessage());
940 }
941 }
942 }
943 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
944 try {
945 UIManager.setLookAndFeel((LookAndFeel) klass.newInstance());
946 } catch (Exception ex) {
947 warn("Cannot set Look and Feel: " + laf + ": "+ex.getMessage());
948 }
949 } else {
950 info("Look and Feel not found: " + laf);
951 Main.pref.put("laf", defaultlaf);
952 }
953 } catch (final UnsupportedLookAndFeelException e) {
954 info("Look and Feel not supported: " + laf);
955 Main.pref.put("laf", defaultlaf);
956 }
957 toolbar = new ToolbarPreferences();
958 contentPanePrivate.updateUI();
959 panel.updateUI();
960 } catch (final Exception e) {
961 error(e);
962 }
963 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
964 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
965 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
966 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
967
968 I18n.translateJavaInternalMessages();
969
970 // init default coordinate format
971 //
972 try {
973 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
974 } catch (IllegalArgumentException iae) {
975 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
976 }
977
978 geometry = WindowGeometry.mainWindow("gui.geometry",
979 args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null,
980 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
981 }
982
983 protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
984 if (args.containsKey(Option.DOWNLOAD)) {
985 List<File> fileList = new ArrayList<>();
986 for (String s : args.get(Option.DOWNLOAD)) {
987 File f = null;
988 switch(paramType(s)) {
989 case httpUrl:
990 downloadFromParamHttp(false, s);
991 break;
992 case bounds:
993 downloadFromParamBounds(false, s);
994 break;
995 case fileUrl:
996 try {
997 f = new File(new URI(s));
998 } catch (URISyntaxException e) {
999 JOptionPane.showMessageDialog(
1000 Main.parent,
1001 tr("Ignoring malformed file URL: \"{0}\"", s),
1002 tr("Warning"),
1003 JOptionPane.WARNING_MESSAGE
1004 );
1005 }
1006 if (f != null) {
1007 fileList.add(f);
1008 }
1009 break;
1010 case fileName:
1011 f = new File(s);
1012 fileList.add(f);
1013 break;
1014 }
1015 }
1016 if (!fileList.isEmpty()) {
1017 OpenFileAction.openFiles(fileList, true);
1018 }
1019 }
1020 if (args.containsKey(Option.DOWNLOADGPS)) {
1021 for (String s : args.get(Option.DOWNLOADGPS)) {
1022 switch(paramType(s)) {
1023 case httpUrl:
1024 downloadFromParamHttp(true, s);
1025 break;
1026 case bounds:
1027 downloadFromParamBounds(true, s);
1028 break;
1029 case fileUrl:
1030 case fileName:
1031 JOptionPane.showMessageDialog(
1032 Main.parent,
1033 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
1034 tr("Warning"),
1035 JOptionPane.WARNING_MESSAGE
1036 );
1037 }
1038 }
1039 }
1040 if (args.containsKey(Option.SELECTION)) {
1041 for (String s : args.get(Option.SELECTION)) {
1042 SearchAction.search(s, SearchAction.SearchMode.add);
1043 }
1044 }
1045 }
1046
1047 /**
1048 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) for all
1049 * {@link AbstractModifiableLayer} before JOSM exits.
1050 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations.
1051 * {@code false} if the user cancels.
1052 * @since 2025
1053 */
1054 public static boolean saveUnsavedModifications() {
1055 if (!isDisplayingMapView()) return true;
1056 return saveUnsavedModifications(map.mapView.getLayersOfType(AbstractModifiableLayer.class), true);
1057 }
1058
1059 /**
1060 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) before data layers deletion.
1061 *
1062 * @param selectedLayers The layers to check. Only instances of {@link AbstractModifiableLayer} are considered.
1063 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
1064 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations.
1065 * {@code false} if the user cancels.
1066 * @since 5519
1067 */
1068 public static boolean saveUnsavedModifications(Iterable<? extends Layer> selectedLayers, boolean exit) {
1069 SaveLayersDialog dialog = new SaveLayersDialog(parent);
1070 List<AbstractModifiableLayer> layersWithUnmodifiedChanges = new ArrayList<>();
1071 for (Layer l: selectedLayers) {
1072 if (!(l instanceof AbstractModifiableLayer)) {
1073 continue;
1074 }
1075 AbstractModifiableLayer odl = (AbstractModifiableLayer) l;
1076 if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.isModified()) {
1077 layersWithUnmodifiedChanges.add(odl);
1078 }
1079 }
1080 if (exit) {
1081 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
1082 } else {
1083 dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
1084 }
1085 if (!layersWithUnmodifiedChanges.isEmpty()) {
1086 dialog.getModel().populate(layersWithUnmodifiedChanges);
1087 dialog.setVisible(true);
1088 switch(dialog.getUserAction()) {
1089 case PROCEED: return true;
1090 case CANCEL:
1091 default: return false;
1092 }
1093 }
1094
1095 return true;
1096 }
1097
1098 /**
1099 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
1100 * If there are some unsaved data layers, asks first for user confirmation.
1101 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
1102 * @param exitCode The return code
1103 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
1104 * @since 3378
1105 */
1106 public static boolean exitJosm(boolean exit, int exitCode) {
1107 if (Main.saveUnsavedModifications()) {
1108 worker.shutdown();
1109 ImageProvider.shutdown(false);
1110 JCSCacheManager.shutdown();
1111 geometry.remember("gui.geometry");
1112 if (map != null) {
1113 map.rememberToggleDialogWidth();
1114 }
1115 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
1116 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
1117 if (Main.isDisplayingMapView()) {
1118 Collection<Layer> layers = new ArrayList<>(Main.map.mapView.getAllLayers());
1119 for (Layer l: layers) {
1120 Main.main.removeLayer(l);
1121 }
1122 }
1123 worker.shutdownNow();
1124 ImageProvider.shutdown(true);
1125
1126 if (exit) {
1127 System.exit(exitCode);
1128 }
1129 return true;
1130 }
1131 return false;
1132 }
1133
1134 /**
1135 * The type of a command line parameter, to be used in switch statements.
1136 * @see #paramType
1137 */
1138 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
1139
1140 /**
1141 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
1142 * @param s A parameter string
1143 * @return The guessed parameter type
1144 */
1145 private static DownloadParamType paramType(String s) {
1146 if (s.startsWith("http:") || s.startsWith("https:")) return DownloadParamType.httpUrl;
1147 if (s.startsWith("file:")) return DownloadParamType.fileUrl;
1148 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
1149 if (s.matches(coorPattern+"(,"+coorPattern+") {3}")) return DownloadParamType.bounds;
1150 // everything else must be a file name
1151 return DownloadParamType.fileName;
1152 }
1153
1154 /**
1155 * Download area specified on the command line as OSM URL.
1156 * @param rawGps Flag to download raw GPS tracks
1157 * @param s The URL parameter
1158 */
1159 private static void downloadFromParamHttp(final boolean rawGps, String s) {
1160 final Bounds b = OsmUrlToBounds.parse(s);
1161 if (b == null) {
1162 JOptionPane.showMessageDialog(
1163 Main.parent,
1164 tr("Ignoring malformed URL: \"{0}\"", s),
1165 tr("Warning"),
1166 JOptionPane.WARNING_MESSAGE
1167 );
1168 } else {
1169 downloadFromParamBounds(rawGps, b);
1170 }
1171 }
1172
1173 /**
1174 * Download area specified on the command line as bounds string.
1175 * @param rawGps Flag to download raw GPS tracks
1176 * @param s The bounds parameter
1177 */
1178 private static void downloadFromParamBounds(final boolean rawGps, String s) {
1179 final StringTokenizer st = new StringTokenizer(s, ",");
1180 if (st.countTokens() == 4) {
1181 Bounds b = new Bounds(
1182 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())),
1183 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))
1184 );
1185 downloadFromParamBounds(rawGps, b);
1186 }
1187 }
1188
1189 /**
1190 * Download area specified as Bounds value.
1191 * @param rawGps Flag to download raw GPS tracks
1192 * @param b The bounds value
1193 * @see #downloadFromParamBounds(boolean, String)
1194 * @see #downloadFromParamHttp
1195 */
1196 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
1197 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1198 // asynchronously launch the download task ...
1199 Future<?> future = task.download(true, b, null);
1200 // ... and the continuation when the download is finished (this will wait for the download to finish)
1201 Main.worker.execute(new PostDownloadHandler(task, future));
1202 }
1203
1204 /**
1205 * Identifies the current operating system family and initializes the platform hook accordingly.
1206 * @since 1849
1207 */
1208 public static void determinePlatformHook() {
1209 String os = System.getProperty("os.name");
1210 if (os == null) {
1211 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
1212 platform = new PlatformHookUnixoid();
1213 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("windows")) {
1214 platform = new PlatformHookWindows();
1215 } else if ("Linux".equals(os) || "Solaris".equals(os) ||
1216 "SunOS".equals(os) || "AIX".equals(os) ||
1217 "FreeBSD".equals(os) || "NetBSD".equals(os) || "OpenBSD".equals(os)) {
1218 platform = new PlatformHookUnixoid();
1219 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("mac os x")) {
1220 platform = new PlatformHookOsx();
1221 } else {
1222 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
1223 platform = new PlatformHookUnixoid();
1224 }
1225 }
1226
1227 private static class WindowPositionSizeListener extends WindowAdapter implements
1228 ComponentListener {
1229 @Override
1230 public void windowStateChanged(WindowEvent e) {
1231 Main.windowState = e.getNewState();
1232 }
1233
1234 @Override
1235 public void componentHidden(ComponentEvent e) {
1236 }
1237
1238 @Override
1239 public void componentMoved(ComponentEvent e) {
1240 handleComponentEvent(e);
1241 }
1242
1243 @Override
1244 public void componentResized(ComponentEvent e) {
1245 handleComponentEvent(e);
1246 }
1247
1248 @Override
1249 public void componentShown(ComponentEvent e) {
1250 }
1251
1252 private void handleComponentEvent(ComponentEvent e) {
1253 Component c = e.getComponent();
1254 if (c instanceof JFrame && c.isVisible()) {
1255 if (Main.windowState == JFrame.NORMAL) {
1256 Main.geometry = new WindowGeometry((JFrame) c);
1257 } else {
1258 Main.geometry.fixScreen((JFrame) c);
1259 }
1260 }
1261 }
1262 }
1263
1264 protected static void addListener() {
1265 parent.addComponentListener(new WindowPositionSizeListener());
1266 ((JFrame) parent).addWindowStateListener(new WindowPositionSizeListener());
1267 }
1268
1269 /**
1270 * Determines if JOSM currently runs with Java 8 or later.
1271 * @return {@code true} if the current JVM is at least Java 8, {@code false} otherwise
1272 * @since 7894
1273 */
1274 public static boolean isJava8orLater() {
1275 String version = System.getProperty("java.version");
1276 return version != null && !version.matches("^(1\\.)?[7].*");
1277 }
1278
1279 /**
1280 * Checks that JOSM is at least running with Java 7.
1281 * @since 7001
1282 */
1283 public static void checkJavaVersion() {
1284 String version = System.getProperty("java.version");
1285 if (version != null) {
1286 if (version.matches("^(1\\.)?[789].*"))
1287 return;
1288 if (version.matches("^(1\\.)?[56].*")) {
1289 JMultilineLabel ho = new JMultilineLabel("<html>"+
1290 tr("<h2>JOSM requires Java version {0}.</h2>"+
1291 "Detected Java version: {1}.<br>"+
1292 "You can <ul><li>update your Java (JRE) or</li>"+
1293 "<li>use an earlier (Java {2} compatible) version of JOSM.</li></ul>"+
1294 "More Info:", "7", version, "6")+"</html>");
1295 JTextArea link = new JTextArea(HelpUtil.getWikiBaseHelpUrl()+"/Help/SystemRequirements");
1296 link.setEditable(false);
1297 link.setBackground(panel.getBackground());
1298 JPanel panel = new JPanel(new GridBagLayout());
1299 GridBagConstraints gbc = new GridBagConstraints();
1300 gbc.gridwidth = GridBagConstraints.REMAINDER;
1301 gbc.anchor = GridBagConstraints.WEST;
1302 gbc.weightx = 1.0;
1303 panel.add(ho, gbc);
1304 panel.add(link, gbc);
1305 final String EXIT = tr("Exit JOSM");
1306 final String CONTINUE = tr("Continue, try anyway");
1307 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION,
1308 JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
1309 if (ret == 0) {
1310 System.exit(0);
1311 }
1312 return;
1313 }
1314 }
1315 error("Could not recognize Java Version: "+version);
1316 }
1317
1318 /* ----------------------------------------------------------------------------------------- */
1319 /* projection handling - Main is a registry for a single, global projection instance */
1320 /* */
1321 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1322 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1323 /* ----------------------------------------------------------------------------------------- */
1324 /**
1325 * The projection method used.
1326 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1327 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
1328 */
1329 private static volatile Projection proj;
1330
1331 /**
1332 * Replies the current projection.
1333 *
1334 * @return the currently active projection
1335 */
1336 public static Projection getProjection() {
1337 return proj;
1338 }
1339
1340 /**
1341 * Sets the current projection
1342 *
1343 * @param p the projection
1344 */
1345 public static void setProjection(Projection p) {
1346 CheckParameterUtil.ensureParameterNotNull(p);
1347 Projection oldValue = proj;
1348 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
1349 proj = p;
1350 fireProjectionChanged(oldValue, proj, b);
1351 }
1352
1353 /*
1354 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1355 * explicitly removing the listeners and allows us to transparently register every
1356 * created dataset as projection change listener.
1357 */
1358 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
1359
1360 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
1361 if (newValue == null ^ oldValue == null
1362 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
1363
1364 synchronized (Main.class) {
1365 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1366 while (it.hasNext()) {
1367 WeakReference<ProjectionChangeListener> wr = it.next();
1368 ProjectionChangeListener listener = wr.get();
1369 if (listener == null) {
1370 it.remove();
1371 continue;
1372 }
1373 listener.projectionChanged(oldValue, newValue);
1374 }
1375 }
1376 if (newValue != null && oldBounds != null) {
1377 Main.map.mapView.zoomTo(oldBounds);
1378 }
1379 /* TODO - remove layers with fixed projection */
1380 }
1381 }
1382
1383 /**
1384 * Register a projection change listener.
1385 *
1386 * @param listener the listener. Ignored if <code>null</code>.
1387 */
1388 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1389 if (listener == null) return;
1390 synchronized (Main.class) {
1391 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1392 // already registered ? => abort
1393 if (wr.get() == listener) return;
1394 }
1395 listeners.add(new WeakReference<>(listener));
1396 }
1397 }
1398
1399 /**
1400 * Removes a projection change listener.
1401 *
1402 * @param listener the listener. Ignored if <code>null</code>.
1403 */
1404 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1405 if (listener == null) return;
1406 synchronized (Main.class) {
1407 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1408 while (it.hasNext()) {
1409 WeakReference<ProjectionChangeListener> wr = it.next();
1410 // remove the listener - and any other listener which got garbage
1411 // collected in the meantime
1412 if (wr.get() == null || wr.get() == listener) {
1413 it.remove();
1414 }
1415 }
1416 }
1417 }
1418
1419 /**
1420 * Listener for window switch events.
1421 *
1422 * These are events, when the user activates a window of another application
1423 * or comes back to JOSM. Window switches from one JOSM window to another
1424 * are not reported.
1425 */
1426 public interface WindowSwitchListener {
1427 /**
1428 * Called when the user activates a window of another application.
1429 */
1430 void toOtherApplication();
1431 /**
1432 * Called when the user comes from a window of another application
1433 * back to JOSM.
1434 */
1435 void fromOtherApplication();
1436 }
1437
1438 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<>();
1439
1440 /**
1441 * Register a window switch listener.
1442 *
1443 * @param listener the listener. Ignored if <code>null</code>.
1444 */
1445 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1446 if (listener == null) return;
1447 synchronized (Main.class) {
1448 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1449 // already registered ? => abort
1450 if (wr.get() == listener) return;
1451 }
1452 boolean wasEmpty = windowSwitchListeners.isEmpty();
1453 windowSwitchListeners.add(new WeakReference<>(listener));
1454 if (wasEmpty) {
1455 // The following call will have no effect, when there is no window
1456 // at the time. Therefore, MasterWindowListener.setup() will also be
1457 // called, as soon as the main window is shown.
1458 MasterWindowListener.setup();
1459 }
1460 }
1461 }
1462
1463 /**
1464 * Removes a window switch listener.
1465 *
1466 * @param listener the listener. Ignored if <code>null</code>.
1467 */
1468 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1469 if (listener == null) return;
1470 synchronized (Main.class) {
1471 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1472 while (it.hasNext()) {
1473 WeakReference<WindowSwitchListener> wr = it.next();
1474 // remove the listener - and any other listener which got garbage
1475 // collected in the meantime
1476 if (wr.get() == null || wr.get() == listener) {
1477 it.remove();
1478 }
1479 }
1480 if (windowSwitchListeners.isEmpty()) {
1481 MasterWindowListener.teardown();
1482 }
1483 }
1484 }
1485
1486 /**
1487 * WindowListener, that is registered on all Windows of the application.
1488 *
1489 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1490 * another application, e.g. a browser, or back to JOSM.
1491 *
1492 * When changing from JOSM to another application and back (e.g. two times
1493 * alt+tab), the active Window within JOSM may be different.
1494 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1495 * Windows in JOSM, and it does not suffice to monitor the one that was
1496 * deactivated last.
1497 *
1498 * This class is only "active" on demand, i.e. when there is at least one
1499 * WindowSwitchListener registered.
1500 */
1501 protected static class MasterWindowListener extends WindowAdapter {
1502
1503 private static MasterWindowListener INSTANCE;
1504
1505 public static synchronized MasterWindowListener getInstance() {
1506 if (INSTANCE == null) {
1507 INSTANCE = new MasterWindowListener();
1508 }
1509 return INSTANCE;
1510 }
1511
1512 /**
1513 * Register listeners to all non-hidden windows.
1514 *
1515 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1516 */
1517 public static void setup() {
1518 if (!windowSwitchListeners.isEmpty()) {
1519 for (Window w : Window.getWindows()) {
1520 if (w.isShowing()) {
1521 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1522 w.addWindowListener(getInstance());
1523 }
1524 }
1525 }
1526 }
1527 }
1528
1529 /**
1530 * Unregister all listeners.
1531 */
1532 public static void teardown() {
1533 for (Window w : Window.getWindows()) {
1534 w.removeWindowListener(getInstance());
1535 }
1536 }
1537
1538 @Override
1539 public void windowActivated(WindowEvent e) {
1540 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1541 // fire WindowSwitchListeners
1542 synchronized (Main.class) {
1543 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1544 while (it.hasNext()) {
1545 WeakReference<WindowSwitchListener> wr = it.next();
1546 WindowSwitchListener listener = wr.get();
1547 if (listener == null) {
1548 it.remove();
1549 continue;
1550 }
1551 listener.fromOtherApplication();
1552 }
1553 }
1554 }
1555 }
1556
1557 @Override
1558 public void windowDeactivated(WindowEvent e) {
1559 // set up windows that have been created in the meantime
1560 for (Window w : Window.getWindows()) {
1561 if (!w.isShowing()) {
1562 w.removeWindowListener(getInstance());
1563 } else {
1564 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1565 w.addWindowListener(getInstance());
1566 }
1567 }
1568 }
1569 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1570 // fire WindowSwitchListeners
1571 synchronized (Main.class) {
1572 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1573 while (it.hasNext()) {
1574 WeakReference<WindowSwitchListener> wr = it.next();
1575 WindowSwitchListener listener = wr.get();
1576 if (listener == null) {
1577 it.remove();
1578 continue;
1579 }
1580 listener.toOtherApplication();
1581 }
1582 }
1583 }
1584 }
1585 }
1586
1587 /**
1588 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1589 * @param listener The MapFrameListener
1590 * @param fireWhenMapViewPresent If true, will fire an initial mapFrameInitialized event
1591 * when the MapFrame is present. Otherwise will only fire when the MapFrame is created
1592 * or destroyed.
1593 * @return {@code true} if the listeners collection changed as a result of the call
1594 */
1595 public static boolean addMapFrameListener(MapFrameListener listener, boolean fireWhenMapViewPresent) {
1596 boolean changed = listener != null ? mapFrameListeners.add(listener) : false;
1597 if (fireWhenMapViewPresent && changed && map != null) {
1598 listener.mapFrameInitialized(null, map);
1599 }
1600 return changed;
1601 }
1602
1603 /**
1604 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1605 * @param listener The MapFrameListener
1606 * @return {@code true} if the listeners collection changed as a result of the call
1607 * @since 5957
1608 */
1609 public static boolean addMapFrameListener(MapFrameListener listener) {
1610 return addMapFrameListener(listener, false);
1611 }
1612
1613 /**
1614 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1615 * @param listener The MapFrameListener
1616 * @return {@code true} if the listeners collection changed as a result of the call
1617 * @since 5957
1618 */
1619 public static boolean removeMapFrameListener(MapFrameListener listener) {
1620 return listener != null ? mapFrameListeners.remove(listener) : false;
1621 }
1622
1623 /**
1624 * Adds a new network error that occur to give a hint about broken Internet connection.
1625 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1626 *
1627 * @param url The accessed URL that caused the error
1628 * @param t The network error
1629 * @return The previous error associated to the given resource, if any. Can be {@code null}
1630 * @since 6642
1631 */
1632 public static Throwable addNetworkError(URL url, Throwable t) {
1633 if (url != null && t != null) {
1634 Throwable old = addNetworkError(url.toExternalForm(), t);
1635 if (old != null) {
1636 Main.warn("Already here "+old);
1637 }
1638 return old;
1639 }
1640 return null;
1641 }
1642
1643 /**
1644 * Adds a new network error that occur to give a hint about broken Internet connection.
1645 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1646 *
1647 * @param url The accessed URL that caused the error
1648 * @param t The network error
1649 * @return The previous error associated to the given resource, if any. Can be {@code null}
1650 * @since 6642
1651 */
1652 public static Throwable addNetworkError(String url, Throwable t) {
1653 if (url != null && t != null) {
1654 return NETWORK_ERRORS.put(url, t);
1655 }
1656 return null;
1657 }
1658
1659 /**
1660 * Returns the network errors that occured until now.
1661 * @return the network errors that occured until now, indexed by URL
1662 * @since 6639
1663 */
1664 public static Map<String, Throwable> getNetworkErrors() {
1665 return new HashMap<>(NETWORK_ERRORS);
1666 }
1667
1668 /**
1669 * Returns the command-line arguments used to run the application.
1670 * @return the command-line arguments used to run the application
1671 * @since 8356
1672 */
1673 public static List<String> getCommandLineArgs() {
1674 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
1675 }
1676
1677 /**
1678 * Returns the JOSM website URL.
1679 * @return the josm website URL
1680 * @since 6897
1681 */
1682 public static String getJOSMWebsite() {
1683 if (Main.pref != null)
1684 return Main.pref.get("josm.url", JOSM_WEBSITE);
1685 return JOSM_WEBSITE;
1686 }
1687
1688 /**
1689 * Returns the JOSM XML URL.
1690 * @return the josm XML URL
1691 * @since 6897
1692 */
1693 public static String getXMLBase() {
1694 // Always return HTTP (issues reported with HTTPS)
1695 return "http://josm.openstreetmap.de";
1696 }
1697
1698 /**
1699 * Returns the OSM website URL.
1700 * @return the OSM website URL
1701 * @since 6897
1702 */
1703 public static String getOSMWebsite() {
1704 if (Main.pref != null)
1705 return Main.pref.get("osm.url", OSM_WEBSITE);
1706 return OSM_WEBSITE;
1707 }
1708
1709 /**
1710 * Replies the base URL for browsing information about a primitive.
1711 * @return the base URL, i.e. https://www.openstreetmap.org
1712 * @since 7678
1713 */
1714 public static String getBaseBrowseUrl() {
1715 if (Main.pref != null)
1716 return Main.pref.get("osm-browse.url", getOSMWebsite());
1717 return getOSMWebsite();
1718 }
1719
1720 /**
1721 * Replies the base URL for browsing information about a user.
1722 * @return the base URL, i.e. https://www.openstreetmap.org/user
1723 * @since 7678
1724 */
1725 public static String getBaseUserUrl() {
1726 if (Main.pref != null)
1727 return Main.pref.get("osm-user.url", getOSMWebsite() + "/user");
1728 return getOSMWebsite() + "/user";
1729 }
1730
1731 /**
1732 * Determines if we are currently running on OSX.
1733 * @return {@code true} if we are currently running on OSX
1734 * @since 6957
1735 */
1736 public static boolean isPlatformOsx() {
1737 return Main.platform instanceof PlatformHookOsx;
1738 }
1739
1740 /**
1741 * Determines if we are currently running on Windows.
1742 * @return {@code true} if we are currently running on Windows
1743 * @since 7335
1744 */
1745 public static boolean isPlatformWindows() {
1746 return Main.platform instanceof PlatformHookWindows;
1747 }
1748
1749 /**
1750 * Determines if the given online resource is currently offline.
1751 * @param r the online resource
1752 * @return {@code true} if {@code r} is offline and should not be accessed
1753 * @since 7434
1754 */
1755 public static boolean isOffline(OnlineResource r) {
1756 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1757 }
1758
1759 /**
1760 * Sets the given online resource to offline state.
1761 * @param r the online resource
1762 * @return {@code true} if {@code r} was not already offline
1763 * @since 7434
1764 */
1765 public static boolean setOffline(OnlineResource r) {
1766 return OFFLINE_RESOURCES.add(r);
1767 }
1768
1769 /**
1770 * Sets the given online resource to online state.
1771 * @param r the online resource
1772 * @return {@code true} if {@code r} was offline
1773 * @since 8506
1774 */
1775 public static boolean setOnline(OnlineResource r) {
1776 return OFFLINE_RESOURCES.remove(r);
1777 }
1778
1779 /**
1780 * Replies the set of online resources currently offline.
1781 * @return the set of online resources currently offline
1782 * @since 7434
1783 */
1784 public static Set<OnlineResource> getOfflineResources() {
1785 return new HashSet<>(OFFLINE_RESOURCES);
1786 }
1787}
Note: See TracBrowser for help on using the repository browser.