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

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

sonar - squid:CallToDeprecatedMethod - remove calls to deprecated methods

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