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

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

sonar - fb-contrib:ACEM_ABSTRACT_CLASS_EMPTY_METHODS

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