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

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

checkstyle: blocks

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