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

Last change on this file since 10781 was 10759, checked in by Don-vip, 8 years ago

sonar - squid:S2440 - Classes with only "static" methods should not be instantiated

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