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

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

fix #13309 - fix unit tests (patch by michael2402) - gsoc-core

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