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