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

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

see #13306, see #13392 - remove Main.isOpenJdk, not used anymore

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