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

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

sonar - squid:S2301 - Public methods should not contain selector arguments

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