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

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

sonar - squid:S1641 - Sets with elements that are enum values should be replaced with EnumSet

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