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

Last change on this file since 7816 was 7816, checked in by bastiK, 9 years ago

fixed #10860 - set initial viewport correctly when mapview is opened

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