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

Last change on this file since 8925 was 8870, checked in by Don-vip, 9 years ago

sonar - squid:S2325 - "private" methods that don't access instance data should be "static"

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