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

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

fix #12478, fix #12565, fix #11114 - Use ​Swing Copy/Paste instead of CopyAction/PasteAction with custom buffer (patch by michael2402, modified) - gsoc-core

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