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

Last change on this file since 11342 was 11339, checked in by simon04, 7 years ago

Loop can be replaced with Collection.removeIf()

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