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

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

see #12472 - fix warning "OperatorPrecedence"

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