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

Last change on this file since 9238 was 9238, checked in by stoecker, 8 years ago

see #8562 - restart JOSM in case we switched from IPv6 to IPv4 only, so we have no broken connection

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