001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trn;
006import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
007
008import java.awt.AWTError;
009import java.awt.Container;
010import java.awt.Dimension;
011import java.awt.Font;
012import java.awt.GraphicsEnvironment;
013import java.awt.GridBagLayout;
014import java.awt.Toolkit;
015import java.io.File;
016import java.io.IOException;
017import java.io.InputStream;
018import java.lang.reflect.Field;
019import java.net.Authenticator;
020import java.net.Inet6Address;
021import java.net.InetAddress;
022import java.net.ProxySelector;
023import java.net.URL;
024import java.nio.file.InvalidPathException;
025import java.nio.file.Paths;
026import java.security.AllPermission;
027import java.security.CodeSource;
028import java.security.GeneralSecurityException;
029import java.security.KeyStoreException;
030import java.security.NoSuchAlgorithmException;
031import java.security.PermissionCollection;
032import java.security.Permissions;
033import java.security.Policy;
034import java.security.cert.CertificateException;
035import java.util.ArrayList;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.List;
040import java.util.Locale;
041import java.util.Map;
042import java.util.Objects;
043import java.util.Optional;
044import java.util.ResourceBundle;
045import java.util.Set;
046import java.util.TreeSet;
047import java.util.concurrent.ExecutorService;
048import java.util.concurrent.Executors;
049import java.util.concurrent.Future;
050import java.util.logging.Level;
051import java.util.stream.Collectors;
052import java.util.stream.Stream;
053
054import javax.net.ssl.SSLSocketFactory;
055import javax.swing.Action;
056import javax.swing.InputMap;
057import javax.swing.JComponent;
058import javax.swing.JLabel;
059import javax.swing.JOptionPane;
060import javax.swing.JPanel;
061import javax.swing.KeyStroke;
062import javax.swing.LookAndFeel;
063import javax.swing.RepaintManager;
064import javax.swing.SwingUtilities;
065import javax.swing.UIManager;
066import javax.swing.UnsupportedLookAndFeelException;
067
068import org.jdesktop.swinghelper.debug.CheckThreadViolationRepaintManager;
069import org.openstreetmap.josm.actions.DeleteAction;
070import org.openstreetmap.josm.actions.JosmAction;
071import org.openstreetmap.josm.actions.OpenFileAction;
072import org.openstreetmap.josm.actions.OpenFileAction.OpenFileTask;
073import org.openstreetmap.josm.actions.PreferencesAction;
074import org.openstreetmap.josm.actions.RestartAction;
075import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
076import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
077import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
078import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
079import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
080import org.openstreetmap.josm.actions.search.SearchAction;
081import org.openstreetmap.josm.cli.CLIModule;
082import org.openstreetmap.josm.command.DeleteCommand;
083import org.openstreetmap.josm.command.SplitWayCommand;
084import org.openstreetmap.josm.data.Bounds;
085import org.openstreetmap.josm.data.Preferences;
086import org.openstreetmap.josm.data.UndoRedoHandler;
087import org.openstreetmap.josm.data.UndoRedoHandler.CommandQueueListener;
088import org.openstreetmap.josm.data.Version;
089import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
090import org.openstreetmap.josm.data.osm.UserInfo;
091import org.openstreetmap.josm.data.osm.search.SearchMode;
092import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
093import org.openstreetmap.josm.data.preferences.JosmUrls;
094import org.openstreetmap.josm.data.preferences.sources.SourceType;
095import org.openstreetmap.josm.data.projection.ProjectionBoundsProvider;
096import org.openstreetmap.josm.data.projection.ProjectionCLI;
097import org.openstreetmap.josm.data.projection.ProjectionRegistry;
098import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileSource;
099import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileWrapper;
100import org.openstreetmap.josm.data.projection.datum.NTV2Proj4DirGridShiftFileSource;
101import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker;
102import org.openstreetmap.josm.gui.ProgramArguments.Option;
103import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
104import org.openstreetmap.josm.gui.bugreport.BugReportDialog;
105import org.openstreetmap.josm.gui.bugreport.DefaultBugReportSendingHandler;
106import org.openstreetmap.josm.gui.download.DownloadDialog;
107import org.openstreetmap.josm.gui.io.CredentialDialog;
108import org.openstreetmap.josm.gui.io.CustomConfigurator.XMLCommandProcessor;
109import org.openstreetmap.josm.gui.io.SaveLayersDialog;
110import org.openstreetmap.josm.gui.layer.AutosaveTask;
111import org.openstreetmap.josm.gui.layer.Layer;
112import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
113import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
114import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
115import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
116import org.openstreetmap.josm.gui.layer.MainLayerManager;
117import org.openstreetmap.josm.gui.layer.OsmDataLayer;
118import org.openstreetmap.josm.gui.mappaint.RenderingCLI;
119import org.openstreetmap.josm.gui.mappaint.loader.MapPaintStyleLoader;
120import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
121import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
122import org.openstreetmap.josm.gui.preferences.display.LafPreference;
123import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
124import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
125import org.openstreetmap.josm.gui.progress.swing.ProgressMonitorExecutor;
126import org.openstreetmap.josm.gui.util.GuiHelper;
127import org.openstreetmap.josm.gui.util.RedirectInputMap;
128import org.openstreetmap.josm.gui.util.WindowGeometry;
129import org.openstreetmap.josm.gui.widgets.UrlLabel;
130import org.openstreetmap.josm.io.CachedFile;
131import org.openstreetmap.josm.io.CertificateAmendment;
132import org.openstreetmap.josm.io.ChangesetUpdater;
133import org.openstreetmap.josm.io.DefaultProxySelector;
134import org.openstreetmap.josm.io.FileWatcher;
135import org.openstreetmap.josm.io.MessageNotifier;
136import org.openstreetmap.josm.io.NetworkManager;
137import org.openstreetmap.josm.io.OnlineResource;
138import org.openstreetmap.josm.io.OsmConnection;
139import org.openstreetmap.josm.io.OsmTransferException;
140import org.openstreetmap.josm.io.auth.AbstractCredentialsAgent;
141import org.openstreetmap.josm.io.auth.CredentialsManager;
142import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
143import org.openstreetmap.josm.io.protocols.data.Handler;
144import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
145import org.openstreetmap.josm.plugins.PluginHandler;
146import org.openstreetmap.josm.plugins.PluginInformation;
147import org.openstreetmap.josm.spi.lifecycle.InitStatusListener;
148import org.openstreetmap.josm.spi.lifecycle.Lifecycle;
149import org.openstreetmap.josm.spi.preferences.Config;
150import org.openstreetmap.josm.tools.FontsManager;
151import org.openstreetmap.josm.tools.GBC;
152import org.openstreetmap.josm.tools.I18n;
153import org.openstreetmap.josm.tools.ImageProvider;
154import org.openstreetmap.josm.tools.JosmRuntimeException;
155import org.openstreetmap.josm.tools.Logging;
156import org.openstreetmap.josm.tools.OsmUrlToBounds;
157import org.openstreetmap.josm.tools.PlatformHook.NativeOsCallback;
158import org.openstreetmap.josm.tools.PlatformHookWindows;
159import org.openstreetmap.josm.tools.PlatformManager;
160import org.openstreetmap.josm.tools.ReflectionUtils;
161import org.openstreetmap.josm.tools.Shortcut;
162import org.openstreetmap.josm.tools.Utils;
163import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
164import org.openstreetmap.josm.tools.bugreport.BugReportQueue;
165import org.openstreetmap.josm.tools.bugreport.BugReportSender;
166import org.xml.sax.SAXException;
167
168/**
169 * Main window class application.
170 *
171 * @author imi
172 */
173public class MainApplication {
174
175    /**
176     * Command-line arguments used to run the application.
177     */
178    private static volatile List<String> commandLineArgs;
179
180    /**
181     * The main menu bar at top of screen.
182     */
183    static MainMenu menu;
184
185    /**
186     * The main panel, required to be static for {@link MapFrameListener} handling.
187     */
188    static MainPanel mainPanel;
189
190    /**
191     * The private content pane of {@link MainFrame}, required to be static for shortcut handling.
192     */
193    static JComponent contentPanePrivate;
194
195    /**
196     * The MapFrame.
197     */
198    static MapFrame map;
199
200    /**
201     * The toolbar preference control to register new actions.
202     */
203    static volatile ToolbarPreferences toolbar;
204
205    private static MainFrame mainFrame;
206
207    /**
208     * The worker thread slave. This is for executing all long and intensive
209     * calculations. The executed runnables are guaranteed to be executed separately and sequential.
210     * @since 12634 (as a replacement to {@code Main.worker})
211     */
212    public static final ExecutorService worker = new ProgressMonitorExecutor("main-worker-%d", Thread.NORM_PRIORITY);
213
214    /**
215     * Provides access to the layers displayed in the main view.
216     */
217    private static final MainLayerManager layerManager = new MainLayerManager();
218
219    private static final LayerChangeListener undoRedoCleaner = new LayerChangeListener() {
220        @Override
221        public void layerRemoving(LayerRemoveEvent e) {
222            Layer layer = e.getRemovedLayer();
223            if (layer instanceof OsmDataLayer) {
224                UndoRedoHandler.getInstance().clean(((OsmDataLayer) layer).getDataSet());
225            }
226        }
227
228        @Override
229        public void layerOrderChanged(LayerOrderChangeEvent e) {
230            // Do nothing
231        }
232
233        @Override
234        public void layerAdded(LayerAddEvent e) {
235            // Do nothing
236        }
237    };
238
239    private static final ProjectionBoundsProvider mainBoundsProvider = new ProjectionBoundsProvider() {
240        @Override
241        public Bounds getRealBounds() {
242            return isDisplayingMapView() ? map.mapView.getRealBounds() : null;
243        }
244
245        @Override
246        public void restoreOldBounds(Bounds oldBounds) {
247            if (isDisplayingMapView()) {
248                map.mapView.zoomTo(oldBounds);
249            }
250        }
251    };
252
253    private static final List<CLIModule> cliModules = new ArrayList<>();
254
255    /**
256     * Default JOSM command line interface.
257     * <p>
258     * Runs JOSM and performs some action, depending on the options and positional
259     * arguments.
260     */
261    public static final CLIModule JOSM_CLI_MODULE = new CLIModule() {
262        @Override
263        public String getActionKeyword() {
264            return "runjosm";
265        }
266
267        @Override
268        public void processArguments(String[] argArray) {
269            ProgramArguments args = null;
270            // construct argument table
271            try {
272                args = new ProgramArguments(argArray);
273            } catch (IllegalArgumentException e) {
274                System.err.println(e.getMessage());
275                System.exit(1);
276            }
277            mainJOSM(args);
278        }
279    };
280
281    /**
282     * Listener that sets the enabled state of undo/redo menu entries.
283     */
284    final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
285            menu.undo.setEnabled(queueSize > 0);
286            menu.redo.setEnabled(redoSize > 0);
287        };
288
289    /**
290     * Source of NTV2 shift files: Download from JOSM website.
291     * @since 12777
292     */
293    public static final NTV2GridShiftFileSource JOSM_WEBSITE_NTV2_SOURCE = gridFileName -> {
294        String location = Config.getUrls().getJOSMWebsite() + "/proj/" + gridFileName;
295        // Try to load grid file
296        @SuppressWarnings("resource")
297        CachedFile cf = new CachedFile(location);
298        try {
299            return cf.getInputStream();
300        } catch (IOException ex) {
301            Logging.warn(ex);
302            return null;
303        }
304    };
305
306    static {
307        registerCLIModule(JOSM_CLI_MODULE);
308        registerCLIModule(ProjectionCLI.INSTANCE);
309        registerCLIModule(RenderingCLI.INSTANCE);
310    }
311
312    /**
313     * Register a command line interface module.
314     * @param module the module
315     * @since 12886
316     */
317    public static void registerCLIModule(CLIModule module) {
318        cliModules.add(module);
319    }
320
321    /**
322     * Constructs a new {@code MainApplication} without a window.
323     */
324    public MainApplication() {
325        this(null);
326    }
327
328    /**
329     * Constructs a main frame, ready sized and operating. Does not display the frame.
330     * @param mainFrame The main JFrame of the application
331     * @since 10340
332     */
333    public MainApplication(MainFrame mainFrame) {
334        MainApplication.mainFrame = mainFrame;
335        getLayerManager().addLayerChangeListener(undoRedoCleaner);
336        ProjectionRegistry.setboundsProvider(mainBoundsProvider);
337        Lifecycle.setShutdownSequence(new MainTermination());
338    }
339
340    /**
341     * Asks user to update its version of Java.
342     * @param updVersion target update version
343     * @param url download URL
344     * @param major true for a migration towards a major version of Java (8:9), false otherwise
345     * @param eolDate the EOL/expiration date
346     * @since 12270
347     */
348    public static void askUpdateJava(String updVersion, String url, String eolDate, boolean major) {
349        ExtendedDialog ed = new ExtendedDialog(
350                mainFrame,
351                tr("Outdated Java version"),
352                tr("OK"), tr("Update Java"), tr("Cancel"));
353        // Check if the dialog has not already been permanently hidden by user
354        if (!ed.toggleEnable("askUpdateJava"+updVersion).toggleCheckState()) {
355            ed.setButtonIcons("ok", "java", "cancel").setCancelButton(3);
356            ed.setMinimumSize(new Dimension(480, 300));
357            ed.setIcon(JOptionPane.WARNING_MESSAGE);
358            StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.",
359                    "<b>"+getSystemProperty("java.version")+"</b>")).append("<br><br>");
360            if ("Sun Microsystems Inc.".equals(getSystemProperty("java.vendor")) && !PlatformManager.getPlatform().isOpenJDK()) {
361                content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
362                        "Oracle", eolDate)).append("</b><br><br>");
363            }
364            content.append("<b>")
365                   .append(major ?
366                        tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", updVersion) :
367                        tr("You may face critical Java bugs; we highly recommend you to update to Java {0}.", updVersion))
368                   .append("</b><br><br>")
369                   .append(tr("Would you like to update now ?"));
370            ed.setContent(content.toString());
371
372            if (ed.showDialog().getValue() == 2) {
373                try {
374                    PlatformManager.getPlatform().openUrl(url);
375                } catch (IOException e) {
376                    Logging.warn(e);
377                }
378            }
379        }
380    }
381
382    /**
383     * Called once at startup to initialize the main window content.
384     * Should set {@link #menu} and {@link #mainPanel}
385     */
386    protected void initializeMainWindow() {
387        if (mainFrame != null) {
388            mainPanel = mainFrame.getPanel();
389            mainFrame.initialize();
390            menu = mainFrame.getMenu();
391        } else {
392            // required for running some tests.
393            mainPanel = new MainPanel(layerManager);
394            menu = new MainMenu();
395        }
396        mainPanel.addMapFrameListener((o, n) -> redoUndoListener.commandChanged(0, 0));
397        mainPanel.reAddListeners();
398    }
399
400    /**
401     * Returns the JOSM main frame.
402     * @return the JOSM main frame
403     * @since 14140
404     */
405    public static MainFrame getMainFrame() {
406        return mainFrame;
407    }
408
409    /**
410     * Returns the command-line arguments used to run the application.
411     * @return the command-line arguments used to run the application
412     * @since 11650
413     */
414    public static List<String> getCommandLineArgs() {
415        return Collections.unmodifiableList(commandLineArgs);
416    }
417
418    /**
419     * Returns the main layer manager that is used by the map view.
420     * @return The layer manager. The value returned will never change.
421     * @since 12636 (as a replacement to {@code Main.getLayerManager()})
422     */
423    public static MainLayerManager getLayerManager() {
424        return layerManager;
425    }
426
427    /**
428     * Returns the MapFrame.
429     * <p>
430     * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
431     * @return the MapFrame
432     * @see MainPanel
433     * @since 12630
434     */
435    public static MapFrame getMap() {
436        return map;
437    }
438
439    /**
440     * Returns the main panel.
441     * @return the main panel
442     * @since 12642
443     */
444    public static MainPanel getMainPanel() {
445        return mainPanel;
446    }
447
448    /**
449     * Returns the main menu, at top of screen.
450     * @return the main menu
451     * @since 12643 (as a replacement to {@code MainApplication.getMenu()})
452     */
453    public static MainMenu getMenu() {
454        return menu;
455    }
456
457    /**
458     * Returns the toolbar preference control to register new actions.
459     * @return the toolbar preference control
460     * @since 12637
461     */
462    public static ToolbarPreferences getToolbar() {
463        return toolbar;
464    }
465
466    /**
467     * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
468     * it only shows the MOTD panel.
469     * <p>
470     * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
471     *
472     * @return <code>true</code> if JOSM currently displays a map view
473     * @since 12630 (as a replacement to {@code Main.isDisplayingMapView()})
474     */
475    public static boolean isDisplayingMapView() {
476        return map != null && map.mapView != null;
477    }
478
479    /**
480     * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
481     * If there are some unsaved data layers, asks first for user confirmation.
482     * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
483     * @param exitCode The return code
484     * @param reason the reason for exiting
485     * @return {@code true} if JOSM has been closed, {@code false} if the user has cancelled the operation.
486     * @since 12636 (specialized version of {@link Lifecycle#exitJosm})
487     */
488    public static boolean exitJosm(boolean exit, int exitCode, SaveLayersDialog.Reason reason) {
489        final boolean proceed = Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
490                SaveLayersDialog.saveUnsavedModifications(layerManager.getLayers(),
491                        reason != null ? reason : SaveLayersDialog.Reason.EXIT)));
492        if (proceed) {
493            return Lifecycle.exitJosm(exit, exitCode);
494        }
495        return false;
496    }
497
498    /**
499     * Redirects the key inputs from {@code source} to main content pane.
500     * @param source source component from which key inputs are redirected
501     */
502    public static void redirectToMainContentPane(JComponent source) {
503        RedirectInputMap.redirect(source, contentPanePrivate);
504    }
505
506    /**
507     * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
508     * <p>
509     * It will fire an initial mapFrameInitialized event when the MapFrame is present.
510     * Otherwise will only fire when the MapFrame is created or destroyed.
511     * @param listener The MapFrameListener
512     * @return {@code true} if the listeners collection changed as a result of the call
513     * @see #addMapFrameListener
514     * @since 12639 (as a replacement to {@code Main.addAndFireMapFrameListener})
515     */
516    public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
517        return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
518    }
519
520    /**
521     * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
522     * @param listener The MapFrameListener
523     * @return {@code true} if the listeners collection changed as a result of the call
524     * @see #addAndFireMapFrameListener
525     * @since 12639 (as a replacement to {@code Main.addMapFrameListener})
526     */
527    public static boolean addMapFrameListener(MapFrameListener listener) {
528        return mainPanel != null && mainPanel.addMapFrameListener(listener);
529    }
530
531    /**
532     * Unregisters the given {@code MapFrameListener} from MapFrame changes
533     * @param listener The MapFrameListener
534     * @return {@code true} if the listeners collection changed as a result of the call
535     * @since 12639 (as a replacement to {@code Main.removeMapFrameListener})
536     */
537    public static boolean removeMapFrameListener(MapFrameListener listener) {
538        return mainPanel != null && mainPanel.removeMapFrameListener(listener);
539    }
540
541    /**
542     * Registers a {@code JosmAction} and its shortcut.
543     * @param action action defining its own shortcut
544     * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
545     */
546    public static void registerActionShortcut(JosmAction action) {
547        registerActionShortcut(action, action.getShortcut());
548    }
549
550    /**
551     * Registers an action and its shortcut.
552     * @param action action to register
553     * @param shortcut shortcut to associate to {@code action}
554     * @since 12639 (as a replacement to {@code Main.registerActionShortcut})
555     */
556    public static void registerActionShortcut(Action action, Shortcut shortcut) {
557        KeyStroke keyStroke = shortcut.getKeyStroke();
558        if (keyStroke == null)
559            return;
560
561        InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
562        Object existing = inputMap.get(keyStroke);
563        if (existing != null && !existing.equals(action)) {
564            Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
565        }
566        inputMap.put(keyStroke, action);
567
568        contentPanePrivate.getActionMap().put(action, action);
569    }
570
571    /**
572     * Unregisters a shortcut.
573     * @param shortcut shortcut to unregister
574     * @since 12639 (as a replacement to {@code Main.unregisterShortcut})
575     */
576    public static void unregisterShortcut(Shortcut shortcut) {
577        contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
578    }
579
580    /**
581     * Unregisters a {@code JosmAction} and its shortcut.
582     * @param action action to unregister
583     * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
584     */
585    public static void unregisterActionShortcut(JosmAction action) {
586        unregisterActionShortcut(action, action.getShortcut());
587    }
588
589    /**
590     * Unregisters an action and its shortcut.
591     * @param action action to unregister
592     * @param shortcut shortcut to unregister
593     * @since 12639 (as a replacement to {@code Main.unregisterActionShortcut})
594     */
595    public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
596        unregisterShortcut(shortcut);
597        contentPanePrivate.getActionMap().remove(action);
598    }
599
600    /**
601     * Replies the registered action for the given shortcut
602     * @param shortcut The shortcut to look for
603     * @return the registered action for the given shortcut
604     * @since 12639 (as a replacement to {@code Main.getRegisteredActionShortcut})
605     */
606    public static Action getRegisteredActionShortcut(Shortcut shortcut) {
607        KeyStroke keyStroke = shortcut.getKeyStroke();
608        if (keyStroke == null)
609            return null;
610        Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
611        if (action instanceof Action)
612            return (Action) action;
613        return null;
614    }
615
616    /**
617     * Displays help on the console
618     * @since 2748
619     */
620    public static void showHelp() {
621        // TODO: put in a platformHook for system that have no console by default
622        System.out.println(getHelp());
623    }
624
625    static String getHelp() {
626        return tr("Java OpenStreetMap Editor")+" ["
627                +Version.getInstance().getAgentString()+"]\n\n"+
628                tr("usage")+":\n"+
629                "\tjava -jar josm.jar [<command>] <options>...\n\n"+
630                tr("commands")+":\n"+
631                "\trunjosm     "+tr("launch JOSM (default, performed when no command is specified)")+'\n'+
632                "\trender      "+tr("render data and save the result to an image file")+'\n'+
633                "\tproject     "+tr("convert coordinates from one coordinate reference system to another")+"\n\n"+
634                tr("For details on the {0} and {1} commands, run them with the {2} option.", "render", "project", "--help")+'\n'+
635                tr("The remainder of this help page documents the {0} command.", "runjosm")+"\n\n"+
636                tr("options")+":\n"+
637                "\t--help|-h                                 "+tr("Show this help")+'\n'+
638                "\t--geometry=widthxheight(+|-)x(+|-)y       "+tr("Standard unix geometry argument")+'\n'+
639                "\t[--download=]minlat,minlon,maxlat,maxlon  "+tr("Download the bounding box")+'\n'+
640                "\t[--download=]<URL>                        "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z)")+'\n'+
641                "\t[--download=]<filename>                   "+tr("Open a file (any file type that can be opened with File/Open)")+'\n'+
642                "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw GPS")+'\n'+
643                "\t--downloadgps=<URL>                       "+tr("Download the location at the URL (with lat=x&lon=y&zoom=z) as raw GPS")+'\n'+
644                "\t--selection=<searchstring>                "+tr("Select with the given search")+'\n'+
645                "\t--[no-]maximize                           "+tr("Launch in maximized mode")+'\n'+
646                "\t--reset-preferences                       "+tr("Reset the preferences to default")+"\n\n"+
647                "\t--load-preferences=<url-to-xml>           "+tr("Changes preferences according to the XML file")+"\n\n"+
648                "\t--set=<key>=<value>                       "+tr("Set preference key to value")+"\n\n"+
649                "\t--language=<language>                     "+tr("Set the language")+"\n\n"+
650                "\t--version                                 "+tr("Displays the JOSM version and exits")+"\n\n"+
651                "\t--debug                                   "+tr("Print debugging messages to console")+"\n\n"+
652                "\t--skip-plugins                            "+tr("Skip loading plugins")+"\n\n"+
653                "\t--offline=<osm_api|josm_website|all>      "+tr("Disable access to the given resource(s), separated by comma")+"\n\n"+
654                tr("options provided as Java system properties")+":\n"+
655                align("\t-Djosm.dir.name=JOSM") + tr("Change the JOSM directory name") + "\n\n" +
656                align("\t-Djosm.pref=" + tr("/PATH/TO/JOSM/PREF    ")) + tr("Set the preferences directory") + "\n" +
657                align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultPrefDirectory()) + "\n\n" +
658                align("\t-Djosm.userdata=" + tr("/PATH/TO/JOSM/USERDATA")) + tr("Set the user data directory") + "\n" +
659                align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultUserDataDirectory()) + "\n\n" +
660                align("\t-Djosm.cache=" + tr("/PATH/TO/JOSM/CACHE   ")) + tr("Set the cache directory") + "\n" +
661                align("\t") + tr("Default: {0}", PlatformManager.getPlatform().getDefaultCacheDirectory()) + "\n\n" +
662                align("\t-Djosm.home=" + tr("/PATH/TO/JOSM/HOMEDIR ")) +
663                tr("Set the preferences+data+cache directory (cache directory will be josm.home/cache)")+"\n\n"+
664                tr("-Djosm.home has lower precedence, i.e. the specific setting overrides the general one")+"\n\n"+
665                tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
666                        "      Java option to specify the maximum size of allocated memory in megabytes")+":\n"+
667                        "\t-Xmx...m\n\n"+
668                tr("examples")+":\n"+
669                "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
670                "\tjava -jar josm.jar "+OsmUrlToBounds.getURL(43.2, 11.1, 13)+'\n'+
671                "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
672                "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
673                "\tjava -Djosm.pref=$XDG_CONFIG_HOME -Djosm.userdata=$XDG_DATA_HOME -Djosm.cache=$XDG_CACHE_HOME -jar josm.jar\n"+
674                "\tjava -Djosm.dir.name=josm_dev -jar josm.jar\n"+
675                "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
676                "\tjava -Xmx1024m -jar josm.jar\n\n"+
677                tr("Parameters --download, --downloadgps, and --selection are processed in this order.")+'\n'+
678                tr("Make sure you load some data if you use --selection.")+'\n';
679    }
680
681    private static String align(String str) {
682        return str + Stream.generate(() -> " ").limit(Math.max(0, 43 - str.length())).collect(Collectors.joining(""));
683    }
684
685    /**
686     * Main application Startup
687     * @param argArray Command-line arguments
688     */
689    public static void main(final String[] argArray) {
690        I18n.init();
691        commandLineArgs = Arrays.asList(Arrays.copyOf(argArray, argArray.length));
692
693        if (argArray.length > 0) {
694            String moduleStr = argArray[0];
695            for (CLIModule module : cliModules) {
696                if (Objects.equals(moduleStr, module.getActionKeyword())) {
697                   String[] argArrayCdr = Arrays.copyOfRange(argArray, 1, argArray.length);
698                   module.processArguments(argArrayCdr);
699                   return;
700                }
701            }
702        }
703        // no module specified, use default (josm)
704        JOSM_CLI_MODULE.processArguments(argArray);
705    }
706
707    /**
708     * Main method to run the JOSM GUI.
709     * @param args program arguments
710     */
711    public static void mainJOSM(ProgramArguments args) {
712
713        if (!GraphicsEnvironment.isHeadless()) {
714            BugReportQueue.getInstance().setBugReportHandler(BugReportDialog::showFor);
715            BugReportSender.setBugReportSendingHandler(new DefaultBugReportSendingHandler());
716        }
717
718        Level logLevel = args.getLogLevel();
719        Logging.setLogLevel(logLevel);
720        if (!args.showVersion() && !args.showHelp()) {
721            Logging.info(tr("Log level is at {0} ({1}, {2})", logLevel.getLocalizedName(), logLevel.getName(), logLevel.intValue()));
722        }
723
724        Optional<String> language = args.getSingle(Option.LANGUAGE);
725        I18n.set(language.orElse(null));
726
727        try {
728            Policy.setPolicy(new Policy() {
729                // Permissions for plug-ins loaded when josm is started via webstart
730                private PermissionCollection pc;
731
732                {
733                    pc = new Permissions();
734                    pc.add(new AllPermission());
735                }
736
737                @Override
738                public PermissionCollection getPermissions(CodeSource codesource) {
739                    return pc;
740                }
741            });
742        } catch (SecurityException e) {
743            Logging.log(Logging.LEVEL_ERROR, "Unable to set permissions", e);
744        }
745
746        try {
747            Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
748        } catch (SecurityException e) {
749            Logging.log(Logging.LEVEL_ERROR, "Unable to set uncaught exception handler", e);
750        }
751
752        // initialize the platform hook, and
753        PlatformManager.getPlatform().setNativeOsCallback(new DefaultNativeOsCallback());
754        // call the really early hook before we do anything else
755        PlatformManager.getPlatform().preStartupHook();
756
757        Preferences prefs = Preferences.main();
758        Config.setPreferencesInstance(prefs);
759        Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
760        Config.setUrlsProvider(JosmUrls.getInstance());
761
762        if (args.showVersion()) {
763            System.out.println(Version.getInstance().getAgentString());
764            return;
765        } else if (args.showHelp()) {
766            showHelp();
767            return;
768        }
769
770        boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
771        if (skipLoadingPlugins) {
772            Logging.info(tr("Plugin loading skipped"));
773        }
774
775        if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
776            // Enable debug in OAuth signpost via system preference, but only at trace level
777            Utils.updateSystemProperty("debug", "true");
778            Logging.info(tr("Enabled detailed debug level (trace)"));
779        }
780
781        try {
782            Preferences.main().init(args.hasOption(Option.RESET_PREFERENCES));
783        } catch (SecurityException e) {
784            Logging.log(Logging.LEVEL_ERROR, "Unable to initialize preferences", e);
785        }
786
787        args.getPreferencesToSet().forEach(prefs::put);
788
789        if (!language.isPresent()) {
790            I18n.set(Config.getPref().get("language", null));
791        }
792        updateSystemProperties();
793        Preferences.main().addPreferenceChangeListener(e -> updateSystemProperties());
794
795        checkIPv6();
796
797        processOffline(args);
798
799        PlatformManager.getPlatform().afterPrefStartupHook();
800
801        applyWorkarounds();
802
803        FontsManager.initialize();
804
805        GuiHelper.setupLanguageFonts();
806
807        Handler.install();
808
809        WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
810                args.getSingle(Option.GEOMETRY).orElse(null),
811                !args.hasOption(Option.NO_MAXIMIZE) && Config.getPref().getBoolean("gui.maximized", false));
812        final MainFrame mainFrame = createMainFrame(geometry);
813        final Container contentPane = mainFrame.getContentPane();
814        if (contentPane instanceof JComponent) {
815            contentPanePrivate = (JComponent) contentPane;
816        }
817        mainPanel = mainFrame.getPanel();
818
819        if (args.hasOption(Option.LOAD_PREFERENCES)) {
820            XMLCommandProcessor config = new XMLCommandProcessor(prefs);
821            for (String i : args.get(Option.LOAD_PREFERENCES)) {
822                try {
823                    URL url = i.contains(":/") ? new URL(i) : Paths.get(i).toUri().toURL();
824                    Logging.info("Reading preferences from " + url);
825                    try (InputStream is = Utils.openStream(url)) {
826                        config.openAndReadXML(is);
827                    }
828                } catch (IOException | InvalidPathException ex) {
829                    Logging.error(ex);
830                    return;
831                }
832            }
833        }
834
835        try {
836            CertificateAmendment.addMissingCertificates();
837        } catch (IOException | GeneralSecurityException ex) {
838            Logging.warn(ex);
839            Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
840        }
841        try {
842            Authenticator.setDefault(DefaultAuthenticator.getInstance());
843        } catch (SecurityException e) {
844            Logging.log(Logging.LEVEL_ERROR, "Unable to set default authenticator", e);
845        }
846        DefaultProxySelector proxySelector = null;
847        try {
848            proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
849        } catch (SecurityException e) {
850            Logging.log(Logging.LEVEL_ERROR, "Unable to get default proxy selector", e);
851        }
852        try {
853            if (proxySelector != null) {
854                ProxySelector.setDefault(proxySelector);
855            }
856        } catch (SecurityException e) {
857            Logging.log(Logging.LEVEL_ERROR, "Unable to set default proxy selector", e);
858        }
859        OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance());
860
861        setupCallbacks();
862
863        final SplashScreen splash = GuiHelper.runInEDTAndWaitAndReturn(SplashScreen::new);
864        // splash can be null sometimes on Linux, in this case try to load JOSM silently
865        final SplashProgressMonitor monitor = splash != null ? splash.getProgressMonitor() : new SplashProgressMonitor(null, e -> {
866            if (e != null) {
867                Logging.debug(e.toString());
868            }
869        });
870        monitor.beginTask(tr("Initializing"));
871        if (splash != null) {
872            GuiHelper.runInEDT(() -> splash.setVisible(Config.getPref().getBoolean("draw.splashscreen", true)));
873        }
874        Lifecycle.setInitStatusListener(new InitStatusListener() {
875
876            @Override
877            public Object updateStatus(String event) {
878                monitor.beginTask(event);
879                return event;
880            }
881
882            @Override
883            public void finish(Object status) {
884                if (status instanceof String) {
885                    monitor.finishTask((String) status);
886                }
887            }
888        });
889
890        Collection<PluginInformation> pluginsToLoad = null;
891
892        if (!skipLoadingPlugins) {
893            pluginsToLoad = updateAndLoadEarlyPlugins(splash, monitor);
894        }
895
896        monitor.indeterminateSubTask(tr("Setting defaults"));
897        setupUIManager();
898        toolbar = new ToolbarPreferences();
899        ProjectionPreference.setProjection();
900        setupNadGridSources();
901        GuiHelper.translateJavaInternalMessages();
902
903        monitor.indeterminateSubTask(tr("Creating main GUI"));
904        Lifecycle.initialize(new MainInitialization(new MainApplication(mainFrame)));
905
906        if (!skipLoadingPlugins) {
907            loadLatePlugins(splash, monitor, pluginsToLoad);
908        }
909
910        // Wait for splash disappearance (fix #9714)
911        GuiHelper.runInEDTAndWait(() -> {
912            if (splash != null) {
913                splash.setVisible(false);
914                splash.dispose();
915            }
916            mainFrame.setVisible(true);
917        });
918
919        boolean maximized = Config.getPref().getBoolean("gui.maximized", false);
920        if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
921            mainFrame.setMaximized(true);
922        }
923        if (menu.fullscreenToggleAction != null) {
924            menu.fullscreenToggleAction.initial();
925        }
926
927        SwingUtilities.invokeLater(new GuiFinalizationWorker(args, proxySelector));
928
929        if (PlatformManager.isPlatformWindows()) {
930            try {
931                // Check for insecure certificates to remove.
932                // This is Windows-dependant code but it can't go to preStartupHook (need i18n)
933                // neither startupHook (need to be called before remote control)
934                PlatformHookWindows.removeInsecureCertificates();
935            } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
936                Logging.error(e);
937            }
938        }
939
940        if (RemoteControl.PROP_REMOTECONTROL_ENABLED.get()) {
941            RemoteControl.start();
942        }
943
944        if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
945            MessageNotifier.start();
946        }
947
948        ChangesetUpdater.start();
949
950        if (Config.getPref().getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) {
951            // Repaint manager is registered so late for a reason - there is lots of violation during startup process
952            // but they don't seem to break anything and are difficult to fix
953            Logging.info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console");
954            RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
955        }
956    }
957
958    private static MainFrame createMainFrame(WindowGeometry geometry) {
959        try {
960            return new MainFrame(geometry);
961        } catch (AWTError e) {
962            // #12022 #16666 On Debian, Ubuntu and Linux Mint the first AWT toolkit access can fail because of ATK wrapper
963            // Good news: the error happens after the toolkit initialization so we can just try again and it will work
964            Logging.error(e);
965            return new MainFrame(geometry);
966        }
967    }
968
969    /**
970     * Updates system properties with the current values in the preferences.
971     */
972    private static void updateSystemProperties() {
973        if ("true".equals(Config.getPref().get("prefer.ipv6", "auto"))
974                && !"true".equals(Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true"))) {
975            // never set this to false, only true!
976            Logging.info(tr("Try enabling IPv6 network, preferring IPv6 over IPv4 (only works on early startup)."));
977        }
978        Utils.updateSystemProperty("http.agent", Version.getInstance().getAgentString());
979        Utils.updateSystemProperty("user.language", Config.getPref().get("language"));
980        // Workaround to fix a Java bug. This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
981        // Force AWT toolkit to update its internal preferences (fix #6345).
982        // Does not work anymore with Java 9, to remove with Java 9 migration
983        if (Utils.getJavaVersion() < 9 && !GraphicsEnvironment.isHeadless()) {
984            try {
985                Field field = Toolkit.class.getDeclaredField("resources");
986                ReflectionUtils.setObjectsAccessible(field);
987                field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
988            } catch (ReflectiveOperationException | RuntimeException e) { // NOPMD
989                // Catch RuntimeException in order to catch InaccessibleObjectException, new in Java 9
990                Logging.log(Logging.LEVEL_WARN, null, e);
991            }
992        }
993        // Possibility to disable SNI (not by default) in case of misconfigured https servers
994        // See #9875 + http://stackoverflow.com/a/14884941/2257172
995        // then https://josm.openstreetmap.de/ticket/12152#comment:5 for details
996        if (Config.getPref().getBoolean("jdk.tls.disableSNIExtension", false)) {
997            Utils.updateSystemProperty("jsse.enableSNIExtension", "false");
998        }
999    }
1000
1001    /**
1002     * Setup the sources for NTV2 grid shift files for projection support.
1003     * @since 12795
1004     */
1005    public static void setupNadGridSources() {
1006        NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
1007                NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_LOCAL,
1008                NTV2Proj4DirGridShiftFileSource.getInstance());
1009        NTV2GridShiftFileWrapper.registerNTV2GridShiftFileSource(
1010                NTV2GridShiftFileWrapper.NTV2_SOURCE_PRIORITY_DOWNLOAD,
1011                JOSM_WEBSITE_NTV2_SOURCE);
1012    }
1013
1014    static void applyWorkarounds() {
1015        // Workaround for JDK-8180379: crash on Windows 10 1703 with Windows L&F and java < 8u141 / 9+172
1016        // To remove during Java 9 migration
1017        if (getSystemProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows 10") &&
1018                PlatformManager.getPlatform().getDefaultStyle().equals(LafPreference.LAF.get())) {
1019            try {
1020                String build = PlatformHookWindows.getCurrentBuild();
1021                if (build != null) {
1022                    final int currentBuild = Integer.parseInt(build);
1023                    final int javaVersion = Utils.getJavaVersion();
1024                    final int javaUpdate = Utils.getJavaUpdate();
1025                    final int javaBuild = Utils.getJavaBuild();
1026                    // See https://technet.microsoft.com/en-us/windows/release-info.aspx
1027                    if (currentBuild >= 15_063 && ((javaVersion == 8 && javaUpdate < 141)
1028                            || (javaVersion == 9 && javaUpdate == 0 && javaBuild < 173))) {
1029                        // Workaround from https://bugs.openjdk.java.net/browse/JDK-8179014
1030                        UIManager.put("FileChooser.useSystemExtensionHiding", Boolean.FALSE);
1031                    }
1032                }
1033            } catch (NumberFormatException | ReflectiveOperationException | JosmRuntimeException e) {
1034                Logging.error(e);
1035            } catch (ExceptionInInitializerError e) {
1036                Logging.log(Logging.LEVEL_ERROR, null, e);
1037            }
1038        }
1039    }
1040
1041    static void setupCallbacks() {
1042        OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
1043        AbstractCredentialsAgent.setCredentialsProvider(CredentialDialog::promptCredentials);
1044        MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages);
1045        DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
1046        SplitWayCommand.setWarningNotifier(msg -> new Notification(msg).setIcon(JOptionPane.WARNING_MESSAGE).show());
1047        FileWatcher.registerLoader(SourceType.MAP_PAINT_STYLE, MapPaintStyleLoader::reloadStyle);
1048        FileWatcher.registerLoader(SourceType.TAGCHECKER_RULE, MapCSSTagChecker::reloadRule);
1049        OsmUrlToBounds.setMapSizeSupplier(() -> {
1050            if (isDisplayingMapView()) {
1051                MapView mapView = getMap().mapView;
1052                return new Dimension(mapView.getWidth(), mapView.getHeight());
1053            } else {
1054                return GuiHelper.getScreenSize();
1055            }
1056        });
1057    }
1058
1059    static void setupUIManager() {
1060        String defaultlaf = PlatformManager.getPlatform().getDefaultStyle();
1061        String laf = LafPreference.LAF.get();
1062        try {
1063            UIManager.setLookAndFeel(laf);
1064        } catch (final NoClassDefFoundError | ClassNotFoundException e) {
1065            // Try to find look and feel in plugin classloaders
1066            Logging.trace(e);
1067            Class<?> klass = null;
1068            for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
1069                try {
1070                    klass = cl.loadClass(laf);
1071                    break;
1072                } catch (ClassNotFoundException ex) {
1073                    Logging.trace(ex);
1074                }
1075            }
1076            if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
1077                try {
1078                    UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
1079                } catch (ReflectiveOperationException ex) {
1080                    Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
1081                } catch (UnsupportedLookAndFeelException ex) {
1082                    Logging.info("Look and Feel not supported: " + laf);
1083                    LafPreference.LAF.put(defaultlaf);
1084                    Logging.trace(ex);
1085                }
1086            } else {
1087                Logging.info("Look and Feel not found: " + laf);
1088                LafPreference.LAF.put(defaultlaf);
1089            }
1090        } catch (UnsupportedLookAndFeelException e) {
1091            Logging.info("Look and Feel not supported: " + laf);
1092            LafPreference.LAF.put(defaultlaf);
1093            Logging.trace(e);
1094        } catch (InstantiationException | IllegalAccessException e) {
1095            Logging.error(e);
1096        }
1097
1098        UIManager.put("OptionPane.okIcon", ImageProvider.getIfAvailable("ok"));
1099        UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
1100        UIManager.put("OptionPane.cancelIcon", ImageProvider.getIfAvailable("cancel"));
1101        UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
1102        // Ensures caret color is the same than text foreground color, see #12257
1103        // See https://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
1104        for (String p : Arrays.asList(
1105                "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
1106            UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
1107        }
1108
1109        double menuFontFactor = Config.getPref().getDouble("gui.scale.menu.font", 1.0);
1110        if (menuFontFactor != 1.0) {
1111            for (String key : Arrays.asList(
1112                    "Menu.font", "MenuItem.font", "CheckBoxMenuItem.font", "RadioButtonMenuItem.font", "MenuItem.acceleratorFont")) {
1113                Font font = UIManager.getFont(key);
1114                if (font != null) {
1115                    UIManager.put(key, font.deriveFont(font.getSize2D() * (float) menuFontFactor));
1116                }
1117            }
1118        }
1119    }
1120
1121    static Collection<PluginInformation> updateAndLoadEarlyPlugins(SplashScreen splash, SplashProgressMonitor monitor) {
1122        Collection<PluginInformation> pluginsToLoad;
1123        pluginsToLoad = PluginHandler.buildListOfPluginsToLoad(splash, monitor.createSubTaskMonitor(1, false));
1124        if (!pluginsToLoad.isEmpty() && PluginHandler.checkAndConfirmPluginUpdate(splash)) {
1125            monitor.subTask(tr("Updating plugins"));
1126            pluginsToLoad = PluginHandler.updatePlugins(splash, null, monitor.createSubTaskMonitor(1, false), false);
1127        }
1128
1129        monitor.indeterminateSubTask(tr("Installing updated plugins"));
1130        try {
1131            PluginHandler.installDownloadedPlugins(pluginsToLoad, true);
1132        } catch (SecurityException e) {
1133            Logging.log(Logging.LEVEL_ERROR, "Unable to install plugins", e);
1134        }
1135
1136        monitor.indeterminateSubTask(tr("Loading early plugins"));
1137        PluginHandler.loadEarlyPlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
1138        return pluginsToLoad;
1139    }
1140
1141    static void loadLatePlugins(SplashScreen splash, SplashProgressMonitor monitor, Collection<PluginInformation> pluginsToLoad) {
1142        monitor.indeterminateSubTask(tr("Loading plugins"));
1143        PluginHandler.loadLatePlugins(splash, pluginsToLoad, monitor.createSubTaskMonitor(1, false));
1144        GuiHelper.runInEDTAndWait(() -> toolbar.refreshToolbarControl());
1145    }
1146
1147    private static void processOffline(ProgramArguments args) {
1148        for (String offlineNames : args.get(Option.OFFLINE)) {
1149            for (String s : offlineNames.split(",")) {
1150                try {
1151                    NetworkManager.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
1152                } catch (IllegalArgumentException e) {
1153                    Logging.log(Logging.LEVEL_ERROR,
1154                            tr("''{0}'' is not a valid value for argument ''{1}''. Possible values are {2}, possibly delimited by commas.",
1155                            s.toUpperCase(Locale.ENGLISH), Option.OFFLINE.getName(), Arrays.toString(OnlineResource.values())), e);
1156                    System.exit(1);
1157                    return;
1158                }
1159            }
1160        }
1161        Set<OnlineResource> offline = NetworkManager.getOfflineResources();
1162        if (!offline.isEmpty()) {
1163            Logging.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
1164                    "JOSM is running in offline mode. These resources will not be available: {0}",
1165                    offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
1166        }
1167    }
1168
1169    /**
1170     * Check if IPv6 can be safely enabled and do so. Because this cannot be done after network activation,
1171     * disabling or enabling IPV6 may only be done with next start.
1172     */
1173    private static void checkIPv6() {
1174        if ("auto".equals(Config.getPref().get("prefer.ipv6", "auto"))) {
1175            new Thread((Runnable) () -> { /* this may take some time (DNS, Connect) */
1176                boolean hasv6 = false;
1177                boolean wasv6 = Config.getPref().getBoolean("validated.ipv6", false);
1178                try {
1179                    /* Use the check result from last run of the software, as after the test, value
1180                       changes have no effect anymore */
1181                    if (wasv6) {
1182                        Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1183                    }
1184                    for (InetAddress a : InetAddress.getAllByName("josm.openstreetmap.de")) {
1185                        if (a instanceof Inet6Address) {
1186                            if (a.isReachable(1000)) {
1187                                /* be sure it REALLY works */
1188                                SSLSocketFactory.getDefault().createSocket(a, 443).close();
1189                                Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true");
1190                                if (!wasv6) {
1191                                    Logging.info(tr("Detected useable IPv6 network, preferring IPv6 over IPv4 after next restart."));
1192                                } else {
1193                                    Logging.info(tr("Detected useable IPv6 network, preferring IPv6 over IPv4."));
1194                                }
1195                                hasv6 = true;
1196                            }
1197                            break; /* we're done */
1198                        }
1199                    }
1200                } catch (IOException | SecurityException e) {
1201                    Logging.debug("Exception while checking IPv6 connectivity: {0}", e);
1202                    Logging.trace(e);
1203                }
1204                if (wasv6 && !hasv6) {
1205                    Logging.info(tr("Detected no useable IPv6 network, preferring IPv4 over IPv6 after next restart."));
1206                    Config.getPref().putBoolean("validated.ipv6", hasv6); // be sure it is stored before the restart!
1207                    try {
1208                        RestartAction.restartJOSM();
1209                    } catch (IOException e) {
1210                        Logging.error(e);
1211                    }
1212                }
1213                Config.getPref().putBoolean("validated.ipv6", hasv6);
1214            }, "IPv6-checker").start();
1215        }
1216    }
1217
1218    /**
1219     * Download area specified as Bounds value.
1220     * @param rawGps Flag to download raw GPS tracks
1221     * @param b The bounds value
1222     * @return the complete download task (including post-download handler)
1223     */
1224    static List<Future<?>> downloadFromParamBounds(final boolean rawGps, Bounds b) {
1225        DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
1226        // asynchronously launch the download task ...
1227        Future<?> future = task.download(new DownloadParams().withNewLayer(true), b, null);
1228        // ... and the continuation when the download is finished (this will wait for the download to finish)
1229        return Collections.singletonList(MainApplication.worker.submit(new PostDownloadHandler(task, future)));
1230    }
1231
1232    /**
1233     * Handle command line instructions after GUI has been initialized.
1234     * @param args program arguments
1235     * @return the list of submitted tasks
1236     */
1237    static List<Future<?>> postConstructorProcessCmdLine(ProgramArguments args) {
1238        List<Future<?>> tasks = new ArrayList<>();
1239        List<File> fileList = new ArrayList<>();
1240        for (String s : args.get(Option.DOWNLOAD)) {
1241            tasks.addAll(DownloadParamType.paramType(s).download(s, fileList));
1242        }
1243        if (!fileList.isEmpty()) {
1244            tasks.add(OpenFileAction.openFiles(fileList, true));
1245        }
1246        for (String s : args.get(Option.DOWNLOADGPS)) {
1247            tasks.addAll(DownloadParamType.paramType(s).downloadGps(s));
1248        }
1249        final Collection<String> selectionArguments = args.get(Option.SELECTION);
1250        if (!selectionArguments.isEmpty()) {
1251            tasks.add(MainApplication.worker.submit(() -> {
1252                for (String s : selectionArguments) {
1253                    SearchAction.search(s, SearchMode.add);
1254                }
1255            }));
1256        }
1257        return tasks;
1258    }
1259
1260    private static class GuiFinalizationWorker implements Runnable {
1261
1262        private final ProgramArguments args;
1263        private final DefaultProxySelector proxySelector;
1264
1265        GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
1266            this.args = args;
1267            this.proxySelector = proxySelector;
1268        }
1269
1270        @Override
1271        public void run() {
1272
1273            // Handle proxy/network errors early to inform user he should change settings to be able to use JOSM correctly
1274            if (!handleProxyErrors()) {
1275                handleNetworkErrors();
1276            }
1277
1278            // Restore autosave layers after crash and start autosave thread
1279            handleAutosave();
1280
1281            // Handle command line instructions
1282            postConstructorProcessCmdLine(args);
1283
1284            // Show download dialog if autostart is enabled
1285            DownloadDialog.autostartIfNeeded();
1286        }
1287
1288        private static void handleAutosave() {
1289            if (AutosaveTask.PROP_AUTOSAVE_ENABLED.get()) {
1290                AutosaveTask autosaveTask = new AutosaveTask();
1291                List<File> unsavedLayerFiles = autosaveTask.getUnsavedLayersFiles();
1292                if (!unsavedLayerFiles.isEmpty()) {
1293                    ExtendedDialog dialog = new ExtendedDialog(
1294                            mainFrame,
1295                            tr("Unsaved osm data"),
1296                            tr("Restore"), tr("Cancel"), tr("Discard")
1297                            );
1298                    dialog.setContent(
1299                            trn("JOSM found {0} unsaved osm data layer. ",
1300                                    "JOSM found {0} unsaved osm data layers. ", unsavedLayerFiles.size(), unsavedLayerFiles.size()) +
1301                                    tr("It looks like JOSM crashed last time. Would you like to restore the data?"));
1302                    dialog.setButtonIcons("ok", "cancel", "dialogs/delete");
1303                    int selection = dialog.showDialog().getValue();
1304                    if (selection == 1) {
1305                        autosaveTask.recoverUnsavedLayers();
1306                    } else if (selection == 3) {
1307                        autosaveTask.discardUnsavedLayers();
1308                    }
1309                }
1310                try {
1311                    autosaveTask.schedule();
1312                } catch (SecurityException e) {
1313                    Logging.log(Logging.LEVEL_ERROR, "Unable to schedule autosave!", e);
1314                }
1315            }
1316        }
1317
1318        private static boolean handleNetworkOrProxyErrors(boolean hasErrors, String title, String message) {
1319            if (hasErrors) {
1320                ExtendedDialog ed = new ExtendedDialog(
1321                        mainFrame, title,
1322                        tr("Change proxy settings"), tr("Cancel"));
1323                ed.setButtonIcons("dialogs/settings", "cancel").setCancelButton(2);
1324                ed.setMinimumSize(new Dimension(460, 260));
1325                ed.setIcon(JOptionPane.WARNING_MESSAGE);
1326                ed.setContent(message);
1327
1328                if (ed.showDialog().getValue() == 1) {
1329                    PreferencesAction.forPreferenceSubTab(null, null, ProxyPreference.class).run();
1330                }
1331            }
1332            return hasErrors;
1333        }
1334
1335        private boolean handleProxyErrors() {
1336            return proxySelector != null &&
1337                handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
1338                    tr("JOSM tried to access the following resources:<br>" +
1339                            "{0}" +
1340                            "but <b>failed</b> to do so, because of the following proxy errors:<br>" +
1341                            "{1}" +
1342                            "Would you like to change your proxy settings now?",
1343                            Utils.joinAsHtmlUnorderedList(proxySelector.getErrorResources()),
1344                            Utils.joinAsHtmlUnorderedList(proxySelector.getErrorMessages())
1345                    ));
1346        }
1347
1348        private static boolean handleNetworkErrors() {
1349            Map<String, Throwable> networkErrors = NetworkManager.getNetworkErrors();
1350            boolean condition = !networkErrors.isEmpty();
1351            if (condition) {
1352                Set<String> errors = new TreeSet<>();
1353                for (Throwable t : networkErrors.values()) {
1354                    errors.add(t.toString());
1355                }
1356                return handleNetworkOrProxyErrors(condition, tr("Network errors occurred"),
1357                        tr("JOSM tried to access the following resources:<br>" +
1358                                "{0}" +
1359                                "but <b>failed</b> to do so, because of the following network errors:<br>" +
1360                                "{1}" +
1361                                "It may be due to a missing proxy configuration.<br>" +
1362                                "Would you like to change your proxy settings now?",
1363                                Utils.joinAsHtmlUnorderedList(networkErrors.keySet()),
1364                                Utils.joinAsHtmlUnorderedList(errors)
1365                        ));
1366            }
1367            return false;
1368        }
1369    }
1370
1371    private static class DefaultNativeOsCallback implements NativeOsCallback {
1372        @Override
1373        public void openFiles(List<File> files) {
1374            Executors.newSingleThreadExecutor(Utils.newThreadFactory("openFiles-%d", Thread.NORM_PRIORITY)).submit(
1375                    new OpenFileTask(files, null) {
1376                @Override
1377                protected void realRun() throws SAXException, IOException, OsmTransferException {
1378                    // Wait for JOSM startup is advanced enough to load a file
1379                    while (mainFrame == null || !mainFrame.isVisible()) {
1380                        try {
1381                            Thread.sleep(25);
1382                        } catch (InterruptedException e) {
1383                            Logging.warn(e);
1384                            Thread.currentThread().interrupt();
1385                        }
1386                    }
1387                    super.realRun();
1388                }
1389            });
1390        }
1391
1392        @Override
1393        public boolean handleQuitRequest() {
1394            return MainApplication.exitJosm(false, 0, null);
1395        }
1396
1397        @Override
1398        public void handleAbout() {
1399            MainApplication.getMenu().about.actionPerformed(null);
1400        }
1401
1402        @Override
1403        public void handlePreferences() {
1404            MainApplication.getMenu().preferences.actionPerformed(null);
1405        }
1406    }
1407
1408    static void notifyNewMessages(UserInfo userInfo) {
1409        GuiHelper.runInEDT(() -> {
1410            JPanel panel = new JPanel(new GridBagLayout());
1411            panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.",
1412                    userInfo.getUnreadMessages(), userInfo.getUnreadMessages())),
1413                    GBC.eol());
1414            panel.add(new UrlLabel(Config.getUrls().getBaseUserUrl() + '/' + userInfo.getDisplayName() + "/inbox",
1415                    tr("Click here to see your inbox.")), GBC.eol());
1416            panel.setOpaque(false);
1417            new Notification().setContent(panel)
1418                .setIcon(JOptionPane.INFORMATION_MESSAGE)
1419                .setDuration(Notification.TIME_LONG)
1420                .show();
1421        });
1422    }
1423}