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

Last change on this file since 11196 was 11106, checked in by Don-vip, 8 years ago

do not shutdown static executor services in headless mode for jenkins unit tests

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