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

Last change on this file since 12043 was 12011, checked in by Don-vip, 22 months ago

improve unit test coverage of Main

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