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