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

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

see #9400 - see #10387 - see #12914 - initial implementation of boundaries file, replacing left-right-hand-traffic.osm, discourage contributors to use operator=RFF and operator=ERDF in France (territories rules must be manually eabled on existing installations)

  • Property svn:eol-style set to native
File size: 53.1 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 public interface InitStatusListener {
468
469 Object updateStatus(String event);
470
471 void finish(Object status);
472 }
473
474 public static void setInitStatusListener(InitStatusListener listener) {
475 CheckParameterUtil.ensureParameterNotNull(listener);
476 initListener = listener;
477 }
478
479 /**
480 * Constructs new {@code Main} object.
481 * @see #initialize()
482 */
483 public Main() {
484 main = this;
485 mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
486 }
487
488 /**
489 * Initializes the main object. A lot of global variables are initialized here.
490 * @since 10340
491 */
492 public void initialize() {
493 fileWatcher.start();
494
495 new InitializationTask(tr("Executing platform startup hook"), platform::startupHook).call();
496
497 new InitializationTask(tr("Building main menu"), this::initializeMainWindow).call();
498
499 undoRedo.addCommandQueueListener(redoUndoListener);
500
501 // creating toolbar
502 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
503
504 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
505 KeyEvent.VK_F1, Shortcut.DIRECT));
506
507 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
508 List<Callable<Void>> tasks = new ArrayList<>();
509
510 tasks.add(new InitializationTask(tr("Initializing OSM API"), () -> {
511 // We try to establish an API connection early, so that any API
512 // capabilities are already known to the editor instance. However
513 // if it goes wrong that's not critical at this stage.
514 try {
515 OsmApi.getOsmApi().initialize(null, true);
516 } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
517 Main.warn(getErrorMessage(Utils.getRootCause(e)));
518 }
519 }));
520
521 tasks.add(new InitializationTask(tr("Initializing internal boundaries data"), Territories::initialize));
522
523 tasks.add(new InitializationTask(tr("Initializing internal traffic data"), RightAndLefthandTraffic::initialize));
524
525 tasks.add(new InitializationTask(tr("Initializing validator"), OsmValidator::initialize));
526
527 tasks.add(new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize));
528
529 tasks.add(new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize));
530
531 tasks.add(new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize));
532
533 try {
534 ExecutorService service = Executors.newFixedThreadPool(
535 Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
536 for (Future<Void> i : service.invokeAll(tasks)) {
537 i.get();
538 }
539 // asynchronous initializations to be completed eventually
540 service.submit((Runnable) TMSLayer::getCache);
541 service.submit((Runnable) OsmValidator::initializeTests);
542 service.submit(OverpassTurboQueryWizard::getInstance);
543 service.shutdown();
544 } catch (InterruptedException | ExecutionException ex) {
545 throw new RuntimeException(ex);
546 }
547
548 // hooks for the jmapviewer component
549 FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
550 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
551 FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
552
553 new InitializationTask(tr("Updating user interface"), () -> {
554 toolbar.refreshToolbarControl();
555 toolbar.control.updateUI();
556 contentPanePrivate.updateUI();
557 }).call();
558 }
559
560 /**
561 * Called once at startup to initialize the main window content.
562 * Should set {@link #menu}
563 */
564 protected void initializeMainWindow() {
565 // can be implementd by subclasses
566 }
567
568 private static class InitializationTask implements Callable<Void> {
569
570 private final String name;
571 private final Runnable task;
572
573 protected InitializationTask(String name, Runnable task) {
574 this.name = name;
575 this.task = task;
576 }
577
578 @Override
579 public Void call() {
580 Object status = null;
581 if (initListener != null) {
582 status = initListener.updateStatus(name);
583 }
584 task.run();
585 if (initListener != null) {
586 initListener.finish(status);
587 }
588 return null;
589 }
590 }
591
592 /**
593 * Returns the main layer manager that is used by the map view.
594 * @return The layer manager. The value returned will never change.
595 * @since 10279
596 */
597 public static MainLayerManager getLayerManager() {
598 return layerManager;
599 }
600
601 /**
602 * Add a new layer to the map.
603 *
604 * If no map exists, create one.
605 *
606 * @param layer the layer
607 * @param bounds the bounds of the layer (target zoom area); can be null, then
608 * the viewport isn't changed
609 */
610 public final void addLayer(Layer layer, ProjectionBounds bounds) {
611 addLayer(layer, bounds == null ? null : new ViewportData(bounds));
612 }
613
614 /**
615 * Add a new layer to the map.
616 *
617 * If no map exists, create one.
618 *
619 * @param layer the layer
620 * @param viewport the viewport to zoom to; can be null, then the viewport isn't changed
621 */
622 public final void addLayer(Layer layer, ViewportData viewport) {
623 getLayerManager().addLayer(layer);
624 if (viewport != null && Main.map.mapView != null) {
625 // MapView may be null in headless mode here.
626 Main.map.mapView.scheduleZoomTo(viewport);
627 }
628 }
629
630 /**
631 * Replies the current selected primitives, from a end-user point of view.
632 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
633 * Indeed, if the user is currently in drawing mode, only the way currently being drawn is returned,
634 * see {@link DrawAction#getInProgressSelection()}.
635 *
636 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
637 * @since 6546
638 */
639 public Collection<OsmPrimitive> getInProgressSelection() {
640 if (map != null && map.mapMode instanceof DrawAction) {
641 return ((DrawAction) map.mapMode).getInProgressSelection();
642 } else {
643 DataSet ds = getLayerManager().getEditDataSet();
644 if (ds == null) return null;
645 return ds.getSelected();
646 }
647 }
648
649 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
650
651 public static void redirectToMainContentPane(JComponent source) {
652 RedirectInputMap.redirect(source, contentPanePrivate);
653 }
654
655 public static void registerActionShortcut(JosmAction action) {
656 registerActionShortcut(action, action.getShortcut());
657 }
658
659 public static void registerActionShortcut(Action action, Shortcut shortcut) {
660 KeyStroke keyStroke = shortcut.getKeyStroke();
661 if (keyStroke == null)
662 return;
663
664 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
665 Object existing = inputMap.get(keyStroke);
666 if (existing != null && !existing.equals(action)) {
667 info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
668 }
669 inputMap.put(keyStroke, action);
670
671 contentPanePrivate.getActionMap().put(action, action);
672 }
673
674 public static void unregisterShortcut(Shortcut shortcut) {
675 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
676 }
677
678 public static void unregisterActionShortcut(JosmAction action) {
679 unregisterActionShortcut(action, action.getShortcut());
680 }
681
682 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
683 unregisterShortcut(shortcut);
684 contentPanePrivate.getActionMap().remove(action);
685 }
686
687 /**
688 * Replies the registered action for the given shortcut
689 * @param shortcut The shortcut to look for
690 * @return the registered action for the given shortcut
691 * @since 5696
692 */
693 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
694 KeyStroke keyStroke = shortcut.getKeyStroke();
695 if (keyStroke == null)
696 return null;
697 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
698 if (action instanceof Action)
699 return (Action) action;
700 return null;
701 }
702
703 ///////////////////////////////////////////////////////////////////////////
704 // Implementation part
705 ///////////////////////////////////////////////////////////////////////////
706
707 /**
708 * Global panel.
709 */
710 public static final JPanel panel = mainPanel;
711
712 private final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
713 menu.undo.setEnabled(queueSize > 0);
714 menu.redo.setEnabled(redoSize > 0);
715 };
716
717 /**
718 * Should be called before the main constructor to setup some parameter stuff
719 */
720 public static void preConstructorInit() {
721 ProjectionPreference.setProjection();
722
723 String defaultlaf = platform.getDefaultStyle();
724 String laf = Main.pref.get("laf", defaultlaf);
725 try {
726 UIManager.setLookAndFeel(laf);
727 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
728 // Try to find look and feel in plugin classloaders
729 Main.trace(e);
730 Class<?> klass = null;
731 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
732 try {
733 klass = cl.loadClass(laf);
734 break;
735 } catch (ClassNotFoundException ex) {
736 Main.trace(ex);
737 }
738 }
739 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
740 try {
741 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
742 } catch (ReflectiveOperationException ex) {
743 warn(ex, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage());
744 } catch (UnsupportedLookAndFeelException ex) {
745 info("Look and Feel not supported: " + laf);
746 Main.pref.put("laf", defaultlaf);
747 trace(ex);
748 }
749 } else {
750 info("Look and Feel not found: " + laf);
751 Main.pref.put("laf", defaultlaf);
752 }
753 } catch (UnsupportedLookAndFeelException e) {
754 info("Look and Feel not supported: " + laf);
755 Main.pref.put("laf", defaultlaf);
756 trace(e);
757 } catch (InstantiationException | IllegalAccessException e) {
758 error(e);
759 }
760 toolbar = new ToolbarPreferences();
761 contentPanePrivate.updateUI();
762 panel.updateUI();
763
764 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
765 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
766 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
767 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
768 // Ensures caret color is the same than text foreground color, see #12257
769 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
770 for (String p : Arrays.asList(
771 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
772 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
773 }
774
775 I18n.translateJavaInternalMessages();
776
777 // init default coordinate format
778 //
779 try {
780 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
781 } catch (IllegalArgumentException iae) {
782 Main.trace(iae);
783 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
784 }
785 }
786
787 protected static void postConstructorProcessCmdLine(ProgramArguments args) {
788 List<File> fileList = new ArrayList<>();
789 for (String s : args.get(Option.DOWNLOAD)) {
790 DownloadParamType.paramType(s).download(s, fileList);
791 }
792 if (!fileList.isEmpty()) {
793 OpenFileAction.openFiles(fileList, true);
794 }
795 for (String s : args.get(Option.DOWNLOADGPS)) {
796 DownloadParamType.paramType(s).downloadGps(s);
797 }
798 for (String s : args.get(Option.SELECTION)) {
799 SearchAction.search(s, SearchAction.SearchMode.add);
800 }
801 }
802
803 /**
804 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
805 * If there are some unsaved data layers, asks first for user confirmation.
806 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
807 * @param exitCode The return code
808 * @param reason the reason for exiting
809 * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
810 * @since 11093 (3378 with a different function signature)
811 */
812 public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
813 final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
814 SaveLayersDialog.saveUnsavedModifications(getLayerManager().getLayers(),
815 reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
816 if (proceed) {
817 if (Main.main != null) {
818 Main.main.shutdown();
819 }
820
821 if (exit) {
822 System.exit(exitCode);
823 }
824 return true;
825 }
826 return false;
827 }
828
829 protected void shutdown() {
830 if (!GraphicsEnvironment.isHeadless()) {
831 worker.shutdown();
832 ImageProvider.shutdown(false);
833 JCSCacheManager.shutdown();
834 }
835 if (map != null) {
836 map.rememberToggleDialogWidth();
837 }
838 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
839 getLayerManager().resetState();
840 try {
841 pref.saveDefaults();
842 } catch (IOException ex) {
843 Main.warn(ex, tr("Failed to save default preferences."));
844 }
845 if (!GraphicsEnvironment.isHeadless()) {
846 worker.shutdownNow();
847 ImageProvider.shutdown(true);
848 }
849 }
850
851 /**
852 * The type of a command line parameter, to be used in switch statements.
853 * @see #paramType
854 */
855 enum DownloadParamType {
856 httpUrl {
857 @Override
858 void download(String s, Collection<File> fileList) {
859 new OpenLocationAction().openUrl(false, s);
860 }
861
862 @Override
863 void downloadGps(String s) {
864 final Bounds b = OsmUrlToBounds.parse(s);
865 if (b == null) {
866 JOptionPane.showMessageDialog(
867 Main.parent,
868 tr("Ignoring malformed URL: \"{0}\"", s),
869 tr("Warning"),
870 JOptionPane.WARNING_MESSAGE
871 );
872 return;
873 }
874 downloadFromParamBounds(true, b);
875 }
876 }, fileUrl {
877 @Override
878 void download(String s, Collection<File> fileList) {
879 File f = null;
880 try {
881 f = new File(new URI(s));
882 } catch (URISyntaxException e) {
883 Main.warn(e);
884 JOptionPane.showMessageDialog(
885 Main.parent,
886 tr("Ignoring malformed file URL: \"{0}\"", s),
887 tr("Warning"),
888 JOptionPane.WARNING_MESSAGE
889 );
890 }
891 if (f != null) {
892 fileList.add(f);
893 }
894 }
895 }, bounds {
896
897 /**
898 * Download area specified on the command line as bounds string.
899 * @param rawGps Flag to download raw GPS tracks
900 * @param s The bounds parameter
901 */
902 private void downloadFromParamBounds(final boolean rawGps, String s) {
903 final StringTokenizer st = new StringTokenizer(s, ",");
904 if (st.countTokens() == 4) {
905 Bounds b = new Bounds(
906 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())),
907 new LatLon(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))
908 );
909 Main.downloadFromParamBounds(rawGps, b);
910 }
911 }
912
913 @Override
914 void download(String param, Collection<File> fileList) {
915 downloadFromParamBounds(false, param);
916 }
917
918 @Override
919 void downloadGps(String param) {
920 downloadFromParamBounds(true, param);
921 }
922 }, fileName {
923 @Override
924 void download(String s, Collection<File> fileList) {
925 fileList.add(new File(s));
926 }
927 };
928
929 /**
930 * Performs the download
931 * @param param represents the object to be downloaded
932 * @param fileList files which shall be opened, should be added to this collection
933 */
934 abstract void download(String param, Collection<File> fileList);
935
936 /**
937 * Performs the GPS download
938 * @param param represents the object to be downloaded
939 */
940 void downloadGps(String param) {
941 JOptionPane.showMessageDialog(
942 Main.parent,
943 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
944 tr("Warning"),
945 JOptionPane.WARNING_MESSAGE
946 );
947 }
948
949 /**
950 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
951 *
952 * @param s A parameter string
953 * @return The guessed parameter type
954 */
955 static DownloadParamType paramType(String s) {
956 if (s.startsWith("http:") || s.startsWith("https:")) return DownloadParamType.httpUrl;
957 if (s.startsWith("file:")) return DownloadParamType.fileUrl;
958 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
959 if (s.matches(coorPattern + "(," + coorPattern + "){3}")) return DownloadParamType.bounds;
960 // everything else must be a file name
961 return DownloadParamType.fileName;
962 }
963 }
964
965 /**
966 * Download area specified as Bounds value.
967 * @param rawGps Flag to download raw GPS tracks
968 * @param b The bounds value
969 */
970 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
971 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
972 // asynchronously launch the download task ...
973 Future<?> future = task.download(true, b, null);
974 // ... and the continuation when the download is finished (this will wait for the download to finish)
975 Main.worker.execute(new PostDownloadHandler(task, future));
976 }
977
978 /**
979 * Identifies the current operating system family and initializes the platform hook accordingly.
980 * @since 1849
981 */
982 public static void determinePlatformHook() {
983 String os = System.getProperty("os.name");
984 if (os == null) {
985 warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
986 platform = new PlatformHookUnixoid();
987 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("windows")) {
988 platform = new PlatformHookWindows();
989 } else if ("Linux".equals(os) || "Solaris".equals(os) ||
990 "SunOS".equals(os) || "AIX".equals(os) ||
991 "FreeBSD".equals(os) || "NetBSD".equals(os) || "OpenBSD".equals(os)) {
992 platform = new PlatformHookUnixoid();
993 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("mac os x")) {
994 platform = new PlatformHookOsx();
995 } else {
996 warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
997 platform = new PlatformHookUnixoid();
998 }
999 }
1000
1001 /* ----------------------------------------------------------------------------------------- */
1002 /* projection handling - Main is a registry for a single, global projection instance */
1003 /* */
1004 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
1005 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
1006 /* ----------------------------------------------------------------------------------------- */
1007 /**
1008 * The projection method used.
1009 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
1010 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
1011 */
1012 private static volatile Projection proj;
1013
1014 /**
1015 * Replies the current projection.
1016 *
1017 * @return the currently active projection
1018 */
1019 public static Projection getProjection() {
1020 return proj;
1021 }
1022
1023 /**
1024 * Sets the current projection
1025 *
1026 * @param p the projection
1027 */
1028 public static void setProjection(Projection p) {
1029 CheckParameterUtil.ensureParameterNotNull(p);
1030 Projection oldValue = proj;
1031 Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
1032 proj = p;
1033 fireProjectionChanged(oldValue, proj, b);
1034 }
1035
1036 /*
1037 * Keep WeakReferences to the listeners. This relieves clients from the burden of
1038 * explicitly removing the listeners and allows us to transparently register every
1039 * created dataset as projection change listener.
1040 */
1041 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
1042
1043 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
1044 if ((newValue == null ^ oldValue == null)
1045 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
1046 if (Main.map != null) {
1047 // This needs to be called first
1048 Main.map.mapView.fixProjection();
1049 }
1050 synchronized (Main.class) {
1051 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1052 while (it.hasNext()) {
1053 WeakReference<ProjectionChangeListener> wr = it.next();
1054 ProjectionChangeListener listener = wr.get();
1055 if (listener == null) {
1056 it.remove();
1057 continue;
1058 }
1059 listener.projectionChanged(oldValue, newValue);
1060 }
1061 }
1062 if (newValue != null && oldBounds != null) {
1063 Main.map.mapView.zoomTo(oldBounds);
1064 }
1065 /* TODO - remove layers with fixed projection */
1066 }
1067 }
1068
1069 /**
1070 * Register a projection change listener.
1071 *
1072 * @param listener the listener. Ignored if <code>null</code>.
1073 */
1074 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
1075 if (listener == null) return;
1076 synchronized (Main.class) {
1077 for (WeakReference<ProjectionChangeListener> wr : listeners) {
1078 // already registered ? => abort
1079 if (wr.get() == listener) return;
1080 }
1081 listeners.add(new WeakReference<>(listener));
1082 }
1083 }
1084
1085 /**
1086 * Removes a projection change listener.
1087 *
1088 * @param listener the listener. Ignored if <code>null</code>.
1089 */
1090 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
1091 if (listener == null) return;
1092 synchronized (Main.class) {
1093 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
1094 while (it.hasNext()) {
1095 WeakReference<ProjectionChangeListener> wr = it.next();
1096 // remove the listener - and any other listener which got garbage
1097 // collected in the meantime
1098 if (wr.get() == null || wr.get() == listener) {
1099 it.remove();
1100 }
1101 }
1102 }
1103 }
1104
1105 /**
1106 * Listener for window switch events.
1107 *
1108 * These are events, when the user activates a window of another application
1109 * or comes back to JOSM. Window switches from one JOSM window to another
1110 * are not reported.
1111 */
1112 public interface WindowSwitchListener {
1113 /**
1114 * Called when the user activates a window of another application.
1115 */
1116 void toOtherApplication();
1117
1118 /**
1119 * Called when the user comes from a window of another application back to JOSM.
1120 */
1121 void fromOtherApplication();
1122 }
1123
1124 private static final List<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<>();
1125
1126 /**
1127 * Register a window switch listener.
1128 *
1129 * @param listener the listener. Ignored if <code>null</code>.
1130 */
1131 public static void addWindowSwitchListener(WindowSwitchListener listener) {
1132 if (listener == null) return;
1133 synchronized (Main.class) {
1134 for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
1135 // already registered ? => abort
1136 if (wr.get() == listener) return;
1137 }
1138 boolean wasEmpty = windowSwitchListeners.isEmpty();
1139 windowSwitchListeners.add(new WeakReference<>(listener));
1140 if (wasEmpty) {
1141 // The following call will have no effect, when there is no window
1142 // at the time. Therefore, MasterWindowListener.setup() will also be
1143 // called, as soon as the main window is shown.
1144 MasterWindowListener.setup();
1145 }
1146 }
1147 }
1148
1149 /**
1150 * Removes a window switch listener.
1151 *
1152 * @param listener the listener. Ignored if <code>null</code>.
1153 */
1154 public static void removeWindowSwitchListener(WindowSwitchListener listener) {
1155 if (listener == null) return;
1156 synchronized (Main.class) {
1157 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1158 while (it.hasNext()) {
1159 WeakReference<WindowSwitchListener> wr = it.next();
1160 // remove the listener - and any other listener which got garbage
1161 // collected in the meantime
1162 if (wr.get() == null || wr.get() == listener) {
1163 it.remove();
1164 }
1165 }
1166 if (windowSwitchListeners.isEmpty()) {
1167 MasterWindowListener.teardown();
1168 }
1169 }
1170 }
1171
1172 /**
1173 * WindowListener, that is registered on all Windows of the application.
1174 *
1175 * Its purpose is to notify WindowSwitchListeners, that the user switches to
1176 * another application, e.g. a browser, or back to JOSM.
1177 *
1178 * When changing from JOSM to another application and back (e.g. two times
1179 * alt+tab), the active Window within JOSM may be different.
1180 * Therefore, we need to register listeners to <strong>all</strong> (visible)
1181 * Windows in JOSM, and it does not suffice to monitor the one that was
1182 * deactivated last.
1183 *
1184 * This class is only "active" on demand, i.e. when there is at least one
1185 * WindowSwitchListener registered.
1186 */
1187 protected static class MasterWindowListener extends WindowAdapter {
1188
1189 private static MasterWindowListener INSTANCE;
1190
1191 public static synchronized MasterWindowListener getInstance() {
1192 if (INSTANCE == null) {
1193 INSTANCE = new MasterWindowListener();
1194 }
1195 return INSTANCE;
1196 }
1197
1198 /**
1199 * Register listeners to all non-hidden windows.
1200 *
1201 * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
1202 */
1203 public static void setup() {
1204 if (!windowSwitchListeners.isEmpty()) {
1205 for (Window w : Window.getWindows()) {
1206 if (w.isShowing() && !Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1207 w.addWindowListener(getInstance());
1208 }
1209 }
1210 }
1211 }
1212
1213 /**
1214 * Unregister all listeners.
1215 */
1216 public static void teardown() {
1217 for (Window w : Window.getWindows()) {
1218 w.removeWindowListener(getInstance());
1219 }
1220 }
1221
1222 @Override
1223 public void windowActivated(WindowEvent e) {
1224 if (e.getOppositeWindow() == null) { // we come from a window of a different application
1225 // fire WindowSwitchListeners
1226 synchronized (Main.class) {
1227 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1228 while (it.hasNext()) {
1229 WeakReference<WindowSwitchListener> wr = it.next();
1230 WindowSwitchListener listener = wr.get();
1231 if (listener == null) {
1232 it.remove();
1233 continue;
1234 }
1235 listener.fromOtherApplication();
1236 }
1237 }
1238 }
1239 }
1240
1241 @Override
1242 public void windowDeactivated(WindowEvent e) {
1243 // set up windows that have been created in the meantime
1244 for (Window w : Window.getWindows()) {
1245 if (!w.isShowing()) {
1246 w.removeWindowListener(getInstance());
1247 } else {
1248 if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
1249 w.addWindowListener(getInstance());
1250 }
1251 }
1252 }
1253 if (e.getOppositeWindow() == null) { // we go to a window of a different application
1254 // fire WindowSwitchListeners
1255 synchronized (Main.class) {
1256 Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
1257 while (it.hasNext()) {
1258 WeakReference<WindowSwitchListener> wr = it.next();
1259 WindowSwitchListener listener = wr.get();
1260 if (listener == null) {
1261 it.remove();
1262 continue;
1263 }
1264 listener.toOtherApplication();
1265 }
1266 }
1267 }
1268 }
1269 }
1270
1271 /**
1272 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1273 * @param listener The MapFrameListener
1274 * @param fireWhenMapViewPresent If true, will fire an initial mapFrameInitialized event
1275 * when the MapFrame is present. Otherwise will only fire when the MapFrame is created
1276 * or destroyed.
1277 * @return {@code true} if the listeners collection changed as a result of the call
1278 */
1279 public static boolean addMapFrameListener(MapFrameListener listener, boolean fireWhenMapViewPresent) {
1280 if (fireWhenMapViewPresent) {
1281 return mainPanel.addAndFireMapFrameListener(listener);
1282 } else {
1283 return mainPanel.addMapFrameListener(listener);
1284 }
1285 }
1286
1287 /**
1288 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1289 * @param listener The MapFrameListener
1290 * @return {@code true} if the listeners collection changed as a result of the call
1291 * @since 5957
1292 */
1293 public static boolean addMapFrameListener(MapFrameListener listener) {
1294 return mainPanel.addMapFrameListener(listener);
1295 }
1296
1297 /**
1298 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1299 * @param listener The MapFrameListener
1300 * @return {@code true} if the listeners collection changed as a result of the call
1301 * @since 5957
1302 */
1303 public static boolean removeMapFrameListener(MapFrameListener listener) {
1304 return mainPanel.removeMapFrameListener(listener);
1305 }
1306
1307 /**
1308 * Adds a new network error that occur to give a hint about broken Internet connection.
1309 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1310 *
1311 * @param url The accessed URL that caused the error
1312 * @param t The network error
1313 * @return The previous error associated to the given resource, if any. Can be {@code null}
1314 * @since 6642
1315 */
1316 public static Throwable addNetworkError(URL url, Throwable t) {
1317 if (url != null && t != null) {
1318 Throwable old = addNetworkError(url.toExternalForm(), t);
1319 if (old != null) {
1320 Main.warn("Already here "+old);
1321 }
1322 return old;
1323 }
1324 return null;
1325 }
1326
1327 /**
1328 * Adds a new network error that occur to give a hint about broken Internet connection.
1329 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1330 *
1331 * @param url The accessed URL that caused the error
1332 * @param t The network error
1333 * @return The previous error associated to the given resource, if any. Can be {@code null}
1334 * @since 6642
1335 */
1336 public static Throwable addNetworkError(String url, Throwable t) {
1337 if (url != null && t != null) {
1338 return NETWORK_ERRORS.put(url, t);
1339 }
1340 return null;
1341 }
1342
1343 /**
1344 * Returns the network errors that occured until now.
1345 * @return the network errors that occured until now, indexed by URL
1346 * @since 6639
1347 */
1348 public static Map<String, Throwable> getNetworkErrors() {
1349 return new HashMap<>(NETWORK_ERRORS);
1350 }
1351
1352 /**
1353 * Returns the command-line arguments used to run the application.
1354 * @return the command-line arguments used to run the application
1355 * @since 8356
1356 */
1357 public static List<String> getCommandLineArgs() {
1358 return Collections.unmodifiableList(COMMAND_LINE_ARGS);
1359 }
1360
1361 /**
1362 * Returns the JOSM website URL.
1363 * @return the josm website URL
1364 * @since 6897
1365 */
1366 public static String getJOSMWebsite() {
1367 if (Main.pref != null)
1368 return Main.pref.get("josm.url", JOSM_WEBSITE);
1369 return JOSM_WEBSITE;
1370 }
1371
1372 /**
1373 * Returns the JOSM XML URL.
1374 * @return the josm XML URL
1375 * @since 6897
1376 */
1377 public static String getXMLBase() {
1378 // Always return HTTP (issues reported with HTTPS)
1379 return "http://josm.openstreetmap.de";
1380 }
1381
1382 /**
1383 * Returns the OSM website URL.
1384 * @return the OSM website URL
1385 * @since 6897
1386 */
1387 public static String getOSMWebsite() {
1388 if (Main.pref != null)
1389 return Main.pref.get("osm.url", OSM_WEBSITE);
1390 return OSM_WEBSITE;
1391 }
1392
1393 /**
1394 * Replies the base URL for browsing information about a primitive.
1395 * @return the base URL, i.e. https://www.openstreetmap.org
1396 * @since 7678
1397 */
1398 public static String getBaseBrowseUrl() {
1399 if (Main.pref != null)
1400 return Main.pref.get("osm-browse.url", getOSMWebsite());
1401 return getOSMWebsite();
1402 }
1403
1404 /**
1405 * Replies the base URL for browsing information about a user.
1406 * @return the base URL, i.e. https://www.openstreetmap.org/user
1407 * @since 7678
1408 */
1409 public static String getBaseUserUrl() {
1410 if (Main.pref != null)
1411 return Main.pref.get("osm-user.url", getOSMWebsite() + "/user");
1412 return getOSMWebsite() + "/user";
1413 }
1414
1415 /**
1416 * Determines if we are currently running on OSX.
1417 * @return {@code true} if we are currently running on OSX
1418 * @since 6957
1419 */
1420 public static boolean isPlatformOsx() {
1421 return Main.platform instanceof PlatformHookOsx;
1422 }
1423
1424 /**
1425 * Determines if we are currently running on Windows.
1426 * @return {@code true} if we are currently running on Windows
1427 * @since 7335
1428 */
1429 public static boolean isPlatformWindows() {
1430 return Main.platform instanceof PlatformHookWindows;
1431 }
1432
1433 /**
1434 * Determines if the given online resource is currently offline.
1435 * @param r the online resource
1436 * @return {@code true} if {@code r} is offline and should not be accessed
1437 * @since 7434
1438 */
1439 public static boolean isOffline(OnlineResource r) {
1440 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1441 }
1442
1443 /**
1444 * Sets the given online resource to offline state.
1445 * @param r the online resource
1446 * @return {@code true} if {@code r} was not already offline
1447 * @since 7434
1448 */
1449 public static boolean setOffline(OnlineResource r) {
1450 return OFFLINE_RESOURCES.add(r);
1451 }
1452
1453 /**
1454 * Sets the given online resource to online state.
1455 * @param r the online resource
1456 * @return {@code true} if {@code r} was offline
1457 * @since 8506
1458 */
1459 public static boolean setOnline(OnlineResource r) {
1460 return OFFLINE_RESOURCES.remove(r);
1461 }
1462
1463 /**
1464 * Replies the set of online resources currently offline.
1465 * @return the set of online resources currently offline
1466 * @since 7434
1467 */
1468 public static Set<OnlineResource> getOfflineResources() {
1469 return EnumSet.copyOf(OFFLINE_RESOURCES);
1470 }
1471}
Note: See TracBrowser for help on using the repository browser.