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

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

see #11390 - remove non-working java version check as it would need to compile some classes with JDK7

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