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

Last change on this file since 11660 was 11656, checked in by Don-vip, 7 years ago

FindBugs - ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD

  • Property svn:eol-style set to native
File size: 54.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.BorderLayout;
7import java.awt.Component;
8import java.awt.GraphicsEnvironment;
9import java.awt.Window;
10import java.awt.event.KeyEvent;
11import java.awt.event.WindowAdapter;
12import java.awt.event.WindowEvent;
13import java.io.File;
14import java.io.IOException;
15import java.lang.ref.WeakReference;
16import java.net.URI;
17import java.net.URISyntaxException;
18import java.net.URL;
19import java.text.MessageFormat;
20import java.util.ArrayList;
21import java.util.Arrays;
22import java.util.Collection;
23import java.util.EnumSet;
24import java.util.HashMap;
25import java.util.Iterator;
26import java.util.List;
27import java.util.Locale;
28import java.util.Map;
29import java.util.Objects;
30import java.util.Set;
31import java.util.StringTokenizer;
32import java.util.concurrent.Callable;
33import java.util.concurrent.ExecutionException;
34import java.util.concurrent.ExecutorService;
35import java.util.concurrent.Executors;
36import java.util.concurrent.Future;
37
38import javax.swing.Action;
39import javax.swing.InputMap;
40import javax.swing.JComponent;
41import javax.swing.JOptionPane;
42import javax.swing.JPanel;
43import javax.swing.KeyStroke;
44import javax.swing.LookAndFeel;
45import javax.swing.UIManager;
46import javax.swing.UnsupportedLookAndFeelException;
47
48import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
49import org.openstreetmap.josm.actions.JosmAction;
50import org.openstreetmap.josm.actions.OpenFileAction;
51import org.openstreetmap.josm.actions.OpenLocationAction;
52import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
53import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
54import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
55import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
56import org.openstreetmap.josm.actions.mapmode.DrawAction;
57import org.openstreetmap.josm.actions.search.SearchAction;
58import org.openstreetmap.josm.data.Bounds;
59import org.openstreetmap.josm.data.Preferences;
60import org.openstreetmap.josm.data.ProjectionBounds;
61import org.openstreetmap.josm.data.UndoRedoHandler;
62import org.openstreetmap.josm.data.ViewportData;
63import org.openstreetmap.josm.data.cache.JCSCacheManager;
64import org.openstreetmap.josm.data.coor.CoordinateFormat;
65import org.openstreetmap.josm.data.coor.LatLon;
66import org.openstreetmap.josm.data.osm.DataSet;
67import org.openstreetmap.josm.data.osm.OsmPrimitive;
68import org.openstreetmap.josm.data.projection.Projection;
69import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
70import org.openstreetmap.josm.data.validation.OsmValidator;
71import org.openstreetmap.josm.gui.MainFrame;
72import org.openstreetmap.josm.gui.MainMenu;
73import org.openstreetmap.josm.gui.MainPanel;
74import org.openstreetmap.josm.gui.MapFrame;
75import org.openstreetmap.josm.gui.MapFrameListener;
76import org.openstreetmap.josm.gui.ProgramArguments;
77import org.openstreetmap.josm.gui.ProgramArguments.Option;
78import org.openstreetmap.josm.gui.io.SaveLayersDialog;
79import org.openstreetmap.josm.gui.layer.Layer;
80import org.openstreetmap.josm.gui.layer.MainLayerManager;
81import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
82import org.openstreetmap.josm.gui.layer.TMSLayer;
83import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
84import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
85import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
86import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
87import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
88import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
89import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
90import org.openstreetmap.josm.gui.util.GuiHelper;
91import org.openstreetmap.josm.gui.util.RedirectInputMap;
92import org.openstreetmap.josm.io.FileWatcher;
93import org.openstreetmap.josm.io.OnlineResource;
94import org.openstreetmap.josm.io.OsmApi;
95import org.openstreetmap.josm.io.OsmApiInitializationException;
96import org.openstreetmap.josm.io.OsmTransferCanceledException;
97import org.openstreetmap.josm.plugins.PluginHandler;
98import org.openstreetmap.josm.tools.CheckParameterUtil;
99import org.openstreetmap.josm.tools.I18n;
100import org.openstreetmap.josm.tools.ImageProvider;
101import org.openstreetmap.josm.tools.JosmRuntimeException;
102import org.openstreetmap.josm.tools.Logging;
103import org.openstreetmap.josm.tools.OpenBrowser;
104import org.openstreetmap.josm.tools.OsmUrlToBounds;
105import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
106import org.openstreetmap.josm.tools.PlatformHook;
107import org.openstreetmap.josm.tools.PlatformHookOsx;
108import org.openstreetmap.josm.tools.PlatformHookUnixoid;
109import org.openstreetmap.josm.tools.PlatformHookWindows;
110import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
111import org.openstreetmap.josm.tools.Shortcut;
112import org.openstreetmap.josm.tools.Territories;
113import org.openstreetmap.josm.tools.Utils;
114import org.openstreetmap.josm.tools.bugreport.BugReport;
115
116/**
117 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
118 * @since 98
119 */
120public abstract class Main {
121
122 /**
123 * The JOSM website URL.
124 * @since 6897 (was public from 6143 to 6896)
125 */
126 private static final String JOSM_WEBSITE = "https://josm.openstreetmap.de";
127
128 /**
129 * The OSM website URL.
130 * @since 6897 (was public from 6453 to 6896)
131 */
132 private static final String OSM_WEBSITE = "https://www.openstreetmap.org";
133
134 /**
135 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
136 * it only shows the MOTD panel.
137 * <p>
138 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
139 *
140 * @return <code>true</code> if JOSM currently displays a map view
141 */
142 public static boolean isDisplayingMapView() {
143 return map != null && map.mapView != null;
144 }
145
146 /**
147 * Global parent component for all dialogs and message boxes
148 */
149 public static Component parent;
150
151 /**
152 * Global application.
153 */
154 public static volatile Main main;
155
156 /**
157 * The worker thread slave. This is for executing all long and intensive
158 * calculations. The executed runnables are guaranteed to be executed separately
159 * and sequential.
160 */
161 public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
162
163 /**
164 * Global application preferences
165 */
166 public static final Preferences pref = new Preferences();
167
168 /**
169 * The MapFrame.
170 * <p>
171 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
172 *
173 * @see MainPanel
174 */
175 public static MapFrame map;
176
177 /**
178 * Provides access to the layers displayed in the main view.
179 * @since 10271
180 */
181 private static final MainLayerManager layerManager = new MainLayerManager();
182
183 /**
184 * The toolbar preference control to register new actions.
185 */
186 public static volatile ToolbarPreferences toolbar;
187
188 /**
189 * The commands undo/redo handler.
190 */
191 public final UndoRedoHandler undoRedo = new UndoRedoHandler();
192
193 /**
194 * The progress monitor being currently displayed.
195 */
196 public static PleaseWaitProgressMonitor currentProgressMonitor;
197
198 /**
199 * The main menu bar at top of screen.
200 */
201 public MainMenu menu;
202
203 /**
204 * The file watcher service.
205 */
206 public static final FileWatcher fileWatcher = new FileWatcher();
207
208 private static final Map<String, Throwable> NETWORK_ERRORS = new HashMap<>();
209
210 private static final Set<OnlineResource> OFFLINE_RESOURCES = EnumSet.noneOf(OnlineResource.class);
211
212 /**
213 * Logging level (5 = trace, 4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
214 * @since 6248
215 * @deprecated Use {@link Logging} class.
216 */
217 @Deprecated
218 public static int logLevel = 3;
219
220 /**
221 * The real main panel. This field may be removed any time and made private to {@link MainFrame}
222 * @see #panel
223 */
224 protected static final MainPanel mainPanel = new MainPanel(getLayerManager());
225
226 /**
227 * Replies the first lines of last 5 error and warning messages, used for bug reports
228 * @return the first lines of last 5 error and warning messages
229 * @since 7420
230 */
231 public static final Collection<String> getLastErrorAndWarnings() {
232 return Logging.getLastErrorAndWarnings();
233 }
234
235 /**
236 * Clears the list of last error and warning messages.
237 * @since 8959
238 */
239 public static void clearLastErrorAndWarnings() {
240 Logging.clearLastErrorAndWarnings();
241 }
242
243 /**
244 * Prints an error message if logging is on.
245 * @param msg The message to print.
246 * @since 6248
247 */
248 public static void error(String msg) {
249 Logging.error(msg);
250 }
251
252 /**
253 * Prints a warning message if logging is on.
254 * @param msg The message to print.
255 */
256 public static void warn(String msg) {
257 Logging.warn(msg);
258 }
259
260 /**
261 * Prints an informational message if logging is on.
262 * @param msg The message to print.
263 */
264 public static void info(String msg) {
265 Logging.info(msg);
266 }
267
268 /**
269 * Prints a debug message if logging is on.
270 * @param msg The message to print.
271 */
272 public static void debug(String msg) {
273 Logging.debug(msg);
274 }
275
276 /**
277 * Prints a trace message if logging is on.
278 * @param msg The message to print.
279 */
280 public static void trace(String msg) {
281 Logging.trace(msg);
282 }
283
284 /**
285 * Determines if debug log level is enabled.
286 * Useful to avoid costly construction of debug messages when not enabled.
287 * @return {@code true} if log level is at least debug, {@code false} otherwise
288 * @since 6852
289 */
290 public static boolean isDebugEnabled() {
291 return Logging.isLoggingEnabled(Logging.LEVEL_DEBUG);
292 }
293
294 /**
295 * Determines if trace log level is enabled.
296 * Useful to avoid costly construction of trace messages when not enabled.
297 * @return {@code true} if log level is at least trace, {@code false} otherwise
298 * @since 6852
299 */
300 public static boolean isTraceEnabled() {
301 return Logging.isLoggingEnabled(Logging.LEVEL_TRACE);
302 }
303
304 /**
305 * Prints a formatted error message if logging is on. Calls {@link MessageFormat#format}
306 * function to format text.
307 * @param msg The formatted message to print.
308 * @param objects The objects to insert into format string.
309 * @since 6248
310 */
311 public static void error(String msg, Object... objects) {
312 Logging.error(msg, objects);
313 }
314
315 /**
316 * Prints a formatted warning message if logging is on. Calls {@link MessageFormat#format}
317 * function to format text.
318 * @param msg The formatted message to print.
319 * @param objects The objects to insert into format string.
320 */
321 public static void warn(String msg, Object... objects) {
322 Logging.warn(msg, objects);
323 }
324
325 /**
326 * Prints a formatted informational message if logging is on. Calls {@link MessageFormat#format}
327 * function to format text.
328 * @param msg The formatted message to print.
329 * @param objects The objects to insert into format string.
330 */
331 public static void info(String msg, Object... objects) {
332 Logging.info(msg, objects);
333 }
334
335 /**
336 * Prints a formatted debug message if logging is on. Calls {@link MessageFormat#format}
337 * function to format text.
338 * @param msg The formatted message to print.
339 * @param objects The objects to insert into format string.
340 */
341 public static void debug(String msg, Object... objects) {
342 Logging.debug(msg, objects);
343 }
344
345 /**
346 * Prints a formatted trace message if logging is on. Calls {@link MessageFormat#format}
347 * function to format text.
348 * @param msg The formatted message to print.
349 * @param objects The objects to insert into format string.
350 */
351 public static void trace(String msg, Object... objects) {
352 Logging.trace(msg, objects);
353 }
354
355 /**
356 * Prints an error message for the given Throwable.
357 * @param t The throwable object causing the error
358 * @since 6248
359 */
360 public static void error(Throwable t) {
361 Logging.logWithStackTrace(Logging.LEVEL_ERROR, t);
362 }
363
364 /**
365 * Prints a warning message for the given Throwable.
366 * @param t The throwable object causing the error
367 * @since 6248
368 */
369 public static void warn(Throwable t) {
370 Logging.logWithStackTrace(Logging.LEVEL_WARN, t);
371 }
372
373 /**
374 * Prints a debug message for the given Throwable. Useful for exceptions usually ignored
375 * @param t The throwable object causing the error
376 * @since 10420
377 */
378 public static void debug(Throwable t) {
379 Logging.log(Logging.LEVEL_DEBUG, t);
380 }
381
382 /**
383 * Prints a trace message for the given Throwable. Useful for exceptions usually ignored
384 * @param t The throwable object causing the error
385 * @since 10420
386 */
387 public static void trace(Throwable t) {
388 Logging.log(Logging.LEVEL_TRACE, t);
389 }
390
391 /**
392 * Prints an error message for the given Throwable.
393 * @param t The throwable object causing the error
394 * @param stackTrace {@code true}, if the stacktrace should be displayed
395 * @since 6642
396 */
397 public static void error(Throwable t, boolean stackTrace) {
398 if (stackTrace) {
399 Logging.log(Logging.LEVEL_ERROR, t);
400 } else {
401 Logging.logWithStackTrace(Logging.LEVEL_ERROR, t);
402 }
403 }
404
405 /**
406 * Prints an error message for the given Throwable.
407 * @param t The throwable object causing the error
408 * @param message additional error message
409 * @since 10420
410 */
411 public static void error(Throwable t, String message) {
412 Logging.log(Logging.LEVEL_ERROR, message, t);
413 }
414
415 /**
416 * Prints a warning message for the given Throwable.
417 * @param t The throwable object causing the error
418 * @param stackTrace {@code true}, if the stacktrace should be displayed
419 * @since 6642
420 */
421 public static void warn(Throwable t, boolean stackTrace) {
422 if (stackTrace) {
423 Logging.log(Logging.LEVEL_WARN, t);
424 } else {
425 Logging.logWithStackTrace(Logging.LEVEL_WARN, t);
426 }
427 }
428
429 /**
430 * Prints a warning message for the given Throwable.
431 * @param t The throwable object causing the error
432 * @param message additional error message
433 * @since 10420
434 */
435 public static void warn(Throwable t, String message) {
436 Logging.log(Logging.LEVEL_WARN, message, t);
437 }
438
439 /**
440 * Returns a human-readable message of error, also usable for developers.
441 * @param t The error
442 * @return The human-readable error message
443 * @since 6642
444 */
445 public static String getErrorMessage(Throwable t) {
446 if (t == null) {
447 return null;
448 } else {
449 return Logging.getErrorMessage(t);
450 }
451 }
452
453 /**
454 * Platform specific code goes in here.
455 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
456 * So if you need to hook into those early ones, split your class and send the one with the early hooks
457 * to the JOSM team for inclusion.
458 */
459 public static volatile PlatformHook platform;
460
461 private static volatile InitStatusListener initListener;
462
463 /**
464 * Initialization task listener.
465 */
466 public interface InitStatusListener {
467
468 /**
469 * Called when an initialization task updates its status.
470 * @param event task name
471 * @return new status
472 */
473 Object updateStatus(String event);
474
475 /**
476 * Called when an initialization task completes.
477 * @param status final status
478 */
479 void finish(Object status);
480 }
481
482 /**
483 * Sets initialization task listener.
484 * @param listener initialization task listener
485 */
486 public static void setInitStatusListener(InitStatusListener listener) {
487 CheckParameterUtil.ensureParameterNotNull(listener);
488 initListener = listener;
489 }
490
491 /**
492 * Constructs new {@code Main} object.
493 * @see #initialize()
494 */
495 protected Main() {
496 setInstance(this);
497 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
498 }
499
500 private static void setInstance(Main instance) {
501 main = instance;
502 }
503
504 /**
505 * Initializes the main object. A lot of global variables are initialized here.
506 * @since 10340
507 */
508 public void initialize() {
509 fileWatcher.start();
510
511 new InitializationTask(tr("Executing platform startup hook"), platform::startupHook).call();
512
513 new InitializationTask(tr("Building main menu"), this::initializeMainWindow).call();
514
515 undoRedo.addCommandQueueListener(redoUndoListener);
516
517 // creating toolbar
518 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
519
520 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
521 KeyEvent.VK_F1, Shortcut.DIRECT));
522
523 // This needs to be done before RightAndLefthandTraffic::initialize is called
524 try {
525 new InitializationTask(tr("Initializing internal boundaries data"), Territories::initialize).call();
526 } catch (JosmRuntimeException e) {
527 // Can happen if the current projection needs NTV2 grid which is not available
528 // In this case we want the user be able to change his projection
529 BugReport.intercept(e).warn();
530 }
531
532 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
533 List<Callable<Void>> tasks = new ArrayList<>();
534
535 tasks.add(new InitializationTask(tr("Initializing OSM API"), () -> {
536 // We try to establish an API connection early, so that any API
537 // capabilities are already known to the editor instance. However
538 // if it goes wrong that's not critical at this stage.
539 try {
540 OsmApi.getOsmApi().initialize(null, true);
541 } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
542 Main.warn(getErrorMessage(Utils.getRootCause(e)));
543 }
544 }));
545
546 tasks.add(new InitializationTask(tr("Initializing internal traffic data"), RightAndLefthandTraffic::initialize));
547
548 tasks.add(new InitializationTask(tr("Initializing validator"), OsmValidator::initialize));
549
550 tasks.add(new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize));
551
552 tasks.add(new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize));
553
554 tasks.add(new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize));
555
556 try {
557 ExecutorService service = Executors.newFixedThreadPool(
558 Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
559 for (Future<Void> i : service.invokeAll(tasks)) {
560 i.get();
561 }
562 // asynchronous initializations to be completed eventually
563 service.submit((Runnable) TMSLayer::getCache);
564 service.submit((Runnable) OsmValidator::initializeTests);
565 service.submit(OverpassTurboQueryWizard::getInstance);
566 service.shutdown();
567 } catch (InterruptedException | ExecutionException ex) {
568 throw new JosmRuntimeException(ex);
569 }
570
571 // hooks for the jmapviewer component
572 FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
573 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
574 FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
575
576 new InitializationTask(tr("Updating user interface"), () -> {
577 toolbar.refreshToolbarControl();
578 toolbar.control.updateUI();
579 contentPanePrivate.updateUI();
580 }).call();
581 }
582
583 /**
584 * Called once at startup to initialize the main window content.
585 * Should set {@link #menu}
586 */
587 protected abstract void initializeMainWindow();
588
589 private static class InitializationTask implements Callable<Void> {
590
591 private final String name;
592 private final Runnable task;
593
594 protected InitializationTask(String name, Runnable task) {
595 this.name = name;
596 this.task = task;
597 }
598
599 @Override
600 public Void call() {
601 Object status = null;
602 if (initListener != null) {
603 status = initListener.updateStatus(name);
604 }
605 task.run();
606 if (initListener != null) {
607 initListener.finish(status);
608 }
609 return null;
610 }
611 }
612
613 /**
614 * Returns the main layer manager that is used by the map view.
615 * @return The layer manager. The value returned will never change.
616 * @since 10279
617 */
618 public static MainLayerManager getLayerManager() {
619 return layerManager;
620 }
621
622 /**
623 * Add a new layer to the map.
624 *
625 * If no map exists, create one.
626 *
627 * @param layer the layer
628 * @param bounds the bounds of the layer (target zoom area); can be null, then
629 * the viewport isn't changed
630 */
631 public final void addLayer(Layer layer, ProjectionBounds bounds) {
632 addLayer(layer, bounds == null ? null : new ViewportData(bounds));
633 }
634
635 /**
636 * Add a new layer to the map.
637 *
638 * If no map exists, create one.
639 *
640 * @param layer the layer
641 * @param viewport the viewport to zoom to; can be null, then the viewport isn't changed
642 */
643 public final void addLayer(Layer layer, ViewportData viewport) {
644 getLayerManager().addLayer(layer);
645 if (viewport != null && Main.map.mapView != null) {
646 // MapView may be null in headless mode here.
647 Main.map.mapView.scheduleZoomTo(viewport);
648 }
649 }
650
651 /**
652 * Replies the current selected primitives, from a end-user point of view.
653 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
654 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
655 * see {@link DrawAction#getInProgressSelection()}.
656 *
657 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
658 * @since 6546
659 */
660 public Collection<OsmPrimitive> getInProgressSelection() {
661 if (map != null && map.mapMode instanceof DrawAction) {
662 return ((DrawAction) map.mapMode).getInProgressSelection();
663 } else {
664 DataSet ds = getLayerManager().getEditDataSet();
665 if (ds == null) return null;
666 return ds.getSelected();
667 }
668 }
669
670 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
671
672 public static void redirectToMainContentPane(JComponent source) {
673 RedirectInputMap.redirect(source, contentPanePrivate);
674 }
675
676 /**
677 * Registers a {@code JosmAction} and its shortcut.
678 * @param action action defining its own shortcut
679 */
680 public static void registerActionShortcut(JosmAction action) {
681 registerActionShortcut(action, action.getShortcut());
682 }
683
684 /**
685 * Registers an action and its shortcut.
686 * @param action action to register
687 * @param shortcut shortcut to associate to {@code action}
688 */
689 public static void registerActionShortcut(Action action, Shortcut shortcut) {
690 KeyStroke keyStroke = shortcut.getKeyStroke();
691 if (keyStroke == null)
692 return;
693
694 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
695 Object existing = inputMap.get(keyStroke);
696 if (existing != null && !existing.equals(action)) {
697 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
698 }
699 inputMap.put(keyStroke, action);
700
701 contentPanePrivate.getActionMap().put(action, action);
702 }
703
704 /**
705 * Unregisters a shortcut.
706 * @param shortcut shortcut to unregister
707 */
708 public static void unregisterShortcut(Shortcut shortcut) {
709 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
710 }
711
712 /**
713 * Unregisters a {@code JosmAction} and its shortcut.
714 * @param action action to unregister
715 */
716 public static void unregisterActionShortcut(JosmAction action) {
717 unregisterActionShortcut(action, action.getShortcut());
718 }
719
720 /**
721 * Unregisters an action and its shortcut.
722 * @param action action to unregister
723 * @param shortcut shortcut to unregister
724 */
725 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
726 unregisterShortcut(shortcut);
727 contentPanePrivate.getActionMap().remove(action);
728 }
729
730 /**
731 * Replies the registered action for the given shortcut
732 * @param shortcut The shortcut to look for
733 * @return the registered action for the given shortcut
734 * @since 5696
735 */
736 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
737 KeyStroke keyStroke = shortcut.getKeyStroke();
738 if (keyStroke == null)
739 return null;
740 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
741 if (action instanceof Action)
742 return (Action) action;
743 return null;
744 }
745
746 ///////////////////////////////////////////////////////////////////////////
747 // Implementation part
748 ///////////////////////////////////////////////////////////////////////////
749
750 /**
751 * Global panel.
752 */
753 public static final JPanel panel = mainPanel;
754
755 private final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
756 menu.undo.setEnabled(queueSize > 0);
757 menu.redo.setEnabled(redoSize > 0);
758 };
759
760 /**
761 * Should be called before the main constructor to setup some parameter stuff
762 */
763 public static void preConstructorInit() {
764 ProjectionPreference.setProjection();
765
766 String defaultlaf = platform.getDefaultStyle();
767 String laf = Main.pref.get("laf", defaultlaf);
768 try {
769 UIManager.setLookAndFeel(laf);
770 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
771 // Try to find look and feel in plugin classloaders
772 Main.trace(e);
773 Class<?> klass = null;
774 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
775 try {
776 klass = cl.loadClass(laf);
777 break;
778 } catch (ClassNotFoundException ex) {
779 Main.trace(ex);
780 }
781 }
782 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
783 try {
784 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
785 } catch (ReflectiveOperationException ex) {
786 warn(ex, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage());
787 } catch (UnsupportedLookAndFeelException ex) {
788 info("Look and Feel not supported: " + laf);
789 Main.pref.put("laf", defaultlaf);
790 trace(ex);
791 }
792 } else {
793 info("Look and Feel not found: " + laf);
794 Main.pref.put("laf", defaultlaf);
795 }
796 } catch (UnsupportedLookAndFeelException e) {
797 info("Look and Feel not supported: " + laf);
798 Main.pref.put("laf", defaultlaf);
799 trace(e);
800 } catch (InstantiationException | IllegalAccessException e) {
801 error(e);
802 }
803 toolbar = new ToolbarPreferences();
804 contentPanePrivate.updateUI();
805 panel.updateUI();
806
807 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
808 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
809 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
810 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
811 // Ensures caret color is the same than text foreground color, see #12257
812 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
813 for (String p : Arrays.asList(
814 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
815 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
816 }
817
818 I18n.translateJavaInternalMessages();
819
820 // init default coordinate format
821 //
822 try {
823 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
824 } catch (IllegalArgumentException iae) {
825 Main.trace(iae);
826 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
827 }
828 }
829
830 protected static void postConstructorProcessCmdLine(ProgramArguments args) {
831 List<File> fileList = new ArrayList<>();
832 for (String s : args.get(Option.DOWNLOAD)) {
833 DownloadParamType.paramType(s).download(s, fileList);
834 }
835 if (!fileList.isEmpty()) {
836 OpenFileAction.openFiles(fileList, true);
837 }
838 for (String s : args.get(Option.DOWNLOADGPS)) {
839 DownloadParamType.paramType(s).downloadGps(s);
840 }
841 for (String s : args.get(Option.SELECTION)) {
842 SearchAction.search(s, SearchAction.SearchMode.add);
843 }
844 }
845
846 /**
847 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
848 * If there are some unsaved data layers, asks first for user confirmation.
849 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
850 * @param exitCode The return code
851 * @param reason the reason for exiting
852 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
853 * @since 11093 (3378 with a different function signature)
854 */
855 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
856 final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
857 SaveLayersDialog.saveUnsavedModifications(getLayerManager().getLayers(),
858 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
859 if (proceed) {
860 if (Main.main != null) {
861 Main.main.shutdown();
862 }
863
864 if (exit) {
865 System.exit(exitCode);
866 }
867 return true;
868 }
869 return false;
870 }
871
872 protected void shutdown() {
873 if (!GraphicsEnvironment.isHeadless()) {
874 worker.shutdown();
875 ImageProvider.shutdown(false);
876 JCSCacheManager.shutdown();
877 }
878 if (map != null) {
879 map.rememberToggleDialogWidth();
880 }
881 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
882 getLayerManager().resetState();
883 try {
884 pref.saveDefaults();
885 } catch (IOException ex) {
886 Main.warn(ex, tr("Failed to save default preferences."));
887 }
888 if (!GraphicsEnvironment.isHeadless()) {
889 worker.shutdownNow();
890 ImageProvider.shutdown(true);
891 }
892 }
893
894 /**
895 * The type of a command line parameter, to be used in switch statements.
896 * @see #paramType
897 */
898 enum DownloadParamType {
899 httpUrl {
900 @Override
901 void download(String s, Collection<File> fileList) {
902 new OpenLocationAction().openUrl(false, s);
903 }
904
905 @Override
906 void downloadGps(String s) {
907 final Bounds b = OsmUrlToBounds.parse(s);
908 if (b == null) {
909 JOptionPane.showMessageDialog(
910 Main.parent,
911 tr("Ignoring malformed URL: \"{0}\"", s),
912 tr("Warning"),
913 JOptionPane.WARNING_MESSAGE
914 );
915 return;
916 }
917 downloadFromParamBounds(true, b);
918 }
919 }, fileUrl {
920 @Override
921 void download(String s, Collection<File> fileList) {
922 File f = null;
923 try {
924 f = new File(new URI(s));
925 } catch (URISyntaxException e) {
926 Main.warn(e);
927 JOptionPane.showMessageDialog(
928 Main.parent,
929 tr("Ignoring malformed file URL: \"{0}\"", s),
930 tr("Warning"),
931 JOptionPane.WARNING_MESSAGE
932 );
933 }
934 if (f != null) {
935 fileList.add(f);
936 }
937 }
938 }, bounds {
939
940 /**
941 * Download area specified on the command line as bounds string.
942 * @param rawGps Flag to download raw GPS tracks
943 * @param s The bounds parameter
944 */
945 private void downloadFromParamBounds(final boolean rawGps, String s) {
946 final StringTokenizer st = new StringTokenizer(s, ",");
947 if (st.countTokens() == 4) {
948 Bounds b = new Bounds(
949 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())),
950 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))
951 );
952 Main.downloadFromParamBounds(rawGps, b);
953 }
954 }
955
956 @Override
957 void download(String param, Collection<File> fileList) {
958 downloadFromParamBounds(false, param);
959 }
960
961 @Override
962 void downloadGps(String param) {
963 downloadFromParamBounds(true, param);
964 }
965 }, fileName {
966 @Override
967 void download(String s, Collection<File> fileList) {
968 fileList.add(new File(s));
969 }
970 };
971
972 /**
973 * Performs the download
974 * @param param represents the object to be downloaded
975 * @param fileList files which shall be opened, should be added to this collection
976 */
977 abstract void download(String param, Collection<File> fileList);
978
979 /**
980 * Performs the GPS download
981 * @param param represents the object to be downloaded
982 */
983 void downloadGps(String param) {
984 JOptionPane.showMessageDialog(
985 Main.parent,
986 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
987 tr("Warning"),
988 JOptionPane.WARNING_MESSAGE
989 );
990 }
991
992 /**
993 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
994 *
995 * @param s A parameter string
996 * @return The guessed parameter type
997 */
998 static DownloadParamType paramType(String s) {
999 if (s.startsWith("http:") || s.startsWith("https:")) return DownloadParamType.httpUrl;
1000 if (s.startsWith("file:")) return DownloadParamType.fileUrl;
1001 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
1002 if (s.matches(coorPattern + "(," + coorPattern + "){3}")) return DownloadParamType.bounds;
1003 // everything else must be a file name
1004 return DownloadParamType.fileName;
1005 }
1006 }
1007
1008 /**
1009 * Download area specified as Bounds value.
1010 * @param rawGps Flag to download raw GPS tracks
1011 * @param b The bounds value
1012 */
1013 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
1014 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1015 // asynchronously launch the download task ...
1016 Future<?> future = task.download(true, b, null);
1017 // ... and the continuation when the download is finished (this will wait for the download to finish)
1018 Main.worker.execute(new PostDownloadHandler(task, future));
1019 }
1020
1021 /**
1022 * Identifies the current operating system family and initializes the platform hook accordingly.
1023 * @since 1849
1024 */
1025 public static void determinePlatformHook() {
1026 String os = System.getProperty("os.name");
1027 if (os == null) {
1028 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
1029 platform = new PlatformHookUnixoid();
1030 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("windows")) {
1031 platform = new PlatformHookWindows();
1032 } else if ("Linux".equals(os) || "Solaris".equals(os) ||
1033 "SunOS".equals(os) || "AIX".equals(os) ||
1034 "FreeBSD".equals(os) || "NetBSD".equals(os) || "OpenBSD".equals(os)) {
1035 platform = new PlatformHookUnixoid();
1036 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("mac os x")) {
1037 platform = new PlatformHookOsx();
1038 } else {
1039 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
1040 platform = new PlatformHookUnixoid();
1041 }
1042 }
1043
1044 /* ----------------------------------------------------------------------------------------- */
1045 /* projection handling - Main is a registry for a single, global projection instance */
1046 /* */
1047 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1048 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1049 /* ----------------------------------------------------------------------------------------- */
1050 /**
1051 * The projection method used.
1052 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1053 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
1054 */
1055 private static volatile Projection proj;
1056
1057 /**
1058 * Replies the current projection.
1059 *
1060 * @return the currently active projection
1061 */
1062 public static Projection getProjection() {
1063 return proj;
1064 }
1065
1066 /**
1067 * Sets the current projection
1068 *
1069 * @param p the projection
1070 */
1071 public static void setProjection(Projection p) {
1072 CheckParameterUtil.ensureParameterNotNull(p);
1073 Projection oldValue = proj;
1074 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
1075 proj = p;
1076 fireProjectionChanged(oldValue, proj, b);
1077 }
1078
1079 /*
1080 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1081 * explicitly removing the listeners and allows us to transparently register every
1082 * created dataset as projection change listener.
1083 */
1084 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
1085
1086 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
1087 if ((newValue == null ^ oldValue == null)
1088 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
1089 if (Main.map != null) {
1090 // This needs to be called first
1091 Main.map.mapView.fixProjection();
1092 }
1093 synchronized (Main.class) {
1094 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1095 while (it.hasNext()) {
1096 WeakReference<ProjectionChangeListener> wr = it.next();
1097 ProjectionChangeListener listener = wr.get();
1098 if (listener == null) {
1099 it.remove();
1100 continue;
1101 }
1102 listener.projectionChanged(oldValue, newValue);
1103 }
1104 }
1105 if (newValue != null && oldBounds != null) {
1106 Main.map.mapView.zoomTo(oldBounds);
1107 }
1108 /* TODO - remove layers with fixed projection */
1109 }
1110 }
1111
1112 /**
1113 * Register a projection change listener.
1114 *
1115 * @param listener the listener. Ignored if <code>null</code>.
1116 */
1117 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1118 if (listener == null) return;
1119 synchronized (Main.class) {
1120 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1121 // already registered ? => abort
1122 if (wr.get() == listener) return;
1123 }
1124 listeners.add(new WeakReference<>(listener));
1125 }
1126 }
1127
1128 /**
1129 * Removes a projection change listener.
1130 *
1131 * @param listener the listener. Ignored if <code>null</code>.
1132 */
1133 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1134 if (listener == null) return;
1135 synchronized (Main.class) {
1136 // remove the listener - and any other listener which got garbage
1137 // collected in the meantime
1138 listeners.removeIf(wr -> wr.get() == null || wr.get() == listener);
1139 }
1140 }
1141
1142 /**
1143 * Listener for window switch events.
1144 *
1145 * These are events, when the user activates a window of another application
1146 * or comes back to JOSM. Window switches from one JOSM window to another
1147 * are not reported.
1148 */
1149 public interface WindowSwitchListener {
1150 /**
1151 * Called when the user activates a window of another application.
1152 */
1153 void toOtherApplication();
1154
1155 /**
1156 * Called when the user comes from a window of another application back to JOSM.
1157 */
1158 void fromOtherApplication();
1159 }
1160
1161 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<>();
1162
1163 /**
1164 * Register a window switch listener.
1165 *
1166 * @param listener the listener. Ignored if <code>null</code>.
1167 */
1168 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1169 if (listener == null) return;
1170 synchronized (Main.class) {
1171 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1172 // already registered ? => abort
1173 if (wr.get() == listener) return;
1174 }
1175 boolean wasEmpty = windowSwitchListeners.isEmpty();
1176 windowSwitchListeners.add(new WeakReference<>(listener));
1177 if (wasEmpty) {
1178 // The following call will have no effect, when there is no window
1179 // at the time. Therefore, MasterWindowListener.setup() will also be
1180 // called, as soon as the main window is shown.
1181 MasterWindowListener.setup();
1182 }
1183 }
1184 }
1185
1186 /**
1187 * Removes a window switch listener.
1188 *
1189 * @param listener the listener. Ignored if <code>null</code>.
1190 */
1191 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1192 if (listener == null) return;
1193 synchronized (Main.class) {
1194 // remove the listener - and any other listener which got garbage
1195 // collected in the meantime
1196 windowSwitchListeners.removeIf(wr -> wr.get() == null || wr.get() == listener);
1197 if (windowSwitchListeners.isEmpty()) {
1198 MasterWindowListener.teardown();
1199 }
1200 }
1201 }
1202
1203 /**
1204 * WindowListener, that is registered on all Windows of the application.
1205 *
1206 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1207 * another application, e.g. a browser, or back to JOSM.
1208 *
1209 * When changing from JOSM to another application and back (e.g. two times
1210 * alt+tab), the active Window within JOSM may be different.
1211 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1212 * Windows in JOSM, and it does not suffice to monitor the one that was
1213 * deactivated last.
1214 *
1215 * This class is only "active" on demand, i.e. when there is at least one
1216 * WindowSwitchListener registered.
1217 */
1218 protected static class MasterWindowListener extends WindowAdapter {
1219
1220 private static MasterWindowListener INSTANCE;
1221
1222 public static synchronized MasterWindowListener getInstance() {
1223 if (INSTANCE == null) {
1224 INSTANCE = new MasterWindowListener();
1225 }
1226 return INSTANCE;
1227 }
1228
1229 /**
1230 * Register listeners to all non-hidden windows.
1231 *
1232 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1233 */
1234 public static void setup() {
1235 if (!windowSwitchListeners.isEmpty()) {
1236 for (Window w : Window.getWindows()) {
1237 if (w.isShowing() && !Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1238 w.addWindowListener(getInstance());
1239 }
1240 }
1241 }
1242 }
1243
1244 /**
1245 * Unregister all listeners.
1246 */
1247 public static void teardown() {
1248 for (Window w : Window.getWindows()) {
1249 w.removeWindowListener(getInstance());
1250 }
1251 }
1252
1253 @Override
1254 public void windowActivated(WindowEvent e) {
1255 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1256 // fire WindowSwitchListeners
1257 synchronized (Main.class) {
1258 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1259 while (it.hasNext()) {
1260 WeakReference<WindowSwitchListener> wr = it.next();
1261 WindowSwitchListener listener = wr.get();
1262 if (listener == null) {
1263 it.remove();
1264 continue;
1265 }
1266 listener.fromOtherApplication();
1267 }
1268 }
1269 }
1270 }
1271
1272 @Override
1273 public void windowDeactivated(WindowEvent e) {
1274 // set up windows that have been created in the meantime
1275 for (Window w : Window.getWindows()) {
1276 if (!w.isShowing()) {
1277 w.removeWindowListener(getInstance());
1278 } else {
1279 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1280 w.addWindowListener(getInstance());
1281 }
1282 }
1283 }
1284 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1285 // fire WindowSwitchListeners
1286 synchronized (Main.class) {
1287 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1288 while (it.hasNext()) {
1289 WeakReference<WindowSwitchListener> wr = it.next();
1290 WindowSwitchListener listener = wr.get();
1291 if (listener == null) {
1292 it.remove();
1293 continue;
1294 }
1295 listener.toOtherApplication();
1296 }
1297 }
1298 }
1299 }
1300 }
1301
1302 /**
1303 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1304 * @param listener The MapFrameListener
1305 * @param fireWhenMapViewPresent If true, will fire an initial mapFrameInitialized event
1306 * when the MapFrame is present. Otherwise will only fire when the MapFrame is created
1307 * or destroyed.
1308 * @return {@code true} if the listeners collection changed as a result of the call
1309 */
1310 public static boolean addMapFrameListener(MapFrameListener listener, boolean fireWhenMapViewPresent) {
1311 if (fireWhenMapViewPresent) {
1312 return mainPanel.addAndFireMapFrameListener(listener);
1313 } else {
1314 return mainPanel.addMapFrameListener(listener);
1315 }
1316 }
1317
1318 /**
1319 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1320 * @param listener The MapFrameListener
1321 * @return {@code true} if the listeners collection changed as a result of the call
1322 * @since 5957
1323 */
1324 public static boolean addMapFrameListener(MapFrameListener listener) {
1325 return mainPanel.addMapFrameListener(listener);
1326 }
1327
1328 /**
1329 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1330 * @param listener The MapFrameListener
1331 * @return {@code true} if the listeners collection changed as a result of the call
1332 * @since 5957
1333 */
1334 public static boolean removeMapFrameListener(MapFrameListener listener) {
1335 return mainPanel.removeMapFrameListener(listener);
1336 }
1337
1338 /**
1339 * Adds a new network error that occur to give a hint about broken Internet connection.
1340 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1341 *
1342 * @param url The accessed URL that caused the error
1343 * @param t The network error
1344 * @return The previous error associated to the given resource, if any. Can be {@code null}
1345 * @since 6642
1346 */
1347 public static Throwable addNetworkError(URL url, Throwable t) {
1348 if (url != null && t != null) {
1349 Throwable old = addNetworkError(url.toExternalForm(), t);
1350 if (old != null) {
1351 Main.warn("Already here "+old);
1352 }
1353 return old;
1354 }
1355 return null;
1356 }
1357
1358 /**
1359 * Adds a new network error that occur to give a hint about broken Internet connection.
1360 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1361 *
1362 * @param url The accessed URL that caused the error
1363 * @param t The network error
1364 * @return The previous error associated to the given resource, if any. Can be {@code null}
1365 * @since 6642
1366 */
1367 public static Throwable addNetworkError(String url, Throwable t) {
1368 if (url != null && t != null) {
1369 return NETWORK_ERRORS.put(url, t);
1370 }
1371 return null;
1372 }
1373
1374 /**
1375 * Returns the network errors that occured until now.
1376 * @return the network errors that occured until now, indexed by URL
1377 * @since 6639
1378 */
1379 public static Map<String, Throwable> getNetworkErrors() {
1380 return new HashMap<>(NETWORK_ERRORS);
1381 }
1382
1383 /**
1384 * Returns the JOSM website URL.
1385 * @return the josm website URL
1386 * @since 6897
1387 */
1388 public static String getJOSMWebsite() {
1389 if (Main.pref != null)
1390 return Main.pref.get("josm.url", JOSM_WEBSITE);
1391 return JOSM_WEBSITE;
1392 }
1393
1394 /**
1395 * Returns the JOSM XML URL.
1396 * @return the josm XML URL
1397 * @since 6897
1398 */
1399 public static String getXMLBase() {
1400 // Always return HTTP (issues reported with HTTPS)
1401 return "http://josm.openstreetmap.de";
1402 }
1403
1404 /**
1405 * Returns the OSM website URL.
1406 * @return the OSM website URL
1407 * @since 6897
1408 */
1409 public static String getOSMWebsite() {
1410 if (Main.pref != null)
1411 return Main.pref.get("osm.url", OSM_WEBSITE);
1412 return OSM_WEBSITE;
1413 }
1414
1415 /**
1416 * Returns the OSM website URL depending on the selected {@link OsmApi}.
1417 * @return the OSM website URL depending on the selected {@link OsmApi}
1418 */
1419 private static String getOSMWebsiteDependingOnSelectedApi() {
1420 final String api = OsmApi.getOsmApi().getServerUrl();
1421 if (OsmApi.DEFAULT_API_URL.equals(api)) {
1422 return getOSMWebsite();
1423 } else {
1424 return api.replaceAll("/api$", "");
1425 }
1426 }
1427
1428 /**
1429 * Replies the base URL for browsing information about a primitive.
1430 * @return the base URL, i.e. https://www.openstreetmap.org
1431 * @since 7678
1432 */
1433 public static String getBaseBrowseUrl() {
1434 if (Main.pref != null)
1435 return Main.pref.get("osm-browse.url", getOSMWebsiteDependingOnSelectedApi());
1436 return getOSMWebsiteDependingOnSelectedApi();
1437 }
1438
1439 /**
1440 * Replies the base URL for browsing information about a user.
1441 * @return the base URL, i.e. https://www.openstreetmap.org/user
1442 * @since 7678
1443 */
1444 public static String getBaseUserUrl() {
1445 if (Main.pref != null)
1446 return Main.pref.get("osm-user.url", getOSMWebsiteDependingOnSelectedApi() + "/user");
1447 return getOSMWebsiteDependingOnSelectedApi() + "/user";
1448 }
1449
1450 /**
1451 * Determines if we are currently running on OSX.
1452 * @return {@code true} if we are currently running on OSX
1453 * @since 6957
1454 */
1455 public static boolean isPlatformOsx() {
1456 return Main.platform instanceof PlatformHookOsx;
1457 }
1458
1459 /**
1460 * Determines if we are currently running on Windows.
1461 * @return {@code true} if we are currently running on Windows
1462 * @since 7335
1463 */
1464 public static boolean isPlatformWindows() {
1465 return Main.platform instanceof PlatformHookWindows;
1466 }
1467
1468 /**
1469 * Determines if the given online resource is currently offline.
1470 * @param r the online resource
1471 * @return {@code true} if {@code r} is offline and should not be accessed
1472 * @since 7434
1473 */
1474 public static boolean isOffline(OnlineResource r) {
1475 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1476 }
1477
1478 /**
1479 * Sets the given online resource to offline state.
1480 * @param r the online resource
1481 * @return {@code true} if {@code r} was not already offline
1482 * @since 7434
1483 */
1484 public static boolean setOffline(OnlineResource r) {
1485 return OFFLINE_RESOURCES.add(r);
1486 }
1487
1488 /**
1489 * Sets the given online resource to online state.
1490 * @param r the online resource
1491 * @return {@code true} if {@code r} was offline
1492 * @since 8506
1493 */
1494 public static boolean setOnline(OnlineResource r) {
1495 return OFFLINE_RESOURCES.remove(r);
1496 }
1497
1498 /**
1499 * Replies the set of online resources currently offline.
1500 * @return the set of online resources currently offline
1501 * @since 7434
1502 */
1503 public static Set<OnlineResource> getOfflineResources() {
1504 return EnumSet.copyOf(OFFLINE_RESOURCES);
1505 }
1506}
Note: See TracBrowser for help on using the repository browser.