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