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