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

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

javadoc

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